Demo: RDFS Inference

This notebook demonstrates the current end-to-end RDFS inference path at the RDFLib level:

  • add asserted triples to an RDFLib Dataset

  • let RETEStore materialize inferred triples through RETEEngine

  • confirm that the inferred goal triple is present in the graph

  • inspect the rule applications that justify that entailment

Where does this notebook fit?

Topic

Notebook

RDFS inference + derivation inspection

this notebook

OWL 2 RL inference + derivation inspection

demo-owl2-rl-inference.ipynb

RDFS inference retraction after graph updates

demo-rdfs-retraction.ipynb

Contradiction diagnostics + explanation

demo-contradiction-rules.ipynb

1. Inference-Backed RDFLib Graph

We use an in-memory RDFLib store wrapped by RETEStore so that ordinary graph updates trigger RDFS materialization. An InMemoryDerivationLogger is enabled as well so we can inspect which rule applications justify one inferred triple.

ℹ️: You don’t need a derivation_logger to use RDFS inference. If you don’t need explanations, just don’t override derivation_logger_factory

from dataclasses import replace

from rdflib import Dataset, Graph, URIRef
from rdflib_reasoning.engine import (
    RDFS_RETE_MATERIALIZED,
    InMemoryDerivationLogger,
)

spec = replace(
    RDFS_RETE_MATERIALIZED,
    derivation_logger_factory=lambda _context: InMemoryDerivationLogger(),
)

dataset: Dataset = spec.dataset()
graph: Graph = dataset.default_graph

2. Triggering Inference

We create some basic terms and construct a minimal ontology of 3 statements. Due to our forward-chaining inference engine, the production RDFS profile materializes a visible closure beyond those asserted triples. 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.

In general, using a graph like this should just look like working with a normal RDFLib graph and should be fairly intuitive.

from rdflib import RDF, RDFS

graph.bind("ex", "urn:example:")

alice = URIRef("urn:example:alice")
person = URIRef("urn:example:Person")
mammal = URIRef("urn:example:Mammal")
animal = URIRef("urn:example:Animal")

print("triples before assertions:", len(graph))

graph.add((alice, RDF.type, person))
graph.add((person, RDFS.subClassOf, mammal))
graph.add((mammal, RDFS.subClassOf, animal))

print("triples after assertions:", len(graph))
print("-" * 80)
print(graph.serialize(format="turtle"))
triples before assertions: 0
triples after assertions: 9
--------------------------------------------------------------------------------
@prefix ex: <urn:example:> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

ex:Animal a rdfs:Class .

ex:Mammal a rdfs:Class ;
    rdfs:subClassOf ex:Animal .

ex:Person a rdfs:Class ;
    rdfs:subClassOf ex:Animal,
        ex:Mammal .

ex:alice a ex:Animal,
        ex:Mammal,
        ex:Person .

3. Explaining Inferences

To explain one inferred triple, we reconstruct a proof from the derivation log captured during inference.

Here the goal is (ex:alice rdf:type ex:Animal), which should be entailed by two applications of rdfs9 over the subclass chain. That gives us a DirectProof object that we can inspect just enough to see why the inference fired.

from typing import cast

from rdflib_reasoning.engine import (
    DerivationProofReconstructor,
    DirectProof,
    RETEStore,
    TripleFact,
)

graph_engine = cast(RETEStore, dataset.store).engines[graph.identifier]
logger = cast(InMemoryDerivationLogger, graph_engine.derivation_logger)

goal = TripleFact(context=graph.identifier, triple=(alice, RDF.type, animal))
# goal = TripleFact(context=graph.identifier, triple=(animal, RDF.type, RDFS.Class))
print("Goal triple materialized:", goal.triple in graph)

proof: DirectProof = DerivationProofReconstructor().reconstruct(goal, logger.records)

print("Verdict:", proof.verdict)
print("Top-level node kind:", proof.proof.node_kind)
Goal triple materialized: True
Verdict: proved
Top-level node kind: rule_application

The derivation log includes every recorded rule application for the run, including bootstrap and bookkeeping inferences. For this tutorial, the important point is that rdfs9 appears twice: once to derive ex:Mammal, and once again to derive ex:Animal. 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.

print("Recorded derivations:", len(logger.records))
Recorded derivations: 69

3.1. Which RDFS Rules Fired?

The Mermaid rendering is the quickest way to see the two rdfs9 applications that justify the final inferred type.

from rdflib_reasoning.engine.proof_notebook import display_proof_mermaid

display_proof_mermaid(proof, namespace_manager=graph.namespace_manager)
flowchart TD
n2[["rdfs:rdfs9
IF (?x, rdfs:subClassOf, ?y) AND (?a, rdf:type, ?x) AND different_terms(?x, ?y)
THEN (?a, rdf:type, ?y)"]]
n3("(ex:alice rdf:type ex:Animal)")
n3 -->|entailed_by| n2
n4["(ex:Mammal rdfs:subClassOf ex:Animal)"]
n2 -->|had_premise| n4
n5[["rdfs:rdfs9
IF (?x, rdfs:subClassOf, ?y) AND (?a, rdf:type, ?x) AND different_terms(?x, ?y)
THEN (?a, rdf:type, ?y)"]]
n6("(ex:alice rdf:type ex:Mammal)")
n6 -->|entailed_by| n5
n7["(ex:Person rdfs:subClassOf ex:Mammal)"]
n5 -->|had_premise| n7
n8["(ex:alice rdf:type ex:Person)"]
n5 -->|had_premise| n8
n2 -->|had_premise| n6
n1>"(ex:alice rdf:type ex:Animal)"]
n1 -->|justified_by| n3

Notes

  • The graph materialization is driven entirely through the RDFLib store integration path.

  • The proof reconstruction currently uses derivation logs, not a public graph.explain(...) API.

  • If multiple derivation records can justify the same goal, the current reconstructor chooses the shallowest matching derivation.

  • For alternate renderings and raw proof inspection, see demo-proof-reconstructor.ipynb.