nispace.api.NiSpace

class nispace.api.NiSpace(x, y=None, z=None, x_labels=None, y_labels=None, z_labels=None, data_space='MNI152NLin6Asym', standardize='xz', drop_nan=False, parcellation=None, parcellation_labels=None, parcellation_space='MNI152NLin6Asym', parcellation_hemi=['L', 'R'], parcellation_symmetric=False, parcellation_l2rmap=None, parcellation_idc_lh=None, parcellation_idc_rh=None, parcellation_idc_sc=None, parcellation_dist_mat=None, parcellation_spin_mat=None, load_dist_mat=True, load_spin_mat=True, resampling_target='data', n_proc=1, seed=None, verbose=True, dtype=<class 'numpy.float32'>, return_self=True, binary_y=False, **kwargs)[source]

Bases: object

Main analysis object for spatial colocalization / imaging-transcriptomics-style workflows between a set of X (predictor) maps and a set of Y (target) maps, with optional Z covariate maps. Import via from nispace import NiSpace.

Typical usage follows a fixed pipeline of method calls, each acting on and updating the same object:

  1. Construct with x/y/(optional z) and a parcellation, then call fit() to parcellate/validate the data.

  2. Optionally reduce/clean/transform the data: reduce_x(), clean_y(), transform_y(), transform_z().

  3. Compute colocalization statistics between X and Y with colocalize().

  4. Optionally decompose a colocalization result region-by-region with regional_influence() / regional_contribution().

  5. Assess significance via permutation testing with permute(), then correct_p() for multiple comparisons and/or normalize_colocalizations() against the null distribution.

  6. Retrieve results with the get_* methods (get_x, get_y, get_z, get_colocalizations, get_p_values, get_regional_influence, get_regional_contribution, …), visualize with plot() / plot_brain(), and persist the object with to_pickle() / from_pickle() / copy().

Parameters:
  • x (ndarray | DataFrame | Series | List[str | Path | Nifti1Image | GiftiImage] | Dict[str, str | Path | Nifti1Image | GiftiImage]) –

  • y (ndarray | DataFrame | Series | List[str | Path | Nifti1Image | GiftiImage] | Dict[str, str | Path | Nifti1Image | GiftiImage]) –

  • z (Literal['gm', 'wm', 'csf', 'veins', 'arteries'] | ~typing.List[~typing.Literal['gm', 'wm', 'csf', 'veins', 'arteries']] | ~numpy.ndarray | ~pandas.core.frame.DataFrame | ~pandas.core.series.Series | ~typing.List[str | ~pathlib.Path | ~nibabel.nifti1.Nifti1Image | ~nibabel.gifti.gifti.GiftiImage] | ~typing.Dict[str, str | ~pathlib.Path | ~nibabel.nifti1.Nifti1Image | ~nibabel.gifti.gifti.GiftiImage]) –

  • x_labels (Sequence[str]) –

  • y_labels (Sequence[str]) –

  • z_labels (Sequence[str]) –

  • data_space (Literal['MNI152NLin6Asym', 'MNI152NLin2009cAsym', 'fsaverage', 'fsLR']) –

  • standardize (Literal['x', 'y', 'z', 'xy', 'xz', 'yz', 'xyz'] | bool) –

  • drop_nan (bool) –

  • parcellation (str | Path | Nifti1Image | GiftiImage) –

  • parcellation_labels (Sequence[str]) –

  • parcellation_space (Literal['MNI152NLin6Asym', 'MNI152NLin2009cAsym', 'fsaverage', 'fsLR']) –

  • parcellation_hemi (Literal['R', 'L'] | ~typing.Sequence[~typing.Literal['L', 'R']]) –

  • parcellation_symmetric (bool) –

  • parcellation_l2rmap (DataFrame) –

  • parcellation_idc_lh (Sequence[int]) –

  • parcellation_idc_rh (Sequence[int]) –

  • parcellation_idc_sc (Sequence[int]) –

  • parcellation_dist_mat (ndarray | DataFrame) –

  • parcellation_spin_mat (ndarray) –

  • load_dist_mat (bool) –

  • load_spin_mat (bool) –

  • resampling_target (Literal['data', 'parcellation']) –

  • n_proc (int) –

  • seed (int) –

  • verbose (bool) –

  • dtype (type | str) –

  • return_self (bool) –

  • binary_y (bool) –

`NiSpace` has no public instance attributes. All state (data, colocalization
results, null distributions, p-values, parcellation, and internal settings) is
stored on private, underscore-prefixed attributes and is not meant to be
accessed directly use the `get_*` methods instead.
clean_y(how, covariates_within=None, covariates_between=None, protect=None, within_y_specific=False, combat=False, combat_protect=None, combat_keep=None, combat_train=None, combat_model=None, combat_kwargs=None, plot_design_between=False, n_proc=None, replace=True, verbose=None)[source]

Regress covariates out of Y, “within” (across parcels, per map) and/or “between” (across maps/subjects, per parcel), with optional ComBat site harmonization for the between-subject case.

“Within” regression removes a per-parcel confound from each Y map individually – e.g. regressing a grey-matter probability map out of an MRI map so that the result reflects tissue-corrected signal rather than partial-volume effects. “Between” regression removes subject/map-level confounds shared across parcels – e.g. age, sex, or scan site – fit and applied jointly across all parcels via one design matrix. The two are independent and can be combined in one call.

Parameters:
  • how (str or list of str) – Which regression(s) to perform: "within", "between", or both.

  • covariates_within (array-like or "z", optional) – Per-parcel covariate map(s) to regress out of each Y map. Only used if "within" in how; ignored (with no regression performed) if None. The literal string "z"/"Z" regresses the Z data provided at fit() instead of an explicit array (raises if no Z was provided). A single covariate map is broadcast to every Y map unless within_y_specific=True, in which case one covariate map per Y row is expected.

  • covariates_between (array-like, Series, or DataFrame, optional) – Subject/map-level covariate(s) to regress out across parcels. Only used if "between" in how; ignored if None. Categorical columns (object/string/categorical dtype, or a column literally named "site") are one-hot encoded; continuous columns are used as-is.

  • protect (array-like, Series, or DataFrame, optional) – Covariates to hold constant (partial out) while regressing covariates_between, without themselves being removed from Y – typically group/subject design columns that should not be regressed away. Only relevant with "between".

  • within_y_specific (bool, default False) – If True, covariates_within supplies one covariate map per Y row instead of a single map broadcast to all rows.

  • combat (bool, default False) – Apply ComBat harmonization during the between-subject step. Requires a "site" column in covariates_between; otherwise silently disabled with a warning. Requires the optional neuroHarmonize package.

  • combat_protect (array-like, Series, or DataFrame, optional) – Additional covariates ComBat should protect (preserve biological variance for) without using them as regression covariates.

  • combat_keep (optional) – Deprecated and ignored; all regression covariates are now automatically protected during ComBat harmonization.

  • combat_train (array-like of bool, optional) – Boolean vector marking a training subset: if valid, ComBat is fit only on this subset and applied to the rest. Ignored (full-sample fit) if the length doesn’t match or values aren’t boolean-like.

  • combat_model (optional) – A previously fitted ComBat model to apply (rather than refit). If None, a fresh model is fit and stored (together with the covariates used) on the object for later reuse.

  • combat_kwargs (dict, optional) – Additional keyword arguments forwarded to neuroHarmonize’s harmonizationLearn.

  • plot_design_between (bool, default False) – Plot the between-subject design matrix (diagnostic only, no effect on the result).

  • n_proc (int, optional) – Number of parallel processes for the per-parcel/per-subject regression loops. Defaults to the value set at init.

  • replace (bool, default True) – Overwrite self ‘s stored Y with the cleaned result. If False, the cleaned data is computed and returned but the object’s Y is left untouched.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

The cleaned Y data (same shape, columns, and index as the input Y).

Return type:

pandas.DataFrame

colocalize(method=None, X_reduction=None, Y_transform=None, xsea=None, xsea_aggregation_method='mean', regress_z=True, zy_matched=False, X=None, Y=None, Z=None, store=True, n_proc=None, seed=None, verbose=None, dist_mat_kwargs=None, force_dict=False, **kwargs)[source]

