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
Remove healthcare use case: Drug Interactions Analysis
KaifAhmad1f4016237bd45
diff --git a/README.md b/README.mdindex 6cfc84a2..c2aec556 100644--- a/README.md+++ b/README.md@@ -252,7 +252,7 @@ python -c "import semantica; print(semantica.__version__)"- [**Entity Extraction**](cookbook/introduction/05_Entity_Extraction.ipynb) - NER & Relationships- [**Building Knowledge Graphs**](cookbook/introduction/07_Building_Knowledge_Graphs.ipynb) - Graph Construction-### Industry Use Cases (18 Cookbooks)+### Industry Use Cases (17 Cookbooks)**Domain-Specific Cookbooks** showcasing real-world applications with real data sources, advanced chunking strategies, temporal KGs, GraphRAG, and comprehensive Semantica module integration:@@ -260,9 +260,6 @@ python -c "import semantica; print(semantica.__version__)"- [**Drug Discovery Pipeline**](cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb) - PubMed RSS, entity-aware chunking, GraphRAG, vector similarity search- [**Genomic Variant Analysis**](cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb) - bioRxiv RSS, temporal KGs, deduplication, pathway analysis-#### Healthcare-- [**Drug Interactions Analysis**](cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb) - Medical RSS, relation-aware chunking, conflict detection, safety ontology-#### Finance- [**Financial Data Integration MCP**](cookbook/use_cases/finance/01_Financial_Data_Integration_MCP.ipynb) - Alpha Vantage API, MCP servers, seed data, real-time ingestion- [**Fraud Detection**](cookbook/use_cases/finance/02_Fraud_Detection.ipynb) - Transaction streams, temporal KGs, pattern detection, conflict resolution, **Context Graph**, **Context Retriever**, GraphRAG with Groq LLM@@ -685,9 +682,9 @@ print(f"Answer: {result.answer} | Nodes: {kg.node_count}, Edges: {kg.edge_count}**Finance & Trading** — Fraud detection, market intelligence, risk assessment.-**Healthcare & Biomedical** — Clinical reports, drug discovery, medical literature analysis.+**Biomedical** — Drug discovery, medical literature analysis.-[**Explore Use Case Examples**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases) — See real-world implementations in finance, healthcare, cybersecurity, trading, and more. **18 comprehensive domain-specific cookbooks** with real data sources, advanced chunking strategies, temporal KGs, GraphRAG, and full Semantica module integration.+[**Explore Use Case Examples**](https://github.com/Hawksight-AI/semantica/tree/main/cookbook/use_cases) — See real-world implementations in finance, biomedical, cybersecurity, trading, and more. **17 comprehensive domain-specific cookbooks** with real data sources, advanced chunking strategies, temporal KGs, GraphRAG, and full Semantica module integration.## 🔬 Advanced Featuresdiff --git a/STRATEGIES_SUMMARY.md b/STRATEGIES_SUMMARY.mdindex adf1ce02..81600adc 100644--- a/STRATEGIES_SUMMARY.md+++ b/STRATEGIES_SUMMARY.md@@ -4,8 +4,6 @@| Use Case | Deduplication Method | Merge Strategy | Conflict Detection | Conflict Resolution ||----------|---------------------|----------------|-------------------|---------------------|-| **Healthcare** |-| `02_Drug_Interactions_Analysis` | `EntityResolver` (semantic) | - | `relationship` | `voting` || **Finance** || `01_Financial_Data_Integration_MCP` | `DuplicateDetector` (incremental) | `keep_highest_confidence` | `temporal` | `most_recent` || `02_Fraud_Detection` | `ClusterBuilder` (graph_based) | `merge_all` | `logical` | `expert_review` |@@ -33,9 +31,6 @@## Strategy Rationale by Domain-### Healthcare-- **Drug Interactions**: Semantic matching for drug names; voting for interaction data aggregation-### Finance- **Financial Data Integration**: Incremental for streaming data; most_recent for time-sensitive financial data- **Fraud Detection**: Graph-based clustering for fraud groups; expert_review for fraud assessmentdiff --git a/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynbdeleted file mode 100644index a7fdbb2f..00000000--- a/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb+++ /dev/null@@ -1,860 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "[](https://colab.research.google.com/github/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb)\n",- "\n",- "# Drug Interactions Analysis - Ontology & Reasoning\n",- "\n",- "## Overview\n",- "\n",- "This notebook demonstrates **drug interactions analysis** using Semantica with focus on **multi-source correlation**, **safety ontology**, and **interaction detection**. The pipeline analyzes FDA databases, medical literature, and drug interaction sources to detect drug-drug and drug-condition interactions using ontology-based reasoning and temporal pattern detection.\n",- "\n",- "### Key Features\n",- "\n",- "- **Ontology Generation**: Creates safety ontologies for drug interactions\n",- "- **Multi-Source Correlation**: Correlates data from FDA databases and medical literature\n",- "- **Interaction Detection**: Detects drug-drug and drug-condition interactions\n",- "- **Safety Ontology**: Uses domain ontologies for safety analysis\n",- "- **Reasoning**: Emphasizes ontology and reasoning for interaction prediction\n",- "- **Conflict Resolution**: Resolves conflicting interaction reports from multiple sources\n",- "- **Temporal Pattern Detection**: Identifies interaction patterns over time\n",- "\n",- "### Learning Objectives\n",- "\n",- "- Understand how to generate safety ontologies from knowledge graphs\n",- "- Learn to detect and resolve conflicts in drug interaction data\n",- "- Master temporal pattern detection for interaction analysis\n",- "- Explore reasoning-based interaction inference\n",- "- Practice multi-source correlation and data integration\n",- "- Analyze drug network structures and community detection\n",- "\n",- "### Pipeline Flow\n",- "\n",- "```mermaid\n",- "graph TD\n",- " A[Data Ingestion] --> B[Document Parsing]\n",- " B --> C[Text Processing]\n",- " C --> D[Entity Extraction]\n",- " D --> E[Relationship Extraction]\n",- " E --> F[Deduplication]\n",- " F --> G[Conflict Detection]\n",- " G --> H[KG Construction]\n",- " H --> I[Embedding Generation]\n",- " I --> J[Vector Store]\n",- " H --> K[Ontology Generation]\n",- " H --> L[Graph Analytics]\n",- " H --> M[Temporal Patterns]\n",- " K --> N[Reasoning]\n",- " M --> N\n",- " J --> O[GraphRAG Queries]\n",- " L --> P[Visualization]\n",- " N --> P\n",- " K --> Q[Export RDF/TTL]\n",- "```\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn rdflib\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Configuration & Setup\n",- "\n",- "Configure API keys and set up constants for the drug interactions analysis pipeline, including ontology base URI.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "\n",- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key-here\")\n",- "\n",- "# Configuration constants\n",- "EMBEDDING_DIMENSION = 384\n",- "EMBEDDING_MODEL = \"sentence-transformers/all-MiniLM-L6-v2\"\n",- "CHUNK_SIZE = 1000\n",- "CHUNK_OVERLAP = 200\n",- "ONTOLOGY_BASE_URI = \"https://drug-safety.example.org/ontology/\"\n",- "TEMPORAL_GRANULARITY = \"day\" # For interaction pattern detection\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Data Ingestion\n",- "\n",- "Ingest drug interaction data from multiple sources including FDA RSS feeds, PubMed, medical literature, and drug interaction databases.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "import os\n",- "\n",- "os.makedirs(\"data\", exist_ok=True)\n",- "\n",- "documents = []\n",- "\n",- "# Ingest from FDA drug safety RSS feeds\n",- "fda_feeds = [\n",- " \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-drug-safety-communications\",\n",- " \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\"\n",- "]\n",- "\n",- "for feed_url in fda_feeds:\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " feed_ingestor = FeedIngestor()\n",- " feed_docs = feed_ingestor.ingest(feed_url, method=\"rss\")\n",- " documents.extend(feed_docs)\n",- " except Exception:\n",- " pass\n",- "\n",- "# Ingest from PubMed RSS (drug interactions)\n",- "pubmed_feeds = [\n",- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+interaction&limit=10\",\n",- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+safety&limit=10\",\n",- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=adverse+drug+reaction&limit=10\"\n",- "]\n",- "\n",- "for feed_url in pubmed_feeds:\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " feed_ingestor = FeedIngestor()\n",- " feed_docs = feed_ingestor.ingest(feed_url, method=\"rss\")\n",- " documents.extend(feed_docs)\n",- " except Exception:\n",- " pass\n",- "\n",- "# Example: Web ingestion from DrugBank API (commented - requires API key)\n",- "# web_ingestor = WebIngestor()\n",- "# drugbank_docs = web_ingestor.ingest(\"https://go.drugbank.com/releases/latest\", method=\"api\")\n",- "\n",- "# Fallback: Sample drug interaction data\n",- "if not documents:\n",- " drug_data = \"\"\"\n",- " Warfarin interacts with Aspirin, increasing bleeding risk. Severity: Major.\n",- " Metformin should not be used with patients having kidney disease. Contraindication: Severe renal impairment.\n",- " Ibuprofen can interact with ACE inhibitors, reducing effectiveness. Severity: Moderate.\n",- " Statins may interact with grapefruit juice, increasing side effects. Mechanism: CYP3A4 inhibition.\n",- " Digoxin interacts with Amiodarone, increasing toxicity risk. Severity: Major.\n",- " Aspirin and Warfarin together increase bleeding risk significantly.\n",- " Metformin contraindicated in patients with creatinine clearance < 30 mL/min.\n",- " \"\"\"\n",- " with open(\"data/drug_interactions.txt\", \"w\", encoding=\"utf-8\") as f:\n",- " f.write(drug_data)\n",- " file_ingestor = FileIngestor()\n",- " documents = file_ingestor.ingest(\"data/drug_interactions.txt\")\n",- "\n",- "print(f\"Ingested {len(documents)} documents\")\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.parse import DocumentParser\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "parser = DocumentParser()\n",- "\n",- "print(f\"Parsing {len(documents)} documents...\")\n",- "parsed_documents = []\n",- "for i, doc in enumerate(documents, 1):\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " parsed = parser.parse(\n",- " doc.content if hasattr(doc, 'content') else str(doc),\n",- " format=\"auto\"\n",- " )\n",- " parsed_documents.append(parsed)\n",- " except Exception:\n",- " parsed_documents.append(doc.content if hasattr(doc, 'content') else str(doc))\n",- " if i % 50 == 0 or i == len(documents):\n",- " print(f\" Parsed {i}/{len(documents)} documents...\")\n",- "\n",- "print(f\"Parsed {len(parsed_documents)} documents\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Text Processing\n",- "\n",- "Normalize drug names and use relation-aware chunking to preserve drug interaction triplets. This is critical for maintaining interaction relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.normalize import TextNormalizer\n",- "from semantica.split import TextSplitter\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "normalizer = TextNormalizer()\n",- "print(f\"Normalizing {len(parsed_documents)} documents...\")\n",- "normalized_docs = []\n",- "\n",- "for i, doc in enumerate(parsed_documents, 1):\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " normalized = normalizer.normalize(\n",- " doc if isinstance(doc, str) else str(doc),\n",- " clean_html=True,\n",- " normalize_entities=True,\n",- " remove_extra_whitespace=True\n",- " )\n",- " normalized_docs.append(normalized)\n",- " except Exception:\n",- " normalized_docs.append(doc if isinstance(doc, str) else str(doc))\n",- " if i % 50 == 0 or i == len(parsed_documents):\n",- " print(f\" Normalized {i}/{len(parsed_documents)} documents...\")\n",- "\n",- "# Use relation-aware chunking to preserve drug interaction triplets\n",- "relation_splitter = TextSplitter(\n",- " method=\"relation_aware\",\n",- " chunk_size=CHUNK_SIZE,\n",- " chunk_overlap=CHUNK_OVERLAP\n",- ")\n",- "\n",- "print(f\"Chunking {len(normalized_docs)} documents...\")\n",- "chunked_docs = []\n",- "for i, doc_text in enumerate(normalized_docs, 1):\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " chunks = relation_splitter.split(doc_text)\n",- " chunked_docs.extend([chunk.content if hasattr(chunk, 'content') else str(chunk) for chunk in chunks])\n",- " except Exception:\n",- " chunked_docs.append(doc_text)\n",- " if i % 50 == 0 or i == len(normalized_docs):\n",- " print(f\" Chunked {i}/{len(normalized_docs)} documents ({len(chunked_docs)} chunks so far)\")\n",- "\n",- "print(f\"Created {len(chunked_docs)} chunks from {len(normalized_docs)} documents\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Entity Extraction\n",- "\n",- "Extract drug interaction entities including drugs, interactions, conditions, side effects, contraindications, and mechanisms.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.semantic_extract import NERExtractor\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "extractor = NERExtractor(\n",- " provider=\"groq\",\n",- " model=\"llama-3.1-8b-instant\"\n",- ")\n",- "\n",- "entity_types = [\n",- " \"Drug\", \"Interaction\", \"Condition\", \"SideEffect\",\n",- " \"Contraindication\", \"Mechanism\"\n",- "]\n",- "\n",- "all_entities = []\n",- "chunks_to_process = chunked_docs[:10] # Limit for demo\n",- "print(f\"Extracting entities from {len(chunks_to_process)} chunks...\")\n",- "for i, chunk in enumerate(chunks_to_process, 1):\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " entities = extractor.extract(\n",- " chunk,\n",- " entity_types=entity_types\n",- " )\n",- " all_entities.extend(entities)\n",- " except Exception:\n",- " pass\n",- " \n",- " if i % 5 == 0 or i == len(chunks_to_process):\n",- " print(f\" Processed {i}/{len(chunks_to_process)} chunks ({len(all_entities)} entities found)\")\n",- "\n",- "print(f\"Extracted {len(all_entities)} entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Relationship Extraction\n",- "\n",- "Extract drug interaction relationships including interacts_with, causes, increases_risk, contraindicated_with, has_mechanism, and affects.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.semantic_extract import RelationExtractor\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "relation_extractor = RelationExtractor(\n",- " provider=\"groq\",\n",- " model=\"llama-3.1-8b-instant\"\n",- ")\n",- "\n",- "relation_types = [\n",- " \"interacts_with\", \"causes\", \"increases_risk\",\n",- " \"contraindicated_with\", \"has_mechanism\", \"affects\"\n",- "]\n",- "\n",- "all_relationships = []\n",- "chunks_to_process = chunked_docs[:10] # Limit for demo\n",- "print(f\"Extracting relationships from {len(chunks_to_process)} chunks...\")\n",- "for i, chunk in enumerate(chunks_to_process, 1):\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " relationships = relation_extractor.extract(\n",- " chunk,\n",- " relation_types=relation_types\n",- " )\n",- " all_relationships.extend(relationships)\n",- " except Exception:\n",- " pass\n",- " \n",- " if i % 5 == 0 or i == len(chunks_to_process):\n",- " print(f\" Processed {i}/{len(chunks_to_process)} chunks ({len(all_relationships)} relationships found)\")\n",- "\n",- "print(f\"Extracted {len(all_relationships)} relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Deduplication\n",- "\n",- "Deduplicate drug entities and interaction records to ensure data consistency.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.kg import EntityResolver\n",- "from semantica.semantic_extract import Entity\n",- "\n",- "# Convert Entity objects to dictionaries for EntityResolver\n",- "print(f\"Converting {len(all_entities)} entities to dictionaries...\")\n",- "entity_dicts = [{\"name\": e.get(\"name\", e.get(\"text\", \"\")), \"type\": e.get(\"type\", \"\"), \"start_char\": getattr(e, 'start_char', 0), \"end_char\": getattr(e, 'end_char', 0), \"confidence\": e.get(\"confidence\", 1.0)} for e in all_entities]\n",- "\n",- "# Use semantic strategy for drug names (handles synonyms and variations)\n",- "# Semantic matching is essential for drug names which may have multiple representations\n",- "entity_resolver = EntityResolver(strategy=\"semantic\", similarity_threshold=0.85)\n",- "\n",- "print(f\"Resolving duplicates in {len(entity_dicts)} entities using semantic matching...\")\n",- "resolved_entities = entity_resolver.resolve_entities(entity_dicts)\n",- "\n",- "# Convert back to Entity objects\n",- "print(f\"Converting {len(resolved_entities)} resolved entities back to Entity objects...\")\n",- "merged_entities = [\n",- " Entity(text=e[\"name\"], label=e[\"type\"], start_char=e.get(\"start_char\", 0), end_char=e.get(\"end_char\", 0), confidence=e.get(\"confidence\", 1.0))\n",- " if isinstance(e, dict) else e\n",- " for e in resolved_entities\n",- "]\n",- "\n",- "all_entities = merged_entities\n",- "print(f\"Deduplicated {len(entity_dicts)} entities to {len(merged_entities)} unique entities\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Conflict Detection\n",- "\n",- "Detect and resolve conflicts in drug interaction data from multiple sources. This is unique to this notebook and critical for multi-source correlation.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.conflicts import ConflictDetector, ConflictResolver\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "# Use relationship conflict detection for drug interaction disagreements\n",- "# voting strategy aggregates multiple sources for interaction data\n",- "conflict_detector = ConflictDetector()\n",- "conflict_resolver = ConflictResolver()\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " print(f\"Detecting relationship conflicts in drug interaction data...\")\n",- " # Detect relationship conflicts (multiple sources may report different interactions)\n",- " conflicts = conflict_detector.detect_conflicts(\n",- " entities=all_entities,\n",- " relationships=all_relationships,\n",- " method=\"relationship\" # Focus on relationship conflicts\n",- " )\n",- " \n",- " print(f\"Detected {len(conflicts)} relationship conflicts in drug interaction data\")\n",- " \n",- " # Resolve conflicts using voting strategy (aggregate multiple sources)\n",- " if conflicts:\n",- " print(f\"Resolving conflicts using voting strategy...\")\n",- " resolved = conflict_resolver.resolve_conflicts(\n",- " conflicts,\n",- " strategy=\"voting\" # Majority vote from multiple sources\n",- " )\n",- " print(f\"Resolved {len(resolved)} conflicts\")\n",- " \n",- " # Update relationships with resolved conflicts\n",- " for conflict in resolved:\n",- " # Remove conflicting relationships and keep resolved ones\n",- " pass\n",- "except Exception:\n",- " print(\"Conflict detection completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Knowledge Graph Construction\n",- "\n",- "Build the drug interaction knowledge graph from extracted entities and relationships.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.kg import GraphBuilder\n",- "\n",- "builder = GraphBuilder()\n",- "\n",- "kg = builder.build(\n",- " entities=all_entities,\n",- " relationships=all_relationships\n",- ")\n",- "\n",- "print(f\"Built KG with {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Embedding Generation & Vector Store\n",- "\n",- "Generate embeddings for drug interaction documents and store them in a vector database for semantic search.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.embeddings import EmbeddingGenerator\n",- "from semantica.vector_store import VectorStore\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "embedding_gen = EmbeddingGenerator(\n",- " model_name=EMBEDDING_MODEL,\n",- " dimension=EMBEDDING_DIMENSION\n",- ")\n",- "\n",- "# Generate embeddings for chunks\n",- "embeddings = []\n",- "for chunk in chunked_docs[:20]: # Limit for demo\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " embedding = embedding_gen.generate(chunk)\n",- " embeddings.append(embedding)\n",- " except Exception:\n",- " pass\n",- "\n",- "# Create vector store\n",- "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",- "\n",- "# Add embeddings to vector store\n",- "for i, (chunk, embedding) in enumerate(zip(chunked_docs[:20], embeddings)):\n",- " try:\n",- " vector_store.add(\n",- " id=str(i),\n",- " embedding=embedding,\n",- " metadata={\"text\": chunk[:100]} # Store first 100 chars\n",- " )\n",- " except Exception:\n",- " pass\n",- "\n",- "print(f\"Generated {len(embeddings)} embeddings and stored in vector database\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Safety Ontology Generation\n",- "\n",- "Generate a safety ontology from the knowledge graph. This is unique to this notebook and enables semantic reasoning about drug interactions.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.ontology import OntologyGenerator\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " ontology_gen = OntologyGenerator(base_uri=ONTOLOGY_BASE_URI)\n",- " ontology = ontology_gen.generate_from_graph(kg)\n",- " \n",- " print(f\"Generated safety ontology with {len(ontology.get('classes', []))} classes\")\n",- " print(f\"Ontology includes {len(ontology.get('properties', []))} properties\")\n",- "except Exception:\n",- " print(\"Ontology generation completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Analyzing Drug Network Structure\n",- "\n",- "Analyze the drug interaction knowledge graph to identify key drugs, interaction patterns, and communities.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.kg import GraphAnalyzer, CentralityCalculator, CommunityDetector\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "graph_analyzer = GraphAnalyzer(kg)\n",- "centrality_calc = CentralityCalculator(kg)\n",- "community_detector = CommunityDetector(kg)\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " # Calculate centrality metrics\n",- " degree_centrality = centrality_calc.degree_centrality()\n",- " betweenness_centrality = centrality_calc.betweenness_centrality()\n",- " \n",- " # Find key drugs (high degree centrality)\n",- " if degree_centrality:\n",- " top_drugs = sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]\n",- " print(f\"Top 5 drugs by connectivity: {[d[0] for d in top_drugs]}\")\n",- " \n",- " # Detect communities in drug interaction network\n",- " communities = community_detector.detect_communities()\n",- " print(f\"Detected {len(communities)} communities in drug network\")\n",- " \n",- " # Analyze graph structure\n",- " stats = graph_analyzer.get_statistics()\n",- " print(f\"Graph statistics: {stats.get('num_nodes', 0)} nodes, {stats.get('num_edges', 0)} edges\")\n",- "except Exception:\n",- " print(\"Graph analysis completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Temporal Pattern Detection\n",- "\n",- "Detect temporal patterns in drug interactions over time. This helps identify emerging interaction trends and safety concerns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.kg import TemporalPatternDetector\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "# Build temporal graph for pattern detection\n",- "temporal_builder = GraphBuilder(enable_temporal=True, temporal_granularity=TEMPORAL_GRANULARITY)\n",- "temporal_kg = temporal_builder.build(entities=all_entities, relationships=all_relationships)\n",- "\n",- "pattern_detector = TemporalPatternDetector(temporal_kg)\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " # Detect interaction patterns over time\n",- " patterns = pattern_detector.detect_patterns(\n",- " pattern_type=\"interaction\",\n",- " time_granularity=TEMPORAL_GRANULARITY\n",- " )\n",- " \n",- " print(f\"Detected {len(patterns)} temporal interaction patterns\")\n",- " \n",- " # Analyze evolution of drug interactions\n",- " evolution = pattern_detector.analyze_evolution(\n",- " entity_type=\"Interaction\",\n",- " time_window=None\n",- " )\n",- " print(f\"Analyzed interaction evolution over time\")\n",- "except Exception:\n",- " print(\"Temporal pattern detection completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Reasoning and Interaction Detection\n",- "\n",- "Use reasoning with custom rules to infer new drug interactions and detect potential safety concerns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.reasoning import Reasoner\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "reasoner = Reasoner(kg)\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " # Add custom rules for drug interaction inference\n",- " rules = [\n",- " \"IF Drug A interacts_with Drug B AND Drug B interacts_with Drug C THEN Drug A may_interact_with Drug C\",\n",- " \"IF Drug has_mechanism CYP3A4_inhibition AND Other_Drug metabolized_by CYP3A4 THEN Drug increases_risk interaction_with Other_Drug\",\n",- " \"IF Drug contraindicated_with Condition AND Patient has Condition THEN Drug contraindicated_for Patient\"\n",- " ]\n",- " \n",- " for rule in rules:\n",- " reasoner.add_rule(rule)\n",- " \n",- " # Infer new facts\n",- " inferred_facts = reasoner.infer_facts()\n",- " print(f\"Inferred {len(inferred_facts)} new interaction facts\")\n",- " \n",- " # Find interaction patterns\n",- " interaction_patterns = reasoner.find_patterns(pattern_type=\"interaction\")\n",- " print(f\"Found {len(interaction_patterns)} interaction patterns\")\n",- " \n",- " # Identify drug-drug interactions\n",- " drug_interactions = [r for r in kg.get(\"relationships\", []) \n",- " if \"interact\" in str(r.get(\"predicate\", \"\")).lower()]\n",- " print(f\"Identified {len(drug_interactions)} drug-drug interactions\")\n",- "except Exception:\n",- " print(\"Reasoning and interaction detection completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## GraphRAG Queries\n",- "\n",- "Use hybrid retrieval combining vector search and graph traversal to answer complex drug interaction questions.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.context import AgentContext\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "agent_context = AgentContext(\n",- " vector_store=vector_store,\n",- " knowledge_graph=kg\n",- ")\n",- "\n",- "queries = [\n",- " \"What drugs interact with Warfarin?\",\n",- " \"What are the contraindications for Metformin?\",\n",- " \"What mechanisms cause drug interactions?\",\n",- " \"Which drugs have the highest interaction risk?\"\n",- "]\n",- "\n",- "for query in queries:\n",- " try:\n",- " with redirect_stderr(StringIO()):\n",- " results = agent_context.query(\n",- " query=query,\n",- " top_k=5\n",- " )\n",- " print(f\"Query: {query}\")\n",- " print(f\"Found {len(results.get('results', []))} relevant results\")\n",- " except Exception:\n",- " pass\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Visualization\n",- "\n",- "Visualize the drug interaction knowledge graph to explore relationships, communities, and interaction patterns.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.visualization import KGVisualizer\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "visualizer = KGVisualizer()\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " visualizer.visualize(\n",- " kg,\n",- " output_path=\"drug_interactions_kg.html\",\n",- " layout=\"force_directed\"\n",- " )\n",- " print(\"Knowledge graph visualization saved to drug_interactions_kg.html\")\n",- "except Exception:\n",- " print(\"Visualization completed\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---\n",- "\n",- "## Export\n",- "\n",- "Export the knowledge graph and ontology in multiple formats including JSON, GraphML, and RDF/TTL for ontology sharing and interoperability.\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from semantica.export import GraphExporter\n",- "from contextlib import redirect_stderr\n",- "from io import StringIO\n",- "\n",- "exporter = GraphExporter()\n",- "\n",- "try:\n",- " with redirect_stderr(StringIO()):\n",- " # Export knowledge graph as JSON\n",- " exporter.export(kg, format=\"json\", output_path=\"drug_interactions_kg.json\")\n",- " \n",- " # Export as GraphML\n",- " exporter.export(kg, format=\"graphml\", output_path=\"drug_interactions_kg.graphml\")\n",- " \n",- " # Export ontology as RDF/TTL (for ontology sharing)\n",- " exporter.export(kg, format=\"rdf\", output_path=\"drug_safety_ontology.ttl\")\n",- " \n",- " print(\"Exported knowledge graph and ontology in JSON, GraphML, and RDF/TTL formats\")\n",- "except Exception:\n",- " print(\"Export completed\")\n"- ]- }- ],- "metadata": {- "language_info": {- "name": "python"- }- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 220f4422..2f4f7b3b 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -359,22 +359,6 @@ Real-world examples and end-to-end applications across various industries.</div>-### Healthcare--<div class="grid cards" markdown>--- :material-pill-multiple: **Drug Interactions Analysis**- ---- Identifying potential drug interactions and contraindications using medical RSS feeds, relation-aware chunking, conflict detection, and safety ontology generation.-- **Topics**: Pharmacology, Drug Safety, Ontology, Conflict Resolution-- **Difficulty**: Advanced-- [Open Notebook](https://github.com/Hawksight-AI/semantica/blob/main/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb)--</div>-### Finance<div class="grid cards" markdown>diff --git a/docs/index.md b/docs/index.mdindex 1d9cd9f5..8874e8d5 100644--- a/docs/index.md+++ b/docs/index.md@@ -307,7 +307,7 @@ Power GraphRAG applications with:- :material-chef-hat: **Cookbook**---- Interactive tutorials, real-world examples, and **18 domain-specific cookbooks**.+ Interactive tutorials, real-world examples, and **17 domain-specific cookbooks**.[:arrow_right: Explore Cookbook](cookbook.md)@@ -443,7 +443,7 @@ print(result.confidence) # 0.98- [Getting Started Guide](getting-started.md) - Your first knowledge graph in 5 minutes- [Core Concepts](concepts.md) - Deep dive into knowledge graphs and ontologies-- [Cookbook](cookbook.md) - Real-world examples and **18 domain-specific cookbooks**+- [Cookbook](cookbook.md) - Real-world examples and **17 domain-specific cookbooks**- [API Reference](reference/core.md) - Complete technical documentation---