OWL-RL

7.1.4 · active · verified Wed Apr 15

OWL-RL is a Python library that provides a simple implementation of the OWL2 RL Profile, as well as basic RDFS inference, on top of RDFLib. It performs mechanical forward chaining to compute the deductive closure of RDF graphs. The current version is 7.1.4, and it is actively maintained with a focus on semantic web inference capabilities.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an RDFLib graph, populate it with some triples, and then use `owlrl.DeductiveClosure` with `OWLRL_Semantics` or `RDFS_Semantics` to infer new triples based on the respective OWL 2 RL or RDFS rules. The `expand` method modifies the graph in place, adding all possible derived triples. It shows how to check for an inferred triple after expansion.

from rdflib import Graph, Literal, Namespace, RDF, RDFS
from owlrl import DeductiveClosure, OWLRL_Semantics

# Define a simple namespace for demonstration
ex = Namespace("http://example.org/ontology#")

# Create an RDFLib graph
graph = Graph()
graph.bind("ex", ex)

# Add some initial triples (asserted facts)
graph.add((ex.Person, RDF.type, RDFS.Class))
graph.add((ex.Student, RDFS.subClassOf, ex.Person))
graph.add((ex.John, RDF.type, ex.Student))

# Add a rule that says if someone is a Person, they are also an Agent
graph.add((ex.Agent, RDF.type, RDFS.Class))
graph.add((ex.Person, RDFS.subClassOf, ex.Agent))

print(f"Graph size before OWL RL expansion: {len(graph)}")

# Initialize and run the OWL 2 RL deductive closure
closure = DeductiveClosure(OWLRL_Semantics)
closure.expand(graph)

# The graph now contains inferred triples, e.g., John is a Person, and also an Agent
print(f"Graph size after OWL RL expansion: {len(graph)}")

# Check for an inferred triple
if (ex.John, RDF.type, ex.Agent) in graph:
    print("Inferred: John is an Agent.")

# You can also run RDFS inference separately
rdfs_graph = Graph()
rdfs_graph.bind("ex", ex)
rdfs_graph.add((ex.Teacher, RDFS.subClassOf, ex.Person))
rdfs_graph.add((ex.Jane, RDF.type, ex.Teacher))

print(f"\nGraph size before RDFS expansion: {len(rdfs_graph)}")
from owlrl import RDFS_Semantics
rdfs_closure = DeductiveClosure(RDFS_Semantics)
rdfs_closure.expand(rdfs_graph)
print(f"Graph size after RDFS expansion: {len(rdfs_graph)}")
if (ex.Jane, RDF.type, ex.Person) in rdfs_graph:
    print("Inferred: Jane is a Person.")

view raw JSON →