{ "cells": [ { "cell_type": "markdown", "id": "a1125de7", "metadata": {}, "source": [ "# Demo: OWL 2 RL Inference\n", "\n", "This notebook demonstrates the current end-to-end OWL 2 RL inference path at the RDFLib level:\n", "\n", "- add asserted triples to an RDFLib `Dataset`\n", "- let `RETEStore` materialize inferred triples through `RETEEngine`\n", "- confirm that the inferred goal triple is present in the graph\n", "- inspect the rule applications that justify that entailment\n", "\n", "It is the OWL 2 RL counterpart to [demo-rdfs-inference.ipynb](demo-rdfs-inference.ipynb). The call shape is the same (`specification.dataset()`); only the ruleset and vocabulary differ.\n", "\n", "## Where does this notebook fit?\n", "\n", "| Topic | Notebook |\n", "|-------|----------|\n", "| RDFS inference + derivation inspection | [demo-rdfs-inference.ipynb](demo-rdfs-inference.ipynb) |\n", "| OWL 2 RL inference + derivation inspection | **this notebook** |\n", "| RDFS inference retraction after graph updates | [demo-rdfs-retraction.ipynb](demo-rdfs-retraction.ipynb) |\n", "| Contradiction diagnostics + explanation | [demo-contradiction-rules.ipynb](demo-contradiction-rules.ipynb) |" ] }, { "cell_type": "markdown", "id": "a4e98e09", "metadata": {}, "source": [ "## 1. Inference-Backed RDFLib Graph\n", "\n", "We use an in-memory RDFLib store wrapped by `RETEStore` so that ordinary graph updates trigger OWL 2 RL materialization.\n", "An `InMemoryDerivationLogger` is enabled as well so we can inspect which rule applications justify one inferred triple.\n", "\n", "> ℹ️: You don't need a `derivation_logger` to use OWL 2 RL inference.\n", "> If you don't need explanations, just don't override `derivation_logger_factory`.\n", "\n", "`OWL2_RL_RETE_MATERIALIZED` includes both OWL 2 RL entailment rules and contradiction diagnostics. The default recorder policy raises when a contradiction is detected; this tutorial stays in the positive-entailment path." ] }, { "cell_type": "code", "execution_count": 1, "id": "1dc83aa9", "metadata": { "execution": { "iopub.execute_input": "2026-11-07T05:18:12.965398Z", "iopub.status.busy": "2026-11-07T05:18:12.965279Z", "iopub.status.idle": "2026-11-07T05:18:13.920761Z", "shell.execute_reply": "2026-11-07T05:18:13.920179Z" } }, "outputs": [], "source": [ "from dataclasses import replace\n", "\n", "from rdflib import Dataset, Graph, URIRef\n", "from rdflib_reasoning.engine import (\n", " OWL2_RL_RETE_MATERIALIZED,\n", " InMemoryDerivationLogger,\n", ")\n", "\n", "spec = replace(\n", " OWL2_RL_RETE_MATERIALIZED,\n", " derivation_logger_factory=lambda _context: InMemoryDerivationLogger(),\n", ")\n", "\n", "dataset: Dataset = spec.dataset()\n", "graph: Graph = dataset.default_graph" ] }, { "cell_type": "markdown", "id": "2490891f", "metadata": {}, "source": [ "## 2. Triggering Inference\n", "\n", "We create some basic terms and construct a minimal ontology of 3 statements:\n", "\n", "1. `ex:Person` is declared equivalent to `ex:Human`\n", "2. `ex:Human` is a subclass of `ex:Animal`\n", "3. `ex:alice` is asserted to be a `ex:Person`\n", "\n", "Due to our forward-chaining inference engine, the OWL 2 RL profile materializes a visible closure beyond those asserted triples. In particular, class equivalence propagates typing (`cax-eqc1`), and subclass typing propagates membership (`cax-sco`). Schema rules such as `scm-eqc2` may also expand `owl:equivalentClass` into mutual `rdfs:subClassOf` links.\n", "\n", "Compared with the RDFS demo, the serialized graph is noisier: equality rules such as `eq-ref` add reflexive `owl:sameAs` statements for terms that participate in the closure. The user-facing entailment we care about here is still that `ex:alice` is typed as `ex:Human` and `ex:Animal`.\n", "\n", "In general, using a graph like this should just look like working with a normal RDFLib graph and should be fairly intuitive." ] }, { "cell_type": "code", "execution_count": 2, "id": "4a58cccf", "metadata": { "execution": { "iopub.execute_input": "2026-11-07T05:18:13.922294Z", "iopub.status.busy": "2026-11-07T05:18:13.922160Z", "iopub.status.idle": "2026-11-07T05:18:16.237366Z", "shell.execute_reply": "2026-11-07T05:18:16.236962Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "triples before assertions: 0\n", "triples after assertions: 17\n", "--------------------------------------------------------------------------------\n", "@prefix ex: .\n", "@prefix owl: .\n", "@prefix rdf: .\n", "@prefix rdfs: .\n", "\n", "rdf:type owl:sameAs rdf:type .\n", "\n", "rdfs:subClassOf owl:sameAs rdfs:subClassOf .\n", "\n", "owl:equivalentClass owl:sameAs owl:equivalentClass .\n", "\n", "owl:sameAs owl:sameAs owl:sameAs .\n", "\n", "ex:alice a ex:Animal,\n", " ex:Human,\n", " ex:Person ;\n", " owl:sameAs ex:alice .\n", "\n", "ex:Animal owl:sameAs ex:Animal .\n", "\n", "ex:Human rdfs:subClassOf ex:Animal,\n", " ex:Person ;\n", " owl:equivalentClass ex:Person ;\n", " owl:sameAs ex:Human .\n", "\n", "ex:Person rdfs:subClassOf ex:Animal,\n", " ex:Human ;\n", " owl:equivalentClass ex:Human ;\n", " owl:sameAs ex:Person .\n", "\n", "\n" ] } ], "source": [ "from rdflib import OWL, RDF, RDFS\n", "\n", "graph.bind(\"ex\", \"urn:example:\")\n", "\n", "alice = URIRef(\"urn:example:alice\")\n", "person = URIRef(\"urn:example:Person\")\n", "human = URIRef(\"urn:example:Human\")\n", "animal = URIRef(\"urn:example:Animal\")\n", "\n", "print(\"triples before assertions:\", len(graph))\n", "\n", "graph.add((person, OWL.equivalentClass, human))\n", "graph.add((human, RDFS.subClassOf, animal))\n", "graph.add((alice, RDF.type, person))\n", "\n", "print(\"triples after assertions:\", len(graph))\n", "print(\"-\" * 80)\n", "print(graph.serialize(format=\"turtle\"))" ] }, { "cell_type": "markdown", "id": "f79ed399", "metadata": {}, "source": [ "## 3. Explaining Inferences\n", "\n", "To explain one inferred triple, we reconstruct a proof from the derivation log captured during inference.\n", "\n", "Here the goal is `(ex:alice rdf:type ex:Animal)`, which should be entailed by typing across `owl:equivalentClass` and then across `rdfs:subClassOf`.\n", "That gives us a `DirectProof` object that we can inspect just enough to see why the inference fired." ] }, { "cell_type": "code", "execution_count": 3, "id": "a8b28d3d", "metadata": { "execution": { "iopub.execute_input": "2026-11-07T05:18:16.238682Z", "iopub.status.busy": "2026-11-07T05:18:16.238602Z", "iopub.status.idle": "2026-11-07T05:18:16.249142Z", "shell.execute_reply": "2026-11-07T05:18:16.248753Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Goal triple materialized: True\n", "Verdict: proved\n", "Top-level node kind: rule_application\n" ] } ], "source": [ "from typing import cast\n", "\n", "from rdflib_reasoning.engine import (\n", " DerivationProofReconstructor,\n", " DirectProof,\n", " RETEStore,\n", " TripleFact,\n", ")\n", "\n", "graph_engine = cast(RETEStore, dataset.store).engines[graph.identifier]\n", "logger = cast(InMemoryDerivationLogger, graph_engine.derivation_logger)\n", "\n", "goal = TripleFact(context=graph.identifier, triple=(alice, RDF.type, animal))\n", "print(\"Goal triple materialized:\", goal.triple in graph)\n", "\n", "proof: DirectProof = DerivationProofReconstructor().reconstruct(goal, logger.records)\n", "\n", "print(\"Verdict:\", proof.verdict)\n", "print(\"Top-level node kind:\", proof.proof.node_kind)" ] }, { "cell_type": "markdown", "id": "4051232b", "metadata": {}, "source": [ "The derivation log includes every recorded rule application for the run, including schema bookkeeping inferences from the OWL 2 RL ruleset.\n", "For this tutorial, the important point is that the reconstructed proof focuses on the rule applications that justify `ex:alice` being typed as `ex:Animal`, rather than every intermediate schema expansion." ] }, { "cell_type": "code", "execution_count": 4, "id": "82873835", "metadata": { "execution": { "iopub.execute_input": "2026-11-07T05:18:16.250467Z", "iopub.status.busy": "2026-11-07T05:18:16.250385Z", "iopub.status.idle": "2026-11-07T05:18:16.252440Z", "shell.execute_reply": "2026-11-07T05:18:16.252065Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Recorded derivations: 105\n" ] } ], "source": [ "print(\"Recorded derivations:\", len(logger.records))" ] }, { "cell_type": "markdown", "id": "903fb8fe", "metadata": {}, "source": [ "### 3.1. Which OWL 2 RL Rules Fired?\n", "\n", "The Mermaid rendering is the quickest way to see the class-equivalence and subclass typing steps that justify the final inferred type." ] }, { "cell_type": "code", "execution_count": 5, "id": "1c753c2e", "metadata": { "execution": { "iopub.execute_input": "2026-11-07T05:18:16.253614Z", "iopub.status.busy": "2026-11-07T05:18:16.253548Z", "iopub.status.idle": "2026-11-07T05:18:16.258412Z", "shell.execute_reply": "2026-11-07T05:18:16.257942Z" } }, "outputs": [ { "data": { "text/markdown": [ "```mermaid\n", "flowchart TD\n", "n2[[\"owl2-rl:cax-sco\"]]\n", "n3(\"(ex:alice rdf:type ex:Animal)\")\n", "n3 -->|entailed_by| n2\n", "n4[[\"owl2-rl:scm-sco\"]]\n", "n5(\"(ex:Person rdfs:subClassOf ex:Animal)\")\n", "n5 -->|entailed_by| n4\n", "n6[[\"owl2-rl:scm-eqc1\"]]\n", "n7(\"(ex:Person rdfs:subClassOf ex:Human)\")\n", "n7 -->|entailed_by| n6\n", "n8(\"(ex:Human rdfs:subClassOf ex:Person)\")\n", "n8 -->|entailed_by| n6\n", "n9[\"(ex:Person owl:equivalentClass ex:Human)\"]\n", "n6 -->|had_premise| n9\n", "n4 -->|had_premise| n7\n", "n10[\"(ex:Human rdfs:subClassOf ex:Animal)\"]\n", "n4 -->|had_premise| n10\n", "n2 -->|had_premise| n5\n", "n11[\"(ex:alice rdf:type ex:Person)\"]\n", "n2 -->|had_premise| n11\n", "n1>\"(ex:alice rdf:type ex:Animal)\"]\n", "n1 -->|justified_by| n3\n", "```" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "from rdflib_reasoning.engine.proof_notebook import display_proof_mermaid\n", "\n", "display_proof_mermaid(proof, namespace_manager=graph.namespace_manager)" ] }, { "cell_type": "markdown", "id": "3e44bbe7", "metadata": {}, "source": [ "## Notes\n", "\n", "- The graph materialization is driven entirely through the RDFLib store integration path via `OWL2_RL_RETE_MATERIALIZED`.\n", "- The proof reconstruction currently uses derivation logs, not a public `graph.explain(...)` API.\n", "- If multiple derivation records can justify the same goal, the current reconstructor chooses the shallowest matching derivation.\n", "- For alternate renderings and raw proof inspection, see [demo-proof-reconstructor.ipynb](demo-proof-reconstructor.ipynb).\n", "- For contradiction diagnostics when OWL 2 RL false-family rules fire, see [demo-contradiction-rules.ipynb](demo-contradiction-rules.ipynb)." ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 5 }