nirspipe.pipeline.restingstate#

Module Contents#

Functions#

lomb_scargle

Lomb-Scargle power of each row from its kept samples, on the periodogram’s own grid.

compute_alff

ALFF/fALFF per channel plus cross-channel mALFF/zALFF standardization.

compute_alff_roi

ROI-level amplitude: the mean of each ROI’s member channels, per chromophore.

compute_fc

Functional connectivity for one chromophore: channel-by-channel Pearson matrix.

fisher_z

Fisher r-to-z of an FC matrix (diagonal n/a), for group-level stats.

compute_fc_roi

ROI-level FC for one chromophore: average each ROI’s channels, then Pearson corr between ROIs.

compute_fc_seed

Seed-to-whole-brain FC: each ROI’s mean signal against every channel.

Data#

API#

nirspipe.pipeline.restingstate.logger = 'get_logger(...)'#
nirspipe.pipeline.restingstate.lomb_scargle(data: numpy.ndarray, keep: numpy.ndarray, sfreq: float) → tuple[numpy.ndarray, numpy.ndarray]#

Lomb-Scargle power of each row from its kept samples, on the periodogram’s own grid.

The classic periodogram with Scargle’s time shift \(\tau\), over the kept sample times \(t_j\) of a series demeaned on them:

\[P(\omega) = \frac{1}{N_k} \left[ \frac{\left(\sum_j y_j \cos \omega (t_j - \tau)\right)^2}{\sum_j \cos^2 \omega (t_j - \tau)} + \frac{\left(\sum_j y_j \sin \omega (t_j - \tau)\right)^2}{\sum_j \sin^2 \omega (t_j - \tau)} \right], \qquad \tan 2\omega\tau = \frac{\sum_j \sin 2\omega t_j}{\sum_j \cos 2\omega t_j}\]

at the Fourier frequencies of the full length, \(N_k\) the kept count. This is scipy.signal.lombscargle(..., normalize=True) times the kept samples’ variance, which puts it on the scale of scipy.signal.periodogram(..., scaling="spectrum"); with every sample kept the two are equal.

Parameters:
  • data (ndarray, shape (n_channels, n_times)) -- Full-length series; values at dropped samples are ignored.

  • keep (ndarray of bool, shape (n_times,)) -- False on dropped samples.

  • sfreq (float) -- Sampling rate in Hz.

