Closed-Loop Neuromodulation

A Parkinson’s implant that stimulates only when a brain rhythm rises, and a spine implant that turns the thought of stepping into steps. Both close the loop between sensing and stimulating.

Learn how an implant reads the brain, decides, and acts within milliseconds, and why the same stimulation does more good when it follows the brain than when it runs blind.

Pick a controller, then drag the threshold. Watch the same made-up brain rhythm get the same stimulation, at different moments. Then we build, piece by piece, the signal chain, the controller, the decoder and the safety checks.

You need a feel for a signal that goes up and down over time and a little Python for the code. We build the rest from zero.

Built from the primary papers: Little et al., Annals of Neurology 2013; Oehrn et al., Nature Medicine 2024; Lorach et al., Nature 2023. Part of the series Brain-Computer Interfaces, from the spike to the foundation model.

Follow the rhythm, or ignore it

1.18

The trace is a made-up beta envelope (baseline 1, bursts on top), the same on every visit. Stimulation lowers the burst part by 60 percent while it is on, ramped over 250 ms: a toy rule. The result bars for the chosen controller are from Little et al. 2013 (8 patients; blinded video ratings of the upper limb, stimulation on-time, energy). Random mode is the trial’s control: same time on, not tied to beta.

Chapter 0

Why Stimulation Should Listen

See why a pulse generator that ignores the brain wastes energy and effect, and meet the two implants that listen

Picture a man with advanced Parkinson’s disease. A thin wire runs deep into his brain and ends in a small knot of cells called the subthalamic nucleus. A battery under his collarbone sends the wire 130 electrical pulses every second, day and night. This is deep brain stimulation (DBS), and it calms his tremor and stiffness.

A clinician chose the settings in a clinic, weeks ago. The settings do not change when he walks, sleeps, takes his pills or gets stressed. His brain changes all day. The stimulation does not.

Now picture a second man. A cycling accident damaged his spinal cord in the neck. His brain still sends the command to step. Almost none of it reaches his legs, because the injury blocks the road. His legs and the part of the spinal cord below the cut are healthy and wait for a signal.

Both men need the same thing: an implant that notices what the nervous system is doing and answers at the right moment. This lesson builds both implants from zero. The first reads a brain rhythm and gates the stimulation. The second reads the intent to move and drives the spinal cord.

Open loop and closed loop

A heater with one fixed power setting is an open-loop controller. It acts and never checks the result. A thermostat is a closed-loop controller. It measures the room, compares the reading with a target, and switches the heater on or off.

Every closed loop has three parts. Sense: measure something. Decide: compare the measure with a rule. Act: change what the heater, or the stimulator, does. The result of the act feeds back into the next measurement. That return path is the loop.

Try it on the room. The fixed heater is tuned for a mild day. Then the weather turns. Drag the outside temperature and compare both controllers.

Fixed heater or thermostat

The warm strip shows when the heater is on. The line is the room temperature. The weather changes at the dashed line. Choose a controller, then drag the new outside temperature.

-10 °C

Toy room, not a measurement: the room loses 4 percent of its gap to the outside each minute; the fixed heater adds 0.4 °C per minute; the thermostat heater adds 0.8 °C per minute and switches at 19.5 and 20.5 °C. Energy is the heater power added up over four hours, in degree-minutes.

The fixed heater is perfect on the mild day and wrong on every other day. On a cold day the room sinks. On a warm day the room overheats and the heater wastes energy. The thermostat holds 20 degrees in both cases, and uses more energy only when the cold demands it.

A pulse generator in the brain is the same kind of heater. If the brain only needs help part of the time, a fixed setting delivers stimulation that nobody needs. That costs battery. It can also cost comfort, because stimulation has side effects such as tingling or speech trouble.

Two implants, one pattern

In 2013 an Oxford group led by Simon Little and Peter Brown tested the first idea in eight patients. They recorded a brain rhythm from the stimulating wire itself, and switched stimulation on only while the rhythm was high. Their paper calls the system a BCI-controlled DBS, because the brain signal is the controller’s input. Chapters 1 to 5 follow this story and its 2024 successor.

In 2023 a team from Lausanne and Grenoble (Henri Lorach, Grégoire Courtine, Jocelyne Bloch, Guillaume Charvet and colleagues) connected the cortex to the spinal cord. Electrodes on the brain surface record the intent to move. A decoder turns that intent into a stimulation pattern for the spine. The one participant stood and walked. Chapters 6 to 8 follow this story.

The last chapters ask what can go wrong when you close a loop, and give you a field guide. The word latency will keep returning. It means the time from the event in the brain to the response in the tissue. In a closed loop, a late answer can be worse than no answer.

The road

  1. Parkinson’s and the beta rhythm: what DBS is and which signal tracks the symptoms.
  2. From wire to envelope: the signal chain that turns a recording into one number.
  3. The threshold controller: the rule, the threshold, and why it can chatter.
  4. The 2013 trial: the numbers, and why a random control matters.
  5. Choosing the signal: the 2024 trial and picking a marker from data.
  6. A bridge to the spine: the 2023 brain-spine interface, part by part.
  7. Decoding intent: a gate, a hidden Markov model and amplitude.
  8. Calibrating in minutes: online learning that keeps up with the brain.
  9. When the loop misbehaves: delay, gain and instability.
  10. Field guide: numbers, code, sources.
What makes a controller closed loop?

Chapter 1

Parkinson’s and the Beta Rhythm

Learn what the stimulating wire can hear, and why one slow rhythm tracks how stiff and slow a patient is

A surgeon has just placed a DBS wire in a patient’s subthalamic nucleus (STN). The patient is awake and has taken no pills for a night. Before the battery goes in, the wire ends outside the scalp, and a neurologist connects it to an amplifier. The screen shows a wobbling line. What is it?

The wire tip has four metal rings, called contacts, numbered 0 to 3 from the tip upward. Each ring picks up a tiny voltage from the tissue around it. That voltage is the sum of electrical currents from thousands of nearby cells. It is called the local field potential (LFP). Think of a stadium. A spike (the signal of one cell, from lesson 1) is one person shouting. The LFP is the roar of the whole crowd.

The roar has a rhythm. When many cells fire in step, the voltage rises and falls together. The count of rises per second is the frequency, in hertz (Hz). A plot of how much of the roar sits at each frequency is the power spectrum. If you want the machinery that builds a spectrum from a recording, see the lessons on the DFT and the short-time Fourier transform.

The beta band

Brain rhythms are sorted into bands. The band from about 13 to 30 Hz is called beta. In the STN of people with Parkinson’s disease, the spectrum often shows a clear bump in this band. Little and colleagues note that beta is found in the STN LFP of these patients, that it stays stable over time, and that its level tracks motor impairment with and without treatment. The bump is high when the patient is off medication and stiff. It falls when levodopa or stimulation helps.

