{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Notice**: The `semantica.kg_qa` module is temporarily unavailable and will be reintroduced in a future release. Any quality assessment examples in this notebook are disabled."
   ]
  },
  {
   "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/03_Drug_Interactions_Analysis.ipynb)\n",
    "\n",
    "# Drug Interactions Analysis Pipeline\n",
    "\n",
    "## Overview\n",
    "\n",
    "This notebook demonstrates a complete drug interactions analysis pipeline: ingest drug data from multiple sources (FDA databases, drug interaction databases, medical literature), extract drug information, build drug knowledge graph, detect interactions, and generate drug safety ontology.\n",
    "\n",
    "\n",
    "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",
    "\n",
    "### Modules Used (20+)\n",
    "\n",
    "- **Ingestion**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor\n",
    "- **Parsing**: DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
    "- **Extraction**: NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
    "- **KG**: GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
    "- **Analytics**: ConnectivityAnalyzer, TemporalGraphQuery\n",
    "- **Ontology**: OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
    "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator\n",
    "- **Quality**: KGQualityAssessor, ConflictDetector\n",
    "- **Export**: JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
    "- **Visualization**: KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",
    "\n",
    "### Pipeline\n",
    "\n",
    "**Drug Data Sources → Parse → Extract Drug Info → Build Drug KG → Detect Interactions → Generate Ontology → Generate Reports → Visualize**\n",
    "\n",
    "## Installation\n",
    "\n",
    "Install Semantica from PyPI:\n",
    "\n",
    "```bash\n",
    "pip install semantica\n",
    "# Or with all optional dependencies:\n",
    "pip install semantica[all]\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "## Step 1: Ingest Drug Data from Multiple Sources\n",
    "\n",
    "Ingest drug data from FDA databases, drug interaction databases, and medical literature.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantica.ingest import FileIngestor, WebIngestor, DBIngestor, FeedIngestor\n",
    "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser, JSONParser\n",
    "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor, SemanticAnalyzer\n",
    "from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector\n",
    "from semantica.kg import ConnectivityAnalyzer, TemporalGraphQuery\n",
    "from semantica.ontology import OntologyGenerator, ClassInferrer, PropertyGenerator, OntologyValidator\n",
    "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
    
    "from semantica.conflicts import ConflictDetector\n",
    "from semantica.export import JSONExporter, RDFExporter, OWLExporter, ReportGenerator\n",
    "from semantica.visualization import KGVisualizer, OntologyVisualizer, AnalyticsVisualizer\n",
    "import tempfile\n",
    "import os\n",
    "import json\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "file_ingestor = FileIngestor()\n",
    "web_ingestor = WebIngestor()\n",
    "db_ingestor = DBIngestor()\n",
    "feed_ingestor = FeedIngestor()\n",
    "\n",
    "document_parser = DocumentParser()\n",
    "pdf_parser = PDFParser()\n",
    "structured_parser = StructuredDataParser()\n",
    "json_parser = JSONParser()\n",
    "\n",
    "# Real drug data sources\n",
    "drug_apis = [\n",
    "    \"https://api.fda.gov/drug/label.json\",  # FDA Drug Labeling API\n",
    "    \"https://api.fda.gov/drug/event.json\",  # FDA Adverse Events API\n",
    "    \"https://api.logicahealth.org/fhir/R4/Medication\"  # FHIR Medications\n",
    "]\n",
    "\n",
    "medical_feeds = [\n",
    "    \"https://www.cdc.gov/rss.xml\",  # CDC Health Alerts\n",
    "    \"https://www.who.int/rss-feeds/news-english.xml\"  # WHO News\n",
    "]\n",
    "\n",
    "# Real database connection for drug data\n",
    "db_connection_string = \"postgresql://user:password@localhost:5432/drug_db\"\n",
    "db_query = \"SELECT drug_name, drug_class, interactions, contraindications, side_effects FROM drugs WHERE last_updated > CURRENT_DATE - INTERVAL '1 year' ORDER BY drug_name\"\n",
    "\n",
    "temp_dir = tempfile.mkdtemp()\n",
    "\n",
    "# Sample drug interaction data\n",
    "drug_file = os.path.join(temp_dir, \"drug_data.json\")\n",
    "drug_data = {\n",
    "    \"drugs\": [\n",
    "        {\n",
    "            \"drug_name\": \"Lisinopril\",\n",
    "            \"drug_class\": \"ACE Inhibitor\",\n",
    "            \"interactions\": [\"Potassium supplements\", \"Diuretics\", \"NSAIDs\"],\n",
    "            \"contraindications\": [\"Pregnancy\", \"Angioedema\"],\n",
    "            \"side_effects\": [\"Cough\", \"Dizziness\", \"Hyperkalemia\"]\n",
    "        },\n",
    "        {\n",
    "            \"drug_name\": \"Metformin\",\n",
    "            \"drug_class\": \"Biguanide\",\n",
    "            \"interactions\": [\"Alcohol\", \"Contrast agents\"],\n",
    "            \"contraindications\": [\"Renal impairment\", \"Lactic acidosis\"],\n",
    "            \"side_effects\": [\"Nausea\", \"Diarrhea\", \"Lactic acidosis\"]\n",
    "        },\n",
    "        {\n",
    "            \"drug_name\": \"Warfarin\",\n",
    "            \"drug_class\": \"Anticoagulant\",\n",
    "            \"interactions\": [\"Aspirin\", \"Antibiotics\", \"Vitamin K\"],\n",
    "            \"contraindications\": [\"Active bleeding\", \"Pregnancy\"],\n",
    "            \"side_effects\": [\"Bleeding\", \"Bruising\", \"Hair loss\"]\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n",
    "with open(drug_file, 'w') as f:\n",
    "    json.dump(drug_data, f, indent=2)\n",
    "\n",
    "file_objects = file_ingestor.ingest_file(drug_file, read_content=True)\n",
    "parsed_data = structured_parser.parse_json(drug_file)\n",
    "\n",
    "# Ingest from drug APIs\n",
    "drug_api_list = []\n",
    "for api_url in drug_apis[:1]:\n",
    "    api_content = web_ingestor.ingest_url(api_url)\n",
    "    if api_content:\n",
    "        drug_api_list.append(api_content)\n",
    "        print(f\"  Ingested drug API: {api_url}\")\n",
    "\n",
    "print(f\"\\n📊 Ingestion Summary:\")\n",
    "print(f\"  Drug data files: {len([file_objects]) if file_objects else 0}\")\n",
    "print(f\"  Drug API sources: {len(drug_api_list)}\")\n",
    "print(f\"  Database sources: 1\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Extract Drug Information\n",
    "\n",
    "Extract drug entities and interaction information.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ner_extractor = NERExtractor()\n",
    "relation_extractor = RelationExtractor()\n",
    "triple_extractor = TripleExtractor()\n",
    "semantic_analyzer = SemanticAnalyzer()\n",
    "\n",
    "drug_entities = []\n",
    "drug_relationships = []\n",
    "\n",
    "# Extract from drug data\n",
    "if parsed_data and parsed_data.data:\n",
    "    drugs = parsed_data.data.get(\"drugs\", []) if isinstance(parsed_data.data, dict) else parsed_data.data if isinstance(parsed_data.data, list) else []\n",
    "    \n",
    "    for drug in drugs:\n",
    "        if isinstance(drug, dict):\n",
    "            drug_name = drug.get(\"drug_name\", \"\")\n",
    "            \n",
    "            drug_entities.append({\n",
    "                \"id\": drug_name,\n",
    "                \"type\": \"Drug\",\n",
    "                \"name\": drug_name,\n",
    "                \"properties\": {\n",
    "                    \"drug_class\": drug.get(\"drug_class\", \"\")\n",
    "                }\n",
    "            })\n",
    "            \n",
    "            # Drug interactions\n",
    "            for interaction in drug.get(\"interactions\", []):\n",
    "                drug_entities.append({\n",
    "                    \"id\": interaction,\n",
    "                    \"type\": \"Drug\",\n",
    "                    \"name\": interaction,\n",
    "                    \"properties\": {}\n",
    "                })\n",
    "                drug_relationships.append({\n",
    "                    \"source\": drug_name,\n",
    "                    \"target\": interaction,\n",
    "                    \"type\": \"interacts_with\",\n",
    "                    \"properties\": {\"severity\": \"moderate\"}\n",
    "                })\n",
    "            \n",
    "            # Contraindications\n",
    "            for contraindication in drug.get(\"contraindications\", []):\n",
    "                drug_entities.append({\n",
    "                    \"id\": contraindication,\n",
    "                    \"type\": \"Contraindication\",\n",
    "                    \"name\": contraindication,\n",
    "                    \"properties\": {}\n",
    "                })\n",
    "                drug_relationships.append({\n",
    "                    \"source\": drug_name,\n",
    "                    \"target\": contraindication,\n",
    "                    \"type\": \"contraindicated_in\",\n",
    "                    \"properties\": {}\n",
    "                })\n",
    "            \n",
    "            # Side effects\n",
    "            for side_effect in drug.get(\"side_effects\", []):\n",
    "                drug_entities.append({\n",
    "                    \"id\": side_effect,\n",
    "                    \"type\": \"Side_Effect\",\n",
    "                    \"name\": side_effect,\n",
    "                    \"properties\": {}\n",
    "                })\n",
    "                drug_relationships.append({\n",
    "                    \"source\": drug_name,\n",
    "                    \"target\": side_effect,\n",
    "                    \"type\": \"causes\",\n",
    "                    \"properties\": {}\n",
    "                })\n",
    "\n",
    "print(f\"Extracted {len(drug_entities)} drug entities\")\n",
    "print(f\"Extracted {len(drug_relationships)} drug relationships\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Build Drug Knowledge Graph\n",
    "\n",
    "Build knowledge graph from drug entities and relationships.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "builder = GraphBuilder()\n",
    "graph_analyzer = GraphAnalyzer()\n",
    "centrality_calculator = CentralityCalculator()\n",
    "community_detector = CommunityDetector()\n",
    "connectivity_analyzer = ConnectivityAnalyzer()\n",
    "\n",
    "drug_kg = builder.build(drug_entities, drug_relationships)\n",
    "\n",
    "metrics = graph_analyzer.compute_metrics(drug_kg)\n",
    "centrality_result = centrality_calculator.calculate_degree_centrality(drug_kg)\n",
    "centrality_scores = centrality_result.get('centrality', {})\n",
    "communities = community_detector.detect_communities(drug_kg)\n",
    "connectivity = connectivity_analyzer.analyze_connectivity(drug_kg)\n",
    "\n",
    "print(f\"Built drug knowledge graph\")\n",
    "print(f\"  Entities: {len(drug_kg.get('entities', []))}\")\n",
    "print(f\"  Relationships: {len(drug_kg.get('relationships', []))}\")\n",
    "print(f\"  Graph density: {metrics.get('density', 0):.3f}\")\n",
    "print(f\"  Communities: {len(communities)}\")\n",
    "print(f\"  Central drugs: {len([e for e, score in centrality_scores.items() if score > 0])}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Detect Drug Interactions\n",
    "\n",
    "Detect drug-drug interactions using inference engine.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_engine = InferenceEngine()\n",
    "rule_manager = RuleManager()\n",
    "explanation_generator = ExplanationGenerator()\n",
    "\n",
    "# Drug interaction detection rules\n",
    "inference_engine.add_rule(\"IF drug1 interacts_with drug2 AND drug2 interacts_with drug1 THEN bidirectional_interaction\")\n",
    "inference_engine.add_rule(\"IF drug interacts_with Anticoagulant AND drug is Antibiotic THEN increased_bleeding_risk\")\n",
    "inference_engine.add_rule(\"IF drug contraindicated_in Pregnancy AND patient is pregnant THEN contraindicated\")\n",
    "\n",
    "# Detect interactions\n",
    "interactions = []\n",
    "for relationship in drug_relationships:\n",
    "    if relationship.get(\"type\") == \"interacts_with\":\n",
    "        drug1 = relationship.get(\"source\")\n",
    "        drug2 = relationship.get(\"target\")\n",
    "        \n",
    "        # Check for bidirectional interaction\n",
    "        reverse_interaction = [r for r in drug_relationships \n",
    "                              if r.get(\"source\") == drug2 and r.get(\"target\") == drug1 and r.get(\"type\") == \"interacts_with\"]\n",
    "        \n",
    "        if reverse_interaction:\n",
    "            interactions.append({\n",
    "                \"drug1\": drug1,\n",
    "                \"drug2\": drug2,\n",
    "                \"type\": \"bidirectional\",\n",
    "                \"severity\": relationship.get(\"properties\", {}).get(\"severity\", \"unknown\")\n",
    "            })\n",
    "        else:\n",
    "            interactions.append({\n",
    "                \"drug1\": drug1,\n",
    "                \"drug2\": drug2,\n",
    "                \"type\": \"unidirectional\",\n",
    "                \"severity\": relationship.get(\"properties\", {}).get(\"severity\", \"unknown\")\n",
    "            })\n",
    "        \n",
    "        inference_engine.add_fact({\n",
    "            \"drug1\": drug1,\n",
    "            \"drug2\": drug2,\n",
    "            \"interaction_type\": relationship.get(\"type\")\n",
    "        })\n",
    "\n",
    "detected_interactions = inference_engine.forward_chain()\n",
    "\n",
    "print(f\"Detected {len(interactions)} drug interactions\")\n",
    "print(f\"Inferred {len(detected_interactions)} interaction patterns\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Generate Drug Ontology\n",
    "\n",
    "Generate drug safety ontology from drug knowledge graph.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ontology_generator = OntologyGenerator()\n",
    "class_inferrer = ClassInferrer()\n",
    "property_generator = PropertyGenerator()\n",
    "ontology_validator = OntologyValidator()\n",
    "\n",
    "drug_ontology = ontology_generator.generate_ontology({\n",
    "    \"entities\": drug_entities,\n",
    "    \"relationships\": drug_relationships\n",
    "}, entities=drug_entities, relationships=drug_relationships)\n",
    "\n",
    "classes = class_inferrer.infer_classes(drug_entities)\n",
    "properties = property_generator.infer_properties(drug_entities, drug_relationships, classes)\n",
    "\n",
    "validation_result = ontology_validator.validate_ontology(drug_ontology)\n",
    "\n",
    "print(f\"Generated drug safety ontology\")\n",
    "print(f\"  Classes: {len(drug_ontology.get('classes', []))}\")\n",
    "print(f\"  Properties: {len(drug_ontology.get('properties', []))}\")\n",
    "print(f\"  Ontology valid: {validation_result.valid}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Generate Reports and Visualize\n",
    "\n",
    "Generate drug interaction reports and visualize results.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "quality_assessor = KGQualityAssessor()\n",
    "json_exporter = JSONExporter()\n",
    "rdf_exporter = RDFExporter()\n",
    "owl_exporter = OWLExporter()\n",
    "report_generator = ReportGenerator()\n",
    "\n",
    "quality_score = quality_assessor.assess_overall_quality(drug_kg)\n",
    "\n",
    "json_exporter.export_knowledge_graph(drug_kg, os.path.join(temp_dir, \"drug_kg.json\"))\n",
    "rdf_exporter.export_knowledge_graph(drug_kg, os.path.join(temp_dir, \"drug_kg.rdf\"))\n",
    "owl_exporter.export(drug_ontology, os.path.join(temp_dir, \"drug_ontology.owl\"))\n",
    "\n",
    "report_data = {\n",
    "    \"summary\": f\"Drug interactions analysis identified {len(interactions)} interactions from {len(drug_entities)} drug entities\",\n",
    "    \"drugs_analyzed\": len([e for e in drug_entities if e.get(\"type\") == \"Drug\"]),\n",
    "    \"interactions\": len(interactions),\n",
    "    \"quality_score\": quality_score.get('overall_score', 0)\n",
    "}\n",
    "\n",
    "report = report_generator.generate_report(report_data, format=\"markdown\")\n",
    "\n",
    "kg_visualizer = KGVisualizer()\n",
    "ontology_visualizer = OntologyVisualizer()\n",
    "analytics_visualizer = AnalyticsVisualizer()\n",
    "\n",
    "kg_viz = kg_visualizer.visualize_network(drug_kg, output=\"interactive\")\n",
    "ontology_viz = ontology_visualizer.visualize_hierarchy(drug_ontology, output=\"interactive\")\n",
    "analytics_viz = analytics_visualizer.visualize_analytics(drug_kg, output=\"interactive\")\n",
    "\n",
    "print(f\"Total modules used: 20+\")\n",
    "print(f\"Pipeline complete: Drug Data → Parse → Extract → Build KG → Detect Interactions → Generate Ontology → Reports → Visualize\")\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
