A raw electrode trace hides its spikes under hum and slow waves. A filter carves them out, but a filter that peeks at the future cannot run inside a live brain-computer interface.
Learn how a digital filter works from the first multiplication, how to pick its type, order and edges for spikes and for slow brain waves, and what a live decoder gives up when it filters in real time.
Pick Spike band, then drag the edge. Watch the spikes appear, and then fade. Then we build, piece by piece, the filter that did it.
You need to know that a wave repeats a number of times each second (that count is its frequency, in hertz). We build the rest from zero.
Built from the primary sources: Quiroga, Nadasdy and Ben-Shaul (Neural Computation 2004) and the open Neuromatch Academy tutorial on filters, plus the SciPy documentation. Part of the series on brain-computer interfaces.
Illustrative synthetic data: 8 spikes, a slow wave (150 µV), 60 Hz hum (100 µV) and white noise (8 µV), sampled at 30 kHz. The filters are fourth-order Butterworth. The slow band is a low-pass at the edge; the spike band is a high-pass at the edge and a low-pass at 6,000 Hz. A spike counts when the filtered trace falls below minus 4 times the median noise estimate of Chapter 8.
Chapter 0
See why one electrode wire carries several signals at once, and why we split them by speed
A thin wire sits in the motor cortex of a person who cannot move their arm. At its tip, the wire measures one thing: a voltage, a few millionths of a volt (a microvolt, written µV), compared with a reference far away. A chip reads that voltage 30,000 times each second. The result is a list of numbers, 30,000 per second, and nothing else.
That list is the whole raw material of a brain-computer interface. It holds the neuron firing next to the tip. It also holds a lot of things that are not that neuron. Your first job is to see what those things are.
The wire cannot tell its sources apart. It only adds them. At any one instant, five things push on the voltage.
Here is one instant, with toy numbers. The slow wave is at +120 µV. The hum is at −40. The drift adds +30. The noise adds +5. No spike is firing. The wire reports 120 − 40 + 30 + 5 = 115 µV. A moment later a spike of −90 µV arrives, and the wire reports 25 µV. From the single number 25, nobody can say what the parts were.
One number at one instant cannot separate the sources. But a stretch of numbers can, because the five sources move at very different speeds. Drift takes seconds to change. A slow wave repeats a few times a second. Hum repeats exactly 60 times a second. A spike is over in a millisecond.
The count of repeats per second is the frequency, measured in hertz (Hz). A fast wiggle is a high frequency. A range of frequencies is a band. Spikes live in a high band, with most of their energy between a few hundred and a few thousand hertz. Slow waves live in a low band. Hum sits at one exact frequency in the middle of the low band.
A filter is a rule that turns the list of numbers into a new list of numbers, so that some bands pass through and others fade out. A digital filter does this with plain arithmetic on the samples. The rest of this lesson shows how to build one, how to pick it, and what it costs.
One fact about the sample list sets the ceiling. A list of 30,000 samples per second can only describe waves up to 15,000 Hz, half the sampling rate. Anything faster folds back as a false slower wave. The analog front end lesson deals with that; for the DFT view of it, see the DFT lesson. Here we take the 30 kHz list as given. The Neuromatch tutorial uses the same rate for a real Neuropixels recording.
Top: the sum of the sources you switched on, over 80 ms. Bottom: where each source lives on the frequency ruler, from 0.1 Hz to 15,000 Hz. Switch sources on and off and see what the wire has to add up.
Illustrative amplitudes: spikes 90 to 120 µV, slow waves about 150 µV, hum 100 µV, drift 60 µV, noise 8 µV rms. The frequency ranges are typical, not exact. The 300 Hz dividing line is the one the Neuromatch tutorial uses to split the LFP from the spikes.
A decoder could try to learn the sum directly. Three facts say it should not. First, the junk is often bigger than the signal. In the demo above, the hum swings 100 µV, as large as a spike. Second, a threshold needs a fair estimate of the noise level, and hum and drift make that estimate far too high. The hero showed it: on the raw trace the threshold sat above every spike. Third, every sample costs power and radio bandwidth. If a band carries no information, you want to drop it early, before you send it anywhere. Chapter 10 of the series, implant compression, picks up that thread.
The slow band is not rubbish. It carries rhythms that matter for other kinds of decoding; the brain rhythms lesson uses them. The point is that the two bands need different handling, so we split them first.
The road ahead follows the order in which the ideas depend on each other.
Chapter 1
Build a filter from a short list of weights that slides along the recording
You read a cheap thermometer. The needle jitters: 20.4, 19.7, 20.9, 20.1, 19.8. You do not trust any one reading. So you average the last five and call that the temperature. You just built a filter.
Look at what you did. For each new reading, you took the last five readings, gave each the same weight of one fifth, and added them up. A digital filter does the same thing with a chosen list of weights.
The list of weights is the kernel. Another name for it is the impulse response, because it is exactly what comes out when you feed in an impulse: a recording of zeros with a single 1 in it. Feed the impulse in, and the filter plays the kernel back, one weight per sample. The Neuromatch tutorial puts it this way: the impulse response is the output of the system when the input is a single impulse.
For the thermometer, the kernel is five weights, each 0.2. For an input with two readings, say, the kernel could be 0.5 and 0.5. Now the rule for a whole recording.
This sum is called convolution. In words: put the kernel over the recording, flip it so the newest weight meets the newest sample, multiply each pair, and add. Then slide one step and repeat. The Neuromatch tutorial describes the effect well: each input sample is replaced by a scaled copy of the kernel.
Take the input x = [2, 4, 6, 8, 6, 4] and the kernel h = [0.5, 0.5], an average of two samples. Each output uses the current sample and the one before it. Before the start, we count the missing samples as zero.
The output is [1, 3, 5, 7, 7, 5]. The peak of 8 became 7, and it arrived one step late. Both effects matter for a spike. The smoothing lowers the peak, and the delay moves it. Keep both in mind; Chapters 6 and 7 measure them.
Change the weights, and you change what the filter keeps. A kernel of equal positive weights smooths: it keeps what changes slowly and averages away what changes fast. A kernel that subtracts the recent average from the newest sample does the reverse. It keeps what changes fast and removes what changes slowly. Try both on a recording that holds noise, a spike and a slow wave.
Top: the input, 10 ms of noise, one spike and a slow wave. Middle: the kernel as bars. Bottom: the output. Choose a kernel type and drag its width.
Illustrative test signals at 30 kHz: white noise of 10 µV rms, a 100 µV spike (about 0.3 ms wide at the trough), and an 80 Hz wave of 80 µV. Each number comes from running the kernel on that signal alone, in your browser. The kernel is causal: only the newest sample and earlier ones are used.
Slide the width of the average up and watch two numbers trade. The noise shrinks, because independent noise partly cancels in an average. The spike also shrinks, because it lasts only a few samples and the average smears it over all N. A spike about 9 samples wide is already damaged at N = 6.
In code, one second of recording is an array of 30,000 numbers, shape (30000,). The kernel is an array of K numbers, shape (K,). The output has shape (30000,) again. For each output sample the machine does K multiplications and K−1 additions. At 30,000 samples per second, a kernel of 100 weights costs 3 million multiplications each second, for every channel. A chip with 1,024 channels would need 3 billion. This is why designers care about kernel length (Chapter 3).
How do you pick the weights to keep a chosen band? Guessing is slow. Chapter 2 gives the shortcut: describe the filter by which frequencies it passes, and a design rule hands you the weights.
Chapter 2
Read a filter by what it passes and what it blocks, from low-pass to notch
Picture the equaliser in a music app. Each slider sets how loud one band of sound plays: bass, middle, treble. Push the treble slider to zero and the hiss vanishes. A filter is that equaliser, with the sliders fixed in place.
Chapter 1 described a filter by its weights. That description is exact, but it hides the question we care about: which frequencies pass? There is a fact that makes the question answerable.
Feed a pure wave of one frequency into a filter of the kind in Chapter 1. Out comes a pure wave of the same frequency. Only two things can change: its height and its timing. The ratio of output height to input height is the gain at that frequency. A gain of 1 means the wave passes unchanged. A gain of 0.1 means it comes out ten times smaller. A gain of 0 means it is gone.
Measure the gain at every frequency and plot it. The plot is the frequency response. It is the best picture of a filter, because it tells you at a glance what the filter keeps and what it removes. The Neuromatch tutorial calls it a frequency mask, and imagines isolating the 4 to 8 Hz theta band of an LFP this way.
Nearly every neural filter is one of four shapes. Each has a passband (where gain is near 1), a stopband (where gain is near 0) and a transition band between them. The cutoff is the frequency where the gain has fallen to 0.707 of its passband value, which is the point where the signal's power has halved.
| Shape | Keeps | Neural use |
|---|---|---|
| Low-pass | Below the cutoff | The LFP: keep below 300 Hz |
| High-pass | Above the cutoff | The spike band: keep above 300 Hz |
| Band-pass | Between two cutoffs | Spikes alone: 300 to 6,000 Hz, as in Quiroga and colleagues |
| Notch | Everything but a thin slice | Mains hum: remove 60 Hz (50 Hz in Europe) |
A band-pass is a high-pass and a low-pass in series. The high-pass sets the lower edge and the low-pass sets the upper edge. The Neuromatch exercise for splitting a real Neuropixels recording uses two fourth-order Butterworth filters, both with the cutoff at 300 Hz: a low-pass for the LFP and a high-pass for the spike band.
Gains span a huge range, so people use a log scale, the decibel (dB). The rule is dB = 20 · log10(gain). A gain of 1 is 0 dB. A gain of 0.707 is −3 dB. A gain of 0.1 is −20 dB. A gain of 0.01 is −40 dB. Each extra −20 dB is another factor of ten in height.
A filter changes gain gradually, not with a cliff. How fast depends on its order, the number of poles it has (the count of memory terms in its recipe; Chapter 4 opens that up). Each pole adds a slope of −6 dB for every doubling of frequency. A fourth-order filter falls 24 dB per doubling, far enough from its cutoff.
The classic design is the Butterworth filter. The Neuromatch tutorial calls it a solid default: a maximally flat passband with no ripple and a smooth roll-off. Its gain has a simple form. For a high-pass of order n with cutoff fc, at frequency f:
Now remove 60 Hz hum with a fourth-order high-pass at 300 Hz. Here fc/f = 300/60 = 5, and 2n = 8.
That is far under the 5 µV rms of noise that remains after the spike band. At 1,000 Hz the same filter has a ratio of 0.3 and a gain of 0.99997, so a spike's main content passes. The formula is for the high-pass shape; the low-pass flips the ratio to f/fc.
The curve shows gain in dB at each frequency, on a log frequency axis. The vertical line is a test wave. Pick a shape, an order and a cutoff, and see what happens to a 100 µV wave at the test frequency.
The curves are the exact gain of Butterworth sections built by the bilinear transform at a 30 kHz sampling rate. The band-pass has its upper edge fixed at 6,000 Hz. The notch has Q = 10 (Chapter 5) and ignores the cutoff and order sliders.
Drag the cutoff of the high-pass up and down. The curve slides along the axis but keeps its shape. Switch the order to 8 and the slope steepens. Park the test wave at 60 Hz and watch the read-out: the hum shrinks by a factor you can read in decibels.
Chapter 3
Compare a filter that looks only at inputs with one that feeds its own output back
You want a smooth estimate of a jittery reading. There are two ways. The first: keep the last 100 readings in a notebook and average them every time. The second: keep one number, the current estimate, and nudge it a tenth of the way toward each new reading.
The second way needs one number of memory and two multiplications per reading. The first needs a hundred of each. Both smooth. They are the two families of digital filter.
The first way is an FIR filter, short for finite impulse response. Each output is a weighted sum of the last N inputs, exactly the convolution of Chapter 1. Feed in an impulse and the output is the kernel, which ends after N samples. The weights are called taps, from the old picture of a delay line with a tap at each stage.
FIR has two strong points. It is always stable, because it only adds up past inputs, so nothing can run away. And with symmetric taps it has linear phase: every frequency is delayed by the same time, so the shape of a spike is kept. That delay is (N − 1)/2 samples. Its weak point is length. A sharp edge needs many taps.
The second way is an IIR filter, infinite impulse response. Each output uses the last few inputs and the last few outputs. The output feeds back into itself. The simplest case is the nudge rule above:
Feed in an impulse and see what comes out. With α = 0.1: y[0] = 0.1. Then y[1] = 0.9 · 0.1 = 0.09, y[2] = 0.9 · 0.09 = 0.081, y[3] = 0.0729, and so on, shrinking by 10% each step. It never reaches exactly zero. That is the "infinite" in the name, although in practice it fades below the noise after a while.
IIR gets a sharp edge from a few numbers because the feedback does the repeating work. Its weak points mirror FIR's strong ones. It can be unstable, if the feedback gain grows. And its delay differs by frequency, which bends shapes (Chapter 6).
Take the job from Chapter 2: a high-pass near 300 Hz at a 30 kHz sampling rate. The edge must go from blocked at 100 Hz to open at 300 Hz.
A fourth-order Butterworth IIR does it with two biquads (a biquad is a feedback filter with two past inputs and two past outputs). Each biquad uses five multiplications per sample, so the total is 10. At 100 Hz its gain is −38 dB.
A FIR filter with the same edge needs far more taps. A common rule for a Hamming-window design says the transition width is about 3.3 · fs / N. With fs = 30,000 Hz and a transition of 200 Hz, N is about 3.3 · 30,000 / 200 = 495 taps. That is 495 multiplications per sample, about 50 times the IIR, for every channel. It also delays the output by (495 − 1)/2 = 247 samples, which is 8.2 ms. Even then the FIR is not better: its edge sits near 325 Hz, and it blocks 60 Hz by 46 dB where the IIR blocks it by 56 dB. Use the device to see the trade at other lengths.
Both filters are meant as a high-pass at 300 Hz. Top: the impulse response of each (the first peak is clipped to show the tails). Bottom: the gain. Drag the number of FIR taps and watch where each filter's edge lands.
The IIR is the fourth-order Butterworth of Chapter 2 (two biquads). The FIR is a Hamming-windowed sinc high-pass with an odd number of taps, designed for a 300 Hz cutoff. Gains are exact for both. The edge is the lowest frequency where the gain reaches 0.707 (−3 dB). The delay is the FIR's (N − 1)/2 samples at 30 kHz.
Start with the 101 taps in the device. The FIR edge sits near 450 Hz, not 300, and 60 Hz is blocked by only 34 dB. A short filter cannot hold a sharp edge at a low frequency, so its edge drifts upward. Raise the taps and the edge creeps toward 300 Hz, but the cost per sample and the delay grow in step. At 11 taps the edge has moved to about 3.5 kHz, right through the middle of the spike band.
That is why on-chip and low-power neural filters lean on IIR biquads: few multiplications per channel per sample. FIR keeps its place where exact linear phase matters, usually in offline analysis.
Chapter 4
Trade sharper rejection against longer ringing and more arithmetic
Think of a fence between two fields. A low fence of one plank stops almost nothing. A tall fence of ten planks stops everything, but it costs ten planks and casts a long shadow. A filter's order is the number of planks.
Chapter 2 gave the rule: each pole adds −6 dB per doubling of frequency. Now we pay the bill. A higher order gives a steeper edge. It also costs more arithmetic and rings for longer. This chapter measures all three on the 300 Hz high-pass that guards the spike band.
A pole is one unit of memory in the filter's feedback. A Butterworth filter of order n has n poles. The design places them evenly along half a circle, which is what makes its passband flat. You do not need the complex numbers. What you need is the consequence: the poles come in pairs, and each pair becomes one biquad, the five-multiplication block from Chapter 3.
The pairs differ in one number, the quality factor Q. A high Q means the section has a bump just before the cutoff and rings after a kick. For a Butterworth of order n, section k has
Work the fourth-order case, n = 4, so two sections. For k = 0: sin(π/8) = 0.3827, so Q = 1/(2 · 0.3827) = 1.307. For k = 1: sin(3π/8) = 0.9239, so Q = 1/(2 · 0.9239) = 0.541. The first section has a mild bump. The second is overdamped. Their product is exactly flat in the passband. This is the filter this page builds in the browser, and the same recipe is in scipy.signal.butter.
Why cascade small sections instead of one big recipe? Rounding. A single high-order recipe with a low cutoff has coefficients that must be exact to many digits, or the filter misbehaves. The SciPy documentation warns that high-order and narrow-band filters in plain transfer-function form can give unstable or incorrect results, and recommends second-order sections. It also states that sosfiltfilt should be preferred over filtfilt for most filtering tasks, for the same reason.
The device below filters two things through the 300 Hz high-pass at orders 2 to 10: a 100 µV, 60 Hz hum, and a 100 µV spike. It reports what is left of the hum, how long the filter keeps ringing, and how many multiplications it costs.
Top: a spike (blue) and what the high-pass makes of it (warm). Bottom: the hum left over, against the noise floor of the spike band. Drag the order.
Illustrative signals (a 100 µV spike and a 100 µV hum) through our Butterworth cascade at 30 kHz. The noise floor of 5 µV rms is what 8 µV of white noise leaves after a 300 to 6,000 Hz band-pass. Ringing time is the last moment the impulse response is above 1% of its first value.
Read the numbers at order 2. The hum is cut to 4.0 µV, which is nearly the size of the 5 µV noise. It still disturbs the threshold. At order 4 the hum falls to 0.16 µV, thirty times below the noise. At order 8 it is 0.00026 µV and no longer matters. But the ringing grows from 0.87 ms at order 2 to 1.7 ms at order 4 and 3.3 ms at order 8, and the multiplications climb from 5 to 10 to 20.
Here is the arithmetic for the choice, step by step. The spike band has about 5 µV of noise. We want leftover hum at least ten times smaller, so at most 0.5 µV. Hum is 100 µV, so we need a gain of 0.005 or less at 60 Hz, which is −46 dB. Order 2 gives −28 dB, which is too weak. Order 4 gives −56 dB, which passes. We stop at order 4, because order 6 costs 15 multiplications instead of 10 and rings 2.5 ms instead of 1.7 ms, for hum that is already below the noise.
The ringing matters because a neuron cannot fire again for about a millisecond or two after a spike. If the filter's tail lasts longer than that, a bump in the tail can look like a second spike. The Neuromatch tutorial warns about the same effect for slow rhythms: any broadband event, passed through a sharp narrow filter, produces an oscillation that is the filter's own impulse response, not a neural oscillation.
Order 4 is the usual compromise. Quiroga and colleagues filter their recordings from 300 to 6,000 Hz with a four-pole Butterworth, and the Neuromatch exercise uses order 4 too. Other families trade differently, as the tutorial lists. Chebyshev and elliptic filters get a sharper roll-off by accepting ripple. Bessel filters keep a flat delay but fall slowly. The rule behind all of them is the same: a sharper frequency edge means a longer, more oscillatory impulse response.
Chapter 5
Cut 60 Hz hum without cutting the signal next to it, even when the mains drifts
The high-pass of Chapter 4 threw out the 60 Hz hum along with everything else below 300 Hz. That works for spikes. But you may also want the slow band. The slow band holds the rhythms from 1 to 100 Hz, and 60 Hz sits right in the middle of it. A low-pass cannot remove one frequency from the middle of a band. For that you need a notch.
A notch filter has gain 1 almost everywhere and gain 0 at one chosen frequency. Picture a comb with a single missing tooth, or a radio you tune to the one station you do not want and mute.
The power lines and the equipment around the recording radiate a wave at the mains frequency. The wires of the recording system pick it up like a weak antenna. In North America and parts of Asia the mains runs at 60 Hz; in Europe and most of the world it runs at 50 Hz. The Neuromatch tutorial lists it as environmental noise, electrical interference from the building, and builds a 60 Hz notch with quality factor Q = 30.
The hum is rarely a clean wave. Distortion in the supply and the equipment adds copies at whole multiples of the mains: 120 Hz, 180 Hz and so on. A spike-band high-pass at 300 Hz already removes these well. But in the slow band every copy below 300 Hz stays, so a careful design notches 60 Hz and also 120 and 180 Hz. Each notch is one more biquad.
A notch biquad has two parts. Its zeros sit exactly on the unit circle at the target frequency f0, which forces the gain there to zero. Its poles sit just inside the circle at the same angle, which pulls the gain back to 1 on both sides. The closer the poles are to the zeros, the thinner the notch.
One number sets the width: the quality factor Q. The notch bandwidth, where the gain is within 3 dB of flat, is
At Q = 30 the width is 60/30 = 2 Hz. At Q = 10 it is 6 Hz. At Q = 2 it is 30 Hz, wide enough to dent the neighbouring rhythms.
It is tempting to choose a huge Q so that nothing near 60 Hz is touched. Two things go wrong.
Cost one: the mains is not exactly 60 Hz. The grid frequency wanders by a fraction of a hertz. A thin notch tuned to 60.0 Hz then misses a hum at 59.8 Hz. We measure it below. At Q = 30, a hum 0.2 Hz off passes at 19.6% of its height. At Q = 10 it passes at 6.7%. At Q = 2 it passes at 1.3%.
Cost two: the notch rings. A thin filter takes a long time to forget a kick. The ringing fades with a time constant of Q / (π · f0). For Q = 30 and f0 = 60 Hz this is 30 / (π · 60) = 0.159 s. After a large artifact, such as a stimulation pulse, the notch hums at 60 Hz for around half a second. At Q = 10 the time constant is 53 ms, and at Q = 2 it is 11 ms.
Top: a slow-band recording with hum, before (blue) and after (warm) the notch. Bottom: the notch gain from 40 to 80 Hz, with a line at the true mains frequency. Drag the notch width and the mains frequency.
Illustrative recording: 8 and 23 Hz waves (60 µV) plus a 100 µV hum and 3 µV of noise. The hum left over is measured by passing a pure 100 µV wave at the true mains frequency through the notch. The notch is a second-order section tuned to 60 Hz. The ring time is Q / (π · 60 Hz).
First set the mains to 60.0 Hz and watch every Q remove the hum. Then set the mains to 59.8 Hz and raise Q: the thin notch lets the hum return. Then lower Q to 2 and look at the gain at 55 Hz. The wide notch dips by almost 10 dB there, so it also cuts a real 55 Hz brain rhythm.
No setting is best for every purpose. For a closed-loop BCI that uses slow rhythms, a mid-sized Q near 10 is a common middle: it follows a small drift and rings for about 50 ms. For spike detection alone, skip the notch and use the high-pass.
Chapter 6
Measure how a filter that only looks back delays and bends a spike
A choir sings one chord. The chord is five notes sounded together. Now suppose each singer is a little late, and the bass is later than the sopranos. The notes are all still there, but the chord no longer sounds like the same chord. It has been smeared in time.
A spike is a chord. It is a blend of waves of many frequencies that line up at one instant to make the sharp dip. A filter can keep every note at full volume and still ruin the chord, if it delays each note by a different time.
Every filter shifts the timing of the waves that pass through. The shift of one wave is its phase: how far along its cycle it is, compared with where it was at the input. A shift of a whole cycle returns the wave to the same look. A shift of a quarter cycle slides it by a quarter of its period.
Convert phase to time and you get the delay of that wave. The delay that matters for a burst of many waves is the group delay, the delay at each frequency. If group delay is the same at all frequencies, the chord survives intact, only later. If it varies, the chord is bent.
A symmetric FIR filter has constant group delay: (N − 1)/2 samples at every frequency. A Butterworth IIR does not. Its delay swells near the cutoff and shrinks far above it.
We measured the group delay of the 300 to 6,000 Hz band-pass of Chapters 2 to 4 (a fourth-order high-pass and a fourth-order low-pass in series). The values come from the filter's exact phase at a 30 kHz sampling rate.
| Frequency | 100 Hz | 300 Hz | 500 Hz | 1 kHz | 2 kHz | 4 kHz |
|---|---|---|---|---|---|---|
| Group delay | 1.52 ms | 2.02 ms | 0.67 ms | 0.19 ms | 0.10 ms | 0.10 ms |
The spread is the point. The sharp trough of a spike lives mostly at 1 to 3 kHz, where the delay is 0.1 to 0.2 ms. The slower rebound that follows lives nearer 300 to 500 Hz, where the delay is up to 2 ms. The parts of one spike arrive at different times, so the shape changes.
The Neuromatch tutorial states the same fact for slow rhythms. A causal filter introduces a frequency-dependent time shift, and different frequencies are delayed by different amounts. Its example: if you study the timing of gamma bursts against theta phase, the filter's own phase shift can produce false conclusions about who leads and who lags.
One spike (blue) goes through the band-pass with a lower edge you choose. Warm is the causal output. Teal is the zero-phase output. Drag the edge and watch the shapes diverge.
A 100 µV synthetic spike, noise-free, through a fourth-order Butterworth band-pass from the edge to 6,000 Hz at 30 kHz. The causal output uses only past samples. The zero-phase output is run forward and then backward (Chapter 7). Group delay is computed from the exact phase of the causal filter.
At 300 Hz the causal filter cuts the trough from 100 µV to about 44 µV and raises a +75 µV rebound behind it. The biggest swing is now upward. The zero-phase result keeps 88 µV and a +37 µV rebound, much closer to the original shape. Neither is the exact original, because both filters remove everything under the edge. The causal one also bends what is left.
If you train a decoder on offline zero-phase data and run it on online causal data, the two inputs have different shapes. The thresholds, the spike templates and the features no longer match. The fix is to filter training data the same way you will filter live data. Use the causal filter in both places, so that the decoder sees at test time what it saw at training time.
The symptom. A team sorts spikes offline with a zero-phase filter and gets six clean clusters. They then run the live system with a causal filter, using the same templates, and the clusters fall apart. Spikes that matched a template offline no longer match it online.
The measurement. Filter one spike both ways, as the device did. At a 300 Hz edge, the offline trough is 88 µV and the rebound is 37 µV. Online, the trough is 44 µV and the rebound is 75 µV. The two shapes are different objects. A template built from the first cannot match the second, however good the sorter is.
The fix. Rebuild the templates from data that went through the live filter. If you must keep a zero-phase view for plots, treat it as a picture and never as input to the decoder. Also log the filter settings with every recording, so that anyone can tell later which shape the data had.
Chapter 7
See why filtfilt reads the future, and how much waiting a live decoder can afford
Reading yesterday's newspaper, you know how every story ended. A live commentator does not. When she says "and it looks like a goal", she cannot also say what happens next. A filter has the same split. A filter on a finished recording can look at the future of every sample. A filter on a live signal cannot.
Chapter 6 showed the cost of a causal filter: it bends the spike. There is a trick that removes the bend. It works only when the whole recording is already in hand.
The trick is called zero-phase filtering. In SciPy it is filtfilt, and the documentation describes it as applying a linear digital filter twice, once forward and once backwards. In four steps:
The SciPy page states the result: the combined filter has zero phase and a filter order twice that of the original. Two passes also square the gain, so a −3 dB point becomes −6 dB and the roll-off doubles in slope. With zero phase, every frequency has zero delay, the spike keeps its shape, and its peak lines up with the true peak. That is why offline analysis loves it. The Neuromatch tutorial advises using it for offline work whenever temporal precision matters.
The edges need care. At each end the filter has no history, and SciPy pads the signal by extending it, three times the larger of the coefficient-list lengths by default. Even so, the documentation says that transient effects at the edges are unavoidable. It also recommends sosfiltfilt over filtfilt for most tasks, for the numerical reasons in Chapter 4.
Look at step 3. The second pass starts from the end of the recording and works toward the start. To output sample t, it needs the forward result of every sample after t, all the way to the end. In a live system those samples do not exist yet. The filter is non-causal: its output at one time depends on inputs from later times. The Neuromatch tutorial states the rule directly: a causal filter uses only past and present samples, and this is required for real-time systems like BCIs.
There is a second, stranger effect. A zero-phase filter responds before an event. Feed it a single impulse at time 0. The output is a symmetric burst centred on 0, with a tail on the left side that starts earlier than 0. For our 300 to 6,000 Hz filter the burst starts about 1.3 ms ahead of the impulse (where it first exceeds 1% of its peak). A decoder fed this signal would see the spike's echo before the spike. Offline, that is harmless. Live, it is impossible, because the future is not there to echo.
Latency matters here. A decoder that moves a cursor or speaks has a tight delay budget. Neuralink states, in a public engineering posting for its BCI applications, a target of 15 ms from neural stream to device control (a company claim; we could not check it independently). Every millisecond the filter waits comes out of that budget.
You can buy back some of the zero-phase shape by waiting. Run the forward pass causally. Then, to output sample t, wait until D more milliseconds have arrived and run the backward pass only over that short stretch, starting from zero memory at t + D. The longer you wait, the closer you get to the full forward-backward result. The cost is a delay of exactly D. We measured it on a noisy spike.
Teal is the offline zero-phase answer. Warm is the plain causal filter. Yellow is the look-ahead filter. Drag how long it may wait.
A 100 µV synthetic spike with 4 µV of noise through the 300 to 6,000 Hz fourth-order band-pass at 30 kHz. The error is the rms difference from the full zero-phase output across the 5.3 ms shown, divided by the rms of that output. The look-ahead filter runs the backward pass from zero memory over the next D milliseconds only.
The curve of cost against accuracy is steep. With 0.5 ms of waiting the error against the ideal is 35%. At 1 ms it is 28%, at 2 ms 8.4%, at 3 ms 3.9%, and at 5 ms 0.2%. The plain causal filter has 104% error: its shape differs from the zero-phase shape by about as much as the shape is big. A few milliseconds of waiting recovers almost everything, but a few milliseconds may be the whole budget.
So a live BCI usually keeps the causal filter and lives with its bend, as Chapter 6 advised. It trains on data filtered the same way. If it needs zero-phase quality, for example to sort spikes into neurons, it does that offline on the stored recording, and uses the result to set up the live system.
Chapter 8
Set a spike threshold from the filtered noise and watch the filter change the count
Back to the hero. After the filter, the spikes stand out as dips. How does a machine decide which dips are spikes? It draws a line and calls every dip that crosses it a spike. The whole question is where to draw the line.
Draw it too close to zero, and the noise crosses it. You count spikes that are not there. Draw it too far, and real spikes stay under it. You miss them. The right line depends on how big the noise is, so we must measure the noise first, in the same filtered signal.
Quiroga, Nadasdy and Ben-Shaul detect spikes by amplitude thresholding after band-pass filtering the signal from 300 to 6,000 Hz with a four-pole Butterworth filter. They set the threshold automatically:
The paper credits the median estimate to Donoho and Johnstone (1994), and states why it prefers the median to the plain standard deviation. A standard deviation that includes the spikes can give very high threshold values, especially at high firing rates and large spike amplitudes. The median is hardly touched by a few large values, as long as spikes are a small fraction of all samples.
Take nine filtered samples, in µV (toy values): 3, −5, 4, −6, 5, −4, −70, 5, −90. Two of them are spikes.
Two spikes in nine samples are too many for a real recording, which makes the example loud. The effect is real, though, and the device below measures it.
A band-passed recording with spikes of 60 to 140 µV. The solid line is the median threshold. The dashed line is the standard deviation threshold. Drag the firing rate and watch both lines move.
Illustrative synthetic data: 0.5 s at 30 kHz, 8 µV white noise, spike peaks drawn between 60 and 140 µV, at least 3 ms apart, filtered by the 300 to 6,000 Hz band-pass. A spike is found if a downward crossing falls within 2 ms of it. The sign of the crossing is our choice for these downward spikes.
At 5 spikes per second the two rules agree. At 100 per second the standard deviation reads 17 µV, more than twice the median's 7.3 µV, and its threshold sits above every spike. The median rule finds all 45 spikes in the half second. At 150 per second the median rule starts to give way (it finds 50 of 71), because spikes now fill a large fraction of all samples, which is the one assumption the paper names. At 250 per second both rules fail.
Too many spikes found. The symptom is a firing rate that looks far too high, with a burst of crossings at the same moment on many channels. The measurement is the time of each crossing: if they line up on every channel, the cause is a shared artifact such as a movement or a stimulation pulse, not neurons. The fix is to drop crossings that appear on most channels at once, or to blank the artifact before detection.
Too few spikes found. The symptom is a quiet channel next to a busy one. The measurement is σn on each channel: if the quiet channel has a large σn, hum or drift is lifting its threshold. The fix is the notch or a higher edge, then re-measure.
The same spike counted twice. The symptom is pairs of events 1 to 1.5 ms apart. The measurement is the gap between crossings: it matches the ringing of the filter. The fix is a dead time of about 2 ms after each crossing, or a lower order.
The threshold is only as good as the filter before it. A high edge shrinks the spikes, as the hero showed. A low edge or a missing notch lets hum raise σn, and so the threshold. A filter with too much ringing makes a second dip after the first. A dead time of about 2 ms after each crossing (our devices use 60 samples) stops one spike from counting twice.
The output of this stage is small. For each crossing, the Quiroga pipeline saves a snippet of 64 samples, about 2.5 ms at their rates, and hands the stack of snippets to a spike sorter. The shape is (k, 64) for k spikes. The spike detection lesson builds on this, and the spike sorting lesson clusters the snippets. The wavelet features the paper uses are in the wavelets lesson.
Chapter 9
Stream a filter block by block, keep its memory, and store its numbers in fixed point
So far we filtered a recording that sat in memory. A live implant never has that. Samples arrive 30,000 times a second, in small packets, and the filter must keep up for hours without a single reset. This chapter covers the two things that decide whether your design survives that: the filter's memory, and the numbers inside it.
Recall the biquad of Chapter 4. To make the next output it needs the last two of its own values. Those two numbers are its state. Here is the exact update, in the form most code uses (direct form II transposed), for one input sample v:
That is five multiplications and four additions, with two stored numbers. A fourth-order filter has two biquads, so its whole state is a small table of shape (2 sections, 2 values). In SciPy this table is called zi when you hand it in and zf when it comes back out of sosfilt. For a 1,024-channel chip the state is 1,024 such tables, one for each channel, and each channel keeps its own.
Data arrives in blocks. Say the chip collects 1 ms of samples, 30 per channel, and then filters them. There are two ways to do it. You can carry the state over from the end of one block to the start of the next. Or you can reset it to zero at each block. Only the first is a filter. The second chops the recording into pieces and starts the filter cold on each piece.
A cold start is bad news. The filter assumes the signal was zero before the block. If the real signal is a slow wave of 100 µV, the filter sees a sudden jump from 0 to 100 µV at the start of every block. It answers with a start-up burst, just as it would for a step. The burst is large because the slow wave is far bigger than the spike band. Try it.
Teal is the answer you get from filtering the whole recording at once. Warm is the answer from block-by-block filtering. Switch the memory off and shrink the blocks.
Illustrative signal at 30 kHz: a 100 µV slow wave, 5 µV noise and one 100 µV spike, through the 300 to 6,000 Hz fourth-order band-pass. The error is the rms difference from the whole-recording output over 100 ms, divided by the rms of that output. The thin lines mark block edges when they are wide enough to show.
With memory carried, the block output is identical to the whole-recording output: the difference is zero, to the last digit. With the memory reset, the error is 4.1 times the size of the answer at 1 ms blocks and still 1.4 times at 10 ms blocks. The shorter the block, the more start-ups per second.
Block length also costs time. A 1 ms block means the first sample in it waits 1 ms before anything is computed. Filtering sample by sample removes that wait. It costs more calls but no buffering. This is a real design choice on a chip that must meet a delay budget.
A small implant chip may not have floating-point hardware. It stores each coefficient as an integer and treats the last few bits as a fraction. This is fixed point. A coefficient with f fractional bits is rounded to the nearest multiple of 2−f. The quantization lesson covers the rounding error of the signal itself; here we look at rounding the filter's own coefficients.
It looks harmless. It is not, for a low cutoff. Our 300 Hz high-pass at 30 kHz has poles very close to the point z = 1. Its two biquads have a1 = −1.9492 and a2 = 0.9531, and a1 = −1.8866 and a2 = 0.8903. A pole near 1 moves a lot when a coefficient moves a little. Round those numbers too coarsely, and the poles slide, the cutoff slides, and the filter can go unstable.
Teal is the exact 300 Hz high-pass. Warm is the same filter with every coefficient rounded to the number of fractional bits you choose.
The fourth-order Butterworth high-pass at 300 Hz and 30 kHz, with each of the ten coefficients rounded to the nearest multiple of 2 to the minus f. Gains are exact for the rounded coefficients. A section is stable when |a2| < 1 and |a1| < 1 + a2. Rounding of the signal is not modelled.
At 12 bits the filter behaves: the edge is near 310 Hz and 60 Hz is blocked by about 60 dB. At 8 bits it is stable but no longer a high-pass at all, since 60 Hz passes almost unchanged. At 6 bits and below, a section is unstable and its output grows without limit. The cure is more bits or a different structure, such as wider words, or a design that does the work at a lower sampling rate. That is a hardware trade between bits, area and power.
Chapter 10
Numbers, terms, a checklist, the core code, and where to go next
One wire carries five signals: spikes, slow waves, hum, drift and noise. They differ in speed, so a filter can separate them. A filter is a kernel slid over the samples. You read it by its frequency response, build it as FIR taps or IIR biquads, and set its order and edges by trading rejection against ringing, arithmetic and delay. A live system must filter causally, which bends spikes and keeps the future out. It must also carry its memory between blocks and survive rounding.
Sourced values come from the papers and docs named in the last column. The rest are measurements from this page's own toy signals and are marked illustrative.
| Quantity | Value | Source |
|---|---|---|
| Spike band and filter | 300 to 6,000 Hz, four-pole Butterworth | Quiroga et al. 2004, sec. 3.1 |
| Detection threshold | 4 · median(|x|) / 0.6745 | Quiroga et al. 2004, eq. 3.1 |
| Snippet saved per spike | 64 samples, about 2.5 ms | Quiroga et al. 2004 |
| LFP and spike split | 300 Hz, fourth-order Butterworth, applied zero-phase | Neuromatch W2D2 T3, exercise 3 |
| Neuropixels sampling rate in that exercise | 30,000 Hz | Neuromatch W2D2 T3 |
| Mains hum | 60 Hz (North America), 50 Hz (Europe); example notch Q = 30 | Neuromatch W2D2 T3 |
| filtfilt | zero phase, twice the order; sosfiltfilt preferred | SciPy documentation |
| Live BCI latency target | 15 ms, neural stream to device control (company claim, not independently checked) | Neuralink public engineering posting |
| Order 4 high-pass at 300 Hz | 60 Hz gain 0.0016 (−56 dB); 100 µV hum leaves 0.16 µV | This page, exact formula |
| Ringing, order 2 / 4 / 8 | 0.87 / 1.7 / 3.3 ms | This page, illustrative |
| Group delay of the 300 to 6,000 Hz band-pass | 2.0 ms at 300 Hz, 0.19 ms at 1 kHz | This page, exact phase |
| Look-ahead error vs zero-phase | 35% at 0.5 ms, 8.4% at 2 ms, 0.2% at 5 ms | This page, illustrative |
| Coefficient rounding, order 4 at 300 Hz | 12 bits works, 8 bits not a high-pass, 6 bits unstable | This page, exact |
| Term | One line |
|---|---|
| Kernel, impulse response | The weights a filter applies; what comes out when you feed in a single 1. |
| FIR / IIR | Inputs only, ends after N taps / feedback, decays but never ends. |
| Biquad | One second-order IIR block: 5 multiplications, 2 stored numbers. |
| Order | Number of poles; each adds 6 dB per octave of slope. |
| Q | Sharpness. For a notch, bandwidth = f0 / Q. |
| Group delay | The delay of each frequency. Flat means the shape is kept. |
| Causal / zero-phase | Uses the past only / uses the future too and cancels the phase bend. |
| State | The stored memory of a filter between samples. |
| Fixed point | Numbers stored as integers with f fractional bits. |
This is the whole pipeline in Python with SciPy. Shapes are in the comments. The last function is the biquad update of Chapter 9, so you can see that nothing is hidden.
pythonimport numpy as np from scipy.signal import butter, sosfilt, sosfiltfilt, iirnotch, tf2sos fs = 30_000 # band-pass 300 to 6000 Hz. order=4 per edge, so 4 biquads: sos has shape (4, 6) sos = butter(4, [300, 6000], btype="band", fs=fs, output="sos") # optional 60 Hz notch for the slow band: bandwidth = 60 / Q = 2 Hz b, a = iirnotch(60.0, Q=30.0, fs=fs) sos_notch = tf2sos(b, a) # shape (1, 6) # OFFLINE: x has shape (n,). Zero phase, forward and backward. y_off = sosfiltfilt(sos, x) # shape (n,) # ONLINE: causal, block by block, state carried. block has shape (30,) = 1 ms zi = np.zeros((sos.shape[0], 2)) # (sections, 2) per channel for block in stream(): y, zi = sosfilt(sos, block, zi=zi) # y shape (30,), zi updated # Quiroga threshold on the filtered signal y_all (shape (n,)) sigma = np.median(np.abs(y_all)) / 0.6745 thr = 4 * sigma hits = np.flatnonzero(y_all < -thr) # downward crossings, then add a dead time # one biquad, one sample (row = [b0, b1, b2, a0, a1, a2], z = [z1, z2]) def biquad(v, row, z): o = row[0] * v + z[0] z[0] = row[1] * v - row[4] * o + z[1] z[1] = row[2] * v - row[5] * o return o
Filtering is the first software step after the analog front end and the last step before detection or decoding. The sources of this lesson are Quiroga, Nadasdy and Ben-Shaul, Unsupervised spike detection and sorting with wavelets and superparamagnetic clustering (Neural Computation, 2004); the open Neuromatch Academy tutorial Filters, Convolution and the Convolution Theorem; and the SciPy documentation for filtfilt and butter. The 15 ms figure is a company claim from Neuralink’s public pages.
Now press Present or Teach and explain, from memory, why a live BCI filters causally, what that does to a spike, and what you give up. Then go back to the recording at the top, drag the edge to 60 Hz and to 1,500 Hz, and say aloud what goes wrong each time.
Credit: signal processing after Quiroga, Nadasdy and Ben-Shaul (2004) and the Neuromatch Academy Computational Neuroscience course (open tutorials, W2D2). Every demo here uses synthetic signals made in your browser; amounts are illustrative unless a source is named.