neurolang.frontend.query_resolution module

Query Builder Base, Region and Neurosynth Mixins

Base classes to construct Datalog programs. Capabilities to declare, manage and manipulate symbols. Mixins provide capabilities related to brain volumes and Neurosynth metadata manipulation

class neurolang.frontend.query_resolution.NeuroSynthMixin

Bases: object

Neurosynth is a platform for large-scale, automated synthesis of functional magnetic resonance imaging (fMRI) data. see https://neurosynth.org/ This Mixin complements a QueryBuilderBase with methods related to coordinate-based meta-analysis (CBMA) data loading.

Methods

load_neurosynth_mni_peaks_reported(data_dir)

Load the coordinates for the peaks reported by studies in the Neurosynth dataset.

load_neurosynth_study_ids(data_dir[, name, ...])

Load all study ids (PMIDs) that are part of the Neurosynth database.

load_neurosynth_term_study_associations(data_dir)

Load TF-IDF values for each (term, study) association within the Neurosynth database.

load_neurosynth_mni_peaks_reported(data_dir: Path, name: str | None = None, version: int = 7, convert_study_ids: bool = False) Symbol

Load the coordinates for the peaks reported by studies in the Neurosynth dataset. Coordinates for the peaks are in MNI space.

This loads a tuple of (id, int, int, int) values for each reported peak.

Parameters:
namestr (optional)

Name of the symbol associated with the resulting set of (study id, voxel id) tuples. Randomly generated by default

Returns:
fe.Symbol

fe.Symbol associated to the resulting set.

load_neurosynth_study_ids(data_dir: Path, name: str | None = None, version: int = 7, convert_study_ids: bool = False) Symbol

Load all study ids (PMIDs) that are part of the Neurosynth database.

Parameters:
data_dirPath

the path for the directory where downloaded data should be saved.

nameOptional[str], optional

the name for the symbol, randomly generated if None

versionint, optional

the neurosynth data version, by default 7

convert_study_idsbool, optional

if True, cast study ids as StudyID, by default False

Returns:
fe.Symbol

fe.Symbol associated to the resulting set.

load_neurosynth_term_study_associations(data_dir: Path, name: str | None = None, version: int = 7, convert_study_ids: bool = False, tfidf_threshold: float | None = None) Symbol

Load TF-IDF values for each (term, study) association within the Neurosynth database.

This loads a tuple of (id, str, float) for each (term, study) association.

Parameters:
data_dirPath

the path for the directory where downloaded data should be saved.

nameOptional[str], optional

the name for the symbol, randomly generated if None

versionint, optional

the neurosynth data version, by default 7

convert_study_idsbool, optional

if True, cast study ids as StudyID, by default False

tfidf_thresholdOptional[float], optional

the minimum tfidf value for the (term, study) associations, by default None

Returns:
fe.Symbol

fe.Symbol associated to the resulting set.

class neurolang.frontend.query_resolution.QueryBuilderBase(program_ir: DatalogProgram, logic_programming: bool = False)

Bases: object

Base class to construct Datalog programs. Capabilities to declare, manage and manipulate symbols.

Attributes:
environment

Dynamic context that can be used to create symbols to write a Datalog program.

functions

Returns the list of symbols corresponding to callables

scope

Dynamic context that can be used to create symbols to write a Datalog program.

symbol_table

Projector to the program_ir’s symbol_table

symbols

Iterator through the symbol’s names

types

Returns a list of the types of the symbols currently

Methods

add_symbol(value[, name, type_])

Creates a symbol with given value and adds it to the current symbol_table.

add_tuple_set(iterable[, type_, name])

Creates an AbstractSet fe.Symbol containing the elements specified in the iterable with a List[Tuple[Any, ...]] format (see examples).

all(quantified_variable, body)

Universal predicate on the body.

del_symbol(name)

Deletes the symbol with parameter name from the symbol_table

exists(quantified_variable, body)

Existential predicate on the body.

get_symbol(symbol_name)

Retrieves symbol via its name, either providing a fe.Expression with the correct name or the name itself

new_symbol([type_, name])

Creates a symbol and associated expression, optionally specifying it's type and/or name

add_symbol(value: ~neurolang.frontend.query_resolution_expressions.Expression | ~neurolang.expressions.Constant | ~typing.Any, name: str | None = None, type_: ~typing.Type = <class 'neurolang.type_system.Unknown'>) Symbol

Creates a symbol with given value and adds it to the current symbol_table. Can typicaly be used to decorate callables, or add an ir.Constant to the program.

