SHACL Validation for Ontology Compliance in Semantica: A Complete Implementation Guide
Semantica delivers an end-to-end SHACL validation pipeline that automatically generates constraint shapes from OWL-style ontology definitions and validates RDF knowledge graphs against them using a modular three-tier architecture consisting of SHACLGenerator, a pyshacl wrapper, and the OntologyEngine high-level API.
The semantica-agi/semantica repository provides a robust framework for ensuring ontology compliance through SHACL validation. This system bridges the gap between high-level ontology definitions and concrete data quality enforcement by converting semantic class structures into executable SHACL constraints. Developers can leverage this pipeline to validate incoming knowledge graphs, enforce data quality tiers, and generate machine-readable violation reports suitable for automated CI/CD integration.
Core Components of the SHACL Architecture
SHACLGenerator for Shape Construction
Located in semantica/ontology/ontology_generator.py, the SHACLGenerator class (lines 56-66) constructs a SHACLGraph composed of NodeShape and PropertyShape objects from ontology dictionaries. The generate() method translates class hierarchies, property domains, and ranges into formal SHACL constraints that mirror the ontology's structure.
Low-Level Validation Engine
The _run_pyshacl function in semantica/ontology/ontology_validator.py (lines 138-190) serves as the execution wrapper around the pyshacl library. This component executes the actual SHACL validation, parses the result graph, and instantiates SHACLViolation objects for each discovered inconsistency, isolating domain-specific logic from the generic validation engine.
High-Level Orchestration API
The OntologyEngine.validate method in semantica/ontology/engine.py (lines 31-73) provides the unified entry point. It accepts either pre-written SHACL documents or raw ontology dictionaries, automatically triggers shape generation when needed, invokes the validation engine, and returns a comprehensive SHACLValidationReport with optional English explanations.
How the SHACL Validation Pipeline Works
-
Shape Generation – The
SHACLGenerator.generate()method builds an internalSHACLGraphfrom the ontology'sclassesandpropertiesdefinitions. It applies a configurable quality tier (basic,standard, orstrict) via the_apply_quality_tiermethod, where thestricttier closes shapes to enforce "no extra properties" constraints. -
Serialization – The
SHACLGraphis serialized to Turtle (default), JSON-LD, or N-Triples viaSHACLGenerator.serialize(), preparing the constraints for the validation engine. -
Validation Execution –
OntologyEngine.validate()combines the data graph with the SHACL shapes, invoking_run_pyshaclto execute constraint checking. The engine handles both auto-generated shapes from ontology dictionaries and user-supplied SHACL files. -
Structured Reporting – The pipeline returns a
SHACLValidationReportcontaining a booleanconformsflag and categorized lists ofviolations,warnings, andinfos. EachSHACLViolationexposes machine-readable fields (focus_node,result_path,constraint) and generates human-readable explanations throughexplain_violations().
Practical Implementation Examples
Generating SHACL Shapes from an Ontology
Use the SHACLGenerator class to convert ontology definitions into executable constraints:
from semantica.ontology import SHACLGenerator
# Minimal ontology dict (normally produced by OntologyGenerator)
ontology = {
"namespace": {"base_uri": "https://example.com/"},
"classes": [
{"name": "Person", "label": "Person", "description": "A human being"},
],
"properties": [
{"name": "birthDate", "domain": "Person", "range": "xsd:date"},
],
}
shacl_gen = SHACLGenerator(base_uri="https://example.com/shapes/")
shacl_graph = shacl_gen.generate(ontology) # Build internal graph
shacl_ttl = shacl_gen.serialize(shacl_graph) # Turtle string output
print(shacl_ttl) # → SHACL Turtle ready for validation
This corresponds to the implementation in semantica/ontology/ontology_generator.py at line 998.
Validating RDF Data Graphs
The OntologyEngine orchestrates validation against generated or existing SHACL:
from semantica.ontology import OntologyEngine
# Sample data graph in Turtle (could be loaded from a file)
data_graph = """
@prefix ex: <https://example.com/> .
ex:john a ex:Person ; ex:birthDate "2024-01-01"^^xsd:date .
"""
engine = OntologyEngine() # Engine with configured store
report = engine.validate(
data_graph=data_graph,
ontology=ontology, # ← Auto-generates SHACL from dict
explain=True # ← Adds plain-English messages
)
print(report.conforms) # False if constraints broken
print(report.summary()) # Human-readable summary
for v in report.violations:
print(v.explanation) # Detailed explanation per violation
See semantica/ontology/engine.py line 31 for the implementation details.
Consuming Validation Reports
Export structured results for downstream automation:
import json
# Export the report as JSON for CI/CD or monitoring
json_report = json.dumps(report.to_dict(), indent=2)
print(json_report)
The to_dict() method is implemented in semantica/ontology/ontology_validator.py at line 27, converting the SHACLValidationReport into serializable dictionaries containing all violation metadata.
Summary
- SHACLGenerator in
semantica/ontology/ontology_generator.pycreates constraint shapes from ontology dictionaries with configurable quality tiers (basic,standard,strict). _run_pyshaclinsemantica/ontology/ontology_validator.pywraps the pyshacl library to execute validation and parse results intoSHACLViolationobjects.- OntologyEngine.validate provides a unified API in
semantica/ontology/engine.pythat automates shape generation, validation execution, and structured reporting. - The system outputs SHACLValidationReport instances containing machine-readable violation data (
focus_node,result_path,constraint) and human-readable explanations suitable for automated pipelines and debugging workflows.
Frequently Asked Questions
What are the quality tiers in Semantica's SHACL generation?
Semantica supports three quality tiers—basic, standard, and strict—applied through the internal _apply_quality_tier method. The strict tier generates closed shapes that forbid any properties not explicitly defined in the ontology, while basic allows additional properties. These tiers determine the rigor of generated constraints without requiring manual SHACL authoring.
Can I validate against existing SHACL files instead of generating from an ontology?
Yes. The OntologyEngine.validate() method accepts a shacl_graph parameter containing pre-written SHACL Turtle or RDF documents. When provided, the engine bypasses SHACLGenerator and validates directly against your custom shapes, enabling validation against external standards or domain-specific constraint sets.
How does the validation report support CI/CD automation?
The SHACLValidationReport class provides a to_dict() method that serializes the boolean conforms flag, violation lists, and severity levels into JSON format. This structured output integrates directly with automated testing frameworks, allowing build pipelines to fail when ontology compliance violations exceed defined thresholds or severity limits.
What metadata does each SHACL violation contain?
Each SHACLViolation object captures machine-readable identifiers including focus_node (the violating resource), result_path (the offending property), and constraint type, along with severity classification. The explanation property provides plain-English descriptions suitable for debugging, while the explain_violations() method aggregates multiple violations into comprehensive human-readable reports.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →