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, verbose=True, dtype=<class 'numpy.float32'>, return_self=True, **kwargs)[source]
Bases:
objectThe NiSpace class. To be imported via from nispace import NiSpace. Docs under construction.
- 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) –
verbose (bool) –
dtype (type | str) –
return_self (bool) –
- 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]
- 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]
- correct_p(mc_method='meff', mc_alpha=0.05, mc_dimension='array', coloc_method=None, store=True, verbose=None)[source]
- 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 three most commonly needed ones are:- ignore_background_databool
Whether to exclude background voxels from parcel-mean computation. Default: True
- background_valuefloat, list, set, array, or ‘auto’
Value(s) treated as background. Scalar,
'auto'(border-voxel auto-detection),None(same as'auto'), or any collection of the above. Default:['auto', 0.0]- drop_background_parcelsbool
Whether to set all-background parcels to NaN after aggregation. Redundant when
ignore_background_data=Truebecause those parcels already return NaN from empty-mean aggregation; only useful withignore_background_data=False. Default: False
- 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:
- 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)[source]
- 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]
- 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 (requiresY_transform);"sets"— X set membership labels (requires XSEA). Allowed combinations:["maps", "groups"],["maps", "sets"],["groups", "sets"]. Three-way simultaneous permutation is not supported and falls back to["groups", "sets"].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. Options:
"moran"(default for volumetric),"alexander_bloch"/"spin"(surface),"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) —Falsefor single-Y,"mean"otherwise.p_from_average_y_coloc (str or bool, optional) – Deprecated. Use
pooled_pinstead.n_proc (int, optional) – Number of parallel processes. Defaults to the value set at init.
seed (int, optional) – Random seed for reproducibility.
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:
"proportional"(default) or"random". Remaining kwargs (no prefix) are forwarded tocolocalize().
- 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_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]
Performs dimensionality reduction on X data. Under construction.
- 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) –