Parameters:
valueUnion[fe.Expression, ir.Constant, Any]

value of the symbol to add. If not an fe.Expression, will be cast as an ir.Constant

namestr, optional

overrides automatic naming of the symbol, by default None

Returns:
fe.Symbol

created symbol

add_tuple_set(iterable: ~typing.Iterable | ~typing.Iterable[~typing.Tuple[~typing.Any, ...]], type_: ~typing.Type = <class 'neurolang.type_system.Unknown'>, name: str | None = None) Symbol

Creates an AbstractSet fe.Symbol containing the elements specified in the iterable with a List[Tuple[Any, …]] format (see examples). Typically used to create extensional facts from existing databases

Parameters:
iterableUnion[Iterable, Iterable[Tuple[Any, …]]]

typically a list of tuples of values, other formats will be interpreted as the latter (see examples)

type_Type, optional

type of elements for the tuples, if not specified will be inferred from the first element, by default Unknown

namestr, optional

name for the AbstractSet symbol, by default None

Returns:
fe.Symbol

see description

Examples

>>> p_ir = DatalogProgram()
>>> nl = QueryBuilderBase(program_ir=p_ir)
>>> nl.add_tuple_set([(1, 2), (3, 4)], name="l1")
l1: typing.AbstractSet[typing.Tuple[int, int]] =             [(1, 2), (3, 4)]
>>> nl.add_tuple_set([[1, 2, 3], (3, 4)], name="l2")
l2: typing.AbstractSet[typing.Tuple[int, int, float]] =             [(1, 2, 3.0), (3, 4, nan)]
>>> nl.add_tuple_set((1, 2, 3), name="l3")
l3: typing.AbstractSet[typing.Tuple[int]] =             [(1,), (2,), (3,)]
all(quantified_variable: Symbol, body: Expression) All

Universal predicate on the body. The predicate will be cosidered satisfied if all instances of quantified_variable satify body.

Parameters:
quantified_variablefe.Symbol

universally-quantified variable

body: fe.Expression

first order logic proposition which to be satisfied by the universal quatifier.

Returns:
fe.All

representation of the universal predicate.

del_symbol(name: str) None

Deletes the symbol with parameter name from the symbol_table

Parameters:
namestr

Name of the symbol to delete

Raises:
ValueError

if no symbol could be found with given name

property environment: QuerySymbolsProxy

Dynamic context that can be used to create symbols to write a Datalog program. Contrary to a scope, symbols stay in the symbol_table when exiting the environment context

Yields:
QuerySymbolsProxy

in dynamic mode, can be used to create symbols on-the-fly

exists(quantified_variable: Symbol, body: Expression) Exists

Existential predicate on the body. The predicate will be cosidered satisfied if any instance of quantified_variable satifies body.

Parameters:
quantified_variablefe.Symbol

existentially-quantified variable

body: fe.Expression

first order logic proposition which to be satisfied by the existential quatifier.

Returns:
fe.Exists

representation of the existential predicate.

property functions: List[str]

Returns the list of symbols corresponding to callables

Returns:
List[str]

list of symbols of type leq Callable

get_symbol(symbol_name: str | Expression) Symbol

Retrieves symbol via its name, either providing a fe.Expression with the correct name or the name itself

Parameters:
symbol_nameUnion[str, fe.Expression]

name of the symbol to be retrieved. If of type fe.Expression, expression’s name is used as the name

Returns:
fe.Symbol

symbol corresponding to the input name

Raises:
ValueError

if no symbol could be found with given name

new_symbol(type_: ~typing.Any | ~typing.Tuple[~typing.Any, ...] | ~typing.List[~typing.Any] = <class 'neurolang.type_system.Unknown'>, name: str | None = None) Expression

Creates a symbol and associated expression, optionally specifying it’s type and/or name

Parameters:
type_Union[Any, Tuple[Any, …], List[Any]], optional

type of the created symbol, by default Unknown if Iterable, will be cast to a Tuple

namestr, optional

name of the created symbol, by default None

Returns:
fe.Expression

associated to the created symbol

property scope: QuerySymbolsProxy

Dynamic context that can be used to create symbols to write a Datalog program. Contrary to an environment, symbols disappear from the symbol_table when exiting the scope context

Yields:
QuerySymbolsProxy

in dynamic mode, can be used to create symbols on-the-fly

property symbol_table: TypedSymbolTable

Projector to the program_ir’s symbol_table