Compute colocalization statistics between each X map (or set, if XSEA is active) and each Y map, optionally regressing Z out of X and/or Y first. This is the core computation step of the NiSpace pipeline, feeding permute(), correct_p(), regional_influence(), and regional_contribution().

Parameters:
  • method (str, optional) –

    Colocalization method. Defaults to the last method used in colocalize() (raises if none has ever been set). One of:

    • "pearson" – Pearson correlation

    • "spearman" – Pearson correlation on ranks

    • "partialpearson" – Pearson with Z regressed out

    • "partialspearman" – Spearman with Z regressed out (Z is also ranked, a “standard” partial-Spearman)

    • "mi" – mutual information

    • "slr" – simple linear regression (one X predictor at a time)

    • "mlr" – multiple linear regression (all X maps as joint predictors)

    • "dominance" – dominance analysis (partitions R² across predictors)

    • "pls" – partial least squares regression

    • "pcr" – principal component regression

    • "lasso", "ridge", "elasticnet" – regularized regression with spatial (parcel-fold) cross-validation

  • X_reduction (str, optional) – Label of a previously computed X dimensionality reduction (see reduce_x()) to use instead of the raw X data. Defaults to the last one used (or the raw X data if none has been used).

  • Y_transform (str, optional) – Label of a previously computed Y transform (see transform_y()) to use instead of the raw Y data. Defaults to the last one used (or the raw Y data if none has been used). If this transform has not been computed yet, it is run automatically (using groups/ subjects from **kwargs if given) with a warning.

  • xsea (bool, optional) – Aggregate X maps into sets before colocalizing (X-Set Enrichment Analysis) – requires X to have a "set" MultiIndex level. Defaults to the last value used. Combined with a correlation method ("pearson"/"spearman"), this requires Fisher-z transformed correlations – r_to_z=False in **kwargs is overridden to True with a warning.

  • xsea_aggregation_method (str, default "mean") – How to aggregate per-set colocalization statistics across a set’s members when xsea is active: "mean", "median", "absmean", "absmedian", "weightedmean", or "weightedabsmean" (the weighted variants require a "weight" MultiIndex level on X; fall back to unweighted with a warning if missing).

  • regress_z (bool, default True) – Regress Z out of X and/or Y before colocalizing (requires Z to have been provided at fit(); a no-op otherwise). Forced on for partial* methods. Defaults to the last value used.

  • zy_matched (bool, default False) – Treat Z as having one map per Y row (rather than a single/shared Z used for every Y row) – e.g. per-subject nuisance maps matched to per-subject Y maps. Incompatible with partial* methods (falls back to the corresponding non-partial method with a warning). Defaults to the last value used.

  • X (array-like or DataFrame, optional) – Explicit data overriding the object’s own fitted X/Y/Z (or the resolved X_reduction/Y_transform). Rarely needed.

  • Y (array-like or DataFrame, optional) – Explicit data overriding the object’s own fitted X/Y/Z (or the resolved X_reduction/Y_transform). Rarely needed.

  • Z (array-like or DataFrame, optional) – Explicit data overriding the object’s own fitted X/Y/Z (or the resolved X_reduction/Y_transform). Rarely needed.

  • store (bool, default True) – Store the result on the object (accessible via get_colocalizations()), and remember method, X_reduction, Y_transform, xsea, regress_z, and zy_matched as the “last used” settings for subsequent calls with unset (None) arguments.

  • n_proc (int, optional) – Number of parallel processes (one per Y row). Defaults to the value set at init.

  • seed (int, optional) – Random seed forwarded to the regularized-regression methods’ cross-validation splitting. Not persisted across calls. Defaults to the seed set at init (NiSpace(seed=...)) if not given here.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • dist_mat_kwargs (dict, optional) – Only used for method in {"lasso", "ridge", "elasticnet"}. Recognized keys: parcel_tr_te_splits (pre-computed spatial CV splits), euclidean_dist_mat (pre-computed distance matrix), parcel_train_pct (default 0.75). Remaining keys are forwarded to the internal distance-matrix computation.

  • force_dict (bool, default False) – Always return a dict even when the method produces a single statistic (e.g. "pearson"’s rho).

  • **kwargs

    groups, subjectsoptional

    Forwarded to transform_y() if Y_transform needs to be auto-run (see above); unused otherwise.

    rankbool, optional

    Rank-transform X (and Y) before colocalizing. Forced True for "spearman"/"partialspearman"; otherwise defaults to False. Deliberately not resolved from a prior call’s setting (unlike the parameters above), since inheriting it across a method change would silently mislabel results.

    Other recognized keys are forwarded to the underlying colocalization function: r_to_z (bool, default True – Fisher-z transform correlation coefficients), r_equal_one (default "raise" – behavior when a correlation is exactly 1), adj_r2 (bool, default True – adjusted vs. raw R² for slr/mlr/dominance/pcr), mlr_individual (bool, default False – compute per-predictor unique-R² contributions for "mlr"), n_components (int, default 1 – for "pls"/"pcr"), n_neighbors (for "mi"), and sklearn Lasso/Ridge/ ElasticNet keyword arguments for the regularized methods.

Returns:

X labels (or set names, if xsea) as columns, Y labels as rows. A dict of {stat: DataFrame} is returned when the method produces more than one statistic (e.g. "mlr") or when force_dict=True.

Return type:

pandas.DataFrame or dict of pandas.DataFrame

copy(deep=True, verbose=True)[source]

Duplicate this NiSpace object, e.g. to try an alternative analysis branch without mutating the original.

Parameters:
  • deep (bool, default True) – If True, recursively duplicate everything (all stored X/Y/Z data, colocalizations, nulls, p-values, etc.) so the copy shares no mutable state with the original. If False, only the top-level object is duplicated – its attributes still reference the same underlying dicts/DataFrames as the original, so in-place mutation of e.g. a shared dict would affect both.

  • verbose (bool, default True) – Print progress messages.

Returns:

The duplicated object.

Return type:

NiSpace

correct_p(mc_method='meff', mc_alpha=0.05, mc_dimension='array', coloc_method=None, store=True, verbose=None)[source]

Apply a multiple-comparisons correction to the uncorrected p-values previously computed by permute(), storing the corrected result under its own key (so several mc_method corrections of the same permutation result can coexist and be retrieved separately via get_p_values()/get_corrected_p_values()).

Parameters:
  • mc_method (str, default "meff") –

    Correction method. One of:

    • "meff" / "meff_galwey" (default) – Šidák correction using an effective number of independent tests estimated from the eigenvalues of X’s (and, for mc_dimension="array" with multiple Y rows, also Y’s) correlation matrix. [32]

    • "meff_li_ji" – same Šidák-correction scheme, with an alternative eigenvalue-based effective-N estimator. [33]

    • "maxT" – single-step max-statistic FWER correction from the permutation null computed by permute(); requires the null colocalization distributions to still be available (i.e. not dropped via save_nulls=False). [31]

    • "step_maxT" – step-down variant of "maxT", more powerful while preserving FWER control. [31]

    • "fdr_bh" – Benjamini-Hochberg false discovery rate. [34]

    • "bonferroni", or any other method name accepted by statsmodels.stats.multitest.multipletests (e.g. "holm", "hommel", "sidak", "fdr_by") – passed through as-is.

  • mc_alpha (float, default 0.05) – Alpha threshold used by the correction.

  • mc_dimension (str, default "array") – Axis over which to correct: "array" (jointly across all X x Y comparisons), "x"/"columns" (per X column), or "y"/"rows" (per Y row). Not all combinations are supported by every method – e.g. "maxT"/"step_maxT" don’t support per-column correction, and for the meff methods with multiple Y rows, "array" applies a joint X x Y correction that is only meaningful when the Y rows are related entities examined together (e.g. several disorders’ effect-size maps); use mc_dimension="y" for independent per-Y-row correction (e.g. individual-subject maps).

  • coloc_method (str, optional) – Restrict correction to p-values from one colocalization method (useful when several methods’ results are stored at once). Defaults to correcting all stored uncorrected p-values.

  • store (bool, default True) – Store the corrected p-values on the object, and remember mc_method as the “last used” correction (read by get_corrected_p_values(), plot()).

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

Corrected p-values keyed by their internal storage key string.

Return type:

