Skip to content

Biological Neurons and Neural Coding

NeuroAI sits at the intersection of neuroscience and artificial intelligence, asking both how biological brains inspire smarter machines and how neural networks serve as testable models of living minds. This file builds from the biophysics of a single spiking neuron up to how populations of neurons encode the world efficiently on low-dimensional manifolds.

Why NeuroAI Exists as a Two-Way Street

  • Imagine two engineers trying to build a flying machine. One studies birds in a wind tunnel, while the other builds aerodynamic simulations to test theories about how birds actually stay aloft. NeuroAI is that exact two-way street between biological neuroscience and artificial intelligence.

  • On the first lane (neuroscience inspiring AI), nearly every foundational breakthrough in modern deep learning drew direct inspiration from the brain. Hierarchical receptive fields in convolutional networks (chapter 08) came from visual cortex physiology, reinforcement learning's temporal-difference error (chapter 06) echoed midbrain dopamine signalling, experience replay mirrors hippocampal sleep reactivation, and attention mechanisms echo selective cortical gating.

  • On the second lane (AI illuminating neuroscience), deep neural networks have given neuroscientists something they never had before, namely working, image-computable models that actually solve vision, language, and navigation. Instead of guessing what a visual neuron cares about with simple bars of light, researchers can now compare living brain recordings directly against the hidden layers of an artificial network doing the same task.

  • Still, the human brain runs on roughly 20 watts of power (less than a dim desk lamp), learns new concepts from a handful of examples, and generalises effortlessly across unfamiliar lighting, accents, and environments. Understanding how biological hardware achieves this starts with looking closely at its basic building block, the biological neuron.

Anatomy of a Biological Neuron

  • In chapter 06, an artificial neuron was summarised in a single clean formula. You take a weighted sum of inputs, add a bias, and pass it through a pointwise nonlinearity such as \(\text{ReLU}(\mathbf{w}^T \mathbf{x} + b)\). That abstraction launched a technological revolution, yet it hides just how sophisticated a real biological cell truly is.

  • Picture a real cortical pyramidal neuron not as a single dot-product node, but as a sprawling oak tree whose branches are lined with thousands of tiny computational switches. Each anatomical part plays a distinct role.

    • Dendrites are branching input fibres that receive signals from roughly 1,000 to 10,000 upstream neurons. Crucially, dendrites are not passive copper wires. Local branches contain voltage-gated ion channels (such as NMDA receptors) that fire localised dendritic spikes when nearby synapses activate together. This means a single dendritic branch can perform local coincidence detection and even XOR-like nonlinearities before the signal ever reaches the cell body.
    • The soma (cell body) integrates currents arriving from all dendritic trees and acts as the metabolic hub. At its exit point (the axon hillock), the cell decides whether the accumulated voltage has crossed firing threshold.
    • The axon is a long output cable, often wrapped in insulating myelin sheaths, that transmits an all-or-none electrical pulse (action potential or spike) without decay over distances ranging from millimetres to over a metre.
    • Chemical synapses are microscopic junctions where the arriving electrical spike triggers the release of chemical neurotransmitters across a tiny synaptic cleft. Those molecules bind to receptors on the downstream dendrite, opening ion channels and nudging the target neuron's voltage up or down. Changing synaptic strength over time is the physical substrate of learning and memory.
  • Because each dendritic branch acts like a nonlinear hidden subunit feeding into the soma, computational studies (such as Beniaguev et al., 2021) have shown that accurately mimicking the input-output behaviour of one single cortical pyramidal neuron requires a 5-to-8-layer deep artificial neural network. A biological neuron is closer to a miniature multi-layer perceptron than to a single ReLU(Wx + b).

  • Biological neurons also obey a strict structural constraint rarely seen in artificial networks, known as Dale's Law. Under Dale's Law, a single neuron releases the same primary neurotransmitter at all of its outgoing synapses.

    • Excitatory neurons (typically releasing glutamate, roughly 80% of cortical neurons) exclusively increase the firing probability of their targets, meaning all of their outgoing weights are positive (\(W_{ij} \ge 0\)).
    • Inhibitory interneurons (typically releasing GABA, roughly 20% of cortical neurons) exclusively decrease the firing probability of their targets, meaning all of their outgoing weights are negative (\(W_{ij} \le 0\)).
    • In matrix terms (chapter 02), Dale's Law forces every column of the synaptic weight matrix \(W\) to have a single uniform sign, whereas standard artificial neural networks allow any unit to excite one downstream neuron and inhibit another. Maintaining tight excitation-inhibition (E/I) balance keeps cortical networks poised at the edge of stability, responsive to weak inputs without exploding into epileptic seizures.

