coord2region.utils#

Coord2Region utilities for file I/O, images, and working-directory tools.

Submodules#

Classes#

AtlasFileHandler

Handle file operations for atlas fetching.

Functions#

save_as_csv(→ None)

Save pipeline results to a CSV file.

save_as_pdf(→ None)

Save pipeline results to a PDF file or directory.

save_batch_folder(→ None)

Save results as a directory with individual JSON files and images.

add_watermark(→ bytes)

Overlay a semi-transparent watermark onto image bytes.

generate_mni152_image(→ bytes)

Return a PNG image of a sphere drawn on the MNI152 template.

ensure_mne_data_directory(→ pathlib.Path)

Ensure the MNE data directory exists and is registered with MNE.

resolve_working_directory(→ pathlib.Path)

Return the root working directory for coord2region assets.

fetch_labels(labels)

Parse a labels input.

pack_surf_output(atlas_name, fetcher[, subject, ...])

Load a surface-based atlas using FreeSurfer annotations.

pack_vol_output(file)

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. If None, the value is inferred from mne.get_config().

data_dir#

Base directory where atlas files and other outputs are stored.

Type:

str

cached_data_dir#

Directory for cached datasets.

Type:

str

generated_images_dir#

Directory for generated images.

Type:

str

results_dir#

Directory for exported results.

Type:

str

subjects_dir#

Path to the FreeSurfer subjects directory.

Type:

str or None

nilearn_data#

Directory for caching Nilearn datasets.

Type:

str

mne_data_dir#

Directory registered with MNE for dataset downloads.

Type:

str

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 None if 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:
  • atlas_file (str) – The name of the atlas file.

  • atlas_dir (str) – Directory where the atlas file is located.

  • labels (str or list) – Labels file or a list of label names.

Returns:

Dictionary containing the atlas data.

Return type:

dict

Raises:

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:

str

Raises:

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.

Parameters:
  • image_bytes (bytes) – Original image encoded as bytes.

  • text (str, optional) – Watermark text to overlay. Defaults to "AI approximation for illustrative purposes".

Returns:

PNG-encoded image bytes with the watermark applied.

Return type:

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:
  • coord (sequence of float) – MNI coordinate (x, y, z) in millimetres.

  • radius (int, optional) – Radius of the sphere in millimetres. Defaults to 6.

  • cmap (str, optional) – Matplotlib colormap used for the overlay. Defaults to "autumn".

Returns:

PNG-encoded image bytes representing the sphere on the MNI152 template.

Return type:

bytes

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.

Parameters:

base (str or None, optional) – User supplied base directory. If None (default) the path ~/coord2region is returned. Relative paths are interpreted relative to the user’s home directory.

Returns:

Absolute path to the working directory.

Return type:

Path

coord2region.utils.fetch_labels(labels)[source]#

Parse a labels input.

A list is returned as-is. If labels is 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:

list of str

Raises:

ValueError – If the XML file is invalid, cannot be parsed, contains no labels, or if labels is 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:

dict

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:

dict

Raises:

ValueError – If the file format or object type is not supported.

Examples

>>> pack_vol_output('atlas.nii.gz')  
{'vol': array(...), 'hdr': array(...)}