dict of pandas.DataFrame

correlate_within_region(X=None, Y=None, method='pearson', X_reduction=None, Y_transform=None, n_perm=1000, seed=None, store=True, verbose=None)[source]

Per-parcel, across-subject correlation between X and Y – the transpose of colocalize() (which correlates across parcels, within a subject/map). For each parcel independently: do maps with a higher X value at this parcel also have a higher Y value at this parcel, across the set of X/Y maps (e.g. subjects)?

By default, operates on the object’s stored X/Y (via get_x()/ get_y(), respecting X_reduction/Y_transform). Pass X/ Y directly to override with different data – including a 1D, subject-length vector (e.g. an external covariate like age), which is broadcast against every parcel of the other (2D) side.

If the object’s stored X/Y is used (not overridden) and was constructed with standardize including "x"/"y", a warning is raised: that z-scores each map across its own parcels, which is the right normalization for colocalize()’s across-parcel axis, but distorts the across-subject axis this method actually correlates along (each map/subject would get its own rescaling before the per-parcel comparison).

A binary (two-level, e.g. 0/1) 1D vector is a common special case of this: with method="pearson", the per-parcel rho is exactly the point-biserial correlation, which converts deterministically to the classic pooled-variance (Student’s) two-sample t-statistic via t = rho * sqrt((n-2)/(1-rho**2)) – so it recovers the same per-parcel effect ranking as an independent-samples t-test. The default permutation null (subject/group-label pairing shuffled, group sizes preserved since the labels themselves aren’t resampled) is exactly the classical nonparametric permutation test for two independent samples – valid without the normality/equal-variance assumptions the parametric t-test needs, since it only relies on exchangeability under the true null. Combined with maxT/ step_maxT (see get_within_region_correlations()), this gives a mass-univariate, FWER-controlled group-difference test per parcel – distinct from transform_y()’s hedges(a,b)/colocalize() route, which tests whether the shape of a group-difference map matches other maps, not per-parcel significance of the difference itself. Note that rho’s sign depends on which group is coded higher.

The null distribution is built by permuting map/subject identity (which X row pairs with which Y row) – not a spatial/spin null, since parcels are not the resampled axis here. The same permutation is applied consistently across all parcels within one iteration, which is what makes maxT-style FWER correction (via get_within_region_correlations()) valid.

Parameters:
  • X (array-like, DataFrame, Series, or None) – Override data. 2D input must be shape (n_subjects, n_parcels); 1D input must be length n_subjects (broadcast across parcels). A (n_subjects, 1) 2D input (e.g. a single-column DataFrame) is treated the same as 1D. At least one of the (possibly-defaulted) X/Y must be 2D with more than one column. Defaults (None) to the object’s stored get_x()/get_y() output.

  • Y (array-like, DataFrame, Series, or None) – Override data. 2D input must be shape (n_subjects, n_parcels); 1D input must be length n_subjects (broadcast across parcels). A (n_subjects, 1) 2D input (e.g. a single-column DataFrame) is treated the same as 1D. At least one of the (possibly-defaulted) X/Y must be 2D with more than one column. Defaults (None) to the object’s stored get_x()/get_y() output.

  • method ({"pearson", "spearman"}, default "pearson") –

  • X_reduction (str, optional) – Which stored X reduction to use when X is not given directly (see reduce_x()). Defaults to the last one used, or raw X.

  • Y_transform (str, optional) – Which stored Y transform to use when Y is not given directly (see transform_y()). Defaults to the last one used, or raw Y.

  • n_perm (int, default 1000) – Number of map/subject-identity permutations for the null. 0/None skips the null (rho only, no p-values).

  • seed (int, optional) – Defaults to the seed set at init (NiSpace(seed=...)).

  • store (bool, default True) – Store the result (accessible via get_within_region_correlations()) and remember these settings as “last used”.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

self if self._return_self (default), else the observed per-parcel correlation as a one-row DataFrame.

Return type:

NiSpace or pandas.DataFrame

fit(**kwargs)[source]

“Fit” the NiSpace class instance, i.e., check input and apply parcellation if necessary. Input and parameters are set on initialization.

Parameters:

**kwargs

Any keyword argument accepted by parcellate_data() can be passed here and will override that function’s defaults. The most commonly needed ones are:

background_valuefloat, list, set, array, ‘auto’, False, or dict

Value(s) treated as background, or False to disable background exclusion entirely (background/zero is then real data, e.g. for binary/coverage-style maps – NaN is still always excluded regardless). 'auto' (default) auto-detects a border-voxel/medial-wall value and combines it with exact 0.0. Also accepts a per-role dict, {"x": ..., "y": ..., "z": ...}, to set X/Y/Z independently – any of the above per key; roles absent from the dict fall back to 'auto'. Default: 'auto'

NiSpace(binary_y=True) automatically applies background_value=False to Y only (an all-zero parcel in a binary/fractional cluster-coverage map is a genuine 0%-overlap result, not missing background); this default backs off only if the dict passed here explicitly contains a "y" key – a plain top-level scalar/list meant for X/Z does not affect it.

report_background_parcelsbool

Whether to explicitly flag (and log) all-background parcels. Such parcels are already NaN via empty-mean aggregation regardless of this flag, so it only affects whether they’re recorded/logged, not the returned values. Always a no-op for a role resolved to background_value=False (e.g. Y under binary_y=True). Default: False

min_num_valid_datapointsint, optional

Minimum number of valid (non-background, non-NaN) datapoints required per parcel; parcels below this are set to NaN. Default: None

min_fraction_valid_datapointsfloat, optional

Minimum fraction of valid (non-background, non-NaN) datapoints, relative to the parcel’s total size in the resampled parcellation, required per parcel. Default: None

The deprecated ignore_background_data/drop_background_parcels kwargs are still accepted (forwarded through, with a deprecation warning) but bypass the per-role background_value dict/ binary_y resolution above entirely – use background_value instead.

Returns:

self – Returns the instance itself.

Return type:

object

static from_pickle(filepath, verbose=True)[source]

Load a NiSpace object from a pickle file.

Parameters:
  • filepath (str) – Filepath to load the NiSpace object from.

  • verbose (bool, optional) – Whether to print verbose output. Defaults to True.

Returns:

nispace_object – The loaded NiSpace object.

Return type:

NiSpace

get_colocalizations(method=None, stats=None, X_reduction=None, Y_transform=None, xsea=None, normalized=False, perm=None, get_nulls=False, nulls_permute_what=None, pooled_p=None, force_dict=False, verbose=None, copy=True)[source]

Retrieve a stored colocalize() result (or, with normalized=True, a stored normalize_colocalizations() result – this is what get_normalized_colocalizations() calls under the hood).

Parameters:
  • method (optional) – Identify which stored result to retrieve; see colocalize(). All default to the last-used values.

  • X_reduction (optional) – Identify which stored result to retrieve; see colocalize(). All default to the last-used values.

  • Y_transform (optional) – Identify which stored result to retrieve; see colocalize(). All default to the last-used values.

  • xsea (optional) – Identify which stored result to retrieve; see colocalize(). All default to the last-used values.

  • stats (str or list of str, optional) – Which statistic(s) to retrieve (e.g. "rho", "beta"). Defaults to all stats produced by method (or, if normalized=True, only the subset for which a null distribution exists).

  • normalized (bool, default False) – Retrieve the null-normalized z-scores from normalize_colocalizations() instead of the raw observed statistics. Raises KeyError if that hasn’t been run.

  • perm (str, optional) – Which permutation (“what”) the retrieved normalized result was computed against; see permute(). Only relevant with normalized=True. Defaults to the last-used value.

  • get_nulls (bool, default False) – Also return the null colocalization distributions alongside the observed statistics, as a (colocalizations, nulls) tuple. Requires nulls_permute_what to identify which permutation’s nulls to fetch.

  • nulls_permute_what (str, optional) – Which permutation’s null distributions to fetch when get_nulls=True (e.g. "maps", "groups", "sets", "pairs"; see permute()’s what argument).

  • pooled_p (bool or str, optional) – Pooling mode used for the stored null distribution being retrieved; see permute(). Defaults to the last-used value.

  • force_dict (bool, default False) – Always return a dict even when only one statistic is retrieved.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return independent copies rather than live references to the object’s internal data. Only applies to the non-normalized path; normalized results are always returned as copies.

