Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

neighborhoods

neighborhoods

Spatial neighborhood computation for neuroimaging analyses.

This module provides efficient computation and caching of spatial neighborhoods (spheres) around brain voxels. It is designed to support searchlight analyses, ISC, and other operations that require iterating over local brain regions.

The key insight is that for a given mask and radius, the neighborhood structure is deterministic and can be cached for reuse across analyses.

Example

import nibabel as nib from nltools.data.braindata.neighborhoods import compute_searchlight_neighborhoods

mask = nib.load(“mask.nii.gz”) neighborhoods = compute_searchlight_neighborhoods(mask, radius_mm=10.0)

Iterate over all voxels and their neighborhoods

for center_idx, neighbor_indices in neighborhoods.iter_neighborhoods(): ... # Extract data for these voxels ... local_data = data[:, neighbor_indices] ... result[center_idx] = analyze(local_data)

Classes:

NameDescription
SphereNeighborhoodsPrecomputed sphere neighborhoods for a brain mask.

Methods:

NameDescription
compute_searchlight_neighborhoodsCompute sphere neighborhoods for all voxels in a brain mask.

Classes

SphereNeighborhoods

SphereNeighborhoods(adjacency: sparse.csr_matrix, mask_hash: str, radius_mm: float, n_voxels: int) -> None

Precomputed sphere neighborhoods for a brain mask.

This dataclass stores a sparse adjacency matrix where row i contains True for all voxels within the specified radius of voxel i. It provides efficient iteration over neighborhoods for searchlight-style analyses.

Attributes:

NameTypeDescription
adjacencycsr_matrixSparse CSR matrix (n_voxels, n_voxels) where adjacency[i, j] is True if voxel j is within radius of voxel i
mask_hashstrHash of the source mask for validation
radius_mmfloatRadius in millimeters
n_voxelsintNumber of voxels in the mask
Example

neighborhoods = compute_searchlight_neighborhoods(mask, radius_mm=10.0) print(f"Mean neighborhood size: {neighborhoods.mean_size:.1f} voxels")

Get neighbors of a specific voxel

neighbor_idx = neighborhoods.get_neighbors(100) print(f"Voxel 100 has {len(neighbor_idx)} neighbors")

Methods:

NameDescription
get_neighborhood_sizeGet the number of voxels in a neighborhood.
get_neighborsGet indices of all voxels in the neighborhood of a given voxel.
iter_neighborhoodsIterate over all neighborhoods.
Methods
get_neighborhood_size
get_neighborhood_size(voxel_idx: int) -> int

Get the number of voxels in a neighborhood.

Parameters:

NameTypeDescriptionDefault
voxel_idxintIndex of the center voxelrequired

Returns:

TypeDescription
intNumber of voxels in the neighborhood
get_neighbors
get_neighbors(voxel_idx: int) -> np.ndarray

Get indices of all voxels in the neighborhood of a given voxel.

Parameters:

NameTypeDescriptionDefault
voxel_idxintIndex of the center voxel (0 to n_voxels-1)required

Returns:

TypeDescription
ndarrayArray of voxel indices within radius of the center voxel
iter_neighborhoods
iter_neighborhoods(*, progress_bar: bool = False) -> Iterator[tuple[int, np.ndarray]]

Iterate over all neighborhoods.

Parameters:

NameTypeDescriptionDefault
progress_barboolIf True, wrap iterator with tqdm progress barFalse

Yields:

TypeDescription
tuple [ int , ndarray ]Tuple of (center_voxel_idx, neighbor_indices) for each voxel

Methods

compute_searchlight_neighborhoods

compute_searchlight_neighborhoods(mask_img: Nifti1Image, radius_mm: float = 10.0, use_cache: bool = True) -> SphereNeighborhoods

Compute sphere neighborhoods for all voxels in a brain mask.

For each voxel in the mask, this function identifies all other voxels within the specified radius (in millimeters). The result is cached to disk for fast reloading in subsequent analyses.

The algorithm uses sklearn’s BallTree for efficient radius queries in world coordinates (mm), ensuring accurate neighborhoods regardless of voxel resolution.

Parameters:

NameTypeDescriptionDefault
mask_imgNifti1ImageNIfTI mask image defining the brain regionrequired
radius_mmfloatRadius of spheres in millimeters (default: 10.0)10.0
use_cacheboolIf True, cache results to ~/.nltools/cache/searchlight/ for fast reloading (default: True)True

Returns:

TypeDescription
SphereNeighborhoodsSphereNeighborhoods with precomputed adjacency matrix
Example

import nibabel as nib mask = nib.load(“brain_mask.nii.gz”)

First call computes and caches (may take a few seconds)

neighborhoods = compute_searchlight_neighborhoods(mask, radius_mm=8.0)

Subsequent calls load from cache (~50ms)

neighborhoods = compute_searchlight_neighborhoods(mask, radius_mm=8.0)

print(neighborhoods) SphereNeighborhoods(n_voxels=50000, radius=8.0mm, mean_size=33.2)

Note

Cache location: ~/.nltools/cache/searchlight/{mask_hash}_{radius}mm.npz

For a typical 2mm MNI mask (~50k voxels) with 10mm radius:

  • First run: ~1-2 seconds

  • Cached load: ~50ms