# How to Validate Ontology Shapes Using Semantica's OntologyValidator

> Learn to validate ontology shapes with Semantica's OntologyValidator. Ensure structural integrity and RDF graph conformance against SHACL shapes for robust data quality.

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

---

**Semantica provides a dual-layer validation system where the `OntologyValidator` class checks structural integrity and logical consistency, while the `run_shacl_validation` function verifies RDF graph conformance against SHACL shapes, returning detailed report objects for programmatic inspection.**

The semantica-agi/semantica framework ships with a dedicated validation subsystem to ensure ontology quality at both the dictionary and RDF graph levels. Located in [`semantica/ontology/ontology_validator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/ontology_validator.py), these tools allow you to validate ontology shapes programmatically, whether you are verifying internal schema structure or enforcing domain-specific constraints via SHACL.

## Installing SHACL Dependencies

Before running SHACL shape validation, you must install the optional dependencies that power the RDF processing pipeline. The validator relies on **rdflib** for graph parsing and **pySHACL** for constraint checking.

Install the required extras using pip:

```bash
pip install semantica[shacl]

```

If these dependencies are missing, the validator raises an informative `ImportError` directing you to the correct installation command. The structural validation components in `OntologyValidator` do not require these external libraries.

## Structural and Logical Validation with OntologyValidator

The `OntologyValidator` class performs structural checks on ontology dictionaries, verifying that required sections such as `classes` and `properties` are present and correctly formatted. It can also interface with symbolic reasoners like HermiT or Pellet to check logical consistency and satisfiability.

### Validating Ontology Dictionaries

To validate an ontology defined as a Python dictionary, instantiate `OntologyValidator` and call the `validate()` method. This returns a `ValidationResult` object containing validity flags and any diagnostic messages.

```python
from semantica.ontology.ontology_validator import OntologyValidator

ontology_dict = {
    "name": "MyOntology",
    "classes": [...],
    "properties": [...],
}

validator = OntologyValidator()
result = validator.validate(ontology_dict)

print("Valid?", result.valid)
print("Consistent:", result.consistent)
print("Warnings:", result.warnings)

```

### Understanding the ValidationResult Object

The `ValidationResult` object returned by `validate()` encapsulates the overall health of your ontology. Key attributes include:

- **`valid`** – Boolean indicating whether the ontology passes structural requirements.
- **`consistent`** – Boolean indicating logical consistency (when a reasoner is attached).
- **`satisfiable`** – Boolean indicating whether the ontology is satisfiable.
- **`errors`** – List of critical issues preventing validation.
- **`warnings`** – List of non-critical suggestions for improvement.

For a quick convenience wrapper that handles instantiation internally, use the `validate_ontology()` function:

```python
from semantica.ontology.ontology_validator import validate_ontology

summary = validate_ontology(ontology_dict)
print(summary)

# Output: {'valid': True, 'consistent': True, 'satisfiable': True, 'errors': [], 'warnings': []}

```

## SHACL Shape Validation for RDF Graphs

When you need to validate that generated RDF data conforms to specific shapes, Semantica provides the `run_shacl_validation` function. This tool parses data graphs and SHACL constraints using **rdflib**, executes validation via **pySHACL**, and produces a comprehensive `SHACLValidationReport`.

### Running SHACL Validation

The `run_shacl_validation` function accepts string representations of your data graph and SHACL shapes (typically in Turtle format), returning a rich report object.

```python
from semantica.ontology.ontology_validator import run_shacl_validation

# RDF data graph (Turtle format)

data_ttl = """
@prefix ex: <http://example.org/> .
ex:Alice a ex:Person ; ex:age 30 .
"""

# SHACL shapes describing required structure

shacl_ttl = """
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix ex: <http://example.org/> .

ex:PersonShape a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:property [
        sh:path ex:age ;
        sh:datatype xsd:integer ;
        sh:minCount 1 ;
        sh:maxCount 1 ;
    ] .
"""

report = run_shacl_validation(data_ttl, shacl_ttl)
print(report.summary())

```

### Inspecting SHACLValidationReport and Violations

The `SHACLValidationReport` object provides granular access to validation outcomes without requiring external LLM calls. Key components include:

- **`conforms`** – Boolean indicating overall graph conformance.
- **`violations`** – List of `SHACLViolation` objects representing constraint failures.
- **`warnings`** – List of non-critical constraint violations.
- **`infos`** – List of informational constraint notices.

Each `SHACLViolation` captures the **focus node**, **constraint component**, **severity level**, and **message**. To generate plain-English explanations of failures, call `explain_violations()` before iterating over the results:

```python
report.explain_violations()
for v in report.violations:
    print(v.explanation)

```

## Complete Validation Workflow Example

A robust validation pipeline typically combines both approaches: first verifying the ontology structure, then ensuring RDF output conforms to shape constraints.

```python
from semantica.ontology.ontology_validator import (
    OntologyValidator,
    run_shacl_validation,
    validate_ontology
)

# Step 1: Validate ontology dictionary structure

ontology_dict = {
    "name": "ResearchOntology",
    "classes": [{"name": "Paper", "superclasses": ["Document"]}],
    "properties": [{"name": "hasAuthor", "domain": "Paper", "range": "Person"}]
}

structural_result = validate_ontology(ontology_dict)
assert structural_result["valid"], "Ontology structure is invalid"

# Step 2: Convert to RDF (implementation-specific)

rdf_data = convert_to_rdf(ontology_dict)  # Your serialization logic

# Step 3: Validate against SHACL shapes

shacl_shapes = load_shacl_shapes()  # Your shapes file

report = run_shacl_validation(rdf_data, shacl_shapes)

if not report.conforms:
    report.explain_violations()
    for v in report.violations:
        print(f"Violation at {v.focus_node}: {v.explanation}")
else:
    print("Graph conforms to all SHACL constraints.")

```

## Summary

- **Install optional dependencies** with `pip install semantica[shacl]` to enable RDF and SHACL processing capabilities.
- **Use `OntologyValidator`** in [`semantica/ontology/ontology_validator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/ontology/ontology_validator.py) to check structural integrity and logical consistency of ontology dictionaries.
- **Call `run_shacl_validation`** to verify that RDF graphs conform to SHACL shape constraints without external API dependencies.
- **Inspect `ValidationResult` and `SHACLValidationReport`** objects to access detailed diagnostics, including the `explain_violations()` method for human-readable error messages.
- **Leverage the convenience wrapper `validate_ontology()`** for quick structural checks that return serializable dictionaries.

## Frequently Asked Questions

### What is the difference between OntologyValidator and run_shacl_validation?

**`OntologyValidator`** validates the internal structure and logical consistency of ontology dictionaries (Python objects), checking for required keys like `classes` and `properties`. **`run_shacl_validation`** operates on serialized RDF graphs (strings or files) to check conformance against SHACL shapes, ensuring that the actual RDF output meets domain-specific constraints.

### How do I install the dependencies required for SHACL validation?

Install the optional extra using `pip install semantica[shacl]`, which includes **rdflib** for RDF parsing and **pySHACL** for constraint validation. If these are missing, the validator raises an `ImportError` with specific installation instructions rather than failing silently.

### Can I generate human-readable explanations of validation failures without using an LLM?

Yes. The `SHACLValidationReport` object provides an `explain_violations()` method that populates the `explanation` attribute on each `SHACLViolation` with plain-English descriptions. This operates entirely locally using **pySHACL** and does not require external API calls to language models.

### What file formats does the SHACL validator support?

The validator accepts RDF data and SHACL shapes as strings in **Turtle** (TTL), **JSON-LD**, or **XML** formats, parsed via **rdflib**. When working with files, you can read them into strings before passing them to `run_shacl_validation()`, as the function expects string inputs rather than file paths directly.