Returns:

A dict of {stat: DataFrame} if more than one stats entry is retrieved or force_dict=True, otherwise a single DataFrame. If get_nulls=True, a (colocalizations, nulls) tuple is returned instead.

Return type:

pandas.DataFrame or dict of pandas.DataFrame, or a tuple thereof

get_corrected_p_values(mc_method=None, **kwargs)[source]

Shortcut for get_p_values() that defaults mc_method to whichever correction was last used in correct_p(), instead of get_p_values’s own default of retrieving the uncorrected p-values.

Parameters:
  • mc_method (str, optional) – Defaults to the last correction method used in correct_p(). Raises ValueError if correct_p() was never run.

  • **kwargs – Forwarded to get_p_values() (method, permute_what, stats, xsea, pooled_p, X_reduction, Y_transform, force_dict, verbose, copy).

Returns:

See get_p_values().

Return type:

pandas.DataFrame or dict of pandas.DataFrame

get_normalized_colocalizations(**kwargs)[source]

Shortcut for get_colocalizations(normalized=True, ...) – retrieves the null-normalized z-scores produced by normalize_colocalizations().

Parameters:

**kwargs – Forwarded to get_colocalizations() (method, stats, X_reduction, Y_transform, xsea, perm, get_nulls, nulls_permute_what, pooled_p, force_dict, verbose).

Returns:

See get_colocalizations().

Return type:

pandas.DataFrame or dict of pandas.DataFrame

get_p_values(method=None, permute_what=None, stats=None, xsea=None, mc_method=None, pooled_p=None, X_reduction=None, Y_transform=None, force_dict=False, verbose=None, copy=True)[source]

Retrieve p-values computed by permute(), uncorrected by default, or a specific multiple-comparisons-corrected result previously produced by correct_p().

Parameters:
  • method (optional) – Identify which stored colocalization result the p-values belong to; see colocalize(). All default to the last-used values.

  • X_reduction (optional) – Identify which stored colocalization result the p-values belong to; see colocalize(). All default to the last-used values.

  • Y_transform (optional) – Identify which stored colocalization result the p-values belong to; see colocalize(). All default to the last-used values.

  • xsea (optional) – Identify which stored colocalization result the p-values belong to; see colocalize(). All default to the last-used values.

  • permute_what (str, optional) – Which permutation (“what”) the p-values were computed against, see permute()’s what argument. Defaults to the last-used value.

  • stats (str or list of str, optional) – Which statistic(s)’ p-values to retrieve. Defaults to all stats for which a permutation null exists.

  • mc_method (str, optional) – Which correction to retrieve, as passed to correct_p(mc_method=...). Defaults to None, which retrieves the uncorrected p-values (the default, and the input correct_p() itself corrects) – not the last-used correction; for that, use get_corrected_p_values().

  • pooled_p (bool or str, optional) – Pooling mode used for the stored result being retrieved; see permute(). Defaults to the last-used value.

  • force_dict (bool, default False) – Always return a dict even when only one statistic is retrieved.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return independent copies rather than live references to the object’s internal data.

Returns:

A dict of {stat: DataFrame} if more than one statistic is retrieved or force_dict=True, otherwise a single DataFrame.

Return type:

pandas.DataFrame or dict of pandas.DataFrame

Raises:

KeyError – If the requested combination was never computed (e.g. permute() was never run).

get_regional_contribution(method=None, X_reduction=None, Y_transform=None, xsea=None, quadrant=False, pooled=None, verbose=None, copy=True)[source]

Retrieve a stored regional_contribution() result.

