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.

cache

cache

Disk-based caching infrastructure for expensive computations.

This module provides a general-purpose caching system for nltools, designed to be reused across various computationally expensive operations like searchlight neighborhoods, ISC, and SRM.

Example

from nltools.data.braindata.cache import CacheManager, hash_mask import nibabel as nib

Hash a mask for cache key generation

mask = nib.load(“mask.nii.gz”) mask_hash = hash_mask(mask)

Use cache manager for searchlight neighborhoods

cache = CacheManager(“searchlight”) if not cache.exists(f"{mask_hash}_10mm"): ... # Compute expensive operation ... result = compute_something() ... cache.save(f"{mask_hash}_10mm", data=result) else: ... result = cache.load(f"{mask_hash}_10mm")[“data”]

Classes:

NameDescription
CacheManagerManages disk-based caching for expensive computations.

Methods:

NameDescription
clear_cacheClear the nltools cache.
get_cache_dirGet the nltools cache directory.
hash_maskCompute a stable hash for a NIfTI mask image.

Classes

CacheManager

CacheManager(category: str = 'general')

Manages disk-based caching for expensive computations.

CacheManager provides a simple key-value interface for caching numpy arrays to disk. It organizes cached files by category (e.g., “searchlight”, “isc”) in separate subdirectories.

Parameters:

NameTypeDescriptionDefault
categorystrCategory name for organizing cached files (e.g., “searchlight”)‘general’
Example

cache = CacheManager(“searchlight”)

Check if something is cached

if cache.exists(“mykey”): ... data = cache.load(“mykey”) ... else: ... result = expensive_computation() ... cache.save(“mykey”, adjacency=result, metadata=metadata) ... data = {“adjacency”: result, “metadata”: metadata}

Attributes:

NameTypeDescription
cache_dir
category

Methods:

NameDescription
clearClear all cached files in this category.
deleteDelete a cached file.
existsCheck if a cache key exists.
get_pathGet the file path for a cache key.
list_keysList all cached keys in this category.
loadLoad cached data.
saveSave arrays to cache.
Methods
clear
clear() -> int

Clear all cached files in this category.

Returns:

TypeDescription
intNumber of files deleted
delete
delete(key: str, ext: str = '.npz') -> bool

Delete a cached file.

Parameters:

NameTypeDescriptionDefault
keystrCache keyrequired
extstrFile extension‘.npz’

Returns:

TypeDescription
boolTrue if file was deleted, False if it didn’t exist
exists
exists(key: str, ext: str = '.npz') -> bool

Check if a cache key exists.

Parameters:

NameTypeDescriptionDefault
keystrCache keyrequired
extstrFile extension (default: “.npz”)‘.npz’

Returns:

TypeDescription
boolTrue if cached file exists
get_path
get_path(key: str, ext: str = '.npz') -> Path

Get the file path for a cache key.

Parameters:

NameTypeDescriptionDefault
keystrCache keyrequired
extstrFile extension (default: “.npz”)‘.npz’

Returns:

TypeDescription
PathPath to the cache file
list_keys
list_keys(ext: str = '.npz') -> list[str]

List all cached keys in this category.

Parameters:

NameTypeDescriptionDefault
extstrFile extension to match‘.npz’

Returns:

TypeDescription
list [ str ]List of cache keys (without extension)
load
load(key: str) -> dict | None

Load cached data.

Parameters:

NameTypeDescriptionDefault
keystrCache keyrequired

Returns:

TypeDescription
dict | NoneDictionary of cached arrays, or None if not cached
save
save(key: str, compressed: bool = True, **arrays: bool) -> Path

Save arrays to cache.

Parameters:

NameTypeDescriptionDefault
keystrCache keyrequired
compressedboolIf True, use compressed npz format (smaller but slower)True
**arraysNamed arrays to cache{}

Returns:

TypeDescription
PathPath to saved cache file

Methods

clear_cache

clear_cache(category: str | None = None) -> int

Clear the nltools cache.

Parameters:

NameTypeDescriptionDefault
categorystr | NoneIf provided, only clear this category. Otherwise clear all.None

Returns:

TypeDescription
intNumber of files deleted

get_cache_dir

get_cache_dir() -> Path

Get the nltools cache directory.

Returns ~/.nltools/cache, creating it if necessary.

Returns:

TypeDescription
PathPath to cache directory

hash_mask

hash_mask(mask_img: Nifti1Image) -> str

Compute a stable hash for a NIfTI mask image.

The hash is based on the mask’s shape, affine transformation, and the actual voxel positions. This ensures that masks with the same shape but different voxel locations (or different affines) produce different hashes.

Parameters:

NameTypeDescriptionDefault
mask_imgNifti1ImageNIfTI image to hash (typically a binary mask)required

Returns:

TypeDescription
str16-character hexadecimal hash string
Example

import nibabel as nib mask = nib.load(“mask.nii.gz”) hash_mask(mask) ‘a1b2c3d4e5f60789’