What Is SHACL Validation in Semantica? How It Works and How to Use It

SHACL validation in Semantica is a two-stage process that automatically generates SHACL shapes from OWL ontologies and validates RDF data against those constraints, producing structured violation reports with human-readable explanations.

The semantica-agi/semantica repository treats SHACL (Shapes Constraint Language) as both a generation and validation mechanism. Rather than requiring manual shape authoring, Semantica derives SHACL constraints directly from the ontologies it builds, then validates incoming RDF data against those constraints with detailed diagnostics.

How SHACL Validation Works in Semantica

The SHACL validation pipeline consists of three tightly-coupled components that bridge ontology generation and data verification.

SHACL Shape Generation

The SHACLGenerator class in semantica/ontology/ontology_generator.py builds a complete SHACLGraph from a Semantica OWL ontology dictionary. It follows a deterministic 6-stage pipeline:

  1. Indexing classes — catalog all ontology classes
  2. Creating node shapes — generate SHACL node shapes for each class
  3. Attaching property shapes — map OWL properties to SHACL constraints
  4. Propagating inheritance — apply superclass constraints to subclasses
  5. Applying quality tier — enforce "basic", "standard", or "strict" validation levels
  6. Serialising results — output Turtle, JSON-LD, or N-Triples format

You control validation strictness via the quality_tier parameter:

from semantica.ontology.ontology_generator import SHACLGenerator

# Build an ontology from your domain model

ontology = {
    "classes": [{"name": "Person", "uri": "https://example.org/Person"}],
    "properties": [
        {
            "name": "age",
            "type": "datatype",
            "range": "xsd:integer",
            "domain": ["Person"],
            "required": True,
        }
    ],
}

# Generate SHACL shapes with your chosen quality tier

shacl_gen = SHACLGenerator(quality_tier="standard")  # "basic" | "standard" | "strict"

shacl_graph = shacl_gen.generate(ontology)

# Serialize to your preferred format

shacl_ttl = shacl_gen.serialize(shacl_graph, format="turtle")

SHACL Validation Models

The semantica/ontology/ontology_validator.py module defines structured data models for capturing validation outcomes:

  • SHACLViolation — represents a single constraint violation with explanation, severity, focus_node, and result_path attributes
  • SHACLValidationReport — aggregates violations, warnings, and info messages with a top-level conforms boolean

These models transform raw pySHACL output into a machine-readable, explorable report that your application logic can act upon.

Running Validation Against RDF Data

The run_shacl_validation function orchestrates the actual validation. It accepts string-serialized graphs, invokes pyshacl.validate, and returns a populated SHACLValidationReport:

from semantica.ontology.ontology_validator import run_shacl_validation

# RDF data graph with a type error: "twenty" is not an xsd:integer

data_ttl = """
@prefix ex: <https://example.org/> .
ex:john a ex:Person ;
        ex:age "twenty" .
"""

# Validate data against the generated SHACL shapes

report = run_shacl_validation(
    data_graph_str=data_ttl,
    shacl_str=shacl_ttl,
    data_graph_format="turtle",
    shacl_format="turtle"
)

# Inspect results

print(report.conforms)        # → False

print(report.violation_count) # → 1

for violation in report.violations:
    print(violation.explanation)  # Human-readable explanation of the failure

Complete SHACL Validation Workflow Example

Combine generation and validation in a reusable helper:

from semantica.ontology.ontology_generator import SHACLGenerator
from semantica.ontology.ontology_validator import run_shacl_validation, SHACLValidationReport

def validate_ontology(ontology: dict, data_graph_str: str, quality_tier: str = "standard") -> SHACLValidationReport:
    """Generate SHACL from ontology and validate RDF data in one call."""
    gen = SHACLGenerator(quality_tier=quality_tier)
    shacl_graph = gen.generate(ontology)
    shacl_ttl = gen.serialize(shacl_graph, format="turtle")
    
    return run_shacl_validation(
        data_graph_str=data_graph_str,
        shacl_str=shacl_ttl
    )

# Usage

validation: SHACLValidationReport = validate_ontology(ontology, data_ttl)
print(validation.summary())

Quality Tiers and Their Behavior

Tier Behavior Use Case
basic Minimal constraints, required properties only Rapid prototyping, permissive ingestion
standard Full datatype, cardinality, and range constraints Production data validation
strict Additional closed-world assumptions and inverse constraints Compliance-critical applications

Set the tier in SHACLGenerator.__init__ via the quality_tier parameter (default: "standard").

Summary

  • SHACL generation in Semantica is automatic and deterministic, derived from OWL ontology definitions via SHACLGenerator
  • Three quality tiers ("basic", "standard", "strict") control validation strictness without manual shape editing
  • run_shacl_validation wraps pySHACL and rdflib to execute validation and produce structured reports
  • SHACLValidationReport and SHACLViolation provide programmatic access to both high-level conformance status and detailed violation explanations
  • The complete pipeline spans semantica/ontology/ontology_generator.py (shape generation) and semantica/ontology/ontology_validator.py (execution and reporting)

Frequently Asked Questions

What is the difference between SHACL generation and SHACL validation in Semantica?

SHACL generation creates constraint definitions from your ontology using SHACLGenerator, producing a SHACL graph that describes valid data structures. SHACL validation checks actual RDF data against those generated shapes using run_shacl_validation, reporting which constraints pass or fail. Generation happens once per ontology revision; validation happens repeatedly as new data arrives.

Does Semantica require manual SHACL authoring?

No. Semantica eliminates manual SHACL authoring by deriving shapes automatically from OWL ontology dictionaries. The SHACLGenerator class inspects class definitions, property ranges, cardinality constraints, and inheritance hierarchies to build equivalent SHACL node and property shapes. You tune behavior through the quality_tier parameter rather than writing Turtle by hand.

What libraries does Semantica use for SHACL validation?

Semantica delegates to pySHACL for core SHACL engine execution and rdflib for RDF graph parsing and serialization. These appear as dependencies in run_shacl_validation, where input strings are parsed into rdflib.Graph objects before pyshacl.validate processes them against the SHACL constraints.

How do I interpret a failed SHACL validation result?

Access the conforms boolean on SHACLValidationReport for a quick pass/fail check. For diagnostics, iterate over report.violations—each SHACLViolation provides an explanation string describing what constraint failed, which node violated it (focus_node), and which property path was involved (result_path). The violation_count property gives a quick severity summary.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →