Algorithm Search⌘K

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
Properties
data independentdeterministicexactsaturation
Origin
Diego Calvanese, Giuseppe De Giacomo, Domenico Lembo, Maurizio Lenzerini, Riccardo Rosati, 2007

PerfectRef is a query rewriting algorithm for DL-LiteR_R: it turns a conjunctive query qq and a TBox TT into a finite union of conjunctive queries whose answers over any ABox, read as a plain database, are the certain answers of qq over TT 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 TT, 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-LiteR_R TBox TT has concept inclusions B1⊑B2B_1 \sqsubseteq B_2 and B1⊑¬B2B_1 \sqsubseteq \neg B_2 between basic concepts B::=A∣∃P∣∃P−B ::= A \mid \exists P \mid \exists P^-, and role inclusions R1⊑R2R_1 \sqsubseteq R_2 and R1⊑¬R2R_1 \sqsubseteq \neg R_2 between roles R::=P∣P−R ::= P \mid P^- (DL-Lite). An ABox AA is a finite set of facts A(a)A(a) and P(a,b)P(a, b) (TBox and ABox). A conjunctive query q(x⃗)=∃y⃗. φq(\vec x) = \exists \vec y.\, \varphi is a conjunction of atoms A(t)A(t) and P(t1,t2)P(t_1, t_2) over the answer variables x⃗\vec x and the bound variables y⃗\vec y. A tuple a⃗\vec a of individuals is a certain answer if it is an answer of qq in every model of (T,A)(T, A). This is ontology-mediated query answering under the open world assumption.

The task of PerfectRef is to compute, from qq and TT alone, a union of conjunctive queries QQ with cert(q,T,A)=Q(A)\mathrm{cert}(q, T, A) = Q(A) for every ABox AA for which (T,A)(T, A) 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 τ(q)\tau(q): a variable that occurs once in the body and not in the head is written _\_. An inclusion II is applicable to an atom gg in these cases, and gr(g,I)\mathrm{gr}(g, I) is the new atom:

atom gg inclusion II gr(g,I)\mathrm{gr}(g, I)
A(t)A(t) B⊑AB \sqsubseteq A B(t)B(t)
P(t,_)P(t, \_) B⊑∃PB \sqsubseteq \exists P B(t)B(t)
P(_,t)P(\_, t) B⊑∃P−B \sqsubseteq \exists P^- B(t)B(t)
P(t1,t2)P(t_1, t_2) Q⊑PQ \sqsubseteq P or Q−⊑PQ^- \sqsubseteq P Q(t1,t2)Q(t_1, t_2) or Q(t2,t1)Q(t_2, t_1)

Here B(t)B(t) stands for A′(t)A'(t), Q(t,_)Q(t, \_) or Q(_,t)Q(\_, t) when BB is A′A', ∃Q\exists Q or ∃Q−\exists Q^-. The role inclusion row also covers P−P^- on the right, with the two terms swapped.

  1. PERFECTREF(q, T) ▷ q and every new query are in the normal form τ
  2. 1PR ← {q}; TODO ← [q]
  3. 2while TODO is not empty do
  4. 3take q′ from TODO; for each atom g of q′ do
  5. 4for each inclusion I of T applicable to g do
  6. 5add τ(q′ with g replaced by gr(g, I)) to NEW
  7. 6for each pair of atoms g1, g2 of q′ with the same predicate do
  8. 7if g1 and g2 unify: add τ(reduce(q′, g1, g2)) to NEW
  9. 8for each q″ in NEW that is not in PR: add q″ to PR and to TODO
  10. 9return PR ▷ evaluate the union of PR over the ABox

Lines L3 to L5 go backwards through one inclusion: if gr(g,I)\mathrm{gr}(g, I) holds, then gg holds in every model of TT. The condition _\_ in the table matters. The inclusion B⊑∃PB \sqsubseteq \exists P only says that some PP-successor exists, so it can stand in for P(t,_)P(t, \_), where the successor is not used anywhere else, but not for P(t,y)P(t, y) with yy shared by another atom. Lines L6 and L7 make such a shared variable unshared: unifying P(x,y)P(x, y) with P(_,y)P(\_, y) gives one atom P(x,y)P(x, y), and after τ\tau it is P(x,_)P(x, \_), 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 Professor⊑∃teaches\mathit{Professor} \sqsubseteq \exists \mathit{teaches} and ∃teaches−⊑Course\exists \mathit{teaches}^- \sqsubseteq \mathit{Course}, and the query is q(x)=∃y. teaches(x,y)∧Course(y)q(x) = \exists y.\, \mathit{teaches}(x, y) \wedge \mathit{Course}(y). The run makes four queries:

