Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor biomedical notebooks: Use modular architecture with cell-specific imports and comprehensive data sources

KaifAhmad13f74040509a2
diff --git a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
index 414e9ef9..d3ba3e62 100644
--- a/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
+++ b/cookbook/use_cases/biomedical/01_Drug_Discovery_Pipeline.ipynb
@@ -1,1231 +1,601 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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 - Vector Similarity Search\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates a **complete drug discovery pipeline** using Semantica that focuses on **vector similarity search** and **interaction prediction**. The pipeline ingests drug and protein data, extracts compound and target entities, builds a drug-target knowledge graph, and performs similarity search to predict drug-target interactions.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **Vector-Focused Approach**: Emphasizes embeddings and vector similarity search for drug-target interaction prediction\n",
- "- **Compound-Target Extraction**: Extracts drug compounds, proteins, and targets from biomedical literature\n",
- "- **Similarity Search**: Uses vector embeddings to find similar compounds and predict interactions\n",
- "- **Knowledge Graph Construction**: Builds structured drug-target relationship graphs\n",
- "- **Interaction Prediction**: Predicts potential drug-target interactions using similarity metrics\n",
- "\n",
- "### What You'll Learn\n",
- "\n",
- "- How to ingest biomedical data (drug databases, protein data, literature)\n",
- "- How to extract compound and target entities from unstructured text\n",
- "- How to generate embeddings for drugs and proteins\n",
- "- How to perform similarity search to find similar compounds\n",
- "- How to build drug-target knowledge graphs\n",
- "- How to predict drug-target interactions using vector similarity\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: Biomedical Data Ingestion\n",
- "3. **Phase 2**: Document Parsing & Processing\n",
- "4. **Phase 3**: Entity Extraction (Drugs, Proteins, Targets)\n",
- "5. **Phase 4**: Embedding Generation\n",
- "6. **Phase 5**: Vector Store Population\n",
- "7. **Phase 6**: Similarity Search & Interaction Prediction\n",
- "8. **Phase 7**: Knowledge Graph Construction\n",
- "9. **Phase 8**: Visualization & Export\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n",
- "\n",
- "Install Semantica and required dependencies:\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Note: you may need to restart the kernel to use updated packages.\n"
- ]
- },
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
- "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
- ]
- }
- ],
- "source": [
- "# Install Semantica and required dependencies\n",
- "%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers scikit-learn\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Setup & Configuration\n",
- "\n",
- "- Configure Semantica for drug discovery\n",
- "- Focus on vector similarity search\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Environment configured.\n"
- ]
- }
- ],
- "source": [
- "import os\n",
- "\n",
- "# Set API keys\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"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\")\n",
- "\n",
- "print(\"Environment configured.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "- Import and configure Semantica core components\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Semantica core configured.\n"
- ]
- }
- ],
- "source": [
- "from semantica.core import Semantica, ConfigManager\n",
- "\n",
- "# Configure for drug discovery with vector similarity focus\n",
- "config_dict = {\n",
- " \"project_name\": \"Drug_Discovery_Pipeline\",\n",
- " \"embedding\": {\n",
- " \"provider\": \"sentence_transformers\",\n",
- " \"model\": \"all-MiniLM-L6-v2\" # 384-dimensional embeddings\n",
- " },\n",
- " \"extraction\": {\n",
- " \"provider\": \"groq\",\n",
- " \"model\": \"llama-3.1-8b-instant\",\n",
- " \"temperature\": 0.0\n",
- " },\n",
- " \"vector_store\": {\n",
- " \"provider\": \"faiss\",\n",
- " \"dimension\": 384\n",
- " },\n",
- " \"knowledge_graph\": {\n",
- " \"backend\": \"networkx\",\n",
- " \"merge_entities\": True\n",
- " }\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "\n",
- "print(\"Semantica core configured.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Vector store initialized.\n"
- ]
- }
- ],
- "source": [
- "from semantica.vector_store import VectorStore\n",
- "\n",
- "# Initialize vector store with FAISS backend\n",
- "vector_store = VectorStore(backend=\"faiss\", dimension=384)\n",
- "\n",
- "print(\"Vector store initialized.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Biomedical Data Ingestion\n",
- "\n",
- "- Ingest biomedical data from PubMed RSS feeds\n",
- "- Use FeedIngestor for data collection\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Data directory ready.\n"
- ]
- }
- ],
- "source": [
- "import os\n",
- "# Create data directory if it doesn't exist\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "print(\"Data directory ready.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Configured 8 RSS feed sources\n"
- ]
- }
- ],
- "source": [
- "from semantica.ingest import FeedIngestor\n",
- "from contextlib import redirect_stderr\n",
- "from io import StringIO\n",
- "\n",
- "# Multiple RSS feed options for biomedical data\n",
- "feed_urls = [\n",
- " (\"PubMed - Drug Discovery\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+discovery&limit=10&sort=pub_date&fc=article_type\"),\n",
- " (\"PubMed - Drug Target Interaction\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+target+interaction&limit=10&sort=pub_date\"),\n",
- " (\"PubMed - Pharmacokinetics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=pharmacokinetics&limit=10&sort=pub_date\"),\n",
- " (\"PubMed - Pharmacodynamics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=pharmacodynamics&limit=10&sort=pub_date\"),\n",
- " (\"PubMed - Clinical Trial\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=clinical+trial&limit=10&sort=pub_date\"),\n",
- " (\"PubMed - Protein Target\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=protein+target&limit=10&sort=pub_date\"),\n",
- " (\"BioRxiv - Pharmacology\", \"https://connect.biorxiv.org/biorxiv_xml.php?subject=pharmacology_and_toxicology\"),\n",
- " (\"Nature - Drug Discovery\", \"https://www.nature.com/subjects/drug-discovery.rss\")\n",
- "]\n",
- "\n",
- "print(f\"Configured {len(feed_urls)} RSS feed sources\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "FeedIngestor initialized\n"
- ]
- }
- ],
- "source": [
- "# Initialize FeedIngestor\n",
- "feed_ingestor = FeedIngestor()\n",
- "print(\"FeedIngestor initialized\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [
- {
- "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 normalizing</td><td>πŸ”§ normalize</td><td>TextNormalizer</td><td>-</td><td>0.00s</td></tr><tr><td>βœ…</td><td>Semantica is extracting</td><td>🎯 semantic_extract</td><td>NERExtractor</td><td>-</td><td>0.65s</td></tr><tr><td>βœ…</td><td>Semantica is processing</td><td>⏳ core</td><td>LifecycleManager</td><td>-</td><td>1.19s</td></tr><tr><td>πŸ”„</td><td>Semantica is processing</td><td>⏳ core</td><td>Semantica</td><td>-</td><td>0.06s</td></tr><tr><td>βœ…</td><td>Semantica is executing</td><td>βš™οΈ pipeline</td><td>PipelineBuilder</td><td>-</td><td>0.03s</td></tr><tr><td>βœ…</td><td>Semantica is executing</td><td>βš™οΈ pipeline</td><td>PipelineValidator</td><td>-</td><td>0.01s</td></tr><tr><td>πŸ”„</td><td>Semantica is processing</td><td>⏳ core</td><td>build_knowledge_base</td><td>chunk_0.txt</td><td>0.01s</td></tr><tr><td>πŸ”„</td><td>Semantica is executing</td><td>βš™οΈ pipeline</td><td>ExecutionEngine</td><td>chunk_0.txt</td><td>0.01s</td></tr><tr><td>πŸ”„</td><td>Semantica is executing</td><td>βš™οΈ pipeline</td><td>ExecutionEngine</td><td>-</td><td>0.01s</td></tr><tr><td>πŸ”„</td><td>Semantica is executing</td><td>βš™οΈ pipeline</td><td>ResourceScheduler</td><td>-</td><td>0.00s</td></tr></table></div>"
- ],
- "text/plain": [
- "<IPython.core.display.HTML object>"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "βœ“ Successfully ingested 30 documents from Nature - Drug Discovery\n"
- ]
- }
- ],
- "source": [
- "# Try each feed URL until one succeeds (suppress error messages)\n",
- "documents = None\n",
- "\n",
- "for feed_name, feed_url in feed_urls:\n",
- " try:\n",
- " # Suppress stderr to avoid cluttering output with parsing errors\n",
- " with redirect_stderr(StringIO()):\n",
- " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
- " \n",
- " # Convert FeedItem objects to documents\n",
- " documents = []\n",
- " for item in feed_data.items:\n",
- " if not item.content:\n",
- " item.content = item.description or item.title or \"\"\n",
- " if item.content:\n",
- " documents.append(item)\n",
- " \n",
- " if documents:\n",
- " print(f\"βœ“ Successfully ingested {len(documents)} documents from {feed_name}\")\n",
- " break\n",
- " except Exception:\n",
- " continue\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Fallback to sample data if all RSS feeds failed\n",
- "from semantica.ingest import FileIngestor\n",
- "\n",
- "if not documents:\n",
- " sample_drug_data = \"\"\"\n",
- " Aspirin (acetylsalicylic acid) is a medication used to reduce pain, fever, or inflammation. \n",
- " It targets cyclooxygenase enzymes COX-1 and COX-2. Aspirin is commonly used for cardiovascular protection.\n",
- " Ibuprofen is a nonsteroidal anti-inflammatory drug (NSAID) that targets COX-1 and COX-2 enzymes.\n",
- " Metformin is an antidiabetic medication that targets AMP-activated protein kinase (AMPK).\n",
- " Insulin targets the insulin receptor (INSR) to regulate glucose metabolism.\n",
- " Warfarin is an anticoagulant that targets vitamin K epoxide reductase complex subunit 1 (VKORC1).\n",
- " Atorvastatin is a statin medication that targets HMG-CoA reductase.\n",
- " \"\"\"\n",
- " \n",
- " import os\n",
- " os.makedirs(\"data\", exist_ok=True)\n",
- " with open(\"data/sample_drugs.txt\", \"w\") as f:\n",
- " f.write(sample_drug_data)\n",
- " \n",
- " file_ingestor = FileIngestor()\n",
- " documents = file_ingestor.ingest(\"data/sample_drugs.txt\")\n",
- " print(f\"Ingested {len(documents)} documents from sample data\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "TextNormalizer initialized\n"
- ]
- }
- ],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "\n",
- "# Initialize text normalizer\n",
- "normalizer = TextNormalizer()\n",
- "print(\"TextNormalizer initialized\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Normalized 30 documents\n"
- ]
- }
- ],
- "source": [
- "# Normalize all documents\n",
- "normalized_documents = []\n",
- "for doc in documents:\n",
- " normalized_text = normalizer.normalize(\n",
- " doc.content if hasattr(doc, 'content') else str(doc),\n",
- " clean_html=True,\n",
- " normalize_entities=True,\n",
- " remove_extra_whitespace=True,\n",
- " lowercase=False # Preserve drug names (case-sensitive)\n",
- " )\n",
- " normalized_documents.append(normalized_text)\n",
- "\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Preview normalized text\n",
- "if normalized_documents:\n",
- " print(f\"Sample normalized text (first 200 chars): {normalized_documents[0][:200]}\")\n",
- "else:\n",
- " print(\"No normalized documents available\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Text Normalization & Cleaning\n",
- "\n",
- "- Clean HTML tags and special characters\n",
- "- Normalize entity names\n",
- "- Remove extra whitespace\n",
- "- Preserve drug names (case-sensitive)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Entity-Aware Chunking\n",
- "\n",
- "- Use entity-aware chunking to preserve drug/protein entity boundaries\n",
- "- Essential for GraphRAG operations\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "TextSplitter initialized with entity-aware chunking\n"
- ]
- }
- ],
- "source": [
- "from semantica.split import TextSplitter\n",
- "from contextlib import redirect_stderr\n",
- "from io import StringIO\n",
- "\n",
- "# Initialize TextSplitter with entity-aware chunking\n",
- "# Using 'spacy' instead of 'llm' to avoid API key requirements\n",
- "splitter = TextSplitter(\n",
- " method=\"entity_aware\",\n",
- " ner_method=\"spacy\", # Use spaCy for entity recognition (no API key needed)\n",
- " chunk_size=1000,\n",
- " chunk_overlap=200\n",
- ")\n",
- "\n",
- "print(\"TextSplitter initialized with entity-aware chunking\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Created 30 chunks\n"
- ]
- }
- ],
- "source": [
- "# Chunk normalized documents (suppress error messages)\n",
- "chunked_documents = []\n",
- "for doc_text in normalized_documents:\n",
- " try:\n",
- " # Suppress stderr to avoid cluttering output with NER errors\n",
- " with redirect_stderr(StringIO()):\n",
- " chunks = splitter.split(doc_text)\n",
- " chunked_documents.extend(chunks)\n",
- " except Exception:\n",
- " # Fallback to simple recursive splitting if entity-aware fails\n",
- " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=1000, chunk_overlap=200)\n",
- " chunks = simple_splitter.split(doc_text)\n",
- " chunked_documents.extend(chunks)\n",
- "\n",
- "print(f\"Created {len(chunked_documents)} chunks\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Sample chunk (first 200 chars): Apoptotic signatures allow early and rapid screening of drug-induced liver injury to accelerate drug discovery\n"
- ]
- }
- ],
- "source": [
- "# Preview sample chunk\n",
- "if chunked_documents:\n",
- " sample_chunk = chunked_documents[0]\n",
- " chunk_text = sample_chunk.text if hasattr(sample_chunk, 'text') else str(sample_chunk)\n",
- " print(f\"Sample chunk (first 200 chars): {chunk_text[:200]}\")\n",
- "else:\n",
- " print(\"No chunks available\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Entity Extraction & Knowledge Graph Construction\n",
- "\n",
- "- Extract drug and protein entities\n",
- "- Build knowledge graph from extracted entities\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Prepared 30 chunk files for entity extraction\n"
- ]
- }
- ],
- "source": [
- "# Convert chunks to text files\n",
- "# build_knowledge_base requires file paths or URLs, not raw text\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data/chunks\", exist_ok=True)\n",
- "chunk_files = []\n",
- "\n",
- "for i, chunk in enumerate(chunked_documents):\n",
- " # Extract text from chunk object\n",
- " if hasattr(chunk, 'text'):\n",
- " chunk_text = chunk.text\n",
- " elif hasattr(chunk, 'content'):\n",
- " chunk_text = chunk.content\n",
- " else:\n",
- " chunk_text = str(chunk)\n",
- " \n",
- " # Save chunk to temporary file\n",
- " chunk_file = f\"data/chunks/chunk_{i}.txt\"\n",
- " with open(chunk_file, \"w\", encoding=\"utf-8\") as f:\n",
- " f.write(chunk_text)\n",
- " chunk_files.append(chunk_file)\n",
- "\n",
- "print(f\"Prepared {len(chunk_files)} chunk files for entity extraction\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Build knowledge base with entity extraction\n",
- "result = core.build_knowledge_base(\n",
- " sources=chunk_files,\n",
- " custom_entity_types=[\"Drug\", \"Protein\", \"Target\", \"Compound\", \"Enzyme\", \"Receptor\"],\n",
- " embeddings=True,\n",
- " graph=True\n",
- ")\n",
- "\n",
- "print(\"Knowledge base built successfully\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Extract entities from result\n",
- "entities = result[\"entities\"]\n",
- "print(f\"Total entities extracted: {len(entities)}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Filter drugs and proteins\n",
- "drugs = [e for e in entities if e.get(\"type\") == \"Drug\" or \"drug\" in e.get(\"type\", \"\").lower()]\n",
- "proteins = [e for e in entities if e.get(\"type\") == \"Protein\" or \"protein\" in e.get(\"type\", \"\").lower()]\n",
- "\n",
- "print(f\"Extracted {len(drugs)} drugs and {len(proteins)} proteins\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Preview sample drugs\n",
- "print(\"Sample drugs:\")\n",
- "for d in drugs[:3]:\n",
- " print(f\" - {d.get('text', 'Unknown')[:50]}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Preview sample proteins\n",
- "print(\"Sample proteins:\")\n",
- "for p in proteins[:3]:\n",
- " print(f\" - {p.get('text', 'Unknown')[:50]}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Get knowledge graph statistics\n",
- "kg = result[\"knowledge_graph\"]\n",
- "print(f\"Knowledge graph contains:\")\n",
- "print(f\" - {len(kg.get('entities', []))} entities\")\n",
- "print(f\" - {len(kg.get('relationships', []))} relationships\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Entity-Aware Chunking\n",
- "\n",
- "- Use entity-aware chunking to preserve drug/protein entity boundaries\n",
- "- Essential for GraphRAG operations\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Define GraphRAG query\n",
- "query = \"What drugs target COX enzymes?\"\n",
- "print(f\"Query: {query}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Retrieve using GraphRAG (hybrid vector + graph retrieval)\n",
- "results = context.retrieve(\n",
- " query,\n",
- " max_results=10,\n",
- " use_graph=True, # Enable graph traversal\n",
- " expand_graph=True, # Expand graph relationships\n",
- " include_entities=True, # Include related entities\n",
- " include_relationships=True # Include relationships\n",
- ")\n",
- "\n",
- "print(f\"GraphRAG retrieved {len(results)} results\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display GraphRAG results\n",
- "for i, result in enumerate(results[:5], 1):\n",
- " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
- " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n",
- " print()\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Created 30 chunks using entity-aware chunking\n"
- ]
- }
- ],
- "source": [
- "from semantica.split import TextSplitter\n",
- "from contextlib import redirect_stderr\n",
- "from io import StringIO\n",
- "\n",
- "# Use entity-aware chunking to preserve drug/protein entity boundaries\n",
- "# Using 'spacy' instead of 'llm' to avoid API key requirements\n",
- "splitter = TextSplitter(\n",
- " method=\"entity_aware\",\n",
- " ner_method=\"spacy\", # Use spaCy for entity recognition (no API key needed)\n",
- " chunk_size=1000,\n",
- " chunk_overlap=200\n",
- ")\n",
- "\n",
- "# Chunk normalized documents (suppress error messages)\n",
- "chunked_documents = []\n",
- "for doc_text in normalized_documents:\n",
- " try:\n",
- " # Suppress stderr to avoid cluttering output with NER errors\n",
- " with redirect_stderr(StringIO()):\n",
- " chunks = splitter.split(doc_text)\n",
- " chunked_documents.extend(chunks)\n",
- " except Exception:\n",
- " # Fallback to simple recursive splitting if entity-aware fails\n",
- " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=1000, chunk_overlap=200)\n",
- " chunks = simple_splitter.split(doc_text)\n",
- " chunked_documents.extend(chunks)\n",
- "\n",
- "print(f\"Created {len(chunked_documents)} chunks using entity-aware chunking\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Prepare drug texts for embedding\n",
- "drug_texts = [f\"{d.get('text', '')} {d.get('description', '')}\" for d in drugs]\n",
- "print(f\"Prepared {len(drug_texts)} drug texts for embedding\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Generate drug embeddings\n",
- "drug_embeddings = embedding_gen.generate_embeddings(drug_texts)\n",
- "print(f\"Generated {len(drug_embeddings)} drug embeddings\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Store embeddings in vector store\n",
- "drug_ids = vector_store.store_vectors(\n",
- " vectors=drug_embeddings,\n",
- " metadata=[{\"type\": \"drug\", \"name\": d.get(\"text\", \"\")} for d in drugs]\n",
- ")\n",
- "\n",
- "print(f\"Stored {len(drug_ids)} drug embeddings in vector store\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Entity Extraction & Knowledge Graph Construction\n",
- "\n",
- "- Extract drug and protein entities\n",
- "- Build knowledge graph from extracted entities\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Generate query embedding\n",
- "query_embedding = embedding_gen.generate_embeddings([query_drug])[0]\n",
- "print(\"Query embedding generated\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Search for similar drugs\n",
- "similar_drugs = vector_store.search_vectors(query_embedding, k=5)\n",
- "print(f\"Found {len(similar_drugs)} similar drugs\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display similar drugs\n",
- "print(f\"Drugs similar to '{query_drug}':\")\n",
- "for i, result in enumerate(similar_drugs, 1):\n",
- " print(f\"{i}. {result['metadata'].get('name', 'Unknown')} (similarity: {result['score']:.3f})\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Prepared 30 chunk files for entity extraction\n"
- ]
- }
- ],
- "source": [
- "# Convert chunks to text strings and save to temporary files\n",
- "# build_knowledge_base requires file paths or URLs, not raw text\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data/chunks\", exist_ok=True)\n",
- "chunk_files = []\n",
- "\n",
- "for i, chunk in enumerate(chunked_documents):\n",
- " # Extract text from chunk object\n",
- " if hasattr(chunk, 'text'):\n",
- " chunk_text = chunk.text\n",
- " elif hasattr(chunk, 'content'):\n",
- " chunk_text = chunk.content\n",
- " else:\n",
- " chunk_text = str(chunk)\n",
- " \n",
- " # Save chunk to temporary file\n",
- " chunk_file = f\"data/chunks/chunk_{i}.txt\"\n",
- " with open(chunk_file, \"w\", encoding=\"utf-8\") as f:\n",
- " f.write(chunk_text)\n",
- " chunk_files.append(chunk_file)\n",
- "\n",
- "print(f\"Prepared {len(chunk_files)} chunk files for entity extraction\")\n",
- "\n",
- "# Build knowledge base with entity extraction\n",
- "result = core.build_knowledge_base(\n",
- " sources=chunk_files,\n",
- " custom_entity_types=[\"Drug\", \"Protein\", \"Target\", \"Compound\", \"Enzyme\", \"Receptor\"],\n",
- " embeddings=True,\n",
- " graph=True\n",
- ")\n",
- "\n",
- "# Extract entities\n",
- "entities = result[\"entities\"]\n",
- "drugs = [e for e in entities if e.get(\"type\") == \"Drug\" or \"drug\" in e.get(\"type\", \"\").lower()]\n",
- "proteins = [e for e in entities if e.get(\"type\") == \"Protein\" or \"protein\" in e.get(\"type\", \"\").lower()]\n",
- "\n",
- "print(f\"Extracted {len(drugs)} drugs and {len(proteins)} proteins\")\n",
- "print(f\"\\nSample drugs:\")\n",
- "for d in drugs[:3]:\n",
- " print(f\" - {d.get('text', 'Unknown')[:50]}\")\n",
- "print(f\"\\nSample proteins:\")\n",
- "for p in proteins[:3]:\n",
- " print(f\" - {p.get('text', 'Unknown')[:50]}\")\n",
- "\n",
- "# Get knowledge graph\n",
- "kg = result[\"knowledge_graph\"]\n",
- "print(f\"\\nKnowledge graph contains:\")\n",
- "print(f\" - {len(kg.get('entities', []))} entities\")\n",
- "print(f\" - {len(kg.get('relationships', []))} relationships\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Define GraphRAG query\n",
- "query = \"What drugs target COX enzymes?\"\n",
- "print(f\"Query: {query}\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Retrieve using GraphRAG (hybrid vector + graph retrieval)\n",
- "results = context.retrieve(\n",
- " query,\n",
- " max_results=10,\n",
- " use_graph=True, # Enable graph traversal\n",
- " expand_graph=True, # Expand graph relationships\n",
- " include_entities=True, # Include related entities\n",
- " include_relationships=True # Include relationships\n",
- ")\n",
- "\n",
- "print(f\"GraphRAG retrieved {len(results)} results\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display GraphRAG results\n",
- "for i, result in enumerate(results[:5], 1):\n",
- " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
- " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n",
- " print()\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Generate knowledge graph visualization\n",
- "visualizer.visualize(\n",
- " kg,\n",
- " output_path=\"drug_target_kg.html\",\n",
- " layout=\"spring\",\n",
- " node_size=20\n",
- ")\n",
- "\n",
- "print(\"Knowledge graph visualization saved to drug_target_kg.html\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display graph statistics\n",
- "print(f\"Graph contains {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Embedding Generation & Vector Store Population\n",
- "\n",
- "- Generate embeddings for drugs and proteins\n",
- "- Populate vector store for similarity search\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.context import AgentContext\n",
- "\n",
- "# Initialize GraphRAG context with vector store and knowledge graph\n",
- "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
- "\n",
- "# Example GraphRAG query: Find drugs and their targets\n",
- "query = \"What drugs target COX enzymes?\"\n",
- "print(f\"Query: {query}\\n\")\n",
- "\n",
- "# Retrieve using GraphRAG (hybrid vector + graph retrieval)\n",
- "results = context.retrieve(\n",
- " query,\n",
- " max_results=10,\n",
- " use_graph=True, # Enable graph traversal\n",
- " expand_graph=True, # Expand graph relationships\n",
- " include_entities=True, # Include related entities\n",
- " include_relationships=True # Include relationships\n",
- ")\n",
- "\n",
- "print(f\"GraphRAG retrieved {len(results)} results:\\n\")\n",
- "for i, result in enumerate(results[:5], 1):\n",
- " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
- " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n",
- " print()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Similarity Search & Interaction Prediction\n",
- "\n",
- "- Use vector similarity to find similar drugs\n",
- "- Predict drug-target interactions\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.embeddings import EmbeddingGenerator\n",
- "\n",
- "# Generate embeddings for drugs and proteins\n",
- "embedding_gen = EmbeddingGenerator(provider=\"sentence_transformers\", model=\"all-MiniLM-L6-v2\")\n",
- "\n",
- "# Create drug embeddings\n",
- "drug_texts = [f\"{d.get('text', '')} {d.get('description', '')}\" for d in drugs]\n",
- "drug_embeddings = embedding_gen.generate_embeddings(drug_texts)\n",
- "\n",
- "# Store in vector store\n",
- "drug_ids = vector_store.store_vectors(\n",
- " vectors=drug_embeddings,\n",
- " metadata=[{\"type\": \"drug\", \"name\": d.get(\"text\", \"\")} for d in drugs]\n",
- ")\n",
- "\n",
- "print(f\"Stored {len(drug_ids)} drug embeddings in vector store\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Retrieve using GraphRAG (hybrid vector + graph retrieval)\n",
- "results = context.retrieve(\n",
- " query,\n",
- " max_results=10,\n",
- " use_graph=True, # Enable graph traversal\n",
- " expand_graph=True, # Expand graph relationships\n",
- " include_entities=True, # Include related entities\n",
- " include_relationships=True # Include relationships\n",
- ")\n",
- "\n",
- "print(f\"GraphRAG retrieved {len(results)} results\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display GraphRAG results\n",
- "for i, result in enumerate(results[:5], 1):\n",
- " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
- " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
- " if result.get('related_entities'):\n",
- " print(f\" Related entities: {len(result['related_entities'])}\")\n",
- " print()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Knowledge Graph Visualization\n",
- "\n",
- "- Visualize drug-target knowledge graph\n",
- "- Display relationships between entities\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "# Initialize KG visualizer\n",
- "visualizer = KGVisualizer()\n",
- "print(\"KGVisualizer initialized\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Generate knowledge graph visualization\n",
- "visualizer.visualize(\n",
- " kg,\n",
- " output_path=\"drug_target_kg.html\",\n",
- " layout=\"spring\",\n",
- " node_size=20\n",
- ")\n",
- "\n",
- "print(\"Knowledge graph visualization saved to drug_target_kg.html\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Display graph statistics\n",
- "print(f\"Graph contains {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Example: Find drugs similar to Aspirin\n",
- "query_drug = \"Aspirin\"\n",
- "query_embedding = embedding_gen.generate_embeddings([query_drug])[0]\n",
- "\n",
- "# Search for similar drugs\n",
- "similar_drugs = vector_store.search_vectors(query_embedding, k=5)\n",
- "\n",
- "print(f\"Drugs similar to '{query_drug}':\")\n",
- "for i, result in enumerate(similar_drugs, 1):\n",
- " print(f\"{i}. {result['metadata'].get('name', 'Unknown')} (similarity: {result['score']:.3f})\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "# Get knowledge graph from result\n",
- "kg = result[\"knowledge_graph\"]\n",
- "\n",
- "# Visualize drug-target relationships\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(\n",
- " kg,\n",
- " output_path=\"drug_target_kg.html\",\n",
- " layout=\"spring\",\n",
- " node_size=20\n",
- ")\n",
- "\n",
- "print(\"Knowledge graph visualization saved to drug_target_kg.html\")\n",
- "print(f\"Graph contains {len(kg.get('entities', []))} entities and {len(kg.get('relationships', []))} relationships\")\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.9"
- }
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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 - Vector Similarity Search\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates a **complete drug discovery pipeline** using Semantica's modular architecture. We'll use individual modules directly to build a comprehensive system for drug-target interaction prediction using vector similarity search and knowledge graphs.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Modular Architecture**: Uses Semantica modules directly (`NERExtractor`, `GraphBuilder`, `EmbeddingGenerator`, `VectorStore`)\n",
+ "- **Multiple Data Sources**: Ingests from 15+ PubMed RSS feeds, preprint servers, and journal feeds\n",
+ "- **Vector Similarity Search**: Emphasizes embeddings and vector similarity for drug-target interaction prediction\n",
+ "- **Entity Extraction**: Extracts drug compounds, proteins, targets, enzymes, and receptors\n",
+ "- **Knowledge Graph**: Builds structured drug-target relationship graphs\n",
+ "- **GraphRAG**: Hybrid vector + graph retrieval for enhanced querying\n",
+ "\n",
+ "### What You'll Learn\n",
+ "\n",
+ "- How to use Semantica modules directly (avoiding the core orchestrator)\n",
+ "- How to ingest biomedical data from multiple sources\n",
+ "- How to extract entities using `NERExtractor`\n",
+ "- How to extract relationships using `RelationExtractor`\n",
+ "- How to generate embeddings with `EmbeddingGenerator`\n",
+ "- How to build knowledge graphs with `GraphBuilder`\n",
+ "- How to perform similarity search with `VectorStore`\n",
+ "- How to use GraphRAG with `AgentContext` for hybrid retrieval\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph LR\n",
+ " A[Data Ingestion] --> B[Text Processing]\n",
+ " B --> C[Entity Extraction]\n",
+ " C --> D[Relationship Extraction]\n",
+ " D --> E[Deduplication]\n",
+ " E --> F[Embedding Generation]\n",
+ " F --> G[Vector Store]\n",
+ " G --> H[Knowledge Graph]\n",
+ " H --> I[Similarity Search]\n",
+ " H --> J[GraphRAG Queries]\n",
+ " I --> K[Visualization]\n",
+ " J --> K\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "**PubMed RSS Feeds:**\n",
+ "- Drug Discovery, Drug Target Interaction, Pharmacokinetics, Pharmacodynamics\n",
+ "- Clinical Trials, Protein Targets, Drug Repurposing, Molecular Docking\n",
+ "- ADME, Drug Metabolism, Drug Safety, Precision Medicine\n",
+ "- Biomarkers, Drug Resistance, Combinatorial Therapy\n",
+ "\n",
+ "**Preprint Servers:**\n",
+ "- BioRxiv (Pharmacology & Toxicology, Drug Discovery)\n",
+ "- MedRxiv (Clinical Trials)\n",
+ "- ChemRxiv\n",
+ "\n",
+ "**Journal RSS Feeds:**\n",
+ "- Nature (Drug Discovery, Pharmacology)\n",
+ "- Science Translational Medicine\n",
+ "- Cell Chemical Biology\n",
+ "- Journal of Medicinal Chemistry\n",
+ "- Drug Discovery Today\n",
+ "- Trends in Pharmacological Sciences\n",
+ "\n",
+ "**Database Links (for reference):**\n",
+ "- [ChEMBL](https://www.ebi.ac.uk/chembl/) - Bioactive molecules\n",
+ "- [DrugBank](https://go.drugbank.com/) - Drug and drug target database\n",
+ "- [PubChem](https://pubchem.ncbi.nlm.nih.gov/) - Chemical compound database\n",
+ "- [UniProt](https://www.uniprot.org/) - Protein sequence database\n",
+ "- [ClinicalTrials.gov](https://clinicaltrials.gov/) - Clinical trial registry\n",
+ "- [FDA Drug Approvals](https://www.fda.gov/drugs/drug-approvals-and-databases) - FDA drug information\n",
+ "- [WHO Drug Information](https://www.who.int/medicines/publications/druginformation/en/) - WHO drug resources\n",
+ "\n",
+ "---\n"
+ ]
},
- "nbformat": 4,
- "nbformat_minor": 2
-}
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Installation\n",
+ "\n",
+ "Install Semantica and required dependencies:\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\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Configuration & Setup\n",
+ "\n",
+ "Set up environment variables and configuration constants.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"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\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "EMBEDDING_DIMENSION = 384\n",
+ "EMBEDDING_MODEL = \"all-MiniLM-L6-v2\"\n",
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Ingesting Biomedical Data from Multiple Sources\n",
+ "\n",
+ "Ingest data from comprehensive biomedical sources including PubMed RSS feeds, preprint servers, and journal feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "feed_sources = [\n",
+ " # PubMed RSS Feeds\n",
+ " (\"PubMed - Drug Discovery\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+discovery&limit=15&sort=pub_date&fc=article_type\"),\n",
+ " (\"PubMed - Drug Target Interaction\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+target+interaction&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Pharmacokinetics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=pharmacokinetics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Pharmacodynamics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=pharmacodynamics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Clinical Trial\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=clinical+trial&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Protein Target\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=protein+target&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Drug Repurposing\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+repurposing&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Molecular Docking\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=molecular+docking&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - ADME\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=ADME&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Drug Metabolism\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+metabolism&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Drug Safety\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+safety&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Precision Medicine\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=precision+medicine&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Biomarkers\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=biomarkers&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Drug Resistance\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+resistance&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Combinatorial Therapy\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=combinatorial+therapy&limit=15&sort=pub_date\"),\n",
+ " \n",
+ " # Preprint Servers\n",
+ " (\"BioRxiv - Pharmacology\", \"https://connect.biorxiv.org/biorxiv_xml.php?subject=pharmacology_and_toxicology\"),\n",
+ " (\"BioRxiv - Drug Discovery\", \"https://connect.biorxiv.org/biorxiv_xml.php?subject=drug_discovery\"),\n",
+ " (\"MedRxiv - Clinical Trials\", \"https://connect.medrxiv.org/medrxiv_xml.php?subject=clinical_trials\"),\n",
+ " (\"ChemRxiv\", \"https://chemrxiv.org/engage/chemrxiv/rss.xml\"),\n",
+ " \n",
+ " # Journal RSS Feeds\n",
+ " (\"Nature - Drug Discovery\", \"https://www.nature.com/subjects/drug-discovery.rss\"),\n",
+ " (\"Nature - Pharmacology\", \"https://www.nature.com/subjects/pharmacology.rss\"),\n",
+ " (\"Science Translational Medicine\", \"https://www.science.org/action/showFeed?type=etoc&feed=rss&jc=scitransmed\"),\n",
+ " (\"Cell Chemical Biology\", \"https://www.cell.com/chemical-biology.rss\"),\n",
+ " (\"Journal of Medicinal Chemistry\", \"https://pubs.acs.org/action/showFeed?type=etoc&feed=rss&jc=jmcmar\"),\n",
+ " (\"Drug Discovery Today\", \"https://www.sciencedirect.com/journal/drug-discovery-today.rss\"),\n",
+ " (\"Trends in Pharmacological Sciences\", \"https://www.cell.com/trends/pharmacological-sciences.rss\"),\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "all_documents = []\n",
+ "\n",
+ "for feed_name, feed_url in feed_sources:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
+ " \n",
+ " for item in feed_data.items:\n",
+ " if not item.content:\n",
+ " item.content = item.description or item.title or \"\"\n",
+ " if item.content:\n",
+ " if not hasattr(item, 'metadata'):\n",
+ " item.metadata = {}\n",
+ " item.metadata['source'] = feed_name\n",
+ " all_documents.append(item)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "if not all_documents:\n",
+ " sample_drug_data = \"\"\"\n",
+ " Aspirin (acetylsalicylic acid) is a medication used to reduce pain, fever, or inflammation. \n",
+ " It targets cyclooxygenase enzymes COX-1 and COX-2. Aspirin is commonly used for cardiovascular protection.\n",
+ " Ibuprofen is a nonsteroidal anti-inflammatory drug (NSAID) that targets COX-1 and COX-2 enzymes.\n",
+ " Metformin is an antidiabetic medication that targets AMP-activated protein kinase (AMPK).\n",
+ " Insulin targets the insulin receptor (INSR) to regulate glucose metabolism.\n",
+ " Warfarin is an anticoagulant that targets vitamin K epoxide reductase complex subunit 1 (VKORC1).\n",
+ " Atorvastatin is a statin medication that targets HMG-CoA reductase.\n",
+ " \"\"\"\n",
+ " \n",
+ " with open(\"data/sample_drugs.txt\", \"w\") as f:\n",
+ " f.write(sample_drug_data)\n",
+ " \n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/sample_drugs.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Documents\n",
+ "\n",
+ "Clean and normalize text, then split into chunks using entity-aware chunking to preserve drug/protein entity boundaries.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " ner_method=\"spacy\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"Drug\", \"Protein\", \"Target\", \"Compound\", \"Enzyme\", \"Receptor\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "drugs = [e for e in all_entities if e.label in [\"Drug\", \"Compound\"] or \"drug\" in e.label.lower()]\n",
+ "proteins = [e for e in all_entities if e.label in [\"Protein\", \"Target\", \"Enzyme\", \"Receptor\"] or \"protein\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(drugs)} drugs and {len(proteins)} proteins\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Drug-Target Relationships\n",
+ "\n",
+ "Extract relationships between drugs and proteins to understand drug-target interactions.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"targets\", \"inhibits\", \"activates\", \"binds_to\", \"interacts_with\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate Entities\n",
+ "\n",
+ "Detect and merge duplicate entities to ensure data quality and consistency.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
+ "\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generating Vector Embeddings\n",
+ "\n",
+ "Generate embeddings for drugs and proteins to enable similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.embeddings import EmbeddingGenerator\n",
+ "from semantica.vector_store import VectorStore\n",
+ "\n",
+ "embedding_gen = EmbeddingGenerator(\n",
+ " provider=\"sentence_transformers\",\n",
+ " model=EMBEDDING_MODEL\n",
+ ")\n",
+ "\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=EMBEDDING_DIMENSION)\n",
+ "\n",
+ "drug_texts = [f\"{d.text} {getattr(d, 'description', '')}\" for d in drugs]\n",
+ "drug_embeddings = embedding_gen.generate_embeddings(drug_texts)\n",
+ "\n",
+ "protein_texts = [f\"{p.text} {getattr(p, 'description', '')}\" for p in proteins]\n",
+ "protein_embeddings = embedding_gen.generate_embeddings(protein_texts)\n",
+ "\n",
+ "print(f\"Generated {len(drug_embeddings)} drug embeddings and {len(protein_embeddings)} protein embeddings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Populating Vector Database\n",
+ "\n",
+ "Store drug and protein embeddings in the vector database with metadata for efficient similarity search.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "drug_ids = vector_store.store_vectors(\n",
+ " vectors=drug_embeddings,\n",
+ " metadata=[{\"type\": \"drug\", \"name\": d.text, \"label\": d.label} for d in drugs]\n",
+ ")\n",
+ "\n",
+ "protein_ids = vector_store.store_vectors(\n",
+ " vectors=protein_embeddings,\n",
+ " metadata=[{\"type\": \"protein\", \"name\": p.text, \"label\": p.label} for p in proteins]\n",
+ ")\n",
+ "\n",
+ "print(f\"Stored {len(drug_ids)} drug vectors and {len(protein_ids)} protein vectors\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building Drug-Target Knowledge Graph\n",
+ "\n",
+ "Construct a knowledge graph from extracted entities and relationships to enable graph-based reasoning.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\"\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
+ "\n",
+ "kg = graph_builder.build(kg_sources)\n",
+ "\n",
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Finding Similar Drugs via Vector Search\n",
+ "\n",
+ "Use vector similarity search to find drugs similar to a query drug based on their embeddings.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "query_drug = \"Aspirin\"\n",
+ "query_embedding = embedding_gen.generate_embeddings([query_drug])[0]\n",
+ "similar_drugs = vector_store.search_vectors(query_embedding, k=5)\n",
+ "\n",
+ "print(f\"Drugs similar to '{query_drug}':\")\n",
+ "for i, result in enumerate(similar_drugs, 1):\n",
+ " print(f\"{i}. {result['metadata'].get('name', 'Unknown')} (similarity: {result['score']:.3f})\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## GraphRAG: Hybrid Vector + Graph Retrieval\n",
+ "\n",
+ "Use GraphRAG to combine vector similarity search with knowledge graph traversal for enhanced retrieval and reasoning.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.context import AgentContext\n",
+ "\n",
+ "context = AgentContext(vector_store=vector_store, knowledge_graph=kg)\n",
+ "\n",
+ "query = \"What drugs target COX enzymes?\"\n",
+ "results = context.retrieve(\n",
+ " query,\n",
+ " max_results=10,\n",
+ " use_graph=True,\n",
+ " expand_graph=True,\n",
+ " include_entities=True,\n",
+ " include_relationships=True\n",
+ ")\n",
+ "\n",
+ "print(f\"GraphRAG query: '{query}'\")\n",
+ "print(f\"\\nRetrieved {len(results)} results:\\n\")\n",
+ "for i, result in enumerate(results[:5], 1):\n",
+ " print(f\"{i}. Score: {result.get('score', 0):.3f}\")\n",
+ " print(f\" Content: {result.get('content', '')[:200]}...\")\n",
+ " if result.get('related_entities'):\n",
+ " print(f\" Related entities: {len(result['related_entities'])}\")\n",
+ " print()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Knowledge Graph\n",
+ "\n",
+ "Generate an interactive visualization of the drug-target knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"drug_target_kg.html\",\n",
+ " layout=\"spring\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to drug_target_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n",
+ "\n",
+ "Export the knowledge graph to various formats for further analysis or integration with other tools.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"drug_target_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"drug_target_kg.graphml\", format=\"graphml\")\n",
+ "\n",
+ "print(\"Exported knowledge graph to JSON and GraphML formats\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
\ No newline at end of file
diff --git a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
index 86fded2e..07fa3cf1 100644
--- a/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
+++ b/cookbook/use_cases/biomedical/02_Genomic_Variant_Analysis.ipynb
@@ -1,311 +1,609 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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 - Graph Analytics & Pathway Analysis\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates **genomic variant analysis** using Semantica with focus on **graph analytics**, **pathway analysis**, and **temporal knowledge graphs**. The pipeline analyzes genomic data to extract variant entities, build temporal genomic knowledge graphs, and analyze disease associations through reasoning.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **Graph Analytics Focus**: Emphasizes graph reasoning, centrality measures, and pathway analysis\n",
- "- **Temporal Analysis**: Builds temporal genomic knowledge graphs to track variant evolution\n",
- "- **Disease Association**: Analyzes relationships between variants, genes, and diseases\n",
- "- **Pathway Analysis**: Uses graph traversal to identify biological pathways\n",
- "- **Impact Prediction**: Predicts variant impact using graph-based reasoning\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: Genomic Data Ingestion\n",
- "3. **Phase 2**: Variant Entity Extraction\n",
- "4. **Phase 3**: Temporal Knowledge Graph Construction\n",
- "5. **Phase 4**: Graph Analytics (Centrality, Communities)\n",
- "6. **Phase 5**: Pathway Analysis & Reasoning\n",
- "7. **Phase 6**: Disease Association Analysis\n",
- "8. **Phase 7**: Visualization & Export\n",
- "\n",
- "---\n",
- "\n",
- "## Installation\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "%pip install -qU semantica networkx matplotlib plotly pandas groq\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 0: Setup & Configuration\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "from semantica.core import Semantica, ConfigManager\n",
- "from semantica.kg import KnowledgeGraphBuilder\n",
- "from semantica.reasoning import GraphReasoner\n",
- "\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Genomic_Variant_Analysis\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\", \"temporal\": True}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "print(\"Configured for genomic variant analysis with graph analytics focus\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (bioRxiv RSS Feed)\n",
- "\n",
- "Ingest genomic variant data from bioRxiv RSS feeds using FeedIngestor.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import FeedIngestor, FileIngestor\n",
- "import os\n",
- "\n",
- "# Create data directory if it doesn't exist\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "# Option 1: Ingest from bioRxiv RSS feed (real data source)\n",
- "# bioRxiv RSS feed for genomic variant research\n",
- "biorxiv_rss_url = \"https://connect.biorxiv.org/biorxiv_xml.php?subject=genetics\"\n",
- "\n",
- "try:\n",
- " feed_ingestor = FeedIngestor()\n",
- " # Ingest from bioRxiv RSS feed\n",
- " feed_documents = feed_ingestor.ingest(biorxiv_rss_url, method=\"rss\")\n",
- " print(f\"Ingested {len(feed_documents)} documents from bioRxiv RSS feed\")\n",
- " documents = feed_documents\n",
- "except Exception as e:\n",
- " print(f\"RSS feed ingestion failed (using sample data): {e}\")\n",
- " # Fallback: Sample genomic variant data\n",
- " variant_data = \"\"\"\n",
- " Variant rs699 is located in the AGT gene and associated with hypertension.\n",
- " Variant rs7412 in APOE gene is linked to Alzheimer's disease risk.\n",
- " BRCA1 variant c.5266dupC increases breast cancer susceptibility.\n",
- " CFTR variant F508del causes cystic fibrosis.\n",
- " Variant rs1800566 in NAT2 gene affects drug metabolism.\n",
- " \"\"\"\n",
- " \n",
- " with open(\"data/variants.txt\", \"w\") as f:\n",
- " f.write(variant_data)\n",
- " \n",
- " documents = FileIngestor().ingest(\"data/variants.txt\")\n",
- " print(f\"Ingested {len(documents)} documents from sample data\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 2: Text Normalization & Deduplication\n",
- "\n",
- "Normalize genomic data and detect duplicate variants.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "from semantica.deduplication import DuplicateDetector\n",
- "\n",
- "# Normalize genomic data\n",
- "normalizer = TextNormalizer()\n",
- "normalized_documents = []\n",
- "for doc in documents:\n",
- " normalized_text = normalizer.normalize(\n",
- " doc.content if hasattr(doc, 'content') else str(doc),\n",
- " clean_html=True,\n",
- " normalize_entities=True,\n",
- " remove_extra_whitespace=True\n",
- " )\n",
- " normalized_documents.append(normalized_text)\n",
- "\n",
- "print(f\"Normalized {len(normalized_documents)} documents\")\n",
- "\n",
- "# Build knowledge base first to get entities for deduplication\n",
- "result = core.build_knowledge_base(\n",
- " sources=normalized_documents,\n",
- " custom_entity_types=[\"Variant\", \"Gene\", \"Disease\", \"Pathway\"],\n",
- " graph=True,\n",
- " temporal=True\n",
- ")\n",
- "\n",
- "# Detect duplicate variants\n",
- "entities = result[\"entities\"]\n",
- "variants = [e for e in entities if e.get(\"type\") == \"Variant\" or \"variant\" in e.get(\"type\", \"\").lower()]\n",
- "\n",
- "detector = DuplicateDetector()\n",
- "duplicates = detector.detect_duplicates(variants, threshold=0.9)\n",
- "deduplicated_variants = detector.resolve_duplicates(variants, duplicates)\n",
- "\n",
- "print(f\"Detected {len(duplicates)} duplicate variant groups\")\n",
- "print(f\"Deduplicated: {len(variants)} -> {len(deduplicated_variants)} unique variants\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 3: Temporal Knowledge Graph Construction\n",
- "\n",
- "Build temporal knowledge graph with temporal query capabilities.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.kg import GraphBuilder, TemporalGraphQuery\n",
- "\n",
- "# Get knowledge graph from result\n",
- "kg = result[\"knowledge_graph\"]\n",
- "\n",
- "# Initialize temporal graph query engine\n",
- "temporal_query = TemporalGraphQuery(\n",
- " enable_temporal_reasoning=True,\n",
- " temporal_granularity=\"day\"\n",
- ")\n",
- "\n",
- "# Query graph at specific time point\n",
- "# Example: Query variants active on a specific date\n",
- "query_results = temporal_query.query_at_time(\n",
- " kg,\n",
- " query={\"type\": \"Variant\"},\n",
- " at_time=\"2024-01-01\"\n",
- ")\n",
- "\n",
- "# Analyze temporal evolution\n",
- "evolution = temporal_query.analyze_evolution(kg)\n",
- "\n",
- "print(f\"Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"Temporal queries: {len(query_results)} variants at query time\")\n",
- "print(f\"Graph emphasizes: graph analytics, pathway analysis, temporal reasoning\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.kg import GraphAnalytics\n",
- "\n",
- "# Perform graph analytics (centrality, communities)\n",
- "analytics = GraphAnalytics(kg)\n",
- "centrality = analytics.calculate_centrality(method=\"betweenness\")\n",
- "communities = analytics.detect_communities()\n",
- "\n",
- "# Use reasoning for pathway analysis\n",
- "reasoner = GraphReasoner(kg)\n",
- "pathways = reasoner.find_paths(\n",
- " source_type=\"Variant\",\n",
- " target_type=\"Disease\",\n",
- " max_hops=3\n",
- ")\n",
- "\n",
- "# Temporal pattern detection\n",
- "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
- "\n",
- "print(f\"Graph analytics: {len(communities)} communities detected\")\n",
- "print(f\"Pathway analysis: {len(pathways)} variant-disease pathways found\")\n",
- "print(f\"Temporal patterns: {len(temporal_patterns)} temporal patterns detected\")\n",
- "print(\"This cookbook emphasizes graph analytics, temporal reasoning, and pathway analysis\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 6-7: Visualization & Export\n",
- "\n",
- "Visualize temporal knowledge graph and export results.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "from semantica.export import GraphExporter\n",
- "\n",
- "# Visualize temporal knowledge graph\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"genomic_variant_kg.html\", layout=\"hierarchical\")\n",
- "\n",
- "# Export graph\n",
- "exporter = GraphExporter()\n",
- "exporter.export(kg, format=\"graphml\", output_path=\"genomic_variant_kg.graphml\")\n",
- "\n",
- "print(\"Visualization and export complete\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"βœ“ Ingested {len(documents)} documents from bioRxiv RSS feed\")\n",
- "print(f\"βœ“ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"βœ“ Deduplicated {len(variants)} variants to {len(deduplicated_variants)} unique variants\")\n",
- "print(f\"βœ“ Built temporal KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"βœ“ Detected {len(communities)} communities and {len(pathways)} pathways\")\n",
- "print(f\"βœ“ This cookbook demonstrates graph analytics, temporal reasoning, and pathway analysis\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](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 - Graph Analytics & Pathway Analysis\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **genomic variant analysis** using Semantica's modular architecture with focus on **graph analytics**, **pathway analysis**, and **temporal knowledge graphs**. The pipeline analyzes genomic data to extract variant entities, build temporal genomic knowledge graphs, and analyze disease associations through reasoning.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **Graph Analytics Focus**: Emphasizes graph reasoning, centrality measures, and pathway analysis\n",
+ "- **Temporal Analysis**: Builds temporal genomic knowledge graphs to track variant evolution\n",
+ "- **Disease Association**: Analyzes relationships between variants, genes, and diseases\n",
+ "- **Pathway Analysis**: Uses graph traversal to identify biological pathways\n",
+ "- **Impact Prediction**: Predicts variant impact using graph-based reasoning\n",
+ "\n",
+ "### What You'll Learn\n",
+ "\n",
+ "- How to use Semantica modules directly for genomic analysis\n",
+ "- How to ingest genomic data from multiple sources\n",
+ "- How to extract variant, gene, and disease entities\n",
+ "- How to build temporal knowledge graphs\n",
+ "- How to perform graph analytics (centrality, communities)\n",
+ "- How to use temporal queries for variant evolution\n",
+ "- How to analyze pathways using reasoning\n",
+ "- How to visualize and export genomic knowledge graphs\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph LR\n",
+ " A[Data Ingestion] --> B[Text Processing]\n",
+ " B --> C[Entity Extraction]\n",
+ " C --> D[Relationship Extraction]\n",
+ " D --> E[Deduplication]\n",
+ " E --> F[Temporal KG]\n",
+ " F --> G[Graph Analytics]\n",
+ " F --> H[Temporal Queries]\n",
+ " G --> I[Pathway Analysis]\n",
+ " H --> I\n",
+ " I --> J[Disease Associations]\n",
+ " J --> K[Visualization]\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "**PubMed RSS Feeds:**\n",
+ "- Genetics, Genomics, Variant Analysis, GWAS\n",
+ "- Genomic Medicine, Precision Medicine, Pharmacogenomics\n",
+ "- Population Genetics, Evolutionary Genomics\n",
+ "\n",
+ "**Preprint Servers:**\n",
+ "- BioRxiv (Genetics, Genomics)\n",
+ "- MedRxiv (Genomics, Clinical Genomics)\n",
+ "\n",
+ "**Journal RSS Feeds:**\n",
+ "- Nature Genetics, Genome Research\n",
+ "- American Journal of Human Genetics\n",
+ "- Human Molecular Genetics\n",
+ "\n",
+ "**Database Links (for reference):**\n",
+ "- [dbSNP](https://www.ncbi.nlm.nih.gov/snp/) - Single Nucleotide Polymorphism database\n",
+ "- [ClinVar](https://www.ncbi.nlm.nih.gov/clinvar/) - Clinical significance of variants\n",
+ "- [gnomAD](https://gnomad.broadinstitute.org/) - Genome Aggregation Database\n",
+ "- [1000 Genomes](https://www.internationalgenome.org/) - Human genetic variation\n",
+ "- [Ensembl](https://www.ensembl.org/) - Genome browser and annotation\n",
+ "- [UCSC Genome Browser](https://genome.ucsc.edu/) - Genome visualization\n",
+ "- [OMIM](https://www.omim.org/) - Online Mendelian Inheritance in Man\n",
+ "\n",
+ "---\n"
+ ]
},
- "nbformat": 4,
- "nbformat_minor": 2
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Installation\n",
+ "\n",
+ "Install Semantica and required dependencies:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%pip install -qU semantica networkx matplotlib plotly pandas groq sentence-transformers\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Configuration & Setup\n",
+ "\n",
+ "Set up environment variables and configuration constants.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"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\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "CHUNK_SIZE = 1000\n",
+ "CHUNK_OVERLAP = 200\n",
+ "TEMPORAL_GRANULARITY = \"day\"\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Ingesting Genomic Data from Multiple Sources\n",
+ "\n",
+ "Ingest data from comprehensive genomic sources including PubMed RSS feeds, preprint servers, and journal feeds.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.ingest import FeedIngestor, FileIngestor\n",
+ "import os\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "os.makedirs(\"data\", exist_ok=True)\n",
+ "\n",
+ "feed_sources = [\n",
+ " # PubMed RSS Feeds\n",
+ " (\"PubMed - Genetics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=genetics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Genomics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=genomics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Variant Analysis\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=variant+analysis&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - GWAS\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=GWAS&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Genomic Medicine\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=genomic+medicine&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Precision Medicine\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=precision+medicine&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Pharmacogenomics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=pharmacogenomics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Population Genetics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=population+genetics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Evolutionary Genomics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=evolutionary+genomics&limit=15&sort=pub_date\"),\n",
+ " (\"PubMed - Clinical Genomics\", \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=clinical+genomics&limit=15&sort=pub_date\"),\n",
+ " \n",
+ " # Preprint Servers\n",
+ " (\"BioRxiv - Genetics\", \"https://connect.biorxiv.org/biorxiv_xml.php?subject=genetics\"),\n",
+ " (\"BioRxiv - Genomics\", \"https://connect.biorxiv.org/biorxiv_xml.php?subject=genomics\"),\n",
+ " (\"MedRxiv - Genomics\", \"https://connect.medrxiv.org/medrxiv_xml.php?subject=genomics\"),\n",
+ " (\"MedRxiv - Clinical Genomics\", \"https://connect.medrxiv.org/medrxiv_xml.php?subject=clinical_genomics\"),\n",
+ " \n",
+ " # Journal RSS Feeds\n",
+ " (\"Nature Genetics\", \"https://www.nature.com/ng.rss\"),\n",
+ " (\"Genome Research\", \"https://genome.cshlp.org/rss/current.xml\"),\n",
+ " (\"American Journal of Human Genetics\", \"https://www.cell.com/ajhg.rss\"),\n",
+ " (\"Human Molecular Genetics\", \"https://academic.oup.com/hmg/rss/current\"),\n",
+ "]\n",
+ "\n",
+ "feed_ingestor = FeedIngestor()\n",
+ "all_documents = []\n",
+ "\n",
+ "for feed_name, feed_url in feed_sources:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " feed_data = feed_ingestor.ingest_feed(feed_url, validate=False)\n",
+ " \n",
+ " for item in feed_data.items:\n",
+ " if not item.content:\n",
+ " item.content = item.description or item.title or \"\"\n",
+ " if item.content:\n",
+ " if not hasattr(item, 'metadata'):\n",
+ " item.metadata = {}\n",
+ " item.metadata['source'] = feed_name\n",
+ " all_documents.append(item)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "if not all_documents:\n",
+ " variant_data = \"\"\"\n",
+ " Variant rs699 is located in the AGT gene and associated with hypertension.\n",
+ " Variant rs7412 in APOE gene is linked to Alzheimer's disease risk.\n",
+ " BRCA1 variant c.5266dupC increases breast cancer susceptibility.\n",
+ " CFTR variant F508del causes cystic fibrosis.\n",
+ " Variant rs1800566 in NAT2 gene affects drug metabolism.\n",
+ " Variant rs1042713 in ADRB2 gene is associated with asthma response.\n",
+ " TP53 variant R273H is linked to multiple cancer types.\n",
+ " Variant rs1799853 in CYP2C9 gene affects warfarin metabolism.\n",
+ " \"\"\"\n",
+ " \n",
+ " with open(\"data/variants.txt\", \"w\") as f:\n",
+ " f.write(variant_data)\n",
+ " \n",
+ " file_ingestor = FileIngestor()\n",
+ " all_documents = file_ingestor.ingest(\"data/variants.txt\")\n",
+ "\n",
+ "documents = all_documents\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Normalizing and Chunking Genomic Documents\n",
+ "\n",
+ "Clean and normalize text, then split into chunks using entity-aware chunking to preserve variant/gene entity boundaries.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.split import TextSplitter\n",
+ "\n",
+ "normalizer = TextNormalizer()\n",
+ "splitter = TextSplitter(\n",
+ " method=\"entity_aware\",\n",
+ " ner_method=\"spacy\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "normalized_documents = []\n",
+ "for doc in documents:\n",
+ " normalized_text = normalizer.normalize(\n",
+ " doc.content if hasattr(doc, 'content') else str(doc),\n",
+ " clean_html=True,\n",
+ " normalize_entities=True,\n",
+ " remove_extra_whitespace=True,\n",
+ " lowercase=False\n",
+ " )\n",
+ " normalized_documents.append(normalized_text)\n",
+ "\n",
+ "chunked_documents = []\n",
+ "for doc_text in normalized_documents:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n",
+ " except Exception:\n",
+ " simple_splitter = TextSplitter(method=\"recursive\", chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)\n",
+ " chunks = simple_splitter.split(doc_text)\n",
+ " chunked_documents.extend(chunks)\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import NERExtractor\n",
+ "\n",
+ "entity_extractor = NERExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " entities = entity_extractor.extract_entities(\n",
+ " chunk_text,\n",
+ " entity_types=[\"Variant\", \"Gene\", \"Disease\", \"Pathway\", \"Protein\"]\n",
+ " )\n",
+ " all_entities.extend(entities)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "variants = [e for e in all_entities if e.label == \"Variant\" or \"variant\" in e.label.lower()]\n",
+ "genes = [e for e in all_entities if e.label == \"Gene\" or \"gene\" in e.label.lower()]\n",
+ "diseases = [e for e in all_entities if e.label == \"Disease\" or \"disease\" in e.label.lower()]\n",
+ "\n",
+ "print(f\"Extracted {len(variants)} variants, {len(genes)} genes, {len(diseases)} diseases\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extracting Genomic Relationships\n",
+ "\n",
+ "Extract relationships between variants, genes, and diseases to understand genomic associations.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.semantic_extract import RelationExtractor\n",
+ "\n",
+ "relation_extractor = RelationExtractor(\n",
+ " method=\"llm\",\n",
+ " provider=\"groq\",\n",
+ " llm_model=\"llama-3.1-8b-instant\",\n",
+ " temperature=0.0\n",
+ ")\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_documents:\n",
+ " chunk_text = chunk.text if hasattr(chunk, 'text') else str(chunk)\n",
+ " try:\n",
+ " relationships = relation_extractor.extract_relations(\n",
+ " chunk_text,\n",
+ " entities=all_entities,\n",
+ " relation_types=[\"associated_with\", \"located_in\", \"causes\", \"increases_risk\", \"affects\", \"linked_to\"]\n",
+ " )\n",
+ " all_relationships.extend(relationships)\n",
+ " except Exception:\n",
+ " continue\n",
+ "\n",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Resolving Duplicate Variants\n",
+ "\n",
+ "Detect and merge duplicate variants to ensure data quality and consistency.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "duplicate_detector = DuplicateDetector(\n",
+ " similarity_threshold=0.85,\n",
+ " method=\"semantic\"\n",
+ ")\n",
+ "\n",
+ "deduplicated_entities = duplicate_detector.detect_duplicates(all_entities)\n",
+ "merged_entities = duplicate_detector.merge_duplicates(deduplicated_entities)\n",
+ "\n",
+ "print(f\"Deduplicated {len(all_entities)} entities to {len(merged_entities)} unique entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Building Temporal Genomic Knowledge Graph\n",
+ "\n",
+ "Construct a temporal knowledge graph from extracted entities and relationships to enable time-aware analysis and variant evolution tracking.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "\n",
+ "graph_builder = GraphBuilder(\n",
+ " merge_entities=True,\n",
+ " resolve_conflicts=True,\n",
+ " entity_resolution_strategy=\"fuzzy\",\n",
+ " enable_temporal=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "kg_sources = [{\n",
+ " \"entities\": [{\"text\": e.text, \"type\": e.label, \"confidence\": e.confidence} for e in merged_entities],\n",
+ " \"relationships\": [{\"source\": r.source, \"target\": r.target, \"type\": r.label, \"confidence\": r.confidence} for r in all_relationships]\n",
+ "}]\n",
+ "\n",
+ "kg = graph_builder.build(kg_sources)\n",
+ "\n",
+ "entities_count = len(kg.get('entities', []))\n",
+ "relationships_count = len(kg.get('relationships', []))\n",
+ "print(f\"Graph: {entities_count} entities, {relationships_count} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Analyzing Graph Structure\n",
+ "\n",
+ "Perform comprehensive graph analytics including centrality measures, community detection, and connectivity analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer()\n",
+ "centrality_calc = CentralityCalculator()\n",
+ "community_detector = CommunityDetector()\n",
+ "\n",
+ "analysis = graph_analyzer.analyze_graph(kg)\n",
+ "\n",
+ "degree_centrality = centrality_calc.calculate_degree_centrality(kg)\n",
+ "betweenness_centrality = centrality_calc.calculate_betweenness_centrality(kg)\n",
+ "closeness_centrality = centrality_calc.calculate_closeness_centrality(kg)\n",
+ "\n",
+ "communities = community_detector.detect_communities(kg, method=\"louvain\")\n",
+ "connectivity = graph_analyzer.analyze_connectivity(kg)\n",
+ "\n",
+ "print(f\"Graph analytics:\")\n",
+ "print(f\" - Communities: {len(communities)}\")\n",
+ "print(f\" - Connected components: {len(connectivity.get('components', []))}\")\n",
+ "print(f\" - Graph density: {analysis.get('density', 0):.3f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Temporal Graph Queries\n",
+ "\n",
+ "Query the temporal knowledge graph at specific time points, analyze temporal evolution, and detect temporal patterns.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(\n",
+ " enable_temporal_reasoning=True,\n",
+ " temporal_granularity=TEMPORAL_GRANULARITY\n",
+ ")\n",
+ "\n",
+ "query_results = temporal_query.query_at_time(\n",
+ " kg,\n",
+ " query={\"type\": \"Variant\"},\n",
+ " at_time=\"2024-01-01\"\n",
+ ")\n",
+ "\n",
+ "evolution = temporal_query.analyze_evolution(kg)\n",
+ "temporal_patterns = temporal_query.detect_temporal_patterns(kg, pattern_type=\"sequence\")\n",
+ "\n",
+ "print(f\"Temporal queries: {len(query_results)} variants at query time\")\n",
+ "print(f\"Temporal patterns detected: {len(temporal_patterns)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Pathway Analysis & Reasoning\n",
+ "\n",
+ "Use graph reasoning to find pathways between variants and diseases, and infer biological pathways through logical reasoning.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.reasoning import Reasoner\n",
+ "\n",
+ "reasoner = Reasoner()\n",
+ "\n",
+ "pathways = reasoner.find_paths(\n",
+ " kg,\n",
+ " source_type=\"Variant\",\n",
+ " target_type=\"Disease\",\n",
+ " max_hops=3\n",
+ ")\n",
+ "\n",
+ "reasoner.add_rule(\"IF Variant associated_with Gene AND Gene causes Disease THEN Variant increases_risk Disease\")\n",
+ "inferred_facts = reasoner.infer_facts(kg)\n",
+ "\n",
+ "print(f\"Pathway analysis: {len(pathways)} variant-disease pathways found\")\n",
+ "print(f\"Inferred facts: {len(inferred_facts)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Analyzing Disease Associations\n",
+ "\n",
+ "Use graph traversal to find variant-disease associations and calculate association scores.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "disease_associations = []\n",
+ "for variant in variants[:10]:\n",
+ " variant_name = variant.text\n",
+ " paths = graph_analyzer.find_paths(\n",
+ " kg,\n",
+ " source=variant_name,\n",
+ " target_type=\"Disease\",\n",
+ " max_hops=2\n",
+ " )\n",
+ " for path in paths:\n",
+ " if path.get('target_type') == 'Disease':\n",
+ " disease_associations.append({\n",
+ " 'variant': variant_name,\n",
+ " 'disease': path.get('target'),\n",
+ " 'path_length': len(path.get('path', [])),\n",
+ " 'confidence': variant.confidence\n",
+ " })\n",
+ "\n",
+ "disease_associations.sort(key=lambda x: x['confidence'], reverse=True)\n",
+ "\n",
+ "print(f\"Top disease associations:\")\n",
+ "for i, assoc in enumerate(disease_associations[:5], 1):\n",
+ " print(f\"{i}. {assoc['variant']} -> {assoc['disease']} (confidence: {assoc['confidence']:.3f})\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Visualizing the Temporal Knowledge Graph\n",
+ "\n",
+ "Generate an interactive visualization of the temporal genomic knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.visualization import KGVisualizer\n",
+ "\n",
+ "visualizer = KGVisualizer()\n",
+ "visualizer.visualize(\n",
+ " kg,\n",
+ " output_path=\"genomic_variant_kg.html\",\n",
+ " layout=\"hierarchical\",\n",
+ " node_size=20\n",
+ ")\n",
+ "\n",
+ "print(\"Visualization saved to genomic_variant_kg.html\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Exporting Results\n",
+ "\n",
+ "Export the temporal knowledge graph to various formats for further analysis or integration with other tools.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.export import GraphExporter\n",
+ "\n",
+ "exporter = GraphExporter()\n",
+ "exporter.export(kg, output_path=\"genomic_variant_kg.json\", format=\"json\")\n",
+ "exporter.export(kg, output_path=\"genomic_variant_kg.graphml\", format=\"graphml\")\n",
+ "\n",
+ "print(\"Exported knowledge graph to JSON and GraphML formats\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
}