Here is the central fact of this lesson. Beta is a biomarker: a measurable signal that stands in for something you cannot measure directly. Nobody can read “how stiff is this patient right now” from a wire. But the wire can read beta, and beta moves with stiffness.

In the 2013 trial, the effect was large and tidy. Across the stimulation conditions, the drop in beta peak height matched the clinical gain. The correlation of the block averages was R² = 0.99 against the blinded ratings, and 0.85 (not significant, p = 0.08) against the live ratings. Only 8 patients and four conditions stand behind that number, so treat it as a strong sign, not a law. It still gave the team a reason to use beta as the controller’s eyes.

Pβ
Beta power: one number for how much of the roar sits in the beta band.
∫1330
Add up everything from 13 Hz to 30 Hz. In code this is a sum over the spectrum’s bins.
S(f)
The power spectrum: power at each frequency f.
df
The width of one frequency step, so that the sum has the right units.

Now play with a spectrum. The device draws a made-up spectrum: a falling background plus a beta bump. Drag the treatment strength to flatten the bump, and move the peak to where a given patient has it.

Find the beta bump

The shaded band is 13 to 30 Hz. The blue line is the spectrum. The faint line is the untreated spectrum with the same peak. Drag treatment strength up, then move the peak frequency.

0.00
20 Hz

Illustrative spectrum: a background that falls as 1/f1.2 plus a Gaussian bump 3 Hz wide, with its height scaled by (1 minus strength). The shape is made up; only the idea (a beta bump that shrinks with treatment) is the papers’.

Notice that the peak frequency moves from patient to patient. In the 2013 trial the team found each patient’s own peak and filtered a narrow band around it. The bands in their Table 2 run from 16 to 18 Hz in one patient up to 28 to 34 Hz in another. A fixed band would have missed some of them. Chapter 2 builds that filter.

Why record from the stimulating wire

The team could have added a second sensor. They did not. Their paper names two hard problems: the feedback signal must stay robust over time, and the surgery should touch the brain at one site only. Recording from the stimulating wire solves both. It adds no hole and no extra lead.

The price is a hard analog problem. Stimulation pulses are far larger than the LFP: the paper gives about 2 volts of stimulation against a beta signal of about 2.6 microvolts peak to peak, a ratio near a million to one (our arithmetic from the paper’s numbers). The amplifier must record microvolts while the neighbouring contact is shouting in volts. The team used a bipolar recording: they measured the voltage difference between two contacts, 0 and 2, or 1 and 3. A disturbance that reaches both contacts equally cancels in the difference. A common-mode rejection amplifier does that cancellation. The lesson on the analog front end shows how.

When beta is not enough

Consider a patient after a big dose of levodopa. He now moves too much, with writhing movements called dyskinesia. His beta is low, since his stiffness is gone. A controller that watches only beta sees a “healthy” signal and keeps the stimulation high or turns it off. In both cases it is blind to the new problem.

The measurement that shows this is a second signal. The 2024 trial found that a faster rhythm, gamma, tracked the high-dopamine state better than beta did in its four patients. The fix is to choose the marker per patient from data. Chapter 5 shows how.

Why did the 2013 team record the beta signal from the stimulating wire itself?

Chapter 2

From Wire to Envelope

Build the signal chain that turns a wobbling voltage into one number that rises when a beta burst starts

The neurologist’s screen shows a wobbling line. A controller cannot read a wobbling line. It needs one number, updated many times a second, that is low when the patient is fine and high when a beta burst is under way. Four steps make that number. The 2013 team used all four.

Step 1: pick the best pair of contacts

The wire has four contacts. The team recorded two bipolar pairs, contacts 0 and 2, and contacts 1 and 3. At rest, off stimulation and off medication, they compared the beta amplitude on each pair, on the side opposite to the worst-affected arm. The pair with more beta won. Stimulation then went to the contact between the two recording contacts.

Step 2: find the peak and filter around it

Next they found the frequency where the beta bump peaks in that patient. They then applied a band-pass filter around it. A band-pass filter is a gate in frequency: it lets one band through and weakens everything else. Their Table 2 lists the bands, such as 16 to 22 Hz for one patient and 28 to 34 Hz for another. The bands are 2 to 8 Hz wide.

This step matters, because the roar of the crowd has much more power at low frequencies than in beta. Without the filter, slow drift would swamp the number.

Step 3: rectify

The filtered signal swings above and below zero, 20 times a second or so. Its average is zero, which tells the controller nothing. Rectifying means taking the absolute value, so that every swing counts as positive. Now bigger swings give bigger values.

Step 4: smooth with a moving average

A rectified wave still jumps up and down within each cycle. A moving average replaces each sample with the mean of the last L samples. The team used a window of 400 ms. The result is the envelope: the outline of the oscillation’s height, drawn as a slow curve.

env[n]
The envelope at sample n: the number the controller reads.
1/L
One over the window length in samples. At 1,000 samples per second, 400 ms is L = 400.
∑
Add the last L absolute values.
|y[n−k]|
The band-passed signal k samples ago, made positive. Only the past appears, so the filter works in real time.

A tiny example, with L = 3 and band-passed samples y = 0.5, −1.2, 0.8, −0.3, 1.0, −0.9. The absolute values are 0.5, 1.2, 0.8, 0.3, 1.0, 0.9. At the third sample the average is (0.5 + 1.2 + 0.8) / 3 = 0.83. At the fourth it is (1.2 + 0.8 + 0.3) / 3 = 0.77. At the fifth it is (0.8 + 0.3 + 1.0) / 3 = 0.70. At the sixth it is (0.3 + 1.0 + 0.9) / 3 = 0.73. The jumpy input became a gentle line.

The moving average has a hidden cost. It looks back over L samples, so its output trails the true envelope by about (L − 1) / 2 samples. For a 400 ms window that lag is close to 200 ms. A burst has already started when the envelope first admits it. Chapter 9 adds this lag to the other delays in the loop.

In the paper this envelope drove a trigger through a portable computer. After the envelope crossed the threshold, stimulation began 30 to 40 ms later.

Run the chain on a signal

Top to bottom: the raw voltage, the band-passed signal, the rectified signal, and the envelope. The shaded bands are three real bursts. The dashed line is a trigger level halfway between quiet and burst. Drag the window, then drag the filter centre away from 20 Hz.

400 ms
20 Hz

Made-up signal: noise plus three bursts of a 20 Hz wave, sampled at 250 samples per second. The filter is a causal two-pole band-pass 6 Hz wide, as a real-time controller needs. The paper’s window is 400 ms; the rest is illustrative.

