coord2region.utils#
Coord2Region utilities for file I/O, images, and working-directory tools.
Submodules#
Classes#
Handle file operations for atlas fetching. |
Functions#
|
Save pipeline results to a CSV file. |
|
Save pipeline results to a PDF file or directory. |
|
Save results as a directory with individual JSON files and images. |
|
Overlay a semi-transparent watermark onto image bytes. |
|
Return a PNG image of a sphere drawn on the MNI152 template. |
|
Ensure the MNE data directory exists and is registered with MNE. |
|
Return the root working directory for coord2region assets. |
|
Parse a labels input. |
|
Load a surface-based atlas using FreeSurfer annotations. |
|
Load an atlas file and return volume data and header. |
Package Contents#
- class coord2region.utils.AtlasFileHandler(data_dir: str | None = None, subjects_dir: str | None = None)[source]#
Handle file operations for atlas fetching.
- Parameters:
data_dir (str or None, optional) – Base directory for downloaded atlas files. Defaults to
~/coord2region. Relative paths are interpreted relative to the user’s home directory.subjects_dir (str or None, optional) – FreeSurfer
SUBJECTS_DIR. IfNone, the value is inferred frommne.get_config().
Examples
>>> handler = AtlasFileHandler() >>> handler.data_dir '/home/user/coord2region'
- data_dir = ''#
- cached_data_dir#
- generated_images_dir#
- results_dir#
- nilearn_data#
- mne_data_dir = ''#
- subjects_dir#
- save(obj, filename: str)[source]#
Save an object to the data directory using pickle.
- Parameters:
obj (Any) – The object to serialize.
filename (str) – Name of the file to save the object to.
- Raises:
ValueError – If the data directory is not writable.
Exception – If there is an error during saving.
Examples
>>> handler = AtlasFileHandler() >>> handler.save({'a': 1}, 'example.pkl')
- load(filename: str)[source]#
Load an object from the data directory.
- Parameters:
filename (str) – Name of the file to load the object from.
- Returns:
The loaded object, or
Noneif the file does not exist.- Return type:
object or None
- Raises:
Exception – If there is an error during loading.
Examples
>>> handler = AtlasFileHandler() >>> handler.load('missing.pkl') None
- fetch_from_local(atlas_file: str, atlas_dir: str, labels: str | list)[source]#
Load an atlas from a local file.
- Parameters:
- Returns:
Dictionary containing the atlas data.
- Return type:
- Raises:
FileNotFoundError – If the atlas or labels file is not found.
Exception – If there is an error during loading.
Examples
>>> handler = AtlasFileHandler() >>> handler.fetch_from_local('atlas.nii.gz', '.', ['A', 'B']) {'vol': array(...), 'hdr': array(...), 'labels': ['A', 'B']}
- fetch_from_url(atlas_url: str, **kwargs)[source]#
Download an atlas from a URL.
- Parameters:
atlas_url (str) – The URL of the atlas file.
**kwargs – Additional arguments for the download.
- Returns:
Local path to the downloaded (and possibly decompressed) file.
- Return type:
- Raises:
RuntimeError – If the download fails.
ValueError – If the data directory is not writable.
Exception – If there is an error during downloading.
Examples
>>> handler = AtlasFileHandler() >>> handler.fetch_from_url('http://example.com/atlas.nii.gz') '/path/to/atlas.nii.gz'
- coord2region.utils.save_as_csv(results: Sequence[Any], path: str) None[source]#
Save pipeline results to a CSV file.
- coord2region.utils.save_as_pdf(results: Sequence[Any], path: str) None[source]#
Save pipeline results to a PDF file or directory.
- coord2region.utils.save_batch_folder(results: Sequence[Any], path: str) None[source]#
Save results as a directory with individual JSON files and images.
- coord2region.utils.add_watermark(image_bytes: bytes, text: str = 'AI approximation for illustrative purposes') bytes[source]#
Overlay a semi-transparent watermark onto image bytes.
- coord2region.utils.generate_mni152_image(coord: Sequence[float], radius: int = 6, cmap: str = 'autumn') bytes[source]#
Return a PNG image of a sphere drawn on the MNI152 template.
- Parameters:
- Returns:
PNG-encoded image bytes representing the sphere on the MNI152 template.
- Return type:
- coord2region.utils.ensure_mne_data_directory(base: PathLike = None) Path[source]#
Ensure the MNE data directory exists and is registered with MNE.
- coord2region.utils.resolve_working_directory(base: PathLike = None) Path[source]#
Return the root working directory for coord2region assets.
- coord2region.utils.fetch_labels(labels)[source]#
Parse a labels input.
A list is returned as-is. If
labelsis a string, it is treated as the path to an XML file and parsed for entries within a<data><label><name>...</name></label></data>structure.- Parameters:
labels (list of str or str) – A list of label names or a path to an XML file containing labels.
- Returns:
Parsed label names.
- Return type:
- Raises:
ValueError – If the XML file is invalid, cannot be parsed, contains no labels, or if
labelsis neither a list nor a string.
Examples
>>> fetch_labels(['A', 'B']) ['A', 'B'] >>> fetch_labels('atlas.xml') ['Region1', 'Region2']
- coord2region.utils.pack_surf_output(atlas_name, fetcher, subject: str = 'fsaverage', subjects_dir: str | PathLike | None = None, **kwargs)[source]#
Load a surface-based atlas using FreeSurfer annotations.
- Parameters:
atlas_name (str) – Name of the atlas (e.g.,
'aparc').fetcher (callable or None) – Function used to download the atlas if necessary.
subject (str, optional) – Subject identifier, by default
'fsaverage'.subjects_dir (path-like or None, optional) – FreeSurfer subjects directory, by default
None.**kwargs – Additional keyword arguments passed to the fetcher.
- Returns:
Dictionary with
'vol','hdr','labels','indexes'and'regions'keys where'regions'maps region names to vertex indices.- Return type:
- Raises:
ValueError – If the atlas cannot be located or fetched.
Examples
>>> pack_surf_output('aparc', None) {'vol': [...], 'hdr': None, 'labels': array([...]), 'indexes': array([...]), 'regions': {'Region': array([...])}}
- coord2region.utils.pack_vol_output(file)[source]#
Load an atlas file and return volume data and header.
- Parameters:
file (str or Nifti1Image) – Path to a NIfTI/NPZ file or a loaded
Nifti1Image.- Returns:
Dictionary with
'vol'and'hdr'entries.- Return type:
- Raises:
ValueError – If the file format or object type is not supported.
Examples
>>> pack_vol_output('atlas.nii.gz') {'vol': array(...), 'hdr': array(...)}