query made at from step body
q0q_0 L1 input teaches(x,y)∧Course(y)\mathit{teaches}(x, y) \wedge \mathit{Course}(y)
q1q_1 L4, L5 q0q_0 Course(y)\mathit{Course}(y) with ∃teaches−⊑Course\exists \mathit{teaches}^- \sqsubseteq \mathit{Course} teaches(x,y)∧teaches(_,y)\mathit{teaches}(x, y) \wedge \mathit{teaches}(\_, y)
q2q_2 L6, L7 q1q_1 unify the two atoms, then τ\tau teaches(x,_)\mathit{teaches}(x, \_)
q3q_3 L4, L5 q2q_2 teaches(x,_)\mathit{teaches}(x, \_) with Professor⊑∃teaches\mathit{Professor} \sqsubseteq \exists \mathit{teaches} Professor(x)\mathit{Professor}(x)

The atom teaches(x,y)\mathit{teaches}(x, y) of q0q_0 cannot use Professor⊑∃teaches\mathit{Professor} \sqsubseteq \exists \mathit{teaches}, because yy is shared with Course(y)\mathit{Course}(y). Over the ABox {Professor(ann),teaches(bob,c1)}\{\mathit{Professor}(\mathit{ann}), \mathit{teaches}(\mathit{bob}, c_1)\} the query q0q_0 alone has no answer. The rewriting gives bob\mathit{bob} from q1q_1 and q2q_2 and ann\mathit{ann} from q3q_3, and {ann,bob}\{\mathit{ann}, \mathit{bob}\} is the set of certain answers. If the TBox also has AssocProf⊑Professor\mathit{AssocProf} \sqsubseteq \mathit{Professor} and the role inclusion lectures⊑teaches\mathit{lectures} \sqsubseteq \mathit{teaches}, 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 TT, 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 (T,A)(T, A) 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 TT is a DL-LiteR_R TBox with positive inclusions only: concept inclusions B1⊑B2B_1 \sqsubseteq B_2 between basic concepts B::=A∣∃P∣∃P−B ::= A \mid \exists P \mid \exists P^-, and role inclusions R1⊑R2R_1 \sqsubseteq R_2 between roles R::=P∣P−R ::= P \mid P^-. Negative inclusions only decide whether the knowledge base is consistent (see the end). A conjunctive query (CQ) q(x⃗)q(\vec x) is a set of atoms A(t)A(t) and P(t1,t2)P(t_1, t_2) over variables; the head x⃗\vec x lists the answer variables. Every CQ is kept in the normal form τ(q)\tau(q): 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 basic(B,t)\mathrm{basic}(B, t) is A(t)A(t) for B=AB = A, Q(t,_)Q(t, \_) for B=∃QB = \exists Q and Q(_,t)Q(\_, t) for B=∃Q−B = \exists Q^-. An inclusion II is applicable to an atom gg, and gr(g,I)\mathrm{gr}(g, I) is defined, in these cases:

  • g=A(t)g = A(t) and I=B⊑AI = B \sqsubseteq A: gr(g,I)=basic(B,t)\mathrm{gr}(g, I) = \mathrm{basic}(B, t).
  • g=P(t,_)g = P(t, \_) and I=B⊑∃PI = B \sqsubseteq \exists P: gr(g,I)=basic(B,t)\mathrm{gr}(g, I) = \mathrm{basic}(B, t).
  • g=P(_,t)g = P(\_, t) and I=B⊑∃P−I = B \sqsubseteq \exists P^-: gr(g,I)=basic(B,t)\mathrm{gr}(g, I) = \mathrm{basic}(B, t).
  • g=P(t1,t2)g = P(t_1, t_2) and I=R⊑PI = R \sqsubseteq P or I=R⊑P−I = R \sqsubseteq P^-: gr(g,I)\mathrm{gr}(g, I) is R(t1,t2)R(t_1, t_2), or R(t2,t1)R(t_2, t_1) in the second case, with Q−(s,s′)Q^-(s, s') read as Q(s′,s)Q(s', s).