The window is a trade

Set the window short, such as 60 ms. The envelope reacts fast, but it also jumps on every noise ripple. The symptom is a trigger that fires when nothing is happening. The measurement is the count of false crossings in the read-out. The fix is a longer window.

Set it long, such as 800 ms. The envelope is smooth, but it climbs slowly. The paper’s Table 2 lists gaps of roughly 0.5 to 1.8 seconds between stimulation bursts in adaptive mode, so bursts come about once a second. A burst of 300 ms through an 800 ms window never reaches its full height, and the trigger comes late or never. The measurement is the lag in the read-out. The fix is a shorter window. The 400 ms of the paper is a compromise between the two failures.

Likewise, a filter centred at the wrong frequency lets the burst through only weakly. Move the centre to 10 Hz and the burst nearly vanishes from the envelope. That is why the team found each patient’s own peak first.

The same chain in code

pythonimport numpy as np
from scipy.signal import butter, sosfilt

def beta_envelope(lfp, fs, f_peak, half_bw=3.0, win_ms=400):
    """lfp: 1-D samples from one bipolar pair, shape (T,). Returns the envelope, shape (T,)."""
    sos  = butter(2, [f_peak - half_bw, f_peak + half_bw], btype="band", fs=fs, output="sos")
    beta = sosfilt(sos, lfp)                  # causal: no look-ahead, (T,)
    rect = np.abs(beta)                       # rectify, (T,)
    L    = int(round(win_ms * fs / 1000))
    return np.convolve(rect, np.ones(L) / L)[: len(lfp)]   # causal moving average, (T,)

A wavelet gives the same result in one move, because a Morlet wavelet is a band-pass filter and an envelope in one object. Chapter 6 uses exactly that for the spinal interface. See the lesson on wavelets, and the lesson on filtering neural signals for filter design.

Why rectify the band-passed signal before averaging?

Chapter 3

The Threshold Controller

Write the rule that turns an envelope into pulses, and watch a loop talk to itself

A patient sits in a chair with the wire connected to a laptop. The laptop shows his beta envelope. Most of the time it rests near a baseline. Every second or so it climbs in a burst, and falls again. The team’s idea was simple: stimulate during the burst, and rest between bursts.

The rule

The 2013 controller had one parameter, a threshold: a level on the envelope. When the envelope rose above it, the laptop sent a trigger to a custom stimulator. Once triggered, stimulation continued until the envelope fell below the threshold again. That is all.

The stimulator gave 130 Hz pulses, each 100 microseconds wide, in a monopolar montage (one contact against a distant return). It ramped up and down over 250 ms, because abrupt switching caused tingling, called paresthesia. After the envelope crossed the threshold, the delay to stimulation onset was 30 to 40 ms. The stimulation voltage was found beforehand by raising it in 0.5 V steps every 3 to 4 minutes until the patient improved without side effects. The mean voltage was 2.1 V.

As a state machine: the controller is either off or on. It switches on when the envelope exceeds the on-threshold. It switches off when the envelope drops below the off-threshold. Between the two, it keeps its state.

s[n]
Whether stimulation is commanded at sample n: 1 is on, 0 is off.
θon
The level the envelope must pass to start stimulation.
θoff
The level the envelope must fall under to stop. The 2013 paper used one level for both, so θoff = θon.
s[n−1]
The previous state, kept when the envelope sits between the two levels. This memory is called hysteresis.

Picking the threshold

The team had no formula. Before each test block they tuned the threshold by hand, to cut the time on stimulation by about 50 percent while keeping the clinical effect. The mean threshold ended up only 3.9 percent (plus or minus 3.8) above the mean beta amplitude. That is just above the baseline.

A threshold that low sounds fragile. It works because the loop is closed. When the burst starts, stimulation starts, and stimulation lowers the beta. The envelope falls, crosses back, and stimulation stops. The burst then wants to return, and the cycle repeats. The controller does not wait for the burst to end. It presses against it.

A worked picture of the tuning. Suppose you record the envelope for ten minutes with no stimulation and sort the values. A threshold at the 56th percentile would put the envelope above it 44 percent of the time. That is the time on you would expect with an open loop. In a closed loop the answer changes, because every stimulation burst lowers the envelope and shortens its own time above the line. So the team could not set the level from a recording alone. They set it live, with stimulation running, and adjusted until about half the stimulation time was gone.

The paper noted one more effect. With a fixed threshold, the share of time on stimulation tended to fall over a block: the mean correlation with elapsed time was −0.23 across patients. The authors read this as a sign that the beta bursts became less frequent. They called for more trials before relying on it.

Tune the threshold

The blue line is the envelope the controller sees. The teal dashes are the two thresholds. The warm strip is stimulation. Start with the gap at zero and the threshold near 1.2, then widen the gap.

1.18
0.00

Toy trace, same as the hero. Burst load left is the burst part of the envelope after stimulation, as a share of the untreated burst part. In this toy, always-on leaves 40 percent and random stimulation with matched time on leaves 68 percent. These are not clinical numbers.

Worked example: chatter

Take a short envelope: 1.25, 1.15, 1.25, 1.15, 1.25, 1.0, and a single threshold of 1.2. The state is 1, 0, 1, 0, 1, 0. Counting the start, that is six switches in six samples. Now use two levels, θon = 1.2 and θoff = 1.1. The 1.15 values sit between the levels, so the state holds. It reads 1, 1, 1, 1, 1, 0: two switches.

This failure is chatter: a controller that flips back and forth because the signal hovers at the threshold. The symptom in a patient is tingling or buzzing at each switch. The measurement is the switch count in the read-out. In the device, a gap of zero near the baseline gives dozens of switches. The fix is the gap. Later work used two thresholds, and the 2024 trial cites a paper on dual-threshold control (Velisar et al., 2019). Press reports say the 2025 Medtronic approval rested on a trial that compared dual-threshold and single-threshold modes.

The opposite failure is a threshold set too high. The controller then misses bursts. Drag the threshold to 2.5 and the read-out says stimulation was on a few percent of the time and most of the burst load stayed. The measurement is the burst load left. The fix is a lower threshold.

The controller in code

pythonclass BetaController:
    def __init__(self, th_on, th_off, ramp_s=0.25, dt=0.02):
        self.th_on, self.th_off, self.on = th_on, th_off, False
        self.amp, self.step = 0.0, dt / ramp_s       # amp in [0, 1], ramps in 250 ms

    def update(self, env):                       # env: one float, the latest envelope
        if not self.on and env > self.th_on:  self.on = True
        elif self.on and env < self.th_off:  self.on = False
        self.amp = min(1.0, max(0.0, self.amp + (self.step if self.on else -self.step)))
        return self.amp * V_STIM                  # volts to the stimulator, 2.1 V on average in 2013