Membrane Biophysics and the Leaky Integrate-and-Fire Model

  • To write down the maths of a spiking neuron, picture a leaky wooden bucket sitting under a rainspout. Incoming excitatory currents pour water into the bucket, raising the water level (membrane voltage \(V\)). At the same time, a small hole near the bottom constantly drains water back toward a baseline level (\(V_{\text{rest}}\)). If the rain arrives fast enough to beat the leak, the water hits the rim (\(V_{\text{th}}\)), the bucket tips over in a sharp splash (an action potential), empties back to a reset level (\(V_{\text{reset}}\)), and pauses briefly before it can fill again.

  • Physically, the neuron's fatty cell membrane separates electrical charge like a capacitor (\(C_m\)), while constantly open leak ion channels act like a resistor (\(R\)) letting charge trickle back toward resting potential \(V_{\text{rest}} \approx -70\,\text{mV}\). Applying Kirchhoff's current law yields the Leaky Integrate-and-Fire (LIF) differential equation (connecting directly to first-order ODEs in chapter 03).

\[\tau_m \frac{dV(t)}{dt} = -\bigl(V(t) - V_{\text{rest}}\bigr) + R\,I(t)\]
  • Every symbol here has a direct physical meaning.

    • \(V(t)\) is the membrane potential (voltage inside the cell relative to outside) at time \(t\).
    • \(V_{\text{rest}}\) is the resting potential (typically around \(-70\,\text{mV}\)).
    • \(R\) is the membrane leak resistance and \(C_m\) is the membrane capacitance, whose product \(\tau_m = R C_m\) is the membrane time constant (typically \(10\text{--}20\,\text{ms}\)). It controls how quickly voltage forgets past inputs, so when \(I(t) = 0\), \(V(t)\) decays exponentially back to \(V_{\text{rest}}\) as \(e^{-t/\tau_m}\).
    • \(I(t)\) is the total synaptic input current at time \(t\).
  • The continuous differential equation only describes subthreshold dynamics. To produce spikes, the LIF model adds three discrete event rules.

    1. Crossing threshold occurs whenever \(V(t) \ge V_{\text{th}}\) (say, \(-55\,\text{mV}\)), causing the neuron to emit a spike at time \(t^{(f)}\).
    2. An immediate reset clamps the voltage back down to \(V_{\text{reset}}\) (often at or below \(V_{\text{rest}}\)) right after the spike fires.
    3. An absolute refractory period holds the cell silent for a short window \(\tau_{\text{ref}}\) (roughly \(1\text{--}2\,\text{ms}\)) regardless of how strong \(I(t)\) is, capping its maximum firing rate at \(1 / \tau_{\text{ref}}\).

Biological neuron anatomy showing nonlinear dendritic branches, soma, myelinated axon, and synapses alongside the Leaky Integrate-and-Fire membrane voltage trace with threshold crossing, spike emission, reset, and refractory period

  • Under a constant input current \(I\) strong enough to push steady-state voltage \(V_{\text{rest}} + R I\) above \(V_{\text{th}}\), we can solve the LIF equation analytically for the inter-spike interval and obtain the neuron's firing-rate curve (\(f\)-\(I\) curve). It stays zero below threshold, then rises smoothly and saturates at \(1/\tau_{\text{ref}}\). Notice that this looks remarkably similar to a shifted, saturating ReLU, showing how continuous ANN activations emerge as a time-averaged approximation of spiking biophysics.

