223P Validation Example (improved!)
2025-12-04
I recommend installing uv to handle Python dependencies and versions.
Here’s the new and improved script for doing 223P validation+inference in Python.
This uses the new OntoEnv API to manage ontology dependencies, and I’m pretty happy with how it looks now.
(I have one more simplifying change to make to the API that I’ll include in the next release; I’d like to just write
s223_with_dependencies = env.get_closure(s223_id) to both get the ontology and its dependencies in one step.)
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "rdflib",
# "pyshacl",
# "pyontoenv>=0.4.1a1",
# ]
# ///
from rdflib import Graph
import pyshacl
from ontoenv import OntoEnv
env = OntoEnv(temporary=True, no_search=True)
model_graph = Graph().parse(sys.argv[1], format="turtle")
# add a local copy of 223p.ttl to the environment
s223_id = env.add("223p.ttl")
# returns an rdflib Graph of the ontology with all its dependencies, e.g. QUDT
s223_with_dependencies = env.get_graph(s223_id)
env.import_dependencies(s223_with_dependencies)
print(len(s223_with_dependencies))
# validate your model against the SHACL shapes
valid, report_graph, report_human = pyshacl.validate(
data_graph=model_graph,
shacl_graph=s223_with_dependencies,
ont_graph=s223_with_dependencies,
advanced=True,
inplace=True, # this will add inferred triples to 'model_graph'
js=True,
allow_warnings=True,
)
print(report_human)
print(f"Is the data graph valid? {valid}")
Run the script with uv run python validate_223p.py <path/to/my_building_model.ttl>.
I recommend downloading the 223P ontology from my website. It disables some long-running rules and has a couple minor bug fixes.