Coherence & Time-Frequency Representations (TFR)¶
Coherence between two signals, and complex Morlet TFRs with streaming accumulation. Power spectra and decibel formation are on Power Spectra & Decibels.
1. Cross-Area Coherence & Imaginary Coherency¶
Cross-Area Coherence (cross_area_coherence)¶
Quantifies frequency-resolved phase synchronization between two LFP signals:
coh_dict = jnwb.cross_area_coherence(
lfp_area1,
lfp_area2,
fs=1000.0,
freq_bands=jnwb.CANONICAL_BANDS
)
# Returns dict containing:
# - 'band_coherence': Dict[band_name -> float]
# - 'coherence_spectrum': np.ndarray (frequency-by-frequency coherence values)
# - 'frequencies': np.ndarray
partial_coherence(X, Y, Z) gives the coherence of X and Y given one further signal Z (Dahlhaus,
2000): |G_xy|²/(G_xx G_yy), with G the inverse of the Welch cross-spectral matrix. It is reported
per band as band_coherence, with a circular-shift p-value in band_significance, and beside the
ordinary coherence on the same segments as unconditioned_band_coherence. A common driver is
removed only when it is Z. A singular cross-spectral matrix raises, naming the frequency. Each
conditioner costs a degree of freedom, so with one conditioner the null mean is about 1/(K−1) for
K segments.
coherence_bias_floor(signals, fs=..., freq_bands=...) takes epochs shaped (n_sites, n_epochs,
n_times) and gives, per band, the coherence that unrelated epochs reach by bias alone. Uniform
derangements pair each epoch of one site with another epoch of the next, n_draws times; the mean
over draws is taken per site pair, and the floor is the maximum of those means over the pairs
(Maris et al., 2007; Bastos and Schoffelen, 2016). The floor estimates the bias of a finite epoch
count. Exceeding it does not establish significance: with few site pairs the maximum sits near the
null mean, so a threshold needs the maximum over many site pairs.
Imaginary Coherency & Weighted Phase Lag Index (imaginary_coherency, wpli)¶
Measures based on the imaginary cross-spectrum reduce sensitivity specifically to zero-phase-lag
coupling (instantaneous volume conduction, shared reference contamination). They do not confer
immunity to non-zero-lag common inputs, source mixing, or reference-induced phase structure.
icoh_mean is signed: positive means x leads when the wrapped lag phase is in (0, pi); in
(pi, 2pi) the sign reverses, and the band mean can cancel across frequencies. The convention
is the one phase_slope_index follows. wpli is unsigned.
# Imaginary coherency (Nolte et al. 2004)
imag_coh = jnwb.imaginary_coherency(
lfp_area1,
lfp_area2,
fs=1000.0,
freq_range=(15.0, 30.0),
signal_class="lfp",
)
# Weighted Phase Lag Index (Vinck et al. 2011)
# Returns standard wPLI, debiased squared wPLI, and spectrum across segments
wpli_res = jnwb.wpli(
lfp_area1,
lfp_area2,
fs=1000.0,
freq_range=(15.0, 30.0),
)
Validation: synthetic | N = 1 signal pair | seed 42, 64 | input synthetic | jnwb 0.2.17