Intuition for Hodgkin-Huxley Ion Channels

  • The LIF model treats the spike itself as an artificial "if-then" reset. Where does a real ~1 ms action potential actually come from? In 1952, Alan Hodgkin and Andrew Huxley explained the full mechanism by measuring giant squid axons (work that won the Nobel Prize).

  • Think of two automated pressure valves built into the membrane.

    • Fast sodium (\(\text{Na}^+\)) channels snap open when \(V\) rises past threshold. Because sodium is concentrated outside the cell, positively charged \(\text{Na}^+\) ions flood in, pushing \(V\) sharply upward toward \(+40\,\text{mV}\) in an explosive positive-feedback loop. Within a millisecond, these channels automatically slam shut into an inactivated state.
    • Delayed potassium (\(\text{K}^+\)) channels are triggered by the same depolarisation but open slightly more slowly, letting positively charged potassium ions rush out of the cell. This pulls \(V\) rapidly back down, briefly overshooting below \(V_{\text{rest}}\) (hyperpolarisation) before settling back to rest.
  • The full Hodgkin-Huxley system uses four coupled nonlinear differential equations (voltage \(V\) plus three channel gating probabilities \(m, h, n\)). LIF strips away those gating dynamics to capture the essential leaky integration and thresholding at a fraction of the computational cost.

How Spikes Carry Information

  • Because every action potential has nearly the same height and duration (~100 mV, ~1 ms), spikes are effectively binary events in time, forming a sequence of timestamps \(\{t^{(1)}, t^{(2)}, \dots\}\) called a spike train. How does a stream of identical electrical clicks encode the rich texture of a face, the warmth of a voice, or the trajectory of a reaching hand? Neuroscience has uncovered three complementary coding schemes.

Rate Coding

  • Imagine measuring how busy a motorway is by counting how many cars pass a bridge in one minute. Rate coding reads a neuron's message from its average firing frequency over a time window \(\Delta t\).
\[r = \frac{N_{\text{spikes}}}{\Delta t}\]
  • Rate coding is robust to jittery synaptic noise and directly justifies treating each neuron's output as a single real number (just like an artificial neuron's activation). However, it has a glaring limitation. If a visual neuron fires at 20 Hz, it only produces one or two spikes in the 100 ms it takes you to recognise a friend's face, so counting spikes over a long window is often far too slow for real-time perception.

Temporal and Latency Coding

  • Now imagine a starting pistol firing at a race. The fastest runner crosses the finish line first, carrying information in when they arrive rather than how many laps they run. In temporal coding, the exact timing of spikes carries information.

    • Time-to-first-spike (latency coding) lets neurons whose preferred feature matches the stimulus strongly reach threshold first and fire earliest. A downstream layer can decode the stimulus from the order of the very first wave of spikes in under 20 ms.
    • Phase-of-firing coding leverages rhythmic background oscillations in cortical and hippocampal networks (such as 8 Hz theta waves). Firing slightly earlier or later within each oscillation cycle encodes continuous variables like an animal's exact position within a place field (phase precession).

Population Coding and Tuning Curves

  • Even better than relying on one heroic neuron is pooling the votes of an entire crowd. Think of human colour vision. Your retina has only three types of cone photoreceptors (roughly tuned to red, green, and blue wavelengths), each with a broad, overlapping sensitivity curve. No single cone can tell yellow from dim red, yet comparing the ratio of responses across all three lets you distinguish millions of hues.

  • Cortical areas use this exact population coding strategy. Each neuron \(i\) has a tuning curve \(r_i(s)\) describing its average firing rate as a function of a stimulus variable \(s\).

    • In primary visual cortex (V1), David Hubel and Torsten Wiesel discovered in 1959 that neurons respond selectively to oriented bars of light, producing smooth bell-shaped tuning curves centred on each cell's preferred orientation \(\theta_i\).
    • In primary motor cortex (M1), Apostolos Georgopoulos showed that arm-reaching neurons follow remarkably clean cosine tuning as a function of reach direction \(\theta\).