A controller with a single threshold switches stimulation on and off dozens of times a minute because the envelope hovers near the threshold. What is the standard fix?

Chapter 4

The 2013 Trial: Better With Half the Stimulation

Read the experiment like an engineer: what was compared, what was blinded, and what the random control rules out

The wires are still outside the scalp. The patients have several days between two operations, and that is the only window for this experiment. They are tired, after a night without medication. Each block of stimulation can last about ten minutes, and no more. So the design must be tight.

Four conditions, each once

Eight patients with advanced Parkinson’s disease took part. Each one was tested in four conditions, in a random order, once each: no stimulation; continuous DBS (cDBS), the standard always-on mode; adaptive DBS (aDBS), triggered by beta; and random stimulation, bursts of stimulation not tied to beta. Five minutes of rest came before each block. The blocks lasted about 500 to 640 seconds on average.

The clinical score was the hemibody part of the Unified Parkinson’s Disease Rating Scale (UPDRS), items 20, 22 and 23, for the arm opposite to the stimulated side. Raters scored it live, which is unblinded. The sessions were also filmed, and three movement disorder specialists who were not part of the team rated the videos without knowing the condition. Their agreement between raters was 0.52, which is moderate. Raters scored at least 300 seconds into each block, since the effect of stimulation builds up slowly.

The numbers

Without stimulation or medication, the mean hemibody score was 5.8 (unblinded) and 6.3 (blinded). The table shows the mean drop from that baseline.

ConditionUnblinded gainBlinded gainTime on
Continuous54.3%30.5%100%
Random33.7%6.7%43.3%
Adaptive66.2%49.7%44.2%

Adaptive stimulation beat continuous stimulation on both ratings. The paper reports it as 28.7 percent better (unblinded, p = 0.03) and 27.0 percent better (blinded, p = 0.005). Those figures come from the authors’ own comparison of aDBS with cDBS, and we do not rebuild their formula here. The gap between the group means is 11.9 points unblinded (66.2 minus 54.3) and 19.2 points blinded (49.7 minus 30.5).

Notice the unblinded numbers are all higher than the blinded ones. The rater who knows the condition, and wants the patient to do well, scores generously. That is the symptom. The measurement is the gap: 66.2 against 49.7 for the same condition. The fix is the blinded video rating, which is why the team collected it.

Why the random control matters

Suppose the team had stopped at cDBS against aDBS. The adaptive mode is on 44 percent of the time and works better. A sceptic could say: maybe plain intermittency helps. Stimulation switched on and off might avoid a kind of tolerance in the tissue.

The random condition answers the sceptic. It was on for 43.3 percent of the time, close to the 44.2 percent of the adaptive mode (the difference was not significant, p = 0.59), and its gaps between bursts were similar. The only difference was the timing. Random stimulation produced a blinded gain of 6.7 percent, against 49.7 percent for the adaptive mode. So the benefit comes from putting the stimulation where the beta bursts are, and not from the intermittency alone.

Compare the three controllers

Choose a measure. Each bar is one controller, with the number from the 2013 trial. Look at random against adaptive: same time on, very different gain.

All values are from Little et al. 2013 (Ann Neurol 74:449), 8 patients, upper-limb items 20, 22 and 23. Time on for continuous is 100 percent by definition. The paper reports energy for continuous and adaptive only.

The energy bill

The mean electrical energy was 132 microwatts for aDBS against 270 for cDBS, assuming 0.5 kilohm of tissue resistance. A quick check: 44.2 percent of 270 is 119. The measured 132 is a little higher, in the right neighbourhood. The paper does not say what the small gap is made of, and its time-on estimate includes the ramps, so we leave it there.

The authors went on to estimate what this means for the battery. A circuit that tracks one channel of beta should cost about 10 microwatts. Halving the stimulation power would then be enough to double the life of the implanted generator. Average battery life for continuous DBS is under 4 years, and replacing it needs surgery. These are the authors’ estimates, not a measured battery life.

What the trial cannot say

It was a proof of principle. The blocks lasted about ten minutes. Only a few UPDRS items were scored, on one arm, and the stimulation was unilateral. The leads were still externalised, and the stimulator was a custom bench device, not an implant. A bilateral follow-up from the same group (Little et al., J Neurol Neurosurg Psychiatry 2016) reports that two-sided aDBS can improve axial and limb symptoms across drug states. A chronic, blinded, randomized crossover trial came later from another group. Chapter 5 covers it.

The random condition was on for 43.3% of the time, matching the adaptive mode, but gave a far smaller blinded gain. What does this show?

Chapter 5

Choosing the Signal From Data

Learn how the 2024 trial picked a different marker for each patient, and how to score a marker before you trust it

Eleven years after the Oxford trial, a patient has a DBS system that senses and stimulates inside the same implant. His system runs in one mode, then in the other, and he does not know which. This is the design of the 2024 trial by Oehrn and colleagues, from the University of California, San Francisco (Nature Medicine 30:3345).

We could read the abstract, the data statement and the reference list. The full text sits behind a paywall, so we give no more numbers than the abstract does.

What the trial did

Four men with Parkinson’s disease and motor fluctuations took part. All four received both adaptive and continuous DBS, in a blinded randomized cross-over design: the order of the two modes was random, each patient served as his own control, and the people judging did not know the mode. The authors call it a feasibility trial: its job is to show the approach can work, not to prove it does.

The central finding is about the signal. The team looked for the best marker of a patient’s dopamine state (high or low) and of his remaining motor signs. In all four patients, the best marker was a stimulation-entrained gamma oscillation: a fast rhythm that locks to the stimulation itself. The abstract says it was recorded in the subthalamic nucleus or the motor cortex. With that marker driving the controller, the abstract reports improved motor symptoms and quality of life compared with clinically optimized standard stimulation. Press coverage gave about 50 percent improvement on the most bothersome symptom. We treat that as a press figure from four people.

Notice what changed from 2013. The controller is the same kind of rule: a signal, a threshold, an action. The difference is the choice of signal. It came from data, per patient, instead of from a belief that beta fits everyone.

How to score a marker

Suppose you recorded the same patient in a low-dopamine state (off medication, stiff) and a high-dopamine state (on medication, moving well). For each candidate marker, such as beta power in the STN or gamma power in the cortex, you now have a pile of numbers from each state. A good marker puts the two piles far apart.

One measure is d-prime: the distance between the two pile averages, in units of the spread. Another is the area under the ROC curve (AUC): the chance that a random sample from the high state is larger than a random sample from the low state. An AUC of 0.5 is a coin flip. An AUC of 1.0 is perfect.

