coord2region#
Coord2Region: map brain coordinates to regions, studies, and AI insights.
Submodules#
Attributes#
Classes#
Register and dispatch to different AI model providers. |
|
Parsed result returned by |
|
Structured payload describing the coordinate, atlas, and studies. |
|
Stores a single atlas and provides coordinate conversions. |
|
Provide batch (vectorized) conversions for a single atlas mapper. |
|
Manage multiple atlases and provide batch queries across them. |
|
Fetch atlases from multiple sources. |
|
Handle file operations for atlas fetching. |
Functions#
|
Construct chat messages for the reasoned report prompt. |
|
Return prompt components for |
|
Infer the hemisphere from an MNI coordinate. |
|
Split the reasoned report narrative and JSON payload. |
|
Generate and parse a reasoned report, returning metadata alongside. |
|
Create a deduplicated dataset across sources using PMIDs. |
|
Fetch and convert NiMARE datasets into |
|
Find studies reporting an MNI coordinate across all datasets. |
|
Load a previously saved deduplicated dataset. |
|
Load or create a deduplicated NiMARE dataset. |
|
Search selected datasets for studies reporting an MNI coordinate. |
|
Generate summaries for multiple coordinates. |
|
Generate a detailed prompt for language models based on studies. |
|
Return a PNG image of a sphere drawn on the MNI152 template. |
|
Generate an image for a brain region using an AI model. |
|
Generate a text summary for a coordinate based on studies. |
|
Asynchronously generate a text summary for a coordinate. |
|
Stream a text summary for a coordinate in chunks. |
|
Return absolute path to the coord2region working directory. |
|
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
Falsethe provider is skipped.**config (dict, optional) – Configuration forwarded to the provider constructor when
provideris given as a string.
- supports_batching(model: str) bool[source]#
Return whether the provider for
modelsupports 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.
- 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().
- class coord2region.ReasonedReportContext[source]#
Structured payload describing the coordinate, atlas, and studies.
- 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:
- 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:
- coord2region.infer_hemisphere(coord: Sequence[float]) str[source]#
Infer the hemisphere from an MNI coordinate.
- 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:
- 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
ReasonedReportand metadata.- Return type:
- 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 iflabelsis 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”).
- vol#
Volumetric atlas array.
- Type:
np.ndarray
- hdr#
Affine transform mapping voxel indices to MNI/world coordinates.
- Type:
np.ndarray
- 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.
- 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:
- 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:
- 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_distancereturn"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_coordto a region centroid.
- distance_to_region_boundary(mni_coord: list[float] | ndarray, region: int | str) float[source]#
Return distance from
mni_coordto the nearest point inregion.
- membership_scores(mni_coord: list[float] | ndarray, method: str = 'centroid') dict[int | str, float][source]#
Return normalized membership probabilities for all regions.
- classmethod load(filename: str) AtlasMapper[source]#
Load an
AtlasMapperfromfilename.- Parameters:
filename (str) – Path to the serialized mapper.
- Returns:
A reconstructed mapper instance.
- Return type:
- 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:
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.
- 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
AtlasFetcherin order to retrieve each atlas.
- mappers#
Mapping of atlas names to
BatchAtlasMapperinstances.- Type:
- 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, …], …}.
- classmethod load(filename: str) MultiAtlasMapper[source]#
Load a
MultiAtlasMapperinstance fromfilename.
- 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 withoutmergewill return the first dataset unchanged.- Parameters:
- Returns:
A deduplicated NiMARE
Datasetcombining all inputs, orNoneif 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
Datasetobjects.- Parameters:
- Returns:
Dictionary of NiMARE
Datasetobjects 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 indatasets. When a single deduplicated dataset is supplied, it is treated as a combined source.- Parameters:
datasets (Union[Dict[str, Dataset], Dataset]) – NiMARE
Datasetobjects keyed by source name, or a single deduplicatedDatasetinstance.coord (Union[List[float], Tuple[float, float, float]]) – MNI coordinate
[x, y, z].radius (float, default=0) – Search radius in millimeters around the coordinate.
0indicates 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
datasetsis 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
Datasetobject, orNoneif 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~/coord2regionis 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
Datasetobject, orNoneif 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
Datasetobjects 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.
0indicates an exact match.sources (Optional[List[str]], optional) – Specific dataset names to query.
Nonesearches 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:
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.
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
preferflag allows choosing the primary source ("nilearn"or"mne").- Parameters:
- Returns:
Atlas volume, header, labels, and description.
- Return type:
- Raises:
ValueError – If the atlas name is not recognized.
FileNotFoundError – If the atlas file or labels file is not found.
Exception – If there is an error during fetching.
Examples
>>> fetcher = AtlasFetcher() >>> out = fetcher.fetch_atlas('aal') >>> out['labels'][0] 'Precentral_L'
- 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:
- 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
coordandstudiesplaceholders.
- Returns:
Fully formatted prompt ready for submission to a language model.
- Return type:
- 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:
- Returns:
PNG-encoded image bytes representing the sphere on the MNI152 template.
- Return type:
- 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:
- 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"withcustom_promptto 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
coordandstudiesplaceholders.max_tokens (int, optional) – Maximum number of tokens requested from the language model.
- Returns:
Textual summary returned by the AI model.
- Return type:
- 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:
- 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~/coord2regionis 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:
- 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 wheninput_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
resultssubfolder. Required whenoutput_formatis 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 withgenerate_summary_async().progress_callback (callable, optional) – Function invoked after each input is processed. Receives the number of completed items, the total count and the
PipelineResultfor the processed item. WhenNone, progress is logged vialogging.
- 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. 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'