{
 "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/supply_chain/02_Supply_Chain_Risk_Management.ipynb)\n",
    "\n",
    "# Supply Chain Risk Management with Semantica\n",
    "\n",
    "## Overview\n",
    "\n",
    "This notebook demonstrates using **Semantica as the core framework** to transform supply chains into dynamic, interconnected networks for real-time visualization, analysis, and proactive risk management.\n",
    "\n",
    "\n",
    "**Documentation**: [API Reference](https://semantica.readthedocs.io/use-cases/)\n",
    "\n",
    "### Why Semantica?\n",
    "\n",
    "Semantica provides comprehensive graph technology capabilities essential for supply chain risk management:\n",
    "\n",
    "- **Graph Modeling**: Semantica's KG modules naturally model complex supply chain relationships and dependencies\n",
    "- **Real-Time Analysis**: Semantica's GraphAnalyzer enables real-time network analysis and risk assessment\n",
    "- **Cascade Effect Analysis**: Semantica's ConnectivityAnalyzer identifies how disruptions cascade through networks\n",
    "- **Graph Algorithms**: Semantica's graph analytics provide betweenness centrality for alternative sourcing identification\n",
    "- **Risk Clustering**: Semantica's community detection identifies supplier risk clusters\n",
    "- **Visualization**: Semantica's visualization modules provide real-time supply chain network visualization\n",
    "\n",
    "### Key Features\n",
    "\n",
    "- Graph modeling of complex supply chain relationships and dependencies using Semantica\n",
    "- Real-time visualization of supply chain networks\n",
    "- Risk analysis for tariffs, extreme weather, component shortages\n",
    "- Cascade effect analysis through network\n",
    "- Alternative sourcing identification using Semantica's graph algorithms (betweenness centrality)\n",
    "- Product redesign impact modeling\n",
    "- Supplier risk clustering\n",
    "\n",
    "### Semantica Modules Used (15+)\n",
    "\n",
    "- **Ingest**: FileIngestor, WebIngestor, FeedIngestor, StreamIngestor, DBIngestor, RepoIngestor, EmailIngestor, MCPIngestor (supply chain data from multiple sources)\n",
    "- **Parse**: StructuredDataParser, JSONParser, CSVParser (BOM data, supplier data, tariff data)\n",
    "- **Normalize**: TextNormalizer, DataNormalizer (for data standardization)\n",
    "- **Semantic Extract**: RelationExtractor, TripleExtractor (supplier relationships, dependencies, risk factors)\n",
    "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (supply chain graph construction)\n",
    "- **Graph Analytics**: Use Semantica's GraphAnalyzer for community detection, centrality measures (PageRank, Betweenness, Closeness)\n",
    "- **Embeddings**: EmbeddingGenerator (for supplier similarity, risk clustering)\n",
    "- **Vector Store**: VectorStore, HybridSearch (for supplier search and risk analysis)\n",
    "- **Reasoning**: InferenceEngine, RuleManager (for risk propagation rules, tariff impact analysis)\n",
    "- **Seed**: SeedDataManager (for loading supplier master data)\n",
    "- **Visualization**: KGVisualizer, AnalyticsVisualizer, QualityVisualizer (network visualization, risk heatmaps, supply chain dashboards)\n",
    "- **Export**: JSONExporter, CSVExporter, ReportGenerator (for risk reports)\n",
    "- **Pipeline**: PipelineBuilder, ExecutionEngine (for end-to-end supply chain analysis pipeline)\n",
    "\n",
    "### Pipeline Overview\n",
    "\n",
    "**Supply Chain Data \u2192 Parse \u2192 Extract Relationships \u2192 Build Supply Chain Graph \u2192 Analyze Risks \u2192 Identify Alternatives \u2192 Visualize \u2192 Generate Reports**\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: Setup and Import Semantica Modules\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import all Semantica modules - using Semantica as the core framework\n",
    "from semantica.ingest import FileIngestor, DBIngestor, WebIngestor, StreamIngestor\n",
    "from semantica.parse import StructuredDataParser, JSONParser, CSVParser\n",
    "from semantica.normalize import TextNormalizer, DataNormalizer\n",
    "from semantica.semantic_extract import RelationExtractor, TripleExtractor\n",
    "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
    "from semantica.embeddings import EmbeddingGenerator\n",
    "from semantica.vector_store import VectorStore, HybridSearch\n",
    "from semantica.reasoning import InferenceEngine, RuleManager\n",
    "from semantica.seed import SeedDataManager\n",
    "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, QualityVisualizer\n",
    "from semantica.export import JSONExporter, CSVExporter, ReportGenerator\n",
    "from semantica.pipeline import PipelineBuilder, ExecutionEngine\n",
    "\n",
    "import tempfile\n",
    "import os\n",
    "import json\n",
    "from datetime import datetime, timedelta\n",
    "import numpy as np\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Ingest Supply Chain Data Using Semantica\n",
    "\n",
    "Using Semantica's ingest modules to load supply chain data including BOM (Bill of Materials), supplier information, and tariff data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica ingestors\n",
    "file_ingestor = FileIngestor()\n",
    "db_ingestor = DBIngestor()\n",
    "web_ingestor = WebIngestor()\n",
    "stream_ingestor = StreamIngestor()\n",
    "seed_loader = SeedDataManager()\n",
    "\n",
    "# Create temporary directory for sample data\n",
    "temp_dir = tempfile.mkdtemp()\n",
    "\n",
    "# Sample BOM (Bill of Materials) data\n",
    "bom_data = {\n",
    "    \"product_id\": \"PROD-001\",\n",
    "    \"product_name\": \"Electronic Device\",\n",
    "    \"components\": [\n",
    "        {\"component_id\": \"COMP-001\", \"name\": \"Processor\", \"supplier_id\": \"SUP-001\", \"quantity\": 1},\n",
    "        {\"component_id\": \"COMP-002\", \"name\": \"Memory\", \"supplier_id\": \"SUP-002\", \"quantity\": 2},\n",
    "        {\"component_id\": \"COMP-003\", \"name\": \"Display\", \"supplier_id\": \"SUP-003\", \"quantity\": 1},\n",
    "        {\"component_id\": \"COMP-004\", \"name\": \"Battery\", \"supplier_id\": \"SUP-001\", \"quantity\": 1}\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Sample supplier data\n",
    "supplier_data = {\n",
    "    \"suppliers\": [\n",
    "        {\n",
    "            \"supplier_id\": \"SUP-001\",\n",
    "            \"name\": \"Global Electronics Inc\",\n",
    "            \"location\": \"China\",\n",
    "            \"risk_factors\": [\"tariff_impact\", \"weather_risk\"],\n",
    "            \"alternatives\": [\"SUP-005\", \"SUP-006\"]\n",
    "        },\n",
    "        {\n",
    "            \"supplier_id\": \"SUP-002\",\n",
    "            \"name\": \"Memory Solutions Ltd\",\n",
    "            \"location\": \"South Korea\",\n",
    "            \"risk_factors\": [\"tariff_impact\"],\n",
    "            \"alternatives\": [\"SUP-007\"]\n",
    "        },\n",
    "        {\n",
    "            \"supplier_id\": \"SUP-003\",\n",
    "            \"name\": \"Display Tech Corp\",\n",
    "            \"location\": \"Taiwan\",\n",
    "            \"risk_factors\": [\"weather_risk\"],\n",
    "            \"alternatives\": [\"SUP-008\"]\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Sample tariff data\n",
    "tariff_data = {\n",
    "    \"tariffs\": [\n",
    "        {\n",
    "            \"tariff_id\": \"TAR-001\",\n",
    "            \"country\": \"China\",\n",
    "            \"category\": \"Electronics\",\n",
    "            \"rate\": 0.25,\n",
    "            \"effective_date\": \"2025-01-01\",\n",
    "            \"impacted_suppliers\": [\"SUP-001\"]\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Save sample data\n",
    "bom_file = os.path.join(temp_dir, \"bom.json\")\n",
    "supplier_file = os.path.join(temp_dir, \"suppliers.json\")\n",
    "tariff_file = os.path.join(temp_dir, \"tariffs.json\")\n",
    "\n",
    "with open(bom_file, 'w') as f:\n",
    "    json.dump(bom_data, f, indent=2)\n",
    "\n",
    "with open(supplier_file, 'w') as f:\n",
    "    json.dump(supplier_data, f, indent=2)\n",
    "\n",
    "with open(tariff_file, 'w') as f:\n",
    "    json.dump(tariff_data, f, indent=2)\n",
    "\n",
    "# Ingest using Semantica FileIngestor\n",
    "bom_file_obj = file_ingestor.ingest_file(bom_file, read_content=True)\n",
    "supplier_file_obj = file_ingestor.ingest_file(supplier_file, read_content=True)\n",
    "tariff_file_obj = file_ingestor.ingest_file(tariff_file, read_content=True)\n",
    "\n",
    "# Load supplier master data using Semantica SeedDataManager\n",
    "supplier_seed_data = seed_loader.load_from_json(supplier_file)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica parsers and normalizers\n",
    "structured_parser = StructuredDataParser()\n",
    "json_parser = JSONParser()\n",
    "csv_parser = CSVParser()\n",
    "text_normalizer = TextNormalizer()\n",
    "data_normalizer = DataNormalizer()\n",
    "\n",
    "# Parse BOM data using Semantica\n",
    "parsed_bom = structured_parser.parse_data(bom_file, data_format=\"json\")\n",
    "bom_data_parsed = parsed_bom.get(\"data\") if isinstance(parsed_bom, dict) else parsed_bom\n",
    "\n",
    "# Parse supplier data using Semantica\n",
    "parsed_suppliers = structured_parser.parse_data(supplier_file, data_format=\"json\")\n",
    "supplier_data_parsed = parsed_suppliers.get(\"data\") if isinstance(parsed_suppliers, dict) else parsed_suppliers\n",
    "\n",
    "# Parse tariff data using Semantica\n",
    "parsed_tariffs = structured_parser.parse_data(tariff_file, data_format=\"json\")\n",
    "tariff_data_parsed = parsed_tariffs.get(\"data\") if isinstance(parsed_tariffs, dict) else parsed_tariffs\n",
    "\n",
    "# Normalize supplier names using Semantica\n",
    "if isinstance(supplier_data_parsed, dict):\n",
    "    for supplier in supplier_data_parsed.get('suppliers', []):\n",
    "        supplier['normalized_name'] = text_normalizer.normalize_text(supplier.get('name', ''))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Extract Supply Chain Relationships Using Semantica\n",
    "\n",
    "Using Semantica's semantic extraction modules to extract supplier relationships, dependencies, and risk factors.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica extractors\n",
    "relation_extractor = RelationExtractor()\n",
    "triple_extractor = TripleExtractor()\n",
    "\n",
    "# Build supply chain entities and relationships\n",
    "supply_chain_entities = []\n",
    "supply_chain_relationships = []\n",
    "\n",
    "# Add product entity\n",
    "if isinstance(bom_data_parsed, dict):\n",
    "    supply_chain_entities.append({\n",
    "        \"id\": bom_data_parsed.get('product_id', ''),\n",
    "        \"type\": \"Product\",\n",
    "        \"name\": bom_data_parsed.get('product_name', ''),\n",
    "        \"properties\": {}\n",
    "    })\n",
    "\n",
    "# Add component entities and relationships\n",
    "if isinstance(bom_data_parsed, dict):\n",
    "    for component in bom_data_parsed.get('components', []):\n",
    "        supply_chain_entities.append({\n",
    "            \"id\": component.get('component_id', ''),\n",
    "            \"type\": \"Component\",\n",
    "            \"name\": component.get('name', ''),\n",
    "            \"properties\": {\n",
    "                \"quantity\": component.get('quantity', 0)\n",
    "            }\n",
    "        })\n",
    "        \n",
    "        # Product-Component relationship\n",
    "        supply_chain_relationships.append({\n",
    "            \"source\": bom_data_parsed.get('product_id', ''),\n",
    "            \"target\": component.get('component_id', ''),\n",
    "            \"type\": \"contains\",\n",
    "            \"properties\": {\n",
    "                \"quantity\": component.get('quantity', 0)\n",
    "            }\n",
    "        })\n",
    "        \n",
    "        # Component-Supplier relationship\n",
    "        supply_chain_relationships.append({\n",
    "            \"source\": component.get('component_id', ''),\n",
    "            \"target\": component.get('supplier_id', ''),\n",
    "            \"type\": \"supplied_by\",\n",
    "            \"properties\": {}\n",
    "        })\n",
    "\n",
    "# Add supplier entities\n",
    "if isinstance(supplier_data_parsed, dict):\n",
    "    for supplier in supplier_data_parsed.get('suppliers', []):\n",
    "        supply_chain_entities.append({\n",
    "            \"id\": supplier.get('supplier_id', ''),\n",
    "            \"type\": \"Supplier\",\n",
    "            \"name\": supplier.get('name', ''),\n",
    "            \"properties\": {\n",
    "                \"location\": supplier.get('location', ''),\n",
    "                \"risk_factors\": supplier.get('risk_factors', [])\n",
    "            }\n",
    "        })\n",
    "        \n",
    "        # Alternative supplier relationships\n",
    "        for alt_supplier in supplier.get('alternatives', []):\n",
    "            supply_chain_relationships.append({\n",
    "                \"source\": supplier.get('supplier_id', ''),\n",
    "                \"target\": alt_supplier,\n",
    "                \"type\": \"alternative_to\",\n",
    "                \"properties\": {}\n",
    "            })\n",
    "\n",
    "# Add tariff entities and relationships\n",
    "if isinstance(tariff_data_parsed, dict):\n",
    "    for tariff in tariff_data_parsed.get('tariffs', []):\n",
    "        supply_chain_entities.append({\n",
    "            \"id\": tariff.get('tariff_id', ''),\n",
    "            \"type\": \"Tariff\",\n",
    "            \"name\": f\"Tariff {tariff.get('country', '')}\",\n",
    "            \"properties\": {\n",
    "                \"rate\": tariff.get('rate', 0),\n",
    "                \"effective_date\": tariff.get('effective_date', '')\n",
    "            }\n",
    "        })\n",
    "        \n",
    "        # Tariff-Supplier relationship\n",
    "        for supplier_id in tariff.get('impacted_suppliers', []):\n",
    "            supply_chain_relationships.append({\n",
    "                \"source\": tariff.get('tariff_id', ''),\n",
    "                \"target\": supplier_id,\n",
    "                \"type\": \"impacts\",\n",
    "                \"properties\": {\n",
    "                    \"impact_type\": \"tariff\"\n",
    "                }\n",
    "            })\n",
    "\n",
    "print(f\"  - Products: {len([e for e in supply_chain_entities if e.get('type') == 'Product'])}\")\n",
    "print(f\"  - Components: {len([e for e in supply_chain_entities if e.get('type') == 'Component'])}\")\n",
    "print(f\"  - Suppliers: {len([e for e in supply_chain_entities if e.get('type') == 'Supplier'])}\")\n",
    "print(f\"  - Tariffs: {len([e for e in supply_chain_entities if e.get('type') == 'Tariff'])}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5: Build Supply Chain Knowledge Graph Using Semantica\n",
    "\n",
    "Using Semantica's KG modules to build a supply chain knowledge graph.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica KG builders and analyzers\n",
    "graph_builder = GraphBuilder()\n",
    "graph_analyzer = GraphAnalyzer()\n",
    "connectivity_analyzer = ConnectivityAnalyzer()\n",
    "\n",
    "# Build supply chain knowledge graph using Semantica\n",
    "supply_chain_kg = graph_builder.build(supply_chain_entities, supply_chain_relationships)\n",
    "\n",
    "# Analyze the graph using Semantica\n",
    "kg_metrics = graph_analyzer.compute_metrics(supply_chain_kg)\n",
    "connectivity = connectivity_analyzer.analyze_connectivity(supply_chain_kg)\n",
    "\n",
    "print(f\"  - Entities: {len(supply_chain_kg.get('entities', []))}\")\n",
    "print(f\"  - Relationships: {len(supply_chain_kg.get('relationships', []))}\")\n",
    "print(f\"  - Graph density: {kg_metrics.get('density', 0):.4f}\")\n",
    "print(f\"  - Connected components: {connectivity.get('num_components', 0)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6: Analyze Supply Chain Risks Using Semantica Graph Analytics\n",
    "\n",
    "Using Semantica's GraphAnalyzer to perform risk analysis including community detection, centrality measures, and cascade effect analysis.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Perform graph analytics using Semantica\n",
    "\n",
    "# 1. Community detection for supplier risk clustering\n",
    "communities = graph_analyzer.detect_communities(supply_chain_kg, method=\"louvain\")\n",
    "\n",
    "# 2. Centrality measures for alternative sourcing identification\n",
    "pagerank_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"pagerank\")\n",
    "betweenness_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"betweenness\")\n",
    "closeness_centrality = graph_analyzer.compute_centrality(supply_chain_kg, method=\"closeness\")\n",
    "\n",
    "# 3. Identify critical suppliers (high betweenness = alternative sourcing options)\n",
    "critical_suppliers = sorted(\n",
    "    [(node, score) for node, score in betweenness_centrality.items() if node.startswith('SUP-')],\n",
    "    key=lambda x: x[1],\n",
    "    reverse=True\n",
    ")[:5]\n",
    "\n",
    "# 4. Cascade effect analysis - identify suppliers at risk\n",
    "at_risk_suppliers = []\n",
    "for entity in supply_chain_entities:\n",
    "    if entity.get('type') == 'Supplier':\n",
    "        risk_factors = entity.get('properties', {}).get('risk_factors', [])\n",
    "        if risk_factors:\n",
    "            at_risk_suppliers.append({\n",
    "                \"supplier_id\": entity.get('id'),\n",
    "                \"supplier_name\": entity.get('name'),\n",
    "                \"risk_factors\": risk_factors,\n",
    "                \"betweenness_centrality\": betweenness_centrality.get(entity.get('id'), 0)\n",
    "            })\n",
    "\n",
    "print(f\"  - Communities detected: {communities.get('num_communities', 0)}\")\n",
    "print(f\"  - Critical suppliers (high betweenness): {len(critical_suppliers)}\")\n",
    "print(f\"  - At-risk suppliers: {len(at_risk_suppliers)}\")\n",
    "print(f\"\\nTop Critical Suppliers (Alternative Sourcing Options):\")\n",
    "for supplier_id, score in critical_suppliers:\n",
    "    supplier_name = next((e.get('name', '') for e in supply_chain_entities if e.get('id') == supplier_id), 'Unknown')\n",
    "    print(f\"  - {supplier_name} ({supplier_id}): {score:.4f}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 7: Implement Risk Propagation Rules Using Semantica Reasoning\n",
    "\n",
    "Using Semantica's reasoning modules to implement risk propagation rules for tariff impacts and cascade effects.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica reasoning modules\n",
    "inference_engine = InferenceEngine()\n",
    "rule_manager = RuleManager()\n",
    "\n",
    "# Define risk propagation rules using Semantica\n",
    "risk_rules = [\n",
    "    {\n",
    "        \"rule_id\": \"tariff_impact_rule\",\n",
    "        \"condition\": \"IF supplier has tariff_impact AND supplier supplies component THEN component has cost_increase\",\n",
    "        \"action\": \"propagate_cost_increase\"\n",
    "    },\n",
    "    {\n",
    "        \"rule_id\": \"cascade_effect_rule\",\n",
    "        \"condition\": \"IF supplier has risk_factor AND supplier is critical THEN product has supply_risk\",\n",
    "        \"action\": \"flag_supply_risk\"\n",
    "    },\n",
    "    {\n",
    "        \"rule_id\": \"alternative_sourcing_rule\",\n",
    "        \"condition\": \"IF supplier has high_betweenness_centrality THEN supplier is alternative_sourcing_option\",\n",
    "        \"action\": \"identify_alternative\"\n",
    "    }\n",
    "]\n",
    "\n",
    "# Add rules using Semantica\n",
    "for rule in risk_rules:\n",
    "    rule_manager.add_rule(rule)\n",
    "\n",
    "# Apply risk propagation using Semantica InferenceEngine\n",
    "risk_analysis_results = inference_engine.infer(\n",
    "    knowledge_graph=supply_chain_kg,\n",
    "    rules=risk_rules,\n",
    "    facts=at_risk_suppliers\n",
    ")\n",
    "\n",
    "print(f\"  - Rules defined: {len(risk_rules)}\")\n",
    "print(f\"  - Risk analysis results: {len(risk_analysis_results) if isinstance(risk_analysis_results, list) else 1}\")\n",
    "print(f\"  - Cascade effects identified: Enabled\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica visualizers\n",
    "kg_visualizer = KGVisualizer(layout=\"force\", color_scheme=\"vibrant\")\n",
    "analytics_visualizer = AnalyticsVisualizer()\n",
    "quality_visualizer = QualityVisualizer()\n",
    "\n",
    "# Visualize supply chain network using Semantica\n",
    "network_fig = kg_visualizer.visualize_network(\n",
    "    supply_chain_kg,\n",
    "    output=\"interactive\"\n",
    ")\n",
    "\n",
    "# Visualize communities (supplier risk clusters) using Semantica\n",
    "communities_data = {\n",
    "    \"graph\": supply_chain_kg,\n",
    "    \"communities\": communities\n",
    "}\n",
    "communities_fig = kg_visualizer.visualize_communities(\n",
    "    supply_chain_kg,\n",
    "    communities,\n",
    "    output=\"interactive\"\n",
    ")\n",
    "\n",
    "# Visualize centrality rankings using Semantica\n",
    "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",
    "    betweenness_centrality,\n",
    "    centrality_type=\"betweenness\",\n",
    "    top_n=10,\n",
    "    output=\"interactive\"\n",
    ")\n",
    "\n",
    "# Create risk dashboard data\n",
    "risk_dashboard_data = {\n",
    "    \"overall_score\": 0.75,\n",
    "    \"tariff_risk_score\": 0.80,\n",
    "    \"weather_risk_score\": 0.60,\n",
    "    \"supply_risk_score\": 0.70\n",
    "}\n",
    "\n",
    "# Visualize risk dashboard using Semantica\n",
    "risk_dashboard_fig = quality_visualizer.visualize_dashboard(\n",
    "    risk_dashboard_data,\n",
    "    output=\"interactive\"\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 9: Generate Risk Reports Using Semantica\n",
    "\n",
    "Using Semantica's export modules to generate comprehensive risk reports.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Semantica exporters\n",
    "json_exporter = JSONExporter()\n",
    "csv_exporter = CSVExporter()\n",
    "report_generator = ReportGenerator()\n",
    "\n",
    "# Export supply chain graph as JSON using Semantica\n",
    "kg_json_file = os.path.join(temp_dir, \"supply_chain_kg.json\")\n",
    "json_exporter.export(supply_chain_kg, kg_json_file)\n",
    "\n",
    "# Export at-risk suppliers as CSV using Semantica\n",
    "at_risk_suppliers_csv = os.path.join(temp_dir, \"at_risk_suppliers.csv\")\n",
    "csv_exporter.export(at_risk_suppliers, at_risk_suppliers_csv)\n",
    "\n",
    "# Generate comprehensive risk report using Semantica\n",
    "risk_report_data = {\n",
    "    \"title\": \"Supply Chain Risk Management Report\",\n",
    "    \"knowledge_graph_metrics\": kg_metrics,\n",
    "    \"at_risk_suppliers\": at_risk_suppliers,\n",
    "    \"critical_suppliers\": critical_suppliers,\n",
    "    \"risk_analysis\": risk_analysis_results,\n",
    "    \"risk_dashboard\": risk_dashboard_data\n",
    "}\n",
    "risk_report_file = os.path.join(temp_dir, \"supply_chain_risk_report.html\")\n",
    "report_generator.generate_report(risk_report_data, risk_report_file, format=\"html\")\n",
    "\n",
    "print(f\"  - Knowledge graph JSON: {kg_json_file}\")\n",
    "print(f\"  - At-risk suppliers CSV: {at_risk_suppliers_csv}\")\n",
    "print(f\"  - Risk report HTML: {risk_report_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 10: Complete Pipeline Orchestration Using Semantica\n",
    "\n",
    "Using Semantica's pipeline module to orchestrate the complete supply chain risk analysis pipeline.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build complete pipeline using Semantica PipelineBuilder\n",
    "pipeline_builder = PipelineBuilder()\n",
    "\n",
    "def ingest_handler(data, **config):\n",
    "    source_dir = config.get(\"source\", temp_dir)\n",
    "    files = []\n",
    "    try:\n",
    "        files = [os.path.join(source_dir, f) for f in os.listdir(source_dir)]\n",
    "    except Exception:\n",
    "        pass\n",
    "    return {**data, \"files\": files}\n",
    "def parse_handler(data, **config):\n",
    "    records = []\n",
    "    files = data.get(\"files\", [])\n",
    "    for fp in files:\n",
    "        try:\n",
    "            with open(fp, \"r\", encoding=\"utf-8\") as f:\n",
    "                records.append(json.load(f))\n",
    "        except Exception:\n",
    "            pass\n",
    "    return {**data, \"records\": records}\n",
    "def normalize_handler(data, **config):\n",
    "    records = data.get(\"records\", [])\n",
    "    normalized = records\n",
    "    return {**data, \"normalized\": normalized}\n",
    "def extract_handler(data, **config):\n",
    "    normalized = data.get(\"normalized\", [])\n",
    "    entities = data.get(\"entities\") or []\n",
    "    relationships = data.get(\"relationships\") or []\n",
    "    return {**data, \"entities\": entities, \"relationships\": relationships}\n",
    "def build_kg_handler(data, **config):\n",
    "    ents = data.get(\"entities\", [])\n",
    "    rels = data.get(\"relationships\", [])\n",
    "    kg = graph_builder.build({\"entities\": ents, \"relationships\": rels})\n",
    "    return {**data, \"supply_chain_kg\": kg}\n",
    "def analyze_risks_handler(data, **config):\n",
    "    kg = data.get(\"supply_chain_kg\")\n",
    "    risks = graph_analyzer.compute_metrics(kg) if kg is not None else {}\n",
    "    return {**data, \"risk_analysis\": risks}\n",
    "def propagate_risks_handler(data, **config):\n",
    "    kg = data.get(\"supply_chain_kg\")\n",
    "    propagation = reasoning_engine.infer(knowledge_graph=kg, rules=[]) if kg is not None else {}\n",
    "    return {**data, \"risk_propagation\": propagation}\n",
    "def visualize_handler(data, **config):\n",
    "    kg = data.get(\"supply_chain_kg\")\n",
    "    fig = KGVisualizer().visualize_network(kg) if kg is not None else None\n",
    "    return {**data, \"visualization\": fig}\n",
    "def report_handler(data, **config):\n",
    "    report = ReportGenerator().generate({\"risks\": data.get(\"risk_analysis\"), \"propagation\": data.get(\"risk_propagation\")})\n",
    "    return {**data, \"report\": report}\n",
    "supply_chain_pipeline = (\n",
    "    pipeline_builder\n",
    "    .add_step(\"ingest\", \"ingest\", handler=ingest_handler, source=temp_dir)\n",
    "    .add_step(\"parse\", \"parse\", dependencies=[\"ingest\"], handler=parse_handler, formats=[\"json\"])\n",
    "    .add_step(\"normalize\", \"normalize\", dependencies=[\"parse\"], handler=normalize_handler)\n",
    "    .add_step(\"extract\", \"extract\", dependencies=[\"normalize\"], handler=extract_handler)\n",
    "    .add_step(\"build_kg\", \"build_kg\", dependencies=[\"extract\"], handler=build_kg_handler)\n",
    "    .add_step(\"analyze_risks\", \"analyze_graph\", dependencies=[\"build_kg\"], handler=analyze_risks_handler)\n",
    "    .add_step(\"propagate_risks\", \"reasoning\", dependencies=[\"build_kg\"], handler=propagate_risks_handler)\n",
    "    .add_step(\"visualize\", \"visualize\", dependencies=[\"analyze_risks\"], handler=visualize_handler)\n",
    "    .add_step(\"generate_report\", \"report\", dependencies=[\"visualize\"], handler=report_handler)\n",
    "    .build()\n",
    ")\n",
    "\n",
    "execution_engine = ExecutionEngine()\n",
    "input_data = {\"entities\": supply_chain_entities if 'supply_chain_entities' in globals() else [], \"relationships\": supply_chain_relationships if 'supply_chain_relationships' in globals() else []}\n",
    "pipeline_result = execution_engine.execute_pipeline(supply_chain_pipeline, data=input_data)\n",
    "\n",
    "print(f\"  - Pipeline steps: {len(supply_chain_pipeline.steps)}\")\n",
    "print(f\"  - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion and Best Practices\n",
    "\n",
    "### Key Takeaways\n",
    "\n",
    "1. **Semantica as Core Framework**: This notebook demonstrated using Semantica as the exclusive framework for supply chain risk management\n",
    "2. **Graph Modeling**: Semantica's KG modules naturally model complex supply chain relationships and dependencies\n",
    "3. **Risk Analysis**: Semantica's GraphAnalyzer provides powerful algorithms for risk identification and alternative sourcing\n",
    "4. **Cascade Effects**: Semantica's ConnectivityAnalyzer identifies how disruptions cascade through supply networks\n",
    "5. **Real-Time Visualization**: Semantica's visualization modules provide real-time supply chain network visualization\n",
    "6. **Risk Propagation**: Semantica's Reasoning modules enable rule-based risk propagation analysis\n",
    "\n",
    "### Semantica-Specific Performance Considerations\n",
    "\n",
    "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient centrality and community detection on large supply chains\n",
    "- **Batch Processing**: Leverage Semantica's batch processing for large-scale supplier data ingestion\n",
    "- **Caching**: Utilize Semantica's caching for frequently accessed supplier relationships\n",
    "- **Parallel Execution**: Use Semantica's ExecutionEngine for parallel risk analysis\n",
    "\n",
    "### Deployment Recommendations Using Semantica\n",
    "\n",
    "1. **Production Setup**:\n",
    "   - Use Semantica's configuration management for supply chain data sources\n",
    "   - Leverage Semantica's Pipeline module for automated risk monitoring\n",
    "   - Use Semantica's StreamIngestor for real-time supply chain data updates\n",
    "\n",
    "2. **Scalability**:\n",
    "   - Use Semantica's batch processing for large supplier networks\n",
    "   - Leverage Semantica's graph analytics optimizations\n",
    "   - Utilize Semantica's parallel execution for concurrent risk analysis\n",
    "\n",
    "3. **Real-Time Monitoring**:\n",
    "   - Use Semantica's StreamIngestor for real-time tariff and weather updates\n",
    "   - Leverage Semantica's visualization modules for live dashboards\n",
    "   - Utilize Semantica's reasoning modules for automated risk alerts\n",
    "\n",
    "### How Semantica's Architecture Benefits Supply Chain Risk Management\n",
    "\n",
    "- **Natural Graph Modeling**: Semantica's graph structure naturally represents supply chain relationships\n",
    "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms (centrality, communities, connectivity)\n",
    "- **Extensibility**: Semantica's registry system enables custom risk analysis methods\n",
    "- **Integration**: Semantica's unified framework simplifies integration with existing supply chain systems\n",
    "- **Performance**: Semantica's optimized algorithms handle large-scale supply chain networks efficiently\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}