nirspipe.pipeline.hyper.surrogate#

Surrogate coherence: what a dyad’s value is read against.

phase_scramble             One surrogate trace, the spectrum kept and the phases randomised.
phase_rotate               Several traces rotated by one shared set of random phases.
compute_wtc_phase_null     Each pairing against a phase-scrambled later member, computed
                           inside the per-group pass.
compute_wtc_pair_null      The accounting the re-paired null needs, whose draws are real
                           recordings rather than scrambled ones and therefore arrive from
                           outside.

Module Contents#

Classes#

NullDraws

One chromophore’s null: the draws, the levels, and the summary of both.

Functions#

phase_scramble

Surrogate with the same power spectrum as sig and its phases randomised.

phase_rotate

Surrogates of several signals, each frequency’s phase moved by one random angle shared by all rows.

compute_wtc_phase_null

Phase-scrambled band means: WTC against a phase-scrambled partner, averaged over n_iter.

compute_wtc_pair_null

Re-paired band means: WTC of one member against people they never interacted with.

Data#

API#

nirspipe.pipeline.hyper.surrogate.logger = 'get_logger(...)'#
nirspipe.pipeline.hyper.surrogate.phase_scramble(sig: numpy.ndarray, rng: numpy.random.Generator) → numpy.ndarray#

Surrogate with the same power spectrum as sig and its phases randomised.

Scrambling one side’s phases destroys every temporal relationship while leaving each signal’s own spectrum and autocorrelation intact, so coherence computed against the surrogate is the coherence two unrelated recordings of this kind produce.

Phases are randomised under Hermitian symmetry, so the inverse transform is real and the magnitude spectrum is preserved exactly. DC and, on an even-length record, Nyquist have no mirror partner and keep their sign instead of taking a phase.

nirspipe.pipeline.hyper.surrogate.phase_rotate(rows: numpy.ndarray, rng: numpy.random.Generator) → numpy.ndarray#

Surrogates of several signals, each frequency’s phase moved by one random angle shared by all rows.

The multivariate surrogate of Prichard and Theiler (1994): each row keeps its power spectrum, as in phase_scramble(), and the rows keep their cross-spectra, so a member’s channels stay as correlated with each other as they were recorded. DC and, on an even-length record, Nyquist keep their values, as in phase_scramble().

class nirspipe.pipeline.hyper.surrogate.NullDraws#

One chromophore’s null: the draws, the levels, and the summary of both.

Carries either null. They differ in how a draw is made, phase randomisation against re-pairing, and in nothing after that, so both summarise through the same code and their tables subtract from the same real table.

The draws are kept rather than averaged on the spot, since a real value is ranked inside them by a step that runs after this one. summarise() is that step’s half.

draws: list[pd.DataFrame] = None#
cond_draws: list[pd.DataFrame] = None#
keys: list[str] = None#
levels: dict = None#
partners: list[str] | None = None#
cond_draw_ids: list[str] | None = None#
cond_levels: dict | None = None#
roi_levels: dict | None = None#
summarise(real: pandas.DataFrame | None = None, real_by_cond: pandas.DataFrame | None = None) → tuple[pd.DataFrame, pd.DataFrame | None]#

The whole-run and per-condition null tables, ranked against real if given.

real is the true-dyad band-mean table this null sits beside, matched on the key columns, and turns on the percentile column: the share of a cell’s draws its real value beat. Exact rather than interpolated from the stored quantiles. real_by_cond does the same for the per-condition table.

summarise_roi(roi_map: dict[str, list[str]], real: pandas.DataFrame | None = None, real_by_cond: pandas.DataFrame | None = None, min_channels: int = ROI_MIN_CHANNELS, crossed: bool = False, real_channels: pandas.DataFrame | None = None) → tuple[pd.DataFrame, pd.DataFrame | None]#

The same two tables at ROI level, for roi_mean_of_homologous().

Each iteration is grouped into ROIs before the iterations are summarised, so the null of an ROI mean keeps how its channels’ draws move together within an iteration.

The draws being averaged are the ones already taken for the channel table; no surrogate is transformed twice.

By default this is the homologous ROI value. A crossed (roi, roi) cell also holds the within-region cross pairings, which a homologous null never draws. crossed groups every pairing instead, roi_mean_of_channels()’s ROI x ROI matrix, and is only meaningful on draws that were themselves crossed.

real_channels, the real channel table per condition, puts each condition draw on the real pairing’s channels (_region_on_real_channels()).

nirspipe.pipeline.hyper.surrogate.NULL_ARROW_QUANTILE = 0.95#
nirspipe.pipeline.hyper.surrogate.compute_wtc_phase_null(raws: dict[str, mne.io.Raw], band_fmin: float, band_fmax: float, n_iter: int = 100, fmin: float = 0.004, fmax: float = 0.2, seed: int | None = None, cross: bool = False, limit_scales: bool = True, mask_coi: bool = True, ch_type: str = 'hbo', sep_bands=None, windows: list[tuple[str, float, float]] | None = None, analysis_window: tuple[float, float] | None = None, roi_map: dict[str, list[str]] | None = None, roi_min_channels: int = ROI_MIN_CHANNELS, device=None, shared: bool = False, cond_cone: bool = False, margins: dict[str, tuple[float, float]] | None = None) → nirspipe.pipeline.hyper.surrogate.NullDraws#

