How Semantica Supports SHACL and OWL for Data Governance

Semantica provides a full-stack, programmatic toolkit to generate, export, and validate SHACL shapes and OWL ontologies from a single Python-native ontology definition, enabling automated data governance workflows without external dependencies.

Semantica is an open-source semantic framework that bridges plain Python dictionaries and W3C semantic standards. The library converts dictionary-based ontology definitions into SHACL (Shapes Constraint Language) constraints for data validation and OWL (Web Ontology Language) ontologies for semantic interoperability. According to the semantica-agi/semantica source code, this process is handled by specialized generator classes and a unified validation engine defined in the ontology module.

SHACL Generation Engine

The SHACLGenerator class in semantica/ontology/ontology_generator.py transforms Python ontology dictionaries into valid SHACL graphs. It constructs NodeShape and PropertyShape objects programmatically, handling complex inheritance hierarchies and namespace resolution.

The Six-Step Shape Construction Pipeline

The generator orchestrates shape creation through a deterministic pipeline defined in the generate method:

  1. _build_class_index – Creates an O(1) lookup index for all ontology classes to accelerate subsequent operations.

  2. _generate_node_shapes – Instantiates one NodeShape per class, initializing target declarations and basic metadata.

  3. _attach_property_shapes – Maps properties to their domain classes, converting datatype and object properties into corresponding PropertyShape constraints.

  4. _propagate_inheritance – Copies parent shape constraints to child classes safely, ensuring polymorphic validation behavior.

  5. _apply_quality_tier – Enforces governance strictness; when quality_tier="strict" is passed to the constructor, it marks all shapes as closed to prevent unspecified properties.

  6. serialize – Outputs the SHACLGraph to Turtle, JSON-LD, or N-Triples formats.

The generator also respects the attach_domainless_properties flag, which preserves legacy behavior by attaching properties lacking explicit domains to every generated shape.

OWL Generation Engine

The OWLGenerator class in semantica/ontology/owl_generator.py emits standard OWL/RDF ontologies using rdflib when available, falling back to a lightweight string formatter for environments without heavy dependencies.

Namespace Management and Serialization

The generation process begins with NamespaceManager, which constructs base URIs from ontology.get("uri") or sensible defaults. The _generate_with_rdflib method constructs an RDF Graph, adding triples for owl:Class, owl:ObjectProperty, and owl:DatatypeProperty declarations while attaching version metadata. If rdflib is unavailable, _generate_basic constructs valid Turtle syntax manually.

The generate_owl method returns either an rdflib Graph object for programmatic manipulation or a formatted string, while export_owl persists the output directly to the filesystem. This dual-output approach supports both pipeline integration and human-readable documentation generation.

SHACL Validation Pipeline

Validation occurs in semantica/ontology/ontology_validator.py through the run_shacl_validation function. This wrapper leverages pySHACL and rdflib to validate arbitrary RDF data graphs against generated SHACL shapes, returning a structured SHACLValidationReport.

Structured Validation Reports

The SHACLValidationReport class provides machine-readable governance feedback through three key attributes:

  • conforms – Boolean indicating overall data compliance
  • violations – List of SHACLViolation objects containing severity, focus node, and constraint details
  • explain_violations – Method generating human-readable descriptions of each constraint breach

This structure enables CI/CD integration, allowing automated rejection of non-conforming data without invoking external AI services.

Practical Code Examples

Generating SHACL Shapes

The following example creates strict SHACL constraints from a minimal ontology definition:

from semantica.ontology.ontology_generator import SHACLGenerator

# Define ontology as plain Python structures

my_ontology = {
    "namespace": {"base_uri": "https://example.org/"},
    "classes": [{"name": "Person", "description": "A human"}],
    "properties": [
        {"name": "name", "type": "datatype", "datatype": "string", "domain": "Person"},
        {"name": "knows", "type": "object", "range": "Person", "domain": "Person"},
    ],
}

# Initialize generator with strict quality tier

shacl_gen = SHACLGenerator(quality_tier="strict")
shacl_graph = shacl_gen.generate(my_ontology)

# Export to Turtle for distribution

turtle_output = shacl_gen.serialize(shacl_graph, format="turtle")
print(turtle_output)

Validating RDF Data Against SHACL

Use run_shacl_validation to check concrete RDF instances against your shapes:

from semantica.ontology.ontology_validator import run_shacl_validation

# Sample data graph

data_ttl = """
@prefix ex: <https://example.org/> .
ex:alice a ex:Person ; ex:name "Alice" .
"""

# Assuming shacl_ttl contains Turtle from the generator above

shacl_ttl = """{paste generated Turtle here}"""

report = run_shacl_validation(data_ttl, shacl_ttl)

print(f"Conforms: {report.conforms}")
report.explain_violations()

for violation in report.violations:
    print(violation.explanation)

Exporting OWL Ontologies

Generate OWL/RDF for semantic interoperability:

from semantica.ontology.owl_generator import OWLGenerator

owl_gen = OWLGenerator()

# Returns rdflib Graph (if installed) or formatted string

ttl_string = owl_gen.generate_owl(my_ontology, format="turtle")
print(ttl_string)

# Or write directly to file

owl_gen.export_owl(my_ontology, path="ontology.ttl", format="turtle")

Summary

Semantica delivers a unified Python-native interface for semantic data governance through three core capabilities:

  • Programmatic SHACL Generation: The SHACLGenerator class converts Python dictionaries into closed or open shapes using a six-step pipeline that handles inheritance and property attachment.
  • Dual-Mode OWL Export: The OWLGenerator produces standards-compliant OWL ontologies via rdflib or lightweight string formatting, supporting both generate_owl (in-memory) and export_owl (file-based) workflows.
  • Integrated Validation: The run_shacl_validation function returns structured SHACLValidationReport objects containing machine-readable SHACLViolation details and human-readable explanations.

These components reside in semantica/ontology/ontology_generator.py, semantica/ontology/owl_generator.py, and semantica/ontology/ontology_validator.py, providing a complete governance stack without external AI dependencies.

Frequently Asked Questions

How does Semantica handle properties without explicit domains?

Semantica provides the attach_domainless_properties flag in SHACLGenerator. When enabled, properties lacking a defined domain are attached to every generated node shape, preserving backward compatibility with legacy ontology definitions that assume global property applicability.

Can Semantica validate RDF data without installing rdflib?

No, SHACL validation requires both rdflib and pySHACL as dependencies. The run_shacl_validation function in ontology_validator.py explicitly uses rdflib to parse data graphs and pySHACL to execute constraint checking. However, OWL generation can function without rdflib using the fallback _generate_basic string formatter.

What is the difference between strict and default quality tiers in SHACL generation?

The quality_tier="strict" parameter forces SHACLGenerator to mark all node shapes as closed during the _apply_quality_tier step. Closed shapes reject properties not explicitly defined in the ontology, enforcing rigorous data governance, while the default tier permits additional properties to accommodate evolving schemas.

How do I export SHACL shapes to formats other than Turtle?

The serialize method of SHACLGenerator accepts a format parameter supporting Turtle, JSON-LD, and N-Triples. This delegates to the underlying SHACLGraph serialization logic, allowing shapes to integrate with diverse RDF processing pipelines regardless of preferred syntax.

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 →