# SHACL Validation for Ontology Compliance in Semantica: A Complete Implementation Guide

> Implement SHACL validation for ontology compliance in Semantica. This guide details automatic shape generation from OWL ontologies and RDF graph validation with a three-tier architecture.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-18

---

**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`](https://github.com/semantica-agi/semantica/blob/main/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`](https://github.com/semantica-agi/semantica/blob/main/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`](https://github.com/semantica-agi/semantica/blob/main/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

1. **Shape Generation** – The `SHACLGenerator.generate()` method builds an internal `SHACLGraph` from the ontology's `classes` and `properties` definitions. It applies a configurable **quality tier** (`basic`, `standard`, or `strict`) via the `_apply_quality_tier` method, where the `strict` tier closes shapes to enforce "no extra properties" constraints.

2. **Serialization** – The `SHACLGraph` is serialized to Turtle (default), JSON-LD, or N-Triples via `SHACLGenerator.serialize()`, preparing the constraints for the validation engine.

3. **Validation Execution** – `OntologyEngine.validate()` combines the data graph with the SHACL shapes, invoking `_run_pyshacl` to execute constraint checking. The engine handles both auto-generated shapes from ontology dictionaries and user-supplied SHACL files.

4. **Structured Reporting** – The pipeline returns a `SHACLValidationReport` containing a boolean `conforms` flag and categorized lists of `violations`, `warnings`, and `infos`. Each `SHACLViolation` exposes machine-readable fields (`focus_node`, `result_path`, `constraint`) and generates human-readable explanations through `explain_violations()`.

## Practical Implementation Examples

### Generating SHACL Shapes from an Ontology

Use the `SHACLGenerator` class to convert ontology definitions into executable constraints:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/ontology_generator.py) at line 998.

### Validating RDF Data Graphs

The `OntologyEngine` orchestrates validation against generated or existing SHACL:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/engine.py) line 31 for the implementation details.

### Consuming Validation Reports

Export structured results for downstream automation:

```python
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`](https://github.com/semantica-agi/semantica/blob/main/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.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/ontology_generator.py) creates constraint shapes from ontology dictionaries with configurable quality tiers (`basic`, `standard`, `strict`).
- **`_run_pyshacl`** in [`semantica/ontology/ontology_validator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/ontology_validator.py) wraps the pyshacl library to execute validation and parse results into `SHACLViolation` objects.
- **OntologyEngine.validate** provides a unified API in [`semantica/ontology/engine.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/engine.py) that 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.