A worked case. Two piles with averages 1.0 and 2.0 and a common spread of 0.5. The d-prime is (2.0 − 1.0) / 0.5 = 2. For two equal normal piles, AUC = Φ(d′ / √2) = Φ(1.41), which is about 0.92. If the spread grows to 1.0, d-prime falls to 1 and AUC to about 0.76. The same averages become a much weaker marker once the spread grows. This is how a marker can be present on average and still be useless to a controller.

A common way to score a marker is linear discriminant analysis, a classifier that finds the best straight cut between two piles. It is a close cousin of the linear decoders of earlier lessons.

Score the markers

Pick a toy patient, then pick a marker. The top plot shows how that marker spreads in the low state (blue) and the high state (green). The bars show the AUC of all four markers for this patient.

Everything here is simulated: 150 samples per state from two normal piles whose separations are invented, seeded so they repeat. Only the idea is the trial’s: in the real trial an entrained gamma signal, in the STN or in the motor cortex, was the best marker in all four patients (abstract).

From trial to product

On 24 February 2025 the US regulator approved Medtronic’s BrainSense Adaptive DBS, as reported by several trade outlets. Those reports say it was the first approved adaptive DBS system, that it works with the Percept neurostimulator, and that approval rested on a randomized cross-over trial called ADAPT-PD with 68 participants (another report says 85 adults were being evaluated). They describe dual- and single-threshold modes tested against continuous DBS. These are press and company statements, and we did not check the regulator’s own record.

The lesson for an engineer is in the pattern. Stimulation, sensing and the controller sit in the same device, the signal comes from the patient’s own data, and a clinician still sets the thresholds. The loop is partly closed by the machine and partly by the clinic.

When the marker fails

A marker can fail the way a thermostat can: the sensor drifts. The symptom is a patient whose state and whose marker disagree. The measurement is the AUC you recompute on fresh recordings. The fix is to reselect. The 2024 team released their data and the biomarker selection code, with the explicit goal that others can replicate the choice.

Two candidate markers have the same difference between their low-state and high-state averages, but marker B has twice the spread. Which statement is right?

Chapter 6

A Digital Bridge to the Spine

Follow one decision from the brain surface to the leg muscle, and read the shape of the data at every step

A 38-year-old man has had a spinal cord injury for years. His brain still plans to take a step. The plan travels down the spinal cord and mostly stops at the injury, which is an incomplete one in the neck. Below it, the part of the spinal cord that drives his legs is healthy, but it hears too little.

Walking is largely produced in the lower spinal cord (the lumbosacral region). Groups of nerve cells there, called motor pools, each drive one set of muscles, for weight acceptance, propulsion or swing. Electrical stimulation of the dorsal root entry zones, where sensory nerves enter the cord, recruits those motor pools. This is epidural electrical stimulation: current from electrodes laid on top of the cord's protective layer. He had used such stimulation before, in an earlier trial. The paper argues that a system which lets the person set the timing and strength of the stimulation can restore more natural control.

In 2023 the team (Lorach, Galvez and colleagues, with Courtine, Bloch and Charvet as senior authors) closed that gap. Their brain-spine interface (BSI) reads the brain’s intent and sets the stimulation. In the paper’s words, it is a digital bridge across the injury. It has been tested in one participant, in the STIMO-BSI clinical trial.

The parts

Recording. Two WIMAGINE implants sit on the surface of the brain, one over each side of the movement area of the cortex. Each is an 8 by 8 grid of 64 electrodes with a spacing of 4 by 4.5 mm, set in a titanium disc 50 mm wide that is as thick as the skull. This kind of recording is called electrocorticography (ECoG): electrodes on the cortex, under the skull, which see a patch of cortex more clearly than scalp EEG does but less finely than single-neuron probes. The recording map lesson compares them.

Before surgery the team mapped the leg area with a 306-channel magnetoencephalography (MEG) scanner. The leg-related contacts lay on the most medial part of the implant. Hip, knee and ankle movements had different spatial patterns, so the decoder could tell them apart.

Link. A headset with two antennas holds the link. One antenna powers the implant by induction at 13.56 MHz. The other, at 402 to 405 MHz, streams the ECoG to a portable base station that runs the decoder. Only 32 of the 64 contacts on each implant are used, to keep the signal stable at 586 samples per second given the limited radio bandwidth. A quick count: 64 channels at 586 samples per second is 37,504 samples per second. Using all 128 contacts would double the load. The paper does not give bits per sample in the text we read.

Stimulation. A pulse generator sends current to a paddle lead with 16 electrodes on the lumbosacral cord. A library of stimulation programs targets specific muscle groups. The base station sets the amplitude of each program over a wireless link, with a latency of about 100 ms.

The data flow

Run one decision through the chain. Step through it in the device below.

Send one decision down the bridge

Press Send to follow a decision from the brain to the muscle. Or tap a stage to jump to it. The right column is the shape of the data at that stage.

Numbers are from Lorach et al. 2023 (Nature 618:126): 32 of 64 contacts per implant, 586 Hz, 24 wavelet frequencies, a 100 ms step, stimulation updates every 300 ms. The animation timing is only a picture, not a measured latency.

Three details deserve attention. First, the features. The decoder does not read the raw voltage. A bank of Morlet wavelets, centred at 2, 5 to 100 in steps of 5, 125, 150 and 200 Hz, measures how strong each band is. That is 24 frequencies. The wavelet is a band-pass filter and an envelope in one, as in Chapter 2. Epochs of 200 to 500 ms are cut with a 100 ms sliding step and reduced to 2 to 5 time points. So the decoder sees a tensor of channels by 24 frequencies by 2 to 5 time points, every 100 ms.

Second, the output. The decoder outputs probabilities, one per intended joint. A control layer turns them into stimulation amplitudes, rescaled linearly into a range in milliamps that the experimenter sets. The pulse generator receives updated commands every 300 ms. So the decoder predicts about 10 times a second, and the stimulator hears about 3 of those updates each second.

Third, the loop. Unlike the beta controller, no sensor watches the muscle. The loop closes through the person. He feels and sees his legs move, and he adjusts his intent. The man is inside the controller. A decoder that is slightly wrong can still work, because he compensates.

When the link is the limit

The symptom: dropped or noisy samples in the stream. The measurement: samples per second against the radio bandwidth, as in the count above. The fix the team used was to reduce the channel count, trading some spatial detail for a stable sampling rate.

In the brain-spine interface, which part closes the feedback loop?

Chapter 7

Decoding Intent With a Gate and a Hidden Markov Model

Turn a jittery stream of per-window guesses into a stable decision about which leg the person wants to move

The participant stands between his crutches. He pauses on purpose for thirty seconds. Then he decides to take a step with his right leg. If the decoder fires a false step during the pause, the spine gets a burst of current, a leg moves, and he may fall. If the decoder is late at the start of the step, he feels the system fight him. The decoder has two jobs: do not fire early, and do not lag.

