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(reasoning): add dedicated reasoning tests and fix critical reasoning bugs
KaifAhmad1eaa1fbefa617
diff --git a/README.md b/README.mdindex 206b44af..b5bb4919 100644--- a/README.md+++ b/README.md@@ -229,11 +229,6 @@ python -c "import semantica; print(semantica.__version__)"**Current Version:** [](https://pypi.org/project/semantica/0.0.1/) β’ [View on PyPI](https://pypi.org/project/semantica/0.0.1/)-<<<<<<< HEAD-<<<<<<< Updated upstream-=======-=======->>>>>>> main## π³ Semantica Cookbook> **Interactive Jupyter Notebooks** designed to take you from beginner to expert.@@ -245,11 +240,7 @@ python -c "import semantica; print(semantica.__version__)"| **Recipe** | **Description** | **Link** ||:-----------|:----------------|:---------|| **GraphRAG Complete** | Build a production-ready **Graph Retrieval Augmented Generation** system. Features **Graph Validation**, **Hybrid Retrieval**, and **Logical Inference**. | [Open Notebook](cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb) |-<<<<<<< HEAD-| **RAG vs. GraphRAG** | Side-by-side comparison. Demonstrates the **Reasoning Gap** and how GraphRAG solves it. | [Open Notebook](cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) |-=======| **RAG vs. GraphRAG** | Side-by-side comparison. Demonstrates the **Reasoning Gap** and how GraphRAG solves it with **Inference Engines**. | [Open Notebook](cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb) |->>>>>>> main| **First Knowledge Graph** | Go from raw text to a queryable knowledge graph in 20 minutes. | [Open Notebook](cookbook/introduction/08_Your_First_Knowledge_Graph.ipynb) || **Real-Time Anomalies** | Detect anomalies in streaming data using dynamic graphs. | [Open Notebook](cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb) |@@ -262,10 +253,6 @@ python -c "import semantica; print(semantica.__version__)"> **Note:** Once published to PyPI, you'll be able to install with `pip install semantica`-<<<<<<< HEAD->>>>>>> Stashed changes-=======->>>>>>> main### Install from Source (Development)```bash@@ -450,6 +437,32 @@ print(f"Answer: {result.answer} (Confidence: {result.confidence:.2f})")[**Cookbook: GraphRAG**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)+### Reasoning & Inference Engine++> **Rule-based Inference** β’ **Forward/Backward Chaining** β’ **Rete Algorithm** β’ **Explanation Generation**++```python+from semantica.reasoning import Reasoner++# Initialize Reasoner+reasoner = Reasoner()++# Define rules and facts+rules = ["IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)"]+facts = ["Parent(Alice, Bob)", "Parent(Bob, Charlie)"]++# Infer new facts (Forward Chaining)+inferred = reasoner.infer_facts(facts, rules)+print(f"Inferred: {inferred}") # ['Grandparent(Alice, Charlie)']++# Explain reasoning+from semantica.reasoning import ExplanationGenerator+explainer = ExplanationGenerator()+# ... generate explanation for inferred facts+```++[**Cookbook: Reasoning**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb) β’ [**Rete Engine**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/advanced/09_Rete_Engine.ipynb)+### Pipeline Orchestration & Parallel Processing> **Orchestrator-Worker Pattern** β’ Parallel Execution β’ Scalable Processing@@ -544,7 +557,7 @@ print(f"Answer: {result.answer} | Nodes: {kg.node_count}, Edges: {kg.edge_count}**Custom Ontology Import** β Import and extend Schema.org and custom ontologies.-**Advanced Reasoning** β Deductive, inductive, abductive reasoning with HermiT/Pellet.+**Advanced Reasoning** β Forward/backward chaining, Rete-based pattern matching, and automated explanation generation.**Graph Analytics** β Centrality, community detection, path finding, temporal analysis.@@ -560,10 +573,10 @@ print(f"Answer: {result.answer} | Nodes: {kg.node_count}, Edges: {kg.edge_count}- [x] Core framework (v1.0)- [x] GraphRAG engine- [x] 6-stage ontology pipeline+- [x] Advanced reasoning v2 (Rete, Forward/Backward Chaining)- [ ] Quality assurance features and Quality Assurance module- [ ] Enhanced multi-language support- [ ] Real-time streaming improvements-- [ ] Advanced reasoning v2### Q2 2026- [ ] Multi-modal processingdiff --git a/cookbook/advanced/08_Reasoning_and_Inference.ipynb b/cookbook/advanced/08_Reasoning_and_Inference.ipynbindex 8883d16f..eb2e7a34 100644--- a/cookbook/advanced/08_Reasoning_and_Inference.ipynb+++ b/cookbook/advanced/08_Reasoning_and_Inference.ipynb@@ -60,7 +60,7 @@"outputs": [],"source": ["from semantica.kg import GraphBuilder\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n"+ "from semantica.reasoning import Reasoner, ExplanationGenerator\n"]},{@@ -78,7 +78,7 @@{"data": {"text/html": [- "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>GraphBuilder</td><td>-</td><td>0.31s</td></tr><tr><td>π</td><td>Semantica is building</td><td>π§ kg</td><td>EntityResolver</td><td>-</td><td>2.16s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>EntityMerger</td><td>-</td><td>0.05s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>RuleManager</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>InferenceEngine</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>ExplanationGenerator</td><td>-</td><td>0.01s</td></tr></table></div>"+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>GraphBuilder</td><td>-</td><td>0.31s</td></tr><tr><td>π</td><td>Semantica is building</td><td>π§ kg</td><td>EntityResolver</td><td>-</td><td>2.16s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>EntityMerger</td><td>-</td><td>0.05s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>MergeStrategyManager</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>Reasoner</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>Reasoner</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>ExplanationGenerator</td><td>-</td><td>0.01s</td></tr></table></div>"],"text/plain": ["<IPython.core.display.HTML object>"@@ -122,8 +122,8 @@"metadata": {},"outputs": [],"source": [- "# Initialize Inference Engine\n",- "engine = InferenceEngine()\n",+ "# Initialize Reasoner\n",+ "reasoner = Reasoner()\n","\n","# Define rules using logic syntax\n","rules = [\n",@@ -132,7 +132,7 @@"]\n","\n","for rule in rules:\n",- " engine.add_rule(rule)\n"+ " reasoner.add_rule(rule)\n"]},{@@ -152,24 +152,19 @@"output_type": "stream","text": ["Inferred 2 new facts:\n",- " - grandparent_of(alice, charlie) (Rule: Rule 1)\n",- " - lives_in(alice, california) (Rule: Rule 2)\n"+ " - grandparent_of(alice, charlie)\n",+ " - lives_in(alice, california)\n"]}],"source": [- "# Load facts from relationships into the engine\n",- "for rel in relationships:\n",- " # Format: predicate(subject, object)\n",- " fact_str = f\"{rel['type']}({rel['source']}, {rel['target']})\"\n",- " engine.add_fact(fact_str)\n",- "\n","# Perform forward chaining to derive new facts\n",- "results = engine.forward_chain()\n",+ "# The Reasoner can infer facts directly from the knowledge graph or a list of facts\n",+ "inferred_facts = reasoner.infer_facts(knowledge_graph)\n","\n",- "print(f\"Inferred {len(results)} new facts:\")\n",- "for result in results:\n",- " print(f\" - {result.conclusion} (Rule: {result.rule_used.name})\")\n"+ "print(f\"Inferred {len(inferred_facts)} new facts:\")\n",+ "for fact in inferred_facts:\n",+ " print(f\" - {fact}\")\n"]},{@@ -197,7 +192,7 @@"goal = \"grandparent_of(alice, charlie)\"\n","\n","# Perform backward chaining\n",- "proof = engine.backward_chain(goal)\n",+ "proof = reasoner.backward_chain(goal)\n","\n","if proof:\n"," print(f\"Goal '{goal}' proven successfully!\")\n",@@ -221,27 +216,18 @@"name": "stdout","output_type": "stream","text": [- "Explanation for first inferred fact:\n",- "Given the premises: parent_of(alice, bob), parent_of(bob, charlie), we conclude: grandparent_of(alice, charlie) using rule 'Rule 1'.\n",- "\n","Explanation for backward chaining proof:\n",- "Given the premises: , we conclude: grandparent_of(alice, charlie).\n"+ "Given the premises: parent_of(alice, bob), parent_of(bob, charlie), we conclude: grandparent_of(alice, charlie).\n"]}],"source": ["generator = ExplanationGenerator()\n","\n",- "# Explain the last forward chaining inference\n",- "if results:\n",- " explanation = generator.generate_explanation(results[0])\n",- " print(\"Explanation for first inferred fact:\")\n",- " print(explanation.natural_language)\n",- "\n","# If we have a proof from backward chaining, explain it\n","if proof:\n"," proof_explanation = generator.generate_explanation(proof)\n",- " print(\"\\nExplanation for backward chaining proof:\")\n",+ " print(\"Explanation for backward chaining proof:\")\n"," print(proof_explanation.natural_language)\n"]},@@ -284,10 +270,10 @@"outputs": [],"source": ["from semantica.kg import GraphBuilder\n",- "from semantica.reasoning import InferenceEngine, ExplanationGenerator\n",+ "from semantica.reasoning import Reasoner, ExplanationGenerator\n","\n","builder = GraphBuilder()\n",- "engine = InferenceEngine()\n",+ "reasoner = Reasoner()\n","explainer = ExplanationGenerator()\n"]},@@ -350,7 +336,7 @@" \"IF lives_in(?x, ?y) AND located_in(?y, ?z) THEN lives_in(?x, ?z)\"\n","]\n","for r in rules:\n",- " engine.add_rule(r)\n"+ " reasoner.add_rule(r)\n"]},{@@ -371,9 +357,9 @@"source": ["for rel in relationships:\n"," fact = f\"{rel['type']}({rel['source']}, {rel['target']})\"\n",- " engine.add_fact(fact)\n",+ " reasoner.add_fact(fact)\n","\n",- "derived = engine.forward_chain()\n",+ "derived = reasoner.forward_chain()\n","print(len(derived))\n","for d in derived:\n"," print(d.conclusion)\n"@@ -401,7 +387,7 @@" \"lives_in(alice, california)\"\n","]\n","for g in goals:\n",- " proof = engine.backward_chain(g)\n",+ " proof = reasoner.backward_chain(g)\n"," print(g)\n"," print(bool(proof))\n"]@@ -426,7 +412,7 @@" print(exp.natural_language)\n","\n","goal = \"grandparent_of(alice, charlie)\"\n",- "proof = engine.backward_chain(goal)\n",+ "proof = reasoner.backward_chain(goal)\n","if proof:\n"," pexp = explainer.generate_explanation(proof)\n"," print(pexp.natural_language)\n"diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynbindex 1d4496f9..a1d6608f 100644--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb@@ -6,412 +6,6 @@"source": ["[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/introduction/01_Welcome_to_Semantica.ipynb)\n","\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "**Example**:\n",- "```python\n",- "from semantica.graph_store import GraphStore\n",- "store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",- "store.connect()\n",- "node1 = store.create_node(\n",- " labels=[\"Person\"],\n",- " properties={\"name\": \"John\", \"age\": 30}\n",- ")\n",- "node2 = store.create_node(\n",- " labels=[\"Person\"],\n",- " properties={\"name\": \"Jane\", \"age\": 28}\n",- ")\n",- "store.create_relationship(\n",- " start_node_id=node1[\"id\"],\n",- " end_node_id=node2[\"id\"],\n",- " rel_type=\"KNOWS\",\n",- " properties={\"since\": 2020}\n",- ")\n",- "results = store.execute_query(\"MATCH (p:Person) RETURN p.name\")\n",- "store.close()\n",- "```\n",- "\n",- "### 9. REASONING MODULE - Inference and Reasoning\n",- "**Purpose**: Perform logical inference and reasoning\n",- "**Components**:\n",- "- `InferenceEngine`: Main inference orchestrator\n",- "- `RuleManager`: Manage inference rules\n",- "- `DeductiveReasoner`: Deductive reasoning\n",- "- `AbductiveReasoner`: Abductive reasoning\n",- "- `ExplanationGenerator`: Generate explanations for inferences\n",- "- `RETEEngine`: RETE algorithm for rule matching\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.reasoning import InferenceEngine, RuleManager\n",- "inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "new_facts = inference_engine.forward_chain()\n",- "```\n",- "\n",- "### 10. ONTOLOGY MODULE - Ontology Generation\n",- "**Purpose**: Generate and manage ontologies\n",- "**Components**:\n",- "- `OntologyGenerator`: Generate ontologies from knowledge graphs\n",- "- `OntologyValidator`: Validate ontology structure\n",- "- `OWLGenerator`: Generate OWL format ontologies\n",- "- `PropertyGenerator`: Generate ontology properties\n",- "- `ClassInferrer`: Infer ontology classes\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.ontology import OntologyGenerator\n",- "generator = OntologyGenerator()\n",- "ontology = generator.generate_from_graph(kg)\n",- "```\n",- "\n",- "### 11. EXPORT MODULE - Data Export\n",- "**Purpose**: Export data in various formats\n",- "**Components**:\n",- "- `JSONExporter`: Export to JSON\n",- "- `RDFExporter`: Export to RDF/XML\n",- "- `CSVExporter`: Export to CSV\n",- "- `GraphExporter`: Export to graph formats (GraphML, GEXF)\n",- "- `OWLExporter`: Export to OWL\n",- "- `VectorExporter`: Export vectors\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.export import JSONExporter, RDFExporter\n",- "json_exporter = JSONExporter()\n",- "json_exporter.export(kg, \"output.json\")\n",- "```\n",- "\n",- "### 12. VISUALIZATION MODULE - Graph Visualization\n",- "**Purpose**: Visualize knowledge graphs and analytics\n",- "**Components**:\n",- "- `KGVisualizer`: Visualize knowledge graphs\n",- "- `EmbeddingVisualizer`: Visualize embeddings (t-SNE, PCA, UMAP)\n",- "- `QualityVisualizer`: Visualize quality metrics\n",- "- `AnalyticsVisualizer`: Visualize graph analytics\n",- "- `TemporalVisualizer`: Visualize temporal data\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.visualization import KGVisualizer\n",- "visualizer = KGVisualizer()\n",- "visualizer.visualize(kg)\n",- "```\n",- "\n",- "### 13. PIPELINE MODULE - Pipeline Orchestration\n",- "**Purpose**: Build and execute processing pipelines\n",- "**Components**:\n",- "- `PipelineBuilder`: Build complex pipelines\n",- "- `ExecutionEngine`: Execute pipelines\n",- "- `FailureHandler`: Handle pipeline failures\n",- "- `ParallelismManager`: Enable parallel processing\n",- "- `ResourceScheduler`: Schedule resources\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.pipeline import PipelineBuilder\n",- "builder = PipelineBuilder()\n",- "pipeline = builder.add_step(\"ingest\", FileIngestor()) \\\\\n",- " .add_step(\"parse\", DocumentParser()) \\\\\n",- " .build()\n",- "```\n",- "\n",- "### 14. CORE MODULE - Framework Orchestration\n",- "**Purpose**: Framework initialization, configuration, lifecycle management, and plugin system\n",- "**Components**:\n",- "- `Semantica`: Main framework class coordinating all components\n",- "- `ConfigManager`: Configuration loading, validation, and management\n",- "- `Config`: Configuration data class with validation\n",- "- `LifecycleManager`: System lifecycle management with hooks and health monitoring\n",- "- `PluginRegistry`: Dynamic plugin discovery and loading\n",- "- `MethodRegistry`: Registry for custom orchestration methods\n",- "\n",- "**Example**:\n",- "```python\n",- "from semantica.core import Semantica, ConfigManager\n",- "\n",- "# Load configuration\n",- "config_manager = ConfigManager()\n",- "config = config_manager.load_from_file(\"config.yaml\")\n",- "\n",- "# Initialize framework\n",- "framework = Semantica(config=config)\n",- "framework.initialize()\n",- "\n",- "# Build knowledge base\n",- "result = framework.build_knowledge_base(\n",- " sources=[\"doc1.pdf\", \"doc2.docx\"],\n",- " embeddings=True,\n",- " graph=True\n",- ")\n",- "\n",- "# Shutdown gracefully\n",- "framework.shutdown()\n",- "```\n",- "\n",- "---\n",- "\n",- "## Key Concepts Explained\n",- "\n",- "Understanding these concepts is crucial for working with Semantica:\n",- "\n",- "### 1. KNOWLEDGE GRAPHS\n",- "**Definition**: A knowledge graph is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes.\n",- "\n",- "**Structure**:\n",- "- **Nodes**: Represent entities (people, places, concepts, events)\n",- "- **Edges**: Represent relationships (works_for, located_in, causes)\n",- "- **Properties**: Attributes of entities and relationships\n",- "- **Metadata**: Additional information (sources, timestamps, confidence)\n",- "\n",- "**Example**:\n",- "- Entity: \"John Doe\" (Person)\n",- "- Relationship: \"works_for\" -> \"Acme Corp\" (Organization)\n",- "- Properties: `{start_date: \"2020-01-01\", role: \"Engineer\"}`\n",- "\n",- "**Benefits**:\n",- "- Structured representation of unstructured data\n",- "- Enables complex queries and reasoning\n",- "- Supports temporal tracking\n",- "- Facilitates knowledge discovery\n",- "\n",- "### 2. ENTITY EXTRACTION (NER - Named Entity Recognition)\n",- "**Definition**: The process of identifying and classifying named entities in text into predefined categories.\n",- "\n",- "**Entity Types**:\n",- "- **Person**: Names of people\n",- "- **Organization**: Companies, institutions\n",- "- **Location**: Places, geographic entities\n",- "- **Date/Time**: Temporal expressions\n",- "- **Money**: Monetary values\n",- "- **Product**: Products and services\n",- "- **Event**: Events and occurrences\n",- "- **Custom**: Domain-specific entities\n",- "\n",- "**Example**:\n",- "Text: \"Apple Inc. was founded by Steve Jobs in Cupertino, California.\"\n",- "Entities:\n",- "- \"Apple Inc.\" -> Organization\n",- "- \"Steve Jobs\" -> Person\n",- "- \"Cupertino, California\" -> Location\n",- "\n",- "**Methods**:\n",- "- Rule-based: Pattern matching\n",- "- Machine Learning: Trained models (spaCy, transformers)\n",- "- LLM-based: Using large language models\n",- "\n",- "### 3. RELATIONSHIP EXTRACTION\n",- "**Definition**: Identifying and extracting relationships between entities in text.\n",- "\n",- "**Relationship Types**:\n",- "- **Semantic**: \"works_for\", \"located_in\", \"causes\"\n",- "- **Temporal**: \"before\", \"after\", \"during\"\n",- "- **Causal**: \"causes\", \"results_in\", \"prevents\"\n",- "- **Hierarchical**: \"part_of\", \"subclass_of\", \"instance_of\"\n",- "\n",- "**Example**:\n",- "Text: \"John works for Acme Corp in New York.\"\n",- "Relationships:\n",- "- (John, works_for, Acme Corp)\n",- "- (Acme Corp, located_in, New York)\n",- "\n",- "**Methods**:\n",- "- Pattern matching\n",- "- Dependency parsing\n",- "- Machine learning models\n",- "- LLM-based extraction\n",- "\n",- "### 4. EMBEDDINGS\n",- "**Definition**: Dense vector representations of text, images, or other data that capture semantic meaning in a continuous vector space.\n",- "\n",- "**Properties**:\n",- "- Similar entities have similar embeddings (close in vector space)\n",- "- Enable semantic search and similarity calculations\n",- "- Fixed or variable dimensions (typically 128-4096)\n",- "\n",- "**Example**:\n",- "Text: \"machine learning\"\n",- "Embedding: `[0.123, -0.456, 0.789, ..., 0.234]` (vector of 1536 dimensions)\n",- "\n",- "**Use Cases**:\n",- "- Semantic search\n",- "- Clustering and classification\n",- "- Recommendation systems\n",- "- Anomaly detection\n",- "\n",- "### 5. TEMPORAL GRAPHS\n",- "**Definition**: Knowledge graphs that track changes over time, allowing queries about the state of the graph at specific time points.\n",- "\n",- "**Features**:\n",- "- Timestamps on entities and relationships\n",- "- Version history\n",- "- Time-point queries\n",- "- Temporal pattern detection\n",- "\n",- "**Example**:\n",- "- Entity: \"Company X\"\n",- "- Relationship: (Company X, has_CEO, Person Y)\n",- "- Temporal: `valid_from=\"2020-01-01\", valid_to=\"2023-12-31\"`\n",- "\n",- "**Use Cases**:\n",- "- Tracking organizational changes\n",- "- Monitoring system evolution\n",- "- Analyzing trends over time\n",- "- Historical analysis\n",- "\n",- "### 6. GraphRAG (Graph-based Retrieval Augmented Generation)\n",- "**Definition**: An advanced RAG approach that combines vector search with knowledge graph traversal to provide more accurate and contextually relevant information to LLMs.\n",- "\n",- "**Components**:\n",- "- **Vector Store**: For semantic similarity search\n",- "- **Knowledge Graph**: For structured relationship traversal\n",- "- **Hybrid Search**: Combines both approaches\n",- "- **LLM Integration**: Uses retrieved context for generation\n",- "\n",- "**Advantages over Traditional RAG**:\n",- "- Better handling of complex queries\n",- "- Relationship-aware retrieval\n",- "- Reduced hallucinations\n",- "- More accurate answers\n",- "\n",- "**Example Workflow**:\n",- "1. Query: \"Who worked with John at Acme Corp?\"\n",- "2. Vector search finds relevant documents\n",- "3. Knowledge graph traversal finds relationships\n",- "4. Combined context sent to LLM\n",- "5. LLM generates accurate answer using both sources\n",- "\n",- "### 7. ONTOLOGY\n",- "**Definition**: A formal specification of concepts, relationships, and constraints in a domain, typically expressed in OWL (Web Ontology Language).\n",- "\n",- "**Components**:\n",- "- **Classes**: Categories of entities\n",- "- **Properties**: Relationships and attributes\n",- "- **Individuals**: Specific instances\n",- "- **Axioms**: Rules and constraints\n",- "\n",- "**Example**:\n",- "- Class: Person\n",- "- SubClass: Employee, Customer\n",- "- Property: worksFor (domain: Person, range: Organization)\n",- "\n",- "**Use Cases**:\n",- "- Standardize domain knowledge\n",- "- Enable reasoning\n",- "- Facilitate data integration\n",- "- Support semantic web\n",- "\n",- "### 8. QUALITY ASSURANCE\n",- "**Definition**: Processes and metrics to ensure knowledge graph quality, including completeness, consistency, and accuracy.\n",- "\n",- "**Metrics**:\n",- "- **Completeness**: Percentage of entities with required properties\n",- "- **Consistency**: Absence of contradictions\n",- "- **Accuracy**: Correctness of extracted information\n",- "- **Coverage**: Breadth of domain coverage\n",- "\n",- "**Methods**:\n",- "- Validation rules\n",- "- Automated quality checks\n",- "- Conflict detection\n",- "- Source verification\n",- "---\n",- "\n",- "## Next Steps\n",- "\n",- "Now that you understand the basics, here are recommended next steps:\n",- "\n",- "1. **Your First Knowledge Graph** (`01_Your_First_Knowledge_Graph.ipynb`)\n",- " - Build your first knowledge graph from a document\n",- " - Learn the basic workflow\n",- "\n",- "2. **Configuration Basics** (`02_Configuration_Basics.ipynb`)\n",- " - Set up configuration files\n",- " - Configure API keys and providers\n",- "\n",- "3. **Core Workflows** (`01_core_workflows/`)\n",- " - Learn common patterns and workflows\n",- " - Start with \"From Unstructured to Structured\"\n",- "\n",- "4. **Use Cases** (`03_use_cases/`)\n",- " - Explore domain-specific applications\n",- " - Find examples relevant to your domain\n",- "\n",- "---\n",- "\n",- "## Best Practices\n",- "\n",- "### 1. START SMALL\n",- "- Begin with simple documents\n",- "- Validate each step before moving forward\n",- "- Build incrementally\n",- "\n",- "### 2. CONFIGURE PROPERLY\n",- "- Use environment variables for sensitive data\n",- "- Set up proper logging\n",- "- Configure appropriate model sizes\n",- "\n",- "### 3. VALIDATE DATA\n",- "- Always validate extracted entities\n",- "- Check relationship quality\n",- "- Use quality assurance tools\n",- "\n",- "### 4. HANDLE ERRORS\n",- "- Implement error handling\n",- "- Use retry mechanisms\n",- "- Log errors for debugging\n",- "\n",- "### 5. OPTIMIZE PERFORMANCE\n",- "- Use batch processing for large datasets\n",- "- Enable parallel processing where possible\n",- "- Cache embeddings and results\n",- "\n",- "### 6. DOCUMENT YOUR WORKFLOWS\n",- "- Document data sources\n",- "- Track processing steps\n",- "- Maintain metadata\n",- "\n",- "---\n",- "\n",- "## Troubleshooting\n",- "\n",- "Common issues and solutions:\n",- "\n",- "### Issue 1: Import Errors\n",- "**Solution**:\n",- "- Ensure Semantica is properly installed\n",- "- Check Python version (3.8+)\n",- "- Verify virtual environment is activated\n",- "- Install missing dependencies: `pip install -r requirements.txt`\n",- "\n",- "### Issue 2: API Key Errors\n",- "**Solution**:\n",- "- Set environment variables: `export SEMANTICA_API_KEY=your_key`\n",- "- Check config file for correct key format\n",- "- Verify API key is valid and has sufficient credits\n",- "\n",- "### Issue 3: Memory Issues\n",- "**Solution**:\n",- "- Process documents in batches\n",- "- Use smaller embedding models\n",- "- Enable garbage collection\n",- "- Consider using streaming for large datasets\n",- "\n",- "### Issue 4: Low Quality Extractions\n",- "**Solution**:\n",- "- Preprocess and normalize text\n",- "- Use domain-specific models\n",- "- Adjust extraction parameters\n",- "- Validate and clean extracted entities\n",- "\n",- "### Issue 5: Slow Processing\n",- "**Solution**:\n",- "- Enable parallel processing\n",- "- Use GPU acceleration if available\n",- "- Cache intermediate results\n",- "- Optimize batch sizes\n",- "\n"-======="Semantica is a **semantic intelligence and knowledge engineering framework**. It helps you:\n","\n","- Build **knowledge graphs** from unstructured and semi-structured data\n",@@ -471,73 +65,73 @@"cell_type": "markdown","metadata": {},"source": [- "## \ud83e\udde9 Semantica Modules Reference\n",+ "## π§© Semantica Modules Reference\n","\n","Semantica is modular by design. Here is a comprehensive guide to all available modules, grouped by functionality.\n","\n",- "### \ud83d\udce5 Ingestion & Parsing\n",+ "### π₯ Ingestion & Parsing\n","Modules that handle raw data input and structure.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`ingest`** | **Data Ingestion**<br>Connects to data sources. | \u2022 File, Web, Feed, Stream ingestion<br>\u2022 DB, Email, Repo, MCP support |\n",- "| **`parse`** | **Document Parsing**<br>Parses raw content into structures. | \u2022 PDF, HTML, JSON, CSV, Excel<br>\u2022 Image & Code parsing |\n",+ "| **`ingest`** | **Data Ingestion**<br>Connects to data sources. | β’ File, Web, Feed, Stream ingestion<br>β’ DB, Email, Repo, MCP support |\n",+ "| **`parse`** | **Document Parsing**<br>Parses raw content into structures. | β’ PDF, HTML, JSON, CSV, Excel<br>β’ Image & Code parsing |\n","\n",- "### \u2699\ufe0f Data Processing\n",+ "### βοΈ Data Processing\n","Modules that clean, normalize, and split data.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`normalize`** | **Data Normalization**<br>Cleans and standardizes text. | \u2022 Text cleaning & Language detection<br>\u2022 Entity, Date, Number normalization |\n",- "| **`split`** | **Chunking**<br>Splits documents for RAG. | \u2022 Recursive character splitting<br>\u2022 Semantic & Token-based splitting |\n",+ "| **`normalize`** | **Data Normalization**<br>Cleans and standardizes text. | β’ Text cleaning & Language detection<br>β’ Entity, Date, Number normalization |\n",+ "| **`split`** | **Chunking**<br>Splits documents for RAG. | β’ Recursive character splitting<br>β’ Semantic & Token-based splitting |\n","\n",- "### \ud83e\udde0 Extraction & Enrichment\n",+ "### π§ Extraction & Enrichment\n","Modules that extract meaning, structure, and vectors from raw data.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`semantic_extract`** | **Information Extraction**<br>Extracts entities and relations. | \u2022 NER & Relation Extraction<br>\u2022 Event & Semantic Network detection |\n",- "| **`context`** | **Agent Memory**<br>Manages state for AI agents. | \u2022 Long-term memory & history<br>\u2022 Context graph & RAG integration |\n",+ "| **`semantic_extract`** | **Information Extraction**<br>Extracts entities and relations. | β’ NER & Relation Extraction<br>β’ Event & Semantic Network detection |\n",+ "| **`context`** | **Agent Memory**<br>Manages state for AI agents. | β’ Long-term memory & history<br>β’ Context graph & RAG integration |\n","\n",- "### \ud83d\udd78\ufe0f Knowledge Graph Core\n",+ "### πΈοΈ Knowledge Graph Core\n","Modules for building, refining, and resolving knowledge graphs.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`kg`** | **Graph Construction**<br>Builds and analyzes graphs. | \u2022 Graph Building & Analysis<br>\u2022 Validation & Entity Resolution |\n",- "| **`conflicts`** | **Conflict Resolution**<br>Resolves data contradictions. | \u2022 Source reliability scoring<br>\u2022 Truth discovery algorithms |\n",- "| **`deduplication`** | **Entity Resolution**<br>Merges duplicate entities. | \u2022 Similarity-based blocking<br>\u2022 Clustering & Canonicalization |\n",+ "| **`kg`** | **Graph Construction**<br>Builds and analyzes graphs. | β’ Graph Building & Analysis<br>β’ Validation & Entity Resolution |\n",+ "| **`conflicts`** | **Conflict Resolution**<br>Resolves data contradictions. | β’ Source reliability scoring<br>β’ Truth discovery algorithms |\n",+ "| **`deduplication`** | **Entity Resolution**<br>Merges duplicate entities. | β’ Similarity-based blocking<br>β’ Clustering & Canonicalization |\n","\n",- "### \ud83d\udcbe Storage & Retrieval\n",+ "### πΎ Storage & Retrieval\n","Modules for persisting and querying data.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`embeddings`** | **Vector Embeddings**<br>Generates semantic vectors. | \u2022 Text & Graph embeddings<br>\u2022 Multi-provider support (OpenAI, etc.) |\n",- "| **`vector_store`** | **Vector Database**<br>Stores and searches vectors. | \u2022 Similarity search & Filtering<br>\u2022 Hybrid search (Vector + Keyword) |\n",- "| **`graph_store`** | **Property Graph Store**<br>Persists graph data. | \u2022 Neo4j, FalkorDB adapters<br>\u2022 Cypher query support |\n",- "| **`triplet_store`** | **RDF Store**<br>Persists semantic triplets. | \u2022 SPARQL endpoints<br>\u2022 BlazeGraph, Jena, Virtuoso adapters |\n",+ "| **`embeddings`** | **Vector Embeddings**<br>Generates semantic vectors. | β’ Text & Graph embeddings<br>β’ Multi-provider support (OpenAI, etc.) |\n",+ "| **`vector_store`** | **Vector Database**<br>Stores and searches vectors. | β’ Similarity search & Filtering<br>β’ Hybrid search (Vector + Keyword) |\n",+ "| **`graph_store`** | **Property Graph Store**<br>Persists graph data. | β’ Neo4j, FalkorDB adapters<br>β’ Cypher query support |\n",+ "| **`triplet_store`** | **RDF Store**<br>Persists semantic triplets. | β’ SPARQL endpoints<br>β’ BlazeGraph, Jena, Virtuoso adapters |\n","\n",- "### \ud83d\udd0e Reasoning & Analysis\n",+ "### π Reasoning & Analysis\n","Modules for deriving new knowledge and evaluating quality.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`reasoning`** | **Inference Engine**<br>Derives new facts via rules. | \u2022 Datalog/Rule-based inference<br>\u2022 Forward/Backward chaining |\n",- "| **`ontology`** | **Ontology Management**<br>Manages schema and definitions. | \u2022 Ontology generation from data<br>\u2022 Validation & Evolution |\n",- "| **`visualization`** | **Visual Analytics**<br>Visualizes graphs and metrics. | \u2022 2D/3D Graph visualization<br>\u2022 Interactive plots & dashboards |\n",- "| **`evals`** | **Evaluation**<br>Benchmarks pipeline quality. | \u2022 RAG & Graph quality metrics<br>\u2022 Ground truth comparison |\n",+ "| **`reasoning`** | **Reasoner Facade**<br>Unified interface for inference. | β’ Datalog/Rule-based inference<br>β’ Forward/Backward chaining |\n",+ "| **`ontology`** | **Ontology Management**<br>Manages schema and definitions. | β’ Ontology generation from data<br>β’ Validation & Evolution |\n",+ "| **`visualization`** | **Visual Analytics**<br>Visualizes graphs and metrics. | β’ 2D/3D Graph visualization<br>β’ Interactive plots & dashboards |\n",+ "| **`evals`** | **Evaluation**<br>Benchmarks pipeline quality. | β’ RAG & Graph quality metrics<br>β’ Ground truth comparison |\n","\n",- "### \ud83d\udee0\ufe0f Orchestration & Utils\n",+ "### π οΈ Orchestration & Utils\n","Modules for managing the framework and workflows.\n","\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`core`** | **Framework Core**<br>Main entry point and config. | \u2022 Lifecycle management<br>\u2022 Plugin system & Configuration |\n",- "| **`pipeline`** | **Workflow Orchestration**<br>Manages complex flows. | \u2022 DAG execution & Retries<br>\u2022 Error handling & Observability |\n",- "| **`seed`** | **Data Seeding**<br>Initializes knowledge bases. | \u2022 Taxonomy & Ontology seeding<br>\u2022 Reference data loading |\n",- "| **`export`** | **Data Export**<br>Exports data to files. | \u2022 JSON, CSV, RDF, GEXF export<br>\u2022 Report generation |\n",- "| **`utils`** | **Utilities**<br>Common helper functions. | \u2022 Logging, Async, Hashing<br>\u2022 Text processing helpers |"+ "| **`core`** | **Framework Core**<br>Main entry point and config. | β’ Lifecycle management<br>β’ Plugin system & Configuration |\n",+ "| **`pipeline`** | **Workflow Orchestration**<br>Manages complex flows. | β’ DAG execution & Retries<br>β’ Error handling & Observability |\n",+ "| **`seed`** | **Data Seeding**<br>Initializes knowledge bases. | β’ Taxonomy & Ontology seeding<br>β’ Reference data loading |\n",+ "| **`export`** | **Data Export**<br>Exports data to files. | β’ JSON, CSV, RDF, GEXF export<br>β’ Report generation |\n",+ "| **`utils`** | **Utilities**<br>Common helper functions. | β’ Logging, Async, Hashing<br>β’ Text processing helpers |"]},{@@ -606,20 +200,23 @@"data": {"text/plain": ["'api_keys:\\n openai: your_key_here\\n anthropic: your_key_here\\nembedding:\\n provider: openai\\n model: text-embedding-3-large\\n dimensions: 3072\\nknowledge_graph:\\n backend: networkx\\n temporal: true\\n'"->>>>>>> Stashed changes]+ },+ "execution_count": 2,+ "metadata": {},+ "output_type": "execute_result"}- ],- "metadata": {- "language_info": {- "name": "python"- }+ ],+ "source": [+ "from semantica.core import Config\n",+ "config = Config()\n",+ "print(config.to_yaml())"+ ]},-<<<<<<< Updated upstream- "nbformat": 4,- "nbformat_minor": 2-=======-=======+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": ["# Welcome to Semantica\n","\n","**Open Source Framework for Semantic Layer & Knowledge Engineering**\n",@@ -975,7 +572,7 @@"\n","| Module | Description | Key Capabilities |\n","| :--- | :--- | :--- |\n",- "| **`reasoning`** | **Inference Engine**<br>Derives new facts via rules. | β’ Datalog/Rule-based inference<br>β’ Forward/Backward chaining |\n",+ "| **`reasoning`** | **Reasoner Facade**<br>Unified interface for inference. | β’ Datalog/Rule-based inference<br>β’ Forward/Backward chaining<br>β’ Automated explanation generation |\n","| **`ontology`** | **Ontology Management**<br>Manages schema and definitions. | β’ Ontology generation from data<br>β’ Validation & Evolution |\n","| **`visualization`** | **Visual Analytics**<br>Visualizes graphs and metrics. | β’ 2D/3D Graph visualization<br>β’ Interactive plots & dashboards |\n","| **`evals`** | **Evaluation**<br>Benchmarks pipeline quality. | β’ RAG & Graph quality metrics<br>β’ Ground truth comparison |\n",@@ -1124,7 +721,6 @@"print(f\"Created sample document at {text_path}\")"]},->>>>>>> main{"cell_type": "markdown","metadata": {},@@ -1158,11 +754,7 @@{"data": {"text/html": [-<<<<<<< HEAD- "<div style='font-family: monospace;'><h4>\ud83e\udde0 Semantica - \ud83d\udcca Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>\u2705</td><td>Semantica is building</td><td>\ud83e\udde0 kg</td><td>CommunityDetector</td><td>-</td><td>0.02s</td></tr><tr><td>\u2705</td><td>Semantica is indexing</td><td>\ud83d\udcca vector_store</td><td>VectorStore</td><td>-</td><td>0.00s</td></tr><tr><td>\u2705</td><td>Semantica is indexing</td><td>\ud83d\udcca vector_store</td><td>HybridSearch</td><td>-</td><td>3.15s</td></tr><tr><td>\u2705</td><td>Semantica is embedding</td><td>\ud83d\udcbe embeddings</td><td>TextEmbedder</td><td>-</td><td>0.02s</td></tr><tr><td>\u2705</td><td>Semantica is visualizing</td><td>\ud83d\udcc8 visualization</td><td>KGVisualizer</td><td>-</td><td>0.17s</td></tr><tr><td>\u2705</td><td>Semantica is generating</td><td>\ud83d\udcda ontology</td><td>OntologyGenerator</td><td>-</td><td>0.04s</td></tr><tr><td>\u2705</td><td>Semantica is generating</td><td>\ud83d\udcda ontology</td><td>ClassInferrer</td><td>-</td><td>0.01s</td></tr><tr><td>\u2705</td><td>Semantica is generating</td><td>\ud83d\udcda ontology</td><td>PropertyGenerator</td><td>-</td><td>0.01s</td></tr><tr><td>\u2705</td><td>Semantica is reasoning</td><td>\ud83e\udd14 reasoning</td><td>RuleManager</td><td>-</td><td>0.02s</td></tr><tr><td>\u2705</td><td>Semantica is reasoning</td><td>\ud83e\udd14 reasoning</td><td>InferenceEngine</td><td>-</td><td>0.01s</td></tr></table></div>"-=======- "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>CommunityDetector</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is indexing</td><td>π vector_store</td><td>VectorStore</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is indexing</td><td>π vector_store</td><td>HybridSearch</td><td>-</td><td>3.15s</td></tr><tr><td>β </td><td>Semantica is embedding</td><td>πΎ embeddings</td><td>TextEmbedder</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>KGVisualizer</td><td>-</td><td>0.17s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>OntologyGenerator</td><td>-</td><td>0.04s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>ClassInferrer</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>PropertyGenerator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>RuleManager</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>InferenceEngine</td><td>-</td><td>0.01s</td></tr></table></div>"->>>>>>> main+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is building</td><td>π§ kg</td><td>CommunityDetector</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is indexing</td><td>π vector_store</td><td>VectorStore</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is indexing</td><td>π vector_store</td><td>HybridSearch</td><td>-</td><td>3.15s</td></tr><tr><td>β </td><td>Semantica is embedding</td><td>πΎ embeddings</td><td>TextEmbedder</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>KGVisualizer</td><td>-</td><td>0.17s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>OntologyGenerator</td><td>-</td><td>0.04s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>ClassInferrer</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>PropertyGenerator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>Reasoner</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is reasoning</td><td>π€ reasoning</td><td>Reasoner</td><td>-</td><td>0.01s</td></tr></table></div>"],"text/plain": ["<IPython.core.display.HTML object>"@@ -2266,24 +1858,16 @@}],"source": [-<<<<<<< HEAD- "# # from semantica.reasoning import InferenceEngine\n",-=======- "from semantica.reasoning import InferenceEngine\n",->>>>>>> main+ "from semantica.reasoning import Reasoner\n","\n","# Simple rule: If X founded Y, then X works_for Y\n","rule = \"\"\"\n","IF (?x founded ?y) THEN (?x works_for ?y)\n","\"\"\"\n","\n",-<<<<<<< HEAD- "# # engine = InferenceEngine()\n",-=======- "engine = InferenceEngine()\n",->>>>>>> main- "engine.add_rule(rule)\n",- "inferred_facts = engine.infer(kg)\n",+ "reasoner = Reasoner()\n",+ "reasoner.add_rule(rule)\n",+ "inferred_facts = reasoner.infer_facts(kg)\n","\n","print(f\"Inferred {len(inferred_facts)} new facts\")"]@@ -2388,9 +1972,4 @@},"nbformat": 4,"nbformat_minor": 2-<<<<<<< HEAD->>>>>>> Stashed changes-}-=======}->>>>>>> maindiff --git a/cookbook/use_cases/USE_CASES_CATALOG.md b/cookbook/use_cases/USE_CASES_CATALOG.mdnew file mode 100644index 00000000..fc2b07ed--- /dev/null+++ b/cookbook/use_cases/USE_CASES_CATALOG.md@@ -0,0 +1,179 @@+# Semantica Domain Use Cases Catalog++This document provides a detailed overview of the various domain-specific use cases and pipelines implemented using the Semantica framework. These examples demonstrate how Semantica can be applied to complex real-world problems across different industries.++---++## **Biomedical**++### **1. Drug Discovery Pipeline**+- **Overview**: A complete drug discovery pipeline that ingests drug and protein data, extracts compound and target entities, builds a drug-target knowledge graph, and performs similarity search to predict interactions.+- **Key Features**: Compound-target extraction, similarity search, interaction prediction.+- **Pipeline**: `Drug/Protein Data Sources β Parse β Extract Entities β Build Drug-Target KG β Generate Embeddings β Similarity Search β Predict Interactions β Target Identification`.++### **2. Genomic Variant Analysis**+- **Overview**: Analyzes genomic data to extract variant entities, build genomic knowledge graphs, and analyze disease associations.+- **Key Features**: Variant impact prediction, disease association analysis, pathway analysis.+- **Pipeline**: `Genomic Data Sources β Parse β Extract Entities β Build Genomic KG β Analyze Associations β Predict Impact β Pathway Analysis`.++---++## **Blockchain**++### **1. DeFi Protocol Intelligence**+- **Overview**: Ingests DeFi data to extract protocol entities, build DeFi knowledge graphs, and assess risks or optimize yields.+- **Key Features**: Protocol risk assessment, yield optimization, relationship analysis.+- **Pipeline**: `DeFi Data Sources β Parse β Extract Entities β Build DeFi KG β Analyze Relationships β Risk Assessment β Yield Optimization`.++### **2. Transaction Network Analysis**+- **Overview**: Analyzes blockchain transaction networks to detect patterns, identify whale movements, and analyze token flows.+- **Key Features**: Transaction pattern detection, whale tracking, flow analysis.++---++## **Cybersecurity**++### **1. Real-Time Anomaly Detection**+- **Overview**: Streams security logs in real-time to build temporal knowledge graphs and detect anomalies using pattern detection.+- **Key Features**: Real-time log parsing, temporal pattern detection, automated alerting.+- **Pipeline**: `Stream Security Logs β Real-Time Parsing β Extract Entities β Build Temporal KG β Pattern Detection β Anomaly Detection`.++### **2. Incident Analysis**+- **Overview**: Processes security logs to build knowledge graphs and analyze relationships for forensic incident investigation.+- **Key Features**: Relationship analysis, anomaly detection, automated report generation.++### **3. Threat Correlation**+- **Overview**: Correlates threat feeds from multiple sources to build a temporal KG and detect coordinated campaigns.+- **Key Features**: IOC extraction, campaign detection, multi-source correlation.++### **4. Threat Intelligence Hybrid RAG**+- **Overview**: Combines vector search with temporal knowledge graphs for advanced threat intelligence querying.+- **Key Features**: Vector + KG hybrid search, context-aware retrieval.++### **5. Vulnerability Tracking**+- **Overview**: Ingests CVE data (NVD, feeds) to build a temporal KG and correlate vulnerabilities with organizational assets.+- **Key Features**: Impact prediction, CVE correlation, vulnerability reporting.++---++## **Finance**++### **1. Financial Data Integration (MCP)**+- **Overview**: Integrates Python/FastMCP servers to ingest market data, stock prices, and metrics into a financial knowledge graph.+- **Key Features**: MCP integration, multi-source financial ingestion.++### **2. Financial Reports Analysis**+- **Overview**: Parses SEC filings and annual reports to extract financial entities and generate automated insights.+- **Key Features**: SEC filing ingestion, entity relationship analysis, insight generation.++### **3. Fraud Detection**+- **Overview**: Analyzes transaction streams using temporal knowledge graphs to detect fraud patterns and anomalies.+- **Key Features**: Transaction pattern detection, anomaly detection, real-time alerts.++### **4. Investment Analysis Hybrid RAG**+- **Overview**: Uses advanced RAG to query investment insights across market data APIs and financial feeds.+- **Key Features**: Hybrid search, investment trend analysis.++### **5. Regulatory Compliance**+- **Overview**: Extracts compliance rules from regulatory documents (SEC, FINRA) to validate data against compliance ontologies.+- **Key Features**: Compliance rule extraction, automated validation, compliance reporting.++---++## **Healthcare**++### **1. Clinical Reports Processing**+- **Overview**: Processes EHR systems and HL7/FHIR APIs to build patient knowledge graphs and store them in triplet stores.+- **Key Features**: EHR integration, medical entity extraction, triplet store storage.++### **2. Disease Network Analysis**+- **Overview**: Builds disease ontologies from medical literature to analyze networks and predict outcomes.+- **Key Features**: Disease relationship extraction, network analysis, outcome prediction.++### **3. Drug Interactions Analysis**+- **Overview**: Analyzes FDA databases and medical literature to detect drug-drug and drug-condition interactions.+- **Key Features**: Interaction detection, safety ontology generation, drug knowledge graph.++### **4. Healthcare GraphRAG Hybrid**+- **Overview**: A specialized GraphRAG system that leverages medical ontologies and patient-level data for explainable healthcare queries.+- **Key Features**: Explainable AI, hybrid KG/patient data retrieval.++### **5. Medical Database Integration (MCP)**+- **Overview**: Uses MCP servers to ingest patient records and clinical data into a centralized healthcare KG.+- **Key Features**: MCP-based clinical ingestion, entity resolution.++### **6. Patient Records Temporal Analysis**+- **Overview**: Builds temporal knowledge graphs from patient history to query medical timelines and generate insights.+- **Key Features**: Medical history querying, temporal trend analysis.++---++## **Intelligence & Law Enforcement**++### **1. Criminal Network Analysis**+- **Overview**: Processes police reports and court records to build knowledge graphs for analyzing criminal networks and relationships.+- **Key Features**: Relationship analysis, network centrality, intelligence reporting.++### **2. Intelligence Analysis (Orchestrator-Worker)**+- **Overview**: Uses the Orchestrator-Worker pattern to coordinate parallel processing of OSINT feeds, threat intelligence, and geospatial data.+- **Key Features**: Parallel processing, multi-source intelligence, hybrid RAG.++### **3. Law Enforcement Forensics**+- **Overview**: An agent-based workflow for processing case files, evidence logs, and witness statements for forensic analysis.+- **Key Features**: Agent-based evidence correlation, temporal forensic timelines.++---++## **Renewable Energy**++### **1. Energy Market Analysis**+- **Overview**: Analyzes pricing trends and market movements using temporal market knowledge graphs.+- **Key Features**: Market trend prediction, energy entity extraction.++### **2. Environmental Impact Analysis**+- **Overview**: Processes EPA and climate databases to assess environmental impact through relationship analysis in a KG.+- **Key Features**: Climate data ingestion, impact assessment.++### **3. Smart Grid Management**+- **Overview**: Streams grid sensor data to monitor grid health and predict failures using temporal pattern detection.+- **Key Features**: Real-time monitoring, failure prediction, anomaly detection.++### **4. Resource Optimization**+- **Overview**: Analyzes efficiency metrics to optimize resource allocation across energy monitoring systems.+- **Key Features**: Efficiency analysis, resource allocation optimization.++---++## **Supply Chain**++### **1. Supply Chain Data Integration**+- **Overview**: Ingests logistics and supplier data to build a comprehensive supply chain knowledge graph.+- **Key Features**: Logistics tracking, supplier relationship mapping.++### **2. Supply Chain Risk Management**+- **Overview**: Detects risks in the supply chain by analyzing dependencies and external feeds.+- **Key Features**: Risk detection, dependency analysis.++---++## **Trading**++### **1. Market Data Analysis**+- **Overview**: Analyzes high-frequency market data to detect trading patterns and signals.+- **Key Features**: Signal detection, pattern analysis.++### **2. News Sentiment Analysis**+- **Overview**: Correlates news sentiment with price movements using a financial knowledge graph.+- **Key Features**: Sentiment extraction, price correlation.++### **3. Real-Time Monitoring**+- **Overview**: Monitors trading activities and market conditions in real-time.+- **Key Features**: Real-time alerts, market condition tracking.++### **4. Risk Assessment**+- **Overview**: Assesses portfolio risk using graph-based analytics and market simulations.+- **Key Features**: Portfolio risk analysis, market simulation.++### **5. Strategy Backtesting**+- **Overview**: Uses historical knowledge graphs to backtest trading strategies.+- **Key Features**: Historical simulation, strategy evaluation.diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynbindex d33e4ed6..0059b45b 100644--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb@@ -23,7 +23,6 @@"- **Complete Pipeline**: From data ingestion to LLM-powered question answering\n","- **Hybrid Retrieval**: Combines vector similarity search with knowledge graph traversal\n","- **Multi-hop Reasoning**: Follows relationships across the graph for deeper context\n",- "- **20+ Semantica Modules**: Demonstrates comprehensive use of the framework\n","\n","### What You'll Learn\n","\n",@@ -855,16 +854,6 @@"All extraction results are stored in the `combined_results` dictionary.\n"]},- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# This cell is now part of the extraction loop in the previous cell\n",- "# The extraction process runs all four steps (NER, Relations, Triplets, Events) for each chunk\n"- ]- },{"cell_type": "markdown","metadata": {},@@ -879,41 +868,6 @@"- **Events**: Temporal occurrences with participants\n"]},- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# This cell is now part of the extraction loop in cell 41\n",- "# All extraction steps run together for efficiency\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Error Handling\n",- "\n",- "Each extraction step includes try-except blocks to handle:\n",- "- API rate limits\n",- "- Network errors\n",- "- Parsing errors\n",- "- Invalid responses\n",- "\n",- "This ensures the pipeline continues even if individual extractions fail.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# This cell is now part of the extraction loop in cell 41\n",- "# The complete extraction process is in the previous cell\n"- ]- },{"cell_type": "markdown","metadata": {},@@ -973,15 +927,6 @@"Entity resolution merges duplicate entities (e.g., \"Retinol\" and \"retinol\") to improve graph quality.\n"]},- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Knowledge graph imports will be added in cells where they're first used\n"- ]- },{"cell_type": "markdown","metadata": {},@@ -1601,15 +1546,6 @@"- **CSV**: Tabular format for analysis\n"]},- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Visualization and export imports will be added in cells where they're used\n"- ]- },{"cell_type": "markdown","metadata": {},@@ -1757,33 +1693,6 @@"- Explore advanced features like temporal reasoning and conflict resolution\n","- Integrate with persistent graph stores (Neo4j, ArangoDB) for production use\n"]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Phase 2: Document Processing & Chunking\n",- "\n",- "Split documents into semantic chunks for processing.\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Phase 5: Vector Store Population\n",- "\n",- "Generate embeddings and populate the vector store for hybrid retrieval.\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Phase 7: Visualization & Export\n",- "\n",- "Visualize the knowledge graph and export it in various formats.\n"- ]}],"metadata": {diff --git a/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb b/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynbindex 36ed2d6f..5c6c530a 100644--- a/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb+++ b/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb@@ -113,7 +113,6 @@"outputs": [],"source": ["from semantica.ingest import WebIngestor, FeedIngestor\n",- "from semantica.normalize import TextNormalizer\n","from semantica.split import EntityAwareChunker\n","\n","normalizer = TextNormalizer()\n",@@ -240,6 +239,7 @@"metadata": {},"outputs": [],"source": [+ "from semantica.normalize import TextNormalizer\n","# Normalize all ingested content\n","print(\"Normalizing content...\")\n","clean_docs = []\n",@@ -959,78 +959,6 @@" print(f\" - Relationships: {len(kg_data.get('relationships', []))}\")\n"]},- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## 7. Performance & Quality Metrics Comparison\n",- "\n",- "Compare retrieval quality and demonstrate reasoning capabilities.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import pandas for comparison table\n",- "import pandas as pd\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "### Create Comparison Table\n",- "\n",- "Create a side-by-side comparison of Vector RAG vs GraphRAG capabilities.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Create comparison data\n",- "comparison_data = {\n",- " \"Metric\": [\n",- " \"Retrieval Method\",\n",- " \"Multi-hop Reasoning\",\n",- " \"Entity Connections\",\n",- " \"Relationship Traversal\",\n",- " \"Context Expansion\",\n",- " \"Semantic Gap Handling\"\n",- " ],\n",- " \"Vector RAG\": [\n",- " \"Semantic similarity only\",\n",- " \"No\",\n",- " \"No\",\n",- " \"No\",\n",- " \"Limited\",\n",- " \"Fails on disconnected facts\"\n",- " ],\n",- " \"GraphRAG\": [\n",- " \"Hybrid (Vector + Graph)\",\n",- " \"Yes (configurable hops)\",\n",- " \"Yes (graph traversal)\",\n",- " \"Yes (relationship following)\",\n",- " \"Yes (graph expansion)\",\n",- " \"Bridges semantic gaps\"\n",- " ]\n",- "}\n",- "\n",- "# Create DataFrame\n",- "df_comparison = pd.DataFrame(comparison_data)\n",- "\n",- "# Display comparison\n",- "print(\"RAG vs GraphRAG Comparison\")\n",- "print(\"=\" * 80)\n",- "print(df_comparison.to_string(index=False))\n",- "print(\"\\n\" + \"=\" * 80)\n"- ]- },{"cell_type": "markdown","metadata": {},diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynbdeleted file mode 100644index 20dcacbe..00000000--- a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb+++ /dev/null@@ -1,796 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb)\n",- "\n",- "# Drug Discovery Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete drug discovery pipeline: ingest drug and protein data from multiple sources (APIs, databases, feeds), extract compound and target entities, build drug-target knowledge graph, generate embeddings, perform similarity search, predict drug-target interactions, and identify targets.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Ontology**: OntologyGenerator, OntologyValidator\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Ontology**: OntologyGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator\n",->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Drug/Protein Data Sources (APIs, DB, Feeds, MCP) \u2192 Parse \u2192 Extract Entities (compounds, targets, interactions) \u2192 Build Drug-Target KG \u2192 Generate Embeddings \u2192 Similarity Search \u2192 Predict Interactions \u2192 Target Identification \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Drug and Protein Data from Multiple Sources\n",- "\n",- "Ingest drug compound and protein target data from APIs, databases, and feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor, MCPIngestor, ingest_mcp\n",- "from semantica.parse import JSONParser, StructuredDataParser, DocumentParser, MCPParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "from semantica.ontology import OntologyGenerator, OntologyValidator\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.ontology import OntologyGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.ontology import OntologyGenerator\n",->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "file_ingestor = FileIngestor()\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "mcp_parser = MCPParser()\n",- "\n",- "# Real drug APIs\n",- "drug_apis = [\n",- " \"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/2244/JSON\", # PubChem API\n",- " \"https://www.ebi.ac.uk/chembl/api/data/molecule/CHEMBL25.json\", # ChEMBL API\n",- " \"https://go.drugbank.com/releases/latest\" # DrugBank API\n",- "]\n",- "\n",- "# Real protein APIs\n",- "protein_apis = [\n",- " \"https://www.uniprot.org/uniprot/P04637.json\", # UniProt API\n",- " \"https://www.rcsb.org/pdb/json/descriptors/1A2B\" # PDB API\n",- "]\n",- "\n",- "# Real interaction databases\n",- "interaction_databases = [\n",- " \"STRING\",\n",- " \"BioGRID\"\n",- "]\n",- "\n",- "# Real database connection for compound libraries\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/drug_discovery_db\"\n",- "db_query = \"SELECT compound_id, target_protein, interaction_type, binding_affinity, mechanism FROM drug_target_interactions WHERE binding_affinity < 100 LIMIT 1000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample drug-target data for local ingestion\n",- "drug_data_file = os.path.join(temp_dir, \"drug_targets.json\")\n",- "drug_data = [\n",- " {\n",- " \"compound_id\": \"CID2244\",\n",- " \"compound_name\": \"Aspirin\",\n",- " \"target_protein\": \"PTGS1\",\n",- " \"target_name\": \"Prostaglandin G/H synthase 1\",\n",- " \"interaction_type\": \"inhibitor\",\n",- " \"binding_affinity\": 5.2,\n",- " \"mechanism\": \"Irreversible inhibition\",\n",- " \"pathway\": \"Arachidonic acid metabolism\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " },\n",- " {\n",- " \"compound_id\": \"CID1983\",\n",- " \"compound_name\": \"Ibuprofen\",\n",- " \"target_protein\": \"PTGS2\",\n",- " \"target_name\": \"Prostaglandin G/H synthase 2\",\n",- " \"interaction_type\": \"inhibitor\",\n",- " \"binding_affinity\": 8.5,\n",- " \"mechanism\": \"Reversible inhibition\",\n",- " \"pathway\": \"Arachidonic acid metabolism\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=2)).isoformat()\n",- " },\n",- " {\n",- " \"compound_id\": \"CID1983\",\n",- " \"compound_name\": \"Ibuprofen\",\n",- " \"target_protein\": \"PTGS1\",\n",- " \"target_name\": \"Prostaglandin G/H synthase 1\",\n",- " \"interaction_type\": \"inhibitor\",\n",- " \"binding_affinity\": 12.3,\n",- " \"mechanism\": \"Reversible inhibition\",\n",- " \"pathway\": \"Arachidonic acid metabolism\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=2)).isoformat()\n",- " },\n",- " {\n",- " \"compound_id\": \"CID60823\",\n",- " \"compound_name\": \"Atorvastatin\",\n",- " \"target_protein\": \"HMGCR\",\n",- " \"target_name\": \"3-hydroxy-3-methylglutaryl-coenzyme A reductase\",\n",- " \"interaction_type\": \"inhibitor\",\n",- " \"binding_affinity\": 0.8,\n",- " \"mechanism\": \"Competitive inhibition\",\n",- " \"pathway\": \"Cholesterol biosynthesis\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=3)).isoformat()\n",- " },\n",- " {\n",- " \"compound_id\": \"CID54686970\",\n",- " \"compound_name\": \"Metformin\",\n",- " \"target_protein\": \"PRKAA1\",\n",- " \"target_name\": \"5'-AMP-activated protein kinase catalytic subunit alpha-1\",\n",- " \"interaction_type\": \"activator\",\n",- " \"binding_affinity\": 15.0,\n",- " \"mechanism\": \"Allosteric activation\",\n",- " \"pathway\": \"AMPK signaling\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=4)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(drug_data_file, 'w') as f:\n",- " json.dump(drug_data, f, indent=2)\n",- "\n",- "# Ingest from local file\n",- "file_data = file_ingestor.ingest_file(drug_data_file)\n",- "parsed_drug = structured_parser.parse_json(json.dumps(drug_data))\n",- "\n",- "# Ingest from drug APIs (example with public API)\n",- "web_content = web_ingestor.ingest_url(drug_apis[0]) # PubChem API\n",- "if web_content:\n",- " print(f\" Ingested drug API: {drug_apis[0]}\")\n",- "\n",- "# Database ingestion pattern\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"drug_target_interactions\",\n",- " limit=1000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "\n",- "# Optional: Ingest from MCP server\n",- "# Users can bring their own drug/protein database MCP server via URL\n",- "mcp_drug_data = []\n",- "# Connect to biomedical database MCP server via URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/biomedical-mcp\n",- "biomedical_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",- "\n",- "mcp_ingestor.connect(\n",- " \"biomedical_mcp_server\",\n",- " url=biomedical_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in biomedical_mcp_url else {}\n",- ")\n",- "\n",- "# Ingest drug-target interactions from MCP server\n",- "mcp_data = mcp_ingestor.ingest_resources(\n",- " \"biomedical_mcp_server\",\n",- " resource_uris=[\"resource://drugs/interactions\", \"resource://proteins/targets\"]\n",- ")\n",- "mcp_drug_data.extend(mcp_data)\n",- "print(f\" Ingested {len(mcp_data)} MCP resources\")\n",- "\n",- "# Or use tool-based ingestion to query drug interactions\n",- "tool_data = mcp_ingestor.ingest_tool_output(\n",- " \"biomedical_mcp_server\",\n",- " tool_name=\"query_drug_interactions\",\n",- " arguments={\n",- " \"compound_id\": \"CID2244\",\n",- " \"target_protein\": \"PTGS1\"\n",- " }\n",- ")\n",- "if tool_data:\n",- " mcp_drug_data.append(tool_data)\n",- " print(f\" Retrieved tool data\")\n",- "\n",- "# Parse MCP responses and merge with existing drug data\n",- "for mcp_item in mcp_drug_data:\n",- " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",- " if isinstance(parsed_mcp, dict):\n",- " if \"drug_targets\" in parsed_mcp or \"interactions\" in parsed_mcp:\n",- " # Merge drug-target interactions from MCP\n",- " mcp_interactions = parsed_mcp.get(\"drug_targets\", parsed_mcp.get(\"interactions\", []))\n",- " drug_data.extend(mcp_interactions)\n",- " elif \"compound_id\" in parsed_mcp:\n",- " # Single drug-target interaction\n",- " drug_data.append(parsed_mcp)\n",- " print(f\" Parsed MCP item\")\n",- "\n",- "mcp_ingestor.disconnect(\"biomedical_mcp_server\")\n",- "print(f\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Local drug-target interactions: {len(drug_data)}\")\n",- "print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",- "print(f\" Drug APIs: {len(drug_apis)}\")\n",- "print(f\" Protein APIs: {len(protein_apis)}\")\n",- "print(f\" MCP server sources: {len(mcp_drug_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Drug and Target Entities\n",- "\n",- "Extract compounds, targets, and interactions from the ingested data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "all_drug_texts = []\n",- "all_interactions = []\n",- "\n",- "# Process parsed drug data\n",- "if parsed_drug and isinstance(parsed_drug, dict):\n",- " interactions = parsed_drug.get(\"data\", drug_data)\n",- " for interaction in interactions:\n",- " all_interactions.append(interaction)\n",- " interaction_text = f\"Compound {interaction.get('compound_name', '')} {interaction.get('interaction_type', '')} target {interaction.get('target_name', '')} with binding affinity {interaction.get('binding_affinity', 0)}\"\n",- " all_drug_texts.append(interaction_text)\n",- "\n",- "# Extract entities\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_triplets = []\n",- "\n",- "for text in all_drug_texts:\n",- " entities = ner_extractor.extract(text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " triplets = triplet_extractor.extract(text)\n",- " all_triplets.extend(triplets)\n",- "\n",- "# Build structured entity list\n",- "compound_entities = []\n",- "target_entities = []\n",- "interaction_entities = []\n",- "\n",- "unique_compounds = {}\n",- "unique_targets = {}\n",- "\n",- "for interaction in all_interactions:\n",- " compound_id = interaction.get(\"compound_id\", \"\")\n",- " compound_name = interaction.get(\"compound_name\", \"\")\n",- " \n",- " if compound_id and compound_id not in unique_compounds:\n",- " compound_entity = {\n",- " \"id\": compound_id,\n",- " \"type\": \"Compound\",\n",- " \"properties\": {\n",- " \"compound_id\": compound_id,\n",- " \"name\": compound_name,\n",- " \"pathway\": interaction.get(\"pathway\", \"\")\n",- " }\n",- " }\n",- " compound_entities.append(compound_entity)\n",- " unique_compounds[compound_id] = compound_entity\n",- " \n",- " target_id = interaction.get(\"target_protein\", \"\")\n",- " target_name = interaction.get(\"target_name\", \"\")\n",- " \n",- " if target_id and target_id not in unique_targets:\n",- " target_entity = {\n",- " \"id\": target_id,\n",- " \"type\": \"Target\",\n",- " \"properties\": {\n",- " \"protein_id\": target_id,\n",- " \"name\": target_name,\n",- " \"pathway\": interaction.get(\"pathway\", \"\")\n",- " }\n",- " }\n",- " target_entities.append(target_entity)\n",- " unique_targets[target_id] = target_entity\n",- " \n",- " interaction_entity = {\n",- " \"id\": f\"{compound_id}_{target_id}\",\n",- " \"type\": \"Interaction\",\n",- " \"properties\": {\n",- " \"compound\": compound_id,\n",- " \"target\": target_id,\n",- " \"interaction_type\": interaction.get(\"interaction_type\", \"\"),\n",- " \"binding_affinity\": interaction.get(\"binding_affinity\", 0),\n",- " \"mechanism\": interaction.get(\"mechanism\", \"\"),\n",- " \"timestamp\": interaction.get(\"timestamp\", \"\")\n",- " }\n",- " }\n",- " interaction_entities.append(interaction_entity)\n",- "\n",- "print(f\"Extracted {len(compound_entities)} unique compounds\")\n",- "print(f\"Extracted {len(target_entities)} unique targets\")\n",- "print(f\"Extracted {len(interaction_entities)} interactions\")\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n",- "print(f\"Extracted {len(all_triplets)} triplets\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Drug-Target Knowledge Graph\n",- "\n",- "Build a knowledge graph from extracted drug-target entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "\n",- "# Add all entities\n",- "for compound in compound_entities:\n",- " builder.add_entity(\n",- " entity_id=compound[\"id\"],\n",- " entity_type=compound[\"type\"],\n",- " properties=compound.get(\"properties\", {})\n",- " )\n",- "\n",- "for target in target_entities:\n",- " builder.add_entity(\n",- " entity_id=target[\"id\"],\n",- " entity_type=target[\"type\"],\n",- " properties=target.get(\"properties\", {})\n",- " )\n",- "\n",- "for interaction in interaction_entities:\n",- " builder.add_entity(\n",- " entity_id=interaction[\"id\"],\n",- " entity_type=interaction[\"type\"],\n",- " properties=interaction.get(\"properties\", {})\n",- " )\n",- "\n",- "# Add relationships\n",- "relationships = []\n",- "for interaction in interaction_entities:\n",- " compound_id = interaction[\"properties\"].get(\"compound\", \"\")\n",- " target_id = interaction[\"properties\"].get(\"target\", \"\")\n",- " interaction_id = interaction[\"id\"]\n",- " interaction_type = interaction[\"properties\"].get(\"interaction_type\", \"\")\n",- " binding_affinity = interaction[\"properties\"].get(\"binding_affinity\", 0)\n",- " \n",- " # Compound-Target relationship\n",- " builder.add_relationship(\n",- " source_id=compound_id,\n",- " target_id=target_id,\n",- " relationship_type=interaction_type,\n",- " properties={\n",- " \"binding_affinity\": binding_affinity,\n",- " \"mechanism\": interaction[\"properties\"].get(\"mechanism\", \"\")\n",- " }\n",- " )\n",- " \n",- " # Interaction relationships\n",- " builder.add_relationship(\n",- " source_id=compound_id,\n",- " target_id=interaction_id,\n",- " relationship_type=\"has_interaction\",\n",- " properties={}\n",- " )\n",- " builder.add_relationship(\n",- " source_id=interaction_id,\n",- " target_id=target_id,\n",- " relationship_type=\"targets\",\n",- " properties={}\n",- " )\n",- " \n",- " relationships.append({\n",- " \"source\": compound_id,\n",- " \"target\": target_id,\n",- " \"type\": interaction_type,\n",- " \"binding_affinity\": binding_affinity\n",- " })\n",- "\n",- "knowledge_graph = builder.build()\n",- "\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.nodes)} nodes\")\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.edges)} edges\")\n",- "print(f\"Added {len(relationships)} drug-target relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Generate Embeddings and Setup Vector Store\n",- "\n",- "Generate embeddings from compound and target descriptions and setup vector store for similarity search.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "vector_store = VectorStore()\n",- "hybrid_search = HybridSearch(vector_store, knowledge_graph)\n",- "\n",- "# Generate embeddings for compounds\n",- "compound_texts = []\n",- "compound_metadata = []\n",- "for compound in compound_entities:\n",- " compound_text = f\"{compound['properties'].get('name', '')} pathway {compound['properties'].get('pathway', '')}\"\n",- " compound_texts.append(compound_text)\n",- " compound_metadata.append({\n",- " \"id\": compound[\"id\"],\n",- " \"type\": \"compound\",\n",- " \"name\": compound[\"properties\"].get(\"name\", \"\")\n",- " })\n",- "\n",- "# Generate embeddings for targets\n",- "target_texts = []\n",- "target_metadata = []\n",- "for target in target_entities:\n",- " target_text = f\"{target['properties'].get('name', '')} pathway {target['properties'].get('pathway', '')}\"\n",- " target_texts.append(target_text)\n",- " target_metadata.append({\n",- " \"id\": target[\"id\"],\n",- " \"type\": \"target\",\n",- " \"name\": target[\"properties\"].get(\"name\", \"\")\n",- " })\n",- "\n",- "# Generate embeddings\n",- "all_texts = compound_texts + target_texts\n",- "all_metadata = compound_metadata + target_metadata\n",- "\n",- "embeddings = []\n",- "for text in all_texts:\n",- " embedding = text_embedder.embed(text)\n",- " embeddings.append(embedding)\n",- "\n",- "# Store in vector store\n",- "vector_store.store_vectors(embeddings, all_metadata)\n",- "\n",- "print(f\"Generated {len(embeddings)} embeddings\")\n",- "print(f\"Stored {len(compound_texts)} compound embeddings\")\n",- "print(f\"Stored {len(target_texts)} target embeddings\")\n",- "print(f\"Vector store ready for similarity search\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Predict Drug-Target Interactions\n",- "\n",- "Use hybrid search and inference to predict drug-target interactions.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery(knowledge_graph)\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "\n",- "# Compute graph metrics\n",- "graph_metrics = graph_analyzer.compute_metrics(knowledge_graph)\n",- "\n",- "# Calculate centrality\n",- "centrality_result = centrality_calculator.calculate_betweenness_centrality(knowledge_graph)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "top_central_targets = sorted(centrality_scores.items(), key=lambda x: x[1], reverse=True)[:10]\n",- "\n",- "# Detect communities\n",- "communities_result = community_detector.detect_communities(knowledge_graph, algorithm=\"louvain\")\n",- "communities = communities_result.get('communities', [])\n",- "community_count = len(communities) if communities else 0\n",- "\n",- "# Analyze connectivity\n",- "connectivity_results = connectivity_analyzer.analyze_connectivity(knowledge_graph)\n",- "\n",- "# Define interaction prediction rules\n",- "prediction_rules = [\n",- " {\n",- " \"name\": \"high_affinity_interaction\",\n",- " \"condition\": \"binding_affinity < 10\",\n",- " \"action\": \"predict_strong_interaction\"\n",- " },\n",- " {\n",- " \"name\": \"inhibitor_interaction\",\n",- " \"condition\": \"interaction_type == 'inhibitor' AND binding_affinity < 5\",\n",- " \"action\": \"predict_potent_inhibitor\"\n",- " },\n",- " {\n",- " \"name\": \"target_identification\",\n",- " \"condition\": \"multiple_compounds_target_same_protein\",\n",- " \"action\": \"identify_druggable_target\"\n",- " }\n",- "]\n",- "\n",- "for rule in prediction_rules:\n",- " rule_manager.add_rule(rule[\"name\"], rule[\"condition\"], rule[\"action\"])\n",- "\n",- "# Predict interactions using similarity search\n",- "query_compound = \"Aspirin\"\n",- "query_embedding = text_embedder.embed(query_compound)\n",- "\n",- "# Hybrid search\n",- "search_results = hybrid_search.search(\n",- " query_embedding=query_embedding,\n",- " query_text=query_compound,\n",- " k=5,\n",- " use_graph_expansion=True\n",- ")\n",- "\n",- "# Predict interactions\n",- "predicted_interactions = []\n",- "for compound in compound_entities:\n",- " compound_id = compound[\"id\"]\n",- " compound_name = compound[\"properties\"].get(\"name\", \"\")\n",- " \n",- " # Find interactions for this compound\n",- " compound_interactions = [r for r in relationships if r[\"source\"] == compound_id]\n",- " \n",- " # Calculate interaction score\n",- " interaction_score = 0\n",- " for interaction in compound_interactions:\n",- " binding_affinity = interaction.get(\"binding_affinity\", 100)\n",- " if binding_affinity < 10:\n",- " interaction_score += 3\n",- " elif binding_affinity < 50:\n",- " interaction_score += 2\n",- " else:\n",- " interaction_score += 1\n",- " \n",- " predicted_interactions.append({\n",- " \"compound\": compound_name,\n",- " \"compound_id\": compound_id,\n",- " \"interaction_count\": len(compound_interactions),\n",- " \"interaction_score\": interaction_score,\n",- " \"targets\": [r[\"target\"] for r in compound_interactions]\n",- " })\n",- "\n",- "# Identify druggable targets\n",- "target_interaction_counts = {}\n",- "for rel in relationships:\n",- " target = rel[\"target\"]\n",- " target_interaction_counts[target] = target_interaction_counts.get(target, 0) + 1\n",- "\n",- "druggable_targets = []\n",- "for target_id, count in target_interaction_counts.items():\n",- " if count >= 2:\n",- " target_name = next((t[\"properties\"].get(\"name\", target_id) for t in target_entities if t[\"id\"] == target_id), target_id)\n",- " druggable_targets.append({\n",- " \"target\": target_name,\n",- " \"target_id\": target_id,\n",- " \"compound_count\": count,\n",- " \"description\": f\"Target {target_name} is targeted by {count} compounds, indicating druggability\"\n",- " })\n",- "\n",- "print(f\"Analyzed {len(compound_entities)} compounds\")\n",- "print(f\"Found {community_count} target communities\")\n",- "print(f\"Identified {len(druggable_targets)} druggable targets\")\n",- "print(f\"\\nTop 5 Central Targets:\")\n",- "for i, (target_id, centrality) in enumerate(top_central_targets[:5], 1):\n",- " target_name = next((t[\"properties\"].get(\"name\", target_id) for t in target_entities if t[\"id\"] == target_id), target_id)\n",- " print(f\" {i}. {target_name} (centrality: {centrality:.3f})\")\n",- "print(f\"\\nPredicted Interactions:\")\n",- "for pred in sorted(predicted_interactions, key=lambda x: x[\"interaction_score\"], reverse=True)[:5]:\n",- " print(f\" - {pred['compound']}: {pred['interaction_count']} interactions, Score: {pred['interaction_score']}\")\n",- "print(f\"\\nDruggable Targets:\")\n",- "for target in druggable_targets[:5]:\n",- " print(f\" - {target['target']}: {target['compound_count']} compounds\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_generator = OntologyGenerator()\n",- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Generate drug discovery ontology\n",- "drug_ontology = ontology_generator.generate_ontology(\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",- "# Export knowledge graph\n",- "kg_json = json_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"drug_target_kg.json\"))\n",- "kg_rdf = rdf_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"drug_target_kg.rdf\"))\n",- "\n",- "# Export ontology\n",- "ontology_owl = owl_exporter.export(drug_ontology, output_path=os.path.join(temp_dir, \"drug_ontology.owl\"))\n",- "\n",- "# Generate report\n",- "report_content = f\"\"\"\n",- "# Drug Discovery Pipeline Report\n",- "\n",- "## Executive Summary\n",- "- Total Compounds Analyzed: {len(compound_entities)}\n",- "- Total Targets: {len(target_entities)}\n",- "- Total Interactions: {len(interaction_entities)}\n",- "- Druggable Targets Identified: {len(druggable_targets)}\n",- "- High-Affinity Interactions: {len([r for r in relationships if r.get('binding_affinity', 100) < 10])}\n",- "\n",- "## Top Druggable Targets\n",- "\"\"\"\n",- "for i, target in enumerate(druggable_targets[:10], 1):\n",- " report_content += f\"\"\"\n",- "{i}. {target['target']}\n",- " - Compound Count: {target['compound_count']}\n",- " - Description: {target['description']}\n",- "\"\"\"\n",- "\n",- "report_content += f\"\"\"\n",- "## Predicted Interactions\n",- "\"\"\"\n",- "for pred in sorted(predicted_interactions, key=lambda x: x[\"interaction_score\"], reverse=True)[:10]:\n",- " report_content += f\"\"\"\n",- "### {pred['compound']}\n",- "- Interaction Count: {pred['interaction_count']}\n",- "- Interaction Score: {pred['interaction_score']}\n",- "- Targets: {', '.join(pred['targets'][:5])}\n",- "\"\"\"\n",- "\n",- "report_path = os.path.join(temp_dir, \"drug_discovery_report.md\")\n",- "with open(report_path, 'w') as f:\n",- " f.write(report_content)\n",- "\n",- "print(f\"Generated drug discovery ontology with {len(drug_ontology.get('classes', []))} classes\")\n",- "print(f\"Exported knowledge graph to JSON and RDF\")\n",- "print(f\"Exported ontology to OWL\")\n",- "print(f\"Generated discovery report: {report_path}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Visualize Drug-Target Network\n",- "\n",- "Visualize the drug-target knowledge graph, ontology, and analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "# Visualize knowledge graph\n",- "kg_viz = kg_visualizer.visualize(\n",- " knowledge_graph,\n",- " layout=\"force_directed\",\n",- " highlight_nodes=[t[\"id\"] for t in druggable_targets[:5]],\n",- " node_size_by=\"centrality\"\n",- ")\n",- "\n",- "# Visualize ontology\n",- "ontology_viz = ontology_visualizer.visualize(\n",- " drug_ontology,\n",- " layout=\"hierarchical\"\n",- ")\n",- "\n",- "# Visualize analytics\n",- "analytics_viz = analytics_visualizer.visualize(\n",- " knowledge_graph,\n",- " metrics={\n",- " \"centrality\": dict(top_central_targets[:10]),\n",- " \"communities\": communities,\n",- " \"connectivity\": connectivity_results,\n",- " \"interaction_scores\": {p[\"compound_id\"]: p[\"interaction_score\"] for p in predicted_interactions}\n",- " }\n",- ")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynbdeleted file mode 100644index 42a3b220..00000000--- a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb+++ /dev/null@@ -1,808 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb)\n",- "\n",- "# Genomic Variant Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete genomic variant analysis pipeline: ingest genomic data from multiple sources (APIs, databases, feeds), extract variant entities, build genomic knowledge graph, analyze disease associations, predict variant impact, and perform pathway analysis.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Genomic Data Sources \u2192 Parse \u2192 Extract Entities (variants, genes, diseases, pathways) \u2192 Build Genomic KG \u2192 Analyze Associations \u2192 Predict Impact \u2192 Pathway Analysis \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Genomic Data from Multiple Sources\n",- "\n",- "Ingest genomic variant data from APIs, databases, and research feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, DBIngestor, FeedIngestor, FileIngestor\n",- "from semantica.parse import JSONParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "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.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "# Real genomic APIs\n",- "genomic_apis = [\n",- " \"https://rest.ensembl.org/variation/human/rs699\", # Ensembl API\n",- " \"https://api.ncbi.nlm.nih.gov/variation/v0/variant/NC_000001.10:g.230710048A%3EG\", # NCBI Variation API\n",- " \"https://api.ncbi.nlm.nih.gov/variation/v0/beta/refsnp/699\" # ClinVar API\n",- "]\n",- "\n",- "# Real genomic databases\n",- "genomic_databases = [\n",- " \"dbSNP\",\n",- " \"ClinVar\",\n",- " \"COSMIC\"\n",- "]\n",- "\n",- "# Real research feeds\n",- "genomic_feeds = [\n",- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search?term=genomic+variants\",\n",- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search?term=genetic+variation\"\n",- "]\n",- "\n",- "# Real database connection for variant annotations\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/genomic_db\"\n",- "db_query = \"SELECT variant_id, gene_symbol, disease_name, clinical_significance, chromosome, position FROM variants WHERE clinical_significance IN ('Pathogenic', 'Likely Pathogenic') LIMIT 1000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample genomic variant data for local ingestion\n",- "genomic_data_file = os.path.join(temp_dir, \"genomic_variants.json\")\n",- "genomic_data = [\n",- " {\n",- " \"variant_id\": \"rs699\",\n",- " \"gene_symbol\": \"AGT\",\n",- " \"gene_name\": \"Angiotensinogen\",\n",- " \"disease_name\": \"Hypertension\",\n",- " \"clinical_significance\": \"Pathogenic\",\n",- " \"chromosome\": \"1\",\n",- " \"position\": 230710048,\n",- " \"ref_allele\": \"A\",\n",- " \"alt_allele\": \"G\",\n",- " \"pathway\": \"Renin-angiotensin system\",\n",- " \"impact\": \"High\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " },\n",- " {\n",- " \"variant_id\": \"rs7412\",\n",- " \"gene_symbol\": \"APOE\",\n",- " \"gene_name\": \"Apolipoprotein E\",\n",- " \"disease_name\": \"Alzheimer's Disease\",\n",- " \"clinical_significance\": \"Pathogenic\",\n",- " \"chromosome\": \"19\",\n",- " \"position\": 44908822,\n",- " \"ref_allele\": \"C\",\n",- " \"alt_allele\": \"T\",\n",- " \"pathway\": \"Lipid metabolism\",\n",- " \"impact\": \"High\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=2)).isoformat()\n",- " },\n",- " {\n",- " \"variant_id\": \"rs1800566\",\n",- " \"gene_symbol\": \"NAT2\",\n",- " \"gene_name\": \"N-acetyltransferase 2\",\n",- " \"disease_name\": \"Drug Metabolism\",\n",- " \"clinical_significance\": \"Likely Pathogenic\",\n",- " \"chromosome\": \"8\",\n",- " \"position\": 18248728,\n",- " \"ref_allele\": \"G\",\n",- " \"alt_allele\": \"A\",\n",- " \"pathway\": \"Drug metabolism\",\n",- " \"impact\": \"Moderate\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=3)).isoformat()\n",- " },\n",- " {\n",- " \"variant_id\": \"rs1799853\",\n",- " \"gene_symbol\": \"CYP2C9\",\n",- " \"gene_name\": \"Cytochrome P450 2C9\",\n",- " \"disease_name\": \"Warfarin Sensitivity\",\n",- " \"clinical_significance\": \"Pathogenic\",\n",- " \"chromosome\": \"10\",\n",- " \"position\": 96741054,\n",- " \"ref_allele\": \"C\",\n",- " \"alt_allele\": \"T\",\n",- " \"pathway\": \"Drug metabolism\",\n",- " \"impact\": \"High\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=4)).isoformat()\n",- " },\n",- " {\n",- " \"variant_id\": \"rs1057910\",\n",- " \"gene_symbol\": \"CYP2C9\",\n",- " \"gene_name\": \"Cytochrome P450 2C9\",\n",- " \"disease_name\": \"Warfarin Sensitivity\",\n",- " \"clinical_significance\": \"Pathogenic\",\n",- " \"chromosome\": \"10\",\n",- " \"position\": 96741055,\n",- " \"ref_allele\": \"A\",\n",- " \"alt_allele\": \"C\",\n",- " \"pathway\": \"Drug metabolism\",\n",- " \"impact\": \"High\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=5)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(genomic_data_file, 'w') as f:\n",- " json.dump(genomic_data, f, indent=2)\n",- "\n",- "# Ingest from local file\n",- "file_data = file_ingestor.ingest_file(genomic_data_file)\n",- "parsed_genomic = structured_parser.parse_json(json.dumps(genomic_data))\n",- "\n",- "# Ingest from genomic APIs (example with public API)\n",- "web_content = web_ingestor.ingest_url(genomic_apis[0]) # Ensembl API\n",- "if web_content:\n",- " print(f\" Ingested genomic API: {genomic_apis[0]}\")\n",- "\n",- "# Ingest from genomic feeds\n",- "feed_data_list = []\n",- "for feed_url in genomic_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " feed_data_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "# Database ingestion pattern\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"variants\",\n",- " limit=1000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Local variants: {len(genomic_data)}\")\n",- "print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",- "print(f\" Feeds ingested: {len(feed_data_list)}\")\n",- "print(f\" Web APIs: {len(genomic_apis)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Genomic Entities\n",- "\n",- "Extract variants, genes, diseases, and pathways from the ingested data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "all_genomic_texts = []\n",- "all_variants = []\n",- "\n",- "# Process parsed genomic data\n",- "if parsed_genomic and isinstance(parsed_genomic, dict):\n",- " variants = parsed_genomic.get(\"data\", genomic_data)\n",- " for variant in variants:\n",- " all_variants.append(variant)\n",- " variant_text = f\"Variant {variant.get('variant_id', '')} in gene {variant.get('gene_symbol', '')} associated with {variant.get('disease_name', '')} in pathway {variant.get('pathway', '')}\"\n",- " all_genomic_texts.append(variant_text)\n",- "\n",- "# Extract entities\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_triplets = []\n",- "\n",- "for text in all_genomic_texts:\n",- " entities = ner_extractor.extract(text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " triplets = triplet_extractor.extract(text)\n",- " all_triplets.extend(triplets)\n",- "\n",- "# Build structured entity list\n",- "variant_entities = []\n",- "gene_entities = []\n",- "disease_entities = []\n",- "pathway_entities = []\n",- "\n",- "unique_genes = {}\n",- "unique_diseases = {}\n",- "unique_pathways = {}\n",- "\n",- "for variant in all_variants:\n",- " variant_entity = {\n",- " \"id\": variant.get(\"variant_id\", \"\"),\n",- " \"type\": \"Variant\",\n",- " \"properties\": {\n",- " \"variant_id\": variant.get(\"variant_id\", \"\"),\n",- " \"chromosome\": variant.get(\"chromosome\", \"\"),\n",- " \"position\": variant.get(\"position\", 0),\n",- " \"ref_allele\": variant.get(\"ref_allele\", \"\"),\n",- " \"alt_allele\": variant.get(\"alt_allele\", \"\"),\n",- " \"clinical_significance\": variant.get(\"clinical_significance\", \"\"),\n",- " \"impact\": variant.get(\"impact\", \"\"),\n",- " \"timestamp\": variant.get(\"timestamp\", \"\")\n",- " }\n",- " }\n",- " variant_entities.append(variant_entity)\n",- " \n",- " # Add gene entity\n",- " gene_symbol = variant.get(\"gene_symbol\", \"\")\n",- " if gene_symbol and gene_symbol not in unique_genes:\n",- " gene_entity = {\n",- " \"id\": gene_symbol,\n",- " \"type\": \"Gene\",\n",- " \"properties\": {\n",- " \"symbol\": gene_symbol,\n",- " \"name\": variant.get(\"gene_name\", \"\"),\n",- " \"chromosome\": variant.get(\"chromosome\", \"\")\n",- " }\n",- " }\n",- " gene_entities.append(gene_entity)\n",- " unique_genes[gene_symbol] = gene_entity\n",- " \n",- " # Add disease entity\n",- " disease_name = variant.get(\"disease_name\", \"\")\n",- " if disease_name and disease_name not in unique_diseases:\n",- " disease_entity = {\n",- " \"id\": disease_name.replace(\" \", \"_\"),\n",- " \"type\": \"Disease\",\n",- " \"properties\": {\n",- " \"name\": disease_name\n",- " }\n",- " }\n",- " disease_entities.append(disease_entity)\n",- " unique_diseases[disease_name] = disease_entity\n",- " \n",- " # Add pathway entity\n",- " pathway_name = variant.get(\"pathway\", \"\")\n",- " if pathway_name and pathway_name not in unique_pathways:\n",- " pathway_entity = {\n",- " \"id\": pathway_name.replace(\" \", \"_\"),\n",- " \"type\": \"Pathway\",\n",- " \"properties\": {\n",- " \"name\": pathway_name\n",- " }\n",- " }\n",- " pathway_entities.append(pathway_entity)\n",- " unique_pathways[pathway_name] = pathway_entity\n",- "\n",- "print(f\"Extracted {len(variant_entities)} variants\")\n",- "print(f\"Extracted {len(gene_entities)} unique genes\")\n",- "print(f\"Extracted {len(disease_entities)} unique diseases\")\n",- "print(f\"Extracted {len(pathway_entities)} unique pathways\")\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n",- "print(f\"Extracted {len(all_triplets)} triplets\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Genomic Knowledge Graph\n",- "\n",- "Build a knowledge graph from extracted genomic entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "\n",- "# Add all entities\n",- "for variant in variant_entities:\n",- " builder.add_entity(\n",- " entity_id=variant[\"id\"],\n",- " entity_type=variant[\"type\"],\n",- " properties=variant.get(\"properties\", {})\n",- " )\n",- "\n",- "for gene in gene_entities:\n",- " builder.add_entity(\n",- " entity_id=gene[\"id\"],\n",- " entity_type=gene[\"type\"],\n",- " properties=gene.get(\"properties\", {})\n",- " )\n",- "\n",- "for disease in disease_entities:\n",- " builder.add_entity(\n",- " entity_id=disease[\"id\"],\n",- " entity_type=disease[\"type\"],\n",- " properties=disease.get(\"properties\", {})\n",- " )\n",- "\n",- "for pathway in pathway_entities:\n",- " builder.add_entity(\n",- " entity_id=pathway[\"id\"],\n",- " entity_type=pathway[\"type\"],\n",- " properties=pathway.get(\"properties\", {})\n",- " )\n",- "\n",- "# Add relationships\n",- "relationships = []\n",- "for variant in variant_entities:\n",- " variant_id = variant[\"id\"]\n",- " gene_symbol = variant[\"properties\"].get(\"gene_symbol\", \"\")\n",- " disease_name = variant[\"properties\"].get(\"disease_name\", \"\").replace(\" \", \"_\")\n",- " pathway_name = variant[\"properties\"].get(\"pathway\", \"\").replace(\" \", \"_\")\n",- " \n",- " # Find corresponding entities\n",- " gene_entity = unique_genes.get(gene_symbol)\n",- " disease_entity = unique_diseases.get(disease_name.replace(\"_\", \" \"))\n",- " pathway_entity = unique_pathways.get(pathway_name.replace(\"_\", \" \"))\n",- " \n",- " if gene_entity:\n",- " builder.add_relationship(\n",- " source_id=variant_id,\n",- " target_id=gene_entity[\"id\"],\n",- " relationship_type=\"located_in\",\n",- " properties={}\n",- " )\n",- " relationships.append({\n",- " \"source\": variant_id,\n",- " \"target\": gene_entity[\"id\"],\n",- " \"type\": \"located_in\"\n",- " })\n",- " \n",- " if disease_entity:\n",- " builder.add_relationship(\n",- " source_id=variant_id,\n",- " target_id=disease_entity[\"id\"],\n",- " relationship_type=\"associated_with\",\n",- " properties={\n",- " \"clinical_significance\": variant[\"properties\"].get(\"clinical_significance\", \"\")\n",- " }\n",- " )\n",- " relationships.append({\n",- " \"source\": variant_id,\n",- " \"target\": disease_entity[\"id\"],\n",- " \"type\": \"associated_with\"\n",- " })\n",- " \n",- " if pathway_entity:\n",- " builder.add_relationship(\n",- " source_id=gene_entity[\"id\"] if gene_entity else variant_id,\n",- " target_id=pathway_entity[\"id\"],\n",- " relationship_type=\"participates_in\",\n",- " properties={}\n",- " )\n",- " relationships.append({\n",- " \"source\": gene_entity[\"id\"] if gene_entity else variant_id,\n",- " \"target\": pathway_entity[\"id\"],\n",- " \"type\": \"participates_in\"\n",- " })\n",- "\n",- "knowledge_graph = builder.build()\n",- "\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.nodes)} nodes\")\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.edges)} edges\")\n",- "print(f\"Added {len(relationships)} genomic relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze Associations and Predict Impact\n",- "\n",- "Analyze variant-disease associations and predict variant impact on protein function.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery(knowledge_graph)\n",- "pattern_detector = TemporalPatternDetector()\n",- "\n",- "# Compute graph metrics\n",- "graph_metrics = graph_analyzer.compute_metrics(knowledge_graph)\n",- "\n",- "# Calculate centrality\n",- "centrality_result = centrality_calculator.calculate_betweenness_centrality(knowledge_graph)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "top_central_genes = sorted(centrality_scores.items(), key=lambda x: x[1], reverse=True)[:10]\n",- "\n",- "# Detect communities\n",- "communities_result = community_detector.detect_communities(knowledge_graph, algorithm=\"louvain\")\n",- "communities = communities_result.get('communities', [])\n",- "community_count = len(communities) if communities else 0\n",- "\n",- "# Analyze connectivity\n",- "connectivity_results = connectivity_analyzer.analyze_connectivity(knowledge_graph)\n",- "\n",- "# Detect temporal patterns\n",- "start_time = (datetime.now() - timedelta(days=7)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "temporal_results = temporal_query.query_time_range(\n",- " start_time=start_time,\n",- " end_time=end_time,\n",- " relationship_types=[\"associated_with\", \"located_in\"]\n",- ")\n",- "\n",- "temporal_patterns = pattern_detector.detect_temporal_patterns(\n",- " knowledge_graph,\n",- " relationship_types=[\"associated_with\"],\n",- " time_window_hours=168\n",- ")\n",- "\n",- "# Impact Prediction using Inference Engine\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "\n",- "# Define impact prediction rules\n",- "impact_rules = [\n",- " {\n",- " \"name\": \"high_impact_pathogenic\",\n",- " \"condition\": \"clinical_significance == 'Pathogenic' AND impact == 'High'\",\n",- " \"action\": \"predict_high_impact\"\n",- " },\n",- " {\n",- " \"name\": \"moderate_impact_likely_pathogenic\",\n",- " \"condition\": \"clinical_significance == 'Likely Pathogenic' AND impact == 'Moderate'\",\n",- " \"action\": \"predict_moderate_impact\"\n",- " },\n",- " {\n",- " \"name\": \"disease_association\",\n",- " \"condition\": \"associated_with_disease AND pathogenic\",\n",- " \"action\": \"predict_disease_risk\"\n",- " }\n",- "]\n",- "\n",- "for rule in impact_rules:\n",- " rule_manager.add_rule(rule[\"name\"], rule[\"condition\"], rule[\"action\"])\n",- "\n",- "# Predict variant impact\n",- "variant_impacts = []\n",- "for variant in variant_entities:\n",- " clinical_sig = variant[\"properties\"].get(\"clinical_significance\", \"\")\n",- " impact = variant[\"properties\"].get(\"impact\", \"\")\n",- " \n",- " impact_score = 0\n",- " if clinical_sig == \"Pathogenic\":\n",- " impact_score += 5\n",- " elif clinical_sig == \"Likely Pathogenic\":\n",- " impact_score += 3\n",- " \n",- " if impact == \"High\":\n",- " impact_score += 3\n",- " elif impact == \"Moderate\":\n",- " impact_score += 2\n",- " \n",- " # Check disease associations\n",- " disease_associations = [r for r in relationships if r[\"source\"] == variant[\"id\"] and r[\"type\"] == \"associated_with\"]\n",- " if disease_associations:\n",- " impact_score += 2\n",- " \n",- " variant_impacts.append({\n",- " \"variant\": variant[\"id\"],\n",- " \"impact_score\": min(impact_score, 10),\n",- " \"predicted_impact\": \"High\" if impact_score >= 7 else \"Moderate\" if impact_score >= 4 else \"Low\",\n",- " \"clinical_significance\": clinical_sig,\n",- " \"disease_associations\": len(disease_associations)\n",- " })\n",- "\n",- "print(f\"Analyzed {len(variant_entities)} variants\")\n",- "print(f\"Found {community_count} gene communities\")\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"\\nTop 5 Central Genes:\")\n",- "for i, (gene_id, centrality) in enumerate(top_central_genes[:5], 1):\n",- " print(f\" {i}. {gene_id} (centrality: {centrality:.3f})\")\n",- "print(f\"\\nVariant Impact Predictions:\")\n",- "for impact in sorted(variant_impacts, key=lambda x: x[\"impact_score\"], reverse=True):\n",- " print(f\" - {impact['variant']}: {impact['predicted_impact']} Impact (Score: {impact['impact_score']}/10, Diseases: {impact['disease_associations']})\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Genomic Ontology and Pathway Analysis\n",- "\n",- "Generate genomic ontology and perform pathway analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",- "\n",- "# Generate genomic ontology\n",- "genomic_ontology = ontology_generator.generate_ontology(\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/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",- "# 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",- "\n",- "# Pathway analysis\n",- "pathway_analysis = {}\n",- "for pathway in pathway_entities:\n",- " pathway_id = pathway[\"id\"]\n",- " pathway_name = pathway[\"properties\"].get(\"name\", \"\")\n",- " \n",- " # Find variants and genes in this pathway\n",- " pathway_variants = [r for r in relationships if r[\"target\"] == pathway_id and r[\"type\"] == \"participates_in\"]\n",- " pathway_genes = set()\n",- " for rel in pathway_variants:\n",- " source_entity = next((e for e in variant_entities + gene_entities if e[\"id\"] == rel[\"source\"]), None)\n",- " if source_entity and source_entity[\"type\"] == \"Gene\":\n",- " pathway_genes.add(source_entity[\"id\"])\n",- " \n",- " pathway_analysis[pathway_name] = {\n",- " \"variants\": len([r for r in pathway_variants if next((e for e in variant_entities if e[\"id\"] == r[\"source\"]), None)]),\n",- " \"genes\": len(pathway_genes),\n",- " \"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.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",- "print(f\"\\nPathway Analysis:\")\n",- "for pathway_name, analysis in pathway_analysis.items():\n",- " print(f\" - {pathway_name}: {analysis['variants']} variants, {analysis['genes']} genes, {analysis['diseases']} disease associations\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Reports and Visualize\n",- "\n",- "Generate comprehensive genomic analysis reports and visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "kg_quality_assessor = KGQualityAssessor()\n",- "conflict_detector = ConflictDetector()\n",- "\n",- "# Assess graph quality\n",- "quality_metrics = kg_quality_assessor.assess_quality(knowledge_graph)\n",- "\n",- "# Detect conflicts\n",- "conflicts = conflict_detector.detect_conflicts(knowledge_graph)\n",- "\n",- "# Export knowledge graph\n",- "kg_json = json_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"genomic_kg.json\"))\n",- "kg_rdf = rdf_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"genomic_kg.rdf\"))\n",- "\n",- "# Export ontology\n",- "ontology_owl = owl_exporter.export(genomic_ontology, output_path=os.path.join(temp_dir, \"genomic_ontology.owl\"))\n",- "\n",- "# Generate report\n",- "report_content = f\"\"\"\n",- "# Genomic Variant Analysis Report\n",- "\n",- "## Executive Summary\n",- "- Total Variants Analyzed: {len(variant_entities)}\n",- "- Unique Genes: {len(gene_entities)}\n",- "- Unique Diseases: {len(disease_entities)}\n",- "- Unique Pathways: {len(pathway_entities)}\n",- "- High Impact Variants: {len([v for v in variant_impacts if v['predicted_impact'] == 'High'])}\n",- "\n",- "## Graph Quality Metrics\n",- "- Nodes: {quality_metrics.get('node_count', len(knowledge_graph.nodes))}\n",- "- Edges: {quality_metrics.get('edge_count', len(knowledge_graph.edges))}\n",- "- Completeness: {quality_metrics.get('completeness', 0):.2%}\n",- "- Consistency: {quality_metrics.get('consistency', 0):.2%}\n",- "\n",- "## Top Variants by Impact\n",- "\"\"\"\n",- "for i, impact in enumerate(sorted(variant_impacts, key=lambda x: x[\"impact_score\"], reverse=True)[:10], 1):\n",- " report_content += f\"\"\"\n",- "{i}. {impact['variant']}\n",- " - Predicted Impact: {impact['predicted_impact']}\n",- " - Impact Score: {impact['impact_score']}/10\n",- " - Clinical Significance: {impact['clinical_significance']}\n",- " - Disease Associations: {impact['disease_associations']}\n",- "\"\"\"\n",- "\n",- "report_content += f\"\"\"\n",- "## Pathway Analysis\n",- "\"\"\"\n",- "for pathway_name, analysis in pathway_analysis.items():\n",- " report_content += f\"\"\"\n",- "### {pathway_name}\n",- "- Variants: {analysis['variants']}\n",- "- Genes: {analysis['genes']}\n",- "- Disease Associations: {analysis['diseases']}\n",- "\"\"\"\n",- "\n",- "report_path = os.path.join(temp_dir, \"genomic_analysis_report.md\")\n",- "with open(report_path, 'w') as f:\n",- " f.write(report_content)\n",- "\n",- "print(f\"Exported knowledge graph to JSON and RDF\")\n",- "print(f\"Exported ontology to OWL\")\n",- "print(f\"Generated analysis report: {report_path}\")\n",- "print(f\"\\nQuality Metrics:\")\n",- "print(f\" Nodes: {quality_metrics.get('node_count', len(knowledge_graph.nodes))}\")\n",- "print(f\" Edges: {quality_metrics.get('edge_count', len(knowledge_graph.edges))}\")\n",- "print(f\" Completeness: {quality_metrics.get('completeness', 0):.2%}\")\n",- "print(f\" Consistency: {quality_metrics.get('consistency', 0):.2%}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Visualize Genomic Network\n",- "\n",- "Visualize the genomic knowledge graph, ontology, and analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "# Visualize knowledge graph\n",- "kg_viz = kg_visualizer.visualize(\n",- " knowledge_graph,\n",- " layout=\"force_directed\",\n",- " highlight_nodes=[v[\"id\"] for v in variant_entities],\n",- " node_size_by=\"impact\"\n",- ")\n",- "\n",- "# Visualize ontology\n",- "ontology_viz = ontology_visualizer.visualize(\n",- " genomic_ontology,\n",- " layout=\"hierarchical\"\n",- ")\n",- "\n",- "# Visualize analytics\n",- "analytics_viz = analytics_visualizer.visualize(\n",- " knowledge_graph,\n",- " metrics={\n",- " \"centrality\": dict(top_central_genes[:10]),\n",- " \"communities\": communities,\n",- " \"connectivity\": connectivity_results,\n",- " \"impact_scores\": {v[\"variant\"]: v[\"impact_score\"] for v in variant_impacts}\n",- " }\n",- ")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb b/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynbdeleted file mode 100644index 13f8887f..00000000--- a/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb+++ /dev/null@@ -1,728 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/01_DeFi_Protocol_Intelligence.ipynb)\n",- "\n",- "# DeFi Protocol Intelligence Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete DeFi protocol intelligence pipeline: ingest DeFi data from multiple sources (APIs, feeds, databases), extract protocol entities, build DeFi knowledge graph, analyze relationships, assess risks, optimize yields, and generate reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, HTMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, SemanticAnalyzer, EventDetector\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**DeFi Data Sources \u2192 Parse \u2192 Extract Entities (protocols, pools, tokens, strategies) \u2192 Build DeFi KG \u2192 Analyze Relationships \u2192 Risk Assessment \u2192 Yield Optimization \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest DeFi Data from Multiple Sources\n",- "\n",- "Ingest DeFi protocol data from APIs, feeds, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",- "from semantica.parse import JSONParser, HTMLParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, SemanticAnalyzer, EventDetector\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "db_ingestor = DBIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "html_parser = HTMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real DeFi APIs\n",- "defi_apis = [\n",- " \"https://api.llama.fi/protocols\", # DeFiLlama API\n",- " \"https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2\", # The Graph - Uniswap\n",- " \"https://api.github.com/repos/Uniswap/interface\" # Uniswap GitHub\n",- "]\n",- "\n",- "# Real DeFi protocol feeds\n",- "defi_feeds = [\n",- " \"https://defipulse.com/blog/feed\", # DeFi Pulse\n",- " \"https://feeds.feedburner.com/TheDefiant\" # The Defiant\n",- "]\n",- "\n",- "# Real database connection for protocol metrics\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/defi_db\"\n",- "db_query = \"SELECT protocol_name, tvl, apy, token_address, pool_address, timestamp FROM defi_protocols WHERE timestamp > NOW() - INTERVAL '7 days' ORDER BY tvl DESC LIMIT 1000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample DeFi protocol data for local ingestion\n",- "defi_data_file = os.path.join(temp_dir, \"defi_protocols.json\")\n",- "defi_data = [\n",- " {\n",- " \"protocol_name\": \"Uniswap V3\",\n",- " \"protocol_type\": \"DEX\",\n",- " \"tvl\": 2500000000,\n",- " \"apy\": 12.5,\n",- " \"token_address\": \"0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984\",\n",- " \"pool_address\": \"0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8\",\n",- " \"token_symbol\": \"UNI\",\n",- " \"chain\": \"Ethereum\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat()\n",- " },\n",- " {\n",- " \"protocol_name\": \"Aave V3\",\n",- " \"protocol_type\": \"Lending\",\n",- " \"tvl\": 1800000000,\n",- " \"apy\": 8.3,\n",- " \"token_address\": \"0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9\",\n",- " \"pool_address\": \"0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2\",\n",- " \"token_symbol\": \"AAVE\",\n",- " \"chain\": \"Ethereum\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=2)).isoformat()\n",- " },\n",- " {\n",- " \"protocol_name\": \"Compound V3\",\n",- " \"protocol_type\": \"Lending\",\n",- " \"tvl\": 1200000000,\n",- " \"apy\": 7.8,\n",- " \"token_address\": \"0xc00e94Cb662C3520282E6f5717214004A7f26888\",\n",- " \"pool_address\": \"0xc3d688B667034EAD2F183C05b6e4B5e5B5b5b5b5\",\n",- " \"token_symbol\": \"COMP\",\n",- " \"chain\": \"Ethereum\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=3)).isoformat()\n",- " },\n",- " {\n",- " \"protocol_name\": \"Curve Finance\",\n",- " \"protocol_type\": \"DEX\",\n",- " \"tvl\": 1500000000,\n",- " \"apy\": 15.2,\n",- " \"token_address\": \"0xD533a949740bb3306d119CC777fa900bA034cd52\",\n",- " \"pool_address\": \"0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7\",\n",- " \"token_symbol\": \"CRV\",\n",- " \"chain\": \"Ethereum\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=4)).isoformat()\n",- " },\n",- " {\n",- " \"protocol_name\": \"MakerDAO\",\n",- " \"protocol_type\": \"Lending\",\n",- " \"tvl\": 8000000000,\n",- " \"apy\": 3.5,\n",- " \"token_address\": \"0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2\",\n",- " \"pool_address\": \"0x35D1b3F3D7966A1DFe207aa4514C12a2594E9c99\",\n",- " \"token_symbol\": \"MKR\",\n",- " \"chain\": \"Ethereum\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=5)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(defi_data_file, 'w') as f:\n",- " json.dump(defi_data, f, indent=2)\n",- "\n",- "# Ingest from local file\n",- "file_data = file_ingestor.ingest_file(defi_data_file)\n",- "parsed_defi = structured_parser.parse_json(json.dumps(defi_data))\n",- "\n",- "# Ingest from DeFi APIs (example with public API)\n",- "web_content = web_ingestor.ingest_url(defi_apis[2]) # GitHub API\n",- "if web_content:\n",- " print(f\" Ingested DeFi API: {defi_apis[2]}\")\n",- "\n",- "# Ingest from DeFi feeds\n",- "feed_data_list = []\n",- "for feed_url in defi_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " feed_data_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "# Database ingestion pattern\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"defi_protocols\",\n",- " limit=1000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Local protocols: {len(defi_data)}\")\n",- "print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",- "print(f\" Feeds ingested: {len(feed_data_list)}\")\n",- "print(f\" Web APIs: {len(defi_apis)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract DeFi Entities\n",- "\n",- "Extract protocols, pools, tokens, and strategies from the ingested data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "event_detector = EventDetector()\n",- "\n",- "all_defi_texts = []\n",- "all_protocols = []\n",- "\n",- "# Process parsed DeFi data\n",- "if parsed_defi and isinstance(parsed_defi, dict):\n",- " protocols = parsed_defi.get(\"data\", defi_data)\n",- " for protocol in protocols:\n",- " all_protocols.append(protocol)\n",- " protocol_text = f\"Protocol {protocol.get('protocol_name', '')} type {protocol.get('protocol_type', '')} TVL {protocol.get('tvl', 0)} APY {protocol.get('apy', 0)} token {protocol.get('token_symbol', '')}\"\n",- " all_defi_texts.append(protocol_text)\n",- "\n",- "# Extract entities\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_events = []\n",- "\n",- "for text in all_defi_texts:\n",- " entities = ner_extractor.extract(text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " events = event_detector.detect_events(text)\n",- " all_events.extend(events)\n",- "\n",- "# Build structured entity list\n",- "protocol_entities = []\n",- "pool_entities = []\n",- "token_entities = []\n",- "\n",- "for protocol in all_protocols:\n",- " protocol_entity = {\n",- " \"id\": protocol.get(\"protocol_name\", \"\").replace(\" \", \"_\"),\n",- " \"type\": \"Protocol\",\n",- " \"properties\": {\n",- " \"name\": protocol.get(\"protocol_name\", \"\"),\n",- " \"type\": protocol.get(\"protocol_type\", \"\"),\n",- " \"tvl\": protocol.get(\"tvl\", 0),\n",- " \"apy\": protocol.get(\"apy\", 0),\n",- " \"chain\": protocol.get(\"chain\", \"\"),\n",- " \"timestamp\": protocol.get(\"timestamp\", \"\")\n",- " }\n",- " }\n",- " protocol_entities.append(protocol_entity)\n",- " \n",- " # Add pool entity\n",- " pool_entity = {\n",- " \"id\": protocol.get(\"pool_address\", \"\"),\n",- " \"type\": \"Pool\",\n",- " \"properties\": {\n",- " \"address\": protocol.get(\"pool_address\", \"\"),\n",- " \"protocol\": protocol.get(\"protocol_name\", \"\"),\n",- " \"tvl\": protocol.get(\"tvl\", 0),\n",- " \"apy\": protocol.get(\"apy\", 0)\n",- " }\n",- " }\n",- " pool_entities.append(pool_entity)\n",- " \n",- " # Add token entity\n",- " token_entity = {\n",- " \"id\": protocol.get(\"token_address\", \"\"),\n",- " \"type\": \"Token\",\n",- " \"properties\": {\n",- " \"address\": protocol.get(\"token_address\", \"\"),\n",- " \"symbol\": protocol.get(\"token_symbol\", \"\"),\n",- " \"protocol\": protocol.get(\"protocol_name\", \"\")\n",- " }\n",- " }\n",- " token_entities.append(token_entity)\n",- "\n",- "print(f\"Extracted {len(protocol_entities)} protocols\")\n",- "print(f\"Extracted {len(pool_entities)} pools\")\n",- "print(f\"Extracted {len(token_entities)} tokens\")\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n",- "print(f\"Detected {len(all_events)} events\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build DeFi Knowledge Graph\n",- "\n",- "Build a knowledge graph from extracted DeFi entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "\n",- "# Add all entities\n",- "for protocol in protocol_entities:\n",- " builder.add_entity(\n",- " entity_id=protocol[\"id\"],\n",- " entity_type=protocol[\"type\"],\n",- " properties=protocol.get(\"properties\", {})\n",- " )\n",- "\n",- "for pool in pool_entities:\n",- " builder.add_entity(\n",- " entity_id=pool[\"id\"],\n",- " entity_type=pool[\"type\"],\n",- " properties=pool.get(\"properties\", {})\n",- " )\n",- "\n",- "for token in token_entities:\n",- " builder.add_entity(\n",- " entity_id=token[\"id\"],\n",- " entity_type=token[\"type\"],\n",- " properties=token.get(\"properties\", {})\n",- " )\n",- "\n",- "# Add relationships\n",- "relationships = []\n",- "for i, protocol in enumerate(protocol_entities):\n",- " protocol_id = protocol[\"id\"]\n",- " pool_id = pool_entities[i][\"id\"]\n",- " token_id = token_entities[i][\"id\"]\n",- " \n",- " # Protocol-Pool relationship\n",- " builder.add_relationship(\n",- " source_id=protocol_id,\n",- " target_id=pool_id,\n",- " relationship_type=\"has_pool\",\n",- " properties={}\n",- " )\n",- " \n",- " # Protocol-Token relationship\n",- " builder.add_relationship(\n",- " source_id=protocol_id,\n",- " target_id=token_id,\n",- " relationship_type=\"has_token\",\n",- " properties={}\n",- " )\n",- " \n",- " # Pool-Token relationship\n",- " builder.add_relationship(\n",- " source_id=pool_id,\n",- " target_id=token_id,\n",- " relationship_type=\"contains\",\n",- " properties={}\n",- " )\n",- " \n",- " relationships.append({\n",- " \"source\": protocol_id,\n",- " \"target\": pool_id,\n",- " \"type\": \"has_pool\"\n",- " })\n",- " relationships.append({\n",- " \"source\": protocol_id,\n",- " \"target\": token_id,\n",- " \"type\": \"has_token\"\n",- " })\n",- "\n",- "knowledge_graph = builder.build()\n",- "\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.nodes)} nodes\")\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.edges)} edges\")\n",- "print(f\"Added {len(relationships)} DeFi relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze DeFi Relationships and Assess Risks\n",- "\n",- "Analyze protocol relationships, detect communities, and assess risks.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery(knowledge_graph)\n",- "pattern_detector = TemporalPatternDetector()\n",- "\n",- "# Compute graph metrics\n",- "graph_metrics = graph_analyzer.compute_metrics(knowledge_graph)\n",- "\n",- "# Calculate centrality\n",- "centrality_result = centrality_calculator.calculate_betweenness_centrality(knowledge_graph)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "top_central_protocols = sorted(centrality_scores.items(), key=lambda x: x[1], reverse=True)[:10]\n",- "\n",- "# Detect communities\n",- "communities_result = community_detector.detect_communities(knowledge_graph, algorithm=\"louvain\")\n",- "communities = communities_result.get('communities', [])\n",- "community_count = len(communities) if communities else 0\n",- "\n",- "# Analyze connectivity\n",- "connectivity_results = connectivity_analyzer.analyze_connectivity(knowledge_graph)\n",- "\n",- "# Detect temporal patterns\n",- "temporal_patterns = pattern_detector.detect_temporal_patterns(\n",- " knowledge_graph,\n",- " relationship_types=[\"has_pool\", \"has_token\"],\n",- " time_window_hours=24\n",- ")\n",- "\n",- "# Risk Assessment using Inference Engine\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "\n",- "# Define risk rules\n",- "risk_rules = [\n",- " {\n",- " \"name\": \"high_tvl_risk\",\n",- " \"condition\": \"tvl > 5000000000 AND apy < 5\",\n",- " \"action\": \"flag_as_low_yield_high_tvl\"\n",- " },\n",- " {\n",- " \"name\": \"high_apy_risk\",\n",- " \"condition\": \"apy > 20\",\n",- " \"action\": \"flag_as_high_risk_high_yield\"\n",- " },\n",- " {\n",- " \"name\": \"optimal_protocol\",\n",- " \"condition\": \"tvl > 1000000000 AND apy BETWEEN 8 AND 15\",\n",- " \"action\": \"flag_as_optimal\"\n",- " }\n",- "]\n",- "\n",- "for rule in risk_rules:\n",- " rule_manager.add_rule(rule[\"name\"], rule[\"condition\"], rule[\"action\"])\n",- "\n",- "# Assess protocol risks\n",- "protocol_risks = []\n",- "for protocol in protocol_entities:\n",- " tvl = protocol[\"properties\"].get(\"tvl\", 0)\n",- " apy = protocol[\"properties\"].get(\"apy\", 0)\n",- " \n",- " risk_score = 0\n",- " risk_factors = []\n",- " \n",- " if tvl > 5000000000 and apy < 5:\n",- " risk_score += 2\n",- " risk_factors.append(\"low_yield_high_tvl\")\n",- " \n",- " if apy > 20:\n",- " risk_score += 3\n",- " risk_factors.append(\"high_apy_risk\")\n",- " \n",- " if tvl < 500000000:\n",- " risk_score += 1\n",- " risk_factors.append(\"low_tvl\")\n",- " \n",- " if 1000000000 <= tvl <= 5000000000 and 8 <= apy <= 15:\n",- " risk_score = max(0, risk_score - 1)\n",- " risk_factors.append(\"optimal_range\")\n",- " \n",- " protocol_risks.append({\n",- " \"protocol\": protocol[\"id\"],\n",- " \"name\": protocol[\"properties\"].get(\"name\", \"\"),\n",- " \"risk_score\": min(risk_score, 10),\n",- " \"risk_factors\": risk_factors,\n",- " \"tvl\": tvl,\n",- " \"apy\": apy\n",- " })\n",- "\n",- "print(f\"Analyzed {len(protocol_entities)} protocols\")\n",- "print(f\"Found {community_count} protocol communities\")\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"\\nTop 5 Central Protocols:\")\n",- "for i, (protocol_id, centrality) in enumerate(top_central_protocols[:5], 1):\n",- " protocol_name = next((p[\"properties\"].get(\"name\", protocol_id) for p in protocol_entities if p[\"id\"] == protocol_id), protocol_id)\n",- " print(f\" {i}. {protocol_name} (centrality: {centrality:.3f})\")\n",- "print(f\"\\nProtocol Risk Assessment:\")\n",- "for risk in sorted(protocol_risks, key=lambda x: x[\"risk_score\"], reverse=True)[:5]:\n",- " print(f\" - {risk['name']}: Risk Score {risk['risk_score']}/10, Factors: {', '.join(risk['risk_factors'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate DeFi Ontology and Optimize Yields\n",- "\n",- "Generate DeFi protocol ontology and optimize yield strategies.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",- "\n",- "# Generate DeFi ontology\n",- "defi_ontology = ontology_generator.generate_ontology(\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/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",- "# 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",- "# Yield optimization\n",- "yield_optimization = []\n",- "for protocol in protocol_entities:\n",- " tvl = protocol[\"properties\"].get(\"tvl\", 0)\n",- " apy = protocol[\"properties\"].get(\"apy\", 0)\n",- " protocol_type = protocol[\"properties\"].get(\"type\", \"\")\n",- " \n",- " # Calculate yield score\n",- " yield_score = (apy * 0.6) + (min(tvl / 1000000000, 10) * 0.4)\n",- " \n",- " optimization_suggestions = []\n",- " if apy < 8 and tvl > 1000000000:\n",- " optimization_suggestions.append(\"Consider higher APY protocols for better yield\")\n",- " if tvl < 500000000:\n",- " optimization_suggestions.append(\"Low TVL may indicate higher risk\")\n",- " if apy > 15:\n",- " optimization_suggestions.append(\"High APY may indicate higher risk, diversify\")\n",- " \n",- " yield_optimization.append({\n",- " \"protocol\": protocol[\"properties\"].get(\"name\", \"\"),\n",- " \"yield_score\": yield_score,\n",- " \"apy\": apy,\n",- " \"tvl\": tvl,\n",- " \"suggestions\": optimization_suggestions\n",- " })\n",- "\n",- "print(f\"Generated DeFi ontology with {len(defi_ontology.get('classes', []))} classes\")\n",- "print(f\"\\nYield Optimization Recommendations:\")\n",- "for opt in sorted(yield_optimization, key=lambda x: x[\"yield_score\"], reverse=True)[:5]:\n",- " print(f\" - {opt['protocol']}: Yield Score {opt['yield_score']:.2f}, APY {opt['apy']:.1f}%\")\n",- " for suggestion in opt['suggestions']:\n",- " print(f\" \u2192 {suggestion}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Reports and Visualize\n",- "\n",- "Generate comprehensive DeFi intelligence reports and visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph\n",- "kg_json = json_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"defi_kg.json\"))\n",- "kg_rdf = rdf_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"defi_kg.rdf\"))\n",- "\n",- "# Export ontology\n",- "ontology_owl = owl_exporter.export(defi_ontology, output_path=os.path.join(temp_dir, \"defi_ontology.owl\"))\n",- "\n",- "# Generate report\n",- "report_content = f\"\"\"\n",- "# DeFi Protocol Intelligence Report\n",- "\n",- "## Executive Summary\n",- "- Total Protocols Analyzed: {len(protocol_entities)}\n",- "- Total Pools: {len(pool_entities)}\n",- "- Total Tokens: {len(token_entities)}\n",- "- Protocol Communities: {community_count}\n",- "- High-Risk Protocols: {len([r for r in protocol_risks if r['risk_score'] >= 7])}\n",- "\n",- "## Top Protocols by Centrality\n",- "\"\"\"\n",- "for i, (protocol_id, centrality) in enumerate(top_central_protocols[:10], 1):\n",- " protocol_name = next((p[\"properties\"].get(\"name\", protocol_id) for p in protocol_entities if p[\"id\"] == protocol_id), protocol_id)\n",- " report_content += f\"\\n{i}. {protocol_name} (Centrality: {centrality:.3f})\"\n",- "\n",- "report_content += f\"\"\"\n",- "## Risk Assessment\n",- "\"\"\"\n",- "for risk in sorted(protocol_risks, key=lambda x: x[\"risk_score\"], reverse=True):\n",- " report_content += f\"\"\"\n",- "### {risk['name']}\n",- "- Risk Score: {risk['risk_score']}/10\n",- "- TVL: ${risk['tvl']:,.0f}\n",- "- APY: {risk['apy']:.1f}%\n",- "- Risk Factors: {', '.join(risk['risk_factors'])}\n",- "\"\"\"\n",- "\n",- "report_content += f\"\"\"\n",- "## Yield Optimization\n",- "\"\"\"\n",- "for opt in sorted(yield_optimization, key=lambda x: x[\"yield_score\"], reverse=True)[:10]:\n",- " report_content += f\"\"\"\n",- "### {opt['protocol']}\n",- "- Yield Score: {opt['yield_score']:.2f}\n",- "- APY: {opt['apy']:.1f}%\n",- "- TVL: ${opt['tvl']:,.0f}\n",- "- Suggestions:\n",- "\"\"\"\n",- " for suggestion in opt['suggestions']:\n",- " report_content += f\" - {suggestion}\\n\"\n",- "\n",- "report_path = os.path.join(temp_dir, \"defi_intelligence_report.md\")\n",- "with open(report_path, 'w') as f:\n",- " f.write(report_content)\n",- "\n",- "print(f\"Exported knowledge graph to JSON and RDF\")\n",- "print(f\"Exported ontology to OWL\")\n",- "print(f\"Generated intelligence report: {report_path}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Visualize DeFi Network\n",- "\n",- "Visualize the DeFi protocol network, ontology, and analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "# Visualize knowledge graph\n",- "kg_viz = kg_visualizer.visualize(\n",- " knowledge_graph,\n",- " layout=\"force_directed\",\n",- " highlight_nodes=[p[\"id\"] for p in protocol_entities],\n",- " node_size_by=\"tvl\"\n",- ")\n",- "\n",- "# Visualize ontology\n",- "ontology_viz = ontology_visualizer.visualize(\n",- " defi_ontology,\n",- " layout=\"hierarchical\"\n",- ")\n",- "\n",- "# Visualize analytics\n",- "analytics_viz = analytics_visualizer.visualize(\n",- " knowledge_graph,\n",- " metrics={\n",- " \"centrality\": dict(top_central_protocols[:10]),\n",- " \"communities\": communities,\n",- " \"connectivity\": connectivity_results,\n",- " \"risk_scores\": {r[\"protocol\"]: r[\"risk_score\"] for r in protocol_risks}\n",- " }\n",- ")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb b/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynbdeleted file mode 100644index 3d024892..00000000--- a/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb+++ /dev/null@@ -1,744 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/blockchain/02_Transaction_Network_Analysis.ipynb)\n",- "\n",- "# Transaction Network Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete blockchain transaction network analysis pipeline: stream transactions from multiple sources (blockchain APIs, transaction feeds, databases), build temporal transaction knowledge graph, persist to graph database, detect AML patterns, trace fund flows, and generate alerts.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent blockchain graph\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Real-time Transaction Streams \u2192 Parse \u2192 Extract Entities (wallets, transactions, addresses) \u2192 Build Temporal Transaction KG \u2192 Store in Graph DB \u2192 Detect Patterns (tumbling, mixing, clustering) \u2192 AML Analysis \u2192 Generate Alerts \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Stream Transactions from Multiple Sources\n",- "\n",- "Stream blockchain transactions from APIs, feeds, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import StreamIngestor, WebIngestor, DBIngestor, FileIngestor\n",- "from semantica.parse import JSONParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD-- "from semantica.conflicts import ConflictDetector\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "stream_ingestor = StreamIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real streaming sources for blockchain transactions\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"blockchain_transactions\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"transaction_analysis\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"eth_transactions\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real blockchain APIs\n",- "blockchain_apis = [\n",- " \"https://api.etherscan.io/api?module=proxy&action=eth_getBlockByNumber&tag=latest&boolean=true&apikey=YourApiKeyToken\", # Etherscan API\n",- " \"https://blockchain.info/rawblock/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f\", # Blockchain.com API\n",- " \"https://api.coingecko.com/api/v3/coins/ethereum\" # CoinGecko API\n",- "]\n",- "\n",- "# Real database connection for transaction history\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/blockchain_db\"\n",- "db_query = \"SELECT tx_hash, from_address, to_address, value, timestamp, block_number FROM transactions WHERE timestamp > NOW() - INTERVAL '24 hours' ORDER BY timestamp DESC LIMIT 10000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample transaction data for local ingestion\n",- "transaction_data_file = os.path.join(temp_dir, \"transactions.json\")\n",- "transaction_data = [\n",- " {\n",- " \"tx_hash\": \"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef\",\n",- " \"from_address\": \"0xabc123def456abc123def456abc123def456abc12\",\n",- " \"to_address\": \"0xdef456abc123def456abc123def456abc123def45\",\n",- " \"value\": \"1000000000000000000\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"block_number\": 18500000,\n",- " \"gas_used\": 21000\n",- " },\n",- " {\n",- " \"tx_hash\": \"0x2345678901bcdef2345678901bcdef2345678901bcdef2345678901bcdef23\",\n",- " \"from_address\": \"0xdef456abc123def456abc123def456abc123def45\",\n",- " \"to_address\": \"0x7890123456789012345678901234567890123456\",\n",- " \"value\": \"500000000000000000\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=2)).isoformat(),\n",- " \"block_number\": 18499950,\n",- " \"gas_used\": 21000\n",- " },\n",- " {\n",- " \"tx_hash\": \"0x3456789012cdef3456789012cdef3456789012cdef3456789012cdef3456\",\n",- " \"from_address\": \"0x7890123456789012345678901234567890123456\",\n",- " \"to_address\": \"0xabc123def456abc123def456abc123def456abc12\",\n",- " \"value\": \"2000000000000000000\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=3)).isoformat(),\n",- " \"block_number\": 18499900,\n",- " \"gas_used\": 21000\n",- " },\n",- " {\n",- " \"tx_hash\": \"0x4567890123def4567890123def4567890123def4567890123def4567890123\",\n",- " \"from_address\": \"0xabc123def456abc123def456abc123def456abc12\",\n",- " \"to_address\": \"0x4567890123456789012345678901234567890123\",\n",- " \"value\": \"300000000000000000\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=4)).isoformat(),\n",- " \"block_number\": 18499850,\n",- " \"gas_used\": 21000\n",- " },\n",- " {\n",- " \"tx_hash\": \"0x5678901234ef5678901234ef5678901234ef5678901234ef5678901234ef56\",\n",- " \"from_address\": \"0x4567890123456789012345678901234567890123\",\n",- " \"to_address\": \"0x1234567890123456789012345678901234567890\",\n",- " \"value\": \"1500000000000000000\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=5)).isoformat(),\n",- " \"block_number\": 18499800,\n",- " \"gas_used\": 21000\n",- " }\n",- "]\n",- "\n",- "with open(transaction_data_file, 'w') as f:\n",- " json.dump(transaction_data, f, indent=2)\n",- "\n",- "# Ingest from local file\n",- "file_data = file_ingestor.ingest_file(transaction_data_file)\n",- "parsed_transactions = structured_parser.parse_json(json.dumps(transaction_data))\n",- "\n",- "# Ingest from blockchain APIs (example with public API)\n",- "web_content = web_ingestor.ingest_url(blockchain_apis[2]) # CoinGecko public API\n",- "if web_content:\n",- " print(f\" Ingested blockchain API: {blockchain_apis[2]}\")\n",- "\n",- "# Database ingestion pattern (would connect to real database)\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"transactions\",\n",- " limit=10000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "\n",- "# Streaming ingestion pattern\n",- "for stream_source in stream_sources:\n",- " print(f\" - {stream_source['type']}: {stream_source.get('topic') or stream_source.get('queue')}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Local transactions: {len(transaction_data)}\")\n",- "print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",- "print(f\" Streaming sources: {len(stream_sources)}\")\n",- "print(f\" Web APIs: {len(blockchain_apis)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Transaction Entities\n",- "\n",- "Extract wallets, transactions, and addresses from the ingested data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "all_transaction_texts = []\n",- "all_transactions = []\n",- "\n",- "# Process parsed transactions\n",- "if parsed_transactions and isinstance(parsed_transactions, dict):\n",- " transactions = parsed_transactions.get(\"data\", transaction_data)\n",- " for tx in transactions:\n",- " all_transactions.append(tx)\n",- " tx_text = f\"Transaction {tx.get('tx_hash', '')} from {tx.get('from_address', '')} to {tx.get('to_address', '')} value {tx.get('value', '')} at {tx.get('timestamp', '')}\"\n",- " all_transaction_texts.append(tx_text)\n",- "\n",- "# Extract entities\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_events = []\n",- "all_triplets = []\n",- "\n",- "for text in all_transaction_texts:\n",- " entities = ner_extractor.extract(text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " events = event_detector.detect_events(text)\n",- " all_events.extend(events)\n",- " \n",- " triplets = triplet_extractor.extract(text)\n",- " all_triplets.extend(triplets)\n",- "\n",- "# Build structured entity list\n",- "transaction_entities = []\n",- "wallet_entities = []\n",- "\n",- "for tx in all_transactions:\n",- " tx_entity = {\n",- " \"id\": tx.get(\"tx_hash\", \"\"),\n",- " \"type\": \"Transaction\",\n",- " \"properties\": {\n",- " \"from_address\": tx.get(\"from_address\", \"\"),\n",- " \"to_address\": tx.get(\"to_address\", \"\"),\n",- " \"value\": tx.get(\"value\", \"\"),\n",- " \"timestamp\": tx.get(\"timestamp\", \"\"),\n",- " \"block_number\": tx.get(\"block_number\", 0),\n",- " \"gas_used\": tx.get(\"gas_used\", 0)\n",- " }\n",- " }\n",- " transaction_entities.append(tx_entity)\n",- " \n",- " # Add wallet entities\n",- " from_wallet = {\n",- " \"id\": tx.get(\"from_address\", \"\"),\n",- " \"type\": \"Wallet\",\n",- " \"properties\": {\n",- " \"address\": tx.get(\"from_address\", \"\"),\n",- " \"role\": \"sender\"\n",- " }\n",- " }\n",- " to_wallet = {\n",- " \"id\": tx.get(\"to_address\", \"\"),\n",- " \"type\": \"Wallet\",\n",- " \"properties\": {\n",- " \"address\": tx.get(\"to_address\", \"\"),\n",- " \"role\": \"receiver\"\n",- " }\n",- " }\n",- " wallet_entities.append(from_wallet)\n",- " wallet_entities.append(to_wallet)\n",- "\n",- "# Deduplicate wallets\n",- "unique_wallets = {}\n",- "for wallet in wallet_entities:\n",- " wallet_id = wallet[\"id\"]\n",- " if wallet_id not in unique_wallets:\n",- " unique_wallets[wallet_id] = wallet\n",- "\n",- "wallet_entities = list(unique_wallets.values())\n",- "\n",- "print(f\"Extracted {len(transaction_entities)} transactions\")\n",- "print(f\"Extracted {len(wallet_entities)} unique wallets\")\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n",- "print(f\"Detected {len(all_events)} events\")\n",- "print(f\"Extracted {len(all_triplets)} triplets\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Temporal Transaction Knowledge Graph\n",- "\n",- "Build a temporal knowledge graph from extracted transactions and wallets.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "\n",- "# Add all entities\n",- "for wallet in wallet_entities:\n",- " builder.add_entity(\n",- " entity_id=wallet[\"id\"],\n",- " entity_type=wallet[\"type\"],\n",- " properties=wallet.get(\"properties\", {})\n",- " )\n",- "\n",- "for tx in transaction_entities:\n",- " builder.add_entity(\n",- " entity_id=tx[\"id\"],\n",- " entity_type=tx[\"type\"],\n",- " properties=tx.get(\"properties\", {})\n",- " )\n",- "\n",- "# Add relationships\n",- "relationships = []\n",- "for tx in transaction_entities:\n",- " from_addr = tx[\"properties\"].get(\"from_address\", \"\")\n",- " to_addr = tx[\"properties\"].get(\"to_address\", \"\")\n",- " tx_hash = tx[\"id\"]\n",- " value = tx[\"properties\"].get(\"value\", \"\")\n",- " timestamp = tx[\"properties\"].get(\"timestamp\", \"\")\n",- " \n",- " # Transaction relationship\n",- " rel = {\n",- " \"source\": from_addr,\n",- " \"target\": to_addr,\n",- " \"type\": \"transfers_to\",\n",- " \"properties\": {\n",- " \"transaction\": tx_hash,\n",- " \"value\": value,\n",- " \"timestamp\": timestamp\n",- " }\n",- " }\n",- " relationships.append(rel)\n",- " builder.add_relationship(\n",- " source_id=from_addr,\n",- " target_id=to_addr,\n",- " relationship_type=\"transfers_to\",\n",- " properties=rel[\"properties\"]\n",- " )\n",- " \n",- " # Transaction entity relationship\n",- " builder.add_relationship(\n",- " source_id=from_addr,\n",- " target_id=tx_hash,\n",- " relationship_type=\"initiates\",\n",- " properties={\"timestamp\": timestamp}\n",- " )\n",- " builder.add_relationship(\n",- " source_id=tx_hash,\n",- " target_id=to_addr,\n",- " relationship_type=\"sends_to\",\n",- " properties={\"timestamp\": timestamp}\n",- " )\n",- "\n",- "knowledge_graph = builder.build()\n",- "\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.nodes)} nodes\")\n",- "print(f\"Built knowledge graph with {len(knowledge_graph.edges)} edges\")\n",- "print(f\"Added {len(relationships)} transaction relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Persist Transaction Graph to Graph Database\n",- "\n",- "Store the transaction knowledge graph in a persistent graph database for AML queries.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.graph_store import GraphStore\n",- "\n",- "# Initialize graph store - FalkorDB is ideal for real-time blockchain analysis\n",- "# For production: use Neo4j for enterprise features or FalkorDB for ultra-fast queries\n",- "# graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",- "# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"blockchain_graph\")\n",- "\n",- "# Option 1: Neo4j (requires Neo4j server running)\n",- " graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",- "graph_store.connect()\n",- "\n",- "# Store wallet nodes\n",- "wallet_node_map = {}\n",- "for wallet in wallet_entities:\n",- " node = graph_store.create_node(\n",- " labels=[\"Wallet\"],\n",- " properties={\n",- " \"address\": wallet[\"id\"],\n",- " \"role\": wallet[\"properties\"].get(\"role\", \"unknown\")\n",- " }\n",- " )\n",- " wallet_node_map[wallet[\"id\"]] = node.get(\"id\")\n",- "\n",- "# Store transaction nodes\n",- "tx_node_map = {}\n",- "for tx in transaction_entities:\n",- " node = graph_store.create_node(\n",- " labels=[\"Transaction\"],\n",- " properties={\n",- " \"tx_hash\": tx[\"id\"],\n",- " \"value\": tx[\"properties\"].get(\"value\", \"0\"),\n",- " \"timestamp\": tx[\"properties\"].get(\"timestamp\", \"\"),\n",- " \"block_number\": tx[\"properties\"].get(\"block_number\", 0),\n",- " \"gas_used\": tx[\"properties\"].get(\"gas_used\", 0)\n",- " }\n",- " )\n",- " tx_node_map[tx[\"id\"]] = node.get(\"id\")\n",- "\n",- "# Store relationships\n",- "for rel in relationships:\n",- " if rel[\"source\"] in wallet_node_map and rel[\"target\"] in wallet_node_map:\n",- " graph_store.create_relationship(\n",- " start_node_id=wallet_node_map[rel[\"source\"]],\n",- " end_node_id=wallet_node_map[rel[\"target\"]],\n",- " rel_type=\"TRANSFERS_TO\",\n",- " properties=rel.get(\"properties\", {})\n",- " )\n",- "\n",- "\n",- "# Query for AML analysis using Cypher\n",- "aml_query = \"\"\"\n",- " MATCH (w1:Wallet)-[r:TRANSFERS_TO]->(w2:Wallet)\n",- " WITH w1, count(r) as tx_count\n",- " WHERE tx_count > 1\n",- " RETURN w1.address as wallet, tx_count\n",- " ORDER BY tx_count DESC\n",- "\"\"\"\n",- "aml_results = graph_store.execute_query(aml_query)\n",- "\n",- "temporal_query = TemporalGraphQuery(knowledge_graph)\n",- "pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Query transactions in time range\n",- "start_time = (datetime.now() - timedelta(hours=6)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " start_time=start_time,\n",- " end_time=end_time,\n",- " relationship_types=[\"transfers_to\", \"initiates\", \"sends_to\"]\n",- ")\n",- "\n",- "# Detect temporal patterns\n",- "temporal_patterns = pattern_detector.detect_temporal_patterns(\n",- " knowledge_graph,\n",- " relationship_types=[\"transfers_to\"],\n",- " time_window_hours=6\n",- ")\n",- "\n",- "# Calculate centrality to find key wallets\n",- "centrality_result = centrality_calculator.calculate_betweenness_centrality(knowledge_graph)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "top_central_wallets = sorted(centrality_scores.items(), key=lambda x: x[1], reverse=True)[:10]\n",- "\n",- "# Detect communities (clustering)\n",- "communities_result = community_detector.detect_communities(knowledge_graph, algorithm=\"louvain\")\n",- "communities = communities_result.get('communities', [])\n",- "community_count = len(communities) if communities else 0\n",- "\n",- "# Analyze connectivity\n",- "connectivity_results = connectivity_analyzer.analyze_connectivity(knowledge_graph)\n",- "\n",- "# AML Pattern Detection using Inference Engine\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "\n",- "# Define AML rules\n",- "aml_rules = [\n",- " {\n",- " \"name\": \"tumbling_pattern\",\n",- " \"condition\": \"high_transaction_count AND multiple_intermediate_wallets\",\n",- " \"action\": \"flag_as_tumbling\"\n",- " },\n",- " {\n",- " \"name\": \"mixing_pattern\",\n",- " \"condition\": \"funds_split_into_multiple_addresses AND rapid_consolidation\",\n",- " \"action\": \"flag_as_mixing\"\n",- " },\n",- " {\n",- " \"name\": \"suspicious_flow\",\n",- " \"condition\": \"large_value_transfer AND short_time_window\",\n",- " \"action\": \"flag_as_suspicious\"\n",- " }\n",- "]\n",- "\n",- "for rule in aml_rules:\n",- " rule_manager.add_rule(rule[\"name\"], rule[\"condition\"], rule[\"action\"])\n",- "\n",- "# Add facts from graph analysis\n",- "aml_facts = []\n",- "for wallet_id, centrality in top_central_wallets[:5]:\n",- " aml_facts.append({\n",- " \"wallet\": wallet_id,\n",- " \"centrality\": centrality,\n",- " \"high_transaction_count\": True if centrality > 0.1 else False\n",- " })\n",- "\n",- "# Detect patterns\n",- "suspicious_patterns = []\n",- "for wallet_id, centrality in top_central_wallets:\n",- " if centrality > 0.15:\n",- " suspicious_patterns.append({\n",- " \"wallet\": wallet_id,\n",- " \"pattern\": \"high_centrality\",\n",- " \"risk_score\": min(centrality * 10, 10),\n",- " \"description\": f\"Wallet {wallet_id[:10]}... has high betweenness centrality ({centrality:.3f}), indicating potential mixing/tumbling\"\n",- " })\n",- "\n",- "# Check for rapid transactions (tumbling pattern)\n",- "wallet_transaction_counts = {}\n",- "for rel in relationships:\n",- " source = rel[\"source\"]\n",- " wallet_transaction_counts[source] = wallet_transaction_counts.get(source, 0) + 1\n",- "\n",- "for wallet_id, count in wallet_transaction_counts.items():\n",- " if count >= 3:\n",- " suspicious_patterns.append({\n",- " \"wallet\": wallet_id,\n",- " \"pattern\": \"rapid_transactions\",\n",- " \"risk_score\": min(count * 2, 10),\n",- " \"description\": f\"Wallet {wallet_id[:10]}... has {count} outgoing transactions, potential tumbling\"\n",- " })\n",- "\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"Found {community_count} wallet communities\")\n",- "print(f\"Identified {len(suspicious_patterns)} suspicious patterns\")\n",- "print(f\"\\nTop 5 Central Wallets:\")\n",- "for i, (wallet_id, centrality) in enumerate(top_central_wallets[:5], 1):\n",- " print(f\" {i}. {wallet_id[:20]}... (centrality: {centrality:.3f})\")\n",- "print(f\"\\nSuspicious Patterns Detected:\")\n",- "for pattern in suspicious_patterns[:5]:\n",- " print(f\" - {pattern['pattern']}: {pattern['wallet'][:20]}... (risk: {pattern['risk_score']:.1f}/10)\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Alerts and Reports\n",- "\n",- "Generate AML alerts and comprehensive analysis reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "kg_quality_assessor = KGQualityAssessor()\n",- "conflict_detector = ConflictDetector()\n",- "\n",- "# Assess graph quality\n",- "quality_metrics = kg_quality_assessor.assess_quality(knowledge_graph)\n",-=======- "\n",- "quality_metrics = {'completeness': 0.95, 'consistency': 0.98}\n",->>>>>>> Stashed changes-=======--- "\n",- "quality_metrics = {'completeness': 0.95, 'consistency': 0.98}\n",-->>>>>>> main- "\n",- "# Detect conflicts\n",- "conflicts = []\n",- "\n",- "# Generate alerts\n",- "alerts = []\n",- "for pattern in suspicious_patterns:\n",- " if pattern[\"risk_score\"] >= 5.0:\n",- " alerts.append({\n",- " \"alert_id\": f\"AML_{pattern['wallet'][:8]}\",\n",- " \"type\": \"AML_SUSPICIOUS_PATTERN\",\n",- " \"severity\": \"HIGH\" if pattern[\"risk_score\"] >= 7.0 else \"MEDIUM\",\n",- " \"wallet\": pattern[\"wallet\"],\n",- " \"pattern\": pattern[\"pattern\"],\n",- " \"risk_score\": pattern[\"risk_score\"],\n",- " \"description\": pattern[\"description\"],\n",- " \"timestamp\": datetime.now().isoformat()\n",- " })\n",- "\n",- "# Export knowledge graph\n",- "kg_json = json_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"transaction_kg.json\"))\n",- "kg_rdf = rdf_exporter.export(knowledge_graph, output_path=os.path.join(temp_dir, \"transaction_kg.rdf\"))\n",- "\n",- "# Generate report\n",- "report_content = f\"\"\"\n",- "# Blockchain Transaction Network Analysis Report\n",- "\n",- "## Executive Summary\n",- "- Total Transactions Analyzed: {len(transaction_entities)}\n",- "- Unique Wallets: {len(wallet_entities)}\n",- "- Suspicious Patterns Detected: {len(suspicious_patterns)}\n",- "- High-Risk Alerts: {len([a for a in alerts if a['severity'] == 'HIGH'])}\n",- "\n",- "## Graph Quality Metrics\n",- "- Nodes: {quality_metrics.get('node_count', len(knowledge_graph.nodes))}\n",- "- Edges: {quality_metrics.get('edge_count', len(knowledge_graph.edges))}\n",- "- Completeness: {quality_metrics.get('completeness', 0):.2%}\n",- "- Consistency: {quality_metrics.get('consistency', 0):.2%}\n",- "\n",- "## Top Suspicious Patterns\n",- "\"\"\"\n",- "for i, pattern in enumerate(suspicious_patterns[:10], 1):\n",- " report_content += f\"\"\"\n",- "### {i}. {pattern['pattern'].upper()}\n",- "- Wallet: {pattern['wallet']}\n",- "- Risk Score: {pattern['risk_score']:.1f}/10\n",- "- Description: {pattern['description']}\n",- "\"\"\"\n",- "\n",- "report_content += f\"\"\"\n",- "## Alerts Generated\n",- "\"\"\"\n",- "for alert in alerts:\n",- " report_content += f\"\"\"\n",- "- **{alert['alert_id']}** ({alert['severity']}): {alert['description']}\n",- "\"\"\"\n",- "\n",- "report_path = os.path.join(temp_dir, \"aml_analysis_report.md\")\n",- "with open(report_path, 'w') as f:\n",- " f.write(report_content)\n",- "\n",- "print(f\"Generated {len(alerts)} AML alerts\")\n",- "print(f\"Exported knowledge graph to JSON and RDF\")\n",- "print(f\"Generated analysis report: {report_path}\")\n",- "print(f\"\\nQuality Metrics:\")\n",- "print(f\" Nodes: {quality_metrics.get('node_count', len(knowledge_graph.nodes))}\")\n",- "print(f\" Edges: {quality_metrics.get('edge_count', len(knowledge_graph.edges))}\")\n",- "print(f\" Completeness: {quality_metrics.get('completeness', 0):.2%}\")\n",- "print(f\" Consistency: {quality_metrics.get('consistency', 0):.2%}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Visualize Transaction Network\n",- "\n",- "Visualize the transaction network, patterns, and analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "# Visualize knowledge graph\n",- "kg_viz = kg_visualizer.visualize(\n",- " knowledge_graph,\n",- " layout=\"force_directed\",\n",- " highlight_nodes=[p[\"wallet\"] for p in suspicious_patterns[:5]],\n",- " node_size_by=\"centrality\"\n",- ")\n",- "\n",- "# Visualize temporal patterns\n",- "temporal_viz = temporal_visualizer.visualize(\n",- " knowledge_graph,\n",- " time_attribute=\"timestamp\",\n",- " relationship_types=[\"transfers_to\"]\n",- ")\n",- "\n",- "# Visualize analytics\n",- "analytics_viz = analytics_visualizer.visualize(\n",- " knowledge_graph,\n",- " metrics={\n",- " \"centrality\": dict(top_central_wallets[:10]),\n",- " \"communities\": communities,\n",- " \"connectivity\": connectivity_results\n",- " }\n",- ")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb b/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynbdeleted file mode 100644index 7d2c5073..00000000--- a/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb+++ /dev/null@@ -1,517 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/01_Anomaly_Detection_Real_Time.ipynb)\n",- "\n",- "# Real-Time Anomaly Detection Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete real-time anomaly detection pipeline for cybersecurity: stream security logs from multiple sources, parse in real-time, build temporal knowledge graph, detect anomalies using pattern detection and inference, generate alerts, and monitor continuously.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalPatternDetector, TemporalGraphQuery, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, AutomatedFixer\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Stream Security Logs \u2192 Real-Time Parsing \u2192 Extract Entities \u2192 Build Temporal KG \u2192 Pattern Detection \u2192 Anomaly Detection \u2192 Generate Alerts \u2192 Monitor \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Stream Security Logs from Multiple Sources\n",- "\n",- "Stream security logs from files, databases, and real-time sources.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalPatternDetector, TemporalGraphQuery, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "import time\n",- "from datetime import datetime, timedelta\n",- "from collections import deque\n",- "\n",- "stream_ingestor = StreamIngestor()\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "# Real streaming sources configuration\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"security_logs\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"semantica_security_monitor\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"security_events\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real database connection for security logs\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/security_logs_db\"\n",- "db_query = \"SELECT * FROM security_events WHERE timestamp > NOW() - INTERVAL '1 hour' ORDER BY timestamp DESC LIMIT 1000\"\n",- "\n",- "# Real security feed URLs for threat intelligence\n",- "security_feeds = [\n",- " \"https://www.cisa.gov/news.xml\",\n",- " \"https://www.us-cert.gov/ncas/alerts.xml\"\n",- "]\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Real-world streaming security log format (simulating real-time stream)\n",- "security_log_stream_file = os.path.join(temp_dir, \"security_log_stream.json\")\n",- "stream_logs = [\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=5)).isoformat(),\n",- " \"source_ip\": \"192.168.1.50\",\n",- " \"destination_ip\": \"10.0.0.100\",\n",- " \"event_type\": \"normal_traffic\",\n",- " \"bytes_sent\": 1024,\n",- " \"bytes_received\": 2048,\n",- " \"protocol\": \"TCP\",\n",- " \"port\": 80\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=4)).isoformat(),\n",- " \"source_ip\": \"203.0.113.100\",\n",- " \"destination_ip\": \"10.0.0.100\",\n",- " \"event_type\": \"suspicious_connection\",\n",- " \"bytes_sent\": 5000000,\n",- " \"bytes_received\": 1000,\n",- " \"protocol\": \"TCP\",\n",- " \"port\": 443\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=3)).isoformat(),\n",- " \"source_ip\": \"192.168.1.50\",\n",- " \"destination_ip\": \"10.0.0.100\",\n",- " \"event_type\": \"normal_traffic\",\n",- " \"bytes_sent\": 512,\n",- " \"bytes_received\": 1024,\n",- " \"protocol\": \"UDP\",\n",- " \"port\": 53\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=2)).isoformat(),\n",- " \"source_ip\": \"198.51.100.50\",\n",- " \"destination_ip\": \"10.0.0.100\",\n",- " \"event_type\": \"port_scan\",\n",- " \"bytes_sent\": 100,\n",- " \"bytes_received\": 0,\n",- " \"protocol\": \"TCP\",\n",- " \"port\": 22\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=1)).isoformat(),\n",- " \"source_ip\": \"203.0.113.100\",\n",- " \"destination_ip\": \"10.0.0.100\",\n",- " \"event_type\": \"data_exfiltration\",\n",- " \"bytes_sent\": 10000000,\n",- " \"bytes_received\": 500,\n",- " \"protocol\": \"TCP\",\n",- " \"port\": 443\n",- " }\n",- "]\n",- "\n",- "with open(security_log_stream_file, 'w') as f:\n",- " json.dump(stream_logs, f, indent=2)\n",- "\n",- "# Simulate streaming by processing logs in batches\n",- "log_stream = deque(stream_logs)\n",- "file_objects = file_ingestor.ingest_file(security_log_stream_file, read_content=True)\n",- "\n",- "# Parse streaming logs\n",- "parsed_stream = json_parser.parse(security_log_stream_file)\n",- "\n",- "print(f\"Streaming security logs initialized\")\n",- "print(f\"Ingested {len([file_objects]) if file_objects else 0} log stream files\")\n",- "print(f\"Parsed {len(parsed_stream.data) if parsed_stream and parsed_stream.data else 0} log entries\")\n",- "print(f\"Stream ready for real-time processing\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Real-Time Parsing and Entity Extraction\n",- "\n",- "Parse streaming logs in real-time and extract security entities.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "# Real-time processing loop (simulated)\n",- "security_entities = []\n",- "stream_relationships = []\n",- "detected_events = []\n",- "\n",- "# Process logs in real-time batches\n",- "for log_entry in parsed_stream.data if parsed_stream and parsed_stream.data else []:\n",- " if isinstance(log_entry, dict):\n",- " log_text = f\"{log_entry.get('event_type', '')} from {log_entry.get('source_ip', '')} to {log_entry.get('destination_ip', '')} on port {log_entry.get('port', '')}\"\n",- " \n",- " entities = ner_extractor.extract(log_text)\n",- " relationships = relation_extractor.extract(log_text, entities)\n",- " events = event_detector.detect_events(log_text)\n",- " \n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"source_ip\", \"\"),\n",- " \"type\": \"IP_Address\",\n",- " \"name\": log_entry.get(\"source_ip\", \"\"),\n",- " \"properties\": {\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\"),\n",- " \"source\": \"stream\"\n",- " }\n",- " })\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"type\": \"IP_Address\",\n",- " \"name\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"properties\": {\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\"),\n",- " \"source\": \"stream\"\n",- " }\n",- " })\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"event_type\", \"\"),\n",- " \"type\": \"Security_Event\",\n",- " \"name\": log_entry.get(\"event_type\", \"\"),\n",- " \"properties\": {\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\"),\n",- " \"bytes_sent\": log_entry.get(\"bytes_sent\", 0),\n",- " \"bytes_received\": log_entry.get(\"bytes_received\", 0),\n",- " \"protocol\": log_entry.get(\"protocol\", \"\"),\n",- " \"port\": log_entry.get(\"port\", 0)\n",- " }\n",- " })\n",- " \n",- " stream_relationships.append({\n",- " \"source\": log_entry.get(\"source_ip\", \"\"),\n",- " \"target\": log_entry.get(\"event_type\", \"\"),\n",- " \"type\": \"triggered\",\n",- " \"properties\": {\"timestamp\": log_entry.get(\"timestamp\", \"\")}\n",- " })\n",- " stream_relationships.append({\n",- " \"source\": log_entry.get(\"event_type\", \"\"),\n",- " \"target\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"type\": \"targeted\",\n",- " \"properties\": {\"timestamp\": log_entry.get(\"timestamp\", \"\")}\n",- " })\n",- " \n",- " detected_events.extend(events)\n",- "\n",- "print(f\"Real-time processing complete\")\n",- "print(f\"Extracted {len(security_entities)} security entities\")\n",- "print(f\"Extracted {len(stream_relationships)} relationships\")\n",- "print(f\"Detected {len(detected_events)} events\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Temporal Knowledge Graph\n",- "\n",- "Build and continuously update temporal knowledge graph from streaming data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "# Build temporal KG from streaming data\n",- "temporal_kg = builder.build(security_entities, stream_relationships)\n",- "\n",- "# Analyze graph structure in real-time\n",- "metrics = graph_analyzer.compute_metrics(temporal_kg)\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(temporal_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(temporal_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(temporal_kg)\n",- "\n",- "print(f\"Built temporal knowledge graph from stream\")\n",- "print(f\" Entities: {len(temporal_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(temporal_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities: {len(communities)}\")\n",- "print(f\" Central entities: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Real-Time Pattern Detection\n",- "\n",- "Detect temporal patterns and anomalies in real-time.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Detect temporal patterns\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " temporal_kg,\n",- " pattern_type=\"anomaly\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Real-time anomaly detection using inference\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Define real-time anomaly detection rules\n",- "inference_engine.add_rule(\"IF bytes_sent > 1000000 AND bytes_received < 1000 THEN potential_data_exfiltration\")\n",- "inference_engine.add_rule(\"IF event_type is port_scan AND port is 22 THEN ssh_brute_force\")\n",- "inference_engine.add_rule(\"IF multiple events from same source_ip in short time THEN suspicious_activity\")\n",- "\n",- "# Add facts from streaming logs\n",- "for log_entry in parsed_stream.data if parsed_stream and parsed_stream.data else []:\n",- " if isinstance(log_entry, dict):\n",- " inference_engine.add_fact({\n",- " \"source_ip\": log_entry.get(\"source_ip\", \"\"),\n",- " \"event_type\": log_entry.get(\"event_type\", \"\"),\n",- " \"bytes_sent\": log_entry.get(\"bytes_sent\", 0),\n",- " \"bytes_received\": log_entry.get(\"bytes_received\", 0),\n",- " \"port\": log_entry.get(\"port\", 0),\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\")\n",- " })\n",- "\n",- "# # inferred_anomalies = inference_engine.forward_chain()\n",- "\n",- "# Real-time anomaly scoring\n",- "real_time_anomalies = []\n",- "for log_entry in parsed_stream.data if parsed_stream and parsed_stream.data else []:\n",- " if isinstance(log_entry, dict):\n",- " anomaly_score = 0\n",- " reasons = []\n",- " \n",- " if log_entry.get(\"bytes_sent\", 0) > 1000000:\n",- " anomaly_score += 5\n",- " reasons.append(\"Unusually large data transfer\")\n",- " \n",- " if log_entry.get(\"event_type\") in [\"port_scan\", \"data_exfiltration\"]:\n",- " anomaly_score += 4\n",- " reasons.append(\"High-risk event type\")\n",- " \n",- " if log_entry.get(\"bytes_sent\", 0) > log_entry.get(\"bytes_received\", 0) * 100:\n",- " anomaly_score += 3\n",- " reasons.append(\"Asymmetric traffic pattern\")\n",- " \n",- " if anomaly_score >= 3:\n",- " real_time_anomalies.append({\n",- " \"source_ip\": log_entry.get(\"source_ip\", \"\"),\n",- " \"destination_ip\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"event_type\": log_entry.get(\"event_type\", \"\"),\n",- " \"severity\": \"high\" if anomaly_score >= 5 else \"medium\",\n",- " \"score\": anomaly_score,\n",- " \"reasons\": reasons,\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\")\n",- " })\n",- "\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"Inferred {len(inferred_anomalies)} anomalies from rules\")\n",- "print(f\"Identified {len(real_time_anomalies)} real-time anomalies\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Real-Time Alerts\n",- "\n",- "Generate and send alerts for detected anomalies.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(temporal_kg)\n",- "\n",- "# Generate alerts\n",- "alerts = []\n",- "for anomaly in real_time_anomalies:\n",- " alert = {\n",- " \"alert_id\": f\"alert_{anomaly['source_ip']}_{int(time.time())}\",\n",- " \"severity\": anomaly[\"severity\"],\n",- " \"source_ip\": anomaly[\"source_ip\"],\n",- " \"destination_ip\": anomaly[\"destination_ip\"],\n",- " \"event_type\": anomaly[\"event_type\"],\n",- " \"score\": anomaly[\"score\"],\n",- " \"reasons\": anomaly[\"reasons\"],\n",- " \"timestamp\": anomaly[\"timestamp\"],\n",- " \"status\": \"active\"\n",- " }\n",- " alerts.append(alert)\n",- "\n",- "# Export alerts\n",- "json_exporter.export_knowledge_graph(temporal_kg, os.path.join(temp_dir, \"realtime_kg.json\"))\n",- "csv_exporter.export_entities(security_entities, os.path.join(temp_dir, \"realtime_entities.csv\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Real-time anomaly detection identified {len(real_time_anomalies)} anomalies\",\n",- " \"total_events\": len(parsed_stream.data) if parsed_stream and parsed_stream.data else 0,\n",- " \"anomalies\": len(real_time_anomalies),\n",- " \"alerts\": len(alerts),\n",- " \"quality_score\": quality_score.get('overall_score', 0),\n",- " \"high_severity\": len([a for a in alerts if a.get('severity') == 'high'])\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Generated {len(alerts)} real-time alerts\")\n",- "print(f\"High severity alerts: {len([a for a in alerts if a.get('severity') == 'high'])}\")\n",- "print(f\"Report length: {len(report)} characters\")\n",- "print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Real-Time Monitoring and Visualization\n",- "\n",- "Monitor security events in real-time and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(temporal_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(temporal_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(temporal_kg, output=\"interactive\")\n",- "\n",- "print(f\"Real-time monitoring active\")\n",- "print(f\"Monitoring {len(temporal_kg.get('entities', []))} entities in real-time\")\n",- "print(f\"Active alerts: {len(alerts)}\")\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Stream Logs \u2192 Real-Time Parse \u2192 Extract \u2192 Temporal KG \u2192 Pattern Detection \u2192 Anomaly Detection \u2192 Alerts \u2192 Monitor \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb b/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynbdeleted file mode 100644index 2b0f9205..00000000--- a/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb+++ /dev/null@@ -1,528 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/02_Incident_Analysis.ipynb)\n",- "\n",- "# Incident Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete security incident analysis pipeline: ingest security logs from multiple sources (files, databases, streams), parse structured and unstructured logs, extract security entities, build knowledge graph, analyze relationships, detect anomalies, and generate incident reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, XMLParser, StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector, ProvenanceTracker\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Quality**: ProvenanceTracker\n",->>>>>>> Stashed changes-=======- "- **Quality**: ProvenanceTracker\n",->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Multiple Security Sources \u2192 Parse Logs \u2192 Extract Security Entities \u2192 Build Incident KG \u2192 Analyze Relationships \u2192 Detect Anomalies \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Security Logs from Multiple Sources\n",- "\n",- "Ingest security logs from files, databases, streams, and threat intelligence feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, XMLParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD-- "from semantica.conflicts import ConflictDetector\n",-=======- "# from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "from semantica.kg import ProvenanceTracker\n",- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "xml_parser = XMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Real-world security log formats\n",- "security_logs_json = os.path.join(temp_dir, \"security_logs.json\")\n",- "security_logs_data = [\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(hours=2)).isoformat(),\n",- " \"source_ip\": \"192.168.1.100\",\n",- " \"destination_ip\": \"10.0.0.50\",\n",- " \"event_type\": \"failed_login\",\n",- " \"user\": \"admin\",\n",- " \"severity\": \"medium\",\n",- " \"message\": \"Multiple failed login attempts detected\"\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"source_ip\": \"203.0.113.45\",\n",- " \"destination_ip\": \"10.0.0.50\",\n",- " \"event_type\": \"port_scan\",\n",- " \"severity\": \"high\",\n",- " \"message\": \"Port scanning activity detected from external IP\"\n",- " },\n",- " {\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=30)).isoformat(),\n",- " \"source_ip\": \"192.168.1.100\",\n",- " \"destination_ip\": \"10.0.0.75\",\n",- " \"event_type\": \"data_exfiltration\",\n",- " \"user\": \"user123\",\n",- " \"severity\": \"critical\",\n",- " \"message\": \"Large data transfer detected to external server\"\n",- " }\n",- "]\n",- "\n",- "with open(security_logs_json, 'w') as f:\n",- " json.dump(security_logs_data, f, indent=2)\n",- "\n",- "# XML format security events (common in SIEM systems)\n",- "security_events_xml = os.path.join(temp_dir, \"security_events.xml\")\n",- "xml_content = \"\"\"<?xml version=\"1.0\"?>\n",- "<security_events>\n",- " <event>\n",- " <timestamp>2024-01-15T14:30:00</timestamp>\n",- " <source_ip>172.16.0.10</source_ip>\n",- " <destination_ip>10.0.0.50</destination_ip>\n",- " <event_type>malware_detection</event_type>\n",- " <severity>high</severity>\n",- " <description>Malware signature detected in file transfer</description>\n",- " </event>\n",- " <event>\n",- " <timestamp>2024-01-15T15:00:00</timestamp>\n",- " <source_ip>192.168.1.200</source_ip>\n",- " <destination_ip>10.0.0.50</destination_ip>\n",- " <event_type>unauthorized_access</event_type>\n",- " <severity>critical</severity>\n",- " <description>Unauthorized access attempt to restricted resource</description>\n",- " </event>\n",- "</security_events>\"\"\"\n",- "\n",- "with open(security_events_xml, 'w') as f:\n",- " f.write(xml_content)\n",- "\n",- "# Ingest from files\n",- "file_objects = file_ingestor.ingest_file(security_logs_json, read_content=True)\n",- "file_objects_xml = file_ingestor.ingest_file(security_events_xml, read_content=True)\n",- "\n",- "# Parse structured logs\n",- "parsed_json = json_parser.parse(security_logs_json)\n",- "parsed_xml = xml_parser.parse(security_events_xml)\n",- "\n",- "# Real security intelligence feed URLs\n",- "security_feeds = [\n",- " \"https://www.cisa.gov/news.xml\", # CISA Security Advisories\n",- " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT Alerts\n",- " \"https://feeds.feedburner.com/SecurityWeek\", # Security Week\n",- " \"https://www.darkreading.com/rss.xml\" # Dark Reading\n",- "]\n",- "\n",- "threat_feed_list = []\n",- "for feed_url in security_feeds:\n",- " threat_feed = feed_ingestor.ingest_feed(feed_url)\n",- " if threat_feed:\n",- " threat_feed_list.append(threat_feed)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "print(f\"Ingested {len([file_objects]) if file_objects else 0} JSON log files\")\n",- "print(f\"Ingested {len([file_objects_xml]) if file_objects_xml else 0} XML event files\")\n",- "print(f\"Parsed {len(parsed_json.data) if parsed_json and parsed_json.data else 0} JSON log entries\")\n",- "print(f\"Parsed {len(parsed_xml.elements) if parsed_xml else 0} XML event elements\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Security Entities and Relationships\n",- "\n",- "Extract security entities (IPs, users, events) and relationships from parsed logs.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_events = []\n",- "\n",- "# Extract from JSON logs\n",- "if parsed_json and parsed_json.data:\n",- " for log_entry in parsed_json.data:\n",- " if isinstance(log_entry, dict):\n",- " log_text = f\"{log_entry.get('event_type', '')} from {log_entry.get('source_ip', '')} to {log_entry.get('destination_ip', '')}: {log_entry.get('message', '')}\"\n",- " \n",- " entities = ner_extractor.extract(log_text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(log_text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " events = event_detector.detect_events(log_text)\n",- " all_events.extend(events)\n",- "\n",- "# Extract from XML events\n",- "if parsed_xml and parsed_xml.elements:\n",- " for elem in parsed_xml.elements:\n",- " if hasattr(elem, 'text') and elem.text:\n",- " entities = ner_extractor.extract(elem.text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(elem.text, entities)\n",- " all_relationships.extend(relationships)\n",- "\n",- "# Build structured entities from log data\n",- "security_entities = []\n",- "for log_entry in parsed_json.data if parsed_json and parsed_json.data else []:\n",- " if isinstance(log_entry, dict):\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"source_ip\", \"\"),\n",- " \"type\": \"IP_Address\",\n",- " \"name\": log_entry.get(\"source_ip\", \"\"),\n",- " \"properties\": {\"source\": \"security_logs\"}\n",- " })\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"type\": \"IP_Address\",\n",- " \"name\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"properties\": {\"source\": \"security_logs\"}\n",- " })\n",- " if log_entry.get(\"user\"):\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"user\", \"\"),\n",- " \"type\": \"User\",\n",- " \"name\": log_entry.get(\"user\", \"\"),\n",- " \"properties\": {\"source\": \"security_logs\"}\n",- " })\n",- " security_entities.append({\n",- " \"id\": log_entry.get(\"event_type\", \"\"),\n",- " \"type\": \"Security_Event\",\n",- " \"name\": log_entry.get(\"event_type\", \"\"),\n",- " \"properties\": {\n",- " \"severity\": log_entry.get(\"severity\", \"\"),\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\"),\n",- " \"message\": log_entry.get(\"message\", \"\")\n",- " }\n",- " })\n",- "\n",- "incident_relationships = []\n",- "for log_entry in parsed_json.data if parsed_json and parsed_json.data else []:\n",- " if isinstance(log_entry, dict):\n",- " incident_relationships.append({\n",- " \"source\": log_entry.get(\"source_ip\", \"\"),\n",- " \"target\": log_entry.get(\"event_type\", \"\"),\n",- " \"type\": \"triggered\",\n",- " \"properties\": {\"timestamp\": log_entry.get(\"timestamp\", \"\")}\n",- " })\n",- " incident_relationships.append({\n",- " \"source\": log_entry.get(\"event_type\", \"\"),\n",- " \"target\": log_entry.get(\"destination_ip\", \"\"),\n",- " \"type\": \"targeted\",\n",- " \"properties\": {\"timestamp\": log_entry.get(\"timestamp\", \"\")}\n",- " })\n",- "\n",- "print(f\"Extracted {len(security_entities)} security entities\")\n",- "print(f\"Extracted {len(incident_relationships)} incident relationships\")\n",- "print(f\"Detected {len(all_events)} security events\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Incident Knowledge Graph\n",- "\n",- "Build a knowledge graph from security entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "provenance_tracker = ProvenanceTracker()\n",- "\n",- "incident_kg = builder.build(security_entities, incident_relationships)\n",- "\n",- "# Track provenance\n",- "for entity in security_entities:\n",- " provenance_tracker.track_entity(entity.get(\"id\"), entity.get(\"properties\", {}).get(\"source\", \"unknown\"), entity)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(incident_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(incident_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(incident_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "\n",- "print(f\"Built incident knowledge graph\")\n",- "print(f\" Entities: {len(incident_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(incident_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n",- "print(f\" Central entities: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze Relationships and Detect Anomalies\n",- "\n",- "Analyze security relationships and detect anomalous patterns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "conflict_detector = ConflictDetector()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "# Define security rules\n",- "inference_engine.add_rule(\"IF event_type is port_scan AND severity is high THEN potential_intrusion\")\n",- "inference_engine.add_rule(\"IF event_type is data_exfiltration AND severity is critical THEN data_breach\")\n",- "inference_engine.add_rule(\"IF multiple failed_login events from same source_ip THEN brute_force_attack\")\n",- "\n",- "# Add facts from security events\n",- "for log_entry in parsed_json.data if parsed_json and parsed_json.data else []:\n",- " if isinstance(log_entry, dict):\n",- " inference_engine.add_fact({\n",- " \"event_type\": log_entry.get(\"event_type\", \"\"),\n",- " \"severity\": log_entry.get(\"severity\", \"\"),\n",- " \"source_ip\": log_entry.get(\"source_ip\", \"\")\n",- " })\n",- "\n",- "# Run inference\n",- "# inferred_threats = inference_engine.forward_chain()\n",- "\n",- "# Detect anomalies based on patterns\n",- "anomalies = []\n",- "for log_entry in parsed_json.data if parsed_json and parsed_json.data else []:\n",- " if isinstance(log_entry, dict):\n",- " anomaly_score = 0\n",- " reasons = []\n",- " \n",- " if log_entry.get(\"severity\") == \"critical\":\n",- " anomaly_score += 5\n",- " reasons.append(\"Critical severity event\")\n",- " \n",- " if log_entry.get(\"event_type\") in [\"data_exfiltration\", \"unauthorized_access\"]:\n",- " anomaly_score += 4\n",- " reasons.append(\"High-risk event type\")\n",- " \n",- " if log_entry.get(\"severity\") == \"high\" and log_entry.get(\"event_type\") == \"port_scan\":\n",- " anomaly_score += 3\n",- " reasons.append(\"Port scanning detected\")\n",- " \n",- " if anomaly_score >= 3:\n",- " anomalies.append({\n",- " \"event\": log_entry.get(\"event_type\", \"\"),\n",- " \"source_ip\": log_entry.get(\"source_ip\", \"\"),\n",- " \"severity\": log_entry.get(\"severity\", \"\"),\n",- " \"score\": anomaly_score,\n",- " \"reasons\": reasons,\n",- " \"timestamp\": log_entry.get(\"timestamp\", \"\")\n",- " })\n",- "\n",- "# Detect conflicts in security data\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "conflicts = conflict_detector.detect_value_conflicts(security_entities, \"name\")\n",-=======-->>>>>>> main- "\n",- "print(f\"Analyzed security relationships\")\n",- "print(f\"Inferred {len(inferred_threats)} potential threats\")\n",- "print(f\"Detected {len(anomalies)} anomalies\")\n",-<<<<<<< HEAD- "print(f\"Found {len(conflicts)} data conflicts\")\n"-=======- "\n",- "print(f\"Analyzed security relationships\")\n",- "print(f\"Inferred {len(inferred_threats)} potential threats\")\n",- "print(f\"Detected {len(anomalies)} anomalies\")\n"->>>>>>> Stashed changes-=======-->>>>>>> main- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Incident Reports\n",- "\n",- "Generate comprehensive incident analysis reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_score = quality_assessor.assess_overall_quality(incident_kg)\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "json_exporter.export_knowledge_graph(incident_kg, os.path.join(temp_dir, \"incident_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(incident_kg, os.path.join(temp_dir, \"incident_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Security incident analysis identified {len(anomalies)} anomalies and {len(inferred_threats)} potential threats\",\n",- " \"total_events\": len(parsed_json.data) if parsed_json and parsed_json.data else 0,\n",- " \"anomalies\": len(anomalies),\n",- " \"threats\": len(inferred_threats),\n",- " \"quality_score\": 0.95,\n",- " \"critical_events\": len([e for e in anomalies if e.get('severity') == 'critical'])\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n",- "print(f\"Graph quality score: 0.950\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Visualize Security Incidents\n",- "\n",- "Visualize incident knowledge graph and security patterns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(incident_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(incident_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(incident_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Multiple Security Sources \u2192 Parse Logs \u2192 Extract Entities \u2192 Build KG \u2192 Analyze \u2192 Detect Anomalies \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/03_Threat_Correlation.ipynb b/cookbook/use_cases/cybersecurity/03_Threat_Correlation.ipynbdeleted file mode 100644index 1793a6ec..00000000--- a/cookbook/use_cases/cybersecurity/03_Threat_Correlation.ipynb+++ /dev/null@@ -1,456 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/03_Threat_Correlation.ipynb)\n",- "\n",- "# Threat Correlation Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete threat correlation pipeline for cybersecurity: ingest threat feeds from multiple sources, extract IOCs, build temporal knowledge graph, correlate threats, detect campaigns, and generate reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: XMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ProvenanceTracker, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), ExplanationGenerator\n",- "- **Quality**: ProvenanceTracker\n",->>>>>>> Stashed changes-=======- "- **Quality**: ProvenanceTracker\n",->>>>>>> main- "- **Export**: RDFExporter, ReportGenerator\n",- "- **Visualization**: AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Multiple Threat Feeds \u2192 Parse \u2192 Extract IOCs \u2192 Build Temporal KG \u2192 Correlate Threats \u2192 Detect Campaigns \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Threat Feeds\n",- "\n",- "Ingest threat intelligence from multiple sources.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, FeedIngestor, DBIngestor, WebIngestor\n",- "from semantica.parse import XMLParser, StructuredDataParser, JSONParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.kg import ProvenanceTracker\n",- "from semantica.conflicts import ConflictDetector\n",- "from semantica.export import RDFExporter, ReportGenerator\n",- "from semantica.visualization import AnalyticsVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "xml_parser = XMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "json_parser = JSONParser()\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Real threat intelligence feed URLs\n",- "threat_feeds = [\n",- " \"https://www.cisa.gov/news.xml\", # CISA Security Advisories\n",- " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT Alerts\n",- " \"https://feeds.feedburner.com/SecurityWeek\", # Security Week\n",- " \"https://www.darkreading.com/rss.xml\" # Dark Reading\n",- "]\n",- "\n",- "# Real database connection pattern (PostgreSQL example)\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/threat_intel_db\"\n",- "db_query = \"SELECT ioc, ioc_type, timestamp, severity, source FROM threat_indicators WHERE timestamp > NOW() - INTERVAL '7 days'\"\n",- "\n",- "# Real web API endpoints for threat intelligence\n",- "threat_apis = [\n",- " \"https://api.github.com/repos/mitre/cti/contents/enterprise-attack/attack-pattern\", # MITRE ATT&CK\n",- " \"https://www.virustotal.com/vtapi/v2/domain/report\", # VirusTotal API (requires API key)\n",- " \"https://api.shodan.io/shodan/host/search\" # Shodan API (requires API key)\n",- "]\n",- "\n",- "# Ingest from real RSS feeds\n",- "feed_data_list = []\n",- "for feed_url in threat_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " feed_data_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- " print(f\" Items: {len(feed_data.items) if hasattr(feed_data, 'items') else 0}\")\n",- "\n",- "# Ingest from web APIs (example with public API)\n",- "web_content = web_ingestor.ingest_url(\"https://api.github.com/repos/mitre/cti\")\n",- "if web_content:\n",- " print(f\" Ingested web content\")\n",- "\n",- "# Database ingestion pattern (would connect to real database)\n",- "# Example: Export from threat intelligence database\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"threat_indicators\",\n",- " limit=1000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "# Simulate database structure for demonstration if needed\n",- "if not db_data:\n",- " db_data = {\n",- " \"data\": [\n",- " {\"ioc\": \"192.168.1.100\", \"ioc_type\": \"IP\", \"timestamp\": datetime.now().isoformat(), \"severity\": \"high\", \"source\": \"threat_feed\"},\n",- " {\"ioc\": \"malicious-domain.com\", \"ioc_type\": \"Domain\", \"timestamp\": datetime.now().isoformat(), \"severity\": \"medium\", \"source\": \"threat_feed\"}\n",- " ]\n",- " }\n",- "\n",- "# Parse feed data\n",- "parsed_feeds = []\n",- "for feed_data in feed_data_list:\n",- " if hasattr(feed_data, 'items'):\n",- " for item in feed_data.items[:10]: # Process first 10 items\n",- " parsed_feeds.append({\n",- " \"title\": item.title if hasattr(item, 'title') else \"\",\n",- " \"description\": item.description if hasattr(item, 'description') else \"\",\n",- " \"published\": item.published if hasattr(item, 'published') else \"\",\n",- " \"link\": item.link if hasattr(item, 'link') else \"\"\n",- " })\n",- "\n",- "parsed_db = structured_parser.parse_json(json.dumps(db_data)) if db_data else None\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Feeds ingested: {len(feed_data_list)}\")\n",- "print(f\" Feed items processed: {len(parsed_feeds)}\")\n",- "print(f\" Database records: {len(db_data.get('data', [])) if db_data else 0}\")\n",- "print(f\" Web sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract IOCs\n",- "\n",- "Extract Indicators of Compromise (IOCs) from threat feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "\n",- "all_threat_texts = []\n",- "if parsed_xml and parsed_xml.elements:\n",- " for elem in parsed_xml.elements:\n",- " if hasattr(elem, 'text') and elem.text:\n",- " all_threat_texts.append(elem.text)\n",- "\n",- "for db_record in parsed_db.get(\"data\", threat_db_data):\n",- " threat_text = f\"IOC: {db_record.get('ioc', '')} Type: {db_record.get('type', '')} Severity: {db_record.get('severity', '')}\"\n",- " all_threat_texts.append(threat_text)\n",- "\n",- "all_entities = []\n",- "all_relationships = []\n",- "all_events = []\n",- "\n",- "for text in all_threat_texts:\n",- " entities = ner_extractor.extract(text)\n",- " all_entities.extend(entities)\n",- " \n",- " relationships = relation_extractor.extract(text, entities)\n",- " all_relationships.extend(relationships)\n",- " \n",- " events = event_detector.detect_events(text)\n",- " all_events.extend(events)\n",- "\n",- "print(f\"Extracted {len(all_entities)} IOCs\")\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n",- "print(f\"Detected {len(all_events)} events\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Temporal Knowledge Graph\n",- "\n",- "Build a temporal knowledge graph from extracted IOCs and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "\n",- "threat_entities = []\n",- "for i, entity in enumerate(all_entities[:10], 1):\n",- " threat_entities.append({\n",- " \"id\": f\"ioc_{i}\",\n",- " \"type\": entity.get(\"type\", \"IOC\"),\n",- " \"name\": entity.get(\"text\", entity.get(\"entity\", \"\")),\n",- " \"properties\": {\"timestamp\": datetime.now().isoformat()}\n",- " })\n",- "\n",- "threat_relationships = []\n",- "for i, rel in enumerate(all_relationships[:5], 1):\n",- " threat_relationships.append({\n",- " \"source\": f\"ioc_{i}\",\n",- " \"target\": f\"ioc_{i+1}\",\n",- " \"type\": rel.get(\"type\", \"related_to\"),\n",- " \"properties\": {\"timestamp\": datetime.now().isoformat()}\n",- " })\n",- "\n",- "threat_kg = builder.build(threat_entities, threat_relationships)\n",- "\n",- "print(f\"Built temporal knowledge graph\")\n",- "print(f\" Entities: {len(threat_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(threat_kg.get('relationships', []))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Correlate Threats\n",- "\n",- "Correlate threats using temporal queries and inference.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "temporal_query = TemporalGraphQuery()\n",- "pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "# # inference_engine = InferenceEngine()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "start_time = (datetime.now() - timedelta(days=7)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=threat_kg,\n",- " query=\"Find threats in the last 7 days\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "patterns = pattern_detector.detect_temporal_patterns(\n",- " threat_kg,\n",- " pattern_type=\"sequence\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "connectivity = connectivity_analyzer.analyze_connectivity(threat_kg)\n",- "\n",- "inference_engine.add_rule(\"IF IOC has high severity AND IOC is related to another IOC THEN potential_campaign\")\n",- "for entity in threat_entities[:3]:\n",- " if entity.get(\"properties\", {}).get(\"severity\") == \"high\":\n",- " inference_engine.add_fact({\"ioc\": entity.get(\"id\"), \"severity\": \"high\"})\n",- "\n",- "# # correlations = inference_engine.forward_chain()\n",- "\n",- "print(f\"Temporal query returned {len(temporal_results.get('entities', []))} entities\")\n",- "print(f\"Detected {len(patterns)} temporal patterns\")\n",- "print(f\"Connectivity: {connectivity.get('is_connected', False)}\")\n",- "print(f\"Inferred {len(correlations)} correlations\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Detect Campaigns\n",- "\n",- "Detect threat campaigns using graph analysis and inference.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "campaigns = []\n",- "\n",- "if len(patterns) > 0:\n",- " campaigns.append({\n",- " \"campaign_id\": \"campaign_1\",\n",- " \"description\": \"Detected threat campaign based on temporal patterns\",\n",- " \"iocs\": [e.get(\"id\") for e in threat_entities[:3]],\n",- " \"severity\": \"high\",\n",- " \"patterns\": len(patterns)\n",- " })\n",- "\n",- "if correlations:\n",- " campaigns.append({\n",- " \"campaign_id\": \"campaign_2\",\n",- " \"description\": \"Detected campaign from inference correlations\",\n",- " \"iocs\": [e.get(\"id\") for e in threat_entities[:2]],\n",- " \"severity\": \"medium\",\n",- " \"correlations\": len(correlations)\n",- " })\n",- "\n",- "print(f\"Detected {len(campaigns)} threat campaigns\")\n",- "for campaign in campaigns:\n",- " print(f\" Campaign: {campaign['campaign_id']} - Severity: {campaign['severity']}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Quality Assessment and Provenance\n",- "\n",- "Assess graph quality and track provenance.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "quality_assessor = KGQualityAssessor()\n",- "provenance_tracker = ProvenanceTracker()\n",- "conflict_detector = ConflictDetector()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(threat_kg)\n",- "\n",- "for entity in threat_entities:\n",- " provenance_tracker.track_entity(entity.get(\"id\"), \"threat_feed\", entity)\n",- "\n",- "conflicts = conflict_detector.detect_value_conflicts(threat_entities, \"name\")\n",- "\n",- "print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n",- "print(f\"Tracked provenance for {len(threat_entities)} entities\")\n",- "print(f\"Detected {len(conflicts)} conflicts\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Generate Reports\n",- "\n",- "Generate threat intelligence reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "rdf_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threats.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Threat correlation analysis detected {len(campaigns)} campaigns\",\n",- " \"iocs\": len(threat_entities),\n",- " \"campaigns\": campaigns,\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Visualize Results\n",- "\n",- "Visualize threat correlation results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "analytics_viz = analytics_visualizer.visualize_analytics(threat_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(threat_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Multi-source ingestion \u2192 Extraction \u2192 Temporal KG \u2192 Correlation \u2192 Campaign Detection \u2192 Quality \u2192 Reports \u2192 Visualization\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynbdeleted file mode 100644index 2d9b7e6e..00000000--- a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb+++ /dev/null@@ -1,612 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb)\n",- "\n",- "# Threat Intelligence Hybrid RAG Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete threat intelligence hybrid RAG pipeline: ingest threat intelligence from multiple sources (files, web, feeds), extract threat entities, build knowledge graph, generate embeddings, set up hybrid search (vector + temporal KG), and query threats using advanced RAG.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch\n",- "- **Context**: ContextRetriever, ContextGraphBuilder\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Multi-Source Threat Intel (Files, Web, Feeds, MCP) \u2192 Parse \u2192 Extract Entities \u2192 Build KG \u2192 Generate Embeddings \u2192 Vector Store \u2192 Hybrid RAG Setup \u2192 Query Threats \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Multi-Source Threat Intelligence Ingestion\n",- "\n",- "Ingest threat intelligence from files, web sources, and feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor, DBIngestor, MCPIngestor, ingest_mcp\n",- "from semantica.parse import JSONParser, XMLParser, HTMLParser, DocumentParser, MCPParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch\n",- "from semantica.context import ContextRetriever, ContextGraphBuilder\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "db_ingestor = DBIngestor()\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "xml_parser = XMLParser()\n",- "html_parser = HTMLParser()\n",- "document_parser = DocumentParser()\n",- "mcp_parser = MCPParser()\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Real-world threat intelligence formats\n",- "threat_intel_json = os.path.join(temp_dir, \"threat_intel.json\")\n",- "threat_data = [\n",- " {\n",- " \"threat_id\": \"APT-001\",\n",- " \"name\": \"Advanced Persistent Threat Group 1\",\n",- " \"description\": \"State-sponsored APT group targeting financial institutions\",\n",- " \"iocs\": [\"192.168.1.100\", \"malicious-domain.com\", \"hash_abc123\"],\n",- " \"tactics\": [\"initial_access\", \"persistence\", \"exfiltration\"],\n",- " \"timestamp\": (datetime.now() - timedelta(days=7)).isoformat(),\n",- " \"severity\": \"high\"\n",- " },\n",- " {\n",- " \"threat_id\": \"APT-002\",\n",- " \"name\": \"Ransomware Campaign\",\n",- " \"description\": \"Large-scale ransomware campaign targeting healthcare sector\",\n",- " \"iocs\": [\"198.51.100.50\", \"ransomware-domain.net\", \"hash_def456\"],\n",- " \"tactics\": [\"initial_access\", \"execution\", \"impact\"],\n",- " \"timestamp\": (datetime.now() - timedelta(days=3)).isoformat(),\n",- " \"severity\": \"critical\"\n",- " },\n",- " {\n",- " \"threat_id\": \"APT-003\",\n",- " \"name\": \"Phishing Campaign\",\n",- " \"description\": \"Sophisticated phishing campaign using social engineering\",\n",- " \"iocs\": [\"203.0.113.75\", \"phishing-site.org\", \"hash_ghi789\"],\n",- " \"tactics\": [\"initial_access\", \"collection\"],\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat(),\n",- " \"severity\": \"medium\"\n",- " }\n",- "]\n",- "\n",- "with open(threat_intel_json, 'w') as f:\n",- " json.dump(threat_data, f, indent=2)\n",- "\n",- "# XML format threat intelligence (STIX format)\n",- "threat_intel_xml = os.path.join(temp_dir, \"threat_intel.xml\")\n",- "xml_content = \"\"\"<?xml version=\"1.0\"?>\n",- "<threat_intelligence>\n",- " <indicator>\n",- " <id>IOC-001</id>\n",- " <type>IP</type>\n",- " <value>172.16.0.50</value>\n",- " <threat_type>malware</threat_type>\n",- " <timestamp>2024-01-15T10:00:00</timestamp>\n",- " </indicator>\n",- " <indicator>\n",- " <id>IOC-002</id>\n",- " <type>Domain</type>\n",- " <value>suspicious-domain.com</value>\n",- " <threat_type>phishing</threat_type>\n",- " <timestamp>2024-01-15T11:00:00</timestamp>\n",- " </indicator>\n",- "</threat_intelligence>\"\"\"\n",- "\n",- "with open(threat_intel_xml, 'w') as f:\n",- " f.write(xml_content)\n",- "\n",- "# Ingest from files\n",- "file_objects_json = file_ingestor.ingest_file(threat_intel_json, read_content=True)\n",- "file_objects_xml = file_ingestor.ingest_file(threat_intel_xml, read_content=True)\n",- "\n",- "# Parse threat intelligence\n",- "parsed_json = json_parser.parse(threat_intel_json)\n",- "parsed_xml = xml_parser.parse(threat_intel_xml)\n",- "\n",- "# Real threat intelligence feed URLs\n",- "threat_intel_feeds = [\n",- " \"https://www.cisa.gov/news.xml\", # CISA Security Advisories\n",- " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT Alerts\n",- " \"https://feeds.feedburner.com/SecurityWeek\", # Security Week\n",- " \"https://www.darkreading.com/rss.xml\", # Dark Reading\n",- " \"https://krebsonsecurity.com/feed/\" # Krebs on Security\n",- "]\n",- "\n",- "threat_feed_list = []\n",- "for feed_url in threat_intel_feeds:\n",- " threat_feed = feed_ingestor.ingest_feed(feed_url)\n",- " if threat_feed:\n",- " threat_feed_list.append(threat_feed)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- " print(f\" Items: {len(threat_feed.items) if hasattr(threat_feed, 'items') else 0}\")\n",- "\n",- "# Real web sources for threat intelligence\n",- "threat_web_sources = [\n",- " \"https://api.github.com/repos/mitre/cti\", # MITRE ATT&CK Framework\n",- " \"https://www.cisa.gov/known-exploited-vulnerabilities-catalog\", # CISA KEV Catalog\n",- " \"https://nvd.nist.gov/vuln/search\" # NIST NVD\n",- "]\n",- "\n",- "web_content_list = []\n",- "for web_url in threat_web_sources[:1]: # Process first URL\n",- " web_content = web_ingestor.ingest_url(web_url)\n",- " if web_content:\n",- " web_content_list.append(web_content)\n",- " print(f\" Ingested web source: {web_url}\")\n",- "\n",- "# Optional: Ingest from MCP server\n",- "# Users can bring their own threat intelligence MCP server via URL\n",- "mcp_threat_data = []\n",- "# Connect to threat intelligence MCP server via URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/threat-mcp\n",- "threat_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",- "\n",- "mcp_ingestor.connect(\n",- " \"threat_mcp_server\",\n",- " url=threat_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in threat_mcp_url else {}\n",- ")\n",- "\n",- "# Ingest threat indicators from MCP server\n",- "mcp_data = mcp_ingestor.ingest_resources(\n",- " \"threat_mcp_server\",\n",- " resource_uris=[\"resource://threats/feed\", \"resource://vulnerabilities/database\"]\n",- ")\n",- "mcp_threat_data.extend(mcp_data)\n",- "print(f\" Ingested MCP resources: {len(mcp_data)}\")\n",- "\n",- "# Or use tool-based ingestion to query threat indicators\n",- "tool_data = mcp_ingestor.ingest_tool_output(\n",- " \"threat_mcp_server\",\n",- " tool_name=\"query_threat_indicators\",\n",- " arguments={\n",- " \"indicator_type\": \"IP\",\n",- " \"date_range\": {\n",- " \"start\": (datetime.now() - timedelta(days=7)).isoformat(),\n",- " \"end\": datetime.now().isoformat()\n",- " }\n",- " }\n",- ")\n",- "if tool_data:\n",- " mcp_threat_data.append(tool_data)\n",- " print(f\" Retrieved tool data\")\n",- "\n",- "# Parse MCP responses and merge with existing threat data\n",- "for mcp_item in mcp_threat_data:\n",- " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",- " if isinstance(parsed_mcp, dict):\n",- " if \"threat_indicators\" in parsed_mcp:\n",- " # Merge threat indicators from MCP\n",- " if parsed_json and parsed_json.data:\n",- " parsed_json.data.extend(parsed_mcp.get(\"threat_indicators\", []))\n",- " else:\n",- " parsed_json.data = parsed_mcp.get(\"threat_indicators\", [])\n",- " elif \"threat_id\" in parsed_mcp:\n",- " # Single threat indicator\n",- " if parsed_json and parsed_json.data:\n",- " parsed_json.data.append(parsed_mcp)\n",- " else:\n",- " parsed_json.data = [parsed_mcp]\n",- " print(f\" Parsed MCP item\")\n",- "\n",- "mcp_ingestor.disconnect(\"threat_mcp_server\")\n",- "print(f\" Disconnected from MCP server\")\n",- "\n",- "print(f\"Ingested {len([file_objects_json]) if file_objects_json else 0} JSON threat intelligence files\")\n",- "print(f\"Ingested {len([file_objects_xml]) if file_objects_xml else 0} XML threat intelligence files\")\n",- "print(f\"Parsed {len(parsed_json.data) if parsed_json and parsed_json.data else 0} JSON threat entries\")\n",- "print(f\"Parsed {len(parsed_xml.elements) if parsed_xml else 0} XML indicator elements\")\n",- "print(f\"MCP server sources: {len(mcp_threat_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Threat Intelligence Entities\n",- "\n",- "Extract threat entities, IOCs, and relationships from threat intelligence data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "threat_entities = []\n",- "threat_relationships = []\n",- "all_documents = []\n",- "\n",- "# Extract from JSON threat intelligence\n",- "if parsed_json and parsed_json.data:\n",- " for threat in parsed_json.data:\n",- " if isinstance(threat, dict):\n",- " threat_text = f\"{threat.get('name', '')}: {threat.get('description', '')}\"\n",- " all_documents.append(threat_text)\n",- " \n",- " threat_entities.append({\n",- " \"id\": threat.get(\"threat_id\", \"\"),\n",- " \"type\": \"Threat_Actor\",\n",- " \"name\": threat.get(\"name\", \"\"),\n",- " \"properties\": {\n",- " \"description\": threat.get(\"description\", \"\"),\n",- " \"severity\": threat.get(\"severity\", \"\"),\n",- " \"timestamp\": threat.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " for ioc in threat.get(\"iocs\", []):\n",- " threat_entities.append({\n",- " \"id\": ioc,\n",- " \"type\": \"IOC\",\n",- " \"name\": ioc,\n",- " \"properties\": {\n",- " \"threat_id\": threat.get(\"threat_id\", \"\"),\n",- " \"timestamp\": threat.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " threat_relationships.append({\n",- " \"source\": threat.get(\"threat_id\", \"\"),\n",- " \"target\": ioc,\n",- " \"type\": \"uses\",\n",- " \"properties\": {\"timestamp\": threat.get(\"timestamp\", \"\")}\n",- " })\n",- " \n",- " for tactic in threat.get(\"tactics\", []):\n",- " threat_entities.append({\n",- " \"id\": tactic,\n",- " \"type\": \"Tactic\",\n",- " \"name\": tactic,\n",- " \"properties\": {}\n",- " })\n",- " threat_relationships.append({\n",- " \"source\": threat.get(\"threat_id\", \"\"),\n",- " \"target\": tactic,\n",- " \"type\": \"employs\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Extract from XML indicators\n",- "if parsed_xml and parsed_xml.elements:\n",- " for elem in parsed_xml.elements:\n",- " if hasattr(elem, 'text') and elem.text:\n",- " entities = ner_extractor.extract(elem.text)\n",- " threat_entities.extend(entities)\n",- "\n",- "print(f\"Extracted {len(threat_entities)} threat intelligence entities\")\n",- "print(f\"Extracted {len(threat_relationships)} threat relationships\")\n",- "print(f\"Collected {len(all_documents)} threat intelligence documents\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Threat Intelligence Knowledge Graph\n",- "\n",- "Build knowledge graph from threat entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "threat_kg = builder.build(threat_entities, threat_relationships)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(threat_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(threat_kg)\n",- "\n",- "print(f\"Built threat intelligence knowledge graph\")\n",- "print(f\" Entities: {len(threat_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(threat_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Generate Embeddings and Setup Vector Store\n",- "\n",- "Generate embeddings from threat intelligence documents and store in vector database.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "vector_store = VectorStore()\n",- "hybrid_search = HybridSearch()\n",- "\n",- "# Generate embeddings for threat intelligence documents\n",- "embeddings = embedding_generator.generate_embeddings(all_documents, data_type=\"text\")\n",- "\n",- "# Prepare metadata for vector store\n",- "metadata = []\n",- "for i, doc in enumerate(all_documents):\n",- " metadata.append({\n",- " \"id\": f\"doc_{i}\",\n",- " \"text\": doc,\n",- " \"source\": \"threat_intelligence\"\n",- " })\n",- "\n",- "# Store vectors\n",- "vector_ids = vector_store.store_vectors(embeddings, metadata)\n",- "\n",- "print(f\"Generated embeddings for {len(all_documents)} documents\")\n",- "print(f\"Stored {len(vector_ids)} vectors in vector store\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Setup Hybrid RAG (Vector + Temporal KG)\n",- "\n",- "Setup hybrid search combining vector similarity and temporal knowledge graph queries.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "context_retriever = ContextRetriever()\n",- "context_graph_builder = ContextGraphBuilder()\n",- "\n",- "# Setup context retriever with KG and vector store\n",- "context_retriever = ContextRetriever(\n",- " knowledge_graph=threat_kg,\n",- " vector_store=vector_store\n",- ")\n",- "\n",- "print(f\" Knowledge graph: {len(threat_kg.get('entities', []))} entities\")\n",- "print(f\" Vector store: {len(vector_ids)} vectors\")\n",- "print(f\" Context retriever initialized\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Query Threats Using Hybrid RAG\n",- "\n",- "Query threat intelligence using hybrid search (vector + temporal KG).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Query examples\n",- "queries = [\n",- " \"What are the latest APT threats?\",\n",- " \"Find threats targeting financial institutions\",\n",- " \"What IOCs are associated with ransomware?\"\n",- "]\n",- "\n",- "query_results = []\n",- "\n",- "for query in queries:\n",- " # Generate query embedding\n",- " query_embedding = text_embedder.embed_text(query)\n",- " \n",- " # Vector search\n",- " vector_results = vector_store.search_vectors(query_embedding, k=3)\n",- " \n",- " # Temporal KG query\n",- " start_time = (datetime.now() - timedelta(days=30)).isoformat()\n",- " end_time = datetime.now().isoformat()\n",- " \n",- " temporal_results = temporal_query.query_time_range(\n",- " graph=threat_kg,\n",- " query=query,\n",- " start_time=start_time,\n",- " end_time=end_time\n",- " )\n",- " \n",- " # Hybrid search using context retriever\n",- " context_results = context_retriever.retrieve(\n",- " query=query,\n",- " top_k=3,\n",- " use_graph_expansion=True\n",- " )\n",- " \n",- " query_results.append({\n",- " \"query\": query,\n",- " \"vector_results\": len(vector_results),\n",- " \"temporal_results\": len(temporal_results.get('entities', [])),\n",- " \"context_results\": len(context_results) if context_results else 0\n",- " })\n",- "\n",- "# Inference for threat analysis\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "inference_engine.add_rule(\"IF severity is critical AND tactics includes exfiltration THEN high_priority_threat\")\n",- "inference_engine.add_rule(\"IF threat targets financial AND uses initial_access THEN financial_apt\")\n",- "\n",- "for threat in parsed_json.data if parsed_json and parsed_json.data else []:\n",- " if isinstance(threat, dict):\n",- " inference_engine.add_fact({\n",- " \"threat_id\": threat.get(\"threat_id\", \"\"),\n",- " \"severity\": threat.get(\"severity\", \"\"),\n",- " \"tactics\": threat.get(\"tactics\", [])\n",- " })\n",- "\n",- "# # threat_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Processed {len(queries)} threat intelligence queries\")\n",- "for result in query_results:\n",- " print(f\" Query: '{result['query']}' - Vector: {result['vector_results']}, Temporal: {result['temporal_results']}, Context: {result['context_results']}\")\n",- "print(f\"Generated {len(threat_insights)} threat insights from inference\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_score = quality_assessor.assess_overall_quality(threat_kg)\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "json_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Threat intelligence analysis identified {len(threat_entities)} entities and {len(threat_insights)} insights\",\n",- " \"threats_analyzed\": len(parsed_json.data) if parsed_json and parsed_json.data else 0,\n",- " \"iocs\": len([e for e in threat_entities if e.get(\"type\") == \"IOC\"]),\n",- " \"insights\": len(threat_insights),\n",- " \"quality_score\": 0.95,\n",- " \"critical_threats\": len([t for t in parsed_json.data if isinstance(t, dict) and t.get(\"severity\") == \"critical\"]) if parsed_json and parsed_json.data else 0\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n",- "print(f\"Graph quality score: 0.950\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Visualize Threat Intelligence\n",- "\n",- "Visualize threat intelligence knowledge graph and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(threat_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(threat_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(threat_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Multi-Source Threat Intel \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Embeddings \u2192 Vector Store \u2192 Hybrid RAG \u2192 Query \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb b/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynbdeleted file mode 100644index 3213b93b..00000000--- a/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb+++ /dev/null@@ -1,560 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/05_Threat_Intelligence_Integration.ipynb)\n",- "\n",- "# Threat Intelligence Integration Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for threat intelligence ingestion. Connect to threat intelligence MCP servers via URL, ingest threat feeds, vulnerability data, and security events, then build a threat intelligence knowledge graph.\n",- "\n",- "**IMPORTANT**: This implementation supports ONLY Python-based MCP servers and FastMCP servers. Users can bring their own Python/FastMCP MCP servers via URL connections.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: MCPIngestor, ingest_mcp, WebIngestor, FeedIngestor\n",- "- **Parsing**: MCPParser, JSONParser, XMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Connect to Threat Intel MCP Server \u2192 Ingest Threat Data via MCP \u2192 Parse MCP Responses \u2192 Extract Threat Entities \u2192 Build Threat KG \u2192 Generate Embeddings \u2192 Hybrid RAG \u2192 Analyze Threats \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Connect to Threat Intelligence MCP Server\n",- "\n",- "Connect to a Python/FastMCP MCP server that provides threat intelligence data via URL. The MCP server can expose resources (threat feeds, vulnerability databases) and tools (threat queries, IOC checks).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import MCPIngestor, ingest_mcp\n",- "from semantica.parse import MCPParser, JSONParser, XMLParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "# Initialize MCP ingestor\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "# Connect to threat intelligence MCP server via URL\n",- "# Replace with your actual MCP server URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/threat-mcp\n",- "threat_mcp_url = \"http://localhost:8000/mcp\"\n",- "\n",- "# Connect to MCP server with authentication (if required)\n",- "mcp_ingestor.connect(\n",- " \"threat_server\",\n",- " url=threat_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in threat_mcp_url else {}\n",- ")\n",- "\n",- "# List available resources (threat feeds, vulnerability databases)\n",- "resources = mcp_ingestor.list_available_resources(\"threat_server\")\n",- "print(f\"\\n\ud83d\udcca Available Resources ({len(resources)}):\")\n",- "for resource in resources[:5]: # Show first 5\n",- " print(f\" - {resource.uri}: {resource.name}\")\n",- " if resource.description:\n",- " print(f\" {resource.description[:80]}...\")\n",- "\n",- "# List available tools (threat queries, IOC checks)\n",- "tools = mcp_ingestor.list_available_tools(\"threat_server\")\n",- "print(f\"\\n\ud83d\udd27 Available Tools ({len(tools)}):\")\n",- "for tool in tools[:5]: # Show first 5\n",- " print(f\" - {tool.name}: {tool.description or 'No description'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Ingest Threat Intelligence Data from MCP Server\n",- "\n",- "Ingest threat feeds, vulnerability data, and security events using both resource-based and tool-based methods.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize parsers\n",- "mcp_parser = MCPParser()\n",- "json_parser = JSONParser()\n",- "xml_parser = XMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "threat_data = []\n",- "\n",- "# Method 1: Resource-based ingestion\n",- "# Ingest from MCP resources (threat feeds, vulnerability databases)\n",- "threat_feeds = mcp_ingestor.ingest_resources(\n",- " \"threat_server\",\n",- " resource_uris=[\"resource://threats/feed\", \"resource://vulnerabilities/database\"]\n",- ")\n",- "\n",- "for item in threat_feeds:\n",- " threat_data.append(item)\n",- " print(f\" Ingested resource: {item}\")\n",- "\n",- "# Method 2: Tool-based ingestion\n",- "# Call MCP tools to retrieve data dynamically\n",- "# Example: Query threat indicators\n",- "threat_indicators = mcp_ingestor.ingest_tool_output(\n",- " \"threat_server\",\n",- " tool_name=\"query_threat_indicators\",\n",- " arguments={\n",- " \"indicator_type\": \"IP\",\n",- " \"date_range\": {\n",- " \"start\": (datetime.now() - timedelta(days=7)).isoformat(),\n",- " \"end\": datetime.now().isoformat()\n",- " }\n",- " }\n",- ")\n",- "\n",- "if threat_indicators:\n",- " threat_data.append(threat_indicators)\n",- " print(f\" Retrieved threat indicators\")\n",- "\n",- "# Example: Check IOC (Indicators of Compromise)\n",- "ioc_check = mcp_ingestor.ingest_tool_output(\n",- " \"threat_server\",\n",- " tool_name=\"check_ioc\",\n",- " arguments={\n",- " \"ioc_type\": \"hash\",\n",- " \"ioc_value\": \"abc123def456\"\n",- " }\n",- ")\n",- "\n",- "if ioc_check:\n",- " threat_data.append(ioc_check)\n",- " print(f\" Retrieved IOC check results\")\n",- "\n",- "# Sample threat intelligence data (if MCP server is not available)\n",- "if not threat_data:\n",- " sample_data = {\n",- " \"threat_indicators\": [\n",- " {\n",- " \"indicator_id\": \"TI001\",\n",- " \"indicator_type\": \"IP\",\n",- " \"indicator_value\": \"192.168.1.100\",\n",- " \"threat_type\": \"malware\",\n",- " \"severity\": \"high\",\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat(),\n",- " \"source\": \"ThreatFeed1\"\n",- " },\n",- " {\n",- " \"indicator_id\": \"TI002\",\n",- " \"indicator_type\": \"domain\",\n",- " \"indicator_value\": \"malicious.example.com\",\n",- " \"threat_type\": \"phishing\",\n",- " \"severity\": \"medium\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=12)).isoformat(),\n",- " \"source\": \"ThreatFeed2\"\n",- " },\n",- " {\n",- " \"indicator_id\": \"TI003\",\n",- " \"indicator_type\": \"hash\",\n",- " \"indicator_value\": \"abc123def456\",\n",- " \"threat_type\": \"ransomware\",\n",- " \"severity\": \"critical\",\n",- " \"timestamp\": datetime.now().isoformat(),\n",- " \"source\": \"ThreatFeed1\"\n",- " }\n",- " ],\n",- " \"vulnerabilities\": [\n",- " {\n",- " \"cve_id\": \"CVE-2024-0001\",\n",- " \"description\": \"Remote code execution vulnerability\",\n",- " \"severity\": \"critical\",\n",- " \"affected_products\": [\"Product A\", \"Product B\"],\n",- " \"published_date\": (datetime.now() - timedelta(days=5)).isoformat()\n",- " }\n",- " ]\n",- " }\n",- " threat_data.append(sample_data)\n",- " print(f\" Loaded {len(sample_data['threat_indicators'])} threat indicators\")\n",- " print(f\" Loaded {len(sample_data['vulnerabilities'])} vulnerabilities\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Total threat intelligence data items ingested: {len(threat_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Parse Threat Intelligence Data\n",- "\n",- "Parse the threat intelligence data received from MCP server responses.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "parsed_threat_data = []\n",- "\n",- "# Parse MCP responses\n",- "for data_item in threat_data:\n",- " # Parse MCP response (handles JSON, XML, text, binary)\n",- " if isinstance(data_item, dict):\n",- " parsed_item = data_item\n",- " else:\n",- " parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",- " \n",- " parsed_threat_data.append(parsed_item)\n",- " print(f\" Parsed data item\")\n",- "\n",- "# Extract threat indicators and vulnerabilities\n",- "threat_indicators = []\n",- "vulnerabilities = []\n",- "\n",- "for item in parsed_threat_data:\n",- " if isinstance(item, dict):\n",- " if \"threat_indicators\" in item:\n",- " threat_indicators.extend(item[\"threat_indicators\"])\n",- " elif \"indicator_id\" in item:\n",- " threat_indicators.append(item)\n",- " elif \"vulnerabilities\" in item:\n",- " vulnerabilities.extend(item[\"vulnerabilities\"])\n",- " elif \"cve_id\" in item:\n",- " vulnerabilities.append(item)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Extract Threat Entities and Relationships\n",- "\n",- "Extract threat entities (indicators, vulnerabilities, threat actors) and relationships from MCP data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "threat_entities = []\n",- "threat_relationships = []\n",- "\n",- "# Extract from threat indicators\n",- "for indicator in threat_indicators:\n",- " if isinstance(indicator, dict):\n",- " indicator_id = indicator.get(\"indicator_id\", \"\")\n",- " indicator_type = indicator.get(\"indicator_type\", \"\")\n",- " threat_type = indicator.get(\"threat_type\", \"\")\n",- " source = indicator.get(\"source\", \"\")\n",- " \n",- " # Threat Indicator entity\n",- " threat_entities.append({\n",- " \"id\": indicator_id,\n",- " \"type\": \"ThreatIndicator\",\n",- " \"name\": indicator_id,\n",- " \"properties\": {\n",- " \"indicator_type\": indicator_type,\n",- " \"indicator_value\": indicator.get(\"indicator_value\", \"\"),\n",- " \"threat_type\": threat_type,\n",- " \"severity\": indicator.get(\"severity\", \"\"),\n",- " \"timestamp\": indicator.get(\"timestamp\", \"\"),\n",- " \"source\": source\n",- " }\n",- " })\n",- " \n",- " # Threat Type entity\n",- " if threat_type:\n",- " threat_entities.append({\n",- " \"id\": threat_type,\n",- " \"type\": \"ThreatType\",\n",- " \"name\": threat_type,\n",- " \"properties\": {}\n",- " })\n",- " threat_relationships.append({\n",- " \"source\": indicator_id,\n",- " \"target\": threat_type,\n",- " \"type\": \"classified_as\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Source entity\n",- " if source:\n",- " threat_entities.append({\n",- " \"id\": source,\n",- " \"type\": \"ThreatSource\",\n",- " \"name\": source,\n",- " \"properties\": {}\n",- " })\n",- " threat_relationships.append({\n",- " \"source\": indicator_id,\n",- " \"target\": source,\n",- " \"type\": \"reported_by\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Extract from vulnerabilities\n",- "for vuln in vulnerabilities:\n",- " if isinstance(vuln, dict):\n",- " cve_id = vuln.get(\"cve_id\", \"\")\n",- " \n",- " # Vulnerability entity\n",- " threat_entities.append({\n",- " \"id\": cve_id,\n",- " \"type\": \"Vulnerability\",\n",- " \"name\": cve_id,\n",- " \"properties\": {\n",- " \"description\": vuln.get(\"description\", \"\"),\n",- " \"severity\": vuln.get(\"severity\", \"\"),\n",- " \"published_date\": vuln.get(\"published_date\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Affected products\n",- " for product in vuln.get(\"affected_products\", []):\n",- " threat_entities.append({\n",- " \"id\": product,\n",- " \"type\": \"Product\",\n",- " \"name\": product,\n",- " \"properties\": {}\n",- " })\n",- " threat_relationships.append({\n",- " \"source\": cve_id,\n",- " \"target\": product,\n",- " \"type\": \"affects\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Remove duplicates\n",- "seen_entities = set()\n",- "unique_entities = []\n",- "for entity in threat_entities:\n",- " entity_key = (entity[\"id\"], entity[\"type\"])\n",- " if entity_key not in seen_entities:\n",- " seen_entities.add(entity_key)\n",- " unique_entities.append(entity)\n",- "\n",- "threat_entities = unique_entities\n",- "\n",- "print(f\" - Threat Indicators: {len([e for e in threat_entities if e['type'] == 'ThreatIndicator'])}\")\n",- "print(f\" - Vulnerabilities: {len([e for e in threat_entities if e['type'] == 'Vulnerability'])}\")\n",- "print(f\" - Threat Types: {len([e for e in threat_entities if e['type'] == 'ThreatType'])}\")\n",- "print(f\" - Sources: {len([e for e in threat_entities if e['type'] == 'ThreatSource'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Build Threat Intelligence Knowledge Graph\n",- "\n",- "Build a temporal knowledge graph from the extracted threat entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Build knowledge graph\n",- "threat_kg = builder.build(threat_entities, threat_relationships)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(threat_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(threat_kg)\n",- "\n",- "print(f\" Entities: {len(threat_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(threat_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Connectivity: {connectivity.get('connected_components', 0)} components\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Embeddings and Set Up Hybrid RAG\n",- "\n",- "Generate embeddings for threat intelligence data and set up hybrid search (vector + temporal KG).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Generate embeddings\n",- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "\n",- "# Generate embeddings for threat entities\n",- "threat_texts = []\n",- "for entity in threat_entities:\n",- " if entity.get(\"type\") == \"ThreatIndicator\":\n",- " text = f\"{entity.get('properties', {}).get('indicator_value', '')} {entity.get('properties', {}).get('threat_type', '')} {entity.get('properties', {}).get('description', '')}\"\n",- " threat_texts.append(text)\n",- "\n",- "embeddings = embedding_generator.generate_embeddings(threat_texts)\n",- "\n",- "# Set up vector store\n",- "vector_store = VectorStore()\n",- "vector_store.add_embeddings(threat_texts, embeddings)\n",- "\n",- "# Set up hybrid search (vector + temporal KG)\n",- "hybrid_search = HybridSearch()\n",- "hybrid_search.setup(vector_store, threat_kg)\n",- "\n",- "\n",- "# Inference engine for threat analysis\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Threat analysis rules\n",- "inference_engine.add_rule(\"IF severity(critical) AND threat_type(ransomware) THEN immediate_response_required\")\n",- "inference_engine.add_rule(\"IF severity(high) AND indicator_type(IP) THEN block_ip\")\n",- "\n",- "# Add facts from threat data\n",- "for indicator in threat_indicators:\n",- " if isinstance(indicator, dict):\n",- " inference_engine.add_fact({\n",- " \"indicator_id\": indicator.get(\"indicator_id\", \"\"),\n",- " \"severity\": indicator.get(\"severity\", \"\"),\n",- " \"threat_type\": indicator.get(\"threat_type\", \"\"),\n",- " \"indicator_type\": indicator.get(\"indicator_type\", \"\")\n",- " })\n",- "\n",- "# Generate threat insights\n",- "# # threat_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\" Threat insights: {len(threat_insights)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Export and Visualize\n",- "\n",- "Export the threat intelligence knowledge graph and generate visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import tempfile\n",- "import os\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph\n",- "json_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(threat_kg, os.path.join(temp_dir, \"threat_kg.rdf\"))\n",- "\n",- "# Generate report\n",- "report_data = {\n",- " \"summary\": f\"Threat intelligence integration from MCP server identified {len(threat_insights)} insights\",\n",- " \"threat_indicators\": len([e for e in threat_entities if e['type'] == 'ThreatIndicator']),\n",- " \"vulnerabilities\": len([e for e in threat_entities if e['type'] == 'Vulnerability']),\n",- " \"threat_types\": len([e for e in threat_entities if e['type'] == 'ThreatType']),\n",- " \"insights\": len(threat_insights)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\" JSON: {os.path.join(temp_dir, 'threat_kg.json')}\")\n",- "print(f\" RDF: {os.path.join(temp_dir, 'threat_kg.rdf')}\")\n",- "\n",- "# Visualize\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(threat_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(threat_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(threat_kg, output=\"interactive\")\n",- "\n",- "\n",- "# Cleanup: Disconnect from MCP server\n",- "mcp_ingestor.disconnect(\"threat_server\")\n",- "print(\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\ud83d\udcca Total modules used: 20+\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb b/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynbdeleted file mode 100644index 0a849937..00000000--- a/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb+++ /dev/null@@ -1,172 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/cybersecurity/06_Vulnerability_Tracking.ipynb)\n",- "\n",- "# Vulnerability Tracking Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete vulnerability tracking pipeline: ingest CVE data from multiple real sources (NVD, CVE feeds, security databases), build temporal knowledge graph, correlate vulnerabilities, predict impact, and generate vulnerability reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, XMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Real CVE Sources \u2192 Parse \u2192 Extract Vulnerabilities \u2192 Build Temporal KG \u2192 Correlate \u2192 Predict Impact \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest CVE Data from Real Sources\n",- "\n",- "Ingest CVE data from NVD, CVE feeds, and security databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",- "from semantica.parse import JSONParser, XMLParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD-- "from semantica.conflicts import ConflictDetector\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "db_ingestor = DBIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "xml_parser = XMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real CVE and vulnerability data sources\n",- "cve_sources = [\n",- " \"https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-recent.json.zip\", # NVD Recent CVEs (JSON)\n",- " \"https://nvd.nist.gov/feeds/xml/cve/2.0/nvdcve-2.0-recent.xml.zip\", # NVD Recent CVEs (XML)\n",- " \"https://cve.mitre.org/data/downloads/allitems.csv\", # CVE MITRE All Items\n",- " \"https://www.cisa.gov/known-exploited-vulnerabilities-catalog/json\" # CISA KEV Catalog\n",- "]\n",- "\n",- "# Real vulnerability feed URLs\n",- "vulnerability_feeds = [\n",- " \"https://www.cisa.gov/news.xml\", # CISA Security Advisories\n",- " \"https://www.us-cert.gov/ncas/alerts.xml\", # US-CERT Alerts\n",- " \"https://feeds.feedburner.com/SecurityWeek\", # Security Week\n",- " \"https://www.darkreading.com/rss.xml\" # Dark Reading\n",- "]\n",- "\n",- "# Real database connection for vulnerability tracking\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/vulnerability_db\"\n",- "db_query = \"SELECT cve_id, description, severity, published_date, affected_products FROM vulnerabilities WHERE published_date > NOW() - INTERVAL '30 days' ORDER BY published_date DESC\"\n",- "\n",- "# Real web API endpoints for CVE data\n",- "cve_apis = [\n",- " \"https://services.nvd.nist.gov/rest/json/cves/2.0\", # NVD CVE API v2.0\n",- " \"https://api.github.com/repos/CVEProject/cvelist\", # CVE Project on GitHub\n",- " \"https://cve.circl.lu/api/last\" # CVE Search API\n",- "]\n",- "\n",- "# Ingest from real CVE feeds\n",- "cve_feed_list = []\n",- "for feed_url in vulnerability_feeds:\n",- " cve_feed = feed_ingestor.ingest_feed(feed_url)\n",- " if cve_feed:\n",- " cve_feed_list.append(cve_feed)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- " print(f\" Items: {len(cve_feed.items) if hasattr(cve_feed, 'items') else 0}\")\n",- "\n",- "# Ingest from real CVE APIs\n",- "cve_api_data = []\n",- "for api_url in cve_apis[:1]: # Process first API\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " cve_api_data.append(api_content)\n",- " print(f\" Ingested CVE API: {api_url}\")\n",- "\n",- "# Database ingestion pattern\n",- "db_data = db_ingestor.export_table(\n",- " connection_string=db_connection_string,\n",- " table_name=\"vulnerabilities\",\n",- " limit=1000\n",- ")\n",- "print(f\" Query pattern: {db_query}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca CVE Ingestion Summary:\")\n",- "print(f\" Vulnerability feeds: {len(cve_feed_list)}\")\n",- "print(f\" CVE API sources: {len(cve_api_data)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynb b/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynbdeleted file mode 100644index a8705631..00000000--- a/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynb+++ /dev/null@@ -1,530 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/01_Financial_Data_Integration.ipynb)\n",- "\n",- "# \ud83d\udcc8 Financial Data Integration Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for financial data ingestion. Connect to financial data MCP servers via URL, ingest market data, stock prices, and financial metrics, then build a knowledge graph for financial analysis.\n",- "\n",- "> [!IMPORTANT]\n",- "> This implementation supports ONLY Python-based MCP servers and FastMCP servers. Users can bring their own Python/FastMCP MCP servers via URL connections.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### \ud83e\udde9 Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: `MCPParser`, `JSONParser`, `StructuredDataParser`\n",- "- **Extraction**: `NERExtractor`, `RelationExtractor`, `EventDetector`, `SemanticAnalyzer`\n",- "- **KG**: `GraphBuilder`, `TemporalGraphQuery`, `GraphAnalyzer`\n",- "- **Analytics**: `CentralityCalculator`, `CommunityDetector`, `ConnectivityAnalyzer`\n",- "- **Reasoning**: `Reasoner (Legacy)`, `RuleManager`, `ExplanationGenerator`\n",- "- **Export**: `JSONExporter`, `CSVExporter`, `RDFExporter`, `ReportGenerator`\n",- "- **Visualization**: `KGVisualizer`, `TemporalVisualizer`, `AnalyticsVisualizer`\n",- "\n",- "### \ud83d\udd04 Pipeline\n",- "\n",- "**Connect to Financial MCP Server \u2192 Ingest Market Data via MCP \u2192 Parse MCP Responses \u2192 Extract Financial Entities \u2192 Build Financial KG \u2192 Analyze Trends \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## \ud83d\udd0c Step 1: Connect to Financial Data MCP Server\n",- "\n",- "Connect to a Python/FastMCP MCP server that provides financial data via URL. The MCP server can expose resources (datasets, market data) and tools (queries, calculations).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import MCPIngestor, ingest_mcp\n",- "from semantica.parse import MCPParser, JSONParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "# Initialize MCP ingestor\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "# Connect to financial data MCP server via URL\n",- "# Replace with your actual MCP server URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/financial-mcp\n",- "financial_mcp_url = \"http://localhost:8000/mcp\"\n",- "\n",- "# Connect to MCP server\n",- "mcp_ingestor.connect(\n",- " \"financial_server\",\n",- " url=financial_mcp_url,\n",- " headers={\"Authorization\": \"Bearer your_token\"} if \"api.example.com\" in financial_mcp_url else {}\n",- ")\n",- "\n",- "# List available resources (datasets, market data feeds)\n",- "resources = mcp_ingestor.list_available_resources(\"financial_server\")\n",- "print(f\"\\n\ud83d\udcca Available Resources ({len(resources)}):\")\n",- "for resource in resources[:5]: # Show first 5\n",- " print(f\" - {resource.uri}: {resource.name}\")\n",- " if resource.description:\n",- " print(f\" {resource.description[:80]}...\")\n",- "\n",- "# List available tools (queries, calculations)\n",- "tools = mcp_ingestor.list_available_tools(\"financial_server\")\n",- "print(f\"\\n\ud83d\udd27 Available Tools ({len(tools)}):\")\n",- "for tool in tools[:5]: # Show first 5\n",- " print(f\" - {tool.name}: {tool.description or 'No description'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \ud83d\udce5 Step 2: Ingest Financial Data from MCP Server\n",- "\n",- "Ingest financial data using both resource-based and tool-based methods from the MCP server.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize parsers\n",- "mcp_parser = MCPParser()\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "financial_data = []\n",- "\n",- "# Method 1: Resource-based ingestion\n",- "# Ingest from MCP resources (pre-defined datasets)\n",- "# Example: Ingest market data resource\n",- "resource_data = mcp_ingestor.ingest_resources(\n",- " \"financial_server\",\n",- " resource_uris=[\"resource://market_data/daily\", \"resource://market_data/stocks\"]\n",- ")\n",- "\n",- "for item in resource_data:\n",- " financial_data.append(item)\n",- " print(f\" Ingested resource: {item}\")\n",- "\n",- "# Method 2: Tool-based ingestion\n",- "# Call MCP tools to retrieve data dynamically\n",- "# Example: Get stock prices for specific symbols\n",- "stock_prices = mcp_ingestor.ingest_tool_output(\n",- " \"financial_server\",\n",- " tool_name=\"get_stock_prices\",\n",- " arguments={\n",- " \"symbols\": [\"AAPL\", \"MSFT\", \"GOOGL\", \"TSLA\"],\n",- " \"date\": datetime.now().isoformat()\n",- " }\n",- ")\n",- "\n",- "if stock_prices:\n",- " financial_data.append(stock_prices)\n",- " print(f\" Retrieved stock prices for {len(stock_prices) if isinstance(stock_prices, list) else 1} symbols\")\n",- "\n",- "# Example: Get market metrics\n",- "market_metrics = mcp_ingestor.ingest_tool_output(\n",- " \"financial_server\",\n",- " tool_name=\"get_market_metrics\",\n",- " arguments={\"sector\": \"Technology\"}\n",- ")\n",- "\n",- "if market_metrics:\n",- " financial_data.append(market_metrics)\n",- " print(f\" Retrieved market metrics\")\n",- "\n",- "# Sample financial data (if MCP server is not available)\n",- "if not financial_data:\n",- " sample_data = {\n",- " \"stock_prices\": [\n",- " {\n",- " \"symbol\": \"AAPL\",\n",- " \"company\": \"Apple Inc.\",\n",- " \"price\": 175.50,\n",- " \"change\": 2.30,\n",- " \"change_percent\": 1.33,\n",- " \"volume\": 45000000,\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"sector\": \"Technology\"\n",- " },\n",- " {\n",- " \"symbol\": \"MSFT\",\n",- " \"company\": \"Microsoft Corporation\",\n",- " \"price\": 380.25,\n",- " \"change\": -1.50,\n",- " \"change_percent\": -0.39,\n",- " \"volume\": 28000000,\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"sector\": \"Technology\"\n",- " },\n",- " {\n",- " \"symbol\": \"GOOGL\",\n",- " \"company\": \"Alphabet Inc.\",\n",- " \"price\": 142.80,\n",- " \"change\": 3.20,\n",- " \"change_percent\": 2.29,\n",- " \"volume\": 32000000,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=30)).isoformat(),\n",- " \"sector\": \"Technology\"\n",- " },\n",- " {\n",- " \"symbol\": \"TSLA\",\n",- " \"company\": \"Tesla Inc.\",\n",- " \"price\": 245.60,\n",- " \"change\": 5.40,\n",- " \"change_percent\": 2.25,\n",- " \"volume\": 55000000,\n",- " \"timestamp\": datetime.now().isoformat(),\n",- " \"sector\": \"Automotive\"\n",- " }\n",- " ],\n",- " \"market_metrics\": {\n",- " \"total_volume\": 150000000,\n",- " \"market_cap\": 15000000000000,\n",- " \"sectors\": [\"Technology\", \"Automotive\"]\n",- " }\n",- " }\n",- " financial_data.append(sample_data)\n",- " print(f\" Loaded {len(sample_data['stock_prices'])} stock prices\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Total financial data items ingested: {len(financial_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \ud83d\udcc4 Step 3: Parse MCP Data\n",- "\n",- "Parse the data received from MCP server responses (JSON, structured data).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "parsed_financial_data = []\n",- "\n",- "# Parse MCP responses\n",- "for data_item in financial_data:\n",- " # Parse MCP response (handles JSON, text, binary)\n",- " if isinstance(data_item, dict):\n",- " # If it's already structured, use it directly\n",- " parsed_item = data_item\n",- " else:\n",- " # Parse using MCP parser\n",- " parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",- " \n",- " parsed_financial_data.append(parsed_item)\n",- " print(f\" Parsed data item\")\n",- "\n",- "# Extract stock prices from parsed data\n",- "stock_prices = []\n",- "for item in parsed_financial_data:\n",- " if isinstance(item, dict):\n",- " if \"stock_prices\" in item:\n",- " stock_prices.extend(item[\"stock_prices\"])\n",- " elif \"symbol\" in item:\n",- " stock_prices.append(item)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \u26cf\ufe0f Step 4: Extract Financial Entities and Relationships\n",- "\n",- "Extract financial entities (companies, stocks, sectors) and relationships from MCP data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "financial_entities = []\n",- "financial_relationships = []\n",- "\n",- "# Extract entities and relationships from stock prices\n",- "for stock in stock_prices:\n",- " if isinstance(stock, dict):\n",- " symbol = stock.get(\"symbol\", \"\")\n",- " company = stock.get(\"company\", \"\")\n",- " sector = stock.get(\"sector\", \"\")\n",- " \n",- " # Stock entity\n",- " financial_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {\n",- " \"price\": stock.get(\"price\", 0),\n",- " \"change\": stock.get(\"change\", 0),\n",- " \"change_percent\": stock.get(\"change_percent\", 0),\n",- " \"volume\": stock.get(\"volume\", 0),\n",- " \"timestamp\": stock.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Company entity\n",- " if company:\n",- " financial_entities.append({\n",- " \"id\": company,\n",- " \"type\": \"Company\",\n",- " \"name\": company,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Stock-Company relationship\n",- " financial_relationships.append({\n",- " \"source\": symbol,\n",- " \"target\": company,\n",- " \"type\": \"ticker_for\",\n",- " \"properties\": {\"timestamp\": stock.get(\"timestamp\", \"\")}\n",- " })\n",- " \n",- " # Sector entity\n",- " if sector:\n",- " financial_entities.append({\n",- " \"id\": sector,\n",- " \"type\": \"Sector\",\n",- " \"name\": sector,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Company-Sector relationship\n",- " if company:\n",- " financial_relationships.append({\n",- " \"source\": company,\n",- " \"target\": sector,\n",- " \"type\": \"belongs_to\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Remove duplicates\n",- "seen_entities = set()\n",- "unique_entities = []\n",- "for entity in financial_entities:\n",- " entity_key = (entity[\"id\"], entity[\"type\"])\n",- " if entity_key not in seen_entities:\n",- " seen_entities.add(entity_key)\n",- " unique_entities.append(entity)\n",- "\n",- "financial_entities = unique_entities\n",- "\n",- "print(f\" - Stocks: {len([e for e in financial_entities if e['type'] == 'Stock'])}\")\n",- "print(f\" - Companies: {len([e for e in financial_entities if e['type'] == 'Company'])}\")\n",- "print(f\" - Sectors: {len([e for e in financial_entities if e['type'] == 'Sector'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \ud83d\udd78\ufe0f Step 5: Build Financial Knowledge Graph\n",- "\n",- "Build a knowledge graph from the extracted financial entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "# Build knowledge graph\n",- "financial_kg = builder.build(financial_entities, financial_relationships)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(financial_kg)\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Calculate graph metrics\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(financial_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(financial_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(financial_kg)\n",- "\n",- "print(f\" Entities: {len(financial_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(financial_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities detected: {len(communities)}\")\n",- "print(f\" Central entities: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \ud83d\udcca Step 6: Analyze Financial Trends\n",- "\n",- "Analyze financial trends using temporal queries and pattern detection.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Temporal analysis\n",- "start_time = (datetime.now() - timedelta(days=7)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=financial_kg,\n",- " query=\"Find stock price movements\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "# Inference engine for financial rules\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Financial analysis rules\n",- "inference_engine.add_rule(\"IF change_percent > 2 AND volume > 40000000 THEN strong_momentum\")\n",- "inference_engine.add_rule(\"IF change_percent < -1 AND volume > 50000000 THEN selling_pressure\")\n",- "inference_engine.add_rule(\"IF change_percent > 0 AND sector == 'Technology' THEN tech_growth\")\n",- "\n",- "# Add facts from stock data\n",- "for stock in stock_prices:\n",- " if isinstance(stock, dict):\n",- " inference_engine.add_fact({\n",- " \"symbol\": stock.get(\"symbol\", \"\"),\n",- " \"change_percent\": stock.get(\"change_percent\", 0),\n",- " \"volume\": stock.get(\"volume\", 0),\n",- " \"sector\": stock.get(\"sector\", \"\")\n",- " })\n",- "\n",- "# Generate insights\n",- "# # financial_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\" Temporal entities: {len(temporal_results.get('entities', []))}\")\n",- "print(f\" Financial insights: {len(financial_insights)}\")\n",- "\n",- "# Display insights\n",- "for insight in financial_insights[:3]:\n",- " print(f\" - {insight}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## \ud83d\udce4 Step 7: Export and Visualize\n",- "\n",- "Export the financial knowledge graph and generate visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import tempfile\n",- "import os\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph\n",- "json_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.json\"))\n",- "csv_exporter.export_entities(financial_entities, os.path.join(temp_dir, \"financial_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.rdf\"))\n",- "\n",- "# Generate report\n",- "report_data = {\n",- " \"summary\": f\"Financial data integration from MCP server identified {len(financial_insights)} insights\",\n",- " \"stocks_analyzed\": len([e for e in financial_entities if e['type'] == 'Stock']),\n",- " \"companies\": len([e for e in financial_entities if e['type'] == 'Company']),\n",- " \"sectors\": len([e for e in financial_entities if e['type'] == 'Sector']),\n",- " \"insights\": len(financial_insights)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\" JSON: {os.path.join(temp_dir, 'financial_kg.json')}\")\n",- "print(f\" CSV: {os.path.join(temp_dir, 'financial_entities.csv')}\")\n",- "print(f\" RDF: {os.path.join(temp_dir, 'financial_kg.rdf')}\")\n",- "\n",- "# Visualize\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(financial_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(financial_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(financial_kg, output=\"interactive\")\n",- "\n",- "\n",- "# Cleanup: Disconnect from MCP server\n",- "mcp_ingestor.disconnect(\"financial_server\")\n",- "print(\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\ud83d\udcca Total modules used: 20+\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb b/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynbdeleted file mode 100644index 76fdc224..00000000--- a/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb+++ /dev/null@@ -1,459 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/02_Financial_Reports_Analysis.ipynb)\n",- "\n",- "# Financial Reports Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete financial reports analysis pipeline: ingest financial documents from multiple sources (SEC filings, annual reports, financial databases), extract financial entities, build knowledge graph, analyze relationships, and generate financial insights.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Financial Documents \u2192 Parse \u2192 Extract Entities \u2192 Build KG \u2192 Analyze Relationships \u2192 Generate Insights \u2192 Export \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Financial Documents from Multiple Sources\n",- "\n",- "Ingest financial reports from SEC filings, annual reports, and financial databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "from semantica.conflicts import ConflictDetector\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======-->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "html_parser = HTMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real financial data sources\n",- "sec_edgar_urls = [\n",- " \"https://www.sec.gov/cgi-bin/browse-edgar\", # SEC EDGAR database\n",- " \"https://www.sec.gov/Archives/edgar/data/\", # SEC EDGAR archives\n",- " \"https://data.sec.gov/submissions/\" # SEC submissions API\n",- "]\n",- "\n",- "financial_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://feeds.reuters.com/reuters/topNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\",\n",- " \"https://feeds.bloomberg.com/markets/news.rss\"\n",- "]\n",- "\n",- "# Real database connection for financial reports\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/financial_reports_db\"\n",- "db_query = \"SELECT company_name, report_type, filing_date, document_url FROM financial_reports WHERE filing_date > CURRENT_DATE - INTERVAL '1 year' ORDER BY filing_date DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample financial report data (simulating real SEC filing structure)\n",- "financial_report_file = os.path.join(temp_dir, \"financial_report.json\")\n",- "report_data = {\n",- " \"company\": \"Apple Inc.\",\n",- " \"symbol\": \"AAPL\",\n",- " \"report_type\": \"10-K\",\n",- " \"filing_date\": (datetime.now() - timedelta(days=30)).isoformat(),\n",- " \"revenue\": 394328000000,\n",- " \"net_income\": 99803000000,\n",- " \"total_assets\": 352755000000,\n",- " \"total_liabilities\": 290437000000,\n",- " \"segments\": [\"iPhone\", \"Mac\", \"iPad\", \"Services\", \"Wearables\"],\n",- " \"geographic_regions\": [\"Americas\", \"Europe\", \"Greater China\", \"Japan\", \"Rest of Asia Pacific\"]\n",- "}\n",- "\n",- "with open(financial_report_file, 'w') as f:\n",- " json.dump(report_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(financial_report_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(financial_report_file, data_format=\"json\")\n",- "\n",- "# Ingest from financial feeds\n",- "financial_feed_list = []\n",- "for feed_url in financial_feeds[:2]: # Process first 2 feeds\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " financial_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "# Ingest from SEC EDGAR (example)\n",- "web_content = web_ingestor.ingest_url(\"https://www.sec.gov/cgi-bin/browse-edgar\")\n",- "if web_content:\n",- " print(f\" Ingested SEC EDGAR content\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Financial reports ingested: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Financial feeds: {len(financial_feed_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Financial Entities\n",- "\n",- "Extract financial entities (companies, metrics, segments, regions) from financial reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "financial_entities = []\n",- "financial_relationships = []\n",- "\n",- "# Extract from financial report data\n",- "if parsed_data and parsed_data.data:\n",- " report = parsed_data.data if isinstance(parsed_data.data, dict) else parsed_data.data[0] if isinstance(parsed_data.data, list) else {}\n",- " \n",- " if isinstance(report, dict):\n",- " # Company entity\n",- " financial_entities.append({\n",- " \"id\": report.get(\"symbol\", \"\"),\n",- " \"type\": \"Company\",\n",- " \"name\": report.get(\"company\", \"\"),\n",- " \"properties\": {\n",- " \"symbol\": report.get(\"symbol\", \"\"),\n",- " \"report_type\": report.get(\"report_type\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Financial metrics\n",- " financial_entities.append({\n",- " \"id\": f\"{report.get('symbol', '')}_revenue\",\n",- " \"type\": \"Financial_Metric\",\n",- " \"name\": \"Revenue\",\n",- " \"properties\": {\n",- " \"value\": report.get(\"revenue\", 0),\n",- " \"currency\": \"USD\",\n",- " \"filing_date\": report.get(\"filing_date\", \"\")\n",- " }\n",- " })\n",- " \n",- " financial_entities.append({\n",- " \"id\": f\"{report.get('symbol', '')}_net_income\",\n",- " \"type\": \"Financial_Metric\",\n",- " \"name\": \"Net Income\",\n",- " \"properties\": {\n",- " \"value\": report.get(\"net_income\", 0),\n",- " \"currency\": \"USD\",\n",- " \"filing_date\": report.get(\"filing_date\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Segments\n",- " for segment in report.get(\"segments\", []):\n",- " financial_entities.append({\n",- " \"id\": f\"{report.get('symbol', '')}_segment_{segment}\",\n",- " \"type\": \"Business_Segment\",\n",- " \"name\": segment,\n",- " \"properties\": {}\n",- " })\n",- " financial_relationships.append({\n",- " \"source\": report.get(\"symbol\", \"\"),\n",- " \"target\": f\"{report.get('symbol', '')}_segment_{segment}\",\n",- " \"type\": \"has_segment\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Geographic regions\n",- " for region in report.get(\"geographic_regions\", []):\n",- " financial_entities.append({\n",- " \"id\": f\"{report.get('symbol', '')}_region_{region}\",\n",- " \"type\": \"Geographic_Region\",\n",- " \"name\": region,\n",- " \"properties\": {}\n",- " })\n",- " financial_relationships.append({\n",- " \"source\": report.get(\"symbol\", \"\"),\n",- " \"target\": f\"{report.get('symbol', '')}_region_{region}\",\n",- " \"type\": \"operates_in\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Relationships\n",- " financial_relationships.append({\n",- " \"source\": report.get(\"symbol\", \"\"),\n",- " \"target\": f\"{report.get('symbol', '')}_revenue\",\n",- " \"type\": \"has_metric\",\n",- " \"properties\": {\"filing_date\": report.get(\"filing_date\", \"\")}\n",- " })\n",- " \n",- " financial_relationships.append({\n",- " \"source\": report.get(\"symbol\", \"\"),\n",- " \"target\": f\"{report.get('symbol', '')}_net_income\",\n",- " \"type\": \"has_metric\",\n",- " \"properties\": {\"filing_date\": report.get(\"filing_date\", \"\")}\n",- " })\n",- "\n",- "print(f\"Extracted {len(financial_entities)} financial entities\")\n",- "print(f\"Extracted {len(financial_relationships)} financial relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Financial Knowledge Graph\n",- "\n",- "Build knowledge graph from financial entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "financial_kg = builder.build(financial_entities, financial_relationships)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(financial_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(financial_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(financial_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(financial_kg)\n",- "\n",- "print(f\"Built financial knowledge graph\")\n",- "print(f\" Entities: {len(financial_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(financial_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities: {len(communities)}\")\n",- "print(f\" Central entities: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze Financial Relationships\n",- "\n",- "Analyze financial relationships and generate insights.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Temporal analysis\n",- "start_time = (datetime.now() - timedelta(days=365)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=financial_kg,\n",- " query=\"Find financial metrics in the last year\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " financial_kg,\n",- " pattern_type=\"trend\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Financial analysis rules\n",- "inference_engine.add_rule(\"IF revenue > 300000000000 AND net_income > 50000000000 THEN high_performer\")\n",- "inference_engine.add_rule(\"IF company has_segment Services AND revenue > 20000000000 THEN services_growth\")\n",- "\n",- "# Add facts from financial data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " report = parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), dict) else parsed_data.get(\"data\")[0] if isinstance(parsed_data.get(\"data\"), list) else {}\n",- " if isinstance(report, dict):\n",- " inference_engine.add_fact({\n",- " \"company\": report.get(\"symbol\", \"\"),\n",- " \"revenue\": report.get(\"revenue\", 0),\n",- " \"net_income\": report.get(\"net_income\", 0),\n",- " \"segments\": report.get(\"segments\", [])\n",- " })\n",- "\n",- "# # financial_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Temporal query returned {len(temporal_results.get('entities', []))} entities\")\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"Generated {len(financial_insights)} financial insights\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Financial Analysis Reports\n",- "\n",- "Generate comprehensive financial analysis reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(financial_kg)\n",- "\n",- "json_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.json\"))\n",- "csv_exporter.export_entities(financial_entities, os.path.join(temp_dir, \"financial_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(financial_kg, os.path.join(temp_dir, \"financial_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Financial analysis identified {len(financial_insights)} insights from {len(financial_entities)} entities\",\n",- " \"entities_analyzed\": len(financial_entities),\n",- " \"relationships\": len(financial_relationships),\n",- " \"insights\": len(financial_insights),\n",- " \"quality_score\": quality_score.get('overall_score', 0),\n",- " \"patterns\": len(temporal_patterns)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n",- "print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Visualize Financial Analysis\n",- "\n",- "Visualize financial knowledge graph and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(financial_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(financial_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(financial_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Financial Documents \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Analyze Relationships \u2192 Generate Insights \u2192 Export \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/finance/03_Fraud_Detection.ipynb b/cookbook/use_cases/finance/03_Fraud_Detection.ipynbdeleted file mode 100644index e62b5663..00000000--- a/cookbook/use_cases/finance/03_Fraud_Detection.ipynb+++ /dev/null@@ -1,435 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/03_Fraud_Detection.ipynb)\n",- "\n",- "# Fraud Detection Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete fraud detection pipeline for finance: ingest transaction streams, build temporal knowledge graph, detect fraud patterns, perform anomaly detection, and generate alerts.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector\n",- "- **KG**: GraphBuilder, TemporalPatternDetector, GraphAnalyzer\n",- "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent fraud graph\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Quality**: KGQualityAssessor, AutomatedFixer\n",- "- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Transaction Stream \u2192 Parse \u2192 Extract \u2192 Build Temporal KG \u2192 Store in Graph DB \u2192 Detect Patterns \u2192 Anomaly Detection \u2192 Generate Alerts \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Process Transactions\n",- "\n",- "Ingest and parse transaction data from multiple sources.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, StreamIngestor, DBIngestor\n",- "from semantica.parse import StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector\n",- "from semantica.kg import GraphBuilder, TemporalPatternDetector, GraphAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "db_ingestor = DBIngestor()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "# Real streaming sources for transaction monitoring\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"transactions\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"fraud_detection\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"payment_events\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real database connection for transaction data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/transactions_db\"\n",- "db_query = \"SELECT transaction_id, user_id, amount, merchant, location, timestamp, device FROM transactions WHERE timestamp > NOW() - INTERVAL '24 hours' ORDER BY timestamp DESC LIMIT 10000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "transactions_file = os.path.join(temp_dir, \"transactions.json\")\n",- "transactions_data = [\n",- " {\"transaction_id\": \"txn_001\", \"user_id\": \"user_123\", \"amount\": 150.00, \"merchant\": \"Online Store\", \"location\": \"New York\", \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(), \"device\": \"mobile\"},\n",- " {\"transaction_id\": \"txn_002\", \"user_id\": \"user_123\", \"amount\": 2500.00, \"merchant\": \"Luxury Store\", \"location\": \"Paris\", \"timestamp\": (datetime.now() - timedelta(minutes=30)).isoformat(), \"device\": \"web\"},\n",- " {\"transaction_id\": \"txn_003\", \"user_id\": \"user_456\", \"amount\": 50.00, \"merchant\": \"Grocery Store\", \"location\": \"San Francisco\", \"timestamp\": (datetime.now() - timedelta(minutes=15)).isoformat(), \"device\": \"mobile\"},\n",- " {\"transaction_id\": \"txn_004\", \"user_id\": \"user_123\", \"amount\": 5000.00, \"merchant\": \"Electronics Store\", \"location\": \"Tokyo\", \"timestamp\": (datetime.now() - timedelta(minutes=5)).isoformat(), \"device\": \"mobile\"}\n",- "]\n",- "\n",- "with open(transactions_file, 'w') as f:\n",- " json.dump(transactions_data, f)\n",- "\n",- "file_objects = file_ingestor.ingest_file(transactions_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(transactions_file)\n",- "\n",- "transaction_stream = []\n",- "for txn in parsed_data.get(\"data\", transactions_data):\n",- " if isinstance(txn, dict):\n",- " txn_copy = txn.copy()\n",- " if \"timestamp\" in txn_copy and isinstance(txn_copy[\"timestamp\"], str):\n",- " txn_copy[\"timestamp\"] = datetime.fromisoformat(txn_copy[\"timestamp\"])\n",- " transaction_stream.append(txn_copy)\n",- "\n",- "print(f\"Ingested {len(file_objects)} transaction files\")\n",- "print(f\"Parsed {len(transaction_stream)} transactions\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Build Temporal Transaction Knowledge Graph\n",- "\n",- "Build a temporal knowledge graph from transaction data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "\n",- "transaction_entities = []\n",- "relationships = []\n",- "\n",- "for txn in transaction_stream:\n",- " txn_id = txn[\"transaction_id\"]\n",- " user_id = txn[\"user_id\"]\n",- " merchant = txn[\"merchant\"]\n",- " location = txn[\"location\"]\n",- "\n",- " transaction_entities.append({\n",- " \"id\": txn_id,\n",- " \"type\": \"Transaction\",\n",- " \"name\": txn_id,\n",- " \"properties\": {\n",- " \"amount\": txn[\"amount\"],\n",- " \"timestamp\": txn[\"timestamp\"].isoformat() if isinstance(txn[\"timestamp\"], datetime) else txn[\"timestamp\"],\n",- " \"device\": txn[\"device\"]\n",- " }\n",- " })\n",- "\n",- " transaction_entities.append({\n",- " \"id\": user_id,\n",- " \"type\": \"User\",\n",- " \"name\": user_id,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " transaction_entities.append({\n",- " \"id\": merchant,\n",- " \"type\": \"Merchant\",\n",- " \"name\": merchant,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " transaction_entities.append({\n",- " \"id\": location,\n",- " \"type\": \"Location\",\n",- " \"name\": location,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": user_id,\n",- " \"target\": txn_id,\n",- " \"type\": \"performed\",\n",- " \"properties\": {\"timestamp\": txn[\"timestamp\"].isoformat() if isinstance(txn[\"timestamp\"], datetime) else txn[\"timestamp\"]}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": txn_id,\n",- " \"target\": merchant,\n",- " \"type\": \"at_merchant\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": txn_id,\n",- " \"target\": location,\n",- " \"type\": \"in_location\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "transaction_kg = builder.build(transaction_entities, relationships)\n",- "\n",- "print(f\"Built temporal knowledge graph with {len(transaction_entities)} entities and {len(relationships)} relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Store in Graph Database\n",- "\n",- "Store the transaction graph in a persistent graph database for real-time fraud queries.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.graph_store import GraphStore\n",- "\n",- "# Initialize graph store - FalkorDB is ideal for real-time fraud detection\n",- "# For production: use FalkorDB with Redis for ultra-fast queries\n",- "# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"fraud_graph\")\n",- "\n",- "# Option 1: Neo4j (requires Neo4j server running)\n",- " graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",- " graph_store.connect()\n",- "\n",- "# Store transaction entities in graph database\n",- "node_id_map = {}\n",- "\n",- "for entity in transaction_entities:\n",- " node = graph_store.create_node(\n",- " labels=[entity[\"type\"]],\n",- " properties={\n",- " \"name\": entity[\"name\"],\n",- " \"original_id\": entity[\"id\"],\n",- " **entity.get(\"properties\", {})\n",- " }\n",- " )\n",- " node_id_map[entity[\"id\"]] = node.get(\"id\")\n",- "\n",- "print(f\"Stored {len(transaction_entities)} entities in graph database\")\n",- "\n",- "# Store relationships\n",- "for rel in relationships:\n",- " if rel[\"source\"] in node_id_map and rel[\"target\"] in node_id_map:\n",- " graph_store.create_relationship(\n",- " start_node_id=node_id_map[rel[\"source\"]],\n",- " end_node_id=node_id_map[rel[\"target\"]],\n",- " rel_type=rel[\"type\"],\n",- " properties=rel.get(\"properties\", {})\n",- " )\n",- "\n",- "print(f\"Stored {len(relationships)} relationships in graph database\")\n",- "\n",- "# Query for high-value transactions using Cypher\n",- "high_value_query = \"\"\"\n",- " MATCH (t:Transaction)\n",- " WHERE t.amount > 1000\n",- " RETURN t.name as transaction_id, t.amount as amount\n",- "\"\"\"\n",- "high_value_results = graph_store.execute_query(high_value_query)\n",- "print(f\"Found {len(high_value_results.get('records', []))} high-value transactions\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Detect Fraud Patterns\n",- "\n",- "Detect fraud patterns using graph queries and temporal analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Use graph queries to detect fraud patterns\n",- "pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "# Query for users with multiple transactions in short time\n",- "rapid_transactions_query = \"\"\"\n",- " MATCH (u:User)-[:performed]->(t:Transaction)\n",- " WITH u, count(t) as txn_count\n",- " WHERE txn_count > 2\n",- " RETURN u.name as user_id, txn_count\n",- "\"\"\"\n",- "rapid_txn_results = graph_store.execute_query(rapid_transactions_query)\n",- "\n",- "# Query for transactions in multiple locations\n",- "location_query = \"\"\"\n",- " MATCH (u:User)-[:performed]->(t:Transaction)-[:in_location]->(l:Location)\n",- " WITH u, collect(DISTINCT l.name) as locations\n",- " WHERE size(locations) > 1\n",- " RETURN u.name as user_id, locations\n",- "\"\"\"\n",- "location_results = graph_store.execute_query(location_query)\n",- "\n",- "# Detect fraud patterns from analysis\n",- "fraud_patterns = []\n",- "user_transactions = {}\n",- "for txn in transaction_stream:\n",- " user_id = txn[\"user_id\"]\n",- " if user_id not in user_transactions:\n",- " user_transactions[user_id] = []\n",- " user_transactions[user_id].append(txn)\n",- "\n",- "for user_id, txns in user_transactions.items():\n",- " if len(txns) > 1:\n",- " amounts = [t[\"amount\"] for t in txns]\n",- " locations = [t[\"location\"] for t in txns]\n",- " \n",- " if max(amounts) > 1000:\n",- " fraud_patterns.append({\n",- " \"type\": \"high_value_transaction\",\n",- " \"user_id\": user_id,\n",- " \"amount\": max(amounts),\n",- " \"severity\": \"medium\"\n",- " })\n",- "\n",- " if len(set(locations)) > 2:\n",- " fraud_patterns.append({\n",- " \"type\": \"rapid_location_change\",\n",- " \"user_id\": user_id,\n",- " \"locations\": list(set(locations)),\n",- " \"severity\": \"high\"\n",- " })\n",- "\n",- "print(f\"Detected {len(fraud_patterns)} fraud patterns using graph analysis\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Alerts and Reports\n",- "\n",- "Generate fraud alerts and reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "json_exporter.export_knowledge_graph(transaction_kg, os.path.join(temp_dir, \"transactions.json\"))\n",- "csv_exporter.export_entities(transaction_entities, os.path.join(temp_dir, \"entities.csv\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Fraud detection analysis identified {len(anomalies)} suspicious transactions\",\n",- " \"fraud_patterns\": len(fraud_patterns),\n",- " \"anomalies\": len(anomalies),\n",- " \"transactions_analyzed\": len(transaction_stream)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Quality Assessment and Visualization\n",- "\n",- "Assess graph quality and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(transaction_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(transaction_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(transaction_kg, output=\"interactive\")\n",- "\n",- "# Get final graph store statistics\n",- "graph_stats = graph_store.get_stats()\n",- "print(f\"Graph store statistics: {graph_stats}\")\n",- "\n",- "# Close graph store connection\n",- "graph_store.close()\n",- "\n",- "print(f\"Graph quality score: {quality_score.get('overall_score', 0):.3f}\")\n",- "print(f\"Total modules used: 20+ (including GraphStore)\")\n",- "print(f\"Pipeline complete: Transaction Stream \u2192 Parse \u2192 Extract \u2192 Temporal KG \u2192 Store in Graph DB \u2192 Pattern Detection \u2192 Anomaly Detection \u2192 Reports \u2192 Visualization\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb b/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynbdeleted file mode 100644index c130e2bb..00000000--- a/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb+++ /dev/null@@ -1,422 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb)\n",- "\n",- "# Investment Analysis Hybrid RAG Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete investment analysis hybrid RAG pipeline: ingest investment data from multiple sources (market data APIs, financial feeds, databases), extract investment entities, build knowledge graph, generate embeddings, set up hybrid search (vector + temporal KG), and query investment insights using advanced RAG.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser, HTMLParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch\n",- "- **Context**: ContextRetriever, ContextGraphBuilder\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Multi-Source Investment Data \u2192 Parse \u2192 Extract Entities \u2192 Build KG \u2192 Generate Embeddings \u2192 Vector Store \u2192 Hybrid RAG Setup \u2192 Query Insights \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Multi-Source Investment Data Ingestion\n",- "\n",- "Ingest investment data from market APIs, financial feeds, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser, HTMLParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch\n",- "from semantica.context import ContextRetriever, ContextGraphBuilder\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "html_parser = HTMLParser()\n",- "\n",- "# Real investment data sources\n",- "investment_apis = [\n",- " \"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2024-01-01/2024-01-31\", # Polygon.io\n",- " \"https://www.alphavantage.co/query?function=OVERVIEW&symbol=AAPL&apikey=demo\", # Alpha Vantage\n",- " \"https://api.github.com/repos/ranaroussi/yfinance\" # Yahoo Finance API\n",- "]\n",- "\n",- "financial_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://feeds.reuters.com/reuters/topNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\",\n",- " \"https://feeds.bloomberg.com/markets/news.rss\"\n",- "]\n",- "\n",- "# Real database connection for investment data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/investment_db\"\n",- "db_query = \"SELECT symbol, company_name, sector, market_cap, pe_ratio, dividend_yield FROM investments WHERE last_updated > NOW() - INTERVAL '7 days' ORDER BY market_cap DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample investment data\n",- "investment_data_file = os.path.join(temp_dir, \"investment_data.json\")\n",- "investment_data = [\n",- " {\n",- " \"symbol\": \"AAPL\",\n",- " \"company\": \"Apple Inc.\",\n",- " \"sector\": \"Technology\",\n",- " \"market_cap\": 2800000000000,\n",- " \"pe_ratio\": 28.5,\n",- " \"dividend_yield\": 0.5,\n",- " \"price\": 175.50,\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " },\n",- " {\n",- " \"symbol\": \"MSFT\",\n",- " \"company\": \"Microsoft Corporation\",\n",- " \"sector\": \"Technology\",\n",- " \"market_cap\": 2800000000000,\n",- " \"pe_ratio\": 32.1,\n",- " \"dividend_yield\": 0.7,\n",- " \"price\": 380.25,\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(investment_data_file, 'w') as f:\n",- " json.dump(investment_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(investment_data_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(investment_data_file)\n",- "\n",- "# Ingest from financial feeds\n",- "financial_feed_list = []\n",- "for feed_url in financial_feeds[:2]:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " financial_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "# Ingest from investment APIs\n",- "api_content_list = []\n",- "for api_url in investment_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " api_content_list.append(api_content)\n",- " print(f\" Ingested API: {api_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Investment data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Financial feeds: {len(financial_feed_list)}\")\n",- "print(f\" Investment APIs: {len(api_content_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Investment Entities and Build Knowledge Graph\n",- "\n",- "Extract investment entities and build knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "investment_entities = []\n",- "investment_relationships = []\n",- "all_documents = []\n",- "\n",- "# Extract from investment data\n",- "if parsed_data and parsed_data.data:\n",- " for investment in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(investment, dict):\n",- " investment_text = f\"{investment.get('company', '')} ({investment.get('symbol', '')}) in {investment.get('sector', '')} sector\"\n",- " all_documents.append(investment_text)\n",- " \n",- " investment_entities.append({\n",- " \"id\": investment.get(\"symbol\", \"\"),\n",- " \"type\": \"Stock\",\n",- " \"name\": investment.get(\"company\", \"\"),\n",- " \"properties\": {\n",- " \"symbol\": investment.get(\"symbol\", \"\"),\n",- " \"sector\": investment.get(\"sector\", \"\"),\n",- " \"market_cap\": investment.get(\"market_cap\", 0),\n",- " \"pe_ratio\": investment.get(\"pe_ratio\", 0),\n",- " \"dividend_yield\": investment.get(\"dividend_yield\", 0),\n",- " \"price\": investment.get(\"price\", 0),\n",- " \"timestamp\": investment.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " investment_entities.append({\n",- " \"id\": investment.get(\"sector\", \"\"),\n",- " \"type\": \"Sector\",\n",- " \"name\": investment.get(\"sector\", \"\"),\n",- " \"properties\": {}\n",- " })\n",- " \n",- " investment_relationships.append({\n",- " \"source\": investment.get(\"symbol\", \"\"),\n",- " \"target\": investment.get(\"sector\", \"\"),\n",- " \"type\": \"belongs_to\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "investment_kg = builder.build(investment_entities, investment_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(investment_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(investment_kg)\n",- "\n",- "print(f\"Extracted {len(investment_entities)} investment entities\")\n",- "print(f\"Extracted {len(investment_relationships)} relationships\")\n",- "print(f\"Collected {len(all_documents)} investment documents\")\n",- "print(f\"Built investment knowledge graph with {len(investment_kg.get('entities', []))} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Generate Embeddings and Setup Vector Store\n",- "\n",- "Generate embeddings and setup vector store for hybrid RAG.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "vector_store = VectorStore()\n",- "hybrid_search = HybridSearch()\n",- "\n",- "embeddings = embedding_generator.generate_embeddings(all_documents, data_type=\"text\")\n",- "\n",- "metadata = []\n",- "for i, doc in enumerate(all_documents):\n",- " metadata.append({\n",- " \"id\": f\"doc_{i}\",\n",- " \"text\": doc,\n",- " \"source\": \"investment_data\"\n",- " })\n",- "\n",- "vector_ids = vector_store.store_vectors(embeddings, metadata)\n",- "\n",- "print(f\"Generated embeddings for {len(all_documents)} documents\")\n",- "print(f\"Stored {len(vector_ids)} vectors in vector store\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Setup Hybrid RAG and Query Investment Insights\n",- "\n",- "Setup hybrid search and query investment insights.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "context_retriever = ContextRetriever(\n",- " knowledge_graph=investment_kg,\n",- " vector_store=vector_store\n",- ")\n",- "\n",- "temporal_query = TemporalGraphQuery()\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Query examples\n",- "queries = [\n",- " \"What are the best performing sectors?\",\n",- " \"Find technology stocks with high market cap\",\n",- " \"What investments have good dividend yields?\"\n",- "]\n",- "\n",- "query_results = []\n",- "for query in queries:\n",- " query_embedding = text_embedder.embed_text(query)\n",- " vector_results = vector_store.search_vectors(query_embedding, k=3)\n",- " \n",- " start_time = (datetime.now() - timedelta(days=30)).isoformat()\n",- " end_time = datetime.now().isoformat()\n",- " \n",- " temporal_results = temporal_query.query_time_range(\n",- " graph=investment_kg,\n",- " query=query,\n",- " start_time=start_time,\n",- " end_time=end_time\n",- " )\n",- " \n",- " context_results = context_retriever.retrieve(\n",- " query=query,\n",- " top_k=3,\n",- " use_graph_expansion=True\n",- " )\n",- " \n",- " query_results.append({\n",- " \"query\": query,\n",- " \"vector_results\": len(vector_results),\n",- " \"temporal_results\": len(temporal_results.get('entities', [])),\n",- " \"context_results\": len(context_results) if context_results else 0\n",- " })\n",- "\n",- "# Investment analysis rules\n",- "inference_engine.add_rule(\"IF pe_ratio < 20 AND dividend_yield > 0.5 THEN value_stock\")\n",- "inference_engine.add_rule(\"IF market_cap > 1000000000000 AND sector is Technology THEN mega_cap_tech\")\n",- "\n",- "for investment in parsed_data.data if parsed_data and parsed_data.data else []:\n",- " if isinstance(investment, dict):\n",- " inference_engine.add_fact({\n",- " \"symbol\": investment.get(\"symbol\", \"\"),\n",- " \"pe_ratio\": investment.get(\"pe_ratio\", 0),\n",- " \"dividend_yield\": investment.get(\"dividend_yield\", 0),\n",- " \"market_cap\": investment.get(\"market_cap\", 0),\n",- " \"sector\": investment.get(\"sector\", \"\")\n",- " })\n",- "\n",- "# # investment_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Processed {len(queries)} investment queries\")\n",- "for result in query_results:\n",- " print(f\" Query: '{result['query']}' - Vector: {result['vector_results']}, Temporal: {result['temporal_results']}, Context: {result['context_results']}\")\n",- "print(f\"Generated {len(investment_insights)} investment insights\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate investment analysis reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(investment_kg)\n",- "\n",- "json_exporter.export_knowledge_graph(investment_kg, os.path.join(temp_dir, \"investment_kg.json\"))\n",- "csv_exporter.export_entities(investment_entities, os.path.join(temp_dir, \"investment_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(investment_kg, os.path.join(temp_dir, \"investment_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Investment analysis identified {len(investment_insights)} insights from {len(investment_entities)} entities\",\n",- " \"investments_analyzed\": len(parsed_data.data) if parsed_data and parsed_data.data else 0,\n",- " \"insights\": len(investment_insights),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(investment_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(investment_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(investment_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Multi-Source Investment Data \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Embeddings \u2192 Vector Store \u2192 Hybrid RAG \u2192 Query \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb b/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynbdeleted file mode 100644index 45684c0b..00000000--- a/cookbook/use_cases/finance/05_Regulatory_Compliance.ipynb+++ /dev/null@@ -1,400 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/finance/06_Regulatory_Compliance.ipynb)\n",- "\n",- "# Regulatory Compliance Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete regulatory compliance pipeline: ingest regulatory documents from multiple sources (SEC, FINRA, regulatory databases), extract compliance rules, build compliance ontology, validate compliance, and generate compliance reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",->>>>>>> main- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes- "- **Quality**: KGQualityAssessor, ValidationEngine, ConflictDetector\n",- "- **Export**: JSONExporter, CSVExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Regulatory Documents \u2192 Parse \u2192 Extract Compliance Rules \u2192 Build Compliance Ontology \u2192 Validate Compliance \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Regulatory Documents from Multiple Sources\n",- "\n",- "Ingest regulatory documents from SEC, FINRA, and regulatory databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import DocumentParser, PDFParser, HTMLParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.conflicts import ConflictDetector\n",- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "html_parser = HTMLParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real regulatory data sources\n",- "regulatory_sources = [\n",- " \"https://www.sec.gov/rules/final.shtml\", # SEC Final Rules\n",- " \"https://www.finra.org/rules-guidance\", # FINRA Rules\n",- " \"https://www.federalreserve.gov/newsevents/pressreleases.htm\" # Federal Reserve\n",- "]\n",- "\n",- "regulatory_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\"\n",- "]\n",- "\n",- "# Real database connection for regulatory documents\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/regulatory_db\"\n",- "db_query = \"SELECT regulation_id, title, effective_date, compliance_requirements FROM regulations WHERE effective_date > CURRENT_DATE - INTERVAL '1 year' ORDER BY effective_date DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample regulatory document data\n",- "regulatory_file = os.path.join(temp_dir, \"regulatory_document.json\")\n",- "regulatory_data = {\n",- " \"regulation_id\": \"REG-2024-001\",\n",- " \"title\": \"Data Privacy and Security Requirements\",\n",- " \"effective_date\": (datetime.now() - timedelta(days=60)).isoformat(),\n",- " \"compliance_requirements\": [\n",- " \"Encrypt sensitive customer data\",\n",- " \"Maintain audit logs for 7 years\",\n",- " \"Report breaches within 72 hours\",\n",- " \"Conduct annual security assessments\"\n",- " ],\n",- " \"applicable_entities\": [\"Financial Institutions\", \"Broker-Dealers\", \"Investment Advisors\"],\n",- " \"penalties\": {\n",- " \"non_compliance\": \"Fines up to $1M per violation\",\n",- " \"willful_violation\": \"Criminal penalties\"\n",- " }\n",- "}\n",- "\n",- "with open(regulatory_file, 'w') as f:\n",- " json.dump(regulatory_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(regulatory_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(regulatory_file)\n",- "\n",- "# Ingest from regulatory sources\n",- "regulatory_web_list = []\n",- "for source_url in regulatory_sources[:1]:\n",- " web_content = web_ingestor.ingest_url(source_url)\n",- " if web_content:\n",- " regulatory_web_list.append(web_content)\n",- " print(f\" Ingested regulatory source: {source_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Regulatory documents: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Regulatory web sources: {len(regulatory_web_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Compliance Rules\n",- "\n",- "Extract compliance rules and requirements from regulatory documents.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "compliance_entities = []\n",- "compliance_relationships = []\n",- "\n",- "# Extract from regulatory data\n",- "if parsed_data and parsed_data.data:\n",- " regulation = parsed_data.data if isinstance(parsed_data.data, dict) else parsed_data.data[0] if isinstance(parsed_data.data, list) else {}\n",- " \n",- " if isinstance(regulation, dict):\n",- " # Regulation entity\n",- " compliance_entities.append({\n",- " \"id\": regulation.get(\"regulation_id\", \"\"),\n",- " \"type\": \"Regulation\",\n",- " \"name\": regulation.get(\"title\", \"\"),\n",- " \"properties\": {\n",- " \"effective_date\": regulation.get(\"effective_date\", \"\"),\n",- " \"regulation_id\": regulation.get(\"regulation_id\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Compliance requirements\n",- " for i, requirement in enumerate(regulation.get(\"compliance_requirements\", [])):\n",- " compliance_entities.append({\n",- " \"id\": f\"{regulation.get('regulation_id', '')}_req_{i}\",\n",- " \"type\": \"Compliance_Requirement\",\n",- " \"name\": requirement,\n",- " \"properties\": {}\n",- " })\n",- " compliance_relationships.append({\n",- " \"source\": regulation.get(\"regulation_id\", \"\"),\n",- " \"target\": f\"{regulation.get('regulation_id', '')}_req_{i}\",\n",- " \"type\": \"has_requirement\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Applicable entities\n",- " for entity_type in regulation.get(\"applicable_entities\", []):\n",- " compliance_entities.append({\n",- " \"id\": entity_type,\n",- " \"type\": \"Regulated_Entity\",\n",- " \"name\": entity_type,\n",- " \"properties\": {}\n",- " })\n",- " compliance_relationships.append({\n",- " \"source\": regulation.get(\"regulation_id\", \"\"),\n",- " \"target\": entity_type,\n",- " \"type\": \"applies_to\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "print(f\"Extracted {len(compliance_entities)} compliance entities\")\n",- "print(f\"Extracted {len(compliance_relationships)} compliance relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Compliance Ontology\n",- "\n",- "Build compliance ontology from extracted rules and requirements.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",- "ontology_validator = OntologyValidator()\n",- "\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",- "print(f\" Relationships: {len(compliance_kg.get('relationships', []))}\")\n",- "print(f\"Generated compliance ontology\")\n",- "print(f\" Classes: {len(compliance_ontology.get('classes', []))}\")\n",- "print(f\" Properties: {len(compliance_ontology.get('properties', []))}\")\n",- "print(f\" Ontology valid: {validation_result.valid}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Validate Compliance\n",- "\n",- "Validate data against compliance rules using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "validation_engine = ValidationEngine()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Define compliance validation rules\n",- "inference_engine.add_rule(\"IF data_encrypted is true AND audit_logs_maintained is true THEN data_security_compliant\")\n",- "inference_engine.add_rule(\"IF breach_reported_within_72h is true THEN breach_reporting_compliant\")\n",- "inference_engine.add_rule(\"IF annual_assessment_conducted is true THEN assessment_compliant\")\n",- "\n",- "# Sample data to validate\n",- "sample_data = {\n",- " \"data_encrypted\": True,\n",- " \"audit_logs_maintained\": True,\n",- " \"breach_reported_within_72h\": True,\n",- " \"annual_assessment_conducted\": True\n",- "}\n",- "\n",- "# Add facts for validation\n",- "for key, value in sample_data.items():\n",- " inference_engine.add_fact({key: value})\n",- "\n",- "# # compliance_status = inference_engine.forward_chain()\n",- "\n",- "# Analyze compliance graph\n",- "metrics = graph_analyzer.compute_metrics(compliance_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(compliance_kg)\n",- "\n",- "print(f\"Compliance validation complete\")\n",- "print(f\" Compliance status: {len(compliance_status)} rules satisfied\")\n",- "print(f\" Graph metrics: density {metrics.get('density', 0):.3f}\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Compliance Reports\n",- "\n",- "Generate comprehensive compliance reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "json_exporter.export_knowledge_graph(compliance_kg, os.path.join(temp_dir, \"compliance_kg.json\"))\n",- "csv_exporter.export_entities(compliance_entities, os.path.join(temp_dir, \"compliance_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(compliance_kg, os.path.join(temp_dir, \"compliance_kg.rdf\"))\n",- "owl_exporter.export(compliance_ontology, os.path.join(temp_dir, \"compliance_ontology.owl\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Compliance validation identified {len(compliance_status)} satisfied rules\",\n",- " \"regulations_analyzed\": len([e for e in compliance_entities if e.get(\"type\") == \"Regulation\"]),\n",- " \"requirements\": len([e for e in compliance_entities if e.get(\"type\") == \"Compliance_Requirement\"]),\n",- " \"compliance_status\": len(compliance_status)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\"Report length: {len(report)} characters\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Visualize Compliance\n",- "\n",- "Visualize compliance knowledge graph and ontology.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(compliance_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_hierarchy(compliance_ontology, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(compliance_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Regulatory Documents \u2192 Parse \u2192 Extract Rules \u2192 Build Ontology \u2192 Validate Compliance \u2192 Generate Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynbdeleted file mode 100644index f6b66a8d..00000000--- a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb+++ /dev/null@@ -1,481 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb)\n",- "\n",- "# Clinical Reports Processing Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete clinical reports processing pipeline: ingest clinical documents from multiple sources (EHR systems, HL7/FHIR APIs, medical databases), extract medical entities, build knowledge graph, store in triplet store, and query patient data.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripleExtractor\n",- "- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",- "- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",-=======- "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripletExtractor\n",- "- **KG**: GraphBuilder, EntityResolver, GraphAnalyzer\n",- "- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",->>>>>>> main- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-=======- "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver, TripletExtractor\n",- "- **KG**: GraphBuilder, EntityResolver, GraphAnalyzer\n",- "- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes- "- **Quality**: KGQualityAssessor, ValidationEngine\n",- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "**Clinical Documents (Files, APIs, DB, MCP) β Parse β Extract Medical Entities β Build Medical KG β Store in Triple Store β Query Patient Data β Generate Reports β Visualize**\n",-=======- "**Clinical Documents (Files, APIs, DB, MCP) \u2192 Parse \u2192 Extract Medical Entities \u2192 Build Medical KG \u2192 Store in Triplet Store \u2192 Query Patient Data \u2192 Generate Reports \u2192 Visualize**\n",->>>>>>> Stashed changes-=======- "**Clinical Documents (Files, APIs, DB, MCP) β Parse β Extract Medical Entities β Build Medical KG β Store in Triplet Store β Query Patient Data β Generate Reports β Visualize**\n",->>>>>>> main- "\n",- "---\n",- "\n",- "## Step 1: Ingest Clinical Documents from Multiple Sources\n",- "\n",- "Ingest clinical documents from EHR systems, HL7/FHIR APIs, and medical databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor, WebIngestor, MCPIngestor, ingest_mcp\n",- "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, CSVParser, MCPParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver, TripletExtractor\n",- "from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",--=======- "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "web_ingestor = WebIngestor()\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "structured_parser = StructuredDataParser()\n",- "csv_parser = CSVParser()\n",- "mcp_parser = MCPParser()\n",- "\n",- "# Real healthcare data sources\n",- "healthcare_apis = [\n",- " \"https://api.logicahealth.org/fhir/R4/Patient\", # Logica Health FHIR API\n",- " \"https://hapi.fhir.org/baseR4/Patient\", # HAPI FHIR Server\n",- " \"https://api.logicahealth.org/fhir/R4/Observation\" # FHIR Observations\n",- "]\n",- "\n",- "medical_feeds = [\n",- " \"https://www.cdc.gov/rss.xml\", # CDC Health Alerts\n",- " \"https://www.who.int/rss-feeds/news-english.xml\" # WHO News\n",- "]\n",- "\n",- "# Real database connection for clinical records (HIPAA compliant)\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/clinical_records_db\"\n",- "db_query = \"SELECT patient_id, visit_date, diagnosis, medication, procedure, doctor FROM clinical_visits WHERE visit_date > CURRENT_DATE - INTERVAL '1 year' ORDER BY visit_date DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample clinical report data\n",- "clinical_report_file = os.path.join(temp_dir, \"clinical_report.json\")\n",- "clinical_data = {\n",- " \"patient_id\": \"P001\",\n",- " \"visit_date\": (datetime.now() - timedelta(days=30)).isoformat(),\n",- " \"diagnosis\": [\"Hypertension\", \"Type 2 Diabetes\"],\n",- " \"medications\": [\"Lisinopril 10mg\", \"Metformin 500mg\"],\n",- " \"procedures\": [\"Blood Pressure Check\", \"HbA1c Test\"],\n",- " \"doctor\": \"Dr. Smith\",\n",- " \"notes\": \"Patient shows improvement in blood pressure control. Continue current medications.\"\n",- "}\n",- "\n",- "with open(clinical_report_file, 'w') as f:\n",- " json.dump(clinical_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(clinical_report_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(clinical_report_file, data_format=\"json\")\n",- "\n",- "# Ingest from FHIR APIs\n",- "fhir_content_list = []\n",- "for api_url in healthcare_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " fhir_content_list.append(api_content)\n",- " print(f\" Ingested FHIR API: {api_url}\")\n",- "\n",- "# Optional: Ingest from MCP server\n",- "# Users can bring their own medical database MCP server via URL\n",- "mcp_clinical_data = []\n",- "# Connect to medical database MCP server via URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/medical-mcp\n",- "medical_mcp_url = \"http://localhost:8000/mcp\" # Replace with your MCP server URL\n",- "\n",- "mcp_ingestor.connect(\n",- " \"clinical_mcp_server\",\n",- " url=medical_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in medical_mcp_url else {}\n",- ")\n",- "\n",- "# Ingest patient records from MCP server\n",- "mcp_data = mcp_ingestor.ingest_resources(\n",- " \"clinical_mcp_server\",\n",- " resource_uris=[\"resource://patients/records\"]\n",- ")\n",- "mcp_clinical_data.extend(mcp_data)\n",- "print(f\" Ingested MCP resources: {len(mcp_data)}\")\n",- "\n",- "# Or use tool-based ingestion to query patient records\n",- "tool_data = mcp_ingestor.ingest_tool_output(\n",- " \"clinical_mcp_server\",\n",- " tool_name=\"query_patient_records\",\n",- " arguments={\n",- " \"patient_id\": \"P001\",\n",- " \"date_range\": {\n",- " \"start\": (datetime.now() - timedelta(days=365)).isoformat(),\n",- " \"end\": datetime.now().isoformat()\n",- " }\n",- " }\n",- ")\n",- "if tool_data:\n",- " mcp_clinical_data.append(tool_data)\n",- " print(f\" Retrieved tool data\")\n",- "\n",- "# Parse MCP responses and merge with existing clinical data\n",- "for mcp_item in mcp_clinical_data:\n",- " parsed_mcp = mcp_parser.parse_response(mcp_item, response_type=\"json\")\n",- " if isinstance(parsed_mcp, dict):\n",- " if \"patient_records\" in parsed_mcp:\n",- " # Merge patient records from MCP\n",- " if isinstance(parsed_data.get(\"data\"), list):\n",- " parsed_data[\"data\"].extend(parsed_mcp.get(\"patient_records\", []))\n",- " elif isinstance(parsed_data.get(\"data\"), dict):\n",- " parsed_data[\"data\"] = [parsed_data.get(\"data\")] + parsed_mcp.get(\"patient_records\", [])\n",- " print(f\" Parsed MCP item\")\n",- "\n",- "mcp_ingestor.disconnect(\"clinical_mcp_server\")\n",- "print(f\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Clinical reports: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" FHIR API sources: {len(fhir_content_list)}\")\n",- "print(f\" Database sources: 1\")\n",- "print(f\" MCP server sources: {len(mcp_clinical_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Medical Entities\n",- "\n",- "Extract medical entities (conditions, medications, procedures, doctors) from clinical reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "coreference_resolver = CoreferenceResolver()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "medical_entities = []\n",- "relationships = []\n",- "\n",- "# Extract from clinical data\n",- "if parsed_data and parsed_data.data:\n",- " clinical = parsed_data.data if isinstance(parsed_data.data, dict) else parsed_data.data[0] if isinstance(parsed_data.data, list) else {}\n",- " \n",- " if isinstance(clinical, dict):\n",- " patient_id = clinical.get(\"patient_id\", \"\")\n",- " \n",- " medical_entities.append({\n",- " \"id\": patient_id,\n",- " \"type\": \"Patient\",\n",- " \"name\": patient_id,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Diagnoses\n",- " for diagnosis in clinical.get(\"diagnosis\", []):\n",- " medical_entities.append({\n",- " \"id\": diagnosis,\n",- " \"type\": \"Diagnosis\",\n",- " \"name\": diagnosis,\n",- " \"properties\": {}\n",- " })\n",- " relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": diagnosis,\n",- " \"type\": \"has_diagnosis\",\n",- " \"properties\": {\"timestamp\": clinical.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Medications\n",- " for medication in clinical.get(\"medications\", []):\n",- " medical_entities.append({\n",- " \"id\": medication,\n",- " \"type\": \"Medication\",\n",- " \"name\": medication,\n",- " \"properties\": {}\n",- " })\n",- " relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": medication,\n",- " \"type\": \"prescribed\",\n",- " \"properties\": {\"timestamp\": clinical.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Procedures\n",- " for procedure in clinical.get(\"procedures\", []):\n",- " medical_entities.append({\n",- " \"id\": procedure,\n",- " \"type\": \"Procedure\",\n",- " \"name\": procedure,\n",- " \"properties\": {}\n",- " })\n",- " relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": procedure,\n",- " \"type\": \"underwent\",\n",- " \"properties\": {\"timestamp\": clinical.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Doctor\n",- " doctor = clinical.get(\"doctor\", \"\")\n",- " if doctor:\n",- " medical_entities.append({\n",- " \"id\": doctor,\n",- " \"type\": \"Doctor\",\n",- " \"name\": doctor,\n",- " \"properties\": {}\n",- " })\n",- " relationships.append({\n",- " \"source\": doctor,\n",- " \"target\": patient_id,\n",- " \"type\": \"treats\",\n",- " \"properties\": {\"timestamp\": clinical.get(\"visit_date\", \"\")}\n",- " })\n",- "\n",- "print(f\"Extracted {len(medical_entities)} medical entities\")\n",- "print(f\"Extracted {len(relationships)} relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Medical Knowledge Graph\n",- "\n",- "Build knowledge graph from medical entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "entity_resolver = EntityResolver()\n",- "graph_validator = GraphValidator()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "resolved_entities = entity_resolver.resolve(medical_entities)\n",- "\n",- "medical_kg = builder.build(resolved_entities, relationships)\n",- "\n",- "validation_result = graph_validator.validate(medical_kg)\n",- "metrics = graph_analyzer.compute_metrics(medical_kg)\n",- "\n",- "print(f\"Built medical knowledge graph\")\n",- "print(f\" Entities: {len(medical_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(medical_kg.get('relationships', []))}\")\n",- "print(f\" Graph valid: {validation_result.get('valid', False)}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Store in Triplet Store and Query Patient Data\n",- "\n",- "Store knowledge graph in triplet store and query patient information.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "triplet_store = TripletStore()\n",- "triplet_manager = TripletManager()\n",- "query_engine = QueryEngine()\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "triplet_store.store_knowledge_graph(medical_kg)\n",- "\n",- "# Query patient data\n",- "patient_id = \"P001\"\n",- "patient_query = f\"SELECT * WHERE {{ ?patient :hasDiagnosis ?diagnosis . ?patient :prescribed ?medication }}\"\n",- "\n",- "query_results = query_engine.query(patient_query, knowledge_graph=medical_kg)\n",- "\n",- "# Medical inference rules\n",- "inference_engine.add_rule(\"IF patient has_diagnosis Hypertension AND patient prescribed Lisinopril THEN treatment_appropriate\")\n",- "inference_engine.add_rule(\"IF patient has_diagnosis Diabetes AND patient prescribed Metformin THEN treatment_appropriate\")\n",- "\n",- "for relationship in relationships:\n",- " if relationship.get(\"type\") == \"has_diagnosis\":\n",- " inference_engine.add_fact({\n",- " \"patient\": relationship.get(\"source\"),\n",- " \"diagnosis\": relationship.get(\"target\")\n",- " })\n",- " if relationship.get(\"type\") == \"prescribed\":\n",- " inference_engine.add_fact({\n",- " \"patient\": relationship.get(\"source\"),\n",- " \"medication\": relationship.get(\"target\")\n",- " })\n",- "\n",- "# # medical_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Stored medical knowledge graph in triplet store\")\n",- "print(f\"Query returned {len(query_results) if query_results else 0} results\")\n",- "print(f\"Generated {len(medical_insights)} medical insights\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate clinical reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "quality_assessor = KGQualityAssessor()\n",- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(medical_kg)\n",- "\n",- "json_exporter.export_knowledge_graph(medical_kg, os.path.join(temp_dir, \"clinical_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(medical_kg, os.path.join(temp_dir, \"clinical_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Clinical reports processing identified {len(medical_entities)} entities and {len(medical_insights)} insights\",\n",- " \"patients_processed\": len([e for e in medical_entities if e.get(\"type\") == \"Patient\"]),\n",- " \"diagnoses\": len([e for e in medical_entities if e.get(\"type\") == \"Diagnosis\"]),\n",- " \"medications\": len([e for e in medical_entities if e.get(\"type\") == \"Medication\"]),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(medical_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(medical_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "print(f\"Pipeline complete: Clinical Documents β Parse β Extract β Build KG β Triple Store β Query β Reports β Visualize\")\n"-=======- "print(f\"Pipeline complete: Clinical Documents \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Triplet Store \u2192 Query \u2192 Reports \u2192 Visualize\")\n"->>>>>>> Stashed changes-=======- "print(f\"Pipeline complete: Clinical Documents β Parse β Extract β Build KG β Triplet Store β Query β Reports β Visualize\")\n"->>>>>>> main- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynbdeleted file mode 100644index c64c2a57..00000000--- a/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb+++ /dev/null@@ -1,471 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Disease_Network_Analysis.ipynb)\n",- "\n",- "# Disease Network Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete disease network analysis pipeline: ingest disease data from multiple sources (medical literature, research databases, clinical trials), extract disease relationships, build disease ontology, analyze networks, and predict outcomes.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Disease Data Sources \u2192 Parse \u2192 Extract Disease Relationships \u2192 Build Disease Ontology \u2192 Analyze Networks \u2192 Predict Outcomes \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Disease Data from Multiple Sources\n",- "\n",- "Ingest disease data from medical literature, research databases, and clinical trials.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "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.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "structured_parser = StructuredDataParser()\n",- "json_parser = JSONParser()\n",- "\n",- "# Real disease data sources\n",- "disease_apis = [\n",- " \"https://api.logicahealth.org/fhir/R4/Condition\", # FHIR Conditions\n",- " \"https://hapi.fhir.org/baseR4/Condition\", # HAPI FHIR Conditions\n",- " \"https://www.ncbi.nlm.nih.gov/books/NBK5197/\" # NCBI Medical Literature\n",- "]\n",- "\n",- "medical_feeds = [\n",- " \"https://www.cdc.gov/rss.xml\", # CDC Health Alerts\n",- " \"https://www.who.int/rss-feeds/news-english.xml\" # WHO News\n",- "]\n",- "\n",- "# Real database connection for disease data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/disease_db\"\n",- "db_query = \"SELECT disease_name, icd10_code, related_diseases, symptoms, treatments FROM diseases WHERE last_updated > CURRENT_DATE - INTERVAL '1 year' ORDER BY disease_name\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample disease data\n",- "disease_file = os.path.join(temp_dir, \"disease_data.json\")\n",- "disease_data = {\n",- " \"diseases\": [\n",- " {\n",- " \"disease_name\": \"Type 2 Diabetes\",\n",- " \"icd10_code\": \"E11\",\n",- " \"related_diseases\": [\"Hypertension\", \"Cardiovascular Disease\", \"Obesity\"],\n",- " \"symptoms\": [\"Increased thirst\", \"Frequent urination\", \"Fatigue\"],\n",- " \"treatments\": [\"Metformin\", \"Insulin\", \"Lifestyle changes\"],\n",- " \"prevalence\": \"High\"\n",- " },\n",- " {\n",- " \"disease_name\": \"Hypertension\",\n",- " \"icd10_code\": \"I10\",\n",- " \"related_diseases\": [\"Type 2 Diabetes\", \"Cardiovascular Disease\", \"Kidney Disease\"],\n",- " \"symptoms\": [\"High blood pressure\", \"Headaches\", \"Dizziness\"],\n",- " \"treatments\": [\"ACE inhibitors\", \"Beta blockers\", \"Lifestyle changes\"],\n",- " \"prevalence\": \"Very High\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "with open(disease_file, 'w') as f:\n",- " json.dump(disease_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(disease_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(disease_file)\n",- "\n",- "# Ingest from disease APIs\n",- "disease_api_list = []\n",- "for api_url in disease_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " disease_api_list.append(api_content)\n",- " print(f\" Ingested disease API: {api_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Disease data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Disease API sources: {len(disease_api_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Disease Relationships\n",- "\n",- "Extract disease entities and relationships from disease data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "disease_entities = []\n",- "disease_relationships = []\n",- "\n",- "# Extract from disease data\n",- "if parsed_data and parsed_data.data:\n",- " diseases = parsed_data.data.get(\"diseases\", []) if isinstance(parsed_data.data, dict) else parsed_data.data if isinstance(parsed_data.data, list) else []\n",- " \n",- " for disease in diseases:\n",- " if isinstance(disease, dict):\n",- " disease_name = disease.get(\"disease_name\", \"\")\n",- " \n",- " disease_entities.append({\n",- " \"id\": disease_name,\n",- " \"type\": \"Disease\",\n",- " \"name\": disease_name,\n",- " \"properties\": {\n",- " \"icd10_code\": disease.get(\"icd10_code\", \"\"),\n",- " \"prevalence\": disease.get(\"prevalence\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Related diseases\n",- " for related in disease.get(\"related_diseases\", []):\n",- " disease_entities.append({\n",- " \"id\": related,\n",- " \"type\": \"Disease\",\n",- " \"name\": related,\n",- " \"properties\": {}\n",- " })\n",- " disease_relationships.append({\n",- " \"source\": disease_name,\n",- " \"target\": related,\n",- " \"type\": \"related_to\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Symptoms\n",- " for symptom in disease.get(\"symptoms\", []):\n",- " disease_entities.append({\n",- " \"id\": symptom,\n",- " \"type\": \"Symptom\",\n",- " \"name\": symptom,\n",- " \"properties\": {}\n",- " })\n",- " disease_relationships.append({\n",- " \"source\": disease_name,\n",- " \"target\": symptom,\n",- " \"type\": \"has_symptom\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Treatments\n",- " for treatment in disease.get(\"treatments\", []):\n",- " disease_entities.append({\n",- " \"id\": treatment,\n",- " \"type\": \"Treatment\",\n",- " \"name\": treatment,\n",- " \"properties\": {}\n",- " })\n",- " disease_relationships.append({\n",- " \"source\": disease_name,\n",- " \"target\": treatment,\n",- " \"type\": \"treated_with\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "print(f\"Extracted {len(disease_entities)} disease entities\")\n",- "print(f\"Extracted {len(disease_relationships)} disease relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Disease Ontology\n",- "\n",- "Build disease ontology from extracted entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "ontology_validator = OntologyValidator()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "disease_kg = builder.build(disease_entities, disease_relationships)\n",- "\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",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "validation_result = ontology_validator.validate_ontology(disease_ontology)\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "print(f\"Built disease knowledge graph\")\n",- "print(f\" Entities: {len(disease_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(disease_kg.get('relationships', []))}\")\n",- "print(f\"Generated disease ontology\")\n",- "print(f\" Classes: {len(disease_ontology.get('classes', []))}\")\n",- "print(f\" Properties: {len(disease_ontology.get('properties', []))}\")\n",- "print(f\" Ontology valid: {validation_result.valid}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze Disease Networks\n",- "\n",- "Analyze disease networks using graph analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "\n",- "metrics = graph_analyzer.compute_metrics(disease_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(disease_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(disease_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(disease_kg)\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " disease_kg,\n",- " pattern_type=\"sequence\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "print(f\"Network analysis complete\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities: {len(communities)}\")\n",- "print(f\" Central diseases: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Predict Disease Outcomes\n",- "\n",- "Predict disease progression and outcomes using inference.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Disease outcome prediction rules\n",- "inference_engine.add_rule(\"IF disease related_to Hypertension AND disease related_to Diabetes THEN high_comorbidity_risk\")\n",- "inference_engine.add_rule(\"IF disease has_symptom Fatigue AND disease prevalence is High THEN common_condition\")\n",- "inference_engine.add_rule(\"IF disease treated_with Insulin AND disease is Type 2 Diabetes THEN advanced_stage\")\n",- "\n",- "# Add facts from disease data\n",- "for disease in disease_entities:\n",- " if disease.get(\"type\") == \"Disease\":\n",- " inference_engine.add_fact({\n",- " \"disease\": disease.get(\"name\", \"\"),\n",- " \"prevalence\": disease.get(\"properties\", {}).get(\"prevalence\", \"\")\n",- " })\n",- "\n",- "for relationship in disease_relationships:\n",- " if relationship.get(\"type\") == \"related_to\":\n",- " inference_engine.add_fact({\n",- " \"disease1\": relationship.get(\"source\"),\n",- " \"disease2\": relationship.get(\"target\")\n",- " })\n",- "\n",- "# # outcome_predictions = inference_engine.forward_chain()\n",- "\n",- "print(f\"Generated {len(outcome_predictions)} disease outcome predictions\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Reports and Visualize\n",- "\n",- "Generate disease network analysis reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = 0.95\n",- "\n",- "json_exporter.export_knowledge_graph(disease_kg, os.path.join(temp_dir, \"disease_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(disease_kg, os.path.join(temp_dir, \"disease_kg.rdf\"))\n",- "owl_exporter.export(disease_ontology, os.path.join(temp_dir, \"disease_ontology.owl\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Disease network analysis identified {len(disease_entities)} entities and {len(outcome_predictions)} predictions\",\n",- " \"diseases_analyzed\": len([e for e in disease_entities if e.get(\"type\") == \"Disease\"]),\n",- " \"relationships\": len(disease_relationships),\n",- " \"predictions\": len(outcome_predictions),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(disease_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_hierarchy(disease_ontology, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(disease_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Disease Data \u2192 Parse \u2192 Extract \u2192 Build Ontology \u2192 Analyze Networks \u2192 Predict Outcomes \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynbdeleted file mode 100644index bb98d5c9..00000000--- a/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb+++ /dev/null@@ -1,488 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/03_Drug_Interactions_Analysis.ipynb)\n",- "\n",- "# Drug Interactions Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete drug interactions analysis pipeline: ingest drug data from multiple sources (FDA databases, drug interaction databases, medical literature), extract drug information, build drug knowledge graph, detect interactions, and generate drug safety ontology.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Drug Data Sources \u2192 Parse \u2192 Extract Drug Info \u2192 Build Drug KG \u2192 Detect Interactions \u2192 Generate Ontology \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Drug Data from Multiple Sources\n",- "\n",- "Ingest drug data from FDA databases, drug interaction databases, and medical literature.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "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.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "structured_parser = StructuredDataParser()\n",- "json_parser = JSONParser()\n",- "\n",- "# Real drug data sources\n",- "drug_apis = [\n",- " \"https://api.fda.gov/drug/label.json\", # FDA Drug Labeling API\n",- " \"https://api.fda.gov/drug/event.json\", # FDA Adverse Events API\n",- " \"https://api.logicahealth.org/fhir/R4/Medication\" # FHIR Medications\n",- "]\n",- "\n",- "medical_feeds = [\n",- " \"https://www.cdc.gov/rss.xml\", # CDC Health Alerts\n",- " \"https://www.who.int/rss-feeds/news-english.xml\" # WHO News\n",- "]\n",- "\n",- "# Real database connection for drug data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/drug_db\"\n",- "db_query = \"SELECT drug_name, drug_class, interactions, contraindications, side_effects FROM drugs WHERE last_updated > CURRENT_DATE - INTERVAL '1 year' ORDER BY drug_name\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample drug interaction data\n",- "drug_file = os.path.join(temp_dir, \"drug_data.json\")\n",- "drug_data = {\n",- " \"drugs\": [\n",- " {\n",- " \"drug_name\": \"Lisinopril\",\n",- " \"drug_class\": \"ACE Inhibitor\",\n",- " \"interactions\": [\"Potassium supplements\", \"Diuretics\", \"NSAIDs\"],\n",- " \"contraindications\": [\"Pregnancy\", \"Angioedema\"],\n",- " \"side_effects\": [\"Cough\", \"Dizziness\", \"Hyperkalemia\"]\n",- " },\n",- " {\n",- " \"drug_name\": \"Metformin\",\n",- " \"drug_class\": \"Biguanide\",\n",- " \"interactions\": [\"Alcohol\", \"Contrast agents\"],\n",- " \"contraindications\": [\"Renal impairment\", \"Lactic acidosis\"],\n",- " \"side_effects\": [\"Nausea\", \"Diarrhea\", \"Lactic acidosis\"]\n",- " },\n",- " {\n",- " \"drug_name\": \"Warfarin\",\n",- " \"drug_class\": \"Anticoagulant\",\n",- " \"interactions\": [\"Aspirin\", \"Antibiotics\", \"Vitamin K\"],\n",- " \"contraindications\": [\"Active bleeding\", \"Pregnancy\"],\n",- " \"side_effects\": [\"Bleeding\", \"Bruising\", \"Hair loss\"]\n",- " }\n",- " ]\n",- "}\n",- "\n",- "with open(drug_file, 'w') as f:\n",- " json.dump(drug_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(drug_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(drug_file)\n",- "\n",- "# Ingest from drug APIs\n",- "drug_api_list = []\n",- "for api_url in drug_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " drug_api_list.append(api_content)\n",- " print(f\" Ingested drug API: {api_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Drug data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Drug API sources: {len(drug_api_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Drug Information\n",- "\n",- "Extract drug entities and interaction information.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "drug_entities = []\n",- "drug_relationships = []\n",- "\n",- "# Extract from drug data\n",- "if parsed_data and parsed_data.data:\n",- " drugs = parsed_data.data.get(\"drugs\", []) if isinstance(parsed_data.data, dict) else parsed_data.data if isinstance(parsed_data.data, list) else []\n",- " \n",- " for drug in drugs:\n",- " if isinstance(drug, dict):\n",- " drug_name = drug.get(\"drug_name\", \"\")\n",- " \n",- " drug_entities.append({\n",- " \"id\": drug_name,\n",- " \"type\": \"Drug\",\n",- " \"name\": drug_name,\n",- " \"properties\": {\n",- " \"drug_class\": drug.get(\"drug_class\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Drug interactions\n",- " for interaction in drug.get(\"interactions\", []):\n",- " drug_entities.append({\n",- " \"id\": interaction,\n",- " \"type\": \"Drug\",\n",- " \"name\": interaction,\n",- " \"properties\": {}\n",- " })\n",- " drug_relationships.append({\n",- " \"source\": drug_name,\n",- " \"target\": interaction,\n",- " \"type\": \"interacts_with\",\n",- " \"properties\": {\"severity\": \"moderate\"}\n",- " })\n",- " \n",- " # Contraindications\n",- " for contraindication in drug.get(\"contraindications\", []):\n",- " drug_entities.append({\n",- " \"id\": contraindication,\n",- " \"type\": \"Contraindication\",\n",- " \"name\": contraindication,\n",- " \"properties\": {}\n",- " })\n",- " drug_relationships.append({\n",- " \"source\": drug_name,\n",- " \"target\": contraindication,\n",- " \"type\": \"contraindicated_in\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Side effects\n",- " for side_effect in drug.get(\"side_effects\", []):\n",- " drug_entities.append({\n",- " \"id\": side_effect,\n",- " \"type\": \"Side_Effect\",\n",- " \"name\": side_effect,\n",- " \"properties\": {}\n",- " })\n",- " drug_relationships.append({\n",- " \"source\": drug_name,\n",- " \"target\": side_effect,\n",- " \"type\": \"causes\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "print(f\"Extracted {len(drug_entities)} drug entities\")\n",- "print(f\"Extracted {len(drug_relationships)} drug relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Drug Knowledge Graph\n",- "\n",- "Build knowledge graph from drug entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "drug_kg = builder.build(drug_entities, drug_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(drug_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(drug_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(drug_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(drug_kg)\n",- "\n",- "print(f\"Built drug knowledge graph\")\n",- "print(f\" Entities: {len(drug_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(drug_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities: {len(communities)}\")\n",- "print(f\" Central drugs: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Detect Drug Interactions\n",- "\n",- "Detect drug-drug interactions using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Drug interaction detection rules\n",- "inference_engine.add_rule(\"IF drug1 interacts_with drug2 AND drug2 interacts_with drug1 THEN bidirectional_interaction\")\n",- "inference_engine.add_rule(\"IF drug interacts_with Anticoagulant AND drug is Antibiotic THEN increased_bleeding_risk\")\n",- "inference_engine.add_rule(\"IF drug contraindicated_in Pregnancy AND patient is pregnant THEN contraindicated\")\n",- "\n",- "# Detect interactions\n",- "interactions = []\n",- "for relationship in drug_relationships:\n",- " if relationship.get(\"type\") == \"interacts_with\":\n",- " drug1 = relationship.get(\"source\")\n",- " drug2 = relationship.get(\"target\")\n",- " \n",- " # Check for bidirectional interaction\n",- " reverse_interaction = [r for r in drug_relationships \n",- " if r.get(\"source\") == drug2 and r.get(\"target\") == drug1 and r.get(\"type\") == \"interacts_with\"]\n",- " \n",- " if reverse_interaction:\n",- " interactions.append({\n",- " \"drug1\": drug1,\n",- " \"drug2\": drug2,\n",- " \"type\": \"bidirectional\",\n",- " \"severity\": relationship.get(\"properties\", {}).get(\"severity\", \"unknown\")\n",- " })\n",- " else:\n",- " interactions.append({\n",- " \"drug1\": drug1,\n",- " \"drug2\": drug2,\n",- " \"type\": \"unidirectional\",\n",- " \"severity\": relationship.get(\"properties\", {}).get(\"severity\", \"unknown\")\n",- " })\n",- " \n",- " inference_engine.add_fact({\n",- " \"drug1\": drug1,\n",- " \"drug2\": drug2,\n",- " \"interaction_type\": relationship.get(\"type\")\n",- " })\n",- "\n",- "# # detected_interactions = inference_engine.forward_chain()\n",- "\n",- "print(f\"Detected {len(interactions)} drug interactions\")\n",- "print(f\"Inferred {len(detected_interactions)} interaction patterns\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Drug Ontology\n",- "\n",- "Generate drug safety ontology from drug knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "ontology_validator = OntologyValidator()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\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",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "validation_result = ontology_validator.validate_ontology(drug_ontology)\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "print(f\"Generated drug safety ontology\")\n",- "print(f\" Classes: {len(drug_ontology.get('classes', []))}\")\n",- "print(f\" Properties: {len(drug_ontology.get('properties', []))}\")\n",- "print(f\" Ontology valid: True\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Reports and Visualize\n",- "\n",- "Generate drug interaction reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_assessor = KGQualityAssessor()\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "quality_score = quality_assessor.assess_overall_quality(drug_kg)\n",-=======->>>>>>> Stashed changes-=======-->>>>>>> main- "\n",- "json_exporter.export_knowledge_graph(drug_kg, os.path.join(temp_dir, \"drug_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(drug_kg, os.path.join(temp_dir, \"drug_kg.rdf\"))\n",- "owl_exporter.export(drug_ontology, os.path.join(temp_dir, \"drug_ontology.owl\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Drug interactions analysis identified {len(interactions)} interactions from {len(drug_entities)} drug entities\",\n",- " \"drugs_analyzed\": len([e for e in drug_entities if e.get(\"type\") == \"Drug\"]),\n",- " \"interactions\": len(interactions),\n",- " \"quality_score\": 0.95\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(drug_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_hierarchy(drug_ontology, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(drug_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Drug Data \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Detect Interactions \u2192 Generate Ontology \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynbdeleted file mode 100644index 04085606..00000000--- a/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb+++ /dev/null@@ -1,849 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/04_Healthcare_GraphRAG_Hybrid.ipynb)\n",- "\n",- "# Healthcare GraphRAG System with Semantica\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates building a **Retrieval-Augmented Generation (GraphRAG) system** using **Semantica as the core framework** that leverages heterogeneous healthcare resources through a combination of materialized knowledge graphs and virtually integrated data sources.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/concepts/)\n",- "\n",- "### Why Semantica?\n",- "\n",- "Semantica provides a comprehensive, unified framework for building GraphRAG systems in healthcare:\n",- "\n",- "- **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies, clinical documents, and reports\n",- "- **Virtual Data Integration**: Semantica's DBIngestor and QueryEngine allow virtual integration with Electronic Health Records (EHRs) without data replication\n",- "- **Hybrid Design**: Semantica's architecture naturally separates structural knowledge from patient-level data\n",- "- **Dynamic Query Orchestration**: Semantica's Reasoning and Triplet Store modules enable orchestration of queries across ontologies, documents, and EHRs\n",- "- **Temporal & Semantic Dimensions**: Semantica's Temporal and Context modules provide historical analysis and semantic understanding\n",- "- **Traceable & Explainable**: Semantica's ExplanationGenerator and ContextRetriever provide traceable, explainable answers\n",- "\n",- "### Key Features\n",- "\n",- "- Materialized knowledge graphs from medical ontologies (SNOMED CT, ICD-10), clinical documents, and reports\n",- "- Virtual integration with Electronic Health Records (EHRs) without data replication\n",- "- Hybrid design separating structural knowledge from patient-level data\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "- Dynamic orchestration of queries across ontologies, documents, and EHRs using Semantica\n",- "- Temporal and semantic dimensions via graph for historical analysis\n",- "- Traceable, explainable, and historically contextualized answers\n",- "\n",- "### Semantica Modules Used (20+)\n",- "\n",- "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (for EHR virtual connections and medical literature)\n",- "- **Parse**: DocumentParser, PDFParser (clinical documents), StructuredDataParser (for structured medical data)\n",- "- **Normalize**: TextNormalizer (for text normalization)\n",- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor (medical entities and relationships)\n",- "- **Ontology**: OntologyGenerator, OWLGenerator (medical ontologies like SNOMED CT, ICD-10)\n",- "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (materialized knowledge graph)\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder (for embeddings)\n",- "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter (for RAG)\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Triple Store**: TripleManager, QueryEngine (for SPARQL queries on ontologies)\n",-=======- "- **Triplet Store**: TripletStore, QueryEngine (for SPARQL queries on ontologies)\n",->>>>>>> main- "- **Reasoning**: InferenceEngine, RuleManager (for query orchestration and medical reasoning)\n",-=======- "- **Triplet Store**: TripletStore, QueryEngine (for SPARQL queries on ontologies)\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager (for query orchestration and medical reasoning)\n",->>>>>>> Stashed changes- "- **Context**: ContextRetriever, ContextGraphBuilder (for contextual retrieval)\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer (for visualization)\n",- "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",- "- **Pipeline**: PipelineBuilder, ExecutionEngine (for orchestrating the complete pipeline)\n",- "\n",- "### Pipeline Overview\n",- "\n",- "**Medical Ontologies + Clinical Documents + EHRs (Virtual) \u2192 Parse \u2192 Extract Medical Entities \u2192 Build Materialized KG \u2192 Generate Embeddings \u2192 Vector Store \u2192 GraphRAG Setup \u2192 Query Orchestration \u2192 Generate Answers \u2192 Visualize & Export**\n",- "\n",- "---\n",- "\n",- "## Step 1: Setup and Import Semantica Modules\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "%pip install -U \"semantica[all]\"\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import all Semantica modules - using Semantica as the core framework\n",- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor\n",- "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser\n",- "from semantica.normalize import TextNormalizer\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor\n",- "from semantica.ontology import OntologyGenerator, OWLGenerator\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "from semantica.triple_store import TripleManager, QueryEngine\n",-=======- "from semantica.triplet_store import TripletStore, QueryEngine\n",->>>>>>> main- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-=======- "from semantica.triplet_store import TripletStore, QueryEngine\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes- "from semantica.context import ContextRetriever, ContextGraphBuilder\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "from semantica.export import JSONExporter, RDFExporter, ReportGenerator\n",- "from semantica.pipeline import PipelineBuilder, ExecutionEngine\n",- "\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "import numpy as np\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Ingest Medical Ontologies and Clinical Documents\n",- "\n",- "Using Semantica's ingest modules to load medical ontologies, clinical documents, and set up virtual connections to EHRs.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica ingestors\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "\n",- "# Create temporary directory for sample data\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample medical ontology data (SNOMED CT concepts)\n",- "snomed_data = {\n",- " \"concepts\": [\n",- " {\n",- " \"concept_id\": \"73211009\",\n",- " \"concept_name\": \"Diabetes mellitus\",\n",- " \"hierarchy\": \"Clinical finding\",\n",- " \"parent_concept\": \"Disorder of glucose metabolism\"\n",- " },\n",- " {\n",- " \"concept_id\": \"44054006\",\n",- " \"concept_name\": \"Type 2 diabetes mellitus\",\n",- " \"hierarchy\": \"Clinical finding\",\n",- " \"parent_concept\": \"Diabetes mellitus\"\n",- " },\n",- " {\n",- " \"concept_id\": \"46635009\",\n",- " \"concept_name\": \"Type 1 diabetes mellitus\",\n",- " \"hierarchy\": \"Clinical finding\",\n",- " \"parent_concept\": \"Diabetes mellitus\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample clinical document\n",- "clinical_document = {\n",- " \"document_id\": \"DOC-001\",\n",- " \"patient_id\": \"PATIENT-001\",\n",- " \"document_type\": \"Clinical Note\",\n",- " \"content\": \"Patient presents with Type 2 diabetes mellitus. Current medications include Metformin 500mg twice daily. Blood glucose levels are well-controlled. Patient reports adherence to dietary recommendations.\",\n",- " \"date\": datetime.now().isoformat(),\n",- " \"physician\": \"Dr. Smith\"\n",- "}\n",- "\n",- "# Save sample data\n",- "snomed_file = os.path.join(temp_dir, \"snomed_concepts.json\")\n",- "clinical_file = os.path.join(temp_dir, \"clinical_note.json\")\n",- "\n",- "with open(snomed_file, 'w') as f:\n",- " json.dump(snomed_data, f, indent=2)\n",- "\n",- "with open(clinical_file, 'w') as f:\n",- " json.dump(clinical_document, f, indent=2)\n",- "\n",- "# Ingest using Semantica FileIngestor\n",- "snomed_file_obj = file_ingestor.ingest_file(snomed_file, read_content=True)\n",- "clinical_file_obj = file_ingestor.ingest_file(clinical_file, read_content=True)\n",- "\n",- "# Virtual EHR connection setup (using Semantica DBIngestor)\n",- "# In production, this would connect to actual EHR database\n",- "ehr_connection_config = {\n",- " \"connection_string\": \"postgresql://user:password@localhost:5432/ehr_db\",\n",- " \"query\": \"SELECT patient_id, diagnosis, medications, lab_results, visit_date FROM patient_records WHERE patient_id = %s\"\n",- "}\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Parse and Normalize Data Using Semantica\n",- "\n",- "Using Semantica's parse and normalize modules to process the ingested data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica parsers and normalizer\n",- "document_parser = DocumentParser()\n",- "pdf_parser = PDFParser()\n",- "structured_parser = StructuredDataParser()\n",- "text_normalizer = TextNormalizer()\n",- "\n",- "# Parse structured data (SNOMED CT)\n",- "parsed_snomed = structured_parser.parse_json(snomed_file)\n",- "snomed_concepts = parsed_snomed.data if hasattr(parsed_snomed, 'data') else parsed_snomed\n",- "\n",- "# Parse clinical document\n",- "parsed_clinical = structured_parser.parse_json(clinical_file)\n",- "clinical_data = parsed_clinical.data if hasattr(parsed_clinical, 'data') else parsed_clinical\n",- "\n",- "# Normalize clinical text using Semantica\n",- "if isinstance(clinical_data, dict) and 'content' in clinical_data:\n",- " normalized_text = text_normalizer.normalize_text(clinical_data['content'])\n",- " clinical_data['normalized_content'] = normalized_text\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Extract Medical Entities and Relationships Using Semantica\n",- "\n",- "Using Semantica's semantic extraction modules to extract medical entities, relationships, and triplets from the parsed data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica extractors\n",- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "# Extract entities from clinical document\n",- "clinical_text = clinical_data.get('normalized_content', clinical_data.get('content', ''))\n",- "extracted_entities = ner_extractor.extract(clinical_text)\n",- "\n",- "# Extract relationships\n",- "extracted_relationships = relation_extractor.extract(clinical_text, entities=extracted_entities)\n",- "\n",- "# Extract triplets\n",- "extracted_triplets = triplet_extractor.extract(clinical_text)\n",- "\n",- "# Build entity list for knowledge graph\n",- "medical_entities = []\n",- "medical_relationships = []\n",- "\n",- "# Add SNOMED CT concepts as entities\n",- "if isinstance(snomed_concepts, dict):\n",- " for concept in snomed_concepts.get('concepts', []):\n",- " medical_entities.append({\n",- " \"id\": f\"snomed_{concept.get('concept_id', '')}\",\n",- " \"type\": \"Medical_Concept\",\n",- " \"name\": concept.get('concept_name', ''),\n",- " \"properties\": {\n",- " \"concept_id\": concept.get('concept_id', ''),\n",- " \"hierarchy\": concept.get('hierarchy', ''),\n",- " \"source\": \"SNOMED_CT\"\n",- " }\n",- " })\n",- "\n",- "# Add extracted entities from clinical document\n",- "for entity in extracted_entities:\n",- " medical_entities.append({\n",- " \"id\": f\"entity_{entity.get('id', len(medical_entities))}\",\n",- " \"type\": entity.get('type', 'Entity'),\n",- " \"name\": entity.get('text', ''),\n",- " \"properties\": {\n",- " \"source\": \"clinical_document\",\n",- " \"document_id\": clinical_data.get('document_id', '')\n",- " }\n",- " })\n",- "\n",- "# Add relationships\n",- "for rel in extracted_relationships:\n",- " medical_relationships.append({\n",- " \"source\": rel.get('source', ''),\n",- " \"target\": rel.get('target', ''),\n",- " \"type\": rel.get('type', 'related_to'),\n",- " \"properties\": {\n",- " \"source\": \"clinical_document\"\n",- " }\n",- " })\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Build Materialized Knowledge Graph Using Semantica\n",- "\n",- "Using Semantica's KG modules to build a materialized knowledge graph from the extracted entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica KG builders and analyzers\n",- "graph_builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Build materialized knowledge graph using Semantica\n",- "materialized_kg = graph_builder.build(medical_entities, medical_relationships)\n",- "\n",- "# Analyze the graph using Semantica\n",- "kg_metrics = graph_analyzer.compute_metrics(materialized_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(materialized_kg)\n",- "\n",- "print(f\" - Entities: {len(materialized_kg.get('entities', []))}\")\n",- "print(f\" - Relationships: {len(materialized_kg.get('relationships', []))}\")\n",- "print(f\" - Graph density: {kg_metrics.get('density', 0):.4f}\")\n",- "print(f\" - Connected components: {connectivity.get('num_components', 0)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Ontology Using Semantica\n",- "\n",- "Using Semantica's ontology modules to generate medical ontologies from the knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# 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 = 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"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Generate Embeddings Using Semantica\n",- "\n",- "Using Semantica's embedding modules to generate vector embeddings for RAG.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica embedding generators\n",- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "\n",- "# Generate embeddings for clinical documents using Semantica\n",- "documents_for_embedding = [clinical_data.get('normalized_content', clinical_data.get('content', ''))]\n",- "\n",- "# Generate embeddings using Semantica\n",- "document_embeddings = []\n",- "for doc in documents_for_embedding:\n",- " embedding = text_embedder.embed(doc)\n",- " document_embeddings.append(embedding)\n",- "\n",- "# Generate embeddings for entities\n",- "entity_embeddings = {}\n",- "for entity in medical_entities[:10]: # Limit for demo\n",- " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",- " embedding = text_embedder.embed(entity_text)\n",- " entity_embeddings[entity.get('id', '')] = embedding\n",- "\n",- "print(f\" - Document embeddings: {len(document_embeddings)}\")\n",- "print(f\" - Entity embeddings: {len(entity_embeddings)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Setup Vector Store and Hybrid Search Using Semantica\n",- "\n",- "Using Semantica's vector store modules to set up RAG with hybrid search capabilities.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica vector store and hybrid search\n",- "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",- "hybrid_search = HybridSearch()\n",- "\n",- "# Prepare metadata for documents\n",- "document_metadata = [{\n",- " \"document_id\": clinical_data.get('document_id', ''),\n",- " \"document_type\": clinical_data.get('document_type', ''),\n",- " \"date\": clinical_data.get('date', ''),\n",- " \"source\": \"clinical_document\"\n",- "}]\n",- "\n",- "# Store document embeddings using Semantica\n",- "document_ids = vector_store.store_vectors(\n",- " vectors=document_embeddings,\n",- " metadata=document_metadata\n",- ")\n",- "\n",- "# Store entity embeddings\n",- "entity_metadata = [{\"entity_id\": eid, \"type\": \"entity\", \"source\": \"kg\"} for eid in entity_embeddings.keys()]\n",- "entity_ids = vector_store.store_vectors(\n",- " vectors=list(entity_embeddings.values()),\n",- " metadata=entity_metadata\n",- ")\n",- "\n",- "print(f\" - Document vectors stored: {len(document_ids)}\")\n",- "print(f\" - Entity vectors stored: {len(entity_ids)}\")\n",- "print(f\" - Hybrid search ready for GraphRAG\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Setup Triplet Store for Ontology Queries Using Semantica\n",- "\n",- "Using Semantica's triplet store modules to enable SPARQL queries on medical ontologies.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica triplet store and query engine\n",- "store = TripletStore(backend=\"jena\", endpoint=\"http://localhost:3030/healthcare\")\n",- "query_engine = store.query_engine\n",- "\n",- "# Convert ontology to triplets and add to store\n",- "# In production, this would load the OWL ontology\n",- "sample_triplets = [\n",- " {\n",- " \"subject\": \"http://semantica.example.org/healthcare#Type2Diabetes\",\n",- " \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",- " \"object\": \"http://semantica.example.org/healthcare#Diabetes\",\n",- " \"confidence\": 1.0\n",- " },\n",- " {\n",- " \"subject\": \"http://semantica.example.org/healthcare#Type1Diabetes\",\n",- " \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",- " \"object\": \"http://semantica.example.org/healthcare#Diabetes\",\n",- " \"confidence\": 1.0\n",- " }\n",- "]\n",- "\n",- "# Add triplets using Semantica\n",- "for triplet in sample_triplets:\n",- " store.add_triplet(triplet)\n",- "\n",- "print(f\" - Triplets added: {len(sample_triplets)}\")\n",- "print(f\" - SPARQL queries enabled for ontology\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 10: Implement GraphRAG Query Orchestration Using Semantica\n",- "\n",- "Using Semantica's reasoning and context modules to orchestrate queries across ontologies, documents, and EHRs.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica reasoning and context modules\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "context_retriever = ContextRetriever()\n",- "context_graph_builder = ContextGraphBuilder()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Define medical reasoning rules using Semantica\n",- "medical_rules = [\n",- " {\n",- " \"rule_id\": \"diabetes_treatment_rule\",\n",- " \"condition\": \"IF patient has Type2Diabetes THEN recommend Metformin\",\n",- " \"action\": \"suggest_treatment\"\n",- " }\n",- "]\n",- "\n",- "# Add rules using Semantica\n",- "for rule in medical_rules:\n",- " rule_manager.add_rule(rule)\n",- "\n",- "# Example query orchestration function using Semantica\n",- "def orchestrate_graphrag_query(query_text, patient_id=None):\n",- " \"\"\"\n",- " Orchestrate GraphRAG query across ontologies, documents, and EHRs using Semantica.\n",- " \"\"\"\n",- " results = {\n",- " \"ontology_results\": [],\n",- " \"document_results\": [],\n",- " \"ehr_results\": [],\n",- " \"graph_results\": [],\n",- " \"context\": {}\n",- " }\n",- " \n",- " # 1. Query ontology using Semantica Triplet Store\n",- " sparql_query = f\"\"\"\n",- " SELECT ?concept WHERE {{\n",- " ?concept rdfs:label ?label .\n",- " FILTER(CONTAINS(LCASE(?label), \"{query_text.lower()}\"))\n",- " }}\n",- " \"\"\"\n",- " ontology_results = store.execute_query(sparql_query)\n",- " results[\"ontology_results\"] = ontology_results.bindings\n",- " \n",- " # 2. Search documents using Semantica Hybrid Search\n",- " query_embedding = text_embedder.embed(query_text)\n",- " document_results = hybrid_search.search(\n",- " query_vector=query_embedding,\n",- " vectors=document_embeddings,\n",- " metadata=document_metadata,\n",- " vector_ids=document_ids,\n",- " k=5\n",- " )\n",- " results[\"document_results\"] = document_results\n",- " \n",- " # 3. Query knowledge graph using Semantica\n",- " graph_results = graph_analyzer.query_graph(materialized_kg, query_text)\n",- " results[\"graph_results\"] = graph_results\n",- " \n",- " # 4. Build context using Semantica\n",- " context_graph = context_graph_builder.build(\n",- " entities=medical_entities,\n",- " relationships=medical_relationships,\n",- " query=query_text\n",- " )\n",- " results[\"context\"] = context_graph\n",- " \n",- " # 5. Virtual EHR query (would execute in production)\n",- " if patient_id:\n",- " # In production: ehr_results = db_ingestor.query(ehr_connection_config, patient_id)\n",- " results[\"ehr_results\"] = {\"note\": \"EHR query would execute here in production\"}\n",- " \n",- " return results\n",- "\n",- "# Example query\n",- "query = \"What are the treatment options for Type 2 diabetes?\"\n",- "orchestrated_results = orchestrate_graphrag_query(query)\n",- "\n",- "print(f\" - Query: '{query}'\")\n",- "print(f\" - Ontology results: {len(orchestrated_results['ontology_results'])}\")\n",- "print(f\" - Document results: {len(orchestrated_results['document_results'])}\")\n",- "print(f\" - Graph results: {len(orchestrated_results['graph_results'])}\")\n",- "print(f\" - Context built: {bool(orchestrated_results['context'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Generate explanation using Semantica\n",- "explanation = explanation_generator.generate(\n",- " query=query,\n",- " results=orchestrated_results,\n",- " knowledge_graph=materialized_kg,\n",- " context=orchestrated_results['context']\n",- ")\n",- "\n",- "print(f\" {explanation.get('answer', 'Answer generated')}\")\n",- "print(f\"\\nSources:\")\n",- "print(f\" - Ontology: {len(orchestrated_results['ontology_results'])} results\")\n",- "print(f\" - Documents: {len(orchestrated_results['document_results'])} results\")\n",- "print(f\" - Knowledge Graph: {len(orchestrated_results['graph_results'])} results\")\n",- "print(f\" - Traceability: Enabled via Semantica ContextRetriever\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 12: Visualize Knowledge Graph and Results Using Semantica\n",- "\n",- "Using Semantica's visualization modules to visualize the knowledge graph and analysis results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica visualizers\n",- "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "# Visualize knowledge graph using Semantica\n",- "kg_fig = kg_visualizer.visualize_network(\n",- " materialized_kg,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize analytics\n",- "centrality = graph_analyzer.compute_centrality(materialized_kg, method=\"pagerank\")\n",- "analytics_data = {\n",- " \"graph\": materialized_kg,\n",- " \"centrality\": centrality\n",- "}\n",- "analytics_fig = analytics_visualizer.visualize_centrality_rankings(\n",- " centrality,\n",- " centrality_type=\"pagerank\",\n",- " top_n=10,\n",- " output=\"interactive\"\n",- ")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 13: Export Results Using Semantica\n",- "\n",- "Using Semantica's export modules to export the knowledge graph, ontology, and reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica exporters\n",- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph as JSON using Semantica\n",- "kg_json_file = os.path.join(temp_dir, \"healthcare_kg.json\")\n",- "json_exporter.export(materialized_kg, kg_json_file)\n",- "\n",- "# Export ontology as RDF using Semantica\n",- "ontology_rdf_file = os.path.join(temp_dir, \"healthcare_ontology.rdf\")\n",- "rdf_exporter.export(ontology_result, ontology_rdf_file)\n",- "\n",- "# Generate comprehensive report using Semantica\n",- "report_data = {\n",- " \"title\": \"Healthcare GraphRAG System Report\",\n",- " \"knowledge_graph_metrics\": kg_metrics,\n",- " \"query_results\": orchestrated_results,\n",- " \"explanation\": explanation\n",- "}\n",- "report_file = os.path.join(temp_dir, \"healthcare_graphrag_report.html\")\n",- "report_generator.generate_report(report_data, report_file, format=\"html\")\n",- "\n",- "print(f\" - Knowledge graph JSON: {kg_json_file}\")\n",- "print(f\" - Ontology RDF: {ontology_rdf_file}\")\n",- "print(f\" - Report HTML: {report_file}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 14: Complete Pipeline Orchestration Using Semantica\n",- "\n",- "Using Semantica's pipeline module to orchestrate the complete GraphRAG pipeline.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Build complete pipeline using Semantica PipelineBuilder\n",- "pipeline_builder = PipelineBuilder()\n",- "\n",- "# Define handlers using existing Semantica modules initialized earlier\n",- "def ingest_handler(data, **config):\n",- " source_dir = config.get(\"source\", temp_dir)\n",- " files = []\n",- " try:\n",- " files = [os.path.join(source_dir, f) for f in os.listdir(source_dir)]\n",- " except Exception:\n",- " pass\n",- " if files:\n",- " file_obj = file_ingestor.ingest_file(files[0], read_content=True)\n",- " return {**data, \"file\": file_obj}\n",- " return data\n",- "\n",- "def parse_handler(data, **config):\n",- " file_obj = data.get(\"file\")\n",- " if file_obj and getattr(file_obj, \"path\", None):\n",- " parsed = document_parser.parse_document(file_obj.path)\n",- " text = parsed.get(\"text\") if isinstance(parsed, dict) else None\n",- " return {**data, \"text\": text or data.get(\"text\")}\n",- " return data\n",- "\n",- "def extract_handler(data, **config):\n",- " text = data.get(\"text\", \"\")\n",- " entities = ner_extractor.extract_entities(text) if hasattr(ner_extractor, 'extract_entities') else ner_extractor.extract(text)\n",- " entity_dicts = [{\"id\": f\"e{i}\", \"name\": getattr(e, 'text', str(e)), \"type\": getattr(e, 'label', getattr(e, 'type', 'Entity'))} for i, e in enumerate(entities)]\n",- " return {**data, \"entities\": entity_dicts}\n",- "\n",- "def build_kg_handler(data, **config):\n",- " entities = data.get(\"entities\", [])\n",- " kg = graph_builder.build({\"entities\": entities})\n",- " return {**data, \"knowledge_graph\": kg}\n",- "healthcare_graphrag_pipeline = (\n",- " pipeline_builder\n",- " .add_step(\"ingest\", \"ingest\", handler=ingest_handler, source=temp_dir)\n",- " .add_step(\"parse\", \"parse\", dependencies=[\"ingest\"], handler=parse_handler)\n",- " .add_step(\"extract\", \"extract\", dependencies=[\"parse\"], handler=extract_handler)\n",- " .add_step(\"build_kg\", \"build_kg\", dependencies=[\"extract\"], handler=build_kg_handler)\n",- " .build()\n",- "\n",- "# Execute pipeline using Semantica ExecutionEngine\n",- "execution_engine = ExecutionEngine()\n",- "pipeline_result = execution_engine.execute_pipeline(healthcare_graphrag_pipeline, {\"files\": []})\n",- "\n",- "print(f\" - Pipeline steps: {len(healthcare_graphrag_pipeline.steps)}\")\n",- "print(f\" - Execution status: {getattr(pipeline_result, 'success', True)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion and Best Practices\n",- "\n",- "### Key Takeaways\n",- "\n",- "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for building a Healthcare GraphRAG system\n",- "2. **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies and documents\n",- "3. **Virtual Data Integration**: Semantica's DBIngestor allows virtual integration with EHRs without data replication\n",- "4. **Hybrid Search**: Semantica's HybridSearch combines vector similarity with knowledge graph queries\n",- "5. **Query Orchestration**: Semantica's Reasoning and Triplet Store modules enable dynamic query orchestration\n",- "6. **Explainability**: Semantica's ExplanationGenerator provides traceable, explainable answers\n",- "\n",- "### Semantica-Specific Performance Considerations\n",- "\n",- "- **Vector Store**: Use Semantica's VectorStore with appropriate backend (FAISS for local, Weaviate for cloud)\n",- "- **Graph Analytics**: Leverage Semantica's GraphAnalyzer for efficient centrality and community detection\n",- "- **Pipeline Execution**: Use Semantica's ExecutionEngine for parallel execution of pipeline steps\n",- "- **Caching**: Utilize Semantica's ContextRetriever caching for frequently accessed contexts\n",- "\n",- "### Deployment Recommendations Using Semantica\n",- "\n",- "1. **Production Setup**:\n",- " - Use Semantica's configuration management for environment-specific settings\n",- " - Leverage Semantica's Pipeline module for production workflows\n",- " - Use Semantica's export modules for data persistence\n",- "\n",- "2. **Scalability**:\n",- " - Use Semantica's batch processing capabilities for large-scale data ingestion\n",- " - Leverage Semantica's vector store adapters for distributed storage\n",- " - Utilize Semantica's parallel execution features\n",- "\n",- "3. **Compliance**:\n",- " - Semantica's virtual data integration ensures EHR data remains in original systems\n",- " - Use Semantica's audit logging for traceability\n",- " - Leverage Semantica's export modules for compliance reporting\n",- "\n",- "### How Semantica's Architecture Benefits Healthcare GraphRAG\n",- "\n",- "- **Unified Framework**: Single framework for all operations reduces integration complexity\n",- "- **Modular Design**: Semantica's modular architecture allows flexible deployment\n",- "- **Extensibility**: Semantica's registry system enables custom method registration\n",- "- **Type Safety**: Semantica's structured data models ensure data consistency\n",- "- **Performance**: Semantica's optimized algorithms provide efficient graph operations\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb b/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynbdeleted file mode 100644index 6c0fe8b8..00000000--- a/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb+++ /dev/null@@ -1,624 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/05_Medical_Database_Integration.ipynb)\n",- "\n",- "# Medical Database Integration Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for medical database ingestion. Connect to medical database MCP servers via URL, ingest patient records, drug interactions, and clinical data, then build a healthcare knowledge graph.\n",- "\n",- "**IMPORTANT**: This implementation supports ONLY Python-based MCP servers and FastMCP servers. Users can bring their own Python/FastMCP MCP servers via URL connections.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",- "- **Parsing**: MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",- "- **Triple Store**: TripleStore, TripleManager, QueryEngine\n",-=======- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, EntityResolver, GraphAnalyzer\n",- "- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",->>>>>>> main- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-=======- "- **Extraction**: NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, EntityResolver, GraphAnalyzer\n",- "- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes- "- **Quality**: KGQualityAssessor, ValidationEngine\n",- "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Connect to Medical MCP Server \u2192 Ingest Patient/Drug Data via MCP \u2192 Parse MCP Responses \u2192 Extract Medical Entities \u2192 Build Healthcare KG \u2192 Query & Analyze \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Connect to Medical Database MCP Server\n",- "\n",- "Connect to a Python/FastMCP MCP server that provides medical database access via URL. The MCP server can expose resources (patient records, drug databases) and tools (queries, drug interaction checks)."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "%pip install -U \"semantica[all]\"\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import MCPIngestor, ingest_mcp\n",- "from semantica.parse import MCPParser, JSONParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphValidator, EntityResolver, GraphAnalyzer\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "from semantica.triple_store import TripleStore, TripleManager, QueryEngine\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",--=======- "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "# Initialize MCP ingestor\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "# Connect to medical database MCP server via URL\n",- "# Replace with your actual MCP server URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/medical-mcp\n",- "medical_mcp_url = \"http://localhost:8000/mcp\"\n",- "\n",- "# Connect to MCP server with authentication (if required)\n",- "mcp_ingestor.connect(\n",- " \"medical_server\",\n",- " url=medical_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in medical_mcp_url else {}\n",- ")\n",- "\n",- "# List available resources (patient records, drug databases)\n",- "resources = mcp_ingestor.list_available_resources(\"medical_server\")\n",- "print(f\"\\n\ud83d\udcca Available Resources ({len(resources)}):\")\n",- "for resource in resources[:5]: # Show first 5\n",- " print(f\" - {resource.uri}: {resource.name}\")\n",- " if resource.description:\n",- " print(f\" {resource.description[:80]}...\")\n",- "\n",- "# List available tools (queries, drug interaction checks)\n",- "tools = mcp_ingestor.list_available_tools(\"medical_server\")\n",- "print(f\"\\n\ud83d\udd27 Available Tools ({len(tools)}):\")\n",- "for tool in tools[:5]: # Show first 5\n",- " print(f\" - {tool.name}: {tool.description or 'No description'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Ingest Medical Data from MCP Server\n",- "\n",- "Ingest patient records, drug interactions, and clinical data using both resource-based and tool-based methods.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize parsers\n",- "mcp_parser = MCPParser()\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "medical_data = []\n",- "\n",- "# Method 1: Resource-based ingestion\n",- "# Ingest from MCP resources (patient records, drug databases)\n",- "# Example: Ingest patient records resource\n",- "patient_data = mcp_ingestor.ingest_resources(\n",- " \"medical_server\",\n",- " resource_uris=[\"resource://patients/records\", \"resource://drugs/interactions\"]\n",- ")\n",- "\n",- "for item in patient_data:\n",- " medical_data.append(item)\n",- " print(f\" Ingested resource: {item}\")\n",- "\n",- "# Method 2: Tool-based ingestion\n",- "# Call MCP tools to retrieve data dynamically\n",- "# Example: Query patient records\n",- "patient_records = mcp_ingestor.ingest_tool_output(\n",- " \"medical_server\",\n",- " tool_name=\"query_patient_records\",\n",- " arguments={\n",- " \"patient_id\": \"P001\",\n",- " \"date_range\": {\n",- " \"start\": (datetime.now() - timedelta(days=365)).isoformat(),\n",- " \"end\": datetime.now().isoformat()\n",- " }\n",- " }\n",- ")\n",- "\n",- "if patient_records:\n",- " medical_data.append(patient_records)\n",- " print(f\" Retrieved patient records\")\n",- "\n",- "# Example: Check drug interactions\n",- "drug_interactions = mcp_ingestor.ingest_tool_output(\n",- " \"medical_server\",\n",- " tool_name=\"check_drug_interactions\",\n",- " arguments={\n",- " \"medications\": [\"Lisinopril\", \"Metformin\", \"Aspirin\"]\n",- " }\n",- ")\n",- "\n",- "if drug_interactions:\n",- " medical_data.append(drug_interactions)\n",- " print(f\" Retrieved drug interactions\")\n",- "\n",- "# Sample medical data (if MCP server is not available)\n",- "if not medical_data:\n",- " sample_data = {\n",- " \"patient_records\": [\n",- " {\n",- " \"patient_id\": \"P001\",\n",- " \"visit_date\": (datetime.now() - timedelta(days=30)).isoformat(),\n",- " \"diagnosis\": [\"Hypertension\", \"Type 2 Diabetes\"],\n",- " \"medications\": [\"Lisinopril 10mg\", \"Metformin 500mg\"],\n",- " \"procedures\": [\"Blood Pressure Check\", \"HbA1c Test\"],\n",- " \"doctor\": \"Dr. Smith\",\n",- " \"notes\": \"Patient shows improvement in blood pressure control.\"\n",- " },\n",- " {\n",- " \"patient_id\": \"P002\",\n",- " \"visit_date\": (datetime.now() - timedelta(days=15)).isoformat(),\n",- " \"diagnosis\": [\"Asthma\"],\n",- " \"medications\": [\"Albuterol Inhaler\"],\n",- " \"procedures\": [\"Spirometry\"],\n",- " \"doctor\": \"Dr. Johnson\",\n",- " \"notes\": \"Asthma well controlled with current medication.\"\n",- " }\n",- " ],\n",- " \"drug_interactions\": [\n",- " {\n",- " \"drug1\": \"Lisinopril\",\n",- " \"drug2\": \"Aspirin\",\n",- " \"interaction_type\": \"moderate\",\n",- " \"description\": \"May increase risk of kidney problems\"\n",- " },\n",- " {\n",- " \"drug1\": \"Metformin\",\n",- " \"drug2\": \"Alcohol\",\n",- " \"interaction_type\": \"severe\",\n",- " \"description\": \"May cause lactic acidosis\"\n",- " }\n",- " ]\n",- " }\n",- " medical_data.append(sample_data)\n",- " print(f\" Loaded {len(sample_data['patient_records'])} patient records\")\n",- " print(f\" Loaded {len(sample_data['drug_interactions'])} drug interactions\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Total medical data items ingested: {len(medical_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Parse MCP Medical Data\n",- "\n",- "Parse the medical data received from MCP server responses.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "parsed_medical_data = []\n",- "\n",- "# Parse MCP responses\n",- "for data_item in medical_data:\n",- " # Parse MCP response (handles JSON, text, binary)\n",- " if isinstance(data_item, dict):\n",- " parsed_item = data_item\n",- " else:\n",- " parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",- " \n",- " parsed_medical_data.append(parsed_item)\n",- " print(f\" Parsed data item\")\n",- "\n",- "# Extract patient records and drug interactions\n",- "patient_records = []\n",- "drug_interactions = []\n",- "\n",- "for item in parsed_medical_data:\n",- " if isinstance(item, dict):\n",- " if \"patient_records\" in item:\n",- " patient_records.extend(item[\"patient_records\"])\n",- " elif \"patient_id\" in item:\n",- " patient_records.append(item)\n",- " elif \"drug_interactions\" in item:\n",- " drug_interactions.extend(item[\"drug_interactions\"])\n",- " elif \"drug1\" in item:\n",- " drug_interactions.append(item)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Extract Medical Entities and Relationships\n",- "\n",- "Extract medical entities (patients, diagnoses, medications, procedures, doctors) and relationships from MCP data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "medical_entities = []\n",- "medical_relationships = []\n",- "\n",- "# Extract from patient records\n",- "for record in patient_records:\n",- " if isinstance(record, dict):\n",- " patient_id = record.get(\"patient_id\", \"\")\n",- " \n",- " # Patient entity\n",- " medical_entities.append({\n",- " \"id\": patient_id,\n",- " \"type\": \"Patient\",\n",- " \"name\": patient_id,\n",- " \"properties\": {\"visit_date\": record.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Diagnoses\n",- " for diagnosis in record.get(\"diagnosis\", []):\n",- " medical_entities.append({\n",- " \"id\": diagnosis,\n",- " \"type\": \"Diagnosis\",\n",- " \"name\": diagnosis,\n",- " \"properties\": {}\n",- " })\n",- " medical_relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": diagnosis,\n",- " \"type\": \"has_diagnosis\",\n",- " \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Medications\n",- " for medication in record.get(\"medications\", []):\n",- " medical_entities.append({\n",- " \"id\": medication,\n",- " \"type\": \"Medication\",\n",- " \"name\": medication,\n",- " \"properties\": {}\n",- " })\n",- " medical_relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": medication,\n",- " \"type\": \"prescribed\",\n",- " \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Procedures\n",- " for procedure in record.get(\"procedures\", []):\n",- " medical_entities.append({\n",- " \"id\": procedure,\n",- " \"type\": \"Procedure\",\n",- " \"name\": procedure,\n",- " \"properties\": {}\n",- " })\n",- " medical_relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": procedure,\n",- " \"type\": \"underwent\",\n",- " \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",- " })\n",- " \n",- " # Doctor\n",- " doctor = record.get(\"doctor\", \"\")\n",- " if doctor:\n",- " medical_entities.append({\n",- " \"id\": doctor,\n",- " \"type\": \"Doctor\",\n",- " \"name\": doctor,\n",- " \"properties\": {}\n",- " })\n",- " medical_relationships.append({\n",- " \"source\": doctor,\n",- " \"target\": patient_id,\n",- " \"type\": \"treats\",\n",- " \"properties\": {\"timestamp\": record.get(\"visit_date\", \"\")}\n",- " })\n",- "\n",- "# Extract from drug interactions\n",- "for interaction in drug_interactions:\n",- " if isinstance(interaction, dict):\n",- " drug1 = interaction.get(\"drug1\", \"\")\n",- " drug2 = interaction.get(\"drug2\", \"\")\n",- " interaction_type = interaction.get(\"interaction_type\", \"\")\n",- " \n",- " if drug1 and drug2:\n",- " medical_relationships.append({\n",- " \"source\": drug1,\n",- " \"target\": drug2,\n",- " \"type\": \"interacts_with\",\n",- " \"properties\": {\n",- " \"interaction_type\": interaction_type,\n",- " \"description\": interaction.get(\"description\", \"\")\n",- " }\n",- " })\n",- "\n",- "# Remove duplicates\n",- "seen_entities = set()\n",- "unique_entities = []\n",- "for entity in medical_entities:\n",- " entity_key = (entity[\"id\"], entity[\"type\"])\n",- " if entity_key not in seen_entities:\n",- " seen_entities.add(entity_key)\n",- " unique_entities.append(entity)\n",- "\n",- "medical_entities = unique_entities\n",- "\n",- "print(f\" - Patients: {len([e for e in medical_entities if e['type'] == 'Patient'])}\")\n",- "print(f\" - Diagnoses: {len([e for e in medical_entities if e['type'] == 'Diagnosis'])}\")\n",- "print(f\" - Medications: {len([e for e in medical_entities if e['type'] == 'Medication'])}\")\n",- "print(f\" - Procedures: {len([e for e in medical_entities if e['type'] == 'Procedure'])}\")\n",- "print(f\" - Doctors: {len([e for e in medical_entities if e['type'] == 'Doctor'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Build Healthcare Knowledge Graph\n",- "\n",- "Build a knowledge graph from the extracted medical entities and relationships, then store in triplet store.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "graph_validator = GraphValidator()\n",- "entity_resolver = EntityResolver()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "# Build knowledge graph\n",- "medical_kg = builder.build(medical_entities, medical_relationships)\n",- "\n",- "# Validate and resolve entities\n",- "validated_kg = graph_validator.validate(medical_kg)\n",- "resolved_kg = entity_resolver.resolve_entities(validated_kg)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(resolved_kg)\n",- "\n",- "# Store in triplet store\n",- "# triplet_store = TripletStore() # TripletStore is a configuration dataclass\n",- "triplet_manager = TripletManager()\n",- "query_engine = QueryEngine()\n",- "\n",- "# Register default store (in-memory for demo)\n",- "store = triplet_manager.register_store(\"medical_kg\", \"jena\", \"http://localhost:3030/medical\")\n",- "\n",- "# Convert KG to triplets and add to store (simplified)\n",- "# In a real scenario, we would convert entities/relations to triplets first\n",- "# triplet_manager.add_triplets(triplets, store_id=\"medical_kg\")\n",- "\n",- "print(f\" Entities: {len(resolved_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(resolved_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Query and Analyze Medical Data\n",- "\n",- "Query the healthcare knowledge graph and analyze medical patterns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Query patient data\n",- "patient_query = query_engine.query(\n",- " \"SELECT ?patient ?diagnosis WHERE { ?patient has_diagnosis ?diagnosis }\"\n",- ")\n",- "\n",- "# Query drug interactions\n",- "interaction_query = query_engine.query(\n",- " \"SELECT ?drug1 ?drug2 ?type WHERE { ?drug1 interacts_with ?drug2 }\"\n",- ")\n",- "\n",- "# Inference engine for medical rules\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Medical analysis rules\n",- "inference_engine.add_rule(\"IF has_diagnosis(Diabetes) AND prescribed(Metformin) THEN diabetes_treatment\")\n",- "inference_engine.add_rule(\"IF interacts_with(Drug1, Drug2) AND interaction_type(severe) THEN contraindication\")\n",- "\n",- "# Add facts from medical data\n",- "for record in patient_records:\n",- " if isinstance(record, dict):\n",- " for diagnosis in record.get(\"diagnosis\", []):\n",- " inference_engine.add_fact({\n",- " \"patient\": record.get(\"patient_id\", \"\"),\n",- " \"diagnosis\": diagnosis\n",- " })\n",- " for medication in record.get(\"medications\", []):\n",- " inference_engine.add_fact({\n",- " \"patient\": record.get(\"patient_id\", \"\"),\n",- " \"medication\": medication\n",- " })\n",- "\n",- "for interaction in drug_interactions:\n",- " if isinstance(interaction, dict):\n",- " inference_engine.add_fact({\n",- " \"drug1\": interaction.get(\"drug1\", \"\"),\n",- " \"drug2\": interaction.get(\"drug2\", \"\"),\n",- " \"interaction_type\": interaction.get(\"interaction_type\", \"\")\n",- " })\n",- "\n",- "# Generate medical insights\n",- "# # medical_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\" Patient-diagnosis relationships: {len(patient_query.get('results', []))}\")\n",- "print(f\" Drug interactions: {len(interaction_query.get('results', []))}\")\n",- "print(f\" Medical insights: {len(medical_insights)}\")\n",- "\n",- "# Quality assessment\n",- "quality_assessor = KGQualityAssessor()\n",- "validation_engine = ValidationEngine()\n",- "\n",- "quality_metrics = quality_assessor.assess_quality(resolved_kg)\n",- "validation_results = validation_engine.validate(resolved_kg)\n",- "\n",- "print(f\" Quality score: {quality_metrics.get('overall_score', 0):.2f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Export and Visualize\n",- "\n",- "Export the healthcare knowledge graph and generate visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import tempfile\n",- "import os\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "json_exporter = JSONExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph\n",- "json_exporter.export_knowledge_graph(resolved_kg, os.path.join(temp_dir, \"medical_kg.json\"))\n",- "rdf_exporter.export_knowledge_graph(resolved_kg, os.path.join(temp_dir, \"medical_kg.rdf\"))\n",- "# Note: OWLExporter expects an ontology structure, not a knowledge graph\n",- "# To export as OWL, first generate an ontology from the KG using OntologyGenerator\n",- "\n",- "# Generate report\n",- "report_data = {\n",- " \"summary\": f\"Medical database integration from MCP server identified {len(medical_insights)} insights\",\n",- " \"patients\": len([e for e in medical_entities if e['type'] == 'Patient']),\n",- " \"diagnoses\": len([e for e in medical_entities if e['type'] == 'Diagnosis']),\n",- " \"medications\": len([e for e in medical_entities if e['type'] == 'Medication']),\n",- " \"drug_interactions\": len(drug_interactions),\n",- " \"insights\": len(medical_insights)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\" JSON: {os.path.join(temp_dir, 'medical_kg.json')}\")\n",- "print(f\" RDF: {os.path.join(temp_dir, 'medical_kg.rdf')}\")\n",- "\n",- "# Visualize\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(resolved_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_ontology(resolved_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(resolved_kg, output=\"interactive\")\n",- "\n",- "\n",- "# Cleanup: Disconnect from MCP server\n",- "mcp_ingestor.disconnect(\"medical_server\")\n",- "print(\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\ud83d\udcca Total modules used: 20+\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb b/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynbdeleted file mode 100644index 04805afc..00000000--- a/cookbook/use_cases/healthcare/06_Patient_Records_Temporal.ipynb+++ /dev/null@@ -1,345 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/07_Patient_Records_Temporal.ipynb)\n",- "\n",- "# Patient Records Temporal Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete patient records temporal analysis pipeline for healthcare: ingest patient records, extract medical entities, build temporal knowledge graph, query medical history, and generate insights.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, DBIngestor, StreamIngestor\n",- "- **Parsing**: DocumentParser, StructuredDataParser, CSVParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, CoreferenceResolver\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, EntityResolver\n",- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",- "- **Triplet Store**: TripletStore, TripletManager, QueryEngine\n",- "- **Export**: RDFExporter, OWLExporter, JSONExporter\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Patient Records β Parse β Extract Medical Entities β Build Temporal KG β Generate Ontology β Store in Triplet Store β Query History β Export β Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Process Patient Records\n",- "\n",- "Ingest and parse patient records from multiple sources.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, DBIngestor, StreamIngestor\n",- "from semantica.parse import DocumentParser, StructuredDataParser, CSVParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, CoreferenceResolver\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, EntityResolver\n",- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "from semantica.triplet_store import TripletStore, TripletManager, QueryEngine\n",- "from semantica.export import RDFExporter, OWLExporter, JSONExporter\n",- "from semantica.visualization import KGVisualizer, OntologyVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "document_parser = DocumentParser()\n",- "structured_parser = StructuredDataParser()\n",- "csv_parser = CSVParser()\n",- "\n",- "# Real database connection for patient records (HIPAA compliant example)\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/patient_records_db\"\n",- "db_query = \"SELECT patient_id, visit_date, diagnosis, medication, doctor FROM patient_visits WHERE visit_date > CURRENT_DATE - INTERVAL '1 year' ORDER BY visit_date DESC\"\n",- "\n",- "# Real HL7/FHIR API endpoints (examples)\n",- "healthcare_apis = [\n",- " \"https://api.logicahealth.org/fhir/R4/Patient\", # Logica Health FHIR API\n",- " \"https://hapi.fhir.org/baseR4/Patient\" # HAPI FHIR Server\n",- "]\n",- "\n",- "# Real medical feed URLs\n",- "medical_feeds = [\n",- " \"https://www.cdc.gov/rss.xml\", # CDC Health Alerts\n",- " \"https://www.who.int/rss-feeds/news-english.xml\" # WHO News\n",- "]\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "patient_records_file = os.path.join(temp_dir, \"patient_records.csv\")\n",- "patient_data = \"\"\"patient_id,visit_date,diagnosis,medication,doctor\n",- "P001,2024-01-15,Hypertension,Lisinopril,Dr. Smith\n",- "P001,2024-02-20,Diabetes,Metformin,Dr. Jones\n",- "P002,2024-01-10,Fever,Acetaminophen,Dr. Smith\"\"\"\n",- "\n",- "with open(patient_records_file, 'w') as f:\n",- " f.write(patient_data)\n",- "\n",- "file_objects = file_ingestor.ingest_file(patient_records_file, read_content=True)\n",- "parsed_csv = csv_parser.parse(patient_records_file)\n",- "\n",- "print(f\"Ingested {len([file_objects]) if file_objects else 0} patient record files\")\n",- "print(f\"Parsed {len(parsed_csv.rows) if parsed_csv else 0} patient records\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Medical Entities\n",- "\n",- "Extract medical entities and relationships from patient records.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "coreference_resolver = CoreferenceResolver()\n",- "\n",- "patient_entities = []\n",- "relationships = []\n",- "\n",- "if parsed_csv and parsed_csv.rows:\n",- " for row in parsed_csv.rows:\n",- " patient_id = row.get(\"patient_id\", \"\")\n",- " diagnosis = row.get(\"diagnosis\", \"\")\n",- " medication = row.get(\"medication\", \"\")\n",- " doctor = row.get(\"doctor\", \"\")\n",- " visit_date = row.get(\"visit_date\", \"\")\n",- "\n",- " patient_entities.append({\n",- " \"id\": patient_id,\n",- " \"type\": \"Patient\",\n",- " \"name\": patient_id,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " patient_entities.append({\n",- " \"id\": diagnosis,\n",- " \"type\": \"Diagnosis\",\n",- " \"name\": diagnosis,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " patient_entities.append({\n",- " \"id\": medication,\n",- " \"type\": \"Medication\",\n",- " \"name\": medication,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " patient_entities.append({\n",- " \"id\": doctor,\n",- " \"type\": \"Doctor\",\n",- " \"name\": doctor,\n",- " \"properties\": {}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": diagnosis,\n",- " \"type\": \"has_diagnosis\",\n",- " \"properties\": {\"timestamp\": visit_date}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": patient_id,\n",- " \"target\": medication,\n",- " \"type\": \"prescribed\",\n",- " \"properties\": {\"timestamp\": visit_date}\n",- " })\n",- "\n",- " relationships.append({\n",- " \"source\": doctor,\n",- " \"target\": patient_id,\n",- " \"type\": \"treats\",\n",- " \"properties\": {\"timestamp\": visit_date}\n",- " })\n",- "\n",- "print(f\"Extracted {len(patient_entities)} medical entities\")\n",- "print(f\"Extracted {len(relationships)} relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Build Temporal Patient Knowledge Graph\n",- "\n",- "Build a temporal knowledge graph from patient data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "entity_resolver = EntityResolver()\n",- "\n",- "resolved_entities = entity_resolver.resolve(patient_entities)\n",- "\n",- "patient_kg = builder.build(resolved_entities, relationships)\n",- "\n",- "print(f\"Built temporal patient knowledge graph\")\n",- "print(f\" Entities: {len(patient_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(patient_kg.get('relationships', []))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Generate Medical Ontology\n",- "\n",- "Generate ontology from medical entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",- "ontology_validator = OntologyValidator()\n",- "\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",- "\n",- "validation_result = ontology_validator.validate_ontology(ontology)\n",- "\n",- "print(f\"Generated medical ontology\")\n",- "print(f\" Classes: {len(ontology.get('classes', []))}\")\n",- "print(f\" Properties: {len(ontology.get('properties', []))}\")\n",- "print(f\" Ontology valid: {validation_result.valid}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Store in Triplet Store and Query\n",- "\n",- "Store knowledge graph in triplet store and query medical history.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "triplet_store = TripletStore()\n",- "triplet_manager = TripletManager()\n",- "query_engine = QueryEngine()\n",- "temporal_query = TemporalGraphQuery()\n",- "\n",- "triplet_store.store_knowledge_graph(patient_kg)\n",- "\n",- "patient_id = \"P001\"\n",- "start_time = \"2024-01-01\"\n",- "end_time = \"2024-12-31\"\n",- "\n",- "medical_history = temporal_query.query_time_range(\n",- " graph=patient_kg,\n",- " query=f\"Find medical history for patient {patient_id}\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "print(f\"Stored patient knowledge graph in triplet store\")\n",- "print(f\"Retrieved {len(medical_history.get('entities', []))} medical events for patient {patient_id}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Export and Visualize\n",- "\n",- "Export patient data and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "json_exporter = JSONExporter()\n",- "\n",- "rdf_exporter.export_knowledge_graph(patient_kg, os.path.join(temp_dir, \"patient_kg.rdf\"))\n",- "owl_exporter.export(ontology, os.path.join(temp_dir, \"medical_ontology.owl\"))\n",- "json_exporter.export_knowledge_graph(patient_kg, os.path.join(temp_dir, \"patient_kg.json\"))\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(patient_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_hierarchy(ontology, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(patient_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Patient Records β Parse β Extract β Temporal KG β Ontology β Triplet Store β Query β Export β Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb b/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynbdeleted file mode 100644index 1c6c14f9..00000000--- a/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb+++ /dev/null@@ -1,933 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/01_Criminal_Network_Analysis.ipynb)\n",- "\n",- "# Criminal Network Analysis with Semantica\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete criminal network analysis pipeline using **Semantica as the core framework** with agent-based workflows, MCP integration, and comprehensive graph analytics. The pipeline ingests data from multiple sources (police reports, court records, surveillance data), builds knowledge graphs, performs network analysis, and generates intelligence reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Why Semantica?\n",- "\n",- "Semantica provides a complete framework for criminal network analysis:\n",- "\n",- "- **Multi-Source Data Ingestion**: Ingest from files, databases, web sources, and MCP-enabled external APIs\n",- "- **MCP Integration**: Access public records databases, court records APIs, and real-time data streams\n",- "- **Agent-Based Workflows**: Autonomous agents with persistent memory for coordinated intelligence gathering\n",- "- **Graph Analytics**: Comprehensive network analysis with centrality measures and community detection\n",- "- **GraphRAG**: Hybrid retrieval combining knowledge graph queries with vector similarity search\n",- "- **Pattern Detection**: Identify suspicious patterns and relationships in criminal networks\n",- "- **Intelligence Reporting**: Generate professional HTML reports with actionable insights\n",- "\n",- "### Key Features\n",- "\n",- "- Ingest criminal network data from multiple sources including MCP-enabled databases\n",- "- Autonomous agent-based data gathering with persistent memory\n",- "- Extract entities (suspects, organizations, locations, events) and relationships\n",- "- Build temporal knowledge graphs for criminal network analysis\n",- "- Comprehensive graph analytics (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",- "- Hybrid RAG for intelligence queries combining KG and vector search\n",- "- Pattern detection for identifying key players and suspicious activities\n",- "- Professional intelligence report generation\n",- "\n",- "### Semantica Modules Used (25+)\n",- "\n",- "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor (multi-source data ingestion)\n",- "- **MCP Integration**: MCP browser tools and resources for external data access\n",- "- **Parse**: StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",- "- **Normalize**: TextNormalizer, DataNormalizer\n",- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",- "- **Graph Store**: GraphStore with Neo4j/FalkorDB for persistent criminal network storage\n",- "- **Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",- "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: ReportGenerator, JSONExporter\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "- **Deduplication**: DuplicateDetector, EntityMerger\n",- "\n",- "### Pipeline Overview\n",- "\n",- "**Data Sources (Police Reports, Court Records, Surveillance) \u2192 MCP Integration \u2192 Agent-Based Data Gathering \u2192 Parse \u2192 Extract Entities/Relationships \u2192 Build Criminal Network KG \u2192 Graph Analytics \u2192 GraphRAG \u2192 Agent Analysis \u2192 Pattern Detection \u2192 Generate Intelligence Report \u2192 Visualize**\n",- "\n",- "---\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Setup and Import Semantica Modules\n",- "\n",- "Import all necessary Semantica modules for criminal network analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import all Semantica modules for criminal network analysis\n",- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",- "from semantica.parse import StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",- "from semantica.normalize import TextNormalizer, DataNormalizer\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer, TemporalGraphQuery\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",- "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import ReportGenerator, JSONExporter\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "from semantica.deduplication import DuplicateDetector, EntityMerger\n",- "\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "import numpy as np\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Initialize Agent Memory and Setup Agents\n",- "\n",- "Set up AgentMemory for persistent context and initialize specialized agents for criminal network analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize vector store for agent memory\n",- "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",- "embedding_generator = EmbeddingGenerator()\n",- "\n",- "# Initialize agent memory for persistent context\n",- "agent_memory = AgentMemory(\n",- " vector_store=vector_store,\n",- " retention_policy=\"unlimited\",\n",- " max_memory_size=10000\n",- ")\n",- "\n",- "# Initialize Semantica modules for agents\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "graph_analyzer = GraphAnalyzer()\n",- "# # inference_engine = InferenceEngine()\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Ingest Criminal Network Data with MCP Integration\n",- "\n",- "Ingest data from multiple sources including police reports, court records, and surveillance data. Use MCP for accessing external databases and APIs.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Create temporary directory for sample data\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample criminal network data - police reports\n",- "police_reports_data = {\n",- " \"reports\": [\n",- " {\n",- " \"report_id\": \"PR001\",\n",- " \"date\": \"2024-01-15\",\n",- " \"suspects\": [\"John Doe\", \"Jane Smith\"],\n",- " \"location\": \"Downtown District\",\n",- " \"incident_type\": \"Drug Trafficking\",\n",- " \"description\": \"Multiple suspects observed in suspicious activity. Connection to known criminal organization.\"\n",- " },\n",- " {\n",- " \"report_id\": \"PR002\",\n",- " \"date\": \"2024-02-10\",\n",- " \"suspects\": [\"Jane Smith\", \"Bob Johnson\"],\n",- " \"location\": \"Warehouse District\",\n",- " \"incident_type\": \"Money Laundering\",\n",- " \"description\": \"Financial transactions linked to criminal network. Multiple bank accounts involved.\"\n",- " },\n",- " {\n",- " \"report_id\": \"PR003\",\n",- " \"date\": \"2024-03-05\",\n",- " \"suspects\": [\"John Doe\", \"Alice Brown\", \"Charlie Wilson\"],\n",- " \"location\": \"Port Area\",\n",- " \"incident_type\": \"Smuggling\",\n",- " \"description\": \"Cargo shipment investigation reveals connections to international criminal network.\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample court records data\n",- "court_records_data = {\n",- " \"cases\": [\n",- " {\n",- " \"case_id\": \"CR001\",\n",- " \"defendant\": \"John Doe\",\n",- " \"charges\": [\"Drug Trafficking\", \"Conspiracy\"],\n",- " \"date\": \"2024-01-20\",\n",- " \"outcome\": \"Pending\",\n",- " \"co_defendants\": [\"Jane Smith\"]\n",- " },\n",- " {\n",- " \"case_id\": \"CR002\",\n",- " \"defendant\": \"Jane Smith\",\n",- " \"charges\": [\"Money Laundering\", \"Racketeering\"],\n",- " \"date\": \"2024-02-15\",\n",- " \"outcome\": \"Pending\",\n",- " \"co_defendants\": [\"Bob Johnson\"]\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample surveillance data\n",- "surveillance_data = {\n",- " \"observations\": [\n",- " {\n",- " \"observation_id\": \"SV001\",\n",- " \"date\": \"2024-01-18\",\n",- " \"subjects\": [\"John Doe\", \"Jane Smith\"],\n",- " \"location\": \"Restaurant XYZ\",\n",- " \"duration_minutes\": 45,\n",- " \"notes\": \"Extended meeting between known associates\"\n",- " },\n",- " {\n",- " \"observation_id\": \"SV002\",\n",- " \"date\": \"2024-02-12\",\n",- " \"subjects\": [\"Jane Smith\", \"Bob Johnson\"],\n",- " \"location\": \"Business Office ABC\",\n",- " \"duration_minutes\": 120,\n",- " \"notes\": \"Business meeting with financial documents exchange\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Save sample data files\n",- "police_reports_file = os.path.join(temp_dir, \"police_reports.json\")\n",- "court_records_file = os.path.join(temp_dir, \"court_records.json\")\n",- "surveillance_file = os.path.join(temp_dir, \"surveillance.json\")\n",- "\n",- "with open(police_reports_file, 'w') as f:\n",- " json.dump(police_reports_data, f, indent=2)\n",- "with open(court_records_file, 'w') as f:\n",- " json.dump(court_records_data, f, indent=2)\n",- "with open(surveillance_file, 'w') as f:\n",- " json.dump(surveillance_data, f, indent=2)\n",- "\n",- "# Ingest files using Semantica\n",- "police_data = file_ingestor.ingest_file(police_reports_file, read_content=True)\n",- "court_data = file_ingestor.ingest_file(court_records_file, read_content=True)\n",- "surveillance_data_obj = file_ingestor.ingest_file(surveillance_file, read_content=True)\n",- "\n",- "# Store in agent memory\n",- "agent_memory.store(\n",- " \"Ingested police reports, court records, and surveillance data\",\n",- " metadata={\n",- " \"type\": \"data_ingestion\",\n",- " \"sources\": [\"police_reports\", \"court_records\", \"surveillance\"],\n",- " \"timestamp\": datetime.now().isoformat()\n",- " }\n",- ")\n",- "\n",- "print(f\" - Police reports: {len(police_reports_data['reports'])}\")\n",- "print(f\" - Court records: {len(court_records_data['cases'])}\")\n",- "print(f\" - Surveillance observations: {len(surveillance_data['observations'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize parsers and normalizers\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "text_normalizer = TextNormalizer()\n",- "data_normalizer = DataNormalizer()\n",- "\n",- "# Parse all data sources\n",- "parsed_police = json_parser.parse(police_reports_file)\n",- "parsed_court = json_parser.parse(court_records_file)\n",- "parsed_surveillance = json_parser.parse(surveillance_file)\n",- "\n",- "# Combine all parsed data\n",- "all_data = {\n",- " \"police_reports\": parsed_police.data if hasattr(parsed_police, 'data') else parsed_police,\n",- " \"court_records\": parsed_court.data if hasattr(parsed_court, 'data') else parsed_court,\n",- " \"surveillance\": parsed_surveillance.data if hasattr(parsed_surveillance, 'data') else parsed_surveillance\n",- "}\n",- "\n",- "print(f\" - Police reports parsed: {len(all_data['police_reports'].get('reports', [])) if isinstance(all_data['police_reports'], dict) else 0}\")\n",- "print(f\" - Court records parsed: {len(all_data['court_records'].get('cases', [])) if isinstance(all_data['court_records'], dict) else 0}\")\n",- "print(f\" - Surveillance parsed: {len(all_data['surveillance'].get('observations', [])) if isinstance(all_data['surveillance'], dict) else 0}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Extract Entities and Relationships\n",- "\n",- "Extract criminal network entities (suspects, organizations, locations, events) and relationships using Semantica's extraction modules.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize extractors\n",- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "event_detector = EventDetector()\n",- "\n",- "# Extract entities and relationships\n",- "criminal_entities = []\n",- "criminal_relationships = []\n",- "entity_id_map = {} # Map names to IDs\n",- "\n",- "# Process police reports\n",- "if isinstance(all_data['police_reports'], dict):\n",- " for report in all_data['police_reports'].get('reports', []):\n",- " # Extract suspects as entities\n",- " for suspect in report.get('suspects', []):\n",- " if suspect not in entity_id_map:\n",- " entity_id = f\"PERSON_{len(entity_id_map) + 1}\"\n",- " entity_id_map[suspect] = entity_id\n",- " criminal_entities.append({\n",- " \"id\": entity_id,\n",- " \"type\": \"Person\",\n",- " \"name\": suspect,\n",- " \"properties\": {\n",- " \"source\": \"police_report\",\n",- " \"report_id\": report.get('report_id')\n",- " }\n",- " })\n",- " \n",- " # Extract location\n",- " location = report.get('location')\n",- " if location:\n",- " loc_id = f\"LOC_{location.replace(' ', '_')}\"\n",- " if loc_id not in [e.get('id') for e in criminal_entities]:\n",- " criminal_entities.append({\n",- " \"id\": loc_id,\n",- " \"type\": \"Location\",\n",- " \"name\": location,\n",- " \"properties\": {\"source\": \"police_report\"}\n",- " })\n",- " \n",- " # Create relationships between suspects\n",- " suspects = report.get('suspects', [])\n",- " for i, suspect1 in enumerate(suspects):\n",- " for suspect2 in suspects[i+1:]:\n",- " if suspect1 in entity_id_map and suspect2 in entity_id_map:\n",- " criminal_relationships.append({\n",- " \"source\": entity_id_map[suspect1],\n",- " \"target\": entity_id_map[suspect2],\n",- " \"type\": \"associated_with\",\n",- " \"properties\": {\n",- " \"incident_type\": report.get('incident_type'),\n",- " \"date\": report.get('date'),\n",- " \"source\": \"police_report\",\n",- " \"report_id\": report.get('report_id')\n",- " }\n",- " })\n",- "\n",- "# Process court records\n",- "if isinstance(all_data['court_records'], dict):\n",- " for case in all_data['court_records'].get('cases', []):\n",- " defendant = case.get('defendant')\n",- " if defendant and defendant in entity_id_map:\n",- " # Add case information to entity\n",- " for entity in criminal_entities:\n",- " if entity.get('id') == entity_id_map[defendant]:\n",- " entity['properties']['cases'] = entity['properties'].get('cases', [])\n",- " entity['properties']['cases'].append({\n",- " \"case_id\": case.get('case_id'),\n",- " \"charges\": case.get('charges'),\n",- " \"outcome\": case.get('outcome')\n",- " })\n",- " \n",- " # Create relationships with co-defendants\n",- " for co_def in case.get('co_defendants', []):\n",- " if co_def in entity_id_map:\n",- " criminal_relationships.append({\n",- " \"source\": entity_id_map[defendant],\n",- " \"target\": entity_id_map[co_def],\n",- " \"type\": \"co_defendant\",\n",- " \"properties\": {\n",- " \"case_id\": case.get('case_id'),\n",- " \"date\": case.get('date')\n",- " }\n",- " })\n",- "\n",- "# Process surveillance data\n",- "if isinstance(all_data['surveillance'], dict):\n",- " for obs in all_data['surveillance'].get('observations', []):\n",- " subjects = obs.get('subjects', [])\n",- " for i, subject1 in enumerate(subjects):\n",- " for subject2 in subjects[i+1:]:\n",- " if subject1 in entity_id_map and subject2 in entity_id_map:\n",- " criminal_relationships.append({\n",- " \"source\": entity_id_map[subject1],\n",- " \"target\": entity_id_map[subject2],\n",- " \"type\": \"observed_with\",\n",- " \"properties\": {\n",- " \"location\": obs.get('location'),\n",- " \"date\": obs.get('date'),\n",- " \"duration_minutes\": obs.get('duration_minutes')\n",- " }\n",- " })\n",- "\n",- "print(f\" - Entities: {len(criminal_entities)}\")\n",- "print(f\" - Relationships: {len(criminal_relationships)}\")\n",- "print(f\" - Unique persons: {len([e for e in criminal_entities if e.get('type') == 'Person'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Build Criminal Network Knowledge Graph\n",- "\n",- "Build the knowledge graph from extracted entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize graph builder\n",- "graph_builder = GraphBuilder()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Build criminal network knowledge graph\n",- "criminal_kg = graph_builder.build(criminal_entities, criminal_relationships)\n",- "\n",- "# Analyze connectivity\n",- "connectivity = connectivity_analyzer.analyze_connectivity(criminal_kg)\n",- "\n",- "# Store in agent memory\n",- "agent_memory.store(\n",- " f\"Built criminal network knowledge graph with {len(criminal_entities)} entities and {len(criminal_relationships)} relationships\",\n",- " metadata={\n",- " \"type\": \"knowledge_graph\",\n",- " \"entity_count\": len(criminal_entities),\n",- " \"relationship_count\": len(criminal_relationships)\n",- " },\n",- " entities=criminal_entities,\n",- " relationships=criminal_relationships\n",- ")\n",- "\n",- "print(f\" - Entities: {len(criminal_kg.get('entities', []))}\")\n",- "print(f\" - Relationships: {len(criminal_kg.get('relationships', []))}\")\n",- "print(f\" - Connected components: {connectivity.get('num_components', 0)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Persist Criminal Network to Graph Database\n",- "\n",- "Store the criminal network knowledge graph in a persistent graph database for real-time queries.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.graph_store import GraphStore\n",- "\n",- "# Initialize graph store for persistent criminal network storage\n",- "# For production: use Neo4j for enterprise features or FalkorDB for real-time queries\n",- "\n",- "# Option 1: Neo4j\n",- "graph_store = GraphStore(backend=\"neo4j\", uri=\"bolt://localhost:7687\", user=\"neo4j\", password=\"password\")\n",- "\n",- "# Option 2: FalkorDB\n",- "# graph_store = GraphStore(backend=\"falkordb\", host=\"localhost\", port=6379, graph_name=\"criminal_network\")\n",- "\n",- "graph_store.connect()\n",- "\n",- "# Store entities as nodes\n",- "entity_node_map = {}\n",- "for entity in criminal_entities:\n",- " node = graph_store.create_node(\n",- " labels=[entity[\"type\"]],\n",- " properties={\n",- " \"original_id\": entity[\"id\"],\n",- " \"name\": entity[\"name\"],\n",- " **entity.get(\"properties\", {})\n",- " }\n",- " )\n",- " entity_node_map[entity[\"id\"]] = node.get(\"id\")\n",- "\n",- "# Store relationships\n",- "for rel in criminal_relationships:\n",- " if rel[\"source\"] in entity_node_map and rel[\"target\"] in entity_node_map:\n",- " graph_store.create_relationship(\n",- " start_node_id=entity_node_map[rel[\"source\"]],\n",- " end_node_id=entity_node_map[rel[\"target\"]],\n",- " rel_type=rel[\"type\"].upper(),\n",- " properties=rel.get(\"properties\", {})\n",- " )\n",- "\n",- "\n",- "# Query for key suspects using Cypher\n",- "suspect_query = \"\"\"\n",- " MATCH (p:Person)-[r]->(other)\n",- " WITH p, count(r) as connections\n",- " ORDER BY connections DESC\n",- " LIMIT 5\n",- " RETURN p.name as suspect, connections\n",- "\"\"\"\n",- "suspect_results = graph_store.execute_query(suspect_query)\n",- "\n",- "# Store in agent memory\n",- "agent_memory.store(\n",- " f\"Criminal network stored in graph database with {len(entity_node_map)} entities\",\n",- " metadata={\n",- " \"type\": \"graph_store\",\n",- " \"entity_count\": len(entity_node_map),\n",- " \"relationship_count\": len(criminal_relationships)\n",- " }\n",- ")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Perform Comprehensive Graph Analytics\n",- "\n",- "Perform all graph analytics including centrality measures, community detection, and connectivity analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Perform comprehensive graph analytics\n",- "# 1. Centrality measures\n",- "pagerank_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"pagerank\")\n",- "betweenness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"betweenness\")\n",- "closeness_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"closeness\")\n",- "eigenvector_centrality = graph_analyzer.compute_centrality(criminal_kg, method=\"eigenvector\")\n",- "\n",- "# 2. Community detection\n",- "communities = graph_analyzer.detect_communities(criminal_kg, method=\"louvain\")\n",- "\n",- "# 3. Graph metrics\n",- "kg_metrics = graph_analyzer.compute_metrics(criminal_kg)\n",- "\n",- "# 4. Identify key players (high centrality)\n",- "key_players_pagerank = sorted(\n",- " [(node, score) for node, score in pagerank_centrality.items()],\n",- " key=lambda x: x[1],\n",- " reverse=True\n",- ")[:5]\n",- "\n",- "key_players_betweenness = sorted(\n",- " [(node, score) for node, score in betweenness_centrality.items()],\n",- " key=lambda x: x[1],\n",- " reverse=True\n",- ")[:5]\n",- "\n",- "# Use graph store for analytics queries\n",- "centrality_query = \"\"\"\n",- " MATCH (p:Person)-[r]-()\n",- " WITH p, count(r) as degree\n",- " RETURN p.name as suspect, degree\n",- " ORDER BY degree DESC\n",- " LIMIT 5\n",- "\"\"\"\n",- "centrality_results = graph_store.execute_query(centrality_query)\n",- "\n",- "# Store analytics in agent memory\n",- "agent_memory.store(\n",- " f\"Graph analytics completed: {len(key_players_pagerank)} key players identified\",\n",- " metadata={\n",- " \"type\": \"graph_analytics\",\n",- " \"key_players_count\": len(key_players_pagerank),\n",- " \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0\n",- " }\n",- ")\n",- "\n",- "print(f\" - PageRank centrality: {len(pagerank_centrality)} entities\")\n",- "print(f\" - Betweenness centrality: {len(betweenness_centrality)} entities\")\n",- "print(f\" - Closeness centrality: {len(closeness_centrality)} entities\")\n",- "print(f\" - Eigenvector centrality: {len(eigenvector_centrality)} entities\")\n",- "print(f\" - Communities detected: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\")\n",- "print(f\"\\nTop Key Players (PageRank):\")\n",- "for entity_id, score in key_players_pagerank:\n",- " entity_name = next((e.get('name', '') for e in criminal_entities if e.get('id') == entity_id), 'Unknown')\n",- " print(f\" - {entity_name} ({entity_id}): {score:.4f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Agent-Based Analysis Workflows\n",- "\n",- "Define and execute specialized agents for criminal network analysis using Pipeline coordination.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize pipeline modules\n",- "pipeline_builder = PipelineBuilder()\n",- "execution_engine = ExecutionEngine()\n",- "parallelism_manager = ParallelismManager(max_workers=4)\n",- "\n",- "# Define specialized agents\n",- "\n",- "# Agent 1: Data Gathering Agent\n",- "def agent_data_gathering(sources, memory):\n",- " \"\"\"Autonomous agent for data gathering with memory.\"\"\"\n",- " # Retrieve relevant context from memory\n",- " context = memory.retrieve(\"criminal network data\", max_results=5)\n",- " # Simulate data gathering\n",- " gathered_data = {\n",- " \"sources_processed\": len(sources),\n",- " \"context_items\": len(context)\n",- " }\n",- " memory.store(\n",- " f\"Data gathering agent processed {len(sources)} sources\",\n",- " metadata={\"agent\": \"data_gathering\", \"sources_count\": len(sources)}\n",- " )\n",- " return gathered_data\n",- "\n",- "# Agent 2: Network Analysis Agent\n",- "def agent_network_analysis(graph, analyzer, memory):\n",- " \"\"\"Agent for network structure analysis.\"\"\"\n",- " metrics = analyzer.compute_metrics(graph)\n",- " centrality = analyzer.compute_centrality(graph, method=\"pagerank\")\n",- " communities = analyzer.detect_communities(graph, method=\"louvain\")\n",- " \n",- " memory.store(\n",- " f\"Network analysis completed: {communities.get('num_communities', 0) if isinstance(communities, dict) else 0} communities detected\",\n",- " metadata={\"agent\": \"network_analysis\", \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0}\n",- " )\n",- " return {\"metrics\": metrics, \"centrality\": centrality, \"communities\": communities}\n",- "\n",- "# Agent 3: Pattern Detection Agent\n",- "def agent_pattern_detection(graph, inference_engine, memory):\n",- " \"\"\"Agent for identifying suspicious patterns.\"\"\"\n",- " # Define pattern detection rules\n",- " pattern_rules = [\n",- " {\n",- " \"rule_id\": \"high_centrality_suspect\",\n",- " \"condition\": \"IF entity has high_pagerank AND entity has multiple_relationships THEN entity is key_player\",\n",- " \"action\": \"flag_key_player\"\n",- " },\n",- " {\n",- " \"rule_id\": \"dense_network\",\n",- " \"condition\": \"IF entities form dense_cluster AND high_communication THEN entities form_criminal_ring\",\n",- " \"action\": \"identify_criminal_ring\"\n",- " }\n",- " ]\n",- " \n",- " patterns = inference_engine.infer(knowledge_graph=graph, rules=pattern_rules)\n",- " memory.store(\n",- " f\"Pattern detection identified {len(patterns) if isinstance(patterns, list) else 1} patterns\",\n",- " metadata={\"agent\": \"pattern_detection\", \"patterns_count\": len(patterns) if isinstance(patterns, list) else 1}\n",- " )\n",- " return {\"patterns\": patterns, \"rules\": pattern_rules}\n",- "\n",- "# Agent 4: Report Generation Agent\n",- "def agent_report_generation(analysis_results, memory):\n",- " \"\"\"Agent for compiling intelligence reports.\"\"\"\n",- " # Retrieve all relevant context\n",- " context = memory.retrieve(\"criminal network\", max_results=10)\n",- " report_data = {\n",- " \"analysis_results\": analysis_results,\n",- " \"context_items\": len(context),\n",- " \"timestamp\": datetime.now().isoformat()\n",- " }\n",- " memory.store(\n",- " \"Report generation agent compiled intelligence report\",\n",- " metadata={\"agent\": \"report_generation\", \"context_items\": len(context)}\n",- " )\n",- " return report_data\n",- "\n",- "def data_gathering_handler(data, **config):\n",- " sources = data.get(\"sources\", [])\n",- " memory = data.get(\"memory\")\n",- " r = agent_data_gathering(sources, memory)\n",- " return {**data, \"gathered\": r}\n",- "def network_analysis_handler(data, **config):\n",- " graph = data.get(\"criminal_kg\")\n",- " analyzer = data.get(\"graph_analyzer\")\n",- " memory = data.get(\"memory\")\n",- " r = agent_network_analysis(graph, analyzer, memory)\n",- " return {**data, \"network_analysis\": r}\n",- "def pattern_detection_handler(data, **config):\n",- " graph = data.get(\"criminal_kg\")\n",- " inf = data.get(\"inference_engine\")\n",- " memory = data.get(\"memory\")\n",- " r = agent_pattern_detection(graph, inf, memory)\n",- " return {**data, \"patterns\": r}\n",- "def report_generation_handler(data, **config):\n",- " memory = data.get(\"memory\")\n",- " analysis_results = {\n",- " \"network\": data.get(\"network_analysis\"),\n",- " \"patterns\": data.get(\"patterns\")\n",- " }\n",- " r = agent_report_generation(analysis_results, memory)\n",- " return {**data, \"report\": r}\n",- "criminal_network_pipeline = (\n",- " pipeline_builder\n",- " .add_step(\"data_gathering\", \"ingest\", handler=data_gathering_handler)\n",- " .add_step(\"network_analysis\", \"analyze_graph\", dependencies=[\"data_gathering\"], handler=network_analysis_handler)\n",- " .add_step(\"pattern_detection\", \"analysis\", dependencies=[\"network_analysis\"], handler=pattern_detection_handler)\n",- " .add_step(\"report_generation\", \"report\", dependencies=[\"pattern_detection\"], handler=report_generation_handler)\n",- ")\n",- ".build()\n",- "input_data = {\"sources\": [police_reports_file, court_records_file, surveillance_file], \"criminal_kg\": criminal_kg, \"graph_analyzer\": graph_analyzer, \"inference_engine\": inference_engine, \"memory\": agent_memory}\n",- "pipeline_result = execution_engine.execute_pipeline(criminal_network_pipeline, data=input_data, parallel=True)\n",- "\n",- "print(f\" - Pipeline steps: {len(criminal_network_pipeline.steps)}\")\n",- "print(f\" - Parallel execution: Enabled\")\n",- "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize visualizers\n",- "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "# Visualize criminal network\n",- "network_fig = kg_visualizer.visualize_network(\n",- " criminal_kg,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize communities\n",- "communities_fig = kg_visualizer.visualize_communities(\n",- " criminal_kg,\n",- " communities,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize centrality rankings\n",- "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",- " pagerank_centrality,\n",- " centrality_type=\"pagerank\",\n",- " top_n=10,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize centrality comparison\n",- "centrality_comparison = {\n",- " \"pagerank\": pagerank_centrality,\n",- " \"betweenness\": betweenness_centrality,\n",- " \"closeness\": closeness_centrality\n",- "}\n",- "comparison_fig = analytics_visualizer.visualize_centrality_comparison(\n",- " centrality_comparison,\n",- " top_n=10,\n",- " output=\"interactive\"\n",- ")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 11: Generate Intelligence Report\n",- "\n",- "Generate a comprehensive intelligence report on the criminal network structure.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize report generator\n",- "report_generator = ReportGenerator()\n",- "json_exporter = JSONExporter()\n",- "\n",- "# Prepare intelligence report data\n",- "intelligence_report_data = {\n",- " \"title\": \"Criminal Network Analysis Intelligence Report\",\n",- " \"executive_summary\": \"Analysis of criminal network structure, key players, communities, and patterns\",\n",- " \"knowledge_graph_metrics\": kg_metrics,\n",- " \"communities\": communities,\n",- " \"key_players\": {\n",- " \"pagerank\": key_players_pagerank,\n",- " \"betweenness\": key_players_betweenness\n",- " },\n",- " \"centrality_measures\": {\n",- " \"pagerank\": pagerank_centrality,\n",- " \"betweenness\": betweenness_centrality,\n",- " \"closeness\": closeness_centrality,\n",- " \"eigenvector\": eigenvector_centrality\n",- " },\n",- " \"network_structure\": {\n",- " \"entities\": len(criminal_entities),\n",- " \"relationships\": len(criminal_relationships),\n",- " \"density\": kg_metrics.get('density', 0) if isinstance(kg_metrics, dict) else 0,\n",- " \"components\": connectivity.get('num_components', 0)\n",- " },\n",- " \"agent_memory_stats\": agent_memory.get_statistics(),\n",- " \"graphrag_capabilities\": {\n",- " \"embeddings_count\": len(entity_embeddings),\n",- " \"hybrid_search\": True\n",- " }\n",- "}\n",- "\n",- "# Generate professional HTML report\n",- "intelligence_report_file = os.path.join(temp_dir, \"criminal_network_intelligence_report.html\")\n",- "report_generator.generate_report(\n",- " intelligence_report_data,\n",- " intelligence_report_file,\n",- " format=\"html\"\n",- ")\n",- "\n",- "# Export network data as JSON\n",- "network_json_file = os.path.join(temp_dir, \"criminal_network_data.json\")\n",- "json_exporter.export(criminal_kg, network_json_file)\n",- "\n",- "print(f\" - Intelligence report HTML: {intelligence_report_file}\")\n",- "print(f\" - Network data JSON: {network_json_file}\")\n",- "print(f\" - Report includes: Executive summary, metrics, key players, communities, agent memory stats\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion and Best Practices\n",- "\n",- "### Key Takeaways\n",- "\n",- "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for criminal network analysis\n",- "2. **Agent-Based Workflows**: Semantica's Pipeline module enables parallel agent coordination with persistent memory\n",- "3. **MCP Integration**: MCP can be used for accessing external databases and APIs for real-time data\n",- "4. **Graph Analytics**: Semantica's GraphAnalyzer provides comprehensive algorithms (PageRank, Betweenness, Closeness, Eigenvector, Louvain)\n",- "5. **Hybrid RAG**: Semantica's HybridSearch combines knowledge graph queries with vector similarity search\n",- "6. **Agent Memory**: Semantica's AgentMemory provides persistent context across agent interactions\n",- "7. **Professional Reports**: Semantica's ReportGenerator creates professional HTML intelligence reports\n",- "\n",- "### Semantica-Specific Performance Considerations\n",- "\n",- "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient community detection and centrality calculations on large networks\n",- "- **Parallel Execution**: Leverage Semantica's ParallelismManager for concurrent agent execution\n",- "- **Vector Search**: Use Semantica's HybridSearch for efficient entity similarity search combined with graph queries\n",- "- **Agent Memory**: Utilize Semantica's AgentMemory for persistent context across agent workflows\n",- "\n",- "### Deployment Recommendations Using Semantica\n",- "\n",- "1. **Production Setup**:\n",- " - Use Semantica's configuration management for data source settings\n",- " - Leverage Semantica's Pipeline module for automated intelligence workflows\n",- " - Use Semantica's export modules for report persistence\n",- "\n",- "2. **Scalability**:\n",- " - Use Semantica's batch processing for large-scale network data\n",- " - Leverage Semantica's graph analytics optimizations\n",- " - Utilize Semantica's parallel execution for concurrent analysis\n",- "\n",- "3. **Quality Assurance**:\n",- " - Use Semantica's Deduplication modules for entity resolution\n",- " - Leverage Semantica's ExplanationGenerator for report traceability\n",- " - Utilize Semantica's quality modules for data validation\n",- "\n",- "### How Semantica's Architecture Benefits Criminal Network Analysis\n",- "\n",- "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms in one framework\n",- "- **Unified Pipeline**: Semantica's Pipeline module orchestrates complex multi-agent workflows\n",- "- **Agent Memory**: Semantica's AgentMemory enables persistent context for intelligent agents\n",- "- **Hybrid RAG**: Semantica's HybridSearch combines graph and vector search for comprehensive intelligence queries\n",- "- **Extensibility**: Semantica's registry system enables custom analysis methods\n",- "- **Integration**: Semantica's unified framework simplifies integration with existing systems\n",- "- **Performance**: Semantica's optimized algorithms handle large-scale network analysis efficiently\n",- "- **Explainability**: Semantica's ExplanationGenerator provides traceable intelligence reports\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb b/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynbdeleted file mode 100644index 4671c66b..00000000--- a/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb+++ /dev/null@@ -1,772 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/02_Intelligence_Analysis.ipynb)\n",- "\n",- "# Intelligence Analysis with Orchestrator-Worker Pattern\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates comprehensive intelligence analysis using **Semantica's Orchestrator-Worker Pattern** with complete implementation of graph analytics, hybrid RAG, and ontology building. The pipeline processes OSINT feeds, threat intelligence, and geospatial data to build multi-source intelligence graphs with detailed analysis.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Orchestrator-Worker Architecture\n",- "\n",- "The Orchestrator-Worker pattern uses **ExecutionEngine** as the orchestrator to coordinate **7 specialized workers** in parallel:\n",- "\n",- "- **Orchestrator**: ExecutionEngine coordinates all workers using PipelineBuilder and ParallelismManager\n",- "- **Worker 1 - Data Ingestion Worker**: Multi-source data ingestion (FileIngestor, WebIngestor, StreamIngestor, FeedIngestor, DBIngestor)\n",- "- **Worker 2 - Ontology Building Worker**: Complete 6-stage ontology generation pipeline\n",- "- **Worker 3 - Graph Construction Worker**: Builds knowledge graphs (GraphBuilder, TemporalGraphQuery)\n",- "- **Worker 4 - Graph Analytics Worker**: Comprehensive graph analytics (all centrality measures, community detection, connectivity)\n",- "- **Worker 5 - Hybrid RAG Worker**: Complete hybrid RAG with KG queries + vector search\n",- "- **Worker 6 - Intelligence Analysis Worker**: Threat assessment, geospatial analysis, pattern detection\n",- "- **Worker 7 - Report Generation Worker**: Compiles comprehensive intelligence reports\n",- "\n",- "### Why Semantica?\n",- "\n",- "Semantica provides a complete framework for intelligence analysis:\n",- "\n",- "- **Orchestrator-Worker Pattern**: Efficient parallel processing with coordinated workers\n",- "- **Complete Ontology Building**: 6-stage automatic ontology generation from data\n",- "- **Comprehensive Graph Analytics**: All centrality measures, community detection, connectivity analysis\n",- "- **Hybrid RAG**: Complete implementation combining KG queries with vector similarity search\n",- "- **MCP Integration**: Real-time data fetching, web scraping, API integration, browser automation\n",- "- **Agent Memory**: Persistent memory for threat context and intelligence history\n",- "- **Multi-Source Fusion**: Correlate intelligence from multiple sources\n",- "\n",- "### Key Features\n",- "\n",- "- **Orchestrator-Worker Pattern**: 7 specialized workers coordinated by ExecutionEngine\n",- "- **Complete Ontology Pipeline**: 6-stage ontology generation (semantic network parsing \u2192 YAML-to-definition \u2192 definition-to-types \u2192 hierarchy generation \u2192 TTL generation \u2192 symbolic validation)\n",- "- **All Graph Analytics**: PageRank, Betweenness, Closeness, Eigenvector centrality, Louvain community detection, connectivity analysis, path finding\n",- "- **Hybrid RAG**: Vector store + knowledge graph queries + hybrid search + query orchestration\n",- "- **Multi-Source Intelligence**: OSINT, threat intelligence, social media, news, public records, geospatial data\n",- "- **MCP Integration**: Browser automation, web scraping, API integration\n",- "- **Threat Assessment**: Risk scoring, entity relationship mapping, pattern detection\n",- "- **Geospatial Intelligence**: Location-based tracking, movement pattern analysis\n",- "\n",- "### Semantica Modules Used (30+)\n",- "\n",- "- **Orchestrator**: ExecutionEngine, PipelineBuilder, ParallelismManager\n",- "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **MCP Integration**: MCP browser tools and resources\n",- "- **Parse**: JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",- "- **Normalize**: TextNormalizer, DataNormalizer\n",- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Graph Analytics**: All centrality measures, Louvain, connectivity, path finding\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",- "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: ReportGenerator, JSONExporter\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline Overview\n",- "\n",- "**OSINT Sources \u2192 MCP Integration \u2192 Orchestrator Setup \u2192 Parallel Workers (Data Ingestion \u2192 Ontology Building \u2192 Graph Construction \u2192 Graph Analytics \u2192 Hybrid RAG \u2192 Intelligence Analysis \u2192 Report Generation) \u2192 Visualization \u2192 Reporting**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Setup and Import Semantica Modules\n",- "\n",- "Import all necessary Semantica modules including orchestrator, workers, ontology, graph analytics, and hybrid RAG modules.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import all Semantica modules for intelligence analysis with Orchestrator-Worker pattern\n",- "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, XMLParser, CSVParser, DocumentParser, StructuredDataParser\n",- "from semantica.normalize import TextNormalizer, DataNormalizer\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OWLGenerator\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",- "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import ReportGenerator, JSONExporter\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "import numpy as np\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Initialize Orchestrator and Setup\n",- "\n",- "Initialize the orchestrator (ExecutionEngine) and prepare for worker coordination.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize orchestrator\n",- "orchestrator = ExecutionEngine()\n",- "pipeline_builder = PipelineBuilder()\n",- "parallelism_manager = ParallelismManager(max_workers=7)\n",- "\n",- "# Initialize vector store and agent memory\n",- "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",- "agent_memory = AgentMemory(\n",- " vector_store=vector_store,\n",- " retention_policy=\"unlimited\",\n",- " max_memory_size=10000\n",- ")\n",- "\n",- "# Create temporary directory for data\n",- "temp_dir = tempfile.mkdtemp()\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Define Worker 1 - Data Ingestion Worker\n",- "\n",- "Worker for multi-source data ingestion from OSINT feeds, threat intelligence, and geospatial data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 1: Data Ingestion Worker\n",- "def data_ingestion_worker(sources, memory):\n",- " \"\"\"Multi-source data ingestion worker.\"\"\"\n",- " file_ingestor = FileIngestor()\n",- " web_ingestor = WebIngestor()\n",- " feed_ingestor = FeedIngestor()\n",- " \n",- " ingested_data = []\n",- " \n",- " # Sample OSINT and threat intelligence data\n",- " osint_data = {\n",- " \"threat_actors\": [\n",- " {\"name\": \"Threat Actor A\", \"type\": \"APT\", \"location\": \"Country X\"},\n",- " {\"name\": \"Threat Actor B\", \"type\": \"Cybercriminal\", \"location\": \"Country Y\"}\n",- " ],\n",- " \"indicators\": [\n",- " {\"type\": \"IP\", \"value\": \"192.168.1.100\", \"threat_level\": \"high\"},\n",- " {\"type\": \"Domain\", \"value\": \"malicious.com\", \"threat_level\": \"medium\"}\n",- " ]\n",- " }\n",- " \n",- " # Save sample data\n",- " osint_file = os.path.join(temp_dir, \"osint_data.json\")\n",- " with open(osint_file, 'w') as f:\n",- " json.dump(osint_data, f, indent=2)\n",- " \n",- " ingested_data.append(file_ingestor.ingest_file(osint_file, read_content=True))\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Data ingestion worker processed {len(ingested_data)} sources\",\n",- " metadata={\"worker\": \"data_ingestion\", \"sources_count\": len(ingested_data)}\n",- " )\n",- " \n",- " return {\"ingested_data\": ingested_data, \"osint_data\": osint_data}\n",- "\n",- "# Test worker\n",- "osint_data_result = data_ingestion_worker([], agent_memory)\n",- "print(f\" - Sources processed: {len(osint_data_result.get('ingested_data', []))}\")\n",- "print(f\" - OSINT data ingested: {len(osint_data_result.get('osint_data', {}).get('threat_actors', []))} threat actors\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Define Worker 2 - Ontology Building Worker\n",- "\n",- "Worker for complete 6-stage ontology generation pipeline.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 2: Ontology Building Worker\n",- "def ontology_building_worker(entities, relationships, memory):\n",- " \"\"\"Complete 6-stage ontology generation worker.\"\"\"\n",- " ontology_gen = OntologyGenerator(base_uri=\"https://example.org/intelligence/ontology/\")\n",- " class_inferrer = ClassInferrer()\n",- " property_generator = PropertyGenerator()\n",- " owl_generator = OWLGenerator()\n",- " \n",- " # Stage 1-6: Complete ontology generation pipeline\n",- " ontology = ontology_gen.generate_ontology({\n",- " \"entities\": entities,\n",- " \"relationships\": relationships\n",- " })\n",- " \n",- " # Generate OWL/Turtle\n",- " owl_content = owl_generator.generate_owl(ontology, format=\"turtle\")\n",- " \n",- " # Validate ontology\n",- " validation_result = {\"is_valid\": True}\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Ontology building worker generated ontology with {len(ontology.get('classes', [])) if isinstance(ontology, dict) else 0} classes\",\n",- " metadata={\n",- " \"worker\": \"ontology_building\",\n",- " \"classes_count\": len(ontology.get('classes', [])) if isinstance(ontology, dict) else 0,\n",- " \"validation_passed\": validation_result.get('is_valid', False) if isinstance(validation_result, dict) else False\n",- " }\n",- " )\n",- " \n",- " return {\n",- " \"ontology\": ontology,\n",- " \"owl_content\": owl_content,\n",- " \"validation\": validation_result\n",- " }\n",- "\n",- "# Prepare sample entities and relationships for ontology\n",- "sample_entities = [\n",- " {\"id\": \"E1\", \"type\": \"ThreatActor\", \"name\": \"Threat Actor A\"},\n",- " {\"id\": \"E2\", \"type\": \"Indicator\", \"name\": \"Malicious IP\"},\n",- " {\"id\": \"E3\", \"type\": \"Location\", \"name\": \"Country X\"}\n",- "]\n",- "sample_relationships = [\n",- " {\"source\": \"E1\", \"target\": \"E2\", \"type\": \"uses\"},\n",- " {\"source\": \"E1\", \"target\": \"E3\", \"type\": \"located_in\"}\n",- "]\n",- "\n",- "ontology_result = ontology_building_worker(sample_entities, sample_relationships, agent_memory)\n",- "print(f\" - Ontology generated: {bool(ontology_result.get('ontology'))}\")\n",- "print(f\" - OWL content generated: {len(ontology_result.get('owl_content', ''))} characters\")\n",- "print(f\" - Validation passed: {ontology_result.get('validation', {}).get('is_valid', False) if isinstance(ontology_result.get('validation'), dict) else False}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Define Worker 3 - Graph Construction Worker\n",- "\n",- "Worker for building knowledge graphs from entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 3: Graph Construction Worker\n",- "def graph_construction_worker(entities, relationships, memory):\n",- " \"\"\"Build knowledge graph worker.\"\"\"\n",- " graph_builder = GraphBuilder()\n",- " temporal_query = TemporalGraphQuery()\n",- " \n",- " # Build knowledge graph\n",- " kg = graph_builder.build(entities, relationships)\n",- " \n",- " # Build temporal graph query capability\n",- " temporal_kg = temporal_query.build_temporal_graph(kg)\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Graph construction worker built KG with {len(entities)} entities and {len(relationships)} relationships\",\n",- " metadata={\n",- " \"worker\": \"graph_construction\",\n",- " \"entity_count\": len(entities),\n",- " \"relationship_count\": len(relationships)\n",- " },\n",- " entities=entities,\n",- " relationships=relationships\n",- " )\n",- " \n",- " return {\"knowledge_graph\": kg, \"temporal_graph\": temporal_kg}\n",- "\n",- "# Test worker with sample data\n",- "graph_result = graph_construction_worker(sample_entities, sample_relationships, agent_memory)\n",- "print(f\" - Knowledge graph built: {bool(graph_result.get('knowledge_graph'))}\")\n",- "print(f\" - Temporal graph built: {bool(graph_result.get('temporal_graph'))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Define Worker 4 - Graph Analytics Worker\n",- "\n",- "Worker for comprehensive graph analytics including all centrality measures, community detection, and connectivity analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 4: Graph Analytics Worker\n",- "def graph_analytics_worker(kg, memory):\n",- " \"\"\"Comprehensive graph analytics worker.\"\"\"\n",- " graph_analyzer = GraphAnalyzer()\n",- " connectivity_analyzer = ConnectivityAnalyzer()\n",- " \n",- " # All centrality measures\n",- " pagerank = graph_analyzer.compute_centrality(kg, method=\"pagerank\")\n",- " betweenness = graph_analyzer.compute_centrality(kg, method=\"betweenness\")\n",- " closeness = graph_analyzer.compute_centrality(kg, method=\"closeness\")\n",- " eigenvector = graph_analyzer.compute_centrality(kg, method=\"eigenvector\")\n",- " \n",- " # Community detection\n",- " communities = graph_analyzer.detect_communities(kg, method=\"louvain\")\n",- " \n",- " # Connectivity analysis\n",- " connectivity = connectivity_analyzer.analyze_connectivity(kg)\n",- " \n",- " # Graph metrics\n",- " metrics = graph_analyzer.compute_metrics(kg)\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Graph analytics worker completed: {len(pagerank)} entities analyzed\",\n",- " metadata={\n",- " \"worker\": \"graph_analytics\",\n",- " \"centrality_measures\": 4,\n",- " \"communities\": communities.get('num_communities', 0) if isinstance(communities, dict) else 0\n",- " }\n",- " )\n",- " \n",- " return {\n",- " \"pagerank\": pagerank,\n",- " \"betweenness\": betweenness,\n",- " \"closeness\": closeness,\n",- " \"eigenvector\": eigenvector,\n",- " \"communities\": communities,\n",- " \"connectivity\": connectivity,\n",- " \"metrics\": metrics\n",- " }\n",- "\n",- "# Test worker\n",- "analytics_result = graph_analytics_worker(graph_result.get('knowledge_graph'), agent_memory)\n",- "print(f\" - PageRank computed: {len(analytics_result.get('pagerank', {}))}\")\n",- "print(f\" - Betweenness computed: {len(analytics_result.get('betweenness', {}))}\")\n",- "print(f\" - Closeness computed: {len(analytics_result.get('closeness', {}))}\")\n",- "print(f\" - Eigenvector computed: {len(analytics_result.get('eigenvector', {}))}\")\n",- "print(f\" - Communities detected: {analytics_result.get('communities', {}).get('num_communities', 0) if isinstance(analytics_result.get('communities'), dict) else 0}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Define Worker 5 - Hybrid RAG Worker\n",- "\n",- "Worker for complete hybrid RAG implementation with vector store, KG queries, and hybrid search.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 5: Hybrid RAG Worker\n",- "def hybrid_rag_worker(kg, vector_store, entities, memory):\n",- " \"\"\"Complete hybrid RAG worker.\"\"\"\n",- " embedding_generator = EmbeddingGenerator()\n",- " text_embedder = TextEmbedder()\n",- " hybrid_search = HybridSearch(vector_store=vector_store, knowledge_graph=kg)\n",- " context_retriever = ContextRetriever()\n",- " \n",- " # Generate embeddings for entities\n",- " entity_embeddings = {}\n",- " for entity in entities:\n",- " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",- " embedding = text_embedder.embed(entity_text)\n",- " entity_embeddings[entity.get('id', '')] = embedding\n",- " \n",- " # Store embeddings in vector store\n",- " entity_metadata = [\n",- " {\"entity_id\": eid, \"name\": next((e.get('name', '') for e in entities if e.get('id') == eid), '')}\n",- " for eid in entity_embeddings.keys()\n",- " ]\n",- " vector_store.store_vectors(\n",- " vectors=list(entity_embeddings.values()),\n",- " metadata=entity_metadata\n",- " )\n",- " \n",- " # Example hybrid search query\n",- " query = \"What are the key threat actors?\"\n",- " hybrid_results = hybrid_search.search(\n",- " query=query,\n",- " top_k=5,\n",- " use_graph=True,\n",- " use_vectors=True\n",- " )\n",- " \n",- " # Context retrieval\n",- " context = context_retriever.retrieve(\n",- " query=query,\n",- " knowledge_graph=kg,\n",- " top_k=10\n",- " )\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Hybrid RAG worker setup: {len(entity_embeddings)} embeddings, hybrid search ready\",\n",- " metadata={\n",- " \"worker\": \"hybrid_rag\",\n",- " \"embeddings_count\": len(entity_embeddings),\n",- " \"hybrid_search\": True\n",- " }\n",- " )\n",- " \n",- " return {\n",- " \"embeddings\": entity_embeddings,\n",- " \"hybrid_search\": hybrid_search,\n",- " \"query_results\": hybrid_results,\n",- " \"context\": context\n",- " }\n",- "\n",- "# Test worker\n",- "rag_result = hybrid_rag_worker(\n",- " graph_result.get('knowledge_graph'),\n",- " vector_store,\n",- " sample_entities,\n",- " agent_memory\n",- ")\n",- "print(f\" - Entity embeddings: {len(rag_result.get('embeddings', {}))}\")\n",- "print(f\" - Hybrid search ready: {bool(rag_result.get('hybrid_search'))}\")\n",- "print(f\" - Query results: {len(rag_result.get('query_results', [])) if isinstance(rag_result.get('query_results'), list) else 1}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Define Worker 6 - Intelligence Analysis Worker\n",- "\n",- "Worker for threat assessment, geospatial analysis, and pattern detection.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 6: Intelligence Analysis Worker\n",- "def intelligence_analysis_worker(kg, analytics_results, memory):\n",- " \"\"\"Threat assessment and geospatial analysis worker.\"\"\"\n",- "# # inference_engine = InferenceEngine()\n",- " rule_manager = RuleManager()\n",- " \n",- " # Threat assessment rules\n",- " threat_rules = [\n",- " {\n",- " \"rule_id\": \"high_centrality_threat\",\n",- " \"condition\": \"IF entity has high_pagerank AND entity is threat_actor THEN entity is high_priority_threat\",\n",- " \"action\": \"flag_high_priority\"\n",- " },\n",- " {\n",- " \"rule_id\": \"geospatial_cluster\",\n",- " \"condition\": \"IF entities in same_location AND high_connectivity THEN entities form_geospatial_cluster\",\n",- " \"action\": \"identify_cluster\"\n",- " }\n",- " ]\n",- " \n",- " # Pattern detection\n",- " patterns = inference_engine.infer(knowledge_graph=kg, rules=threat_rules)\n",- " \n",- " # Threat scoring based on centrality\n",- " threat_scores = {}\n",- " pagerank = analytics_results.get('pagerank', {})\n",- " for entity_id, score in pagerank.items():\n",- " threat_scores[entity_id] = score * 100 # Scale to 0-100\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " f\"Intelligence analysis worker: {len(patterns) if isinstance(patterns, list) else 1} patterns detected\",\n",- " metadata={\n",- " \"worker\": \"intelligence_analysis\",\n",- " \"patterns_count\": len(patterns) if isinstance(patterns, list) else 1,\n",- " \"threat_scores\": len(threat_scores)\n",- " }\n",- " )\n",- " \n",- " return {\n",- " \"patterns\": patterns,\n",- " \"threat_scores\": threat_scores,\n",- " \"rules\": threat_rules\n",- " }\n",- "\n",- "# Test worker\n",- "intelligence_result = intelligence_analysis_worker(\n",- " graph_result.get('knowledge_graph'),\n",- " analytics_result,\n",- " agent_memory\n",- ")\n",- "print(f\" - Patterns detected: {len(intelligence_result.get('patterns', [])) if isinstance(intelligence_result.get('patterns'), list) else 1}\")\n",- "print(f\" - Threat scores computed: {len(intelligence_result.get('threat_scores', {}))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Define Worker 7 - Report Generation Worker\n",- "\n",- "Worker for compiling comprehensive intelligence reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Worker 7: Report Generation Worker\n",- "def report_generation_worker(all_results, memory):\n",- " \"\"\"Compile comprehensive intelligence report worker.\"\"\"\n",- " report_generator = ReportGenerator()\n",- " \n",- " # Retrieve all context from memory\n",- " context = memory.retrieve(\"intelligence analysis\", max_results=20)\n",- " \n",- " # Compile report data\n",- " report_data = {\n",- " \"title\": \"Intelligence Analysis Report\",\n",- " \"executive_summary\": \"Comprehensive intelligence analysis using Orchestrator-Worker pattern\",\n",- " \"ontology\": all_results.get('ontology', {}),\n",- " \"knowledge_graph\": {\n",- " \"entities\": len(all_results.get('graph', {}).get('knowledge_graph', {}).get('entities', [])),\n",- " \"relationships\": len(all_results.get('graph', {}).get('knowledge_graph', {}).get('relationships', []))\n",- " },\n",- " \"graph_analytics\": all_results.get('analytics', {}),\n",- " \"hybrid_rag\": {\n",- " \"embeddings_count\": len(all_results.get('rag', {}).get('embeddings', {}))\n",- " },\n",- " \"intelligence_analysis\": all_results.get('intelligence', {}),\n",- " \"agent_memory_stats\": memory.get_statistics(),\n",- " \"context_items\": len(context)\n",- " }\n",- " \n",- " # Store in memory\n",- " memory.store(\n",- " \"Report generation worker compiled comprehensive intelligence report\",\n",- " metadata={\"worker\": \"report_generation\", \"context_items\": len(context)}\n",- " )\n",- " \n",- " return {\"report_data\": report_data, \"context\": context}\n",- "\n",- "# Prepare all results for report generation\n",- "all_worker_results = {\n",- " \"ontology\": ontology_result,\n",- " \"graph\": graph_result,\n",- " \"analytics\": analytics_result,\n",- " \"rag\": rag_result,\n",- " \"intelligence\": intelligence_result\n",- "}\n",- "\n",- "report_result = report_generation_worker(all_worker_results, agent_memory)\n",- "print(f\" - Report data compiled: {bool(report_result.get('report_data'))}\")\n",- "print(f\" - Context items: {len(report_result.get('context', []))}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 10: Orchestrator Coordination - Execute All Workers in Parallel\n",- "\n",- "Use the orchestrator to coordinate all 7 workers in parallel using PipelineBuilder.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "def data_ingestion_handler(data, **config):\n",- " sources = data.get(\"sources\", [])\n",- " memory = data.get(\"memory\")\n",- " r = data_ingestion_worker(sources, memory)\n",- " return {**data, \"osint\": r}\n",- "def ontology_handler(data, **config):\n",- " entities = data.get(\"entities\", [])\n",- " relationships = data.get(\"relationships\", [])\n",- " memory = data.get(\"memory\")\n",- " r = ontology_building_worker(entities, relationships, memory)\n",- " return {**data, \"ontology_result\": r}\n",- "def graph_handler(data, **config):\n",- " entities = data.get(\"entities\", [])\n",- " relationships = data.get(\"relationships\", [])\n",- " memory = data.get(\"memory\")\n",- " r = graph_construction_worker(entities, relationships, memory)\n",- " return {**data, \"graph_result\": r}\n",- "def analytics_handler(data, **config):\n",- " kg = data.get(\"graph_result\", {}).get(\"knowledge_graph\")\n",- " memory = data.get(\"memory\")\n",- " r = graph_analytics_worker(kg, memory)\n",- " return {**data, \"analytics_result\": r}\n",- "def rag_handler(data, **config):\n",- " kg = data.get(\"graph_result\", {}).get(\"knowledge_graph\")\n",- " vector_store = data.get(\"vector_store\")\n",- " entities = data.get(\"entities\", [])\n",- " memory = data.get(\"memory\")\n",- " r = hybrid_rag_worker(kg, vector_store, entities, memory)\n",- " return {**data, \"rag_result\": r}\n",- "def intel_handler(data, **config):\n",- " kg = data.get(\"graph_result\", {}).get(\"knowledge_graph\")\n",- " analytics_results = data.get(\"analytics_result\")\n",- " memory = data.get(\"memory\")\n",- " r = intelligence_analysis_worker(kg, analytics_results, memory)\n",- " return {**data, \"intelligence_result\": r}\n",- "def report_handler(data, **config):\n",- " memory = data.get(\"memory\")\n",- " all_results = {\"ontology\": data.get(\"ontology_result\"), \"graph\": data.get(\"graph_result\"), \"analytics\": data.get(\"analytics_result\"), \"rag\": data.get(\"rag_result\"), \"intelligence\": data.get(\"intelligence_result\")}\n",- " r = report_generation_worker(all_results, memory)\n",- " return {**data, \"report_result\": r}\n",- "intelligence_pipeline = (\n",- " pipeline_builder\n",- " .add_step(\"data_ingestion\", \"ingest\", handler=data_ingestion_handler)\n",- " .add_step(\"ontology_building\", \"ontology\", dependencies=[\"data_ingestion\"], handler=ontology_handler)\n",- " .add_step(\"graph_construction\", \"build_graph\", dependencies=[\"ontology_building\"], handler=graph_handler)\n",- " .add_step(\"graph_analytics\", \"analyze_graph\", dependencies=[\"graph_construction\"], handler=analytics_handler)\n",- " .add_step(\"hybrid_rag\", \"rag\", dependencies=[\"graph_construction\"], handler=rag_handler)\n",- " .add_step(\"intelligence_analysis\", \"analysis\", dependencies=[\"graph_analytics\", \"hybrid_rag\"], handler=intel_handler)\n",- " .add_step(\"report_generation\", \"report\", dependencies=[\"intelligence_analysis\"], handler=report_handler)\n",- ")\n",- ".build()\n",- "\n",- "input_data = {\"sources\": [], \"entities\": sample_entities, \"relationships\": sample_relationships, \"vector_store\": vector_store, \"memory\": agent_memory}\n",- "pipeline_result = orchestrator.execute_pipeline(intelligence_pipeline, data=input_data, parallel=True, max_workers=7)\n",- "\n",- "print(f\" - Pipeline steps: {len(intelligence_pipeline.steps)}\")\n",- "print(f\" - Execution status: {getattr(pipeline_result, 'success', True)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 11: Generate Final Intelligence Report\n",- "\n",- "Generate comprehensive intelligence report with all analysis results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Generate final intelligence report\n",- "report_generator = ReportGenerator()\n",- "intelligence_report_file = os.path.join(temp_dir, \"intelligence_analysis_report.html\")\n",- "\n",- "report_generator.generate_report(\n",- " report_result.get('report_data'),\n",- " intelligence_report_file,\n",- " format=\"html\"\n",- ")\n",- "\n",- "print(f\" - Report file: {intelligence_report_file}\")\n",- "print(f\" - Report includes: Ontology, KG, Graph Analytics, Hybrid RAG, Intelligence Analysis, Agent Memory Stats\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion and Best Practices\n",- "\n",- "### Key Takeaways\n",- "\n",- "1. **Orchestrator-Worker Pattern**: Semantica's ExecutionEngine efficiently coordinates 7 specialized workers in parallel\n",- "2. **Complete Ontology Building**: 6-stage ontology generation pipeline automatically creates domain ontologies\n",- "3. **Comprehensive Graph Analytics**: All centrality measures, community detection, and connectivity analysis in one framework\n",- "4. **Hybrid RAG**: Complete implementation combining knowledge graph queries with vector similarity search\n",- "5. **Agent Memory**: Persistent context across all worker interactions\n",- "6. **MCP Integration**: External data access and browser automation for OSINT gathering\n",- "7. **Scalable Architecture**: Parallel execution enables efficient processing of large-scale intelligence data\n",- "\n",- "### Orchestrator-Worker Pattern Benefits\n",- "\n",- "- **Efficiency**: Parallel execution of workers reduces total processing time\n",- "- **Modularity**: Each worker has a specific responsibility\n",- "- **Scalability**: Easy to add or modify workers\n",- "- **Coordination**: Orchestrator manages dependencies and execution order\n",- "- **Error Handling**: Centralized error handling and recovery\n",- "\n",- "### Semantica-Specific Performance Considerations\n",- "\n",- "- **Parallel Execution**: Leverage ParallelismManager for concurrent worker execution\n",- "- **Graph Analytics**: Use GraphAnalyzer for efficient analysis on large networks\n",- "- **Hybrid RAG**: Combine KG and vector search for comprehensive intelligence queries\n",- "- **Agent Memory**: Utilize persistent memory for context across workers\n",- "\n",- "### Deployment Recommendations\n",- "\n",- "1. **Production Setup**: Use Semantica's configuration management and pipeline orchestration\n",- "2. **Scalability**: Leverage parallel execution for large-scale intelligence processing\n",- "3. **Quality Assurance**: Use Semantica's validation and quality modules\n",- "4. **Integration**: Semantica's unified framework simplifies integration with existing systems\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb b/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynbdeleted file mode 100644index 604eaf00..00000000--- a/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb+++ /dev/null@@ -1,539 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/intelligence/03_Law_Enforcement_Forensics.ipynb)\n",- "\n",- "# Law Enforcement and Forensics Analysis with Semantica\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete forensic analysis pipeline using **Semantica as the core framework** with agent-based workflows for processing case files, evidence logs, witness statements, and forensic reports. The pipeline builds temporal knowledge graphs, correlates evidence across cases, and generates comprehensive forensic analysis reports.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Why Semantica?\n",- "\n",- "Semantica provides a complete framework for forensic analysis:\n",- "\n",- "- **Multi-Source Evidence Processing**: Process case files, evidence logs, witness statements, forensic reports, and crime scene data\n",- "- **Agent-Based Workflows**: Autonomous agents with persistent memory for coordinated evidence analysis\n",- "- **Temporal Knowledge Graphs**: Build time-aware knowledge graphs for case timelines and evidence correlation\n",- "- **Cross-Case Correlation**: Identify connections and patterns across multiple cases\n",- "- **Graph Analytics**: Analyze evidence networks and case relationships\n",- "- **GraphRAG**: Semantic search across case files with context-aware evidence retrieval\n",- "- **Forensic Reporting**: Generate comprehensive forensic analysis reports with evidence chains\n",- "\n",- "### Key Features\n",- "\n",- "- Process forensic evidence from multiple sources\n",- "- Extract entities (persons, locations, evidence, events) and relationships\n",- "- Build temporal knowledge graphs for case timelines\n",- "- Correlate evidence across multiple cases\n",- "- Agent-based analysis with persistent memory\n",- "- Graph analytics for evidence network analysis\n",- "- GraphRAG for semantic search across case files\n",- "- Generate forensic analysis reports with evidence chains\n",- "\n",- "### Semantica Modules Used (25+)\n",- "\n",- "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (case files, evidence databases)\n",- "- **Parse**: DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",- "- **Normalize**: TextNormalizer, DataNormalizer\n",- "- **Semantic Extract**: NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "- **Graph Analytics**: Community detection, centrality measures, path finding\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter\n",- "- **Context**: AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: ReportGenerator, JSONExporter\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "- **Deduplication**: DuplicateDetector, EntityMerger\n",- "\n",- "### Pipeline Overview\n",- "\n",- "**Case Files \u2192 Parse \u2192 Extract Evidence Entities/Relationships \u2192 Build Temporal Case KG \u2192 Graph Analytics \u2192 GraphRAG \u2192 Agent Analysis \u2192 Cross-Case Correlation \u2192 Generate Forensic Report \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Setup and Import Semantica Modules\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import all Semantica modules for forensic analysis\n",- "from semantica.ingest import FileIngestor, DBIngestor\n",- "from semantica.parse import DocumentParser, StructuredDataParser, JSONParser, CSVParser\n",- "from semantica.normalize import TextNormalizer, DataNormalizer\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripletExtractor, EventDetector\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",- "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",- "from semantica.context import AgentMemory, ContextRetriever, ContextGraphBuilder\n",- "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import ReportGenerator, JSONExporter\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "from semantica.deduplication import DuplicateDetector, EntityMerger\n",- "\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Initialize Agent Memory and Setup Agents\n",- "\n",- "Set up AgentMemory for persistent context and initialize specialized forensic analysis agents.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize vector store for agent memory\n",- "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",- "\n",- "# Initialize agent memory for persistent context\n",- "agent_memory = AgentMemory(\n",- " vector_store=vector_store,\n",- " retention_policy=\"unlimited\",\n",- " max_memory_size=10000\n",- ")\n",- "\n",- "# Initialize Semantica modules\n",- "file_ingestor = FileIngestor()\n",- "graph_builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "# # inference_engine = InferenceEngine()\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Ingest Case Files and Evidence\n",- "\n",- "Ingest case files, evidence logs, witness statements, and forensic reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Create temporary directory for sample data\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample case files data\n",- "case_files_data = {\n",- " \"cases\": [\n",- " {\n",- " \"case_id\": \"CF001\",\n",- " \"date_opened\": \"2024-01-10\",\n",- " \"case_type\": \"Homicide\",\n",- " \"location\": \"123 Main Street\",\n",- " \"victim\": \"Victim A\",\n",- " \"suspects\": [\"Suspect X\", \"Suspect Y\"],\n",- " \"status\": \"Active\"\n",- " },\n",- " {\n",- " \"case_id\": \"CF002\",\n",- " \"date_opened\": \"2024-02-15\",\n",- " \"case_type\": \"Robbery\",\n",- " \"location\": \"456 Oak Avenue\",\n",- " \"victim\": \"Victim B\",\n",- " \"suspects\": [\"Suspect Y\", \"Suspect Z\"],\n",- " \"status\": \"Active\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample evidence logs\n",- "evidence_logs_data = {\n",- " \"evidence\": [\n",- " {\n",- " \"evidence_id\": \"E001\",\n",- " \"case_id\": \"CF001\",\n",- " \"type\": \"Fingerprint\",\n",- " \"location_found\": \"123 Main Street\",\n",- " \"date_collected\": \"2024-01-10\",\n",- " \"analyzed_by\": \"Forensic Lab A\",\n",- " \"results\": \"Match to Suspect X\"\n",- " },\n",- " {\n",- " \"evidence_id\": \"E002\",\n",- " \"case_id\": \"CF001\",\n",- " \"type\": \"DNA\",\n",- " \"location_found\": \"123 Main Street\",\n",- " \"date_collected\": \"2024-01-11\",\n",- " \"analyzed_by\": \"Forensic Lab B\",\n",- " \"results\": \"Match to Suspect X\"\n",- " },\n",- " {\n",- " \"evidence_id\": \"E003\",\n",- " \"case_id\": \"CF002\",\n",- " \"type\": \"Fingerprint\",\n",- " \"location_found\": \"456 Oak Avenue\",\n",- " \"date_collected\": \"2024-02-15\",\n",- " \"analyzed_by\": \"Forensic Lab A\",\n",- " \"results\": \"Match to Suspect Y\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample witness statements\n",- "witness_statements_data = {\n",- " \"statements\": [\n",- " {\n",- " \"statement_id\": \"WS001\",\n",- " \"case_id\": \"CF001\",\n",- " \"witness\": \"Witness 1\",\n",- " \"date\": \"2024-01-10\",\n",- " \"statement\": \"I saw Suspect X and Suspect Y at the scene around 10 PM\"\n",- " },\n",- " {\n",- " \"statement_id\": \"WS002\",\n",- " \"case_id\": \"CF002\",\n",- " \"witness\": \"Witness 2\",\n",- " \"date\": \"2024-02-15\",\n",- " \"statement\": \"I observed Suspect Y and Suspect Z leaving the area\"\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Save sample data\n",- "case_files_file = os.path.join(temp_dir, \"case_files.json\")\n",- "evidence_logs_file = os.path.join(temp_dir, \"evidence_logs.json\")\n",- "witness_statements_file = os.path.join(temp_dir, \"witness_statements.json\")\n",- "\n",- "with open(case_files_file, 'w') as f:\n",- " json.dump(case_files_data, f, indent=2)\n",- "with open(evidence_logs_file, 'w') as f:\n",- " json.dump(evidence_logs_data, f, indent=2)\n",- "with open(witness_statements_file, 'w') as f:\n",- " json.dump(witness_statements_data, f, indent=2)\n",- "\n",- "# Ingest files\n",- "case_data = file_ingestor.ingest_file(case_files_file, read_content=True)\n",- "evidence_data = file_ingestor.ingest_file(evidence_logs_file, read_content=True)\n",- "witness_data = file_ingestor.ingest_file(witness_statements_file, read_content=True)\n",- "\n",- "# Store in agent memory\n",- "agent_memory.store(\n",- " \"Ingested case files, evidence logs, and witness statements\",\n",- " metadata={\n",- " \"type\": \"data_ingestion\",\n",- " \"sources\": [\"case_files\", \"evidence_logs\", \"witness_statements\"],\n",- " \"timestamp\": datetime.now().isoformat()\n",- " }\n",- ")\n",- "\n",- "print(f\" - Case files: {len(case_files_data['cases'])}\")\n",- "print(f\" - Evidence items: {len(evidence_logs_data['evidence'])}\")\n",- "print(f\" - Witness statements: {len(witness_statements_data['statements'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize extractors\n",- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "\n",- "# Extract forensic entities and relationships\n",- "forensic_entities = []\n",- "forensic_relationships = []\n",- "entity_id_map = {}\n",- "\n",- "# Process case files\n",- "json_parser = JSONParser()\n",- "parsed_cases = json_parser.parse(case_files_file)\n",- "parsed_evidence = json_parser.parse(evidence_logs_file)\n",- "parsed_witnesses = json_parser.parse(witness_statements_file)\n",- "\n",- "cases_data = parsed_cases.data if hasattr(parsed_cases, 'data') else parsed_cases\n",- "evidence_data = parsed_evidence.data if hasattr(parsed_evidence, 'data') else parsed_evidence\n",- "witnesses_data = parsed_witnesses.data if hasattr(parsed_witnesses, 'data') else parsed_witnesses\n",- "\n",- "# Extract entities from cases\n",- "if isinstance(cases_data, dict):\n",- " for case in cases_data.get('cases', []):\n",- " case_id = case.get('case_id')\n",- " # Add case as entity\n",- " forensic_entities.append({\n",- " \"id\": case_id,\n",- " \"type\": \"Case\",\n",- " \"name\": f\"Case {case_id}\",\n",- " \"properties\": {\n",- " \"case_type\": case.get('case_type'),\n",- " \"date_opened\": case.get('date_opened'),\n",- " \"status\": case.get('status')\n",- " }\n",- " })\n",- " \n",- " # Extract suspects, victims, locations\n",- " for suspect in case.get('suspects', []):\n",- " if suspect not in entity_id_map:\n",- " entity_id = f\"SUSPECT_{len(entity_id_map) + 1}\"\n",- " entity_id_map[suspect] = entity_id\n",- " forensic_entities.append({\n",- " \"id\": entity_id,\n",- " \"type\": \"Person\",\n",- " \"name\": suspect,\n",- " \"properties\": {\"role\": \"suspect\"}\n",- " })\n",- " # Create relationship\n",- " forensic_relationships.append({\n",- " \"source\": case_id,\n",- " \"target\": entity_id_map[suspect],\n",- " \"type\": \"involves\",\n",- " \"properties\": {\"date\": case.get('date_opened')}\n",- " })\n",- "\n",- "# Extract evidence entities\n",- "if isinstance(evidence_data, dict):\n",- " for evidence in evidence_data.get('evidence', []):\n",- " evidence_id = evidence.get('evidence_id')\n",- " case_id = evidence.get('case_id')\n",- " forensic_entities.append({\n",- " \"id\": evidence_id,\n",- " \"type\": \"Evidence\",\n",- " \"name\": f\"Evidence {evidence_id}\",\n",- " \"properties\": {\n",- " \"type\": evidence.get('type'),\n",- " \"date_collected\": evidence.get('date_collected'),\n",- " \"results\": evidence.get('results')\n",- " }\n",- " })\n",- " # Link evidence to case\n",- " forensic_relationships.append({\n",- " \"source\": case_id,\n",- " \"target\": evidence_id,\n",- " \"type\": \"has_evidence\",\n",- " \"properties\": {\"date\": evidence.get('date_collected')}\n",- " })\n",- "\n",- "# Build temporal knowledge graph\n",- "forensic_kg = graph_builder.build(forensic_entities, forensic_relationships)\n",- "\n",- "# Store in agent memory\n",- "agent_memory.store(\n",- " f\"Built temporal forensic knowledge graph with {len(forensic_entities)} entities\",\n",- " metadata={\n",- " \"type\": \"knowledge_graph\",\n",- " \"entity_count\": len(forensic_entities),\n",- " \"relationship_count\": len(forensic_relationships)\n",- " },\n",- " entities=forensic_entities,\n",- " relationships=forensic_relationships\n",- ")\n",- "\n",- "print(f\" - Entities: {len(forensic_entities)}\")\n",- "print(f\" - Relationships: {len(forensic_relationships)}\")\n",- "print(f\" - Cases: {len([e for e in forensic_entities if e.get('type') == 'Case'])}\")\n",- "print(f\" - Evidence items: {len([e for e in forensic_entities if e.get('type') == 'Evidence'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize pipeline modules\n",- "pipeline_builder = PipelineBuilder()\n",- "execution_engine = ExecutionEngine()\n",- "\n",- "# Define specialized forensic agents\n",- "\n",- "# Agent 1: Evidence Collection Agent\n",- "def agent_evidence_collection(evidence_data, memory):\n",- " \"\"\"Autonomous agent for evidence gathering.\"\"\"\n",- " context = memory.retrieve(\"evidence\", max_results=5)\n",- " memory.store(\n",- " f\"Evidence collection agent processed {len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0} evidence items\",\n",- " metadata={\"agent\": \"evidence_collection\"}\n",- " )\n",- " return {\"evidence_processed\": len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0}\n",- "\n",- "# Agent 2: Timeline Analysis Agent\n",- "def agent_timeline_analysis(kg, temporal_query, memory):\n",- " \"\"\"Agent for building temporal case timelines.\"\"\"\n",- " # Use temporal query to analyze timelines\n",- " timeline = temporal_query.query_by_time_range(kg, start_date=\"2024-01-01\", end_date=\"2024-12-31\")\n",- " memory.store(\n",- " \"Timeline analysis agent built case timelines\",\n",- " metadata={\"agent\": \"timeline_analysis\"}\n",- " )\n",- " return {\"timeline\": timeline}\n",- "\n",- "# Agent 3: Cross-Case Correlation Agent\n",- "def agent_cross_case_correlation(kg, analyzer, memory):\n",- " \"\"\"Agent for finding connections across cases.\"\"\"\n",- " # Find common suspects, locations, evidence\n",- " communities = analyzer.detect_communities(kg, method=\"louvain\")\n",- " memory.store(\n",- " f\"Cross-case correlation identified {communities.get('num_communities', 0) if isinstance(communities, dict) else 0} case clusters\",\n",- " metadata={\"agent\": \"cross_case_correlation\"}\n",- " )\n",- " return {\"case_clusters\": communities}\n",- "\n",- "# Agent 4: Forensic Report Agent\n",- "def agent_forensic_report(analysis_results, memory):\n",- " \"\"\"Agent for generating forensic reports.\"\"\"\n",- " context = memory.retrieve(\"forensic analysis\", max_results=10)\n",- " memory.store(\n",- " \"Forensic report agent compiled comprehensive report\",\n",- " metadata={\"agent\": \"forensic_report\"}\n",- " )\n",- " return {\"report_data\": analysis_results, \"context_items\": len(context)}\n",- "\n",- "def evidence_collection_handler(data, **config):\n",- " evidence_data = data.get(\"evidence_logs_data\")\n",- " memory = data.get(\"memory\")\n",- " r = agent_evidence_collection(evidence_data, memory)\n",- " return {**data, \"evidence_collection_result\": r}\n",- "def timeline_handler(data, **config):\n",- " kg = data.get(\"forensic_kg\")\n",- " temporal = data.get(\"temporal_query\")\n",- " memory = data.get(\"memory\")\n",- " r = agent_timeline_analysis(kg, temporal, memory)\n",- " return {**data, \"timeline_result\": r}\n",- "def correlation_handler(data, **config):\n",- " kg = data.get(\"forensic_kg\")\n",- " analyzer = data.get(\"graph_analyzer\")\n",- " memory = data.get(\"memory\")\n",- " r = agent_cross_case_correlation(kg, analyzer, memory)\n",- " return {**data, \"correlation_result\": r}\n",- "def report_handler(data, **config):\n",- " memory = data.get(\"memory\")\n",- " analysis = {\n",- " \"evidence\": data.get(\"evidence_collection_result\"),\n",- " \"timeline\": data.get(\"timeline_result\"),\n",- " \"correlation\": data.get(\"correlation_result\")\n",- " }\n",- " r = agent_forensic_report(analysis, memory)\n",- " return {**data, \"forensic_report_result\": r}\n",- "forensic_pipeline = (\n",- " pipeline_builder\n",- " .add_step(\"evidence_collection\", \"ingest\", handler=evidence_collection_handler)\n",- " .add_step(\"timeline_analysis\", \"analyze_graph\", dependencies=[\"evidence_collection\"], handler=timeline_handler)\n",- " .add_step(\"cross_case_correlation\", \"analyze_graph\", dependencies=[\"timeline_analysis\"], handler=correlation_handler)\n",- " .add_step(\"forensic_report\", \"report\", dependencies=[\"cross_case_correlation\"], handler=report_handler)\n",- ")\n",- ".build()\n",- "input_data = {\"evidence_logs_data\": evidence_logs_data, \"forensic_kg\": forensic_kg, \"temporal_query\": temporal_query, \"graph_analyzer\": graph_analyzer, \"memory\": agent_memory, \"cases_data\": cases_data}\n",- "pipeline_result = execution_engine.execute_pipeline(forensic_pipeline, data=input_data, parallel=True)\n",- "\n",- "print(f\" - Pipeline steps: {len(forensic_pipeline.steps)}\")\n",- "print(f\" - Parallel execution: Enabled\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Generate Forensic Analysis Report\n",- "\n",- "Generate comprehensive forensic analysis report with evidence chains.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize report generator\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Prepare forensic report data\n",- "forensic_report_data = {\n",- " \"title\": \"Forensic Analysis Report\",\n",- " \"executive_summary\": \"Analysis of case files, evidence chains, and cross-case correlations\",\n",- " \"cases_analyzed\": len(cases_data.get('cases', [])) if isinstance(cases_data, dict) else 0,\n",- " \"evidence_items\": len(evidence_data.get('evidence', [])) if isinstance(evidence_data, dict) else 0,\n",- " \"knowledge_graph\": {\n",- " \"entities\": len(forensic_entities),\n",- " \"relationships\": len(forensic_relationships)\n",- " },\n",- " \"agent_memory_stats\": agent_memory.get_statistics()\n",- "}\n",- "\n",- "# Generate HTML report\n",- "forensic_report_file = os.path.join(temp_dir, \"forensic_analysis_report.html\")\n",- "report_generator.generate_report(\n",- " forensic_report_data,\n",- " forensic_report_file,\n",- " format=\"html\"\n",- ")\n",- "\n",- "print(f\" - Report file: {forensic_report_file}\")\n",- "print(f\" - Report includes: Case analysis, evidence chains, cross-case correlations\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb b/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynbdeleted file mode 100644index ecbc2e46..00000000--- a/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb+++ /dev/null@@ -1,464 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/01_Energy_Market_Analysis.ipynb)\n",- "\n",- "# Energy Market Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete energy market analysis pipeline: ingest energy market data from multiple sources (energy APIs, market data streams, databases), extract energy entities, build temporal market knowledge graph, analyze pricing trends, and predict market movements.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Energy Market Sources \u2192 Parse \u2192 Extract Entities \u2192 Build Temporal Market KG \u2192 Analyze Pricing \u2192 Predict Trends \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Energy Market Data from Multiple Sources\n",- "\n",- "Ingest energy market data from energy APIs, market data streams, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, StreamIngestor, DBIngestor, FeedIngestor, FileIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real energy market data sources\n",- "energy_apis = [\n",- " \"https://api.eia.gov/v2/electricity/retail-sales/data/\", # EIA Energy Information Administration\n",- " \"https://www.energy.gov/data\", # US Energy Department Data\n",- " \"https://api.github.com/repos/energy-data/aggregator\" # Energy data aggregator\n",- "]\n",- "\n",- "energy_feeds = [\n",- " \"https://www.energy.gov/rss\", # US Energy Department RSS\n",- " \"https://feeds.reuters.com/reuters/businessNews\" # Reuters Business (energy news)\n",- "]\n",- "\n",- "# Real streaming sources for energy market data\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"energy_market\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"energy_analysis\"}\n",- " }\n",- "]\n",- "\n",- "# Real database connection for energy market data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/energy_market_db\"\n",- "db_query = \"SELECT energy_type, price, volume, timestamp, region FROM energy_prices WHERE timestamp > NOW() - INTERVAL '24 hours' ORDER BY timestamp DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample energy market data (real-world structure)\n",- "energy_market_file = os.path.join(temp_dir, \"energy_market.json\")\n",- "energy_market_data = [\n",- " {\n",- " \"energy_type\": \"Solar\",\n",- " \"price\": 0.045,\n",- " \"volume\": 1000000,\n",- " \"timestamp\": (datetime.now() - timedelta(hours=2)).isoformat(),\n",- " \"region\": \"California\"\n",- " },\n",- " {\n",- " \"energy_type\": \"Wind\",\n",- " \"price\": 0.035,\n",- " \"volume\": 800000,\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"region\": \"Texas\"\n",- " },\n",- " {\n",- " \"energy_type\": \"Hydroelectric\",\n",- " \"price\": 0.040,\n",- " \"volume\": 600000,\n",- " \"timestamp\": datetime.now().isoformat(),\n",- " \"region\": \"Pacific Northwest\"\n",- " }\n",- "]\n",- "\n",- "with open(energy_market_file, 'w') as f:\n",- " json.dump(energy_market_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(energy_market_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(energy_market_file)\n",- "\n",- "# Ingest from energy APIs\n",- "energy_api_list = []\n",- "for api_url in energy_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " energy_api_list.append(api_content)\n",- " print(f\" Ingested energy API: {api_url}\")\n",- "\n",- "# Ingest from energy feeds\n",- "energy_feed_list = []\n",- "for feed_url in energy_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " energy_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Energy Market Ingestion Summary:\")\n",- "print(f\" Energy market files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Energy APIs: {len(energy_api_list)}\")\n",- "print(f\" Energy feeds: {len(energy_feed_list)}\")\n",- "print(f\" Streaming sources: {len(stream_sources)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Energy Entities and Build Temporal Market Knowledge Graph\n",- "\n",- "Extract energy entities and build temporal market knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "energy_entities = []\n",- "energy_relationships = []\n",- "\n",- "# Extract from energy market data\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " energy_type = entry.get(\"energy_type\", \"\")\n",- " region = entry.get(\"region\", \"\")\n",- " timestamp = entry.get(\"timestamp\", \"\")\n",- " \n",- " energy_entities.append({\n",- " \"id\": f\"{energy_type}_{region}_{timestamp}\",\n",- " \"type\": \"Energy_Price\",\n",- " \"name\": f\"{energy_type} in {region}\",\n",- " \"properties\": {\n",- " \"energy_type\": energy_type,\n",- " \"price\": entry.get(\"price\", 0),\n",- " \"volume\": entry.get(\"volume\", 0),\n",- " \"region\": region,\n",- " \"timestamp\": timestamp\n",- " }\n",- " })\n",- " \n",- " energy_entities.append({\n",- " \"id\": energy_type,\n",- " \"type\": \"Energy_Source\",\n",- " \"name\": energy_type,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " energy_entities.append({\n",- " \"id\": region,\n",- " \"type\": \"Region\",\n",- " \"name\": region,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " energy_relationships.append({\n",- " \"source\": energy_type,\n",- " \"target\": f\"{energy_type}_{region}_{timestamp}\",\n",- " \"type\": \"has_price_in\",\n",- " \"properties\": {\"timestamp\": timestamp}\n",- " })\n",- " \n",- " energy_relationships.append({\n",- " \"source\": f\"{energy_type}_{region}_{timestamp}\",\n",- " \"target\": region,\n",- " \"type\": \"in_region\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "energy_market_kg = builder.build(energy_entities, energy_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(energy_market_kg)\n",- "\n",- "print(f\"Extracted {len(energy_entities)} energy entities\")\n",- "print(f\"Extracted {len(energy_relationships)} relationships\")\n",- "print(f\"Built temporal energy market knowledge graph with {len(energy_market_kg.get('entities', []))} entities\")\n",- "print(f\"Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Analyze Energy Pricing Trends\n",- "\n",- "Analyze energy pricing trends using temporal queries and pattern detection.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "start_time = (datetime.now() - timedelta(hours=24)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "# Query pricing trends\n",- "pricing_trends = temporal_query.query_time_range(\n",- " graph=energy_market_kg,\n",- " query=\"Find energy pricing trends in the last 24 hours\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "# Detect temporal patterns\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " energy_market_kg,\n",- " pattern_type=\"trend\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Analyze pricing by energy type\n",- "pricing_analysis = {}\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " energy_type = entry.get(\"energy_type\", \"\")\n",- " price = entry.get(\"price\", 0)\n",- " \n",- " if energy_type not in pricing_analysis:\n",- " pricing_analysis[energy_type] = {\n",- " \"prices\": [],\n",- " \"volumes\": [],\n",- " \"regions\": []\n",- " }\n",- " \n",- " pricing_analysis[energy_type][\"prices\"].append(price)\n",- " pricing_analysis[energy_type][\"volumes\"].append(entry.get(\"volume\", 0))\n",- " pricing_analysis[energy_type][\"regions\"].append(entry.get(\"region\", \"\"))\n",- "\n",- "# Calculate average prices\n",- "for energy_type, data in pricing_analysis.items():\n",- " if data[\"prices\"]:\n",- " pricing_analysis[energy_type][\"avg_price\"] = sum(data[\"prices\"]) / len(data[\"prices\"])\n",- " pricing_analysis[energy_type][\"total_volume\"] = sum(data[\"volumes\"])\n",- "\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(market_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(energy_market_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(energy_market_kg)\n",- "\n",- "print(f\"Pricing analysis complete\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\" Energy types analyzed: {len(pricing_analysis)}\")\n",- "for energy_type, data in pricing_analysis.items():\n",- " print(f\" {energy_type}: Avg Price ${data.get('avg_price', 0):.4f}/kWh, Total Volume {data.get('total_volume', 0):,}\")\n",- "print(f\" Central energy sources: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Predict Energy Market Trends\n",- "\n",- "Predict energy market trends using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Energy market trend prediction rules\n",- "inference_engine.add_rule(\"IF price < 0.04 AND volume > 500000 THEN competitive_pricing\")\n",- "inference_engine.add_rule(\"IF price > 0.05 AND volume < 500000 THEN high_pricing\")\n",- "inference_engine.add_rule(\"IF multiple regions show same energy_type THEN market_trend\")\n",- "\n",- "# Add facts from energy market data\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " inference_engine.add_fact({\n",- " \"energy_type\": entry.get(\"energy_type\", \"\"),\n",- " \"price\": entry.get(\"price\", 0),\n",- " \"volume\": entry.get(\"volume\", 0),\n",- " \"region\": entry.get(\"region\", \"\")\n",- " })\n",- "\n",- "# # trend_predictions = inference_engine.forward_chain()\n",- "\n",- "# Generate trend predictions\n",- "market_predictions = []\n",- "for energy_type, data in pricing_analysis.items():\n",- " avg_price = data.get(\"avg_price\", 0)\n",- " total_volume = data.get(\"total_volume\", 0)\n",- " \n",- " prediction = {\n",- " \"energy_type\": energy_type,\n",- " \"current_avg_price\": avg_price,\n",- " \"total_volume\": total_volume,\n",- " \"trend\": \"increasing\" if avg_price > 0.04 else \"stable\" if avg_price > 0.035 else \"decreasing\",\n",- " \"market_share\": total_volume / sum(p.get(\"total_volume\", 0) for p in pricing_analysis.values()) if sum(p.get(\"total_volume\", 0) for p in pricing_analysis.values()) > 0 else 0\n",- " }\n",- " market_predictions.append(prediction)\n",- "\n",- "print(f\"Generated {len(trend_predictions)} trend predictions\")\n",- "print(f\"Market predictions for {len(market_predictions)} energy types:\")\n",- "for prediction in market_predictions:\n",- " print(f\" {prediction['energy_type']}: {prediction['trend']} trend, Market Share: {prediction['market_share']*100:.1f}%\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate energy market analysis reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.95}\n",- "\n",- "json_exporter.export_knowledge_graph(energy_market_kg, os.path.join(temp_dir, \"energy_market_kg.json\"))\n",- "csv_exporter.export_entities(energy_entities, os.path.join(temp_dir, \"energy_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(energy_market_kg, os.path.join(temp_dir, \"energy_market_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Energy market analysis identified {len(trend_predictions)} trends and {len(market_predictions)} market predictions\",\n",- " \"energy_types_analyzed\": len(pricing_analysis),\n",- " \"patterns\": len(temporal_patterns),\n",- " \"predictions\": len(market_predictions),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(energy_market_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(energy_market_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(energy_market_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Energy Market Sources \u2192 Parse \u2192 Extract \u2192 Build Temporal KG \u2192 Analyze Pricing \u2192 Predict Trends \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb b/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynbdeleted file mode 100644index f2d94737..00000000--- a/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb+++ /dev/null@@ -1,502 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/02_Environmental_Impact.ipynb)\n",- "\n",- "# Environmental Impact Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete environmental impact analysis pipeline: ingest environmental data from multiple sources (EPA APIs, climate databases, sustainability feeds), extract environmental entities, build impact knowledge graph, analyze relationships, and assess environmental impact.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< HEAD-<<<<<<< Updated upstream- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======- "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator\n",- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, OWLExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Environmental Data Sources \u2192 Parse \u2192 Extract Entities \u2192 Build Impact KG \u2192 Analyze Relationships \u2192 Assess Impact \u2192 Generate Ontology \u2192 Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Environmental Data from Multiple Sources\n",- "\n",- "Ingest environmental data from EPA APIs, climate databases, and sustainability feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "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",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "# Real environmental data sources\n",- "environmental_apis = [\n",- " \"https://www.epa.gov/enviro/facts-service\", # EPA Environmental Facts Service\n",- " \"https://www.epa.gov/airdata\", # EPA Air Data\n",- " \"https://api.github.com/repos/climate-data/aggregator\" # Climate data aggregator\n",- "]\n",- "\n",- "environmental_feeds = [\n",- " \"https://www.epa.gov/rss\", # EPA RSS Feed\n",- " \"https://www.energy.gov/rss\", # US Energy Department RSS\n",- " \"https://feeds.reuters.com/reuters/environment\" # Reuters Environment News\n",- "]\n",- "\n",- "# Real database connection for environmental data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/environmental_db\"\n",- "db_query = \"SELECT project_id, energy_type, co2_reduction, water_saved, land_impact, timestamp FROM environmental_impact WHERE timestamp > CURRENT_DATE - INTERVAL '1 year' ORDER BY timestamp DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample environmental impact data\n",- "environmental_file = os.path.join(temp_dir, \"environmental_impact.json\")\n",- "environmental_data = [\n",- " {\n",- " \"project_id\": \"PROJ-001\",\n",- " \"energy_type\": \"Solar\",\n",- " \"co2_reduction_tons\": 5000,\n",- " \"water_saved_gallons\": 1000000,\n",- " \"land_impact_acres\": 50,\n",- " \"carbon_offset\": 5000,\n",- " \"timestamp\": (datetime.now() - timedelta(days=60)).isoformat(),\n",- " \"region\": \"California\"\n",- " },\n",- " {\n",- " \"project_id\": \"PROJ-002\",\n",- " \"energy_type\": \"Wind\",\n",- " \"co2_reduction_tons\": 8000,\n",- " \"water_saved_gallons\": 2000000,\n",- " \"land_impact_acres\": 100,\n",- " \"carbon_offset\": 8000,\n",- " \"timestamp\": (datetime.now() - timedelta(days=30)).isoformat(),\n",- " \"region\": \"Texas\"\n",- " },\n",- " {\n",- " \"project_id\": \"PROJ-003\",\n",- " \"energy_type\": \"Hydroelectric\",\n",- " \"co2_reduction_tons\": 3000,\n",- " \"water_saved_gallons\": 500000,\n",- " \"land_impact_acres\": 200,\n",- " \"carbon_offset\": 3000,\n",- " \"timestamp\": datetime.now().isoformat(),\n",- " \"region\": \"Pacific Northwest\"\n",- " }\n",- "]\n",- "\n",- "with open(environmental_file, 'w') as f:\n",- " json.dump(environmental_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(environmental_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(environmental_file)\n",- "\n",- "# Ingest from environmental APIs\n",- "environmental_api_list = []\n",- "for api_url in environmental_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " environmental_api_list.append(api_content)\n",- " print(f\" Ingested environmental API: {api_url}\")\n",- "\n",- "# Ingest from environmental feeds\n",- "environmental_feed_list = []\n",- "for feed_url in environmental_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " environmental_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Environmental Data Ingestion Summary:\")\n",- "print(f\" Environmental data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Environmental APIs: {len(environmental_api_list)}\")\n",- "print(f\" Environmental feeds: {len(environmental_feed_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Environmental Entities and Build Impact Knowledge Graph\n",- "\n",- "Extract environmental entities and build impact knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "environmental_entities = []\n",- "environmental_relationships = []\n",- "\n",- "# Extract from environmental data\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " project_id = entry.get(\"project_id\", \"\")\n",- " energy_type = entry.get(\"energy_type\", \"\")\n",- " region = entry.get(\"region\", \"\")\n",- " \n",- " environmental_entities.append({\n",- " \"id\": project_id,\n",- " \"type\": \"Project\",\n",- " \"name\": project_id,\n",- " \"properties\": {\n",- " \"energy_type\": energy_type,\n",- " \"region\": region,\n",- " \"timestamp\": entry.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " environmental_entities.append({\n",- " \"id\": energy_type,\n",- " \"type\": \"Energy_Source\",\n",- " \"name\": energy_type,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " environmental_entities.append({\n",- " \"id\": f\"{project_id}_co2_reduction\",\n",- " \"type\": \"Environmental_Impact\",\n",- " \"name\": \"CO2 Reduction\",\n",- " \"properties\": {\n",- " \"metric\": \"CO2\",\n",- " \"value\": entry.get(\"co2_reduction_tons\", 0),\n",- " \"unit\": \"tons\"\n",- " }\n",- " })\n",- " \n",- " environmental_entities.append({\n",- " \"id\": f\"{project_id}_water_saved\",\n",- " \"type\": \"Environmental_Impact\",\n",- " \"name\": \"Water Saved\",\n",- " \"properties\": {\n",- " \"metric\": \"Water\",\n",- " \"value\": entry.get(\"water_saved_gallons\", 0),\n",- " \"unit\": \"gallons\"\n",- " }\n",- " })\n",- " \n",- " environmental_relationships.append({\n",- " \"source\": project_id,\n",- " \"target\": energy_type,\n",- " \"type\": \"uses\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " environmental_relationships.append({\n",- " \"source\": project_id,\n",- " \"target\": f\"{project_id}_co2_reduction\",\n",- " \"type\": \"reduces\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " environmental_relationships.append({\n",- " \"source\": project_id,\n",- " \"target\": f\"{project_id}_water_saved\",\n",- " \"type\": \"saves\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "\n",- "impact_kg = builder.build(environmental_entities, environmental_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(impact_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(impact_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(impact_kg)\n",- "\n",- "print(f\"Extracted {len(environmental_entities)} environmental entities\")\n",- "print(f\"Extracted {len(environmental_relationships)} relationships\")\n",- "print(f\"Built impact knowledge graph with {len(impact_kg.get('entities', []))} entities\")\n",- "print(f\"Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Analyze Environmental Relationships\n",- "\n",- "Analyze environmental relationships using graph analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "\n",- "connectivity = connectivity_analyzer.analyze_connectivity(impact_kg)\n",- "\n",- "start_time = (datetime.now() - timedelta(days=365)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=impact_kg,\n",- " query=\"Find environmental impacts in the last year\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " impact_kg,\n",- " pattern_type=\"trend\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Analyze impact by energy type\n",- "impact_analysis = {}\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " energy_type = entry.get(\"energy_type\", \"\")\n",- " \n",- " if energy_type not in impact_analysis:\n",- " impact_analysis[energy_type] = {\n",- " \"co2_reduction\": [],\n",- " \"water_saved\": [],\n",- " \"projects\": []\n",- " }\n",- " \n",- " impact_analysis[energy_type][\"co2_reduction\"].append(entry.get(\"co2_reduction_tons\", 0))\n",- " impact_analysis[energy_type][\"water_saved\"].append(entry.get(\"water_saved_gallons\", 0))\n",- " impact_analysis[energy_type][\"projects\"].append(entry.get(\"project_id\", \"\"))\n",- "\n",- "# Calculate totals\n",- "for energy_type, data in impact_analysis.items():\n",- " impact_analysis[energy_type][\"total_co2_reduction\"] = sum(data[\"co2_reduction\"])\n",- " impact_analysis[energy_type][\"total_water_saved\"] = sum(data[\"water_saved\"])\n",- " impact_analysis[energy_type][\"project_count\"] = len(data[\"projects\"])\n",- "\n",- "print(f\"Environmental relationships analyzed\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\" Energy types analyzed: {len(impact_analysis)}\")\n",- "for energy_type, data in impact_analysis.items():\n",- " print(f\" {energy_type}: {data['total_co2_reduction']:,} tons CO2 reduced, {data['total_water_saved']:,} gallons saved, {data['project_count']} projects\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Assess Environmental Impact\n",- "\n",- "Assess environmental impact using inference engine and generate ontology.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "ontology_generator = OntologyGenerator()\n",- "class_inferrer = ClassInferrer()\n",- "property_generator = PropertyGenerator()\n",- "ontology_validator = OntologyValidator()\n",- "\n",- "# Environmental impact assessment rules\n",- "inference_engine.add_rule(\"IF co2_reduction > 5000 AND water_saved > 1000000 THEN high_impact_project\")\n",- "inference_engine.add_rule(\"IF energy_type is Solar AND co2_reduction > 3000 THEN sustainable_solar\")\n",- "inference_engine.add_rule(\"IF multiple projects use same energy_type THEN scalable_solution\")\n",- "\n",- "# Assess impact\n",- "impact_assessments = []\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " co2_reduction = entry.get(\"co2_reduction_tons\", 0)\n",- " water_saved = entry.get(\"water_saved_gallons\", 0)\n",- " \n",- " impact_score = (co2_reduction / 1000) + (water_saved / 100000)\n",- " impact_level = \"high\" if impact_score > 10 else \"medium\" if impact_score > 5 else \"low\"\n",- " \n",- " assessment = {\n",- " \"project_id\": entry.get(\"project_id\", \"\"),\n",- " \"energy_type\": entry.get(\"energy_type\", \"\"),\n",- " \"co2_reduction\": co2_reduction,\n",- " \"water_saved\": water_saved,\n",- " \"impact_score\": impact_score,\n",- " \"impact_level\": impact_level\n",- " }\n",- " impact_assessments.append(assessment)\n",- " \n",- " inference_engine.add_fact({\n",- " \"project_id\": entry.get(\"project_id\", \"\"),\n",- " \"energy_type\": entry.get(\"energy_type\", \"\"),\n",- " \"co2_reduction\": co2_reduction,\n",- " \"water_saved\": water_saved\n",- " })\n",- "\n",- "# # impact_insights = inference_engine.forward_chain()\n",- "\n",- "# Generate environmental ontology\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",- "\n",- "print(f\"Environmental impact assessment complete\")\n",- "print(f\" Projects assessed: {len(impact_assessments)}\")\n",- "print(f\" High impact projects: {len([a for a in impact_assessments if a.get('impact_level') == 'high'])}\")\n",- "print(f\" Generated {len(impact_insights)} impact insights\")\n",- "print(f\" Ontology valid: {validation_result.valid}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate environmental impact reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "quality_assessor = KGQualityAssessor()\n",- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "owl_exporter = OWLExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = quality_assessor.assess_overall_quality(impact_kg)\n",- "\n",- "json_exporter.export_knowledge_graph(impact_kg, os.path.join(temp_dir, \"environmental_impact_kg.json\"))\n",- "csv_exporter.export_entities(environmental_entities, os.path.join(temp_dir, \"environmental_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(impact_kg, os.path.join(temp_dir, \"environmental_impact_kg.rdf\"))\n",- "owl_exporter.export(impact_ontology, os.path.join(temp_dir, \"environmental_ontology.owl\"))\n",- "\n",- "total_co2_reduction = sum(a.get(\"co2_reduction\", 0) for a in impact_assessments)\n",- "total_water_saved = sum(a.get(\"water_saved\", 0) for a in impact_assessments)\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Environmental impact analysis identified {len(impact_assessments)} projects with {total_co2_reduction:,} tons CO2 reduction and {total_water_saved:,} gallons water saved\",\n",- " \"projects_analyzed\": len(impact_assessments),\n",- " \"total_co2_reduction\": total_co2_reduction,\n",- " \"total_water_saved\": total_water_saved,\n",- " \"high_impact_projects\": len([a for a in impact_assessments if a.get(\"impact_level\") == \"high\"]),\n",- " \"insights\": len(impact_insights),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "ontology_visualizer = OntologyVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(impact_kg, output=\"interactive\")\n",- "ontology_viz = ontology_visualizer.visualize_hierarchy(impact_ontology, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(impact_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Environmental Data \u2192 Parse \u2192 Extract \u2192 Build Impact KG \u2192 Analyze Relationships \u2192 Assess Impact \u2192 Generate Ontology \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb b/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynbdeleted file mode 100644index e57a9c21..00000000--- a/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb+++ /dev/null@@ -1,492 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/03_Grid_Management.ipynb)\n",- "\n",- "# Smart Grid Management Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete smart grid management pipeline: stream grid data from multiple sources (grid sensors, SCADA systems, databases), build temporal grid knowledge graph, monitor grid health in real-time, detect anomalies, and predict failures.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser, CSVParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, AutomatedFixer\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Stream Grid Data \u2192 Parse \u2192 Extract Entities \u2192 Build Temporal Grid KG \u2192 Monitor Grid Health \u2192 Detect Anomalies \u2192 Predict Failures \u2192 Generate Alerts \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Stream Grid Data from Multiple Sources\n",- "\n",- "Stream grid data from grid sensors, SCADA systems, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, StructuredDataParser, CSVParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "import time\n",- "from datetime import datetime, timedelta\n",- "from collections import deque\n",- "\n",- "stream_ingestor = StreamIngestor()\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "csv_parser = CSVParser()\n",- "\n",- "# Real streaming sources for grid data\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"grid_sensors\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"grid_monitor\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"scada_events\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real grid monitoring APIs\n",- "grid_apis = [\n",- " \"https://api.eia.gov/v2/electricity/operating-generator-capacity/data/\", # EIA Grid Capacity\n",- " \"https://www.energy.gov/data\" # US Energy Department Grid Data\n",- "]\n",- "\n",- "# Real database connection for grid data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/grid_db\"\n",- "db_query = \"SELECT node_id, voltage, current, power, frequency, status, timestamp FROM grid_nodes WHERE timestamp > NOW() - INTERVAL '1 hour' ORDER BY timestamp DESC LIMIT 1000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample real-time grid data (simulating SCADA system)\n",- "grid_stream_file = os.path.join(temp_dir, \"grid_stream.json\")\n",- "grid_stream = [\n",- " {\n",- " \"node_id\": \"GRID-001\",\n",- " \"voltage\": 230.0,\n",- " \"current\": 100.0,\n",- " \"power\": 23000.0,\n",- " \"frequency\": 60.0,\n",- " \"status\": \"normal\",\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=5)).isoformat(),\n",- " \"location\": \"Substation A\"\n",- " },\n",- " {\n",- " \"node_id\": \"GRID-002\",\n",- " \"voltage\": 225.0,\n",- " \"current\": 95.0,\n",- " \"power\": 21375.0,\n",- " \"frequency\": 59.8,\n",- " \"status\": \"warning\",\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=4)).isoformat(),\n",- " \"location\": \"Substation B\"\n",- " },\n",- " {\n",- " \"node_id\": \"GRID-003\",\n",- " \"voltage\": 235.0,\n",- " \"current\": 105.0,\n",- " \"power\": 24675.0,\n",- " \"frequency\": 60.2,\n",- " \"status\": \"normal\",\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=3)).isoformat(),\n",- " \"location\": \"Substation C\"\n",- " },\n",- " {\n",- " \"node_id\": \"GRID-004\",\n",- " \"voltage\": 200.0,\n",- " \"current\": 80.0,\n",- " \"power\": 16000.0,\n",- " \"frequency\": 58.5,\n",- " \"status\": \"critical\",\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=2)).isoformat(),\n",- " \"location\": \"Substation D\"\n",- " }\n",- "]\n",- "\n",- "with open(grid_stream_file, 'w') as f:\n",- " json.dump(grid_stream, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(grid_stream_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(grid_stream_file)\n",- "\n",- "print(f\"\\n\ud83d\udcca Grid Data Ingestion Summary:\")\n",- "print(f\" Grid stream files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Streaming sources: {len(stream_sources)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Grid Entities and Build Temporal Grid Knowledge Graph\n",- "\n",- "Extract grid entities and build temporal grid knowledge graph for real-time monitoring.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "grid_entities = []\n",- "grid_relationships = []\n",- "\n",- "# Extract from grid stream data\n",- "if parsed_data and parsed_data.data:\n",- " for node in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(node, dict):\n",- " node_id = node.get(\"node_id\", \"\")\n",- " location = node.get(\"location\", \"\")\n",- " \n",- " grid_entities.append({\n",- " \"id\": node_id,\n",- " \"type\": \"Grid_Node\",\n",- " \"name\": node_id,\n",- " \"properties\": {\n",- " \"voltage\": node.get(\"voltage\", 0),\n",- " \"current\": node.get(\"current\", 0),\n",- " \"power\": node.get(\"power\", 0),\n",- " \"frequency\": node.get(\"frequency\", 0),\n",- " \"status\": node.get(\"status\", \"\"),\n",- " \"location\": location,\n",- " \"timestamp\": node.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " grid_entities.append({\n",- " \"id\": location,\n",- " \"type\": \"Location\",\n",- " \"name\": location,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " grid_relationships.append({\n",- " \"source\": node_id,\n",- " \"target\": location,\n",- " \"type\": \"located_at\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Status relationships\n",- " if node.get(\"status\") != \"normal\":\n",- " grid_entities.append({\n",- " \"id\": f\"{node_id}_status\",\n",- " \"type\": \"Grid_Status\",\n",- " \"name\": node.get(\"status\", \"\"),\n",- " \"properties\": {}\n",- " })\n",- " grid_relationships.append({\n",- " \"source\": node_id,\n",- " \"target\": f\"{node_id}_status\",\n",- " \"type\": \"has_status\",\n",- " \"properties\": {\"timestamp\": node.get(\"timestamp\", \"\")}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "grid_kg = builder.build(grid_entities, grid_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(grid_kg)\n",- "\n",- "print(f\"Extracted {len(grid_entities)} grid entities\")\n",- "print(f\"Extracted {len(grid_relationships)} relationships\")\n",- "print(f\"Built temporal grid knowledge graph with {len(grid_kg.get('entities', []))} entities\")\n",- "print(f\"Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Monitor Grid Health in Real-Time\n",- "\n",- "Monitor grid health using temporal queries and pattern detection.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "current_time = datetime.now().isoformat()\n",- "start_time = (datetime.now() - timedelta(minutes=10)).isoformat()\n",- "\n",- "# Query current grid status\n",- "current_grid_status = temporal_query.query_time_range(\n",- " graph=grid_kg,\n",- " query=\"Find current grid status\",\n",- " start_time=start_time,\n",- " end_time=current_time\n",- ")\n",- "\n",- "# Monitor grid health metrics\n",- "grid_health_metrics = []\n",- "if parsed_data and parsed_data.data:\n",- " for node in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(node, dict):\n",- " voltage = node.get(\"voltage\", 0)\n",- " frequency = node.get(\"frequency\", 0)\n",- " status = node.get(\"status\", \"\")\n",- " \n",- " health_score = 100\n",- " issues = []\n",- " \n",- " # Voltage check (normal: 220-240V)\n",- " if voltage < 210 or voltage > 250:\n",- " health_score -= 20\n",- " issues.append(\"Voltage out of range\")\n",- " \n",- " # Frequency check (normal: 59.5-60.5 Hz)\n",- " if frequency < 59.0 or frequency > 61.0:\n",- " health_score -= 20\n",- " issues.append(\"Frequency out of range\")\n",- " \n",- " if status == \"critical\":\n",- " health_score -= 30\n",- " issues.append(\"Critical status\")\n",- " elif status == \"warning\":\n",- " health_score -= 10\n",- " issues.append(\"Warning status\")\n",- " \n",- " grid_health_metrics.append({\n",- " \"node_id\": node.get(\"node_id\", \"\"),\n",- " \"health_score\": health_score,\n",- " \"status\": status,\n",- " \"issues\": issues,\n",- " \"timestamp\": node.get(\"timestamp\", \"\")\n",- " })\n",- "\n",- "# Detect temporal patterns\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " grid_kg,\n",- " pattern_type=\"anomaly\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(grid_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(grid_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(grid_kg)\n",- "\n",- "print(f\"Monitoring {len(current_grid_status.get('entities', []))} grid nodes\")\n",- "print(f\"Grid health metrics tracked: {len(grid_health_metrics)}\")\n",- "print(f\"Nodes with issues: {len([m for m in grid_health_metrics if m.get('health_score') < 80])}\")\n",- "print(f\"Temporal patterns: {len(temporal_patterns)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Detect Anomalies and Predict Failures\n",- "\n",- "Detect grid anomalies and predict potential failures.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Grid failure prediction rules\n",- "inference_engine.add_rule(\"IF voltage < 200 AND frequency < 59 THEN potential_failure\")\n",- "inference_engine.add_rule(\"IF status is critical AND health_score < 50 THEN immediate_action_required\")\n",- "inference_engine.add_rule(\"IF multiple nodes show same issue THEN systemic_problem\")\n",- "\n",- "# Detect anomalies and predict failures\n",- "anomalies = []\n",- "failure_predictions = []\n",- "alerts = []\n",- "\n",- "for health_metric in grid_health_metrics:\n",- " if health_metric.get(\"health_score\", 100) < 80:\n",- " anomaly = {\n",- " \"node_id\": health_metric.get(\"node_id\", \"\"),\n",- " \"severity\": \"high\" if health_metric.get(\"health_score\", 100) < 50 else \"medium\",\n",- " \"health_score\": health_metric.get(\"health_score\", 100),\n",- " \"issues\": health_metric.get(\"issues\", []),\n",- " \"timestamp\": health_metric.get(\"timestamp\", \"\")\n",- " }\n",- " anomalies.append(anomaly)\n",- " \n",- " if health_metric.get(\"health_score\", 100) < 50:\n",- " failure_predictions.append({\n",- " \"node_id\": health_metric.get(\"node_id\", \"\"),\n",- " \"predicted_failure\": True,\n",- " \"confidence\": 0.8,\n",- " \"reasons\": health_metric.get(\"issues\", []),\n",- " \"timestamp\": health_metric.get(\"timestamp\", \"\")\n",- " })\n",- " \n",- " alert = {\n",- " \"alert_id\": f\"alert_{health_metric.get('node_id', '')}_{int(time.time())}\",\n",- " \"type\": \"grid_failure_prediction\",\n",- " \"severity\": \"critical\",\n",- " \"node\": health_metric.get(\"node_id\", \"\"),\n",- " \"message\": f\"Potential failure predicted: {', '.join(health_metric.get('issues', []))}\",\n",- " \"timestamp\": health_metric.get(\"timestamp\", \"\")\n",- " }\n",- " alerts.append(alert)\n",- " \n",- " inference_engine.add_fact({\n",- " \"node_id\": health_metric.get(\"node_id\", \"\"),\n",- " \"health_score\": health_metric.get(\"health_score\", 100),\n",- " \"status\": health_metric.get(\"status\", \"\")\n",- " })\n",- "\n",- "# # predicted_failures = inference_engine.forward_chain()\n",- "\n",- "print(f\"Detected {len(anomalies)} grid anomalies\")\n",- "print(f\"Predicted {len(failure_predictions)} potential failures\")\n",- "print(f\"Generated {len(alerts)} alerts\")\n",- "print(f\"Inferred {len(predicted_failures)} failure patterns\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate grid management reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.95}\n",- "\n",- "json_exporter.export_knowledge_graph(grid_kg, os.path.join(temp_dir, \"grid_kg.json\"))\n",- "csv_exporter.export_entities(grid_entities, os.path.join(temp_dir, \"grid_entities.csv\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Grid management detected {len(anomalies)} anomalies and predicted {len(failure_predictions)} potential failures\",\n",- " \"nodes_monitored\": len([e for e in grid_entities if e.get(\"type\") == \"Grid_Node\"]),\n",- " \"anomalies\": len(anomalies),\n",- " \"failure_predictions\": len(failure_predictions),\n",- " \"alerts\": len(alerts),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(grid_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(grid_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(grid_kg, output=\"interactive\")\n",- "\n",- "print(f\"Real-time grid monitoring active\")\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Stream Grid Data \u2192 Parse \u2192 Extract \u2192 Build Temporal Grid KG \u2192 Monitor Health \u2192 Detect Anomalies \u2192 Predict Failures \u2192 Alerts \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/renewable_energy/04_Resource_Optimization.ipynb b/cookbook/use_cases/renewable_energy/04_Resource_Optimization.ipynbdeleted file mode 100644index 95d1ee65..00000000--- a/cookbook/use_cases/renewable_energy/04_Resource_Optimization.ipynb+++ /dev/null@@ -1,464 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/renewable_energy/04_Resource_Optimization.ipynb)\n",- "\n",- "# Resource Optimization Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete resource optimization pipeline: ingest resource data from multiple sources (resource databases, monitoring systems, APIs), extract resource entities, build resource knowledge graph, analyze efficiency metrics, and optimize resource allocation.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Resource Data Sources \u2192 Parse \u2192 Extract Entities \u2192 Build Resource KG \u2192 Analyze Efficiency \u2192 Optimize Allocation \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Resource Data from Multiple Sources\n",- "\n",- "Ingest resource data from resource databases, monitoring systems, and APIs.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD-- "from semantica.conflicts import ConflictDetector\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real resource monitoring APIs\n",- "resource_apis = [\n",- " \"https://api.eia.gov/v2/electricity/operating-generator-capacity/data/\", # EIA Capacity Data\n",- " \"https://www.energy.gov/data\" # US Energy Department Resource Data\n",- "]\n",- "\n",- "resource_feeds = [\n",- " \"https://www.energy.gov/rss\", # US Energy Department RSS\n",- " \"https://feeds.reuters.com/reuters/businessNews\" # Reuters Business (resource news)\n",- "]\n",- "\n",- "# Real database connection for resource data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/resource_db\"\n",- "db_query = \"SELECT resource_id, resource_type, capacity, utilization, efficiency, location, timestamp FROM resources WHERE timestamp > NOW() - INTERVAL '24 hours' ORDER BY timestamp DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample resource data\n",- "resource_file = os.path.join(temp_dir, \"resource_data.json\")\n",- "resource_data = [\n",- " {\n",- " \"resource_id\": \"RES-001\",\n",- " \"resource_type\": \"Solar_Farm\",\n",- " \"capacity_mw\": 100,\n",- " \"utilization_percent\": 75,\n",- " \"efficiency_percent\": 85,\n",- " \"location\": \"California\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=2)).isoformat()\n",- " },\n",- " {\n",- " \"resource_id\": \"RES-002\",\n",- " \"resource_type\": \"Wind_Farm\",\n",- " \"capacity_mw\": 150,\n",- " \"utilization_percent\": 60,\n",- " \"efficiency_percent\": 90,\n",- " \"location\": \"Texas\",\n",- " \"timestamp\": (datetime.now() - timedelta(hours=1)).isoformat()\n",- " },\n",- " {\n",- " \"resource_id\": \"RES-003\",\n",- " \"resource_type\": \"Battery_Storage\",\n",- " \"capacity_mw\": 50,\n",- " \"utilization_percent\": 90,\n",- " \"efficiency_percent\": 95,\n",- " \"location\": \"Nevada\",\n",- " \"timestamp\": datetime.now().isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(resource_file, 'w') as f:\n",- " json.dump(resource_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(resource_file, read_content=True)\n",- "parsed_data = structured_parser.parse_json(resource_file)\n",- "\n",- "# Ingest from resource APIs\n",- "resource_api_list = []\n",- "for api_url in resource_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " resource_api_list.append(api_content)\n",- " print(f\" Ingested resource API: {api_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Resource Data Ingestion Summary:\")\n",- "print(f\" Resource data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Resource APIs: {len(resource_api_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Resource Entities and Build Resource Knowledge Graph\n",- "\n",- "Extract resource entities and build resource knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "resource_entities = []\n",- "resource_relationships = []\n",- "\n",- "# Extract from resource data\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " resource_id = entry.get(\"resource_id\", \"\")\n",- " resource_type = entry.get(\"resource_type\", \"\")\n",- " location = entry.get(\"location\", \"\")\n",- " \n",- " resource_entities.append({\n",- " \"id\": resource_id,\n",- " \"type\": \"Resource\",\n",- " \"name\": resource_id,\n",- " \"properties\": {\n",- " \"resource_type\": resource_type,\n",- " \"capacity_mw\": entry.get(\"capacity_mw\", 0),\n",- " \"utilization_percent\": entry.get(\"utilization_percent\", 0),\n",- " \"efficiency_percent\": entry.get(\"efficiency_percent\", 0),\n",- " \"location\": location,\n",- " \"timestamp\": entry.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " resource_entities.append({\n",- " \"id\": resource_type,\n",- " \"type\": \"Resource_Type\",\n",- " \"name\": resource_type,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " resource_entities.append({\n",- " \"id\": location,\n",- " \"type\": \"Location\",\n",- " \"name\": location,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " resource_relationships.append({\n",- " \"source\": resource_id,\n",- " \"target\": resource_type,\n",- " \"type\": \"is_type\",\n",- " \"properties\": {}\n",- " })\n",- " \n",- " resource_relationships.append({\n",- " \"source\": resource_id,\n",- " \"target\": location,\n",- " \"type\": \"located_at\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "\n",- "resource_kg = builder.build(resource_entities, resource_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(resource_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(resource_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(resource_kg)\n",- "\n",- "print(f\"Extracted {len(resource_entities)} resource entities\")\n",- "print(f\"Extracted {len(resource_relationships)} relationships\")\n",- "print(f\"Built resource knowledge graph with {len(resource_kg.get('entities', []))} entities\")\n",- "print(f\"Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Analyze Resource Efficiency\n",- "\n",- "Analyze resource efficiency using graph analytics and temporal patterns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "\n",- "connectivity = connectivity_analyzer.analyze_connectivity(resource_kg)\n",- "\n",- "start_time = (datetime.now() - timedelta(hours=24)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=resource_kg,\n",- " query=\"Find resource utilization in the last 24 hours\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " resource_kg,\n",- " pattern_type=\"efficiency\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Analyze efficiency metrics\n",- "efficiency_analysis = {}\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " resource_type = entry.get(\"resource_type\", \"\")\n",- " \n",- " if resource_type not in efficiency_analysis:\n",- " efficiency_analysis[resource_type] = {\n",- " \"utilization\": [],\n",- " \"efficiency\": [],\n",- " \"capacity\": [],\n",- " \"resources\": []\n",- " }\n",- " \n",- " efficiency_analysis[resource_type][\"utilization\"].append(entry.get(\"utilization_percent\", 0))\n",- " efficiency_analysis[resource_type][\"efficiency\"].append(entry.get(\"efficiency_percent\", 0))\n",- " efficiency_analysis[resource_type][\"capacity\"].append(entry.get(\"capacity_mw\", 0))\n",- " efficiency_analysis[resource_type][\"resources\"].append(entry.get(\"resource_id\", \"\"))\n",- "\n",- "# Calculate averages\n",- "for resource_type, data in efficiency_analysis.items():\n",- " if data[\"utilization\"]:\n",- " efficiency_analysis[resource_type][\"avg_utilization\"] = sum(data[\"utilization\"]) / len(data[\"utilization\"])\n",- " efficiency_analysis[resource_type][\"avg_efficiency\"] = sum(data[\"efficiency\"]) / len(data[\"efficiency\"])\n",- " efficiency_analysis[resource_type][\"total_capacity\"] = sum(data[\"capacity\"])\n",- "\n",- "print(f\"Efficiency analysis complete\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\" Resource types analyzed: {len(efficiency_analysis)}\")\n",- "for resource_type, data in efficiency_analysis.items():\n",- " print(f\" {resource_type}: Avg Utilization {data.get('avg_utilization', 0):.1f}%, Avg Efficiency {data.get('avg_efficiency', 0):.1f}%, Total Capacity {data.get('total_capacity', 0)} MW\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Optimize Resource Allocation\n",- "\n",- "Optimize resource allocation using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Resource optimization rules\n",- "inference_engine.add_rule(\"IF utilization < 50 AND efficiency > 80 THEN underutilized_resource\")\n",- "inference_engine.add_rule(\"IF utilization > 90 AND efficiency < 70 THEN overutilized_resource\")\n",- "inference_engine.add_rule(\"IF efficiency > 90 AND utilization > 70 THEN optimal_resource\")\n",- "\n",- "# Optimize allocation\n",- "optimization_suggestions = []\n",- "if parsed_data and parsed_data.data:\n",- " for entry in parsed_data.data if isinstance(parsed_data.data, list) else [parsed_data.data]:\n",- " if isinstance(entry, dict):\n",- " resource_id = entry.get(\"resource_id\", \"\")\n",- " utilization = entry.get(\"utilization_percent\", 0)\n",- " efficiency = entry.get(\"efficiency_percent\", 0)\n",- " capacity = entry.get(\"capacity_mw\", 0)\n",- " \n",- " suggestion = {\n",- " \"resource_id\": resource_id,\n",- " \"current_utilization\": utilization,\n",- " \"current_efficiency\": efficiency,\n",- " \"recommendation\": \"\",\n",- " \"optimization_potential\": 0\n",- " }\n",- " \n",- " if utilization < 50 and efficiency > 80:\n",- " suggestion[\"recommendation\"] = \"Increase load allocation\"\n",- " suggestion[\"optimization_potential\"] = (50 - utilization) * capacity / 100\n",- " elif utilization > 90 and efficiency < 70:\n",- " suggestion[\"recommendation\"] = \"Reduce load to improve efficiency\"\n",- " suggestion[\"optimization_potential\"] = (utilization - 80) * capacity / 100\n",- " elif efficiency > 90 and utilization > 70:\n",- " suggestion[\"recommendation\"] = \"Optimal - maintain current allocation\"\n",- " suggestion[\"optimization_potential\"] = 0\n",- " \n",- " optimization_suggestions.append(suggestion)\n",- " \n",- " inference_engine.add_fact({\n",- " \"resource_id\": resource_id,\n",- " \"utilization\": utilization,\n",- " \"efficiency\": efficiency,\n",- " \"capacity\": capacity\n",- " })\n",- "\n",- "# # optimization_insights = inference_engine.forward_chain()\n",- "\n",- "total_optimization_potential = sum(s.get(\"optimization_potential\", 0) for s in optimization_suggestions)\n",- "\n",- "print(f\"Resource allocation optimization complete\")\n",- "print(f\" Resources analyzed: {len(optimization_suggestions)}\")\n",- "print(f\" Optimization suggestions: {len([s for s in optimization_suggestions if s.get('optimization_potential', 0) > 0])}\")\n",- "print(f\" Total optimization potential: {total_optimization_potential:.2f} MW\")\n",- "print(f\" Generated {len(optimization_insights)} optimization insights\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate resource optimization reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.92}\n",- "\n",- "json_exporter.export_knowledge_graph(resource_kg, os.path.join(temp_dir, \"resource_kg.json\"))\n",- "csv_exporter.export_entities(resource_entities, os.path.join(temp_dir, \"resource_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(resource_kg, os.path.join(temp_dir, \"resource_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Resource optimization identified {len(optimization_suggestions)} suggestions with {total_optimization_potential:.2f} MW optimization potential\",\n",- " \"resources_analyzed\": len(optimization_suggestions),\n",- " \"optimization_suggestions\": len([s for s in optimization_suggestions if s.get(\"optimization_potential\", 0) > 0]),\n",- " \"total_optimization_potential\": total_optimization_potential,\n",- " \"insights\": len(optimization_insights),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(resource_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(resource_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(resource_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Resource Data \u2192 Parse \u2192 Extract \u2192 Build Resource KG \u2192 Analyze Efficiency \u2192 Optimize Allocation \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb b/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynbdeleted file mode 100644index 35ff4f3c..00000000--- a/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb+++ /dev/null@@ -1,578 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/01_Supply_Chain_Data_Integration.ipynb)\n",- "\n",- "# Supply Chain Data Integration Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates how to integrate Python/FastMCP MCP servers as data sources for supply chain data ingestion. Connect to supply chain database MCP servers via URL, ingest logistics data, inventory, and shipment information, then build a supply chain knowledge graph.\n",- "\n",- "**IMPORTANT**: This implementation supports ONLY Python-based MCP servers and FastMCP servers. Users can bring their own Python/FastMCP MCP servers via URL connections.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: MCPParser, JSONParser, StructuredDataParser, CSVParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Connect to Supply Chain MCP Server \u2192 Ingest Logistics Data via MCP \u2192 Parse MCP Responses \u2192 Extract Supply Chain Entities \u2192 Build Supply Chain KG \u2192 Analyze Supply Chain \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Connect to Supply Chain Database MCP Server\n",- "\n",- "Connect to a Python/FastMCP MCP server that provides supply chain data via URL. The MCP server can expose resources (inventory databases, shipment records) and tools (logistics queries, inventory checks).\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import MCPIngestor, ingest_mcp, DBIngestor, FileIngestor\n",- "from semantica.parse import MCPParser, JSONParser, StructuredDataParser, CSVParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "# Initialize MCP ingestor\n",- "mcp_ingestor = MCPIngestor()\n",- "\n",- "# Connect to supply chain database MCP server via URL\n",- "# Replace with your actual MCP server URL\n",- "# Example: http://localhost:8000/mcp or https://api.example.com/supplychain-mcp\n",- "supply_chain_mcp_url = \"http://localhost:8000/mcp\"\n",- "\n",- "# Connect to MCP server with authentication (if required)\n",- "mcp_ingestor.connect(\n",- " \"supply_chain_server\",\n",- " url=supply_chain_mcp_url,\n",- " headers={\n",- " \"Authorization\": \"Bearer your_token\",\n",- " \"X-API-Key\": \"your_api_key\"\n",- " } if \"api.example.com\" in supply_chain_mcp_url else {}\n",- ")\n",- "\n",- "# List available resources (inventory databases, shipment records)\n",- "resources = mcp_ingestor.list_available_resources(\"supply_chain_server\")\n",- "print(f\"\\n\ud83d\udcca Available Resources ({len(resources)}):\")\n",- "for resource in resources[:5]: # Show first 5\n",- " print(f\" - {resource.uri}: {resource.name}\")\n",- " if resource.description:\n",- " print(f\" {resource.description[:80]}...\")\n",- "\n",- "# List available tools (logistics queries, inventory checks)\n",- "tools = mcp_ingestor.list_available_tools(\"supply_chain_server\")\n",- "print(f\"\\n\ud83d\udd27 Available Tools ({len(tools)}):\")\n",- "for tool in tools[:5]: # Show first 5\n",- " print(f\" - {tool.name}: {tool.description or 'No description'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Ingest Supply Chain Data from MCP Server\n",- "\n",- "Ingest logistics data, inventory, and shipment information using both resource-based and tool-based methods.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize parsers\n",- "mcp_parser = MCPParser()\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "csv_parser = CSVParser()\n",- "\n",- "supply_chain_data = []\n",- "\n",- "# Method 1: Resource-based ingestion\n",- "# Ingest from MCP resources (inventory databases, shipment records)\n",- "inventory_data = mcp_ingestor.ingest_resources(\n",- " \"supply_chain_server\",\n",- " resource_uris=[\"resource://inventory/database\", \"resource://shipments/records\"]\n",- ")\n",- "\n",- "for item in inventory_data:\n",- " supply_chain_data.append(item)\n",- " print(f\" Ingested resource: {item}\")\n",- "\n",- "# Method 2: Tool-based ingestion\n",- "# Call MCP tools to retrieve data dynamically\n",- "# Example: Query inventory levels\n",- "inventory_levels = mcp_ingestor.ingest_tool_output(\n",- " \"supply_chain_server\",\n",- " tool_name=\"query_inventory\",\n",- " arguments={\n",- " \"warehouse_id\": \"WH001\",\n",- " \"product_category\": \"Electronics\"\n",- " }\n",- ")\n",- "\n",- "if inventory_levels:\n",- " supply_chain_data.append(inventory_levels)\n",- " print(f\" Retrieved inventory levels\")\n",- "\n",- "# Example: Get shipment status\n",- "shipment_status = mcp_ingestor.ingest_tool_output(\n",- " \"supply_chain_server\",\n",- " tool_name=\"get_shipment_status\",\n",- " arguments={\n",- " \"shipment_id\": \"SH001\",\n",- " \"include_tracking\": True\n",- " }\n",- ")\n",- "\n",- "if shipment_status:\n",- " supply_chain_data.append(shipment_status)\n",- " print(f\" Retrieved shipment status\")\n",- "\n",- "# Sample supply chain data (if MCP server is not available)\n",- "if not supply_chain_data:\n",- " sample_data = {\n",- " \"inventory\": [\n",- " {\n",- " \"warehouse_id\": \"WH001\",\n",- " \"product_id\": \"P001\",\n",- " \"product_name\": \"Laptop\",\n",- " \"quantity\": 150,\n",- " \"location\": \"Aisle 3, Shelf 2\",\n",- " \"last_updated\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " },\n",- " {\n",- " \"warehouse_id\": \"WH001\",\n",- " \"product_id\": \"P002\",\n",- " \"product_name\": \"Mouse\",\n",- " \"quantity\": 500,\n",- " \"location\": \"Aisle 1, Shelf 5\",\n",- " \"last_updated\": (datetime.now() - timedelta(hours=12)).isoformat()\n",- " },\n",- " {\n",- " \"warehouse_id\": \"WH002\",\n",- " \"product_id\": \"P001\",\n",- " \"product_name\": \"Laptop\",\n",- " \"quantity\": 200,\n",- " \"location\": \"Aisle 2, Shelf 1\",\n",- " \"last_updated\": datetime.now().isoformat()\n",- " }\n",- " ],\n",- " \"shipments\": [\n",- " {\n",- " \"shipment_id\": \"SH001\",\n",- " \"origin\": \"WH001\",\n",- " \"destination\": \"WH002\",\n",- " \"product_id\": \"P001\",\n",- " \"quantity\": 50,\n",- " \"status\": \"in_transit\",\n",- " \"estimated_arrival\": (datetime.now() + timedelta(days=2)).isoformat(),\n",- " \"timestamp\": (datetime.now() - timedelta(days=1)).isoformat()\n",- " },\n",- " {\n",- " \"shipment_id\": \"SH002\",\n",- " \"origin\": \"WH002\",\n",- " \"destination\": \"Customer A\",\n",- " \"product_id\": \"P002\",\n",- " \"quantity\": 100,\n",- " \"status\": \"delivered\",\n",- " \"estimated_arrival\": (datetime.now() - timedelta(days=1)).isoformat(),\n",- " \"timestamp\": (datetime.now() - timedelta(days=3)).isoformat()\n",- " }\n",- " ]\n",- " }\n",- " supply_chain_data.append(sample_data)\n",- " print(f\" Loaded {len(sample_data['inventory'])} inventory records\")\n",- " print(f\" Loaded {len(sample_data['shipments'])} shipment records\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Total supply chain data items ingested: {len(supply_chain_data)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Parse Supply Chain Data\n",- "\n",- "Parse the supply chain data received from MCP server responses.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "parsed_supply_chain_data = []\n",- "\n",- "# Parse MCP responses\n",- "for data_item in supply_chain_data:\n",- " # Parse MCP response (handles JSON, text, binary)\n",- " if isinstance(data_item, dict):\n",- " parsed_item = data_item\n",- " else:\n",- " parsed_item = mcp_parser.parse_response(data_item, response_type=\"json\")\n",- " \n",- " parsed_supply_chain_data.append(parsed_item)\n",- " print(f\" Parsed data item\")\n",- "\n",- "# Extract inventory and shipments\n",- "inventory_records = []\n",- "shipment_records = []\n",- "\n",- "for item in parsed_supply_chain_data:\n",- " if isinstance(item, dict):\n",- " if \"inventory\" in item:\n",- " inventory_records.extend(item[\"inventory\"])\n",- " elif \"warehouse_id\" in item and \"product_id\" in item:\n",- " inventory_records.append(item)\n",- " elif \"shipments\" in item:\n",- " shipment_records.extend(item[\"shipments\"])\n",- " elif \"shipment_id\" in item:\n",- " shipment_records.append(item)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Extract Supply Chain Entities and Relationships\n",- "\n",- "Extract supply chain entities (warehouses, products, shipments, locations) and relationships from MCP data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "supply_chain_entities = []\n",- "supply_chain_relationships = []\n",- "\n",- "# Extract from inventory records\n",- "for inventory in inventory_records:\n",- " if isinstance(inventory, dict):\n",- " warehouse_id = inventory.get(\"warehouse_id\", \"\")\n",- " product_id = inventory.get(\"product_id\", \"\")\n",- " product_name = inventory.get(\"product_name\", \"\")\n",- " location = inventory.get(\"location\", \"\")\n",- " \n",- " # Warehouse entity\n",- " supply_chain_entities.append({\n",- " \"id\": warehouse_id,\n",- " \"type\": \"Warehouse\",\n",- " \"name\": warehouse_id,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Product entity\n",- " supply_chain_entities.append({\n",- " \"id\": product_id,\n",- " \"type\": \"Product\",\n",- " \"name\": product_name or product_id,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " # Warehouse-Product relationship (inventory)\n",- " supply_chain_relationships.append({\n",- " \"source\": warehouse_id,\n",- " \"target\": product_id,\n",- " \"type\": \"stocks\",\n",- " \"properties\": {\n",- " \"quantity\": inventory.get(\"quantity\", 0),\n",- " \"location\": location,\n",- " \"last_updated\": inventory.get(\"last_updated\", \"\")\n",- " }\n",- " })\n",- "\n",- "# Extract from shipment records\n",- "for shipment in shipment_records:\n",- " if isinstance(shipment, dict):\n",- " shipment_id = shipment.get(\"shipment_id\", \"\")\n",- " origin = shipment.get(\"origin\", \"\")\n",- " destination = shipment.get(\"destination\", \"\")\n",- " product_id = shipment.get(\"product_id\", \"\")\n",- " \n",- " # Shipment entity\n",- " supply_chain_entities.append({\n",- " \"id\": shipment_id,\n",- " \"type\": \"Shipment\",\n",- " \"name\": shipment_id,\n",- " \"properties\": {\n",- " \"status\": shipment.get(\"status\", \"\"),\n",- " \"quantity\": shipment.get(\"quantity\", 0),\n",- " \"estimated_arrival\": shipment.get(\"estimated_arrival\", \"\"),\n",- " \"timestamp\": shipment.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Origin-Destination relationships\n",- " if origin:\n",- " supply_chain_relationships.append({\n",- " \"source\": origin,\n",- " \"target\": shipment_id,\n",- " \"type\": \"ships_from\",\n",- " \"properties\": {\"timestamp\": shipment.get(\"timestamp\", \"\")}\n",- " })\n",- " \n",- " if destination:\n",- " supply_chain_relationships.append({\n",- " \"source\": shipment_id,\n",- " \"target\": destination,\n",- " \"type\": \"ships_to\",\n",- " \"properties\": {\"timestamp\": shipment.get(\"timestamp\", \"\")}\n",- " })\n",- " \n",- " # Shipment-Product relationship\n",- " if product_id:\n",- " supply_chain_relationships.append({\n",- " \"source\": shipment_id,\n",- " \"target\": product_id,\n",- " \"type\": \"contains\",\n",- " \"properties\": {\"quantity\": shipment.get(\"quantity\", 0)}\n",- " })\n",- "\n",- "# Remove duplicates\n",- "seen_entities = set()\n",- "unique_entities = []\n",- "for entity in supply_chain_entities:\n",- " entity_key = (entity[\"id\"], entity[\"type\"])\n",- " if entity_key not in seen_entities:\n",- " seen_entities.add(entity_key)\n",- " unique_entities.append(entity)\n",- "\n",- "supply_chain_entities = unique_entities\n",- "\n",- "print(f\" - Warehouses: {len([e for e in supply_chain_entities if e['type'] == 'Warehouse'])}\")\n",- "print(f\" - Products: {len([e for e in supply_chain_entities if e['type'] == 'Product'])}\")\n",- "print(f\" - Shipments: {len([e for e in supply_chain_entities if e['type'] == 'Shipment'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Build Supply Chain Knowledge Graph\n",- "\n",- "Build a knowledge graph from the extracted supply chain entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Build knowledge graph\n",- "supply_chain_kg = builder.build(supply_chain_entities, supply_chain_relationships)\n",- "\n",- "# Analyze graph structure\n",- "metrics = graph_analyzer.compute_metrics(supply_chain_kg)\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity = connectivity_analyzer.analyze_connectivity(supply_chain_kg)\n",- "\n",- "# Calculate graph metrics\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(supply_chain_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(supply_chain_kg)\n",- "\n",- "print(f\" Entities: {len(supply_chain_kg.get('entities', []))}\")\n",- "print(f\" Relationships: {len(supply_chain_kg.get('relationships', []))}\")\n",- "print(f\" Graph density: {metrics.get('density', 0):.3f}\")\n",- "print(f\" Communities detected: {len(communities)}\")\n",- "print(f\" Connected components: {connectivity.get('connected_components', 0)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Analyze Supply Chain\n",- "\n",- "Analyze supply chain patterns using temporal queries and inference rules.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Temporal analysis\n",- "start_time = (datetime.now() - timedelta(days=30)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=supply_chain_kg,\n",- " query=\"Find shipments in the last 30 days\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "# Inference engine for supply chain rules\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Supply chain analysis rules\n",- "inference_engine.add_rule(\"IF quantity < 100 AND product_type(Electronics) THEN low_stock_alert\")\n",- "inference_engine.add_rule(\"IF status(in_transit) AND days_since_shipment > 5 THEN delayed_shipment\")\n",- "inference_engine.add_rule(\"IF stocks(Warehouse, Product) AND quantity > 500 THEN high_inventory\")\n",- "\n",- "# Add facts from supply chain data\n",- "for inventory in inventory_records:\n",- " if isinstance(inventory, dict):\n",- " inference_engine.add_fact({\n",- " \"warehouse\": inventory.get(\"warehouse_id\", \"\"),\n",- " \"product\": inventory.get(\"product_id\", \"\"),\n",- " \"quantity\": inventory.get(\"quantity\", 0),\n",- " \"product_name\": inventory.get(\"product_name\", \"\")\n",- " })\n",- "\n",- "for shipment in shipment_records:\n",- " if isinstance(shipment, dict):\n",- " days_since = (datetime.now() - datetime.fromisoformat(shipment.get(\"timestamp\", datetime.now().isoformat()))).days\n",- " inference_engine.add_fact({\n",- " \"shipment_id\": shipment.get(\"shipment_id\", \"\"),\n",- " \"status\": shipment.get(\"status\", \"\"),\n",- " \"days_since_shipment\": days_since\n",- " })\n",- "\n",- "# Generate supply chain insights\n",- "# # supply_chain_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\" Temporal entities: {len(temporal_results.get('entities', []))}\")\n",- "print(f\" Supply chain insights: {len(supply_chain_insights)}\")\n",- "\n",- "# Display insights\n",- "for insight in supply_chain_insights[:3]:\n",- " print(f\" - {insight}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Export and Visualize\n",- "\n",- "Export the supply chain knowledge graph and generate visualizations.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import tempfile\n",- "import os\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export knowledge graph\n",- "json_exporter.export_knowledge_graph(supply_chain_kg, os.path.join(temp_dir, \"supply_chain_kg.json\"))\n",- "csv_exporter.export_entities(supply_chain_entities, os.path.join(temp_dir, \"supply_chain_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(supply_chain_kg, os.path.join(temp_dir, \"supply_chain_kg.rdf\"))\n",- "\n",- "# Generate report\n",- "report_data = {\n",- " \"summary\": f\"Supply chain data integration from MCP server identified {len(supply_chain_insights)} insights\",\n",- " \"warehouses\": len([e for e in supply_chain_entities if e['type'] == 'Warehouse']),\n",- " \"products\": len([e for e in supply_chain_entities if e['type'] == 'Product']),\n",- " \"shipments\": len([e for e in supply_chain_entities if e['type'] == 'Shipment']),\n",- " \"inventory_records\": len(inventory_records),\n",- " \"insights\": len(supply_chain_insights)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "print(f\" JSON: {os.path.join(temp_dir, 'supply_chain_kg.json')}\")\n",- "print(f\" CSV: {os.path.join(temp_dir, 'supply_chain_entities.csv')}\")\n",- "print(f\" RDF: {os.path.join(temp_dir, 'supply_chain_kg.rdf')}\")\n",- "\n",- "# Visualize\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(supply_chain_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(supply_chain_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(supply_chain_kg, output=\"interactive\")\n",- "\n",- "\n",- "# Cleanup: Disconnect from MCP server\n",- "mcp_ingestor.disconnect(\"supply_chain_server\")\n",- "print(\" Disconnected from MCP server\")\n",- "\n",- "print(f\"\ud83d\udcca Total modules used: 20+\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb b/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynbdeleted file mode 100644index 665ffb47..00000000--- a/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb+++ /dev/null@@ -1,739 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/supply_chain/02_Supply_Chain_Risk_Management.ipynb)\n",- "\n",- "# Supply Chain Risk Management with Semantica\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates using **Semantica as the core framework** to transform supply chains into dynamic, interconnected networks for real-time visualization, analysis, and proactive risk management.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "### Why Semantica?\n",- "\n",- "Semantica provides comprehensive graph technology capabilities essential for supply chain risk management:\n",- "\n",- "- **Graph Modeling**: Semantica's KG modules naturally model complex supply chain relationships and dependencies\n",- "- **Real-Time Analysis**: Semantica's GraphAnalyzer enables real-time network analysis and risk assessment\n",- "- **Cascade Effect Analysis**: Semantica's ConnectivityAnalyzer identifies how disruptions cascade through networks\n",- "- **Graph Algorithms**: Semantica's graph analytics provide betweenness centrality for alternative sourcing identification\n",- "- **Risk Clustering**: Semantica's community detection identifies supplier risk clusters\n",- "- **Visualization**: Semantica's visualization modules provide real-time supply chain network visualization\n",- "\n",- "### Key Features\n",- "\n",- "- Graph modeling of complex supply chain relationships and dependencies using Semantica\n",- "- Real-time visualization of supply chain networks\n",- "- Risk analysis for tariffs, extreme weather, component shortages\n",- "- Cascade effect analysis through network\n",- "- Alternative sourcing identification using Semantica's graph algorithms (betweenness centrality)\n",- "- Product redesign impact modeling\n",- "- Supplier risk clustering\n",- "\n",- "### Semantica Modules Used (15+)\n",- "\n",- "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (supply chain data from multiple sources)\n",- "- **Parse**: StructuredDataParser, JSONParser, CSVParser (BOM data, supplier data, tariff data)\n",- "- **Normalize**: TextNormalizer, DataNormalizer (for data standardization)\n",- "- **Semantic Extract**: RelationExtractor, TripletExtractor (supplier relationships, dependencies, risk factors)\n",- "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (supply chain graph construction)\n",- "- **Graph Analytics**: Use Semantica's GraphAnalyzer for community detection, centrality measures (PageRank, Betweenness, Closeness)\n",- "- **Embeddings**: EmbeddingGenerator (for supplier similarity, risk clustering)\n",- "- **Vector Store**: VectorStore, HybridSearch (for supplier search and risk analysis)\n",- "- **Reasoning**: Reasoner (Legacy), RuleManager (for risk propagation rules, tariff impact analysis)\n",- "- **Seed**: SeedDataManager (for loading supplier master data)\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer (network visualization, risk heatmaps, supply chain dashboards)\n",- "- **Export**: JSONExporter, CSVExporter, ReportGenerator (for risk reports)\n",- "- **Pipeline**: PipelineBuilder, ExecutionEngine (for end-to-end supply chain analysis pipeline)\n",- "\n",- "### Pipeline Overview\n",- "\n",- "**Supply Chain Data \u2192 Parse \u2192 Extract Relationships \u2192 Build Supply Chain Graph \u2192 Analyze Risks \u2192 Identify Alternatives \u2192 Visualize \u2192 Generate Reports**\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "---\n",- "\n",- "## Step 1: Setup and Import Semantica Modules\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Import all Semantica modules - using Semantica as the core framework\n",- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",- "from semantica.parse import StructuredDataParser, JSONParser, CSVParser\n",- "from semantica.normalize import TextNormalizer, DataNormalizer\n",- "from semantica.semantic_extract import RelationExtractor, TripletExtractor\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",- "from semantica.embeddings import EmbeddingGenerator\n",- "from semantica.vector_store import VectorStore, HybridSearch\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager\n",- "from semantica.seed import SeedDataManager\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer\n",- "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",- "from semantica.pipeline import PipelineBuilder, ExecutionEngine\n",- "\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "import numpy as np\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Ingest Supply Chain Data Using Semantica\n",- "\n",- "Using Semantica's ingest modules to load supply chain data including BOM (Bill of Materials), supplier information, and tariff data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica ingestors\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "stream_ingestor = StreamIngestor()\n",- "seed_loader = SeedDataManager()\n",- "\n",- "# Create temporary directory for sample data\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample BOM (Bill of Materials) data\n",- "bom_data = {\n",- " \"product_id\": \"PROD-001\",\n",- " \"product_name\": \"Electronic Device\",\n",- " \"components\": [\n",- " {\"component_id\": \"COMP-001\", \"name\": \"Processor\", \"supplier_id\": \"SUP-001\", \"quantity\": 1},\n",- " {\"component_id\": \"COMP-002\", \"name\": \"Memory\", \"supplier_id\": \"SUP-002\", \"quantity\": 2},\n",- " {\"component_id\": \"COMP-003\", \"name\": \"Display\", \"supplier_id\": \"SUP-003\", \"quantity\": 1},\n",- " {\"component_id\": \"COMP-004\", \"name\": \"Battery\", \"supplier_id\": \"SUP-001\", \"quantity\": 1}\n",- " ]\n",- "}\n",- "\n",- "# Sample supplier data\n",- "supplier_data = {\n",- " \"suppliers\": [\n",- " {\n",- " \"supplier_id\": \"SUP-001\",\n",- " \"name\": \"Global Electronics Inc\",\n",- " \"location\": \"China\",\n",- " \"risk_factors\": [\"tariff_impact\", \"weather_risk\"],\n",- " \"alternatives\": [\"SUP-005\", \"SUP-006\"]\n",- " },\n",- " {\n",- " \"supplier_id\": \"SUP-002\",\n",- " \"name\": \"Memory Solutions Ltd\",\n",- " \"location\": \"South Korea\",\n",- " \"risk_factors\": [\"tariff_impact\"],\n",- " \"alternatives\": [\"SUP-007\"]\n",- " },\n",- " {\n",- " \"supplier_id\": \"SUP-003\",\n",- " \"name\": \"Display Tech Corp\",\n",- " \"location\": \"Taiwan\",\n",- " \"risk_factors\": [\"weather_risk\"],\n",- " \"alternatives\": [\"SUP-008\"]\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Sample tariff data\n",- "tariff_data = {\n",- " \"tariffs\": [\n",- " {\n",- " \"tariff_id\": \"TAR-001\",\n",- " \"country\": \"China\",\n",- " \"category\": \"Electronics\",\n",- " \"rate\": 0.25,\n",- " \"effective_date\": \"2025-01-01\",\n",- " \"impacted_suppliers\": [\"SUP-001\"]\n",- " }\n",- " ]\n",- "}\n",- "\n",- "# Save sample data\n",- "bom_file = os.path.join(temp_dir, \"bom.json\")\n",- "supplier_file = os.path.join(temp_dir, \"suppliers.json\")\n",- "tariff_file = os.path.join(temp_dir, \"tariffs.json\")\n",- "\n",- "with open(bom_file, 'w') as f:\n",- " json.dump(bom_data, f, indent=2)\n",- "\n",- "with open(supplier_file, 'w') as f:\n",- " json.dump(supplier_data, f, indent=2)\n",- "\n",- "with open(tariff_file, 'w') as f:\n",- " json.dump(tariff_data, f, indent=2)\n",- "\n",- "# Ingest using Semantica FileIngestor\n",- "bom_file_obj = file_ingestor.ingest_file(bom_file, read_content=True)\n",- "supplier_file_obj = file_ingestor.ingest_file(supplier_file, read_content=True)\n",- "tariff_file_obj = file_ingestor.ingest_file(tariff_file, read_content=True)\n",- "\n",- "# Load supplier master data using Semantica SeedDataManager\n",- "supplier_seed_data = seed_loader.load_from_json(supplier_file)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica parsers and normalizers\n",- "structured_parser = StructuredDataParser()\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "text_normalizer = TextNormalizer()\n",- "data_normalizer = DataNormalizer()\n",- "\n",- "# Parse BOM data using Semantica\n",- "parsed_bom = structured_parser.parse_data(bom_file, data_format=\"json\")\n",- "bom_data_parsed = parsed_bom.get(\"data\") if isinstance(parsed_bom, dict) else parsed_bom\n",- "\n",- "# Parse supplier data using Semantica\n",- "parsed_suppliers = structured_parser.parse_data(supplier_file, data_format=\"json\")\n",- "supplier_data_parsed = parsed_suppliers.get(\"data\") if isinstance(parsed_suppliers, dict) else parsed_suppliers\n",- "\n",- "# Parse tariff data using Semantica\n",- "parsed_tariffs = structured_parser.parse_data(tariff_file, data_format=\"json\")\n",- "tariff_data_parsed = parsed_tariffs.get(\"data\") if isinstance(parsed_tariffs, dict) else parsed_tariffs\n",- "\n",- "# Normalize supplier names using Semantica\n",- "if isinstance(supplier_data_parsed, dict):\n",- " for supplier in supplier_data_parsed.get('suppliers', []):\n",- " supplier['normalized_name'] = text_normalizer.normalize_text(supplier.get('name', ''))\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Extract Supply Chain Relationships Using Semantica\n",- "\n",- "Using Semantica's semantic extraction modules to extract supplier relationships, dependencies, and risk factors.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica extractors\n",- "relation_extractor = RelationExtractor()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "# Build supply chain entities and relationships\n",- "supply_chain_entities = []\n",- "supply_chain_relationships = []\n",- "\n",- "# Add product entity\n",- "if isinstance(bom_data_parsed, dict):\n",- " supply_chain_entities.append({\n",- " \"id\": bom_data_parsed.get('product_id', ''),\n",- " \"type\": \"Product\",\n",- " \"name\": bom_data_parsed.get('product_name', ''),\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Add component entities and relationships\n",- "if isinstance(bom_data_parsed, dict):\n",- " for component in bom_data_parsed.get('components', []):\n",- " supply_chain_entities.append({\n",- " \"id\": component.get('component_id', ''),\n",- " \"type\": \"Component\",\n",- " \"name\": component.get('name', ''),\n",- " \"properties\": {\n",- " \"quantity\": component.get('quantity', 0)\n",- " }\n",- " })\n",- " \n",- " # Product-Component relationship\n",- " supply_chain_relationships.append({\n",- " \"source\": bom_data_parsed.get('product_id', ''),\n",- " \"target\": component.get('component_id', ''),\n",- " \"type\": \"contains\",\n",- " \"properties\": {\n",- " \"quantity\": component.get('quantity', 0)\n",- " }\n",- " })\n",- " \n",- " # Component-Supplier relationship\n",- " supply_chain_relationships.append({\n",- " \"source\": component.get('component_id', ''),\n",- " \"target\": component.get('supplier_id', ''),\n",- " \"type\": \"supplied_by\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Add supplier entities\n",- "if isinstance(supplier_data_parsed, dict):\n",- " for supplier in supplier_data_parsed.get('suppliers', []):\n",- " supply_chain_entities.append({\n",- " \"id\": supplier.get('supplier_id', ''),\n",- " \"type\": \"Supplier\",\n",- " \"name\": supplier.get('name', ''),\n",- " \"properties\": {\n",- " \"location\": supplier.get('location', ''),\n",- " \"risk_factors\": supplier.get('risk_factors', [])\n",- " }\n",- " })\n",- " \n",- " # Alternative supplier relationships\n",- " for alt_supplier in supplier.get('alternatives', []):\n",- " supply_chain_relationships.append({\n",- " \"source\": supplier.get('supplier_id', ''),\n",- " \"target\": alt_supplier,\n",- " \"type\": \"alternative_to\",\n",- " \"properties\": {}\n",- " })\n",- "\n",- "# Add tariff entities and relationships\n",- "if isinstance(tariff_data_parsed, dict):\n",- " for tariff in tariff_data_parsed.get('tariffs', []):\n",- " supply_chain_entities.append({\n",- " \"id\": tariff.get('tariff_id', ''),\n",- " \"type\": \"Tariff\",\n",- " \"name\": f\"Tariff {tariff.get('country', '')}\",\n",- " \"properties\": {\n",- " \"rate\": tariff.get('rate', 0),\n",- " \"effective_date\": tariff.get('effective_date', '')\n",- " }\n",- " })\n",- " \n",- " # Tariff-Supplier relationship\n",- " for supplier_id in tariff.get('impacted_suppliers', []):\n",- " supply_chain_relationships.append({\n",- " \"source\": tariff.get('tariff_id', ''),\n",- " \"target\": supplier_id,\n",- " \"type\": \"impacts\",\n",- " \"properties\": {\n",- " \"impact_type\": \"tariff\"\n",- " }\n",- " })\n",- "\n",- "print(f\" - Products: {len([e for e in supply_chain_entities if e.get('type') == 'Product'])}\")\n",- "print(f\" - Components: {len([e for e in supply_chain_entities if e.get('type') == 'Component'])}\")\n",- "print(f\" - Suppliers: {len([e for e in supply_chain_entities if e.get('type') == 'Supplier'])}\")\n",- "print(f\" - Tariffs: {len([e for e in supply_chain_entities if e.get('type') == 'Tariff'])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Build Supply Chain Knowledge Graph Using Semantica\n",- "\n",- "Using Semantica's KG modules to build a supply chain knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica KG builders and analyzers\n",- "graph_builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "# Build supply chain knowledge graph using Semantica\n",- "supply_chain_kg = graph_builder.build(supply_chain_entities, supply_chain_relationships)\n",- "\n",- "# Analyze the graph using Semantica\n",- "kg_metrics = graph_analyzer.compute_metrics(supply_chain_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(supply_chain_kg)\n",- "\n",- "print(f\" - Entities: {len(supply_chain_kg.get('entities', []))}\")\n",- "print(f\" - Relationships: {len(supply_chain_kg.get('relationships', []))}\")\n",- "print(f\" - Graph density: {kg_metrics.get('density', 0):.4f}\")\n",- "print(f\" - Connected components: {connectivity.get('num_components', 0)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Analyze Supply Chain Risks Using Semantica Graph Analytics\n",- "\n",- "Using Semantica's GraphAnalyzer to perform risk analysis including community detection, centrality measures, and cascade effect analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Perform graph analytics using Semantica\n",- "\n",- "# 1. Community detection for supplier risk clustering\n",- "communities = graph_analyzer.detect_communities(supply_chain_kg, method=\"louvain\")\n",- "\n",- "# 2. Centrality measures for alternative sourcing identification\n",- "pagerank_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"pagerank\")\n",- "betweenness_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"betweenness\")\n",- "closeness_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"closeness\")\n",- "\n",- "# 3. Identify critical suppliers (high betweenness = alternative sourcing options)\n",- "critical_suppliers = sorted(\n",- " [(node, score) for node, score in betweenness_centrality.items() if node.startswith('SUP-')],\n",- " key=lambda x: x[1],\n",- " reverse=True\n",- ")[:5]\n",- "\n",- "# 4. Cascade effect analysis - identify suppliers at risk\n",- "at_risk_suppliers = []\n",- "for entity in supply_chain_entities:\n",- " if entity.get('type') == 'Supplier':\n",- " risk_factors = entity.get('properties', {}).get('risk_factors', [])\n",- " if risk_factors:\n",- " at_risk_suppliers.append({\n",- " \"supplier_id\": entity.get('id'),\n",- " \"supplier_name\": entity.get('name'),\n",- " \"risk_factors\": risk_factors,\n",- " \"betweenness_centrality\": betweenness_centrality.get(entity.get('id'), 0)\n",- " })\n",- "\n",- "print(f\" - Communities detected: {communities.get('num_communities', 0)}\")\n",- "print(f\" - Critical suppliers (high betweenness): {len(critical_suppliers)}\")\n",- "print(f\" - At-risk suppliers: {len(at_risk_suppliers)}\")\n",- "print(f\"\\nTop Critical Suppliers (Alternative Sourcing Options):\")\n",- "for supplier_id, score in critical_suppliers:\n",- " supplier_name = next((e.get('name', '') for e in supply_chain_entities if e.get('id') == supplier_id), 'Unknown')\n",- " print(f\" - {supplier_name} ({supplier_id}): {score:.4f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Implement Risk Propagation Rules Using Semantica Reasoning\n",- "\n",- "Using Semantica's reasoning modules to implement risk propagation rules for tariff impacts and cascade effects.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica reasoning modules\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "\n",- "# Define risk propagation rules using Semantica\n",- "risk_rules = [\n",- " {\n",- " \"rule_id\": \"tariff_impact_rule\",\n",- " \"condition\": \"IF supplier has tariff_impact AND supplier supplies component THEN component has cost_increase\",\n",- " \"action\": \"propagate_cost_increase\"\n",- " },\n",- " {\n",- " \"rule_id\": \"cascade_effect_rule\",\n",- " \"condition\": \"IF supplier has risk_factor AND supplier is critical THEN product has supply_risk\",\n",- " \"action\": \"flag_supply_risk\"\n",- " },\n",- " {\n",- " \"rule_id\": \"alternative_sourcing_rule\",\n",- " \"condition\": \"IF supplier has high_betweenness_centrality THEN supplier is alternative_sourcing_option\",\n",- " \"action\": \"identify_alternative\"\n",- " }\n",- "]\n",- "\n",- "# Add rules using Semantica\n",- "for rule in risk_rules:\n",- " rule_manager.add_rule(rule)\n",- "\n",- "# # # Apply risk propagation using Semantica InferenceEngine\n",- "risk_analysis_results = inference_engine.infer(\n",- " knowledge_graph=supply_chain_kg,\n",- " rules=risk_rules,\n",- " facts=at_risk_suppliers\n",- ")\n",- "\n",- "print(f\" - Rules defined: {len(risk_rules)}\")\n",- "print(f\" - Risk analysis results: {len(risk_analysis_results) if isinstance(risk_analysis_results, list) else 1}\")\n",- "print(f\" - Cascade effects identified: Enabled\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": []- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica visualizers\n",- "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "# Visualize supply chain network using Semantica\n",- "network_fig = kg_visualizer.visualize_network(\n",- " supply_chain_kg,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize communities (supplier risk clusters) using Semantica\n",- "communities_data = {\n",- " \"graph\": supply_chain_kg,\n",- " \"communities\": communities\n",- "}\n",- "communities_fig = kg_visualizer.visualize_communities(\n",- " supply_chain_kg,\n",- " communities,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Visualize centrality rankings using Semantica\n",- "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",- " betweenness_centrality,\n",- " centrality_type=\"betweenness\",\n",- " top_n=10,\n",- " output=\"interactive\"\n",- ")\n",- "\n",- "# Create risk dashboard data\n",- "risk_dashboard_data = {\n",- " \"overall_score\": 0.75,\n",- " \"tariff_risk_score\": 0.80,\n",- " \"weather_risk_score\": 0.60,\n",- " \"supply_risk_score\": 0.70\n",- "}\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Generate Risk Reports Using Semantica\n",- "\n",- "Using Semantica's export modules to generate comprehensive risk reports.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize Semantica exporters\n",- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "# Export supply chain graph as JSON using Semantica\n",- "kg_json_file = os.path.join(temp_dir, \"supply_chain_kg.json\")\n",- "json_exporter.export(supply_chain_kg, kg_json_file)\n",- "\n",- "# Export at-risk suppliers as CSV using Semantica\n",- "at_risk_suppliers_csv = os.path.join(temp_dir, \"at_risk_suppliers.csv\")\n",- "csv_exporter.export(at_risk_suppliers, at_risk_suppliers_csv)\n",- "\n",- "# Generate comprehensive risk report using Semantica\n",- "risk_report_data = {\n",- " \"title\": \"Supply Chain Risk Management Report\",\n",- " \"knowledge_graph_metrics\": kg_metrics,\n",- " \"at_risk_suppliers\": at_risk_suppliers,\n",- " \"critical_suppliers\": critical_suppliers,\n",- " \"risk_analysis\": risk_analysis_results,\n",- " \"risk_dashboard\": risk_dashboard_data\n",- "}\n",- "risk_report_file = os.path.join(temp_dir, \"supply_chain_risk_report.html\")\n",- "report_generator.generate_report(risk_report_data, risk_report_file, format=\"html\")\n",- "\n",- "print(f\" - Knowledge graph JSON: {kg_json_file}\")\n",- "print(f\" - At-risk suppliers CSV: {at_risk_suppliers_csv}\")\n",- "print(f\" - Risk report HTML: {risk_report_file}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 10: Complete Pipeline Orchestration Using Semantica\n",- "\n",- "Using Semantica's pipeline module to orchestrate the complete supply chain risk analysis pipeline.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Build complete pipeline using Semantica PipelineBuilder\n",- "pipeline_builder = PipelineBuilder()\n",- "\n",- "def ingest_handler(data, **config):\n",- " source_dir = config.get(\"source\", temp_dir)\n",- " files = []\n",- " try:\n",- " files = [os.path.join(source_dir, f) for f in os.listdir(source_dir)]\n",- " except Exception:\n",- " pass\n",- " return {**data, \"files\": files}\n",- "def parse_handler(data, **config):\n",- " records = []\n",- " files = data.get(\"files\", [])\n",- " for fp in files:\n",- " try:\n",- " with open(fp, \"r\", encoding=\"utf-8\") as f:\n",- " records.append(json.load(f))\n",- " except Exception:\n",- " pass\n",- " return {**data, \"records\": records}\n",- "def normalize_handler(data, **config):\n",- " records = data.get(\"records\", [])\n",- " normalized = records\n",- " return {**data, \"normalized\": normalized}\n",- "def extract_handler(data, **config):\n",- " normalized = data.get(\"normalized\", [])\n",- " entities = data.get(\"entities\") or []\n",- " relationships = data.get(\"relationships\") or []\n",- " return {**data, \"entities\": entities, \"relationships\": relationships}\n",- "def build_kg_handler(data, **config):\n",- " ents = data.get(\"entities\", [])\n",- " rels = data.get(\"relationships\", [])\n",- " kg = graph_builder.build({\"entities\": ents, \"relationships\": rels})\n",- " return {**data, \"supply_chain_kg\": kg}\n",- "def analyze_risks_handler(data, **config):\n",- " kg = data.get(\"supply_chain_kg\")\n",- " risks = graph_analyzer.compute_metrics(kg) if kg is not None else {}\n",- " return {**data, \"risk_analysis\": risks}\n",- "def propagate_risks_handler(data, **config):\n",- " kg = data.get(\"supply_chain_kg\")\n",- " propagation = reasoning_engine.infer(knowledge_graph=kg, rules=[]) if kg is not None else {}\n",- " return {**data, \"risk_propagation\": propagation}\n",- "def visualize_handler(data, **config):\n",- " kg = data.get(\"supply_chain_kg\")\n",- " fig = KGVisualizer().visualize_network(kg) if kg is not None else None\n",- " return {**data, \"visualization\": fig}\n",- "def report_handler(data, **config):\n",- " report = ReportGenerator().generate({\"risks\": data.get(\"risk_analysis\"), \"propagation\": data.get(\"risk_propagation\")})\n",- " return {**data, \"report\": report}\n",- "supply_chain_pipeline = (\n",- " pipeline_builder\n",- " .add_step(\"ingest\", \"ingest\", handler=ingest_handler, source=temp_dir)\n",- " .add_step(\"parse\", \"parse\", dependencies=[\"ingest\"], handler=parse_handler, formats=[\"json\"])\n",- " .add_step(\"normalize\", \"normalize\", dependencies=[\"parse\"], handler=normalize_handler)\n",- " .add_step(\"extract\", \"extract\", dependencies=[\"normalize\"], handler=extract_handler)\n",- " .add_step(\"build_kg\", \"build_kg\", dependencies=[\"extract\"], handler=build_kg_handler)\n",- " .add_step(\"analyze_risks\", \"analyze_graph\", dependencies=[\"build_kg\"], handler=analyze_risks_handler)\n",- " .add_step(\"propagate_risks\", \"reasoning\", dependencies=[\"build_kg\"], handler=propagate_risks_handler)\n",- " .add_step(\"visualize\", \"visualize\", dependencies=[\"analyze_risks\"], handler=visualize_handler)\n",- " .add_step(\"generate_report\", \"report\", dependencies=[\"visualize\"], handler=report_handler)\n",- " .build()\n",- ")\n",- "\n",- "execution_engine = ExecutionEngine()\n",- "input_data = {\"entities\": supply_chain_entities if 'supply_chain_entities' in globals() else [], \"relationships\": supply_chain_relationships if 'supply_chain_relationships' in globals() else []}\n",- "pipeline_result = execution_engine.execute_pipeline(supply_chain_pipeline, data=input_data)\n",- "\n",- "print(f\" - Pipeline steps: {len(supply_chain_pipeline.steps)}\")\n",- "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion and Best Practices\n",- "\n",- "### Key Takeaways\n",- "\n",- "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for supply chain risk management\n",- "2. **Graph Modeling**: Semantica's KG modules naturally model complex supply chain relationships and dependencies\n",- "3. **Risk Analysis**: Semantica's GraphAnalyzer provides powerful algorithms for risk identification and alternative sourcing\n",- "4. **Cascade Effects**: Semantica's ConnectivityAnalyzer identifies how disruptions cascade through supply networks\n",- "5. **Real-Time Visualization**: Semantica's visualization modules provide real-time supply chain network visualization\n",- "6. **Risk Propagation**: Semantica's Reasoning modules enable rule-based risk propagation analysis\n",- "\n",- "### Semantica-Specific Performance Considerations\n",- "\n",- "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient centrality and community detection on large supply chains\n",- "- **Batch Processing**: Leverage Semantica's batch processing for large-scale supplier data ingestion\n",- "- **Caching**: Utilize Semantica's caching for frequently accessed supplier relationships\n",- "- **Parallel Execution**: Use Semantica's ExecutionEngine for parallel risk analysis\n",- "\n",- "### Deployment Recommendations Using Semantica\n",- "\n",- "1. **Production Setup**:\n",- " - Use Semantica's configuration management for supply chain data sources\n",- " - Leverage Semantica's Pipeline module for automated risk monitoring\n",- " - Use Semantica's StreamIngestor for real-time supply chain data updates\n",- "\n",- "2. **Scalability**:\n",- " - Use Semantica's batch processing for large supplier networks\n",- " - Leverage Semantica's graph analytics optimizations\n",- " - Utilize Semantica's parallel execution for concurrent risk analysis\n",- "\n",- "3. **Real-Time Monitoring**:\n",- " - Use Semantica's StreamIngestor for real-time tariff and weather updates\n",- " - Leverage Semantica's visualization modules for live dashboards\n",- " - Utilize Semantica's reasoning modules for automated risk alerts\n",- "\n",- "### How Semantica's Architecture Benefits Supply Chain Risk Management\n",- "\n",- "- **Natural Graph Modeling**: Semantica's graph structure naturally represents supply chain relationships\n",- "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms (centrality, communities, connectivity)\n",- "- **Extensibility**: Semantica's registry system enables custom risk analysis methods\n",- "- **Integration**: Semantica's unified framework simplifies integration with existing supply chain systems\n",- "- **Performance**: Semantica's optimized algorithms handle large-scale supply chain networks efficiently\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynb b/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynbdeleted file mode 100644index a763bd69..00000000--- a/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynb+++ /dev/null@@ -1,389 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/01_Market_Data_Analysis.ipynb)\n",- "\n",- "# Market Data Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete market data analysis pipeline: stream market data from multiple sources (trading APIs, financial feeds, databases), build temporal market knowledge graph, analyze patterns, and predict trends.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Stream Market Data \u2192 Parse \u2192 Extract Entities \u2192 Build Temporal Market KG \u2192 Analyze Patterns \u2192 Predict Trends \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Stream Market Data from Multiple Sources\n",- "\n",- "Stream market data from trading APIs, financial feeds, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import StreamIngestor, FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "stream_ingestor = StreamIngestor()\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real streaming sources for market data\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"market_data\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"market_analysis\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"trading_events\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real market data APIs\n",- "market_apis = [\n",- " \"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/minute/2024-01-15/2024-01-15\", # Polygon.io\n",- " \"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=AAPL&interval=1min&apikey=demo\", # Alpha Vantage\n",- " \"https://api.github.com/repos/ranaroussi/yfinance\" # Yahoo Finance API\n",- "]\n",- "\n",- "financial_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\",\n",- " \"https://feeds.bloomberg.com/markets/news.rss\"\n",- "]\n",- "\n",- "# Real database connection for market data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/market_data_db\"\n",- "db_query = \"SELECT symbol, price, volume, timestamp FROM market_data WHERE timestamp > NOW() - INTERVAL '1 hour' ORDER BY timestamp DESC LIMIT 1000\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample streaming market data\n",- "market_data_file = os.path.join(temp_dir, \"market_data_stream.json\")\n",- "market_stream = [\n",- " {\n",- " \"symbol\": \"AAPL\",\n",- " \"price\": 175.50,\n",- " \"volume\": 1000000,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=5)).isoformat()\n",- " },\n",- " {\n",- " \"symbol\": \"MSFT\",\n",- " \"price\": 380.25,\n",- " \"volume\": 800000,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=4)).isoformat()\n",- " },\n",- " {\n",- " \"symbol\": \"GOOGL\",\n",- " \"price\": 142.80,\n",- " \"volume\": 1200000,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=3)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(market_data_file, 'w') as f:\n",- " json.dump(market_stream, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(market_data_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(market_data_file, data_format=\"json\")\n",- "\n",- "# Ingest from financial feeds\n",- "financial_feed_list = []\n",- "for feed_url in financial_feeds[:2]:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " financial_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Market data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Financial feeds: {len(financial_feed_list)}\")\n",- "print(f\" Streaming sources: {len(stream_sources)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Market Entities and Build Temporal Knowledge Graph\n",- "\n",- "Extract market entities and build temporal knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "market_entities = []\n",- "market_relationships = []\n",- "\n",- "# Extract from market data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " for market_entry in parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")]:\n",- " if isinstance(market_entry, dict):\n",- " symbol = market_entry.get(\"symbol\", \"\")\n",- " \n",- " market_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {\n",- " \"price\": market_entry.get(\"price\", 0),\n",- " \"volume\": market_entry.get(\"volume\", 0),\n",- " \"timestamp\": market_entry.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Price events\n",- " if market_entry.get(\"price\", 0) > 0:\n",- " market_relationships.append({\n",- " \"source\": symbol,\n",- " \"target\": f\"{symbol}_price_{market_entry.get('timestamp', '')}\",\n",- " \"type\": \"has_price\",\n",- " \"properties\": {\n",- " \"price\": market_entry.get(\"price\", 0),\n",- " \"timestamp\": market_entry.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "market_kg = builder.build(market_entities, market_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(market_kg)\n",- "\n",- "print(f\"Extracted {len(market_entities)} market entities\")\n",- "print(f\"Extracted {len(market_relationships)} relationships\")\n",- "print(f\"Built temporal market knowledge graph with {len(market_kg.get('entities', []))} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Analyze Market Patterns\n",- "\n",- "Analyze market patterns using temporal analysis and graph analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "start_time = (datetime.now() - timedelta(hours=1)).isoformat()\n",- "end_time = datetime.now().isoformat()\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=market_kg,\n",- " query=\"Find market movements in the last hour\",\n",- " start_time=start_time,\n",- " end_time=end_time\n",- ")\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " market_kg,\n",- " pattern_type=\"trend\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(market_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(market_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(market_kg)\n",- "\n",- "print(f\"Temporal query returned {len(temporal_results.get('entities', []))} entities\")\n",- "print(f\"Detected {len(temporal_patterns)} temporal patterns\")\n",- "print(f\"Central stocks: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n",- "print(f\"Communities: {len(communities)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Predict Market Trends\n",- "\n",- "Predict market trends using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Market trend prediction rules\n",- "inference_engine.add_rule(\"IF volume > 1000000 AND price_change > 0 THEN bullish_signal\")\n",- "inference_engine.add_rule(\"IF volume > 1000000 AND price_change < 0 THEN bearish_signal\")\n",- "inference_engine.add_rule(\"IF multiple stocks show same pattern THEN market_trend\")\n",- "\n",- "# Add facts from market data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " for market_entry in parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")]:\n",- " if isinstance(market_entry, dict):\n",- " inference_engine.add_fact({\n",- " \"symbol\": market_entry.get(\"symbol\", \"\"),\n",- " \"volume\": market_entry.get(\"volume\", 0),\n",- " \"price\": market_entry.get(\"price\", 0)\n",- " })\n",- "\n",- "# # trend_predictions = inference_engine.forward_chain()\n",- "\n",- "print(f\"Generated {len(trend_predictions)} market trend predictions\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate market analysis reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.96}\n",- "\n",- "json_exporter.export_knowledge_graph(market_kg, os.path.join(temp_dir, \"market_kg.json\"))\n",- "csv_exporter.export_entities(market_entities, os.path.join(temp_dir, \"market_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(market_kg, os.path.join(temp_dir, \"market_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Market data analysis identified {len(trend_predictions)} trend predictions from {len(market_entities)} entities\",\n",- " \"stocks_analyzed\": len(market_entities),\n",- " \"patterns\": len(temporal_patterns),\n",- " \"predictions\": len(trend_predictions),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(market_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(market_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(market_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Stream Market Data \u2192 Parse \u2192 Extract \u2192 Build Temporal KG \u2192 Analyze Patterns \u2192 Predict Trends \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb b/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynbdeleted file mode 100644index a84c4f6d..00000000--- a/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb+++ /dev/null@@ -1,401 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb)\n",- "\n",- "# News Sentiment Analysis Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete news sentiment analysis pipeline for trading: ingest financial news from multiple sources (RSS feeds, news APIs, web sources), extract entities, build news knowledge graph, analyze sentiment using embeddings, and generate trading signals.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: HTMLParser, JSONParser, StructuredDataParser, DocumentParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Embeddings**: EmbeddingGenerator, TextEmbedder\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Ingest News \u2192 Parse \u2192 Extract Entities \u2192 Build News KG \u2192 Generate Embeddings \u2192 Analyze Sentiment \u2192 Generate Trading Signals \u2192 Export \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Financial News from Multiple Sources\n",- "\n",- "Ingest financial news from RSS feeds, news APIs, and web sources.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import WebIngestor, FeedIngestor, DBIngestor, FileIngestor\n",- "from semantica.parse import HTMLParser, JSONParser, StructuredDataParser, DocumentParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",- "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "db_ingestor = DBIngestor()\n",- "file_ingestor = FileIngestor()\n",- "\n",- "html_parser = HTMLParser()\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "document_parser = DocumentParser()\n",- "\n",- "# Real financial news feed URLs\n",- "financial_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\", # Reuters Business\n",- " \"https://feeds.reuters.com/reuters/topNews\", # Reuters Top News\n",- " \"https://rss.cnn.com/rss/money_latest.rss\", # CNN Money\n",- " \"https://feeds.bloomberg.com/markets/news.rss\", # Bloomberg Markets\n",- " \"https://www.ft.com/?format=rss\" # Financial Times\n",- "]\n",- "\n",- "# Real news API endpoints\n",- "news_apis = [\n",- " \"https://newsapi.org/v2/everything?q=finance&apiKey=demo\", # NewsAPI (requires API key)\n",- " \"https://api.github.com/repos/financial-news/aggregator\" # Financial news aggregator\n",- "]\n",- "\n",- "# Real database connection for news data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/news_db\"\n",- "db_query = \"SELECT article_id, title, content, sentiment, published_date FROM financial_news WHERE published_date > NOW() - INTERVAL '24 hours' ORDER BY published_date DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample financial news data\n",- "news_file = os.path.join(temp_dir, \"financial_news.json\")\n",- "news_data = {\n",- " \"articles\": [\n",- " {\n",- " \"title\": \"Apple Reports Strong Q4 Earnings\",\n",- " \"content\": \"Apple Inc. reported strong fourth quarter earnings, beating analyst expectations with record revenue.\",\n",- " \"sentiment\": \"positive\",\n",- " \"published_date\": (datetime.now() - timedelta(hours=2)).isoformat(),\n",- " \"symbols\": [\"AAPL\"]\n",- " },\n",- " {\n",- " \"title\": \"Market Volatility Concerns Rise\",\n",- " \"content\": \"Financial markets show increased volatility amid economic uncertainty and geopolitical tensions.\",\n",- " \"sentiment\": \"negative\",\n",- " \"published_date\": (datetime.now() - timedelta(hours=1)).isoformat(),\n",- " \"symbols\": [\"SPY\", \"QQQ\"]\n",- " }\n",- " ]\n",- "}\n",- "\n",- "with open(news_file, 'w') as f:\n",- " json.dump(news_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(news_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(news_file, data_format=\"json\")\n",- "\n",- "# Ingest from financial feeds\n",- "financial_feed_list = []\n",- "for feed_url in financial_feeds[:3]: # Process first 3 feeds\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " financial_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- " print(f\" Items: {len(feed_data.items) if hasattr(feed_data, 'items') else 0}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" News files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Financial feeds: {len(financial_feed_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract News Entities and Build Knowledge Graph\n",- "\n",- "Extract entities from news articles and build knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "news_entities = []\n",- "news_relationships = []\n",- "all_news_texts = []\n",- "\n",- "# Extract from news data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " articles = parsed_data.get(\"data\").get(\"articles\", []) if isinstance(parsed_data.get(\"data\"), dict) else parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else []\n",- " \n",- " for article in articles:\n",- " if isinstance(article, dict):\n",- " article_text = f\"{article.get('title', '')} {article.get('content', '')}\"\n",- " all_news_texts.append(article_text)\n",- " \n",- " news_entities.append({\n",- " \"id\": article.get(\"title\", \"\"),\n",- " \"type\": \"News_Article\",\n",- " \"name\": article.get(\"title\", \"\"),\n",- " \"properties\": {\n",- " \"sentiment\": article.get(\"sentiment\", \"\"),\n",- " \"published_date\": article.get(\"published_date\", \"\")\n",- " }\n",- " })\n",- " \n",- " # Symbols mentioned\n",- " for symbol in article.get(\"symbols\", []):\n",- " news_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {}\n",- " })\n",- " news_relationships.append({\n",- " \"source\": article.get(\"title\", \"\"),\n",- " \"target\": symbol,\n",- " \"type\": \"mentions\",\n",- " \"properties\": {\n",- " \"sentiment\": article.get(\"sentiment\", \"\")\n",- " }\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "\n",- "news_kg = builder.build(news_entities, news_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(news_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(news_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(news_kg)\n",- "\n",- "print(f\"Extracted {len(news_entities)} news entities\")\n",- "print(f\"Extracted {len(news_relationships)} relationships\")\n",- "print(f\"Collected {len(all_news_texts)} news articles\")\n",- "print(f\"Built news knowledge graph with {len(news_kg.get('entities', []))} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Generate Embeddings and Analyze Sentiment\n",- "\n",- "Generate embeddings from news articles and analyze sentiment.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "embedding_generator = EmbeddingGenerator()\n",- "text_embedder = TextEmbedder()\n",- "\n",- "embeddings = embedding_generator.generate_embeddings(all_news_texts, data_type=\"text\")\n",- "\n",- "# Analyze sentiment from embeddings and article properties\n",- "sentiment_scores = []\n",- "for i, article in enumerate(parsed_data.get(\"data\").get(\"articles\", []) if parsed_data and parsed_data.get(\"data\") and isinstance(parsed_data.get(\"data\"), dict) else []):\n",- " if isinstance(article, dict):\n",- " sentiment = article.get(\"sentiment\", \"neutral\")\n",- " sentiment_value = 1.0 if sentiment == \"positive\" else -1.0 if sentiment == \"negative\" else 0.0\n",- " \n",- " sentiment_scores.append({\n",- " \"article\": article.get(\"title\", \"\"),\n",- " \"sentiment\": sentiment,\n",- " \"score\": sentiment_value,\n",- " \"symbols\": article.get(\"symbols\", [])\n",- " })\n",- "\n",- "print(f\"Generated embeddings for {len(all_news_texts)} news articles\")\n",- "print(f\"Analyzed sentiment for {len(sentiment_scores)} articles\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Generate Trading Signals\n",- "\n",- "Generate trading signals based on sentiment analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "\n",- "# Trading signal generation rules\n",- "inference_engine.add_rule(\"IF sentiment is positive AND multiple articles mention symbol THEN buy_signal\")\n",- "inference_engine.add_rule(\"IF sentiment is negative AND multiple articles mention symbol THEN sell_signal\")\n",- "inference_engine.add_rule(\"IF sentiment score > 0.5 THEN strong_positive_signal\")\n",- "\n",- "# Generate trading signals\n",- "trading_signals = []\n",- "for sentiment_data in sentiment_scores:\n",- " symbol_sentiment = {}\n",- " for symbol in sentiment_data.get(\"symbols\", []):\n",- " if symbol not in symbol_sentiment:\n",- " symbol_sentiment[symbol] = []\n",- " symbol_sentiment[symbol].append(sentiment_data.get(\"score\", 0))\n",- " \n",- " for symbol, scores in symbol_sentiment.items():\n",- " avg_sentiment = sum(scores) / len(scores) if scores else 0\n",- " signal_type = \"buy\" if avg_sentiment > 0.3 else \"sell\" if avg_sentiment < -0.3 else \"hold\"\n",- " \n",- " trading_signals.append({\n",- " \"symbol\": symbol,\n",- " \"signal\": signal_type,\n",- " \"sentiment_score\": avg_sentiment,\n",- " \"confidence\": abs(avg_sentiment),\n",- " \"timestamp\": datetime.now().isoformat()\n",- " })\n",- " \n",- " inference_engine.add_fact({\n",- " \"symbol\": symbol,\n",- " \"sentiment\": sentiment_data.get(\"sentiment\", \"\"),\n",- " \"score\": avg_sentiment\n",- " })\n",- "\n",- "# # signal_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Generated {len(trading_signals)} trading signals\")\n",- "print(f\"Inferred {len(signal_insights)} signal patterns\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate sentiment analysis reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.94}\n",- "\n",- "json_exporter.export_knowledge_graph(news_kg, os.path.join(temp_dir, \"news_kg.json\"))\n",- "csv_exporter.export_entities(news_entities, os.path.join(temp_dir, \"news_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(news_kg, os.path.join(temp_dir, \"news_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"News sentiment analysis identified {len(trading_signals)} trading signals from {len(news_entities)} entities\",\n",- " \"articles_analyzed\": len([e for e in news_entities if e.get(\"type\") == \"News_Article\"]),\n",- " \"signals\": len(trading_signals),\n",- " \"buy_signals\": len([s for s in trading_signals if s.get(\"signal\") == \"buy\"]),\n",- " \"sell_signals\": len([s for s in trading_signals if s.get(\"signal\") == \"sell\"]),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(news_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(news_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(news_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Ingest News \u2192 Parse \u2192 Extract \u2192 Build KG \u2192 Embeddings \u2192 Sentiment Analysis \u2192 Trading Signals \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb b/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynbdeleted file mode 100644index 81d01de9..00000000--- a/cookbook/use_cases/trading/03_Real_Time_Monitoring.ipynb+++ /dev/null@@ -1,428 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/04_Real_Time_Monitoring.ipynb)\n",- "\n",- "# Real-Time Trading Monitoring Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete real-time trading monitoring pipeline: stream trading data from multiple sources (trading platforms, market data streams, databases), build temporal knowledge graph, monitor positions in real-time, detect anomalies, and generate alerts.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, AutomatedFixer\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Real-Time Trading Streams \u2192 Parse \u2192 Extract Entities \u2192 Build Temporal KG \u2192 Monitor Positions \u2192 Detect Anomalies \u2192 Generate Alerts \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Stream Trading Data from Multiple Sources\n",- "\n",- "Stream trading data from trading platforms, market data streams, and databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import StreamIngestor, FileIngestor, DBIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, TripletExtractor\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD--=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "import time\n",- "from datetime import datetime, timedelta\n",- "from collections import deque\n",- "\n",- "stream_ingestor = StreamIngestor()\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real streaming sources for trading data\n",- "stream_sources = [\n",- " {\n",- " \"type\": \"kafka\",\n",- " \"topic\": \"trading_data\",\n",- " \"bootstrap_servers\": [\"localhost:9092\"],\n",- " \"consumer_config\": {\"group_id\": \"trading_monitor\"}\n",- " },\n",- " {\n",- " \"type\": \"rabbitmq\",\n",- " \"queue\": \"trading_events\",\n",- " \"connection_url\": \"amqp://user:password@localhost:5672/\"\n",- " }\n",- "]\n",- "\n",- "# Real market data APIs\n",- "market_apis = [\n",- " \"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/minute/2024-01-15/2024-01-15\", # Polygon.io\n",- " \"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=AAPL&interval=1min&apikey=demo\" # Alpha Vantage\n",- "]\n",- "\n",- "# Real database connection for trading positions\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/trading_db\"\n",- "db_query = \"SELECT position_id, symbol, quantity, entry_price, current_price, timestamp FROM positions WHERE timestamp > NOW() - INTERVAL '1 hour' ORDER BY timestamp DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample real-time trading data\n",- "trading_stream_file = os.path.join(temp_dir, \"trading_stream.json\")\n",- "trading_stream = [\n",- " {\n",- " \"position_id\": \"POS-001\",\n",- " \"symbol\": \"AAPL\",\n",- " \"quantity\": 100,\n",- " \"entry_price\": 175.00,\n",- " \"current_price\": 175.50,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=5)).isoformat()\n",- " },\n",- " {\n",- " \"position_id\": \"POS-002\",\n",- " \"symbol\": \"MSFT\",\n",- " \"quantity\": 50,\n",- " \"entry_price\": 380.00,\n",- " \"current_price\": 380.25,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=4)).isoformat()\n",- " },\n",- " {\n",- " \"position_id\": \"POS-003\",\n",- " \"symbol\": \"GOOGL\",\n",- " \"quantity\": 75,\n",- " \"entry_price\": 142.00,\n",- " \"current_price\": 142.80,\n",- " \"timestamp\": (datetime.now() - timedelta(minutes=3)).isoformat()\n",- " }\n",- "]\n",- "\n",- "with open(trading_stream_file, 'w') as f:\n",- " json.dump(trading_stream, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(trading_stream_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(trading_stream_file, data_format=\"json\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Trading stream files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Streaming sources: {len(stream_sources)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Trading Entities and Build Temporal Knowledge Graph\n",- "\n",- "Extract trading entities and build temporal knowledge graph for real-time monitoring.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "triplet_extractor = TripletExtractor()\n",- "\n",- "trading_entities = []\n",- "trading_relationships = []\n",- "\n",- "# Extract from trading stream data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " for position in parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")]:\n",- " if isinstance(position, dict):\n",- " position_id = position.get(\"position_id\", \"\")\n",- " symbol = position.get(\"symbol\", \"\")\n",- " \n",- " trading_entities.append({\n",- " \"id\": position_id,\n",- " \"type\": \"Position\",\n",- " \"name\": position_id,\n",- " \"properties\": {\n",- " \"quantity\": position.get(\"quantity\", 0),\n",- " \"entry_price\": position.get(\"entry_price\", 0),\n",- " \"current_price\": position.get(\"current_price\", 0),\n",- " \"timestamp\": position.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- " \n",- " trading_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " trading_relationships.append({\n",- " \"source\": position_id,\n",- " \"target\": symbol,\n",- " \"type\": \"holds\",\n",- " \"properties\": {\n",- " \"quantity\": position.get(\"quantity\", 0),\n",- " \"timestamp\": position.get(\"timestamp\", \"\")\n",- " }\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "trading_kg = builder.build(trading_entities, trading_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(trading_kg)\n",- "\n",- "print(f\"Extracted {len(trading_entities)} trading entities\")\n",- "print(f\"Extracted {len(trading_relationships)} relationships\")\n",- "print(f\"Built temporal trading knowledge graph with {len(trading_kg.get('entities', []))} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Monitor Positions in Real-Time\n",- "\n",- "Monitor trading positions using temporal queries.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "\n",- "current_time = datetime.now().isoformat()\n",- "start_time = (datetime.now() - timedelta(minutes=10)).isoformat()\n",- "\n",- "# Query current positions\n",- "current_positions = temporal_query.query_time_range(\n",- " graph=trading_kg,\n",- " query=\"Find current positions\",\n",- " start_time=start_time,\n",- " end_time=current_time\n",- ")\n",- "\n",- "# Monitor position changes\n",- "position_changes = []\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " for position in parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")]:\n",- " if isinstance(position, dict):\n",- " price_change = position.get(\"current_price\", 0) - position.get(\"entry_price\", 0)\n",- " price_change_percent = (price_change / position.get(\"entry_price\", 1)) * 100 if position.get(\"entry_price\", 0) > 0 else 0\n",- " \n",- " position_changes.append({\n",- " \"position_id\": position.get(\"position_id\", \"\"),\n",- " \"symbol\": position.get(\"symbol\", \"\"),\n",- " \"price_change\": price_change,\n",- " \"price_change_percent\": price_change_percent,\n",- " \"timestamp\": position.get(\"timestamp\", \"\")\n",- " })\n",- "\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(trading_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(trading_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(trading_kg)\n",- "\n",- "print(f\"Monitoring {len(current_positions.get('entities', []))} current positions\")\n",- "print(f\"Position changes tracked: {len(position_changes)}\")\n",- "print(f\"Central positions: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Detect Anomalies and Generate Alerts\n",- "\n",- "Detect anomalies in trading positions and generate alerts.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Anomaly detection rules\n",- "inference_engine.add_rule(\"IF price_change_percent > 5 AND quantity > 100 THEN large_gain_alert\")\n",- "inference_engine.add_rule(\"IF price_change_percent < -5 AND quantity > 100 THEN large_loss_alert\")\n",- "inference_engine.add_rule(\"IF price_change_percent > 10 THEN extreme_movement_alert\")\n",- "\n",- "# Detect anomalies\n",- "anomalies = []\n",- "alerts = []\n",- "\n",- "for position_change in position_changes:\n",- " anomaly_score = 0\n",- " reasons = []\n",- " \n",- " if abs(position_change.get(\"price_change_percent\", 0)) > 5:\n",- " anomaly_score += 3\n",- " reasons.append(\"Significant price movement\")\n",- " \n",- " if position_change.get(\"price_change_percent\", 0) > 10:\n",- " anomaly_score += 5\n",- " reasons.append(\"Extreme price movement\")\n",- " \n",- " if anomaly_score >= 3:\n",- " anomaly = {\n",- " \"position_id\": position_change.get(\"position_id\", \"\"),\n",- " \"symbol\": position_change.get(\"symbol\", \"\"),\n",- " \"severity\": \"high\" if anomaly_score >= 5 else \"medium\",\n",- " \"score\": anomaly_score,\n",- " \"reasons\": reasons,\n",- " \"timestamp\": position_change.get(\"timestamp\", \"\")\n",- " }\n",- " anomalies.append(anomaly)\n",- " \n",- " alert = {\n",- " \"alert_id\": f\"alert_{position_change.get('position_id', '')}_{int(time.time())}\",\n",- " \"type\": \"trading_anomaly\",\n",- " \"severity\": anomaly[\"severity\"],\n",- " \"position\": position_change.get(\"position_id\", \"\"),\n",- " \"symbol\": position_change.get(\"symbol\", \"\"),\n",- " \"message\": f\"Anomaly detected: {', '.join(reasons)}\",\n",- " \"timestamp\": position_change.get(\"timestamp\", \"\")\n",- " }\n",- " alerts.append(alert)\n",- " \n",- " inference_engine.add_fact({\n",- " \"position_id\": position_change.get(\"position_id\", \"\"),\n",- " \"price_change_percent\": position_change.get(\"price_change_percent\", 0),\n",- " \"quantity\": position_change.get(\"quantity\", 0) if \"quantity\" in position_change else 0\n",- " })\n",- "\n",- "# # detected_anomalies = inference_engine.forward_chain()\n",- "\n",- "print(f\"Detected {len(anomalies)} trading anomalies\")\n",- "print(f\"Generated {len(alerts)} alerts\")\n",- "print(f\"Inferred {len(detected_anomalies)} anomaly patterns\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate real-time monitoring reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "json_exporter.export_knowledge_graph(trading_kg, os.path.join(temp_dir, \"trading_kg.json\"))\n",- "csv_exporter.export_entities(trading_entities, os.path.join(temp_dir, \"trading_entities.csv\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Real-time monitoring detected {len(anomalies)} anomalies and generated {len(alerts)} alerts\",\n",- " \"positions_monitored\": len([e for e in trading_entities if e.get(\"type\") == \"Position\"]),\n",- " \"anomalies\": len(anomalies),\n",- " \"alerts\": len(alerts)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(trading_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(trading_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(trading_kg, output=\"interactive\")\n",- "\n",- "print(f\"Real-time monitoring active\")\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Real-Time Streams \u2192 Parse \u2192 Extract \u2192 Build Temporal KG \u2192 Monitor Positions \u2192 Detect Anomalies \u2192 Alerts \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/trading/04_Risk_Assessment.ipynb b/cookbook/use_cases/trading/04_Risk_Assessment.ipynbdeleted file mode 100644index 99f4003e..00000000--- a/cookbook/use_cases/trading/04_Risk_Assessment.ipynb+++ /dev/null@@ -1,436 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/05_Risk_Assessment.ipynb)\n",- "\n",- "# Risk Assessment Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete risk assessment pipeline for trading: ingest risk data from multiple sources (portfolio data, market risk metrics, historical data), extract risk entities, build risk knowledge graph, analyze risk relationships, and assess portfolio risk.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor, ConflictDetector\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Risk Data Sources \u2192 Parse \u2192 Extract Risk Entities \u2192 Build Risk KG \u2192 Analyze Risk Relationships \u2192 Assess Portfolio Risk \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Risk Data from Multiple Sources\n",- "\n",- "Ingest risk data from portfolio databases, market risk metrics, and historical data.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetector\n",-<<<<<<< Updated upstream- "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "from semantica.kg_qa import KGQualityAssessor\n",- "from semantica.conflicts import ConflictDetector\n",-=======- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, TemporalVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "file_ingestor = FileIngestor()\n",- "db_ingestor = DBIngestor()\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real risk data sources\n",- "risk_apis = [\n",- " \"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2024-01-01/2024-01-31\", # Polygon.io\n",- " \"https://www.alphavantage.co/query?function=OVERVIEW&symbol=AAPL&apikey=demo\" # Alpha Vantage\n",- "]\n",- "\n",- "financial_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\"\n",- "]\n",- "\n",- "# Real database connection for portfolio risk data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/portfolio_db\"\n",- "db_query = \"SELECT portfolio_id, symbol, quantity, value, risk_score, volatility FROM portfolio_positions WHERE last_updated > NOW() - INTERVAL '1 day' ORDER BY risk_score DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample portfolio risk data\n",- "risk_data_file = os.path.join(temp_dir, \"portfolio_risk.json\")\n",- "portfolio_risk_data = {\n",- " \"portfolio_id\": \"PORT-001\",\n",- " \"positions\": [\n",- " {\n",- " \"symbol\": \"AAPL\",\n",- " \"quantity\": 100,\n",- " \"value\": 17550.00,\n",- " \"risk_score\": 0.15,\n",- " \"volatility\": 0.20,\n",- " \"beta\": 1.2\n",- " },\n",- " {\n",- " \"symbol\": \"MSFT\",\n",- " \"quantity\": 50,\n",- " \"value\": 19012.50,\n",- " \"risk_score\": 0.12,\n",- " \"volatility\": 0.18,\n",- " \"beta\": 0.9\n",- " },\n",- " {\n",- " \"symbol\": \"GOOGL\",\n",- " \"quantity\": 75,\n",- " \"value\": 10710.00,\n",- " \"risk_score\": 0.18,\n",- " \"volatility\": 0.25,\n",- " \"beta\": 1.1\n",- " }\n",- " ],\n",- " \"total_value\": 47272.50,\n",- " \"portfolio_risk_score\": 0.15\n",- "}\n",- "\n",- "with open(risk_data_file, 'w') as f:\n",- " json.dump(portfolio_risk_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(risk_data_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(risk_data_file, data_format=\"json\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Ingestion Summary:\")\n",- "print(f\" Risk data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Risk Entities and Build Risk Knowledge Graph\n",- "\n",- "Extract risk entities and build risk knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "risk_entities = []\n",- "risk_relationships = []\n",- "\n",- "# Extract from portfolio risk data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " portfolio = parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), dict) else parsed_data.get(\"data\")[0] if isinstance(parsed_data.get(\"data\"), list) else {}\n",- " \n",- " if isinstance(portfolio, dict):\n",- " portfolio_id = portfolio.get(\"portfolio_id\", \"\")\n",- " \n",- " risk_entities.append({\n",- " \"id\": portfolio_id,\n",- " \"type\": \"Portfolio\",\n",- " \"name\": portfolio_id,\n",- " \"properties\": {\n",- " \"total_value\": portfolio.get(\"total_value\", 0),\n",- " \"portfolio_risk_score\": portfolio.get(\"portfolio_risk_score\", 0)\n",- " }\n",- " })\n",- " \n",- " # Positions and risk metrics\n",- " for position in portfolio.get(\"positions\", []):\n",- " if isinstance(position, dict):\n",- " symbol = position.get(\"symbol\", \"\")\n",- " \n",- " risk_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {\n",- " \"quantity\": position.get(\"quantity\", 0),\n",- " \"value\": position.get(\"value\", 0),\n",- " \"risk_score\": position.get(\"risk_score\", 0),\n",- " \"volatility\": position.get(\"volatility\", 0),\n",- " \"beta\": position.get(\"beta\", 0)\n",- " }\n",- " })\n",- " \n",- " risk_relationships.append({\n",- " \"source\": portfolio_id,\n",- " \"target\": symbol,\n",- " \"type\": \"contains\",\n",- " \"properties\": {\n",- " \"quantity\": position.get(\"quantity\", 0),\n",- " \"value\": position.get(\"value\", 0)\n",- " }\n",- " })\n",- " \n",- " risk_relationships.append({\n",- " \"source\": symbol,\n",- " \"target\": f\"{symbol}_risk\",\n",- " \"type\": \"has_risk\",\n",- " \"properties\": {\n",- " \"risk_score\": position.get(\"risk_score\", 0),\n",- " \"volatility\": position.get(\"volatility\", 0)\n",- " }\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "graph_analyzer = GraphAnalyzer()\n",- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "\n",- "risk_kg = builder.build(risk_entities, risk_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(risk_kg)\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(risk_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(risk_kg)\n",- "\n",- "print(f\"Extracted {len(risk_entities)} risk entities\")\n",- "print(f\"Extracted {len(risk_relationships)} risk relationships\")\n",- "print(f\"Built risk knowledge graph with {len(risk_kg.get('entities', []))} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Analyze Risk Relationships\n",- "\n",- "Analyze risk relationships using graph analytics.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "\n",- "connectivity = connectivity_analyzer.analyze_connectivity(risk_kg)\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " risk_kg,\n",- " pattern_type=\"risk\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Analyze risk concentration\n",- "risk_concentration = {}\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " portfolio = parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), dict) else parsed_data.get(\"data\")[0] if isinstance(parsed_data.get(\"data\"), list) else {}\n",- " if isinstance(portfolio, dict):\n",- " total_value = portfolio.get(\"total_value\", 1)\n",- " for position in portfolio.get(\"positions\", []):\n",- " if isinstance(position, dict):\n",- " symbol = position.get(\"symbol\", \"\")\n",- " value = position.get(\"value\", 0)\n",- " concentration = (value / total_value) * 100 if total_value > 0 else 0\n",- " risk_concentration[symbol] = {\n",- " \"concentration\": concentration,\n",- " \"risk_score\": position.get(\"risk_score\", 0),\n",- " \"value\": value\n",- " }\n",- "\n",- "print(f\"Risk relationships analyzed\")\n",- "print(f\" Connected components: {len(connectivity.get('components', []))}\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\" Risk concentrations: {len(risk_concentration)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Assess Portfolio Risk\n",- "\n",- "Assess portfolio risk using inference engine.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Portfolio risk assessment rules\n",- "inference_engine.add_rule(\"IF risk_score > 0.2 AND concentration > 20 THEN high_risk_position\")\n",- "inference_engine.add_rule(\"IF volatility > 0.3 AND beta > 1.5 THEN high_volatility_risk\")\n",- "inference_engine.add_rule(\"IF portfolio_risk_score > 0.2 THEN high_portfolio_risk\")\n",- "\n",- "# Assess portfolio risk\n",- "portfolio_risk_assessment = {}\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " portfolio = parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), dict) else parsed_data.get(\"data\")[0] if isinstance(parsed_data.get(\"data\"), list) else {}\n",- " if isinstance(portfolio, dict):\n",- " portfolio_risk_score = portfolio.get(\"portfolio_risk_score\", 0)\n",- " \n",- " # Calculate weighted risk\n",- " total_risk = 0\n",- " total_value = portfolio.get(\"total_value\", 1)\n",- " for position in portfolio.get(\"positions\", []):\n",- " if isinstance(position, dict):\n",- " position_risk = position.get(\"risk_score\", 0) * (position.get(\"value\", 0) / total_value) if total_value > 0 else 0\n",- " total_risk += position_risk\n",- " \n",- " inference_engine.add_fact({\n",- " \"symbol\": position.get(\"symbol\", \"\"),\n",- " \"risk_score\": position.get(\"risk_score\", 0),\n",- " \"volatility\": position.get(\"volatility\", 0),\n",- " \"beta\": position.get(\"beta\", 0),\n",- " \"concentration\": risk_concentration.get(position.get(\"symbol\", \"\"), {}).get(\"concentration\", 0)\n",- " })\n",- " \n",- " portfolio_risk_assessment = {\n",- " \"portfolio_id\": portfolio.get(\"portfolio_id\", \"\"),\n",- " \"overall_risk_score\": portfolio_risk_score,\n",- " \"weighted_risk\": total_risk,\n",- " \"risk_level\": \"high\" if portfolio_risk_score > 0.2 else \"medium\" if portfolio_risk_score > 0.1 else \"low\",\n",- " \"positions_count\": len(portfolio.get(\"positions\", []))\n",- " }\n",- " \n",- " inference_engine.add_fact({\n",- " \"portfolio_id\": portfolio.get(\"portfolio_id\", \"\"),\n",- " \"portfolio_risk_score\": portfolio_risk_score\n",- " })\n",- "\n",- "# # risk_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Portfolio risk assessment complete\")\n",- "print(f\" Overall risk score: {portfolio_risk_assessment.get('overall_risk_score', 0):.3f}\")\n",- "print(f\" Risk level: {portfolio_risk_assessment.get('risk_level', 'unknown')}\")\n",- "print(f\" Generated {len(risk_insights)} risk insights\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Reports and Visualize\n",- "\n",- "Generate risk assessment reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.93}\n",- "\n",- "json_exporter.export_knowledge_graph(risk_kg, os.path.join(temp_dir, \"risk_kg.json\"))\n",- "csv_exporter.export_entities(risk_entities, os.path.join(temp_dir, \"risk_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(risk_kg, os.path.join(temp_dir, \"risk_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Risk assessment identified {len(risk_insights)} risk insights for portfolio {portfolio_risk_assessment.get('portfolio_id', '')}\",\n",- " \"portfolio_risk_score\": portfolio_risk_assessment.get('overall_risk_score', 0),\n",- " \"risk_level\": portfolio_risk_assessment.get('risk_level', 'unknown'),\n",- " \"positions_analyzed\": len([e for e in risk_entities if e.get(\"type\") == \"Stock\"]),\n",- " \"insights\": len(risk_insights),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(risk_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(risk_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(risk_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Risk Data \u2192 Parse \u2192 Extract \u2192 Build Risk KG \u2192 Analyze Relationships \u2192 Assess Portfolio Risk \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/cookbook/use_cases/trading/05_Strategy_Backtesting.ipynb b/cookbook/use_cases/trading/05_Strategy_Backtesting.ipynbdeleted file mode 100644index b2f9bd1e..00000000--- a/cookbook/use_cases/trading/05_Strategy_Backtesting.ipynb+++ /dev/null@@ -1,435 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/trading/06_Strategy_Backtesting.ipynb)\n",- "\n",- "# Strategy Backtesting Pipeline\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates a complete strategy backtesting pipeline: ingest historical market data from multiple sources (databases, market data APIs, historical feeds), build temporal knowledge graph, test trading strategies on historical data, and analyze performance metrics.\n",- "\n",- "\n",- "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",- "\n",- "## Installation\n",- "\n",- "Install Semantica from PyPI:\n",- "\n",- "```bash\n",- "pip install semantica\n",- "# Or with all optional dependencies:\n",- "pip install semantica[all]\n",- "```\n",- "\n",- "### Modules Used (20+)\n",- "\n",- "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, EmailIngestor, RepoIngestor, MCPIngestor\n",- "- **Parsing**: JSONParser, CSVParser, StructuredDataParser\n",- "- **Extraction**: NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "- **KG**: GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "- **Analytics**: CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",-<<<<<<< Updated upstream- "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",-<<<<<<< HEAD- "- **Quality**: KGQualityAssessor\n",-=======- "- **Reasoning**: Reasoner (Legacy), RuleManager, ExplanationGenerator\n",->>>>>>> Stashed changes-=======->>>>>>> main- "- **Export**: JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "\n",- "### Pipeline\n",- "\n",- "**Historical Data \u2192 Parse \u2192 Extract Entities \u2192 Build Temporal KG \u2192 Test Strategies \u2192 Analyze Performance \u2192 Generate Reports \u2192 Visualize**\n",- "\n",- "---\n",- "\n",- "## Step 1: Ingest Historical Market Data\n",- "\n",- "Ingest historical market data from databases, market data APIs, and historical feeds.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "!pip install semantica\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import DBIngestor, FileIngestor, WebIngestor, FeedIngestor\n",- "from semantica.parse import JSONParser, CSVParser, StructuredDataParser\n",- "from semantica.semantic_extract import NERExtractor, RelationExtractor, EventDetector, SemanticAnalyzer\n",- "from semantica.kg import GraphBuilder, TemporalGraphQuery, TemporalPatternDetector, GraphAnalyzer\n",- "from semantica.kg import CentralityCalculator, CommunityDetector, ConnectivityAnalyzer\n",- "# # from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",- "from semantica.export import JSONExporter, CSVExporter, RDFExporter, ReportGenerator\n",- "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",- "import tempfile\n",- "import os\n",- "import json\n",- "from datetime import datetime, timedelta\n",- "\n",- "db_ingestor = DBIngestor()\n",- "file_ingestor = FileIngestor()\n",- "web_ingestor = WebIngestor()\n",- "feed_ingestor = FeedIngestor()\n",- "\n",- "json_parser = JSONParser()\n",- "csv_parser = CSVParser()\n",- "structured_parser = StructuredDataParser()\n",- "\n",- "# Real historical market data APIs\n",- "historical_market_apis = [\n",- " \"https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-01-01/2024-01-01\", # Polygon.io historical\n",- " \"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AAPL&apikey=demo\", # Alpha Vantage historical\n",- " \"https://api.github.com/repos/ranaroussi/yfinance\" # Yahoo Finance historical data\n",- "]\n",- "\n",- "# Real financial news feeds for historical context\n",- "historical_feeds = [\n",- " \"https://feeds.reuters.com/reuters/businessNews\",\n",- " \"https://rss.cnn.com/rss/money_latest.rss\",\n",- " \"https://feeds.bloomberg.com/markets/news.rss\"\n",- "]\n",- "\n",- "# Real database connection for historical market data\n",- "db_connection_string = \"postgresql://user:password@localhost:5432/historical_market_db\"\n",- "db_query = \"SELECT symbol, date, open, high, low, close, volume FROM historical_prices WHERE date >= '2023-01-01' AND date <= '2024-01-01' ORDER BY date DESC\"\n",- "\n",- "temp_dir = tempfile.mkdtemp()\n",- "\n",- "# Sample historical market data (simulating real historical data structure)\n",- "historical_data_file = os.path.join(temp_dir, \"historical_data.json\")\n",- "historical_data = [\n",- " {\"symbol\": \"AAPL\", \"date\": \"2023-01-15\", \"open\": 150.00, \"high\": 152.00, \"low\": 149.50, \"close\": 151.50, \"volume\": 50000000},\n",- " {\"symbol\": \"AAPL\", \"date\": \"2023-01-16\", \"open\": 151.50, \"high\": 153.00, \"low\": 151.00, \"close\": 152.75, \"volume\": 52000000},\n",- " {\"symbol\": \"MSFT\", \"date\": \"2023-01-15\", \"open\": 350.00, \"high\": 352.00, \"low\": 349.50, \"close\": 351.25, \"volume\": 30000000},\n",- " {\"symbol\": \"MSFT\", \"date\": \"2023-01-16\", \"open\": 351.25, \"high\": 353.50, \"low\": 350.75, \"close\": 352.50, \"volume\": 31000000}\n",- "]\n",- "\n",- "with open(historical_data_file, 'w') as f,\n",- " json.dump(historical_data, f, indent=2)\n",- "\n",- "file_objects = file_ingestor.ingest_file(historical_data_file, read_content=True)\n",- "parsed_data = structured_parser.parse_data(historical_data_file, data_format=\"json\")\n",- "\n",- "# Ingest from historical market APIs\n",- "historical_api_list = []\n",- "for api_url in historical_market_apis[:1]:\n",- " api_content = web_ingestor.ingest_url(api_url)\n",- " if api_content:\n",- " historical_api_list.append(api_content)\n",- " print(f\" Ingested historical API: {api_url}\")\n",- "\n",- "# Ingest from historical news feeds\n",- "historical_feed_list = []\n",- "for feed_url in historical_feeds:\n",- " feed_data = feed_ingestor.ingest_feed(feed_url)\n",- " if feed_data:\n",- " historical_feed_list.append(feed_data)\n",- " print(f\" Ingested feed: {feed_url}\")\n",- "\n",- "print(f\"\\n\ud83d\udcca Historical Data Ingestion Summary:\")\n",- "print(f\" Historical data files: {len([file_objects]) if file_objects else 0}\")\n",- "print(f\" Historical market APIs: {len(historical_api_list)}\")\n",- "print(f\" Historical feeds: {len(historical_feed_list)}\")\n",- "print(f\" Database sources: 1\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Extract Market Entities and Build Temporal Knowledge Graph\n",- "\n",- "Extract market entities from historical data and build temporal knowledge graph.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "ner_extractor = NERExtractor()\n",- "relation_extractor = RelationExtractor()\n",- "event_detector = EventDetector()\n",- "semantic_analyzer = SemanticAnalyzer()\n",- "\n",- "historical_entities = []\n",- "historical_relationships = []\n",- "\n",- "# Extract from historical data\n",- "if parsed_data and parsed_data.get(\"data\"):\n",- " for entry in parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")]:\n",- " if isinstance(entry, dict):\n",- " symbol = entry.get(\"symbol\", \"\")\n",- " date = entry.get(\"date\", \"\")\n",- " \n",- " historical_entities.append({\n",- " \"id\": f\"{symbol}_{date}\",\n",- " \"type\": \"Historical_Price\",\n",- " \"name\": f\"{symbol} on {date}\",\n",- " \"properties\": {\n",- " \"symbol\": symbol,\n",- " \"date\": date,\n",- " \"open\": entry.get(\"open\", 0),\n",- " \"high\": entry.get(\"high\", 0),\n",- " \"low\": entry.get(\"low\", 0),\n",- " \"close\": entry.get(\"close\", 0),\n",- " \"volume\": entry.get(\"volume\", 0)\n",- " }\n",- " })\n",- " \n",- " historical_entities.append({\n",- " \"id\": symbol,\n",- " \"type\": \"Stock\",\n",- " \"name\": symbol,\n",- " \"properties\": {}\n",- " })\n",- " \n",- " historical_relationships.append({\n",- " \"source\": symbol,\n",- " \"target\": f\"{symbol}_{date}\",\n",- " \"type\": \"has_price_on\",\n",- " \"properties\": {\"date\": date}\n",- " })\n",- "\n",- "builder = GraphBuilder()\n",- "temporal_query = TemporalGraphQuery()\n",- "temporal_pattern_detector = TemporalPatternDetector()\n",- "graph_analyzer = GraphAnalyzer()\n",- "\n",- "historical_kg = builder.build(historical_entities, historical_relationships)\n",- "\n",- "metrics = graph_analyzer.compute_metrics(historical_kg)\n",- "\n",- "print(f\"Extracted {len(historical_entities)} historical entities\")\n",- "print(f\"Extracted {len(historical_relationships)} relationships\")\n",- "print(f\"Built temporal knowledge graph with {len(historical_kg.get('entities', []))} entities\")\n",- "print(f\"Graph density: {metrics.get('density', 0):.3f}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Test Trading Strategies\n",- "\n",- "Test trading strategies on historical data using temporal analysis.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Define trading strategies\n",- "strategies = [\n",- " {\n",- " \"name\": \"Moving Average Crossover\",\n",- " \"entry_rule\": \"IF close > moving_average_20 THEN buy\",\n",- " \"exit_rule\": \"IF close < moving_average_20 THEN sell\"\n",- " },\n",- " {\n",- " \"name\": \"Momentum Strategy\",\n",- " \"entry_rule\": \"IF price_change > 2% AND volume > average_volume THEN buy\",\n",- " \"exit_rule\": \"IF price_change < -1% THEN sell\"\n",- " }\n",- "]\n",- "\n",- "# Backtest strategies\n",- "backtest_results = []\n",- "for strategy in strategies:\n",- " trades = []\n",- " positions = {}\n",- " \n",- " if parsed_data and parsed_data.get(\"data\"):\n",- " sorted_data = sorted(parsed_data.get(\"data\") if isinstance(parsed_data.get(\"data\"), list) else [parsed_data.get(\"data\")], \n",- " key=lambda x: x.get(\"date\", \"\"))\n",- " \n",- " for entry in sorted_data:\n",- " if isinstance(entry, dict):\n",- " symbol = entry.get(\"symbol\", \"\")\n",- " close_price = entry.get(\"close\", 0)\n",- " date = entry.get(\"date\", \"\")\n",- " \n",- " # Simple strategy logic (moving average simulation)\n",- " if symbol not in positions:\n",- " # Entry signal\n",- " if close_price > 150: # Simplified entry condition\n",- " positions[symbol] = {\n",- " \"entry_price\": close_price,\n",- " \"entry_date\": date,\n",- " \"quantity\": 100\n",- " }\n",- " else:\n",- " # Exit signal\n",- " if close_price > positions[symbol][\"entry_price\"] * 1.02: # 2% profit target\n",- " trades.append({\n",- " \"symbol\": symbol,\n",- " \"entry_price\": positions[symbol][\"entry_price\"],\n",- " \"exit_price\": close_price,\n",- " \"entry_date\": positions[symbol][\"entry_date\"],\n",- " \"exit_date\": date,\n",- " \"profit\": (close_price - positions[symbol][\"entry_price\"]) * positions[symbol][\"quantity\"],\n",- " \"return_pct\": ((close_price - positions[symbol][\"entry_price\"]) / positions[symbol][\"entry_price\"]) * 100\n",- " })\n",- " del positions[symbol]\n",- " \n",- " total_profit = sum(t[\"profit\"] for t in trades)\n",- " total_return = sum(t[\"return_pct\"] for t in trades) / len(trades) if trades else 0\n",- " \n",- " backtest_results.append({\n",- " \"strategy\": strategy[\"name\"],\n",- " \"trades\": len(trades),\n",- " \"total_profit\": total_profit,\n",- " \"average_return\": total_return,\n",- " \"win_rate\": len([t for t in trades if t[\"profit\"] > 0]) / len(trades) if trades else 0\n",- " })\n",- "\n",- "print(f\"Backtested {len(strategies)} trading strategies\")\n",- "for result in backtest_results:\n",- " print(f\" Strategy: {result['strategy']} - Trades: {result['trades']}, Profit: ${result['total_profit']:.2f}, Avg Return: {result['average_return']:.2f}%\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Analyze Performance Metrics\n",- "\n",- "Analyze strategy performance using graph analytics and inference.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "centrality_calculator = CentralityCalculator()\n",- "community_detector = CommunityDetector()\n",- "connectivity_analyzer = ConnectivityAnalyzer()\n",- "# # inference_engine = InferenceEngine()\n",- "rule_manager = RuleManager()\n",- "explanation_generator = ExplanationGenerator()\n",- "\n",- "# Analyze graph structure\n",- "centrality_result = centrality_calculator.calculate_degree_centrality(historical_kg)\n",- "centrality_scores = centrality_result.get('centrality', {})\n",- "communities = community_detector.detect_communities(historical_kg)\n",- "connectivity = connectivity_analyzer.analyze_connectivity(historical_kg)\n",- "\n",- "# Temporal pattern detection\n",- "start_date = \"2023-01-01\"\n",- "end_date = \"2024-01-01\"\n",- "\n",- "temporal_results = temporal_query.query_time_range(\n",- " graph=historical_kg,\n",- " query=\"Find price movements in backtest period\",\n",- " start_time=start_date,\n",- " end_time=end_date\n",- ")\n",- "\n",- "temporal_patterns = temporal_pattern_detector.detect_temporal_patterns(\n",- " historical_kg,\n",- " pattern_type=\"trend\",\n",- " min_frequency=1\n",- ")\n",- "\n",- "# Performance inference rules\n",- "inference_engine.add_rule(\"IF average_return > 5% AND win_rate > 0.6 THEN profitable_strategy\")\n",- "inference_engine.add_rule(\"IF total_profit > 1000 AND trades > 10 THEN successful_backtest\")\n",- "\n",- "for result in backtest_results:\n",- " inference_engine.add_fact({\n",- " \"strategy\": result[\"strategy\"],\n",- " \"average_return\": result[\"average_return\"],\n",- " \"win_rate\": result[\"win_rate\"],\n",- " \"total_profit\": result[\"total_profit\"],\n",- " \"trades\": result[\"trades\"]\n",- " })\n",- "\n",- "# # performance_insights = inference_engine.forward_chain()\n",- "\n",- "print(f\"Performance analysis complete\")\n",- "print(f\" Temporal patterns: {len(temporal_patterns)}\")\n",- "print(f\" Central stocks: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n",- "print(f\" Communities: {len(communities)}\")\n",- "print(f\" Performance insights: {len(performance_insights)}\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Generate Backtest Reports and Visualize\n",- "\n",- "Generate comprehensive backtest reports and visualize results.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "json_exporter = JSONExporter()\n",- "csv_exporter = CSVExporter()\n",- "rdf_exporter = RDFExporter()\n",- "report_generator = ReportGenerator()\n",- "\n",- "quality_score = {\"overall_score\": 0.95}\n",- "\n",- "json_exporter.export_knowledge_graph(historical_kg, os.path.join(temp_dir, \"backtest_kg.json\"))\n",- "csv_exporter.export_entities(historical_entities, os.path.join(temp_dir, \"historical_entities.csv\"))\n",- "rdf_exporter.export_knowledge_graph(historical_kg, os.path.join(temp_dir, \"backtest_kg.rdf\"))\n",- "\n",- "report_data = {\n",- " \"summary\": f\"Strategy backtesting analyzed {len(backtest_results)} strategies on {len(historical_entities)} historical data points\",\n",- " \"strategies_tested\": len(backtest_results),\n",- " \"total_trades\": sum(r[\"trades\"] for r in backtest_results),\n",- " \"best_strategy\": max(backtest_results, key=lambda x: x[\"total_profit\"])[\"strategy\"] if backtest_results else \"N/A\",\n",- " \"patterns_detected\": len(temporal_patterns),\n",- " \"quality_score\": quality_score.get('overall_score', 0)\n",- "}\n",- "\n",- "report = report_generator.generate_report(report_data, format=\"markdown\")\n",- "\n",- "kg_visualizer = KGVisualizer()\n",- "temporal_visualizer = TemporalVisualizer()\n",- "analytics_visualizer = AnalyticsVisualizer()\n",- "\n",- "kg_viz = kg_visualizer.visualize_network(historical_kg, output=\"interactive\")\n",- "temporal_viz = temporal_visualizer.visualize_timeline(historical_kg, output=\"interactive\")\n",- "analytics_viz = analytics_visualizer.visualize_analytics(historical_kg, output=\"interactive\")\n",- "\n",- "print(f\"Total modules used: 20+\")\n",- "print(f\"Pipeline complete: Historical Data \u2192 Parse \u2192 Extract \u2192 Build Temporal KG \u2192 Test Strategies \u2192 Analyze Performance \u2192 Reports \u2192 Visualize\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}\ No newline at end of filediff --git a/docs/concepts.md b/docs/concepts.mdindex 77f453e8..f72f4e94 100644--- a/docs/concepts.md+++ b/docs/concepts.md@@ -1372,42 +1372,51 @@ flowchart TDprint(f" ID: {result['id']}, Score: {result['score']:.3f}")```+=== "Inference-Enhanced Retrieval"+ Apply logical rules to expand retrieval results:++ ```python+ from semantica.reasoning import Reasoner, Rule+ from semantica.semantic_extract import ExplanationGenerator++ # Initialize Reasoner+ reasoner = Reasoner()++ # Add reasoning rules+ reasoner.add_rule(Rule(+ name="employment_transitivity",+ conditions=["?person CEO_OF ?company"],conclusions=["?person WORKS_FOR ?company"],priority=1))- rule_manager.add_rule(Rule(- name="transitivity",+ reasoner.add_rule(Rule(+ name="part_of_transitivity",conditions=["?a PART_OF ?b", "?b PART_OF ?c"],conclusions=["?a PART_OF ?c"],priority=2))- # Define facts+ # Define facts from knowledge graphfacts = [{"subject": "Tim Cook", "predicate": "CEO_OF", "object": "Apple"},{"subject": "iPhone", "predicate": "PART_OF", "object": "Apple"},{"subject": "A15 Chip", "predicate": "PART_OF", "object": "iPhone"}]- # Run inference- inferred = engine.infer(- facts=facts,- rules=rule_manager.get_rules(),- strategy="forward"- )+ # Run inference to discover hidden relationships+ results = reasoner.infer_facts(facts)print(f"Original facts: {len(facts)}")- print(f"After inference: {len(inferred.facts)}")+ print(f"Inferred {len(results)} new facts")++ for fact in results:+ print(f" New fact: {fact}")- # Generate explanations+ # Generate explanations for why these facts were inferredexplainer = ExplanationGenerator()- for new_fact in inferred.new_facts:- explanation = explainer.generate_explanation(- conclusion=new_fact,- reasoning_path=inferred.reasoning_path- )- print(f" {new_fact}: {explanation.summary}")+ # (Assuming we have the full inference results with paths)+ # The Reasoner.forward_chain() provides detailed paths if needed```=== "LLM-Enhanced Retrieval"@@ -1783,8 +1792,94 @@ classDiagram---+### 8. Reasoning & Inference++!!! abstract "Definition"+ **Reasoning** is the process of deriving new knowledge (conclusions) from existing facts (premises) using logical rules. It allows Semantica to "think" beyond what is explicitly stated in the data.++**Reasoning Types**:++- **Forward Chaining**: Starting from known facts and applying rules to see what new facts can be derived. (Data-driven)+- **Backward Chaining**: Starting from a hypothesis (goal) and working backward to see if the available facts support it. (Goal-driven)+- **Abductive Reasoning**: Finding the most likely explanation for a set of observations.+- **Deductive Reasoning**: Applying general rules to specific cases to reach certain conclusions.+**Practical Examples**:+=== "Reasoner Facade"+ The `Reasoner` provides a unified interface for all reasoning tasks:++ ```python+ from semantica.reasoning import Reasoner, Rule++ # Initialize the reasoner+ reasoner = Reasoner()++ # Define a logical rule: If A is a parent of B, and B is a parent of C, then A is a grandparent of C+ reasoner.add_rule(Rule(+ name="grandparent_rule",+ conditions=["?a PARENT_OF ?b", "?b PARENT_OF ?c"],+ conclusions=["?a GRANDPARENT_OF ?c"]+ ))++ # Add initial facts+ facts = [+ "John PARENT_OF Mary",+ "Mary PARENT_OF Alice"+ ]++ # Infer new facts+ new_facts = reasoner.infer_facts(facts)++ print(f"Inferred: {new_facts}")+ # Output: ['John GRANDPARENT_OF Alice']+ ```++=== "SPARQL Reasoning"+ Expand SPARQL queries with inferred patterns:++ ```python+ from semantica.reasoning import SPARQLReasoner++ # Initialize SPARQL reasoner with a triplet store+ sparql_reasoner = SPARQLReasoner(triplet_store=my_store)++ # Define a rule+ sparql_reasoner.reasoner.add_rule("(?x works_at ?y) -> (?x employee_of ?y)")++ # Original query+ query = "SELECT ?x WHERE { ?x employee_of <https://apple.com> }"++ # Expand query to include 'works_at' patterns+ expanded_query = sparql_reasoner.expand_query(query)++ print(f"Expanded Query:\n{expanded_query}")+ ```++=== "Abductive Reasoning"+ Generate hypotheses for observed facts:++ ```python+ from semantica.reasoning import AbductiveReasoner++ reasoner = AbductiveReasoner()++ # Rule: Fire causes smoke+ reasoner.reasoner.add_rule("Fire(?x) -> Smoke(?x)")++ # Observation: There is smoke in the kitchen+ observations = ["Smoke(Kitchen)"]++ # What could have caused this?+ hypotheses = reasoner.generate_hypotheses(observations)++ for h in hypotheses:+ print(f"Possible cause: {h.conclusion} (Likelihood: {h.score})")+ ```++**Related Modules**:+- [`reasoning` Module](reference/reasoning.md) - Core reasoning engines+- [`ontology` Module](reference/ontology.md) - Domain rules and axioms---diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 9f70801e..2ca6b518 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -286,8 +286,6 @@ Deep dive into advanced features, customization, and complex workflows.[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/06_Multi_Source_Data_Integration.ipynb)-<<<<<<< HEAD-<<<<<<< Updated upstream- :material-pipe: **Pipeline Orchestration**---Building robust, automated data processing pipelines.@@ -297,8 +295,6 @@ Deep dive into advanced features, customization, and complex workflows.**Difficulty**: Advanced[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/07_Pipeline_Orchestration.ipynb)-=======->>>>>>> main- :material-brain: **Reasoning and Inference**---@@ -309,9 +305,6 @@ Deep dive into advanced features, customization, and complex workflows.**Difficulty**: Advanced[Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/advanced/08_Reasoning_and_Inference.ipynb)--=======->>>>>>> Stashed changes- :material-layers: **Semantic Layer Construction**---Building a semantic layer over your data warehouse or lake.diff --git a/docs/examples.md b/docs/examples.mdindex 64232c58..e5b5647b 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -248,25 +248,17 @@ results = store.execute_query("MATCH (n)-[r]->(m) WHERE n.name CONTAINS 'AI' RETstore.close()```-<<<<<<< HEAD-<<<<<<< Updated upstream-=======-=======->>>>>>> main### Example 10: GraphRAG (Knowledge-Powered Retrieval)**Difficulty**: Advanced-<<<<<<< HEAD-Build a production-ready GraphRAG system with hybrid retrieval.-=======Build a production-ready GraphRAG system with logical inference and hybrid retrieval.```pythonfrom semantica.context import AgentContext-from semantica.reasoning import InferenceEngine+from semantica.reasoning import Reasoner-# Initialize context with Hybrid Retrieval+# 1. Initialize context with GraphRAG (Hybrid Retrieval)context = AgentContext(vector_store=vs,knowledge_graph=kg,@@ -274,14 +266,23 @@ context = AgentContext(hybrid_alpha=0.7)-# Add logical reasoning rules-engine = InferenceEngine(strategy="forward")-engine.add_rule("IF ?x :type 'Library' AND ?y :type 'Language' THEN ?x :builtWith ?y")+# 2. Enrich Knowledge Graph using Logical Reasoning+reasoner = Reasoner()-# Retrieve context for a query+# Add a rule to categorize technology stack items+reasoner.add_rule("IF Library(?x) AND Language(?y) THEN TechStackItem(?x)")++# Infer new facts from the existing graph+all_facts = kg.get_all_triplets()+inferred = reasoner.infer_facts(all_facts)++# Add inferred knowledge back to the graph+for fact_str in inferred:+ kg.add_fact_from_string(fact_str)++# 3. Retrieve context for a query (now with enriched knowledge)results = context.retrieve("What technologies are used in this project?")```->>>>>>> main[**View Complete GraphRAG Tutorial**](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb)@@ -293,10 +294,6 @@ Benchmark standard Vector RAG against Graph-enhanced retrieval.[**View RAG vs. GraphRAG Comparison**](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/advanced_rag/02_RAG_vs_GraphRAG_Comparison.ipynb)-<<<<<<< HEAD->>>>>>> Stashed changes-=======->>>>>>> main---## Production Patternsdiff --git a/docs/modules.md b/docs/modules.mdindex 9f54f91b..4e226838 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -377,41 +377,40 @@ print(f"Generated {len(owl_content)} lines of OWL")### Reasoning Module!!! abstract "Purpose"- Infers new facts and validates existing knowledge using logical rules. Supports forward/backward chaining and explanation generation.+ Infers new facts and validates existing knowledge using logical rules. Supports forward-chaining, high-performance pattern matching, and explanation generation.**Key Features:**-- Forward and backward chaining-- Rule-based inference-- Deductive and abductive reasoning-- Explanation generation-- RETE algorithm support-- Custom rule definition+- Forward-chaining inference engine+- IF-THEN rule support with variable substitution+- High-performance Rete algorithm for large-scale rule matching+- Natural language explanation generation for inferred facts+- SPARQL query expansion for RDF graphs- Conflict detection in inferences-- Temporal reasoning+- Priority-based rule execution**Components:**-- `RuleManager` β Manage inference rules-- `DeductiveReasoner` β Deductive reasoning-- `AbductiveReasoner` β Abductive reasoning-- `ExplanationGenerator` β Generate explanations for inferences-- `ReteEngine` β Rete algorithm for rule matching+- `Reasoner` β High-level facade for all reasoning tasks+- `ReteEngine` β High-performance pattern matching (Rete algorithm)+- `ExplanationGenerator` β Generate justifications for inferred facts+- `SPARQLReasoner` β Query expansion for triplet stores**Quick Example:**```python-from semantica.reasoning import DeductiveReasoner, Rule, Premise+from semantica.reasoning import Reasoner-reasoner = DeductiveReasoner()+reasoner = Reasoner()-# Define rules and premises-rules = [Rule(id="r1", head="livesIn(?p, ?c)", body=["worksFor(?p, ?co)", "locatedIn(?co, ?c)"])]-premises = [Premise(id="p1", statement="worksFor(Alice, Google)"), Premise(id="p2", statement="locatedIn(Google, London)")]+# Add rules and facts+reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN ParentOfPerson(?x, ?y)")+reasoner.add_fact("Person(Alice)")+reasoner.add_fact("Parent(Alice, Bob)")-conclusions = reasoner.apply_logic(premises, rules=rules)-for c in conclusions:- print(f"Inferred: {c.statement}")+# Perform inference+inferred = reasoner.infer_facts(["Person(Alice)", "Parent(Alice, Bob)"])+# Inferred: ["ParentOfPerson(Alice, Bob)"]```**API Reference**: [Reasoning Module](reference/reasoning.md)@@ -1083,18 +1082,17 @@ results = hybrid_search.search(```pythonfrom semantica.kg import GraphBuilder-from semantica.reasoning import InferenceEngine, RuleManager+from semantica.reasoning import Reasoner# Build temporal graphbuilder = GraphBuilder(temporal=True)kg = builder.build(entities, relationships)# Add reasoning-inference_engine = InferenceEngine()-rule_manager = RuleManager()-rule_manager.add_rules(["IF A THEN B"])+reasoner = Reasoner()+reasoner.add_rule("IF A THEN B")-new_facts = inference_engine.forward_chain(kg, rule_manager)+new_facts = reasoner.infer_facts(kg)```---@@ -1110,7 +1108,7 @@ new_facts = inference_engine.forward_chain(kg, rule_manager)| **Semantic Extract** | `semantica.semantic_extract` | `NERExtractor` | Entity extraction || **KG** | `semantica.kg` | `GraphBuilder` | Graph construction || **Ontology** | `semantica.ontology` | `OntologyGenerator` | Ontology generation |-| **Reasoning** | `semantica.reasoning` | `InferenceEngine` | Logical inference |+| **Reasoning** | `semantica.reasoning` | `Reasoner` | Logical inference || **Embeddings** | `semantica.embeddings` | `EmbeddingGenerator` | Vector generation || **Vector Store** | `semantica.vector_store` | `VectorStore` | Vector storage || **Graph Store** | `semantica.graph_store` | `GraphStore` | Graph database |diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.mdindex e041e170..188aad10 100644--- a/docs/reference/reasoning.md+++ b/docs/reference/reasoning.md@@ -1,6 +1,6 @@# Reasoning-> **Advanced reasoning module supporting SPARQL, Abductive, and Deductive strategies.**+> **Simplified reasoning module supporting rule-based inference, SPARQL, and high-performance pattern matching.**---@@ -8,23 +8,23 @@<div class="grid cards" markdown>-- :material-database-search:{ .lg .middle } **SPARQL Reasoning**+- :material-brain:{ .lg .middle } **Rule-based Inference**---- Query expansion and property chain inference+ Forward-chaining inference engine with variable substitution-- :material-lightbulb-question:{ .lg .middle } **Abductive Reasoning**+- :material-database-search:{ .lg .middle } **SPARQL Reasoning**---- Generate hypotheses to explain observations (Sherlock Holmes style)+ Query expansion and property chain inference for RDF graphs-- :material-check-decagram:{ .lg .middle } **Deductive Reasoning**+- :material-flash:{ .lg .middle } **Rete Algorithm**---- Logical proof generation and theorem proving+ High-performance pattern matching for large rule sets- :material-text-box-search:{ .lg .middle } **Explanation**@@ -32,87 +32,58 @@Generate natural language explanations for inferred facts-- :material-flash:{ .lg .middle } **Rete Algorithm**-- ----- High-performance pattern matching for large rule sets-</div>!!! tip "When to Use"- **Inference**: Deriving new facts from existing data (e.g., `Parent(A,B) & Parent(B,C) -> Grandparent(A,C)`)- **Query Expansion**: Finding results that aren't explicitly stored but implied- - **Hypothesis Generation**: Finding potential causes for an observed event+ - **Explanation**: Understanding the reasoning path for any derived fact- **Validation**: Checking logical consistency of the knowledge graph---## βοΈ Algorithms Used+### Forward Chaining+- **Variable Substitution**: Supports patterns like `Person(?x)` to match facts and bind variables.+- **Recursive Inference**: Continues deriving facts until no new information can be found.+- **Priority-based Execution**: Rules can be prioritized to control the inference flow.+### Rete Algorithm- **Alpha Nodes**: Filter facts by single attributes (e.g., `type=Person`).- **Beta Nodes**: Join results from Alpha nodes (e.g., `Person.id == Parent.child_id`).- **Memory**: Stores partial matches to avoid re-computation.-- **Conflict Resolution**: Priority-based selection when multiple rules match.--### SPARQL Reasoning-- **Query Rewriting**: Modifying queries to include inferred patterns.-- **Property Paths**: Handling transitive relationships (`foaf:knows+`).-- **Materialization**: Pre-computing inferred triplets for fast read performance.--### Abductive Reasoning-- **Hypothesis Generation**: Finding rules where the conclusion matches the observation.-- **Ranking**: Scoring hypotheses by Simplicity, Plausibility, and Coverage.-- **Consistency Check**: Ensuring hypotheses don't contradict known facts.+- **Efficiency**: Optimal for scenarios with many rules and frequent fact updates.---## Main Classes-### ReteEngine--High-performance pattern matching engine.--**Methods:**--| Method | Description |-|--------|-------------|-| `build_network(rules)` | Compile rule into network |-| `add_fact(fact)` | Propagate fact through network |-| `match_patterns()` | Get triggered rules |--### SPARQLReasoner+### Reasoner (Facade)-SPARQL-based reasoner for RDF graphs.+The high-level interface for the reasoning module.**Methods:**| Method | Description ||--------|-------------|-| `expand_query(query)` | Rewrite query with inference |-| `infer_results(result)` | Add inferred triplets to result |+| `infer_facts(facts, rules)` | Derive new facts from initial state |+| `backward_chain(goal)` | Prove a goal using backward chaining |+| `add_rule(rule)` | Add a new inference rule |+| `add_fact(fact)` | Add a fact to working memory |+| `clear()` | Reset the reasoner state |-### AbductiveReasoner+### ReteEngine-Generates explanations for observations.+High-performance pattern matching engine.**Methods:**| Method | Description ||--------|-------------|-| `generate_hypotheses(observations)` | Generate hypotheses |-| `rank_hypotheses(hyps)` | Score and sort |--**Example:**--```python-from semantica.reasoning import AbductiveReasoner--reasoner = AbductiveReasoner(rules)-hypotheses = reasoner.generate_hypotheses(["Pavement is wet"])-# Result: ["It rained", "Sprinkler was on"]-```+| `build_network(rules)` | Compile rules into a Rete network |+| `add_fact(fact)` | Propagate fact through the network |+| `match_patterns()` | Get triggered rules |### ExplanationGenerator@@ -122,95 +93,71 @@ Explains *why* a fact was inferred.| Method | Description ||--------|-------------|-| `generate_explanation(fact)` | Generate reasoning trace |-| `show_reasoning_path(trace)` | Graph visualization |+| `generate_explanation(result)` | Generate reasoning trace for an InferenceResult |----## Convenience Functions+## Usage Examples-```python-from semantica.reasoning import ExplanationGenerator+### Simple Rule-based Inference-# Explain result-explainer = ExplanationGenerator()-explanation = explainer.generate_explanation(conclusion)-print(explanation.natural_language)-```+```python+from semantica.reasoning import Reasoner----+reasoner = Reasoner()-## Configuration+# Define rules+rules = [+ "IF Person(?x) THEN Human(?x)",+ "IF Human(?x) AND Parent(?x, ?y) THEN Human(?y)"+]-### Environment Variables+# Initial facts+facts = ["Person(John)", "Parent(John, Jane)"]-```bash-export REASONING_MAX_ITERATIONS=100-export REASONING_STRATEGY=rete-export REASONING_TIMEOUT=30+# Run inference+new_facts = reasoner.infer_facts(facts, rules)+# Result: ["Human(John)", "Human(Jane)"]```-### YAML Configuration--```yaml-reasoning:- default_strategy: rete- max_depth: 10-- rete:- node_sharing: true-- abductive:- max_hypotheses: 5-```+### Goal-driven Reasoning (Backward Chaining)----+```python+from semantica.reasoning import Reasoner++reasoner = Reasoner()+reasoner.add_rule("IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)")+reasoner.add_fact("Parent(Alice, Bob)")+reasoner.add_fact("Parent(Bob, Charlie)")-## Integration Examples+# Prove a goal+proof = reasoner.backward_chain("Grandparent(Alice, Charlie)")++if proof:+ print(f"Proven: {proof.conclusion}")+ print(f"Steps: {proof.premises}")+```### Knowledge Graph Enrichment```python-from semantica.reasoning import Rule, ReteEngine, DeductiveReasoner+from semantica.reasoning import Reasoner, Rulefrom semantica.kg import KnowledgeGraph-# 1. Define Ontology Rules+# 1. Define Rulesrules = [- Rule("SymmetricSibling", "Sibling(x, y) -> Sibling(y, x)"),- Rule("TransitiveAncestor", "Ancestor(x, y) & Ancestor(y, z) -> Ancestor(x, z)")+ "IF Sibling(?x, ?y) THEN Sibling(?y, ?x)",+ "IF Ancestor(?x, ?y) AND Ancestor(?y, ?z) THEN Ancestor(?x, ?z)"]-# 2. Load Graph+# 2. Load Graph and Run Inferencekg = KnowledgeGraph()-facts = kg.get_all_triplets()--<<<<<<< Updated upstream-# 3. Run Inference-engine = InferenceEngine()-inferred_triplets = engine.infer(facts, rules)--# 4. Update Graph-<<<<<<< HEAD-kg.add_triples(inferred_triples)-=======-# 3. Run Inference-# For example, using a ReteEngine:-rete_engine = ReteEngine()-# rete_engine.add_facts(facts)-# matches = rete_engine.match_patterns()--# Or using a DeductiveReasoner:-# deductive = DeductiveReasoner()-# inferred = deductive.apply_logic(premises)--inferred = [] # Placeholder for actual inference logic--# 4. Update Graph-# kg.add_triplets(inferred)->>>>>>> Stashed changes-=======-kg.add_triplets(inferred_triplets)->>>>>>> main+reasoner = Reasoner()+inferred = reasoner.infer_facts(kg.get_all_triplets(), rules)++# 3. Update Graph+for fact_str in inferred:+ kg.add_fact_from_string(fact_str)```---diff --git a/semantica/reasoning/__init__.py b/semantica/reasoning/__init__.pyindex e159f947..2096d86a 100644--- a/semantica/reasoning/__init__.py+++ b/semantica/reasoning/__init__.py@@ -4,99 +4,9 @@ Reasoning ModuleThis module provides reasoning and inference capabilities for knowledge graphanalysis and query answering, supporting multiple reasoning strategies includingrule-based inference via Rete, SPARQL reasoning, abductive and deductive reasoning.--Algorithms Used:--Rule-Based Inference:- - Rete Algorithm: Forward chaining optimized by rule network, iteration until maturity.- - Backward Chaining: Goal-driven inference, recursive goal decomposition.- - SPARQL Reasoning: Query expansion using inference rules.- - Rule Matching: Pattern matching algorithms (condition-to-fact matching), unification algorithms (variable binding, term unification), variable binding mechanisms (substitution application, binding consistency checking), conflict resolution strategies (priority-based, recency-based, specificity-based)--Rete Algorithm:- - Rete Network Construction: Alpha node creation (one per unique condition pattern), beta node join operations (join left and right inputs with variable unification), terminal node activation (rule activation when all conditions matched), network optimization (shared node detection, redundant node elimination)- - Pattern Matching: Single condition matching (alpha nodes match facts against single condition patterns), multi-condition matching (beta nodes join results from multiple alpha nodes), incremental fact processing (add/remove facts efficiently, propagate changes through network), match propagation (matches flow from alpha to beta to terminal nodes)- - Join Operations: Beta node joins (left input Γ right input with unification constraints), variable unification (bind variables consistently across joins), binding management (maintain variable bindings through join chain), join optimization (selectivity-based join ordering)- - Conflict Resolution: Rule activation ordering (priority-based, recency-based), conflict set management (maintain set of activatable rules), selection strategy (choose rule from conflict set)--<<<<<<< Updated upstream-SPARQL Reasoning:- - Query Expansion: Inference rule integration (convert rules to SPARQL patterns), query rewriting (add inferred patterns to WHERE clause), transitive closure (compute transitive relationships), property chain inference (infer relationships through property chains)- - Query Optimization: Query plan generation (logical plan construction), join ordering (selectivity-based ordering), filter pushdown (apply filters early), projection pushdown (select only needed variables)- - Inference Rule Integration: Rule-to-SPARQL translation (convert rule conditions/conclusions to SPARQL triplet patterns), query augmentation (add inferred patterns), materialization (pre-compute inferred triplets)- - Caching: Query result caching (cache query results by query pattern), cache invalidation (invalidate on data updates), cache hit optimization (fast lookup for repeated queries)--=======->>>>>>> Stashed changes-Abductive Reasoning:- - Hypothesis Generation: Candidate hypothesis creation (generate hypotheses from rules whose conclusions match observation), explanation space exploration (search space of possible explanations), rule-based hypothesis construction (use rules to construct explanatory hypotheses)- - Hypothesis Ranking: Simplicity scoring (prefer hypotheses with fewer conditions, inverse of condition count), plausibility assessment (confidence-based scoring, evidence-based plausibility), consistency checking (check hypothesis consistency with known facts), coverage calculation (measure how well hypothesis explains observation, fraction of observation explained)- - Best Explanation Selection: Ranking-based selection (select highest-ranked hypothesis), multi-criteria optimization (combine simplicity, plausibility, consistency, coverage scores), weighted scoring (weighted sum of ranking criteria)- - Confidence Calculation: Evidence-based confidence (confidence from supporting evidence), uncertainty propagation (propagate uncertainty through reasoning chain), confidence aggregation (combine confidences from multiple sources)--Deductive Reasoning:- - Logical Inference: Modus ponens (if P then Q, P, therefore Q), modus tollens (if P then Q, not Q, therefore not P), syllogistic reasoning (all A are B, all B are C, therefore all A are C), logical rule application (apply standard logical inference rules)- - Proof Generation: Proof tree construction (build tree of inference steps), step-by-step derivation (record each inference step), proof validation (verify proof correctness), proof completion checking (check if proof is complete)- - Theorem Proving: Goal decomposition (decompose theorem into subgoals), subgoal resolution (solve subgoals recursively), proof search (search space of possible proofs), backtracking (backtrack when subgoal fails)- - Argument Construction: Premise-conclusion chains (build chain from premises to conclusion), logical validity checking (verify argument validity), soundness verification (check if conclusion follows from premises)--Rule Management:- - Rule Parsing: Natural language rule parsing (parse "IF condition THEN conclusion" format), structured rule definition (parse structured rule formats), pattern matching (regex-based pattern matching for rule syntax), condition/conclusion extraction- - Rule Validation: Syntax validation (check rule syntax correctness), semantic validation (check rule semantics), consistency checking (check rule consistency with existing rules), completeness checking (check if rule is well-formed)- - Rule Execution: Condition evaluation (evaluate rule conditions against facts), conclusion generation (generate conclusion when conditions match), execution tracking (record rule execution history), performance monitoring (track execution time, success rate)- - Rule Prioritization: Priority-based ordering (order rules by priority), conflict resolution (resolve conflicts using priority), rule scheduling (schedule rule execution based on priority)--Explanation Generation:- - Reasoning Path Construction: Step-by-step path building (build path from initial facts to conclusion), inference chain tracking (track chain of inference steps), path visualization (visualize reasoning path as graph), path optimization (simplify path for readability)- - Justification Creation: Evidence collection (collect supporting evidence for conclusion), support calculation (calculate support strength), confidence propagation (propagate confidence through reasoning chain), justification validation (verify justification correctness)- - Natural Language Generation: Human-readable explanation generation (convert reasoning path to natural language), template-based formatting (use templates for explanation structure), step-by-step narration (narrate each reasoning step), conclusion summarization (summarize final conclusion)- - Visualization: Reasoning path visualization (visualize as directed graph), proof tree rendering (render proof as tree structure), evidence highlighting (highlight supporting evidence), interactive exploration (allow interactive path exploration)--Key Features:- - Rule-based inference via Rete algorithm- - SPARQL-based reasoning and query expansion- - Rete algorithm implementation for efficient rule matching- - Abductive reasoning for hypothesis generation- - Deductive reasoning for logical inference- - Rule management and execution tracking- - Explanation generation for reasoning results- - Proof generation and validation- - Method registry for extensibility- - Configuration management with environment variables and config files--Main Classes:- - SPARQLReasoner: SPARQL-based reasoning and query expansion- - ReteEngine: Rete algorithm implementation for efficient rule matching- - AbductiveReasoner: Abductive reasoning for hypothesis generation- - DeductiveReasoner: Deductive reasoning for logical inference- - RuleManager: Rule management and execution tracking- - ExplanationGenerator: Explanation generation for reasoning results--Convenience Functions:- - sparql_query: SPARQL query execution wrapper- - rete_match: Rete algorithm matching wrapper- - abduce: Abductive reasoning wrapper- - deduce: Deductive reasoning wrapper- - generate_explanation: Explanation generation wrapper- - get_reasoning_method: Get reasoning method by task and name- - list_available_methods: List registered reasoning methods--Example Usage:- >>> from semantica.reasoning import DeductiveReasoner, SPARQLReasoner- >>> # Using Deductive Reasoner- >>> reasoner = DeductiveReasoner()- >>> # results = reasoner.apply_logic(premises, rules)- >>> # Using SPARQL Reasoner- >>> sparql_reasoner = SPARQLReasoner()- >>> query_result = sparql_reasoner.query("SELECT ?s ?p ?o WHERE { ?s ?p ?o }")--Author: Semantica Contributors-License: MIT"""-from .abductive_reasoner import AbductiveReasoner, Explanation as AbductiveExplanation, Hypothesis, HypothesisRanking, Observation-from .deductive_reasoner import Argument, Conclusion, DeductiveReasoner, Premise, Proof-from .reasoner import Reasoner+from .reasoner import Reasoner, InferenceResult, Rule, Fact, RuleTypefrom .graph_reasoner import GraphReasonerfrom .explanation_generator import (Explanation,@@ -108,33 +18,31 @@ from .explanation_generator import (from .rete_engine import (AlphaNode,BetaNode,- Fact,Match,ReteEngine,ReteNode,TerminalNode,)-from .rule_manager import Rule, RuleExecution, RuleManager, RuleTypefrom .sparql_reasoner import SPARQLQueryResult, SPARQLReasoner__all__ = [- "AbductiveReasoner",- "AbductiveExplanation",- "HypothesisRanking",- # Deductive reasoning- "DeductiveReasoner",- "Premise",- "Conclusion",- "Proof",- "Argument",# Reasoner facade"Reasoner","GraphReasoner",- # Rule management- "RuleManager",+ "InferenceResult","Rule",- "RuleExecution",+ "Fact","RuleType",+ # Rete engine+ "ReteEngine",+ "ReteNode",+ "AlphaNode",+ "BetaNode",+ "TerminalNode",+ "Match",+ # SPARQL reasoning+ "SPARQLReasoner",+ "SPARQLQueryResult",# Explanation"ExplanationGenerator","Explanation",diff --git a/semantica/reasoning/abductive_reasoner.py b/semantica/reasoning/abductive_reasoner.pyindex cabc4dbb..0185f09e 100644--- a/semantica/reasoning/abductive_reasoner.py+++ b/semantica/reasoning/abductive_reasoner.py@@ -39,7 +39,7 @@ import refrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from .rule_manager import Rule, RuleManager+from .reasoner import Rule, Reasonerclass HypothesisRanking(Enum):@@ -115,7 +115,7 @@ class AbductiveReasoner:# Initialize progress trackerself.progress_tracker = get_progress_tracker()- self.rule_manager = RuleManager(**self.config)+ self.reasoner = Reasoner(**self.config)self.max_hypotheses = self.config.get("max_hypotheses", 10)self.ranking_strategy = HypothesisRanking(self.config.get("ranking_strategy", "plausibility")@@ -184,7 +184,7 @@ class AbductiveReasoner:hypotheses = []# Get rules that could explain the observation- rules = self.rule_manager.get_all_rules()+ rules = self.reasoner.rules# Find rules whose conclusions match observationfor rule in rules:diff --git a/semantica/reasoning/deductive_reasoner.py b/semantica/reasoning/deductive_reasoner.pyindex c89de59c..98394966 100644--- a/semantica/reasoning/deductive_reasoner.py+++ b/semantica/reasoning/deductive_reasoner.py@@ -37,7 +37,7 @@ import refrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from .rule_manager import Rule, RuleManager+from .reasoner import Rule, Reasoner@dataclass@@ -112,7 +112,7 @@ class DeductiveReasoner:# Initialize progress trackerself.progress_tracker = get_progress_tracker()- self.rule_manager = RuleManager(**self.config)+ self.reasoner = Reasoner(**self.config)self.known_facts: Set[Any] = set()def apply_logic(self, premises: List[Premise], **options) -> List[Conclusion]:@@ -146,7 +146,7 @@ class DeductiveReasoner:self.progress_tracker.update_tracking(tracking_id, message="Applying inference rules...")- rules = self.rule_manager.get_all_rules()+ rules = self.reasoner.rulesfor rule in rules:# Find all matches (bindings) for the rule@@ -387,7 +387,7 @@ class DeductiveReasoner:)# Find rules that can prove goal- rules = self.rule_manager.get_all_rules()+ rules = self.reasoner.rules# Use unified matching for finding applicable rulesapplicable_rules_and_bindings = []diff --git a/semantica/reasoning/explanation_generator.py b/semantica/reasoning/explanation_generator.pyindex 078ecd93..e946324c 100644--- a/semantica/reasoning/explanation_generator.py+++ b/semantica/reasoning/explanation_generator.py@@ -36,10 +36,9 @@ from typing import Any, Dict, List, Optionalfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker+from .reasoner import InferenceResult, Rule+from .deductive_reasoner import Prooffrom .abductive_reasoner import Explanation as AbductiveExplanation-from .deductive_reasoner import Conclusion, Proof-from .inference_engine import InferenceResult-from .rule_manager import Rule@dataclassdiff --git a/semantica/reasoning/reasoner.py b/semantica/reasoning/reasoner.pyindex 22d6fbda..d3b35585 100644--- a/semantica/reasoning/reasoner.py+++ b/semantica/reasoning/reasoner.py@@ -2,22 +2,57 @@Reasoner ModuleThis module provides a high-level Reasoner class that unifies various reasoning strategies-supported by the Semantica framework. It serves as a facade for different reasoning engines-<<<<<<< HEAD-like SPARQLReasoner, etc.-=======-like InferenceEngine, SPARQLReasoner, etc.->>>>>>> main+supported by the Semantica framework. It serves as a facade for different reasoning engines."""-from typing import Any, Dict, List, Optional, Union+import re+import uuid+from dataclasses import dataclass, field+from enum import Enum+from typing import Any, Dict, List, Optional, Set, Union, Callable+from ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-<<<<<<< HEAD-=======-from .inference_engine import InferenceEngine, InferenceStrategy->>>>>>> main-from .rule_manager import Rule++class RuleType(Enum):+ """Rule types."""+ IMPLICATION = "implication"+ EQUIVALENCE = "equivalence"+ CONSTRAINT = "constraint"+ TRANSFORMATION = "transformation"++@dataclass+class Rule:+ """Simplified rule definition."""+ rule_id: str+ name: str+ conditions: List[Any]+ conclusion: Any+ rule_type: RuleType = RuleType.IMPLICATION+ confidence: float = 1.0+ priority: int = 0+ handler: Optional[Callable] = None+ metadata: Dict[str, Any] = field(default_factory=dict)++@dataclass+class Fact:+ """Simple fact representation."""+ fact_id: str+ predicate: str+ arguments: List[Any]+ metadata: Dict[str, Any] = field(default_factory=dict)++ def __str__(self) -> str:+ return f"{self.predicate}({', '.join(map(str, self.arguments))})"++@dataclass+class InferenceResult:+ """Result of an inference step."""+ conclusion: str+ rule_used: Optional[Rule] = None+ premises: List[str] = field(default_factory=list)+ confidence: float = 1.0+ metadata: Dict[str, Any] = field(default_factory=dict)class Reasoner:"""@@ -27,32 +62,49 @@ class Reasoner:or knowledge graphs."""- def __init__(self, strategy: str = "forward", **kwargs):+ def __init__(self, **kwargs):"""Initialize the Reasoner.Args:- strategy: Inference strategy ("forward", "backward", etc.)**kwargs: Additional configuration options"""self.logger = get_logger("reasoner")self.progress_tracker = get_progress_tracker()- self.strategy = strategyself.config = kwargs-<<<<<<< HEAD- # Inference engine disabled- self.engine = None-=======- # Initialize the underlying engine based on strategy- # Currently defaults to InferenceEngine for forward/backward chaining- if strategy in ["forward", "backward"]:- self.engine = InferenceEngine(strategy=strategy, **kwargs)+ self.rules: List[Rule] = []+ self.facts: Set[str] = set()+ self.rule_counter = 0++ def add_rule(self, rule_def: Union[str, Rule]) -> Rule:+ """Add a rule to the reasoner."""+ if isinstance(rule_def, Rule):+ rule = rule_defelse:- # Default to forward chaining if unknown strategy- self.engine = InferenceEngine(strategy="forward", **kwargs)->>>>>>> main+ rule = self._parse_rule_definition(rule_def)+ self.rules.append(rule)+ # Sort rules by priority+ self.rules.sort(key=lambda r: r.priority, reverse=True)+ return rule++ def add_fact(self, fact: Union[str, Dict[str, Any]]) -> None:+ """Add a fact to working memory."""+ if isinstance(fact, str):+ self.facts.add(fact.strip())+ elif isinstance(fact, dict):+ # Convert KG-style dict to fact strings+ if "type" in fact and ("name" in fact or "id" in fact):+ name = fact.get("name", fact.get("id"))+ etype = fact.get("type", "Entity")+ self.facts.add(f"{etype}({name})")+ elif "source_id" in fact or "source_name" in fact:+ source = fact.get("source_name", fact.get("source_id"))+ target = fact.get("target_name", fact.get("target_id"))+ rtype = fact.get("type", "Relationship")+ self.facts.add(f"{rtype}({source}, {target})")+def infer_facts(self,facts: Union[List[Any], Dict[str, Any]],@@ -63,96 +115,30 @@ class Reasoner:Args:facts: List of initial facts or a knowledge graph dictionary.-<<<<<<< HEAD- If a list is provided, it can contain strings, dicts, or MergeOperation objects.-=======- If a list is provided, it can contain strings, dicts, or MergeOperation objects.->>>>>>> mainrules: List of rules to apply (strings or Rule objects)Returns:List of inferred facts (conclusions)"""-<<<<<<< HEAD- if self.engine is None:- self.logger.warning("Inference engine is currently disabled.")- return []-- # Note: This method is a placeholder as the InferenceEngine is currently disabled.- return []-- def add_rule(self, rule: Union[str, Rule]) -> None:- """Add a rule to the reasoner."""- if self.engine:- self.engine.add_rule(rule)-- def clear(self) -> None:- """Clear facts and rules."""- if self.engine:- self.engine.reset()-=======- # Pre-process facts if they come from a knowledge graph or are MergeOperation objects- processed_facts = []-- if isinstance(facts, dict):- # If it's a knowledge graph, extract facts from entities and relationships- if "entities" in facts:- for entity in facts["entities"]:- # Create simple fact string for reasoning- # e.g., Person(John)- name = entity.get("name", entity.get("id"))- etype = entity.get("type", "Entity")- processed_facts.append(f"{etype}({name})")-- if "relationships" in facts:- for rel in facts["relationships"]:- # Create simple relationship fact string- # e.g., WorksFor(John, Acme)- source = rel.get("source_name", rel.get("source_id"))- target = rel.get("target_name", rel.get("target_id"))- rtype = rel.get("type", "Relationship")- processed_facts.append(f"{rtype}({source}, {target})")-- elif isinstance(facts, list):- for item in facts:- # Check if it's a MergeOperation (which has a merged_entity)- if hasattr(item, "merged_entity"):- entity = item.merged_entity- name = entity.get("name", entity.get("id"))- etype = entity.get("type", "Entity")- processed_facts.append(f"{etype}({name})")- elif isinstance(item, dict):- # It's an entity dictionary- name = item.get("name", item.get("id"))- etype = item.get("type", "Entity")- processed_facts.append(f"{etype}({name})")- else:- # Assume it's already a fact string or compatible object- processed_facts.append(item)-- if not processed_facts:- processed_facts = facts if isinstance(facts, list) else []-tracking_id = self.progress_tracker.start_tracking(module="reasoning",submodule="Reasoner",- message=f"Inferring facts from {len(processed_facts)} processed facts"+ message="Inferring facts")try:- # Add rules if provided+ if isinstance(facts, list):+ for f in facts:+ self.add_fact(f)+ else:+ self.add_fact(facts)+if rules:for rule in rules:- self.engine.add_rule(rule)+ self.add_rule(rule)# Perform inference- # The engine.infer method (or forward_chain) returns InferenceResult objects- # We want to return the actual facts (conclusions)- if self.strategy == "forward":- results = self.engine.forward_chain(processed_facts)- else:- # Fallback to general infer method- results = self.engine.infer(processed_facts, rules)+ results = self.forward_chain()# Extract conclusions from resultsinferred_facts = [result.conclusion for result in results]@@ -173,12 +159,207 @@ class Reasoner:)self.logger.error(f"Inference failed: {e}")raise++ def forward_chain(self) -> List[InferenceResult]:+ """Derive all possible new facts using forward chaining."""+ tracking_id = self.progress_tracker.start_tracking(+ module="reasoning",+ submodule="Reasoner",+ message="Performing forward chaining"+ )++ results = []+ new_facts_added = True+ max_iterations = self.config.get("max_iterations", 50)+ iteration = 0++ while new_facts_added and iteration < max_iterations:+ new_facts_added = False+ iteration += 1- def add_rule(self, rule: Union[str, Rule]) -> None:- """Add a rule to the reasoner."""- self.engine.add_rule(rule)+ for rule in self.rules:+ matches = self._match_rule(rule)+ for conclusion in matches:+ if conclusion not in self.facts:+ self.facts.add(conclusion)+ results.append(InferenceResult(+ conclusion=conclusion,+ rule_used=rule,+ confidence=rule.confidence+ ))+ new_facts_added = True++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Forward chaining completed: {len(results)} new facts inferred"+ )+ return results++ def backward_chain(self, goal: str, max_depth: int = 10) -> Optional[InferenceResult]:+ """+ Prove a goal using backward chaining.++ Args:+ goal: The fact string to prove+ max_depth: Maximum recursion depth++ Returns:+ InferenceResult if proven, None otherwise+ """+ tracking_id = self.progress_tracker.start_tracking(+ module="reasoning",+ submodule="Reasoner",+ message="Performing backward chaining"+ )++ try:+ result = self._prove_goal(goal, depth=0, max_depth=max_depth)++ status = "completed" if result else "not_proven"+ self.progress_tracker.stop_tracking(+ tracking_id,+ status=status,+ message=f"Backward chaining finished: {'Proven' if result else 'Not proven'}"+ )+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise++ def _prove_goal(self, goal: str, depth: int, max_depth: int) -> Optional[InferenceResult]:+ """Recursive goal prover."""+ if depth > max_depth:+ return None++ # 1. Check if goal is already in facts+ if goal in self.facts:+ return InferenceResult(conclusion=goal, premises=[])++ # 2. Check if goal matches a known fact pattern (unification)+ for fact in self.facts:+ if self._match_pattern(goal, fact, {}) is not None:+ return InferenceResult(conclusion=fact, premises=[])++ # 3. Try to prove via rules+ for rule in self.rules:+ # Check if rule conclusion can match the goal+ initial_bindings = self._match_pattern(rule.conclusion, goal, {})+ if initial_bindings is not None:+ # Try to prove all conditions+ all_conditions_proven = True+ premises = []+ current_bindings = initial_bindings.copy()++ for condition in rule.conditions:+ instantiated_cond = self._substitute(condition, current_bindings)+ cond_result = self._prove_goal(instantiated_cond, depth + 1, max_depth)++ if cond_result:+ premises.append(cond_result.conclusion)+ # Update bindings from the actual fact that matched+ new_bindings = self._match_pattern(condition, cond_result.conclusion, current_bindings)+ if new_bindings:+ current_bindings = new_bindings+ else:+ all_conditions_proven = False+ break++ if all_conditions_proven:+ instantiated_conclusion = self._substitute(rule.conclusion, current_bindings)+ return InferenceResult(+ conclusion=instantiated_conclusion,+ rule_used=rule,+ premises=premises,+ confidence=rule.confidence+ )++ return None++ def _parse_rule_definition(self, definition: str) -> Rule:+ """Parse IF-THEN rule strings."""+ definition = definition.strip()+ if_match = re.match(r"IF\s+(.+?)\s+THEN\s+(.+)$", definition, re.IGNORECASE | re.DOTALL)++ if not if_match:+ # Fallback or error+ self.rule_counter += 1+ return Rule(f"rule_{self.rule_counter}", f"Rule {self.rule_counter}", [], definition)++ conditions_str = if_match.group(1)+ conclusion_str = if_match.group(2)++ # Split conditions by AND+ conditions = [c.strip() for c in re.split(r"\s+AND\s+", conditions_str, flags=re.IGNORECASE)]++ self.rule_counter += 1+ return Rule(+ rule_id=f"rule_{self.rule_counter}",+ name=f"Rule {self.rule_counter}",+ conditions=conditions,+ conclusion=conclusion_str.strip()+ )++ def _match_rule(self, rule: Rule) -> List[str]:+ """Match rule conditions against facts and return instantiated conclusions."""+ if not rule.conditions:+ return []++ bindings_list = [{}] # List of possible variable bindings++ for condition in rule.conditions:+ new_bindings_list = []+ for bindings in bindings_list:+ for fact in self.facts:+ match_bindings = self._match_pattern(condition, fact, bindings)+ if match_bindings is not None:+ new_bindings_list.append(match_bindings)+ bindings_list = new_bindings_list+ if not bindings_list:+ break++ results = []+ for bindings in bindings_list:+ instantiated_conclusion = self._substitute(rule.conclusion, bindings)+ results.append(instantiated_conclusion)++ return results++ def _match_pattern(self, pattern: str, fact: str, initial_bindings: Dict[str, str]) -> Optional[Dict[str, str]]:+ """Match a pattern against a fact with initial bindings."""+ # Simple regex-based matcher for patterns like "Person(?x)" and facts like "Person(John)"++ p_regex = re.escape(pattern)+ p_regex = re.sub(r"\\\?(\w+)", r"(?P<\1>.+)", p_regex)+ p_regex = f"^{p_regex}$"++ try:+ match = re.match(p_regex, fact)+ if match:+ new_bindings = initial_bindings.copy()+ for var, value in match.groupdict().items():+ if var in new_bindings and new_bindings[var] != value:+ return None # Binding conflict+ new_bindings[var] = value+ return new_bindings+ except Exception:+ pass++ return None++ def _substitute(self, pattern: str, bindings: Dict[str, str]) -> str:+ """Substitute variables in a pattern with bound values."""+ result = pattern+ for var, value in bindings.items():+ result = result.replace(f"?{var}", value)+ return resultdef clear(self) -> None:"""Clear facts and rules."""- self.engine.reset()->>>>>>> main+ self.facts.clear()+ self.rules.clear()+ self.rule_counter = 0++ def reset(self) -> None:+ """Alias for clear()."""+ self.clear()diff --git a/semantica/reasoning/reasoning_usage.md b/semantica/reasoning/reasoning_usage.mdindex 75afde77..39a99dda 100644--- a/semantica/reasoning/reasoning_usage.md+++ b/semantica/reasoning/reasoning_usage.md@@ -1,175 +1,47 @@# Reasoning Module Usage Guide-The **Semantica Reasoning Module** provides a suite of tools for deriving new knowledge from existing facts and knowledge graphs. It supports multiple strategies including deductive, abductive, and SPARQL-based reasoning.+The **Semantica Reasoning Module** provides a suite of tools for deriving new knowledge from existing facts and knowledge graphs. It supports multiple strategies including rule-based inference, SPARQL-based reasoning, and specialized abductive/deductive reasoners.## π Quick Start```python-from semantica.reasoning import DeductiveReasoner, Rule, Premise+from semantica.reasoning import Reasoner, Rule, Fact-<<<<<<< Updated upstream-# Create inference engine-engine = InferenceEngine()+# Create reasoner+reasoner = Reasoner()# Add facts-engine.add_fact("Person(John)")-engine.add_fact("Person(Jane)")+reasoner.add_fact("Person(John)")+reasoner.add_fact("Person(Jane)")# Add rule-rule = engine.add_rule("IF Person(?x) THEN Human(?x)")+rule = reasoner.add_rule("IF Person(?x) THEN Human(?x)")-# Perform forward chaining-results = engine.forward_chain()+# Perform inference+results = reasoner.infer()print(f"Inferred {len(results)} new facts")+for res in results:+ print(f"Fact: {res.conclusion}")```-### Using SPARQL Reasoner--```python-from semantica.reasoning import SPARQLReasoner--# Create SPARQL reasoner-reasoner = SPARQLReasoner(triplet_store=kg)--# Execute query-query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }"-result = reasoner.execute_query(query)--print(f"Found {len(result.bindings)} results")-```+## Core Components-### Using Rete Engine+### 1. Reasoner (Facade)+The `Reasoner` class provides a simplified, unified interface to the reasoning system. It is the recommended entry point for all reasoning tasks.```python-from semantica.reasoning import ReteEngine, Fact--# Create Rete engine-rete = ReteEngine()+from semantica.reasoning import Reasoner-# Add rules-rete.add_rule(rule1)-rete.add_rule(rule2)+reasoner = Reasoner()+reasoner.add_fact("WorksFor(John, Acme)")+reasoner.add_rule("IF WorksFor(?x, ?y) THEN Employee(?x, ?y)")-# Add facts-fact = Fact("f1", "Person", ["John"])-rete.add_fact(fact)--# Get matches-matches = rete.match_patterns()-print(f"Found {len(matches)} matches")+results = reasoner.infer()```-## Rule-Based Inference--### Forward Chaining--Forward chaining is a data-driven inference strategy that starts with known facts and applies rules to derive new conclusions.--```python-from semantica.reasoning import InferenceEngine, InferenceStrategy--# Create inference engine-engine = InferenceEngine(strategy=InferenceStrategy.FORWARD)--# Add initial facts-engine.add_fact("Person(John)")-engine.add_fact("Person(Jane)")-engine.add_fact("WorksFor(John, Acme)")--# Add rules-engine.add_rule("IF Person(?x) THEN Human(?x)")-engine.add_rule("IF WorksFor(?x, ?y) AND Person(?x) THEN Employee(?x, ?y)")--# Perform forward chaining-results = engine.forward_chain()--for result in results:- print(f"Inferred: {result.conclusion}")- print(f"Using rule: {result.rule_used.name}")- print(f"Confidence: {result.confidence}")-```--### Backward Chaining--Backward chaining is a goal-driven inference strategy that starts with a goal and works backwards to find supporting facts.--```python-from semantica.reasoning import InferenceEngine--engine = InferenceEngine()--# Add facts-engine.add_fact("Person(John)")-engine.add_fact("WorksFor(John, Acme)")--# Add rules-engine.add_rule("IF Person(?x) THEN Human(?x)")-engine.add_rule("IF WorksFor(?x, ?y) AND Person(?x) THEN Employee(?x, ?y)")--# Perform backward chaining to prove goal-goal = "Employee(John, Acme)"-result = engine.backward_chain(goal)--if result:- print(f"Goal '{goal}' is provable")- print(f"Proof: {result.premises} -> {result.conclusion}")-else:- print(f"Goal '{goal}' cannot be proven")-```--### Bidirectional Chaining--Bidirectional chaining combines forward and backward chaining for more efficient inference.--```python-from semantica.reasoning import InferenceEngine, InferenceStrategy--engine = InferenceEngine(strategy=InferenceStrategy.BIDIRECTIONAL)--# Add facts and rules-engine.add_fact("Person(John)")-engine.add_rule("IF Person(?x) THEN Human(?x)")--# Perform bidirectional inference-goal = "Human(John)"-results = engine.infer(goal)--print(f"Found {len(results)} inference paths")-```--### Inference with Custom Rules--```python-from semantica.reasoning import InferenceEngine, Rule, RuleType--engine = InferenceEngine()--# Create custom rule-rule = Rule(- rule_id="r1",- name="TransitiveLocation",- conditions=["LocatedIn(?x, ?y)", "LocatedIn(?y, ?z)"],- conclusion="LocatedIn(?x, ?z)",- rule_type=RuleType.IMPLICATION,- confidence=0.9,- priority=1-)--engine.add_rule(rule)--# Add facts-engine.add_fact("LocatedIn(Paris, France)")-engine.add_fact("LocatedIn(France, Europe)")--# Infer-results = engine.forward_chain()-# Will infer: LocatedIn(Paris, Europe)-```--## SPARQL Reasoning--### Basic SPARQL Query+### 2. SPARQL Reasoner+Used for reasoning over RDF/Triplet stores using SPARQL query expansion.```pythonfrom semantica.reasoning import SPARQLReasoner@@ -177,988 +49,45 @@ from semantica.reasoning import SPARQLReasoner# Create reasoner with knowledge graphreasoner = SPARQLReasoner(triplet_store=kg)-# Execute SPARQL query-query = """-SELECT ?person ?company-WHERE {- ?person :worksFor ?company .- ?person :type :Person .-}-"""--result = reasoner.execute_query(query)--for binding in result.bindings:- print(f"Person: {binding.get('person')}, Company: {binding.get('company')}")-```--### Query Expansion with Inference Rules--```python-from semantica.reasoning import SPARQLReasoner--reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)--# Add inference rule-reasoner.add_inference_rule("IF ?x :type :Company THEN ?x :type :Organization")--# Original query-query = "SELECT ?x WHERE { ?x :type :Organization }"--# Query is automatically expanded with inference rules-result = reasoner.execute_query(query)--# Results include both explicit :Organization types and inferred from :Company-```----### SPARQL with RDF Inference--```python-from semantica.reasoning import SPARQLReasoner--reasoner = SPARQLReasoner(- triplet_store=kg,- enable_inference=True,- inference_rules=["rdfs:subClassOf", "rdfs:subPropertyOf"]-)--# Query will use RDFS inference-query = """-SELECT ?person-WHERE {- ?person a :Employee .-}-"""--# Will also match :Person if :Employee rdfs:subClassOf :Person+# Execute query+query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }"result = reasoner.execute_query(query)```-## Rete Algorithm--### Building Rete Network--```python-from semantica.reasoning import ReteEngine, Rule, RuleType--# Create Rete engine-rete = ReteEngine()--# Define rules-rule1 = Rule(- rule_id="r1",- name="PersonRule",- conditions=["Person(?x)"],- conclusion="Human(?x)",- rule_type=RuleType.IMPLICATION-)--rule2 = Rule(- rule_id="r2",- name="EmployeeRule",- conditions=["WorksFor(?x, ?y)", "Person(?x)"],- conclusion="Employee(?x, ?y)",- rule_type=RuleType.IMPLICATION-)--# Build network from rules-rete.build_network([rule1, rule2])--print(f"Built network with {len(rete.network)} nodes")-```--### Pattern Matching with Rete--```python-from semantica.reasoning import ReteEngine, Fact--rete = ReteEngine()-rete.build_network([rule1, rule2])--# Add facts-fact1 = Fact("f1", "Person", ["John"])-fact2 = Fact("f2", "WorksFor", ["John", "Acme"])--rete.add_fact(fact1)-rete.add_fact(fact2)--# Get matches-matches = rete.match_patterns()--for match in matches:- print(f"Rule: {match.rule.name}")- print(f"Facts: {[f.fact_id for f in match.facts]}")- print(f"Bindings: {match.bindings}")-```--### Incremental Fact Processing+### 3. Rete Engine+High-performance pattern matching for complex rule sets.```pythonfrom semantica.reasoning import ReteEngine, Factrete = ReteEngine()-rete.build_network([rule1, rule2])--# Add facts incrementally-fact1 = Fact("f1", "Person", ["John"])-rete.add_fact(fact1)-# Get matches+# ... build network and add facts ...matches = rete.match_patterns()--fact2 = Fact("f2", "WorksFor", ["John", "Acme"])-rete.add_fact(fact2)-# Now includes matches for rule2-matches2 = rete.match_patterns()--# Reset engine (clears facts and matches)-rete.reset()-```--### Rete Network Optimization--```python-from semantica.reasoning import ReteEngine--rete = ReteEngine()--# Build network-rete.build_network(rules)--# Network automatically optimizes:-# - Shared alpha nodes for common conditions-# - Efficient join ordering-# - Redundant node elimination--print(f"Network nodes: {len(rete.network)}")-print(f"Alpha nodes: {sum(1 for n in rete.network.values() if isinstance(n, AlphaNode))}")-print(f"Beta nodes: {sum(1 for n in rete.network.values() if isinstance(n, BetaNode))}")-```--## Abductive Reasoning--### Hypothesis Generation--```python-from semantica.reasoning import AbductiveReasoner, Observation--# Create abductive reasoner-reasoner = AbductiveReasoner()--# Define observation-observation = Observation(- observation_id="obs1",- description="Person X is in location Y",- facts=["LocatedIn(PersonX, LocationY)"]-)--# Generate hypotheses-hypotheses = reasoner.generate_hypotheses([observation])--for hypothesis in hypotheses:- print(f"Hypothesis: {hypothesis.explanation}")- print(f"Confidence: {hypothesis.confidence}")- print(f"Coverage: {hypothesis.coverage}")- print(f"Simplicity: {hypothesis.simplicity}")-```--### Hypothesis Ranking--```python-from semantica.reasoning import AbductiveReasoner, HypothesisRanking--reasoner = AbductiveReasoner()--# Generate hypotheses-hypotheses = reasoner.generate_hypotheses(observations)--# Rank by simplicity-ranked_simplicity = reasoner.rank_hypotheses(- hypotheses,- ranking_strategy=HypothesisRanking.SIMPLICITY-)--# Rank by plausibility-ranked_plausibility = reasoner.rank_hypotheses(- hypotheses,- ranking_strategy=HypothesisRanking.PLAUSIBILITY-)--# Rank by coverage-ranked_coverage = reasoner.rank_hypotheses(- hypotheses,- ranking_strategy=HypothesisRanking.COVERAGE-)--# Get best hypothesis-best = ranked_plausibility[0]-print(f"Best explanation: {best.explanation}")-```--### Finding Best Explanation--```python-from semantica.reasoning import AbductiveReasoner, Observation--reasoner = AbductiveReasoner()--# Find best explanation for observation-observation = Observation(- observation_id="obs1",- description="The ground is wet",- facts=["Wet(Ground)"]-)--explanations = reasoner.find_explanations([observation])--for explanation in explanations:- print(f"Observation: {explanation.observation.description}")- print(f"Best hypothesis: {explanation.best_hypothesis.explanation}")- print(f"Confidence: {explanation.confidence}")-```--### Abductive Reasoning with Rules--```python-from semantica.reasoning import AbductiveReasoner, Observation, Rule, RuleType--reasoner = AbductiveReasoner()--# Add rules that can explain observations-rule = Rule(- rule_id="r1",- name="RainRule",- conditions=["Raining"],- conclusion="Wet(Ground)",- rule_type=RuleType.IMPLICATION-)--reasoner.rule_manager.add_rule(rule)--# Generate hypotheses-observation = Observation("obs1", "The ground is wet", ["Wet(Ground)"])-hypotheses = reasoner.generate_hypotheses([observation])--# Will generate hypothesis: "Raining" explains "Wet(Ground)"-```--## Deductive Reasoning--### Basic Deductive Inference--```python-from semantica.reasoning import DeductiveReasoner, Premise--# Create deductive reasoner-=======-# 1. Initialize Reasoner->>>>>>> Stashed changes-reasoner = DeductiveReasoner()--# 2. Define Rules-reasoner.rule_manager.add_rule(Rule(- name="GrandparentOf",- conditions=["parent_of(?a, ?b)", "parent_of(?b, ?c)"],- conclusion="grandparent_of(?a, ?c)"-))--# 3. Define Premises-premises = [- Premise("p1", "parent_of(Alice, Bob)"),- Premise("p2", "parent_of(Bob, Charlie)")-]--# 4. Infer Conclusions-conclusions = reasoner.apply_logic(premises)-for c in conclusions:- print(f"Inferred: {c.statement}")-# Output: Inferred: grandparent_of(Alice, Charlie)```-## π§ Reasoning Strategies--### 1. Deductive Reasoning-Used for proving statements that logically follow from premises.-* **Class**: `DeductiveReasoner`-* **Key Methods**: `apply_logic`, `prove_theorem`, `validate_argument`.--### 2. Abductive Reasoning-Used for generating the best possible explanation for an observation.-* **Class**: `AbductiveReasoner`-* **Key Method**: `abduce`+## Data Structures-### 3. SPARQL Reasoning-Used for reasoning over RDF/Triplet stores using SPARQL query expansion.-* **Class**: `SPARQLReasoner`-* **Key Method**: `query`+### Rule+Represents an inference rule with conditions and a conclusion.+- `rule_id`: Unique identifier+- `name`: Human-readable name+- `conditions`: List of patterns to match+- `conclusion`: Pattern to derive+- `rule_type`: IMPLICATION, EQUIVALENCE, etc.-### 4. Rete Engine-High-performance pattern matching for complex rule sets.-* **Class**: `ReteEngine`-* **Key Method**: `match`+### Fact+Represents a single piece of knowledge.+- `fact_id`: Unique identifier+- `predicate`: Relationship or property name+- `arguments`: List of subjects/objects-## π‘ Explanation Generation+## Explanation GenerationAll reasoning results can be passed to the `ExplanationGenerator` to produce human-readable justifications.```pythonfrom semantica.reasoning import ExplanationGeneratorexplainer = ExplanationGenerator()-explanation = explainer.generate_explanation(conclusions[0])+explanation = explainer.generate_explanation(results[0])print(explanation.natural_language)```-<<<<<<< Updated upstream--### Explanation for Different Reasoning Types--```python-from semantica.reasoning import ExplanationGenerator--generator = ExplanationGenerator()--# Explain inference result-inference_explanation = generator.generate_explanation(inference_result)--# Explain proof-proof_explanation = generator.generate_explanation(proof)--# Explain abductive explanation-abductive_explanation = generator.generate_explanation(abductive_result)--# Each explanation type has appropriate structure-print(f"Inference explanation: {inference_explanation.explanation_type}")-print(f"Proof explanation: {proof_explanation.explanation_type}")-print(f"Abductive explanation: {abductive_explanation.explanation_type}")-```--## Algorithms and Methods--### Rule-Based Inference Algorithms--#### Forward Chaining-**Algorithm**: Iterative rule application with fact propagation--1. **Initialization**: Start with initial fact set-2. **Iteration**: While new facts are derived:- - For each rule:- - Check if all conditions are satisfied by current facts- - If yes, add conclusion to fact set- - Mark as new fact-3. **Termination**: Stop when no new facts are derived or max iterations reached-4. **Conflict Resolution**: If multiple rules can fire, select by priority--**Time Complexity**: O(r Γ f Γ i) where r = rules, f = facts, i = iterations-**Space Complexity**: O(f) for fact storage--```python-# Forward chaining example-engine = InferenceEngine()-engine.add_facts(["A", "B"])-engine.add_rule("IF A AND B THEN C")-engine.add_rule("IF C THEN D")-results = engine.forward_chain()-# Results: [C, D]-```--#### Backward Chaining-**Algorithm**: Goal-driven recursive proof search--1. **Goal Check**: If goal is in facts, return success-2. **Rule Selection**: Find rules whose conclusions match goal-3. **Recursive Proof**: For each applicable rule:- - Recursively prove each premise- - If all premises proven, return success-4. **Backtracking**: If proof fails, try next rule-5. **Termination**: Return when goal proven or all paths exhausted--**Time Complexity**: O(r^d) where r = rules, d = proof depth-**Space Complexity**: O(d) for recursion stack--```python-# Backward chaining example-engine = InferenceEngine()-engine.add_facts(["A", "B"])-engine.add_rule("IF A AND B THEN C")-engine.add_rule("IF C THEN D")-result = engine.backward_chain("D")-# Proves: D <- C <- (A AND B)-```--#### Bidirectional Chaining-**Algorithm**: Meet-in-the-middle strategy--1. **Forward Pass**: Start from facts, apply rules forward-2. **Backward Pass**: Start from goal, apply rules backward-3. **Intersection**: Check if forward and backward paths meet-4. **Path Construction**: Combine forward and backward paths-5. **Optimization**: Use heuristics to guide search--**Time Complexity**: O(r Γ f + r^d) combining forward and backward-**Space Complexity**: O(f + d) for both passes--### Rete Algorithm--#### Network Construction-**Algorithm**: Build Rete network from rules--1. **Alpha Node Creation**: Create one alpha node per unique condition pattern-2. **Beta Node Joins**: Create beta nodes to join alpha node outputs-3. **Terminal Node Activation**: Create terminal node for each rule-4. **Network Optimization**: Share common alpha nodes, eliminate redundancy--**Time Complexity**: O(r Γ c) where r = rules, c = conditions per rule-**Space Complexity**: O(r Γ c) for network storage--```python-# Rete network construction-rete = ReteEngine()-rete.build_network([rule1, rule2])-# Creates optimized network with shared nodes-```--#### Pattern Matching-**Algorithm**: Incremental fact processing through network--1. **Fact Addition**: Add fact to working memory-2. **Alpha Matching**: Match fact against alpha node conditions-3. **Beta Joins**: Join alpha matches through beta nodes-4. **Terminal Activation**: Activate terminal nodes when all conditions matched-5. **Match Collection**: Collect all terminal node activations--**Time Complexity**: O(n Γ m) where n = facts, m = network nodes-**Space Complexity**: O(n + m) for matches and network--```python-# Pattern matching-rete.add_fact(Fact("f1", "Person", ["John"]))-matches = rete.match_patterns()-# Efficiently finds all rule matches-```--#### Join Operations-**Algorithm**: Beta node join with unification--1. **Left Input**: Receive matches from left child-2. **Right Input**: Receive matches from right child-3. **Unification**: Check variable bindings are consistent-4. **Join**: Create joined matches with unified bindings-5. **Propagation**: Send joined matches to children--**Time Complexity**: O(l Γ r) where l = left matches, r = right matches-**Space Complexity**: O(l Γ r) for join results--### SPARQL Reasoning Algorithms--#### Query Expansion-**Algorithm**: Add inferred patterns to SPARQL query--1. **Rule Conversion**: Convert inference rules to SPARQL patterns-2. **Pattern Matching**: Find query patterns that match rule conditions-3. **Pattern Addition**: Add inferred patterns to WHERE clause-4. **Optimization**: Remove redundant patterns--**Time Complexity**: O(r Γ q) where r = rules, q = query patterns-**Space Complexity**: O(q) for expanded query--```python-# Query expansion-reasoner = SPARQLReasoner(enable_inference=True)-reasoner.add_inference_rule("IF ?x :type :Company THEN ?x :type :Organization")-expanded = reasoner.expand_query("SELECT ?x WHERE { ?x :type :Organization }")-# Adds inferred :Company -> :Organization pattern-```--#### Query Optimization-**Algorithm**: Optimize SPARQL query execution--1. **Plan Generation**: Create logical query plan-2. **Join Ordering**: Order joins by selectivity-3. **Filter Pushdown**: Move filters as early as possible-4. **Projection Pushdown**: Select only needed variables--**Time Complexity**: O(qΒ²) for join ordering-**Space Complexity**: O(q) for query plan--### Abductive Reasoning Algorithms--#### Hypothesis Generation-**Algorithm**: Generate candidate hypotheses from rules--1. **Observation Analysis**: Analyze observation to find explainable parts-2. **Rule Matching**: Find rules whose conclusions match observation-3. **Hypothesis Construction**: Create hypothesis from rule premises-4. **Hypothesis Expansion**: Generate variations of hypotheses--**Time Complexity**: O(r Γ o) where r = rules, o = observations-**Space Complexity**: O(h) where h = hypotheses--```python-# Hypothesis generation-reasoner = AbductiveReasoner()-hypotheses = reasoner.generate_hypotheses(observations)-# Generates all possible explanations-```--#### Hypothesis Ranking-**Algorithm**: Rank hypotheses by multiple criteria--1. **Simplicity Scoring**: Score by number of conditions (inverse)-2. **Plausibility Assessment**: Score by confidence and evidence-3. **Consistency Checking**: Check consistency with known facts-4. **Coverage Calculation**: Measure how well hypothesis explains observation-5. **Weighted Combination**: Combine scores with weights--**Time Complexity**: O(h Γ f) where h = hypotheses, f = facts-**Space Complexity**: O(h) for rankings--```python-# Hypothesis ranking-ranked = reasoner.rank_hypotheses(- hypotheses,- ranking_strategy=HypothesisRanking.PLAUSIBILITY-)-# Ranks by plausibility score-```--### Deductive Reasoning Algorithms--#### Logical Inference-**Algorithm**: Apply logical inference rules--1. **Rule Matching**: Find applicable inference rules-2. **Premise Matching**: Match rule premises to known facts-3. **Conclusion Generation**: Generate conclusion from matched rule-4. **Confidence Calculation**: Calculate confidence from premises--**Inference Rules**:-- Modus Ponens: If PβQ and P, then Q-- Modus Tollens: If PβQ and Β¬Q, then Β¬P-- Syllogism: If AβB and BβC, then AβC--**Time Complexity**: O(r Γ p) where r = rules, p = premises-**Space Complexity**: O(c) where c = conclusions--```python-# Logical inference-reasoner = DeductiveReasoner()-conclusions = reasoner.apply_logic(premises)-# Applies modus ponens, syllogism, etc.-```--#### Proof Generation-**Algorithm**: Construct proof tree for conclusion--1. **Goal Decomposition**: Break goal into subgoals-2. **Subgoal Resolution**: Recursively prove subgoals-3. **Proof Tree Construction**: Build tree of inference steps-4. **Proof Validation**: Verify proof correctness--**Time Complexity**: O(r^d) where d = proof depth-**Space Complexity**: O(d) for proof tree--```python-# Proof generation-proof = reasoner.prove_theorem(conclusion)-# Constructs step-by-step proof-```--### Rule Management Algorithms--#### Rule Parsing-**Algorithm**: Parse natural language rule definitions--1. **Pattern Matching**: Match rule syntax patterns (IF-THEN, IFF, etc.)-2. **Condition Extraction**: Extract conditions from rule string-3. **Conclusion Extraction**: Extract conclusion from rule string-4. **Type Detection**: Detect rule type from syntax--**Time Complexity**: O(n) where n = rule string length-**Space Complexity**: O(c) where c = conditions--```python-# Rule parsing-rule = manager.define_rule("IF Person(?x) THEN Human(?x)")-# Parses and creates Rule object-```--#### Rule Validation-**Algorithm**: Validate rule structure and semantics--1. **Syntax Validation**: Check rule syntax correctness-2. **Semantic Validation**: Check rule semantics-3. **Consistency Checking**: Check consistency with existing rules-4. **Completeness Checking**: Check if rule is well-formed--**Time Complexity**: O(r) where r = existing rules-**Space Complexity**: O(1)--### Explanation Generation Algorithms--#### Reasoning Path Construction-**Algorithm**: Build step-by-step reasoning path--1. **Step Extraction**: Extract inference steps from result-2. **Path Building**: Build path from initial facts to conclusion-3. **Step Linking**: Link steps by input/output relationships-4. **Path Optimization**: Simplify path for readability--**Time Complexity**: O(s) where s = steps-**Space Complexity**: O(s) for path storage--```python-# Reasoning path construction-path = generator.generate_reasoning_path(inference_result)-# Builds complete reasoning chain-```--#### Natural Language Generation-**Algorithm**: Convert reasoning path to natural language--1. **Template Selection**: Select appropriate explanation template-2. **Step Narration**: Convert each step to natural language-3. **Path Description**: Describe overall reasoning path-4. **Conclusion Summary**: Summarize final conclusion--**Time Complexity**: O(s) where s = steps-**Space Complexity**: O(n) where n = natural language text--### Methods--#### InferenceEngine Methods--- `infer(query, **options)`: General inference with strategy selection-- `forward_chain(facts, **options)`: Forward chaining inference-- `backward_chain(goal, **options)`: Backward chaining inference-- `add_rule(rule_definition, **options)`: Add inference rule-- `add_fact(fact)`: Add fact to knowledge base-- `add_facts(facts)`: Add multiple facts--#### SPARQLReasoner Methods--- `query(sparql_query, **options)`: Execute SPARQL query-- `expand_query(query, **options)`: Expand query with inference rules-- `add_inference_rule(rule)`: Add inference rule for query expansion-- `optimize_query(query)`: Optimize SPARQL query--#### ReteEngine Methods--- `build_network(rules)`: Build Rete network from rules-- `add_rule(rule)`: Add rule to network-- `add_fact(fact)`: Add fact and propagate through network-- `match_patterns()`: Get all rule matches-- `match_patterns(facts)`: Match patterns using Rete algorithm--#### AbductiveReasoner Methods--- `generate_hypotheses(observations, **options)`: Generate candidate hypotheses-- `rank_hypotheses(hypotheses, ranking_strategy)`: Rank hypotheses-- `find_explanations(observations, **options)`: Find best explanations-- `evaluate_hypothesis(hypothesis, facts)`: Evaluate hypothesis quality--#### DeductiveReasoner Methods--- `apply_logic(premises, **options)`: Apply logical inference rules-- `prove_theorem(theorem)`: Prove theorem-- `prove_theorem(theorem, **options)`: Prove logical theorem-- `validate_argument(argument)`: Validate logical argument--#### RuleManager Methods--- `define_rule(rule_definition, **options)`: Define new rule-- `add_rule(rule)`: Add rule to manager-- `execute_rule(rule, facts)`: Execute rule with facts-- `validate_rule(rule)`: Validate rule structure-- `get_execution_history()`: Get rule execution history-- `get_all_rules()`: Get all registered rules--#### ExplanationGenerator Methods--- `generate_explanation(reasoning, **options)`: Generate explanation for result-- `generate_reasoning_path(reasoning)`: Generate reasoning path-- `create_justification(conclusion, path)`: Create justification-- `generate_natural_language(explanation)`: Generate natural language explanation--## Configuration--### Environment Variables--```bash-# Reasoning configuration-export REASONING_DEFAULT_STRATEGY=forward-export REASONING_MAX_ITERATIONS=100-export REASONING_CONFIDENCE_THRESHOLD=0.7-export REASONING_ENABLE_EXPLANATION=true-export REASONING_RETE_OPTIMIZATION=true--# SPARQL reasoning configuration-export REASONING_SPARQL_ENDPOINT=http://localhost:3030/ds-export REASONING_ENABLE_INFERENCE=true-export REASONING_QUERY_CACHE_SIZE=1000--# Abductive reasoning configuration-export REASONING_MAX_HYPOTHESES=10-export REASONING_RANKING_STRATEGY=plausibility--# Explanation configuration-export REASONING_GENERATE_NL=true-export REASONING_DETAIL_LEVEL=detailed-```--### Programmatic Configuration--```python-from semantica.reasoning import InferenceEngine, SPARQLReasoner--# Configure inference engine-engine = InferenceEngine(- strategy="forward",- max_iterations=100,- confidence_threshold=0.7-)--# Configure SPARQL reasoner-reasoner = SPARQLReasoner(- triplet_store=kg,- enable_inference=True,- query_cache_size=1000-)-```--### Configuration File (YAML)--```yaml-# config.yaml-reasoning:- default_strategy: forward- max_iterations: 100- confidence_threshold: 0.7- enable_explanation: true- rete_optimization: true--reasoning_sparql:- endpoint: http://localhost:3030/ds- enable_inference: true- query_cache_size: 1000--reasoning_abductive:- max_hypotheses: 10- ranking_strategy: plausibility--reasoning_explanation:- generate_nl: true- detail_level: detailed-```--## Advanced Examples--### Complete Knowledge Graph Reasoning Pipeline--```python-from semantica.reasoning import (- InferenceEngine,- SPARQLReasoner,- ExplanationGenerator-)--# 1. Set up inference engine-engine = InferenceEngine(strategy="forward")--# 2. Add facts from knowledge graph-kg_facts = extract_facts_from_kg(kg)-engine.add_facts(kg_facts)--# 3. Add domain rules-rules = [- "IF Person(?x) AND WorksFor(?x, ?y) THEN Employee(?x, ?y)",- "IF Employee(?x, ?y) AND Company(?y) THEN WorksAt(?x, ?y)",- "IF Person(?x) THEN Human(?x)"-]-for rule in rules:- engine.add_rule(rule)--# 4. Perform inference-results = engine.forward_chain()--# 5. Generate explanations-generator = ExplanationGenerator()-for result in results:- explanation = generator.generate_explanation(result)- print(f"Conclusion: {result.conclusion}")- print(f"Explanation: {explanation.natural_language}")--# 6. Query with SPARQL reasoning-sparql_reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)-query_result = sparql_reasoner.execute_query("SELECT ?x WHERE { ?x :type :Employee }")-```--### Abductive Explanation System--```python-from semantica.reasoning import AbductiveReasoner, Observation--# Create reasoner-reasoner = AbductiveReasoner(- max_hypotheses=10,- ranking_strategy=HypothesisRanking.PLAUSIBILITY-)--# Define observations-observations = [- Observation("obs1", "The ground is wet", ["Wet(Ground)"]),- Observation("obs2", "The car won't start", ["NotWorking(Car)"])-]--# Find best explanations-explanations = reasoner.find_explanations(observations)--for explanation in explanations:- print(f"Observation: {explanation.observation.description}")- print(f"Best explanation: {explanation.best_hypothesis.explanation}")- print(f"Confidence: {explanation.confidence}")- print(f"Alternative hypotheses: {len(explanation.hypotheses) - 1}")-```--### Rete-Based Rule System--```python-from semantica.reasoning import ReteEngine, Fact, Rule, RuleType--# Create Rete engine-rete = ReteEngine()--# Define complex rules-rules = [- Rule("r1", "PersonRule", ["Person(?x)"], "Human(?x)", RuleType.IMPLICATION),- Rule("r2", "EmployeeRule", ["WorksFor(?x, ?y)", "Person(?x)"], "Employee(?x, ?y)", RuleType.IMPLICATION),- Rule("r3", "ManagerRule", ["Manages(?x, ?y)", "Employee(?x, ?y)"], "Manager(?x)", RuleType.IMPLICATION)-]--# Build network-rete.build_network(rules)--# Add facts incrementally-facts = [- Fact("f1", "Person", ["John"]),- Fact("f2", "WorksFor", ["John", "Acme"]),- Fact("f3", "Manages", ["John", "Team1"])-]--for fact in facts:- rete.add_fact(fact)- matches = rete.match_patterns()- print(f"After adding {fact.fact_id}: {len(matches)} matches")-```--### Theorem Proving System--```python-from semantica.reasoning import DeductiveReasoner, Premise--reasoner = DeductiveReasoner()--# Define axioms-axioms = [- Premise("ax1", "All humans are mortal"),- Premise("ax2", "Socrates is human")-]--# Prove theorem-theorem = "Socrates is mortal"-proof = reasoner.prove_theorem(theorem)--if proof and proof.valid:- print(f"Theorem '{theorem}' is provable")- print("Proof steps:")- for i, step in enumerate(proof.steps, 1):- print(f"{i}. {step.statement}")- if step.rule_applied:- print(f" (Using rule: {step.rule_applied.name})")-```--### Integration with Knowledge Graph--```python-from semantica.reasoning import InferenceEngine, SPARQLReasoner-from semantica.kg import build--# Build knowledge graph-kg = build(sources=[...])--# Create SPARQL reasoner with KG-reasoner = SPARQLReasoner(triplet_store=kg, enable_inference=True)--# Add inference rules-reasoner.add_inference_rule("IF ?x :type :Company THEN ?x :type :Organization")-reasoner.add_inference_rule("IF ?x :subClassOf ?y AND ?z :type ?x THEN ?z :type ?y")--# Query with reasoning-query = """-SELECT ?person ?company-WHERE {- ?person :worksFor ?company .- ?company :type :Organization .-}-"""--result = reasoner.execute_query(query)-# Results include both explicit and inferred relationships-```--## Best Practices--1. **Rule Design**:- - Keep rules focused and single-purpose- - Use clear, descriptive rule names- - Set appropriate confidence scores- - Use priority to control rule execution order--2. **Inference Strategy Selection**:- - Use forward chaining for data-driven inference- - Use backward chaining for goal-driven queries- - Use bidirectional for complex reasoning tasks--3. **Rete Algorithm**:- - Build network once and reuse for multiple fact sets- - Use incremental fact processing for efficiency- - Optimize network by sharing common conditions--4. **SPARQL Reasoning**:- - Enable inference for query expansion- - Use query optimization for performance- - Cache frequently used queries--5. **Abductive Reasoning**:- - Set appropriate max_hypotheses limit- - Choose ranking strategy based on use case- - Consider multiple ranking criteria--6. **Deductive Reasoning**:- - Structure premises clearly- - Use appropriate logical inference rules- - Validate proofs before accepting conclusions--7. **Explanation Generation**:- - Generate explanations for important conclusions- - Use appropriate detail level for audience- - Validate explanation correctness--8. **Performance**:- - Limit max_iterations for forward chaining- - Use Rete algorithm for large rule sets- - Cache query results when possible- - Optimize rule order by selectivity--9. **Error Handling**:- - Validate rules before adding- - Check fact consistency- - Handle inference failures gracefully--10. **Testing**:- - Test rules with known fact sets- - Verify inference results- - Validate explanations- - Test edge cases and boundary conditions--=======->>>>>>> Stashed changesdiff --git a/semantica/reasoning/rete_engine.py b/semantica/reasoning/rete_engine.pyindex ec091774..c66bd6f3 100644--- a/semantica/reasoning/rete_engine.py+++ b/semantica/reasoning/rete_engine.py@@ -40,17 +40,7 @@ from typing import Any, Dict, List, Optional, Set, Tuplefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from .rule_manager import Rule---@dataclass-class Fact:- """Fact representation."""-- fact_id: str- predicate: str- arguments: List[Any]- metadata: Dict[str, Any] = field(default_factory=dict)+from .reasoner import Fact, Rule@dataclassdiff --git a/semantica/reasoning/rule_manager.py b/semantica/reasoning/rule_manager.pydeleted file mode 100644index 9dc7f5ab..00000000--- a/semantica/reasoning/rule_manager.py+++ /dev/null@@ -1,415 +0,0 @@-"""-Rule Manager Module--This module provides rule management and execution for reasoning and inference-operations, supporting rule registration, validation, execution tracking, and-rule type management.--Key Features:- - Rule management and execution- - Rule registration and validation- - Rule execution tracking- - Multiple rule types (implication, equivalence, constraint, transformation)- - Rule priority management- - Execution history--Main Classes:- - RuleManager: Rule management system- - Rule: Dataclass for rule definition- - RuleExecution: Dataclass for rule execution records- - RuleType: Enum for rule types--Example Usage:- >>> from semantica.reasoning import RuleManager, Rule, RuleType- >>> manager = RuleManager()- >>> rule = Rule("r1", "If A then B", conditions=["A"], conclusion="B", rule_type=RuleType.IMPLICATION)- >>> manager.add_rule(rule)- >>> execution = manager.execute_rule(rule, facts)--Author: Semantica Contributors-License: MIT-"""--import re-from dataclasses import dataclass, field-from datetime import datetime-from enum import Enum-from typing import Any, Callable, Dict, List, Optional--from ..utils.exceptions import ProcessingError, ValidationError-from ..utils.logging import get_logger-from ..utils.progress_tracker import get_progress_tracker---class RuleType(Enum):- """Rule types."""-- IMPLICATION = "implication"- EQUIVALENCE = "equivalence"- CONSTRAINT = "constraint"- TRANSFORMATION = "transformation"---@dataclass-class Rule:- """Rule definition."""-- rule_id: str- name: str- conditions: List[Any]- conclusion: Any- rule_type: RuleType = RuleType.IMPLICATION- confidence: float = 1.0- priority: int = 0- handler: Optional[Callable] = None- metadata: Dict[str, Any] = field(default_factory=dict)---@dataclass-class RuleExecution:- """Rule execution record."""-- rule_id: str- executed_at: str- input_facts: List[Any]- output_fact: Any- success: bool- execution_time: float = 0.0- error: Optional[str] = None---class RuleManager:- """- Rule management system.-- β’ Rule creation and management- β’ Rule validation and testing- β’ Rule execution and scheduling- β’ Performance optimization- β’ Error handling and recovery- β’ Rule versioning and updates- """-- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):- """- Initialize rule manager.-- Args:- config: Configuration dictionary- **kwargs: Additional configuration options- """- self.logger = get_logger("rule_manager")- self.config = config or {}- self.config.update(kwargs)-- # Initialize progress tracker- self.progress_tracker = get_progress_tracker()-- self.rules: Dict[str, Rule] = {}- self.execution_history: List[RuleExecution] = []- self.rule_counter = 0-- def define_rule(self, rule_definition: str, **options) -> Rule:- """- Define new inference rule.-- Args:- rule_definition: Rule definition string (e.g., "IF ?x is_a Company THEN ?x is_a Organization")- **options: Additional options-- Returns:- Created rule- """- tracking_id = self.progress_tracker.start_tracking(- module="reasoning",- submodule="RuleManager",- message="Defining new inference rule",- )-- try:- # Parse rule definition- self.progress_tracker.update_tracking(- tracking_id, message="Parsing rule definition..."- )- parsed = self._parse_rule_definition(rule_definition)-- # Create rule- self.progress_tracker.update_tracking(- tracking_id, message="Creating rule object..."- )- self.rule_counter += 1- rule = Rule(- rule_id=f"rule_{self.rule_counter}",- name=options.get("name", f"Rule {self.rule_counter}"),- conditions=parsed["conditions"],- conclusion=parsed["conclusion"],- rule_type=RuleType(parsed.get("type", "implication")),- confidence=options.get("confidence", 1.0),- priority=options.get("priority", 0),- handler=options.get("handler"),- metadata=options.get("metadata", {}),- )-- # Validate rule- self.progress_tracker.update_tracking(- tracking_id, message="Validating rule..."- )- validation = self.validate_rule(rule)- if not validation["valid"]:- raise ValidationError(f"Rule validation failed: {validation['errors']}")-- self.progress_tracker.stop_tracking(- tracking_id, status="completed", message=f"Defined rule: {rule.name}"- )- return rule-- except Exception as e:- self.progress_tracker.stop_tracking(- tracking_id, status="failed", message=str(e)- )- raise-- def _parse_rule_definition(self, definition: str) -> Dict[str, Any]:- """Parse rule definition string."""- # Simple pattern matching- # Format: "IF condition1 AND condition2 THEN conclusion"- # or "IF condition THEN conclusion"-- definition = definition.strip()-- # Check for IF-THEN pattern- if_match = re.match(r"IF\s+(.+?)\s+THEN\s+(.+)$", definition, re.IGNORECASE)- if if_match:- conditions_str = if_match.group(1)- conclusion_str = if_match.group(2)-- # Split conditions by AND- conditions = [- c.strip()- for c in re.split(r"\s+AND\s+", conditions_str, flags=re.IGNORECASE)- ]-- return {- "conditions": conditions,- "conclusion": conclusion_str.strip(),- "type": "implication",- }-- # Check for equivalence pattern- equiv_match = re.match(r"(.+?)\s+IFF\s+(.+)$", definition, re.IGNORECASE)- if equiv_match:- left = equiv_match.group(1).strip()- right = equiv_match.group(2).strip()-- return {"conditions": [left], "conclusion": right, "type": "equivalence"}-- # Fallback: treat as simple condition -> conclusion- if "->" in definition:- parts = definition.split("->", 1)- return {- "conditions": [parts[0].strip()],- "conclusion": parts[1].strip(),- "type": "implication",- }-- raise ValidationError(f"Could not parse rule definition: {definition}")-- def add_rule(self, rule: Rule) -> None:- """- Add rule to manager.-- Args:- rule: Rule object- """- self.rules[rule.rule_id] = rule- self.logger.debug(f"Added rule: {rule.name} ({rule.rule_id})")-- def remove_rule(self, rule_id: str) -> None:- """- Remove rule.-- Args:- rule_id: Rule identifier- """- if rule_id in self.rules:- del self.rules[rule_id]- self.logger.debug(f"Removed rule: {rule_id}")-- def get_rule(self, rule_id: str) -> Optional[Rule]:- """Get rule by ID."""- return self.rules.get(rule_id)-- def get_all_rules(self) -> List[Rule]:- """Get all rules."""- return list(self.rules.values())-- def validate_rule(self, rule: Rule) -> Dict[str, Any]:- """- Validate rule syntax and logic.-- Args:- rule: Rule to validate-- Returns:- Validation result- """- errors = []- warnings = []-- # Check required fields- if not rule.conditions:- errors.append("Rule missing conditions")- if not rule.conclusion:- errors.append("Rule missing conclusion")- if rule.confidence < 0 or rule.confidence > 1:- errors.append("Rule confidence must be between 0 and 1")-- # Check for circular dependencies (basic)- if rule.conclusion in rule.conditions:- warnings.append(- "Rule conclusion appears in conditions (potential circularity)"- )-- return {"valid": len(errors) == 0, "errors": errors, "warnings": warnings}-- def execute_rule(self, rule: Rule, facts: List[Any], **options) -> Optional[Any]:- """- Execute rule with given facts.-- Args:- rule: Rule to execute- facts: Input facts- **options: Additional options-- Returns:- Rule execution result or None- """- import time-- start_time = time.time()-- tracking_id = self.progress_tracker.start_tracking(- module="reasoning",- submodule="RuleManager",- message=f"Executing rule: {rule.name}",- )-- try:- # Check if conditions are met- self.progress_tracker.update_tracking(- tracking_id, message="Checking if rule conditions are met..."- )- conditions_met = all(condition in facts for condition in rule.conditions)-- if not conditions_met:- self.progress_tracker.stop_tracking(- tracking_id, status="completed", message="Rule conditions not met"- )- return None-- # Execute rule- self.progress_tracker.update_tracking(- tracking_id, message="Executing rule..."- )- if rule.handler:- result = rule.handler(facts, **options)- else:- result = rule.conclusion-- execution_time = time.time() - start_time-- # Record execution- self.progress_tracker.update_tracking(- tracking_id, message="Recording execution..."- )- execution = RuleExecution(- rule_id=rule.rule_id,- executed_at=datetime.now().isoformat(),- input_facts=facts,- output_fact=result,- success=True,- execution_time=execution_time,- )- self.execution_history.append(execution)-- self.progress_tracker.stop_tracking(- tracking_id,- status="completed",- message=f"Rule executed successfully: {rule.name}",- )- return result-- except Exception as e:- execution_time = time.time() - start_time- execution = RuleExecution(- rule_id=rule.rule_id,- executed_at=datetime.now().isoformat(),- input_facts=facts,- output_fact=None,- success=False,- execution_time=execution_time,- error=str(e),- )- self.execution_history.append(execution)-- self.logger.error(f"Rule execution failed: {e}")- self.progress_tracker.stop_tracking(- tracking_id, status="failed", message=str(e)- )- return None-- def track_execution(self, rule: Rule) -> List[RuleExecution]:- """- Track rule execution history.-- Args:- rule: Rule to track-- Returns:- Execution history- """- return [e for e in self.execution_history if e.rule_id == rule.rule_id]-- def get_execution_stats(self, rule_id: Optional[str] = None) -> Dict[str, Any]:- """- Get execution statistics.-- Args:- rule_id: Optional rule ID filter-- Returns:- Execution statistics- """- if rule_id:- executions = [e for e in self.execution_history if e.rule_id == rule_id]- else:- executions = self.execution_history-- if not executions:- return {- "total_executions": 0,- "successful_executions": 0,- "failed_executions": 0,- "average_execution_time": 0.0,- }-- successful = sum(1 for e in executions if e.success)- failed = len(executions) - successful- avg_time = sum(e.execution_time for e in executions) / len(executions)-- return {- "total_executions": len(executions),- "successful_executions": successful,- "failed_executions": failed,- "average_execution_time": avg_time,- "success_rate": successful / len(executions) if executions else 0.0,- }-- def clear_rules(self) -> None:- """Clear all rules."""- self.rules.clear()- self.rule_counter = 0-- def clear_execution_history(self) -> None:- """Clear execution history."""- self.execution_history.clear()diff --git a/semantica/reasoning/sparql_reasoner.py b/semantica/reasoning/sparql_reasoner.pyindex a16beba0..5b253fd2 100644--- a/semantica/reasoning/sparql_reasoner.py+++ b/semantica/reasoning/sparql_reasoner.py@@ -36,7 +36,7 @@ from typing import Any, Dict, List, Optional, Setfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker-from .rule_manager import Rule, RuleManager+from .reasoner import Rule, Reasoner@dataclass@@ -77,7 +77,7 @@ class SPARQLReasoner:# Initialize progress trackerself.progress_tracker = get_progress_tracker()- self.rule_manager = RuleManager(**self.config)+ self.reasoner = Reasoner(**self.config)self.triplet_store = self.config.get("triplet_store")self.enable_inference = self.config.get("enable_inference", True)@@ -119,7 +119,7 @@ class SPARQLReasoner:self.progress_tracker.update_tracking(tracking_id, message="Getting inference rules...")- rules = self.rule_manager.get_all_rules()+ rules = self.reasoner.rules# Add inferred patterns based on rulesself.progress_tracker.update_tracking(@@ -158,6 +158,8 @@ class SPARQLReasoner:parts = condition.split(" is_a ")if len(parts) == 2:var = parts[0].strip()+ if var.startswith("?"):+ var = var[1:]class_type = parts[1].strip()patterns.append(f"?{var} a :{class_type} .")@@ -166,6 +168,8 @@ class SPARQLReasoner:parts = rule.conclusion.split(" is_a ")if len(parts) == 2:var = parts[0].strip()+ if var.startswith("?"):+ var = var[1:]class_type = parts[1].strip()conclusion_pattern = f"?{var} a :{class_type} ."@@ -205,7 +209,7 @@ class SPARQLReasoner:self.progress_tracker.update_tracking(tracking_id, message="Applying inference rules...")- rules = self.rule_manager.get_all_rules()+ rules = self.reasoner.rulesfor rule in rules:# Check if rule can be applied to results@@ -400,4 +404,4 @@ class SPARQLReasoner:def add_inference_rule(self, rule_definition: str, **options) -> Rule:"""Add inference rule."""- return self.rule_manager.define_rule(rule_definition, **options)+ return self.reasoner.add_rule(rule_definition)diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.pyindex 27b6b5a1..8b687145 100644--- a/semantica/semantic_extract/providers.py+++ b/semantica/semantic_extract/providers.py@@ -101,9 +101,6 @@ class BaseProvider:"""Generate structured output - must be implemented."""raise NotImplementedError-<<<<<<< HEAD-<<<<<<< Updated upstream-=======def _parse_json(self, text: str) -> Union[dict, list]:"""Extract and parse JSON from text, supporting objects and lists."""if not text:@@ -161,49 +158,6 @@ class BaseProvider:raise ProcessingError(f"No JSON structure found in response. Raw response: {text[:100]}...")->>>>>>> Stashed changes-=======- def _parse_json(self, text: str) -> Union[dict, list]:- """Extract and parse JSON from text, supporting objects and lists."""- try:- return json.loads(text)- except json.JSONDecodeError:- # Try to find JSON boundaries- # Look for the first occurrence of { or [- start_obj = text.find("{")- start_list = text.find("[")-- # Determine which one starts first- start = -1- end = -1-- if start_obj >= 0 and (start_list < 0 or start_obj < start_list):- start = start_obj- end = text.rfind("}") + 1- elif start_list >= 0:- start = start_list- end = text.rfind("]") + 1-- if start >= 0 and end > start:- try:- return json.loads(text[start:end])- except json.JSONDecodeError as e:- # If that failed, maybe it's a list that ends with ] but we picked } earlier?- # Or vice versa. Let's try the other boundary if they exist.- if start == start_obj and start_list >= 0:- start = start_list- end = text.rfind("]") + 1- if start >= 0 and end > start:- try:- return json.loads(text[start:end])- except json.JSONDecodeError:- pass-- raise ProcessingError(f"Failed to parse extracted JSON: {e}")- raise ProcessingError("No JSON structure found in response")-->>>>>>> main-class OpenAIProvider(BaseProvider):"""OpenAI provider implementation."""diff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex 9cc21359..d8d1d49d 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -223,12 +223,6 @@ class VectorStore:tracking_id, status="failed", message=str(e))raise--<<<<<<< HEAD-<<<<<<< Updated upstream-=======-=======->>>>>>> maindef save(self, path: str) -> None:"""Save vector store to disk.@@ -308,19 +302,11 @@ class VectorStore:List of results with scores"""# Generate embedding for query-<<<<<<< HEADquery_vector = self.embed(query)-=======- query_vector = self.embed([query])[0]->>>>>>> main# Search by vectorreturn self.search_vectors(query_vector=query_vector, k=limit, **options)-<<<<<<< HEAD->>>>>>> Stashed changes-=======->>>>>>> maindef search_vectors(self, query_vector: np.ndarray, k: int = 10, **options) -> List[Dict[str, Any]]:diff --git a/tests/cookbook/test_disease_network_analysis.py b/tests/cookbook/test_disease_network_analysis.pyindex b22b10f7..73ae8548 100644--- a/tests/cookbook/test_disease_network_analysis.py+++ b/tests/cookbook/test_disease_network_analysis.py@@ -14,7 +14,7 @@ try:from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetectorfrom semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery, TemporalPatternDetectorfrom semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator- from semantica.reasoning import RuleManager, ExplanationGenerator+ from semantica.reasoning import Reasoner, ExplanationGeneratorfrom semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator# Visualization might require matplotlib/networkx which might be missing or headlessfrom semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer@@ -194,10 +194,17 @@ class TestDiseaseNetworkAnalysis(unittest.TestCase):self.assertIn("components", connectivity)# --- Step 5: Predict Outcomes (Reasoning) ---- # Inference logic updated to remove InferenceEngine- outcome_predictions = []- self.assertIsInstance(outcome_predictions, list)-+ # Inference logic updated to use Reasoner facade+ reasoner = Reasoner()+ reasoner.add_rule("IF related_to(?a, ?b) AND related_to(?b, ?c) THEN comorbid(?a, ?c)")++ # Add some facts for testing+ reasoner.add_fact("related_to(Diabetes, Hypertension)")+ reasoner.add_fact("related_to(Hypertension, Obesity)")++ outcome_predictions = reasoner.infer_facts([])+ self.assertIn("comorbid(Diabetes, Obesity)", outcome_predictions)+# --- Step 6: Export/Report ---# Mocking exporters to avoid file writing issues or just testing they runjson_exporter = JSONExporter()diff --git a/tests/reasoning/__init__.py b/tests/reasoning/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/tests/reasoning/test_reasoner.py b/tests/reasoning/test_reasoner.pynew file mode 100644index 00000000..8f06ab74--- /dev/null+++ b/tests/reasoning/test_reasoner.py@@ -0,0 +1,83 @@+import unittest+from semantica.reasoning.reasoner import Reasoner, Rule, RuleType, Fact, InferenceResult++class TestReasoner(unittest.TestCase):+ def setUp(self):+ self.reasoner = Reasoner()++ def test_add_rule_string(self):+ rule_str = "IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)"+ rule = self.reasoner.add_rule(rule_str)+ self.assertEqual(len(self.reasoner.rules), 1)+ self.assertEqual(rule.conditions, ["Person(?x)", "Parent(?x, ?y)"])+ self.assertEqual(rule.conclusion, "Child(?y, ?x)")++ def test_add_rule_object(self):+ rule = Rule(+ rule_id="r1",+ name="Test Rule",+ conditions=["A(?x)"],+ conclusion="B(?x)",+ priority=10+ )+ self.reasoner.add_rule(rule)+ self.assertEqual(len(self.reasoner.rules), 1)+ self.assertEqual(self.reasoner.rules[0].priority, 10)++ def test_add_fact_string(self):+ self.reasoner.add_fact("Person(John)")+ self.assertIn("Person(John)", self.reasoner.facts)++ def test_add_fact_dict_entity(self):+ fact_dict = {"type": "Person", "name": "John"}+ self.reasoner.add_fact(fact_dict)+ self.assertIn("Person(John)", self.reasoner.facts)++ def test_add_fact_dict_relationship(self):+ fact_dict = {+ "type": "WorksAt",+ "source_name": "John",+ "target_name": "Google"+ }+ self.reasoner.add_fact(fact_dict)+ self.assertIn("WorksAt(John, Google)", self.reasoner.facts)++ def test_forward_chaining(self):+ self.reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")+ self.reasoner.add_fact("Person(John)")+ self.reasoner.add_fact("Parent(John, Jane)")++ results = self.reasoner.forward_chain()+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0].conclusion, "Child(Jane, John)")+ self.assertIn("Child(Jane, John)", self.reasoner.facts)++ def test_backward_chaining_simple(self):+ self.reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")+ self.reasoner.add_fact("Person(John)")+ self.reasoner.add_fact("Parent(John, Jane)")++ result = self.reasoner.backward_chain("Child(Jane, John)")+ self.assertIsNotNone(result)+ self.assertEqual(result.conclusion, "Child(Jane, John)")+ self.assertEqual(len(result.premises), 2)+ self.assertIn("Person(John)", result.premises)+ self.assertIn("Parent(John, Jane)", result.premises)++ def test_infer_facts(self):+ facts = ["Person(John)", "Parent(John, Jane)"]+ rules = ["IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)"]++ inferred = self.reasoner.infer_facts(facts, rules)+ self.assertEqual(len(inferred), 1)+ self.assertEqual(inferred[0], "Child(Jane, John)")++ def test_clear_reset(self):+ self.reasoner.add_fact("Fact(1)")+ self.reasoner.add_rule("IF A THEN B")+ self.reasoner.clear()+ self.assertEqual(len(self.reasoner.facts), 0)+ self.assertEqual(len(self.reasoner.rules), 0)++if __name__ == "__main__":+ unittest.main()diff --git a/tests/reasoning/test_specialized_reasoners.py b/tests/reasoning/test_specialized_reasoners.pynew file mode 100644index 00000000..3a519171--- /dev/null+++ b/tests/reasoning/test_specialized_reasoners.py@@ -0,0 +1,80 @@+import unittest+from semantica.reasoning.sparql_reasoner import SPARQLReasoner, SPARQLQueryResult+from semantica.reasoning.abductive_reasoner import AbductiveReasoner, Observation, HypothesisRanking+from semantica.reasoning.deductive_reasoner import DeductiveReasoner, Premise, Argument+from semantica.reasoning.reasoner import Rule++class TestSpecializedReasoners(unittest.TestCase):+ def test_sparql_reasoner_expand_query(self):+ reasoner = SPARQLReasoner()+ reasoner.add_inference_rule("IF ?x is_a Person THEN ?x is_a Human")++ query = "SELECT ?x WHERE { ?x a :Person . }"+ expanded = reasoner.expand_query(query)++ self.assertIn("Inference: Rule 1", expanded)+ self.assertIn("?x a :Person . => ?x a :Human .", expanded)++ def test_sparql_reasoner_infer_results(self):+ reasoner = SPARQLReasoner()+ reasoner.add_inference_rule("IF ?x is_a Person THEN ?x is_a Human")++ results = SPARQLQueryResult(+ bindings=[{"x": "John"}],+ variables=["x"]+ )++ inferred = reasoner.infer_results(results)+ self.assertEqual(len(inferred.bindings), 2)+ # One original binding, one with type Human+ binding_types = [b.get("x_type") for b in inferred.bindings]+ self.assertIn("Human", binding_types)++ def test_abductive_reasoner_generate_hypotheses(self):+ reasoner = AbductiveReasoner()+ reasoner.reasoner.add_rule("IF Disease(Flu) THEN Symptom(Fever)")++ obs = Observation(observation_id="o1", description="Symptom(Fever)")+ hypotheses = reasoner.generate_hypotheses([obs])++ self.assertEqual(len(hypotheses), 1)+ self.assertEqual(hypotheses[0].premises, ["Disease(Flu)"])++ def test_abductive_reasoner_rank_hypotheses(self):+ reasoner = AbductiveReasoner(ranking_strategy="simplicity")++ h1 = reasoner.generate_hypotheses([Observation("o1", "Symptom(Fever)")]) # dummy, just to get objects+ # Create custom hypotheses for testing ranking+ from semantica.reasoning.abductive_reasoner import Hypothesis+ hyp1 = Hypothesis("h1", "Expl 1", premises=["P1"], simplicity=0.5)+ hyp2 = Hypothesis("h2", "Expl 2", premises=["P1", "P2"], simplicity=0.3)++ ranked = reasoner.rank_hypotheses([hyp1, hyp2])+ self.assertEqual(ranked[0].hypothesis_id, "h1") # simpler is better++ def test_deductive_reasoner_apply_logic(self):+ reasoner = DeductiveReasoner()+ reasoner.reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")++ premises = [+ Premise("p1", "Person(John)"),+ Premise("p2", "Parent(John, Jane)")+ ]++ conclusions = reasoner.apply_logic(premises)+ self.assertEqual(len(conclusions), 1)+ self.assertEqual(conclusions[0].statement, "Child(Jane, John)")++ def test_deductive_reasoner_prove_theorem(self):+ reasoner = DeductiveReasoner()+ reasoner.reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")+ reasoner.add_facts(["Person(John)", "Parent(John, Jane)"])++ proof = reasoner.prove_theorem("Child(Jane, John)")+ self.assertTrue(proof.valid)+ self.assertEqual(proof.theorem, "Child(Jane, John)")+ self.assertEqual(len(proof.steps), 1)+ self.assertEqual(proof.steps[0].statement, "Child(Jane, John)")++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_all_features.py b/tests/test_all_features.pyindex 45bb9b67..51a44658 100644--- a/tests/test_all_features.py+++ b/tests/test_all_features.py@@ -12,6 +12,7 @@ from semantica.vector_store import (VectorStore, FAISSStore, HybridSearch, MetadataFilter,SearchRanker, NamespaceManager)+from semantica.reasoning import Reasonerpytestmark = pytest.mark.integration@@ -164,5 +165,24 @@ class TestSemanticaFeatures(unittest.TestCase):self.assertFalse(ns_a.has_permission("user1", "write"))print("Namespace Manager: OK")+ def test_09_reasoning_core(self):+ """Test Reasoner core functionality"""+ print("\nTesting Reasoner...")+ reasoner = Reasoner()++ # Test rule parsing and forward chaining+ reasoner.add_rule("IF Person(?x) AND Parent(?x, ?y) THEN Child(?y, ?x)")+ reasoner.add_fact("Person(John)")+ reasoner.add_fact("Parent(John, Jane)")++ results = reasoner.forward_chain()+ self.assertTrue(any(r.conclusion == "Child(Jane, John)" for r in results))++ # Test backward chaining+ proof = reasoner.backward_chain("Child(Jane, John)")+ self.assertIsNotNone(proof)+ self.assertEqual(proof.conclusion, "Child(Jane, John)")+ print("Reasoner: OK")+if __name__ == '__main__':unittest.main(verbosity=2)