Common Mistakes¶
Failure modes in neuronal data analysis, and how jnwb guards against each.
1. Averaging Decibels Instead of Power (Jensen's Inequality)¶
The Mistake¶
Converting individual trials or channels to decibels (\(10 \log_{10}(P / P_0)\)) and then averaging the decibel values:
# WRONG: Jensen's inequality error
db_trials = 10 * np.log10(power / baseline)
mean_db = np.mean(db_trials) # Biased by individual trial noisiness!
Because the logarithm is strictly concave, Jensen's inequality guarantees: $\(\mathbb{E}[\log_{10}(X)] \le \log_{10}(\mathbb{E}[X])\)$
Averaging decibels underestimates physical power and disproportionately weights noisy trials with near-zero baseline power, pulling the aggregate away from the true population effect.
The Correct Pattern¶
Form the ratio on the linear power scale, aggregate the ratios, and take the logarithm exactly once at the end:
# CORRECT: Log-last rule via jnwb.aggregate_to_db
import jnwb
# Option A: Every unit/trial weighted equally
db_mean = jnwb.aggregate_to_db(power, baseline, how="mean_of_ratios", aggregate_over=0)
# Option B: Weighted by baseline power (conserves total physical energy)
db_weighted = jnwb.aggregate_to_db(power, baseline, how="ratio_of_means", aggregate_over=0)
jnwb.aggregate_to_db enforces this; its negative-input guard is described in Decibel Formation.
2. Inclusive Bin Boundaries Double-Counting Spikes¶
The Mistake¶
Using right-closed or inclusive bin intervals \([t_k, t_{k+1}]\) when binning spikes across contiguous time windows:
# WRONG: Spike at 100.0 ms falls into BOTH [0.0, 100.0] and [100.0, 200.0]
window_1 = (spikes >= 0.0) & (spikes <= 100.0)
window_2 = (spikes >= 100.0) & (spikes <= 200.0)
A spike landing precisely on the bin boundary (\(t = 100.0\text{ ms}\)) is counted twice, artificially inflating firing rates and distorting latency estimates.
The Correct Pattern¶
Use uniform right-open intervals \([t_k, t_{k+1}) = [t_0 + k\Delta,\; t_0 + (k+1)\Delta)\):
# CORRECT: jnwb.bin_spikes, jnwb.fires_in_window, and jnwb.rate_in_window
# Spikes at 100.0 ms are counted in window 2, never in window 1
rate_w1 = jnwb.rate_in_window(spikes, onset_s=0.0, window_ms=(0.0, 100.0))
rate_w2 = jnwb.rate_in_window(spikes, onset_s=0.0, window_ms=(100.0, 200.0))
# Or vectorized across multiple trials:
rates, centers = jnwb.bin_spikes(spikes_list, window=(0.0, 0.5), bin_size_ms=10.0, output="rate", return_centers=True)
3. Global Shuffling on Structured Trials (Exchangeability Violations)¶
The Mistake¶
Using an unconstrained global permutation (np.random.permutation(y)) to construct a null distribution when data has hierarchical structure (e.g. repeated stimulus blocks, sessions, or animals):
# WRONG: Breaks exchangeability when labels are correlated with session/cycle
y_null = np.random.permutation(y_true)
If class proportions vary across sessions or cycles, global shuffling destroys the covariance structure between trial covariates and labels, yielding an overly optimistic null distribution and inflated false positive rates (\(p < 0.05\) under the null).
The Correct Pattern¶
Permute labels within each group independently, preserving each block's internal marginal composition:
# CORRECT: jnwb.permute_labels with explicit within_group scheme
rng = np.random.default_rng(42)
y_null = jnwb.permute_labels(
y_true,
groups=cycle_ids,
scheme="within_group",
rng=rng
)
jnwb.permute_labels requires an explicit scheme ("within_group" or "global") and rejects implicit defaults.
4. Pre-Split Feature Scaling & Cross-Validation Leakage¶
The Mistake¶
Normalizing (z-scoring) the entire feature matrix \(X\) before partitioning into cross-validation folds:
# WRONG: Information from test fold leaks into training normalization
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
for train_idx, test_idx in kfold.split(X_scaled, y):
clf.fit(X_scaled[train_idx], y[train_idx])
The mean and variance of held-out test trials leak into the training features, leading to overly optimistic cross-validation accuracy that collapses when tested on genuinely independent data.
The Correct Pattern¶
Fit scalers and feature transformers strictly on training folds inside a Pipeline:
# CORRECT: jnwb.nested_cv_linear_svm fits the scaler inside each training fold
res = jnwb.nested_cv_linear_svm(X, labels, n_splits=5)
print("Row-wise outer CV accuracy (upper bound):", res["accuracy"])
print("Fold Majority Baseline:", res["majority_baseline_accuracy"])
This removes scaler and hyperparameter-selection leakage, not block leakage. Report
accuracy as an upper bound on the block-held-out accuracy; Decoding & Unit-Quality Plots gives the mechanism.
5. Conflating Hardware Channel ID with DataFrame Row Index¶
The Mistake¶
Assuming that electrode channel IDs match DataFrame row indices:
# WRONG: If electrodes_df was filtered or reset_index() was called,
# row 10 does not necessarily correspond to channel ID 10!
location = electrodes_df.loc[10, "location"]
In high-density probes where noisy or non-connected channels are removed, electrodes_df has non-contiguous channel IDs or a standard 0..N-1 RangeIndex. Looking up by integer index returns the wrong contact or throws a KeyError.
The Correct Pattern¶
Use jnwb's channel resolution functions. They search hardware_channel when the table has that column (a peak channel names a hardware channel; -1 is no channel; a value found on electrodes of more than one probe, when the table names probes, resolves to None). Otherwise they search one identifier column, the first of channel_id, id and electrode_id present. A channel missing from the searched column resolves to None; the row index is read only when the table has none of these columns:
# CORRECT: Robust addressing handles filtered, non-contiguous, or multi-area probes
area = jnwb.map_peak_channel_to_area(peak_channel_id=10, electrodes_df=electrodes_df)
depth_class = jnwb.classify_layer_from_depth(peak_channel_id=10, electrodes_df=electrodes_df, depth_unit="um")
6. Conflating Statistical Predictability with Physical Causality¶
The Mistake¶
Interpreting Granger causality, Phase Slope Index (PSI), or Transfer Entropy (TE) as perturbational causal mechanisms:
| Metric | What it measures | What it cannot rule out |
|---|---|---|
| Granger causality | Whether past values of \(X\) improve linear autoregressive prediction of \(Y\) | The pitfalls below |
| Phase Slope Index | The sum over adjacent frequency bins of \(\mathrm{Im}(C^*_f\,C_{f+\delta f})\) on the coherency \(C\); its sign is read as which signal leads. It tests neither linearity nor a delay | A common driver with asymmetric conduction delays |
| Transfer Entropy | Information-theoretic reduction in uncertainty of \(Y\) given \(X\)'s past. Non-parametric | Anything: it is still observational |
The Correct Pattern¶
Report directed metrics as statistical predictability or phase-lead asymmetries, reserving causal claims for perturbation experiments (e.g. optogenetics, microstimulation, lesioning):
# CORRECT: Explicit directional reporting
gc = jnwb.granger(x, y, order=10)
print(f"X -> Y log variance ratio: {gc.x_to_y:.4f} (p = {gc.p_x_to_y:.4f})")
print(f"Y -> X log variance ratio: {gc.y_to_x:.4f} (p = {gc.p_y_to_x:.4f})")
7. Misinterpreting Phase Slope Index on Narrowband Signals¶
The Mistake¶
Interpreting a near-zero Phase Slope Index (\(|z| < 2\)) on a pure sinusoid or very narrowband signal as evidence of no directional lead:
# TRAP (receipt: 2000 samples at 1 kHz, seed=42, n_surrogates=50): a 20 Hz sinusoid
# with 10 ms delay in an 18–24 Hz band gives net PSI = nan and band z = nan
# (one 5.26 Hz bin at the default nperseg of 190). The same delay on 15–30 Hz broadband noise gives
# net ≈ 0.64 and band z ≈ 7.9.
At a single discrete frequency \(f_0\), a time delay \(\Delta t\) and a constant phase offset \(\Delta \phi = 2\pi f_0 \Delta t\) are indistinguishable. PSI requires phase information across multiple neighboring frequency bins to estimate a phase slope (\(\frac{d\phi}{df}\)).
Validation: synthetic | N = 1 signal pair | seed 0, 42 | input synthetic | jnwb 0.2.17

The figure is synthetic: one seeded pair of 2000 samples at 1 kHz, with Y equal to X delayed 10 ms plus noise. jnwb.phase_slope_index over 18–24 Hz holds one bin, so its net is nan; over 15–30 Hz the net is 0.641 (z = 7.91), positive, so X leads Y.
The Correct Pattern¶
Evaluate PSI over a broadband band with multiple frequency bins; inspect per_band and spectrum, not a single-bin z-score:
import numpy as np
import jnwb
rng = np.random.default_rng(42)
fs = 1000.0
t = np.arange(2000) / fs
x = np.sin(2 * np.pi * 20 * t)
y = np.roll(x, int(0.01 * fs)) # 10 ms delay
psi_narrow = jnwb.phase_slope_index(x, y, fs=fs, bands=(18.0, 24.0), n_surrogates=50, rng=0)
noise_x = rng.normal(size=2000)
noise_y = np.roll(noise_x, int(0.01 * fs)) + 0.3 * rng.normal(size=2000)
psi_broad = jnwb.phase_slope_index(
noise_x, noise_y, fs=fs, bands=(15.0, 30.0), n_surrogates=50, rng=0,
)
print("Narrow band net:", psi_narrow.net) # nan: 18-24 Hz holds one bin, no slope
print("Broad band net:", psi_broad.net) # >> 0 for broadband noise + delay
print("Broad band z:", psi_broad.per_band["band"]["z"])
# Directional association only — not perturbational causality.
8. Ignoring Causal Filter Group Delay in Onset Latency¶
The Mistake¶
Comparing onset latencies across frequency bands or conditions when different smoothing filters or filter orders were used:
# TRAP: A causal exponential filter with tau=50 ms shifts the step response by ~35 ms!
# Interpreting t_observed = 85 ms as an 85 ms biological latency is erroneous.
A causal filter introduces a deterministic group delay:
| Measure | Delay |
|---|---|
| Impulse response centroid (mean delay) | \(\bar{t} = \tau_{\text{ms}}\) |
| Step response 50% amplitude rise | \(t_{50\%} = \tau_{\text{ms}} \ln(2) \approx 0.693 \cdot \tau_{\text{ms}}\) |
| Step response 10% amplitude rise | \(t_{10\%} = \tau_{\text{ms}} \ln(1/0.9) \approx 0.105 \cdot \tau_{\text{ms}}\) |
Validation: synthetic | N = 1 signal | seed none | input synthetic | jnwb 0.2.17

The figure is synthetic: with tau = 50 ms, jnwb.causal_exp_smooth puts the 50% crossing of a 5-to-40 Hz step 33.3 ms after its onset at 1 ms bins, against tau ln 2 = 34.7 ms for the continuous filter, and jnwb.gaussian_smooth_rate (sigma = 20 ms) reaches its 10% level 26.1 ms before the onset.
The Correct Pattern¶
- Fix \(\tau\) and \(\Delta t\) uniformly across all conditions being compared.
- Use causality-bounded parametric fitting (
jnwb.fit_exponential_onset), which fits \(t_0\) to the whole rise rather than to one threshold crossing. On a graded rise the fitted \(t_0\) still moves withtau_ms, which is why step 1 fixes it; no fixed filter-delay correction applies to it. - Check
fit["bound_status"], which says only whether \(t_0\) sits at an end oft0_bounds_ms. A fit to noise can readNonewithtauat an end oftau_bounds_msandr2near 0, so read those two as well.
9. Assuming a Schema the File Does Not Have¶
The Mistake¶
Carrying one session's layout into the next one:
# WRONG: every one of these is an assumption, and none of them errors loudly
onsets = jnwb.event_onsets("session.nwb") # which interval table?
table = jnwb.events("session.nwb") # which column holds codes?
lfp, fs = jnwb.acquisition_channel("session.nwb", channel=0) # which acquisition?
NWB constrains the container, not the contents. The code column is named by the file's author,
and Errors says what the codes default does with a file that
names it otherwise. A file may hold five interval tables, of which the one you
want is not the first. Onsets are seconds here and milliseconds in other
toolboxes, and a continuous array may be stored time-by-channel or channel-by-time.
The one of those jnwb resolves for you is the array orientation: acquisition_channel
reads the channel axis from the series' own electrode region, so channel=0 is the same
channel in either orientation, and inspect reports which one it found under layout.
Where the electrode count settles nothing: neither dimension matches it, or the array is
square so both do. layout is "ambiguous" and acquisition_channel raises
AmbiguousLayoutError rather than return a slice taken across channels at one instant as
though it were a channel's time course.
The Correct Pattern¶
Read the layout first and pass what you found:
# CORRECT: inspect reports the structure; every choice after it is explicit
info = jnwb.inspect("session.nwb")
for table in info["interval_tables"]:
print(table["name"], [column["name"] for column in table["columns"]])
for acquisition in info["acquisitions"]:
print(acquisition["name"], acquisition["data_shape"], acquisition["layout"], acquisition["rate_hz"])
onsets = jnwb.event_onsets(
"session.nwb", table="trials", code_column="stimulus", codes=["grating"],
)
Several interval tables and none
named trials raises AmbiguousIntervalTableError listing the names; a code column that
does not exist raises ColumnNotFoundError listing the columns that do; on a table with no
codes column, events returns its onsets and warns that it found no codes. Each message contains
the argument you need, so the fix is to pass it rather than to fall back to a default.
examples/tutorials/00_your_own_file.py is this pattern end to end on a file it has never
seen.
10. Reading a Zero That Was Never Estimated¶
A zero returned for a selection that contained nothing is indistinguishable, downstream, from a zero that was measured. It plots, it averages, it enters a t-test, and it drags the group mean toward the origin, and nothing in the array says which kind it was.
The policy across jnwb: an explicitly requested population with no observations yields an
unavailable estimate, never zero. Zero is a valid answer only when zero was estimated
from observations.
| Where the estimate lives | The unavailable value |
|---|---|
| A float array | NaN |
| A type that can carry absence | None, or an explicit availability field |
| A component that could not be estimated: fewer units than requested components, no variance to decompose | NaN, never a padded 0.0 |
# An area with no units. The trajectory is not at the origin; there is no trajectory.
res = jnwb.compute_population_trajectory(session, area="NONEXISTENT", epochs_df=epochs,
time_window_ms=(-1000, 2000))
assert np.all(np.isnan(res["trajectory"]))
assert np.all(np.isnan(res["explained_variance_ratio"]))
# An empty layer mask. The average over no channels is not zero.
sup, deep = jnwb.TFRAnalyzer.average_across_channels(tfr, layer_mask=mask)
assert np.all(np.isnan(sup))
So check availability rather than magnitude:
# WRONG: an unobserved population and a silent one give the same answer
if np.nansum(res["explained_variance_ratio"]) == 0.0:
...
# CORRECT: the two conditions are distinguishable, so distinguish them
if np.all(np.isnan(res["explained_variance_ratio"])):
... # PCA did not run -- nothing was selected
elif np.nansum(res["explained_variance_ratio"]) < 0.01:
... # PCA ran and found almost no structure
A count is the exception that proves the rule. bin_spikes returns 0 for a bin a unit was
recorded through and did not fire in: that zero was observed, and it is correct.
11. Onsets on a Different Clock from the Data¶
The Mistake¶
start_time is seconds in the NWB specification, and milliseconds in the
toolboxes that wrote the file you were handed. Nothing in the file says which, and the
difference is a factor of 1000 that every function downstream will accept:
# WRONG: the onsets are milliseconds, the session is 1.0 s long, nothing says so
onsets = jnwb.event_onsets("session.nwb", table="trials") # [1000. 2000. ... 5000.]
epochs, t = jnwb.epoch_continuous(lfp, onsets, win_s=(-0.2, 0.6), fs=fs)
epochs.shape # (5, 800) -- the right shape
np.all(np.isnan(epochs)) # True -- and not one number in it
A mean of that is NaN, a spectrum of it peaks at 0 Hz, and a figure of it is blank. The array is the correct shape with the correct dtype beside a correct time axis, so nothing in it reads as an error.
The Correct Pattern¶
Compare the onsets against the extent of the data before trusting either. Onsets are
session time and sample 0 is at the series' starting_time, or at its first timestamp when
the series stores timestamps (starting_time is then None), so the data span that start to
that start plus the duration:
import numpy as np
from pynwb import NWBHDF5IO
series = jnwb.inspect("session.nwb")["acquisitions"][0]
if series["starting_time"] is not None: # stored with starting_time and rate
data, fs = jnwb.acquisition_channel("session.nwb", name=series["name"], channel=0)
start_s = series["starting_time"]
else: # stored with timestamps, sampled regularly
with NWBHDF5IO("session.nwb", "r") as io:
stored = io.read().acquisition[series["name"]]
t, data = stored.timestamps[:], stored.data[:, 0] # series["layout"], raw samples
fs, start_s = 1.0 / np.median(np.diff(t)), float(t[0])
onsets = jnwb.event_onsets("session.nwb", table="trials")
if onsets.max() > start_s + len(data) / fs:
onsets = onsets / 1000.0 # they were milliseconds; say so in the script
epochs, t = jnwb.epoch_continuous(data, onsets - start_s, win_s=(-0.2, 0.6), fs=fs)
epoch_continuous warns when most epochs fall entirely outside the data under
boundary_policy="nan", naming both spans, because that is what a unit mismatch looks
like. A single stray event does not warn. Events near the edges of a recording are
ordinary, and their epochs are partly NaN by design. A non-finite onset raises
InvalidOnsetValueError, as in events and event_onsets.
time_unit on an EventTable is a label, not a measurement: the interval table carries
no extent to check it against. The check is possible only where the onsets meet the
continuous data, which is epoch_continuous.
12. Sorter Labels Read as Ground Truth¶
The Mistake¶
Reading a sorter's good label, or its quality column, as proof that a unit is a single
neuron. A label is the sorter's output and no measure of jnwb.unit_quality confirms it.
The Correct Pattern¶
Screen units against cut-offs you state, report a measure the input cannot support (NaN,
'Unknown') as not estimable, and leave the single-neuron claim unmade. The fifth safeguard of
the jnwb-qc skill holds the
rule.
13. A Coherence Graph Thresholded Without Distance¶
The Mistake¶
Thresholding a coherence matrix keeps the edges field spread put there. Nearby contacts cohere through spread alone, so the graph is dense among neighbors and sparse between distant sites: one threshold keeps the spread edges and can drop a real far-pair interaction sitting below them.
The Correct Pattern¶
Divide each edge by the mean coherence of the other pairs at its separation before
thresholding: pairs one, two and three steps apart by their own separation's mean,
farther pairs by the pooled far mean. The pair itself is left out of its baseline,
so a strong edge cannot lift the bar it is read against. Dividing by the
separation mean removes edges that are high only because they are near, and keeps
an interaction that stands above its own separation. Nejat and Hajipour Sardouie
(2021) normalize edge weights by how coherence changes with distance before comparing
groups edge by edge (Pitfalls). cross_area_coherence with
network_topology builds the graph; the distance-bin normalization is the caller's step.
Interpretational Pitfalls of Coupling and Direction¶
Each pitfall is stated here once. Sources are rows of the
Pitfalls table (Bastos and Schoffelen 2016, Vezoli et al. 2021, Friston
et al. 2014, Barnett and Seth 2011). A pitfall with no guard in jnwb is the caller's step.
| Pitfall | What goes wrong | Guard in jnwb, or the caller's step |
|---|---|---|
| Common reference | A reference shared by two channels adds zero-lag coherence and Granger influence between them | Caller: apply bipolar_reference or laplacian_reference before coherence or Granger. No estimator detects a shared reference |
| Volume conduction | Field spread couples sites with no interaction | Stated under imaginary coherency and wPLI |
| Signal-to-noise asymmetry | One source on two channels with no interaction gives significant Granger influence both ways, and with unequal noise the net direction credits the cleaner channel. With 6x noise on y the net runs x to y in 20 of 20 seeds at orders 1, 2 and 8; with the noise on x it runs y to x in 20 of 20 | Caller: compare power between channels and conditions before reading direction. granger_time_reversed gives a time-reversal control; jnwb has no power-stratification control |
| Common input | An unrecorded source drives both signals and leaves a Granger or phase-slope direction between them | No estimator removes it; a recorded source is conditioned on as stated here, and for coherence partial_coherence conditions on it |
| Bivariate against conditional Granger | A bivariate fit credits X with influence routed through a third recorded signal | Stated here. granger takes Z; directed_network(conditional=True) conditions on all other nodes; granger_spectral has no Z |
| Sample-size bias | Coherence sits near 1/K for K segments under no coupling | PLV bias and PPC are stated here; wpli returns wpli_debiased_sq; cross_area_coherence returns n_segments_used, and coherence_bias_floor gives the trial-level floor. Caller: compare conditions at equal K |
| Phase slope as direction | A phase slope gives a lag asymmetry in the statistics, not an anatomical direction. An unrecorded common input with unequal delays to x and y also reads as a lead | phase_slope_index tests the lead (p_net) apart from coupling; see its page |
| Filtering before Granger | The Granger causality of the process is invariant under an invertible filter (Barnett and Seth 2011), so band-passing cannot isolate a band; the estimate from a finite filtered sample does change, and the fitted order often rises | Caller: do not filter first; read per_band of granger_spectral. No estimator detects a filtered input |
| Non-stationarity | A slowly decaying or drifting mode makes a finite-order VAR fail | granger_spectral records a warning in diagnostics and sets diagnostics['stationary'] false when the fitted VAR's spectral radius reaches 1. That key is a fitted-VAR stability check, not a stationarity test: a slowly decaying mode passes it. granger has no such check, only detrend='linear' on request |
References¶
- Nejat and Hajipour Sardouie (2021)
- Bastos and Schoffelen (2016)
- Vezoli et al. (2021)
- Friston et al. (2014)
- Barnett and Seth (2011)