The 2023 team reports that during a 30-second instructed pause they saw no false positives, and that the interface did not impair his balance score (Berg Balance Scale) and even improved it slightly. This chapter shows the design that makes this possible.

Intent as a state

A state is one answer to the question: what does he intend right now? The participant could control the hip, knee and ankle on each side, plus rest. That makes seven states. The chance level for seven is 1 in 7, about 14 percent.

Every 100 ms the decoder looks at the newest features (Chapter 6) and gives a probability to each state. This model is called the gate, since it gates which joint gets stimulation. The paper then adds a second model for each joint, an expert, a linear regression that predicts the direction and relative size of the intended movement. Together they form a mixture of multilinear experts.

The gate alone is jittery. One 100 ms window can look like a right-hip attempt because of random fluctuations in the cortex. If the stimulator obeyed every window, the leg would twitch.

Intent changes slowly

People do not change their minds ten times a second. A person who rests at one moment very likely rests 100 ms later. A hidden Markov model (HMM) turns that fact into maths. The hidden state is the true intent. The observation is what the gate sees. A transition matrix T holds the chance of moving from each state to each other state in one step. Staying put gets a high chance, such as 0.9.

The belief about the hidden state is updated in two moves. First predict: spread yesterday’s belief through T. Then correct: multiply by how well each state explains the new window, and rescale so the beliefs add up to 1. If you have met the HMM lesson or the Kalman filter, this is the same predict and correct cycle with discrete states.

bt(j)
The belief that state j is the true intent at step t, after seeing the newest window.
et(j)
How well state j explains the newest window: the gate’s output for j.
∑i
Add over every state i the person could have been in a step ago.
Tij
The chance of going from state i to state j in one step. In the paper it is found by counting transitions during calibration.
bt−1(i)
The belief a step ago. This is the memory.

A worked case with two states, rest and step. Say T keeps the state with chance 0.9. The belief is (rest 0.8, step 0.2). A window arrives that favours step, with e = (0.3, 0.7). Predict: rest = 0.8 × 0.9 + 0.2 × 0.1 = 0.74, and step = 0.8 × 0.1 + 0.2 × 0.9 = 0.26. Correct: 0.74 × 0.3 = 0.222 and 0.26 × 0.7 = 0.182. Rescale by the sum 0.404: the belief is (rest 0.55, step 0.45). One vote for step did not flip the decision. A second identical window gives predict (0.54, 0.46), correct (0.162, 0.322), rescale by 0.484: (rest 0.34, step 0.66). Two votes flip it.

The paper updates the models on the fly: every 15 seconds the gate and the experts are refitted by a recursive method, and the transition matrix is recounted from the 150 new transitions of that period (15 seconds at 10 windows a second). Chapter 8 returns to this.

Smooth the decision

Top lane: what he intends. Middle: the gate’s raw best guess every 100 ms. Bottom: the HMM’s guess. Grey is rest, dark purple is the left hip, light purple is the right hip. Drag the stay chance up and down, and the classifier noise.

0.90
1.2

Toy simulation of three states (rest, left hip, right hip) at 10 windows per second, seeded. The paper has seven states, a trained gate and a counted transition matrix; its numbers are in the text: 74 ± 7 percent accuracy against 14 percent chance, and a decoder latency as low as 1.1 s.

The trade, and the paper’s numbers

Push the stay chance from 0.9 to 0.99 and the false calls barely fall further, while the catch-up time grows (0.35 s to 0.5 s in this toy). With stronger noise or a rarer intent the delay grows more. The symptom is a step that starts late. The measurement is the delay in the read-out. The fix is a lower stay chance. Push it down to 0.5 and the filter does nothing: the symptom is stimulation bursts while resting, measured as seconds of false stimulation. The fix is a higher stay chance. The best value sits between.

With the seven-state decoder, the participant reached an accuracy of 74 ± 7 percent for gradual control of each joint on both sides. The decoder latency was as low as 1.1 s (± 0.15 s s.e.m.). For walking, the team simplified. They dropped the experts and drove the stimulation amplitude with the gate’s largest state probability, changing one joint at a time. Left and right steps never happen together, so one at a time is enough.

You raise the HMM stay chance from 0.9 to 0.99. What happens?

Chapter 8

Calibrating in Minutes, and Staying Calibrated

Learn how a decoder updates its weights while it runs, and why it must forget the past a little

It is the first session after surgery. The participant lies down, and the team asks him to attempt to move one hip, then the other, then rest, in short prompted tasks. Every 15 seconds the decoder takes the newest batch of brain features and the prompt that went with it, and refits itself. Within the first session he controls the hips of an avatar on a screen. From a lying position, in under two minutes, he generates hip muscle torque with an accuracy of 97 percent. After 5 minutes of calibration standing, his hip flexor muscles are about five times more active than when he tries without the interface.

This speed is the point of the design. A decoder that needs hours of data each day would not survive in a home. Calibration has to take the time of a short break.

Online learning

The usual way to fit a model is batch learning: gather all the data, fit once, deploy. The BSI uses online learning: start with a rough model and nudge it with every new batch. The nudge is proportional to the prediction error, the gap between what the model said and what happened.

The paper names the algorithm: a recursive, exponentially weighted version of N-way partial least squares. It fits a linear map from many correlated features to a movement signal. The toy below uses the simpler cousin that shows the same two ideas, recursive least squares (RLS): a running update, and exponential forgetting. If you know the Kalman filter, RLS is a Kalman filter whose hidden state is the set of weights, with a gain that shrinks as certainty grows. The lesson on adaptive Kalman filters shows the same family at work.

wt
The decoder weights after batch t: how much each brain feature counts.
wt−1
The weights before it.
kt
The gain: how far to move. Big when the model is unsure, small when it is sure.
yt − xt⊤ wt−1
The prediction error: what happened minus what the old weights predicted from the features xt.

A worked scalar case. Start with w = 0 and a large uncertainty P = 100. The first sample has feature x = 1 and target y = 2. The gain is k = P x / (1 + P x²) = 100 / 101 = 0.990. The weight jumps to 0.990 × 2 = 1.98, and the uncertainty shrinks to P = 100 − 0.990 × 100 = 0.99. A second sample arrives with x = 1 and y = 2.2. Now k = 0.99 / 1.99 = 0.498, the error is 2.2 − 1.98 = 0.22, and w = 1.98 + 0.498 × 0.22 = 2.09. The first sample moved the weight a lot. The second moved it half as much, since the model had gained confidence.

Why forget

