neurolang.NeurolangPDL#
- class neurolang.NeurolangPDL(chase_class=<class 'nl_core.datalog.chase.Chase'>, probabilistic_solvers=(<function solve_succ_query>, <function solve_succ_query>, <function solve_succ_query_sdd_direct>), probabilistic_marg_solvers=(<function solve_marg_query>, <function solve_marg_query>, <function solve_marg_query>), check_qbased_pfact_tuple_unicity=False, solver_class=None)#
Probabilistic Datalog frontend.
Complements
QueryBuilderDatalogwith probabilistic capabilities:add extensional probabilistic facts and choices;
solve probabilistic queries.
- Parameters:
- Return type:
- __init__(chase_class=<class 'nl_core.datalog.chase.Chase'>, probabilistic_solvers=(<function solve_succ_query>, <function solve_succ_query>, <function solve_succ_query_sdd_direct>), probabilistic_marg_solvers=(<function solve_marg_query>, <function solve_marg_query>, <function solve_marg_query>), check_qbased_pfact_tuple_unicity=False, solver_class=None)#
Query builder with probabilistic capabilities
- Parameters:
- chase_classType[Chase], optional
used to compute deterministic solutions, by default Chase
- probabilistic_solversTuple[Callable], optional
used to compute probabilistic solutions, the order of the elements indicates the priority of usage of the solver. by default (lifted_solve_succ_query, wmc_solve_succ_query)
- probabilistic_marg_solversTuple[Callable], optional
used to compute probabilistic solutions, by default (lifted_solve_marg_query, wmc_solve_marg_query)
- solver_classType, optional
Custom solver class to use instead of RegionFrontendCPLogicSolver. Allows injecting custom mixins (e.g. with dimension_type_predicate_names tailored from engine YAML config).
- Returns:
- NeurolangPDL
see description
- Parameters:
- Return type:
Methods
__init__([chase_class, ...])Query builder with probabilistic capabilities
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_constraint(antecedent, consequent)Creates an right implication of the consequent by the antecedent and adds the rule to the current program:
add_probabilistic_choice_from_tuples(iterable)Add probabilistic choice from tuples whose first element contains the probability label attached to that tuple.
add_probabilistic_facts_from_tuples(iterable)Add probabilistic facts from tuples whose first element contains the probability label attached to that tuple.
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
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).
Add uniform probabilistic choice over values in the iterable.
all(quantified_variable, body)Universal predicate on the body.
Computes a Datalog program in classical syntax.
create_region(spatial_image[, label, ...])Creates an ExplicitVBR out of the voxels of a dense spatial_image with specified label
del_symbol(name)Deletes the symbol with parameter name from the symbol_table
execute_datalog_program(code[, ...])Execute a Datalog program in classical syntax.
execute_squall_program(code[, ...])Execute a SQUALL (controlled English) program.
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
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_ontology(paths[, ...])Loads and parses ontology stored at the specified paths, and store them into attributes
magic_sets_rewrite_program(query_expression)make_implicit_regions_explicit(affine, dim)Raises NotImplementedError for now
new_region_symbol([name])Returns symbol with type Region
new_symbol([type_, name])Creates a symbol and associated expression, optionally specifying it's type and/or name
predicate_parameter_names(predicate_name)Get the names of the parameters for the given predicate
query(*args[, show_rewritten, dry_run, show_ra])Performs an inferential query on the database.
Clears current symbol table
solve_all([show_ra])Returns a dictionary of "predicate_name": "Content" for all elements in the solution of the Datalog program.
sphere(center, radius[, name])Creates a Region symbol associated with the spherical volume described by its center and volume
Attributes
Returns the list of Front End Expressions that have currently been declared in the program, or through the program's constraints
Dynamic context that can be used to create symbols to write a Datalog program.
Returns the list of symbols corresponding to callables
Returns the list of symbol names with Region type
Returns the list of symbol names with set_type
Dynamic context that can be used to create symbols to write a Datalog program.
Projector to the program_ir's symbol_table
Iterator through the symbol's names
Returns a list of the types of the symbols currently in the table (type can be Unknown)
- 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
- 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
- Parameters:
name (str)
spatial_image (DataobjImage)
- Return type:
Symbol
- add_constraint(antecedent, consequent)#
Creates an right implication of the consequent by the antecedent and adds the rule to the current program:
antecedent -> consequent
- Parameters:
- antecedentfe.Expression
see description, will be processed to a logic form before creating the right implication rule
- consequentfe.Expression
see description, will be processed to a logic form before creating the right implication rule
- Returns:
- fe.Expression
see description
- Parameters:
antecedent (Expression)
consequent (Expression)
- Return type:
Expression
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderDatalog(program_ir=p_ir) >>> nl.add_tuple_set([(1, 2), (2, 2)], name="l") l: typing.AbstractSet[typing.Tuple[int, int]] = [(1, 2), (2, 2)] >>> with nl.scope as e: ... nl.add_constraint(e.l2[e.x, e.y], e.l2[e.x])
- add_probabilistic_choice_from_tuples(iterable, type_=<class 'nl_expr.type_system.Unknown'>, name=None)#
Add probabilistic choice from tuples whose first element contains the probability label attached to that tuple. In the tuple (p, a, b, …), p is the float probability of tuple (a, b, …) to be True and all remaining tuples to be False in any possible world.
Note that, contrary to a list of probabilistic facts, this represents a choice among possible values for the predicate, meaning that tuples in the set are mutually exclusive. See example for details.
- Parameters:
- iterableIterable[Tuple[Any, …]]
the first float number represents the probability of the tuple constituted of the remaining elements Note that the float probabilities must sum to 1.
- type_Type, optional
type for resulting AbstractSet if None will be inferred from the data, by default ir.Unknown
- nameOptional[str], optional
name for the resulting fe.Symbol, if None will be fresh, by default None
- Returns:
- fe.Symbol
see description
- Raises:
- DistributionDoesNotSumToOneError
if float probabilities do not sum to 1.
- Parameters:
- Return type:
Symbol
Warning
Typing for the iterable is improper, true -but yet unsupported- typing should be Iterable[Tuple[float, Any, …]] See examples
Examples
>>> nl = NeurolangPDL() >>> p = [(0.8, 'a', 'b'), (0.2, 'b', 'c')] >>> nl.add_probabilistic_choice_from_tuples(p, name="P") P: typing.AbstractSet[typing.Tuple[float, str, str]] = [(0.8, 'a', 'b'), (0.2, 'b', 'c')]
- Adds the probabilistic choice:
P((a, b)) : 0.8 v P((b, c)) : 0.2 <- T
- add_probabilistic_facts_from_tuples(iterable, type_=<class 'nl_expr.type_system.Unknown'>, name=None)#
Add probabilistic facts from tuples whose first element contains the probability label attached to that tuple. In the tuple (p, a, b, …), p is the float probability of tuple (a, b, …) to be True in any possible world.
Note that each tuple from the iterable is independent from the others, meaning that multiple tuples can be True in the same possible world, contrary to a probabilistic choice. See example for details.
- Parameters:
- iterableIterable[Tuple[Any, …]]
the first float number represents the probability of the tuple constituted of the remaining elements
- type_Type, optional
type for resulting AbstractSet if None will be inferred from the data, by default ir.Unknown
- nameOptional[str], optional
name for the resulting fe.Symbol, if None will be fresh, by default None
- Returns:
- fe.Symbol
see description
- Parameters:
- Return type:
Symbol
Warning
Typing for the iterable is improper, true -but yet unsupported in Python typing- typing should be Iterable[Tuple[float, Any, …]] See examples
Examples
>>> nl = NeurolangPDL() >>> p = [(0.8, 'a', 'b'), (0.7, 'b', 'c')] >>> nl.add_probabilistic_facts_from_tuples(p, name="P") P: typing.AbstractSet[typing.Tuple[float, str]] = [(0.8, 'a', 'b'), (0.7, 'b', 'c')]
- Adds the probabilistic facts:
P((a, b)) : 0.8 <- T P((b, c)) : 0.7 <- T
- add_region(region, name=None)#
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
- Parameters:
region (Expression)
name (str | None)
- Return type:
Symbol
- add_region_set(region_set, name=None)#
Creates an AbstractSet fe.Symbol containing the elements specified in the iterable with a List[Tuple[Region]] format
- add_symbol(value, name=None, type_=<class 'nl_expr.type_system.Unknown'>)#
Creates a symbol with given value and adds it to the current symbol_table. Can typically 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
- Parameters:
- Return type:
Symbol
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> @nl.add_symbol ... def g(x: int) -> int: ... return x + 2 >>> nl.get_symbol("g") g: typing.Callable[[int], int] = <function g at ...> >>> nl.add_symbol(3, "x") >>> nl.get_symbol("x") x: <class 'int'> = 3
- add_tuple_set(iterable, type_=<class 'nl_expr.type_system.Unknown'>, name=None)#
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:
- iterableIterable
typically a list of tuples of values, other formats will be interpreted as the latter
- 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
- Parameters:
- Return type:
Symbol
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderDatalog(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,)]
- add_uniform_probabilistic_choice_over_set(iterable, type_=<class 'nl_expr.type_system.Unknown'>, name=None)#
Add uniform probabilistic choice over values in the iterable.
Every tuple in the iterable will be assigned the same probability to be True, with all remaining tuples False, in any possible world.
Note that, contrary to a list of probabilistic facts, this represents a choice among possible values for the predicate, meaning that tuples in the set are mutually exclusive.
See example for details.
- Parameters:
- iterableIterable[Tuple[Any, …]]
typically List[Tuple[Any, …]], other types of Iterable will be cast as lists
- type_Type, optional
type for resulting AbstractSet if None will be inferred from the data, by default ir.Unknown
- nameOptional[str], optional
name for the resulting fe.Symbol, if None will be fresh, by default None
- Returns:
- fe.Symbol
see description
- Parameters:
- Return type:
Symbol
Examples
>>> nl = NeurolangPDL() >>> p = [('a',), ('b',)] >>> nl.add_uniform_probabilistic_choice_over_set(p, name="P") P: typing.AbstractSet[typing.Tuple[float, str]] = [(0.5, 'a'), (0.5, 'b')]
- Adds the probabilistic choice:
P(a) : 0.5 v P(b) : 0.5 <- T
- all(quantified_variable, body)#
Universal predicate on the body. The predicate will be cosidered satisfied if all instances of quantified_variable satisfy 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.
- Parameters:
quantified_variable (Symbol)
body (Expression)
- Return type:
All
- compute_datalog_program_for_autocompletion(code, autocompletion_code)#
Computes a Datalog program in classical syntax. Returns the next accepted tokens of the program.
- Parameters:
- codestring
Datalog program.
- autocompletion_codestr
Datalog program for autocompletion.
- Parameters:
code (str)
- Return type:
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderDatalog(program_ir=p_ir) >>> prog_complete = ''' ... l2(x, y) :- l(x, y), (x == y) ... ans(x) :- l2(x, y) ... ''' >>> prog = ''' ... l2(x, y) :- l(x, y), (x == y) ... ans(x) :- ... ''' >>> with nl.environment as e: ... q = nl.compute_datalog_program_for_autocompletion(prog_complete, prog) >>> q ... { ... 'Signs': {'@', '∃', '('}, 'Numbers': set(), 'Text': set(), 'Operators': {'¬', '~'}, ... 'Cmd_identifier': set(), 'Functions': {'lambda'}, 'Identifier_regexp': set(), ... 'Reserved words': {'exists', 'EXISTS'}, 'Boleans': {'⊤', '⊥', 'False', 'True'}, ... 'Expression symbols': set(), 'Python string': set(), ... 'Strings': {'<identifier regular expression>', '<command identifier>'}, 'commands': set(), ... 'functions': set(), 'base symbols': set(), 'query symbols': set() ... }
- static create_region(spatial_image, label=1, prebuild_tree=False)#
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
- Parameters:
spatial_image (DataobjImage)
label (int)
prebuild_tree (bool)
- Return type:
ExplicitVBR
- property current_program: List[Expression]#
Returns the list of Front End Expressions that have currently been declared in the program, or through the program’s constraints
- Returns:
- List[fe.Expression]
see description
Examples
>>> nl = NeurolangPDL() >>> P = nl.add_uniform_probabilistic_choice_over_set( ... [("a",), ("b",), ("c",)], name="P" ... ) >>> Q = nl.add_uniform_probabilistic_choice_over_set( ... [("a",), ("d",), ("c",)], name="Q" ... ) >>> with nl.scope as e: ... e.Z[e.x, e.PROB[e.x]] = P[e.x] & Q[e.x] ... cp = nl.current_program >>> cp [ Z(x, ( PROB(x) )) ← ( P(x) ) ∧ ( Q(x) ) ]
- del_symbol(name)#
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
- Parameters:
name (str)
- Return type:
None
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> nl.add_symbol(3, "x") x: <class 'int'> = 3 >>> nl.get_symbol("x") x: <class 'int'> = 3 >>> nl.del_symbol("x") >>> nl.get_symbol("x") ValueError: Symbol x not defined
- 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
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> with nl.environment as e: ... e.x = 3 >>> "x" in nl True >>> nl.symbols.x == 3 True
- execute_datalog_program(code, show_rewritten=False, dry_run=False, show_ra=False)#
Execute a Datalog program in classical syntax. If the program contains a query, in the form ans(x) :- R(x), then this query is executed against the program and the result is returned. Otherwise returns None.
- Parameters:
- codestring
Datalog program.
- show_rewrittenbool
If True, print the Datalog program after magic-sets rewriting.
- dry_runbool
If True, print the rewritten program and return None without running the chase.
- show_rabool or ShowRAOptions
If True, print the named relational algebra expression of each rule instead of evaluating it. A
ShowRAOptionsselects how the plans are displayed.
- Parameters:
- Return type:
None | bool | RelationalAlgebraFrozenSet
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderDatalog(program_ir=p_ir) >>> nl.add_tuple_set([(1, 2), (2, 2)], name="l") l: typing.AbstractSet[typing.Tuple[int, int]] = [(1, 2), (2, 2)] >>> prog = ''' ... l2(x, y) :- l(x, y), (x == y) ... ans(x) :- l2(x, y) ... ''' >>> with nl.environment as e: ... q = nl.execute_datalog_program(prog) >>> q ... q: typing.AbstractSet[typing.Tuple[int]] = [(2,)]
- execute_squall_program(code, show_rewritten=False, dry_run=False, show_ra=False)#
Execute a SQUALL (controlled English) program.
Parses code as a SQUALL program, walks rule definitions into the engine, and executes
obtainqueries the same way execute_datalog_program handlesans(x) :- R(x)— by building a fresh helper implication and delegating to self.query (or self._execute_query for probabilistic engines).- Parameters:
- codestr
SQUALL program text. May contain any mixture of
define as …rule definitions andobtain …queries.- show_rewrittenbool
If True, print the Datalog program after magic-sets rewriting.
- dry_runbool
If True, print the rewritten program and return None without running the chase.
- show_rabool or ShowRAOptions
If True, print the named relational algebra expression of each rule instead of evaluating it. A
ShowRAOptionsselects how the plans are displayed.
- Returns:
- None
When code contains only rule definitions (no
obtain).- NamedRelationalAlgebraFrozenSet
When code contains exactly one
obtainclause.- Dict[str, NamedRelationalAlgebraFrozenSet]
When code contains two or more
obtainclauses, keyed"obtain_0","obtain_1", … in declaration order.
- Parameters:
- Return type:
None | NamedRelationalAlgebraFrozenSet | Dict[str, NamedRelationalAlgebraFrozenSet]
Examples
>>> from neurolang.frontend import NeurolangPDL >>> nl = NeurolangPDL() >>> _ = nl.add_tuple_set([("alice",), ("bob",)], name="person") >>> _ = nl.add_tuple_set([("alice",)], name="plays") >>> nl.execute_squall_program( ... "define as Active every person that plays." ... ) is None True >>> result = nl.execute_squall_program("obtain every Person that plays.") >>> sorted(result.as_pandas_dataframe().iloc[:, 0].tolist()) ['alice']
- exists(quantified_variable, body)#
Existential predicate on the body. The predicate will be cosidered satisfied if any instance of quantified_variable satisfies 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.
- Parameters:
quantified_variable (Symbol)
body (Expression)
- Return type:
Exists
- property functions: List[str]#
Returns the list of symbols corresponding to callables
- Returns:
- List[str]
list of symbols of type leq Callable
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> def f(x: int) -> int: ... return x+2 >>> nl.add_symbol(f, "f") f: typing.Callable[[int], int] = <function f at ...> >>> "f" in nl.functions True >>> nl.add_symbol(3, "x") x: <class 'int'> = 3 >>> "x" in nl.functions False
- get_symbol(symbol_name)#
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
- Parameters:
symbol_name (str | Expression)
- Return type:
Symbol
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> nl.add_symbol(3, "x") >>> nl.get_symbol("x") x: <class 'int'> = 3
- load_neurosynth_mni_peaks_reported(data_dir, name=None, version=7, convert_study_ids=False)#
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.
- Parameters:
- Return type:
Symbol
- load_neurosynth_study_ids(data_dir, name=None, version=7, convert_study_ids=False)#
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.
- Parameters:
- Return type:
Symbol
- load_neurosynth_term_study_associations(data_dir, name=None, version=7, convert_study_ids=False, tfidf_threshold=None)#
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.
- Parameters:
- Return type:
Symbol
- load_ontology(paths, connector_symbol_name=None, format=None, individuals=False, names='local')#
Loads and parses ontology stored at the specified paths, and store them into attributes
- Parameters:
- pathstyping.Union[str, List[str]]
where the ontology files are stored
- connector_symbol_namestr
name to be used in the connector_symbol. if None, the name is randomly generated
- formatstr or list of str
rdflib format of the files (
xml,turtle,nt…), guessed from their extensions when None.- individualsbool
also load every triple as a fact:
s p oisp(s, o)ands rdf:type Cis alsoC(s), IRIs being the strings of their full IRI. The subclasses of the ontology apply to these facts:Super(x)holds for an instance of a subclass.- namesstr
localnames classes and properties by their local name (Dean,rdf-schema:label);prefixedby the prefixes the files declare (pv:name,rdfs:label), else by their full IRI.
- Returns:
- Expression
the new connector_symbol, to be used in the query program.
- Parameters:
- Return type:
None
- make_implicit_regions_explicit(affine, dim)#
Raises NotImplementedError for now
- new_region_symbol(name=None)#
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
- Parameters:
name (str | None)
- Return type:
Symbol
- new_symbol(type_=<class 'nl_expr.type_system.Unknown'>, name=None)#
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
- Parameters:
- Return type:
Expression
- predicate_parameter_names(predicate_name)#
Get the names of the parameters for the given predicate
- query(*args, show_rewritten=False, dry_run=False, show_ra=False)#
Performs an inferential query on the database. There are three modalities 1. If there is only one argument, the query returns True or False depending on whether the query could be inferred. 2. If there are two arguments and the first is a tuple of fe.Symbol, it returns the set of results meeting the query in the second argument. 3. If the first argument is a predicate (e.g. Q(x)) it performs the query, adds it to the engine memory, and returns the corresponding symbol. See example for 3 modalities
- Parameters:
- show_rewrittenbool
If True, print the Datalog program after magic-sets rewriting.
- dry_runbool
If True, print the rewritten program and return immediately without running the chase.
- show_rabool or ShowRAOptions
If True, print the named relational algebra expression of each rule instead of evaluating it. A
ShowRAOptionsselects how the plans are displayed.
- Returns:
- Union[bool, RelationalAlgebraFrozenSet, fe.Symbol]
read the descrpition.
- Parameters:
- Return type:
bool | RelationalAlgebraFrozenSet | Symbol
Examples
Note: example ran with pandas backend >>> p_ir = DatalogProgram() >>> nl = QueryBuilderDatalog(program_ir=p_ir) >>> nl.add_tuple_set([(1, 2), (2, 2)], name=”l”) l: typing.AbstractSet[typing.Tuple[int, int]] = [(1, 2), (2, 2)] >>> with nl.environment as e: … e.l2[e.x, e.y] = e.l[e.x, e.y] & (e.x == e.y) … s1 = nl.query(e.l2[e.x, e.y]) … s2 = nl.query((e.x,), e.l2[e.x, e.y]) … s3 = nl.query(e.l3[e.x], e.l2[e.x, e.y])
- 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
- reset_program()#
Clears current symbol table
- Return type:
None
- 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
Examples
>>> p_ir = DatalogProgram() >>> nl = QueryBuilderBase(program_ir=p_ir) >>> with nl.scope as e: ... e.x = 3 >>> "x" in nl False
- solve_all(show_ra=False)#
Returns a dictionary of “predicate_name”: “Content” for all elements in the solution of the Datalog program. Typically, probabilities are abstracted and processed similar to symbols, though of different nature (see examples)
- Parameters:
- show_rabool or ShowRAOptions, optional
If True, print the named RA expression of each rule instead of evaluating it, and return an empty solution. A
ShowRAOptionsselects how the plans are displayed.
- Returns:
- Dict[str, NamedRelationalAlgebraFrozenSet]
extensional and intentional facts that have been derived through the current program, optionally with probabilities
- Return type:
Examples
Note: example ran with pandas backend >>> nl = NeurolangPDL() >>> P = nl.add_uniform_probabilistic_choice_over_set( … [(“a”,), (“b”,), (“c”,)], name=”P” … ) >>> Q = nl.add_uniform_probabilistic_choice_over_set( … [(“a”,), (“d”,), (“c”,)], name=”Q” … ) >>> with nl.scope as e: … e.Z[e.PROB[e.x], e.x] = P[e.x] & Q[e.x] … solution = nl.solve_all()
- sphere(center, radius, name=None)#
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
- Parameters:
- Return type:
Symbol
- property symbol_table: TypedSymbolTable#
Projector to the program_ir’s symbol_table