Skip to content

nltools.datasets

Example datasets, Neurovault collections, the files bundled with the package, and the atlas lookups.

Dataset, resource, and atlas lookups.

Functions to fetch example datasets, bundled resources, and parcellations. The curated example datasets (fetch_pain, fetch_emotion_ratings) are hosted on the nltools/niftis Hugging Face dataset and resolve through the same fetch_resource machinery as the MNI templates and atlases. Arbitrary Neurovault collections are available via fetch_neurovault_collection, and list_atlases / load_atlas / label_coords cover the parcellations.

Functions:

Name Description
fetch_pain

Download and load the pain dataset from the nltools HF dataset.

fetch_emotion_ratings

Download and load the emotion-rating dataset from the nltools HF dataset.

fetch_neurovault_collection

Download images and metadata from a Neurovault collection.

load_haxby_example

Load a synthetic Haxby-like dataset on the MNI grid, entirely in-memory.

download_nifti

Download an image from a URL to a nifti file.

get_resource_path

Get the path to the nltools resource directory.

fetch_resource

Return a local path to a file from the nltools/niftis HF dataset.

list_resources

List files available in the nltools/niftis HF dataset.

list_atlases

Return the sorted list of registered atlas names.

load_atlas

Lazy-load an atlas by registry name.

label_coords

Look up anatomical labels for a set of MNI mm coordinates.

Functions:

fetch_pain

fetch_pain(verbose=0)

Download and load the pain dataset from the nltools HF dataset.

Loads the Chang et al. (2015) pain-perception study: 28 subjects x 3 stimulus-intensity conditions = 84 whole-brain contrast images, with a curated metadata table (SubjectID, PainLevel, PainIntensity, Age, Sex, provenance neurovault_id / name).

Data is hosted on the nltools/niftis Hugging Face dataset and cached locally on first use, so this works with no extra setup.

Parameters:

Name Type Description Default
verbose int

Verbosity passed to BrainData while loading. Default: 0

0

Returns:

Type Description
BrainData

BrainData with the 84 images; X holds the metadata table.

References

Chang, L. J., Gianaros, P. J., Manuck, S. B., Krishnan, A., & Wager, T. D. (2015). A sensitive and specific neural signature for picture-induced negative affect. PLoS biology, 13(6), e1002180.

fetch_emotion_ratings

fetch_emotion_ratings(verbose=0)

Download and load the emotion-rating dataset from the nltools HF dataset.

Loads the Chang et al. (2015) IAPS emotion-rating study: 679 whole-brain contrast images across 150 subjects, each rating images 1-5, with a built-in train/test holdout split. X carries the full portable Neurovault metadata (key columns: SubjectID, Rating, Holdout, AGE, SEX).

Data is hosted on the nltools/niftis Hugging Face dataset and cached locally on first use, so this works with no extra setup.

Parameters:

Name Type Description Default
verbose int

Verbosity passed to BrainData while loading. Default: 0

0

Returns:

Type Description
BrainData

BrainData with the 679 images; X holds the metadata table.

References

Chang, L. J., Gianaros, P. J., Manuck, S. B., Krishnan, A., & Wager, T. D. (2015). A sensitive and specific neural signature for picture-induced negative affect. PLoS biology, 13(6), e1002180.

fetch_neurovault_collection

fetch_neurovault_collection(
    collection_id, data_dir=None, verbose=1
)

Download images and metadata from a Neurovault collection.

Wraps nilearn.datasets.fetch_neurovault_ids.

Parameters:

Name Type Description Default
collection_id int

Neurovault collection ID

required
data_dir str

Directory to store downloaded data. If None, uses nilearn's default data directory.

None
verbose int

Verbosity level; 0 is silent, including the data-directory line nilearn reports whatever it is asked for. Default: 1

1

Returns:

Type Description
tuple[DataFrame, list[str]]

(metadata, files) — the image metadata table and the downloaded image paths.

Raises:

Type Description
ValueError

If collection_id is invalid

RuntimeError

If download fails, or if the collection returns no images

load_haxby_example

load_haxby_example(
    n_runs=1,
    *,
    space="mni",
    block_order="independent",
    random_state=42,
)

Load a synthetic Haxby-like dataset on the MNI grid, entirely in-memory.

The quickest way to try nltools: nothing is downloaded beyond the MNI template fetch_resource already caches, and a run takes a second or two to build. Returns paired lists of BrainData and DesignMatrix, one entry per run.

Each run is a randomized block design of the eight conditions from the real Haxby 2001 object-recognition experiment (face, house, cat, bottle, scissors, shoe, chair, scrambledpix): 15 s of stimulation followed by 7.5 s of rest, eight times, at TR = 2.5 s for 72 TRs. Every condition drives an 8 mm sphere at an anatomically plausible location — faces in the right fusiform face area, houses in the left parahippocampal place area, animals in the left fusiform, man-made objects in lateral occipital and posterior fusiform cortex, and scrambled pictures in early visual cortex — with a 3% peak response against 1% white noise. A condition also drives its category-mates' spheres at a third of that, so the eight response patterns carry an animate / man-made / scene / control similarity structure. Each run draws its own block order by default; pass block_order='shared' when the runs have to line up TR by TR, as they do for intersubject correlation, alignment and anything else that compares runs timepoint against timepoint.

Parameters:

Name Type Description Default
n_runs int

Number of runs to generate. Default 1.

1
space str

Voxel space of the data. 'mni' (default) is the package's 3 mm MNI152 mask, so every plotting method, apply_mask and extract_roi work on the result. 'grid' is a 10 x 10 x 5 synthetic volume with random condition clusters, for tests that need construction in milliseconds and never plot.

'mni'
block_order str

