{ "cells": [ { "cell_type": "markdown", "id": "7fb27b941602401d91542211134fc71a", "metadata": {}, "source": [ "# Demo: RDFS Inference\n", "\n", "This notebook demonstrates the current end-to-end RDFS 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", "## Where does this notebook fit?\n", "\n", "| Topic | Notebook |\n", "|-------|----------|\n", "| RDFS inference + derivation inspection | **this notebook** |\n", "| OWL 2 RL inference + derivation inspection | [demo-owl2-rl-inference.ipynb](demo-owl2-rl-inference.ipynb) |\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": "c39fad81", "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 RDFS 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 RDFS inference.\n", "> If you don't need explanations, just don't override `derivation_logger_factory`" ] }, { "cell_type": "code", "execution_count": 1, "id": "baeada82", "metadata": {}, "outputs": [], "source": [ "from dataclasses import replace\n", "\n", "from rdflib import Dataset, Graph, URIRef\n", "from rdflib_reasoning.engine import (\n", " RDFS_RETE_MATERIALIZED,\n", " InMemoryDerivationLogger,\n", ")\n", "\n", "spec = replace(\n", " RDFS_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": "e7c5e24a", "metadata": {}, "source": [ "## 2. Triggering Inference\n", "\n", "We create some basic terms and construct a minimal ontology of 3 statements.\n", "Due to our forward-chaining inference engine, the production RDFS profile materializes a visible closure beyond those asserted triples.\n", "At the moment this example lands at 16 triples: useful user-facing entailments plus some remaining background RDFS closure, while selected schema-only consequences stay internal.\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": "8dd0d8092fe74a7c96281538738b07e2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "triples before assertions: 0\n", "triples after assertions: 9\n", "--------------------------------------------------------------------------------\n", "@prefix ex: .\n", "@prefix rdfs: .\n", "\n", "ex:Animal a rdfs:Class .\n", "\n", "ex:Mammal a rdfs:Class ;\n", " rdfs:subClassOf ex:Animal .\n", "\n", "ex:Person a rdfs:Class ;\n", " rdfs:subClassOf ex:Animal,\n", " ex:Mammal .\n", "\n", "ex:alice a ex:Animal,\n", " ex:Mammal,\n", " ex:Person .\n", "\n", "\n" ] } ], "source": [ "from rdflib import RDF, RDFS\n", "\n", "graph.bind(\"ex\", \"urn:example:\")\n", "\n", "alice = URIRef(\"urn:example:alice\")\n", "person = URIRef(\"urn:example:Person\")\n", "mammal = URIRef(\"urn:example:Mammal\")\n", "animal = URIRef(\"urn:example:Animal\")\n", "\n", "print(\"triples before assertions:\", len(graph))\n", "\n", "graph.add((alice, RDF.type, person))\n", "graph.add((person, RDFS.subClassOf, mammal))\n", "graph.add((mammal, RDFS.subClassOf, animal))\n", "\n", "print(\"triples after assertions:\", len(graph))\n", "print(\"-\" * 80)\n", "print(graph.serialize(format=\"turtle\"))" ] }, { "cell_type": "markdown", "id": "115cf4aa", "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 two applications of `rdfs9` over the subclass chain.\n", "That gives us a `DirectProof` object that we can inspect just enough to see why the inference fired.\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "46052ca0", "metadata": {}, "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", "# goal = TripleFact(context=graph.identifier, triple=(animal, RDF.type, RDFS.Class))\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": "9c45f69f", "metadata": {}, "source": [ "The derivation log includes every recorded rule application for the run, including bootstrap and bookkeeping inferences.\n", "For this tutorial, the important point is that `rdfs9` appears twice: once to derive `ex:Mammal`, and once again to derive `ex:Animal`.\n", "The raw log is therefore noisier than the question we care about here, so we use the reconstructed proof below to focus on the rule applications that justify the inferred triple." ] }, { "cell_type": "code", "execution_count": 4, "id": "2af6a54a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Recorded derivations: 69\n" ] } ], "source": [ "print(\"Recorded derivations:\", len(logger.records))" ] }, { "cell_type": "markdown", "id": "96c10116", "metadata": {}, "source": [ "### 3.1. Which RDFS Rules Fired?\n", "\n", "The Mermaid rendering is the quickest way to see the two `rdfs9` applications that justify the final inferred type." ] }, { "cell_type": "code", "execution_count": 5, "id": "2ea77918", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "```mermaid\n", "flowchart TD\n", "n2[[\"rdfs:rdfs9\n", "IF (?x, rdfs:subClassOf, ?y) AND (?a, rdf:type, ?x) AND different_terms(?x, ?y)\n", "THEN (?a, rdf:type, ?y)\"]]\n", "n3(\"(ex:alice rdf:type ex:Animal)\")\n", "n3 -->|entailed_by| n2\n", "n4[\"(ex:Mammal rdfs:subClassOf ex:Animal)\"]\n", "n2 -->|had_premise| n4\n", "n5[[\"rdfs:rdfs9\n", "IF (?x, rdfs:subClassOf, ?y) AND (?a, rdf:type, ?x) AND different_terms(?x, ?y)\n", "THEN (?a, rdf:type, ?y)\"]]\n", "n6(\"(ex:alice rdf:type ex:Mammal)\")\n", "n6 -->|entailed_by| n5\n", "n7[\"(ex:Person rdfs:subClassOf ex:Mammal)\"]\n", "n5 -->|had_premise| n7\n", "n8[\"(ex:alice rdf:type ex:Person)\"]\n", "n5 -->|had_premise| n8\n", "n2 -->|had_premise| n6\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": "10185d26023b46108eb7d9f57d49d2b3", "metadata": {}, "source": [ "## Notes\n", "\n", "- The graph materialization is driven entirely through the RDFLib store integration path.\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`." ] } ], "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 }