Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
onto_classify_el ran OWL-RL and called it EL-complete; classify by EL completion and report completeness (#324)
FABIOTESS8388136fca5a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28a447e6..4bae12b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,30 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]+### Fixed++- **`onto_classify_el` is an EL classifier now, and says when its table is not+ complete** (reported by @noahgift in #324). It ran the OWL-RL-ext rules+ under a header saying they were "sufficient for the EL fragment" and returned+ "the full classification table". RL derives through a left-hand conjunction+ or existential only for an individual, so `A ⊑ B, A ⊑ C, B ⊓ C ⊑ D` came back+ without `A ⊑ D`, as did an existential reached through a conjunctive filler,+ a domain, a range or a transitive role (MEASURED: all five missing before,+ all five returned after). The issue's second example,+ `A ⊑ ∃r.B, B ⊑ C, ∃r.C ⊑ D`, was already returned, through `scm-svf1`. The+ read-back also stopped at 100,000 rows with no field to say so: a 460-class+ chain (105,570 pairs) came back as 100,000 after about 420 s; it now+ returns all 105,570 in 5.6 s (both debug builds). The tool now normalises the axioms the tableau's+ parser reads and saturates them with the EL completion rules (CR1-CR4,+ ⊥-propagation, role hierarchy, transitive roles, ranges compiled into+ fillers). The report gains `complete` (true only inside EL with nothing set+ aside), `incompleteness`, `consistent`, `truncated` (no cap remains, always+ false) and `unsatisfiable`; outside EL the RL rules are still unioned in.+ `tests/classify_el_differential_test.rs` checks it against the `owl-dl`+ tableau on 120 generated EL TBoxes (no disagreement; dropping the range+ rule makes it report 6) and against HermiT's+ Pizza classification (every reported pair entailed).+## [2.1.0] - 2026-10-23### Fixeddiff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 43548ae1..cd633a9c 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -98,7 +98,7 @@ it withheld.| `onto_cache_remove` | Remove a cached ontology by name. || `onto_cache_status` | Inspect the compile cache: active ontology, all cached entries, and the cache configuration (TTL, auto_refresh, dir). || `onto_certify_action` | CIVeX-style causal certificate for a proposed state-changing ontology action. |-| `onto_classify_el` | Classify the loaded ontology in the OWL-EL fragment (#30). |+| `onto_classify_el` | Classify the loaded ontology by OWL 2 EL completion (#30, #324); `complete: true` only when the input is inside EL. || `onto_clear` | Clear all triples from the in-memory ontology store and unload the active registry slot (cache file is preserved) || `onto_closure_diff` | Which CONCLUSIONS a projection preserves, with no goals supplied. || `onto_coevolve_dependency_graph` | Build the shape→OWL-dependency map for a SHACL document. |diff --git a/src/classify_el.rs b/src/classify_el.rsindex 3502a07b..93b431b3 100644--- a/src/classify_el.rs+++ b/src/classify_el.rs@@ -1,85 +1,708 @@-//! OWL-EL classification primitive (#30, ELK-style).+//! OWL 2 EL classification by completion (#30, #324).//!-//! OWL 2 EL is the polynomial-time profile suitable for ontologies with-//! large class hierarchies but limited expressivity. ELK (Kazakov et al.,-//! 2011) is the canonical EL reasoner.+//! The axioms are read by the tableau's own OWL parser+//! ([`crate::tableaux::parse_owl`]), normalised into the four EL normal forms+//! (`A ⊑ B`, `A₁ ⊓ A₂ ⊑ B`, `A ⊑ ∃r.B`, `∃r.A ⊑ B`, with `B` possibly `⊥`),+//! and saturated with the completion rules of Baader, Brandt and Lutz,+//! *Pushing the EL Envelope* (IJCAI 2005): CR1-CR4 for told subsumption,+//! conjunction and existentials, ⊥-propagation, the role hierarchy, and+//! transitive roles as the chain `r ∘ r ⊑ r`. Ranges are compiled into the+//! existential's filler (`A ⊑ ∃r.B` becomes `A ⊑ ∃r.(B ⊓ ran(r))`), which is the+//! treatment in *Pushing the EL Envelope Further* (OWLED 2008).//!-//! ## Scope+//! ## What it guarantees//!-//! This primitive runs the existing OWL-RL reasoner on the loaded graph-//! (which is sufficient for the EL fragment: subClassOf transitivity,-//! property hierarchies, existential restrictions via owl-rl-ext) and-//! emits the **full classification table** — every materialised-//! `?sub rdfs:subClassOf ?super` pair, sorted, deduplicated.+//! Every subsumption it reports is entailed: each normalised axiom is entailed+//! by the original or is a definition of a fresh name, and an axiom it cannot+//! normalise is dropped, which only loses entailments. The table between named+//! classes is COMPLETE, and the report says `complete: true`, only when nothing+//! was dropped: no axiom outside EL, no inverse or functional role, and none of+//! the constructs the parser does not read at all (`owl:propertyChainAxiom`,+//! nominals, datatype restrictions, and the rest of+//! [`DlReasoner::unmodelled_constructs`]). Otherwise `complete` is false and+//! `incompleteness` names what was set aside.//!-//! For deep SHIQ subsumption, use `onto_dl_check` / `onto_dl_explain` which-//! delegate to the tableaux reasoner.+//! ## Why it is not OWL-RL any more+//!+//! Until #324 this module ran the `owl-rl-ext` rules and read back+//! `rdfs:subClassOf`, under a header saying that was "sufficient for the EL+//! fragment". It is not: RL derives through a left-hand conjunction or+//! existential only for an individual (`cls-int1`, `cls-svf1`), never at TBox+//! level, so `A ⊑ B, A ⊑ C, B ⊓ C ⊑ D` came back without `A ⊑ D`, and so did+//! `A ⊑ ∃r.B, B ⊑ C, ∃r.C ⊑ D`. The read-back also stopped at 100,000 rows+//! without saying so. The RL rules still run, but only on input outside EL,+//! where they can add sound subsumptions the EL fragment does not see (through+//! `owl:allValuesFrom`, for instance); their answer is unioned in, read from the+//! store directly with no row cap.+//!+//! For a complete classification of input outside EL, use `onto_reason` with+//! `owl-dl`, which reports its own `complete` flag.use crate::graph::GraphStore;use crate::reason::Reasoner;+use crate::tableaux::{Concept, DlReasoner, ParseResult, parse_owl};use serde::Serialize;+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};use std::sync::Arc;+const RDFS_SUBCLASS: &str = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";+const OWL_THING: &str = "<http://www.w3.org/2002/07/owl#Thing>";+#[derive(Clone, Debug, Serialize)]pub struct ClassificationReport {+ /// `el-completion` when the EL saturation alone produced the table,+ /// `el-completion+owl-rl-ext` when the RL rules were unioned in because the+ /// input is outside EL.pub profile: String,+ /// True only when the table is every subsumption between named classes+ /// that the ontology entails (see the module docs for the conditions).+ pub complete: bool,+ /// Why `complete` is false, one entry per cause. Empty when complete.+ pub incompleteness: Vec<String>,+ /// False when the saturation derived `⊤ ⊑ ⊥` or an individual in `⊥`. An+ /// inconsistent ontology entails every subsumption, and the table lists+ /// only those derived, so `complete` is then false.+ pub consistent: bool,+ /// Always false: there is no row cap. Kept so a consumer can check for a+ /// cut-off table instead of assuming there is none; the old read-back+ /// stopped at 100,000 rows and had no way to say so.+ pub truncated: bool,+ /// Named classes classified, `owl:Thing` excluded.pub class_count: usize,pub subsumption_count: usize,- /// `[sub, super]` pairs. Sorted by sub then super for stable output.+ /// `[sub, super]` pairs between named classes, `owl:Thing` and `X ⊑ X`+ /// left out. Sorted by sub then super for stable output. An unsatisfiable+ /// class is under every class and its pairs are not listed; it is in+ /// `unsatisfiable` instead, as HermiT reports it.pub subsumptions: Vec<(String, String)>,+ pub unsatisfiable: Vec<String>,+}++/// Node 0 is `⊤` and node 1 is `⊥` in every normalised TBox.+const TOP: usize = 0;+const BOTTOM: usize = 1;++/// The construct that keeps a concept out of EL on the side it occurs.+fn construct(c: &Concept) -> &'static str {+ match c {+ Concept::ForAll(..) => "owl:allValuesFrom",+ Concept::Or(..) => "owl:unionOf",+ Concept::NegAtom(..) => "owl:complementOf",+ Concept::MaxCard(..) => "max cardinality",+ Concept::MinCard(..) => "min cardinality above 1",+ _ => "a class expression",+ }+}++/// The first sub-expression that cannot stand on the LEFT of an EL axiom.+fn lhs_offender(c: &Concept) -> Option<&'static str> {+ match c {+ Concept::Top | Concept::Bottom | Concept::Atom(_) | Concept::MinCard(_, 0, _) => None,+ Concept::And(cs) | Concept::Or(cs) => cs.iter().find_map(lhs_offender),+ Concept::Exists(_, f) | Concept::MinCard(_, 1, f) => lhs_offender(f),+ other => Some(construct(other)),+ }+}++/// Whether a concept can stand on the RIGHT, possibly after the Horn rewrite+/// `X ⊑ ¬N ⊔ D` into `X ⊓ N ⊑ D` (`add_horn`).+fn rhs_el(c: &Concept) -> bool {+ match c {+ Concept::Top | Concept::Bottom | Concept::Atom(_) | Concept::MinCard(_, 0, _) => true,+ Concept::And(cs) => cs.iter().all(rhs_el),+ Concept::Exists(_, f) | Concept::MinCard(_, _, f) => rhs_el(f),+ other => horn_split(other).is_some(),+ }+}++/// `D₁ ⊔ … ⊔ Dₙ` as (the negated disjuncts that are EL left-hand sides, the+/// one remaining positive disjunct), or `None` when more than one disjunct is+/// positive or the positive one is not EL. NNF writes `A ⊑ ¬B` and `A ⊑ ¬∃r.B`+/// as `¬B` and `∀r.¬B`, so disjointness reaches this module in that form and+/// has to be read back out of it.+fn horn_split(c: &Concept) -> Option<(Vec<Concept>, Option<&Concept>)> {+ let disjuncts: Vec<&Concept> = match c {+ Concept::Or(cs) => cs.iter().collect(),+ other => vec![other],+ };+ let mut negs = Vec::new();+ let mut pos = None;+ for d in disjuncts {+ // `x ⊑ D ⊔ R` is `x ⊓ ¬D ⊑ R` exactly, so any disjunct whose+ // negation is an EL left-hand side can move across.+ let n = d.negate();+ if lhs_offender(&n).is_none() {+ negs.push(n);+ // The positive disjunct must be one `add_rhs` takes directly: the four+ // forms excluded here are the ones it sends back to this function.+ } else if pos.is_none()+ && !matches!(d, Concept::Or(_) | Concept::ForAll(..) | Concept::NegAtom(_) | Concept::MaxCard(..))+ && rhs_el(d)+ {+ pos = Some(d);+ } else {+ return None;+ }+ }+ Some((negs, pos))+}++/// A TBox in EL normal form over dense node ids.+struct Normalised {+ told: Vec<Vec<usize>>,+ /// `conj[a]` holds `(b, c)` for every `a ⊓ b ⊑ c`, stored under both conjuncts.+ conj: Vec<Vec<(usize, usize)>>,+ /// `ex_rhs[a]` holds `(r, b)` for every `a ⊑ ∃r.b`.+ ex_rhs: Vec<Vec<(u32, usize)>>,+ /// `∃r.a ⊑ b`, keyed by `(r, a)` and by `r`.+ ex_lhs: HashMap<(u32, usize), Vec<usize>>,+ ex_lhs_by_role: HashMap<u32, Vec<(usize, usize)>>,+ ranges: HashMap<u32, Vec<usize>>,+ atom_node: HashMap<u32, usize>,+ lhs_cache: HashMap<Concept, usize>,+ rhs_cache: HashMap<Concept, usize>,+ thing: u32,+ nothing: u32,+ /// Constructs set aside, with how many axioms (or parts of one) each cost.+ dropped: BTreeMap<String, usize>,+}++impl Normalised {+ fn new(thing: u32, nothing: u32) -> Self {+ let mut n = Self {+ told: Vec::new(),+ conj: Vec::new(),+ ex_rhs: Vec::new(),+ ex_lhs: HashMap::new(),+ ex_lhs_by_role: HashMap::new(),+ ranges: HashMap::new(),+ atom_node: HashMap::new(),+ lhs_cache: HashMap::new(),+ rhs_cache: HashMap::new(),+ thing,+ nothing,+ dropped: BTreeMap::new(),+ };+ n.fresh();+ n.fresh();+ n+ }++ fn len(&self) -> usize {+ self.told.len()+ }++ fn fresh(&mut self) -> usize {+ self.told.push(Vec::new());+ self.conj.push(Vec::new());+ self.ex_rhs.push(Vec::new());+ self.told.len() - 1+ }++ fn atom(&mut self, a: u32) -> usize {+ if a == self.thing {+ return TOP;+ }+ if a == self.nothing {+ return BOTTOM;+ }+ if let Some(&n) = self.atom_node.get(&a) {+ return n;+ }+ let n = self.fresh();+ self.atom_node.insert(a, n);+ n+ }++ fn drop_part(&mut self, why: String) {+ *self.dropped.entry(why).or_default() += 1;+ }++ fn add_conj(&mut self, a: usize, b: usize, c: usize) {+ self.conj[a].push((b, c));+ if a != b {+ self.conj[b].push((a, c));+ }+ }++ fn add_ex_lhs(&mut self, r: u32, a: usize, b: usize) {+ self.ex_lhs.entry((r, a)).or_default().push(b);+ self.ex_lhs_by_role.entry(r).or_default().push((a, b));+ }++ /// A node `n` with `c ⊑ n`. The caller has checked `lhs_offender(c)`.+ fn name_lhs(&mut self, c: &Concept) -> usize {+ match c {+ Concept::Top | Concept::MinCard(_, 0, _) => return TOP,+ Concept::Bottom => return BOTTOM,+ Concept::Atom(a) => return self.atom(*a),+ _ => {}+ }+ if let Some(&n) = self.lhs_cache.get(c) {+ return n;+ }+ let n = match c {+ Concept::And(cs) => {+ let parts: Vec<usize> = cs.iter().map(|p| self.name_lhs(p)).collect();+ let mut acc = parts[0];+ for &p in &parts[1..] {+ let f = self.fresh();+ self.add_conj(acc, p, f);+ acc = f;+ }+ acc+ }+ // `C₁ ⊔ C₂ ⊑ n` is `C₁ ⊑ n` and `C₂ ⊑ n`: two EL axioms, no+ // disjunction left to reason with.+ Concept::Or(cs) => {+ let f = self.fresh();+ for p in cs {+ let pn = self.name_lhs(p);+ self.told[pn].push(f);+ }+ f+ }+ Concept::Exists(r, filler) | Concept::MinCard(r, _, filler) => {+ let fn_ = self.name_lhs(filler);+ let f = self.fresh();+ self.add_ex_lhs(*r, fn_, f);+ f+ }+ other => unreachable!("lhs_offender admitted {other:?}"),+ };+ self.lhs_cache.insert(c.clone(), n);+ n+ }++ /// A node `n` with `n ⊑ c`, as far as `c` is EL.+ fn name_rhs(&mut self, c: &Concept) -> usize {+ match c {+ Concept::Top => return TOP,+ Concept::Bottom => return BOTTOM,+ Concept::Atom(a) => return self.atom(*a),+ _ => {}+ }+ if let Some(&n) = self.rhs_cache.get(c) {+ return n;+ }+ let n = self.fresh();+ self.rhs_cache.insert(c.clone(), n);+ self.add_rhs(n, c);+ n+ }++ /// `x ⊑ c`, keeping every EL part of `c` and dropping the rest. Dropping a+ /// conjunct on the right weakens the axiom, which is sound.+ fn add_rhs(&mut self, x: usize, c: &Concept) {+ match c {+ Concept::Top | Concept::MinCard(_, 0, _) => {}+ Concept::Bottom => self.told[x].push(BOTTOM),+ Concept::Atom(a) => {+ let a = self.atom(*a);+ self.told[x].push(a);+ }+ Concept::And(cs) => {+ for p in cs {+ self.add_rhs(x, p);+ }+ }+ Concept::Exists(r, f) | Concept::MinCard(r, 1, f) => {+ let fnode = self.name_rhs(f);+ self.ex_rhs[x].push((*r, fnode));+ }+ // `≥n r.F` entails `∃r.F`, so reading it as that is sound; what is+ // lost is the count.+ Concept::MinCard(r, _, f) => {+ self.drop_part("min cardinality above 1 on the right-hand side, read as owl:someValuesFrom".into());+ let fnode = self.name_rhs(f);+ self.ex_rhs[x].push((*r, fnode));+ }+ other => self.add_horn(x, other),+ }+ }++ /// `x ⊑ ¬N₁ ⊔ … ⊔ ¬Nₖ ⊔ D` is `x ⊓ N₁ ⊓ … ⊓ Nₖ ⊑ D` (D may be absent,+ /// then `⊥`). Anything with two positive disjuncts is outside EL.+ fn add_horn(&mut self, x: usize, c: &Concept) {+ let Some((negs, pos)) = horn_split(c) else {+ self.drop_part(format!("{} on the right-hand side", construct(c)));+ return;+ };+ let mut acc = x;+ for n in &negs {+ let nn = self.name_lhs(n);+ let f = self.fresh();+ self.add_conj(acc, nn, f);+ acc = f;+ }+ match pos {+ Some(d) => self.add_rhs(acc, d),+ None => self.told[acc].push(BOTTOM),+ }+ }++ fn add_axiom(&mut self, sub: &Concept, sup: &Concept) {+ if let Some(why) = lhs_offender(sub) {+ self.drop_part(format!("{why} on the left-hand side"));+ return;+ }+ let x = self.name_lhs(sub);+ self.add_rhs(x, sup);+ }+}++/// The reflexive-transitive closure of `rdfs:subPropertyOf` from `r`.+fn role_sups(sub_to_super: &HashMap<u32, HashSet<u32>>, r: u32) -> Vec<u32> {+ let mut seen = BTreeSet::from([r]);+ let mut stack = vec![r];+ while let Some(x) = stack.pop() {+ for &y in sub_to_super.get(&x).into_iter().flatten() {+ if seen.insert(y) {+ stack.push(y);+ }+ }+ }+ seen.into_iter().collect()+}++enum Step {+ Add(usize, usize),+ Link(usize, u32, usize),+}++/// The completion sets: `s[x]` is every node `x` is subsumed by, and the+/// `(x, r, y)` edges are the derived `x ⊑ ∃r.y`.+struct Saturation<'a> {+ t: &'a Normalised,+ sups: HashMap<u32, Vec<u32>>,+ sub_to_super: &'a HashMap<u32, HashSet<u32>>,+ transitive: &'a HashSet<u32>,+ s: Vec<HashSet<usize>>,+ context: Vec<bool>,+ edges: HashSet<(usize, u32, usize)>,+ pred: Vec<Vec<(usize, u32)>>,+ succ: Vec<Vec<(u32, usize)>>,+ queue: Vec<Step>,+}++impl<'a> Saturation<'a> {+ fn new(t: &'a Normalised, p: &'a ParseResult) -> Self {+ let n = t.len();+ Self {+ t,+ sups: HashMap::new(),+ sub_to_super: &p.sub_to_super,+ transitive: &p.transitive_roles,+ s: vec![HashSet::new(); n],+ context: vec![false; n],+ edges: HashSet::new(),+ pred: vec![Vec::new(); n],+ succ: vec![Vec::new(); n],+ queue: Vec::new(),+ }+ }++ fn init(&mut self, x: usize) {+ if !self.context[x] {+ self.context[x] = true;+ self.queue.push(Step::Add(x, x));+ self.queue.push(Step::Add(x, TOP));+ }+ }++ fn sups_of(&mut self, r: u32) -> Vec<u32> {+ let sts = self.sub_to_super;+ self.sups.entry(r).or_insert_with(|| role_sups(sts, r)).clone()+ }++ fn run(&mut self) {+ while let Some(step) = self.queue.pop() {+ match step {+ Step::Add(x, a) => self.add(x, a),+ Step::Link(x, r, y) => self.link(x, r, y),+ }+ }+ }++ fn add(&mut self, x: usize, a: usize) {+ if !self.s[x].insert(a) {+ return;+ }+ let t = self.t;+ // CR1: a ⊑ b.+ for &b in &t.told[a] {+ self.queue.push(Step::Add(x, b));+ }+ // CR2: a ⊓ o ⊑ c.+ for &(o, c) in &t.conj[a] {+ if self.s[x].contains(&o) {+ self.queue.push(Step::Add(x, c));+ }+ }+ // CR3: a ⊑ ∃r.b.+ for &(r, b) in &t.ex_rhs[a] {+ self.init(b);+ self.queue.push(Step::Link(x, r, b));+ }+ // CR4 and ⊥: every predecessor of x learns what x's new subsumer gives it.+ for i in 0..self.pred[x].len() {+ let (p, r) = self.pred[x][i];+ if a == BOTTOM {+ self.queue.push(Step::Add(p, BOTTOM));+ }+ for &b in t.ex_lhs.get(&(r, a)).into_iter().flatten() {+ self.queue.push(Step::Add(p, b));+ }+ }+ }++ fn link(&mut self, x: usize, r: u32, y: usize) {+ let t = self.t;+ for s in self.sups_of(r) {+ if !self.edges.insert((x, s, y)) {+ continue;+ }+ self.pred[y].push((x, s));+ self.succ[x].push((s, y));+ if self.s[y].contains(&BOTTOM) {+ self.queue.push(Step::Add(x, BOTTOM));+ }+ // CR4: ∃s.a ⊑ b with a ⊑ y's subsumers; walk whichever side is shorter.+ if let Some(rules) = t.ex_lhs_by_role.get(&s) {+ if rules.len() <= self.s[y].len() {+ for &(a, b) in rules {+ if self.s[y].contains(&a) {+ self.queue.push(Step::Add(x, b));+ }+ }+ } else {+ for &a in &self.s[y] {+ for &b in t.ex_lhs.get(&(s, a)).into_iter().flatten() {+ self.queue.push(Step::Add(x, b));+ }+ }+ }+ }+ // A transitive role is the chain s ∘ s ⊑ s.+ if self.transitive.contains(&s) {+ for &(s2, z) in &self.succ[y] {+ if s2 == s {+ self.queue.push(Step::Link(x, s, z));+ }+ }+ for &(w, s2) in &self.pred[x] {+ if s2 == s {+ self.queue.push(Step::Link(w, s, y));+ }+ }+ }+ }+ }}-/// Classify the loaded ontology in the OWL-EL fragment. Runs OWL-RL-/// materialisation in a sandbox so the original graph is not mutated.+/// Classify the loaded ontology. Works on a copy of the triples, so the+/// graph is not mutated.pub fn classify(graph: &Arc<GraphStore>) -> anyhow::Result<ClassificationReport> {- let sandbox = Arc::new(GraphStore::new());let triples = graph.all_triples()?;- if !triples.is_empty() {- let mut nt = String::with_capacity(triples.len() * 64);- for (s, p, o) in &triples {- nt.push_str(s);- nt.push(' ');- nt.push_str(p);- nt.push(' ');- nt.push_str(o);- nt.push_str(" .\n");- }- sandbox.load_turtle(&nt, None)?;- }- let _ = Reasoner::run(&sandbox, "owl-rl-ext", true)?;-- let q = "SELECT ?sub ?sup WHERE { ?sub <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?sup } LIMIT 100000";- let js = sandbox.sparql_select(q)?;- let v: serde_json::Value = serde_json::from_str(&js)?;- let rows = v["results"].as_array().cloned().unwrap_or_default();-- let mut subs: Vec<(String, String)> = rows+ let p = parse_owl(triples.clone());+ let mut t = Normalised::new(p.thing_id, p.nothing_id);++ for (sub, sup) in &p.axioms {+ t.add_axiom(sub, sup);+ }+ for (a, b) in &p.disjoint_pairs {+ t.add_axiom(&Concept::And(vec![a.clone(), b.clone()]), &Concept::Bottom);+ }+ for (r, c) in &p.role_domains {+ t.add_axiom(&Concept::Exists(*r, Box::new(Concept::Top)), c);+ }+ for (r, c) in &p.role_ranges {+ let n = t.name_rhs(c);+ t.ranges.entry(*r).or_default().push(n);+ }++ // Ranges into fillers: `a ⊑ ∃r.b` becomes `a ⊑ ∃r.(b ⊓ ran(s))` for every+ // `s ⊒ r`. Done once over the TBox's existentials, which is all of them:+ // the saturation derives edges, never new existential axioms.+ let mut range_of: HashMap<u32, Vec<usize>> = HashMap::new();+ let mut ranged: HashMap<(usize, u32), usize> = HashMap::new();+ for a in 0..t.len() {+ for i in 0..t.ex_rhs[a].len() {+ let (r, b) = t.ex_rhs[a][i];+ let rans = range_of+ .entry(r)+ .or_insert_with(|| {+ role_sups(&p.sub_to_super, r)+ .iter()+ .flat_map(|s| t.ranges.get(s).into_iter().flatten().copied())+ .collect()+ })+ .clone();+ if rans.is_empty() {+ continue;+ }+ let node = match ranged.get(&(b, r)) {+ Some(&n) => n,+ None => {+ let n = t.fresh();+ t.told[n].push(b);+ t.told[n].extend(rans);+ ranged.insert((b, r), n);+ n+ }+ };+ t.ex_rhs[a][i] = (r, node);+ }+ }++ // The ABox, each individual as its own node. An assertion `a r b` is+ // `a ⊑ ∃r.b` with the ranges put on `b` itself, not on a filler copy: the+ // r-successor IS `b`, and a range that only reached a copy would miss+ // `∃s.(C ⊓ E) ⊑ ⊥` when `C` comes from the range and `E` from `b`'s type.+ // It matters only for consistency: no ABox fact changes a TBox subsumption+ // of a consistent ontology.+ let mut individuals: BTreeSet<usize> = BTreeSet::new();+ for (&ind, types) in &p.individual_types {+ let i = t.atom(ind);+ individuals.insert(i);+ for &c in types {+ let c = t.atom(c);+ t.told[i].push(c);+ }+ }+ for (&ind, cs) in &p.individual_anon_types {+ let i = t.atom(ind);+ individuals.insert(i);+ for c in cs {+ t.add_rhs(i, c);+ }+ }+ for &(a, r, b) in &p.role_assertions {+ let (ia, ib) = (t.atom(a), t.atom(b));+ individuals.insert(ia);+ individuals.insert(ib);+ t.ex_rhs[ia].push((r, ib));+ for s in role_sups(&p.sub_to_super, r) {+ if let Some(rans) = t.ranges.get(&s).cloned() {+ t.told[ib].extend(rans);+ }+ }+ }++ let classes: Vec<(u32, usize)> = {+ let mut v: Vec<(u32, usize)> = p+ .named_classes+ .iter()+ .filter(|&&c| c != p.thing_id && c != p.nothing_id)+ .map(|&c| (c, t.atom(c)))+ .collect();+ v.sort_unstable();+ v+ };++ let mut sat = Saturation::new(&t, &p);+ sat.init(TOP);+ for &(_, n) in &classes {+ sat.init(n);+ }+ for &i in &individuals {+ sat.init(i);+ }+ sat.run();++ let consistent = !sat.s[TOP].contains(&BOTTOM)+ && individuals.iter().all(|&i| !sat.s[i].contains(&BOTTOM));+ let node_class: HashMap<usize, u32> = classes.iter().map(|&(c, n)| (n, c)).collect();+ let name = |c: u32| p.interner.resolve(c).trim_matches(|ch| ch == '<' || ch == '>').to_string();++ let mut unsat: BTreeSet<String> = BTreeSet::new();+ let mut subs: BTreeSet<(String, String)> = BTreeSet::new();+ for &(c, n) in &classes {+ if sat.s[n].contains(&BOTTOM) {+ unsat.insert(name(c));+ continue;+ }+ for d in &sat.s[n] {+ if let Some(&dc) = node_class.get(d)+ && dc != c+ {+ subs.insert((name(c), name(dc)));+ }+ }+ }++ let mut incompleteness: Vec<String> = t+ .dropped.iter()- .filter_map(|r| {- let s = r["sub"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();- let o = r["sup"].as_str()?.trim_matches(|c| c == '<' || c == '>').to_string();- // Skip trivial X ⊑ X and X ⊑ owl:Thing.- if s == o || o == "http://www.w3.org/2002/07/owl#Thing" {- return None;- }- Some((s, o))- })+ .map(|(why, n)| format!("{why}: {n} axiom part(s) outside OWL 2 EL not used")).collect();- subs.sort();- subs.dedup();-- // Count distinct class IRIs participating in any subsumption.- let mut classes: std::collections::BTreeSet<&String> = std::collections::BTreeSet::new();- for (s, o) in &subs {- classes.insert(s);- classes.insert(o);+ if !p.inverse_roles.is_empty() {+ incompleteness.push(format!(+ "inverse or symmetric roles ({} role(s)): outside OWL 2 EL, each read as an unrelated role",+ p.inverse_roles.len()+ ));+ }+ let functional = p.functional_roles.len() + p.inv_functional_roles.len();+ if functional > 0 {+ incompleteness.push(format!(+ "functional or inverse-functional roles ({functional}): outside OWL 2 EL, not used"+ ));+ }+ for (construct, n) in DlReasoner::unmodelled_constructs(graph) {+ incompleteness.push(format!("{construct} ({n} occurrence(s)): not read by the parser"));}+ if !consistent {+ incompleteness.push(+ "the ontology is inconsistent: it entails every subsumption, and only the derived ones are listed"+ .into(),+ );+ }+ let complete = incompleteness.is_empty();++ // Outside EL the RL rules can still find sound subsumptions the EL part+ // does not reach, so they are unioned in. On EL input they could add+ // nothing: the table is already every entailed subsumption.+ let profile = if complete {+ "el-completion"+ } else {+ let sandbox = Arc::new(GraphStore::new());+ if !triples.is_empty() {+ let mut nt = String::with_capacity(triples.len() * 64);+ for (s, p, o) in &triples {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ sandbox.load_ntriples(&nt)?;+ }+ Reasoner::run(&sandbox, "owl-rl-ext", true)?;+ let named: HashSet<String> = classes.iter().map(|&(c, _)| name(c)).collect();+ for (s, pr, o) in sandbox.all_triples()? {+ if pr != RDFS_SUBCLASS || o == OWL_THING || s == o {+ continue;+ }+ let (s, o) = (s.trim_matches(|c| c == '<' || c == '>'), o.trim_matches(|c| c == '<' || c == '>'));+ if named.contains(s) && named.contains(o) && !unsat.contains(s) {+ subs.insert((s.to_string(), o.to_string()));+ }+ }+ "el-completion+owl-rl-ext"+ };+ let subsumptions: Vec<(String, String)> = subs.into_iter().collect();Ok(ClassificationReport {- profile: "owl-rl-ext".to_string(),+ profile: profile.to_string(),+ complete,+ incompleteness,+ consistent,+ truncated: false,class_count: classes.len(),- subsumption_count: subs.len(),- subsumptions: subs,+ subsumption_count: subsumptions.len(),+ subsumptions,+ unsatisfiable: unsat.into_iter().collect(),})}@@ -137,4 +760,162 @@ mod tests {let _ = classify(&g).unwrap();assert_eq!(pre, g.triple_count());}++ const PREFIXES: &str = "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://ex.org/> .\n";++ fn classify_ttl(body: &str) -> ClassificationReport {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(&format!("{PREFIXES}{body}"), None).unwrap();+ classify(&g).unwrap()+ }++ fn has(r: &ClassificationReport, sub: &str, sup: &str) -> bool {+ r.subsumptions+ .iter()+ .any(|(s, o)| s == &format!("http://ex.org/{sub}") && o == &format!("http://ex.org/{sup}"))+ }++ /// #324, first example: CR2 (a conjunction on the left-hand side).+ #[test]+ fn conjunction_on_the_left_is_derived() {+ let r = classify_ttl(+ "ex:A rdfs:subClassOf ex:B , ex:C .+ [ owl:intersectionOf ( ex:B ex:C ) ] rdfs:subClassOf ex:D .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ }++ /// #324, second example: CR3 + CR4 (an existential on the left-hand side).+ #[test]+ fn existential_on_the_left_is_derived() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:B ] .+ ex:B rdfs:subClassOf ex:C .+ [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:C ] rdfs:subClassOf ex:D .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ }++ /// The issue's second example does come back from OWL-RL — `scm-svf1`+ /// turns `B ⊑ C` into `∃r.B ⊑ ∃r.C` because both restrictions are in the+ /// graph — so it does not separate the two engines. These do: a filler+ /// reached through a conjunction, a domain, and a transitive role. Measured+ /// on the RL read-back before #324, none of the three `A ⊑ D` came back.+ #[test]+ fn existential_through_a_conjunctive_filler_is_derived() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:B ] .+ ex:B rdfs:subClassOf ex:C , ex:E .+ [ a owl:Restriction ; owl:onProperty ex:r ;+ owl:someValuesFrom [ owl:intersectionOf ( ex:C ex:E ) ] ] rdfs:subClassOf ex:D .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ assert!(r.complete, "{:?}", r.incompleteness);+ }++ #[test]+ fn the_domain_of_an_existential_is_derived() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty ; rdfs:domain ex:D .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:B ] .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ assert!(r.complete, "{:?}", r.incompleteness);+ }++ #[test]+ fn an_existential_through_a_transitive_role_is_derived() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty , owl:TransitiveProperty .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:B ] .+ ex:B rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:C ] .+ [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:C ] rdfs:subClassOf ex:D .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ assert!(r.complete, "{:?}", r.incompleteness);+ }++ /// A range reaches the filler: `A ⊑ ∃r.B`, `range(r) = C`, `∃r.(B ⊓ C) ⊑ D`.+ #[test]+ fn a_range_reaches_the_existential_filler() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty ; rdfs:range ex:C .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:someValuesFrom ex:B ] .+ [ a owl:Restriction ; owl:onProperty ex:r ;+ owl:someValuesFrom [ owl:intersectionOf ( ex:B ex:C ) ] ] rdfs:subClassOf ex:D .",+ );+ assert!(has(&r, "A", "D"), "A ⊑ D missing; got {:?}", r.subsumptions);+ }++ /// Disjointness reaches an existential's filler and makes `A` unsatisfiable.+ #[test]+ fn bottom_propagates_back_through_an_existential() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty .+ ex:B owl:disjointWith ex:C .+ ex:A rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ;+ owl:someValuesFrom [ owl:intersectionOf ( ex:B ex:C ) ] ] .",+ );+ assert_eq!(r.unsatisfiable, vec!["http://ex.org/A".to_string()]);+ assert!(r.complete && r.consistent, "{:?}", r.incompleteness);+ }++ /// Input outside EL says so and names why, and still gets the sound part.+ #[test]+ fn input_outside_el_is_marked_incomplete() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty .+ ex:A rdfs:subClassOf ex:B , [ owl:unionOf ( ex:C ex:E ) ] .+ ex:F rdfs:subClassOf [ a owl:Restriction ; owl:onProperty ex:r ; owl:allValuesFrom ex:B ] .",+ );+ assert!(!r.complete);+ assert_eq!(r.profile, "el-completion+owl-rl-ext");+ assert!(r.incompleteness.iter().any(|w| w.contains("owl:unionOf")), "{:?}", r.incompleteness);+ assert!(r.incompleteness.iter().any(|w| w.contains("owl:allValuesFrom")), "{:?}", r.incompleteness);+ assert!(has(&r, "A", "B"));+ }++ /// A property chain is EL but the parser does not read it, so the table+ /// cannot be called complete.+ #[test]+ fn an_unread_construct_is_marked_incomplete() {+ let r = classify_ttl(+ "ex:r a owl:ObjectProperty . ex:s a owl:ObjectProperty . ex:t a owl:ObjectProperty .+ ex:t owl:propertyChainAxiom ( ex:r ex:s ) .+ ex:A rdfs:subClassOf ex:B .",+ );+ assert!(!r.complete);+ assert!(r.incompleteness.iter().any(|w| w.contains("owl:propertyChainAxiom")), "{:?}", r.incompleteness);+ }++ /// An individual in two disjoint classes makes the ontology inconsistent,+ /// and an inconsistent ontology entails every subsumption.+ #[test]+ fn an_inconsistent_abox_is_reported() {+ let r = classify_ttl(+ "ex:B owl:disjointWith ex:C .+ ex:a a ex:B , ex:C .",+ );+ assert!(!r.consistent);+ assert!(!r.complete);+ }++ /// #324: the read-back used to stop at 100,000 rows and say nothing. A+ /// chain of 460 classes has 460·459/2 = 105,570 strict subsumptions.+ #[test]+ fn a_table_over_one_hundred_thousand_pairs_is_not_cut() {+ let n = 460;+ let mut body = String::new();+ for i in 1..n {+ body.push_str(&format!("ex:C{i} rdfs:subClassOf ex:C{} .\n", i - 1));+ }+ let r = classify_ttl(&body);+ assert_eq!(r.subsumption_count, n * (n - 1) / 2);+ assert_eq!(r.subsumptions.len(), r.subsumption_count);+ assert!(r.complete && !r.truncated);+ }}diff --git a/src/server.rs b/src/server.rsindex 74aa315f..6f3a5921 100644--- a/src/server.rs+++ b/src/server.rs@@ -1577,7 +1577,7 @@ impl OpenOntologiesServer {.unwrap_or_else(|e| Self::err_json(format!("serialization: {}", e)))}- #[tool(name = "onto_classify_el", description = "Classify the loaded ontology in the OWL-EL fragment (#30). Materialises OWL-RL-ext entailments in a sandbox copy of the graph and emits every distinct subsumption `?sub rdfs:subClassOf ?super` (transitive closure, deduplicated, owl:Thing-trivial pairs removed). For deep SHIQ subsumption, use `onto_dl_check` / `onto_dl_explain`.")]+ #[tool(name = "onto_classify_el", description = "Classify the loaded ontology by OWL 2 EL completion (#30, #324): conjunction and existentials on both sides, domains, ranges, disjointness, role hierarchy, transitive roles. Returns every derived subsumption between named classes (`owl:Thing` and `X ⊑ X` left out, unsatisfiable classes listed separately), no row cap. `complete: true` only when the input is inside EL and nothing was set aside; otherwise `complete: false`, `incompleteness` names each cause, and the OWL-RL-ext rules are unioned in (sound, not complete). For a complete classification outside EL, use `onto_reason` with `owl-dl`.")]async fn onto_classify_el(&self) -> String {match crate::classify_el::classify(&self.graph) {Ok(r) => serde_json::to_string(&r)diff --git a/src/tableaux.rs b/src/tableaux.rsindex c638ed07..e6e98d15 100644--- a/src/tableaux.rs+++ b/src/tableaux.rs@@ -1290,35 +1290,45 @@ fn parse_card_value(literal: &str) -> Option<u32> {literal.parse().ok()}-struct ParseResult {- interner: Interner,- axioms: Vec<(Concept, Concept)>,- named_classes: HashSet<u32>,- thing_id: u32,- nothing_id: u32,- transitive_roles: HashSet<u32>,- sub_to_super: HashMap<u32, HashSet<u32>>,- disjoint_pairs: Vec<(Concept, Concept)>,- inverse_roles: HashMap<u32, u32>,- functional_roles: HashSet<u32>,- inv_functional_roles: HashSet<u32>,+pub(crate) struct ParseResult {+ pub(crate) interner: Interner,+ pub(crate) axioms: Vec<(Concept, Concept)>,+ pub(crate) named_classes: HashSet<u32>,+ pub(crate) thing_id: u32,+ pub(crate) nothing_id: u32,+ pub(crate) transitive_roles: HashSet<u32>,+ pub(crate) sub_to_super: HashMap<u32, HashSet<u32>>,+ pub(crate) disjoint_pairs: Vec<(Concept, Concept)>,+ pub(crate) inverse_roles: HashMap<u32, u32>,+ pub(crate) functional_roles: HashSet<u32>,+ pub(crate) inv_functional_roles: HashSet<u32>,/// rdfs:domain / rdfs:range, kept as ROLE METADATA rather than GCIs./// Encoding them as axioms puts a non-atomic left-hand side into the GCI/// list, which lands a disjunction on every node and multiplies branching.- role_domains: Vec<(u32, Concept)>,- role_ranges: Vec<(u32, Concept)>,- individual_types: HashMap<u32, HashSet<u32>>,+ pub(crate) role_domains: Vec<(u32, Concept)>,+ pub(crate) role_ranges: Vec<(u32, Concept)>,+ pub(crate) individual_types: HashMap<u32, HashSet<u32>>,/// Individuals typed directly by an ANONYMOUS class expression/// (`:a rdf:type [ owl:Restriction … ]`, an intersection/union/complement)./// These carry no named-class id, so they cannot live in `individual_types`,/// but the constraint they impose is real and an inconsistency arising from/// it must be found rather than silently dropped.- individual_anon_types: HashMap<u32, Vec<Concept>>,- role_assertions: Vec<(u32, u32, u32)>,+ pub(crate) individual_anon_types: HashMap<u32, Vec<Concept>>,+ pub(crate) role_assertions: Vec<(u32, u32, u32)>,/// Datatype-property assertions, for realization only; never tableau edges.- data_assertions: Vec<(u32, u32, u32)>,+ pub(crate) data_assertions: Vec<(u32, u32, u32)>,/// Named class → the concept it is defined as being equivalent to.- definitions: HashMap<u32, Concept>,+ pub(crate) definitions: HashMap<u32, Concept>,+}++/// The OWL parser's reading of a triple set, before `ProcessedTBox` absorbs it.+///+/// `onto_classify_el` normalises these axioms for EL completion rather than+/// writing a second RDF-to-DL reader: one parser means the tableau and the EL+/// saturation disagree only where their rules do, never where their reading+/// of `owl:Restriction` or `rdf:List` does.+pub(crate) fn parse_owl(triples: Vec<(String, String, String)>) -> ParseResult {+ OwlParser::new(triples).parse()}// ── Absorption ──────────────────────────────────────────────────────────diff --git a/tests/classify_el_differential_test.rs b/tests/classify_el_differential_test.rsnew file mode 100644index 00000000..a80681f9--- /dev/null+++ b/tests/classify_el_differential_test.rs@@ -0,0 +1,182 @@+//! `onto_classify_el` against the tableau and against HermiT (#324).+//!+//! The EL saturation claims `complete: true` on input inside EL. That claim is+//! only worth what an independent engine says about it, so two are used:+//!+//! - the `owl-dl` tableau, which since #313 classifies Pizza exactly as+//! HermiT 1.4.3 does, on generated EL TBoxes that use every rule the+//! saturation has (conjunction and existentials on both sides, domains,+//! ranges, disjointness, a role hierarchy and a transitive role). Where the+//! tableau calls itself complete the two tables must be equal, pair for pair.+//! - HermiT's own classification of Pizza, recorded in+//! `tests/fixtures/hermit/pizza_classification.tsv`. Pizza is outside EL+//! (universals, unions, functional roles, nominals), so the saturation must+//! say it is incomplete, and every pair it reports must be one HermiT+//! entails.++use std::collections::BTreeSet;+use std::sync::Arc;++use open_ontologies::classify_el::classify;+use open_ontologies::graph::GraphStore;+use open_ontologies::reason::Reasoner;++const EX: &str = "http://example.org/";+const PIZZA: &str = "https://raw.githubusercontent.com/owlcs/pizza-ontology/refs/heads/master/pizza.owl#";++fn local(s: &str, ns: &str) -> String {+ s.trim_start_matches('<').trim_end_matches('>').trim_start_matches(ns).to_string()+}++/// The tableau's table: (pairs between satisfiable named classes, unsatisfiable classes, complete).+fn tableau(store: &Arc<GraphStore>, ns: &str) -> (BTreeSet<(String, String)>, BTreeSet<String>, bool) {+ let v: serde_json::Value = serde_json::from_str(&Reasoner::run(store, "owl-dl", false).unwrap()).unwrap();+ let unsat: BTreeSet<String> = v["unsatisfiable_classes"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| local(s.as_str().unwrap(), ns))+ .collect();+ let mut pairs = BTreeSet::new();+ for row in v["classification"].as_array().unwrap() {+ let c = local(row["class"].as_str().unwrap(), ns);+ if unsat.contains(&c) {+ continue;+ }+ for s in row["superclasses"].as_array().unwrap() {+ let s = s.as_str().unwrap();+ if !s.ends_with("#Thing>") && local(s, ns) != c {+ pairs.insert((c.clone(), local(s, ns)));+ }+ }+ }+ (pairs, unsat, v["complete"] == true)+}++/// A small deterministic generator: no crate, no seed file, the same TBoxes on+/// every machine.+struct Lcg(u64);+impl Lcg {+ fn next(&mut self, n: u64) -> u64 {+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ (self.0 >> 33) % n+ }+}++fn some(r: &str, filler: &str) -> String {+ format!("[ a owl:Restriction ; owl:onProperty ex:{r} ; owl:someValuesFrom {filler} ]")+}++fn generated_el_tbox(seed: u64) -> String {+ let mut g = Lcg(seed);+ let c = |g: &mut Lcg| format!("ex:C{}", g.next(7));+ let roles = ["r", "s"];+ let mut ttl = String::from("ex:r a owl:ObjectProperty . ex:s a owl:ObjectProperty .\n");+ for i in 0..7 {+ ttl.push_str(&format!("ex:C{i} a owl:Class .\n"));+ }+ if g.next(2) == 0 {+ ttl.push_str("ex:s rdfs:subPropertyOf ex:r .\n");+ }+ if g.next(2) == 0 {+ ttl.push_str("ex:r a owl:TransitiveProperty .\n");+ }+ for _ in 0..(6 + g.next(5)) {+ let role = roles[g.next(2) as usize];+ let (a, b, d) = (c(&mut g), c(&mut g), c(&mut g));+ let axiom = match g.next(9) {+ 0 | 1 => format!("{a} rdfs:subClassOf {b} ."),+ 2 => format!("{a} rdfs:subClassOf {} .", some(role, &b)),+ 3 => format!("{} rdfs:subClassOf {b} .", some(role, &a)),+ 4 => format!("[ owl:intersectionOf ( {a} {b} ) ] rdfs:subClassOf {d} ."),+ 5 => format!("{a} owl:equivalentClass [ owl:intersectionOf ( {b} {} ) ] .", some(role, &d)),+ 6 => format!("ex:{role} rdfs:domain {a} ."),+ 7 => format!("ex:{role} rdfs:range {a} ."),+ _ => {+ if g.next(3) == 0 {+ format!("{a} owl:disjointWith {b} .")+ } else {+ format!("{a} rdfs:subClassOf {} .", some(role, &format!("[ owl:intersectionOf ( {b} {d} ) ]")))+ }+ }+ };+ ttl.push_str(&axiom);+ ttl.push('\n');+ }+ ttl+}++#[test]+fn el_saturation_equals_the_tableau_on_generated_el_tboxes() {+ let prefixes = "@prefix owl: <http://www.w3.org/2002/07/owl#> .\n\+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\+ @prefix ex: <http://example.org/> .\n";+ let mut compared = 0;+ let mut pairs_compared = 0;+ let mut disagreements: Vec<String> = Vec::new();+ for seed in 1..=120u64 {+ let ttl = generated_el_tbox(seed);+ let store = Arc::new(GraphStore::new());+ store.load_turtle(&format!("{prefixes}{ttl}"), None).unwrap();+ let el = classify(&store).unwrap();+ assert!(el.complete, "seed {seed} is EL by construction: {:?}\n{ttl}", el.incompleteness);++ let (want, want_unsat, tableau_complete) = tableau(&store, EX);+ if !tableau_complete {+ continue;+ }+ compared += 1;+ let got: BTreeSet<(String, String)> =+ el.subsumptions.iter().map(|(a, b)| (local(a, EX), local(b, EX))).collect();+ let got_unsat: BTreeSet<String> = el.unsatisfiable.iter().map(|s| local(s, EX)).collect();+ pairs_compared += want.len();+ if got != want || got_unsat != want_unsat {+ disagreements.push(format!(+ "seed {seed}: missed {:?}, extra {:?}, unsat el {:?} vs tableau {:?}\n{ttl}",+ want.difference(&got).collect::<Vec<_>>(),+ got.difference(&want).collect::<Vec<_>>(),+ got_unsat,+ want_unsat+ ));+ }+ }+ // Every generated TBox must reach the oracle, or this test proves nothing.+ assert_eq!(compared, 120, "the tableau must decide every generated TBox");+ assert!(pairs_compared > 200, "the corpus is too thin to say anything: {pairs_compared} pairs");+ assert!(disagreements.is_empty(), "{} disagreement(s):\n{}", disagreements.len(), disagreements.join("\n"));+}++#[test]+fn pizza_is_marked_incomplete_and_every_reported_pair_is_one_hermit_entails() {+ let store = Arc::new(GraphStore::new());+ store.load_file("benchmark/reference/pizza-reference.owl").unwrap();+ let el = classify(&store).unwrap();+ assert!(!el.complete);+ assert!(!el.incompleteness.is_empty());++ let fixture = std::fs::read_to_string("tests/fixtures/hermit/pizza_classification.tsv").unwrap();+ let mut hermit: BTreeSet<(String, String)> = BTreeSet::new();+ let mut hermit_unsat: BTreeSet<String> = BTreeSet::new();+ for line in fixture.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {+ let (a, b) = line.split_once('\t').unwrap();+ if a == "UNSAT" {+ hermit_unsat.insert(b.to_string());+ } else {+ hermit.insert((a.to_string(), b.to_string()));+ }+ }+ let got: BTreeSet<(String, String)> =+ el.subsumptions.iter().map(|(a, b)| (local(a, PIZZA), local(b, PIZZA))).collect();+ let got_unsat: BTreeSet<String> = el.unsatisfiable.iter().map(|s| local(s, PIZZA)).collect();+ // A pair under a class HermiT finds unsatisfiable is entailed too.+ let wrong: Vec<_> = got.iter().filter(|(a, _)| !hermit_unsat.contains(a)).filter(|p| !hermit.contains(*p)).collect();+ assert!(wrong.is_empty(), "pairs HermiT does not entail: {wrong:?}");+ assert!(got_unsat.is_subset(&hermit_unsat), "{got_unsat:?} vs {hermit_unsat:?}");+ eprintln!(+ "pizza: {} of HermiT's {} pairs, {} of {} unsatisfiable classes",+ got.intersection(&hermit).count(),+ hermit.len(),+ got_unsat.len(),+ hermit_unsat.len()+ );+}