API Reference

nispace.api – NiSpace main class

NiSpace(x[, y, z, x_labels, y_labels, ...])

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.

nispace.datasets – Dataset fetchers

fetch_template([template, res, desc, hemi, ...])

Fetch a brain template.

fetch_parcellation([parcellation, space, ...])

Fetch a parcellation, as a Parcellation object (preferred) or, in legacy mode, as individual loaded arrays/paths.

fetch_reference(dataset[, maps, space, ...])

Fetch reference/annotation maps (or parcellated data derived from them) for a dataset.

fetch_collection(collection[, dataset, ...])

Fetch a collection that defines a subset (and optional grouping) of maps.

apply_collection(data, collection)

Re-index a parcellated-data DataFrame by a collection's set/weight structure.

fetch_metadata(dataset[, maps, collection, ...])

Deprecated alias for fetch_map_info().

fetch_map_info(dataset[, maps, overwrite, ...])

Fetch a dataset's per-map metadata table (e.g.

fetch_plot(name[, kind, display, ...])

Fetch the overview plot PNG for a parcellation or reference dataset.

fetch_example(example[, parcellation, ...])

Fetch an integrated example dataset, pre-parcellated with a given parcellation.

nispace.workflows – Workflows

colocalization(y[, x, z, x_collection, ...])

Colocalization workflow.

group_colocalization(y, design[, x, z, ...])

Group-comparison colocalization workflow.

paired_colocalization(y, x[, z, ...])

Within-pair colocalization workflow (SPICE test).

xsea(y[, x, z, x_collection, x_background, ...])

Set enrichment analysis (XSEA) workflow for group-level map(s).

group_xsea(y, design[, x, z, x_collection, ...])

Group-comparison set enrichment analysis (XSEA) workflow.

nimare_colocalization(y[, x, z, ...])

NiMARE colocalization workflow.

nimare_xsea(y[, x, z, x_collection, ...])

NiMARE X-set enrichment analysis (XSEA) workflow.

simple_colocalization(y[, x, z, ...])

Deprecated wrapper for colocalization().

group_comparison(y, design[, x, z, ...])

Deprecated wrapper for group_colocalization().

simple_xsea(y[, x, z, x_collection, ...])

Deprecated wrapper for xsea().

nispace.stats.coloc – Colocalization statistics

rank_array(array)

Backwards-compatibility alias for rank1d (same signature/behavior).

rank1d(arr)

Rank a 1D array using mid-ranks (average rank) for tied values.

rank2d(arr)

Rank a 2D array column-wise using mid-ranks, skipping NaN per column.

corr(x, y[, rank])

Compute Pearson (or, with rank=True, Spearman) correlation for two 1D arrays.

pearson(x, y)

Compute Pearson correlation for two 1D arrays.

partialcorr(x, y, z[, rank])

Closed-form partial correlation between x and y, controlling for z.

partialpearson(x, y, z)

Closed-form partial Pearson correlation between x and y, controlling for z.

mutualinfo(x, y[, n_neighbors, seed])

Compute mutual information between x and y via sklearn's k-NN estimator.

mlr(x, y[, adj_r2, intercept])

Multiple linear regression of predictor(s) x on target y (via pseudo-inverse).

r2(x, y[, adj_r2])

R2 of the regression of predictor(s) x on target y (see mlr).

beta(x, y[, intercept])

Beta coefficients for the regression of predictor(s) x on target y (see mlr).

dominance(x, y[, adj_r2, verbose])

Dominance analysis: decompose R2 into each predictor's average contribution.

pls(x, y[, n_components])

Partial least squares regression of x on y via scikit-learn's NIPALS PLSRegression.

pcr(x, y[, adj_r2, n_components])

Principal component regression: PCA-reduce x, then regress on y via r2.

fast_pls1(x, y, n_components)

Fast PLS via the SIMPLS algorithm for a single target.

elasticnet(x, y[, cv, seed])

Elastic-net regularized regression of x on y via sklearn.linear_model.ElasticNetCV.

lasso(x, y[, cv, seed, kwargs])

Lasso-regularized regression of x on y via sklearn.linear_model.LassoCV.

ridge(x, y[, cv, seed, kwargs])

Ridge-regularized regression of x on y via sklearn.linear_model.RidgeCV.

nispace.stats.effectsize – Effect size calculation

cohen(a, b)

Cohen's d for independent groups: pooled-SD standardized mean difference.

cohen_nan(a, b)

NaN-aware Cohen's d for independent groups (see cohen).

cohen_paired(a, b)

Cohen's d for paired/dependent samples: mean difference over SD of differences.

cohen_paired_nan(a, b)

NaN-aware Cohen's d for paired/dependent samples (see cohen_paired).