Phase-scrambled band means: WTC against a phase-scrambled partner, averaged over n_iter.

Each pairing keeps its earlier member real and has its later member replaced by surrogates, and the whole pairwise WTC is rerun, once per iteration; the band means are averaged across iterations. The summary keys its rows as wtc_band_mean does, so a true-dyad table and this one line up cell by cell, and holds the null’s centre as null_mean and null_mean_z (not coherence) with null_sd, null_p95, n_iter and n_valid_frac, plus percentile once ranked against the real table.

In a group of more than two, every member after the first is scrambled once per iteration and that one surrogate serves every pairing it closes, so each pairing’s draw is a dyad’s while two pairings that share a member keep their covariance in the draws a group mean is ranked against.

Returns a NullDraws, which holds the per-iteration draws as well as their summary: ranking a real value inside its null needs the draws, and the caller that has the real table to rank runs after this one.

Cost is n_iter times a full WTC run. Significance contours are never computed here: this table is the null. The surrogate maps are not saved either; each one is counted into a per-frequency histogram on the way past, and NullDraws.levels is {(sub1, sub2, label): ndarray(n_freqs,)}, the coherence a cell has to clear at each frequency to beat the null. That is what the phase arrows are drawn against, and it is per frequency because surrogate coherence is not flat in frequency.

seed drives the phase randomisation and nothing else. Passing the same value as the real run is what makes the pair reproducible together.

ch_type runs the null on one chromophore, and has to match the real table it is compared against: a null computed on HbO says nothing about an HbR coupling.

windows is [(label, tstart, tstop)], and turns the second return value into a per-condition null with a condition column. Each window is read off the same whole-run transform the whole-run table is averaged from, by window_result(), so one pass of n_iter transforms produces both tables and the null is windowed exactly the way the real table it is compared against was, down to each condition’s own cone when cond_cone is on (margins as in the real run).

analysis_window is --tstart/--tend, and does the same job for the whole-run row that windows does for the per-condition ones: the real whole-run table describes that stretch, so its null has to as well.

roi_map also fills NullDraws.roi_levels, the level each ROI map’s arrows clear: the per-frequency quantile of the surrogate maps averaged into ROIs with the same roi_min_channels, never an average of the channels’ levels.

device is the card the transforms run on, None for the CPU; the surrogates are drawn on the CPU either way.

shared rotates all of a scrambled member’s channels by one set of random phases per draw (phase_rotate()) instead of scrambling each on its own, so they stay as correlated with each other as recorded. The random stream differs between the two, so one seed does not give comparable draws across them.

nirspipe.pipeline.hyper.surrogate.compute_wtc_pair_null(draws: Iterable[tuple[str, dict[str, mne.io.Raw]]], true_pair: tuple[str, str], axis: list[str], band_fmin: float, band_fmax: float, fmin: float = 0.004, fmax: float = 0.2, cross: bool = False, limit_scales: bool = True, mask_coi: bool = True, ch_type: str = 'hbo', sep_bands=None, windows: list[tuple[str, float, float]] | None = None, analysis_window: tuple[float, float] | None = None, on_draw: Callable[[str, dict], None] | None = None, device=None, cond_cone: bool = False, margins: dict[str, tuple[float, float]] | None = None) → nirspipe.pipeline.hyper.surrogate.NullDraws#

Re-paired band means: WTC of one member against people they never interacted with.

draws yields (partner_id, aligned_raws), one false pair per draw, each already cut onto the clock the real table was computed on. Building them is the caller’s job: it needs the pairs table and the derivatives tree, neither of which this module reads.

The difference from compute_wtc_phase_null() is what the surrogate keeps: a re-paired partner is a real recording of the same task, so each member’s own time-locked response to the task survives. Everything downstream of the transform is the other null’s code, so the two tables subtract from the same real table and from each other.

Both the pair key and the per-frequency histogram are relabelled to true_pair. Each draw carries a different partner, and the summary groups by sub1/sub2, so without this every draw would be its own group of one and the table would report n_iter 1 against a null it never averaged.

axis is the real dyad’s channel axis, passed in rather than recomputed: a partner with a different montage would otherwise move the rows and the null could no longer be subtracted from the real table row by row. A label the partner lacks lands as a blank row, the same shape a rejected channel leaves.

The pool is finite, unlike phase randomisation’s, so the number of draws is a property of the cohort rather than a setting. That is what limits the resolution of percentile.

cond_cone marks each condition’s own cone on the draw as the real table marked it, at the condition’s edges margins places either side of a window.

device is the card the transforms run on, None for the CPU.