Brain signals drift. Electrode contact shifts, tiredness changes the rhythms, and the person's own strategy changes. The weights that were right at 10:00 are slightly wrong at 11:00. An RLS that trusts all its history becomes too sure of itself and stops updating. The cure is a forgetting factor λ slightly below 1. Each step, old data count λ times as much as before. The effective memory is about 1 / (1 − λ) samples. With λ = 0.98 that is 50 samples; with λ = 0.999 it is 1,000.

The paper calls its version exponentially weighted. The decoder keeps predicting with its current weights while the models update in parallel, every 15 seconds, whenever updating is allowed. The earlier lessons on drift and recalibration and closed-loop refitting cover the neuroscience of why a decoder must be refreshed.

Learn while it runs

Top: the decoder’s error in its weights over 60 seconds. Bottom: one true weight (dashed) and the estimate (solid). Choose how the brain changes, then drag the forgetting factor.

0.980

Toy regression with 3 features at 10 samples per second and a noise level of 0.3, seeded. It uses plain exponentially weighted least squares, not the paper’s N-way partial least squares. The paper’s numbers are in the text: under 2 minutes to 97 percent hip torque accuracy, 5 minutes to fivefold hip flexor activity.

The trade, again

Set λ = 1.0 and choose “Sudden jump”. The estimate barely moves after the jump, since it trusts 300 old samples. The symptom is a decoder that stays wrong after a change. The measurement is the recovery time in the read-out. The fix is a smaller λ.

Set λ = 0.90 and choose “Steady”. The memory is only about 10 samples, so the estimate wobbles around the truth. The symptom is jitter in the stimulation. The measurement is the weight error that never settles. The fix is a larger λ.

The results over a year show why this matters. Using updated models, the accuracy over steps was 0.92 at the first session (13 steps), 0.93 at 2 months (46 steps), 0.97 at 6 months (41 steps) and 0.97 at 11 months (29 steps). The reliability stayed stable over a year, including independent use at home, which the paper reports for one participant.

A decoder keeps getting worse after the signals change suddenly, yet it was excellent before. Its forgetting factor is 0.9999. What is the most likely fix?

Chapter 9

When the Loop Misbehaves

See how delay and gain turn a helpful loop into an oscillator, and list what an implant must check before it acts

You step into a shower with a long pipe. The water is cold. You turn the tap toward hot. Nothing happens for several seconds. You turn it further. Then scalding water arrives. You turn it back, hard, and wait again. You have built an oscillator out of a tap, a pipe and a nervous reaction. The cause was the delay between your action and its effect.

Every closed-loop implant has a pipe like this. The sensor reads with a delay, the computer decides with a delay, and the tissue answers with a delay. The loop works when the corrections arrive before the situation has moved on. It fails when they arrive late and too strong.

Adding up the delays

For the beta controller, count the delays on the way round. A 400 ms moving average lags the true envelope by about half its length, which is 200 ms. The paper reports a 30 to 40 ms gap from threshold crossing to stimulation onset. The 250 ms ramp means the stimulation reaches full strength about 125 ms later on average. A rough total is 200 + 35 + 125 = 360 ms. That sum is our estimate, not a figure from the paper.

For the brain-spine interface, the paper reports a stimulation latency of about 100 ms, predictions every 100 ms and stimulation updates every 300 ms. A change of intent waits on average 50 ms for the next prediction and 150 ms for the next update, then 100 ms to take effect: roughly 300 ms, before counting the filter. The paper also measured a decoder latency as low as 1.1 s for the seven-state task, which includes the time to become sure. Note that the person is part of this loop: he sees the result and adapts.

Gain and delay together

A useful rule of thumb comes from the loop itself. Compare the delay with how fast the signal moves on its own. In the toy below the signal fades with a time constant of about 0.4 s. A delay of 200 ms is half of that, so the correction still arrives while the problem is alive. A delay of 800 ms is twice that, so it arrives after the problem has changed. The slower the signal, the more delay you can afford. The faster the burst, the less.

Take the simplest model. The quantity you care about, say the beta envelope x, decays on its own with a time constant of about 0.4 s. The controller pushes against it with a strength proportional to what it saw d steps ago. Each step is 20 ms. The push is g times 0.15 times x. A big g corrects hard. A big d means the correction answers an old reading.

A small gain with a short delay settles smoothly. A large gain with a long delay overshoots, and the overshoot sets off an even larger correction the other way. The result is a growing swing. In a real stimulator, the swing stops at the safe maximum current, so you see a square wave at the limit.

Break the loop

At one second a burst kicks the signal. The line shows how the loop answers over ten seconds. The dashed lines mark the stimulator’s limit. Raise the delay first, then the gain.

200 ms
0.60

Toy loop: x[t+1] = 0.95 x[t] − 0.15 g x[t − d] + kick, with 20 ms steps and a limit at 6 units. It is a teaching model, not a model of any implant. The delay sums in the text are estimates built from the papers’ reported timings.

Try it. At 200 ms of delay and a gain of 0.6, the loop settles after one swing. At 600 ms and the same gain, the signal keeps ringing. At a gain of 1.2 with 400 ms, it runs away to the limit. The symptom in a patient would be stimulation that pulses on its own rhythm, or a leg that swings and cannot stop. The measurement is the amplitude late in the run, in the read-out. The fix is a lower gain, a shorter delay, or both. You rarely get the delay down for free, so you lower the gain.

The other ways a loop fails

Delay is only one entry. Each stage of sense, decide and act has its own failure, and the two papers list the checks that guard against them.

StageSymptomMeasureFix
SenseStimulation pulses contaminate the recordingStimulation about 2 V against a beta signal of about 2.6 µV (Little 2013; ratio is our arithmetic)Bipolar recording and a common-mode rejection amplifier
DecideA false step while standingFalse positives during a held pauseHMM smoothing; none seen in a 30 s pause (Lorach 2023)
DecideChatter at the thresholdSwitches per minuteTwo thresholds (Chapter 3)
ActTingling when stimulation startsPatient report at each switchA 250 ms ramp (Little 2013)
ActToo much charge into tissueCharge density, DC currentLimit under 30 µC/cm² and a DC-blocking capacitor (Little 2013)
Whole loopThe interface is offWhat the user can do without itA safe default: with the BSI off he could not step, and walking resumed on turn-on (Lorach 2023)

The last row is a design choice worth noticing. The off state of the BSI is passive, not harmful. Stimulation that depends on a live decoder stops when the decoder stops. For a spine interface that is the safe direction.

A controller rings and then runs away when the loop delay is long and the gain is high. Which change is most likely to restore stable behaviour?

Chapter 10

Field Guide: Closed-Loop Neuromodulation on One Page

Review both implants, keep the numbers and the code, and see where the lesson sits in the series

