{
 "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/advanced/03_Complete_Visualization_Suite.ipynb)\n",
    "\n",
    "# Complete Visualization Suite\n",
    "\n",
    "## Overview\n",
    "\n",
    "Comprehensive visualization capabilities: visualize knowledge graphs, embeddings, quality metrics, analytics, and temporal data.\n",
    "\n",
    "**Documentation**: [API Reference](https://semantica.readthedocs.io/reference/visualization/)\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"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantica.visualization import (\n",
    "    KGVisualizer,\n",
    "    EmbeddingVisualizer,\n",
    "    QualityVisualizer,\n",
    "    AnalyticsVisualizer,\n",
    "    TemporalVisualizer\n",
    ")\n",
    "from semantica.kg import GraphBuilder, GraphAnalyzer\n",
    "from semantica.embeddings import EmbeddingGenerator\n",
    
    "import numpy as np\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Create Sample Knowledge Graph\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "builder = GraphBuilder()\n",
    "\n",
    "entities = [\n",
    "    {\"id\": \"e1\", \"type\": \"Person\", \"name\": \"Alice\", \"properties\": {\"age\": 30}},\n",
    "    {\"id\": \"e2\", \"type\": \"Person\", \"name\": \"Bob\", \"properties\": {\"age\": 35}},\n",
    "    {\"id\": \"e3\", \"type\": \"Organization\", \"name\": \"Tech Corp\", \"properties\": {\"founded\": 2010}},\n",
    "    {\"id\": \"e4\", \"type\": \"Location\", \"name\": \"San Francisco\", \"properties\": {\"country\": \"USA\"}},\n",
    "]\n",
    "\n",
    "relationships = [\n",
    "    {\"source\": \"e1\", \"target\": \"e2\", \"type\": \"knows\", \"properties\": {\"since\": 2020}},\n",
    "    {\"source\": \"e1\", \"target\": \"e3\", \"type\": \"works_for\", \"properties\": {\"role\": \"Engineer\"}},\n",
    "    {\"source\": \"e3\", \"target\": \"e4\", \"type\": \"located_in\", \"properties\": {}},\n",
    "]\n",
    "\n",
    "knowledge_graph = builder.build(entities, relationships)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Knowledge Graph Visualization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",
    "kg_visualizer.visualize_network(knowledge_graph, output=\"interactive\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: Generate Embeddings and Visualize\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "embedding_generator = EmbeddingGenerator()\n",
    "texts = [entity.get(\"name\", \"\") for entity in entities]\n",
    "embeddings = embedding_generator.generate_embeddings(texts, data_type=\"text\")\n",
    "\n",
    "labels = [entity.get(\"type\", \"Unknown\") for entity in entities]\n",
    "\n",
    "embedding_visualizer = EmbeddingVisualizer()\n",
    "embedding_visualizer.visualize_2d_projection(embeddings, labels, method=\"tsne\", output=\"interactive\", file_path=None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Quality Metrics Visualization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "quality_visualizer = QualityVisualizer()\n",
    "quality_report = {\n",
    "    \"overall_score\": 0.85,\n",
    "    \"consistency_score\": 0.90,\n",
    "    \"completeness_score\": 0.80\n",
    "}\n",
    "quality_visualizer.visualize_dashboard(quality_report, output=\"interactive\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Graph Analytics Visualization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph_analyzer = GraphAnalyzer()\n",
    "\n",
    "centrality_results = graph_analyzer.calculate_centrality(\n",
    "    knowledge_graph, \n",
    "    centrality_type=\"degree\"\n",
    ")\n",
    "\n",
    "centrality_scores = {}\n",
    "if centrality_results and \"centrality_measures\" in centrality_results:\n",
    "    degree_centrality = centrality_results[\"centrality_measures\"].get(\"degree\", {})\n",
    "    if isinstance(degree_centrality, dict) and \"centrality\" in degree_centrality:\n",
    "        centrality_scores = degree_centrality[\"centrality\"]\n",
    "    elif isinstance(degree_centrality, dict):\n",
    "        centrality_scores = degree_centrality\n",
    "\n",
    "communities_result = graph_analyzer.detect_communities(\n",
    "    knowledge_graph, \n",
    "    algorithm=\"louvain\"\n",
    ")\n",
    "\n",
    "communities = []\n",
    "community_dict = {}\n",
    "if communities_result and \"communities\" in communities_result:\n",
    "    communities_data = communities_result[\"communities\"]\n",
    "    if isinstance(communities_data, list):\n",
    "        communities = communities_data\n",
    "        for idx, community in enumerate(communities):\n",
    "            if isinstance(community, list):\n",
    "                for node in community:\n",
    "                    community_dict[node] = idx\n",
    "            elif isinstance(community, dict) and \"nodes\" in community:\n",
    "                for node in community[\"nodes\"]:\n",
    "                    community_dict[node] = idx\n",
    "\n",
    "analytics_visualizer = AnalyticsVisualizer()\n",
    "analytics_visualizer.visualize_centrality(centrality_scores, title=\"Node Centrality Scores\")\n",
    "\n",
    "if community_dict:\n",
    "    analytics_visualizer.visualize_communities(\n",
    "        knowledge_graph, \n",
    "        community_dict, \n",
    "        title=\"Community Detection\"\n",
    "    )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Temporal Data Visualization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "temporal_kg = {\n",
    "    \"entities\": entities,\n",
    "    \"relationships\": relationships,\n",
    "    \"timestamps\": {\n",
    "        \"e1\": [2020, 2021, 2022],\n",
    "        \"e2\": [2020, 2021],\n",
    "        \"e3\": [2010, 2015, 2020, 2022],\n",
    "    }\n",
    "}\n",
    "\n",
    "entity_history = {\n",
    "    \"e1\": [\n",
    "        {\"timestamp\": 2020, \"properties\": {\"age\": 28}},\n",
    "        {\"timestamp\": 2021, \"properties\": {\"age\": 29}},\n",
    "        {\"timestamp\": 2022, \"properties\": {\"age\": 30}},\n",
    "    ]\n",
    "}\n",
    "\n",
    "from semantica.kg import TemporalVersionManager\n",
    "temporal_visualizer = TemporalVisualizer()\n",
    "temporal_visualizer.visualize_timeline(temporal_kg, output=\"interactive\")\n",
    "# Convert entity history to metrics for visualization\n",
    "timestamps = [str(item[\"timestamp\"]) for item in entity_history[\"e1\"]]\n",
    "age_values = [item[\"properties\"][\"age\"] for item in entity_history[\"e1\"]]\n",
    "metrics_history = {\"age\": age_values}\n",
    "temporal_visualizer.visualize_metrics_evolution(metrics_history, timestamps, output=\"interactive\")\n",
    "\n",
    "# Create versions for snapshot comparison\n",
    "version_manager = TemporalVersionManager()\n",
    "v1 = version_manager.create_version(temporal_kg, timestamp=\"2020-01-01\", version_label=\"v2020\")\n",
    "temporal_kg_v2 = {\n",
    "    \"entities\": temporal_kg.get(\"entities\", []),\n",
    "    \"relationships\": temporal_kg.get(\"relationships\", []) + [\n",
    "        {\"source\": \"e1\", \"target\": \"e2\", \"type\": \"collaborated_with\", \"valid_from\": \"2023-01-01\"}\n",
    "    ]\n",
    "}\n",
    "v2 = version_manager.create_version(temporal_kg_v2, timestamp=\"2023-01-01\", version_label=\"v2023\")\n",
    "snapshots = {v1[\"timestamp\"]: v1, v2[\"timestamp\"]: v2}\n",
    "temporal_visualizer.visualize_snapshot_comparison(snapshots, output=\"interactive\")\n",
    "version_history = [\n",
    "    {\"version\": v1.get(\"label\"), \"timestamp\": v1.get(\"timestamp\")},\n",
    "    {\"version\": v2.get(\"label\"), \"timestamp\": v2.get(\"timestamp\")}\n",
    "]\n",
    "temporal_visualizer.visualize_version_history(version_history, output=\"interactive\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "All visualization types demonstrated:\n",
    "- Knowledge Graph Visualization\n",
    "- Embedding Visualization (t-SNE)\n",
    "- Quality Metrics Visualization\n",
    "- Graph Analytics Visualization (Centrality & Communities)\n",
    "- Temporal Data Visualization (Timeline & Evolution)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