Parameters:
  • method (str, optional) – Colocalization method whose stored result to retrieve. Only pearson/spearman/partialpearson/partialspearman are supported (the methods with a bidirectional/signed primary stat); see regional_contribution(). Defaults to the last-used value.

  • X_reduction (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • Y_transform (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • xsea (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • quadrant (bool, default False) – If False (default), return the contribution values (the “whole map”). If True, return the categorical quadrant labels (“high_high”/ “low_low”/”discordant”) instead.

  • pooled ({None, False, True, "mean", "median"}, default None) – Pool (reduce) the per-Y-row result across Y (subjects/maps). None defaults to whatever pooled_p was last set to elsewhere in the pipeline. Only valid when quadrant=False – pooling isn’t meaningful for categorical labels.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return independent copies rather than live references to the object’s internal data. Ignored (always independent) when pooled is truthy, since pooling already builds new DataFrames.

Returns:

Keyed by X map/set label – all supported methods are per-X-pair, so the result is always dict-shaped; see regional_contribution()’s Returns.

Return type:

dict of pandas.DataFrame

Raises:
  • KeyError – If no matching regional_contribution() result was ever computed.

  • ValueError – If quadrant=True and pooled is also truthy (pooling isn’t meaningful for categorical labels).

get_regional_influence(method=None, stat=None, engine=None, signed=False, X_reduction=None, Y_transform=None, xsea=None, pooled=None, force_dict=False, verbose=None, copy=True)[source]

Retrieve a stored regional_influence() result.

Parameters:
  • method (str, optional) – Colocalization method whose stored result to retrieve; see regional_influence() for the list of supported methods. Defaults to the last-used value.

  • stat (str, optional) – Which colocalization stat’s influence result to retrieve. Defaults to the method’s primary stat.

  • engine ({"analytic", "bruteforce"}, optional) – Must match the engine actually used to compute the stored result. Defaults to reproducing what regional_influence(engine="auto") would have picked for method ("analytic" for pearson/spearman/partialpearson/partialspearman/mlr, otherwise "bruteforce").

  • signed (bool, default False) – Must match the signed value passed to the regional_influence() call being retrieved.

  • X_reduction (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • Y_transform (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • xsea (optional) – Must match the colocalize() settings used for the stored result; see colocalize(). Default to the last-used values.

  • pooled ({None, False, True, "mean", "median"}, default None) – Pool (reduce) the per-Y-row result across Y (subjects/maps). None defaults to whatever pooled_p was last set to elsewhere in the pipeline (e.g. by permute()); True is treated as “mean”. Pools the per-subject delta directly (median of deltas, not delta of medians) – the correct choice for this paired quantity.

  • force_dict (bool, default False) – For methods that fit one joint model per Y-row (mlr/dominance/pls/ pcr), wrap the single-DataFrame result in a length-1 dict for a uniform return type; see regional_influence().

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return independent copies rather than live references to the object’s internal data. Ignored (always independent) when pooled is truthy, since pooling already builds new DataFrames.

Returns:

See regional_influence()’s Returns.

Return type:

pandas.DataFrame or dict of pandas.DataFrame

Raises:

KeyError – If no matching regional_influence() result was ever computed.

get_within_region_correlations(method=None, mc_method='step_maxT', X_reduction=None, Y_transform=None, verbose=None)[source]

Retrieve per-parcel, across-subject correlation results from correlate_within_region(), optionally multiple-comparison corrected across parcels. See get_within_region_correlations_omnibus() for a single global test across all parcels instead of one p-value per parcel.

Parameters:
  • method ({"pearson", "spearman"}, optional) – Defaults to the last one used.

  • mc_method ({"fdr_bh", "bonferroni", "holm", "maxT", "step_maxT"}, optional) –

    Multiple-comparison correction across parcels. Defaults to "step_maxT" – the recommended, proven-calibrated choice (see below and bench5-1_region_correlation_fpr.ipynb); pass None explicitly to get uncorrected results only ("p_corr" then stays None). Requires correlate_within_region() to have been run with n_perm > 0 – raises KeyError otherwise, including under this default, since silently falling back to uncorrected results would hide that no null was ever computed. Unlike correct_p() (which is specific to colocalize() results), this dispatches directly to the underlying nispace.stats.misc primitives.

    "maxT"/"step_maxT" ([31]) control the family-wise error rate using the same subject-permutation null already generated by correlate_within_region() (requires n_perm > 0 there): for each permutation, the maximum |rho| across all parcels is taken, giving one “how extreme can the single most extreme parcel get under H0” draw per permutation. A parcel’s corrected p-value is the fraction of these per-permutation maxima that meet or exceed its own observed |rho|. Because the max is taken jointly across parcels within each permutation, whatever correlation exists between parcels’ test statistics (e.g. from spatial autocorrelation in X/Y) is preserved automatically – no independence assumption is made, unlike "bonferroni"/ "fdr_bh". "step_maxT" refines this by excluding already-more-extreme parcels from the max at each step, which can reject more parcels than plain "maxT" when several true effects are present – but the two are mathematically identical on whether any parcel is rejected (both reduce to the same top-ranked-parcel computation).

    "meff" (Sidak correction via an effective-number-of- independent-tests estimate) is not supported here: it needs a parcel-parcel correlation matrix estimated from only n_subjects observations, typically far fewer than n_parcels for this method, which badly underestimates true dimensionality and is anti-conservative (see bench5-1_region_correlation_fpr.ipynb). Use "maxT"/ "step_maxT" instead.

  • X_reduction (str, optional) – Which stored X/Y to have used. Defaults to the last one used.

  • Y_transform (str, optional) – Which stored X/Y to have used. Defaults to the last one used.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

{"stat_type": "rho", "mc_method": mc_method, "stat": DataFrame, "p": DataFrame or None, "p_corr": DataFrame or None}. "p" is None if correlate_within_region() was run with n_perm=0; "p_corr" is None unless mc_method is given.

Return type:

dict

get_within_region_correlations_omnibus(omnibus_stat='absrho', method=None, X_reduction=None, Y_transform=None, verbose=None)[source]

Single global test from correlate_within_region(): “are region values more correlated between X and Y, on average across all parcels, than expected by chance?” – one p-value for the whole analysis, as opposed to get_within_region_correlations()’s one p-value per parcel.

Reuses the same subject-permutation null already generated by correlate_within_region() (requires n_perm > 0 there): omnibus_stat aggregates the per-parcel rho into one number, and the same aggregation is applied to each permutation’s per-parcel null to build a null distribution of that one number, against which the observed aggregate is compared (same floor-clipped empirical p-value convention as get_within_region_correlations()’s raw p).

Parameters:
  • omnibus_stat ({"rho", "absrho", "rho2"}, default "absrho") –

    How to aggregate the per-parcel rho values into one number.

    • "rho" – signed mean. Most powerful if you expect a consistent-direction relationship across parcels (mirrors paired_colocalization()’s pooled_p="mean"), but a sign-heterogeneous true effect (positive in some regions, negative in others) can cancel out and hide it.

    • "absrho" (default) – mean absolute value. Robust to sign-heterogeneity; matches the |rho| convention already used by "maxT"/"step_maxT" in get_within_region_correlations().

    • "rho2" – mean squared value (“average variance explained”). More powerful than "absrho" when the true effect is concentrated in a few strongly-correlated parcels rather than spread thinly across most of them, at the cost of being more sensitive to a single outlier parcel.

  • method ({"pearson", "spearman"}, optional) – Defaults to the last one used.

  • X_reduction (str, optional) – Which stored X/Y to have used. Defaults to the last one used.

  • Y_transform (str, optional) – Which stored X/Y to have used. Defaults to the last one used.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

{"stat_type": omnibus_stat, "stat": float, "p": float}.

Return type:

dict

Raises:

KeyError – If the requested combination was never computed, or was computed with n_perm=0 (no null to test the omnibus statistic against).

get_x(X_reduction=None, maps=None, squeeze=False, verbose=None, copy=True)[source]

Retrieve the object’s X data: either the raw, fitted X, or a previously computed dimensionality reduction (see reduce_x()).

Parameters:
  • X_reduction (str, optional) – Label of the reduction to retrieve (as passed to reduce_x(reduction=...)). Defaults to the last one used, or the raw X data if none has been used. Raises KeyError (listing available labels) if the requested reduction was never computed.

  • maps (str or list of str, optional) – Restrict to matching X map/set labels (exact or substring match).

  • squeeze (bool, default False) – If exactly one map remains after any maps filtering, return it as a pandas.Series instead of a single-row DataFrame.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return an independent copy rather than a live reference to the object’s internal data.

Return type:

pandas.DataFrame or pandas.Series

get_y(Y_transform=None, maps=None, squeeze=False, verbose=None, copy=True)[source]

Retrieve the object’s Y data: either the raw, fitted Y, or a previously computed transform (see transform_y()).

Parameters:
  • Y_transform (str, optional) – Label of the transform to retrieve (the formula string passed to transform_y(transform=...)). Defaults to the last one used, or the raw Y data if none has been used. Raises KeyError (listing available labels) if the requested transform was never computed.

  • maps (str or list of str, optional) – Restrict to matching Y map labels (exact or substring match).

  • squeeze (bool, default False) – If exactly one map remains after any maps filtering, return it as a pandas.Series instead of a single-row DataFrame.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return an independent copy rather than a live reference to the object’s internal data.

Return type:

pandas.DataFrame or pandas.Series

get_z(verbose=None, copy=True)[source]

Retrieve the object’s Z (covariate) data, as originally provided at fit() (or as last overwritten in place by transform_z(), if used). Unlike get_x()/get_y(), there is no per-transform lookup for Z – only the current Z is available.

Parameters:
  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • copy (bool, default True) – Return an independent copy rather than a live reference to the object’s internal data.

Return type:

pandas.DataFrame

Raises:

ValueError – If no Z data was ever provided.

normalize_colocalizations(coloc_method=None, z_method='robust', store=True, verbose=None)[source]

Z-score observed colocalization statistics against their null permutation distribution (per X column), producing values that are more comparable across colocalization methods/maps with different natural scales. This is distinct from any z-scoring of the raw input data (standardize= at init) – it normalizes colocalization output against the null computed by permute(), which must have been run first.

Parameters:
  • coloc_method (str, optional) – Restrict normalization to one colocalization method’s stored null results. Defaults to normalizing all of them.

  • z_method ({"robust", "standard"}, default "robust") – "robust" uses a median/MAD-based z-score (columns with zero MAD become NaN); anything else uses a standard mean/SD-based z-score. Remembered as the “last used” z_method for later calls (e.g. plot()).

  • store (bool, default True) – Store the normalized values on the object (accessible via get_normalized_colocalizations()).

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

Returns self (for chaining), regardless of store.

Return type:

NiSpace

permute(what, method=None, X_reduction=None, Y_transform=None, xsea=None, n_perm=10000, maps_which='X', maps_nulls=None, maps_method=None, dist_mat=None, sets_X_background=None, p_tails=None, pooled_p='auto', p_from_average_y_coloc=None, n_proc=None, seed=None, store=True, verbose=None, force_dict=False, **kwargs)[source]

Estimate exact non-parametric p-values via permutation testing.

Parameters:
  • what (str or list of str) – What to permute. One or more of: "maps" — spatially constrained null maps for X and/or Y brain maps; "groups" — Y group labels (requires Y_transform); [2] "sets" — X set membership labels (requires XSEA); "pairs" — within-pair colocalization against a between-pair null (SPICE test; requires N matched maps in both X and Y). [35] Pairs can be subjects, studies, tracer targets, or any unit for which one map exists in each modality. Allowed combinations for multi-element lists: ["maps", "groups"], ["maps", "sets"], ["groups", "sets"]. Three-way simultaneous permutation is not supported and falls back to ["groups", "sets"]. "pairs" cannot be combined with other modes.

  • method (str, optional) – Colocalization method. Defaults to the method used in the last colocalize() call.

  • X_reduction (str, optional) – X dimensionality-reduction label. Defaults to last used.

  • Y_transform (str, optional) – Y transformation label. Defaults to last used.

  • xsea (bool, optional) – Whether to run in XSEA mode. Defaults to last used.

  • n_perm (int, optional) – Number of permutations. Default is 10000.

  • maps_which (str or list of str, optional) – Which data to generate null maps for: "X", "Y", or ["X", "Y"]. Default is "X".

  • maps_nulls (dict, optional) – Pre-computed null maps as {map_name: array(n_perm, n_parcels)}. Bypasses null map generation entirely when provided and valid.

  • maps_method (str, optional) – Null map generation method. Auto-selected from the parcellation when not set (default: "moran" for all parcellation types). Options: "moran" / "msr", "variomoran" / "variomsr", "cornblath" / "spin" (surface only), "alexander_bloch", "burt2018", "burt2020", "random".

  • dist_mat (array-like of shape (n_parcels, n_parcels), optional) – Pre-computed geodesic distance matrix. Generated from the parcellation if not provided (and required by the null method).

  • sets_X_background (array-like of shape (n_maps, n_parcels), optional) – Background X map pool for set permutation. If not provided, the unique observed X maps are used as the background.

  • p_tails (str or dict, optional) – P-value tail(s). "two", "upper", or "lower". Can be a dict keyed by statistic name (e.g. {"rho": "two"}). Defaults to method-appropriate tails.

  • pooled_p (str or bool, optional) – How to aggregate across Y maps before computing p-values: "mean" or "median" (average first, one p-value per X map), False (one p-value per Y×X pair), "auto" (default) — False for single-Y, "mean" otherwise. For what="groups", pooled_p is not a free choice — it always answers a group-level question and is forced to "mean" regardless of what is passed (with a warning if the requested value conflicts), including when "auto" would otherwise resolve to False. For what="pairs", within-pair coupling is always aggregated across pairs; "mean" and "median" are both valid and control the aggregation function; False falls back to "mean".

  • p_from_average_y_coloc (str or bool, optional) – Deprecated. Use pooled_p instead.

  • n_proc (int, optional) – Number of parallel processes. Defaults to the value set at init.

  • seed (int, optional) – Random seed for reproducibility. Defaults to the seed set at init (NiSpace(seed=...)) if not given here.

  • store (bool, optional) – Store p-values and z-scores in the object. Default is True.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

  • force_dict (bool, optional) – Always return a dict even when the result has a single statistic.

  • maps_centroids (bool) – maps_* kwargs → null map generation (generate_null_maps()). Use parcel centroids for geodesic distance matrix. Default False.

  • maps_parc_resample (int) – Voxel size (mm) to resample parcellation before distance-matrix computation. Default 2.

  • maps_lr_mirror_dist_mat (bool) – Mirror left-hemisphere distance matrix to the right. Default False.

  • maps_split_hemi (bool or None) – Generate null maps separately per hemisphere. Default None.

  • maps_split_cxsc (bool) – Generate null maps separately for cortex and subcortex. Default False.

  • maps_cx_sc_minmax_scale (bool) – Min–max scale cortex and subcortex null maps before merging. Default False.

  • maps_procedure (str) – Moran randomisation procedure: "singleton" (default) or "all".

  • maps_joint (bool) – Moran joint randomisation. Default True.

  • distmat_centroids (bool) – distmat_* kwargs → distance-matrix generation (_get_dist_mat). Use centroids for CV distance matrix. Default False.

  • distmat_parc_resample (int) – Resampling voxel size for CV distance matrix. Default 2.

  • groups_paired (bool or "auto") – groups_* kwargs → group-label permutation (permute_groups()). Paired permutation (requires subjects vector). "auto" infers pairing from the Y transform. Default "auto".

  • groups_strategy (str) – Permutation strategy: "shuffle" (default), "proportional", or "draw". Remaining kwargs (no prefix) are forwarded to colocalize().

Returns:

p_values – P-values indexed by Y labels × X labels. A dict is returned when the colocalization method produces multiple statistics or when force_dict=True.

Return type:

DataFrame or dict of DataFrames

plot(kind='categorical', method=None, stats=None, X_reduction=None, Y_transform=None, xsea=None, Y_labels=None, X_labels=None, Y_maps=None, X_maps=None, values='coloc', mc_method=None, plot_nulls=True, annot_p=True, permute_what=None, title='auto', sort_by=None, sort_colocs=False, n_categories=50, colocalizations_dict=None, nulls_dict=None, p_dict=None, pc_dict=None, fig=None, ax=None, figsize=None, show=True, plot_kwargs=None, nullplot_kwargs=None, verbose=None)[source]

Plot a stored colocalization result as a categorical (per-X-map) plot, one figure per requested statistic, optionally overlaid with the null permutation distribution and significance annotation.

Only kind="categorical" is currently implemented – "correlation", "brain", and "nullhist" are planned but not yet built (passing them raises NotImplementedError). For brain-map visualization, use the separate plot_brain() method instead.

Parameters:
  • kind (str, default "categorical") – Only "categorical" is currently supported.

  • method (optional) – Identify which stored colocalize() result to plot; see colocalize(). Default to the last-used values. Ignored if colocalizations_dict is given directly.

  • X_reduction (optional) – Identify which stored colocalize() result to plot; see colocalize(). Default to the last-used values. Ignored if colocalizations_dict is given directly.

  • Y_transform (optional) – Identify which stored colocalize() result to plot; see colocalize(). Default to the last-used values. Ignored if colocalizations_dict is given directly.

  • xsea (optional) – Identify which stored colocalize() result to plot; see colocalize(). Default to the last-used values. Ignored if colocalizations_dict is given directly.

  • stats (str or list of str, optional) – Which statistic(s) to plot, one figure each. Defaults to all stats found for method.

  • Y_maps (str or list of str, optional) – Restrict the plot to matching Y/X map labels (exact or substring match). Y_labels/X_labels are accepted as legacy aliases (used only if the corresponding _maps argument is not given).

  • X_maps (str or list of str, optional) – Restrict the plot to matching Y/X map labels (exact or substring match). Y_labels/X_labels are accepted as legacy aliases (used only if the corresponding _maps argument is not given).

  • values ({"coloc", "z", "p"}, default "coloc") – What to plot: the raw observed statistic (via get_colocalizations()), the null-normalized z-score (via get_normalized_colocalizations(), requires normalize_colocalizations() to have been run), or -log10(p) (via get_p_values(); disables plot_nulls unconditionally, since null distributions aren’t meaningful in p-value space).

  • mc_method (str, optional) – Which p-value correction to use for annotation/values="p". Special values "uncorrected"/"none"/"false" force uncorrected p-values. Defaults to the last correction used in correct_p().

  • plot_nulls (bool, default True) – Overlay the null permutation distribution. Requires permute_what to be resolvable (i.e. permute() to have been run); otherwise disabled with a warning. Always disabled when values="p".

  • annot_p (bool or str, default True) – Annotate significance. Also accepts a mode string forwarded to plotting.print_significance (e.g. "text"). Disabled (with a warning) under the same condition as plot_nulls.

  • permute_what (str, optional) – Which permutation (“what”) to pull null distributions/p-values from; see permute()’s what argument. Defaults to the last-used value. The special value "pairs" collapses an N x N colocalization matrix to its diagonal (matched-pair SPICE-style results) before plotting.

  • title (str, default "auto") – Plot title. "auto" builds one from the method/context (recomputed for each statistic when multiple stats are plotted in one call). A custom string is used verbatim for every statistic’s plot.

  • sort_by ({None, "coloc", "abs_coloc", "z", "abs_z", "p"}, optional) – Sort X categories by the mean (or abs mean) observed value, z-score, or p-value across Y rows. Also enables truncation (see n_categories) when set.

  • sort_colocs (bool, default False) – Deprecated; use sort_by="coloc" instead.

  • n_categories (int, optional, default 50) – Maximum number of X categories to display. If exceeded and sort_by is set, truncates to the top N; if exceeded and sort_by is None, that statistic’s plot is skipped entirely (with a warning) rather than truncating arbitrarily. None disables the limit.

  • colocalizations_dict (dict, optional) – Pre-computed {stat: DataFrame} result (as from get_colocalizations(force_dict=True)) to plot directly, bypassing all internal fetching.

  • nulls_dict (optional) – Pre-computed null-distribution / uncorrected-p / corrected-p data, bypassing the corresponding internal fetch.

  • p_dict (optional) – Pre-computed null-distribution / uncorrected-p / corrected-p data, bypassing the corresponding internal fetch.

  • pc_dict (optional) – Pre-computed null-distribution / uncorrected-p / corrected-p data, bypassing the corresponding internal fetch.

  • fig (optional) – Existing matplotlib Figure/Axes to draw into (for building custom multi-panel figures). Pass both together.

  • ax (optional) – Existing matplotlib Figure/Axes to draw into (for building custom multi-panel figures). Pass both together.

  • figsize (tuple, optional) – Figure size; auto-sized by number of X categories if not given.

  • show (bool, default True) – Call plt.show() after each statistic’s plot.

  • plot_kwargs (dict, optional) – Extra keyword arguments forwarded to nispace.plotting.catplot() and nispace.plotting.nullplot() respectively.

  • nullplot_kwargs (dict, optional) – Extra keyword arguments forwarded to nispace.plotting.catplot() and nispace.plotting.nullplot() respectively.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

(fig, ax, plot) per statistic; a single tuple if only one statistic was plotted, otherwise a dict keyed by stat name.

Return type:

tuple or dict of tuple

plot_brain(data='Y', maps=None, Y_transform=None, X_reduction=None, kind=None, space=None, surf_mesh='inflated', views=None, cmap=None, vmin=None, vmax=None, shared_colorscale=False, symmetric_cmap='auto', colorbar=True, colorbar_label='', ncols=1, title='auto', n_max=5, figsize=None, show=True, verbose=None, **kwargs)[source]

Plot brain maps directly onto surfaces or anatomical volumes.

Parameters:
  • data ({"Y", "X"} or pd.DataFrame) – Which data to plot. “Y” (default) uses the fitted Y maps, “X” the reference maps. A DataFrame can be passed directly.

  • maps (str or list, optional) – Subset of maps to plot. Matches against the DataFrame index (including MultiIndex levels and tuple entries).

  • Y_transform (str, optional) – Y transform to apply when data=”Y”. Defaults to the last used transform.

  • X_reduction (str, optional) – X reduction to apply when data=”X”. Defaults to the last used reduction.

  • kind (str, optional) – Rendering mode: “glass”, “slice”, or “surface”. Defaults to “glass”.

  • space (str, optional) – Parcellation space.

  • surf_mesh (str) – Surface mesh (“inflated”, “pial”, etc.).

  • views (list, optional) – Surface views to render.

  • cmap (str) – Colormap.

  • vmin (float, optional) – Colorscale limits.

  • vmax (float, optional) – Colorscale limits.

  • shared_colorscale (bool) – Share colorscale across all maps.

  • symmetric_cmap (bool) – Force symmetric colorscale around zero.

  • colorbar (bool) – Show colorbar.

  • colorbar_label (str) – Label for the colorbar title.

  • ncols (int) – Number of columns in the subplot grid.

  • n_max (int) – Maximum number of maps to plot. Raises an error if exceeded.

  • figsize (tuple, optional) – Figure size in inches.

  • show (bool) – Call plt.show() after plotting.

  • verbose (bool, optional) – Verbose logging. Defaults to the instance setting.

  • **kwargs – Additional keyword arguments forwarded to brainplot() and from there to the underlying nilearn plotting functions.

Returns:

  • fig (matplotlib.Figure)

  • axes (list of matplotlib.Axes)

reduce_x(reduction, mean_by_set=False, weighted_mean=False, n_components=None, min_ev=None, fa_method='minres', fa_rotation='promax', seed=None, store=True, verbose=None)[source]

Reduce the X data to a smaller number of maps/components before colocalization – either by aggregating (mean/median, optionally per "set") or by a proper dimensionality reduction (PCA/ICA/FA). The result is stored under reduction and picked up by get_x()/colocalize()/etc. via their X_reduction argument.

Parameters:
  • reduction (str) –

    One of:

    • "mean" / "median" – parcel-wise mean/median across X maps (optionally per "set", see mean_by_set).

    • "pca" – principal component analysis (sklearn.PCA).

    • "ica" – independent component analysis (sklearn.FastICA); has no explained-variance concept, so min_ev has no effect.

    • "fa" – factor analysis (requires the optional factor_analyzer package).

    Any other value logs an error and returns None rather than raising.

  • mean_by_set (bool, default False) – For "mean"/"median", group X maps by their "set" MultiIndex level before aggregating (silently disabled if X has no "set" level).

  • weighted_mean (bool, default False) – For "mean"/"median", weight maps by a "weight" MultiIndex level on X (silently disabled if absent).

  • n_components (int, optional) – Number of components to keep for "pca"/"ica"/"fa". Ignored if not applicable. Defaults to the maximum possible (one component per parcel) if neither this nor min_ev is given.

  • min_ev (float, optional) – Minimum cumulative explained-variance (EV) fraction; if given, overrides n_components for "pca"/"fa" by picking the smallest sufficient number of components/factors, which’s cumulative EV exceeds min_ev. Ignored if not applicable.

  • fa_method (str, default "minres") – Factor-extraction method, forwarded to factor_analyzer.FactorAnalyzer. Only used for "fa".

  • fa_rotation (str, default "promax") – Rotation method, forwarded to factor_analyzer.FactorAnalyzer. Only used for "fa".

  • seed (int, optional) – Random seed. Only used by "ica". Defaults to the seed set at init (NiSpace(seed=...)) if not given here.

  • store (bool, default True) – Store the reduced X (accessible via get_x(X_reduction=reduction)) and, for "pca"/"ica"/"fa", its per-component metadata (explained variance, loadings), and remember reduction as the “last used” X reduction for subsequent calls.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

For "mean"/"median": the reduced X DataFrame. For "pca"/"ica"/"fa": a tuple (X_reduced, ev, loadings), where ev is the per-component explained variance (None for "ica") and loadings is a DataFrame of each original parcel/map’s association with each retained component.

Return type:

pandas.DataFrame or tuple

regional_contribution(method=None, X_reduction=None, Y_transform=None, xsea=None, regress_z=True, zy_matched=False, X=None, Y=None, Z=None, store=True, n_proc=None, verbose=None)[source]

Decompose a colocalization result into each region’s own additive share of the reported correlation: contribution_i = zx_i * zy_i (population z-scores of whatever data is already in the pipeline at this point – raw values for pearson, ranks for spearman/partial*, matching colocalize()’s own convention). This is an exact decomposition, not an approximation or a perturbation – mean(contribution) == rho exactly. Requires colocalize() to have been run first with the same method (reuses its stored settings).

Also computes a quadrant label per region – “high_high”, “low_low”, or “discordant” (sign of zx vs zy) – retrievable via get_regional_contribution(quadrant=True). This exists because regional_influence() (leave-one-out) is structurally symmetric between high-high and low-low concordant regions – both reinforce a positive correlation identically, since that symmetry is inherent to what Pearson/ Spearman measure, not fixable within the LOO framework. contribution alone has the same symmetry (both quadrants give a positive value); quadrant is what actually distinguishes them. Default accessor behavior is contribution only (the “whole map”, no quadrant) – quadrant is an explicit opt-in via get_regional_contribution(quadrant=True).

This is a standard decomposition of the spatial correlation between two maps, similar to what was presented in Faskowitz et al. (2026) [36] at OHBM 2026.

Parameters:
  • method (str, optional) – Colocalization method. Defaults to the last method used in colocalize(). Supported: pearson, spearman, partialpearson, partialspearman – the 4 methods with a genuinely bidirectional (signed) primary stat. Not supported for R^2/MI-based methods (mlr, dominance, pls, pcr, mi, slr), which have no “high/low” side to decompose into quadrants.

  • X_reduction (see colocalize().) –

  • Y_transform (see colocalize().) –

  • xsea (see colocalize().) –

  • regress_z (see colocalize(). Must match the colocalize() call) – being explained so the same X/Y data (after ranking/Z-regression) is reproduced.

  • zy_matched (see colocalize(). Must match the colocalize() call) – being explained so the same X/Y data (after ranking/Z-regression) is reproduced.

  • store (bool, default True) – Store the result on the object (accessible via get_regional_contribution()).

Returns:

Keyed by X-map/set label (always dict-shaped – all 4 supported methods are per-X-pair methods). Returns the contribution dict specifically (not quadrant); use get_regional_contribution(quadrant=True) for the labels.

Return type:

dict of pandas.DataFrame

regional_influence(method=None, stat=None, engine='auto', signed=False, X_reduction=None, Y_transform=None, xsea=None, regress_z=True, zy_matched=False, X=None, Y=None, Z=None, store=True, n_proc=None, verbose=None, force_dict=False)[source]

Estimate, per region, the true leave-one-out sensitivity of a colocalization result: |stat_full| - |stat_loo| for the region excluded (or the signed stat_full - stat_loo if signed=True), not an approximation (either computed exactly via closed-form case-deletion identities – engine=”analytic” – or by literally rerunning colocalize() with the region excluded – engine=”bruteforce”). Requires colocalize() to have been run first with the same method (reuses its stored settings/closure).

Reports a stat_full/stat_loo delta per region rather than Cook’s distance/ DFFITS/leverage: those answer a classical outlier-flagging question; this answers “how much does the reported effect change without this region”, which is what’s needed here. Developed and first applied in [5].

The default (signed=False) takes the absolute value of the full-data and LOO stat before differencing. This is a no-op for mlr/dominance/pls/pcr/mi/slr (their stat – R^2 or MI – is already >= 0, no direction to speak of), but for the correlation methods (pearson/spearman/partialpearson/partialspearman) it makes the default homogeneous with the other methods: every method’s default answers “does this region strengthen or weaken the association” without regard to direction. signed=True recovers the original directional delta for the correlation methods – positive means the region pulls the correlation toward +1, negative toward -1, regardless of the sign of the observed correlation itself (a region can oppose the overall trend and still pull toward +1).

Parameters:
  • method (str, optional) – Colocalization method. Defaults to the last method used in colocalize(). Supported: pearson, spearman, partialpearson, partialspearman, mi, slr, mlr, dominance, pls, pcr. Not supported: lasso, ridge, elasticnet (their colocalization closures capture a fixed-size CV split/regularization mask sized to the original number of regions, which would misalign against region-excluded data).

  • stat (str, optional) – Which colocalization stat to compute influence for. Defaults to the method’s primary stat.

  • engine ({"auto", "analytic", "bruteforce"}, default "auto") – “analytic” is only available for pearson/spearman/partialpearson/ partialspearman/mlr; “auto” picks it for those and falls back to “bruteforce” otherwise. “bruteforce” reruns colocalize() once per excluded region and can be slow for many regions – a warning is logged above 1000.

  • signed (bool, default False) – See above. Only changes behavior for pearson/spearman/partialpearson/ partialspearman – a no-op for every other supported method.

  • X_reduction (see colocalize().) –

  • Y_transform (see colocalize().) –

  • xsea (see colocalize().) –

  • regress_z (see colocalize(). Must match the colocalize() call being) – explained so the same X/Y data (after ranking/Z-regression) is reproduced.

  • zy_matched (see colocalize(). Must match the colocalize() call being) – explained so the same X/Y data (after ranking/Z-regression) is reproduced.

  • store (bool, default True) – Store the result on the object (accessible via get_regional_influence()).

  • force_dict (bool, default False) – For methods that fit one joint model per Y-row (mlr/dominance/pls/pcr), the result is a single DataFrame (n_Y x n_regions); force_dict wraps it in a length-1 dict for a uniform return type. For per-predictor/per-set methods (pearson/spearman/partialpearson/partialspearman/mi/slr, or any XSEA call), the result is always a dict of DataFrames keyed by X map / set label, since each X-Y pair (or set) has its own region-influence profile.

Return type:

pandas.DataFrame or dict of pandas.DataFrame

to_pickle(filepath, save_nulls=True, verbose=None)[source]

Save the NiSpace object to a pickle file.

Parameters:
  • filepath (str) – Filepath to save the NiSpace object to.

  • save_nulls (bool, optional) – Whether to save the null distributions. Defaults to True. If False, null colocalizations are dropped, which substantially reduces file size but prevents running correct_p(‘maxT’), correct_p(‘step_maxT’), or normalize_colocalizations() after reloading. Call those methods before saving if you intend to drop nulls.

  • verbose (bool, optional) –

transform_y(transform, groups=None, subjects=None, Y=None, Y_name='Y', store=True, verbose=None)[source]

Apply a group-comparison or aggregation formula to Y, turning per-subject or per-group raw maps into a single comparison/summary map (e.g. an effect size, a z-score, or a group mean) that colocalize() can then use in place of the raw Y data.

Parameters:
  • transform (str) –

    Formula string, e.g. "hedges(a,b)", "zscore(a,b)", "mean(y)". Supported formulas (y = the whole input; a/ b = the two groups defined by groups, smaller/ alphabetically-first value -> a):

    • y – identity (no-op passthrough)

    • mean(y), median(y), std(y), var(y) – summary statistic across rows, per parcel

    • elemdiff(a,b) / a-b – elementwise a - b (paired, requires subjects)

    • meandiff(a,b) / mean(a)-mean(b) – difference of means

    • center(a,b) / a-mean(b)a centered on b’s mean

    • cohen(a,b) – Cohen’s d, independent groups

    • pairedcohen(a,b) – Cohen’s d, paired/dependent groups (requires subjects)

    • hedges(a,b) – Hedges’ g (bias-corrected Cohen’s d)

    • zscore(a) / zscore(a,b) – z-score of a against itself or against reference group b

    • rzscore(a) / rzscore(a,b) – robust (median/MAD) z-score; warns if the reference group has few observations (n<20/n<30)

    • prc(a,b) – percent change (a-b)/a*100 (paired, requires subjects)

    • logfc(a,b) – log fold-change (auto-shifted to stay defined for data that can be negative, e.g. already z-scored/residualized)

    • centile(a) / centile(a,b) – percentile rank of a within the reference distribution

    Note: "pairedhedges(a,b)" (paired/bias-corrected analogue of "hedges(a,b)") is not implemented – calling it raises ValueError.

  • groups (array-like, optional) – 2-level grouping vector, one entry per Y row. Required by any formula referencing a/b; not needed for y-only formulas (e.g. "mean(y)"). Rows with NaN group labels are dropped with a warning.

  • subjects (array-like, optional) – Subject/pair identifiers, one per Y row, used to match rows across groups a/b for paired formulas (elemdiff, pairedcohen, prc). Each ID must appear exactly once per group. If omitted for a paired formula, matched row order within each group is assumed (with a warning).

  • Y (DataFrame, optional) – Data to transform. Defaults to the object’s own Y data (self._Y); passing an explicit DataFrame lets this method operate on other data (this is how transform_z() reuses it for Z).

  • Y_name (str, default "Y") – Cosmetic label used in log messages only (e.g. "Z" when called from transform_z()); has no effect on the computation.

  • store (bool, default True) – Store the transformed data and the resolved groups/subjects on the object (so that colocalize(), get_y(), and permute() can later default to this transform), and remember it as the “last” Y transform for future Y_transform=None calls.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

The transformed data: one row per aggregate statistic for aggregate formulas (e.g. hedges, cohen), or one row per subject/map for row-preserving formulas (e.g. zscore, centile).

Return type:

pandas.DataFrame

transform_z(transform='Y', groups='Y', subjects='Y', replace=True, verbose=None)[source]

Apply a transform_y()-style formula to the object’s Z data instead of Y. A thin wrapper: internally calls transform_y(transform, Y=self._Z, Y_name="Z", store=False), so the transform is never remembered as the “last” Y transform and no per-transform history is kept for Z – replace=True (the default) simply overwrites self’s Z with the result.

Parameters:
  • transform (str, default "Y") – Formula string, see transform_y() for the full list. Unlike groups/subjects below, "Y" here is not a sentinel for “reuse the last Y transform” – it is parsed as a literal formula, which normalizes (case-insensitively) to the identity formula, i.e. the default is “no transformation”, not “whatever transform_y() last used”.

  • groups (array-like or "Y", default "Y") – Grouping vector for the formula (see transform_y()). The literal string "Y" (case-insensitive) is a real sentinel here: it reuses whichever groups vector was set by the last transform_y() call (or None if none was set). Any other value is passed through unchanged.

  • subjects (array-like or "Y", default "Y") – Subject/pair identifiers for the formula (see transform_y()). Same "Y"-sentinel mechanism as groups, reusing the last transform_y() call’s subjects.

  • replace (bool, default True) – Overwrite self ‘s stored Z with the transformed result. If False, the transformed data is computed and returned but the object’s Z is left untouched.

  • verbose (bool, optional) – Print progress messages. Defaults to the value set at init.

Returns:

The transformed Z data – see transform_y()’s Returns for the row-shape convention (aggregate vs. row-preserving formulas).

Return type:

pandas.DataFrame