How the condition order varies across runs. 'independent' (default) draws a fresh order per run; 'shared' draws one order and gives it to every run, so the runs are comparable TR by TR. Noise differs per run either way.

'independent'
random_state int | None

Seed for reproducible output. Default 42.

42

Returns:

Type Description
tuple

(list[BrainData], list[DesignMatrix]), each of length n_runs. Each BrainData carries a .Y with a condition column (the eight condition names plus 'rest') and a run column. The DesignMatrix columns are the eight condition names suffixed with _c0 (HRF-convolved boxcars).

Raises:

Type Description
ValueError

If space is not 'mni' or 'grid', or block_order is not 'independent' or 'shared'.

Examples:

from nltools.datasets import load_haxby_example
from nltools.mask import create_sphere

brain_data, design_matrices = load_haxby_example()
data, dm = brain_data[0], design_matrices[0]

# A first-level contrast; the face patch is visible without a threshold
data.fit("glm", X=dm)
data.compute_contrasts("face_c0 - house_c0").plot(method="glass")

# Decode faces from houses inside the regions that carry the signal
ventral_temporal = create_sphere(
    [[40, -50, -20], [-26, -44, -10]], radius=8, mask=data.mask
)
trs = data[data.Y["condition"].is_in(["face", "house"])]
trs.apply_mask(ventral_temporal).predict(y="condition", cv=3).mean_score
# → 0.83
Note

Decoding and representational similarity need a region, not the whole brain: one run labels only twelve TRs per pair of conditions, and 71,020 voxels of noise swamp the ~150 that respond. Mask down to the response spheres — create_sphere with the centers above — before predict or distance, the way ventral-temporal MVPA is done on the real dataset.

download_nifti

download_nifti(url, data_dir=None)

Download an image from a URL to a nifti file.

Parameters:

Name Type Description Default
url str

URL of the image to download

required
data_dir str

Directory to save the file. If None, uses current directory.

None

Returns:

Type Description
str

Path to the downloaded file

Raises:

Type Description
ImportError

If requests is not available

ValueError

If URL is invalid

get_resource_path

get_resource_path()

Get the path to the nltools resource directory.

Returns:

Type Description
str

Absolute path to nltools/resources/, with a trailing separator.

fetch_resource cached

fetch_resource(relpath: str) -> str

Return a local path to a file from the nltools/niftis HF dataset.

Parameters:

Name Type Description Default
relpath str

Path within the dataset repo, e.g. 'default/2mm-MNI152-2009fsl-mask.nii.gz' or 'masks/k88_parcel_names.csv'. Use list_resources to enumerate what's available.

required

Returns:

Type Description
str

Absolute path to the cached file on disk. The returned path drops straight into anything that takes a NIfTI path — nilearn plotting and masking helpers, nibabel.load, and BrainData(path).

Note

Resolution is memoized per relpath for the session — repeated calls (e.g. every default-mask BrainData construction) return the cached path with no work. A file already in the HF cache is resolved offline, so only a genuine cache miss touches the network. Under Pyodide the file comes from an IndexedDB-backed cache instead, which persists across page reloads.

list_resources

list_resources(prefix: str | None = None) -> list[str]

List files available in the nltools/niftis HF dataset.

Companion to fetch_resource — surfaces what's downloadable without forcing users to remember relpath strings or visit the HF web UI.

Parameters:

Name Type Description Default
prefix str

Path prefix to filter by (e.g. 'masks/', 'default/', 'fmriprep/'). Matches with str.startswith.

None

Returns:

Type Description
list[str]

Sorted relative paths usable with fetch_resource.

Note

Hits the HF API once per session (cached). Under Pyodide this needs httpcore installed — huggingface_hub's client imports it lazily and nothing else in the browser environment pulls it in, so run await micropip.install("httpcore") first.

list_atlases

list_atlases() -> list[str]

Return the sorted list of registered atlas names.

Returns:

Type Description
list[str]

Sorted list of atlas names usable with load_atlas.

load_atlas cached

load_atlas(name: str) -> _Atlas

Lazy-load an atlas by registry name.

The first call fetches the NIfTI + label CSV from huggingface.co/datasets/nltools/niftis (cached locally afterwards). Subsequent calls in the same process are memoized.

Parameters:

Name Type Description Default
name str

Atlas key from list_atlases.

required

Returns:

Type Description
_Atlas

The atlas with image, labels, and metadata loaded.

Raises:

Type Description
ValueError

If name isn't a registered atlas.

Note

An atlas is in MNI space, and nltools resamples it onto your data by header affine alone. That is a grid change, not a spatial normalization, so parcel boundaries are approximate unless your data are already normalized to the same space.

label_coords

label_coords(
    coords: CoordsLike,
    *,
    atlas: str | Sequence[str] = "harvard_oxford",
    prob_threshold: float = 5.0,
) -> DataFrame

Look up anatomical labels for a set of MNI mm coordinates.

For each coordinate, returns the atlas region(s) it falls in. Works for both deterministic atlases (single label per coord) and probabilistic atlases (formatted "42.0% Foo; 18.0% Bar" strings, sorted by descending probability).

Parameters:

Name Type Description Default
coords array - like

(N, 3) MNI mm coordinates (x, y, z). A single coordinate like (-42, -22, 56) is also accepted.

required
atlas str | Sequence[str]

Atlas name or list of names from list_atlases. One column is added to the output per atlas. Default 'harvard_oxford'.

'harvard_oxford'
prob_threshold float

For probabilistic atlases only — drop regions with probability (in percent units) below this threshold. Default 5.0.

5.0

Returns:

Type Description
DataFrame

Frame with columns x, y, z plus one column per atlas. All atlas columns are Utf8.