Returns:

  • freqs (ndarray, shape (n_times // 2 + 1,)) -- np.fft.rfftfreq(n_times, 1 / sfreq), DC included.

  • power (ndarray, shape (n_channels, n_times // 2 + 1)) -- Power per frequency; the DC bin is 0, as after demeaning.

Notes

The kept samples sit on a uniform grid, so every sum above is a DFT of the zero-filled series or of the mask, and the 2ω sums are the mask’s DFT at bin \(2k \bmod n\). The result is exact, not the Press-Rybicki approximation: it matches scipy to about 1e-9. At the Nyquist bin of an even length every \(\sin \omega t_j\) is 0, so that term is dropped rather than divided by zero.

nirspipe.pipeline.restingstate.compute_alff(raw: mne.io.Raw, low_pass: float, high_pass: float, exclude: list[str] | None = None, reference: list[str] | None = None) → pandas.DataFrame#

ALFF/fALFF per channel plus cross-channel mALFF/zALFF standardization.

Expects a broadband (detrended, non-lowpassed) residual: fALFF’s denominator spans the full spectrum, so a bandpassed input collapses fALFF to ~1. ALFF only reads the band, so one broadband signal serves both (Zang 2007; Zou 2008):

\[ \begin{align}\begin{aligned}\text{ALFF} = \frac{1}{|B|} \sum_{f \in B} \sqrt{P(f)}, \qquad \text{fALFF} = \frac{\sum_{f \in B} \sqrt{P(f)}}{\sum_{f > 0} \sqrt{P(f)}},\\\text{mALFF}_c = \frac{\text{ALFF}_c}{\overline{\text{ALFF}}}, \qquad \text{zALFF}_c = \frac{\text{ALFF}_c - \overline{\text{ALFF}}}{\operatorname{sd}(\text{ALFF})},\end{aligned}\end{align} \]

where \(B = [\text{high\_pass}, \text{low\_pass}]\) is the low-frequency band and \(P(f)\) is the periodogram power (amplitude is \(\sqrt{P}\)). fALFF is in \([0, 1]\); the DC bin is dropped from the denominator. mALFF/zALFF standardize the scale-dependent ALFF across channels so it is comparable at the group level.

Notes

With BAD_ spans on the recording, \(P(f)\) is the lomb_scargle() power of the kept samples on the same frequency grid, so both sums run over the same bins as without spans; the denominator still reaches Nyquist. A channel with no finite sample gets NaN for both measures; a constant one keeps 0.

All four measures are NaN on a rejected channel, and the bad column says which those are. The mALFF/zALFF reference mean and SD already exclude them, so the blanking only removes the values themselves.

exclude names channels to treat exactly like rejected ones without calling them rejected: blanked, and out of the reference. It exists for a channel whose residual is identically zero because it was the whole short-channel regressor and was fitted against a copy of itself. Blanking such a channel while leaving it in the reference puts a numerical zero in the mean and SD that every other channel is scaled by, which shifts every other channel’s mALFF. The bad column keeps meaning rejected, since that is what the group tables read.

reference names the channels the mean and SD may come from, None every channel. The pipeline passes the long ones: a short channel samples the scalp, so its amplitude sets no other channel’s scale, though it is still scaled against them.

Rest mode produces two residuals and this function must receive the broadband one. The pipeline runs the confound regression a second time without the low-pass and feeds that residual here (FC keeps the bandpassed one). The linear detrend before the FFT is supplied by the GLM drift regressors.

nirspipe.pipeline.restingstate.ALFF_COLUMNS = None#
nirspipe.pipeline.restingstate.ALFF_ROI_COLUMNS = None#
nirspipe.pipeline.restingstate.ALFF_UNITS = None#
nirspipe.pipeline.restingstate.compute_alff_roi(alff_df: pandas.DataFrame, raw: mne.io.Raw, roi_map: dict[str, list[str]], chromophores: tuple[str, ...] = ('hbo', 'hbr')) → pandas.DataFrame#

ROI-level amplitude: the mean of each ROI’s member channels, per chromophore.

\[\overline{\mathrm{ALFF}}_A = \frac{1}{|A|} \sum_{c \in A} \mathrm{ALFF}_c\]
alff_df (one row per channel) + {"L": ["S1_D1", ...]}
  -> one row per (ROI, chromophore) with the four measures averaged

The averaging happens after the measure, which is the opposite of compute_fc_roi(). An ROI mean signal carries only the part its channels share, so an amplitude measured on it falls as the ROI grows and as its channels agree less.

Rejected channels are dropped before averaging rather than propagating NaN, the way every other ROI-level product here drops them; n_channels records how many survived, without which a thinly covered ROI reads like a well covered one. An ROI with nothing left keeps its row, n_channels 0 and the measures blank, so every subject’s table has the same rows.

nirspipe.pipeline.restingstate.FC_DESCRIPTIONS = None#
nirspipe.pipeline.restingstate.FISHER_Z_DESCRIPTION = 'Fisher z, arctanh(r), of the stat-pearson matrix of the same name, r clipped just below 1 in size.'#
nirspipe.pipeline.restingstate.FISHER_Z_DIAGONAL = ' The diagonal is n/a, arctanh(1) being infinite.'#
nirspipe.pipeline.restingstate.compute_fc(raw: mne.io.Raw, chromophore: str) → pandas.DataFrame#

Functional connectivity for one chromophore: channel-by-channel Pearson matrix.

\[\rho_{ij} = \operatorname{corr}(x_i, x_j)\]

over the channels of a single chromophore (chromophore is “hbo”, “hbr” or “hbt”); HbO and HbR anti-correlate, so a mixed matrix has no clean meaning and each is kept separate. Diagonal is 1. Empty frame if the chromophore has < 2 channels. Only frames outside every BAD_ span enter the correlation, here and in the ROI and seed products. Where a channel has NaN frames (a --combine-runs series, in the runs it was bad) each pair is taken over the frames both channels have, as pandas DataFrame.corr does.

A rejected channel’s row and column are NaN, not dropped: every subject’s matrix keeps the same shape and the same channel order, so a group analysis can stack them however their rejections differ. It is the package’s convention for every channel-by-channel matrix, nirspipe.pipeline.hyper.isc.compute_isc_pairs() included. ROI-level products do the opposite and drop the rejected channels before averaging (see compute_fc_roi()): a bad channel inside an ROI mean reaches every correlation that ROI takes part in, where in a channel matrix it is confined to one row and one column.

Plain Pearson, not shrinkage: a shrinkage estimator shrinks by an amount that tracks the channel-to-sample ratio, so it would differ between subjects. Every FC product here uses the same one.

nirspipe.pipeline.restingstate.fisher_z(fc: pandas.DataFrame) → pandas.DataFrame#

Fisher r-to-z of an FC matrix (diagonal n/a), for group-level stats.

\[z = \operatorname{arctanh}(r) = \tfrac{1}{2} \ln \frac{1 + r}{1 - r}\]

Variance-stabilises correlations so they can be averaged / tested across subjects; r is clipped just below \(\pm 1\) to keep perfect correlations from diverging.

nirspipe.pipeline.restingstate.compute_fc_roi(raw: mne.io.Raw, roi_map: dict[str, list[str]], chromophore: str = 'hbo', signals: dict[str, np.ndarray] | None = None) → pandas.DataFrame#

ROI-level FC for one chromophore: average each ROI’s channels, then Pearson corr between ROIs.

\[\rho_{AB} = \operatorname{corr}(\bar{x}_A, \bar{x}_B), \qquad \bar{x}_A = \frac{1}{|A|} \sum_{c \in A} x_c\]

Averages signals first (higher SNR) rather than averaging channel correlations; roi_map is {ROI label: [channel names]}, matched by S-D base (“S1_D1”), with any chromophore suffix on the map entry replaced by the requested one so the same map serves hbo and hbr.

Every ROI the map lists keeps its row and column; one with no good channel is blank, so every subject’s matrix has the same shape. Empty when fewer than two ROIs resolve, since no correlation is left to compute. signals ({ROI: series}) replaces the averaging, for a joined series whose ROIs were averaged run by run.

nirspipe.pipeline.restingstate.compute_fc_seed(raw: mne.io.Raw, roi_map: dict[str, list[str]], chromophore: str = 'hbo', signals: dict[str, np.ndarray] | None = None, members: dict[str, list[str]] | None = None) → pandas.DataFrame#

Seed-to-whole-brain FC: each ROI’s mean signal against every channel.

\[\rho_{Ac} = \operatorname{corr}(\bar{x}_A, x_c), \qquad \bar{x}_A = \frac{1}{|A|} \sum_{k \in A} x_k\]
Parameters:
  • raw (mne.io.Raw) -- Recording to correlate, one row per channel.

  • roi_map (dict[str, list[str]]) -- {ROI label: [channel names]}; every ROI becomes one seed, i.e. one row.

  • chromophore (str, optional) -- “hbo”, “hbr” or “hbt”. HbO and HbR anti-correlate, so they never share a map.

  • signals (dict, optional) -- {ROI: seed series} and {ROI: the channels averaged into it}, given together for a joined series whose seeds were averaged run by run; by default both come from raw.

  • members (dict, optional) -- {ROI: seed series} and {ROI: the channels averaged into it}, given together for a joined series whose seeds were averaged run by run; by default both come from raw.

Returns:

ROI x channel correlations, one row per listed ROI, blank for one with no good channel. Empty frame if no ROI resolves to a good channel.

Return type:

pd.DataFrame

Notes

Averaging happens on one side only, which makes this a third product rather than a view of the other two: it is neither a slice of compute_fc() (no averaging) nor of compute_fc_roi() (both sides averaged). Averaging first cancels each channel’s independent noise, so the same pair of regions reads higher through an ROI mean than through the mean of its channel-pair correlations.

A seed’s own channels are set to NaN, identified by membership, not by a correlation near 1: they sit inside the average, so their correlation is inflated by construction, and a test by value would also erase a channel that genuinely tracks the seed.

Membership means the channels actually averaged, so a rejected one listed in roi_map is not part of any seed. Columns span every channel, a rejected one’s being NaN, as in compute_fc().