Algorithmresearch
PerfectRef query rewriting
Also called DL-Lite query rewriting.
Rewrites a conjunctive query under a DL-Lite TBox into a union of conjunctive queries that gives the certain answers when it is run on the data alone.
- Time
- (t n)^O(n) worst
- Space
- (t n)^O(n) extra
- Where
- n = the number of atoms of the query; t = the size of the TBox
- Model
- Word RAM
- Properties
- data independentdeterministicexactsaturation
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Diego Calvanese, Giuseppe De Giacomo, Domenico Lembo, Maurizio Lenzerini, Riccardo Rosati, 2007
PerfectRef is a query rewriting algorithm for DL-Lite: it turns a conjunctive query and a TBox into a finite union of conjunctive queries whose answers over any ABox, read as a plain database, are the certain answers of over and that ABox. It works by two steps applied until nothing new appears: it replaces one atom by an atom that implies it under an inclusion of , and it merges two atoms that unify. The TBox is used only once, at rewriting time, so the data can stay in a relational database and the rewritten query runs there as SQL.
In plain words
A company keeps its data in tables, and a small list of rules says how the terms are related, for example "every professor teaches something" and "whatever is taught is a course". A user asks "who teaches a course?". The table of teachers may be empty for a person who is only listed as a professor, yet by the rules that person teaches a course. Instead of adding the missing rows to the tables, the method changes the question. It writes down every other question whose answers must also be answers of the first one, such as "who is a professor?" and "who teaches anything?". All these questions together are asked of the plain tables, and the union of their answers is exactly what follows from the tables and the rules.
The problem
A DL-Lite TBox has concept inclusions and between basic concepts , and role inclusions and between roles (DL-Lite). An ABox is a finite set of facts and (TBox and ABox). A conjunctive query is a conjunction of atoms and over the answer variables and the bound variables . A tuple of individuals is a certain answer if it is an answer of in every model of . This is ontology-mediated query answering under the open world assumption.
The task of PerfectRef is to compute, from and alone, a union of conjunctive queries with for every ABox for which is consistent. Negative inclusions do not change the rewriting; they are used only for the consistency test.
The algorithm
Every query is kept in a normal form : a variable that occurs once in the body and not in the head is written . An inclusion is applicable to an atom in these cases, and is the new atom:
| atom | inclusion | |
|---|---|---|
| or | or |
Here stands for , or when is , or . The role inclusion row also covers on the right, with the two terms swapped.
PERFECTREF(q, T) ▷ q and every new query are in the normal form τ- 1
PR ← {q}; TODO ← [q] - 2
while TODO is not empty do - 3
take q′ from TODO; for each atom g of q′ do - 4
for each inclusion I of T applicable to g do - 5
add τ(q′ with g replaced by gr(g, I)) to NEW - 6
for each pair of atoms g1, g2 of q′ with the same predicate do - 7
if g1 and g2 unify: add τ(reduce(q′, g1, g2)) to NEW - 8
for each q″ in NEW that is not in PR: add q″ to PR and to TODO - 9
return PR ▷ evaluate the union of PR over the ABox
Lines L3 to L5 go backwards through one inclusion: if holds, then holds in every model of . The condition in the table matters. The inclusion only says that some -successor exists, so it can stand in for , where the successor is not used anywhere else, but not for with shared by another atom. Lines L6 and L7 make such a shared variable unshared: unifying with gives one atom , and after it is , to which the existential inclusion applies. The reduction is what lets the algorithm see the anonymous elements that the TBox forces. Line L8 keeps the set of queries without repeats. No step makes new variables, so the set is finite and the loop stops.
Example
The TBox is and , and the query is . The run makes four queries:
| query | made at | from | step | body |
|---|---|---|---|---|
| L1 | input | |||
| L4, L5 | with | |||
| L6, L7 | unify the two atoms, then | |||
| L4, L5 | with |
The atom of cannot use , because is shared with . Over the ABox the query alone has no answer. The rewriting gives from and and from , and is the set of certain answers. If the TBox also has and the role inclusion , the rewriting has 10 queries.
Correctness
Each step is sound: if a query added at line L5 or line L7 has a match in a model of , the query it came from has a match with the same answer. So every tuple found over the ABox is a certain answer. For the other direction, the chase of is a model that maps into every model, so the certain answers are its answers on individuals. A match into the chase can be moved back one chase step at a time: the atoms that hit the newest fact are first merged by line L7, and the single atom left is then replaced at line L5 by the atom that hit the fact the step used. A new anonymous element occurs in only one fact when it is made, which is why the variable mapped to it is after the merges. After as many moves as chase steps, some query of PR matches the ABox itself. The full proof, with termination and the exponential lower bound, is in proofs/correctness.md.
Proof: PerfectRef terminates and its union of conjunctive queries gives exactly the certain answersfull
We use the pseudocode of the page, lines L1 to L9. The TBox is a DL-Lite TBox with positive inclusions only: concept inclusions between basic concepts , and role inclusions between roles . Negative inclusions only decide whether the knowledge base is consistent (see the end). A conjunctive query (CQ) is a set of atoms and over variables; the head lists the answer variables. Every CQ is kept in the normal form : a variable that occurs once in the body and not in the head is written , and each is a different variable. This proof follows the one of Calvanese, De Giacomo, Lembo, Lenzerini and Rosati (2007), with the chase written out in single steps.
Definitions
The atom is for , for and for . An inclusion is applicable to an atom , and is defined, in these cases:
- and : .
- and : .
- and : .
- and or : is , or in the second case, with read as .
For two atoms with the same predicate, applies to the most general unifier of and ; a position with on one side takes the term of the other side, and two stay one . The answers of a CQ over an interpretation are the tuples for the maps from the variables of to the domain with true in for every atom ; such an is a match. An ABox is read as a finite interpretation whose domain is its individuals. The certain answers of over are the tuples of individuals that are answers over every model of .
Termination
Lemma 1. Every CQ in PR has at most atoms, where is the number of atoms of the input, and its terms are among the variables of the input and .
Proof. Line L5 replaces one atom by one atom, and the new atom uses the terms of the old one and possibly . Line L7 merges two atoms into one and only identifies variables that already occur. The map only replaces variables by .
Let be the number of concept and role names of and , and the number of variables of . By Lemma 1, a CQ in PR is a set of at most atoms chosen from at most atoms, so PR has at most elements. Line L8 puts a CQ on TODO only when it is new in PR, and nothing is removed from PR, so the loop of line L2 runs at most times and stops.
Soundness
Lemma 2. If is added at line L5 or line L7 while is processed, then for every model of , every answer of over is an answer of over .
Proof. Let be a match of in .
Line L5: is with replaced by , then . The other atoms hold under . If , then says , and because satisfies the inclusion, so holds. If , then , so has a -successor ; the of occurs nowhere else, so extending with makes true without changing any other atom. The case is the same with predecessors. For a role inclusion, says . In every case , extended on the of , is a match of with the same head values. The map only renames variables that occur once and are not in the head, so it does not change the answers.
Line L7: . Then maps every atom of to the image of an atom of , so it is a match of , and its head values are , the head values of .
Corollary. Every tuple that PR finds over the ABox is a certain answer of over .
Proof. Let in PR have a match in with head values . Every model of contains the facts of with each individual interpreted by itself, so is also a match of in . By Lemma 2 and induction along the steps that made , is an answer of over .
Completeness
The chase of is a sequence of sets of facts. Each step takes one inclusion that is violated in and adds one fact:
- with in : add .
- with in and no -successor of : add for a new element . The case adds .
- with in : add , and the same for .
Here means that some fact is present. If the steps are taken fairly, the union of all is a model of , and it maps into every model of by a homomorphism that is the identity on individuals (Calvanese et al. 2007, the canonical interpretation). A match of in followed by this homomorphism is a match in every model, so a tuple of individuals is a certain answer if and only if it is an answer over . A match uses finitely many facts, so it is a match in some .
Lemma 3. If some in PR has a match in with and head values of individuals, then some in PR has a match in with the same head values.
Proof. Let be the fact added at step . If no atom of is mapped to , is already a match in . Otherwise let be the atoms mapped to . They have the predicate of , and unifies them. If , unifies and , so they have a most general unifier and for some . The CQ was added to PR at line L7 when was processed, it has atoms mapped to by , and the head values do not change. Repeat until ; call the result again and the single atom .
Case , made by : with , and is applicable to . Line L5 added . The step was allowed, so in : either is in , or a fact or is, and extended with matches the new atom. The other atoms of map to facts other than , so has a match in .
Case with a new element , made by : with and , where may already be . The element is new at step , so is the only fact of that contains it. Every atom that contains is mapped to a fact with , that is to , so is the only atom with , and occurs once in it because . The element is not an individual, so is not in the head. Hence has made into , , and is applicable. As in the first case, is in PR and has a match in . The case is symmetric.
Case made by a role inclusion from : , the inclusion is applicable to in any case, and is mapped by to the fact of .
Theorem. For a knowledge base with positive inclusions only, the answers of the union of the CQs of PERFECTREF over are exactly the certain answers of over .
Proof. The Corollary gives one direction. For the other, a certain answer is an answer over , so has a match in some . The input is in PR (line L1). Applying Lemma 3 times gives a CQ of PR with a match in and head values .
Negative inclusions
A negative inclusion or adds no facts to the chase. If is consistent, its models are the models of the positive part that satisfy the negative inclusions, and the chase is one of them, so the certain answers do not change. If is inconsistent, every tuple is a certain answer. Consistency is tested by rewriting, for each negative inclusion, the boolean query that asks for a violation, for example , and evaluating it over (Calvanese et al. 2007). With functional roles in DL-Lite the same method needs one more boolean query for each functionality assertion.
Running time
Processing one CQ of PR costs for lines L3 to L5 and unifications of constant size for lines L6 and L7, plus the hashing of the new CQs at line L8. With the bound of Lemma 1, the time is with , which is polynomial in for a fixed query and exponential in . The rewriting does not depend on . Evaluating a fixed union of CQs over a database is a first-order query, so the data complexity of query answering is in AC.
The exponential family
Let and . Line L5 can replace each by independently, and no two atoms unify, so PR has exactly the CQs with .
No union of CQs with fewer CQs is a rewriting. For a choice of one for each , the ABox has as a certain answer, so some CQ of a correct rewriting matches with head value . All atoms of then have predicates among . If had no atom with or for some , it would also match the ABox without , where is not a certain answer: the interpretation with domain that puts in and for every , and in neither nor , is a model of and of that ABox with . So the predicates of are exactly , and different choices need different CQs.
Complexity
Let have atoms and variables, and let be the number of names in and . Every query in PR has at most atoms over the variables and , so PR has at most queries, and the time is that bound times a polynomial in and . For a fixed query this is polynomial in ; in it is exponential.
The exponential size can occur. For and , PR has exactly queries, one for each choice of or at each position, and no union of conjunctive queries with fewer members is a correct rewriting. A positive existential query has linear size here, so the blow-up belongs to the target language, not to the problem.
The rewriting does not look at the ABox. With and fixed, evaluating the union over the ABox is a fixed first-order query, so the data complexity of query answering in DL-Lite is in AC (AC0).
Properties
- Data independent. The output depends only on and . One rewriting serves every ABox, and the ABox is never changed.
- Exact. The union gives the certain answers, no more and no fewer, when is consistent.
- Syntactic. Every query of PR uses only the variables of and the names of and ; nothing anonymous is made.
- Redundant. PR often contains queries that are contained in others, such as and of the example. They give no new answers.
Variants and improvements
- Removing contained queries. A query of PR that is contained in another one can be dropped; containment of conjunctive queries is decided by a homomorphism test (query containment problem, Chandra and Merlin). This keeps the union smaller but does not avoid the exponential size in the example above.
- Other target languages. Rewriting into positive existential queries or into non-recursive Datalog can be much smaller than a union of conjunctive queries, and several later systems do this.
- Functional roles. For DL-Lite the same algorithm works with the role inclusions left out; functionality, like negative inclusions, only takes part in the consistency test.
- Consistency. Each negative inclusion becomes a boolean query that asks for a violation, for example , and it is rewritten and evaluated in the same way.
- The chase. The opposite approach adds the consequences to the data with the chase. For DL-Lite the chase can be infinite, so it must be cut or folded, and the data must be changed when the TBox changes.
When to use it
Use it when the data is large, kept in a relational database, and the ontology fits in DL-Lite, which is the basis of the OWL 2 QL profile. The database engine does all the work on the data, and the TBox only changes the SQL. Do not use it when the TBox has qualified existentials on the left, such as , or disjunction: then certain answers are not first-order rewritable in general, and methods for EL or for more expressive logics are needed. For long queries over deep hierarchies, the union can be too large to send to a database; a rewriting into a smaller target language fits better there.
Pitfalls
- Rewriting an atom with a shared variable. Line L4 must apply only to an atom . Applying it to with used elsewhere is unsound. With only and the query of the example, the wrong step gives , which returns over . But is not a certain answer, because what she teaches need not be a course.
- Skipping after a merge. Line L7 must apply to the result of the reduction. Without it, of the example stays , line L4 does not see that is unbound, is never made, and is missed.
- Building the merged atom from one side. At line L7, a position where one atom has must take the term of the other atom. Keeping the of the first atom loses a shared variable, and the result is wrong for some inputs; the random tests of the implementation found such cases in an early version.
- Making fresh variables. Line L8 compares queries by their syntax. If each step renamed the variables into new names, no query would repeat and the loop would not stop on a cyclic TBox such as and . Keeping all unbound variables as is what bounds PR.
- Ignoring consistency. Line L9 gives the certain answers only for a consistent knowledge base. If the ABox violates a negative inclusion, every tuple is a certain answer, so the consistency test must run first.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perfectref-rewriting/. The authors are listed in prov/4TB81W.jsonl.
"""PerfectRef: rewrite a conjunctive query over a DL-Lite_R TBox into a union of conjunctive queries.
Notation.
A basic concept is ("A", name) for a concept name, or ("E", P, inverse) for some P or some P^-.
A role is (P, inverse).
The TBox holds positive inclusions: concept inclusions (B1, B2), read B1 is subsumed by B2,
and role inclusions (R1, R2). Negative inclusions do not change the rewriting, only consistency.
A query is (head, body): head is a tuple of variables, body a frozenset of atoms
("C", A, t) and ("R", P, t1, t2). Terms are variable names. The term "_" stands for a variable
that occurs once in the body and not in the head (an unbound variable); each "_" is a new one.
An ABox is a pair (concept facts {(A, a)}, role facts {(P, a, b)}).
"""
from typing import Iterable, Sequence
UNBOUND = "_"
def basic_atom(b: tuple, t: str) -> tuple:
"""The atom that says term t is in the basic concept b."""
if b[0] == "A":
return ("C", b[1], t)
p, inv = b[1], b[2]
return ("R", p, UNBOUND, t) if inv else ("R", p, t, UNBOUND)
def role_atom(r: tuple, t1: str, t2: str) -> tuple:
"""The atom that says (t1, t2) is in the role r."""
p, inv = r
return ("R", p, t2, t1) if inv else ("R", p, t1, t2)
def tau(head: tuple, body: Iterable[tuple]) -> tuple:
"""Replace every variable that occurs once in the body and not in the head by "_"."""
body = list(body)
count: dict[str, int] = {}
for g in body:
for t in g[2:]:
if t != UNBOUND:
count[t] = count.get(t, 0) + 1
hs = set(head)
def f(t: str) -> str:
return UNBOUND if t != UNBOUND and t not in hs and count[t] == 1 else t
return (tuple(head), frozenset(g[:2] + tuple(f(t) for t in g[2:]) for g in body))
def rewrite_atom(g: tuple, tbox_ci: Sequence[tuple], tbox_ri: Sequence[tuple]) -> list[tuple]:
"""gr(g, I) for every inclusion I that is applicable to the atom g."""
out = []
if g[0] == "C":
for lhs, rhs in tbox_ci:
if rhs == ("A", g[1]):
out.append(basic_atom(lhs, g[2]))
return out
_, p, t1, t2 = g
for lhs, rhs in tbox_ci:
if rhs == ("E", p, False) and t2 == UNBOUND:
out.append(basic_atom(lhs, t1))
if rhs == ("E", p, True) and t1 == UNBOUND:
out.append(basic_atom(lhs, t2))
for r1, r2 in tbox_ri:
if r2 == (p, False):
out.append(role_atom(r1, t1, t2))
elif r2 == (p, True):
out.append(role_atom(r1, t2, t1))
return out
def reduce_pair(q: tuple, g1: tuple, g2: tuple):
"""reduce(q, g1, g2): apply the most general unifier of g1 and g2 to q. None if they do not unify."""
if g1[:2] != g2[:2]:
return None
head, body = q
parent: dict[str, str] = {}
def find(t: str) -> str:
while t in parent:
t = parent[t]
return t
hs = set(head)
for a, b in zip(g1[2:], g2[2:]):
if a == UNBOUND or b == UNBOUND:
continue # a new variable that occurs once unifies with anything and binds nothing
a, b = find(a), find(b)
if a != b:
if a in hs: # keep a head variable as the representative
a, b = b, a
parent[a] = b
def sub(t: str) -> str:
return t if t == UNBOUND else find(t)
# The unified atom: at a position where one side is "_", the other side decides.
unified = g1[:2] + tuple(sub(b) if a == UNBOUND else sub(a) for a, b in zip(g1[2:], g2[2:]))
new_head = tuple(sub(t) for t in head)
new_body = [g[:2] + tuple(sub(t) for t in g[2:]) for g in body if g != g1 and g != g2]
return tau(new_head, new_body + [unified])
def perfect_ref(query: tuple, tbox_ci: Sequence[tuple], tbox_ri: Sequence[tuple] = ()) -> set[tuple]:
"""PerfectRef(q, T): the set of conjunctive queries of the rewriting."""
start = tau(*query)
pr = {start} # @line L1
todo = [start]
while todo: # @line L2
q = todo.pop()
head, body = q
new = []
for g in body: # @line L3
for g2 in rewrite_atom(g, tbox_ci, tbox_ri): # @line L4
new.append(tau(head, (body - {g}) | {g2})) # @line L5
atoms = sorted(body)
for i in range(len(atoms)): # @line L6
for j in range(i + 1, len(atoms)):
r = reduce_pair(q, atoms[i], atoms[j]) # @line L7
if r is not None:
new.append(r)
for q2 in new:
if q2 not in pr: # @line L8
pr.add(q2)
todo.append(q2)
return pr # @line L9
def evaluate_cq(q: tuple, abox: tuple) -> set[tuple]:
"""The answers of a conjunctive query over an ABox, as a database (closed world, no TBox)."""
head, body = q
concepts, roles = abox
by_c: dict[str, list] = {}
for a, x in concepts:
by_c.setdefault(a, []).append(x)
by_r: dict[str, list] = {}
for p, x, y in roles:
by_r.setdefault(p, []).append((x, y))
atoms = sorted(body, key=lambda g: -sum(t != UNBOUND for t in g[2:]))
out: set[tuple] = set()
def match(t: str, v, env: dict) -> bool:
if t == UNBOUND:
return True
if t in env:
return env[t] == v
env[t] = v
return True
def go(k: int, env: dict) -> None:
if k == len(atoms):
out.add(tuple(env[t] for t in head))
return
g = atoms[k]
cands = [(x,) for x in by_c.get(g[1], ())] if g[0] == "C" else by_r.get(g[1], ())
for vals in cands:
e = dict(env)
if all(match(t, v, e) for t, v in zip(g[2:], vals)):
go(k + 1, e)
go(0, {})
return out
def evaluate_ucq(ucq: Iterable[tuple], abox: tuple) -> set[tuple]:
out: set[tuple] = set()
for q in ucq:
out |= evaluate_cq(q, abox)
return out
def certain_answers_by_rewriting(query: tuple, tbox_ci: Sequence[tuple], tbox_ri: Sequence[tuple], abox: tuple) -> set[tuple]:
return evaluate_ucq(perfect_ref(query, tbox_ci, tbox_ri), abox)
test_perfectref_rewriting.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perfectref-rewriting/. The authors are listed in prov/4TB81W.jsonl.
"""Tests of PerfectRef against certain answers computed by a chase.
The reference builds the restricted chase of the ABox with the TBox, cut at depth
m + 2|P| + 1, where m is the number of query atoms and |P| the number of role names. Concept and
role inclusions are applied to a fixpoint before each new element is made, so the part of the
chase below an anonymous element depends only on the role that made it. A match of a connected
part of the query that uses only anonymous elements can then be moved up to depth at most
2|P| + m, and a part that touches the ABox stays within depth m of it. So the cut chase has a
match exactly when the full chase has one, and the full chase is a universal model: its answers on
named individuals are the certain answers.
"""
import random
from itertools import product
from perfectref_rewriting import UNBOUND, evaluate_cq, evaluate_ucq, perfect_ref, reduce_pair, rewrite_atom, tau
def chase(tbox_ci, tbox_ri, abox, depth_limit: int):
"""The restricted chase, cut at depth_limit. Inclusions without existentials are applied to a
fixpoint before each new element is made, and new elements are made in order of depth."""
conc: set = set()
roles: set = set()
has: set = set() # basic concepts that hold: ("A", name, x) and ("E", p, inverse, x)
depth: dict = {}
for _, x in abox[0]:
depth[x] = 0
for _, x, y in abox[1]:
depth[x] = depth[y] = 0
order = {x: k for k, x in enumerate(sorted(depth))} # the order in which elements were made
by_lhs: dict = {}
for lhs, rhs in tbox_ci:
by_lhs.setdefault(lhs, []).append(rhs)
queue: list = [("C", a, x) for a, x in abox[0]] + [("R", p, x, y) for p, x, y in abox[1]]
# Existentials to check later, as (depth of x, order of x, rhs, x). Each element handles its own
# existentials in a fixed order, so the part below an anonymous element depends only on the
# role that made it.
needs: list = []
fresh = 0
def basic(b: tuple, x) -> None:
key = b + (x,)
if key in has:
return
has.add(key)
for rhs in by_lhs.get(b, ()):
if rhs[0] == "A":
queue.append(("C", rhs[1], x))
else:
needs.append((depth[x], order[x], rhs, x))
while True:
while queue:
f = queue.pop()
if f[0] == "C":
if (f[1], f[2]) in conc:
continue
conc.add((f[1], f[2]))
basic(("A", f[1]), f[2])
continue
_, p, x, y = f
if (p, x, y) in roles:
continue
roles.add((p, x, y))
basic(("E", p, False), x)
basic(("E", p, True), y)
for r1, r2 in tbox_ri:
if r1[0] != p:
continue
a, b = (x, y) if not r1[1] else (y, x) # (a, b) is in r1
queue.append(("R", r2[0], a, b) if not r2[1] else ("R", r2[0], b, a))
needs.sort(key=lambda t: t[:3])
while needs:
d, _, rhs, x = needs.pop(0)
if d < depth_limit and rhs + (x,) not in has:
break
else:
return conc, roles, depth
fresh += 1
y = ("null", fresh)
depth[y] = d + 1
order[y] = len(order)
queue.append(("R", rhs[1], x, y) if not rhs[2] else ("R", rhs[1], y, x))
def certain_answers(query, tbox_ci, tbox_ri, abox) -> set:
head, body = query
role_names = {g[1] for g in body if g[0] == "R"} | {b[1] for ci in tbox_ci for b in ci if b[0] == "E"}
role_names |= {r[0] for ri in tbox_ri for r in ri} | {p for p, _, _ in abox[1]}
d = len(body) + 2 * len(role_names) + 1
conc, roles, depth = chase(tbox_ci, tbox_ri, abox, d)
named = {x for x in depth if depth[x] == 0}
return {t for t in evaluate_cq(query, (conc, roles)) if all(v in named for v in t)}
def C(a, t):
return ("C", a, t)
def R(p, t1, t2):
return ("R", p, t1, t2)
def test_paper_style_example() -> None:
# Professor is subsumed by some teaches; some teaches^- is subsumed by Course.
ci = [(("A", "Professor"), ("E", "teaches", False)), (("E", "teaches", True), ("A", "Course"))]
q = (("x",), frozenset({R("teaches", "x", "y"), C("Course", "y")}))
ucq = perfect_ref(q, ci)
bodies = {b for _, b in ucq}
assert frozenset({R("teaches", "x", UNBOUND)}) in bodies
assert frozenset({C("Professor", "x")}) in bodies
assert len(ucq) == 4
abox = ({("Professor", "ann")}, {("teaches", "bob", "c1")})
assert evaluate_ucq(ucq, abox) == {("ann",), ("bob",)}
assert evaluate_cq(q, abox) == set() # without the TBox, the query finds nothing
assert certain_answers(q, ci, [], abox) == {("ann",), ("bob",)}
def test_tau_and_reduce() -> None:
q = tau(("x",), [R("r", "x", "y"), R("r", "x", "z"), C("A", "z")])
assert q[1] == frozenset({R("r", "x", UNBOUND), R("r", "x", "z"), C("A", "z")})
red = reduce_pair(q, R("r", "x", UNBOUND), R("r", "x", "z"))
assert red[1] == frozenset({R("r", "x", "z"), C("A", "z")})
assert reduce_pair(q, R("r", "x", "z"), C("A", "z")) is None
def test_bound_variable_blocks_existential() -> None:
# A is subsumed by some r. The atom r(x, y) with y bound cannot be rewritten into A(x).
ci = [(("A", "A"), ("E", "r", False))]
assert rewrite_atom(R("r", "x", "y"), ci, []) == []
assert rewrite_atom(R("r", "x", UNBOUND), ci, []) == [C("A", "x")]
def exponential_family(n: int):
ci = [(("A", f"B{i}"), ("A", f"A{i}")) for i in range(1, n + 1)]
q = (("x",), frozenset(C(f"A{i}", "x") for i in range(1, n + 1)))
return q, ci
def test_exponential_rewriting() -> None:
for n in range(1, 9):
q, ci = exponential_family(n)
ucq = perfect_ref(q, ci)
assert len(ucq) == 2 ** n
# Every UCQ rewriting needs 2^n queries: the ABox that puts a in one of A_i, B_i for each i
# has a as an answer, and a CQ that matches it uses exactly those atoms.
n = 4
q, ci = exponential_family(n)
ucq = perfect_ref(q, ci)
for choice in product((0, 1), repeat=n):
abox = ({(("A" if c == 0 else "B") + str(i + 1), "a") for i, c in enumerate(choice)}, set())
hits = [u for u in ucq if evaluate_cq(u, abox)]
assert len(hits) == 1
assert certain_answers(q, ci, [], abox) == {("a",)}
def rand_basic(rng: random.Random, cn, rn) -> tuple:
if rng.random() < 0.5:
return ("A", rng.choice(cn))
return ("E", rng.choice(rn), rng.random() < 0.5)
def rand_instance(rng: random.Random):
cn, rn = ["A", "B", "C"], ["p", "s"]
ci = [(rand_basic(rng, cn, rn), rand_basic(rng, cn, rn)) for _ in range(rng.randint(2, 5))]
ri = []
if rng.random() < 0.5:
r1 = (rng.choice(rn), rng.random() < 0.5)
r2 = (rng.choice(rn), rng.random() < 0.5)
if r1[0] != r2[0] or r1[1] != r2[1]:
ri.append((r1, r2))
inds = ["a", "b", "c"]
conc = {(rng.choice(cn), rng.choice(inds)) for _ in range(rng.randint(0, 3))}
roles = {(rng.choice(rn), rng.choice(inds), rng.choice(inds)) for _ in range(rng.randint(0, 2))}
vars_ = ["x", "y", "z"] if rng.random() < 0.3 else ["x", "y"]
body = set()
for _ in range(rng.randint(2, 3)):
if rng.random() < 0.45:
body.add(C(rng.choice(cn), rng.choice(vars_)))
else:
body.add(R(rng.choice(rn), rng.choice(vars_), rng.choice(vars_)))
used = sorted({t for g in body for t in g[2:]})
k = rng.randint(0, min(2, len(used)))
head = tuple(rng.sample(used, k))
return (head, frozenset(body)), ci, ri, (conc, roles)
def test_random_against_chase() -> None:
rng = random.Random(31)
tbox_matters = 0
for _ in range(1500):
q, ci, ri, abox = rand_instance(rng)
got = evaluate_ucq(perfect_ref(q, ci, ri), abox)
want = certain_answers(q, ci, ri, abox)
assert got == want, (q, ci, ri, abox)
if want != evaluate_cq(q, abox):
tbox_matters += 1 # the TBox adds answers that the ABox alone does not give
assert tbox_matters >= 100
def test_rewriting_is_finite_on_cycles() -> None:
# Cyclic inclusions: some p is subsumed by some p^- and back, A is subsumed by some p.
ci = [(("E", "p", False), ("E", "p", True)), (("E", "p", True), ("E", "p", False)), (("A", "A"), ("E", "p", False))]
ri = [(("p", False), ("p", True))]
q = (("x",), frozenset({R("p", "x", "y"), R("p", "y", "z")}))
ucq = perfect_ref(q, ci, ri)
assert 0 < len(ucq) < 200
History
Calvanese, De Giacomo, Lembo, Lenzerini and Rosati introduced the DL-Lite family in 2005 as description logics in which query answering can be done by a relational database. Their journal paper of 2007 gave PerfectRef for DL-Lite and DL-Lite, proved that it returns exactly the certain answers, and showed that conjunctive query answering is in AC in data complexity. The OWL 2 QL profile of the Web Ontology Language is based on DL-Lite. Later work studied smaller rewritings, other target languages and lower bounds on the size of rewritings.
References
- Diego Calvanese, Giuseppe De Giacomo, Domenico Lembo, Maurizio Lenzerini and Riccardo Rosati, Tractable reasoning and efficient query answering in description logics, the DL-Lite family, Journal of Automated Reasoning 39(3), 2007, pages 385 to 429 (the section on query answering in DL-Lite_R, with the algorithm PerfectRef, its termination and correctness, and the AC0 data complexity bound; general locator)
- Franz Baader, Ian Horrocks, Carsten Lutz and Ulrike Sattler, An Introduction to Description Logic, Cambridge University Press, 2017, the chapter on query answering in DL-Lite (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4TB81W Edit this page History Report an error Markdown