property symbols: Iterator[str]

Iterator through the symbol’s names

property types: List[Type]

Returns a list of the types of the symbols currently in the table (type can be Unknown)

Returns:
List[Union[fe.Expression, Type]]

List of types or Unknown if symbol has no known type

class neurolang.frontend.query_resolution.QuerySymbolsProxy(query_builder)

Bases: object

Class useful to create symbols on-the-fly Typically used in QueryBuilderBase contexts as the yielded value to write a program. Various methods are projectors to QueryBuilderBase methods

class neurolang.frontend.query_resolution.RegionMixin

Bases: object

Mixin complementing a QueryBuilderBase with methods specific to the manipulation of brain volumes: regions, atlases, etc…

Attributes:
region_names

Returns the list of symbol names with Region type

region_set_names

Returns the list of symbol names with set_type

Methods

add_atlas_set(name, atlas_labels, spatial_image)

Creates an atlas set: 1- for each region specified by a label and name in atlas_labels, creates associated ExplicitVBR and symbols Tuple[region_name: str, Region] 2- groups regions in an AbstractSet[Tuple[str, Region]] symbol with specified name

add_region(region[, name])

Adds region fe.Symbol to symbol_table

add_region_set(region_set[, name])

Creates an AbstractSet fe.Symbol containing the elements specified in the iterable with a List[Tuple[Region]] format

create_region(spatial_image[, label, ...])

Creates an ExplicitVBR out of the voxels of a dense spatial_image with specified label

make_implicit_regions_explicit(affine, dim)

Raises NotImplementedError for now

new_region_symbol([name])

Returns symbol with type Region

sphere(center, radius[, name])

Creates a Region symbol associated with the spherical volume described by its center and volume

add_atlas_set(name: str, atlas_labels: Dict[int, str], spatial_image: DataobjImage) Symbol

Creates an atlas set: 1- for each region specified by a label and name in atlas_labels, creates associated ExplicitVBR and symbols Tuple[region_name: str, Region] 2- groups regions in an AbstractSet[Tuple[str, Region]] symbol with specified name

Parameters:
namestr

name for the output atlas symbol

atlas_labelsDict[int, str]

specifies which voxels to select in the spatial_image, and the associated region name

spatial_imageDataobjImage

contains the .dataobj array ofinterest

Returns:
fe.Symbol

see description

add_region(region: Expression, name: str | None = None) Symbol

Adds region fe.Symbol to symbol_table

Parameters:
regionfe.Expression

should be of the program_ir’s type

nameOptional[str], optional

symbol’s name, if None will be fresh, by default None

Returns:
fe.Symbol

symbol added to the symbol_table

Raises:
ValueError

if region is not of program_ir’s type

add_region_set(region_set: Iterable, name: str | None = None) Symbol

Creates an AbstractSet fe.Symbol containing the elements specified in the iterable with a List[Tuple[Region]] format

Parameters:
region_setIterable

Typically List[Tuple[Region]]

nameOptional[str], optional

symbol’s name, if None will be fresh, by default None

Returns:
fe.Symbol

see description

static create_region(spatial_image: DataobjImage, label: int = 1, prebuild_tree: bool = False) ExplicitVBR

Creates an ExplicitVBR out of the voxels of a dense spatial_image with specified label

Parameters:
spatial_imageDataobjImage

contains the .dataobj array of interest

labelint, optional

selects which voxel to put in the output, by default 1

prebuild_treebool, optional

see ExplicitVBR, by default False

Returns:
ExplicitVBR

see description

make_implicit_regions_explicit(affine, dim)

Raises NotImplementedError for now

new_region_symbol(name: str | None = None) Symbol

Returns symbol with type Region

Parameters:
nameOptional[str], optional

symbol’s name, if None will be fresh, by default None

Returns:
fe.Symbol

see description

property region_names: List[str]

Returns the list of symbol names with Region type

Returns:
List[str]

list of symbol names from symbol_table

property region_set_names: List[str]

Returns the list of symbol names with set_type

Returns:
List[str]

list of symbol names from symbol_table

sphere(center: ndarray | Iterable[int], radius: int, name: str | None = None) Symbol

Creates a Region symbol associated with the spherical volume described by its center and volume

Parameters:
centerUnion[np.ndarray, Iterable[int]]

3D center of the sphere

radiusint

radius of the sphere

nameOptional[str], optional

name of the output symbol, if None will be fresh, by default None

Returns:
fe.Symbol

see description