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
cookbook/ontology: add worked example for object vs data properties; align worksFor to Schema.org; add optional hierarchy visualization; plus commit pending changes across notebooks, docs, and ontology modules
Semantica Bot7878b4a222fb
diff --git a/cookbook/introduction/14_Ontology.ipynb b/cookbook/introduction/14_Ontology.ipynbindex b4198b59..663d5f91 100644--- a/cookbook/introduction/14_Ontology.ipynb+++ b/cookbook/introduction/14_Ontology.ipynb@@ -4,19 +4,19 @@"cell_type": "markdown","metadata": {},"source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/15_Ontology.ipynb)\n",+ "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/14_Ontology.ipynb)\n","\n","# Ontology\n","\n","## Overview\n","\n",- "This notebook demonstrates how to generate and validate ontologies using Semantica's ontology modules. You'll learn to use `OntologyGenerator`, `ClassInferrer`, `PropertyGenerator`, and `OntologyValidator`.\n",+ "This notebook demonstrates how to generate and validate ontologies using Semantica's ontology modules. You'll learn to use `OntologyEngine`, `ClassInferrer`, `PropertyGenerator`, and `OntologyValidator`.\n","\n","**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/ontology/)\n","\n","### Learning Objectives\n","\n",- "- Use `OntologyGenerator` to generate ontologies\n",+ "- Use `OntologyEngine` to generate ontologies\n","- Use `ClassInferrer` to infer classes\n","- Use `PropertyGenerator` to generate properties\n","- Use `OntologyValidator` to validate ontologies\n",@@ -35,7 +35,73 @@"\n","## Step 1: Generate Ontology\n","\n",- "Generate ontology from entities and relationships.\n"+ "Generate ontology from entities and relationships.\n",+ "\n",+ "### Module Map\n",+ "\n",+ "- `OntologyEngine`: Unified API for generation, validation, evaluation, and OWL export\n",+ "- `OntologyGenerator`: 6-stage pipeline to build classes and properties\n",+ "- `ClassInferrer`: Derive class candidates and hierarchies from entities\n",+ "- `PropertyGenerator`: Infer object/data properties from relationships\n",+ "- `OntologyValidator`: Structural and symbolic validation (reasoners optional)\n",+ "- `NamespaceManager`: Consistent IRIs (PascalCase classes, camelCase properties)\n",+ "- `OWLGenerator`/`OWLExporter`: OWL serialization and file export\n",+ "- `RequirementsSpecManager`/`CompetencyQuestionsManager`: requirements & questions\n",+ "- `LLMGenerator`: text-to-ontology generation\n",+ "- `ReuseManager`/`DomainOntologies`: reuse known vocabularies, domain templates\n",+ "- `NamingConventions`: enforce naming guidelines\n",+ "\n",+ "### Engine Options\n",+ "\n",+ "- `base_uri`: namespace root (e.g., `http://example.org/onto#`)\n",+ "- `name`: ontology name (default: `GeneratedOntology`)\n",+ "- `version`: version string (default: `1.0`)\n",+ "\n",+ "### Detailed Guide\n",+ "\n",+ "#### Core Classes & Methods\n",+ "\n",+ "- `OntologyEngine`: `from_data(data, **options)`, `from_text(text, provider=None, model=None, **options)`, `infer_classes(entities)`, `validate(ontology)`, `evaluate(ontology)`, `to_owl(ontology, format)`, `export_owl(ontology, path, format)`\n",+ "- `OntologyGenerator`: `generate_ontology(data, **options)`, `optimize_ontology(ontology, **options)`, `remove_redundancy(ontology)`, `improve_coherence(ontology)`\n",+ "- `ClassInferrer`: `infer_classes(entities)`, `build_class_hierarchy(classes)`, `validate_classes(classes)`\n",+ "- `PropertyGenerator`: `infer_properties(entities, relationships, classes)`\n",+ "- `OntologyValidator`: `validate_ontology(ontology)` (returns `valid`, `consistent`, `errors`, `warnings`, `metrics`)\n",+ "- `NamespaceManager`: `generate_class_iri(name)`, `generate_property_iri(name)`, `register_namespace(prefix, uri)`, `get_all_namespaces()`\n",+ "\n",+ "#### Extended Modules\n",+ "\n",+ "- `OWLGenerator` vs `OWLExporter`: in-memory OWL generation vs file export\n",+ "- `RequirementsSpecManager` & `CompetencyQuestionsManager`: plan and validate coverage\n",+ "- `LLMGenerator`: bootstrap ontology from text with a provider/model\n",+ "- `ReuseManager` & `DomainOntologies`: reuse known vocabularies and templates\n",+ "- `NamingConventions`: enforce consistent, readable names\n",+ "\n",+ "#### Building Ontologies Step-by-Step\n",+ "\n",+ "1) Prepare `entities` and `relationships`\n",+ "2) Generate ontology with engine\n",+ "3) Infer classes\n",+ "4) Infer properties\n",+ "5) Validate\n",+ "6) Export OWL\n",+ "\n",+ "#### Property Types\n",+ "\n",+ "- Object properties: connect classes (domain → range)\n",+ "- Data properties: attach literals (strings, numbers, dates)\n",+ "\n",+ "#### Validator Output\n",+ "\n",+ "- `valid`, `consistent`, `errors`, `warnings`\n",+ "\n",+ "#### OWL Export Formats\n",+ "\n",+ "- `turtle`, `owl-xml`\n",+ "\n",+ "#### Namespace Management\n",+ "\n",+ "- Use stable `base_uri` and versioned IRIs\n",+ "- PascalCase for classes; camelCase for properties\n"]},{@@ -44,9 +110,9 @@"metadata": {},"outputs": [],"source": [- "from semantica.ontology import OntologyGenerator\n",+ "from semantica.ontology import OntologyEngine\n","\n",- "generator = OntologyGenerator()\n",+ "engine = OntologyEngine()\n","\n","entities = [\n"," {\"id\": \"e1\", \"type\": \"Organization\", \"name\": \"Apple Inc.\"},\n",@@ -57,7 +123,10 @@" {\"source\": \"e2\", \"target\": \"e1\", \"type\": \"CEO_of\"}\n","]\n","\n",- "ontology = generator.generate(entities, relationships)\n",+ "ontology = engine.from_data({\n",+ " \"entities\": entities,\n",+ " \"relationships\": relationships\n",+ "})\n","\n","print(f\"Generated ontology\")\n","print(f\"Classes: {len(ontology.get('classes', []))}\")\n",@@ -150,14 +219,126 @@"\n","You've learned how to work with ontologies:\n","\n",- "- **OntologyGenerator**: Generate ontologies from entities and relationships\n",+ "- **OntologyEngine**: Generate ontologies from entities and relationships\n","- **ClassInferrer**: Infer classes from entities\n","- **PropertyGenerator**: Generate properties from relationships\n","- **OntologyValidator**: Validate ontologies\n","\n",+ "### Validate & Evaluate\n",+ "\n",+ "```python\n",+ "result = engine.validate(ontology)\n",+ "print(\"Valid:\", result.valid, \"Consistent:\", result.consistent)\n",+ "print(\"Errors:\", len(result.errors), \"Warnings:\", len(result.warnings))\n",+ "# Optional: evaluate coverage/metrics if available\n",+ "metrics = engine.evaluate(ontology)\n",+ "print(\"Evaluation metrics keys:\", list(metrics.keys()) if isinstance(metrics, dict) else metrics)\n",+ "```\n",+ "\n",+ "### Inspect Classes & Properties\n",+ "\n",+ "```python\n",+ "for cls in ontology.get(\"classes\", [])[:5]:\n",+ " print(\"Class:\", cls.get(\"name\"), \"label:\", cls.get(\"label\"))\n",+ "for prop in ontology.get(\"properties\", [])[:5]:\n",+ " print(\"Property:\", prop.get(\"name\"), \"type:\", prop.get(\"type\"), \"domain:\", prop.get(\"domain\"), \"range:\", prop.get(\"range\"))\n",+ "```\n",+ "\n",+ "### Modeling Checklist\n",+ "\n",+ "- Define scope and competency questions\n",+ "- Choose stable base URI and naming conventions\n",+ "- Map entities → classes, relationships → object properties, attributes → data properties\n",+ "- Add domain/range and only essential constraints\n",+ "- Validate; export OWL; iterate with visualization\n",+ "\n","Next: Learn how to export data in the Export notebook.\n"]}+ ,+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Worked Example: Object vs Data Properties\n",+ "\n",+ "Differentiate object properties (link classes) from data properties (literal values)."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.ontology import ClassInferrer, PropertyGenerator\n",+ "\n",+ "richer_entities = [\n",+ " {\"id\": \"p1\", \"type\": \"Person\", \"name\": \"Alice\", \"birthDate\": \"1990-01-01\"},\n",+ " {\"id\": \"c1\", \"type\": \"Company\", \"name\": \"Acme Corp\", \"foundedYear\": 2005}\n",+ "]\n",+ "\n",+ "richer_relationships = [\n",+ " {\"source_id\": \"p1\", \"target_id\": \"c1\", \"source_type\": \"Person\", \"target_type\": \"Company\", \"type\": \"WORKS_FOR\"}\n",+ "]\n",+ "\n",+ "inferrer = ClassInferrer()\n",+ "classes2 = inferrer.infer_classes(richer_entities)\n",+ "\n",+ "propgen = PropertyGenerator()\n",+ "props2 = propgen.infer_properties(richer_entities, richer_relationships, classes2)\n",+ "\n",+ "obj_props = [p for p in props2 if p.get(\"type\") == \"object\"]\n",+ "data_props = [p for p in props2 if p.get(\"type\") == \"data\"]\n",+ "\n",+ "print(\"Object properties:\", [p.get(\"name\") for p in obj_props])\n",+ "print(\"Data properties:\", [p.get(\"name\") for p in data_props])\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Vocabulary Reuse: Align to Schema.org\n",+ "\n",+ "Align a property to a known vocabulary term for interoperability."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "schema_works_for = \"https://schema.org/worksFor\"\n",+ "for p in obj_props:\n",+ " if p.get(\"name\") == \"worksFor\":\n",+ " p[\"sameAs\"] = schema_works_for\n",+ " print(\"Aligned\", p.get(\"name\"), \"to\", p[\"sameAs\"])\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "### Visualization (Optional)\n",+ "\n",+ "Render the class hierarchy if visualization dependencies are available."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from semantica.visualization import OntologyVisualizer\n",+ "\n",+ "viz = OntologyVisualizer()\n",+ "fig = viz.visualize_hierarchy(ontology, output=\"interactive\")\n",+ "print(\"Visualization generated\")\n"+ ]+ }],"metadata": {"language_info": {diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynbindex fac52c43..3ac53e7a 100644--- a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb+++ b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb@@ -659,8 +659,11 @@"\n","# Generate drug discovery ontology\n","drug_ontology = ontology_generator.generate_ontology(\n",- " knowledge_graph=knowledge_graph,\n",- " domain=\"DrugDiscovery\"\n",+ " {\"entities\": compound_entities + target_entities + interaction_entities, \n",+ " \"relationships\": relationships},\n",+ " name=\"DrugDiscoveryOntology\",\n",+ " entities=compound_entities + target_entities + interaction_entities,\n",+ " relationships=relationships\n",")\n","\n","# Validate ontology\n",@@ -708,7 +711,7 @@"with open(report_path, 'w') as f:\n"," f.write(report_content)\n","\n",- "print(f\"Generated drug discovery ontology with {len(drug_ontology.classes)} classes\")\n",+ "print(f\"Generated drug discovery ontology with {len(drug_ontology.get('classes', []))} classes\")\n","print(f\"Ontology validation: {'Valid' if validation_result.valid else 'Invalid'}\")\n","print(f\" Errors: {len(validation_result.errors)}\")\n","print(f\" Warnings: {len(validation_result.warnings)}\")\n",diff --git a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynbindex aaa6a3bb..30a0ffea 100644--- a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb+++ b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb@@ -594,19 +594,22 @@"\n","# Generate genomic ontology\n","genomic_ontology = ontology_generator.generate_ontology(\n",- " knowledge_graph=knowledge_graph,\n",- " domain=\"Genomics\"\n",+ " {\"entities\": variant_entities + gene_entities + disease_entities + pathway_entities, \n",+ " \"relationships\": relationships},\n",+ " name=\"GenomicsOntology\",\n",+ " entities=variant_entities + gene_entities + disease_entities + pathway_entities,\n",+ " relationships=relationships\n",")\n","\n",- "# Infer classes\n",- "classes = class_inferrer.infer_classes(knowledge_graph)\n",- "for cls in classes:\n",- " genomic_ontology.add_class(cls)\n",+ "# Infer classes/properties (for inspection)\n",+ "classes = class_inferrer.infer_classes(variant_entities + gene_entities + disease_entities + pathway_entities)\n",+ "properties = property_generator.infer_properties(variant_entities + gene_entities + disease_entities + pathway_entities, relationships, classes)\n","\n",- "# Generate properties\n",- "properties = property_generator.generate_properties(knowledge_graph)\n",- "for prop in properties:\n",- " genomic_ontology.add_property(prop)\n",+ "# Ensure ontology dict has classes/properties\n",+ "if not genomic_ontology.get(\"classes\"):\n",+ " genomic_ontology[\"classes\"] = classes\n",+ "if not genomic_ontology.get(\"properties\"):\n",+ " genomic_ontology[\"properties\"] = properties\n","\n","# Validate ontology\n","validation_result = ontology_validator.validate_ontology(genomic_ontology)\n",@@ -631,7 +634,7 @@" \"diseases\": len([r for r in relationships if r[\"source\"] in [e[\"id\"] for e in variant_entities] and r[\"type\"] == \"associated_with\"])\n"," }\n","\n",- "print(f\"Generated genomic ontology with {len(genomic_ontology.classes)} classes\")\n",+ "print(f\"Generated genomic ontology with {len(genomic_ontology.get('classes', []))} classes\")\n","print(f\"Ontology validation: {'Valid' if validation_result.valid else 'Invalid'}\")\n","print(f\" Errors: {len(validation_result.errors)}\")\n","print(f\" Warnings: {len(validation_result.warnings)}\")\n",diff --git a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynbindex 5f34e263..a2c39750 100644--- a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb+++ b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb@@ -516,19 +516,22 @@"\n","# Generate DeFi ontology\n","defi_ontology = ontology_generator.generate_ontology(\n",- " knowledge_graph=knowledge_graph,\n",- " domain=\"DeFi\"\n",+ " {\"entities\": protocol_entities + pool_entities + token_entities, \n",+ " \"relationships\": relationships},\n",+ " name=\"DeFiOntology\",\n",+ " entities=protocol_entities + pool_entities + token_entities,\n",+ " relationships=relationships\n",")\n","\n",- "# Infer classes\n",- "classes = class_inferrer.infer_classes(knowledge_graph)\n",- "for cls in classes:\n",- " defi_ontology.add_class(cls)\n",+ "# Infer classes/properties (for inspection)\n",+ "classes = class_inferrer.infer_classes(protocol_entities + pool_entities + token_entities)\n",+ "properties = property_generator.infer_properties(protocol_entities + pool_entities + token_entities, relationships, classes)\n","\n",- "# Generate properties\n",- "properties = property_generator.generate_properties(knowledge_graph)\n",- "for prop in properties:\n",- " defi_ontology.add_property(prop)\n",+ "# Ensure ontology dict has classes/properties\n",+ "if not defi_ontology.get(\"classes\"):\n",+ " defi_ontology[\"classes\"] = classes\n",+ "if not defi_ontology.get(\"properties\"):\n",+ " defi_ontology[\"properties\"] = properties\n","\n","# Validate ontology\n","validation_result = ontology_validator.validate_ontology(defi_ontology)\n",@@ -559,7 +562,7 @@" \"suggestions\": optimization_suggestions\n"," })\n","\n",- "print(f\"Generated DeFi ontology with {len(defi_ontology.classes)} classes\")\n",+ "print(f\"Generated DeFi ontology with {len(defi_ontology.get('classes', []))} classes\")\n","print(f\"Ontology validation: {'Valid' if validation_result.valid else 'Invalid'}\")\n","print(f\" Errors: {len(validation_result.errors)}\")\n","print(f\" Warnings: {len(validation_result.warnings)}\")\n",diff --git a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb b/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynbindex adc2b90b..bf5e975e 100644--- a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb+++ b/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb@@ -237,14 +237,14 @@"property_generator = PropertyGenerator()\n","ontology_validator = OntologyValidator()\n","\n",- "compliance_kg = builder.build(compliance_entities, compliance_relationships)\n",- "\n",- "compliance_ontology = ontology_generator.generate(compliance_entities, compliance_relationships)\n",- "\n",- "classes = class_inferrer.infer_classes(compliance_entities)\n",- "properties = property_generator.infer_properties(compliance_entities, compliance_relationships, classes)\n",- "\n",- "validation_result = ontology_validator.validate_ontology(compliance_ontology)\n",+ "compliance_kg = builder.build(compliance_entities, compliance_relationships)\n",+ "\n",+ "compliance_ontology = ontology_generator.generate_ontology({\"entities\": compliance_entities, \"relationships\": compliance_relationships}, entities=compliance_entities, relationships=compliance_relationships)\n",+ "\n",+ "classes = class_inferrer.infer_classes(compliance_entities)\n",+ "properties = property_generator.infer_properties(compliance_entities, compliance_relationships, classes)\n",+ "\n",+ "validation_result = ontology_validator.validate_ontology(compliance_ontology)\n","\n","print(f\"Built compliance knowledge graph\")\n","print(f\" Entities: {len(compliance_kg.get('entities', []))}\")\n",diff --git a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynbindex d415c6ad..969485a7 100644--- a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb+++ b/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb@@ -69,7 +69,6 @@"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n","from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n","from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-"from semantica.conflicts import ConflictDetector\n","from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n","from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",@@ -262,7 +261,10 @@"\n","disease_kg = builder.build(disease_entities, disease_relationships)\n","\n",- "disease_ontology = ontology_generator.generate(disease_entities, disease_relationships)\n",+ "disease_ontology = ontology_generator.generate_ontology({\n",+ " \"entities\": disease_entities,\n",+ " \"relationships\": disease_relationships\n",+ "})\n","\n","classes = class_inferrer.infer_classes(disease_entities)\n","properties = property_generator.infer_properties(disease_entities, disease_relationships, classes)\n",diff --git a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynbindex 30fb05ce..7aaa1a4b 100644--- a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb+++ b/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb@@ -362,7 +362,10 @@"property_generator = PropertyGenerator()\n","ontology_validator = OntologyValidator()\n","\n",- "drug_ontology = ontology_generator.generate(drug_entities, drug_relationships)\n",+ "drug_ontology = ontology_generator.generate_ontology({\n",+ " \"entities\": drug_entities,\n",+ " \"relationships\": drug_relationships\n",+ "}, entities=drug_entities, relationships=drug_relationships)\n","\n","classes = class_inferrer.infer_classes(drug_entities)\n","properties = property_generator.infer_properties(drug_entities, drug_relationships, classes)\n",diff --git a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynbindex 03695a46..692f70ab 100644--- a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb+++ b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb@@ -334,23 +334,22 @@"metadata": {},"outputs": [],"source": [- "# Initialize Semantica ontology generators\n",- "ontology_generator = OntologyGenerator()\n",- "owl_generator = OWLGenerator()\n",- "\n",- "# Generate ontology from knowledge graph using Semantica\n",- "ontology_result = ontology_generator.generate(\n",- " semantic_network=materialized_kg,\n",- " domain=\"Healthcare\",\n",- " namespace=\"http://semantica.example.org/healthcare#\"\n",- ")\n",+ "# Initialize Semantica ontology engine\n",+ "from semantica.ontology import OntologyEngine\n",+ "engine = OntologyEngine(base_uri=\"http://semantica.example.org/healthcare#\")\n",+ "\n",+ "# Generate ontology from knowledge graph entities/relationships\n",+ "ontology_result = engine.from_data({\n",+ " \"entities\": medical_entities,\n",+ " \"relationships\": medical_relationships\n",+ "}, name=\"HealthcareOntology\", entities=medical_entities, relationships=medical_relationships)\n","\n","# Generate OWL representation using Semantica\n",- "owl_ontology = owl_generator.generate(ontology_result)\n",+ "owl_ontology = engine.to_owl(ontology_result, format=\"turtle\")\n","\n","print(f\" - Classes: {len(ontology_result.get('classes', []))}\")\n","print(f\" - Properties: {len(ontology_result.get('properties', []))}\")\n",- "print(f\" - OWL generated: {len(owl_ontology) if owl_ontology else 0} characters\")\n"+ "print(f\" - OWL generated: {len(owl_ontology) if owl_ontology else 0} characters\")\n",]},{diff --git a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb b/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynbindex 39e21e92..6a96dd30 100644--- a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb+++ b/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb@@ -241,7 +241,10 @@"property_generator = PropertyGenerator()\n","ontology_validator = OntologyValidator()\n","\n",- "ontology = ontology_generator.generate(resolved_entities, relationships)\n",+ "ontology = ontology_generator.generate_ontology({\n",+ " \"entities\": resolved_entities,\n",+ " \"relationships\": relationships\n",+ "}, entities=resolved_entities, relationships=relationships)\n","\n","classes = class_inferrer.infer_classes(resolved_entities)\n","properties = property_generator.infer_properties(resolved_entities, relationships, classes)\n",diff --git a/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb b/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynbindex 1875d954..1e4c189a 100644--- a/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb+++ b/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb@@ -69,7 +69,6 @@"from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n","from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n","from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-"from semantica.conflicts import ConflictDetector\n","from semantica.export import JSONExporter, CSVExporter, RDFExporter, OWLExporter, ReportGenerator\n","from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",@@ -409,7 +408,10 @@"impact_insights = inference_engine.forward_chain()\n","\n","# Generate environmental ontology\n",- "impact_ontology = ontology_generator.generate(environmental_entities, environmental_relationships)\n",+ "impact_ontology = ontology_generator.generate_ontology({\n",+ " \"entities\": environmental_entities,\n",+ " \"relationships\": environmental_relationships\n",+ "})\n","classes = class_inferrer.infer_classes(environmental_entities)\n","properties = property_generator.infer_properties(environmental_entities, environmental_relationships, classes)\n","validation_result = ontology_validator.validate_ontology(impact_ontology)\n",diff --git a/docs/reference/ontology.md b/docs/reference/ontology.mdindex 0b8d25bf..d0b5aa25 100644--- a/docs/reference/ontology.md+++ b/docs/reference/ontology.md@@ -78,6 +78,66 @@## Main Classes+### OntologyEngine++Unified orchestration for generation, inference, validation, OWL export, and evaluation.++**Methods:**++| Method | Description |+|--------|-------------|+| `from_data(data, **options)` | Generate ontology from structured data |+| `from_text(text, provider=None, model=None, **options)` | LLM-based generation from text |+| `infer_classes(entities, **options)` | Infer classes from entities |+| `infer_properties(entities, relationships, classes, **options)` | Infer properties |+| `validate(ontology, **options)` | Validate ontology (returns `ValidationResult`) |+| `evaluate(ontology, **options)` | Evaluate ontology quality |+| `to_owl(ontology, format="turtle")` | Export OWL/RDF serialization |+| `export_owl(ontology, path, format="turtle")` | Save OWL to file |++**Quick Start:**++```python+from semantica.ontology import OntologyEngine++engine = OntologyEngine(base_uri="https://example.org/ontology/")++data = {"entities": entities, "relationships": relationships}+ontology = engine.from_data(data, name="MyOntology")++result = engine.validate(ontology, reasoner="auto")+turtle = engine.to_owl(ontology, format="turtle")+```++### LLMOntologyGenerator++LLM-based ontology generation with multi-provider support (`openai`, `groq`, `deepseek`, `huggingface_llm`).++**Example:**++```python+from semantica.ontology import OntologyEngine++text = "Acme Corp. hired Alice in 2024. Alice works for Acme."+engine = OntologyEngine()++ontology = engine.from_text(+ text,+ provider="deepseek",+ model="deepseek-chat",+ name="EmploymentOntology",+ base_uri="https://example.org/employment/",+)+```++Environment variables:++```bash+export OPENAI_API_KEY=...+export GROQ_API_KEY=...+export DEEPSEEK_API_KEY=...+```+### OntologyGeneratorMain entry point for the generation pipeline.@@ -110,8 +170,7 @@ Validates ontology consistency.| Method | Description ||--------|-------------|-| `validate(ontology)` | Run symbolic reasoner |-| `check_constraints(ontology)` | Check structural rules |+| `validate_ontology(ontology)` | Run symbolic reasoner and structure checks |### OntologyEvaluator@@ -121,8 +180,8 @@ Scores ontology quality.| Method | Description ||--------|-------------|-| `evaluate(ontology)` | Calculate all metrics |-| `check_competency(questions)` | Verify coverage |+| `evaluate_ontology(ontology)` | Calculate evaluation metrics |+| `calculate_coverage(ontology, questions)` | Verify coverage |### ReuseManager@@ -132,21 +191,30 @@ Manages external dependencies.| Method | Description ||--------|-------------|-| `import_ontology(uri)` | Load external ontology |-| `align_concepts(source, target)` | Map equivalent classes |+| `import_external_ontology(uri, ontology)` | Load and merge external ontology |+| `evaluate_alignment(uri, ontology)` | Assess alignment and compatibility |----## Convenience Functions+## Unified Engine Examples```python-from semantica.ontology import generate_ontology, validate_ontology+from semantica.ontology import OntologyEngine-# Quick generation-onto = generate_ontology(data, method="default")+engine = OntologyEngine(base_uri="https://example.org/ontology/")-# Quick validation-is_valid, report = validate_ontology(onto)+# Generate+ontology = engine.from_data({+ "entities": entities,+ "relationships": relationships,+})++# Validate+result = engine.validate(ontology, reasoner="hermit")+print("valid=", result.valid, "consistent=", result.consistent)++# Export+turtle = engine.to_owl(ontology, format="turtle")```---@@ -182,12 +250,12 @@ ontology:### Schema-First Knowledge Graph```python-from semantica.ontology import OntologyGenerator+from semantica.ontology import OntologyEnginefrom semantica.kg import KnowledgeGraph# 1. Generate Ontology from Sample Data-generator = OntologyGenerator()-ontology = generator.generate_ontology(sample_data)+engine = OntologyEngine()+ontology = engine.from_data(sample_data)# 2. Initialize KG with Ontologykg = KnowledgeGraph(schema=ontology)diff --git a/semantica/ontology/__init__.py b/semantica/ontology/__init__.pyindex 0b1d84a4..aa0b2d30 100644--- a/semantica/ontology/__init__.py+++ b/semantica/ontology/__init__.py@@ -144,23 +144,8 @@ from .class_inferrer import ClassInferrerfrom .competency_questions import CompetencyQuestion, CompetencyQuestionsManagerfrom .config import OntologyConfig, ontology_configfrom .domain_ontologies import DomainOntologies-from .methods import (- add_competency_question,- create_associative_class,- create_requirements_spec,- create_version,- evaluate_ontology,- generate_ontology,- generate_owl,- get_ontology_method,- import_external_ontology,- infer_classes,- infer_properties,- list_available_methods,- manage_namespace,- research_ontology,- validate_ontology,-)+from .llm_generator import LLMOntologyGenerator+from .engine import OntologyEnginefrom .module_manager import ModuleManager, OntologyModulefrom .namespace_manager import NamespaceManagerfrom .naming_conventions import NamingConventions@@ -218,21 +203,8 @@ __all__ = [# 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",+ "LLMOntologyGenerator",+ "OntologyEngine",# Configuration"OntologyConfig","ontology_config",diff --git a/semantica/ontology/engine.py b/semantica/ontology/engine.pynew file mode 100644index 00000000..f5198a6d--- /dev/null+++ b/semantica/ontology/engine.py@@ -0,0 +1,71 @@+from typing import Any, Dict, List, Optional++from ..utils.exceptions import ProcessingError+from ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker+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 .llm_generator import LLMOntologyGenerator+++class OntologyEngine:+ def __init__(self, **config):+ self.logger = get_logger("ontology_engine")+ self.progress = get_progress_tracker()+ self.config = config++ self.generator = OntologyGenerator(**config)+ self.inferrer = ClassInferrer(**config)+ self.propgen = PropertyGenerator(**config)+ self.validator = OntologyValidator(**config)+ self.owl = OWLGenerator(**config)+ self.evaluator = OntologyEvaluator(**config)+ self.llm = LLMOntologyGenerator(**config)++ def from_data(self, data: Dict[str, Any], **options) -> Dict[str, Any]:+ tracking_id = self.progress.start_tracking(+ module="ontology",+ submodule="OntologyEngine",+ message="Generating ontology from data",+ )+ try:+ ontology = self.generator.generate_ontology(data, **options)+ self.progress.update_tracking(tracking_id, message="Ontology generated")+ return ontology+ except Exception as e:+ self.progress.update_tracking(tracking_id, message="Generation failed")+ raise++ def from_text(self, text: str, provider: Optional[str] = None, model: Optional[str] = None, **options) -> Dict[str, Any]:+ if provider:+ self.llm.set_provider(provider, model=model)+ return self.llm.generate_ontology_from_text(text, **options)++ def infer_classes(self, entities: List[Dict[str, Any]], **options) -> List[Dict[str, Any]]:+ return self.inferrer.infer_classes(entities, **options)++ def infer_properties(+ self,+ entities: List[Dict[str, Any]],+ relationships: List[Dict[str, Any]],+ classes: List[Dict[str, Any]],+ **options,+ ) -> List[Dict[str, Any]]:+ return self.propgen.infer_properties(entities, relationships, classes, **options)++ def validate(self, ontology: Dict[str, Any], **options):+ return self.validator.validate_ontology(ontology, **options)++ def evaluate(self, ontology: Dict[str, Any], **options):+ return self.evaluator.evaluate_ontology(ontology, **options)++ def to_owl(self, ontology: Dict[str, Any], format: str = "turtle", **options):+ return self.owl.generate_owl(ontology, format=format, **options)++ def export_owl(self, ontology: Dict[str, Any], path: str, format: str = "turtle"):+ return self.owl.export_owl(ontology, path, format=format)+diff --git a/semantica/ontology/llm_generator.py b/semantica/ontology/llm_generator.pynew file mode 100644index 00000000..0c34b8e7--- /dev/null+++ b/semantica/ontology/llm_generator.py@@ -0,0 +1,130 @@+from typing import Any, Dict, List, Optional++from ..utils.exceptions import ProcessingError, ValidationError+from ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker+from ..semantic_extract.providers import create_provider+++class LLMOntologyGenerator:+ def __init__(self, provider: str = "openai", model: Optional[str] = None, **config):+ self.logger = get_logger("llm_ontology_generator")+ self.progress = get_progress_tracker()+ self.provider_name = provider+ self.model = model+ self.config = config+ self.provider = create_provider(provider, model=model) if provider else None++ def set_provider(self, provider: str, model: Optional[str] = None, **kwargs):+ self.provider_name = provider+ self.model = model or self.model+ self.provider = create_provider(provider, model=self.model, **kwargs)++ def generate_ontology_from_text(self, text: str, **options) -> Dict[str, Any]:+ if not self.provider:+ raise ProcessingError("LLM provider not initialized")++ tracking_id = self.progress.start_tracking(+ module="ontology",+ submodule="LLMOntologyGenerator",+ message="Generating ontology from text",+ )++ base_uri = options.get("base_uri")+ name = options.get("name") or "GeneratedOntology"+ version = options.get("version") or "1.0"++ prompt = self._build_prompt(text=text, name=name, base_uri=base_uri)++ try:+ result = self.provider.generate_structured(+ prompt, model=self.model or options.get("model"), temperature=options.get("temperature", 0.2)+ )+ except Exception as e:+ self.progress.update_tracking(tracking_id, message="LLM generation failed")+ raise ProcessingError(f"LLM ontology generation failed: {e}")++ ontology = self._normalize_output(result, name=name, base_uri=base_uri, version=version)+ self.progress.update_tracking(tracking_id, message="Ontology generated")+ return ontology++ def _build_prompt(self, **kwargs) -> str:+ name = kwargs.get("name") or "GeneratedOntology"+ base_uri = kwargs.get("base_uri") or "https://example.org/ontology/"+ text = kwargs.get("text") or ""+ schema = """+{+ "name": "OntologyName",+ "base_uri": "https://example.org/ontology/",+ "classes": [+ {"name": "ClassName", "label": "Label", "comment": "Description", "parent": "ParentClass", "uri": "IRI"}+ ],+ "properties": [+ {"name": "propName", "type": "object|data", "domain": ["ClassName"], "range": ["ClassName|xsd:string"], "label": "Label", "comment": "Description", "uri": "IRI"}+ ]+}+"""+ instructions = (+ f"You are an ontology generator. Read the following text and produce a concise ontology in JSON. "+ f"Use '{base_uri}' for IRIs when missing. Only output valid JSON. "+ f"Prefer '{name}' as ontology name if appropriate."+ )+ return f"{instructions}\n\nTEXT:\n{text}\n\nJSON SCHEMA EXAMPLE:\n{schema}"++ def _normalize_output(self, result: Dict[str, Any], **meta) -> Dict[str, Any]:+ classes = result.get("classes") or result.get("Classes") or []+ properties = result.get("properties") or result.get("Properties") or []++ def ensure_uri(name: str, uri: Optional[str]) -> str:+ if uri:+ return uri+ base = meta.get("base_uri") or "https://example.org/ontology/"+ return f"{base}{name}"++ normalized_classes: List[Dict[str, Any]] = []+ for cls in classes:+ cname = cls.get("name") or cls.get("Name") or "Class"+ normalized_classes.append(+ {+ "name": cname,+ "uri": ensure_uri(cname, cls.get("uri") or cls.get("IRI")),+ "label": cls.get("label") or cls.get("Label"),+ "comment": cls.get("comment") or cls.get("Description"),+ "parent": cls.get("parent") or cls.get("Parent"),+ }+ )++ normalized_properties: List[Dict[str, Any]] = []+ for prop in properties:+ pname = prop.get("name") or prop.get("Name") or "property"+ dom = prop.get("domain") or prop.get("Domain") or []+ rng = prop.get("range") or prop.get("Range") or []+ ptype = prop.get("type") or prop.get("Type") or "object"+ normalized_properties.append(+ {+ "name": pname,+ "type": ptype,+ "domain": dom if isinstance(dom, list) else [dom] if dom else [],+ "range": rng if isinstance(rng, list) else [rng] if rng else [],+ "label": prop.get("label") or prop.get("Label"),+ "comment": prop.get("comment") or prop.get("Description"),+ "uri": ensure_uri(pname, prop.get("uri") or prop.get("IRI")),+ }+ )++ ontology: Dict[str, Any] = {+ "uri": meta.get("base_uri") or result.get("base_uri"),+ "name": meta.get("name") or result.get("name"),+ "version": meta.get("version") or result.get("version") or "1.0",+ "classes": normalized_classes,+ "properties": normalized_properties,+ "metadata": {"source": "llm", "provider": self.provider_name},+ }++ if not ontology["uri"]:+ ontology["uri"] = meta.get("base_uri") or "https://example.org/ontology/"++ if not ontology["name"]:+ ontology["name"] = "GeneratedOntology"++ return ontologydiff --git a/semantica/ontology/methods.py b/semantica/ontology/methods.pyindex e083367e..f941b925 100644--- a/semantica/ontology/methods.py+++ b/semantica/ontology/methods.py@@ -126,665 +126,48 @@ Example Usage:>>> result = validate_ontology(ontology, method="default")"""-from typing import Any, Callable, Dict, List, Optional, Union--from ..utils.exceptions import ConfigurationError, ProcessingError-from ..utils.logging import get_logger-from .associative_class import AssociativeClassBuilder-from .class_inferrer import ClassInferrer-from .competency_questions import CompetencyQuestionsManager-from .config import ontology_config-from .namespace_manager import NamespaceManager-from .ontology_evaluator import OntologyEvaluator-from .ontology_generator import OntologyGenerator-from .ontology_validator import OntologyValidator-from .owl_generator import OWLGenerator-from .property_generator import PropertyGenerator+from typing import Any, Callable, Dict, List, Optional+from .registry import method_registry-from .requirements_spec import RequirementsSpecManager-from .reuse_manager import ReuseManager-from .version_manager import VersionManager--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+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++pass+++passdef get_ontology_method(task: str, name: str) -> Optional[Callable]:@@ -797,14 +180,4 @@ def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]: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)+passdiff --git a/semantica/ontology/ontology_usage.md b/semantica/ontology/ontology_usage.mdindex 5bdaf75f..b45151f9 100644--- a/semantica/ontology/ontology_usage.md+++ b/semantica/ontology/ontology_usage.md@@ -23,36 +23,6 @@ This comprehensive guide demonstrates how to use the ontology management module## 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@@ -78,9 +48,9 @@ properties = prop_gen.infer_properties(entities, relationships, classes)### Basic Ontology Generation```python-from semantica.ontology import generate_ontology, OntologyGenerator+from semantica.ontology import OntologyEngine, OntologyGenerator-# Using convenience function+# Using OntologyEnginedata = {"entities": [{"type": "Person", "name": "John", "age": 30},@@ -92,8 +62,8 @@ data = {{"type": "worksFor", "source": "Jane", "target": "Acme Corp"}]}--ontology = generate_ontology(data, method="default", name="PersonOrgOntology")+engine = OntologyEngine(base_uri="https://example.org/ontology/")+ontology = engine.from_data(data, name="PersonOrgOntology")print(f"URI: {ontology['uri']}")print(f"Classes: {len(ontology['classes'])}")print(f"Properties: {len(ontology['properties'])}")@@ -135,16 +105,14 @@ print(f"Stage 4: Built hierarchy with {len([c for c in ontology['classes'] if 'p### Generation Options```python-from semantica.ontology import generate_ontology+from semantica.ontology import OntologyEngine# Generate with custom options-ontology = generate_ontology(+engine = OntologyEngine(base_uri="https://example.org/ontology/", min_occurrences=3)+ontology = engine.from_data(data,- method="default",name="CustomOntology",- base_uri="https://example.org/ontology/",build_hierarchy=True,- min_occurrences=3)```@@ -153,7 +121,7 @@ ontology = generate_ontology(### Basic Class Inference```python-from semantica.ontology import infer_classes, ClassInferrer+from semantica.ontology import OntologyEngine, ClassInferrerentities = [{"type": "Person", "name": "John", "age": 30},@@ -162,8 +130,8 @@ entities = [{"type": "Organization", "name": "Tech Inc"}]-# Using convenience function-classes = infer_classes(entities, method="default", build_hierarchy=True)+engine = OntologyEngine()+classes = engine.infer_classes(entities, build_hierarchy=True)for cls in classes:print(f"Class: {cls['name']}, Instances: {cls.get('entity_count', 0)}")@@ -195,15 +163,13 @@ if validation.get("valid"):### Class Inference Options```python-from semantica.ontology import infer_classes+from semantica.ontology import OntologyEngine# Custom inference options-classes = infer_classes(+engine = OntologyEngine()+classes = engine.infer_classes(entities,- method="default",build_hierarchy=True,- min_occurrences=3,- similarity_threshold=0.85)```@@ -212,7 +178,7 @@ classes = infer_classes(### Basic Property Inference```python-from semantica.ontology import infer_properties, PropertyGenerator+from semantica.ontology import OntologyEngine, PropertyGeneratorentities = [{"type": "Person", "name": "John", "age": 30, "email": "[email protected]"},@@ -229,8 +195,8 @@ classes = [{"name": "Organization", "uri": "https://example.org/ontology/Organization"}]-# Using convenience function-properties = infer_properties(entities, relationships, classes, method="default")+engine = OntologyEngine()+properties = engine.infer_properties(entities, relationships, classes)for prop in properties:print(f"Property: {prop['name']}, Type: {prop['type']}")@@ -266,10 +232,11 @@ validation = prop_gen.validate_properties(properties)### Basic Validation```python-from semantica.ontology import validate_ontology, OntologyValidator+from semantica.ontology import OntologyEngine, OntologyValidator-# Using convenience function-result = validate_ontology(ontology, method="default")+# Using OntologyEngine+engine = OntologyEngine()+result = engine.validate(ontology)if result.valid:print("Ontology is valid")@@ -288,29 +255,31 @@ result = validator.validate_ontology(ontology)### Validation with Reasoners```python-from semantica.ontology import validate_ontology+from semantica.ontology import OntologyEngine++engine = OntologyEngine()# HermiT reasoner-result = validate_ontology(ontology, method="hermit", reasoner="hermit")+result = engine.validate(ontology, reasoner="hermit")# Pellet reasoner-result = validate_ontology(ontology, method="pellet", reasoner="pellet")+result = engine.validate(ontology, reasoner="pellet")# Auto-select reasoner-result = validate_ontology(ontology, method="default", reasoner="auto")+result = engine.validate(ontology, reasoner="auto")```### Validation Options```python-from semantica.ontology import validate_ontology+from semantica.ontology import OntologyEngine# Custom validation options-result = validate_ontology(+engine = OntologyEngine()+result = engine.validate(ontology,- method="default",check_consistency=True,- check_satisfiability=True+ check_satisfiability=True,)```@@ -319,10 +288,11 @@ result = validate_ontology(### Basic OWL Generation```python-from semantica.ontology import generate_owl, OWLGenerator+from semantica.ontology import OntologyEngine, OWLGenerator-# Using convenience function-turtle = generate_owl(ontology, format="turtle", method="default")+# Using OntologyEngine+engine = OntologyEngine()+turtle = engine.to_owl(ontology, format="turtle")print(turtle)# Using class directly@@ -333,19 +303,21 @@ turtle = generator.generate_owl(ontology, format="turtle")### Different Formats```python-from semantica.ontology import generate_owl+from semantica.ontology import OntologyEngine++engine = OntologyEngine()# Turtle format-turtle = generate_owl(ontology, format="turtle", method="default")+turtle = engine.to_owl(ontology, format="turtle")# RDF/XML format-rdfxml = generate_owl(ontology, format="rdfxml", method="default")+rdfxml = engine.to_owl(ontology, format="rdfxml")# JSON-LD format-jsonld = generate_owl(ontology, format="json-ld", method="default")+jsonld = engine.to_owl(ontology, format="json-ld")# N3 format-n3 = generate_owl(ontology, format="n3", method="default")+n3 = engine.to_owl(ontology, format="n3")```### Export to File@@ -366,7 +338,7 @@ generator.export_owl(ontology, "ontology.jsonld", format="json-ld")### Basic Evaluation```python-from semantica.ontology import evaluate_ontology, OntologyEvaluator+from semantica.ontology import OntologyEngine, OntologyEvaluatorcompetency_questions = ["Who are the employees of an organization?",@@ -374,11 +346,10 @@ competency_questions = ["What is the age of a person?"]-# Using convenience function-result = evaluate_ontology(+engine = OntologyEngine()+result = engine.evaluate(ontology,competency_questions=competency_questions,- method="default")print(f"Coverage score: {result.coverage_score:.2f}")@@ -416,18 +387,7 @@ report = evaluator.generate_report(ontology)### 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"]-)+from semantica.ontology import RequirementsSpecManager# Using class directlymanager = RequirementsSpecManager()@@ -441,16 +401,7 @@ spec = manager.create_spec(### 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-)+from semantica.ontology import CompetencyQuestionsManager# Using class directlymanager = CompetencyQuestionsManager()@@ -480,14 +431,7 @@ validation = manager.validate_against_spec("PersonOntology", ontology)### 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')}")+from semantica.ontology import ReuseManager# Using class directlymanager = ReuseManager()@@ -497,14 +441,7 @@ 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"-)+from semantica.ontology import ReuseManager# Using class directlymanager = ReuseManager()@@ -533,15 +470,7 @@ print(f"Decision: {alignment.get('decision')}")### 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"]-)+from semantica.ontology import VersionManagerprint(f"Version: {version.version}")print(f"IRI: {version.ontology_iri}")@@ -573,22 +502,7 @@ migrated = manager.migrate_ontology("1.0", "2.0", ontology)### 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}")+from semantica.ontology import NamespaceManager# Using class directlymanager = NamespaceManager(base_uri="https://example.org/ontology/")@@ -618,19 +532,7 @@ namespaces = manager.get_all_namespaces()### 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}")+from semantica.ontology import AssociativeClassBuilder# Using class directlybuilder = AssociativeClassBuilder()@@ -683,61 +585,6 @@ if generate_method:### 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@@ -870,14 +717,9 @@ base_uri = config.get("base_uri")### Complete Ontology Generation Pipeline```python-from semantica.ontology import (- generate_ontology,- infer_classes,- infer_properties,- validate_ontology,- generate_owl,- evaluate_ontology-)+from semantica.ontology import OntologyEngine++engine = OntologyEngine(base_uri="https://example.org/ontology/")# Step 1: Generate ontologydata = {@@ -891,19 +733,19 @@ data = {]}-ontology = generate_ontology(data, method="default", name="PersonOrgOntology")+ontology = engine.from_data(data, name="PersonOrgOntology")# Step 2: Validate ontology-result = validate_ontology(ontology, method="default")+result = engine.validate(ontology)if not result.valid:print(f"Validation errors: {result.errors}")# Step 3: Generate OWL-turtle = generate_owl(ontology, format="turtle", method="default")+turtle = engine.to_owl(ontology, format="turtle")# Step 4: Evaluate ontologycompetency_questions = ["Who are the employees of an organization?"]-evaluation = evaluate_ontology(ontology, competency_questions=competency_questions, method="default")+evaluation = engine.evaluate(ontology, competency_questions=competency_questions)print(f"Coverage: {evaluation.coverage_score:.2f}")print(f"Completeness: {evaluation.completeness_score:.2f}")@@ -950,31 +792,28 @@ 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-)+from semantica.ontology import OntologyEngine, RequirementsSpecManager, CompetencyQuestionsManager# Step 1: Create requirements specification-spec = create_requirements_spec(+manager = RequirementsSpecManager()+spec = manager.create_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")+cq_manager = CompetencyQuestionsManager()+cq_manager.add_question("Who are the employees?", category="organizational")+cq_manager.add_question("What organizations does a person work for?", category="organizational")# Step 3: Generate ontology-ontology = generate_ontology(data, method="default")+engine = OntologyEngine()+ontology = engine.from_data(data)# Step 4: Evaluate against requirementscompetency_questions = ["Who are the employees?", "What organizations does a person work for?"]-evaluation = evaluate_ontology(ontology, competency_questions=competency_questions, method="default")+evaluation = engine.evaluate(ontology, competency_questions=competency_questions)# Step 5: Refine based on gapsif evaluation.gaps:@@ -985,24 +824,22 @@ if evaluation.gaps:### Version Management Workflow```python-from semantica.ontology import (- generate_ontology,- create_version,- VersionManager-)+from semantica.ontology import OntologyEngine, VersionManager# Generate initial ontology-ontology_v1 = generate_ontology(data, method="default", name="PersonOntology")+engine = OntologyEngine()+ontology_v1 = engine.from_data(data, name="PersonOntology")# Create version 1.0-version1 = create_version("1.0", ontology_v1, changes=["Initial version"], method="default")+manager = VersionManager()+version1 = manager.create_version("1.0", ontology_v1, changes=["Initial version"])# 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")+version2 = manager.create_version("2.0", ontology_v2, changes=["Added Role class"])# Compare versionsmanager = VersionManager()@@ -1013,20 +850,21 @@ print(f"Changes: {comparison.get('changes', [])}")### Integration with Knowledge Graph```python-from semantica.ontology import generate_ontology, generate_owl+from semantica.ontology import OntologyEnginefrom semantica.kg import build# Build knowledge graphkg = build(sources=[{"entities": entities, "relationships": relationships}])# Generate ontology from KG-ontology = generate_ontology({+engine = OntologyEngine()+ontology = engine.from_data({"entities": kg.get("entities", []),"relationships": kg.get("relationships", [])-}, method="default")+})# Generate OWL-turtle = generate_owl(ontology, format="turtle", method="default")+turtle = engine.to_owl(ontology, format="turtle")# Export for use in KGwith open("ontology.ttl", "w") as f:@@ -1050,3 +888,181 @@ with open("ontology.ttl", "w") as f:13. **Error Handling**: Always handle ValidationError and ProcessingError exceptions14. **Method Registry**: Register custom methods for domain-specific ontology needs+# Ontology Module Usage++This guide shows the streamlined API for ontology generation, validation, evaluation, and OWL export. It reflects the refactor that removes global convenience wrappers and introduces a single `OntologyEngine` plus an LLM-driven generator.++## Quick Start++```python+from semantica.ontology import OntologyEngine++engine = OntologyEngine(base_uri="https://example.org/ontology/")++# From structured data+data = {"entities": entities, "relationships": relationships}+ontology = engine.from_data(data)++# Validate+result = engine.validate(ontology)+print(result.valid, result.consistent)++# Export OWL+turtle = engine.to_owl(ontology, format="turtle")+with open("ontology.ttl", "w") as f:+ f.write(turtle)+```++## API Overview++- `OntologyEngine` (unified orchestration)+ - `from_data(data, **options)` → ontology dict+ - `from_text(text, provider=None, model=None, **options)` → ontology dict+ - `infer_classes(entities, **options)` → classes list+ - `infer_properties(entities, relationships, classes, **options)` → properties list+ - `validate(ontology, **options)` → `ValidationResult`+ - `evaluate(ontology, **options)` → evaluation dict+ - `to_owl(ontology, format="turtle", **options)` → serialization+ - `export_owl(ontology, path, format="turtle")` → file output++- `LLMOntologyGenerator` (LLM-based generation)+ - `set_provider(provider, model=None, **kwargs)`+ - `generate_ontology_from_text(text, **options)`++## LLM-Based Generation++```python+from semantica.ontology import OntologyEngine++engine = OntologyEngine()++# Choose provider: "openai", "groq", "deepseek", "huggingface_llm"+ontology = engine.from_text(+ text,+ provider="openai",+ model="gpt-4o",+ name="CompanyOntology",+ base_uri="https://example.org/company/",+)++print(len(ontology.get("classes", [])), len(ontology.get("properties", [])))+```++Environment variables used by providers:++```bash+export OPENAI_API_KEY=...+export GROQ_API_KEY=...+export DEEPSEEK_API_KEY=...+```++HuggingFace local models do not require API keys but require `transformers` installed.++## Data-Based Generation++```python+from semantica.ontology import OntologyEngine++engine = OntologyEngine(base_uri="https://example.org/ontology/")++sources = {+ "entities": [+ {"type": "Person", "name": "Alice"},+ {"type": "Organization", "name": "Acme"}+ ],+ "relationships": [+ {"type": "worksFor", "source": "Alice", "target": "Acme"}+ ]+}++ontology = engine.from_data(sources)+```++## Class and Property Inference++```python+classes = engine.infer_classes(entities, build_hierarchy=True)+properties = engine.infer_properties(entities, relationships, classes)+```++## Validation++```python+result = engine.validate(+ ontology,+ reasoner="hermit", # "hermit" | "pellet" | "auto"+ check_consistency=True,+ check_satisfiability=True,+)++if result.errors:+ for e in result.errors:+ print(e)+```++Reference: `OntologyValidator` implementation at `semantica/ontology/ontology_validator.py:59`.++## OWL Export++```python+turtle = engine.to_owl(ontology, format="turtle")+engine.export_owl(ontology, "ontology.ttl", format="turtle")++rdfxml = engine.to_owl(ontology, format="rdfxml")+jsonld = engine.to_owl(ontology, format="json-ld")+```++OWL generation uses `OWLGenerator` at `semantica/ontology/owl_generator.py:277` for fallback formatting and rdflib-based generation at `semantica/ontology/owl_generator.py:156`.++## Evaluation++```python+report = engine.evaluate(ontology)+print(report.get("evaluation", {}))+```++Evaluation includes gap analysis and completeness; see `semantica/ontology/ontology_evaluator.py:203`.++## Migration Notes++- Removed global convenience wrappers (e.g., `generate_ontology`, `validate_ontology`).+- Use `OntologyEngine` or direct classes:+ - Generation: `OntologyGenerator().generate_ontology(...)` at `semantica/ontology/ontology_generator.py:231`+ - Classes: `ClassInferrer().infer_classes(...)` at `semantica/ontology/class_inferrer.py:1`+ - Properties: `PropertyGenerator().infer_properties(...)` at `semantica/ontology/property_generator.py:1`+ - Validation: `OntologyValidator().validate_ontology(...)` at `semantica/ontology/ontology_validator.py:59`+ - OWL: `OWLGenerator().generate_owl(...)` at `semantica/ontology/owl_generator.py:277`++## End-to-End Example++```python+from semantica.ontology import OntologyEngine++text = """+Acme Corp. hired Alice as a Software Engineer in 2024. Alice works for Acme.+"""++engine = OntologyEngine()++ontology = engine.from_text(+ text,+ provider="deepseek",+ model="deepseek-chat",+ name="EmploymentOntology",+ base_uri="https://example.org/employment/",+)++result = engine.validate(ontology, reasoner="auto")+print("valid=", result.valid, "consistent=", result.consistent)++ttl = engine.to_owl(ontology, format="turtle")+with open("employment.ttl", "w") as f:+ f.write(ttl)+```++## Best Practices++- Always validate LLM-generated ontologies using a reasoner.+- Prefer domain prompts and few-shot examples for LLM generation.+- Keep class names PascalCase and properties camelCase; use stable base URIs.+- Export and version your ontology as part of CI.diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.pyindex 3176e356..e6d5e207 100644--- a/semantica/semantic_extract/providers.py+++ b/semantica/semantic_extract/providers.py@@ -431,6 +431,57 @@ class OllamaProvider(BaseProvider):raise ProcessingError("Failed to parse JSON from Ollama response")+class DeepSeekProvider(BaseProvider):+ def __init__(self, api_key: Optional[str] = None, model: str = "deepseek-chat", **kwargs):+ super().__init__(**kwargs)+ self.api_key = api_key or config.get_api_key("deepseek")+ self.model = model+ self.client = None+ self._init_client()++ def _init_client(self):+ try:+ import deepseek++ if self.api_key:+ self.client = deepseek.Client(api_key=self.api_key)+ except ImportError:+ self.client = None+ self.logger.warning(+ "deepseek library not installed. Install with: pip install semantica[llm-deepseek]"+ )++ def is_available(self) -> bool:+ return self.client is not None++ def generate(self, prompt: str, **kwargs) -> str:+ if not self.client:+ raise ProcessingError("DeepSeek client not initialized. Set DEEPSEEK_API_KEY or pass api_key.")+ response = self.client.chat.completions.create(+ model=kwargs.get("model", self.model),+ messages=[{"role": "user", "content": prompt}],+ temperature=kwargs.get("temperature", 0.3),+ )+ return response.choices[0].message.content++ def generate_structured(self, prompt: str, **kwargs) -> dict:+ if not self.client:+ raise ProcessingError("DeepSeek client not initialized.")+ response = self.client.chat.completions.create(+ model=kwargs.get("model", self.model),+ messages=[{"role": "user", "content": prompt}],+ temperature=kwargs.get("temperature", 0.3),+ )+ text = response.choices[0].message.content+ try:+ return json.loads(text)+ except json.JSONDecodeError:+ start = text.find("{")+ end = text.rfind("}") + 1+ if start >= 0 and end > start:+ return json.loads(text[start:end])+ raise ProcessingError("Failed to parse JSON from DeepSeek response")+class HuggingFaceLLMProvider(BaseProvider):"""HuggingFace transformers for LLM tasks."""@@ -620,6 +671,7 @@ def create_provider(name: str, **kwargs) -> BaseProvider:"anthropic": AnthropicProvider,"ollama": OllamaProvider,"huggingface_llm": HuggingFaceLLMProvider,+ "deepseek": DeepSeekProvider,}provider_class = builtin.get(name.lower())