Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(#318): SHACL Shape Generation & Validation (Phase 1 + Phase 2)

KaifAhmad1dae368532c8d
diff --git a/README.md b/README.md
index 9a19ff57..5db9030d 100644
--- a/README.md
+++ b/README.md
@@ -78,6 +78,14 @@ See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the full per-contributor breakdown
---
+## Unreleased / Coming Next
+
+| Area | Highlights |
+|------|-----------|
+| **SHACL Constraints** | `OntologyEngine.to_shacl()` auto-derives SHACL shapes from any OWL ontology; `validate_graph()` returns structured `SHACLValidationReport` with plain-English violation explanations; three quality tiers (`"basic"`, `"standard"`, `"strict"`); three output formats (Turtle, JSON-LD, N-Triples); 3-level inheritance propagation |
+
+---
+
## Features
### Context & Decision Intelligence
@@ -146,6 +154,7 @@ See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the full per-contributor breakdown
- **Parquet** — `ParquetExporter` for entities, relationships, and full KG export
- **ArangoDB AQL** — ready-to-run INSERT statements via `ArangoAQLExporter`
- **OWL ontologies** — export generated ontologies in Turtle or RDF/XML
+- **SHACL shapes** — export auto-derived constraint shapes via `RDFExporter.export_shacl()` (`.ttl`, `.jsonld`, `.nt`, `.shacl`)
### Pipeline & Production
- **Pipeline builder** — `PipelineBuilder` with stage chaining and parallel workers
@@ -158,6 +167,11 @@ See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the full per-contributor breakdown
- **Auto-generation** — derive OWL ontologies from knowledge graphs via `OntologyGenerator`
- **Import** — load existing OWL, RDF, Turtle, JSON-LD ontologies via `OntologyImporter`
- **Validation** — HermiT/Pellet compatible consistency checking
+- **SHACL shape generation** — `OntologyEngine.to_shacl()` auto-derives SHACL node and property shapes from any Semantica ontology dict; zero hand-authoring; deterministic (same ontology → same shapes)
+- **SHACL validation** — `OntologyEngine.validate_graph()` runs shapes against a data graph and returns a `SHACLValidationReport` with machine-readable violations and plain-English explanations
+- **Quality tiers** — `"basic"` (structure + cardinality), `"standard"` (+ enumerations, inheritance), `"strict"` (+ `sh:closed` rejects undeclared properties)
+- **Inheritance propagation** — child shapes automatically include all ancestor property shapes (up to 3+ levels), cycle-safe
+- **Three output formats** — Turtle (`.ttl`), JSON-LD, N-Triples; file export via `export_shacl()`
---
@@ -172,7 +186,7 @@ See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the full per-contributor breakdown
| `semantica.vector_store` | FAISS, Pinecone, Weaviate, Qdrant, Milvus, PgVector, in-memory; hybrid & filtered search |
| `semantica.export` | RDF (Turtle/JSON-LD/N-Triples/XML), Parquet, ArangoDB AQL, CSV, YAML, OWL, graph formats |
| `semantica.ingest` | Files (PDF, DOCX, CSV, HTML), web crawl, feeds, databases, Snowflake, MCP, email, repositories |
-| `semantica.ontology` | Auto-generation (6-stage pipeline), OWL/RDF export, import (OWL/RDF/Turtle/JSON-LD), validation, versioning |
+| `semantica.ontology` | Auto-generation (6-stage pipeline), OWL/RDF export, import (OWL/RDF/Turtle/JSON-LD), validation, versioning, **SHACL shape generation & validation** |
| `semantica.pipeline` | Pipeline DSL, parallel workers, validation, retry policies, failure handling, resource scheduling |
| `semantica.graph_store` | Graph database backends — Neo4j, FalkorDB, Apache AGE, Amazon Neptune; Cypher queries |
| `semantica.embeddings` | Text embedding generation — Sentence-Transformers, FastEmbed, OpenAI, BGE; similarity calculation |
@@ -654,6 +668,85 @@ ontology = importer.load("schema.ttl", format="turtle")
ontology = importer.load("context.jsonld")
```
+### SHACL Shape Generation & Validation
+
+Semantica turns ontologies into executable data contracts. The constraints layer completes a hybrid reasoning system — symbolic constraints (SHACL) alongside semantic retrieval (embeddings).
+
+**Phase 1 — Generate shapes from any ontology dict:**
+
+```python
+from semantica.ontology import OntologyEngine
+
+engine = OntologyEngine()
+ontology = engine.from_data(data) # or engine.from_text(...) / engine.to_owl(...)
+
+# Generate SHACL shapes — zero hand-authoring
+shacl_ttl = engine.to_shacl(ontology) # Turtle string (default)
+shacl_jld = engine.to_shacl(ontology, format="json-ld") # JSON-LD string
+shacl_nt = engine.to_shacl(ontology, format="n-triples") # N-Triples string
+
+# Write to file
+engine.export_shacl(ontology, path="shapes/domain.ttl")
+```
+
+**Quality tiers — control constraint strictness:**
+
+```python
+# "basic" — node shapes, property paths, datatypes, cardinality
+# "standard" — + enumerations (sh:in), patterns, inheritance propagation [DEFAULT]
+# "strict" — + sh:closed true on all shapes (rejects undeclared properties)
+
+shacl = engine.to_shacl(ontology, quality_tier="strict")
+```
+
+**Phase 2 — Validate a graph against the shapes:**
+
+```python
+import pathlib
+
+report = engine.validate_graph(
+ data_graph=pathlib.Path("data/graph.ttl").read_text(),
+ ontology=ontology, # auto-generates SHACL before validating
+ explain=True, # populate plain-English explanations on each violation
+)
+
+print(report.summary())
+# → "Graph does NOT conform: 2 violation(s)."
+
+for v in report.violations:
+ print(v.explanation)
+# → "Node <https://example.com/john> is missing required property <ex:name>. At least 1 value(s) are required."
+# → "Node <https://example.com/acme> has value '999' for <ex:employeeCount> but the expected datatype is xsd:string."
+
+import json
+print(json.dumps(report.to_dict(), indent=2)) # machine-readable — feed to LLM or pipeline
+```
+
+**Or validate against a pre-built SHACL file:**
+
+```python
+report = engine.validate_graph(
+ data_graph=graph_turtle_string,
+ shacl="shapes/domain.ttl", # path or SHACL string
+)
+```
+
+**Regenerate shapes in CI to detect breaking ontology changes:**
+
+```bash
+python -c "
+from semantica.ontology import OntologyEngine
+import json, pathlib
+engine = OntologyEngine()
+onto = engine.from_data(json.loads(pathlib.Path('ontology.json').read_text()))
+engine.export_shacl(onto, 'shapes/shapes.ttl')
+"
+git diff shapes/shapes.ttl # detects breaking ontology changes
+```
+
+> **Requires pyshacl for `validate_graph()`:** `pip install semantica[shacl]`
+> Shape generation (`to_shacl`, `export_shacl`) works without any optional dependencies.
+
---
## Integrations
@@ -715,6 +808,9 @@ pip install semantica[vectorstore-qdrant]
pip install semantica[vectorstore-milvus]
pip install semantica[vectorstore-pgvector]
+# SHACL validation (validate_graph)
+pip install semantica[shacl]
+
# Snowflake ingestion
pip install semantica[db-snowflake]
diff --git a/semantica/export/rdf_exporter.py b/semantica/export/rdf_exporter.py
index 6d4e87df..bf6beaf7 100644
--- a/semantica/export/rdf_exporter.py
+++ b/semantica/export/rdf_exporter.py
@@ -1234,3 +1234,36 @@ class RDFExporter:
)
return {"namespaces": resolved, "declarations": declarations}
+
+ def export_shacl(
+ self,
+ shacl_string: str,
+ file_path: Union[str, Path],
+ format: str = "turtle",
+ encoding: str = "utf-8",
+ ) -> None:
+ """
+ Write a SHACL shapes string produced by SHACLGenerator to a file.
+
+ Args:
+ shacl_string: Serialized SHACL content (Turtle, JSON-LD, or N-Triples).
+ file_path: Output path. Allowed extensions: .ttl, .jsonld, .nt, .shacl.
+ format: Format hint used for logging — "turtle", "json-ld", "n-triples".
+ encoding: File encoding (default "utf-8").
+
+ Raises:
+ ValidationError: If the file extension is not in the allowed set.
+ """
+ allowed_extensions = {".ttl", ".jsonld", ".nt", ".shacl"}
+ path = Path(file_path)
+ if path.suffix.lower() not in allowed_extensions:
+ raise ValidationError(
+ f"Unsupported SHACL file extension '{path.suffix}'. "
+ f"Allowed: {sorted(allowed_extensions)}"
+ )
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(shacl_string, encoding=encoding)
+ self.logger.info(
+ f"SHACL shapes ({format}) exported to {file_path} "
+ f"({len(shacl_string)} chars)"
+ )
diff --git a/semantica/ontology/__init__.py b/semantica/ontology/__init__.py
index 258717ec..98edff7a 100644
--- a/semantica/ontology/__init__.py
+++ b/semantica/ontology/__init__.py
@@ -146,11 +146,21 @@ from .ontology_documentation import OntologyDocumentation, OntologyDocumentation
from .ontology_evaluator import EvaluationResult, OntologyEvaluator
from .ontology_generator import (
ClassInferencer,
+ NodeShape,
OntologyGenerator,
OntologyOptimizer,
PropertyInferencer,
+ PropertyShape,
+ SHACLGenerator,
+ SHACLGraph,
+)
+from .ontology_validator import (
+ OntologyValidator,
+ SHACLValidationReport,
+ SHACLViolation,
+ ValidationResult,
+ validate_ontology,
)
-from .ontology_validator import OntologyValidator, ValidationResult, validate_ontology
from .owl_generator import OWLGenerator
from .property_generator import PropertyGenerator
from .registry import MethodRegistry, method_registry
@@ -175,6 +185,13 @@ __all__ = [
"validate_ontology",
"OntologyEvaluator",
"EvaluationResult",
+ # SHACL generation and validation
+ "SHACLGenerator",
+ "SHACLGraph",
+ "NodeShape",
+ "PropertyShape",
+ "SHACLValidationReport",
+ "SHACLViolation",
# OWL/RDF generation
"OWLGenerator",
# Requirements and competency questions
diff --git a/semantica/ontology/engine.py b/semantica/ontology/engine.py
index dbec4883..ffb54c21 100644
--- a/semantica/ontology/engine.py
+++ b/semantica/ontology/engine.py
@@ -191,6 +191,202 @@ class OntologyEngine:
self.logger.error(f"Failed to list alignments: {e}")
raise ProcessingError(f"Failed to list alignments: {e}")
+ # ── SHACL Phase 1: Generation ─────────────────────────────────────────────
+
+ def to_shacl(
+ self,
+ ontology: Dict[str, Any],
+ *,
+ format: str = "turtle",
+ base_uri: Optional[str] = None,
+ shapes_uri: Optional[str] = None,
+ include_inherited: bool = True,
+ severity: str = "Violation",
+ quality_tier: str = "standard",
+ validate_output: bool = False,
+ **options,
+ ) -> str:
+ """
+ Auto-derive SHACL node shapes and property shapes from a Semantica ontology dict.
+
+ Args:
+ ontology: Ontology dict from any OntologyEngine generation method.
+ format: Output format — "turtle" (default), "json-ld", or "n-triples".
+ base_uri: Base URI for generated shape URIs (inferred from ontology if omitted).
+ shapes_uri: URI for the shapes graph declaration.
+ include_inherited: Propagate parent class property shapes to child shapes.
+ severity: Default severity — "Violation", "Warning", or "Info".
+ quality_tier: Constraint completeness — "basic", "standard" (default), "strict".
+ validate_output: Syntax-check output via rdflib before returning.
+
+ Returns:
+ Serialized SHACL shapes string.
+ """
+ from .ontology_generator import SHACLGenerator
+
+ tracking_id = self.progress.start_tracking(
+ module="ontology",
+ submodule="OntologyEngine",
+ message="Generating SHACL shapes",
+ )
+ try:
+ ns = ontology.get("namespace", {}) if isinstance(ontology, dict) else {}
+ resolved_base = (
+ base_uri
+ or (ns.get("base_uri") if isinstance(ns, dict) else None)
+ or "https://semantica.dev/shapes/"
+ )
+ generator = SHACLGenerator(
+ base_uri=resolved_base,
+ shapes_uri=shapes_uri,
+ include_inherited=include_inherited,
+ severity=severity,
+ quality_tier=quality_tier,
+ )
+ graph = generator.generate(ontology, **options)
+ self.progress.update_tracking(tracking_id, message="Serializing SHACL graph")
+ result = generator.serialize(graph, format=format)
+ if validate_output:
+ try:
+ import rdflib
+ _fmt_map = {
+ "turtle": "turtle", "ttl": "turtle",
+ "json-ld": "json-ld", "jsonld": "json-ld", "json_ld": "json-ld",
+ "n-triples": "nt", "ntriples": "nt", "nt": "nt",
+ }
+ rdflib_fmt = _fmt_map.get(format.lower().strip(), format)
+ g = rdflib.Graph()
+ g.parse(data=result, format=rdflib_fmt)
+ except Exception as e:
+ self.logger.warning(f"SHACL output syntax check failed: {e}")
+ self.progress.stop_tracking(
+ tracking_id, status="completed", message="SHACL generation complete"
+ )
+ return result
+ except Exception as e:
+ self.progress.stop_tracking(tracking_id, status="failed", message=str(e))
+ raise
+
+ def export_shacl(
+ self,
+ ontology: Dict[str, Any],
+ path,
+ format: str = "turtle",
+ encoding: str = "utf-8",
+ **options,
+ ) -> None:
+ """
+ Generate SHACL shapes from ontology and write to a file.
+
+ Args:
+ ontology: Ontology dict.
+ path: Output file path (str or Path). Parent directories are created if needed.
+ format: Output format — "turtle", "json-ld", or "n-triples".
+ encoding: File encoding (default "utf-8").
+ """
+ from pathlib import Path
+
+ shacl_str = self.to_shacl(ontology, format=format, **options)
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(shacl_str, encoding=encoding)
+ self.logger.info(f"SHACL shapes exported to {path}")
+
+ # ── SHACL Phase 2: Runtime Validation ────────────────────────────────────
+
+ def validate_graph(
+ self,
+ data_graph,
+ shacl=None,
+ *,
+ ontology: Optional[Dict[str, Any]] = None,
+ data_graph_format: str = "turtle",
+ shacl_format: str = "turtle",
+ explain: bool = True,
+ abort_on_first: bool = False,
+ **options,
+ ):
+ """
+ Validate a data graph against SHACL shapes.
+
+ Args:
+ data_graph: The graph to validate — RDF string or rdflib.Graph.
+ shacl: Pre-built SHACL string or file Path (mutually exclusive with ontology).
+ ontology: Ontology dict — SHACL is auto-generated before validation
+ (mutually exclusive with shacl).
+ data_graph_format: RDF format of data_graph when passed as a string.
+ shacl_format: RDF format of the shacl argument when it is a string or file
+ — "turtle" (default), "json-ld", or "n-triples". Ignored when
+ ontology is provided (auto-generated shapes are always Turtle).
+ explain: Populate plain-English explanation on each violation.
+ abort_on_first: Stop after the first violation.
+
+ Returns:
+ SHACLValidationReport with structured violations and optional explanations.
+
+ Raises:
+ ValueError: If both or neither of shacl/ontology are provided.
+ ImportError: If pyshacl is not installed.
+ """
+ from .ontology_validator import _run_pyshacl
+
+ if (shacl is None) == (ontology is None):
+ raise ValueError(
+ "Exactly one of 'shacl' or 'ontology' must be provided, not both or neither."
+ )
+
+ tracking_id = self.progress.start_tracking(
+ module="ontology",
+ submodule="OntologyEngine",
+ message="Preparing graph validation",
+ )
+ try:
+ if ontology is not None:
+ self.progress.update_tracking(
+ tracking_id, message="Generating SHACL from ontology"
+ )
+ shacl_str = self.to_shacl(ontology, **options)
+ shacl_format = "turtle" # auto-generated shapes are always Turtle
+ else:
+ import os
+ from pathlib import Path
+
+ if isinstance(shacl, Path) or (
+ isinstance(shacl, str) and os.path.exists(shacl)
+ ):
+ shacl_str = Path(shacl).read_text(encoding="utf-8")
+ else:
+ shacl_str = str(shacl)
+
+ if isinstance(data_graph, str):
+ data_graph_str = data_graph
+ else:
+ data_graph_str = data_graph.serialize(format=data_graph_format)
+
+ self.progress.update_tracking(tracking_id, message="Running pyshacl validator")
+ report = _run_pyshacl(
+ data_graph_str,
+ shacl_str,
+ data_graph_format=data_graph_format,
+ shacl_format=shacl_format,
+ )
+
+ if explain:
+ self.progress.update_tracking(
+ tracking_id, message="Generating violation explanations"
+ )
+ report.explain_violations()
+
+ self.progress.stop_tracking(
+ tracking_id, status="completed", message="Validation complete"
+ )
+ return report
+ except Exception as e:
+ self.progress.stop_tracking(tracking_id, status="failed", message=str(e))
+ raise
+
+ # ── Ontology Evaluation / Validation ─────────────────────────────────────
+
def evaluate(self, ontology: Dict[str, Any], **options):
return self.evaluator.evaluate_ontology(ontology, **options)
diff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.py
index e1559104..80851f63 100644
--- a/semantica/ontology/ontology_generator.py
+++ b/semantica/ontology/ontology_generator.py
@@ -30,6 +30,7 @@ Author: Semantica Contributors
License: MIT
"""
+from dataclasses import dataclass, field, replace as dataclass_replace
from datetime import datetime
from typing import Any, Dict, List, Optional
@@ -709,3 +710,496 @@ class OntologyOptimizer:
prop["range"] = ["owl:Thing"]
return ontology
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# SHACL Shape Generation
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+@dataclass
+class PropertyShape:
+ """Internal model for a SHACL sh:PropertyShape."""
+ path: str
+ name: Optional[str] = None
+ description: Optional[str] = None
+ datatype: Optional[str] = None # sh:datatype
+ class_: Optional[str] = None # sh:class
+ min_count: Optional[int] = None
+ max_count: Optional[int] = None
+ in_values: Optional[List[str]] = None
+ has_value: Optional[str] = None
+ pattern: Optional[str] = None
+ severity: str = "Violation"
+
+
+@dataclass
+class NodeShape:
+ """Internal model for a SHACL sh:NodeShape."""
+ target_class: str
+ name: Optional[str] = None
+ description: Optional[str] = None
+ property_shapes: List[PropertyShape] = field(default_factory=list)
+ closed: bool = False
+ severity: str = "Violation"
+
+
+@dataclass
+class SHACLGraph:
+ """Internal model representing the complete SHACL shapes graph."""
+ base_uri: str
+ shapes_uri: str
+ node_shapes: List[NodeShape] = field(default_factory=list)
+ prefixes: Dict[str, str] = field(default_factory=dict)
+
+
+class SHACLGenerator:
+ """
+ Generates SHACL shapes from Semantica OWL ontology dicts.
+
+ 6-stage internal pipeline:
+ 1. _build_class_index() — {class_name: class_dict} for O(1) lookup
+ 2. _generate_node_shapes() — one NodeShape per OWL class
+ 3. _attach_property_shapes() — map properties to their domain node shapes
+ 4. _propagate_inheritance() — copy parent shapes to children (iterative, cycle-safe)
+ 5. _apply_quality_tier() — strict tier: set closed=True on all shapes
+ 6. serialize() — Turtle / JSON-LD / N-Triples
+ """
+
+ _XSD_ALIASES: Dict[str, str] = {
+ "string": "xsd:string", "str": "xsd:string",
+ "int": "xsd:integer", "integer": "xsd:integer",
+ "float": "xsd:decimal", "decimal": "xsd:decimal",
+ "boolean": "xsd:boolean", "bool": "xsd:boolean",
+ "date": "xsd:date",
+ "datetime": "xsd:dateTime",
+ "uri": "xsd:anyURI", "anyuri": "xsd:anyURI",
+ }
+
+ def __init__(
+ self,
+ base_uri: str = "https://semantica.dev/shapes/",
+ shapes_uri: Optional[str] = None,
+ include_inherited: bool = True,
+ severity: str = "Violation",
+ quality_tier: str = "standard",
+ config: Optional[Dict[str, Any]] = None,
+ ):
+ self.logger = get_logger("ontology_shacl")
+ self.progress_tracker = get_progress_tracker()
+ self.base_uri = base_uri.rstrip("/") + "/"
+ self.shapes_uri = shapes_uri or (self.base_uri + "shapes")
+ self.include_inherited = include_inherited
+ self.severity = severity
+ self.quality_tier = quality_tier
+ self.config = config or {}
+
+ # ── Public API ────────────────────────────────────────────────────────────
+
+ def generate(self, ontology: Dict[str, Any], **options) -> SHACLGraph:
+ """Generate a SHACLGraph from a Semantica ontology dict."""
+ if not isinstance(ontology, dict):
+ raise ValueError("ontology must be a dict")
+ if "classes" not in ontology and "properties" not in ontology:
+ raise ValueError(
+ "ontology must contain at least a 'classes' or 'properties' key"
+ )
+
+ tracking_id = self.progress_tracker.start_tracking(
+ module="ontology", submodule="SHACLGenerator", message="Building SHACL index"
+ )
+ try:
+ classes = ontology.get("classes", [])
+ properties = ontology.get("properties", [])
+
+ # Resolve base_uri from ontology namespace if present
+ ns = ontology.get("namespace", {})
+ base_uri = (
+ ns.get("base_uri", self.base_uri) if isinstance(ns, dict) else self.base_uri
+ )
+ if not base_uri.endswith("/") and not base_uri.endswith("#"):
+ base_uri += "/"
+
+ prefixes = {
+ "sh": "http://www.w3.org/ns/shacl#",
+ "xsd": "http://www.w3.org/2001/XMLSchema#",
+ "owl": "http://www.w3.org/2002/07/owl#",
+ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
+ "ex": base_uri,
+ }
+
+ graph = SHACLGraph(
+ base_uri=base_uri,
+ shapes_uri=self.shapes_uri,
+ prefixes=prefixes,
+ )
+
+ self.progress_tracker.update_tracking(tracking_id, message="Generating node shapes")
+ class_index = self._build_class_index(classes)
+ self._generate_node_shapes(graph, classes)
+
+ self.progress_tracker.update_tracking(tracking_id, message="Attaching property shapes")
+ self._attach_property_shapes(graph, properties)
+
+ if self.include_inherited:
+ self.progress_tracker.update_tracking(tracking_id, message="Propagating inheritance")
+ self._propagate_inheritance(graph, class_index)
+
+ self._apply_quality_tier(graph)
+
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="completed", message="SHACL graph built"
+ )
+ return graph
+
+ except (ValueError, TypeError):
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message="Generation failed"
+ )
+ raise
+ except Exception as exc:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(exc)
+ )
+ from ..utils.exceptions import ProcessingError
+ raise ProcessingError(f"SHACL generation failed: {exc}") from exc
+
+ def serialize(self, graph: SHACLGraph, format: str = "turtle") -> str:
+ """Serialize a SHACLGraph to a string in the requested format."""
+ tracking_id = self.progress_tracker.start_tracking(
+ module="ontology", submodule="SHACLGenerator", message="Serializing SHACL graph"
+ )
+ try:
+ fmt = format.lower().strip()
+ if fmt in ("turtle", "ttl"):
+ result = self._serialize_turtle(graph)
+ elif fmt in ("json-ld", "jsonld", "json_ld"):
+ result = self._serialize_jsonld(graph)
+ elif fmt in ("n-triples", "ntriples", "nt"):
+ result = self._serialize_ntriples(graph)
+ else:
+ raise ValueError(
+ f"Unsupported SHACL serialization format: '{format}'. "
+ "Supported formats: 'turtle', 'json-ld', 'n-triples'"
+ )
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="completed", message="Serialized"
+ )
+ return result
+ except ValueError:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message="Unsupported format"
+ )
+ raise
+ except Exception as exc:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(exc)
+ )
+ from ..utils.exceptions import ProcessingError
+ raise ProcessingError(f"SHACL serialization failed: {exc}") from exc
+
+ # ── Internal pipeline stages ──────────────────────────────────────────────
+
+ def _build_class_index(
+ self, classes: List[Dict[str, Any]]
+ ) -> Dict[str, Dict[str, Any]]:
+ return {c["name"]: c for c in classes if c.get("name")}
+
+ def _generate_node_shapes(
+ self, graph: SHACLGraph, classes: List[Dict[str, Any]]
+ ) -> None:
+ for cls in classes:
+ name = cls.get("name")
+ if not name:
+ continue
+ shape = NodeShape(
+ target_class=name,
+ name=cls.get("label") or cls.get("name"),
+ description=cls.get("description") or cls.get("comment"),
+ severity=self.severity,
+ )
+ graph.node_shapes.append(shape)
+
+ def _attach_property_shapes(
+ self, graph: SHACLGraph, properties: List[Dict[str, Any]]
+ ) -> None:
+ shape_by_class = {ns.target_class: ns for ns in graph.node_shapes}
+
+ for prop in properties:
+ pname = prop.get("name")
+ if not pname:
+ continue
+
+ domain = prop.get("domain")
+ if isinstance(domain, list):
+ domains = [d for d in domain if d]
+ elif isinstance(domain, str) and domain:
+ domains = [domain]
+ else:
+ domains = []
+
+ if domains:
+ for d in domains:
+ if d in shape_by_class:
+ shape_by_class[d].property_shapes.append(
+ self._build_property_shape(prop)
+ )
+ else:
+ self.logger.debug(
+ f"Property '{pname}' domain '{d}' has no matching node shape — skipped"
+ )
+ else:
+ # No domain declared → attach to all shapes
+ self.logger.debug(
+ f"Property '{pname}' has no domain — attaching to all node shapes"
+ )
+ for node_shape in graph.node_shapes:
+ node_shape.property_shapes.append(self._build_property_shape(prop))
+
+ def _build_property_shape(self, prop: Dict[str, Any]) -> PropertyShape:
+ ptype = prop.get("type", "")
+ range_ = prop.get("range", "")
+ if isinstance(range_, list):
+ range_ = range_[0] if range_ else ""
+
+ cardinality = prop.get("cardinality") or {}
+ min_count = cardinality.get("min") if isinstance(cardinality, dict) else None
+ max_count = cardinality.get("max") if isinstance(cardinality, dict) else None
+
+ if prop.get("required") and min_count is None:
+ min_count = 1
+
+ datatype = None
+ class_ = None
+ if ptype in ("datatype", "data", "DatatypeProperty"):
+ datatype = self._resolve_xsd(range_) if range_ else None
+ elif ptype in ("object", "ObjectProperty"):
+ class_ = range_ if range_ else None
+
+ in_values = (
+ prop.get("one_of") or prop.get("enum") or prop.get("allowed_values")
+ )
+ if in_values and self.quality_tier in ("standard", "strict"):
+ in_values = list(in_values)
+ else:
+ in_values = None
+
+ pattern = prop.get("pattern") if self.quality_tier in ("standard", "strict") else None
+
+ return PropertyShape(
+ path=prop.get("name", ""),
+ name=prop.get("label") or prop.get("name"),
+ description=prop.get("description") or prop.get("comment"),
+ datatype=datatype,
+ class_=class_,
+ min_count=min_count,
+ max_count=max_count,
+ in_values=in_values,
+ has_value=prop.get("has_value"),
+ pattern=pattern,
+ severity=self.severity,
+ )
+
+ def _propagate_inheritance(
+ self, graph: SHACLGraph, class_index: Dict[str, Dict[str, Any]]
+ ) -> None:
+ shape_by_class = {ns.target_class: ns for ns in graph.node_shapes}
+
+ for _ in range(20): # max 20 passes; stops early when stable
+ changed = False
+ for node_shape in graph.node_shapes:
+ cls_data = class_index.get(node_shape.target_class, {})
+ parent_name = cls_data.get("parent") or cls_data.get("parent_class")
+ if not parent_name or parent_name not in shape_by_class:
+ continue
+ parent_shape = shape_by_class[parent_name]
+ existing_paths = {ps.path for ps in node_shape.property_shapes}
+ for pps in parent_shape.property_shapes:
+ if pps.path not in existing_paths:
+ node_shape.property_shapes.append(dataclass_replace(pps))
+ existing_paths.add(pps.path)
+ changed = True
+ if not changed:
+ break
+
+ def _apply_quality_tier(self, graph: SHACLGraph) -> None:
+ if self.quality_tier == "strict":
+ for node_shape in graph.node_shapes:
+ # Only close shapes that declare at least one property
+ if node_shape.property_shapes:
+ node_shape.closed = True
+
+ # ── Serializers ───────────────────────────────────────────────────────────
+
+ def _prefix_decls(self, graph: SHACLGraph) -> str:
+ return "\n".join(f"@prefix {p}: <{u}> ." for p, u in sorted(graph.prefixes.items()))
+
+ def _uri(self, graph: SHACLGraph, local: str) -> str:
+ """Return a compact URI reference; fall back to ex:local for bare names."""
+ if local.startswith("http://") or local.startswith("https://"):
+ return f"<{local}>"
+ if ":" in local:
+ return local
+ return f"ex:{local}"
+
+ def _serialize_turtle(self, graph: SHACLGraph) -> str:
+ lines = [self._prefix_decls(graph), ""]
+ lines.append(f"<{graph.shapes_uri}> a owl:Ontology .")
+ lines.append("")
+
+ for node_shape in graph.node_shapes:
+ shape_uri = f"{graph.base_uri}{node_shape.target_class}Shape"
+ block = [f"<{shape_uri}>"]
+ block.append(" a sh:NodeShape ;")
+ block.append(
+ f" sh:targetClass {self._uri(graph, node_shape.target_class)} ;"
+ )
+ if node_shape.name:
+ block.append(f' sh:name "{node_shape.name}" ;')
+ if node_shape.description:
+ escaped = node_shape.description.replace('"', '\\"')
+ block.append(f' sh:description "{escaped}" ;')
+ if node_shape.closed:
+ block.append(" sh:closed true ;")
+ block.append(" sh:ignoredProperties ( <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ) ;")
+
+ for i, ps in enumerate(node_shape.property_shapes):
+ is_last = i == len(node_shape.property_shapes) - 1
+ terminator = " ." if is_last else " ;"
+ parts = [" sh:property ["]
+ parts.append(f" sh:path {self._uri(graph, ps.path)} ;")
+ if ps.datatype:
+ parts.append(f" sh:datatype {ps.datatype} ;")
+ if ps.class_:
+ parts.append(f" sh:class {self._uri(graph, ps.class_)} ;")
+ if ps.min_count is not None:
+ parts.append(f" sh:minCount {ps.min_count} ;")
+ if ps.max_count is not None:
+ parts.append(f" sh:maxCount {ps.max_count} ;")
+ if ps.in_values is not None:
+ vals = " ".join(f'"{v}"' for v in ps.in_values)
+ parts.append(f" sh:in ( {vals} ) ;")
+ if ps.has_value is not None:
+ parts.append(f" sh:hasValue {self._uri(graph, ps.has_value)} ;")
+ if ps.pattern:
+ escaped_p = ps.pattern.replace('"', '\\"')
+ parts.append(f' sh:pattern "{escaped_p}" ;')
+ parts.append(f" sh:severity sh:{ps.severity}")
+ parts.append(" ]" + terminator)
+ block.extend(parts)
+
+ if not node_shape.property_shapes:
+ # Close the declaration when there are no property shapes
+ block[-1] = block[-1].rstrip(" ;") + " ."
+
+ lines.append("\n".join(block))
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def _serialize_jsonld(self, graph: SHACLGraph) -> str:
+ import json
+
+ context: Dict[str, Any] = dict(graph.prefixes)
+ context["sh"] = "http://www.w3.org/ns/shacl#"
+ context["@vocab"] = graph.base_uri
+
+ graph_list: List[Dict[str, Any]] = [
+ {"@id": graph.shapes_uri, "@type": "owl:Ontology"}
+ ]
+ for node_shape in graph.node_shapes:
+ shape_id = f"{graph.base_uri}{node_shape.target_class}Shape"
+ node: Dict[str, Any] = {
+ "@id": shape_id,
+ "@type": "sh:NodeShape",
+ "sh:targetClass": {"@id": f"{graph.base_uri}{node_shape.target_class}"},
+ }
+ if node_shape.name:
+ node["sh:name"] = node_shape.name
+ if node_shape.description:
+ node["sh:description"] = node_shape.description
+ if node_shape.closed:
+ node["sh:closed"] = True
+ node["sh:ignoredProperties"] = [{"@id": "rdf:type"}]
+ if node_shape.property_shapes:
+ props = []
+ for ps in node_shape.property_shapes:
+ p: Dict[str, Any] = {
+ "sh:path": {"@id": f"{graph.base_uri}{ps.path}"}
+ }
+ if ps.datatype:
+ dt = ps.datatype.replace(
+ "xsd:", "http://www.w3.org/2001/XMLSchema#"
+ )
+ p["sh:datatype"] = {"@id": dt}
+ if ps.class_:
+ p["sh:class"] = {"@id": f"{graph.base_uri}{ps.class_}"}
+ if ps.min_count is not None:
+ p["sh:minCount"] = ps.min_count
+ if ps.max_count is not None:
+ p["sh:maxCount"] = ps.max_count
+ if ps.in_values:
+ p["sh:in"] = {"@list": ps.in_values}
+ if ps.has_value is not None:
+ p["sh:hasValue"] = ps.has_value
+ if ps.pattern:
+ p["sh:pattern"] = ps.pattern
+ p["sh:severity"] = {"@id": f"sh:{ps.severity}"}
+ props.append(p)
+ node["sh:property"] = props
+ graph_list.append(node)
+
+ return json.dumps({"@context": context, "@graph": graph_list}, indent=2)
+
+ def _serialize_ntriples(self, graph: SHACLGraph) -> str:
+ SHACL = "http://www.w3.org/ns/shacl#"
+ OWL = "http://www.w3.org/2002/07/owl#"
+ RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ XSD = "http://www.w3.org/2001/XMLSchema#"
+
+ lines: List[str] = []
+
+ def t(s: str, p: str, o: str) -> None:
+ lines.append(f"{s} {p} {o} .")
+
+ t(f"<{graph.shapes_uri}>", f"<{RDF}type>", f"<{OWL}Ontology>")
+
+ for i, node_shape in enumerate(graph.node_shapes):
+ shape_uri = f"<{graph.base_uri}{node_shape.target_class}Shape>"
+ class_uri = f"<{graph.base_uri}{node_shape.target_class}>"
+ t(shape_uri, f"<{RDF}type>", f"<{SHACL}NodeShape>")
+ t(shape_uri, f"<{SHACL}targetClass>", class_uri)
+ if node_shape.name:
+ t(shape_uri, f"<{SHACL}name>", f'"{node_shape.name}"')
+ if node_shape.closed:
+ t(
+ shape_uri,
+ f"<{SHACL}closed>",
+ f'"true"^^<{XSD}boolean>',
+ )
+
+ for j, ps in enumerate(node_shape.property_shapes):
+ bnode = f"_:ps{i}_{j}"
+ t(shape_uri, f"<{SHACL}property>", bnode)
+ prop_uri = f"<{graph.base_uri}{ps.path}>"
+ t(bnode, f"<{SHACL}path>", prop_uri)
+ if ps.datatype:
+ dt_uri = ps.datatype.replace("xsd:", XSD)
+ t(bnode, f"<{SHACL}datatype>", f"<{dt_uri}>")
+ if ps.class_:
+ t(bnode, f"<{SHACL}class>", f"<{graph.base_uri}{ps.class_}>")
+ if ps.min_count is not None:
+ t(bnode, f"<{SHACL}minCount>", f'"{ps.min_count}"^^<{XSD}integer>')
+ if ps.max_count is not None:
+ t(bnode, f"<{SHACL}maxCount>", f'"{ps.max_count}"^^<{XSD}integer>')
+ t(bnode, f"<{SHACL}severity>", f"<{SHACL}{ps.severity}>")
+
+ return "\n".join(lines)
+
+ # ── Helper ────────────────────────────────────────────────────────────────
+
+ def _resolve_xsd(self, range_str: str) -> str:
+ """Map ontology range strings to xsd:-prefixed datatypes."""
+ key = range_str.lower().strip()
+ return self._XSD_ALIASES.get(key, f"xsd:{range_str}")
diff --git a/semantica/ontology/ontology_validator.py b/semantica/ontology/ontology_validator.py
index 3adb9956..4a03f2d1 100644
--- a/semantica/ontology/ontology_validator.py
+++ b/semantica/ontology/ontology_validator.py
@@ -16,6 +16,222 @@ from dataclasses import dataclass, field
from ..utils.logging import get_logger
+
+# ─────────────────────────────────────────────────────────────────────────────
+# SHACL Validation Models
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+@dataclass
+class SHACLViolation:
+ """Represents a single SHACL constraint violation."""
+ focus_node: str
+ result_path: Optional[str] = None
+ constraint: str = ""
+ severity: str = "Violation"
+ message: Optional[str] = None
+ value: Optional[str] = None
+ shape: Optional[str] = None
+ explanation: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "focus_node": self.focus_node,
+ "result_path": self.result_path,
+ "constraint": self.constraint,
+ "severity": self.severity,
+ "message": self.message,
+ "value": self.value,
+ "shape": self.shape,
+ "explanation": self.explanation,
+ }
+
+
+@dataclass
+class SHACLValidationReport:
+ """Structured SHACL validation report with machine-readable violations and explanations."""
+ conforms: bool
+ violations: List[SHACLViolation] = field(default_factory=list)
+ warnings: List[SHACLViolation] = field(default_factory=list)
+ infos: List[SHACLViolation] = field(default_factory=list)
+ raw_report: Optional[str] = None
+
+ @property
+ def violation_count(self) -> int:
+ return len(self.violations)
+
+ @property
+ def warning_count(self) -> int:
+ return len(self.warnings)
+
+ def summary(self) -> str:
+ if self.conforms:
+ return "Graph conforms to all SHACL constraints."
+ return f"Graph does NOT conform: {self.violation_count} violation(s)."
+
+ def explain_violations(self) -> None:
+ """Populate a plain-English explanation on every violation. No LLM call."""
+ _TEMPLATES = {
+ "MinCountConstraintComponent": (
+ "Node <{focus_node}> is missing required property <{path}>. "
+ "At least {min_count} value(s) are required."
+ ),
+ "MaxCountConstraintComponent": (
+ "Node <{focus_node}> has too many values for <{path}>. "
+ "At most {max_count} value(s) are allowed."
+ ),
+ "DatatypeConstraintComponent": (
+ "Node <{focus_node}> has value '{value}' for <{path}> "
+ "but the expected datatype is {datatype}."
+ ),
+ "ClassConstraintComponent": (
+ "Node <{focus_node}> has value '{value}' for <{path}> "
+ "but it must be an instance of {class_}."
+ ),
+ "InConstraintComponent": (
+ "Node <{focus_node}> has value '{value}' for <{path}> "
+ "which is not in the allowed set."
+ ),
+ "PatternConstraintComponent": (
+ "Node <{focus_node}> has value '{value}' for <{path}> "
+ "which does not match the required pattern."
+ ),
+ "ClosedConstraintComponent": (
+ "Node <{focus_node}> has undeclared property <{path}> "
+ "which is not allowed by the closed shape."
+ ),
+ }
+ for v in self.violations + self.warnings + self.infos:
+ tmpl = None
+ for key, tpl in _TEMPLATES.items():
+ if key in (v.constraint or ""):
+ tmpl = tpl
+ break
+ if tmpl is None:
+ v.explanation = (
+ f"Node <{v.focus_node}> failed constraint "
+ f"{v.constraint or '(unknown)'}"
+ + (f" on property <{v.result_path}>." if v.result_path else ".")
+ )
+ continue
+ v.explanation = tmpl.format(
+ focus_node=v.focus_node,
+ path=v.result_path or "",
+ value=v.value or "",
+ min_count=1,
+ max_count=1,
+ datatype=v.message or "",
+ class_=v.message or "",
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "conforms": self.conforms,
+ "violation_count": self.violation_count,
+ "warning_count": self.warning_count,
+ "violations": [v.to_dict() for v in self.violations],
+ "warnings": [v.to_dict() for v in self.warnings],
+ "infos": [v.to_dict() for v in self.infos],
+ }
+
+
+def _run_pyshacl(
+ data_graph_str: str,
+ shacl_str: str,
+ data_graph_format: str = "turtle",
+ shacl_format: str = "turtle",
+) -> SHACLValidationReport:
+ """
+ Run pyshacl validation and return a structured SHACLValidationReport.
+
+ Args:
+ data_graph_str: Serialized data graph string.
+ shacl_str: Serialized SHACL shapes string.
+ data_graph_format: RDF format of data_graph_str (default "turtle").
+ shacl_format: RDF format of shacl_str — "turtle", "json-ld", or "nt"
+ (default "turtle").
+
+ Raises ImportError if pyshacl or rdflib are not installed
+ (install with: pip install semantica[shacl]).
+ """
+ try:
+ import pyshacl
+ except ImportError as exc:
+ raise ImportError(
+ "pyshacl is required for SHACL validation. "
+ "Install it with: pip install semantica[shacl]"
+ ) from exc
+
+ try:
+ import rdflib
+ except ImportError as exc:
+ raise ImportError(
+ "rdflib is required for SHACL validation. "
+ "Install it with: pip install rdflib"
+ ) from exc
+
+ data_g = rdflib.Graph()
+ data_g.parse(data=data_graph_str, format=data_graph_format)
+
+ _fmt_map = {
+ "turtle": "turtle", "ttl": "turtle",
+ "json-ld": "json-ld", "jsonld": "json-ld", "json_ld": "json-ld",
+ "n-triples": "nt", "ntriples": "nt", "nt": "nt",
+ }
+ shacl_g = rdflib.Graph()
+ shacl_g.parse(data=shacl_str, format=_fmt_map.get(shacl_format.lower().strip(), shacl_format))
+
+ conforms, results_graph, results_text = pyshacl.validate(
+ data_g,
+ shacl_graph=shacl_g,
+ inference="none",
+ abort_on_first=False,
+ )
+
+ violations: List[SHACLViolation] = []
+ warnings: List[SHACLViolation] = []
+ infos: List[SHACLViolation] = []
+
+ SH = rdflib.Namespace("http://www.w3.org/ns/shacl#")
+ for result in results_graph.subjects(rdflib.RDF.type, SH.ValidationResult):
+ focus = str(results_graph.value(result, SH.focusNode) or "")
+ path_node = results_graph.value(result, SH.resultPath)
+ path = str(path_node) if path_node is not None else None
+ sev_node = results_graph.value(result, SH.resultSeverity)
+ sev_str = str(sev_node).split("#")[-1] if sev_node is not None else "Violation"
+ msg_node = results_graph.value(result, SH.resultMessage)
+ msg = str(msg_node) if msg_node is not None else None
+ val_node = results_graph.value(result, SH.value)
+ val = str(val_node) if val_node is not None else None
+ src_node = results_graph.value(result, SH.sourceConstraintComponent)
+ constraint = str(src_node).split("#")[-1] if src_node is not None else ""
+ shape_node = results_graph.value(result, SH.sourceShape)
+ shape = str(shape_node) if shape_node is not None else None
+
+ v = SHACLViolation(
+ focus_node=focus,
+ result_path=path,
+ constraint=constraint,
+ severity=sev_str,
+ message=msg,
+ value=val,
+ shape=shape,
+ )
+ if sev_str == "Violation":
+ violations.append(v)
+ elif sev_str == "Warning":
+ warnings.append(v)
+ else:
+ infos.append(v)
+
+ return SHACLValidationReport(
+ conforms=conforms,
+ violations=violations,
+ warnings=warnings,
+ infos=infos,
+ raw_report=results_text,
+ )
+
@dataclass
class ValidationResult:
"""Result of an ontology validation operation."""
diff --git a/tests/ontology/test_ontology_advanced.py b/tests/ontology/test_ontology_advanced.py
index 25d257d8..564ca758 100644
--- a/tests/ontology/test_ontology_advanced.py
+++ b/tests/ontology/test_ontology_advanced.py
@@ -210,5 +210,239 @@ class TestOntologyAdvanced(unittest.TestCase):
self.assertEqual(len(alignments), 1)
self.assertEqual(alignments[0]["target"], "http://target.org/2")
+class TestSHACLHierarchicalAndValidation(unittest.TestCase):
+ """Tests 17-34: Hierarchical inheritance, engine integration, and validation models."""
+
+ # 3-level hierarchy ontology: Animal → Dog → GuideDog
+ _HIER_ONTOLOGY = {
+ "classes": [
+ {"name": "Animal"},
+ {"name": "Dog", "parent": "Animal"},
+ {"name": "GuideDog", "parent": "Dog"},
+ ],
+ "properties": [
+ {
+ "name": "name",
+ "type": "datatype",
+ "range": "string",
+ "domain": "Animal",
+ "required": True,
+ },
+ {
+ "name": "breed",
+ "type": "datatype",
+ "range": "string",
+ "domain": "Dog",
+ },
+ {
+ "name": "owner",
+ "type": "object",
+ "range": "Person",
+ "domain": "GuideDog",
+ "required": True,
+ },
+ ],
+ }
+
+ def _make_gen(self, **kwargs):
+ from semantica.ontology.ontology_generator import SHACLGenerator
+
+ with patch(
+ "semantica.ontology.ontology_generator.get_logger",
+ return_value=MagicMock(),
+ ), patch(
+ "semantica.ontology.ontology_generator.get_progress_tracker",
+ return_value=MagicMock(start_tracking=MagicMock(return_value="t")),
+ ):
+ return SHACLGenerator(**kwargs)
+
+ # 17
+ def test_child_inherits_parent_property(self):
+ gen = self._make_gen(include_inherited=True)
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ dog = next(ns for ns in graph.node_shapes if ns.target_class == "Dog")
+ paths = {ps.path for ps in dog.property_shapes}
+ self.assertIn("name", paths) # inherited from Animal
+ self.assertIn("breed", paths) # own
+
+ # 18
+ def test_grandchild_inherits_all_ancestors(self):
+ gen = self._make_gen(include_inherited=True)
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ gd = next(ns for ns in graph.node_shapes if ns.target_class == "GuideDog")
+ paths = {ps.path for ps in gd.property_shapes}
+ self.assertIn("name", paths) # from Animal
+ self.assertIn("breed", paths) # from Dog
+ self.assertIn("owner", paths) # own
+
+ # 19
+ def test_no_inheritance_when_disabled(self):
+ gen = self._make_gen(include_inherited=False)
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ dog = next(ns for ns in graph.node_shapes if ns.target_class == "Dog")
+ paths = {ps.path for ps in dog.property_shapes}
+ self.assertNotIn("name", paths) # parent property should NOT appear
+
+ # 20
+ def test_no_duplicate_shapes_after_inheritance(self):
+ gen = self._make_gen(include_inherited=True)
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ for node_shape in graph.node_shapes:
+ paths = [ps.path for ps in node_shape.property_shapes]
+ self.assertEqual(len(paths), len(set(paths)),
+ f"Duplicate paths in {node_shape.target_class}: {paths}")
+
+ # 21
+ def test_no_domain_property_attaches_to_all_shapes(self):
+ onto = {
+ "classes": [{"name": "A"}, {"name": "B"}],
+ "properties": [
+ {"name": "globalProp", "type": "datatype", "range": "string"}
+ # no domain
+ ],
+ }
+ gen = self._make_gen()
+ graph = gen.generate(onto)
+ for node_shape in graph.node_shapes:
+ paths = {ps.path for ps in node_shape.property_shapes}
+ self.assertIn("globalProp", paths)
+
+ # 22
+ def test_empty_classes_produces_no_shapes(self):
+ gen = self._make_gen()
+ graph = gen.generate({"classes": [], "properties": []})
+ self.assertEqual(len(graph.node_shapes), 0)
+
+ # 23
+ def test_sh_prefix_always_present(self):
+ gen = self._make_gen()
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ self.assertIn("sh", graph.prefixes)
+ self.assertIn("shacl#", graph.prefixes["sh"])
+
+ # 24
+ def test_custom_base_uri(self):
+ gen = self._make_gen(base_uri="https://myorg.com/shapes/")
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ ttl = gen.serialize(graph, format="turtle")
+ self.assertIn("myorg.com", ttl)
+
+ # 25
+ def test_severity_warning(self):
+ gen = self._make_gen(severity="Warning")
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ ttl = gen.serialize(graph, format="turtle")
+ self.assertIn("sh:Warning", ttl)
+ self.assertNotIn("sh:Violation", ttl)
+
+ # 26
+ def test_strict_tier_sets_closed(self):
+ gen = self._make_gen(quality_tier="strict")
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ # Shapes with property_shapes should be closed
+ for node_shape in graph.node_shapes:
+ if node_shape.property_shapes:
+ self.assertTrue(node_shape.closed,
+ f"{node_shape.target_class}Shape should be closed")
+
+ # 27
+ def test_strict_tier_includes_ignored_properties(self):
+ gen = self._make_gen(quality_tier="strict")
+ graph = gen.generate(self._HIER_ONTOLOGY)
+ ttl = gen.serialize(graph, format="turtle")
+ self.assertIn("sh:ignoredProperties", ttl)
+
+ # 28
+ def test_engine_to_shacl_returns_non_empty_string(self):
+ mock_progress = MagicMock()
+ mock_progress.start_tracking.return_value = "tid"
+ with patch("semantica.ontology.engine.get_logger", return_value=MagicMock()), \
+ patch("semantica.ontology.engine.get_progress_tracker", return_value=mock_progress), \
+ patch("semantica.ontology.ontology_generator.get_logger", return_value=MagicMock()), \
+ patch("semantica.ontology.ontology_generator.get_progress_tracker", return_value=mock_progress):
+ from semantica.ontology.engine import OntologyEngine
+ engine = OntologyEngine()
+ result = engine.to_shacl(self._HIER_ONTOLOGY)
+ self.assertIsInstance(result, str)
+ self.assertGreater(len(result), 0)
+ self.assertIn("sh:NodeShape", result)
+
+ # 29
+ def test_engine_to_shacl_jsonld(self):
+ import json
+ mock_progress = MagicMock()
+ mock_progress.start_tracking.return_value = "tid"
+ with patch("semantica.ontology.engine.get_logger", return_value=MagicMock()), \
+ patch("semantica.ontology.engine.get_progress_tracker", return_value=mock_progress), \
+ patch("semantica.ontology.ontology_generator.get_logger", return_value=MagicMock()), \
+ patch("semantica.ontology.ontology_generator.get_progress_tracker", return_value=mock_progress):
+ from semantica.ontology.engine import OntologyEngine
+ engine = OntologyEngine()
+ result = engine.to_shacl(self._HIER_ONTOLOGY, format="json-ld")
+ parsed = json.loads(result)
+ self.assertIn("@graph", parsed)
+
+ # 30
+ def test_shacl_validation_report_summary_conforms(self):
+ from semantica.ontology.ontology_validator import SHACLValidationReport
+ report = SHACLValidationReport(conforms=True)
+ self.assertIn("conforms", report.summary().lower())
+
+ # 31
+ def test_shacl_validation_report_summary_violations(self):
+ from semantica.ontology.ontology_validator import (
+ SHACLValidationReport,
+ SHACLViolation,
+ )
+ v = SHACLViolation(focus_node="https://example.com/node1")
+ report = SHACLValidationReport(conforms=False, violations=[v])
+ self.assertIn("1 violation", report.summary())
+
+ # 32
+ def test_explain_violations_populates_explanation(self):
+ from semantica.ontology.ontology_validator import (
+ SHACLValidationReport,
+ SHACLViolation,
+ )
+ v = SHACLViolation(
+ focus_node="https://example.com/john",
+ result_path="ex:name",
+ constraint="MinCountConstraintComponent",
+ )
+ report = SHACLValidationReport(conforms=False, violations=[v])
+ report.explain_violations()
+ self.assertIsNotNone(v.explanation)
+ self.assertIn("https://example.com/john", v.explanation)
+
+ # 33
+ def test_shacl_violation_to_dict(self):
+ from semantica.ontology.ontology_validator import SHACLViolation
+ v = SHACLViolation(
+ focus_node="https://example.com/n",
+ constraint="DatatypeConstraintComponent",
+ explanation="some explanation",
+ )
+ d = v.to_dict()
+ self.assertIn("focus_node", d)
+ self.assertIn("constraint", d)
+ self.assertIn("explanation", d)
+
+ # 34
+ def test_validation_report_to_dict_structure(self):
+ from semantica.ontology.ontology_validator import (
+ SHACLValidationReport,
+ SHACLViolation,
+ )
+ v = SHACLViolation(focus_node="https://example.com/x")
+ report = SHACLValidationReport(conforms=False, violations=[v])
+ d = report.to_dict()
+ self.assertIn("conforms", d)
+ self.assertIn("violations", d)
+ self.assertIn("warnings", d)
+ self.assertIn("violation_count", d)
+ self.assertEqual(d["violation_count"], 1)
+ self.assertFalse(d["conforms"])
+
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/ontology/test_ontology_comprehensive.py b/tests/ontology/test_ontology_comprehensive.py
index 954899ce..090840f7 100644
--- a/tests/ontology/test_ontology_comprehensive.py
+++ b/tests/ontology/test_ontology_comprehensive.py
@@ -243,5 +243,193 @@ class TestOntologyComprehensive(unittest.TestCase):
self.assertEqual(mod.name, "PersonModule")
self.assertIn("Person", mod.classes)
+class TestSHACLGeneration(unittest.TestCase):
+ """Tests 1-16: SHACL shape generation from flat ontologies."""
+
+ # Shared flat ontology fixture
+ _ONTOLOGY = {
+ "classes": [
+ {"name": "Person", "label": "Person", "description": "A human individual"},
+ {"name": "Organization", "label": "Organization"},
+ ],
+ "properties": [
+ {
+ "name": "name",
+ "type": "datatype",
+ "range": "string",
+ "domain": "Person",
+ "required": True,
+ },
+ {
+ "name": "age",
+ "type": "datatype",
+ "range": "integer",
+ "domain": "Person",
+ "cardinality": {"min": 0, "max": 1},
+ },
+ {
+ "name": "worksFor",
+ "type": "object",
+ "range": "Organization",
+ "domain": "Person",
+ },
+ {
+ "name": "legalName",
+ "type": "datatype",
+ "range": "string",
+ "domain": "Organization",
+ "required": True,
+ },
+ ],
+ }
+
+ def setUp(self):
+ self.mock_logger = MagicMock()
+ self.mock_tracker = MagicMock()
+ self.mock_tracker.start_tracking.return_value = "track_shacl"
+ self.patchers = [
+ patch(
+ "semantica.ontology.ontology_generator.get_logger",
+ return_value=self.mock_logger,
+ ),
+ patch(
+ "semantica.ontology.ontology_generator.get_progress_tracker",
+ return_value=self.mock_tracker,
+ ),
+ ]
+ for p in self.patchers:
+ p.start()
+ from semantica.ontology.ontology_generator import SHACLGenerator
+ self.gen = SHACLGenerator(
+ base_uri="https://semantica.dev/shapes/",
+ quality_tier="standard",
+ )
+
+ def tearDown(self):
+ for p in self.patchers:
+ p.stop()
+
+ # 1
+ def test_generate_returns_shacl_graph(self):
+ from semantica.ontology.ontology_generator import SHACLGraph
+ graph = self.gen.generate(self._ONTOLOGY)
+ self.assertIsInstance(graph, SHACLGraph)
+
+ # 2
+ def test_node_shape_count_matches_class_count(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ self.assertEqual(len(graph.node_shapes), 2)
+
+ # 3
+ def test_node_shape_target_classes(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ classes = {ns.target_class for ns in graph.node_shapes}
+ self.assertIn("Person", classes)
+ self.assertIn("Organization", classes)
+
+ # 4
+ def test_required_property_gets_min_count_1(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ person = next(ns for ns in graph.node_shapes if ns.target_class == "Person")
+ name_ps = next(ps for ps in person.property_shapes if ps.path == "name")
+ self.assertEqual(name_ps.min_count, 1)
+
+ # 5
+ def test_cardinality_min_max(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ person = next(ns for ns in graph.node_shapes if ns.target_class == "Person")
+ age_ps = next(ps for ps in person.property_shapes if ps.path == "age")
+ self.assertEqual(age_ps.min_count, 0)
+ self.assertEqual(age_ps.max_count, 1)
+
+ # 6
+ def test_datatype_property_gets_xsd_datatype(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ person = next(ns for ns in graph.node_shapes if ns.target_class == "Person")
+ name_ps = next(ps for ps in person.property_shapes if ps.path == "name")
+ self.assertEqual(name_ps.datatype, "xsd:string")
+ self.assertIsNone(name_ps.class_)
+
+ # 7
+ def test_object_property_gets_sh_class(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ person = next(ns for ns in graph.node_shapes if ns.target_class == "Person")
+ wf_ps = next(ps for ps in person.property_shapes if ps.path == "worksFor")
+ self.assertEqual(wf_ps.class_, "Organization")
+ self.assertIsNone(wf_ps.datatype)
+
+ # 8
+ def test_turtle_contains_sh_node_shape(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ ttl = self.gen.serialize(graph, format="turtle")
+ self.assertIn("sh:NodeShape", ttl)
+ self.assertIn("sh:targetClass", ttl)
+ self.assertIn("sh:property", ttl)
+
+ # 9
+ def test_jsonld_is_valid_json(self):
+ import json
+ graph = self.gen.generate(self._ONTOLOGY)
+ jld = self.gen.serialize(graph, format="json-ld")
+ parsed = json.loads(jld)
+ self.assertIn("@context", parsed)
+ self.assertIn("@graph", parsed)
+
+ # 10
+ def test_ntriples_uses_expanded_uris(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ nt = self.gen.serialize(graph, format="n-triples")
+ self.assertNotIn("@prefix", nt)
+ self.assertIn("<http://www.w3.org/ns/shacl#NodeShape>", nt)
+
+ # 11
+ def test_unknown_format_raises_value_error(self):
+ graph = self.gen.generate(self._ONTOLOGY)
+ with self.assertRaises(ValueError):
+ self.gen.serialize(graph, format="csv")
+
+ # 12
+ def test_non_dict_ontology_raises_value_error(self):
+ with self.assertRaises(ValueError):
+ self.gen.generate("not a dict")
+
+ # 13
+ def test_ontology_missing_both_keys_raises_value_error(self):
+ with self.assertRaises(ValueError):
+ self.gen.generate({"namespace": {}})
+
+ # 14
+ def test_enumeration_produces_sh_in(self):
+ onto = {
+ "classes": [{"name": "Order"}],
+ "properties": [
+ {
+ "name": "status",
+ "type": "datatype",
+ "range": "string",
+ "domain": "Order",
+ "one_of": ["pending", "shipped", "delivered", "cancelled"],
+ }
+ ],
+ }
+ graph = self.gen.generate(onto)
+ ttl = self.gen.serialize(graph, format="turtle")
+ self.assertIn("sh:in", ttl)
+ self.assertIn('"pending"', ttl)
+
+ # 15
+ def test_custom_namespace_in_prefixes(self):
+ onto = dict(self._ONTOLOGY)
+ onto["namespace"] = {"base_uri": "https://custom.org/onto/"}
+ graph = self.gen.generate(onto)
+ self.assertIn("https://custom.org/onto/", graph.prefixes.values())
+
+ # 16
+ def test_standard_tier_is_default(self):
+ from semantica.ontology.ontology_generator import SHACLGenerator
+ gen = SHACLGenerator()
+ self.assertEqual(gen.quality_tier, "standard")
+
+
if __name__ == '__main__':
unittest.main()