\[r_i(\theta) = r_{0,i} + k_i \cos(\theta - \theta_i)\]
  • Here \(r_{0,i}\) is neuron \(i\)'s baseline firing rate, \(k_i\) is its modulation depth, and \(\theta_i\) is its preferred direction (with corresponding unit vector \(\mathbf{u}_i = [\cos\theta_i, \sin\theta_i]^T\)).

  • Given a noisy snapshot of firing rates across \(N\) motor neurons, how can we decode the intended reach direction? Population vector decoding simply lets every neuron cast a weighted vector vote in its preferred direction.

\[\mathbf{p} = \sum_{i=1}^{N} (r_i - r_{0,i})\,\mathbf{u}_i\]
  • The angle of the resulting vector \(\mathbf{p}\) predicts the arm's movement direction with astonishing accuracy (often to within a few degrees), even though every individual neuron is noisy and broadly tuned. Mathematically, this is an inner product (chapter 01) combining distributed noisy measurements to cancel uncorrelated noise as \(1/\sqrt{N}\) (chapter 04).

Overlapping population tuning curves for four neurons responding to stimulus angle 85 degrees alongside geometric population vector decoding summing firing-rate-weighted preferred direction vectors

Neural Manifolds and Low-Dimensional Latent Dynamics

  • Suppose you record simultaneously from \(N = 1{,}000\) neurons in motor cortex while a monkey reaches toward eight targets. At any millisecond \(t\), the population's firing rates form a point \(\mathbf{r}(t) \in \mathbb{R}^{1000}\). In principle, those 1,000 neurons could wander anywhere inside a staggering 1,000-dimensional hypercube.

  • Yet when neuroscientists actually plot the data, something extraordinary happens. The population state stays tightly confined to a smooth, low-dimensional surface called a neural manifold of dimension \(d \ll N\) (often just \(d \approx 3\text{--}15\) dimensions).

  • Think of a flock of 500 starlings wheeling across the evening sky. Each bird has three spatial coordinates, giving 1,500 degrees of freedom in theory, yet because every bird coordinates with its neighbours, the whole flock moves as a fluid ribbon described by just a handful of collective variables. Similarly, because cortical neurons are densely interconnected by structured recurrent weights, their firing rates are strongly correlated rather than independent.

  • We can uncover this hidden subspace using the exact Singular Value Decomposition (SVD) and PCA machinery from chapter 02. Stack the mean-centred firing rates over \(T\) time steps into a matrix \(X \in \mathbb{R}^{T \times N}\) and decompose it.

\[X = U \Sigma V^T\]
  • The top \(d\) columns of \(V\) define the neural modes (co-activation patterns across neurons), the singular values \(\sigma_1 \ge \sigma_2 \ge \dots\) measure how much variance each mode captures, and the projected trajectory \(Z = X V_{:, 1:d} \in \mathbb{R}^{T \times d}\) reveals the latent dynamical system underneath.

  • In motor cortex, projecting reaching activity onto just the top 2 or 3 modes reveals clean, clock-like rotational trajectories that act like an internal spring launching the arm smoothly toward its target. In the brain's compass (the head-direction system), the neural manifold is literally a 1D ring embedded in high-dimensional neuron space, where the bump of activity glides around the circle as the animal turns its head.