For two atoms g1,g2g_1, g_2 with the same predicate, reduce(q,g1,g2)\mathrm{reduce}(q, g_1, g_2) applies to qq the most general unifier σ\sigma of g1g_1 and g2g_2; a position with _\_ on one side takes the term of the other side, and two _\_ stay one _\_. The answers of a CQ qq over an interpretation II are the tuples h(x⃗)h(\vec x) for the maps hh from the variables of qq to the domain with h(g)h(g) true in II for every atom gg; such an hh is a match. An ABox AA is read as a finite interpretation whose domain is its individuals. The certain answers of qq over K=(T,A)K = (T, A) are the tuples of individuals that are answers over every model of KK.

Termination

Lemma 1. Every CQ in PR has at most nn atoms, where nn 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 τ\tau only replaces variables by _\_. □\square

Let mm be the number of concept and role names of TT and qq, and vv the number of variables of qq. By Lemma 1, a CQ in PR is a set of at most nn atoms chosen from at most a=m(v+1)2a = m(v + 1)^2 atoms, so PR has at most (a+1)n(a + 1)^n 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 (a+1)n(a + 1)^n times and stops.

Soundness

Lemma 2. If q′q' is added at line L5 or line L7 while qq is processed, then for every model II of TT, every answer of q′q' over II is an answer of qq over II.

Proof. Let hh be a match of q′q' in II.

Line L5: q′q' is qq with gg replaced by g′=gr(g,I)g' = \mathrm{gr}(g, I), then τ\tau. The other atoms hold under hh. If g=A(t)g = A(t), then g′g' says h(t)∈BIh(t) \in B^I, and BI⊆AIB^I \subseteq A^I because II satisfies the inclusion, so gg holds. If g=P(t,_)g = P(t, \_), then h(t)∈BI⊆(∃P)Ih(t) \in B^I \subseteq (\exists P)^I, so h(t)h(t) has a PP-successor ee; the _\_ of gg occurs nowhere else, so extending hh with _↦e\_ \mapsto e makes gg true without changing any other atom. The case P(_,t)P(\_, t) is the same with predecessors. For a role inclusion, g′g' says (h(t1),h(t2))∈RI⊆PI(h(t_1), h(t_2)) \in R^I \subseteq P^I. In every case hh, extended on the _\_ of gg, is a match of qq with the same head values. The map τ\tau only renames variables that occur once and are not in the head, so it does not change the answers.

Line L7: q′=τ(σ(q))q' = \tau(\sigma(q)). Then h∘σh \circ \sigma maps every atom of qq to the image of an atom of σ(q)\sigma(q), so it is a match of qq, and its head values are h(σ(x⃗))h(\sigma(\vec x)), the head values of q′q'. □\square

Corollary. Every tuple that PR finds over the ABox AA is a certain answer of qq over K=(T,A)K = (T, A).

Proof. Let q′q' in PR have a match hh in AA with head values a⃗\vec a. Every model II of KK contains the facts of AA with each individual interpreted by itself, so hh is also a match of q′q' in II. By Lemma 2 and induction along the steps that made q′q', a⃗\vec a is an answer of qq over II. □\square

Completeness

The chase of KK is a sequence A=C0⊆C1⊆…A = C_0 \subseteq C_1 \subseteq \dots of sets of facts. Each step takes one inclusion that is violated in Ck−1C_{k-1} and adds one fact:

  • B⊑AB \sqsubseteq A with c∈Bc \in B in Ck−1C_{k-1}: add A(c)A(c).
  • B⊑∃PB \sqsubseteq \exists P with c∈Bc \in B in Ck−1C_{k-1} and no PP-successor of cc: add P(c,d)P(c, d) for a new element dd. The case ∃P−\exists P^- adds P(d,c)P(d, c).
  • R⊑PR \sqsubseteq P with R(c,e)R(c, e) in Ck−1C_{k-1}: add P(c,e)P(c, e), and the same for P−P^-.

Here c∈∃Qc \in \exists Q means that some fact Q(c,e)Q(c, e) is present. If the steps are taken fairly, the union CC of all CkC_k is a model of KK, and it maps into every model of KK by a homomorphism that is the identity on individuals (Calvanese et al. 2007, the canonical interpretation). A match of qq in CC 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 CC. A match uses finitely many facts, so it is a match in some CkC_k.

Lemma 3. If some q′q' in PR has a match hh in CkC_k with k≥1k \ge 1 and head values a⃗\vec a of individuals, then some q′′q'' in PR has a match in Ck−1C_{k-1} with the same head values.

