{
 "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/advanced/03_Complete_Visualization_Suite.ipynb)\n",
    "\n",
    "# Complete Visualization Suite\n",
    "\n",
    "## Overview\n",
    "\n",
    "Comprehensive visualization capabilities: visualize knowledge graphs, embeddings, 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": [
    "!pip install -qU semantica\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantica.visualization import (\n",
    "    KGVisualizer,\n",
    "    AnalyticsVisualizer,\n",
    "    TemporalVisualizer\n",
    ")\n",
    "from semantica.kg import GraphBuilder, GraphAnalyzer\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\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: 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 5: Temporal Data Visualization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime\n",
    "from semantica.visualization import TemporalVisualizer\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# 1. Setup Data: AI Research Lab Evolution (2020-2024)\n",
    "# This dataset simulates a growing network of researchers, papers, and grants\n",
    "\n",
    "start_date = datetime.date(2020, 1, 1)\n",
    "\n",
    "# Entities with lifespans\n",
    "entities = [\n",
    "    {\"id\": \"Lab_Alpha\", \"type\": \"Organization\", \"start\": \"2020-01-01\", \"end\": \"2024-12-31\", \"properties\": {\"budget\": \"High\"}},\n",
    "    {\"id\": \"Dr_Smith\", \"type\": \"Researcher\", \"start\": \"2020-01-15\", \"end\": \"2024-12-31\", \"properties\": {\"h_index\": 15}},\n",
    "    {\"id\": \"Dr_Jones\", \"type\": \"Researcher\", \"start\": \"2020-03-01\", \"end\": \"2024-12-31\", \"properties\": {\"h_index\": 12}},\n",
    "    {\"id\": \"Paper_X\", \"type\": \"Publication\", \"start\": \"2020-11-20\", \"end\": \"2024-12-31\", \"properties\": {\"citations\": 50}},\n",
    "    {\"id\": \"Grant_A\", \"type\": \"Funding\", \"start\": \"2021-01-01\", \"end\": \"2022-12-31\", \"properties\": {\"amount\": 1000000}},\n",
    "    {\"id\": \"Dr_Chen\", \"type\": \"Researcher\", \"start\": \"2021-06-01\", \"end\": \"2024-12-31\", \"properties\": {\"h_index\": 8}},\n",
    "    {\"id\": \"Paper_Y\", \"type\": \"Publication\", \"start\": \"2022-03-15\", \"end\": \"2024-12-31\", \"properties\": {\"citations\": 25}},\n",
    "    {\"id\": \"Startup_Beta\", \"type\": \"SpinOff\", \"start\": \"2023-01-01\", \"end\": \"2024-12-31\", \"properties\": {\"valuation\": \"5M\"}},\n",
    "]\n",
    "\n",
    "# Relationships with timestamps\n",
    "relationships = [\n",
    "    {\"source\": \"Dr_Smith\", \"target\": \"Lab_Alpha\", \"type\": \"WORKS_AT\", \"timestamp\": \"2020-01-15\"},\n",
    "    {\"source\": \"Dr_Jones\", \"target\": \"Lab_Alpha\", \"type\": \"WORKS_AT\", \"timestamp\": \"2020-03-01\"},\n",
    "    {\"source\": \"Dr_Smith\", \"target\": \"Paper_X\", \"type\": \"AUTHORED\", \"timestamp\": \"2020-11-20\"},\n",
    "    {\"source\": \"Dr_Jones\", \"target\": \"Paper_X\", \"type\": \"AUTHORED\", \"timestamp\": \"2020-11-20\"},\n",
    "    {\"source\": \"Lab_Alpha\", \"target\": \"Grant_A\", \"type\": \"RECEIVED\", \"timestamp\": \"2021-01-01\"},\n",
    "    {\"source\": \"Dr_Chen\", \"target\": \"Lab_Alpha\", \"type\": \"WORKS_AT\", \"timestamp\": \"2021-06-01\"},\n",
    "    {\"source\": \"Dr_Chen\", \"target\": \"Paper_Y\", \"type\": \"AUTHORED\", \"timestamp\": \"2022-03-15\"},\n",
    "    {\"source\": \"Dr_Smith\", \"target\": \"Paper_Y\", \"type\": \"AUTHORED\", \"timestamp\": \"2022-03-15\"},\n",
    "    {\"source\": \"Lab_Alpha\", \"target\": \"Startup_Beta\", \"type\": \"SPUN_OFF\", \"timestamp\": \"2023-01-01\"},\n",
    "    {\"source\": \"Dr_Jones\", \"target\": \"Startup_Beta\", \"type\": \"CTO\", \"timestamp\": \"2023-02-01\"},\n",
    "]\n",
    "\n",
    "# Metrics over time\n",
    "dates = pd.date_range(start=\"2020-01-01\", end=\"2024-01-01\", freq=\"M\")\n",
    "metrics = {\n",
    "    \"dates\": [d.strftime(\"%Y-%m-%d\") for d in dates],\n",
    "    \"funding_usd\": [100000 + (i * 50000) + (np.random.randint(-10000, 10000)) for i in range(len(dates))],\n",
    "    \"team_size\": [2 + int(i/5) for i in range(len(dates))],\n",
    "    \"publications\": [int(i/4) for i in range(len(dates))]\n",
    "}\n",
    "\n",
    "# 4. Generate Timestamps Map (Required for TemporalVisualizer)\n",
    "# This maps each entity to the specific time points where it is \"active\" or relevant\n",
    "timestamps = {}\n",
    "\n",
    "# Collect all relevant dates (monthly granularity)\n",
    "all_dates = [d.strftime(\"%Y-%m-%d\") for d in dates]\n",
    "\n",
    "for entity in entities:\n",
    "    eid = entity[\"id\"]\n",
    "    start = entity.get(\"start\")\n",
    "    end = entity.get(\"end\")\n",
    "    \n",
    "    # In a real app, you'd calculate overlap. Here we'll just assign all dates \n",
    "    # that fall within the entity's lifespan\n",
    "    entity_times = [d for d in all_dates if start <= d <= end]\n",
    "    timestamps[eid] = entity_times\n",
    "    \n",
    "temporal_kg = {\n",
    "    \"entities\": entities,\n",
    "    \"relationships\": relationships,\n",
    "    \"metrics\": metrics,\n",
    "    \"timestamps\": timestamps\n",
    "}\n",
    "\n",
    "# 2. Initialize Visualizer\n",
    "viz = TemporalVisualizer()\n",
    "\n",
    "print(\"1. Generating Temporal Dashboard...\")\n",
    "# This creates a combined view of lifecycles, activity, and metrics\n",
    "dashboard = viz.visualize_temporal_dashboard(\n",
    "    temporal_kg,\n",
    "    title=\"AI Research Lab Evolution (2020-2024)\",\n",
    "    output=\"interactive\"\n",
    ")\n",
    "dashboard.show()\n",
    "\n",
    "print(\"2. Generating Network Evolution Animation...\")\n",
    "# This creates a playable animation of the network graph\n",
    "animation = viz.visualize_network_evolution(\n",
    "    temporal_kg,\n",
    "    title=\"Network Growth Over Time\",\n",
    "    output=\"interactive\"\n",
    ")\n",
    "animation.show()\n",
    "\n",
    "print(\"3. Generating Timeline View...\")\n",
    "timeline = viz.visualize_timeline(\n",
    "    temporal_kg,\n",
    "    title=\"Entity Lifecycles\",\n",
    "    output=\"interactive\"\n",
    ")\n",
    "timeline.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "All visualization types demonstrated:\n",
    "- Knowledge Graph Visualization\n",
    "- Embedding Visualization (t-SNE)\n",
    "- Graph Analytics Visualization (Centrality & Communities)\n",
    "- Temporal Data Visualization (Timeline & Evolution)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