hedges(a, b)

Hedges' g: small-sample bias-corrected Cohen's d for independent groups.

hedges_nan(a, b)

NaN-aware Hedges' g for independent groups (see hedges).

zscore(a[, b])

Standard (mean/SD) z-score of a, optionally against a reference b.

zscore_nan(a[, b])

NaN-aware standard z-score of a, optionally against a reference b.

rzscore_nan(a[, b])

NaN-aware robust z-score of a (median/MAD), optionally against a reference b.

prc(a, b)

Percent change (a - b) / a * 100, element-wise.

logfc_nan(a, b)

NaN-aware log fold-change log((a + c) / (b + c)), with an auto-computed shift c.

nispace.stats.misc – Miscellaneous stats functions

np_any_axis1(x)

Numba-compatible np.any(x, axis=1).

residuals(x, y[, decenter])

OLS residuals of y on x (plus intercept).

residuals_nan(x, y[, decenter])

OLS residuals of y on x (plus intercept), NaN-tolerant.

partial_residuals_nan(x_nuisance, x_protect, y)

Partial residuals: regress x_nuisance from y while controlling for x_protect.

rho_to_z(array[, replace_1])

Fisher's z-transformation of correlation coefficients.

z_to_rho(array)

Inverse Fisher's z-transformation of correlation coefficients.

zscore_df(df[, along, force_df])

Z-standardize a DataFrame/Series/ndarray, preserving its type.

permute_groups(groups[, strategy, paired, ...])

Permute group-membership labels for group-comparison null distributions.

null_to_p(test_value, null_array[, tail, ...])

Return p-value for test value(s) against null array.

mc_correction(p_array[, alpha, method, how, ...])

Multiple-comparison correction via statsmodels.stats.multitest.multipletests.

compute_meff(X[, method])

Effective number of independent tests from data matrix via eigendecomposition.

meff_sidak_correction(p_array, meff[, ...])

Sidak correction using Meff effective number of tests.

maxT_correction(obs_stats, null_colocs, stat)

Max-T FWER correction ([31]).

step_maxT_correction(obs_stats, null_colocs, ...)

Step-down Max-T FWER correction ([31]).

nispace.io – Imaging data input

parcellate_data(data[, data_labels, ...])

Parcellates given imaging data using a specified parcellation.

read_json(json_path)

Load a JSON file, or pass through a dict-like object as a dict.

write_json(json_dict, json_path)

Write a dict to a JSON file (pretty-printed, indent=4).

load_img(img[, override_file_format])

Load one or more nifti/gifti images, passing through already-loaded objects.

load_labels(labels[, concat, header, index])

Load one or more label lists from paths, arrays, or Series.

load_distmat(distmat)

Load one or more distance matrices from paths, arrays, or DataFrames.

load_spinmat(spinmat)

Load one or more spin-permutation index/weight arrays from paths or arrays.

to_pickle(obj, filepath[, use_dill])

Pickle, compress, and save to a file.

from_pickle(filepath[, use_dill])

Unpickle a python object saved with to_pickle().

nispace.parcellate – Parcellation class

Parcellater(parcellation, space[, ...])

Class for parcellating arbitrary volumetric / surface data.

nispace.nulls – Null map generation

generate_null_maps(method, data, parcellation)

Generate spatially-constrained (or fully random) null maps for one or more parcellated inputs.

nulls_moran(data_1d, dist_mat[, n_nulls, seed])

Moran Spectral Randomization (MSR) surrogate maps (Wagner & Dray 2015).

nulls_burt2020(data_1d, dist_mat[, n_nulls, ...])

Variogram-matched surrogate maps (Burt et al. 2020, brainsmash).

nulls_burt2018(data_1d, dist_mat[, n_nulls, ...])

Spatial autoregressive surrogate maps (Burt et al. 2018).

nulls_random(data_1d[, dist_mat, n_nulls, seed])

Fully random (spatially unconstrained) null maps.

generate_spins(parc, parc_space[, n_perm, ...])

Generate spin resampling indices for a surface parcellation.

apply_spins(data_1d, spins_lh, spins_rh, ...)

Apply precomputed spin indices to a 1D data array.

get_distance_matrix(parc, parc_space[, ...])

Compute a parcel-by-parcel distance matrix for a volumetric or surface parcellation.

find_vol_parc_centroids(parc[, affine, ...])

Compute per-parcel mean voxel coordinates in world (MNI) space.

find_surf_parc_centroids(parc[, parc_space, ...])

Compute per-parcel mean vertex coordinates on a standard cortical surface.

correlate_hemis_parc(data[, parc_idc_lh, ...])

Per-row left/right-hemisphere correlation of parcellated data.

find_parcel_hemispheres(parcellation)