Synthetic. Two channels share two rhythms in the alpha and beta bands, and both panels draw the same source and the same noise. Panel A has zero lag: coherence (jnwb.cross_area_coherence, over jnwb.CANONICAL_BANDS) is high at the rhythms, while jnwb.imaginary_coherency and jnwb.wpli stay near zero there; away from the rhythms no signal is shared, and what the three measures show is estimator noise. Panel B delays one channel by a fixed lag: the imaginary coherency and wPLI rise to large values at the rhythms, and coherence does not change. Each panel title gives the Welch segment count that jnwb.wpli reports; wPLI is biased upward when that count is small.
2. High-Level Analyzers (jnwb.analyzers)¶
jnwb.analyzers provides object-oriented interfaces for analyzing session data:
TFRAnalyzer: Time-frequency analysis and coordinate-explicit band extraction.UnitAnalyzer: Single-unit spike train autocorrelation and quality metrics.PopulationAnalyzer: Multi-unit population PSTH and cross-condition comparisons.
Coordinate-Explicit Band Extraction (TFRAnalyzer.extract_band)¶
Requires explicit physical frequency coordinates (freqs) and validates frequency axis alignment:
from jnwb.analyzers import TFRAnalyzer
# tfr_data: (n_channels, n_freqs, n_times)
# freqs: (n_freqs,) exact physical frequency coordinates in Hz
beta_power = TFRAnalyzer.extract_band(
tfr_data,
band="beta",
freqs=freqs,
freq_axis=1
)
3. Complex Morlet Time-Frequency Representations & Accumulation¶
Complex Morlet Transform (complex_tfr, morlet_wavelet)¶
jnwb.complex_tfr computes complex time-frequency coefficients via Morlet wavelets with discrete \(L_1\) amplitude normalization:
import jnwb
import numpy as np
# raw_lfp: (n_channels, n_times)
freqs = np.linspace(10.0, 60.0, 11) # 10 to 60 Hz in 5 Hz steps
# Compute complex coefficients with Cone of Influence (COI) mask
tfr_res = jnwb.complex_tfr(
data=raw_lfp,
fs=1000.0,
freqs=freqs,
n_cycles=5.0,
normalization="amplitude" # unit cosine yields peak |z| = 1.0
)
# Returns ComplexTFR dataclass:
# - tfr_res.z: np.ndarray, complex (n_channels, n_freqs, n_times)
# - tfr_res.coi_mask: np.ndarray, bool (n_channels, n_freqs, n_times)
# - tfr_res.power: np.ndarray (|z|^2)
# - tfr_res.phase: np.ndarray (angle in radians)
# - tfr_res.amplitude: np.ndarray (|z|)
Validation: synthetic | N = 1 signal | seed 3 | input synthetic | jnwb 0.2.17


Panel A of that figure is a synthetic LFP trace carrying one transient oscillatory burst and panel B is
jnwb.complex_tfr on it with the cone of influence drawn and the region outside it veiled: what
the next paragraph excludes is visible, not described.
What coi_mask excludes, and why the average comes after it. Convolution runs with
mode="same", so near each edge part of the kernel hangs off the signal and is filled with
zeros. coi_mask is False for exactly those samples: the excluded region is the kernel
half-width, ceil(cutoff_sigma * sigma_t * fs), which is what coi_sigma=None (the
default) derives it from. A True sample is one no zero-padding reached.
The contaminated samples are not merely noisier. They are pulled toward zero by an amount that depends on the signal's mean, and they sit at the ends of every trial, so they bias the same time points in the same direction in every trial. Average after masking, not before:
# WRONG: the edges are in the mean, and they are biased, not just noisy
mean_power = tfr_res.power.mean(axis=-1)
# CORRECT: exclude them, then average over what is left
masked = np.where(tfr_res.coi_mask, tfr_res.power, np.nan)
mean_power = np.nanmean(masked, axis=-1)
# Streaming: TFRAccumulator takes the mask directly and keeps a per-cell count
acc.add_trial(tfr_res.z, valid=tfr_res.coi_mask)
Low frequencies and high n_cycles both widen sigma_t, so both widen the excluded region:
at 10 Hz the kernel half-width is 191 samples at n_cycles=3 and 637 at n_cycles=10
(fs = 1000 Hz). A short trial at a low frequency can be excluded end to end, which is the
correct answer: there is no uncontaminated estimate to report.
Streaming TFR Accumulation (TFRAccumulator) & NWB fp32 Compression (compress_fp32)¶
TFRAccumulator&assert_mergeable(jnwb.tfr_accumulator): Accumulates running sums and sum-of-squares across streaming trials (add_trial(tfr_res.z, valid=tfr_res.coi_mask)) without storing complete trial tensors in RAM. Its output has already averaged over trials, soaggregate_to_db(how="mean_of_ratios")refuses it. For that estimand, add each trial with its own baseline power (add_trial(..., baseline=...)) and takejnwb.to_db(acc.mean_of_ratios()).compress_fp32(jnwb.compression): On-disk NWB conversion: casts the datasets named inselect=tofloat32inside an NWB file, irreversibly (path I/O, not in-memory array quantization).select=is required; omitting it raisesTypeErrorbefore writing;select=[]casts nothing:
# src and dst are filesystem paths to .nwb files; select names datasets by their path in the file
report = jnwb.compress_fp32(
"raw_session.nwb", "compressed_session.nwb",
select=["acquisition/probe_0_lfp/data"], verify=True,
)
assert report["verification"]["ok"] is True
References¶
The methods on this page are cited in References.