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
feat: standardize ontology module with methods, registry, and config
KaifAhmad1f8412f741422
diff --git a/semantica/ontology/__init__.py b/semantica/ontology/__init__.pyindex d555265d..703bf43d 100644--- a/semantica/ontology/__init__.py+++ b/semantica/ontology/__init__.py@@ -4,6 +4,65 @@ Ontology Management ModuleThis module provides comprehensive ontology management and generation capabilities,following semantic modeling best practices and guidelines for building effective ontologies.+Algorithms Used:++Ontology Generation (6-Stage Pipeline):+ - Stage 1 - Semantic Network Parsing: Extract domain concepts from entities/relationships, entity type analysis (Counter), relationship pattern extraction, concept grouping+ - Stage 2 - YAML-to-Definition: Transform concepts into class definitions, YAML parsing, definition structure creation, class inference (ClassInferrer.infer_classes)+ - Stage 3 - Definition-to-Types: Map definitions to OWL types, type inference, OWL class/property mapping (@type assignment: owl:Class, owl:ObjectProperty, owl:DatatypeProperty), property inference (PropertyGenerator.infer_properties)+ - Stage 4 - Hierarchy Generation: Build taxonomic structures, parent-child relationship inference, hierarchy validation, circular dependency detection (DFS), transitive closure calculation+ - Stage 5 - TTL Generation: Generate OWL/Turtle syntax using rdflib, namespace prefix handling, RDF serialization (rdflib.serialize format="turtle"), triple generation (subject-predicate-object)+ - Stage 6 - Symbolic Validation: HermiT/Pellet reasoning (owlready2.sync_reasoner), consistency checking, satisfiability checking, constraint validation++Class Inference:+ - Pattern-Based Inference: Entity type frequency analysis (Counter), minimum occurrence threshold filtering, similarity-based class merging (threshold matching), entity grouping by type+ - Hierarchy Building: Parent-child relationship inference, transitive closure calculation, hierarchy depth analysis, circular dependency detection (DFS), parent class assignment+ - Class Validation: Naming convention enforcement (PascalCase), IRI generation (namespace_manager.generate_class_iri), namespace validation, class name normalization++Property Inference:+ - Object Property Inference: Relationship type analysis, domain/range inference from entity types, property cardinality detection, relationship-to-property mapping+ - Data Property Inference: Entity attribute analysis, XSD type detection (string, integer, float, boolean, date), property domain inference, attribute frequency analysis+ - Property Validation: Domain/range validation, property hierarchy management, naming convention enforcement (camelCase), property IRI generation++Ontology Validation:+ - Symbolic Reasoning: HermiT reasoner integration (owlready2.sync_reasoner), Pellet reasoner integration, consistency checking, satisfiability checking, reasoner selection (auto/hermit/pellet)+ - Constraint Validation: Domain/range constraint checking, cardinality constraint validation, logical constraint validation, structure validation+ - Hallucination Detection: LLM-generated ontology validation, fact verification, relationship validation, error/warning collection++OWL/RDF Generation:+ - RDF Graph Construction: rdflib.Graph creation, namespace binding, triple generation (subject-predicate-object), namespace prefix declaration+ - Serialization: Turtle format (rdflib.serialize format="turtle"), RDF/XML format, JSON-LD format, N3 format, format selection and conversion+ - Namespace Management: Prefix declaration, IRI resolution, namespace prefix mapping, standard namespace registration (RDF, RDFS, OWL, XSD, SKOS, DC)++Ontology Evaluation:+ - Competency Question Validation: Question parsing, ontology query generation, answer coverage analysis, question-to-ontology element tracing+ - Coverage Metrics: Class coverage calculation, property coverage calculation, relationship coverage calculation, answerable question ratio+ - Completeness Metrics: Required class detection, missing property identification, gap analysis, completeness score calculation+ - Granularity Evaluation: Class granularity assessment, generalization/specialization analysis, granularity score calculation++Requirements Specification:+ - Competency Question Management: Question storage, categorization (general, organizational, temporal), validation, priority assignment (1=high, 2=medium, 3=low)+ - Scope Definition: Domain boundary definition, entity type scoping, relationship scoping, purpose documentation+ - Traceability: Requirements-to-ontology mapping, coverage tracking, trace-to-elements assignment++Ontology Reuse:+ - Ontology Research: Known ontology catalog lookup (FOAF, Dublin Core, Schema.org), URI resolution, metadata extraction, ontology information retrieval+ - Alignment Evaluation: Concept alignment scoring, compatibility assessment, interoperability analysis, alignment score calculation+ - Import Management: External ontology import, namespace merging, conflict resolution, import decision tracking (reuse/partial/reject)++Version Management:+ - Version-Aware IRI Generation: Version in ontology IRI (not element IRIs), version-less element IRIs, logical version-less IRIs, versioned IRI construction (urljoin)+ - Version Comparison: Diff generation, change detection, migration path identification, version diff analysis+ - Multi-Version Coexistence: Version isolation, import closure resolution, version record management++Namespace Management:+ - IRI Generation: Base URI + local name construction (urljoin), namespace prefix mapping, IRI validation, speaking IRI support (human-readable)+ - Prefix Handling: Prefix declaration, namespace binding, prefix resolution, standard namespace registration++Associative Class Creation:+ - Complex Relationship Modeling: N-ary relationship handling, relationship properties, intermediate class creation, multi-entity connection+ - Pattern Detection: Relationship pattern analysis, associative class inference, temporal association detection+Key Features:- Automatic ontology generation from data (6-stage pipeline)- Class and property inference from entities and relationships@@ -19,6 +78,8 @@ Key Features:- Pre-built domain ontologies- Comprehensive documentation management- Associative class creation for complex relationships+ - Method registry for extensibility+ - Configuration management with environment variables and config filesMain Classes:- OntologyGenerator: Main ontology generation class (6-stage pipeline)@@ -37,8 +98,33 @@ Main Classes:- DomainOntologies: Pre-built domain ontologies- OntologyDocumentationManager: Documentation management- AssociativeClassBuilder: Associative class creation+ - MethodRegistry: Registry for custom ontology methods+ - OntologyConfig: Configuration manager for ontology module++Convenience Functions:+ - generate_ontology: Ontology generation wrapper (6-stage pipeline)+ - infer_classes: Class inference wrapper+ - infer_properties: Property inference wrapper+ - validate_ontology: Ontology validation wrapper+ - generate_owl: OWL/RDF generation wrapper+ - evaluate_ontology: Ontology evaluation wrapper+ - create_requirements_spec: Requirements specification wrapper+ - add_competency_question: Competency question management wrapper+ - research_ontology: Ontology research wrapper+ - import_external_ontology: External ontology import wrapper+ - create_version: Version creation wrapper+ - manage_namespace: Namespace management wrapper+ - create_associative_class: Associative class creation wrapper+ - get_ontology_method: Get ontology method by name+ - list_available_methods: List registered methodsExample Usage:+ >>> from semantica.ontology import generate_ontology, infer_classes, validate_ontology, OntologyGenerator+ >>> # Using convenience functions+ >>> ontology = generate_ontology({"entities": [...], "relationships": [...]}, method="default")+ >>> classes = infer_classes(entities, method="default")+ >>> result = validate_ontology(ontology, method="default")+ >>> # Using classes directly>>> from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator>>> generator = OntologyGenerator(base_uri="https://example.org/ontology/")>>> ontology = generator.generate_ontology({"entities": [...], "relationships": [...]})@@ -51,6 +137,8 @@ Author: Semantica ContributorsLicense: MIT"""+from typing import Any, Dict, List, Optional, Union+from .ontology_generator import OntologyGenerator, ClassInferencer, PropertyInferencer, OntologyOptimizerfrom .class_inferrer import ClassInferrerfrom .property_generator import PropertyGenerator@@ -67,6 +155,25 @@ from .module_manager import ModuleManager, OntologyModulefrom .domain_ontologies import DomainOntologiesfrom .ontology_documentation import OntologyDocumentationManager, OntologyDocumentationfrom .associative_class import AssociativeClassBuilder, AssociativeClass+from .registry import MethodRegistry, method_registry+from .methods import (+ generate_ontology,+ infer_classes,+ infer_properties,+ validate_ontology,+ generate_owl,+ evaluate_ontology,+ create_requirements_spec,+ add_competency_question,+ research_ontology,+ import_external_ontology,+ create_version,+ manage_namespace,+ create_associative_class,+ get_ontology_method,+ list_available_methods,+)+from .config import OntologyConfig, ontology_config__all__ = [# Main generators@@ -108,4 +215,27 @@ __all__ = [# Special classes"AssociativeClassBuilder","AssociativeClass",++ # Registry and Methods+ "MethodRegistry",+ "method_registry",+ "generate_ontology",+ "infer_classes",+ "infer_properties",+ "validate_ontology",+ "generate_owl",+ "evaluate_ontology",+ "create_requirements_spec",+ "add_competency_question",+ "research_ontology",+ "import_external_ontology",+ "create_version",+ "manage_namespace",+ "create_associative_class",+ "get_ontology_method",+ "list_available_methods",++ # Configuration+ "OntologyConfig",+ "ontology_config",]diff --git a/semantica/ontology/config.py b/semantica/ontology/config.pynew file mode 100644index 00000000..de3b411a--- /dev/null+++ b/semantica/ontology/config.py@@ -0,0 +1,162 @@+"""+Configuration Management Module for Ontology++This module provides centralized configuration management for ontology operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: ONTOLOGY_BASE_URI, ONTOLOGY_REASONER, ONTOLOGY_FORMAT, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting ontology configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for ontology parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - OntologyConfig: Main configuration manager class for ontology module++Example Usage:+ >>> from semantica.ontology.config import ontology_config+ >>> base_uri = ontology_config.get("base_uri", default="https://semantica.dev/ontology/")+ >>> ontology_config.set("base_uri", "https://example.org/ontology/")+ >>> method_config = ontology_config.get_method_config("generate")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class OntologyConfig:+ """Configuration manager for ontology module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ self.logger = get_logger("ontology_config")+ self._configs: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict] = {}+ self._load_config_file(config_file)+ self._load_env_vars()++ def _load_config_file(self, config_file: Optional[str]):+ if config_file and Path(config_file).exists():+ try:+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):+ import yaml+ with open(config_file, 'r') as f:+ data = yaml.safe_load(f) or {}+ self._configs.update(data.get("ontology", {}))+ self._method_configs.update(data.get("ontology_methods", {}))+ elif config_file.endswith('.json'):+ import json+ with open(config_file, 'r') as f:+ data = json.load(f) or {}+ self._configs.update(data.get("ontology", {}))+ self._method_configs.update(data.get("ontology_methods", {}))+ elif config_file.endswith('.toml'):+ import toml+ with open(config_file, 'r') as f:+ data = toml.load(f) or {}+ if "ontology" in data:+ self._configs.update(data["ontology"])+ if "ontology_methods" in data:+ self._method_configs.update(data["ontology_methods"])+ self.logger.info(f"Loaded ontology config from {config_file}")+ except Exception as e:+ self.logger.warning(f"Failed to load config file {config_file}: {e}")++ def _load_env_vars(self):+ env_mappings = {+ "ONTOLOGY_BASE_URI": ("base_uri", str),+ "ONTOLOGY_REASONER": ("reasoner", str),+ "ONTOLOGY_FORMAT": ("format", str),+ "ONTOLOGY_MIN_OCCURRENCES": ("min_occurrences", int),+ "ONTOLOGY_SIMILARITY_THRESHOLD": ("similarity_threshold", float),+ "ONTOLOGY_CHECK_CONSISTENCY": ("check_consistency", bool),+ "ONTOLOGY_CHECK_SATISFIABILITY": ("check_satisfiability", bool),+ }++ for env_key, (config_key, type_func) in env_mappings.items():+ value = os.getenv(env_key)+ if value:+ try:+ if type_func == bool:+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")+ else:+ self._configs[config_key] = type_func(value)+ except (ValueError, TypeError):+ self.logger.warning(f"Failed to parse {env_key}={value}")++ env_prefix = "ONTOLOGY_"+ for key, value in os.environ.items():+ if key.startswith(env_prefix) and key not in env_mappings:+ config_key = key[len(env_prefix):].lower()+ if value.lower() in ('true', 'false'):+ self._configs[config_key] = value.lower() == 'true'+ elif value.isdigit():+ self._configs[config_key] = int(value)+ else:+ try:+ self._configs[config_key] = float(value)+ except ValueError:+ self._configs[config_key] = value++ def set(self, key: str, value: Any):+ """Set configuration value programmatically."""+ self._configs[key] = value++ def get(self, key: str, default: Any = None) -> Any:+ """Get configuration value with fallback chain: config -> env -> default."""+ if key in self._configs:+ return self._configs[key]++ env_key = f"ONTOLOGY_{key.upper()}"+ value = os.getenv(env_key)+ if value:+ try:+ if isinstance(default, int):+ return int(value)+ elif isinstance(default, float):+ return float(value)+ elif isinstance(default, bool):+ return value.lower() in ("true", "1", "yes", "on")+ return value+ except (ValueError, TypeError):+ pass++ return default++ def set_method_config(self, method: str, **config):+ """Set method-specific configuration."""+ self._method_configs[method] = config++ def get_method_config(self, method: str) -> Dict:+ """Get method-specific configuration."""+ return self._method_configs.get(method, {})++ def get_all(self) -> Dict[str, Any]:+ """Get all configuration."""+ return {+ "config": self._configs.copy(),+ "method_configs": self._method_configs.copy()+ }+++# Global config instance+ontology_config = OntologyConfig()+diff --git a/semantica/ontology/methods.py b/semantica/ontology/methods.pynew file mode 100644index 00000000..b12cb4f9--- /dev/null+++ b/semantica/ontology/methods.py@@ -0,0 +1,803 @@+"""+Ontology Methods Module++This module provides all ontology operations as simple, reusable functions for+ontology generation, class/property inference, validation, evaluation, OWL generation,+requirements specification, reuse management, versioning, namespace management, and+associative class creation. It supports multiple approaches and integrates with the+method registry for extensibility.++Supported Methods:++Ontology Generation:+ - "default": Default ontology generation using 6-stage pipeline+ - "from_data": Generate from entity/relationship data+ - "from_text": Generate from text (future support)++Class/Property Inference:+ - "default": Default inference using ClassInferrer/PropertyGenerator+ - "pattern": Pattern-based inference+ - "hierarchical": Hierarchy-focused inference++Validation:+ - "default": Default validation using OntologyValidator+ - "hermit": HermiT reasoner validation+ - "pellet": Pellet reasoner validation+ - "basic": Basic structure validation only++Evaluation:+ - "default": Default evaluation using OntologyEvaluator+ - "coverage": Coverage-focused evaluation+ - "completeness": Completeness-focused evaluation++OWL Generation:+ - "default": Default OWL generation using OWLGenerator+ - "turtle": Turtle format generation+ - "rdfxml": RDF/XML format generation+ - "jsonld": JSON-LD format generation++Algorithms Used:++Ontology Generation (6-Stage Pipeline):+ - Stage 1 - Semantic Network Parsing: Extract domain concepts from entities/relationships, entity type analysis (Counter), relationship pattern extraction+ - Stage 2 - YAML-to-Definition: Transform concepts into class definitions, YAML parsing, definition structure creation+ - Stage 3 - Definition-to-Types: Map definitions to OWL types, type inference, OWL class/property mapping (@type assignment)+ - Stage 4 - Hierarchy Generation: Build taxonomic structures, parent-child relationship inference, hierarchy validation, circular dependency detection (DFS)+ - Stage 5 - TTL Generation: Generate OWL/Turtle syntax using rdflib, namespace prefix handling, RDF serialization (rdflib.serialize)+ - Stage 6 - Symbolic Validation: HermiT/Pellet reasoning (owlready2.sync_reasoner), consistency checking, satisfiability checking, constraint validation++Class Inference:+ - Pattern-Based Inference: Entity type frequency analysis (Counter), minimum occurrence threshold filtering, similarity-based class merging (threshold matching)+ - Hierarchy Building: Parent-child relationship inference, transitive closure calculation, hierarchy depth analysis, circular dependency detection (DFS)+ - Class Validation: Naming convention enforcement (PascalCase), IRI generation (namespace_manager.generate_class_iri), namespace validation++Property Inference:+ - Object Property Inference: Relationship type analysis, domain/range inference from entity types, property cardinality detection+ - Data Property Inference: Entity attribute analysis, XSD type detection (string, integer, float, boolean, date), property domain inference+ - Property Validation: Domain/range validation, property hierarchy management, naming convention enforcement (camelCase)++Ontology Validation:+ - Symbolic Reasoning: HermiT reasoner integration (owlready2.sync_reasoner), Pellet reasoner integration, consistency checking, satisfiability checking+ - Constraint Validation: Domain/range constraint checking, cardinality constraint validation, logical constraint validation+ - Hallucination Detection: LLM-generated ontology validation, fact verification, relationship validation++OWL/RDF Generation:+ - RDF Graph Construction: rdflib.Graph creation, namespace binding, triple generation (subject-predicate-object)+ - Serialization: Turtle format (rdflib.serialize format="turtle"), RDF/XML format, JSON-LD format, N3 format+ - Namespace Management: Prefix declaration, IRI resolution, namespace prefix mapping++Ontology Evaluation:+ - Competency Question Validation: Question parsing, ontology query generation, answer coverage analysis+ - Coverage Metrics: Class coverage calculation, property coverage calculation, relationship coverage calculation+ - Completeness Metrics: Required class detection, missing property identification, gap analysis+ - Granularity Evaluation: Class granularity assessment, generalization/specialization analysis++Requirements Specification:+ - Competency Question Management: Question storage, categorization, validation+ - Scope Definition: Domain boundary definition, entity type scoping, relationship scoping+ - Traceability: Requirements-to-ontology mapping, coverage tracking++Ontology Reuse:+ - Ontology Research: Known ontology catalog lookup (FOAF, Dublin Core, Schema.org), URI resolution, metadata extraction+ - Alignment Evaluation: Concept alignment scoring, compatibility assessment, interoperability analysis+ - Import Management: External ontology import, namespace merging, conflict resolution++Version Management:+ - Version-Aware IRI Generation: Version in ontology IRI (not element IRIs), version-less element IRIs, logical version-less IRIs+ - Version Comparison: Diff generation, change detection, migration path identification+ - Multi-Version Coexistence: Version isolation, import closure resolution++Namespace Management:+ - IRI Generation: Base URI + local name construction (urljoin), namespace prefix mapping, IRI validation+ - Prefix Handling: Prefix declaration, namespace binding, prefix resolution++Associative Class Creation:+ - Complex Relationship Modeling: N-ary relationship handling, relationship properties, intermediate class creation+ - Pattern Detection: Relationship pattern analysis, associative class inference++Key Features:+ - Multiple ontology operation methods+ - Ontology operations with method dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - generate_ontology: Ontology generation wrapper (6-stage pipeline)+ - infer_classes: Class inference wrapper+ - infer_properties: Property inference wrapper+ - validate_ontology: Ontology validation wrapper+ - generate_owl: OWL/RDF generation wrapper+ - evaluate_ontology: Ontology evaluation wrapper+ - create_requirements_spec: Requirements specification wrapper+ - add_competency_question: Competency question management wrapper+ - research_ontology: Ontology research wrapper+ - import_external_ontology: External ontology import wrapper+ - create_version: Version creation wrapper+ - manage_namespace: Namespace management wrapper+ - create_associative_class: Associative class creation wrapper+ - get_ontology_method: Get ontology method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.ontology.methods import generate_ontology, infer_classes, validate_ontology+ >>> ontology = generate_ontology({"entities": [...], "relationships": [...]}, method="default")+ >>> classes = infer_classes(entities, method="default")+ >>> result = validate_ontology(ontology, method="default")+"""++from typing import Any, Dict, List, Optional, Callable, Union++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError, ConfigurationError+from .ontology_generator import OntologyGenerator+from .class_inferrer import ClassInferrer+from .property_generator import PropertyGenerator+from .ontology_validator import OntologyValidator+from .owl_generator import OWLGenerator+from .ontology_evaluator import OntologyEvaluator+from .requirements_spec import RequirementsSpecManager+from .competency_questions import CompetencyQuestionsManager+from .reuse_manager import ReuseManager+from .version_manager import VersionManager+from .namespace_manager import NamespaceManager+from .associative_class import AssociativeClassBuilder+from .registry import method_registry+from .config import ontology_config++logger = get_logger("ontology_methods")+++def generate_ontology(+ data: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Generate ontology from data using 6-stage pipeline (convenience function).++ This is a user-friendly wrapper that generates ontologies using the specified method.++ Args:+ data: Input data dictionary containing:+ - entities: List of entity dictionaries+ - relationships: List of relationship dictionaries+ - semantic_network: Optional pre-parsed semantic network+ method: Generation method (default: "default")+ - "default": Use OntologyGenerator with 6-stage pipeline+ - "from_data": Generate from entity/relationship data+ **kwargs: Additional options passed to OntologyGenerator+ - name: Ontology name (default: "GeneratedOntology")+ - base_uri: Base URI for ontology+ - build_hierarchy: Whether to build class hierarchy (default: True)++ Returns:+ dict: 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++ Examples:+ >>> from semantica.ontology.methods import generate_ontology+ >>> ontology = generate_ontology({+ ... "entities": [{"type": "Person", "name": "John"}],+ ... "relationships": [{"type": "worksFor", "source": "John", "target": "Acme"}]+ ... }, method="default")+ """+ custom_method = method_registry.get("generate", method)+ if custom_method:+ try:+ return custom_method(data, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("generate")+ config.update(kwargs)++ generator = OntologyGenerator(**config)+ return generator.generate_ontology(data, **kwargs)++ except Exception as e:+ logger.error(f"Failed to generate ontology: {e}")+ raise+++def infer_classes(+ entities: List[Dict[str, Any]],+ method: str = "default",+ **kwargs+) -> List[Dict[str, Any]]:+ """+ Infer classes from entities (convenience function).++ This is a user-friendly wrapper that infers ontology classes using the specified method.++ Args:+ entities: List of entity dictionaries+ method: Inference method (default: "default")+ - "default": Use ClassInferrer with default settings+ - "pattern": Pattern-based inference+ - "hierarchical": Hierarchy-focused inference+ **kwargs: Additional options passed to ClassInferrer+ - build_hierarchy: Whether to build class hierarchy (default: True)+ - min_occurrences: Minimum occurrences for class inference (default: 2)+ - similarity_threshold: Similarity threshold for class merging (default: 0.8)++ Returns:+ list: List of inferred class definition dictionaries++ Examples:+ >>> from semantica.ontology.methods import infer_classes+ >>> classes = infer_classes(entities, method="default", build_hierarchy=True)+ """+ custom_method = method_registry.get("infer", method)+ if custom_method:+ try:+ return custom_method(entities, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("infer")+ config.update(kwargs)++ inferrer = ClassInferrer(**config)+ return inferrer.infer_classes(entities, **kwargs)++ except Exception as e:+ logger.error(f"Failed to infer classes: {e}")+ raise+++def infer_properties(+ entities: List[Dict[str, Any]],+ relationships: List[Dict[str, Any]],+ classes: List[Dict[str, Any]],+ method: str = "default",+ **kwargs+) -> List[Dict[str, Any]]:+ """+ Infer properties from entities and relationships (convenience function).++ This is a user-friendly wrapper that infers ontology properties using the specified method.++ Args:+ entities: List of entity dictionaries+ relationships: List of relationship dictionaries+ classes: List of class definitions+ method: Inference method (default: "default")+ **kwargs: Additional options passed to PropertyGenerator++ Returns:+ list: List of inferred property definitions++ Examples:+ >>> from semantica.ontology.methods import infer_properties+ >>> properties = infer_properties(entities, relationships, classes, method="default")+ """+ custom_method = method_registry.get("infer", method)+ if custom_method:+ try:+ return custom_method(entities, relationships, classes, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("infer")+ config.update(kwargs)++ generator = PropertyGenerator(**config)+ return generator.infer_properties(entities, relationships, classes, **kwargs)++ except Exception as e:+ logger.error(f"Failed to infer properties: {e}")+ raise+++def validate_ontology(+ ontology: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Any:+ """+ Validate ontology structure and consistency (convenience function).++ This is a user-friendly wrapper that validates ontologies using the specified method.++ Args:+ ontology: Ontology dictionary+ method: Validation method (default: "default")+ - "default": Use OntologyValidator with default settings+ - "hermit": HermiT reasoner validation+ - "pellet": Pellet reasoner validation+ - "basic": Basic structure validation only+ **kwargs: Additional options passed to OntologyValidator+ - reasoner: Reasoner to use ('hermit', 'pellet', 'auto')+ - check_consistency: Check consistency (default: True)+ - check_satisfiability: Check satisfiability (default: True)++ Returns:+ ValidationResult: Validation result containing:+ - valid: True if valid, False otherwise+ - consistent: True if consistent, False otherwise+ - errors: List of error messages+ - warnings: List of warning messages+ - metrics: Additional validation metrics++ Examples:+ >>> from semantica.ontology.methods import validate_ontology+ >>> result = validate_ontology(ontology, method="default")+ >>> if result.valid: print("Ontology is valid")+ """+ custom_method = method_registry.get("validate", method)+ if custom_method:+ try:+ return custom_method(ontology, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("validate")+ config.update(kwargs)++ validator = OntologyValidator(**config)+ return validator.validate_ontology(ontology, **kwargs)++ except Exception as e:+ logger.error(f"Failed to validate ontology: {e}")+ raise+++def generate_owl(+ ontology: Dict[str, Any],+ format: Optional[str] = None,+ method: str = "default",+ **kwargs+) -> Union[str, Any]:+ """+ Generate OWL/RDF from ontology dictionary (convenience function).++ This is a user-friendly wrapper that generates OWL using the specified method.++ Args:+ ontology: Ontology dictionary+ format: Output format ('turtle', 'rdfxml', 'json-ld', 'n3', default: 'turtle')+ method: Generation method (default: "default")+ - "default": Use OWLGenerator with default settings+ - "turtle": Turtle format generation+ - "rdfxml": RDF/XML format generation+ - "jsonld": JSON-LD format generation+ **kwargs: Additional options passed to OWLGenerator++ Returns:+ str or Graph: OWL serialization string or rdflib Graph object++ Examples:+ >>> from semantica.ontology.methods import generate_owl+ >>> turtle = generate_owl(ontology, format="turtle", method="default")+ """+ custom_method = method_registry.get("owl", method)+ if custom_method:+ try:+ return custom_method(ontology, format, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("owl")+ config.update(kwargs)++ generator = OWLGenerator(**config)+ return generator.generate_owl(ontology, format=format, **kwargs)++ except Exception as e:+ logger.error(f"Failed to generate OWL: {e}")+ raise+++def evaluate_ontology(+ ontology: Dict[str, Any],+ competency_questions: Optional[List[str]] = None,+ method: str = "default",+ **kwargs+) -> Any:+ """+ Evaluate ontology against competency questions (convenience function).++ This is a user-friendly wrapper that evaluates ontologies using the specified method.++ Args:+ ontology: Ontology dictionary+ competency_questions: List of competency questions (optional)+ method: Evaluation method (default: "default")+ - "default": Use OntologyEvaluator with default settings+ - "coverage": Coverage-focused evaluation+ - "completeness": Completeness-focused evaluation+ **kwargs: Additional options passed to OntologyEvaluator++ Returns:+ EvaluationResult: Evaluation result containing:+ - coverage_score: Coverage score (0.0 to 1.0)+ - completeness_score: Completeness score (0.0 to 1.0)+ - gaps: List of identified gaps+ - suggestions: List of improvement suggestions+ - metrics: Additional evaluation metrics++ Examples:+ >>> from semantica.ontology.methods import evaluate_ontology+ >>> result = evaluate_ontology(ontology, competency_questions=["Who are the employees?"], method="default")+ """+ custom_method = method_registry.get("evaluate", method)+ if custom_method:+ try:+ return custom_method(ontology, competency_questions, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("evaluate")+ config.update(kwargs)++ evaluator = OntologyEvaluator(**config)+ return evaluator.evaluate_ontology(ontology, competency_questions=competency_questions, **kwargs)++ except Exception as e:+ logger.error(f"Failed to evaluate ontology: {e}")+ raise+++def create_requirements_spec(+ name: str,+ purpose: str,+ scope: str,+ method: str = "default",+ **kwargs+) -> Any:+ """+ Create requirements specification (convenience function).++ This is a user-friendly wrapper that creates requirements specifications using the specified method.++ Args:+ name: Specification name+ purpose: Purpose description+ scope: Scope description+ method: Method (default: "default")+ **kwargs: Additional options passed to RequirementsSpecManager+ - domain: Domain name+ - stakeholders: List of stakeholders+ - use_cases: List of use cases++ Returns:+ RequirementsSpec: Created requirements specification++ Examples:+ >>> from semantica.ontology.methods import create_requirements_spec+ >>> spec = create_requirements_spec("PersonOntology", "Model person concepts", "Person entities", method="default")+ """+ custom_method = method_registry.get("requirements", method)+ if custom_method:+ try:+ return custom_method(name, purpose, scope, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("requirements")+ config.update(kwargs)++ manager = RequirementsSpecManager(**config)+ return manager.create_spec(name, purpose, scope, **kwargs)++ except Exception as e:+ logger.error(f"Failed to create requirements spec: {e}")+ raise+++def add_competency_question(+ spec_name: str,+ question: str,+ category: str = "general",+ method: str = "default",+ **kwargs+) -> Any:+ """+ Add competency question to requirements specification (convenience function).++ This is a user-friendly wrapper that adds competency questions using the specified method.++ Args:+ spec_name: Specification name+ question: Question text+ category: Question category (default: "general")+ method: Method (default: "default")+ **kwargs: Additional options passed to CompetencyQuestionsManager++ Returns:+ CompetencyQuestion: Added competency question++ Examples:+ >>> from semantica.ontology.methods import add_competency_question+ >>> cq = add_competency_question("PersonOntology", "Who are the employees?", category="organizational", method="default")+ """+ custom_method = method_registry.get("requirements", method)+ if custom_method:+ try:+ return custom_method(spec_name, question, category, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("requirements")+ config.update(kwargs)++ manager = RequirementsSpecManager(**config)+ return manager.add_competency_question(spec_name, question, category=category, **kwargs)++ except Exception as e:+ logger.error(f"Failed to add competency question: {e}")+ raise+++def research_ontology(+ uri: str,+ method: str = "default",+ **kwargs+) -> Optional[Dict[str, Any]]:+ """+ Research existing ontology (convenience function).++ This is a user-friendly wrapper that researches ontologies using the specified method.++ Args:+ uri: Ontology URI+ method: Method (default: "default")+ **kwargs: Additional options passed to ReuseManager++ Returns:+ Optional[dict]: Ontology information or None if not found++ Examples:+ >>> from semantica.ontology.methods import research_ontology+ >>> info = research_ontology("http://xmlns.com/foaf/0.1/", method="default")+ """+ custom_method = method_registry.get("reuse", method)+ if custom_method:+ try:+ return custom_method(uri, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("reuse")+ config.update(kwargs)++ manager = ReuseManager(**config)+ return manager.research_ontology(uri, **kwargs)++ except Exception as e:+ logger.error(f"Failed to research ontology: {e}")+ raise+++def import_external_ontology(+ source_uri: str,+ target_ontology: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Dict[str, Any]:+ """+ Import external ontology (convenience function).++ This is a user-friendly wrapper that imports external ontologies using the specified method.++ Args:+ source_uri: Source ontology URI+ target_ontology: Target ontology dictionary+ method: Method (default: "default")+ **kwargs: Additional options passed to ReuseManager++ Returns:+ dict: Updated target ontology with imported elements++ Examples:+ >>> from semantica.ontology.methods import import_external_ontology+ >>> updated = import_external_ontology("http://xmlns.com/foaf/0.1/", ontology, method="default")+ """+ custom_method = method_registry.get("reuse", method)+ if custom_method:+ try:+ return custom_method(source_uri, target_ontology, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("reuse")+ config.update(kwargs)++ manager = ReuseManager(**config)+ return manager.import_external_ontology(source_uri, target_ontology, **kwargs)++ except Exception as e:+ logger.error(f"Failed to import external ontology: {e}")+ raise+++def create_version(+ version: str,+ ontology: Dict[str, Any],+ method: str = "default",+ **kwargs+) -> Any:+ """+ Create ontology version (convenience function).++ This is a user-friendly wrapper that creates ontology versions using the specified method.++ Args:+ version: Version string (e.g., "1.0", "2.1")+ ontology: Ontology dictionary+ method: Method (default: "default")+ **kwargs: Additional options passed to VersionManager+ - changes: List of changes+ - metadata: Additional metadata++ Returns:+ OntologyVersion: Created version record++ Examples:+ >>> from semantica.ontology.methods import create_version+ >>> version = create_version("1.0", ontology, changes=["Added Person class"], method="default")+ """+ custom_method = method_registry.get("version", method)+ if custom_method:+ try:+ return custom_method(version, ontology, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("version")+ config.update(kwargs)++ manager = VersionManager(**config)+ return manager.create_version(version, ontology, **kwargs)++ except Exception as e:+ logger.error(f"Failed to create version: {e}")+ raise+++def manage_namespace(+ operation: str,+ **kwargs+) -> Any:+ """+ Manage namespace operations (convenience function).++ This is a user-friendly wrapper that manages namespaces using the specified method.++ Args:+ operation: Operation to perform:+ - "generate_class_iri": Generate class IRI+ - "generate_property_iri": Generate property IRI+ - "register_namespace": Register namespace+ - "get_base_uri": Get base URI+ **kwargs: Additional options passed to NamespaceManager+ - class_name: Class name (for generate_class_iri)+ - property_name: Property name (for generate_property_iri)+ - prefix: Namespace prefix (for register_namespace)+ - uri: Namespace URI (for register_namespace)++ Returns:+ Result depends on operation:+ - generate_class_iri: Class IRI string+ - generate_property_iri: Property IRI string+ - register_namespace: None+ - get_base_uri: Base URI string++ Examples:+ >>> from semantica.ontology.methods import manage_namespace+ >>> class_iri = manage_namespace("generate_class_iri", class_name="Person", base_uri="https://example.org/")+ """+ custom_method = method_registry.get("namespace", "default")+ if custom_method:+ try:+ return custom_method(operation, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("namespace")+ config.update(kwargs)++ manager = NamespaceManager(**config)++ if operation == "generate_class_iri":+ return manager.generate_class_iri(kwargs.get("class_name", ""), **kwargs)+ elif operation == "generate_property_iri":+ return manager.generate_property_iri(kwargs.get("property_name", ""), **kwargs)+ elif operation == "register_namespace":+ return manager.register_namespace(kwargs.get("prefix", ""), kwargs.get("uri", ""), **kwargs)+ elif operation == "get_base_uri":+ return manager.get_base_uri()+ else:+ raise ValueError(f"Unknown namespace operation: {operation}")++ except Exception as e:+ logger.error(f"Failed to manage namespace: {e}")+ raise+++def create_associative_class(+ name: str,+ connects: List[str],+ method: str = "default",+ **kwargs+) -> Any:+ """+ Create associative class (convenience function).++ This is a user-friendly wrapper that creates associative classes using the specified method.++ Args:+ name: Associative class name+ connects: List of class names this associative class connects+ method: Method (default: "default")+ **kwargs: Additional options passed to AssociativeClassBuilder+ - properties: Dictionary of properties+ - temporal: Whether this is a temporal association (default: False)+ - metadata: Additional metadata++ Returns:+ AssociativeClass: Created associative class++ Examples:+ >>> from semantica.ontology.methods import create_associative_class+ >>> position = create_associative_class("Position", ["Person", "Organization", "Role"], method="default")+ """+ custom_method = method_registry.get("associative", method)+ if custom_method:+ try:+ return custom_method(name, connects, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ config = ontology_config.get_method_config("associative")+ config.update(kwargs)++ builder = AssociativeClassBuilder(**config)+ return builder.create_associative_class(name, connects, **kwargs)++ except Exception as e:+ logger.error(f"Failed to create associative class: {e}")+ raise+++def get_ontology_method(task: str, name: str) -> Optional[Callable]:+ """Get ontology method by task and name."""+ return method_registry.get(task, name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """List all registered ontology methods."""+ return method_registry.list_all(task)+++# Register default methods+method_registry.register("generate", "default", generate_ontology)+method_registry.register("infer", "default", infer_classes)+method_registry.register("validate", "default", validate_ontology)+method_registry.register("evaluate", "default", evaluate_ontology)+method_registry.register("owl", "default", generate_owl)+method_registry.register("requirements", "default", create_requirements_spec)+method_registry.register("reuse", "default", research_ontology)+method_registry.register("version", "default", create_version)+method_registry.register("namespace", "default", manage_namespace)+method_registry.register("associative", "default", create_associative_class)+diff --git a/semantica/ontology/ontology_usage.md b/semantica/ontology/ontology_usage.mdnew file mode 100644index 00000000..5bdaf75f--- /dev/null+++ b/semantica/ontology/ontology_usage.md@@ -0,0 +1,1052 @@+# Ontology Management Module Usage Guide++This comprehensive guide demonstrates how to use the ontology management module for ontology generation, class/property inference, validation, evaluation, OWL generation, requirements specification, reuse management, versioning, namespace management, and associative class creation.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [Ontology Generation](#ontology-generation)+3. [Class Inference](#class-inference)+4. [Property Inference](#property-inference)+5. [Ontology Validation](#ontology-validation)+6. [OWL/RDF Generation](#owlrdf-generation)+7. [Ontology Evaluation](#ontology-evaluation)+8. [Requirements Specification](#requirements-specification)+9. [Ontology Reuse](#ontology-reuse)+10. [Version Management](#version-management)+11. [Namespace Management](#namespace-management)+12. [Associative Classes](#associative-classes)+13. [Using Methods](#using-methods)+14. [Using Registry](#using-registry)+15. [Configuration](#configuration)+16. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using the Convenience Functions++```python+from semantica.ontology import generate_ontology, infer_classes, validate_ontology++# Generate ontology+data = {+ "entities": [+ {"type": "Person", "name": "John"},+ {"type": "Organization", "name": "Acme Corp"}+ ],+ "relationships": [+ {"type": "worksFor", "source": "John", "target": "Acme Corp"}+ ]+}++ontology = generate_ontology(data, method="default")+print(f"Generated ontology: {ontology['name']}")++# Infer classes+entities = [{"type": "Person", "name": "John"}]+classes = infer_classes(entities, method="default")+print(f"Inferred {len(classes)} classes")++# Validate ontology+result = validate_ontology(ontology, method="default")+if result.valid:+ print("Ontology is valid")+```++### Using Main Classes++```python+from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator++# Create generators+generator = OntologyGenerator(base_uri="https://example.org/ontology/")+inferrer = ClassInferrer()+prop_gen = PropertyGenerator()++# Generate ontology+ontology = generator.generate_ontology(data)++# Infer classes+classes = inferrer.infer_classes(entities, build_hierarchy=True)++# Infer properties+properties = prop_gen.infer_properties(entities, relationships, classes)+```++## Ontology Generation++### Basic Ontology Generation++```python+from semantica.ontology import generate_ontology, OntologyGenerator++# Using convenience function+data = {+ "entities": [+ {"type": "Person", "name": "John", "age": 30},+ {"type": "Person", "name": "Jane", "age": 25},+ {"type": "Organization", "name": "Acme Corp"}+ ],+ "relationships": [+ {"type": "worksFor", "source": "John", "target": "Acme Corp"},+ {"type": "worksFor", "source": "Jane", "target": "Acme Corp"}+ ]+}++ontology = generate_ontology(data, method="default", name="PersonOrgOntology")+print(f"URI: {ontology['uri']}")+print(f"Classes: {len(ontology['classes'])}")+print(f"Properties: {len(ontology['properties'])}")++# Using class directly+generator = OntologyGenerator(base_uri="https://example.org/ontology/")+ontology = generator.generate_ontology(data, name="PersonOrgOntology")+```++### 6-Stage Pipeline++The ontology generation uses a 6-stage pipeline:++1. **Semantic Network Parsing**: Extract domain concepts+2. **YAML-to-Definition**: Transform to class definitions+3. **Definition-to-Types**: Map to OWL types+4. **Hierarchy Generation**: Build taxonomic structures+5. **TTL Generation**: Generate OWL/Turtle syntax+6. **Symbolic Validation**: HermiT/Pellet reasoning++```python+from semantica.ontology import OntologyGenerator++generator = OntologyGenerator(base_uri="https://example.org/ontology/")++# Generate with full pipeline+ontology = generator.generate_ontology(+ data,+ name="MyOntology",+ build_hierarchy=True+)++# Access pipeline stages+print(f"Stage 1: Parsed {len(ontology.get('metadata', {}).get('concept_count', 0))} concepts")+print(f"Stage 2-3: Generated {len(ontology['classes'])} classes and {len(ontology['properties'])} properties")+print(f"Stage 4: Built hierarchy with {len([c for c in ontology['classes'] if 'parent' in c])} parent-child relationships")+```++### Generation Options++```python+from semantica.ontology import generate_ontology++# Generate with custom options+ontology = generate_ontology(+ data,+ method="default",+ name="CustomOntology",+ base_uri="https://example.org/ontology/",+ build_hierarchy=True,+ min_occurrences=3+)+```++## Class Inference++### Basic Class Inference++```python+from semantica.ontology import infer_classes, ClassInferrer++entities = [+ {"type": "Person", "name": "John", "age": 30},+ {"type": "Person", "name": "Jane", "age": 25},+ {"type": "Organization", "name": "Acme Corp"},+ {"type": "Organization", "name": "Tech Inc"}+]++# Using convenience function+classes = infer_classes(entities, method="default", build_hierarchy=True)++for cls in classes:+ print(f"Class: {cls['name']}, Instances: {cls.get('entity_count', 0)}")++# Using class directly+inferrer = ClassInferrer(min_occurrences=2, similarity_threshold=0.8)+classes = inferrer.infer_classes(entities, build_hierarchy=True)+```++### Hierarchy Building++```python+from semantica.ontology import ClassInferrer++inferrer = ClassInferrer()++# Infer classes with hierarchy+classes = inferrer.infer_classes(entities, build_hierarchy=True)++# Build hierarchy separately+hierarchical = inferrer.build_class_hierarchy(classes)++# Validate classes+validation = inferrer.validate_classes(classes)+if validation.get("valid"):+ print("Classes are valid")+```++### Class Inference Options++```python+from semantica.ontology import infer_classes++# Custom inference options+classes = infer_classes(+ entities,+ method="default",+ build_hierarchy=True,+ min_occurrences=3,+ similarity_threshold=0.85+)+```++## Property Inference++### Basic Property Inference++```python+from semantica.ontology import infer_properties, PropertyGenerator++entities = [+ {"type": "Person", "name": "John", "age": 30, "email": "[email protected]"},+ {"type": "Person", "name": "Jane", "age": 25, "email": "[email protected]"}+]++relationships = [+ {"type": "worksFor", "source": "John", "target": "Acme Corp"},+ {"type": "knows", "source": "John", "target": "Jane"}+]++classes = [+ {"name": "Person", "uri": "https://example.org/ontology/Person"},+ {"name": "Organization", "uri": "https://example.org/ontology/Organization"}+]++# Using convenience function+properties = infer_properties(entities, relationships, classes, method="default")++for prop in properties:+ print(f"Property: {prop['name']}, Type: {prop['type']}")++# Using class directly+prop_gen = PropertyGenerator()+properties = prop_gen.infer_properties(entities, relationships, classes)+```++### Object vs Data Properties++```python+from semantica.ontology import PropertyGenerator++prop_gen = PropertyGenerator()++# Infer all properties+properties = prop_gen.infer_properties(entities, relationships, classes)++# Separate object and data properties+object_props = [p for p in properties if p['type'] == 'object']+data_props = [p for p in properties if p['type'] == 'data']++print(f"Object properties: {len(object_props)}")+print(f"Data properties: {len(data_props)}")++# Validate properties+validation = prop_gen.validate_properties(properties)+```++## Ontology Validation++### Basic Validation++```python+from semantica.ontology import validate_ontology, OntologyValidator++# Using convenience function+result = validate_ontology(ontology, method="default")++if result.valid:+ print("Ontology is valid")+if result.consistent:+ print("Ontology is consistent")+if result.errors:+ print(f"Errors: {len(result.errors)}")+if result.warnings:+ print(f"Warnings: {len(result.warnings)}")++# Using class directly+validator = OntologyValidator(reasoner="hermit")+result = validator.validate_ontology(ontology)+```++### Validation with Reasoners++```python+from semantica.ontology import validate_ontology++# HermiT reasoner+result = validate_ontology(ontology, method="hermit", reasoner="hermit")++# Pellet reasoner+result = validate_ontology(ontology, method="pellet", reasoner="pellet")++# Auto-select reasoner+result = validate_ontology(ontology, method="default", reasoner="auto")+```++### Validation Options++```python+from semantica.ontology import validate_ontology++# Custom validation options+result = validate_ontology(+ ontology,+ method="default",+ check_consistency=True,+ check_satisfiability=True+)+```++## OWL/RDF Generation++### Basic OWL Generation++```python+from semantica.ontology import generate_owl, OWLGenerator++# Using convenience function+turtle = generate_owl(ontology, format="turtle", method="default")+print(turtle)++# Using class directly+generator = OWLGenerator()+turtle = generator.generate_owl(ontology, format="turtle")+```++### Different Formats++```python+from semantica.ontology import generate_owl++# Turtle format+turtle = generate_owl(ontology, format="turtle", method="default")++# RDF/XML format+rdfxml = generate_owl(ontology, format="rdfxml", method="default")++# JSON-LD format+jsonld = generate_owl(ontology, format="json-ld", method="default")++# N3 format+n3 = generate_owl(ontology, format="n3", method="default")+```++### Export to File++```python+from semantica.ontology import OWLGenerator++generator = OWLGenerator()++# Export to file+generator.export_owl(ontology, "ontology.ttl", format="turtle")+generator.export_owl(ontology, "ontology.rdf", format="rdfxml")+generator.export_owl(ontology, "ontology.jsonld", format="json-ld")+```++## Ontology Evaluation++### Basic Evaluation++```python+from semantica.ontology import evaluate_ontology, OntologyEvaluator++competency_questions = [+ "Who are the employees of an organization?",+ "What organizations does a person work for?",+ "What is the age of a person?"+]++# Using convenience function+result = evaluate_ontology(+ ontology,+ competency_questions=competency_questions,+ method="default"+)++print(f"Coverage score: {result.coverage_score:.2f}")+print(f"Completeness score: {result.completeness_score:.2f}")+print(f"Gaps: {len(result.gaps)}")+print(f"Suggestions: {len(result.suggestions)}")++# Using class directly+evaluator = OntologyEvaluator()+result = evaluator.evaluate_ontology(ontology, competency_questions=competency_questions)+```++### Coverage and Completeness++```python+from semantica.ontology import OntologyEvaluator++evaluator = OntologyEvaluator()++# Evaluate coverage+coverage = evaluator.calculate_coverage(ontology, competency_questions)++# Evaluate completeness+completeness = evaluator.calculate_completeness(ontology)++# Identify gaps+gaps = evaluator.identify_gaps(ontology, competency_questions)++# Generate report+report = evaluator.generate_report(ontology)+```++## Requirements Specification++### Creating Requirements Spec++```python+from semantica.ontology import create_requirements_spec, RequirementsSpecManager++# Using convenience function+spec = create_requirements_spec(+ "PersonOntology",+ "Model person-related concepts and relationships",+ "Person, Organization, Role entities and their relationships",+ method="default",+ domain="human resources",+ stakeholders=["domain experts", "developers"],+ use_cases=["employee management", "organizational structure"]+)++# Using class directly+manager = RequirementsSpecManager()+spec = manager.create_spec(+ "PersonOntology",+ "Model person-related concepts",+ "Person entities"+)+```++### Adding Competency Questions++```python+from semantica.ontology import add_competency_question, CompetencyQuestionsManager++# Using convenience function+cq = add_competency_question(+ "PersonOntology",+ "Who are the employees of a given organization?",+ category="organizational",+ method="default",+ priority=1+)++# Using class directly+manager = CompetencyQuestionsManager()+cq = manager.add_question(+ "Who are the employees of a given organization?",+ category="organizational",+ priority=1+)+```++### Requirements Traceability++```python+from semantica.ontology import RequirementsSpecManager++manager = RequirementsSpecManager()++# Trace requirements to ontology+trace = manager.trace_requirements("PersonOntology", ontology)++# Validate against requirements+validation = manager.validate_against_spec("PersonOntology", ontology)+```++## Ontology Reuse++### Researching Ontologies++```python+from semantica.ontology import research_ontology, ReuseManager++# Using convenience function+info = research_ontology("http://xmlns.com/foaf/0.1/", method="default")++if info:+ print(f"Name: {info.get('name')}")+ print(f"Description: {info.get('description')}")++# Using class directly+manager = ReuseManager()+info = manager.research_ontology("http://xmlns.com/foaf/0.1/")+```++### Importing External Ontologies++```python+from semantica.ontology import import_external_ontology, ReuseManager++# Using convenience function+updated = import_external_ontology(+ "http://xmlns.com/foaf/0.1/",+ ontology,+ method="default"+)++# Using class directly+manager = ReuseManager()+updated = manager.import_external_ontology("http://xmlns.com/foaf/0.1/", ontology)+```++### Alignment Evaluation++```python+from semantica.ontology import ReuseManager++manager = ReuseManager()++# Evaluate alignment+alignment = manager.evaluate_alignment(+ "http://xmlns.com/foaf/0.1/",+ ontology+)++print(f"Compatibility score: {alignment.get('compatibility_score', 0):.2f}")+print(f"Decision: {alignment.get('decision')}")+```++## Version Management++### Creating Versions++```python+from semantica.ontology import create_version, VersionManager++# Using convenience function+version = create_version(+ "1.0",+ ontology,+ method="default",+ changes=["Added Person class", "Added worksFor property"]+)++print(f"Version: {version.version}")+print(f"IRI: {version.ontology_iri}")++# Using class directly+manager = VersionManager(base_uri="https://example.org/ontology/")+version = manager.create_version("1.0", ontology, changes=["Added Person class"])+```++### Version Comparison++```python+from semantica.ontology import VersionManager++manager = VersionManager()++# Compare versions+comparison = manager.compare_versions("1.0", "2.0")++# Get version diff+diff = manager.get_version_diff("1.0", "2.0")++# Migrate ontology+migrated = manager.migrate_ontology("1.0", "2.0", ontology)+```++## Namespace Management++### Managing Namespaces++```python+from semantica.ontology import manage_namespace, NamespaceManager++# Using convenience function+class_iri = manage_namespace(+ "generate_class_iri",+ class_name="Person",+ base_uri="https://example.org/ontology/"+)+print(f"Class IRI: {class_iri}")++property_iri = manage_namespace(+ "generate_property_iri",+ property_name="hasName",+ base_uri="https://example.org/ontology/"+)+print(f"Property IRI: {property_iri}")++# Using class directly+manager = NamespaceManager(base_uri="https://example.org/ontology/")+class_iri = manager.generate_class_iri("Person")+property_iri = manager.generate_property_iri("hasName")+```++### Registering Namespaces++```python+from semantica.ontology import NamespaceManager++manager = NamespaceManager()++# Register custom namespace+manager.register_namespace("ex", "https://example.org/")++# Get base URI+base_uri = manager.get_base_uri()++# Get all namespaces+namespaces = manager.get_all_namespaces()+```++## Associative Classes++### Creating Associative Classes++```python+from semantica.ontology import create_associative_class, AssociativeClassBuilder++# Using convenience function+position = create_associative_class(+ "Position",+ ["Person", "Organization", "Role"],+ method="default",+ properties={"startDate": "xsd:date", "endDate": "xsd:date"},+ temporal=True+)++print(f"Associative class: {position.name}")+print(f"Connects: {position.connects}")++# Using class directly+builder = AssociativeClassBuilder()+position = builder.create_associative_class(+ "Position",+ ["Person", "Organization", "Role"],+ properties={"startDate": "xsd:date"},+ temporal=True+)+```++### Position Classes++```python+from semantica.ontology import AssociativeClassBuilder++builder = AssociativeClassBuilder()++# Create position class+position = builder.create_position_class(+ person_class="Person",+ organization_class="Organization",+ role_class="Role"+)++# Validate associative class+validation = builder.validate_associative_class(position)+```++## Using Methods++### Getting Available Methods++```python+from semantica.ontology.methods import get_ontology_method, list_available_methods++# List all available methods+all_methods = list_available_methods()+print("Available methods:", all_methods)++# List methods for specific task+generate_methods = list_available_methods("generate")+print("Generation methods:", generate_methods)++# Get specific method+generate_method = get_ontology_method("generate", "default")+if generate_method:+ ontology = generate_method(data)+```++### Method Examples++```python+from semantica.ontology.methods import (+ generate_ontology,+ infer_classes,+ infer_properties,+ validate_ontology,+ generate_owl,+ evaluate_ontology,+ create_requirements_spec,+ add_competency_question,+ research_ontology,+ import_external_ontology,+ create_version,+ manage_namespace,+ create_associative_class+)++# Generate ontology+ontology = generate_ontology(data, method="default")++# Infer classes+classes = infer_classes(entities, method="default")++# Infer properties+properties = infer_properties(entities, relationships, classes, method="default")++# Validate ontology+result = validate_ontology(ontology, method="default")++# Generate OWL+turtle = generate_owl(ontology, format="turtle", method="default")++# Evaluate ontology+evaluation = evaluate_ontology(ontology, competency_questions=["Who are the employees?"], method="default")++# Create requirements spec+spec = create_requirements_spec("PersonOntology", "Purpose", "Scope", method="default")++# Add competency question+cq = add_competency_question("PersonOntology", "Who are the employees?", method="default")++# Research ontology+info = research_ontology("http://xmlns.com/foaf/0.1/", method="default")++# Import external ontology+updated = import_external_ontology("http://xmlns.com/foaf/0.1/", ontology, method="default")++# Create version+version = create_version("1.0", ontology, method="default")++# Manage namespace+class_iri = manage_namespace("generate_class_iri", class_name="Person", method="default")++# Create associative class+position = create_associative_class("Position", ["Person", "Organization"], method="default")+```++## Using Registry++### Registering Custom Methods++```python+from semantica.ontology.registry import method_registry++# Custom ontology generation method+def custom_ontology_generation(data, **kwargs):+ """Custom generation logic."""+ # Your custom generation code+ return {"uri": "custom", "name": "CustomOntology", "classes": [], "properties": []}++# Register custom method+method_registry.register("generate", "custom", custom_ontology_generation)++# Use custom method+from semantica.ontology.methods import get_ontology_method+custom_method = get_ontology_method("generate", "custom")+ontology = custom_method(data)+```++### Listing Registered Methods++```python+from semantica.ontology.registry import method_registry++# List all registered methods+all_methods = method_registry.list_all()+print("Registered methods:", all_methods)++# List methods for specific task+generate_methods = method_registry.list_all("generate")+print("Generation methods:", generate_methods)++validate_methods = method_registry.list_all("validate")+print("Validation methods:", validate_methods)+```++### Unregistering Methods++```python+from semantica.ontology.registry import method_registry++# Unregister a method+method_registry.unregister("generate", "custom")++# Clear all methods for a task+method_registry.clear("generate")++# Clear all methods+method_registry.clear()+```++## Configuration++### Using Configuration Manager++```python+from semantica.ontology.config import ontology_config++# Get configuration values+base_uri = ontology_config.get("base_uri", default="https://semantica.dev/ontology/")+reasoner = ontology_config.get("reasoner", default="auto")+format = ontology_config.get("format", default="turtle")+min_occurrences = ontology_config.get("min_occurrences", default=2)++# Set configuration values+ontology_config.set("base_uri", "https://example.org/ontology/")+ontology_config.set("reasoner", "hermit")++# Method-specific configuration+ontology_config.set_method_config("generate", base_uri="https://example.org/ontology/", min_occurrences=3)+generate_config = ontology_config.get_method_config("generate")++# Get all configuration+all_config = ontology_config.get_all()+print("All config:", all_config)+```++### Environment Variables++```bash+# Set environment variables+export ONTOLOGY_BASE_URI=https://example.org/ontology/+export ONTOLOGY_REASONER=hermit+export ONTOLOGY_FORMAT=turtle+export ONTOLOGY_MIN_OCCURRENCES=3+export ONTOLOGY_SIMILARITY_THRESHOLD=0.85+export ONTOLOGY_CHECK_CONSISTENCY=true+export ONTOLOGY_CHECK_SATISFIABILITY=true+```++### Configuration File++```yaml+# config.yaml+ontology:+ base_uri: https://example.org/ontology/+ reasoner: hermit+ format: turtle+ min_occurrences: 3+ similarity_threshold: 0.85+ check_consistency: true+ check_satisfiability: true++ontology_methods:+ generate:+ base_uri: https://example.org/ontology/+ min_occurrences: 3+ validate:+ reasoner: hermit+ check_consistency: true+ owl:+ format: turtle+```++```python+from semantica.ontology.config import OntologyConfig++# Load from config file+config = OntologyConfig(config_file="config.yaml")+base_uri = config.get("base_uri")+```++## Advanced Examples++### Complete Ontology Generation Pipeline++```python+from semantica.ontology import (+ generate_ontology,+ infer_classes,+ infer_properties,+ validate_ontology,+ generate_owl,+ evaluate_ontology+)++# Step 1: Generate ontology+data = {+ "entities": [+ {"type": "Person", "name": "John", "age": 30},+ {"type": "Person", "name": "Jane", "age": 25},+ {"type": "Organization", "name": "Acme Corp"}+ ],+ "relationships": [+ {"type": "worksFor", "source": "John", "target": "Acme Corp"}+ ]+}++ontology = generate_ontology(data, method="default", name="PersonOrgOntology")++# Step 2: Validate ontology+result = validate_ontology(ontology, method="default")+if not result.valid:+ print(f"Validation errors: {result.errors}")++# Step 3: Generate OWL+turtle = generate_owl(ontology, format="turtle", method="default")++# Step 4: Evaluate ontology+competency_questions = ["Who are the employees of an organization?"]+evaluation = evaluate_ontology(ontology, competency_questions=competency_questions, method="default")++print(f"Coverage: {evaluation.coverage_score:.2f}")+print(f"Completeness: {evaluation.completeness_score:.2f}")+```++### Custom Ontology Workflow++```python+from semantica.ontology import (+ OntologyGenerator,+ ClassInferrer,+ PropertyGenerator,+ OntologyValidator,+ OWLGenerator+)++# Create generators with custom config+generator = OntologyGenerator(+ base_uri="https://example.org/ontology/",+ min_occurrences=3+)++inferrer = ClassInferrer(min_occurrences=3, similarity_threshold=0.85)+prop_gen = PropertyGenerator()+validator = OntologyValidator(reasoner="hermit")+owl_gen = OWLGenerator()++# Generate ontology+ontology = generator.generate_ontology(data, name="CustomOntology")++# Infer classes+classes = inferrer.infer_classes(entities, build_hierarchy=True)++# Infer properties+properties = prop_gen.infer_properties(entities, relationships, classes)++# Validate+result = validator.validate_ontology(ontology)++# Generate OWL+turtle = owl_gen.generate_owl(ontology, format="turtle")+```++### Requirements-Driven Development++```python+from semantica.ontology import (+ create_requirements_spec,+ add_competency_question,+ generate_ontology,+ evaluate_ontology+)++# Step 1: Create requirements specification+spec = create_requirements_spec(+ "PersonOntology",+ "Model person-related concepts",+ "Person, Organization, Role entities",+ method="default"+)++# Step 2: Add competency questions+add_competency_question("PersonOntology", "Who are the employees?", category="organizational", method="default")+add_competency_question("PersonOntology", "What organizations does a person work for?", category="organizational", method="default")++# Step 3: Generate ontology+ontology = generate_ontology(data, method="default")++# Step 4: Evaluate against requirements+competency_questions = ["Who are the employees?", "What organizations does a person work for?"]+evaluation = evaluate_ontology(ontology, competency_questions=competency_questions, method="default")++# Step 5: Refine based on gaps+if evaluation.gaps:+ print(f"Gaps identified: {evaluation.gaps}")+ print(f"Suggestions: {evaluation.suggestions}")+```++### Version Management Workflow++```python+from semantica.ontology import (+ generate_ontology,+ create_version,+ VersionManager+)++# Generate initial ontology+ontology_v1 = generate_ontology(data, method="default", name="PersonOntology")++# Create version 1.0+version1 = create_version("1.0", ontology_v1, changes=["Initial version"], method="default")++# Modify ontology (add new class)+ontology_v2 = ontology_v1.copy()+ontology_v2["classes"].append({"name": "Role", "uri": "https://example.org/ontology/Role"})++# Create version 2.0+version2 = create_version("2.0", ontology_v2, changes=["Added Role class"], method="default")++# Compare versions+manager = VersionManager()+comparison = manager.compare_versions("1.0", "2.0")+print(f"Changes: {comparison.get('changes', [])}")+```++### Integration with Knowledge Graph++```python+from semantica.ontology import generate_ontology, generate_owl+from semantica.kg import build++# Build knowledge graph+kg = build(sources=[{"entities": entities, "relationships": relationships}])++# Generate ontology from KG+ontology = generate_ontology({+ "entities": kg.get("entities", []),+ "relationships": kg.get("relationships", [])+}, method="default")++# Generate OWL+turtle = generate_owl(ontology, format="turtle", method="default")++# Export for use in KG+with open("ontology.ttl", "w") as f:+ f.write(turtle)+```++## Best Practices++1. **Ontology Generation**: Always validate generated ontologies before use+2. **Class Inference**: Use appropriate minimum occurrence thresholds to avoid noise+3. **Property Inference**: Validate domain/range constraints for properties+4. **Validation**: Use symbolic reasoners (HermiT/Pellet) for consistency checking+5. **OWL Generation**: Prefer Turtle format for readability, RDF/XML for compatibility+6. **Evaluation**: Define competency questions early in the development process+7. **Requirements**: Trace requirements to ontology elements for maintainability+8. **Reuse**: Research existing ontologies before creating new ones+9. **Versioning**: Use version-aware IRIs following best practices+10. **Namespaces**: Use stable, resolvable URIs for namespaces+11. **Associative Classes**: Use for complex relationships with properties+12. **Configuration**: Use configuration files for consistent settings across environments+13. **Error Handling**: Always handle ValidationError and ProcessingError exceptions+14. **Method Registry**: Register custom methods for domain-specific ontology needs+diff --git a/semantica/ontology/registry.py b/semantica/ontology/registry.pynew file mode 100644index 00000000..af5830d0--- /dev/null+++ b/semantica/ontology/registry.py@@ -0,0 +1,138 @@+"""+Method Registry Module for Ontology++This module provides a method registry system for registering custom ontology methods,+enabling extensibility and community contributions to the ontology toolkit.++Supported Registration Types:+ - Method Registry: Register custom ontology methods for:+ * "generate": Ontology generation methods+ * "infer": Class/property inference methods+ * "validate": Validation methods+ * "evaluate": Evaluation methods+ * "owl": OWL/RDF generation methods+ * "requirements": Requirements specification methods+ * "reuse": Ontology reuse methods+ * "version": Version management methods+ * "namespace": Namespace management methods+ * "associative": Associative class creation methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom ontology methods+ - Task-based method organization (generate, infer, validate, evaluate, owl, requirements, reuse, version, namespace, associative)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom ontology methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.ontology.registry import method_registry+ >>> method_registry.register("generate", "custom_method", custom_ontology_generation_function)+ >>> available = method_registry.list_all("generate")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom ontology methods."""++ _methods: Dict[str, Dict[str, Callable]] = {+ "generate": {},+ "infer": {},+ "validate": {},+ "evaluate": {},+ "owl": {},+ "requirements": {},+ "reuse": {},+ "version": {},+ "namespace": {},+ "associative": {},+ }++ @classmethod+ def register(cls, task: str, name: str, method_func: Callable):+ """+ Register a custom ontology method.++ Args:+ task: Task type ("generate", "infer", "validate", "evaluate", "owl", "requirements", "reuse", "version", "namespace", "associative")+ name: Method name+ method_func: Method function+ """+ if task not in cls._methods:+ cls._methods[task] = {}+ cls._methods[task][name] = method_func++ @classmethod+ def get(cls, task: str, name: str) -> Optional[Callable]:+ """+ Get method by task and name.++ Args:+ task: Task type ("generate", "infer", "validate", "evaluate", "owl", "requirements", "reuse", "version", "namespace", "associative")+ name: Method name++ Returns:+ Method function or None+ """+ return cls._methods.get(task, {}).get(name)++ @classmethod+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names+ """+ if task:+ return {task: list(cls._methods.get(task, {}).keys())}+ return {t: list(m.keys()) for t, m in cls._methods.items()}++ @classmethod+ def unregister(cls, task: str, name: str):+ """+ Unregister a method.++ Args:+ task: Task type ("generate", "infer", "validate", "evaluate", "owl", "requirements", "reuse", "version", "namespace", "associative")+ name: Method name+ """+ if task in cls._methods and name in cls._methods[task]:+ del cls._methods[task][name]++ @classmethod+ def clear(cls, task: Optional[str] = None):+ """+ Clear all registered methods for a task or all tasks.++ Args:+ task: Optional task type to clear (clears all if None)+ """+ if task:+ if task in cls._methods:+ cls._methods[task].clear()+ else:+ for task_dict in cls._methods.values():+ task_dict.clear()+++# Global registry+method_registry = MethodRegistry()+