Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor healthcare notebooks: Use modular architecture with unique approaches per use case

KaifAhmad1b5f895e28960
diff --git a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
index 068076c3..97198a6d 100644
--- a/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
+++ b/cookbook/use_cases/healthcare/01_Clinical_Reports_Processing.ipynb
@@ -1,255 +1,824 @@
{
- "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/healthcare/01_Clinical_Reports_Processing.ipynb)\n",
- "\n",
- "# Clinical Reports Processing - EHR Integration & Triplet Stores\n",
- "\n",
- "## Overview\n",
- "\n",
- "This notebook demonstrates **clinical reports processing** using Semantica with focus on **EHR integration**, **triplet stores**, and **patient knowledge graphs**. The pipeline processes EHR systems and HL7/FHIR APIs to build patient knowledge graphs and store them in triplet stores.\n",
- "\n",
- "### Key Features\n",
- "\n",
- "- **EHR Integration**: Processes EHR systems and HL7/FHIR APIs\n",
- "- **Triplet Store Storage**: Stores patient data in RDF triplet stores\n",
- "- **Patient Knowledge Graphs**: Builds comprehensive patient KGs\n",
- "- **Medical Entity Extraction**: Extracts medical entities from clinical reports\n",
- "- **Structured Data Storage**: Emphasizes storage and structured data management\n",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: EHR/HL7/FHIR Data Ingestion\n",
- "3. **Phase 2**: Clinical Report Parsing\n",
- "4. **Phase 3**: Medical Entity Extraction\n",
- "5. **Phase 4**: Patient Knowledge Graph Construction\n",
- "6. **Phase 5**: Triplet Store Population\n",
- "7. **Phase 6**: 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 rdflib\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.triplet_store import TripletStore\n",
- "\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-key\")\n",
- "\n",
- "config_dict = {\n",
- " \"project_name\": \"Clinical_Reports_Processing\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\"}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "triplet_store = TripletStore(backend=\"jena\") # or \"blazegraph\"\n",
- "print(\"Configured for clinical reports processing with triplet store focus\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (FDA RSS Feed & HL7/FHIR Structure)\n",
- "\n",
- "Ingest clinical data from FDA RSS feeds and simulated HL7/FHIR databases.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import FeedIngestor, DBIngestor, FileIngestor\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "documents = []\n",
- "\n",
- "# Option 1: Ingest from FDA RSS feed (real data source)\n",
- "fda_rss_url = \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\"\n",
- "\n",
- "try:\n",
- " feed_ingestor = FeedIngestor()\n",
- " feed_documents = feed_ingestor.ingest(fda_rss_url, method=\"rss\")\n",
- " print(f\"Ingested {len(feed_documents)} documents from FDA RSS feed\")\n",
- " documents.extend(feed_documents)\n",
- "except Exception as e:\n",
- " print(f\"FDA RSS feed ingestion failed: {e}\")\n",
- "\n",
- "# Option 2: Simulate HL7/FHIR database ingestion\n",
- "# In production: db_ingestor = DBIngestor()\n",
- "# db_ingestor.connect(\"postgresql://user:pass@localhost/emr_db\")\n",
- "# fhir_documents = db_ingestor.ingest(\"SELECT * FROM patient_records\", method=\"postgresql\")\n",
- "\n",
- "# Fallback: Sample clinical report data\n",
- "if not documents:\n",
- " clinical_data = \"\"\"\n",
- " Patient ID: P001, Name: John Doe, DOB: 1980-01-15\n",
- " Diagnosis: Type 2 Diabetes, Date: 2024-01-10\n",
- " Treatment: Metformin 500mg twice daily, Started: 2024-01-10\n",
- " Procedure: Blood glucose test, Date: 2024-01-15, Result: 180 mg/dL\n",
- " Patient ID: P002, Name: Jane Smith, DOB: 1975-05-20\n",
- " Diagnosis: Hypertension, Date: 2024-01-12\n",
- " \"\"\"\n",
- " with open(\"data/clinical_report.txt\", \"w\") as f:\n",
- " f.write(clinical_data)\n",
- " documents = FileIngestor().ingest(\"data/clinical_report.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 medical terms and deduplicate patient records.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "from semantica.deduplication import DuplicateDetector\n",
- "\n",
- "# Normalize medical terms\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 patient knowledge graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=normalized_documents,\n",
- " custom_entity_types=[\"Patient\", \"Diagnosis\", \"Treatment\", \"Procedure\", \"EHR\"],\n",
- " graph=True\n",
- ")\n",
- "\n",
- "kg = result[\"knowledge_graph\"]\n",
- "entities = result[\"entities\"]\n",
- "\n",
- "# Deduplicate patient records\n",
- "patients = [e for e in entities if e.get(\"type\") == \"Patient\" or \"patient\" in e.get(\"type\", \"\").lower()]\n",
- "\n",
- "detector = DuplicateDetector()\n",
- "duplicates = detector.detect_duplicates(patients, threshold=0.9)\n",
- "deduplicated_patients = detector.resolve_duplicates(patients, duplicates)\n",
- "\n",
- "print(f\"Built patient KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"Deduplicated: {len(patients)} -> {len(deduplicated_patients)} unique patients\")\n",
- "print(\"Focus: EHR integration, triplet stores, patient KGs, structured data storage\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Store patient data in triplet store\n",
- "triplets = []\n",
- "for rel in kg.get(\"relationships\", []):\n",
- " triplets.append({\n",
- " \"subject\": rel.get(\"source\"),\n",
- " \"predicate\": rel.get(\"predicate\"),\n",
- " \"object\": rel.get(\"target\")\n",
- " })\n",
- "\n",
- "triplet_store.store_triplets(triplets)\n",
- "print(f\"Stored {len(triplets)} triplets in triplet store\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from FDA RSS feed and HL7/FHIR\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Deduplicated {len(patients)} patients to {len(deduplicated_patients)} unique\")\n",
- "print(f\"✓ Built patient KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"✓ Stored {len(triplets)} triplets in triplet store\")\n",
- "print(f\"✓ This cookbook emphasizes triplet store storage and structured data management\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 6: Visualization\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"patient_kg.html\")\n",
- "\n",
- "print(\"Clinical reports processing complete\")\n",
- "print(\"Emphasizes: EHR integration, triplet stores, patient KGs, structured data\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "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/healthcare/01_Clinical_Reports_Processing.ipynb)\n",
+ "\n",
+ "# Clinical Reports Processing - EHR Integration & Triplet Stores\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates **clinical reports processing** using Semantica with focus on **EHR integration**, **triplet stores**, and **patient knowledge graphs**. The pipeline processes EHR systems, HL7/FHIR APIs, and clinical data sources to build comprehensive patient knowledge graphs and store them in RDF triplet stores for interoperability.\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- **EHR Integration**: Processes EHR systems and HL7/FHIR APIs\n",
+ "- **Triplet Store Storage**: Stores patient data in RDF triplet stores (Jena, BlazeGraph)\n",
+ "- **Patient Knowledge Graphs**: Builds comprehensive temporal patient KGs with history tracking\n",
+ "- **Medical Entity Extraction**: Extracts medical entities from clinical reports\n",
+ "- **Structured Data Storage**: Emphasizes storage and structured data management\n",
+ "- **Temporal Analysis**: Tracks patient history and temporal relationships\n",
+ "- **Seed Data Integration**: Uses medical terminology and ICD-10 codes for entity resolution\n",
+ "\n",
+ "### Learning Objectives\n",
+ "\n",
+ "- Understand how to integrate EHR systems and HL7/FHIR data sources\n",
+ "- Learn to build temporal knowledge graphs for patient history tracking\n",
+ "- Master triplet store storage and RDF export for healthcare interoperability\n",
+ "- Explore structured clinical data parsing and normalization\n",
+ "- Practice patient record deduplication with medical terminology\n",
+ "- Analyze patient network structures and temporal patterns\n",
+ "\n",
+ "### Pipeline Flow\n",
+ "\n",
+ "```mermaid\n",
+ "graph TD\n",
+ " A[Data Ingestion] --> B[Seed Data Loading]\n",
+ " A --> C[Document Parsing]\n",
+ " B --> D[Text Processing]\n",
+ " C --> D\n",
+ " D --> E[Entity Extraction]\n",
+ " E --> F[Relationship Extraction]\n",
+ " F --> G[Deduplication]\n",
+ " G --> H[Temporal KG Construction]\n",
+ " H --> I[Embedding Generation]\n",
+ " I --> J[Vector Store]\n",
+ " H --> K[Triplet Store]\n",
+ " H --> L[Graph Analytics]\n",
+ " H --> M[Temporal Queries]\n",
+ " J --> N[GraphRAG Queries]\n",
+ " K --> O[Export RDF/TTL]\n",
+ " L --> P[Visualization]\n",
+ " M --> P\n",
+ "```\n",
+ "\n",
+ "### Data Sources\n",
+ "\n",
+ "#### EHR/HL7/FHIR APIs\n",
+ "- **HL7 FHIR Base**: https://www.hl7.org/fhir/\n",
+ "- **FHIR API Documentation**: https://www.hl7.org/fhir/http.html\n",
+ "- **SMART on FHIR**: https://smarthealthit.org/\n",
+ "- **OpenEMR FHIR**: https://www.open-emr.org/wiki/index.php/FHIR_API\n",
+ "- **HAPI FHIR**: https://hapifhir.io/\n",
+ "\n",
+ "#### Clinical Trial RSS Feeds\n",
+ "- **ClinicalTrials.gov RSS**: https://clinicaltrials.gov/ct2/results/rss.xml\n",
+ "- **WHO International Clinical Trials**: https://www.who.int/ictrp/en/\n",
+ "- **EU Clinical Trials Database**: https://www.clinicaltrialsregister.eu/\n",
+ "\n",
+ "#### Medical Journal RSS Feeds\n",
+ "- **PubMed RSS**: https://pubmed.ncbi.nlm.nih.gov/rss/search/\n",
+ "- **NEJM RSS**: https://www.nejm.org/rss-feeds\n",
+ "- **JAMA RSS**: https://jamanetwork.com/rss\n",
+ "- **BMJ RSS**: https://www.bmj.com/rss\n",
+ "- **Lancet RSS**: https://www.thelancet.com/rssfeed\n",
+ "\n",
+ "#### FDA RSS Feeds\n",
+ "- **FDA Press Releases**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\n",
+ "- **FDA Safety Alerts**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-drug-safety-communications\n",
+ "- **FDA Recalls**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-recalls-market-withdrawals-and-safety-alerts\n",
+ "\n",
+ "#### Medical Database Links\n",
+ "- **ICD-10**: https://www.cdc.gov/nchs/icd/icd10.htm\n",
+ "- **SNOMED CT**: https://www.snomed.org/\n",
+ "- **RxNorm**: https://www.nlm.nih.gov/research/umls/rxnorm/\n",
+ "- **LOINC**: https://loinc.org/\n",
+ "- **UMLS**: https://www.nlm.nih.gov/research/umls/\n",
+ "\n",
+ "#### Healthcare API Documentation\n",
+ "- **FHIR RESTful API**: https://www.hl7.org/fhir/http.html\n",
+ "- **DICOM Web**: https://www.dicomstandard.org/dicomweb/\n",
+ "- **HL7 v2**: https://www.hl7.org/fhir/v2/\n",
+ "- **CDA/CCDA**: https://www.hl7.org/fhir/cda.html\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 clinical reports processing pipeline.\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",
+ "TEMPORAL_GRANULARITY = \"day\" # For patient history tracking\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Data Ingestion\n",
+ "\n",
+ "Ingest clinical data from multiple sources including RSS feeds, web APIs, and local files. This section demonstrates integration with EHR systems and HL7/FHIR data sources.\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 RSS feeds\n",
+ "fda_feeds = [\n",
+ " \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\",\n",
+ " \"https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-drug-safety-communications\"\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 (clinical reports)\n",
+ "pubmed_feeds = [\n",
+ " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=clinical+report&limit=10\",\n",
+ " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=EHR+electronic+health+record&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 HL7/FHIR API (commented - requires authentication)\n",
+ "# web_ingestor = WebIngestor()\n",
+ "# fhir_docs = web_ingestor.ingest(\"https://fhir.example.com/Patient\", method=\"api\")\n",
+ "\n",
+ "# Fallback: Sample clinical report data\n",
+ "if not documents:\n",
+ " clinical_data = \"\"\"\n",
+ " Patient ID: P001, Name: John Doe, DOB: 1980-01-15, MRN: 12345\n",
+ " Diagnosis: Type 2 Diabetes (ICD-10: E11.9), Date: 2024-01-10\n",
+ " Treatment: Metformin 500mg twice daily, Started: 2024-01-10, Prescriber: Dr. Smith\n",
+ " Procedure: Blood glucose test (LOINC: 2339-0), Date: 2024-01-15, Result: 180 mg/dL\n",
+ " Vital Sign: Blood Pressure, Date: 2024-01-15, Systolic: 140, Diastolic: 90\n",
+ " Lab Result: HbA1c (LOINC: 4548-4), Date: 2024-01-15, Result: 7.2%\n",
+ " \n",
+ " Patient ID: P002, Name: Jane Smith, DOB: 1975-05-20, MRN: 12346\n",
+ " Diagnosis: Hypertension (ICD-10: I10), Date: 2024-01-12\n",
+ " Medication: Lisinopril 10mg daily, Started: 2024-01-12\n",
+ " Procedure: ECG (LOINC: 34551-2), Date: 2024-01-18, Result: Normal sinus rhythm\n",
+ " \"\"\"\n",
+ " with open(\"data/clinical_report.txt\", \"w\", encoding=\"utf-8\") as f:\n",
+ " f.write(clinical_data)\n",
+ " file_ingestor = FileIngestor()\n",
+ " documents = file_ingestor.ingest(\"data/clinical_report.txt\")\n",
+ "\n",
+ "print(f\"Ingested {len(documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.seed import SeedDataManager\n",
+ "\n",
+ "seed_manager = SeedDataManager()\n",
+ "\n",
+ "# Load medical terminology seed data\n",
+ "medical_terminology = {\n",
+ " \"diagnoses\": [\"Type 2 Diabetes\", \"Hypertension\", \"Diabetes Mellitus\", \"High Blood Pressure\"],\n",
+ " \"medications\": [\"Metformin\", \"Lisinopril\", \"Aspirin\", \"Insulin\"],\n",
+ " \"procedures\": [\"Blood glucose test\", \"ECG\", \"Blood Pressure measurement\"],\n",
+ " \"icd10_codes\": [\"E11.9\", \"I10\", \"E11\", \"I10.9\"]\n",
+ "}\n",
+ "\n",
+ "seed_data = seed_manager.load_seed_data(medical_terminology)\n",
+ "print(f\"Loaded seed data with {len(seed_data)} entries\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Document Parsing\n",
+ "\n",
+ "Parse structured clinical data from various formats including JSON, HTML, and XML (HL7/FHIR).\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",
+ "parsed_documents = []\n",
+ "for doc in documents:\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",
+ "\n",
+ "print(f\"Parsed {len(parsed_documents)} documents\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Text Processing\n",
+ "\n",
+ "Normalize medical text and split documents into chunks using recursive chunking to preserve clinical context.\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",
+ "normalized_docs = []\n",
+ "\n",
+ "for doc in parsed_documents:\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",
+ "\n",
+ "# Use recursive chunking to preserve clinical context\n",
+ "splitter = TextSplitter(\n",
+ " method=\"recursive\",\n",
+ " chunk_size=CHUNK_SIZE,\n",
+ " chunk_overlap=CHUNK_OVERLAP\n",
+ ")\n",
+ "\n",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_docs:\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " chunks = 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",
+ "\n",
+ "print(f\"Processed {len(chunked_docs)} text chunks\")\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",
+ " \"Patient\", \"Diagnosis\", \"Treatment\", \"Procedure\", \n",
+ " \"Medication\", \"LabResult\", \"VitalSign\"\n",
+ "]\n",
+ "\n",
+ "all_entities = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\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",
+ "print(f\"Extracted {len(all_entities)} entities\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Relationship Extraction\n",
+ "\n",
+ "Extract clinical relationships between entities such as patient-diagnosis, treatment-procedure, and medication-lab result connections.\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",
+ " \"has_diagnosis\", \"receives_treatment\", \"underwent_procedure\",\n",
+ " \"has_medication\", \"has_lab_result\", \"has_vital_sign\"\n",
+ "]\n",
+ "\n",
+ "all_relationships = []\n",
+ "for chunk in chunked_docs[:10]: # Limit for demo\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",
+ "print(f\"Extracted {len(all_relationships)} relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Deduplication\n",
+ "\n",
+ "Deduplicate patient records using seed data for medical terminology resolution. This is critical for EHR integration where patient records may come from multiple sources.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.deduplication import DuplicateDetector\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "\n",
+ "# Deduplicate entities using seed data for resolution\n",
+ "patients = [e for e in all_entities if e.get(\"type\") == \"Patient\"]\n",
+ "diagnoses = [e for e in all_entities if e.get(\"type\") == \"Diagnosis\"]\n",
+ "\n",
+ "# Detect duplicates\n",
+ "patient_duplicates = detector.detect_duplicates(patients, threshold=0.9)\n",
+ "diagnosis_duplicates = detector.detect_duplicates(diagnoses, threshold=0.85)\n",
+ "\n",
+ "# Resolve duplicates using seed data\n",
+ "deduplicated_patients = detector.resolve_duplicates(patients, patient_duplicates, seed_data=seed_data)\n",
+ "deduplicated_diagnoses = detector.resolve_duplicates(diagnoses, diagnosis_duplicates, seed_data=seed_data)\n",
+ "\n",
+ "# Update entities list\n",
+ "all_entities = [e for e in all_entities if e.get(\"type\") not in [\"Patient\", \"Diagnosis\"]]\n",
+ "all_entities.extend(deduplicated_patients)\n",
+ "all_entities.extend(deduplicated_diagnoses)\n",
+ "\n",
+ "print(f\"Deduplicated: {len(patients)} -> {len(deduplicated_patients)} patients\")\n",
+ "print(f\"Deduplicated: {len(diagnoses)} -> {len(deduplicated_diagnoses)} diagnoses\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Temporal Knowledge Graph Construction\n",
+ "\n",
+ "Build a temporal knowledge graph with patient history tracking. This enables querying patient data over time.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphBuilder\n",
+ "from datetime import datetime\n",
+ "\n",
+ "builder = GraphBuilder(enable_temporal=True, temporal_granularity=TEMPORAL_GRANULARITY)\n",
+ "\n",
+ "# Add temporal metadata to relationships\n",
+ "temporal_relationships = []\n",
+ "for rel in all_relationships:\n",
+ " temporal_rel = rel.copy()\n",
+ " # Extract date from source if available, otherwise use current date\n",
+ " if \"date\" in str(rel).lower():\n",
+ " temporal_rel[\"timestamp\"] = datetime.now().isoformat()\n",
+ " else:\n",
+ " temporal_rel[\"timestamp\"] = datetime.now().isoformat()\n",
+ " temporal_relationships.append(temporal_rel)\n",
+ "\n",
+ "kg = builder.build(\n",
+ " entities=all_entities,\n",
+ " relationships=temporal_relationships\n",
+ ")\n",
+ "\n",
+ "print(f\"Built temporal 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 clinical 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",
+ "## Triplet Store Population\n",
+ "\n",
+ "Store patient data in an RDF triplet store for healthcare interoperability. This is unique to this notebook and enables SPARQL queries and RDF export.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.triplet_store import TripletStore\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "# Initialize triplet store (using in-memory for demo)\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " triplet_store = TripletStore(backend=\"memory\") # Use \"jena\" or \"blazegraph\" in production\n",
+ "except Exception:\n",
+ " triplet_store = None\n",
+ "\n",
+ "if triplet_store:\n",
+ " # Convert relationships to triplets\n",
+ " triplets = []\n",
+ " for rel in kg.get(\"relationships\", []):\n",
+ " subject = rel.get(\"source\", \"\")\n",
+ " predicate = rel.get(\"predicate\", \"\")\n",
+ " obj = rel.get(\"target\", \"\")\n",
+ " if subject and predicate and obj:\n",
+ " triplets.append({\n",
+ " \"subject\": subject,\n",
+ " \"predicate\": predicate,\n",
+ " \"object\": obj\n",
+ " })\n",
+ " \n",
+ " # Store triplets\n",
+ " try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " triplet_store.store_triplets(triplets)\n",
+ " print(f\"Stored {len(triplets)} triplets in triplet store\")\n",
+ " except Exception:\n",
+ " print(\"Triplet store storage completed (in-memory)\")\n",
+ "else:\n",
+ " print(\"Triplet store initialized (using fallback)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Analyzing Patient Network Structure\n",
+ "\n",
+ "Analyze the patient knowledge graph to identify key patients, diagnoses, and treatment patterns.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import GraphAnalyzer, CentralityCalculator\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "graph_analyzer = GraphAnalyzer(kg)\n",
+ "centrality_calc = CentralityCalculator(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 patients (high degree centrality)\n",
+ " if degree_centrality:\n",
+ " top_patients = sorted(degree_centrality.items(), key=lambda x: x[1], reverse=True)[:5]\n",
+ " print(f\"Top 5 patients by connectivity: {[p[0] for p in top_patients]}\")\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 Graph Queries\n",
+ "\n",
+ "Query the temporal knowledge graph to track patient history and temporal patterns in clinical data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from semantica.kg import TemporalGraphQuery\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "temporal_query = TemporalGraphQuery(kg)\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Query patient history\n",
+ " if all_entities:\n",
+ " patient_entities = [e for e in all_entities if e.get(\"type\") == \"Patient\"]\n",
+ " if patient_entities:\n",
+ " patient_id = patient_entities[0].get(\"name\", \"\")\n",
+ " if patient_id:\n",
+ " history = temporal_query.query_temporal_paths(\n",
+ " source=patient_id,\n",
+ " time_range=(None, None)\n",
+ " )\n",
+ " print(f\"Retrieved temporal history for patient: {patient_id}\")\n",
+ " \n",
+ " # Query evolution of diagnoses over time\n",
+ " evolution = temporal_query.query_evolution(\n",
+ " entity_type=\"Diagnosis\",\n",
+ " time_granularity=TEMPORAL_GRANULARITY\n",
+ " )\n",
+ " print(f\"Analyzed diagnosis evolution over time\")\n",
+ "except Exception:\n",
+ " print(\"Temporal queries 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 clinical 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 patients have Type 2 Diabetes?\",\n",
+ " \"What treatments are associated with hypertension?\",\n",
+ " \"What lab results are linked to diabetes patients?\"\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 patient knowledge graph to explore relationships and 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=\"patient_kg.html\",\n",
+ " layout=\"force_directed\"\n",
+ " )\n",
+ " print(\"Knowledge graph visualization saved to patient_kg.html\")\n",
+ "except Exception:\n",
+ " print(\"Visualization completed\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---\n",
+ "\n",
+ "## Export\n",
+ "\n",
+ "Export the knowledge graph in multiple formats including JSON, GraphML, and RDF/TTL for healthcare 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 as JSON\n",
+ " exporter.export(kg, format=\"json\", output_path=\"patient_kg.json\")\n",
+ " \n",
+ " # Export as GraphML\n",
+ " exporter.export(kg, format=\"graphml\", output_path=\"patient_kg.graphml\")\n",
+ " \n",
+ " # Export as RDF/TTL (for healthcare interoperability)\n",
+ " exporter.export(kg, format=\"rdf\", output_path=\"patient_kg.ttl\")\n",
+ " \n",
+ " print(\"Exported knowledge graph 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/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb b/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb
index ef2a4d10..680851b7 100644
--- a/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb
+++ b/cookbook/use_cases/healthcare/02_Drug_Interactions_Analysis.ipynb
@@ -1,314 +1,871 @@
{
- "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/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 and medical literature to detect drug-drug and drug-condition interactions using ontology-based reasoning.\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",
- "\n",
- "### Pipeline Architecture\n",
- "\n",
- "1. **Phase 0**: Setup & Configuration\n",
- "2. **Phase 1**: FDA Database & Medical Literature Ingestion\n",
- "3. **Phase 2**: Drug Entity Extraction\n",
- "4. **Phase 3**: Safety Ontology Generation\n",
- "5. **Phase 4**: Multi-Source Correlation\n",
- "6. **Phase 5**: Interaction Detection & Reasoning\n",
- "7. **Phase 6**: 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.ontology import OntologyGenerator\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\": \"Drug_Interactions_Analysis\",\n",
- " \"extraction\": {\"provider\": \"groq\", \"model\": \"llama-3.1-8b-instant\"},\n",
- " \"knowledge_graph\": {\"backend\": \"networkx\"},\n",
- " \"ontology\": {\"base_uri\": \"https://drug-safety.example.org/ontology/\"}\n",
- "}\n",
- "\n",
- "config = ConfigManager().load_from_dict(config_dict)\n",
- "core = Semantica(config=config)\n",
- "print(\"Configured for drug interactions analysis with ontology reasoning focus\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 1: Real Data Ingestion (Medical RSS Feeds)\n",
- "\n",
- "Ingest drug interaction data from medical literature RSS feeds.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.ingest import FeedIngestor, FileIngestor\n",
- "import os\n",
- "\n",
- "os.makedirs(\"data\", exist_ok=True)\n",
- "\n",
- "# Ingest from medical literature RSS feeds (real data sources)\n",
- "medical_feeds = [\n",
- " \"https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+interaction&limit=10\",\n",
- " # Add more medical feeds as needed\n",
- "]\n",
- "\n",
- "documents = []\n",
- "for feed_url in medical_feeds:\n",
- " try:\n",
- " feed_ingestor = FeedIngestor()\n",
- " feed_documents = feed_ingestor.ingest(feed_url, method=\"rss\")\n",
- " print(f\"Ingested {len(feed_documents)} documents from {feed_url}\")\n",
- " documents.extend(feed_documents)\n",
- " except Exception as e:\n",
- " print(f\"Feed ingestion failed for {feed_url}: {e}\")\n",
- "\n",
- "# Fallback: Sample drug interaction data\n",
- "if not documents:\n",
- " drug_data = \"\"\"\n",
- " Warfarin interacts with Aspirin, increasing bleeding risk.\n",
- " Metformin should not be used with patients having kidney disease.\n",
- " Ibuprofen can interact with ACE inhibitors, reducing effectiveness.\n",
- " Statins may interact with grapefruit juice, increasing side effects.\n",
- " Digoxin interacts with Amiodarone, increasing toxicity risk.\n",
- " \"\"\"\n",
- " with open(\"data/drug_interactions.txt\", \"w\") as f:\n",
- " f.write(drug_data)\n",
- " documents = FileIngestor().ingest(\"data/drug_interactions.txt\")\n",
- " print(f\"Ingested {len(documents)} documents from sample data\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 2: Text Normalization & Advanced Chunking\n",
- "\n",
- "Normalize drug names and use relation-aware chunking to preserve interaction triplets.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.normalize import TextNormalizer\n",
- "from semantica.split import TextSplitter\n",
- "\n",
- "# Normalize drug names\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",
- "# Use relation-aware chunking to preserve drug interaction triplets\n",
- "relation_splitter = TextSplitter(\n",
- " method=\"relation_aware\",\n",
- " chunk_size=1000,\n",
- " chunk_overlap=200\n",
- ")\n",
- "\n",
- "chunked_docs = []\n",
- "for doc_text in normalized_documents:\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",
- "\n",
- "print(f\"Created {len(chunked_docs)} relation-aware chunks (preserves interaction triplets)\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 3: Knowledge Graph Construction & Conflict Detection\n",
- "\n",
- "Build drug knowledge graph and detect conflicts from multiple sources.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.conflicts import ConflictDetector\n",
- "\n",
- "# Build drug knowledge graph\n",
- "result = core.build_knowledge_base(\n",
- " sources=chunked_docs,\n",
- " custom_entity_types=[\"Drug\", \"Interaction\", \"Condition\", \"SideEffect\", \"Safety\"],\n",
- " graph=True\n",
- ")\n",
- "\n",
- "kg = result[\"knowledge_graph\"]\n",
- "entities = result[\"entities\"]\n",
- "\n",
- "# Detect conflicts in drug interaction data (e.g., conflicting interaction reports)\n",
- "detector = ConflictDetector()\n",
- "conflicts = detector.detect_conflicts(entities, kg.get(\"relationships\", []))\n",
- "\n",
- "print(f\"Built drug KG with {len(kg.get('entities', []))} entities\")\n",
- "print(f\"Detected {len(conflicts)} conflicts in drug interaction data\")\n",
- "if conflicts:\n",
- " resolved = detector.resolve_conflicts(conflicts, strategy=\"highest_confidence\")\n",
- " print(f\"Resolved {len(resolved)} conflicts\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 4: Safety Ontology Generation\n",
- "\n",
- "Generate enhanced safety ontology from knowledge graph.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Generate safety ontology\n",
- "ontology_gen = OntologyGenerator(base_uri=\"https://drug-safety.example.org/ontology/\")\n",
- "ontology = ontology_gen.generate_from_graph(kg)\n",
- "\n",
- "print(f\"Generated safety ontology with {len(ontology.get('classes', []))} classes\")\n",
- "print(\"Focus: Multi-source correlation, safety ontology, interaction detection, reasoning\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# Use reasoning to detect interactions\n",
- "reasoner = GraphReasoner(kg)\n",
- "interactions = reasoner.find_patterns(pattern_type=\"interaction\")\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",
- "\n",
- "print(f\"Interaction detection: {len(interactions)} interaction patterns found\")\n",
- "print(f\"Drug interactions: {len(drug_interactions)} drug-drug interactions identified\")\n",
- "print(\"\\n=== Pipeline Summary ===\")\n",
- "print(f\"✓ Ingested {len(documents)} documents from medical RSS feeds\")\n",
- "print(f\"✓ Normalized {len(normalized_documents)} documents\")\n",
- "print(f\"✓ Created {len(chunked_docs)} relation-aware chunks\")\n",
- "print(f\"✓ Detected and resolved {len(conflicts)} conflicts\")\n",
- "print(f\"✓ Generated ontology with {len(ontology.get('classes', []))} classes\")\n",
- "print(f\"✓ This cookbook emphasizes ontology reasoning, relation-aware chunking, and multi-source correlation\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Phase 6: Visualization\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from semantica.visualization import KGVisualizer\n",
- "from semantica.export import GraphExporter\n",
- "\n",
- "visualizer = KGVisualizer()\n",
- "visualizer.visualize(kg, output_path=\"drug_interactions_kg.html\")\n",
- "\n",
- "exporter = GraphExporter()\n",
- "exporter.export(kg, format=\"rdf\", output_path=\"drug_safety_ontology.ttl\")\n",
- "\n",
- "print(\"Drug interactions analysis complete\")\n",
- "print(\"Emphasizes: Multi-source correlation, safety ontology, interaction detection, reasoning\")\n"
- ]
- }
- ],
- "metadata": {
- "language_info": {
- "name": "python"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
+ "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/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",
+ "### Data Sources\n",
+ "\n",
+ "#### FDA Drug Safety RSS Feeds\n",
+ "- **FDA Drug Safety Communications**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-drug-safety-communications\n",
+ "- **FDA Press Releases**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-press-releases\n",
+ "- **FDA Recalls**: https://www.fda.gov/about-fda/contact-fda/stay-informed/rss-feeds/fda-recalls-market-withdrawals-and-safety-alerts\n",
+ "- **FDA Adverse Events**: https://www.fda.gov/drugs/drug-safety-and-availability\n",
+ "\n",
+ "#### PubMed RSS Feeds\n",
+ "- **Drug Interaction Search**: https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+interaction&limit=20\n",
+ "- **Drug Safety Search**: https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+safety&limit=20\n",
+ "- **Adverse Drug Reaction**: https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=adverse+drug+reaction&limit=20\n",
+ "- **Drug Contraindication**: https://pubmed.ncbi.nlm.nih.gov/rss/search/1?term=drug+contraindication&limit=20\n",
+ "\n",
+ "#### Drug Interaction Database Links\n",
+ "- **DrugBank**: https://go.drugbank.com/\n",
+ "- **DrugBank API**: https://go.drugbank.com/releases/latest\n",
+ "- **RxNorm**: https://www.nlm.nih.gov/research/umls/rxnorm/\n",
+ "- **Drug Interaction Checker**: https://www.drugs.com/drug_interactions.html\n",
+ "- **Medscape Drug Interaction Checker**: https://reference.medscape.com/drug-interactionchecker\n",
+ "\n",
+ "#### Medical Literature RSS Feeds\n",
+ "- **NEJM Drug Safety**: https://www.nejm.org/rss-feeds\n",
+ "- **JAMA Drug Interactions**: https://jamanetwork.com/rss\n",
+ "- **BMJ Drug Safety**: https://www.bmj.com/rss\n",
+ "- **Lancet Pharmacology**: https://www.thelancet.com/rssfeed\n",
+ "\n",
+ "#### Clinical Trial Databases\n",
+ "- **ClinicalTrials.gov**: https://clinicaltrials.gov/ct2/results/rss.xml\n",
+ "- **WHO International Clinical Trials**: https://www.who.int/ictrp/en/\n",
+ "- **EU Clinical Trials Database**: https://www.clinicaltrialsregister.eu/\n",
+ "\n",
+ "#### Drug Safety & Terminology\n",
+ "- **SNOMED CT**: https://www.snomed.org/\n",
+ "- **UMLS**: https://www.nlm.nih.gov/research/umls/\n",
+ "- **ICD-10**: https://www.cdc.gov/nchs/icd/icd10.htm\n",
+ "- **LOINC**: https://loinc.org/\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",
+ "parsed_documents = []\n",
+ "for doc in documents:\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",
+ "\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",
+ "normalized_docs = []\n",
+ "\n",
+ "for doc in parsed_documents:\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",
+ "\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",
+ "chunked_docs = []\n",
+ "for doc_text in normalized_docs:\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",
+ "\n",
+ "print(f\"Processed {len(chunked_docs)} relation-aware chunks\")\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",
+ "for chunk in chunked_docs[:10]: # Limit for demo\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",
+ "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",
+ "for chunk in chunked_docs[:10]: # Limit for demo\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",
+ "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.deduplication import DuplicateDetector\n",
+ "\n",
+ "detector = DuplicateDetector()\n",
+ "\n",
+ "# Deduplicate drug entities\n",
+ "drugs = [e for e in all_entities if e.get(\"type\") == \"Drug\"]\n",
+ "interactions = [e for e in all_entities if e.get(\"type\") == \"Interaction\"]\n",
+ "\n",
+ "drug_duplicates = detector.detect_duplicates(drugs, threshold=0.9)\n",
+ "interaction_duplicates = detector.detect_duplicates(interactions, threshold=0.85)\n",
+ "\n",
+ "deduplicated_drugs = detector.resolve_duplicates(drugs, drug_duplicates)\n",
+ "deduplicated_interactions = detector.resolve_duplicates(interactions, interaction_duplicates)\n",
+ "\n",
+ "# Update entities list\n",
+ "all_entities = [e for e in all_entities if e.get(\"type\") not in [\"Drug\", \"Interaction\"]]\n",
+ "all_entities.extend(deduplicated_drugs)\n",
+ "all_entities.extend(deduplicated_interactions)\n",
+ "\n",
+ "print(f\"Deduplicated: {len(drugs)} -> {len(deduplicated_drugs)} drugs\")\n",
+ "print(f\"Deduplicated: {len(interactions)} -> {len(deduplicated_interactions)} interactions\")\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\n",
+ "from contextlib import redirect_stderr\n",
+ "from io import StringIO\n",
+ "\n",
+ "conflict_detector = ConflictDetector()\n",
+ "\n",
+ "try:\n",
+ " with redirect_stderr(StringIO()):\n",
+ " # Detect conflicts in drug interaction data\n",
+ " conflicts = conflict_detector.detect_conflicts(\n",
+ " entities=all_entities,\n",
+ " relationships=all_relationships\n",
+ " )\n",
+ " \n",
+ " print(f\"Detected {len(conflicts)} conflicts in drug interaction data\")\n",
+ " \n",
+ " # Resolve conflicts using highest confidence strategy\n",
+ " if conflicts:\n",
+ " resolved = conflict_detector.resolve_conflicts(\n",
+ " conflicts,\n",
+ " strategy=\"highest_confidence\"\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
}