Auto-detect per-parcel hemisphere membership for a parcellation.

nispace.plotting – Plotting functions

brainplot(data[, parcellation, level, kind, ...])

Plot brain maps onto surfaces or anatomical volumes.

view_surf([data, parcellation, hemi, ...])

Quick interactive nilearn surface viewer for parcellated or vertex-wise data on a fetched template/parcellation.

catplot(fig, ax, data_long[, ...])

Draw a categorical plot combining any mix of bars, violins, scatter points, summary dots, and errorbars, built on top of seaborn.objects.

nullplot(fig, ax, data_long[, ...])

Draw a null distribution as shaded percentile bands with a median line (and optionally overlaid violins), per level of categorical_var.

heatmap(ax[, data_colors, data_sizes, ...])

Draw a heatmap-style grid of markers whose color, size, and/or shape each independently encode a separate 2D array (data_colors, data_sizes, data_shapes), with an optional boolean mask and automatic legends for each encoded dimension.

nice_stats_labels(string[, add_dollars])

Map an internal stat/method name (e.g.

print_significance(ax, p_values[, q_values, ...])

Annotate a categorical axis plot with significance markers or p-value text.

move_legend_fig_to_ax(fig, ax, loc[, ...])

Move a figure-level legend (as produced by seaborn.objects.Plot) onto a specific axes, merging it with any existing axes-level legend.

colors_from_values(values, palette_name)

Map a numeric array to RGB colors from a seaborn palette, linearly normalizing values to [0, 1] before indexing into the palette.

hide_empty_axes(axes)

Turn off any axes in a 2D array of subplot axes that were never drawn into (i.e.

linewidth_from_data_units(linewidth, axis[, ...])

Convert a linewidth in data units to linewidth in points.

nispace.transforms – MNI space transforms

mni_to_mni(img, mni_from, mni_to[, order, ...])

Transform a NIfTI image between MNI template spaces using EasyReg fields.

compute_transform_displacement(mni_from, mni_to)

Compute a voxel-wise displacement magnitude map for a MNI space transform.

nispace.helpers – Third-party integration helpers

Note

Functions in this module require optional dependencies not installed with NiSpace by default. Install them separately as needed (e.g. pip install nimare for the NiMARE helpers).

null_maps_from_nimare(result, parcellation)

Generate parcellated null maps from a fitted NiMARE MetaResult.

nimare_fwe_thresholds(corrected_result[, ...])

Extract voxel z-threshold and cluster extent threshold from a NiMARE FWE-corrected result.

get_binary_cluster_map(corrected_result[, ...])

Extract a binary (0/1) cluster mask from a NiMARE FWE-corrected MetaResult.

nispace.utils – Utility functions

set_log(lgr[, verbose])

Set the "nispace" root logger's level and return whether INFO is enabled.

nan_detector(*arrays)

Build a combined 1D NaN mask across one or more arrays sharing dim-0 length.

remove_nan(data[, which])

Drop rows or columns containing NaN from an array/DataFrame/Series.

fill_nan(data, idx[, idx_label, which])

Re-insert all-NaN rows/columns at given positions (inverse of dropping them).

mean_by_set_df(df[, mean_by_set, weighted, ...])

(Weighted) mean/median aggregation of a DataFrame grouped by a "set" index level.

print_arg_pairs(**kwargs)

Format keyword arguments as an aligned two-row key/value log table.

get_column_names(df_or_series[, force_list])

Get column names from a DataFrame, the name from a Series, or None if input is a numpy array.

lower(str_list)

Lowercase a string, or each string element of a list (non-strings passed through).

get_background_value(img[, border_size])

Auto-detect a volumetric image's background value from its border voxels.

vect_to_vol_arr(vect, parc_arr, parc_idc[, ...])

Broadcast a per-parcel value vector back into a full volume array.

vol_to_vect_arr(vol_arr, parc_arr, parc_idc, ...)

Aggregate vol_arr into parcel means, excluding NaN and any values in bg_values.

parc_vect_to_vol(vect, parc)

Convert a per-parcel value vector into a full volumetric NIfTI image.

relabel_gifti_parc(parc[, new_labels])

Reassign a surface parcellation's integer labels to a new label sequence.

relabel_nifti_parc(parc[, new_order, ...])

Reassign a volumetric parcellation's integer labels to a new label sequence.

merge_parcellations(parcellations[, labels, ...])

Combine two or more NIfTI parcellation images into one labeled volume.

mirror_nifti(img[, affine, direction, ...])

Mirror/flip a volumetric image across the (affine-derived) x=0 hemisphere boundary.

mirror_gifti(img[, direction, match_r, mask])

Mirror/flip a bilateral surface image pair across hemispheres.