SQUALL: Controlled English for NeuroLang#
NeuroLang’s SQUALL frontend (also referred to as NSQUALL, for NeuroLang SQUALL) lets you write NeuroLang queries and rules in plain English sentences instead of symbolic Datalog notation. Under the hood, each sentence is translated to a NeuroLang logical expression using Montague semantics in Continuation-Passing Style, building on the original SQUALL language by Sébastien Ferré [Ferre2012]. The probabilistic query answering that SQUALL programs compile to is described in [Zanitti2023].
References
S. Ferré. SQUALL: A Controlled Natural Language for Querying and Updating RDF Graphs. Controlled Natural Languages (CNL), 2012. LNCS 7427, p. 11-25, Springer.
G. E. Zanitti, Y. Soto, V. Iovene, M. V. Martinez, R. O. Rodriguez, G. I. Simari, D. Wassermann. Scalable Query Answering Under Uncertainty to Neuroscientific Ontological Knowledge: The NeuroLang Approach. Neuroinformatics, 21(2), 407-425, 2023.
This tutorial is built around a single real-world neuroimaging problem: Bayes Factor decoding of the right fusiform gyrus. Each section introduces exactly the SQUALL feature needed for the next step, so by the end you will understand every line of a complete probabilistic SQUALL program.
Every example runs in the REPL (Using the REPL), in the browser or in
neurolang-query -i --engine neurosynth, after .mode squall (or the
SQUALL choice of the page’s language selector): type it at the prompt, or
follow Run in the browser REPL under it. An example that uses the rules of
earlier ones has no such link: type the earlier ones first.
The full program we will build, on the studies of Neurosynth and the Destrieux atlas:
define as Activates (?s; ?r) where Destrieux_activated (?r, ?s).
define as Region (?r) where Destrieux (?r, ?x).
define as Active_region every Region that a Selected_study activates.
define as Region_probability with inferred probability
every Active_region.
define as Mentioned_term every Term that a Selected_study mentions.
define as Term_probability with inferred probability
every Mentioned_term.
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
define as Joint_probability with inferred probability
every Cooccurrence (?r; ?t).
define as Bayes_factor (?r; ?t; ?bf)
where Joint_probability (?r, ?t, ?p_rt)
and Region_probability (?r, ?p_r)
and Term_probability (?t, ?p_t)
and ?bf is (?p_rt / ?p_r) / ((?p_t - ?p_rt) / (1.0 - ?p_r)).
obtain every Bayes_factor (?r; ?t; ?bf)
where ?r is 'R G oc temp lat fusifor' as BF.
Part 1: The Bayes Factor Problem#
1.1 What We Are Computing#
Given a set of brain-imaging studies, each reporting activation peaks in some anatomical region and associated with cognitive terms, we want to find which terms are specifically associated with the right fusiform gyrus.
The Bayes Factor quantifies the evidence:
where \(P(R,T)\) is the joint probability that a randomly chosen study activates region \(R\) and mentions term \(T\), \(P(R)\) is the marginal probability of activating \(R\), and \(P(T)\) of mentioning \(T\).
We will compute all three probability distributions as SQUALL rules, then combine them with arithmetic to produce \(\mathrm{BF}\) — all inside NeuroLang with zero post-hoc pandas computation.
1.2 The Data#
The program uses four relations of the neurosynth engine (.predicates
lists them all):
study(study_id)The 14 371 studies of Neurosynth, by PubMed id.
mentions(study_id, term)The terms each study mentions (TF-IDF above 0.03).
term(term)The terms of Neurosynth’s vocabulary.
selected_study(study_id)A uniform probabilistic choice over the studies: each is the selected one with probability \(1/N\) (10.2 defines such a choice in SQUALL).
and two it defines from the Destrieux atlas, the anatomical regions and the studies whose peaks fall in them, with the bare predicate calls of 7.1:
define as Activates (?s; ?r) where Destrieux_activated (?r, ?s).
define as Region (?r) where Destrieux (?r, ?x).
The region we look at is 'R G oc temp lat fusifor', the right fusiform gyrus in the
labels of the atlas.
1.3 Running a SQUALL Program#
In the REPL, .mode squall switches to SQUALL; in the browser, the
language selector over the box does. A sentence ends with a full stop: a
define as adds a rule to the session (the REPL answers defined
active_region/1), and an obtain runs a query and shows its answer.
.datalog shows the Datalog that the last query was translated to.
From Python, a SQUALL program is the text of execute_squall_program
(SQUALL from Python).
Now let’s build this program step by step, starting from the simplest building blocks.
Part 2: Nouns and Basic Queries#
2.1 Nouns as Relations#
A noun in SQUALL names a relation. Region refers to the region EDB,
Term to term, Selected_study to selected_study.
The simplest query asks for all entities in a relation:
obtain every Region.
Result: all anatomical regions in the data set.
The obtain keyword introduces a query. every is a determiner
that asks for all values. The sentence reads like plain English.
2.2 Determiners#
SQUALL supports four determiners:
Keyword |
Meaning |
Example |
|---|---|---|
|
Universal |
|
|
Existential |
|
|
Negative |
|
|
Anaphoric |
|
In the Bayes Factor program, a Selected_study is the existential choice
that quantifies over studies — it introduces a study variable without binding
it in the rule head.
2.3 Named Variables — ?label#
Variables can be named with ?name labels, which bind the variable so it
can be reused in the same rule:
obtain every Joint_probability (?r; ?t; ?p).
Here ?r, ?t, and ?p are bound to the three columns of the
joint_probability relation.
2.4 Tuple Subjects and Wildcards#
When a noun denotes a multi-column relation, a parenthesised tuple of labels follows the noun:
define as Selected_peak every Peak_reported (?i; ?j; ?k; ?s).
The ; separator matches the column structure. Use _ for columns you
want to match but not project into the rule head:
define as Activation every Peak_reported (?i; ?j; ?k; _).
Each _ creates a distinct fresh variable that exists in the query body
but is dropped from the head.
2.5 String Literals#
String literals use single or double quotes; both mean the same:
obtain every study that is 'neuro study'.
obtain every study that is "neuro study".
Use double quotes for a string containing an apostrophe, and single quotes for one containing double quotes:
obtain every Study that mentions "Parkinson's disease".
This is the syntax we will later use to select the target region:
obtain every Bayes_factor (?r; ?t; ?bf)
where ?r is 'R G oc temp lat fusifor' as BF.
The where ?r is '...' clause filters ?r to a fixed constant string.
2.6 Reserved Words and Backtick Quoting#
SQUALL reserves many common English words (every, a, the,
that, is, has, not, and, or, where, who,
which, etc.). If a relation name coincides with a reserved word, wrap it
in backticks:
obtain every `from`.
Variable names use the ? prefix and may contain letters, digits, and
underscores. They cannot clash with reserved words because of the prefix.
Part 3: Verbs and Relations#
Now we add verbs to connect nouns into sentences.
3.1 Transitive Verbs — The Bayes Factor Relations#
The Bayes Factor problem needs two binary relations:
activates(study, region) and mentions(study, term).
In SQUALL, a transitive verb maps subject→first argument, object→second argument, in natural English order:
every Region that a Selected_study activates
Reads as “for every region r, there exists a selected study s such that activates(s, r)” — the study (subject) activates the region (object).
Similarly:
every Term that a Selected_study mentions
Reads as “for every term t, there exists a selected study s such that mentions(s, t)”.
3.2 Argument Order and the ~ Inverse#
The ~ prefix swaps the arguments of a verb: the subject is matched
to the second column and the object to the first. Use it when
the sentence reads naturally from the other side of the relation. With
mentions(study, term):
obtain every Term that ~mentions a Study.
reads “every term t such that some study s has mentions(s, t)”: the
term is the subject of ~mentions and lands in the second column. The
same holds when the verb follows its object, as in
every Voxel that a Study ~reports which maps to
reports(voxel, study) — useful when the EDB stores the voxel first.
With more than two arguments, ~ reverses all of them.
Our Bayes Factor data stores activates(study, region) in natural order
(study first, region second), so no ~ is needed.
3.3 Intransitive Verbs#
An intransitive verb takes only a subject:
define as PlayerPerson every person that plays.
Result: all persons who play.
3.4 Possessive VP — has NP2#
has DET noun2 expresses a possessive verb phrase — the subject has a
thing related to it by the binary noun noun2:
define as Author every person that has a publication.
Result: persons for whom a matching entry in the binary publication
relation exists.
With an optional restrictive relative clause on the possessed noun:
define as ProlificAuthor every person
that has a publication that is highly_cited.
3.5 Existential — there is NP#
there is NP / there are NP asserts that at least one entity matching
the noun phrase exists:
define as HasPlayer every Game that there is a Player.
Useful when the body needs a purely existential check without introducing a join variable.
3.6 Auxiliaries — does / is / has#
does not VP expresses negation-as-failure:
define as NotPlaying every person that does not plays.
Result: persons who do not appear in the plays relation. Note the
ungrammatical does not plays: SQUALL does not inflect verbs, so the verb
must be spelled exactly as the relation name (plays); does not play
would look for a relation called play.
3.7 Function-Call Guard — Predicate(?x, ?y) holds#
An arbitrary relation can be invoked in a relative clause with explicit arguments:
define as Close every Pair (?x; ?y) where euclidean(?x, ?y) holds.
Here ?x and ?y are bound by the tuple labels of Pair, and
euclidean(x, y) is called as a guard in the body. We will see a more
general form of this in section 7.1.
Note
Section 7.1 introduces a closely related pattern — bare predicate
calls with the syntax PredicateName (?a, ?b, ?c) without a verb —
which is used in the Bayes Factor rule body.
3.8 Verbs with Several Objects#
A verb followed by several objects, joined by prepositions, maps to a
relation with one column per argument, in order: subject first, then each
object. With weighs(study, term, weight):
obtain every Study ?s that weighs 'pain' with ?w.
reads weighs(s, 'pain', w). The prepositions (with, by,
to, …) only separate the objects; they do not select columns. An
adjective takes objects in the same way: every Voxel that is reported
by a Study reads reported(voxel, study).
The relation must have exactly that many columns. To match a ternary
relation without a verb, use the noun with a tuple subject instead
(section 10.4): where (?s; ?t; ?w) is a Term_weight.
Part 4: Defining Rules#
Now we move from queries to rule definitions, building the intermediate predicates that the Bayes Factor program needs.
4.1 Simple Unary Rules#
The define as prefix turns a sentence into a Datalog rule:
define as Active_region every Region that a Selected_study activates.
This creates a new predicate active_region(region). In Datalog notation:
active_region(r) :- region(r), selected_study(s), activates(s, r).
The rule says: r is an active region if there exists a selected study s that activates r.
The Bayes Factor program defines two such unary intermediate rules:
define as Active_region every Region that a Selected_study activates.
define as Mentioned_term every Term that a Selected_study mentions.
These two create unary predicates active_region(region) and
mentioned_term(term). They are the building blocks for the marginal
probabilities.
4.2 Multi-Variable Rules — Compound Quantifiers#
To build the joint distribution we need a binary relation:
cooccurrence(region, term) linking each study’s region and term.
The compound quantifier syntax chains for every clauses:
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
This creates:
cooccurrence(r, t) :-
region(r), term(t), selected_study(s),
activates(s, r), mentions(s, t).
The and between quantifiers binds both Region and Term into the
rule head, producing a binary predicate.
4.3 Anaphora — the Noun#
Inside the where clause, the Region and the Term refer back to
the variables introduced by for every Region and for every Term.
This is called anaphora resolution — the reader (human or machine)
understands which variable is meant from context.
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
Without anaphora you would need explicit variables:
define as Cooccurrence
for every Region and for every Term
where a Selected_study ?s activates ?r and mentions ?t.
The anaphoric form is more natural and is what the Bayes Factor program uses.
Note
Anaphora works within a single rule only — there is no inter-sentence
scope yet. Each rule resolves the X from the for every X in its
own head.
Anaphora also works across the conditioned to / given boundary
in conditional probability rules — see section 5.3 for details.
4.4 The ; Separator for Multi-Variable Heads#
An alternative to compound quantifiers uses a ;-separated tuple after
define as:
define as reported for every Study ?s ; with every Voxel ?v that ?s reports.
This is equivalent but reads less naturally than the compound quantifier with anaphora.
4.5 Multiple Rules in One Program#
Rules are separated by a full stop. All the Bayes Factor define
sentences are passed as a single program string:
define as Active_region every Region that a Selected_study activates.
define as Mentioned_term every Term that a Selected_study mentions.
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
...
obtain every Bayes_factor (?r; ?t; ?bf)
where ?r is 'R G oc temp lat fusifor' as BF.
4.6 Fork Quantification — for NP , S#
The for NP , S (fork) construction places a noun phrase as an
outer sentence-level quantifier over an otherwise independent
sentence S:
for every Person ?p, ?p plays.
This reads: “for every person p, p plays”.
The fork form is useful when S is too complex to embed inside a relative
clause.
define as Reported
for every Study ?s,
a Voxel ?v that ?s reports.
Here the fork binds ?s in the outer scope so it can be referenced by the
inner sentence.
4.7 Comparisons#
Relative clauses can include comparisons using the keywords greater,
lower, equal, optionally combined with equal and not,
followed by than or to and an operand:
define as Large every Item that has an item_count greater equal than 2.
Supported forms:
* greater than
* greater equal than
* lower than
* lower equal than
* equal to
* not equal to
4.8 Euclidean Distance Bounds#
The built-in euclidean function takes the coordinates of two points,
those of the first point followed by those of the second one, and returns
their Euclidean distance. Bounding it by a number relates the points of
two relations that are close to each other:
define as Close (?i; ?j; ?k; ?s) where Voxel (?i, ?j, ?k)
and Peak_reported (?i1, ?j1, ?k1, ?s)
and euclidean(?i, ?j, ?k, ?i1, ?j1, ?k1) is lower than 2.
The same bound can name the distance, which then can be used by the head
of the rule: and ?d is euclidean(?i, ?j, ?k, ?i1, ?j1, ?k1) and ?d is
lower than 2. lower than is a strict bound and lower equal than
a non-strict one, and the reserved uppercase EUCLIDEAN behaves as
euclidean. When both points are ranged by stored relations, as here,
the pairs of points within the distance are computed once, when the rule
is defined, rather than by comparing every voxel with every peak; the
coordinates of each point must then be distinct variables. A point of
numbers, such as euclidean(?x, ?y, ?z, -24, -4, -20), counts as
ranged by a stored relation of its own, so the points within the
distance of a given coordinate are found the same way.
Part 5: Probabilistic Rules#
Now we introduce probability — the core of the Bayes Factor computation.
5.1 Probabilistic Facts — probably#
The probably keyword creates a probabilistic fact with a fresh
probability variable:
define as probably reliable every study.
This defines a unary probabilistic predicate reliable(study), each tuple
being an independent probabilistic fact whose probability is a fresh
variable.
5.2 Inferred Probability — with inferred probability#
with inferred probability on a rule head generates a marginal probability
over the joint distribution. This is the key construct for the Bayes Factor:
define as Region_probability with inferred probability
every Active_region.
define as Term_probability with inferred probability
every Mentioned_term.
define as Joint_probability with inferred probability
every Cooccurrence (?r; ?t).
Each produces a predicate with an added probability column:
region_probability(region, PROB(region))— marginal \(P(R)\)term_probability(term, PROB(term))— marginal \(P(T)\)joint_probability(region, term, PROB(region, term))— joint \(P(R,T)\)
The probability is the fraction of studies that satisfy the body given the
probabilistic Selected_study choice. The tuple (?r; ?t) in the
Cooccurrence head tells the solver which variables to keep after
marginalising over studies — the study variable introduced by
a Selected_study in the body is quantified away.
Note
The body of each with inferred probability rule must be a
deterministic predicate. The probabilistic solver combines it with
the selected_study choice automatically. This is why we create
Active_region, Mentioned_term, and Cooccurrence as separate
deterministic rules first — they flatten the existential study variable
before the probabilistic step.
5.3 Conditional Probability — with probability … conditioned to#
with probability … conditioned to computes a conditional probability
(it compiles to the same conditional query as MARG[… // …] in
Datalog: A Rule-Based Query Language for NeuroLang):
define as Activation_given_term with probability
every Activation (?i; ?j; ?k; _)
conditioned to every Term_association (?s; ?t; _) such that ?t is 'auditory'.
Here _ drops the study-id column from the conditioned side and the
TF-IDF weight from the conditioning side. The result has columns
(i, j, k, probability) where the last column is
P(activation(i,j,k) | term_association(s,t) ∧ t = 'auditory').
The keyword given is a synonym for conditioned to:
define as Activation_map with inferred probability every Active_voxel (?i; ?j; ?k; _)
given every Study_term (_; ?t) where ?t is 'emotion'.
This reads: “the inferred probability of activation at (i, j, k) given the study term is ‘emotion’”.
Note
When using conditional probabilities with tuple-labeled relations, the arity of the conditioned
and conditioning noun-phrases must exactly match the corresponding
relation arities. Use _ for columns that exist in the body relation
but should not appear in the head.
Anaphora across the condition boundary#
When the Noun appears on the conditioning side (after given /
conditioned to), it refers back to a noun introduced in the conditioned
side — the main clause:
define as Published with probability every Voxel
that a SelectedStudy reports
given the SelectedStudy mentions 'emotion'.
Here the SelectedStudy in the given clause refers to the same
study variable introduced by a SelectedStudy in the main clause.
The resolver collects the X markers from the conditioning side, finds
a matching noun predicate on the conditioned side, and unifies the
variables:
Conditioned side:
∃ s. voxel(v) ∧ selected_study(s) ∧ reports(s, v)
Conditioning side (before resolution):
∃ s'. selected_study(s') ∧ mentions(s', 'emotion')
After resolution:
Condition(∃ s. voxel(v) ∧ selected_study(s) ∧ reports(s, v),
selected_study(s) ∧ mentions(s, 'emotion'))
After existential lifting (the ∃ s must scope over the whole
Condition):
∃ s. Condition(voxel(v) ∧ selected_study(s) ∧ reports(s, v),
selected_study(s) ∧ mentions(s, 'emotion'))
The variable s is now shared across both sides, so the SelectedStudy
and a SelectedStudy refer to the same study. This is the only resolution
direction supported: the on the conditioning side resolves against a noun
on the conditioned side. See section 4.3 for anaphora within compound
quantifiers (the reverse direction).
5.4 Explicit Probability — with probability NP#
with probability followed by a conditioned/conditioning noun-phrase pair
also supports explicit naming:
define as Activation_given_term with probability
every Activation (?i; ?j; ?k; _)
conditioned to every Term_association (?s; ?t; _) such that ?t is 'auditory'.
5.5 Caveats — Existentials in Body#
When the body contains existentials (e.g. a Selected_study), create an
intermediate deterministic rule first, then define the probabilistic rule
over it. This is exactly the pattern used in the Bayes Factor program:
Active_region— deterministic, flattens the existentialRegion_probability with inferred probability every Active_region— probabilistic, adds the probability column
Part 6: Connectives#
6.1 Conjunction — and#
Multiple conditions in a rule body are joined with and:
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
The activates the Region and mentions the Term is a conjunction of two
verb phrases sharing the same subject (the study).
When predicates are split across separate rules, chain them with an intermediate:
define as Player every person that plays.
define as PlayAndRun every Player that runs.
6.2 Disjunction — or#
With or, the subject must satisfy at least one condition:
define as PlayOrRun every person that plays or runs.
6.3 Negation — not#
does not VP expresses negation-as-failure (see section 3.6):
define as NotPlaying every person that does not plays.
Part 7: The Bayes Factor Formula#
Now we reach the heart of the program — computing the Bayes Factor from the three probability distributions.
7.1 Bare Predicate Calls#
To reference Joint_probability, Region_probability, and
Term_probability inside a rule body, we use the bare predicate call
syntax — the predicate name followed by parenthesised arguments, no verb:
define as Bayes_factor (?r; ?t; ?bf)
where Joint_probability (?r, ?t, ?p_rt)
and Region_probability (?r, ?p_r)
and Term_probability (?t, ?p_t)
and ?bf is (?p_rt / ?p_r) / ((?p_t - ?p_rt) / (1.0 - ?p_r)).
Joint_probability (?r, ?t, ?p_rt) calls the joint_probability
predicate with arguments ?r, ?t, binding ?p_rt to the
probability column. The arguments use comma separators (a, b, c).
The predicate name matches the rule name defined elsewhere in the program
(case-insensitive).
This form is the multi-predicate equivalent of the function-call guard in
section 3.7, but without the holds keyword — it is used in rule bodies
to join several predicates with explicit variable bindings.
7.2 Arithmetic Expressions#
The last conjunct in the rule assigns the result of an arithmetic expression
to ?bf:
?bf is (?p_rt / ?p_r) / ((?p_t - ?p_rt) / (1.0 - ?p_r))
This is the Bayes Factor formula from section 1.1, expressed directly in
SQUALL. The expression supports +, -, *, / with standard
operator precedence; parentheses are supported for grouping.
The is clause translates to an eq builtin with the arithmetic
expression tree as the second argument. The expression is evaluated during
the chase using Python’s operator module functions (truediv,
sub, etc.).
Note
Arithmetic expressions currently support numeric types only.
Non-numeric ?label is 'string' is handled as a constant equality
(see section 2.5). The two uses share the same is keyword but
produce different internal representations.
7.3 The Complete Bayes Factor Rule#
define as Bayes_factor (?r; ?t; ?bf)
where Joint_probability (?r, ?t, ?p_rt)
and Region_probability (?r, ?p_r)
and Term_probability (?t, ?p_t)
and ?bf is (?p_rt / ?p_r) / ((?p_t - ?p_rt) / (1.0 - ?p_r)).
In Datalog notation:
bayes_factor(r, t, bf) :-
joint_probability(r, t, p_rt),
region_probability(r, p_r),
term_probability(t, p_t),
eq(bf, truediv(truediv(p_rt, p_r), truediv(sub(p_t, p_rt), sub(1.0, p_r)))).
Part 8: Querying and Optimization#
8.1 The obtain Clause#
The obtain clause executes a query and shows its results. Unlike
define as, which creates a rule for later use, obtain immediately
solves the query.
obtain every Bayes_factor (?r; ?t; ?bf)
where ?r is 'R G oc temp lat fusifor' as BF.
This asks for all (r, t, bf) triples where r is the target region.
8.2 Named Results — as Name#
The as BF suffix names the result relation: the REPL shows the answer
under that name, and with several obtain clauses in one submission, each
answer under its own. .sort bf:desc shows the largest Bayes factors
first. From Python, the answers come back by name
(SQUALL from Python).
8.3 Magic-Sets Optimization#
The where ?r is 'R G oc temp lat fusifor' filter does more than just
post-filter — NeuroLang’s magic-sets optimisation pushes the constant
backwards through all the rules in the chain:
The
InlineEqualityConstantsMixininlineseq(r, Constant('rfg'))into thebayes_factorcall before the SIPS (Sideways Information Passing Strategy) sees it.The SIPS creates an adorned predicate
bayes_factor^bff_0(Constant('rfg'), t, bf). The adornmentbffhas one letter per argument:b(bound) for the first argument andf(free) for the other two.A magic init
magic_bayes_factor^bff_0(Constant('rfg'))seeds the propagation.Magic rules propagate the bound argument down the dependency chain:
magic_joint_probability^bff_0(r),magic_region_probability^bf_0(r),magic_cooccurrence^bf_0(r),magic_active_region^b_0(r).Each adorned rule now filters its body with a magic predicate, so the computation for the
cooccurrencejoin, the marginal probabilities, and the final Bayes Factor all only see rows wherer = 'right fusiform gyrus'.
The result: with 12 000+ studies and 1 million term-study pairs, the query completes in approximately 30 seconds because only 4 298 studies activating the right fusiform gyrus are evaluated.
Note
Magic-sets works when the constant appears on an IDB (rule-defined)
predicate, as it does here (Bayes_factor is defined by a rule). A
constant on an EDB predicate does not restrict that predicate, but
its rows bind its variables in the IDB predicates after it, whose
magic sets they seed.
Part 9: The Complete Program#
Putting it all together, the program at the top of the page:
define as Activates (?s; ?r) where Destrieux_activated (?r, ?s).
define as Region (?r) where Destrieux (?r, ?x).
define as Active_region every Region that a Selected_study activates.
define as Region_probability with inferred probability
every Active_region.
define as Mentioned_term every Term that a Selected_study mentions.
define as Term_probability with inferred probability
every Mentioned_term.
define as Cooccurrence
for every Region and for every Term
where a Selected_study activates the Region and mentions the Term.
define as Joint_probability with inferred probability
every Cooccurrence (?r; ?t).
define as Bayes_factor (?r; ?t; ?bf)
where Joint_probability (?r, ?t, ?p_rt)
and Region_probability (?r, ?p_r)
and Term_probability (?t, ?p_t)
and ?bf is (?p_rt / ?p_r) / ((?p_t - ?p_rt) / (1.0 - ?p_r)).
obtain every Bayes_factor (?r; ?t; ?bf)
where ?r is 'R G oc temp lat fusifor' as BF.
.sort bf:desc
On the studies of Neurosynth it answers 3 228 terms; the top 20, the same as the Datalog program of Datalog: A Rule-Based Query Language for NeuroLang:
Term |
Bayes Factor |
|---|---|
ffa |
8.92 |
face ffa |
8.43 |
fusiform gyri |
7.50 |
fusiform face |
7.34 |
visual stream |
4.50 |
fusiform |
4.18 |
face recognition |
3.97 |
ventral visual |
3.95 |
fusiform gyrus |
3.88 |
occipital temporal |
3.80 |
inferior occipital |
3.67 |
navigation |
3.57 |
parahippocampal cortex |
3.47 |
object recognition |
3.22 |
occipitotemporal cortex |
3.22 |
face |
3.16 |
identity |
3.10 |
recognize |
3.03 |
occipitotemporal |
3.02 |
scenes |
3.01 |
The first 15 terms exceed the Jeffreys “substantial evidence” threshold of \(\sqrt{10} \approx 3.16\). The top cluster — FFA, face, fusiform face — is exactly what the right fusiform gyrus is known for.
Part 10: Additional SQUALL Syntax#
This section documents features not used directly in the Bayes Factor example but available in the language.
10.1 Aggregations#
Aggregations summarise a set of values into a single result per group.
Supported functions: count, sum, max, min, average.
The examples below use three small relations, typed in the session as
facts (in Datalog, before .mode squall):
paper("s1")
paper("s2")
paper("s3")
measured("s1", 0)
measured("s1", 1)
measured("s2", 2)
measured("s3", 3)
zscore(0)
zscore(1)
zscore(2)
zscore(3)
zscore(4)
The paper relation lists the papers, measured links each paper
to the z-scores of the activation peaks it measured, and zscore
holds every possible z-score value. (The lowercase names are
optional; NeuroLang equates Paper and paper.)
The canonical form groups the aggregation over a subject noun, joining through a binary relationship — e.g. the maximum z-score each paper measured:
define as paper_peak_z for every Paper ;
where every Max of the Zscore that the Paper measured.
The Paper quantifier introduces the group; the anaphoric the Paper
inside the where clause (here in a relative clause that … measured)
ties the aggregation back to it, so no auxiliary variable is needed. The
rule is understood as: for every paper, the maximum zscore value that
the paper measured. It yields one row per paper with the maximum
measured z-score.
The grouped relation is a normal relation and can be queried like any
other — obtain without a tuple label projects every column:
obtain every paper_peak_z.
% → one row per paper: (paper, max z)
obtain every paper_peak_z (?s; ?z).
% → same, with explicit column names
Grouped aggregation is not limited to max: the count, sum,
min and average functions combine with the same anaphoric clause:
define as paper_peak_count for every Paper ;
where every Count of the Zscore that the Paper measured.
define as paper_peak_sum for every Paper ;
where every Sum of the Zscore that the Paper measured.
define as paper_peak_mean for every Paper ;
where every Average of the Zscore that the Paper measured.
Global aggregation (no per-group clause) runs directly through
obtain — the aggregate column is projected onto the result instead of
being dropped:
obtain every Count of the Zscore.
% → 5
obtain every Sum of the Zscore.
% → 10
obtain every Max of the Zscore.
% → 4
obtain every Min of the Zscore.
% → 0
obtain every Average of the Zscore.
% → 2.0
Each returns a single row with one column carrying the aggregate value.
When the aggregated relation has several columns, name the column to
aggregate with a tuple label and write _ for the others; per
groups by a labelled column. With term_in_study_tfidf(study, term,
tfidf):
obtain the Max of the Term_in_study_tfidf (_; _; ?w).
% the largest tf-idf
obtain every Max of the Term_in_study_tfidf (?s; _; ?w) per ?s.
% one row per study: (study, its largest tf-idf)
Without a label (obtain the Max of the Term_in_study_tfidf.) the
column is ambiguous and the query is rejected with an error showing this
form.
In addition to these summary functions, tail aggregations select a
threshold below (Top) or above (Bottom) which a quoted fraction or count
of the values lie. obtain the … reads like English here, so the
definite article is preferred over every:
obtain the Top 5% of the Zscore.
% → 3.8 (95th percentile)
obtain the Bottom 5% of the Zscore.
% → 0.2 (5th percentile)
obtain the Top 2 of the Zscore.
% → 3 (second-largest value)
obtain the Bottom 2 of the Zscore.
% → 1 (second-smallest value)
A percentage selects the value at the corresponding percentile
(Top n% → the (100 − n)-th percentile, Bottom n% → the
n-th); a bare number selects the n-th largest (Top) or n-th
smallest (Bottom) value, clamped to the group size when the group is
smaller than n — e.g. Top 100 of a 5-value column is the smallest
of the five, since all of them lie within the top 100.
Tail aggregations work with the anaphoric per-group clause too, using the
every determiner inside the rule body:
define as paper_top_threshold for every Paper ;
where every Top 10% of the Zscore that the Paper measured.
obtain every paper_top_threshold.
% one row per paper: s1 → 0.9 (90th percentile of {0, 1}),
% s2 → 2, s3 → 3
The aggregated relation can be defined earlier in the same program, and anaphoric definite references to that relation participate in the aggregation:
define as measured_papers every Paper that measured a Zscore.
obtain every Count of the measured_papers.
% single column: the 3 papers that measured a z-score
The aggregation noun may also refer to an N-ary relation, such as a voxel space:
obtain every Voxel in 3D of the Study count of the Study.
10.2 Probabilistic Choice Definitions#
A probabilistic choice creates a predicate whose tuples are mutually exclusive alternatives, each assigned a probability. The simplest form creates a uniform choice:
define as Picked_study as an equiprobable choice over every Study.
This registers picked_study as a probabilistic choice predicate where
every study of the study relation has equal probability 1/N, as the
engine’s own selected_study. The source noun phrase (Study in this
example) must refer to a single-column stored relation, of the engine or
typed in the session.
Unlike define as rules, a choice definition does not produce an IDB
predicate — it registers a probabilistic choice in the engine’s symbol table
that later probabilistic rules (Part 5) can reference via
a Picked_study (existential quantifier). From Python, the same choice is
add_uniform_probabilistic_choice_over_set (NeuroLang in Python).
Weighted choice — the grammar also accepts explicit probability expressions:
define as Picked_study as a choice over every Study with probability ?p.
define as Picked_study as a choice over every Study (?s; ?q)
with probability (?q / ?total).
Here ?p is a variable bound from a multi-column source, and
(?q / ?total) is an arithmetic expression evaluated per tuple.
Support for executing weighted choice definitions directly from
SQUALL is not yet implemented: write them in Datalog
(Datalog: A Rule-Based Query Language for NeuroLang, 10.6), or in Python with
add_probabilistic_choice_from_tuples (NeuroLang in Python).
10.3 Program-Level Directives — #name(args).#
A SQUALL program may include directive lines of the form #name(arg, ...)
to pass configuration to the engine. Directives are processed before rule
walking.
Currently supported:
#set_backend('backend')Switch the relational algebra backend.
backendmay be'pandas'or'polars'. This callsneurolang.config.config.set_query_backendand therefore changes the backend process-wide, for every engine, not only for the current program (see Performance and Configuration).
#set_backend('pandas').
define as Active every person that plays.
obtain every Active.
Unknown directives are silently ignored.
10.4 Inline Type Guards#
Inside a relative clause, where (?i; ?j; ?k) is a Noun asserts that the
tuple belongs to the relation named by Noun:
define as SelectedPeak every Peak_reported (?i; ?j; ?k; ?s)
where (?i; ?j; ?k; ?s) is an Activation.
The scalar form works too: where ?s is a Selected_study. The tuple
form can be combined with other conditions in the same where clause:
obtain every Study ?s
where (?s; ?t; ?w) is a Term_weight and ?t is 'pain'.
10.5 Nested Relative Clauses#
A relative clause can itself contain a noun phrase with its own relative clause:
define as Performer every person that sings a Genre that is popular.
Here that is popular restricts Genre inside the relative clause
that sings a Genre … attached to person. Alternatively, the inner
clause can be factored out into an intermediate IDB predicate that is then
used as the noun:
define as Popular_genre every Genre that is popular.
define as Performer every person that sings a Popular_genre.
Appendix A: Running SQUALL from Python#
Every program of this tutorial runs from Python too, as the text of
execute_squall_program: see SQUALL from Python in
NeuroLang in Python.
Appendix B: IR Builder Cheat-Sheet#
Every SQUALL sentence is compiled into NeuroLang’s intermediate representation (IR). You can also write IR directly using the environment context manager. This is useful when a pattern has no SQUALL syntax yet, or when you need to mix Python logic with declarative rules.
Scope vs Environment
nl.scope — symbols are popped from the symbol table when the with
block exits (clean, no side effects).
nl.environment — symbols persist in the symbol table after exit
(use when rules must be visible to later solve_all() calls).
Both use the same e.<Name> attribute syntax.
Rule equivalence cheat-sheet
Simple unary rule
SQUALL:
define as Active every person that plays.
IR builder:
with nl.environment as e:
e.active[e.x] = e.person(e.x) & e.plays(e.x)
sol = nl.solve_all()
Binary / n-ary rule
SQUALL:
define as author_of for every Paper ?p ; where every Author ?a ; where ?a wrote ?p.
IR builder:
with nl.environment as e:
e.author_of[e.p, e.a] = e.wrote(e.a, e.p)
Probabilistic fact
SQUALL:
define as probably reliable every study.
Equivalent IR expression (a probabilistic fact for every study, with a fresh probability variable):
from neurolang.expressions import Symbol
from neurolang.logic import Implication
from neurolang.probabilistic.expressions import ProbabilisticFact
s, p = Symbol("s"), Symbol.fresh()
rule = Implication(
ProbabilisticFact(p, Symbol("reliable")(s)), Symbol("study")(s)
)
Marginalisation (MARG) query
SQUALL:
define as prob_map with probability every focus_reported (?x; ?y; ?z; ?s)
conditioned to every selected_study ?s that open_world_studies.
IR builder:
from neurolang.probabilistic.expressions import ProbabilisticQuery, Condition, PROB
with nl.environment as e:
x, y, z, s = e.x, e.y, e.z, e.s
e.prob_map[x, y, z, s, ProbabilisticQuery(PROB, (x, y, z, s))] = Condition(
e.focus_reported(x, y, z, s),
e.selected_study(s) & e.open_world_studies(s)
)
Aggregation
SQUALL:
define as max_items for every Item ?i ;
where every Max of the Quantity where ?i item_count per ?i.
IR builder:
from neurolang.datalog.aggregation import AggregationApplication
from neurolang.expressions import Constant
with nl.environment as e:
q = e.q
e.max_items[e.i, AggregationApplication(Constant(max), (q,))] = (
e.item(e.i) & e.item_count(e.i, q)
)
Appendix C: Gap Report#
All features described in this tutorial are supported, except for the execution of weighted choice definitions noted below. The patterns from the codebase that have no complete SQUALL support yet are:
Skolem-like functional terms in rule head — ❌ Not supported. Requires IR changes beyond the grammar transformer scope.
Weighted choice execution from SQUALL — ⏳ Grammar only.
define as X as a choice over Y with probability Pparses but the execution path is not yet implemented. Useadd_probabilistic_choice_from_tuplesin Python for arbitrary probabilities.
Appendix D: Querying from the Command Line#
The neurolang-query command-line tool lets you run SQUALL (or Datalog)
queries without writing Python code. It picks up a preconfigured engine from
the engine registry and executes the
query directly.
Running a SQUALL query inline:
neurolang-query --engine neurosynth --squall \
"obtain every peak_reported."
Running a SQUALL query from a file:
neurolang-query --engine neurosynth --squall -f query.squall
Showing the Datalog IR for a SQUALL query (no execution):
neurolang-query --engine neurosynth --squall --show-datalog \
"obtain every Voxel in 3D that a Study reports."
The neurosynth engine names its relations so that they read as SQUALL:
a Study mentions a Term, a Study reports a Voxel, and the TF-IDF
weight of each term in each study is a Weighted_mention, a noun
followed by the tuple of its columns (study; term; weight):
neurolang-query --engine neurosynth --squall \
"obtain every Weighted_mention (?s; ?t; ?w) such that ?t is 'pain' and ?w is greater than 0.1."
The tool also supports plain Datalog queries (omit --squall). For the
full list of options, see neurolang-query --help or the
neurolang.utils.cli module documentation.
Appendix E: Engine Configuration (engines.yaml)#
See Engine Configuration (engines.yaml) for the full engine registry reference.