Brain-Machine Interfaces¶
A brain-machine interface builds a direct digital bridge between living neural tissue and external computers, translating faint electrical patterns into movement, speech, and sensation. Closing chapter 12, this section traces the physics of neural recording, the signal processing and deep decoding models that turn thoughts into words, the challenge of long-term biological drift, and the ethics of human-AI symbiosis.
Closing the Bridge Between Living Cortex and Silicon¶
-
Think about how astonishingly slow your natural output channels are compared with the richness of your inner mind. Right now, billions of cortical neurons are weaving memories, visual imagery, and subtle grammatical choices in parallel, yet to share a single idea with a computer you have to funnel everything through clumsy mechanical fingers tapping keys or vocal cords vibrating air.
-
A Brain-Machine Interface (BCI) bypasses muscles and peripheral nerves entirely, establishing a direct electronic communication pathway between living brain tissue and a digital processor. In chapter 12 (NeuroAI), we studied how biological neurons fire discrete action potentials and coordinate across low-dimensional neural manifolds. A BCI puts that exact theory into physical practice, listening to live cortical populations in real time and, in bidirectional systems, writing structured sensory information back into the brain.
-
Today's most transformative BCIs are deeply humane medical technologies. For a person living with amyotrophic lateral sclerosis (ALS), a brainstem stroke, or high spinal cord injury, motor cortex often remains vibrantly alive even when the pathways down to the hands or tongue have been severed. By reading intended hand movements or attempted speech directly from cortex, clinical BCIs are already helping paralysed individuals type emails, steer robotic arms, and speak fluidly again through synthesised voices.
The Recording Spectrum and the Physics of Signal vs Invasiveness¶
- Every hardware decision in BCI engineering collides with one stubborn law of physics. Individual cortical neurons emit tiny electrical currents measured in microvolts, and the human skull is a thick, electrically resistive shield that smears and attenuates those signals before they ever reach the outside world.
-
Imagine trying to follow a quiet conversation inside a concert hall while pressing your ear against the brick wall outside. You can tell when the whole audience cheers or claps in rhythm, yet you can never pick out one person's whispered sentence. Moving electrodes closer to the neurons sharpens the signal dramatically, yet each millimetre inward increases surgical complexity and biological risk. This creates three distinct tiers along the BCI recording spectrum.
- Non-invasive interfaces (EEG, fNIRS, MEG). Electroencephalography (EEG) places metal sensors on the scalp to measure summed electrical potentials from tens of millions of synchronously active neurons. Functional near-infrared spectroscopy (fNIRS) shines gentle infrared light through the scalp to track slow blood-oxygenation changes, while magnetoencephalography (MEG) uses ultra-sensitive magnetometers in magnetically shielded rooms to measure tiny neural magnetic fields. Non-invasive headsets require zero surgery and excel at tracking sleep stages, epileptic rhythms, and coarse attention states, yet spatial blurring across centimetres and low signal bandwidth (typically below \(40\text{--}100\,\text{Hz}\)) make rapid, high-precision speech or dexterous finger decoding notoriously difficult.
- Semi-invasive interfaces (ECoG and endovascular Stentrodes). Electrocorticography (ECoG) lays a thin, flexible sheet of electrodes directly on the surface of the brain beneath the skull without piercing cortical tissue. Because the skull barrier is gone, ECoG cleanly captures millimetre-scale population activity up to \(200\,\text{Hz}\). Even more ingeniously, the Stentrode threads a tiny mesh of electrodes through a blood vessel in the neck up into the superior sagittal sinus next to motor cortex, much like a cardiac stent, achieving intracranial signal quality without open-skull craniotomy.
- Invasive intracortical microelectrodes. To hear individual neurons speak, probes must sit within tens of micrometres of living cell bodies inside the cortex. The clinical workhorse for two decades has been the Utah array, a rigid four-millimetre silicon bed of roughly \(100\) sharp needles that has powered landmark human cursor and speech trials. Newer designs such as Neuralink's flexible polymer threads shrink each electrode to a width thinner than a human hair and stitch thousands of recording channels into cortex using surgical robots, allowing probes to sway gently as the brain pulses with every heartbeat.
-
Even the finest intracortical implant faces a fierce biological opponent called biocompatibility. Living brain tissue is as soft as warm tofu, whereas silicon is orders of magnitude stiffer. Microscopic mechanical mismatch triggers the brain's resident immune cells (microglia and astrocytes) to wrap the foreign electrode in an insulating sheath of glial scarring, gradually dimming recorded spike amplitudes over months and years. Minimising probe stiffness and footprint remains one of the grand materials-science challenges of modern neurotechnology.
Neural Signal Acquisition and Preprocessing¶
-
Raw voltage streaming off an intracortical electrode at \(30\,\text{kHz}\) (thirty thousand samples every second per channel) looks at first glance like chaotic radio static. Buried inside that single wire are two complementary biological signals, which engineers separate using the exact digital signal processing (DSP) and spectral filtering tools introduced in chapter 09.
- Action potentials (spikes). Passing the \(30\,\text{kHz}\) trace through a high-pass filter above \(300\,\text{Hz}\) strips away slow baseline waves and reveals sharp \(1\,\text{ms}\) voltage dips whenever a nearby neuron fires. A threshold detector (often set at \(-4.5\) times the background noise standard deviation) snips out each spike waveform. Because one electrode tip can overhear two or three neighbouring neurons at once, spike sorting projects those tiny \(1\,\text{ms}\) waveforms onto their top principal components (PCA from chapter 02) and clusters distinct waveform shapes into separate single units. In high-channel clinical BCIs, decoders often skip fragile spike sorting and simply count threshold crossings per \(20\,\text{ms}\) bin, which turns out to be remarkably fast and robust.
- Local Field Potentials (LFPs). Low-pass filtering the exact same wire below \(300\,\text{Hz}\) captures the collective synaptic hum of thousands of surrounding cells. Breaking LFPs into frequency bands via the Fourier transform (chapter 09) exposes rich physiological rhythms, including delta (\(1\text{--}4\,\text{Hz}\), deep sleep), theta (\(4\text{--}8\,\text{Hz}\), memory and navigation), alpha and mu (\(8\text{--}13\,\text{Hz}\), idling visual and motor cortex), beta (\(13\text{--}30\,\text{Hz}\), movement suppression and posture), and especially high-gamma (\(70\text{--}200\,\text{Hz}\)), whose power tracks local population firing rate so faithfully that ECoG speech BCIs rely on it heavily.
-
Before any neural decoder sees the features, rigorous artefact rejection must scrub away non-brain contamination. Power sockets inject relentless \(50\,\text{Hz}\) or \(60\,\text{Hz}\) sinusoidal hum (removed with narrow notch filters), jaw clenching and eye blinks swamp scalp EEG with millivolt muscle bursts, and head motion shakes electrode cables. Common average referencing subtracts the instantaneous mean across all channels to cancel shared electrical interference, while blind source separation methods like Independent Component Analysis isolate and delete blink components cleanly.
Neural Decoding Architectures¶
- Once cleaned spike counts or high-gamma features arrive every \(10\text{--}20\,\text{ms}\), a neural decoder translates those living electrical patterns into continuous motor commands or discrete words. Over the past twenty years, decoding architectures have evolved from elegant linear state-space models to deep sequence networks.
Classical Motor Decoding with Wiener and Kalman Filters¶
-
Suppose a paralysed user imagines moving a computer mouse toward an icon on screen. The simplest classical approach is a Wiener filter, which predicts cursor velocity \(\hat{\mathbf{v}}_t\) as a linear combination of recent neural firing vectors across the past \(L\) time bins, fitted via ordinary least squares (chapter 02). Wiener filters are blisteringly fast, yet because neural spikes are noisy, the decoded cursor tends to jitter wildly.
-
A Kalman filter solves that jitter by combining two complementary pieces of knowledge (the same Bayesian state-estimation logic behind robotics in chapter 14). First, a state transition model encodes the physical prior that human hands move smoothly rather than teleporting randomly. Second, a linear observation model maps intended kinematic state \(\mathbf{x}_t\) (position, velocity, and bias) to expected neural firing rates \(\mathbf{y}_t\).
- Here \(\mathbf{w}_t \sim \mathcal{N}(0, Q)\) is process noise and \(\mathbf{v}_t \sim \mathcal{N}(0, R)\) is neural observation noise. At every \(20\,\text{ms}\) tick, the Kalman filter predicts where the cursor should coast next, compares the predicted neural firing \(C\hat{\mathbf{x}}_{t|t-1}\) against the actual spikes \(\mathbf{y}_t\) arriving from motor cortex, and blends the two using the optimal Kalman gain \(K_t\). The result is a buttery-smooth 2D or 3D cursor that patients can learn to steer accurately within minutes.
Deep Sequence Decoders for Imagined Handwriting and Speech¶
-
Pointing at letters on an on-screen keyboard tops out around \(10\text{--}15\) words per minute. To unlock natural human communication speed, modern clinical BCIs decode richer, higher-dimensional motor intentions directly using recurrent neural networks (GRUs and RNNs) and Transformers.
-
In a landmark 2021 demonstration by Willett and colleagues, a paralysed participant simply imagined holding a pen and writing letters on paper. Because each letter traces a distinct curved trajectory, the motor cortex generated wildly separable spatiotemporal patterns, allowing an RNN decoder to type at \(90\) characters per minute. Even more dramatically, recent speech BCIs record from ventral speech motor cortex while a participant silently attempts to speak full sentences, decoding articulatory commands at \(60\text{--}80\) words per minute (approaching half the speed of natural conversation).
-
Two machine-learning pillars from earlier chapters make these speech decoders work so accurately.
- Connectionist Temporal Classification (CTC) loss. Nobody speaks at robotic metronome speed, and we have no millisecond-by-millisecond labels telling us exactly when a silent speaker started the phoneme "s" inside an imagined sentence. Just as in automatic speech recognition (chapter 10), the RNN outputs a probability distribution over phonemes plus a special blank token at every \(20\,\text{ms}\) frame, and CTC loss sums over all valid monotonic alignments automatically during training.
- Language model rescoring. Raw neural recordings remain noisy, so the decoder might hesitate between two similar-sounding phoneme sequences like "wreck a nice beach" and "recognise speech". Passing the top beam-search candidates through a modern statistical or neural language model (chapter 07) scores each sentence by linguistic plausibility, slicing word error rates in half and turning noisy neural phonemes into crisp, conversational English.
Non-Stationarity, Drift, and Manifold Alignment¶
-
Here is the secret frustration that kept early BCIs trapped inside university labs. A linear or deep decoder trained carefully on Monday morning often performs noticeably worse by Thursday afternoon, and can fail completely a month later.
-
This breakdown happens because living brains are non-stationary. Microscopic shifts of just twenty micrometres between an electrode tip and neighbouring cells (electrode micromotion), slow glial encapsulation, and natural synaptic plasticity mean that channel \(42\) gradually stops listening to Neuron A and starts picking up Neuron B. From the decoder's naive viewpoint, someone secretly scrambled the wiring overnight!
-
Remarkably, the neural manifold discovery we met earlier in this chapter provides an elegant mathematical escape. Even as individual recorded neurons come and go across weeks, the population's collective activity still lives on the exact same low-dimensional neural manifold, merely viewed from a slightly rotated camera angle.
-
Imagine watching a dancer perform the same waltz on Day 0 and Day 30, except someone moved your tripod slightly to the left on Day 30. You do not need to re-learn what a waltz is from scratch. You only need to find the rigid rotation matrix \(R\) that aligns Day 30's latent trajectories \(\mathbf{Z}_k \in \mathbb{R}^{T \times d}\) back onto Day 0's reference manifold \(\mathbf{Z}_0 \in \mathbb{R}^{T \times d}\). This is the classic orthogonal Procrustes problem.
- Computing the Singular Value Decomposition (chapter 02) of the cross-covariance matrix \(\mathbf{Z}_k^\top \mathbf{Z}_0 = U \Sigma V^\top\) yields the globally optimal rotation in one closed-form line, \(R^\star = U V^\top\). Closely related methods use Canonical Correlation Analysis (CCA) or unsupervised distribution matching to realign manifolds automatically during everyday use, keeping a fixed decoder accurate for months without forcing patients through tedious daily calibration drills.
Bidirectional BCIs and Neural Stimulation¶
-
Reading commands out of motor cortex is only half of how a healthy body interacts with the world. Try picking up a fragile paper coffee cup when your fingertips are completely numb from winter cold. Without instant tactile feedback telling you how hard you are squeezing, you either crush the cup or drop it.
-
Bidirectional BCIs close the sensory loop by both reading neural intent and writing information directly back into the brain via tiny, charge-balanced electrical pulses.
- Intracortical Microstimulation (ICMS). When pressure sensors embedded in the fingertips of a robotic prosthetic hand touch an object, the BCI translates force measurements into microampere pulse trains delivered to primary somatosensory cortex (S1). Participants report genuine, localised feelings of taps, pressure, and even surface texture seeming to come directly from their paralysed fingers, cutting object-grasping times nearly in half.
- Closed-loop Deep Brain Stimulation (DBS). Traditional open-loop brain pacemakers for Parkinson's disease fire continuous electrical pulses twenty-four hours a day, draining implanted batteries and occasionally causing speech or mood side effects. Modern adaptive closed-loop DBS continuously listens for pathological beta-band oscillation bursts in the basal ganglia (or early pre-seizure signatures in drug-resistant epilepsy) and delivers targeted stimulation only at the exact second it is needed.
-
Crucially, once a BCI runs in a closed loop, something extraordinary happens. Not only does the AI decoder adapt to the user, the living brain adapts to the decoder through neuroplasticity! Over days of practice, motor cortex neurons subtly reshape their tuning curves to make the prosthetic arm or cursor easier to drive, forming a genuine co-adaptive partnership between biological and artificial intelligence.
Ethics, Neural Privacy, and the Horizon of Human-AI Symbiosis¶
-
Because neural signals sit right at the source of human perception, intention, and emotion, BCIs raise ethical questions deeper than any previous computing device. A smartphone sees what you choose to type, whereas a high-bandwidth neural implant could potentially glimpse fatigue, stress, subconscious bias, or unspoken inner speech before you ever decide to share it.
-
Protecting human dignity in the age of neurotechnology rests on four emerging ethical commitments.
- Neural privacy and cognitive liberty. Scholars and legal advocates increasingly argue for explicit neurorights, establishing that raw brain recordings belong strictly to the individual, should be processed on-device whenever possible, and can never be mined for advertising, workplace surveillance, or coercive interrogation.
- Agency and authorship. When a language model helps autocomplete a paralysed speaker's noisy neural phonemes, the system must stay scrupulously transparent and faithful to the user's true intent rather than subtly steering their voice toward generic corporate phrasing.
- Long-term stewardship and right to repair. Unlike a forgotten app on your phone, a neural implant sits inside a human skull. Early real-world tragedies where medical startups went bankrupt and left patients with unsupported, unmaintained retinal or neural hardware prove that clinical implants require binding long-term maintenance funds and open hardware/software standards.
- Equitable access. Restorative neurotechnology should lift people living with paralysis, blindness, and neurological disease across every income bracket rather than widening inequality into a biological divide.
-
Stepping back across all six sections of NeuroAI, it is worth pausing to appreciate how tightly neuroscience and artificial intelligence now reinforce one another. From single spiking neurons and cortical hierarchies to representational alignment, biologically plausible plasticity, active inference, and gentle bidirectional neural bridges, studying the living brain gives us deeper blueprints for intelligent machines while modern AI gives us sharper lenses for healing injury and understanding ourselves. In the next two chapters, we carry those lessons straight into unified Multimodal Learning (chapter 13) and physically embodied Autonomous Systems (chapter 14).
Take-Home¶
- Brain-machine interfaces create a direct electronic bridge between living cortex and computers, turning motor intentions into movement or speech and restoring lost independence for people with severe paralysis.
- The skull blurs and damps faint microvolt neural signals, imposing a fundamental tradeoff from safe, coarse non-invasive scalp EEG through semi-invasive ECoG and endovascular Stentrodes down to high-bandwidth \(30\,\text{kHz}\) intracortical arrays that face surgical risk and glial scarring.
- Digital signal processing splits a single \(30\,\text{kHz}\) electrode trace into discrete action potentials (spikes) above \(300\,\text{Hz}\) and local field potential rhythms (especially high-gamma \(70\text{--}200\,\text{Hz}\)) below \(300\,\text{Hz}\), after scrubbing mains hum and motion artefacts.
- Smooth cursor control relies on state-space Kalman filters, while modern speech BCIs achieve \(60\text{--}80\) words per minute by pairing deep sequence decoders (RNNs and Transformers trained with CTC loss) with language model rescoring.
- Because electrode micromotion shifts recorded units over time, long-term BCIs align drifting recordings onto stable low-dimensional neural manifolds via Procrustes or CCA, while bidirectional stimulation closes the sensory loop and demands fierce protection of neural privacy and cognitive liberty.
Coding Tasks (use CoLab or notebook)¶
-
Simulate a synthetic high-rate neural electrode recording containing action potentials from two nearby pyramidal neurons buried in background noise. Detect spikes via amplitude thresholding, extract \(1\,\text{ms}\) snippets around each event, and run SVD/PCA spike sorting to separate the two neurons cleanly.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(10) fs, n_samples, win = 30000.0, 7500, 30 # 0.25 s at 30 kHz, 1 ms window t_w = jnp.linspace(0.0, 1.0, win) template_a = -4.2 * jnp.exp(-((t_w - 0.35) / 0.10) ** 2) + 1.8 * jnp.exp(-((t_w - 0.65) / 0.16) ** 2) template_b = -2.8 * jnp.exp(-((t_w - 0.32) / 0.14) ** 2) + 2.6 * jnp.exp(-((t_w - 0.60) / 0.14) ** 2) # Assemble planted spikes functionally via concatenated segments key, k_noise, k_lbl, k_amp = jax.random.split(key, 4) spike_starts = list(range(80, n_samples - 80, 140)) true_labels = (jax.random.uniform(k_lbl, (len(spike_starts),)) > 0.5).astype(jnp.int32) amp_jitter = 1.0 + 0.08 * jax.random.normal(k_amp, (len(spike_starts),)) segments, cursor = [], 0 for idx, start in enumerate(spike_starts): if start > cursor: segments.append(jnp.zeros(start - cursor)) tmpl = template_a if int(true_labels[idx]) == 0 else template_b segments.append(tmpl * amp_jitter[idx]) cursor = start + win if cursor < n_samples: segments.append(jnp.zeros(n_samples - cursor)) trace = 0.45 * jax.random.normal(k_noise, (n_samples,)) + jnp.concatenate(segments) # Threshold crossing detection and 1 ms waveform extraction noise_std = float(jnp.median(jnp.abs(trace)) / 0.6745) thresh = -4.0 * noise_std below = trace < thresh snippets, i = [], 15 while i < n_samples - 20: if bool(below[i]): trough = i + int(jnp.argmin(trace[i:i + 15])) if trough >= 10 and trough + 20 <= n_samples: snippets.append(trace[trough - 10:trough + 20]) i = trough + 30 else: i += 1 W = jnp.stack(snippets, axis=0) W_c = W - jnp.mean(W, axis=0, keepdims=True) _, _, Vt = jnp.linalg.svd(W_c, full_matrices=False) Z_pca = jnp.dot(W_c, Vt[:2].T) # Two-means clustering in PC1-PC2 space c0, c1 = Z_pca[0], Z_pca[1] for _ in range(15): assign = (jnp.sum((Z_pca - c1) ** 2, axis=1) < jnp.sum((Z_pca - c0) ** 2, axis=1)).astype(jnp.float32) c0 = jnp.sum(Z_pca * (1.0 - assign)[:, None], axis=0) / jnp.maximum(jnp.sum(1.0 - assign), 1.0) c1 = jnp.sum(Z_pca * assign[:, None], axis=0) / jnp.maximum(jnp.sum(assign), 1.0) print(f"Detected {W.shape[0]} spikes (planted {len(spike_starts)}), noise std: {noise_std:.2f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(jnp.arange(1500) / fs * 1000.0, trace[:1500], color="#3498db", lw=0.9) axes[0].axhline(thresh, color="#e74c3c", ls="--", lw=1.2, label="Threshold") axes[0].set_title("Simulated 30 kHz Voltage Trace (First 50 ms)"); axes[0].set_xlabel("Time (ms)"); axes[0].set_ylabel("Voltage"); axes[0].legend() axes[1].scatter(Z_pca[assign == 0, 0], Z_pca[assign == 0, 1], color="#9b59b6", alpha=0.75, label="Unit 1") axes[1].scatter(Z_pca[assign == 1, 0], Z_pca[assign == 1, 1], color="#27ae60", alpha=0.75, label="Unit 2") axes[1].set_title("PCA Spike Sorting Clusters"); axes[1].set_xlabel("PC 1"); axes[1].set_ylabel("PC 2"); axes[1].legend() plt.tight_layout(); plt.show() -
Implement a Kalman filter neural cursor decoder from scratch. Simulate a smooth 2D reaching trajectory driving 40 cosine-tuned motor cortex neurons with noisy firing rates, compare raw instantaneous least-squares velocity decoding against recursive Kalman filtering, and inspect how much smoother and more accurate the decoded path becomes.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(21) T, dt, n_neurons = 220, 0.05, 40 t = jnp.arange(T) * dt X_true = jnp.stack([jnp.sin(0.9 * t), 0.65 * jnp.sin(1.8 * t), 0.9 * jnp.cos(0.9 * t), 1.17 * jnp.cos(1.8 * t)], axis=1) # 40 cosine-tuned motor cortex neurons observing velocity with Gaussian spike noise key, k_pref, k_base, k_noise = jax.random.split(key, 4) pref = jax.random.uniform(k_pref, (n_neurons,), minval=0.0, maxval=2.0 * jnp.pi) C_true = jnp.concatenate([jnp.zeros((n_neurons, 2)), jnp.stack([jnp.cos(pref), jnp.sin(pref)], axis=1) * 1.4], axis=1) baseline = 2.0 + 0.5 * jax.random.normal(k_base, (n_neurons,)) Y_neural = baseline[None, :] + jnp.dot(X_true, C_true.T) + 0.95 * jax.random.normal(k_noise, (T, n_neurons)) # Calibrate linear observation matrix C_hat and noise covariance R_hat on first 100 steps split = 100 y_mean = jnp.mean(Y_neural[:split], axis=0, keepdims=True) Y_cal, X_cal = Y_neural[:split] - y_mean, X_true[:split] C_hat = jnp.dot(Y_cal.T, jnp.linalg.pinv(X_cal.T)) resid = Y_cal - jnp.dot(X_cal, C_hat.T) R_hat = jnp.dot(resid.T, resid) / split + 0.05 * jnp.eye(n_neurons) A = jnp.array([[1.0, 0.0, dt, 0.0], [0.0, 1.0, 0.0, dt], [0.0, 0.0, 0.95, 0.0], [0.0, 0.0, 0.0, 0.95]]) Q = jnp.diag(jnp.array([1e-4, 1e-4, 0.03, 0.03])) Y_test, X_test = Y_neural[split:] - y_mean, X_true[split:] v_raw = jnp.dot(Y_test, jnp.linalg.pinv(C_hat[:, 2:]).T) raw_pos = [X_test[0, :2]] for k in range(1, len(Y_test)): raw_pos.append(raw_pos[-1] + dt * v_raw[k]) raw_pos = jnp.stack(raw_pos, axis=0) x_est, P_est, kf_states, I4 = X_test[0], 0.05 * jnp.eye(4), [X_test[0]], jnp.eye(4) for k in range(1, len(Y_test)): x_pred = jnp.dot(A, x_est) P_pred = jnp.dot(jnp.dot(A, P_est), A.T) + Q K = jnp.dot(jnp.dot(P_pred, C_hat.T), jnp.linalg.inv(jnp.dot(jnp.dot(C_hat, P_pred), C_hat.T) + R_hat)) x_est = x_pred + jnp.dot(K, Y_test[k] - jnp.dot(C_hat, x_pred)) P_est = jnp.dot(I4 - jnp.dot(K, C_hat), P_pred) kf_states.append(x_est) kf_states = jnp.stack(kf_states, axis=0) mse_raw = float(jnp.mean((raw_pos - X_test[:, :2]) ** 2)) mse_kf = float(jnp.mean((kf_states[:, :2] - X_test[:, :2]) ** 2)) print(f"Cursor MSE -> Raw Decoder: {mse_raw:.4f}, Kalman Filter: {mse_kf:.4f}") plt.figure(figsize=(6.8, 4.6)) plt.plot(X_test[:, 0], X_test[:, 1], color="#333", lw=2.5, label="True Path") plt.plot(raw_pos[:, 0], raw_pos[:, 1], color="#e74c3c", lw=1.3, alpha=0.75, label=f"Raw (MSE={mse_raw:.3f})") plt.plot(kf_states[:, 0], kf_states[:, 1], color="#27ae60", lw=2.2, label=f"Kalman (MSE={mse_kf:.3f})") plt.title("Neural Cursor Decoding From 40 Noisy Motor Neurons"); plt.xlabel("Cursor X"); plt.ylabel("Cursor Y") plt.legend(); plt.tight_layout(); plt.show() -
Solve electrode drift via orthogonal Procrustes manifold alignment. Generate Day 0 and Day 30 motor cortex recordings driven by the same underlying 3D neural manifold, while electrode micromotion drastically rotates and alters Day 30's sensor weights. Watch a fixed Day 0 decoder fail on Day 30, then restore accurate decoding in one SVD step without retraining the decoder.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(77) T, n_neurons, d_latent = 240, 64, 3 t = jnp.linspace(0.0, 4.0 * jnp.pi, T) Z_true = jnp.stack([jnp.cos(t), jnp.sin(t), 0.5 * jnp.sin(2.0 * t)], axis=1) target_vel = jnp.stack([-jnp.sin(t), jnp.cos(t)], axis=1) # Different sensor matrices on Day 0 vs Day 30 simulate severe electrode drift key, k0, k30, kn0, kn30 = jax.random.split(key, 5) X_day0 = jnp.dot(Z_true, jax.random.normal(k0, (d_latent, n_neurons))) + 0.35 * jax.random.normal(kn0, (T, n_neurons)) X_day30 = jnp.dot(Z_true, jax.random.normal(k30, (d_latent, n_neurons))) + 0.35 * jax.random.normal(kn30, (T, n_neurons)) # Extract top-3 PCA manifolds separately for each day X0_c = X_day0 - jnp.mean(X_day0, axis=0, keepdims=True) X30_c = X_day30 - jnp.mean(X_day30, axis=0, keepdims=True) _, _, Vt0 = jnp.linalg.svd(X0_c, full_matrices=False) _, _, Vt30 = jnp.linalg.svd(X30_c, full_matrices=False) Z0_pca, Z30_pca = jnp.dot(X0_c, Vt0[:d_latent].T), jnp.dot(X30_c, Vt30[:d_latent].T) # Fixed velocity decoder fitted on Day 0 only D_day0 = jnp.dot(jnp.linalg.pinv(Z0_pca), target_vel) pred_day0 = jnp.dot(Z0_pca, D_day0) pred_unaligned = jnp.dot(Z30_pca, D_day0) # Orthogonal Procrustes alignment: min ||Z30_pca @ R - Z0_pca||_F U, _, Vt = jnp.linalg.svd(jnp.dot(Z30_pca.T, Z0_pca), full_matrices=False) Z30_aligned = jnp.dot(Z30_pca, jnp.dot(U, Vt)) pred_aligned = jnp.dot(Z30_aligned, D_day0) def r2_score(y_true, y_pred): return float(1.0 - jnp.sum((y_true - y_pred) ** 2) / jnp.sum((y_true - jnp.mean(y_true, axis=0)) ** 2)) r2_d0, r2_un, r2_al = r2_score(target_vel, pred_day0), r2_score(target_vel, pred_unaligned), r2_score(target_vel, pred_aligned) print(f"R^2 -> Day 0: {r2_d0:.3f}, Day 30 Unaligned: {r2_un:.3f}, Day 30 Aligned: {r2_al:.3f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(t, target_vel[:, 0], color="#333", lw=2.2, label="True Vel X") axes[0].plot(t, pred_unaligned[:, 0], color="#e74c3c", lw=1.6, ls="--", label="Day 30 Unaligned") axes[0].plot(t, pred_aligned[:, 0], color="#27ae60", lw=1.8, label="Day 30 Aligned") axes[0].set_title("Velocity X Across 30 Days of Drift"); axes[0].set_xlabel("Time (rad)"); axes[0].set_ylabel("Vel X"); axes[0].legend() axes[1].bar(["Day 0", "Day 30\nUnaligned", "Day 30\nAligned"], [r2_d0, max(r2_un, -0.5), r2_al], color=["#3498db", "#e74c3c", "#27ae60"], width=0.55) axes[1].axhline(0.0, color="#333", lw=0.8); axes[1].set_ylim(-0.6, 1.1) axes[1].set_title("Decoding R^2 Before vs After Procrustes"); axes[1].set_ylabel("R^2") plt.tight_layout(); plt.show()