Mice Hippocampus LFP#
A neural recording is observed as a single waveform, but its temporal relationships can be represented as a trajectory in a reconstructed state space. This tutorial uses a mice hippocampus LFP recording to connect two views of the same signal: an autoregressive model of its local dynamics and the geometry of its delay coordinates.
The workflow moves from loading and processing a channel to fitting a classical AR model, inspecting its prediction errors, and comparing observed and reconstructed trajectories. Time-window, delay, and channel comparisons then show which features of the geometry depend on the chosen view. Black curves represent the processed recording; dark-red curves represent the model reconstruction.
The aim is to understand what the model reproduces and how to interpret the resulting geometry, not simply to maximize a prediction score. A loop or torus-like appearance is a useful geometric observation, but a three-dimensional picture alone does not determine topology or count independent generators. These examples use a fitted linear AR model; they do not require training DeepLagField.
1. Set Up the Notebook#
Install the package with its tutorials dependencies as described in
Installation, then run the cells in order.
neuralfieldmanifold is imported as nfm. NumPy handles arrays,
Matplotlib displays the comparisons, and the shared plotting style
keeps figures consistent across the tutorial.
The complete analysis includes multiple recording channels, so it requires the recording file(s) described below. The small bundled samples used in Getting Started are suitable for learning the API but do not contain every channel needed here. The website displays saved results; opening a page does not run the analysis or require access to the recording.
2. Assemble the Reconstruction Pipeline#
The helper functions separate three tasks: preparing a signal, estimating
its dynamics, and comparing observed and reconstructed trajectories.
Signal processing is handled by nfm.preprocessing; the autoregressive
design matrix comes from nfm.embedding.lag_matrix; and
nfm.models.AR estimates the coefficients by ordinary least squares.
An autoregressive model of order \(p\) predicts the next sample from the previous \(p\) samples:
The intercept \(b\) accounts for a constant offset. The coefficients \(a_i\)
describe how recent observations combine to predict the next value.
Fitting minimizes squared prediction error on the training segment.
The returned w stores the intercept first, followed by coefficients
from lag 1 to lag \(p\).
Three settings have different roles throughout this tutorial: AR order \(p\) controls the predictor’s memory, embedding dimension \(m\) controls the number of plotted coordinates, and delay \(\tau\) controls the spacing between those coordinates. Neither \(p\) nor \(m\) is, by itself, a measurement of the number of independent oscillatory modes.
3. Load a Channel from the Recording#
Set NFM_MOUSE_DATA_FILE to the NumPy recording used below. The loader
expects (channels, samples), selects zero-based channel_id = 1,
and obtains a one-dimensional waveform. The acquisition rate is set
explicitly to 20,000 Hz; the array’s shape does not itself specify
a sampling rate.
The single-channel example uses the first five seconds, or 100,000 acquired samples. It reshapes the selected waveform to (samples, 1) for the processing helper. The later channel comparison reloads the full channel-by-sample array and transposes it for that same helper. Keeping these axis conventions explicit prevents selecting a time point where a channel was intended.
The recording path can be changed without changing the workflow, but
its sampling rate, available channels, and duration must match the
parameters supplied to the analysis. All sample-index-to-time
conversions after processing use the returned rate Fs, not the
original acquisition rate.
Loaded LFP: (10841760,) samples at 20000 Hz
4. Prepare the Signal for Dynamical Reconstruction#
Processing defines which activity the subsequent model describes. The following call, rather than the helper’s default arguments, sets the analysis band to 1-20 Hz. The steps run in this order:
Notch at 50 Hz, with quality factor 30, to attenuate a narrow line-frequency component. This example’s setting is not a universal choice for recordings acquired under different line frequencies.
Bandpass at 1-20 Hz with a fourth-order Butterworth design. This emphasizes the temporal activity being reconstructed while reducing slow drift and activity outside that band.
Decimate from 20 kHz to 500 Hz. The integer factor is 40. Decimation includes an anti-alias filter; it is not simply taking every fortieth sample. The retained band is well below the new 250 Hz Nyquist frequency. This rate is used for the low-frequency reconstruction, not for retaining the full acquisition bandwidth.
Normalize by a smoothed amplitude envelope. The normalization stage filters at 1-80 Hz, computes the Hilbert amplitude, smooths the envelope with a 3 Hz lowpass, and divides by that envelope plus a small positive constant. Multiplication by the median envelope retains an overall signal scale.
Envelope normalization reduces slow changes in trajectory size so that phase relationships are easier to compare. It is not a z-score, and its output is not an unmodified voltage trace. The 1-80 Hz envelope band does not restore content removed by the earlier bandpass; division by the time-varying envelope can itself modify the spectrum.
xs is the final normalized signal used for modeling. Despite its
name, xs_raw is the filtered, pre-envelope signal returned by the
helper, not the untouched recording. Filtering is zero-phase and
uses samples on both sides of a point, making this an offline analysis.
Short intervals near filter boundaries should be interpreted with care.
Processed signal: 2500 samples at 500.0 Hz
5. Explore How Much Lag History Is Needed#
The order sweep fits AR models with \(p=2,\ldots,6\). For each order,
nfm.embedding.lag_matrix pairs a row of past observations with its
next-sample target. The first 10% of target rows is used
for fitting, and the remaining rows are used for the displayed error
curve. This is a chronological split, not a random shuffle of samples.
The curve reports one-step test MSE: every test prediction receives the actual preceding observations. A flattening curve indicates that adding lags yields little further improvement for this recording and interval. Increasing order gives the model more flexibility but does not automatically reveal more independent oscillations.
The minimum-MSE order is computed first, after which
best_p_by_mse is explicitly set to 3. Both the reference line
and the subsequent single-channel reconstruction use AR(3).
Read the line as the example’s chosen order rather than an
automatically accepted optimum.
This is an exploratory order comparison. If the curve is used to tune a model for a new prediction study, choose the order within the training data and reserve a separate interval for the final performance estimate.
6. Fit the Model and Reconstruct the Held-Out Interval#
The main example fits AR(3) on the initial 10% of available target rows and evaluates on the later 90%. The coefficients remain fixed after fitting; they are not re-estimated as the test trace advances.
Unlike the order sweep, this step uses a recursive forecast with observed-history refreshes every 10 samples (20 ms at 500 Hz). At each refresh the predictor receives the actual preceding lag values. Within that block, it feeds its predictions back into the model. This tests short stretches of model evolution while limiting accumulated drift. It is neither an uninterrupted free run nor a one-step prediction at every sample.
true_test and yhat_ctrl are aligned observed and predicted test
arrays. The printed MSE measures squared amplitude error, while the
correlation measures waveform covariation. Their protocol differs
from the one-step order curve, so they need not have the same error.
xs_pred_full additionally reconstructs the complete processed
interval for visualization; its initial model history is copied from
the recording.
AR(3): MSE=192.180213, corr=0.990
Interpret the Fitted Coefficients#
Each bar is the coefficient multiplying one lagged sample. Positive coefficients reinforce that sample’s contribution; negative coefficients subtract it. Together, these weights can describe oscillation, decay, or a mixture of temporal patterns. The intercept is not included in this bar plot.
Read the coefficients as a group rather than treating a large bar as a separate oscillation. Neighboring samples of a filtered signal can be highly correlated, so large positive and negative coefficients may partly cancel. Oscillatory modes are associated with complex-conjugate poles of the fitted AR model, not individual coefficients. The pole analysis in the dimensionality tutorial develops that connection.
7. Compare the Reconstructed and Observed Waveforms#
The overlay shows whether the fitted model follows the timing and shape of the processed recording. Between history refreshes, each prediction becomes an input to the next prediction. Errors can therefore accumulate within a block even though the model is periodically re-anchored to observed data.
The prediction function below adds 1 to the observed trace for display
and leaves the prediction unshifted. That vertical separation is a plotting
offset, not an estimated bias. Compare peaks, troughs, and temporal
alignment here; use the residual and scatter plots for amplitude error.
The horizontal axis is the test-sample index, so dividing by Fs gives
elapsed seconds within the test interval.
Accurate short-horizon reconstruction is useful evidence that the AR model captures local dependence. It does not yet establish that an autonomous simulation would reproduce the signal’s longer-term geometry.
Examine What the Model Leaves Unexplained#
A residual is the observed value minus its prediction:
The residual autocorrelation function (ACF) asks whether errors separated
by a given number of samples still vary together. Lag zero is always 1.
Repeated structure at nonzero lags means that the reconstructed waveform
leaves temporal dependence unexplained; an oscillating ACF can reveal
a residual rhythmic component that is not obvious in a small waveform
overlay. Convert an ACF lag to seconds by dividing it by Fs.
The dashed lines are the familiar white-noise reference \(\pm1.96/\sqrt{N}\), where \(N\) is the number of residuals. They are an approximate pointwise guide, not simultaneous confidence bounds across all lags. These residuals also come from periodically refreshed recursive predictions rather than solely one-step innovations. Interpret the overall ACF pattern alongside the prediction protocol, rather than requiring every stem to lie inside the dashed lines.
10
Separate Timing Agreement from Amplitude Agreement#
In the scatter plot, each point pairs one observed test value with its prediction at the same time. Perfect predictions lie on the identity line. A change in slope indicates a gain mismatch, a displaced cloud indicates an offset, and broad scatter indicates samplewise error. Unlike the waveform overlay, the observations are not shifted here.
The two annotations describe different aspects of agreement. Pearson correlation \(\rho\) measures linear covariation and can remain high despite a scale or offset mismatch. The coefficient of determination,
compares squared error with predicting the observed test mean. It is 1 for a perfect reconstruction and can be negative when the prediction is worse than that mean baseline. Both quantities are evaluated on the original prediction amplitudes, before the matching used in the geometry plots.
8. Turn Temporal Relationships into a Spatial Trajectory#
A delay embedding places a sample and two delayed observations in the same three-dimensional point:
Advancing \(t\) traces a curve. For a simple oscillation, delayed coordinates represent different phases and can open a loop. Multiple sustained oscillations can produce richer, torus-like structure when their phases are sufficiently independent and the delays resolve them. Noise, changing amplitudes, finite observation time, and the choice of coordinates affect what is visible; a torus is not guaranteed by choosing a particular AR order.
Here \(m=3\) and \(\tau=10\) samples, or 20 ms at 500 Hz.
nfm.embedding.delay returns rows ordered in time with the newest
sample first. A segment of \(N\) samples produces \(N-2\tau\) points,
because the earliest samples do not have a complete delayed history.
The delay is supplied explicitly in this example, not selected by
an optimization routine.
Before plotting, the predicted trace is shifted and scaled to match the test trace’s mean and standard deviation. This helps compare shape and temporal organization separately from overall amplitude. It uses the observed comparison interval and is not part of the previously reported prediction accuracy. Black is the processed recording and dark red is the amplitude-matched, periodically refreshed reconstruction. No torus surface is fitted in this cell.
/tmp/ipykernel_3766439/2255730326.py:30: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all Axes decorations.
plt.tight_layout(pad=2.5)
9. Compare Geometry across Time Windows#
A long recording can superimpose several locally different geometries. Shorter views help distinguish a coherent local loop from the thicker cloud produced when phase relationships or amplitudes change over time. The next cell extracts 1-2, 2-3, 3-4, and 4-5 seconds and embeds the observed and reconstructed traces with the same delay in each panel.
The AR coefficients are reused; a separate model is not fitted to each displayed interval. Each predicted segment is matched to its observed segment’s mean and standard deviation before embedding. Compare loop opening, thickness, and relative trajectory shape, while remembering that absolute amplitude differences have been removed for display.
The full reconstruction includes both the initial training portion and later samples. These panels are views of that one reconstruction, not independently fitted or independent test trials.
/tmp/ipykernel_3766439/1059032341.py:51: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all Axes decorations.
plt.tight_layout(pad=2.5, w_pad=1.5)
10. Inspect Sensitivity to the Embedding Delay#
The next comparison holds the signal interval and fitted model fixed and changes only the coordinate delay. It uses 2-4 seconds, with \(\tau\) equal to 5, 10, 15, and 20 samples: 10, 20, 30, and 40 ms at 500 Hz.
When a delay is very small relative to the oscillatory timescale, adjacent coordinates are nearly identical, compressing the curve toward a diagonal. A larger delay can separate phases and reveal an opening. Still larger delays can alter the apparent shape, mix changing dynamics across a longer history, or align particular oscillations unfavorably. Larger is therefore not automatically better.
Each three-dimensional point spans \(2\tau\) samples of history, and the number of points decreases as the delay increases. Judge the displayed differences as changes of representation, not changes to the underlying recording or additional fitted models. A useful delay resolves the relevant temporal structure and remains interpretable across nearby choices and time windows; an attractive isolated view alone is not a topology estimate.
/tmp/ipykernel_3766439/2192212464.py:49: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all Axes decorations.
plt.tight_layout(pad=2.5, w_pad=1.5)
11. Reconstruct Individual Recording Channels#
The final comparison repeats preprocessing and AR fitting separately for several channels. Each predictor uses only the history of its own channel. Signals are not averaged across electrodes, and a model trained on one channel is not used to predict another. This distinguishes a collection of univariate reconstructions from a multivariate model.
The four examples use channels 0-3, display intervals 5-6, 6-7, 8-9, and 10-11 seconds, and delays of 10 samples (20 ms). They require the full recording beyond the five-second snippet. The channel helper uses a 1-50 Hz bandpass, 500 Hz output, AR(3), 90% training, and five-sample history refreshes. In contrast, the initial single-channel example uses a 1-20 Hz bandpass, 10% training, and ten-sample refreshes. Both the data interval and some analysis settings therefore change in this panel.
Compare the observed and reconstructed trajectory within each panel first, then look for recurring geometry across panels. Each prediction is amplitude-matched to its corresponding observed interval. Since the displayed times can differ and neighboring electrodes can share activity, these panels are illustrative comparisons, not independent evidence of distinct sources or a cross-channel prediction benchmark.
Full data shape: (4, 10841760)
/tmp/ipykernel_3766439/806345731.py:77: UserWarning: Tight layout not applied. The left and right margins cannot be made large enough to accommodate all Axes decorations.
plt.tight_layout(pad=2.5, w_pad=1.5)
12. What to Take from the Reconstruction#
This example connects a 1-20 Hz processed waveform to a fitted AR(3) predictor and a three-dimensional delay trajectory. The waveform, residual ACF, scatter plot, and state-space views answer complementary questions:
Waveform and scatter: does the model reproduce sample timing and amplitude under the stated history-refresh protocol?
Residual ACF: what temporal structure remains in its errors?
Delay geometry: does the amplitude-matched reconstruction follow the observed local trajectory, and how does that comparison depend on the window and delay?
Channel views: does a similar reconstruction remain useful for other individual traces under their displayed settings?
Use these views together. A high correlation does not establish correct topology, and a visually open loop does not establish a particular number of independent modes. The preprocessing is offline, the AR coefficients are fixed within a fit, and observed-history refreshes constrain the reconstruction. These choices define what the figures demonstrate and how the example can be adapted.
To apply the workflow to another recording, begin with its actual sampling rate and array orientation, choose a physiologically relevant processing band, and keep model order, forecast horizon, and embedding delay distinct. Compare several time intervals rather than relying on a single visually appealing trajectory.
Continue with Intrinsic vs. Embedding Dimensionality for the connection between AR poles and oscillatory modes, or DeepLagField for learning time-varying coefficients and autoregressive order.