You can now follow a closed-loop implant from the wire to the tissue and back. Two systems carried the lesson. The beta controller senses a brain rhythm and gates stimulation. The brain-spine interface decodes intent and sets stimulation for the spinal cord. Both are sense, decide, act, and both fail in the same few ways.

The one-paragraph summary

A closed-loop neuromodulation system measures a signal from the nervous system and uses it to set stimulation. In adaptive DBS, a band-passed, rectified and smoothed beta envelope from the stimulating wire is compared with a threshold, and stimulation follows the bursts, ramped to avoid tingling. In 2013 this gave a larger blinded motor gain than continuous stimulation, with about 44 percent of the stimulation time, and a random control showed the timing matters. In 2024 a small blinded crossover trial chose its marker per patient from data, and found stimulation-entrained gamma best in all four. In the brain-spine interface, ECoG wavelet features feed a gate with a hidden Markov model and a set of linear experts, calibrated online in minutes, and the output sets spinal stimulation amplitudes. Delay and gain decide whether any such loop is stable.

The numbers that matter

WhatNumberSource and caution
Patients, 20138; four conditions, each once; blocks about 8 to 11 minutesLittle 2013; a proof of principle
Blinded motor gain over no stimulationaDBS 49.7%; cDBS 30.5%; random 6.7%Little 2013; three blinded video raters, agreement 0.52
Unblinded motor gainaDBS 66.2%; cDBS 54.3%; random 33.7%Little 2013; higher than blinded in every condition
Time on stimulationaDBS 44.2%; random 43.3%; cDBS 100%Little 2013
Energy132 µW against 270 µWLittle 2013; assumes 0.5 kΩ; battery doubling is the authors’ estimate
Envelope and timing400 ms average; 30 to 40 ms trigger delay; 250 ms ramp; 130 Hz, 100 µs pulsesLittle 2013
Chronic adaptive trial, 20244 patients; entrained gamma best in all fourOehrn 2024 abstract only; feasibility trial
Adaptive DBS approvalUS, 24 Feb 2025; ADAPT-PD, 68 peopleTrade press reporting company and regulator news; not checked at the source
Brain-spine hardware2 implants, 8×8 electrodes, 32 contacts used each, 586 Hz; 16-electrode spinal leadLorach 2023; one participant
Features and timing24 wavelet frequencies; 100 ms step; stimulation update every 300 ms; latency about 100 msLorach 2023
Decoder7 states; 74 ± 7% against 14% chance; latency as low as 1.1 sLorach 2023
Calibrationunder 2 min to 97% hip torque accuracy; 5 min to fivefold hip flexor activityLorach 2023
Stabilitystep accuracy 0.92, 0.93, 0.97, 0.97 at first session, 2, 6 and 11 monthsLorach 2023, with updated models

The core, as code

Chapter 2 gave the envelope and Chapter 3 the controller. These three pieces add the decoder side. Each takes a few lines.

pythonimport numpy as np

def hmm_step(belief, T, emission):
    """belief (S,), T (S, S) with rows summing to 1, emission (S,) -> new belief (S,). Chapter 7."""
    predicted = T.T @ belief                  # spread the old belief through the transitions
    posterior = predicted * emission          # weigh by how well each state explains the newest window
    return posterior / posterior.sum()

class OnlineRLS:
    """Exponentially weighted recursive least squares. Chapter 8 (the paper uses N-way PLS)."""
    def __init__(self, n_feat, lam=0.98):
        self.w, self.P, self.lam = np.zeros(n_feat), 100.0 * np.eye(n_feat), lam
    def update(self, x, y):                  # x: (n_feat,) features, y: the target
        Px = self.P @ x
        k  = Px / (self.lam + x @ Px)          # gain: big when unsure
        self.w = self.w + k * (y - x @ self.w) # move by gain times error
        self.P = (self.P - np.outer(k, Px)) / self.lam
        return self.w

def to_current(p_state, i_min, i_max):
    return i_min + (i_max - i_min) * p_state       # linear rescale into a preset range, in mA

Checklist before you close a loop

  1. Signal: does it move with the need, per patient, on fresh data? Score it with an AUC or a similar measure.
  2. Control: is there a random control with the same time on, and a blinded rating?
  3. Chatter: two thresholds, or a minimum time on?
  4. Delay: have you added up the filter, compute, link, ramp and tissue? Is the gain low enough for that sum?
  5. Drift: does the model forget, and can someone freeze it?
  6. Off state: what does the person get when the system stops?

Where this sits

The lesson on the Kalman decoder and closed-loop refitting showed decoders for a cursor. Here the output is a current into tissue instead of a cursor on a screen, which raises the stakes on every failure above. The lesson on real-time closed-loop systems covers the compute side of the same loop, and drift and recalibration covers why Chapter 8 matters.

Keep going

Sources and credit

Every number in this lesson comes from these sources, which we opened ourselves. Little et al., “Adaptive deep brain stimulation in advanced Parkinson disease”, Annals of Neurology 74:449–457 (2013), read in full. Lorach et al., “Walking naturally after spinal cord injury using a brain–spine interface”, Nature 618:126–133 (2023), read in full. Oehrn et al., “Chronic adaptive deep brain stimulation versus conventional stimulation in Parkinson’s disease: a blinded randomized feasibility trial”, Nature Medicine 30:3345–3356 (2024): abstract, data statement and reference list only, since the full text is paywalled. The bilateral follow-up is Little et al., J Neurol Neurosurg Psychiatry 87:717 (2016), abstract only. The 2025 approval of Medtronic BrainSense Adaptive DBS and the ADAPT-PD trial size come from trade press (for example News-Medical) and count as company and press claims.

The studies are the work of their authors: Simon Little, Peter Brown and colleagues in Oxford; Henri Lorach, Grégoire Courtine, Jocelyne Bloch, Guillaume Charvet and colleagues in Lausanne and Grenoble; and the authors of the 2024 San Francisco trial. The code in this lesson is our own teaching sketch.

The takeaway. A closed loop is sense, decide, act, with the result fed back. It saves stimulation and can do more good than a fixed setting, but only if the signal tracks the need, the controller does not chatter, the model keeps up with drift, and the total delay is small enough for the gain. Each of those is a measurement you can take before you trust the loop.
Which design choice most directly protects a standing user from a false step when the per-window decoder is noisy?

Now press Present or Teach and explain one loop out loud, from memory: what it senses, the rule it follows, what the random control showed, how the decoder smooths and learns, and which delays add up. Then go back to the controllers at the top, switch between random and adaptive at the same threshold, and say why the same time on gives different benefit.

Closed-Loop Neuromodulation: BCI series, lesson 27
Little 2013 · Oehrn 2024 · Lorach 2023 · Back to Gleams