The Efficient Coding Hypothesis and Sparse Coding

  • Why do V1 neurons have oriented edge-detecting receptive fields in the first place? Did evolution hard-code millions of edge templates in our DNA, or do those filters emerge naturally from a deeper mathematical principle?

  • In 1961, Horace Barlow proposed the Efficient Coding Hypothesis, arguing that sensory systems have evolved to represent natural environments with minimal redundancy and minimal metabolic cost. Think of compressing a photograph into a JPEG file (chapter 05, information theory). Natural images are massively redundant, because if one pixel is bright blue sky, its neighbour is almost certainly bright blue sky too. Sending raw pixel intensities from the retina to the brain would waste precious spikes and calories repeating predictable facts.

  • In 1996, Bruno Olshausen and David Field translated Barlow's insight into a landmark optimisation problem called sparse coding. Suppose any small natural image patch \(\mathbf{x} \in \mathbb{R}^D\) can be reconstructed as a linear combination of dictionary elements (basis images) stored as columns of a matrix \(\Phi \in \mathbb{R}^{D \times K}\), weighted by neural activations \(\mathbf{a} \in \mathbb{R}^K\), giving \(\hat{\mathbf{x}} = \Phi \mathbf{a}\).

  • Unlike PCA (which forces orthogonal basis vectors with \(K \le D\)), sparse coding uses an overcomplete dictionary (\(K > D\)) and asks two things simultaneously. It tries to reconstruct the image accurately while keeping almost all neural activations \(a_k\) equal to zero for any given patch.

\[\min_{\Phi,\, \mathbf{a}} \; \frac{1}{2} \|\mathbf{x} - \Phi \mathbf{a}\|_2^2 + \lambda \|\mathbf{a}\|_1\]
  • Two competing terms govern this objective (both familiar from chapters 01 and 06).

    • Reconstruction fidelity \(\frac{1}{2}\|\mathbf{x} - \Phi \mathbf{a}\|_2^2\) ensures no important visual information is lost.
    • The \(\ell_1\) sparsity penalty \(\lambda \|\mathbf{a}\|_1 = \lambda \sum_k |a_k|\) pushes most neurons to remain silent on any given image patch, conserving energy (the exact same geometry as Lasso regression in chapter 06). The hyperparameter \(\lambda > 0\) trades reconstruction accuracy against sparsity.
  • Solving for \(\mathbf{a}\) with \(\Phi\) fixed uses iterative shrinkage (such as ISTA, the Iterative Shrinkage-Thresholding Algorithm), where a gradient step on reconstruction error is followed by a soft-thresholding nonlinearity \(S_\alpha(z) = \text{sign}(z)\,\max(|z| - \alpha, 0)\). Then \(\Phi\) is slowly updated via gradient descent on the reconstruction error while normalising each column so the dictionary cannot cheat by blowing up its weights.

  • When Olshausen and Field trained this purely unsupervised objective on thousands of natural black-and-white photographs of forests and landscapes (with no labels, no biology built in, and no edge-detection rules), the learned dictionary columns \(\Phi\) spontaneously organised into localised, oriented, bandpass Gabor-like filters. They matched the exact receptive fields of V1 simple cells discovered in living brains decades earlier, making efficient sparse coding one of the crown jewels of NeuroAI.

Take-Home

  • NeuroAI is a two-way street where biological brains inspire new AI architectures and algorithms, while AI models provide image-computable hypotheses to test against living neural recordings.
  • A biological neuron is far richer than ReLU(Wx + b) because active dendritic branches perform local nonlinear computations, while Dale's Law enforces strict excitatory (+) versus inhibitory (-) sign constraints per neuron.
  • LIF captures core spiking biophysics via \(\tau_m \frac{dV}{dt} = -(V - V_{\text{rest}}) + R\,I(t)\), modelling leaky capacitive integration, threshold crossing, reset, and refractoriness while abstracting the \(\text{Na}^+/\text{K}^+\) ion-channel dance of Hodgkin-Huxley.
  • Information lives in rates, timing, and crowds, combining rate coding over time windows, millisecond spike latencies, and overlapping population tuning curves that cancel single-cell noise.
  • Population activity lives on low-dimensional neural manifolds, allowing SVD and PCA to uncover smooth collective dynamics hidden inside thousands of correlated neurons.
  • Efficient sparse coding predicts V1, because minimising \(\|\mathbf{x} - \Phi \mathbf{a}\|_2^2 + \lambda \|\mathbf{a}\|_1\) on natural images spontaneously discovers the oriented Gabor-like simple-cell receptive fields of primary visual cortex.

