Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
refactor(ontology): standardize module docstrings to match normalize module format
KaifAhmad1ffc477bd12db
diff --git a/semantica/ontology/__init__.py b/semantica/ontology/__init__.pyindex 2ef0f8ed..d555265d 100644--- a/semantica/ontology/__init__.py+++ b/semantica/ontology/__init__.py@@ -4,23 +4,51 @@ Ontology Management ModuleThis module provides comprehensive ontology management and generation capabilities,following semantic modeling best practices and guidelines for building effective ontologies.-Exports:- - OntologyGenerator: Ontology generation from data (6-stage pipeline)+Key Features:+ - Automatic ontology generation from data (6-stage pipeline)+ - Class and property inference from entities and relationships+ - Ontology validation with symbolic reasoners (HermiT, Pellet)+ - OWL/RDF generation and serialization+ - Ontology quality evaluation and assessment+ - Requirements specification and competency questions+ - Ontology reuse and integration management+ - Version management with best practices+ - Namespace and IRI management+ - Naming convention enforcement+ - Modular ontology development+ - Pre-built domain ontologies+ - Comprehensive documentation management+ - Associative class creation for complex relationships++Main Classes:+ - OntologyGenerator: Main ontology generation class (6-stage pipeline)- ClassInferrer: Class discovery and hierarchy building- PropertyGenerator: Property inference and data types- OntologyValidator: Validation with symbolic reasoners- - OWLGenerator: OWL/RDF generation+ - OWLGenerator: OWL/RDF generation using rdflib- OntologyEvaluator: Ontology quality evaluation- RequirementsSpecManager: Requirements specification and competency questions- CompetencyQuestionsManager: Competency question management- ReuseManager: Ontology reuse management- VersionManager: Ontology versioning- - NamespaceManager: Namespace management+ - NamespaceManager: Namespace and IRI management- NamingConventions: Naming convention enforcement- ModuleManager: Ontology module management- DomainOntologies: Pre-built domain ontologies- OntologyDocumentationManager: Documentation management- AssociativeClassBuilder: Associative class creation++Example Usage:+ >>> from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator+ >>> generator = OntologyGenerator(base_uri="https://example.org/ontology/")+ >>> ontology = generator.generate_ontology({"entities": [...], "relationships": [...]})+ >>> inferrer = ClassInferrer()+ >>> classes = inferrer.infer_classes(entities)+ >>> prop_gen = PropertyGenerator()+ >>> properties = prop_gen.infer_properties(entities, relationships, classes)++Author: Semantica Contributors+License: MIT"""from .ontology_generator import OntologyGenerator, ClassInferencer, PropertyInferencer, OntologyOptimizerdiff --git a/semantica/ontology/associative_class.py b/semantica/ontology/associative_class.pyindex 6d6decc3..91765d94 100644--- a/semantica/ontology/associative_class.py+++ b/semantica/ontology/associative_class.py@@ -1,9 +1,33 @@"""-Associative Class Builder+Associative Class Builder Module-Supports creating associative classes (like Position) that connect-multiple classes together when simple relations are insufficient.-Useful for modeling complex relationships like Person-Role-Organization.+This module provides support for creating associative classes (like Position) that connect+multiple classes together when simple relations are insufficient. This is useful for+modeling complex relationships like Person-Role-Organization, where the relationship+itself has properties and temporal characteristics.++Key Features:+ - Create associative classes connecting multiple entities+ - Model complex multi-entity relationships+ - Support temporal associations (time-based connections)+ - Enable position/role modeling+ - Handle association cardinality+ - Support association property management+ - Validate associative class definitions++Main Classes:+ - AssociativeClassBuilder: Builder for creating associative classes+ - AssociativeClass: Dataclass representing an associative class++Example Usage:+ >>> from semantica.ontology import AssociativeClassBuilder+ >>> builder = AssociativeClassBuilder()+ >>> position = builder.create_position_class("Person", "Organization", "Role")+ >>> membership = builder.create_temporal_association("Membership", ["Person", "Organization"])+ >>> result = builder.validate_associative_class(position)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -15,7 +39,29 @@ from ..utils.logging import get_logger@dataclassclass AssociativeClass:- """Associative class definition."""+ """+ Associative class definition.++ Associative classes are used to model relationships that have their own properties+ and characteristics, beyond simple binary relationships.++ Attributes:+ name: Name of the associative class+ connects: List of class names this associative class connects+ properties: Dictionary of properties for the association+ temporal: Whether this is a temporal association (time-based)+ metadata: Additional metadata for the associative class++ Example:+ ```python+ assoc = AssociativeClass(+ name="Position",+ connects=["Person", "Organization", "Role"],+ properties={"startDate": "xsd:date", "endDate": "xsd:date"},+ temporal=True+ )+ ```+ """name: strconnects: List[str] # List of class names this connectsproperties: Dict[str, Any] = field(default_factory=dict)@@ -27,12 +73,31 @@ class AssociativeClassBuilder:"""Associative class builder for complex relationships.- • Create associative classes connecting multiple entities- • Model complex multi-entity relationships- • Support temporal associations (time-based connections)- • Enable position/role modeling- • Handle association cardinality- • Support association property management+ This class provides functionality to create and manage associative classes that+ connect multiple entities when simple binary relationships are insufficient.++ Features:+ - Create associative classes connecting multiple entities+ - Model complex multi-entity relationships+ - Support temporal associations (time-based connections)+ - Enable position/role modeling+ - Handle association cardinality+ - Support association property management+ - Validate associative class definitions++ Example:+ ```python+ builder = AssociativeClassBuilder()++ # Create position class+ position = builder.create_position_class(+ person_class="Person",+ organization_class="Organization"+ )++ # Validate+ result = builder.validate_associative_class(position)+ ```"""def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):@@ -42,6 +107,11 @@ class AssociativeClassBuilder:Args:config: Configuration dictionary**kwargs: Additional configuration options++ Example:+ ```python+ builder = AssociativeClassBuilder()+ ```"""self.logger = get_logger("associative_class_builder")self.config = config or {}@@ -58,15 +128,33 @@ class AssociativeClassBuilder:"""Create an associative class.+ Creates a new associative class that connects multiple classes together.+ This is useful for modeling relationships that have their own properties+ and characteristics.+Args:- name: Class name- connects: List of class names this connects+ name: Class name (must be non-empty)+ connects: List of class names this connects (must have at least 2 classes)**options: Additional options:- - temporal: Whether this is a temporal association- - properties: Properties for the association+ - temporal: Whether this is a temporal association (default: False)+ - properties: Dictionary of properties for the association (default: {})+ - metadata: Additional metadata dictionary (default: {})Returns:- Created associative class+ Created associative class instance++ Raises:+ ValidationError: If name is empty or connects has fewer than 2 classes++ Example:+ ```python+ assoc = builder.create_associative_class(+ name="Membership",+ connects=["Person", "Organization"],+ temporal=True,+ properties={"startDate": "xsd:date", "endDate": "xsd:date"}+ )+ ```"""if not name:raise ValidationError("Associative class name is required")@@ -98,14 +186,31 @@ class AssociativeClassBuilder:"""Create a position/role associative class.+ Creates a specialized associative class for modeling positions or roles+ that connect a person to an organization (and optionally a role). This+ is a common pattern in organizational modeling.+Args:person_class: Person class nameorganization_class: Organization class namerole_class: Optional role class name- **options: Additional options+ **options: Additional options:+ - name: Name for the position class (default: "Position")+ - temporal: Whether this is temporal (default: True)+ - properties: Additional properties dictionary+ - metadata: Additional metadata dictionaryReturns:- Created associative class+ Created associative class instance++ Example:+ ```python+ position = builder.create_position_class(+ person_class="Person",+ organization_class="Organization",+ role_class="Role"+ )+ ```"""connects = [person_class, organization_class]if role_class:@@ -132,13 +237,26 @@ class AssociativeClassBuilder:"""Create a temporal associative class.+ Creates an associative class with temporal characteristics, automatically+ adding startDate and endDate properties for time-based relationships.+Args:name: Class name- connects: List of class names- **options: Additional options+ connects: List of class names this connects+ **options: Additional options:+ - properties: Additional properties dictionary (startDate and endDate are added automatically)+ - metadata: Additional metadata dictionaryReturns:- Created associative class+ Created associative class instance with temporal properties++ Example:+ ```python+ membership = builder.create_temporal_association(+ name="Membership",+ connects=["Person", "Organization"]+ )+ ```"""return self.create_associative_class(name=name,@@ -156,11 +274,20 @@ class AssociativeClassBuilder:"""Get associative class by name.+ Retrieves an associative class that was previously created.+Args:- name: Class name+ name: Class name to retrieveReturns:- Associative class or None+ Associative class instance if found, None otherwise++ Example:+ ```python+ assoc = builder.get_associative_class("Position")+ if assoc:+ print(f"Found: {assoc.name}")+ ```"""return self.associative_classes.get(name)@@ -168,8 +295,17 @@ class AssociativeClassBuilder:"""List all associative classes.+ Returns a list of all associative classes that have been created.+Returns:- List of associative classes+ List of associative class instances++ Example:+ ```python+ all_classes = builder.list_associative_classes()+ for assoc in all_classes:+ print(assoc.name)+ ```"""return list(self.associative_classes.values())@@ -177,11 +313,26 @@ class AssociativeClassBuilder:"""Validate associative class.+ Validates an associative class definition, checking for required fields,+ proper structure, and potential issues.+Args:- assoc_class: Associative class to validate+ assoc_class: Associative class instance to validateReturns:- Validation result+ Dictionary with validation results:+ - valid: Boolean indicating if validation passed+ - errors: List of error messages+ - warnings: List of warning messages++ Example:+ ```python+ result = builder.validate_associative_class(assoc_class)+ if result["valid"]:+ print("Valid associative class")+ else:+ print(f"Errors: {result['errors']}")+ ```"""errors = []warnings = []diff --git a/semantica/ontology/class_inferrer.py b/semantica/ontology/class_inferrer.pyindex 8b6e5d85..e8598056 100644--- a/semantica/ontology/class_inferrer.py+++ b/semantica/ontology/class_inferrer.py@@ -1,8 +1,31 @@"""-Class inference for Semantica framework.+Class Inference Module-This module provides automatic class discovery and inference-from extracted entities and data patterns.+This module provides automatic class discovery and inference from extracted entities+and data patterns. It analyzes entity types, properties, and relationships to infer+ontology classes with proper naming conventions and hierarchical structures.++Key Features:+ - Automatic class discovery from entities+ - Pattern-based class inference+ - Hierarchical class structure building+ - Class validation and consistency checking+ - Multi-domain class support+ - Circular hierarchy detection+ - Performance optimization++Main Classes:+ - ClassInferrer: Class inference engine for ontology generation++Example Usage:+ >>> from semantica.ontology import ClassInferrer+ >>> inferrer = ClassInferrer(min_occurrences=2)+ >>> classes = inferrer.infer_classes(entities, build_hierarchy=True)+ >>> hierarchical = inferrer.build_class_hierarchy(classes)+ >>> validation = inferrer.validate_classes(classes)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional, Set@@ -17,12 +40,23 @@ class ClassInferrer:"""Class inference engine for ontology generation.- • Automatic class discovery from entities- • Pattern-based class inference- • Hierarchical class structure building- • Class validation and consistency checking- • Multi-domain class support- • Performance optimization+ This class provides automatic discovery and inference of ontology classes from+ entity data, building hierarchical structures and validating class definitions.++ Features:+ - Automatic class discovery from entities+ - Pattern-based class inference+ - Hierarchical class structure building+ - Class validation and consistency checking+ - Multi-domain class support+ - Circular hierarchy detection+ - Performance optimization++ Example:+ ```python+ inferrer = ClassInferrer(min_occurrences=2, similarity_threshold=0.8)+ classes = inferrer.infer_classes(entities)+ ```"""def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):@@ -34,6 +68,15 @@ class ClassInferrer:**kwargs: Additional configuration options:- min_occurrences: Minimum occurrences for class inference (default: 2)- similarity_threshold: Similarity threshold for class merging (default: 0.8)+ - namespace_manager: Optional namespace manager instance++ Example:+ ```python+ inferrer = ClassInferrer(+ min_occurrences=3,+ similarity_threshold=0.85+ )+ ```"""self.logger = get_logger("class_inferrer")self.config = config or {}@@ -51,12 +94,38 @@ class ClassInferrer:"""Infer classes from entities.+ Analyzes a list of entities and infers ontology classes based on entity types+ and common properties. Groups entities by type and creates class definitions+ for types that meet the minimum occurrence threshold.+Args:- entities: List of entity dictionaries- **options: Additional options+ entities: List of entity dictionaries, each containing at least:+ - type or entity_type: Entity type name+ - Additional properties that will be analyzed+ **options: Additional options:+ - build_hierarchy: Whether to build class hierarchy (default: True)+ - namespace_manager: Optional namespace manager for URI generationReturns:- List of inferred class definitions+ List of inferred class definition dictionaries, each containing:+ - name: Normalized class name+ - uri: Class URI (if namespace_manager provided)+ - label: Class label+ - comment: Class description+ - properties: List of common property names+ - entity_count: Number of entities of this type+ - metadata: Additional metadata++ Example:+ ```python+ entities = [+ {"type": "Person", "name": "John", "age": 30},+ {"type": "Person", "name": "Jane", "age": 25},+ {"type": "Organization", "name": "Acme Corp"}+ ]++ classes = inferrer.infer_classes(entities, build_hierarchy=True)+ ```"""# Group entities by typeentity_types = defaultdict(list)@@ -85,12 +154,30 @@ class ClassInferrer:"""Build class hierarchy from classes.+ Analyzes class names and relationships to infer parent-child relationships,+ building a taxonomic hierarchy. Uses naming patterns and common parent classes+ to establish subClassOf relationships.+Args:- classes: List of class definitions- **options: Additional options+ classes: List of class definition dictionaries+ **options: Additional options (currently unused)Returns:- Classes with hierarchy information+ List of class definitions with hierarchy information added:+ - subClassOf: Parent class name (if found)+ - parent: Alias for subClassOf++ Example:+ ```python+ classes = [+ {"name": "Person"},+ {"name": "Employee"},+ {"name": "Manager"}+ ]++ hierarchical = inferrer.build_class_hierarchy(classes)+ # Manager may have subClassOf: "Employee"+ ```"""# Create class mapclass_map = {cls["name"]: cls for cls in classes}@@ -186,12 +273,27 @@ class ClassInferrer:"""Validate inferred classes.+ Validates class definitions for naming conventions, duplicate names,+ and circular hierarchies. Provides suggestions for improvements.+Args:- classes: List of class definitions- **criteria: Validation criteria+ classes: List of class definition dictionaries+ **criteria: Validation criteria (currently unused)Returns:- Validation results+ Dictionary with validation results:+ - valid: Boolean indicating if validation passed+ - errors: List of error messages+ - warnings: List of warning messages with suggestions++ Example:+ ```python+ validation = inferrer.validate_classes(classes)+ if not validation["valid"]:+ print(f"Errors: {validation['errors']}")+ if validation["warnings"]:+ print(f"Warnings: {validation['warnings']}")+ ```"""errors = []warnings = []diff --git a/semantica/ontology/competency_questions.py b/semantica/ontology/competency_questions.pyindex 775dbae2..2d3fa750 100644--- a/semantica/ontology/competency_questions.py+++ b/semantica/ontology/competency_questions.py@@ -1,8 +1,32 @@"""-Competency Questions Manager+Competency Questions Manager Module-Manages competency questions that define what an ontology should answer,-serving as functional requirements that guide modeling decisions.+This module manages competency questions that define what an ontology should answer,+serving as functional requirements that guide modeling decisions. Competency questions+help ensure that the ontology can answer the queries it was designed to support.++Key Features:+ - Define and manage competency questions+ - Validate ontology against competency questions+ - Trace questions to ontology elements+ - Refine questions based on ontology evolution+ - Generate question-answer validation reports+ - Support natural language question formulation+ - Categorize questions by domain and priority++Main Classes:+ - CompetencyQuestionsManager: Manager for competency questions+ - CompetencyQuestion: Dataclass representing a competency question++Example Usage:+ >>> from semantica.ontology import CompetencyQuestionsManager+ >>> manager = CompetencyQuestionsManager()+ >>> manager.add_question("Who are the employees of a given organization?", category="organizational")+ >>> results = manager.validate_ontology(ontology)+ >>> report = manager.generate_report(ontology)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -15,7 +39,29 @@ from ..utils.logging import get_logger@dataclassclass CompetencyQuestion:- """Competency question definition."""+ """+ Competency question definition.++ Represents a question that the ontology should be able to answer, serving as+ a functional requirement for ontology design.++ Attributes:+ question: Question text in natural language+ category: Question category (e.g., "general", "organizational", "temporal")+ priority: Priority level (1=high, 2=medium, 3=low)+ answerable: Whether the ontology can currently answer this question+ trace_to_elements: List of ontology element names relevant to this question+ metadata: Additional metadata dictionary++ Example:+ ```python+ cq = CompetencyQuestion(+ question="Who are the employees of a given organization?",+ category="organizational",+ priority=1+ )+ ```+ """question: strcategory: str = "general"priority: int = 1 # 1=high, 2=medium, 3=low@@ -28,12 +74,25 @@ class CompetencyQuestionsManager:"""Competency questions manager for ontology requirements.- • Define and manage competency questions- • Validate ontology against competency questions- • Trace questions to ontology elements- • Refine questions based on ontology evolution- • Generate question-answer validation reports- • Support natural language question formulation+ This class manages competency questions that serve as functional requirements+ for ontology design. It validates whether an ontology can answer these questions+ and traces questions to relevant ontology elements.++ Features:+ - Define and manage competency questions+ - Validate ontology against competency questions+ - Trace questions to ontology elements+ - Refine questions based on ontology evolution+ - Generate question-answer validation reports+ - Support natural language question formulation+ - Categorize and prioritize questions++ Example:+ ```python+ manager = CompetencyQuestionsManager()+ manager.add_question("Who are the employees?", category="organizational")+ results = manager.validate_ontology(ontology)+ ```"""def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):@@ -43,6 +102,11 @@ class CompetencyQuestionsManager:Args:config: Configuration dictionary**kwargs: Additional configuration options++ Example:+ ```python+ manager = CompetencyQuestionsManager()+ ```"""self.logger = get_logger("competency_questions_manager")self.config = config or {}@@ -60,14 +124,26 @@ class CompetencyQuestionsManager:"""Add a competency question.+ Adds a new competency question to the manager. Competency questions define+ what the ontology should be able to answer.+Args:- question: Question text- category: Question category- priority: Priority (1=high, 2=medium, 3=low)- **metadata: Additional metadata+ question: Question text in natural language+ category: Question category (default: "general")+ priority: Priority level (1=high, 2=medium, 3=low, default: 1)+ **metadata: Additional metadata dictionaryReturns:- Created competency question+ Created CompetencyQuestion instance++ Example:+ ```python+ cq = manager.add_question(+ "Who are the employees of a given organization?",+ category="organizational",+ priority=1+ )+ ```"""cq = CompetencyQuestion(question=question,@@ -89,12 +165,27 @@ class CompetencyQuestionsManager:"""Validate ontology against competency questions.+ Checks whether the ontology can answer each competency question by analyzing+ the presence of relevant classes and properties. Updates the answerable+ status of each question.+Args:- ontology: Ontology dictionary- **options: Additional options+ ontology: Ontology dictionary containing classes and properties+ **options: Additional options (currently unused)Returns:- Validation results+ Dictionary with validation results:+ - total_questions: Total number of questions+ - answerable: Number of answerable questions+ - unanswerable: Number of unanswerable questions+ - by_category: Breakdown by category+ - by_priority: Breakdown by priority++ Example:+ ```python+ results = manager.validate_ontology(ontology)+ print(f"Answerable: {results['answerable']}/{results['total_questions']}")+ ```"""results = {"total_questions": len(self.questions),@@ -155,12 +246,22 @@ class CompetencyQuestionsManager:"""Trace question to ontology elements.+ Identifies which ontology elements (classes and properties) are relevant+ to answering a specific competency question. Uses keyword matching to find+ relevant elements.+Args:- question: Competency question- ontology: Ontology dictionary+ question: CompetencyQuestion instance to trace+ ontology: Ontology dictionary containing classes and propertiesReturns:- List of relevant ontology element names+ List of relevant ontology element names (classes and properties)++ Example:+ ```python+ elements = manager.trace_to_elements(question, ontology)+ print(f"Relevant elements: {elements}")+ ```"""elements = []question_lower = question.question.lower()@@ -187,11 +288,24 @@ class CompetencyQuestionsManager:"""Generate competency question validation report.+ Generates a comprehensive report showing which questions are answerable,+ which elements trace to each question, and overall coverage statistics.+Args:- ontology: Ontology dictionary+ ontology: Ontology dictionary to validateReturns:- Validation report+ Dictionary containing:+ - validation: Validation results dictionary+ - questions: List of question details with trace information+ - generated_at: Timestamp of report generation++ Example:+ ```python+ report = manager.generate_report(ontology)+ for q in report["questions"]:+ print(f"{q['question']}: {q['answerable']}")+ ```"""validation = self.validate_ontology(ontology)diff --git a/semantica/ontology/domain_ontologies.py b/semantica/ontology/domain_ontologies.pyindex f39cf07f..4bccfe6a 100644--- a/semantica/ontology/domain_ontologies.py+++ b/semantica/ontology/domain_ontologies.py@@ -1,8 +1,31 @@"""-Pre-built domain ontologies for Semantica framework.+Pre-built Domain Ontologies Module-This module provides pre-built domain-specific ontologies-for common use cases and domains.+This module provides pre-built domain-specific ontologies for common use cases+and domains. It includes templates for healthcare, finance, legal, research,+and cybersecurity domains, and allows registration of custom domain templates.++Key Features:+ - Healthcare domain ontology templates+ - Finance domain ontology templates+ - Legal domain ontology templates+ - Research domain ontology templates+ - Cybersecurity domain ontology templates+ - Custom domain ontology support+ - Domain template registration++Main Classes:+ - DomainOntologies: Manager for pre-built domain ontologies++Example Usage:+ >>> from semantica.ontology import DomainOntologies+ >>> domains = DomainOntologies()+ >>> template = domains.get_domain_template("healthcare")+ >>> ontology = domains.create_domain_ontology("healthcare", uri="https://example.org/healthcare/")+ >>> domains.register_domain_template("custom", {"classes": [...], "properties": [...]})++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/module_manager.py b/semantica/ontology/module_manager.pyindex 3f7d9671..035d9757 100644--- a/semantica/ontology/module_manager.py+++ b/semantica/ontology/module_manager.py@@ -1,8 +1,32 @@"""-Ontology Module Manager+Ontology Module Manager Module-Manages modular ontology development, supporting imports, subdomain-organization, and coordinated multi-team ontology development.+This module manages modular ontology development, supporting imports, subdomain+organization, and coordinated multi-team ontology development. It handles ontology+imports, module creation, and import closure resolution.++Key Features:+ - Ontology import management+ - Modular ontology organization+ - Subdomain ontology coordination+ - Cross-module reference handling+ - Import closure resolution+ - Module versioning and dependencies+ - Module validation++Main Classes:+ - ModuleManager: Manager for ontology modules+ - OntologyModule: Dataclass representing an ontology module++Example Usage:+ >>> from semantica.ontology import ModuleManager+ >>> manager = ModuleManager()+ >>> module = manager.create_module("PersonModule", "https://example.org/person/", "1.0")+ >>> manager.add_import("PersonModule", "https://example.org/core/")+ >>> imports = manager.resolve_imports("PersonModule")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/namespace_manager.py b/semantica/ontology/namespace_manager.pyindex 1bd3222c..89398386 100644--- a/semantica/ontology/namespace_manager.py+++ b/semantica/ontology/namespace_manager.py@@ -1,8 +1,33 @@"""-Namespace and IRI Manager+Namespace and IRI Manager Module-Manages ontology namespaces and generates consistent, human-readable-IRIs following best practices (speaking IRIs, version management).+This module manages ontology namespaces and generates consistent, human-readable+IRIs following best practices (speaking IRIs, version management). It provides+PascalCase for classes, camelCase for properties, and supports version-aware IRI+generation.++Key Features:+ - Define stable host namespaces+ - Generate consistent IRI conventions+ - PascalCase for classes+ - camelCase for properties and relations+ - Version-aware IRI management+ - Resolvable IRI generation+ - Speaking IRI support (human-readable)+ - Standard namespace registration (RDF, RDFS, OWL, XSD, SKOS, DC)++Main Classes:+ - NamespaceManager: Manager for namespaces and IRI generation++Example Usage:+ >>> from semantica.ontology import NamespaceManager+ >>> manager = NamespaceManager(base_uri="https://example.org/ontology/", version="1.0")+ >>> class_iri = manager.generate_class_iri("Person")+ >>> prop_iri = manager.generate_property_iri("hasName")+ >>> manager.register_namespace("ex", "https://example.org/")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/naming_conventions.py b/semantica/ontology/naming_conventions.pyindex 811469cb..2215da63 100644--- a/semantica/ontology/naming_conventions.py+++ b/semantica/ontology/naming_conventions.py@@ -1,8 +1,32 @@"""-Naming Conventions Manager+Naming Conventions Manager Module-Enforces and validates naming conventions for ontology elements following-semantic modeling best practices.+This module enforces and validates naming conventions for ontology elements+following semantic modeling best practices. It provides validation, suggestions,+and normalization for class names, property names, and ontology names.++Key Features:+ - Class naming: singular, PascalCase, nouns/noun phrases+ - Attribute naming: lowercase, nouns or verbs+ - Relation naming: camelCase, verbs/verb phrases+ - Ontology naming: title case with "Ontology" suffix+ - Vocabulary naming: title case with "Vocabulary" suffix+ - Naming validation and suggestions+ - Consistency checking across ontology+ - Automatic name normalization++Main Classes:+ - NamingConventions: Manager for naming convention enforcement++Example Usage:+ >>> from semantica.ontology import NamingConventions+ >>> conventions = NamingConventions()+ >>> is_valid, suggestion = conventions.validate_class_name("Person")+ >>> normalized = conventions.normalize_class_name("person class")+ >>> suggested = conventions.suggest_property_name("has name", "object")++Author: Semantica Contributors+License: MIT"""import rediff --git a/semantica/ontology/ontology_documentation.py b/semantica/ontology/ontology_documentation.pyindex 78f47470..64ca290a 100644--- a/semantica/ontology/ontology_documentation.py+++ b/semantica/ontology/ontology_documentation.py@@ -1,8 +1,32 @@"""-Ontology Documentation Manager+Ontology Documentation Manager Module-Provides comprehensive ontology documentation including metadata,-descriptions, version information, and contributor tracking.+This module provides comprehensive ontology documentation including metadata,+descriptions, version information, and contributor tracking. It supports+generation of Markdown documentation and export to various formats.++Key Features:+ - Ontology metadata management (description, purpose, scope)+ - Author and contributor tracking+ - Creation date and version tracking+ - License and IRI namespace management+ - Documentation generation and export+ - Documentation validation+ - Markdown and HTML export support++Main Classes:+ - OntologyDocumentationManager: Manager for ontology documentation+ - OntologyDocumentation: Dataclass representing ontology documentation++Example Usage:+ >>> from semantica.ontology import OntologyDocumentationManager+ >>> manager = OntologyDocumentationManager()+ >>> doc = manager.create_documentation("PersonOntology", "Ontology for person entities", "Model person-related concepts", "Person, Organization, Role")+ >>> markdown = manager.generate_markdown("PersonOntology", ontology)+ >>> manager.export_documentation("PersonOntology", "docs.md", format="markdown")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional, Uniondiff --git a/semantica/ontology/ontology_evaluator.py b/semantica/ontology/ontology_evaluator.pyindex 43652314..77b83d47 100644--- a/semantica/ontology/ontology_evaluator.py+++ b/semantica/ontology/ontology_evaluator.py@@ -1,8 +1,32 @@"""-Ontology Evaluator+Ontology Evaluator Module-Evaluates ontologies against competency questions and refines them-to ensure they meet requirements and can answer intended questions.+This module evaluates ontologies against competency questions and refines them+to ensure they meet requirements and can answer intended questions. It provides+coverage scores, completeness metrics, gap identification, and improvement suggestions.++Key Features:+ - Validate ontology against competency questions+ - Identify gaps in ontology coverage+ - Suggest refinements and improvements+ - Evaluate class granularity and generalization+ - Check relation completeness+ - Generate evaluation reports+ - Calculate coverage and completeness scores++Main Classes:+ - OntologyEvaluator: Evaluator for ontology quality assessment+ - EvaluationResult: Dataclass representing evaluation results++Example Usage:+ >>> from semantica.ontology import OntologyEvaluator+ >>> evaluator = OntologyEvaluator()+ >>> result = evaluator.evaluate_ontology(ontology, competency_questions=["Who are the employees?"])+ >>> report = evaluator.generate_report(ontology)+ >>> granularity = evaluator.evaluate_class_granularity(ontology)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/ontology_generator.py b/semantica/ontology/ontology_generator.pyindex d4a96b8c..9b946ab4 100644--- a/semantica/ontology/ontology_generator.py+++ b/semantica/ontology/ontology_generator.py@@ -1,20 +1,33 @@"""Ontology Generation Module-Handles automatic generation of ontologies from data and text.+This module handles automatic generation of ontologies from data and text using+a 6-stage pipeline that transforms raw data into structured OWL ontologies.Key Features:- - Automatic ontology generation+ - Automatic ontology generation (6-stage pipeline)- Class and property inference- Ontology structure optimization- Domain-specific ontology creation- Ontology quality assessment+ - Semantic network parsing+ - Hierarchy generationMain Classes:- OntologyGenerator: Main ontology generation class (6-stage pipeline)- - ClassInferencer: Class inference engine- - PropertyInferencer: Property inference engine+ - ClassInferencer: Class inference engine (legacy alias)+ - PropertyInferencer: Property inference engine (legacy alias)- OntologyOptimizer: Ontology optimization engine++Example Usage:+ >>> from semantica.ontology import OntologyGenerator+ >>> generator = OntologyGenerator(base_uri="https://example.org/ontology/")+ >>> ontology = generator.generate_ontology({"entities": [...], "relationships": [...]})+ >>> classes = generator.infer_classes(data)+ >>> properties = generator.infer_properties(data, classes)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional@@ -52,11 +65,23 @@ class OntologyGenerator:"""Initialize ontology generator.+ Sets up the ontology generator with namespace management, naming conventions,+ and inference engines for classes and properties.+Args:config: Configuration dictionary**kwargs: Additional configuration options:- - base_uri: Base URI for ontology- - namespace_manager: Namespace manager instance+ - base_uri: Base URI for ontology (default: "https://semantica.dev/ontology/")+ - namespace_manager: Optional namespace manager instance+ - min_occurrences: Minimum occurrences for class inference (default: 2)++ Example:+ ```python+ generator = OntologyGenerator(+ base_uri="https://example.org/ontology/",+ min_occurrences=3+ )+ ```"""self.logger = get_logger("ontology_generator")self.config = config or {}@@ -78,12 +103,41 @@ class OntologyGenerator:"""Generate ontology from data using 6-stage pipeline.+ Executes the complete 6-stage ontology generation pipeline:+ 1. Semantic Network Parsing: Extract domain concepts from entities/relationships+ 2. YAML-to-Definition: Transform concepts into class definitions+ 3. Definition-to-Types: Map definitions to OWL types+ 4. Hierarchy Generation: Build taxonomic structures+ 5. TTL Generation: (Handled by OWLGenerator)+ 6. Symbolic Validation: (Handled by OntologyValidator)+Args:- data: Input data (entities, relationships, semantic network)- **options: Generation options+ data: Input data dictionary containing:+ - entities: List of entity dictionaries+ - relationships: List of relationship dictionaries+ - semantic_network: Optional pre-parsed semantic network+ **options: Generation options:+ - name: Ontology name (default: "GeneratedOntology")+ - build_hierarchy: Whether to build class hierarchy (default: True)+ - namespace_manager: Optional namespace manager instanceReturns:- Generated ontology dictionary+ Generated ontology dictionary containing:+ - uri: Ontology URI+ - name: Ontology name+ - version: Version string+ - classes: List of class definitions+ - properties: List of property definitions+ - metadata: Additional metadata++ Example:+ ```python+ generator = OntologyGenerator(base_uri="https://example.org/ontology/")+ ontology = generator.generate_ontology({+ "entities": [{"type": "Person", "name": "John"}],+ "relationships": [{"type": "worksFor", "source": "John", "target": "Acme"}]+ })+ ```"""# Stage 1: Semantic Network Parsingsemantic_network = self._stage1_parse_semantic_network(data, **options)diff --git a/semantica/ontology/ontology_validator.py b/semantica/ontology/ontology_validator.pyindex ccc9e141..54db9030 100644--- a/semantica/ontology/ontology_validator.py+++ b/semantica/ontology/ontology_validator.py@@ -1,11 +1,34 @@"""-Ontology validation for Semantica framework.+Ontology Validator Module-This module provides schema validation and consistency checking-for generated ontologies using symbolic reasoners (HermiT, Pellet)-to achieve F1 scores up to 0.99 while maintaining sub-hour generation times.+This module provides schema validation and consistency checking for generated+ontologies using symbolic reasoners (HermiT, Pellet) to achieve F1 scores up+to 0.99 while maintaining sub-hour generation times. It supports hybrid validation+with LLM draft generation + symbolic reasoner validation + domain expert refinement.-Hybrid architecture: LLM draft generation + symbolic reasoner validation + domain expert refinement+Key Features:+ - Symbolic reasoner integration (HermiT, Pellet)+ - Consistency checking and validation+ - Constraint validation against domain rules+ - Hallucination detection in LLM-generated ontologies+ - Hybrid validation (LLM + symbolic reasoner)+ - Performance optimization for large ontologies+ - Integration with domain expert refinement+ - Circular hierarchy detection+ - Satisfiability checking++Main Classes:+ - OntologyValidator: Validator for ontology structure and consistency+ - ValidationResult: Dataclass representing validation results++Example Usage:+ >>> from semantica.ontology import OntologyValidator+ >>> validator = OntologyValidator(reasoner="hermit")+ >>> result = validator.validate_ontology(ontology)+ >>> if result.valid: print("Ontology is valid")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/owl_generator.py b/semantica/ontology/owl_generator.pyindex fd885302..312bd9d5 100644--- a/semantica/ontology/owl_generator.py+++ b/semantica/ontology/owl_generator.py@@ -1,8 +1,30 @@"""-OWL/RDF generation for Semantica framework.+OWL/RDF Generation Module-This module provides OWL and RDF generation capabilities-using rdflib for ontology serialization.+This module provides OWL and RDF generation capabilities using rdflib for ontology+serialization. It supports multiple RDF formats and provides fallback string-based+generation when rdflib is not available.++Key Features:+ - OWL ontology generation using rdflib+ - RDF serialization in multiple formats (Turtle, RDF/XML, JSON-LD, N3)+ - Namespace management and prefix handling+ - Ontology validation and consistency checking+ - Export to various RDF formats+ - Performance optimization for large ontologies+ - Fallback string-based generation without rdflib++Main Classes:+ - OWLGenerator: Generator for OWL/RDF serialization++Example Usage:+ >>> from semantica.ontology import OWLGenerator+ >>> generator = OWLGenerator()+ >>> turtle = generator.generate_owl(ontology, format="turtle")+ >>> generator.export_owl(ontology, "ontology.ttl", format="turtle")++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional, Union@@ -67,13 +89,28 @@ class OWLGenerator:"""Generate OWL from ontology dictionary.+ Converts an ontology dictionary to OWL/RDF format. Uses rdflib if available,+ otherwise falls back to basic string formatting.+Args:- ontology: Ontology dictionary- format: Output format ('turtle', 'rdfxml', 'json-ld', 'n3')- **options: Additional options+ ontology: Ontology dictionary containing:+ - uri: Ontology URI+ - name: Ontology name+ - version: Version string+ - classes: List of class definitions+ - properties: List of property definitions+ format: Output format ('turtle', 'rdfxml', 'json-ld', 'n3', default: 'turtle')+ **options: Additional options (currently unused)Returns:- OWL serialization string or Graph object+ OWL serialization string (if rdflib not available or format specified)+ or rdflib Graph object (if rdflib available and no format specified)++ Example:+ ```python+ turtle = generator.generate_owl(ontology, format="turtle")+ graph = generator.generate_owl(ontology) # Returns Graph if rdflib available+ ```"""output_format = format or self.default_formatdiff --git a/semantica/ontology/property_generator.py b/semantica/ontology/property_generator.pyindex 895a3814..d37107c7 100644--- a/semantica/ontology/property_generator.py+++ b/semantica/ontology/property_generator.py@@ -1,8 +1,30 @@"""-Property generation for Semantica framework.+Property Generation Module-This module provides property inference and generation-for ontology classes and relationships.+This module provides property inference and generation for ontology classes and+relationships. It analyzes entity attributes and relationships to infer object+and data properties with appropriate domains, ranges, and types.++Key Features:+ - Property inference from data patterns+ - Relationship property generation+ - Property type inference and validation+ - Domain and range specification+ - Property hierarchy management+ - Multi-language property support+ - Automatic XSD type detection++Main Classes:+ - PropertyGenerator: Generator for ontology properties++Example Usage:+ >>> from semantica.ontology import PropertyGenerator+ >>> generator = PropertyGenerator()+ >>> properties = generator.infer_properties(entities, relationships, classes)+ >>> validation = generator.validate_properties(properties)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/requirements_spec.py b/semantica/ontology/requirements_spec.pyindex 70f3d079..31719e77 100644--- a/semantica/ontology/requirements_spec.py+++ b/semantica/ontology/requirements_spec.py@@ -1,8 +1,32 @@"""Ontology Requirements Specification Module-This module supports the ontology requirements specification phase,-including competency questions, scope definition, and purpose documentation.+This module supports the ontology requirements specification phase, including+competency questions, scope definition, and purpose documentation. It helps+ensure that ontologies are designed to meet specific functional requirements.++Key Features:+ - Competency question management+ - Scope definition and validation+ - Purpose and use case documentation+ - Stakeholder collaboration tracking+ - Domain expert input integration+ - Requirements traceability+ - Specification validation++Main Classes:+ - RequirementsSpecManager: Manager for requirements specifications+ - RequirementsSpec: Dataclass representing a requirements specification++Example Usage:+ >>> from semantica.ontology import RequirementsSpecManager+ >>> manager = RequirementsSpecManager()+ >>> spec = manager.create_spec("PersonOntologySpec", "Model person-related concepts", "Person, Organization, Role entities")+ >>> manager.add_competency_question("PersonOntologySpec", "Who are the employees of an organization?", category="organizational")+ >>> trace = manager.trace_requirements("PersonOntologySpec", ontology)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/reuse_manager.py b/semantica/ontology/reuse_manager.pyindex 0c587953..2506daa8 100644--- a/semantica/ontology/reuse_manager.py+++ b/semantica/ontology/reuse_manager.py@@ -1,8 +1,33 @@"""-Ontology Reuse Manager+Ontology Reuse Manager Module-Manages ontology reuse including research, evaluation, and integration-of existing ontologies (internal and external) and non-ontological resources.+This module manages ontology reuse including research, evaluation, and integration+of existing ontologies (internal and external) and non-ontological resources. It+helps identify reusable ontologies, assess compatibility, and manage imports.++Key Features:+ - Research existing ontologies+ - Evaluate ontology alignment and compatibility+ - Assess interoperability benefits+ - Manage external ontology imports+ - Handle internal ontology reuse+ - Convert non-ontological resources to ontologies+ - Track reuse decisions and dependencies+ - Known ontology catalog (FOAF, Dublin Core, Schema.org)++Main Classes:+ - ReuseManager: Manager for ontology reuse+ - ReuseDecision: Dataclass representing a reuse decision++Example Usage:+ >>> from semantica.ontology import ReuseManager+ >>> manager = ReuseManager()+ >>> info = manager.research_ontology("http://xmlns.com/foaf/0.1/")+ >>> alignment = manager.evaluate_alignment(source_uri, target_ontology)+ >>> ontology = manager.import_external_ontology(source_uri, target_ontology)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optionaldiff --git a/semantica/ontology/version_manager.py b/semantica/ontology/version_manager.pyindex e1df8fa2..15313305 100644--- a/semantica/ontology/version_manager.py+++ b/semantica/ontology/version_manager.py@@ -1,5 +1,5 @@"""-Ontology versioning for Semantica framework.+Ontology Version Manager ModuleThis module provides ontology versioning following best practices:- Single ontology IRI that resolves to specific version (includes version in IRI)@@ -7,6 +7,31 @@ This module provides ontology versioning following best practices:- owl:versionInfo for tool compatibility- Version-less logical IRIs for latest stable release- Multiple versions can coexist in same graph database++Key Features:+ - Version-aware IRI generation (version in ontology IRI, not element IRIs)+ - Version-less element IRIs for stability+ - owl:versionInfo metadata support+ - Logical version-less IRIs for latest releases+ - Multi-version coexistence in graph database+ - Import closure resolution under versioning+ - Version comparison and diff generation+ - Migration and upgrade utilities++Main Classes:+ - VersionManager: Manager for ontology versioning+ - OntologyVersion: Dataclass representing an ontology version++Example Usage:+ >>> from semantica.ontology import VersionManager+ >>> manager = VersionManager(base_uri="https://example.org/ontology/")+ >>> version = manager.create_version("1.0", ontology, changes=["Added Person class"])+ >>> element_iri = manager.generate_element_iri("Person", "class")+ >>> comparison = manager.compare_versions("1.0", "2.0")+ >>> migrated = manager.migrate_ontology("1.0", "2.0", ontology)++Author: Semantica Contributors+License: MIT"""from typing import Any, Dict, List, Optional