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.

io

io

BrainData I/O and loading functions.

Standalone functions extracted from BrainData class methods for mask initialization, data loading (from files, lists, URLs, HDF5, other BrainData objects), resampling, writing, and uploading.

Methods:

NameDescription
check_space_matchCheck if data and mask are in same space.
detect_and_update_maskDetect best matching template from data and update mask if mask was None.
detect_spaceDetect if mask is in MNI space or native space.
get_interpolationGet the interpolation method to use for a given image.
initialize_maskInitialize the mask image.
load_from_brain_dataLoad data from another BrainData object.
load_from_fileLoad data from file path or nibabel object.
load_from_h5Load data from HDF5 file.
load_from_listLoad data from a list of BrainData objects or file paths.
load_from_urlLoad data from URL.
mask_imagesMask a list of space-aligned images with a single fitted masker.
resample_toResample BrainData to match target image or resolution.
to_niftiConvert BrainData instance to a nibabel NIfTI image.
upload_neurovaultUpload data to NeuroVault.
warn_if_resamplingWarn about resampling if verbose=True and resample=True.
write_brain_dataWrite out BrainData object to Nifti or HDF5 File.

Methods

check_space_match

check_space_match(data_img, mask_img)

Check if data and mask are in same space.

Parameters:

NameTypeDescriptionDefault
data_imgnibabel Nifti1Image objectrequired
mask_imgnibabel Nifti1Image object (mask)required

Returns:

NameTypeDescription
boolTrue if spaces match (no resampling needed), False otherwise

detect_and_update_mask

detect_and_update_mask(bd, data_img)

Detect best matching template from data and update mask if mask was None.

Also handles resampling if needed based on the resample kwarg.

This function is called during data loading to auto-detect template when mask=None. After detecting or falling back to a template, it checks if resampling is needed and resamples the data_img accordingly.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
data_imgnibabel Nifti1Image object from which to detect templaterequired

Returns:

TypeDescription
nibabel.Nifti1Image: The data_img, possibly resampled to match the mask

detect_space

detect_space(mask)

Detect if mask is in MNI space or native space.

Parameters:

NameTypeDescriptionDefault
masknibabel Nifti1Image objectrequired

Returns:

NameTypeDescription
str‘mni’ if mask is MNI template, ‘native’ otherwise

get_interpolation

get_interpolation(bd, img)

Get the interpolation method to use for a given image.

Resolves ‘auto’ to either ‘nearest’ or ‘continuous’ based on data type.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
imgnibabel image to check (used when interpolation=‘auto’)required

Returns:

NameTypeDescription
strInterpolation method. When ‘auto’, resolves to ‘nearest’ or ‘continuous’ based on data type. Otherwise returns the instance’s configured interpolation setting.

initialize_mask

initialize_mask(bd, mask)

Initialize the mask image.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
maskBrain mask as nibabel object, file path, template name string, or None. Template name strings supported: ‘{res}mm-MNI152-2009{version}’ (e.g., ‘2mm-MNI152-2009c’, ‘3mm-MNI152-2009a’, ‘2mm-MNI152-2009fsl’)required

load_from_brain_data

load_from_brain_data(bd, brain_data, mask = None)

Load data from another BrainData object.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
brain_dataBrainData object to copy from.required
maskOptional mask to use. If None, uses mask from brain_data.None

load_from_file

load_from_file(bd, data)

Load data from file path or nibabel object.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
dataFile path or nibabel object.required

load_from_h5

load_from_h5(bd, file_path, mask)

Load data from HDF5 file.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
file_pathPath to HDF5 file.required
maskUser-specified mask (to determine if we should load mask from file).required

load_from_list

load_from_list(bd, data_list)

Load data from a list of BrainData objects or file paths.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
data_listList of BrainData objects or file paths.required

load_from_url

load_from_url(bd, url)

Load data from URL.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
urlURL to download data from.required

mask_images

mask_images(mask, imgs)

Mask a list of space-aligned images with a single fitted masker.

Validates mask exactly ONCE — one load_mask_img — and reuses the binarized mask across every image in imgs, instead of re-running nilearn’s costly load_mask_img (binarization checks + safe_get_data, which each trigger nilearn’s forced gc.collect) per image.

nilearn.masking.apply_mask is exactly load_mask_img (validate) -> new_img_like (build binary mask) -> apply_mask_fmri (extract), with dtype='f', smoothing_fwhm=None, ensure_finite=True. This hoists the first two out of the per-image loop and calls the lower-level apply_mask_fmri (which “assumes mask_img contains only two different values”) per image, so the result is byte-equivalent to np.vstack([apply_mask(im, mask) for im in imgs]) for space-aligned data.

Images must already share mask’s space (callers resample first); no resampling is done here. Falls back to the per-image functional apply_mask if the fast path raises for any reason.

Parameters:

NameTypeDescriptionDefault
maskA nibabel.Nifti1Image boolean/binary mask.required
imgsList of space-aligned nibabel images to mask.required

Returns:

TypeDescription
np.ndarray of shape (len(imgs), n_voxels).

resample_to

resample_to(bd, *, img = None, resolution = None, interpolation = None)

Resample BrainData to match target image or resolution.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
imgTarget image for resampling. Can be: - nibabel Nifti1Image object - str/Path to .nii/.nii.gz file - None (if using resolution parameter)None
resolutionTarget voxel size in mm. Can be: - float/int: Isotropic resolution (e.g., 2.0 = 2mm^3) - None (if using img parameter)None
interpolationInterpolation method for resampling. Can be: - None (default): Uses instance’s interpolation setting - ‘nearest’: Nearest-neighbor (for atlases, masks, labels) - ‘linear’: Linear interpolation - ‘continuous’: Higher-order spline (for stat maps)None

Returns:

NameTypeDescription
BrainDataNew BrainData instance with resampled data

to_nifti

to_nifti(bd)

Convert BrainData instance to a nibabel NIfTI image.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required

Returns:

TypeDescription
nibabel.Nifti1Image: Brain data in volumetric NIfTI format.

upload_neurovault

upload_neurovault(bd, *, access_token = None, collection_name = None, collection_id = None, img_type = None, img_modality = None, **kwargs)

Upload data to NeuroVault.

Adds any columns in bd.X to image metadata. Index will be used as image name.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
access_tokenstrNeuroVault API access token. Required.None
collection_namestrName of new collection to create.None
collection_idintNeuroVault collection ID if adding images to an existing collection.None
img_typestrNeuroVault map type. Required.None
img_modalitystrNeuroVault image modality. Required.None
**kwargsAdditional keyword arguments passed to the NeuroVault API.{}

Returns:

NameTypeDescription
dictNeuroVault collection information.

warn_if_resampling

warn_if_resampling(bd, context = '')

Warn about resampling if verbose=True and resample=True.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
contextstrContext string to include in warning. Default: empty string.‘’

write_brain_data

write_brain_data(bd, file_name)

Write out BrainData object to Nifti or HDF5 File.

Parameters:

NameTypeDescriptionDefault
bdBrainData instance.required
file_namestr or PathOutput file path. Supports .nii/.nii.gz (NIfTI) and .h5/.hdf5 (HDF5) formats.required