Coding Tasks (use CoLab or notebook)

  1. Simulate a Leaky Integrate-and-Fire (LIF) neuron responding to a fluctuating input current, visualise its membrane potential and spike train, and sweep input current amplitude to plot its \(f\)-\(I\) firing-rate curve.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def simulate_lif(I_trace, dt=0.5, tau_m=15.0, R=10.0,
                     V_rest=-70.0, V_th=-55.0, V_reset=-75.0, t_ref=2.0):
        """Simulate a single LIF neuron using Euler integration (times in ms)."""
        V = V_rest
        ref_steps = int(round(t_ref / dt))
        ref_counter = 0
        V_hist = []
        spikes = []
    
        for I_t in I_trace:
            if ref_counter > 0:
                V = V_reset
                ref_counter -= 1
                spikes.append(0.0)
                V_hist.append(V)
                continue
    
            dV = (-(V - V_rest) + R * float(I_t)) * (dt / tau_m)
            V = V + dV
            if V >= V_th:
                V_hist.append(20.0)   # visual spike peak (+20 mV)
                spikes.append(1.0)
                V = V_reset
                ref_counter = ref_steps
            else:
                V_hist.append(V)
                spikes.append(0.0)
    
        return jnp.array(V_hist), jnp.array(spikes)
    
    # 1. Time-varying noisy input current (250 ms)
    dt = 0.5
    T = 250.0
    times = jnp.arange(0.0, T, dt)
    key = jax.random.PRNGKey(42)
    noise = jax.random.normal(key, (len(times),)) * 0.45
    I_pulse = jnp.where((times >= 40.0) & (times <= 200.0), 2.1, 0.0) + noise
    
    V_trace, spikes = simulate_lif(I_pulse, dt=dt)
    print(f"Total spikes fired: {int(jnp.sum(spikes))}")
    
    # 2. Sweep constant current to measure f-I curve
    currents = jnp.linspace(0.0, 4.0, 25)
    rates_hz = []
    for amp in currents:
        I_const = jnp.full((len(times),), amp)
        _, spk = simulate_lif(I_const, dt=dt)
        rates_hz.append(float(jnp.sum(spk)) / (T / 1000.0))
    rates_hz = jnp.array(rates_hz)
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 4))
    axes[0].plot(times, V_trace, color="#3498db", lw=1.5, label="Membrane V(t)")
    axes[0].axhline(-55.0, color="#e74c3c", ls="--", lw=1.2, label="Threshold V_th")
    axes[0].axhline(-70.0, color="#666666", ls=":", lw=1.0, label="Rest V_rest")
    axes[0].set_xlabel("Time (ms)")
    axes[0].set_ylabel("Voltage (mV)")
    axes[0].set_title("LIF Membrane Potential & Spikes")
    axes[0].legend(loc="upper right")
    
    axes[1].plot(currents, rates_hz, "o-", color="#9b59b6", lw=2)
    axes[1].axvline(1.5, color="#27ae60", ls="--", label="Rheobase (1.5 nA)")
    axes[1].set_xlabel("Constant Input Current I (nA)")
    axes[1].set_ylabel("Firing Rate (Hz)")
    axes[1].set_title("LIF f-I Curve (ReLU-like Threshold + Saturation)")
    axes[1].legend()
    plt.tight_layout()
    plt.show()
    

  2. Build a population of cosine-tuned motor cortex neurons with noisy firing rates, decode movement direction with population vector decoding, and demonstrate how decoding error shrinks as population size \(N\) grows.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def simulate_population_decoding(N, n_trials, key, noise_std=6.0):
        """Simulate cosine-tuned neurons and decode angles via population vector."""
        pref_angles = jnp.linspace(0.0, 2.0 * jnp.pi, N, endpoint=False)
        u_vec = jnp.stack([jnp.cos(pref_angles), jnp.sin(pref_angles)], axis=1)
    
        k1, k2 = jax.random.split(key)
        true_angles = jax.random.uniform(k1, (n_trials,), minval=0.0, maxval=2.0 * jnp.pi)
    
        r0, gain = 20.0, 15.0
        delta = true_angles[:, None] - pref_angles[None, :]
        rates = jnp.maximum(
            0.0,
            r0 + gain * jnp.cos(delta) + jax.random.normal(k2, (n_trials, N)) * noise_std,
        )
    
        pop_vecs = jnp.dot(rates - r0, u_vec)
        decoded_angles = jnp.arctan2(pop_vecs[:, 1], pop_vecs[:, 0])
    
        err_rad = jnp.arctan2(
            jnp.sin(decoded_angles - true_angles),
            jnp.cos(decoded_angles - true_angles),
        )
        return true_angles, decoded_angles, jnp.abs(err_rad) * (180.0 / jnp.pi)
    
    pop_sizes = [4, 8, 16, 32, 64, 128, 256]
    mean_errors = []
    key = jax.random.PRNGKey(7)
    for N in pop_sizes:
        key, subk = jax.random.split(key)
        _, _, errs = simulate_population_decoding(N, n_trials=400, key=subk)
        mean_errors.append(float(jnp.mean(errs)))
        print(f"N = {N:3d} neurons -> mean angular error = {mean_errors[-1]:5.2f} deg")
    
    true_a, dec_a, _ = simulate_population_decoding(64, n_trials=200, key=jax.random.PRNGKey(99))
    dec_a_mod = jnp.mod(dec_a, 2.0 * jnp.pi)
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 4))
    axes[0].scatter(true_a * 180 / jnp.pi, dec_a_mod * 180 / jnp.pi, alpha=0.55, s=18, color="#3498db")
    axes[0].plot([0, 360], [0, 360], "--", color="#e74c3c", lw=1.5)
    axes[0].set_xlabel("True Reach Direction (deg)")
    axes[0].set_ylabel("Decoded Direction (deg)")
    axes[0].set_title("Population Vector Decoding (N = 64)")
    
    axes[1].plot(pop_sizes, mean_errors, "o-", color="#27ae60", lw=2)
    axes[1].set_xscale("log")
    axes[1].set_xlabel("Population Size N (log scale)")
    axes[1].set_ylabel("Mean Decoding Error (deg)")
    axes[1].set_title("Error Shrinks ~ 1/sqrt(N) with Crowd Size")
    plt.tight_layout()
    plt.show()
    

  3. Explore neural manifolds and sparse coding together by using SVD to recover a hidden 2D rotational manifold from 60 noisy neurons, then implementing ISTA sparse coding (\(\min_a \frac{1}{2}\|x - \Phi a\|_2^2 + \lambda\|a\|_1\)) on an overcomplete Gabor-like dictionary to see how \(\lambda\) controls the trade-off between sparsity and reconstruction fidelity.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Part A: Recovering a 2D Neural Manifold with SVD
    key = jax.random.PRNGKey(0)
    k1, k2, k3 = jax.random.split(key, 3)
    
    T, N = 200, 60
    t = jnp.linspace(0.0, 4.0 * jnp.pi, T)
    z_true = jnp.stack([jnp.exp(-0.08 * t) * jnp.cos(t),
                        jnp.exp(-0.08 * t) * jnp.sin(t)], axis=1)
    
    C = jax.random.normal(k1, (2, N))
    X_neural = jnp.dot(z_true, C) + 0.35 * jax.random.normal(k2, (T, N))
    X_centered = X_neural - jnp.mean(X_neural, axis=0, keepdims=True)
    
    _, S, Vt = jnp.linalg.svd(X_centered, full_matrices=False)
    var_explained = (S ** 2) / jnp.sum(S ** 2)
    Z_pca = jnp.dot(X_centered, Vt[:2].T)
    print(f"Variance captured by top 2 neural modes: {float(jnp.sum(var_explained[:2])):.1%}")
    
    # Part B: Sparse Coding via ISTA on an Overcomplete Oriented Dictionary
    gx, gy = jnp.meshgrid(jnp.linspace(-1.0, 1.0, 8), jnp.linspace(-1.0, 1.0, 8))
    atoms = []
    for theta in jnp.linspace(0.0, jnp.pi, 12, endpoint=False):
        for cx in [-0.4, 0.4]:
            for cy in [-0.4, 0.4]:
                for phase in [0.0, jnp.pi / 2.0]:
                    xr = (gx - cx) * jnp.cos(theta) + (gy - cy) * jnp.sin(theta)
                    yr = -(gx - cx) * jnp.sin(theta) + (gy - cy) * jnp.cos(theta)
                    atom = (jnp.exp(-(xr ** 2 + yr ** 2) / 0.18) * jnp.cos(5.5 * xr + phase)).ravel()
                    atoms.append(atom / (jnp.linalg.norm(atom) + 1e-8))
    Phi = jnp.stack(atoms, axis=1)  # (64, 96) overcomplete dictionary
    
    x_patch = (1.2 * Phi[:, 5] - 0.9 * Phi[:, 34] + 1.0 * Phi[:, 71]
               + 0.05 * jax.random.normal(k3, (64,)))
    
    def ista_sparse_code(x, Phi, lam=0.18, n_iter=200):
        """Solve min_a 0.5*||x - Phi a||_2^2 + lam*||a||_1 via soft-thresholding."""
        L = float(jnp.linalg.norm(jnp.dot(Phi.T, Phi), ord=2))
        step = 1.0 / (L + 1e-6)
        a = jnp.zeros(Phi.shape[1])
        for _ in range(n_iter):
            z = a - step * jnp.dot(Phi.T, jnp.dot(Phi, a) - x)
            a = jnp.sign(z) * jnp.maximum(jnp.abs(z) - step * lam, 0.0)
        return a
    
    a_hat = ista_sparse_code(x_patch, Phi, lam=0.18)
    x_recon = jnp.dot(Phi, a_hat)
    n_active = int(jnp.sum(jnp.abs(a_hat) > 1e-3))
    rel_err = float(jnp.linalg.norm(x_patch - x_recon) / jnp.linalg.norm(x_patch))
    print(f"Sparse coding active neurons: {n_active} / {Phi.shape[1]}, relative error: {rel_err:.3f}")
    
    fig, axes = plt.subplots(1, 3, figsize=(13, 3.8))
    axes[0].plot(Z_pca[:, 0], Z_pca[:, 1], color="#3498db", lw=1.8)
    axes[0].set_title("Recovered 2D Neural Manifold (PCA)")
    axes[0].set_xlabel("PC 1"); axes[0].set_ylabel("PC 2")
    
    axes[1].imshow(x_patch.reshape(8, 8), cmap="gray")
    axes[1].set_title("Target Image Patch"); axes[1].axis("off")
    
    axes[2].stem(range(len(a_hat)), a_hat, linefmt="#9b59b6", markerfmt="o", basefmt="k-")
    axes[2].set_title(f"Sparse Code a ({n_active}/96 active)")
    axes[2].set_xlabel("Dictionary Neuron k"); axes[2].set_ylabel("Activation a_k")
    plt.tight_layout()
    plt.show()