coord2region#

Coord2Region: map brain coordinates to regions, studies, and AI insights.

Submodules#

Attributes#

Classes#

AIModelInterface

Register and dispatch to different AI model providers.

ReasonedReport

Parsed result returned by run_reasoned_report().

ReasonedReportContext

Structured payload describing the coordinate, atlas, and studies.

AtlasMapper

Stores a single atlas and provides coordinate conversions.

BatchAtlasMapper

Provide batch (vectorized) conversions for a single atlas mapper.

MultiAtlasMapper

Manage multiple atlases and provide batch queries across them.

AtlasFetcher

Fetch atlases from multiple sources.

AtlasFileHandler

Handle file operations for atlas fetching.

Functions#

build_reasoned_report_messages(→ list[dict[str, str]])

Construct chat messages for the reasoned report prompt.

build_region_image_request(→ dict[str, Any])

Return prompt components for AIModelInterface.generate_image().

infer_hemisphere(→ str)

Infer the hemisphere from an MNI coordinate.

parse_reasoned_report_output(→ ReasonedReport)

Split the reasoned report narrative and JSON payload.

run_reasoned_report(→ tuple[ReasonedReport, dict[str, ...)

Generate and parse a reasoned report, returning metadata alongside.

deduplicate_datasets(→ nimare.dataset.Dataset | None)

Create a deduplicated dataset across sources using PMIDs.

fetch_datasets(→ dict[str, nimare.dataset.Dataset])

Fetch and convert NiMARE datasets into Dataset objects.

get_studies_for_coordinate(→ list[dict[str, Any]])

Find studies reporting an MNI coordinate across all datasets.

load_deduplicated_dataset(→ nimare.dataset.Dataset | None)

Load a previously saved deduplicated dataset.

prepare_datasets(→ nimare.dataset.Dataset | None)

Load or create a deduplicated NiMARE dataset.

search_studies(→ list[dict[str, Any]])

Search selected datasets for studies reporting an MNI coordinate.

generate_batch_summaries(→ list[str])

Generate summaries for multiple coordinates.

generate_llm_prompt(→ str)

Generate a detailed prompt for language models based on studies.

generate_mni152_image(→ bytes)

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

generate_region_image(→ bytes)

Generate an image for a brain region using an AI model.

generate_summary(→ str)

Generate a text summary for a coordinate based on studies.

generate_summary_async(→ str)

Asynchronously generate a text summary for a coordinate.

stream_summary(→ collections.abc.Iterator[str])

Stream a text summary for a coordinate in chunks.

get_working_directory(→ str)

Return absolute path to the coord2region working directory.

run_pipeline(→ list[PipelineResult])

Run the Coord2Region analysis pipeline.

Package Contents#

class coord2region.AIModelInterface(gemini_api_key: str | None = None, openrouter_api_key: str | None = None, openai_api_key: str | None = None, openai_project: str | None = None, anthropic_api_key: str | None = None, huggingface_api_key: str | None = None, groq_api_key: str | None = None, deepseek_api_key: str | None = None, together_api_key: str | None = None, local_openai_base_url: str | None = None, local_openai_api_key: str | None = None, local_openai_models: dict[str, str] | None = None, enabled_providers: list[str] | None = None)[source]#

Register and dispatch to different AI model providers.

register_provider(provider: ModelProvider | str, *, enabled: bool = True, **config: Any) None[source]#

Register a provider and its models.

Parameters:
  • provider (ModelProvider | str) – Either an instantiated provider or the name of a provider defined in _PROVIDER_CLASSES.

  • enabled (bool, optional) – When False the provider is skipped.

  • **config (dict, optional) – Configuration forwarded to the provider constructor when provider is given as a string.

supports(model: str) bool[source]#

Return whether model is registered with any provider.

supports_batching(model: str) bool[source]#

Return whether the provider for model supports batching.

generate_text(model: str, prompt: PromptType, max_tokens: int = 1000, retries: int = 3) str[source]#

Generate text using a registered model with retry.

Parameters:
  • model (see ModelProvider.generate_text())

  • prompt (see ModelProvider.generate_text())

  • max_tokens (see ModelProvider.generate_text())

  • retries (int) – Number of attempts before raising the final error.

async generate_text_async(model: str, prompt: PromptType, max_tokens: int = 1000, retries: int = 3) str[source]#

Asynchronously generate text using a registered model with retry.

Parameters:
  • model (see ModelProvider.generate_text())

  • prompt (see ModelProvider.generate_text())

  • max_tokens (see ModelProvider.generate_text())

  • retries (int) – Number of attempts before raising the final error.

stream_generate_text(model: str, prompt: PromptType, max_tokens: int = 1000, retries: int = 3) Iterator[str][source]#

Stream generated text chunks from a registered model with retry.

Parameters:
  • model (see) – ModelProvider.stream_generate_text()

  • prompt (see) – ModelProvider.stream_generate_text()

  • max_tokens (see) – ModelProvider.stream_generate_text()

  • retries (int) – Number of attempts before raising the final error.

generate_image(model: str, prompt: str, retries: int = 3, **kwargs: Any) bytes[source]#

Generate an image using a registered model with retry.

list_available_models() list[str][source]#

Return the list of registered model names.

provider_name(model: str) str[source]#

Return the provider class name registered for model.

coord2region.DEFAULT_NEGATIVE_PROMPT = 'cartoon, abstract art, texture noise, extra brains, low resolution, blurry, distorted anatomy,...[source]#
coord2region.DEFAULT_SYSTEM_MESSAGE = Multiline-String[source]#
Show Value
"""You are a careful neuroscience assistant. You convert MNI brain coordinates into clear, evidence-grounded explanations using ONLY the data provided in the prompt (atlas labels, neighbors, and the study list).
If something is missing or conflicting, explicitly report "insufficient_evidence" for that part--do not invent facts or citations."""
class coord2region.ReasonedReport[source]#

Parsed result returned by run_reasoned_report().

narrative: str#
json_text: str | None = None#
json_data: dict[str, Any] | None = None#
json_error: str | None = None#
class coord2region.ReasonedReportContext[source]#

Structured payload describing the coordinate, atlas, and studies.

coordinate_mni: Sequence[float]#
hemisphere: str | None = None#
boundary_proximity_mm: float | None = None#
atlas: dict[str, Any]#
atlas_notes: list[str] = []#
studies: list[dict[str, Any]] = []#
allowed_domains: Sequence[str] | None = None#
format_instructions: list[str] = []#
coord2region.build_reasoned_report_messages(context: ReasonedReportContext, *, system_message: str = DEFAULT_SYSTEM_MESSAGE, max_words: int = 180) list[dict[str, str]][source]#

Construct chat messages for the reasoned report prompt.

Parameters:
  • context (ReasonedReportContext) – Context describing the coordinate, atlas, and studies.

  • system_message (str, optional) – System prompt guiding the AI assistant.

  • max_words (int, optional) – Maximum narrative word count requested from the assistant.

Returns:

Stream-ready chat messages for the AI request.

Return type:

list of dict

coord2region.build_region_image_request(coord: Sequence[float], context: ReasonedReportContext, *, sphere_radius_mm: float = 6, negative_prompt: str = DEFAULT_NEGATIVE_PROMPT) dict[str, Any][source]#

Return prompt components for AIModelInterface.generate_image().

Parameters:
  • coord (sequence of float) – Target MNI coordinate for the image.

  • context (ReasonedReportContext) – Context used to describe the coordinate and atlas.

  • sphere_radius_mm (float, optional) – Radius of the spherical highlight in millimetres.

  • negative_prompt (str, optional) – Negative prompt guiding the image generation.

Returns:

Dictionary containing both structured specification and text prompts.

Return type:

dict

coord2region.infer_hemisphere(coord: Sequence[float]) str[source]#

Infer the hemisphere from an MNI coordinate.

Parameters:

coord (sequence of float) – MNI coordinate to evaluate.

Returns:

"left", "right", "midline", or "unknown" depending on the x coordinate.

Return type:

str

coord2region.parse_reasoned_report_output(output: str) ReasonedReport[source]#

Split the reasoned report narrative and JSON payload.

Parameters:

output (str) – Raw text returned by the AI assistant.

Returns:

Parsed narrative along with optional JSON payload information.

Return type:

ReasonedReport

coord2region.run_reasoned_report(ai: AIModelInterface, model: str, context: ReasonedReportContext, *, max_tokens: int = 512, retries: int = 3, system_message: str = DEFAULT_SYSTEM_MESSAGE) tuple[ReasonedReport, dict[str, Any]][source]#

Generate and parse a reasoned report, returning metadata alongside.

Parameters:
  • ai (AIModelInterface) – AI interface used to generate text.

  • model (str) – Model name to use for the completion.

  • context (ReasonedReportContext) – Structured context describing the coordinate, atlas, and studies.

  • max_tokens (int, optional) – Maximum number of tokens requested from the model.

  • retries (int, optional) – Number of retry attempts for the text generation call.

  • system_message (str, optional) – System message that guides the assistant’s tone and scope.

Returns:

Tuple containing the parsed ReasonedReport and metadata.

Return type:

tuple

class coord2region.AtlasMapper(name: str, vol: ndarray, hdr: ndarray, labels: dict[str, str] | list[str] | ndarray | None = None, indexes: list[int] | ndarray | None = None, subject: str | None = 'fsaverage', regions: dict[str, ndarray] | None = None, subjects_dir: str | None = None, system: str = 'mni')[source]#

Stores a single atlas and provides coordinate conversions.

The atlas may be volumetric (a 3D numpy array with an associated 4x4 affine) or surface-based (a vertices array). In either case, the mapper supports conversions between coordinates, voxel indices, and region labels.

Parameters:
  • name (str) – Identifier for the atlas (e.g., “aal” or “brodmann”).

  • vol (np.ndarray) – A 3D numpy array representing the volumetric atlas.

  • hdr (np.ndarray) – A 4x4 affine transform mapping voxel indices to MNI/world coordinates.

  • labels (dict or list or None, optional) – Region labels. If a dict, keys should be strings for numeric indices and values are region names. If a list/array, it should match indexes.

  • indexes (list or np.ndarray or None, optional) – Region indices corresponding to labels. Not needed if labels is a dict.

  • regions (dict or None, optional) – For surface atlases, mapping of region names to vertex indices.

  • system (str, optional) – The anatomical coordinate space (e.g., “mni” or “tal”).

name#

Atlas identifier.

Type:

str

vol#

Volumetric atlas array.

Type:

np.ndarray

hdr#

Affine transform mapping voxel indices to MNI/world coordinates.

Type:

np.ndarray

labels#

Region labels.

Type:

dict or list or None

indexes#

Region indices corresponding to labels.

Type:

list or np.ndarray or None

regions#

Mapping of region names to vertex indices for surface atlases.

Type:

dict or None

system#

Anatomical coordinate space.

Type:

str

shape#

Shape of the volumetric atlas.

Type:

tuple

name#
labels = None#
indexes = None#
vertex_to_region = None#
system = 'mni'#
region_name_from_index(region_idx: int | str) str[source]#

Return region name from numeric region index.

region_index_from_name(region_name: str) int | str | ndarray[source]#

Return region index from region name.

list_all_regions() list[str][source]#

Return a list of all unique region names in this atlas.

infer_hemisphere(region: int | str) str | None[source]#

Return the hemisphere (‘L’ or ‘R’) inferred from region.

Returns None if not found or not applicable.

convert_system(coord: list[float] | ndarray, source_system: str, target_system: str) ndarray[source]#

Convert coordinates between anatomical systems.

mni_to_voxel(mni_coord: list[float] | ndarray) tuple[int, int, int][source]#

Convert an MNI coordinate to the nearest voxel indices.

The coordinate is transformed using the atlas affine. If it does not exactly match a voxel center, the voxel whose MNI coordinates are closest in Euclidean distance is returned.

mni_to_vertex(mni_coord: list[float] | ndarray, hemi: list[int] | int | None = None) ndarray | int[source]#

Convert an MNI coordinate to the nearest vertex index.

Parameters:
  • mni_coord (list | ndarray) – The target MNI coordinate [x, y, z].

  • hemi (int | list[int] | None) – Hemisphere(s) to restrict the search to. 0 for left, 1 for right. If None (default) both hemispheres are searched.

Returns:

Index/indices of the matching vertex. If no vertex matches exactly, the closest vertex is returned.

Return type:

int | ndarray

convert_to_source(target: list[float] | ndarray, hemi: list[int] | int | None = None, source_system: str = 'mni') ndarray[source]#

Convert a coordinate to the atlas source space.

Parameters:
  • target (list | ndarray) – The coordinate to convert.

  • hemi (int | list[int] | None) – Hemisphere(s) to search when using surface atlases. 0 for left and 1 for right. If None (default) both hemispheres are searched.

  • source_system (str, optional) – Coordinate system of target. Defaults to "mni".

voxel_to_mni(voxel_ijk: list[int] | ndarray) ndarray[source]#

Convert voxel indices (i, j, k) to MNI/world coordinates.

Returns an array of shape (3,).

vertex_to_mni(vertices: list[int] | ndarray, hemi: list[int] | int) ndarray[source]#

Convert vertices to MNI coordinates.

Returns an array of shape (3,).

convert_to_mni(source: list[int] | ndarray, hemi: list[int] | int | None = None) ndarray[source]#

Convert source space coordinates to MNI.

mni_to_region_index(mni_coord: list[float] | ndarray, max_distance: float | None = None, hemi: list[int] | int | None = None, return_distance: bool = False) int | str | tuple[int | str, float][source]#

Return the region index for a given MNI coordinate.

Parameters:
  • mni_coord (list | ndarray) – Target MNI coordinate.

  • max_distance (float | None) – If provided, fall back to the nearest region and apply this distance threshold. Distances greater than max_distance return "Unknown".

  • hemi (int | list[int] | None) – Hemisphere restriction for surface atlases.

  • return_distance (bool) – Whether to also return the distance to the reported region.

mni_to_region_name(mni_coord: list[float] | ndarray, max_distance: float | None = None, hemi: list[int] | int | None = None, return_distance: bool = False) str | tuple[str, float][source]#

Return the region name for a given MNI coordinate.

region_index_to_mni(region_idx: int | str | list[int] | ndarray, hemi: int | None = None) ndarray[source]#

Return MNI coordinates for voxels or vertices in region_idx.

Returns an Nx3 array or an empty array if none found.

region_name_to_mni(region_name: str) ndarray[source]#

Return MNI coordinates for voxels matching region_name.

Returns an Nx3 array or an empty array if no matches are found.

region_centroid(region: int | str) ndarray[source]#

Return the centroid MNI coordinate for a region or vertex index.

distance_to_region_centroid(mni_coord: list[float] | ndarray, region: int | str) float[source]#

Return Euclidean distance from mni_coord to a region centroid.

distance_to_region_boundary(mni_coord: list[float] | ndarray, region: int | str) float[source]#

Return distance from mni_coord to the nearest point in region.

membership_scores(mni_coord: list[float] | ndarray, method: str = 'centroid') dict[int | str, float][source]#

Return normalized membership probabilities for all regions.

save(filename: str) None[source]#

Serialize this AtlasMapper to filename using pickle.

classmethod load(filename: str) AtlasMapper[source]#

Load an AtlasMapper from filename.

Parameters:

filename (str) – Path to the serialized mapper.

Returns:

A reconstructed mapper instance.

Return type:

AtlasMapper

Raises:

ValueError – If the file metadata is incompatible.

class coord2region.BatchAtlasMapper(mapper: AtlasMapper)[source]#

Provide batch (vectorized) conversions for a single atlas mapper.

Parameters:

mapper (AtlasMapper) – The atlas mapper to wrap for vectorized operations.

mapper#

Wrapped atlas mapper used for transformations.

Type:

AtlasMapper

Examples

>>> mapper = AtlasMapper(...)
>>> batch = BatchAtlasMapper(mapper)
>>> regions = batch.batch_mni_to_region_name([[0, 0, 0], [10, -20, 30]])
mapper#
batch_region_name_from_index(values: list[int | str]) list[str][source]#

Return the region name for each index in values.

batch_region_index_from_name(labels: list[str]) list[int | str][source]#

Return the region index for each name in labels.

batch_mni_to_voxel(positions: list[list[float]] | ndarray) list[tuple][source]#

Convert MNI coordinates to voxel indices (i, j, k).

batch_voxel_to_mni(sources: list[list[int]] | ndarray) ndarray[source]#

Convert a batch of voxel indices (i, j, k) to MNI coordinates.

Returns an Nx3 array.

batch_mni_to_region_index(positions: list[list[float]] | ndarray, max_distance: float | None = None, hemi: list[int] | int | None = None) list[int | str][source]#

Return region index for each coordinate, using nearest lookup if needed.

batch_mni_to_region_name(positions: list[list[float]] | ndarray, max_distance: float | None = None, hemi: list[int] | int | None = None) list[str][source]#

Return region name for each coordinate, using nearest lookup if needed.

batch_region_index_to_mni(indices: list[int | str]) list[ndarray][source]#

Return MNI coordinates (Nx3) for each region index.

batch_region_name_to_mni(regions: list[str]) list[ndarray][source]#

Return MNI coordinates (Nx3) for each region name.

class coord2region.MultiAtlasMapper(data_dir: str, atlases: dict[str, dict[str, Any]])[source]#

Manage multiple atlases and provide batch queries across them.

Parameters:
  • data_dir (str) – Directory for atlas data.

  • atlases (dict) – Dictionary mapping atlas names to keyword arguments passed to AtlasFetcher in order to retrieve each atlas.

mappers#

Mapping of atlas names to BatchAtlasMapper instances.

Type:

dict

mappers#
batch_mni_to_region_names(coords: list[list[float]] | ndarray, max_distance: float | None = None, hemi: list[int] | int | None = None) dict[str, list[str]][source]#

Convert a batch of MNI coordinates to region names for all atlases.

Returns a dict {atlas_name: [region_name, region_name, …], …}.

batch_region_name_to_mni(region_names: list[str]) dict[str, list[ndarray]][source]#

Convert a list of region names to MNI coordinates for all atlases.

Returns a dict {atlas_name: [np.array_of_coords_per_region, …], …}.

save(filename: str) None[source]#

Serialize all contained mappers to filename using pickle.

classmethod load(filename: str) MultiAtlasMapper[source]#

Load a MultiAtlasMapper instance from filename.

coord2region.deduplicate_datasets(datasets: dict[str, nimare.dataset.Dataset], save_dir: str | None = None) nimare.dataset.Dataset | None[source]#

Create a deduplicated dataset across sources using PMIDs.

Duplicates are identified via PubMed IDs extracted from study identifiers. Datasets are merged sequentially using merge(), introduced in NiMARE 0.0.9. Older NiMARE versions without merge will return the first dataset unchanged.

Parameters:
  • datasets (Dict[str, Dataset]) – Dictionary of NiMARE Dataset objects to deduplicate.

  • save_dir (Optional[str], default=None) – Directory to save the deduplicated dataset (if provided).

Returns:

A deduplicated NiMARE Dataset combining all inputs, or None if no datasets were provided.

Return type:

Optional[Dataset]

coord2region.fetch_datasets(data_dir: str, sources: list[str] | None = None) dict[str, nimare.dataset.Dataset][source]#

Fetch and convert NiMARE datasets into Dataset objects.

Parameters:
  • data_dir (str) – Directory to store downloaded data.

  • sources (Optional[List[str]], optional) – List of dataset names to download. Valid entries include "neurosynth", "neuroquery" and "nidm_pain". If None (default), all available datasets are fetched.

Returns:

Dictionary of NiMARE Dataset objects indexed by dataset name.

Return type:

Dict[str, Dataset]

coord2region.get_studies_for_coordinate(datasets: dict[str, nimare.dataset.Dataset] | nimare.dataset.Dataset, coord: list[float] | tuple[float, float, float], radius: float = 0, email: str | None = None, sources: list[str] | None = None) list[dict[str, Any]][source]#

Find studies reporting an MNI coordinate across all datasets.

This is a thin wrapper around search_studies() that searches every dataset in datasets. When a single deduplicated dataset is supplied, it is treated as a combined source.

Parameters:
  • datasets (Union[Dict[str, Dataset], Dataset]) – NiMARE Dataset objects keyed by source name, or a single deduplicated Dataset instance.

  • coord (Union[List[float], Tuple[float, float, float]]) – MNI coordinate [x, y, z].

  • radius (float, default=0) – Search radius in millimeters around the coordinate. 0 indicates an exact match.

  • email (Optional[str], optional) – Email address for Entrez (if abstract fetching is enabled).

  • sources (Optional[List[str]], optional) – Restrict the search to the specified dataset names when datasets is a mapping.

coord2region.load_deduplicated_dataset(filepath: str) nimare.dataset.Dataset | None[source]#

Load a previously saved deduplicated dataset.

Parameters:

filepath (str) – Path to the saved dataset file (.pkl.gz).

Returns:

The loaded Dataset object, or None if loading fails.

Return type:

Optional[Dataset]

coord2region.prepare_datasets(data_dir: str | None = None, sources: list[str] | None = None) nimare.dataset.Dataset | None[source]#

Load or create a deduplicated NiMARE dataset.

Parameters:
  • data_dir (str, optional) – Base directory for downloaded datasets and the merged cache. If None (default) the path ~/coord2region is used. Relative paths are interpreted relative to the user’s home directory so that passing "my_cache" stores data in ~/my_cache.

  • sources (Optional[List[str]], optional) – Dataset names to fetch if a cache needs to be built. See fetch_datasets() for valid entries. None (default) fetches all available datasets.

Returns:

The deduplicated NiMARE Dataset object, or None if preparation fails.

Return type:

Optional[Dataset]

coord2region.search_studies(datasets: dict[str, nimare.dataset.Dataset], coord: list[float] | tuple[float, float, float], radius: float = 0, sources: list[str] | None = None, email: str | None = None) list[dict[str, Any]][source]#

Search selected datasets for studies reporting an MNI coordinate.

Parameters:
  • datasets (Dict[str, Dataset]) – NiMARE Dataset objects keyed by source name.

  • coord (Union[List[float], Tuple[float, float, float]]) – MNI coordinate [x, y, z].

  • radius (float, default=0) – Search radius in millimeters around the coordinate. 0 indicates an exact match.

  • sources (Optional[List[str]], optional) – Specific dataset names to query. None searches across all provided datasets.

  • email (Optional[str], optional) – Email address for Entrez (if abstract fetching is enabled).

Returns:

Deduplicated list of study metadata dictionaries.

Return type:

List[Dict[str, Any]]

class coord2region.AtlasFetcher(data_dir: str = None)[source]#

Fetch atlases from multiple sources.

Parameters:

data_dir (str or None, optional) – Directory where downloaded files are cached. Defaults to ~/coord2region.

file_handler#

Helper for file operations.

Type:

AtlasFileHandler

data_dir#

Directory for storing downloaded atlas files.

Type:

str

subjects_dir#

Directory for MNE data.

Type:

str or None

nilearn_data#

Directory for storing Nilearn data.

Type:

str

_atlas_fetchers_nilearn#

Mapping of atlas names to Nilearn fetcher functions.

Type:

dict

_coords_fetchers_nilearn#

Mapping of atlas names to Nilearn coordinate fetchers.

Type:

dict

_atlas_fetchers_mne#

Mapping of atlas names to MNE fetcher functions.

Type:

dict

Examples

>>> fetcher = AtlasFetcher()  
>>> 'aal' in fetcher.list_available_atlases()  
True
ATLAS_URLS#
file_handler#
data_dir = ''#
nilearn_data#
subjects_dir#
list_available_atlases()[source]#

Return a sorted list of available atlas identifiers.

Returns:

Sorted list of available atlas identifiers.

Return type:

list of str

Raises:

None

Examples

>>> fetcher = AtlasFetcher()  
>>> isinstance(fetcher.list_available_atlases(), list)  
True
fetch_atlas(atlas_name: str, atlas_url: str = None, prefer: str = 'nilearn', **kwargs)[source]#

Fetch an atlas given an identifier.

The identifier may be a URL, local file path, or a known atlas name. The prefer flag allows choosing the primary source ("nilearn" or "mne").

Parameters:
  • atlas_name (str) – The name of the atlas or a URL.

  • atlas_url (str or None, optional) – Explicit URL of the atlas file.

  • prefer ({"nilearn", "mne"}, optional) – Preferred source for fetching the atlas.

  • **kwargs – Additional keyword arguments for fetching.

Returns:

Atlas volume, header, labels, and description.

Return type:

dict

Raises:

Examples

>>> fetcher = AtlasFetcher()  
>>> out = fetcher.fetch_atlas('aal')  
>>> out['labels'][0]  
'Precentral_L'
coord2region.IMAGE_PROMPT_TEMPLATES: dict[str, str][source]#
coord2region.LLM_PROMPT_TEMPLATES: dict[str, str][source]#
coord2region.generate_batch_summaries(ai: AIModelInterface, coord_studies_pairs: list[tuple[list[float] | tuple[float, float, float], list[dict[str, Any]]]], prompt_type: str = 'summary', model: str = 'gemini-2.0-flash', custom_prompt: str | None = None, max_tokens: int = 1000) list[str][source]#

Generate summaries for multiple coordinates.

Parameters:
  • ai (AIModelInterface) – AI backend used to create the summaries.

  • coord_studies_pairs (list of tuple) – Coordinate-study pairs to summarise.

  • prompt_type (str, optional) – Template key used for each summary prompt.

  • model (str, optional) – Model used for text generation. Defaults to "gemini-2.0-flash".

  • custom_prompt (str, optional) – Template string overriding the built-in prompt for every coordinate.

  • max_tokens (int, optional) – Maximum tokens requested from each AI call.

Returns:

Generated summaries for the provided coordinate pairs.

Return type:

list of str

coord2region.generate_llm_prompt(studies: list[dict[str, Any]], coordinate: list[float] | tuple[float, float, float], prompt_type: str = 'summary', prompt_template: str | None = None) str[source]#

Generate a detailed prompt for language models based on studies.

Parameters:
  • studies (list of dict) – Study metadata dictionaries that describe the activation evidence.

  • coordinate (sequence of float) – MNI coordinate used for formatting the prompt header.

  • prompt_type (str, optional) – Key that selects a built-in template from LLM_PROMPT_TEMPLATES.

  • prompt_template (str, optional) – Custom template string requiring coord and studies placeholders.

Returns:

Fully formatted prompt ready for submission to a language model.

Return type:

str

coord2region.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.generate_region_image(ai: AIModelInterface, coordinate: list[float] | tuple[float, float, float], region_info: dict[str, Any], image_type: str = 'anatomical', model: str = 'stabilityai/stable-diffusion-2', include_atlas_labels: bool = True, prompt_template: str | None = None, retries: int = 3, watermark: bool = True, **kwargs: Any) bytes[source]#

Generate an image for a brain region using an AI model.

Parameters:
  • ai (AIModelInterface) – Interface used to generate images.

  • coordinate (sequence of float) – MNI coordinate for the target region.

  • region_info (dict) – Dictionary containing region summary and atlas labels.

  • image_type (str, optional) – Type of image to generate. Defaults to "anatomical".

  • model (str, optional) – Name of the AI model to use. Defaults to "stabilityai/stable-diffusion-2".

  • include_atlas_labels (bool, optional) – Whether to include atlas label context in the prompt. Defaults to True.

  • prompt_template (str, optional) – Custom template overriding default prompts.

  • retries (int, optional) – Number of times to retry generation on failure. Defaults to 3.

  • watermark (bool, optional) – When True (default), a semi-transparent watermark is applied to the resulting image.

  • **kwargs (Any) – Additional keyword arguments passed to the underlying AI provider.

Returns:

PNG image bytes, optionally watermarked.

Return type:

bytes

coord2region.generate_summary(ai: AIModelInterface, studies: list[dict[str, Any]], coordinate: list[float] | tuple[float, float, float], prompt_type: str = 'summary', model: str = 'gemini-2.0-flash', atlas_labels: dict[str, str] | None = None, custom_prompt: str | None = None, max_tokens: int = 1000) str[source]#

Generate a text summary for a coordinate based on studies.

Parameters:
  • ai (AIModelInterface) – AI backend used to create the summary.

  • studies (list of dict) – Studies reporting activation at the target coordinate.

  • coordinate (sequence of float) – MNI coordinate around which the summary should focus.

  • prompt_type (str, optional) – Key into LLM_PROMPT_TEMPLATES. Use "custom" with custom_prompt to provide a bespoke template.

  • model (str, optional) – Name of the text generation model. Defaults to "gemini-2.0-flash".

  • atlas_labels (dict, optional) – Atlas-derived labels to prepend to the prompt for extra context.

  • custom_prompt (str, optional) – Template string formatted with coord and studies placeholders.

  • max_tokens (int, optional) – Maximum number of tokens requested from the language model.

Returns:

Textual summary returned by the AI model.

Return type:

str

async coord2region.generate_summary_async(ai: AIModelInterface, studies: list[dict[str, Any]], coordinate: list[float] | tuple[float, float, float], prompt_type: str = 'summary', model: str = 'gemini-2.0-flash', atlas_labels: dict[str, str] | None = None, custom_prompt: str | None = None, max_tokens: int = 1000) str[source]#

Asynchronously generate a text summary for a coordinate.

Parameters:
  • ai (AIModelInterface) – AI backend used to create the summary asynchronously.

  • studies (list of dict) – Studies reporting activation at the target coordinate.

  • coordinate (sequence of float) – MNI coordinate for the summary.

  • prompt_type (str, optional) – Prompt template key defaulting to "summary".

  • model (str, optional) – Model name, defaulting to "gemini-2.0-flash".

  • atlas_labels (dict, optional) – Atlas-derived labels to include in the prompt.

  • custom_prompt (str, optional) – User-supplied template applied via str.format.

  • max_tokens (int, optional) – Maximum number of tokens requested for the summary.

Returns:

Generated summary text.

Return type:

str

coord2region.stream_summary(ai: AIModelInterface, studies: list[dict[str, Any]], coordinate: list[float] | tuple[float, float, float], prompt_type: str = 'summary', model: str = 'gemini-2.0-flash', atlas_labels: dict[str, str] | None = None, custom_prompt: str | None = None, max_tokens: int = 1000) Iterator[str][source]#

Stream a text summary for a coordinate in chunks.

Parameters:
  • ai (AIModelInterface) – Streaming AI backend used to generate the summary.

  • studies (list of dict) – Studies reporting activation at the target coordinate.

  • coordinate (sequence of float) – MNI coordinate for the summary.

  • prompt_type (str, optional) – Prompt template key defaulting to "summary".

  • model (str, optional) – Model name, defaulting to "gemini-2.0-flash".

  • atlas_labels (dict, optional) – Atlas-derived labels to include in the prompt.

  • custom_prompt (str, optional) – User-supplied template applied via str.format.

  • max_tokens (int, optional) – Maximum number of tokens requested for the summary.

Returns:

Chunks of text yielded by the streaming AI backend.

Return type:

iterator of str

coord2region.get_working_directory(base: str | None = None) str[source]#

Return absolute path to the coord2region working directory.

Parameters:

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

Returns:

Absolute path to the working directory. The directory is created if it does not already exist.

Return type:

str

coord2region.run_pipeline(inputs: Sequence[Any], input_type: str, outputs: Sequence[str], output_format: str | None = None, output_name: str | None = None, image_backend: str = 'ai', *, config: dict[str, Any] | None = None, async_mode: bool = False, progress_callback: Callable[[int, int, PipelineResult], None] | None = None) list[PipelineResult][source]#

Run the Coord2Region analysis pipeline.

Parameters:
  • inputs (sequence) – Iterable containing the inputs. The interpretation depends on input_type.

  • input_type ({"coords", "region_names"}) – Specifies how to treat inputs.

  • outputs (sequence of) – {“region_labels”, “summaries”, “images”, “raw_studies”, “mni_coordinates”} Requested pieces of information for each input item. The "mni_coordinates" option is only supported when input_type == "region_names".

  • output_format ({"json", "pickle", "csv", "pdf", "directory"}, optional) – When provided, results are exported to the specified format.

  • output_name (str, optional) – File or directory name to use when exporting results. The name is created inside the working directory’s results subfolder. Required when output_format is specified.

  • image_backend ({"ai", "nilearn", "both"}, optional) – Backend used to generate images when "images" is requested.

  • prompt_template (str, optional) – Template to use for AI image generation prompts. One of: ” ‘anatomical’, ‘functional’, ‘schematic’, ‘artistic’, or ‘custom’.

  • async_mode (bool, optional) – When True, processing occurs concurrently using asyncio and summaries are generated with generate_summary_async().

  • progress_callback (callable, optional) – Function invoked after each input is processed. Receives the number of completed items, the total count and the PipelineResult for the processed item. When None, progress is logged via logging.

Returns:

One result object per item in inputs.

Return type:

list of PipelineResult

class coord2region.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'