Proof. Let ff be the fact added at step kk. If no atom of q′q' is mapped to ff, hh is already a match in Ck−1C_{k-1}. Otherwise let g1,…,gjg_1, \dots, g_j be the atoms mapped to ff. They have the predicate of ff, and hh unifies them. If j≥2j \ge 2, hh unifies g1g_1 and g2g_2, so they have a most general unifier σ\sigma and h=h′∘σh = h' \circ \sigma for some h′h'. The CQ τ(reduce(q′,g1,g2))\tau(\mathrm{reduce}(q', g_1, g_2)) was added to PR at line L7 when q′q' was processed, it has j−1j - 1 atoms mapped to ff by h′h', and the head values do not change. Repeat until j=1j = 1; call the result q′q' again and the single atom gg.

Case f=A(c)f = A(c), made by I=B⊑AI = B \sqsubseteq A: g=A(t)g = A(t) with h(t)=ch(t) = c, and II is applicable to gg. Line L5 added q′′=τ(q′[g/basic(B,t)])q'' = \tau(q'[g / \mathrm{basic}(B, t)]). The step was allowed, so c∈Bc \in B in Ck−1C_{k-1}: either B(c)B(c) is in Ck−1C_{k-1}, or a fact Q(c,e)Q(c, e) or Q(e,c)Q(e, c) is, and hh extended with _↦e\_ \mapsto e matches the new atom. The other atoms of q′′q'' map to facts other than ff, so q′′q'' has a match in Ck−1C_{k-1}.

Case f=P(c,d)f = P(c, d) with a new element dd, made by I=B⊑∃PI = B \sqsubseteq \exists P: g=P(s,t)g = P(s, t) with h(s)=ch(s) = c and h(t)=dh(t) = d, where tt may already be _\_. The element dd is new at step kk, so ff is the only fact of CkC_k that contains it. Every atom that contains tt is mapped to a fact with dd, that is to ff, so gg is the only atom with tt, and tt occurs once in it because c≠dc \neq d. The element dd is not an individual, so tt is not in the head. Hence τ\tau has made tt into _\_, g=P(s,_)g = P(s, \_), and II is applicable. As in the first case, q′′=τ(q′[g/basic(B,s)])q'' = \tau(q'[g / \mathrm{basic}(B, s)]) is in PR and has a match in Ck−1C_{k-1}. The case ∃P−\exists P^- is symmetric.

Case f=P(c,e)f = P(c, e) made by a role inclusion from R(c,e)R(c, e): g=P(t1,t2)g = P(t_1, t_2), the inclusion is applicable to gg in any case, and gr(g,I)\mathrm{gr}(g, I) is mapped by hh to the fact R(c,e)R(c, e) of Ck−1C_{k-1}. □\square

Theorem. For a knowledge base K=(T,A)K = (T, A) with positive inclusions only, the answers of the union of the CQs of PERFECTREF(q,T)(q, T) over AA are exactly the certain answers of qq over KK.

Proof. The Corollary gives one direction. For the other, a certain answer a⃗\vec a is an answer over CC, so qq has a match in some CkC_k. The input qq is in PR (line L1). Applying Lemma 3 kk times gives a CQ of PR with a match in C0=AC_0 = A and head values a⃗\vec a. □\square

Negative inclusions

A negative inclusion B1⊑¬B2B_1 \sqsubseteq \neg B_2 or R1⊑¬R2R_1 \sqsubseteq \neg R_2 adds no facts to the chase. If KK is consistent, its models are the models of the positive part that satisfy the negative inclusions, and the chase CC is one of them, so the certain answers do not change. If KK 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 ∃y (B1(y)∧B2(y))\exists y\, (B_1(y) \wedge B_2(y)), and evaluating it over AA (Calvanese et al. 2007). With functional roles in DL-LiteF_F the same method needs one more boolean query for each functionality assertion.

Running time

Processing one CQ of PR costs O(n⋅∣T∣)O(n \cdot |T|) for lines L3 to L5 and O(n2)O(n^2) 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 (a+1)n⋅O(n∣T∣+n3)(a + 1)^n \cdot O(n |T| + n^3) with a=m(v+1)2≤(∣T∣+n)(2n+1)2a = m(v + 1)^2 \le (|T| + n)(2n + 1)^2, which is polynomial in ∣T∣|T| for a fixed query and exponential in nn. The rewriting does not depend on AA. Evaluating a fixed union of CQs over a database is a first-order query, so the data complexity of query answering is in AC0^0.

The exponential family

Let Tn={Bi⊑Ai:1≤i≤n}T_n = \{B_i \sqsubseteq A_i : 1 \le i \le n\} and qn(x)=A1(x)∧⋯∧An(x)q_n(x) = A_1(x) \wedge \dots \wedge A_n(x). Line L5 can replace each Ai(x)A_i(x) by Bi(x)B_i(x) independently, and no two atoms unify, so PR has exactly the 2n2^n CQs X1(x)∧⋯∧Xn(x)X_1(x) \wedge \dots \wedge X_n(x) with Xi∈{Ai,Bi}X_i \in \{A_i, B_i\}.

No union of CQs with fewer CQs is a rewriting. For a choice cc of one XiX_i for each ii, the ABox Ac={X1(a),…,Xn(a)}A_c = \{X_1(a), \dots, X_n(a)\} has aa as a certain answer, so some CQ uu of a correct rewriting matches AcA_c with head value aa. All atoms of uu then have predicates among X1,…,XnX_1, \dots, X_n. If uu had no atom with AiA_i or BiB_i for some ii, it would also match the ABox AcA_c without Xi(a)X_i(a), where aa is not a certain answer: the interpretation with domain {a}\{a\} that puts aa in AjA_j and BjB_j for every j≠ij \ne i, and in neither AiA_i nor BiB_i, is a model of TnT_n and of that ABox with a∉Aia \notin A_i. So the predicates of uu are exactly X1,…,XnX_1, \dots, X_n, and different choices need different CQs. ■\blacksquare

Complexity

Let qq have nn atoms and vv variables, and let mm be the number of names in TT and qq. Every query in PR has at most nn atoms over the vv variables and _\_, so PR has at most (m(v+1)2+1)n(m(v + 1)^2 + 1)^n queries, and the time is that bound times a polynomial in nn and ∣T∣|T|. For a fixed query this is polynomial in ∣T∣|T|; in nn it is exponential.

The exponential size can occur. For Tn={Bi⊑Ai:1≤i≤n}T_n = \{B_i \sqsubseteq A_i : 1 \le i \le n\} and qn(x)=A1(x)∧⋯∧An(x)q_n(x) = A_1(x) \wedge \dots \wedge A_n(x), PR has exactly 2n2^n queries, one for each choice of AiA_i or BiB_i at each position, and no union of conjunctive queries with fewer members is a correct rewriting. A positive existential query ⋀i(Ai(x)∨Bi(x))\bigwedge_i (A_i(x) \vee B_i(x)) 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 qq and TT fixed, evaluating the union over the ABox is a fixed first-order query, so the data complexity of query answering in DL-LiteR_R is in AC0^0 (AC0).

Properties

  • Data independent. The output depends only on qq and TT. One rewriting serves every ABox, and the ABox is never changed.
  • Exact. The union gives the certain answers, no more and no fewer, when (T,A)(T, A) is consistent.
  • Syntactic. Every query of PR uses only the variables of qq and the names of TT and qq; nothing anonymous is made.
  • Redundant. PR often contains queries that are contained in others, such as q1q_1 and q2q_2 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-LiteF_F 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 ∃y. B1(y)∧B2(y)\exists y.\, B_1(y) \wedge B_2(y), 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 ∃P.A⊑A\exists P.A \sqsubseteq A, 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 B⊑∃PB \sqsubseteq \exists P only to an atom P(t,_)P(t, \_). Applying it to P(x,y)P(x, y) with yy used elsewhere is unsound. With only Professor⊑∃teaches\mathit{Professor} \sqsubseteq \exists \mathit{teaches} and the query q0q_0 of the example, the wrong step gives Professor(x)∧Course(y)\mathit{Professor}(x) \wedge \mathit{Course}(y), which returns ann\mathit{ann} over {Professor(ann),Course(db)}\{\mathit{Professor}(\mathit{ann}), \mathit{Course}(\mathit{db})\}. But ann\mathit{ann} is not a certain answer, because what she teaches need not be a course.
  • Skipping τ\tau after a merge. Line L7 must apply τ\tau to the result of the reduction. Without it, q2q_2 of the example stays teaches(x,y)\mathit{teaches}(x, y), line L4 does not see that yy is unbound, q3q_3 is never made, and ann\mathit{ann} 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 ∃P⊑∃P−\exists P \sqsubseteq \exists P^- and ∃P−⊑∃P\exists P^- \sqsubseteq \exists P. 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.

perfectref_rewriting.pyI0RawGitHub
# 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-LiteR_R and DL-LiteF_F, proved that it returns exactly the certain answers, and showed that conjunctive query answering is in AC0^0 in data complexity. The OWL 2 QL profile of the Web Ontology Language is based on DL-LiteR_R. Later work studied smaller rewritings, other target languages and lower bounds on the size of rewritings.

References

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example