Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Add three comprehensive use case notebooks to cookbook

KaifAhmad1112a4126e292
diff --git a/cookbook/use_cases/healthcare/Healthcare_GraphRAG_Hybrid.ipynb b/cookbook/use_cases/healthcare/Healthcare_GraphRAG_Hybrid.ipynb
new file mode 100644
index 00000000..4f505291
--- /dev/null
+++ b/cookbook/use_cases/healthcare/Healthcare_GraphRAG_Hybrid.ipynb
@@ -0,0 +1,810 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Healthcare GraphRAG System with Semantica\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates building a **Retrieval-Augmented Generation (GraphRAG) system** using **Semantica as the core framework** that leverages heterogeneous healthcare resources through a combination of materialized knowledge graphs and virtually integrated data sources.\n",
+ "\n",
+ "### Why Semantica?\n",
+ "\n",
+ "Semantica provides a comprehensive, unified framework for building GraphRAG systems in healthcare:\n",
+ "\n",
+ "- **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies, clinical documents, and reports\n",
+ "- **Virtual Data Integration**: Semantica's DBIngestor and QueryEngine allow virtual integration with Electronic Health Records (EHRs) without data replication\n",
+ "- **Hybrid Design**: Semantica's architecture naturally separates structural knowledge from patient-level data\n",
+ "- **Dynamic Query Orchestration**: Semantica's Reasoning and Triple Store modules enable orchestration of queries across ontologies, documents, and EHRs\n",
+ "- **Temporal & Semantic Dimensions**: Semantica's Temporal and Context modules provide historical analysis and semantic understanding\n",
+ "- **Traceable & Explainable**: Semantica's ExplanationGenerator and ContextRetriever provide traceable, explainable answers\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- Materialized knowledge graphs from medical ontologies (SNOMED CT, ICD-10), clinical documents, and reports\n",
+ "- Virtual integration with Electronic Health Records (EHRs) without data replication\n",
+ "- Hybrid design separating structural knowledge from patient-level data\n",
+ "- Dynamic orchestration of queries across ontologies, documents, and EHRs using Semantica\n",
+ "- Temporal and semantic dimensions via graph for historical analysis\n",
+ "- Traceable, explainable, and historically contextualized answers\n",
+ "\n",
+ "### Semantica Modules Used (20+)\n",
+ "\n",
+ "- **Ingest**: FileIngestor, DBIngestor (for EHR virtual connections), WebIngestor (for medical literature)\n",
+ "- **Parse**: DocumentParser, PDFParser (clinical documents), StructuredDataParser (for structured medical data)\n",
+ "- **Normalize**: TextNormalizer (for text normalization)\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor (medical entities and relationships)\n",
+ "- **Ontology**: OntologyGenerator, OWLGenerator (medical ontologies like SNOMED CT, ICD-10)\n",
+ "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (materialized knowledge graph)\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder (for embeddings)\n",
+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter (for RAG)\n",
+ "- **Triple Store**: TripleManager, QueryEngine (for SPARQL queries on ontologies)\n",
+ "- **Reasoning**: InferenceEngine, RuleManager (for query orchestration and medical reasoning)\n",
+ "- **Context**: ContextRetriever, ContextGraphBuilder (for contextual retrieval)\n",
+ "- **Visualization**: KGVisualizer, TemporalVisualizer, AnalyticsVisualizer (for visualization)\n",
+ "- **Export**: JSONExporter, RDFExporter, ReportGenerator\n",
+ "- **Pipeline**: PipelineBuilder, ExecutionEngine (for orchestrating the complete pipeline)\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "**Medical Ontologies + Clinical Documents + EHRs (Virtual) → Parse → Extract Medical Entities → Build Materialized KG → Generate Embeddings → Vector Store → GraphRAG Setup → Query Orchestration → Generate Answers → Visualize & Export**\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\n",
+ "from semantica.parse import DocumentParser, PDFParser, StructuredDataParser\n",
+ "from semantica.normalize import TextNormalizer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor\n",
+ "from semantica.ontology import OntologyGenerator, OWLGenerator\n",
+ "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
+ "from semantica.triple_store import TripleManager, QueryEngine\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.context import ContextRetriever, ContextGraphBuilder\n",
+ "from semantica.visualization import KGVisualizer, TemporalVisualizer, AnalyticsVisualizer\n",
+ "from semantica.export import JSONExporter, RDFExporter, 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",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Using Semantica as the core framework for Healthcare GraphRAG\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Medical Ontologies and Clinical Documents\n",
+ "\n",
+ "Using Semantica's ingest modules to load medical ontologies, clinical documents, and set up virtual connections to EHRs.\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",
+ "\n",
+ "# Create temporary directory for sample data\n",
+ "temp_dir = tempfile.mkdtemp()\n",
+ "\n",
+ "# Sample medical ontology data (SNOMED CT concepts)\n",
+ "snomed_data = {\n",
+ " \"concepts\": [\n",
+ " {\n",
+ " \"concept_id\": \"73211009\",\n",
+ " \"concept_name\": \"Diabetes mellitus\",\n",
+ " \"hierarchy\": \"Clinical finding\",\n",
+ " \"parent_concept\": \"Disorder of glucose metabolism\"\n",
+ " },\n",
+ " {\n",
+ " \"concept_id\": \"44054006\",\n",
+ " \"concept_name\": \"Type 2 diabetes mellitus\",\n",
+ " \"hierarchy\": \"Clinical finding\",\n",
+ " \"parent_concept\": \"Diabetes mellitus\"\n",
+ " },\n",
+ " {\n",
+ " \"concept_id\": \"46635009\",\n",
+ " \"concept_name\": \"Type 1 diabetes mellitus\",\n",
+ " \"hierarchy\": \"Clinical finding\",\n",
+ " \"parent_concept\": \"Diabetes mellitus\"\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Sample clinical document\n",
+ "clinical_document = {\n",
+ " \"document_id\": \"DOC-001\",\n",
+ " \"patient_id\": \"PATIENT-001\",\n",
+ " \"document_type\": \"Clinical Note\",\n",
+ " \"content\": \"Patient presents with Type 2 diabetes mellitus. Current medications include Metformin 500mg twice daily. Blood glucose levels are well-controlled. Patient reports adherence to dietary recommendations.\",\n",
+ " \"date\": datetime.now().isoformat(),\n",
+ " \"physician\": \"Dr. Smith\"\n",
+ "}\n",
+ "\n",
+ "# Save sample data\n",
+ "snomed_file = os.path.join(temp_dir, \"snomed_concepts.json\")\n",
+ "clinical_file = os.path.join(temp_dir, \"clinical_note.json\")\n",
+ "\n",
+ "with open(snomed_file, 'w') as f:\n",
+ " json.dump(snomed_data, f, indent=2)\n",
+ "\n",
+ "with open(clinical_file, 'w') as f:\n",
+ " json.dump(clinical_document, f, indent=2)\n",
+ "\n",
+ "# Ingest using Semantica FileIngestor\n",
+ "snomed_file_obj = file_ingestor.ingest_file(snomed_file, read_content=True)\n",
+ "clinical_file_obj = file_ingestor.ingest_file(clinical_file, read_content=True)\n",
+ "\n",
+ "# Virtual EHR connection setup (using Semantica DBIngestor)\n",
+ "# In production, this would connect to actual EHR database\n",
+ "ehr_connection_config = {\n",
+ " \"connection_string\": \"postgresql://user:password@localhost:5432/ehr_db\",\n",
+ " \"query\": \"SELECT patient_id, diagnosis, medications, lab_results, visit_date FROM patient_records WHERE patient_id = %s\"\n",
+ "}\n",
+ "\n",
+ "print(f\"✓ Ingested SNOMED CT concepts: {len(snomed_data['concepts'])} concepts\")\n",
+ "print(f\"✓ Ingested clinical document: {clinical_document['document_id']}\")\n",
+ "print(f\"✓ EHR virtual connection configured (not executed - would connect to actual EHR in production)\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse and Normalize Data Using Semantica\n",
+ "\n",
+ "Using Semantica's parse and normalize modules to process the ingested data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica parsers and normalizer\n",
+ "document_parser = DocumentParser()\n",
+ "pdf_parser = PDFParser()\n",
+ "structured_parser = StructuredDataParser()\n",
+ "text_normalizer = TextNormalizer()\n",
+ "\n",
+ "# Parse structured data (SNOMED CT)\n",
+ "parsed_snomed = structured_parser.parse_json(snomed_file)\n",
+ "snomed_concepts = parsed_snomed.data if hasattr(parsed_snomed, 'data') else parsed_snomed\n",
+ "\n",
+ "# Parse clinical document\n",
+ "parsed_clinical = structured_parser.parse_json(clinical_file)\n",
+ "clinical_data = parsed_clinical.data if hasattr(parsed_clinical, 'data') else parsed_clinical\n",
+ "\n",
+ "# Normalize clinical text using Semantica\n",
+ "if isinstance(clinical_data, dict) and 'content' in clinical_data:\n",
+ " normalized_text = text_normalizer.normalize(clinical_data['content'])\n",
+ " clinical_data['normalized_content'] = normalized_text\n",
+ "\n",
+ "print(f\"✓ Parsed SNOMED CT concepts: {len(snomed_concepts.get('concepts', [])) if isinstance(snomed_concepts, dict) else 0}\")\n",
+ "print(f\"✓ Parsed clinical document: {clinical_data.get('document_id', 'N/A')}\")\n",
+ "print(f\"✓ Normalized clinical text: {len(normalized_text) if 'normalized_text' in locals() else 0} characters\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Medical Entities and Relationships Using Semantica\n",
+ "\n",
+ "Using Semantica's semantic extraction modules to extract medical entities, relationships, and triples from the parsed data.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica extractors\n",
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "triple_extractor = TripleExtractor()\n",
+ "\n",
+ "# Extract entities from clinical document\n",
+ "clinical_text = clinical_data.get('normalized_content', clinical_data.get('content', ''))\n",
+ "extracted_entities = ner_extractor.extract(clinical_text)\n",
+ "\n",
+ "# Extract relationships\n",
+ "extracted_relationships = relation_extractor.extract(clinical_text, entities=extracted_entities)\n",
+ "\n",
+ "# Extract triples\n",
+ "extracted_triples = triple_extractor.extract(clinical_text)\n",
+ "\n",
+ "# Build entity list for knowledge graph\n",
+ "medical_entities = []\n",
+ "medical_relationships = []\n",
+ "\n",
+ "# Add SNOMED CT concepts as entities\n",
+ "if isinstance(snomed_concepts, dict):\n",
+ " for concept in snomed_concepts.get('concepts', []):\n",
+ " medical_entities.append({\n",
+ " \"id\": f\"snomed_{concept.get('concept_id', '')}\",\n",
+ " \"type\": \"Medical_Concept\",\n",
+ " \"name\": concept.get('concept_name', ''),\n",
+ " \"properties\": {\n",
+ " \"concept_id\": concept.get('concept_id', ''),\n",
+ " \"hierarchy\": concept.get('hierarchy', ''),\n",
+ " \"source\": \"SNOMED_CT\"\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "# Add extracted entities from clinical document\n",
+ "for entity in extracted_entities:\n",
+ " medical_entities.append({\n",
+ " \"id\": f\"entity_{entity.get('id', len(medical_entities))}\",\n",
+ " \"type\": entity.get('type', 'Entity'),\n",
+ " \"name\": entity.get('text', ''),\n",
+ " \"properties\": {\n",
+ " \"source\": \"clinical_document\",\n",
+ " \"document_id\": clinical_data.get('document_id', '')\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "# Add relationships\n",
+ "for rel in extracted_relationships:\n",
+ " medical_relationships.append({\n",
+ " \"source\": rel.get('source', ''),\n",
+ " \"target\": rel.get('target', ''),\n",
+ " \"type\": rel.get('type', 'related_to'),\n",
+ " \"properties\": {\n",
+ " \"source\": \"clinical_document\"\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "print(f\"✓ Extracted {len(extracted_entities)} medical entities\")\n",
+ "print(f\"✓ Extracted {len(extracted_relationships)} relationships\")\n",
+ "print(f\"✓ Extracted {len(extracted_triples)} triples\")\n",
+ "print(f\"✓ Total entities for KG: {len(medical_entities)}\")\n",
+ "print(f\"✓ Total relationships for KG: {len(medical_relationships)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Materialized Knowledge Graph Using Semantica\n",
+ "\n",
+ "Using Semantica's KG modules to build a materialized knowledge graph from the extracted entities and relationships.\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 materialized knowledge graph using Semantica\n",
+ "materialized_kg = graph_builder.build(medical_entities, medical_relationships)\n",
+ "\n",
+ "# Analyze the graph using Semantica\n",
+ "kg_metrics = graph_analyzer.compute_metrics(materialized_kg)\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(materialized_kg)\n",
+ "\n",
+ "print(f\"✓ Built materialized knowledge graph\")\n",
+ "print(f\" - Entities: {len(materialized_kg.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(materialized_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: Generate Ontology Using Semantica\n",
+ "\n",
+ "Using Semantica's ontology modules to generate medical ontologies from the knowledge graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica ontology generators\n",
+ "ontology_generator = OntologyGenerator()\n",
+ "owl_generator = OWLGenerator()\n",
+ "\n",
+ "# Generate ontology from knowledge graph using Semantica\n",
+ "ontology_result = ontology_generator.generate(\n",
+ " semantic_network=materialized_kg,\n",
+ " domain=\"Healthcare\",\n",
+ " namespace=\"http://semantica.example.org/healthcare#\"\n",
+ ")\n",
+ "\n",
+ "# Generate OWL representation using Semantica\n",
+ "owl_ontology = owl_generator.generate(ontology_result)\n",
+ "\n",
+ "print(f\"✓ Generated ontology using Semantica\")\n",
+ "print(f\" - Classes: {len(ontology_result.get('classes', []))}\")\n",
+ "print(f\" - Properties: {len(ontology_result.get('properties', []))}\")\n",
+ "print(f\" - OWL generated: {len(owl_ontology) if owl_ontology else 0} characters\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Generate Embeddings Using Semantica\n",
+ "\n",
+ "Using Semantica's embedding modules to generate vector embeddings for RAG.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica embedding generators\n",
+ "embedding_generator = EmbeddingGenerator()\n",
+ "text_embedder = TextEmbedder()\n",
+ "\n",
+ "# Generate embeddings for clinical documents using Semantica\n",
+ "documents_for_embedding = [clinical_data.get('normalized_content', clinical_data.get('content', ''))]\n",
+ "\n",
+ "# Generate embeddings using Semantica\n",
+ "document_embeddings = []\n",
+ "for doc in documents_for_embedding:\n",
+ " embedding = text_embedder.embed(doc)\n",
+ " document_embeddings.append(embedding)\n",
+ "\n",
+ "# Generate embeddings for entities\n",
+ "entity_embeddings = {}\n",
+ "for entity in medical_entities[:10]: # Limit for demo\n",
+ " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",
+ " embedding = text_embedder.embed(entity_text)\n",
+ " entity_embeddings[entity.get('id', '')] = embedding\n",
+ "\n",
+ "print(f\"✓ Generated embeddings using Semantica\")\n",
+ "print(f\" - Document embeddings: {len(document_embeddings)}\")\n",
+ "print(f\" - Entity embeddings: {len(entity_embeddings)}\")\n",
+ "print(f\" - Embedding dimension: {len(document_embeddings[0]) if document_embeddings else 0}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 8: Setup Vector Store and Hybrid Search Using Semantica\n",
+ "\n",
+ "Using Semantica's vector store modules to set up RAG with hybrid search capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica vector store and hybrid search\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",
+ "hybrid_search = HybridSearch()\n",
+ "\n",
+ "# Prepare metadata for documents\n",
+ "document_metadata = [{\n",
+ " \"document_id\": clinical_data.get('document_id', ''),\n",
+ " \"document_type\": clinical_data.get('document_type', ''),\n",
+ " \"date\": clinical_data.get('date', ''),\n",
+ " \"source\": \"clinical_document\"\n",
+ "}]\n",
+ "\n",
+ "# Store document embeddings using Semantica\n",
+ "document_ids = vector_store.store_vectors(\n",
+ " vectors=document_embeddings,\n",
+ " metadata=document_metadata\n",
+ ")\n",
+ "\n",
+ "# Store entity embeddings\n",
+ "entity_metadata = [{\"entity_id\": eid, \"type\": \"entity\", \"source\": \"kg\"} for eid in entity_embeddings.keys()]\n",
+ "entity_ids = vector_store.store_vectors(\n",
+ " vectors=list(entity_embeddings.values()),\n",
+ " metadata=entity_metadata\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Set up vector store using Semantica\")\n",
+ "print(f\" - Document vectors stored: {len(document_ids)}\")\n",
+ "print(f\" - Entity vectors stored: {len(entity_ids)}\")\n",
+ "print(f\" - Hybrid search ready for GraphRAG\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 9: Setup Triple Store for Ontology Queries Using Semantica\n",
+ "\n",
+ "Using Semantica's triple store modules to enable SPARQL queries on medical ontologies.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica triple store and query engine\n",
+ "triple_manager = TripleManager()\n",
+ "query_engine = QueryEngine()\n",
+ "\n",
+ "# Register triple store (using in-memory for demo)\n",
+ "store = triple_manager.register_store(\"healthcare_ontology\", \"jena\", \"http://localhost:3030/healthcare\")\n",
+ "\n",
+ "# Convert ontology to triples and add to store\n",
+ "# In production, this would load the OWL ontology\n",
+ "sample_triples = [\n",
+ " {\n",
+ " \"subject\": \"http://semantica.example.org/healthcare#Type2Diabetes\",\n",
+ " \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
+ " \"object\": \"http://semantica.example.org/healthcare#Diabetes\",\n",
+ " \"confidence\": 1.0\n",
+ " },\n",
+ " {\n",
+ " \"subject\": \"http://semantica.example.org/healthcare#Type1Diabetes\",\n",
+ " \"predicate\": \"http://www.w3.org/2000/01/rdf-schema#subClassOf\",\n",
+ " \"object\": \"http://semantica.example.org/healthcare#Diabetes\",\n",
+ " \"confidence\": 1.0\n",
+ " }\n",
+ "]\n",
+ "\n",
+ "# Add triples using Semantica\n",
+ "for triple in sample_triples:\n",
+ " triple_manager.add_triple(triple, store_id=\"healthcare_ontology\")\n",
+ "\n",
+ "print(f\"✓ Set up triple store using Semantica\")\n",
+ "print(f\" - Triples added: {len(sample_triples)}\")\n",
+ "print(f\" - SPARQL queries enabled for ontology\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 10: Implement GraphRAG Query Orchestration Using Semantica\n",
+ "\n",
+ "Using Semantica's reasoning and context modules to orchestrate queries across ontologies, documents, and EHRs.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica reasoning and context modules\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "context_retriever = ContextRetriever()\n",
+ "context_graph_builder = ContextGraphBuilder()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Define medical reasoning rules using Semantica\n",
+ "medical_rules = [\n",
+ " {\n",
+ " \"rule_id\": \"diabetes_treatment_rule\",\n",
+ " \"condition\": \"IF patient has Type2Diabetes THEN recommend Metformin\",\n",
+ " \"action\": \"suggest_treatment\"\n",
+ " }\n",
+ "]\n",
+ "\n",
+ "# Add rules using Semantica\n",
+ "for rule in medical_rules:\n",
+ " rule_manager.add_rule(rule)\n",
+ "\n",
+ "# Example query orchestration function using Semantica\n",
+ "def orchestrate_graphrag_query(query_text, patient_id=None):\n",
+ " \"\"\"\n",
+ " Orchestrate GraphRAG query across ontologies, documents, and EHRs using Semantica.\n",
+ " \"\"\"\n",
+ " results = {\n",
+ " \"ontology_results\": [],\n",
+ " \"document_results\": [],\n",
+ " \"ehr_results\": [],\n",
+ " \"graph_results\": [],\n",
+ " \"context\": {}\n",
+ " }\n",
+ " \n",
+ " # 1. Query ontology using Semantica Triple Store\n",
+ " sparql_query = f\"\"\"\n",
+ " SELECT ?concept WHERE {{\n",
+ " ?concept rdfs:label ?label .\n",
+ " FILTER(CONTAINS(LCASE(?label), \"{query_text.lower()}\"))\n",
+ " }}\n",
+ " \"\"\"\n",
+ " try:\n",
+ " ontology_results = query_engine.execute_query(sparql_query, store)\n",
+ " results[\"ontology_results\"] = ontology_results.get(\"bindings\", [])\n",
+ " except:\n",
+ " pass\n",
+ " \n",
+ " # 2. Search documents using Semantica Hybrid Search\n",
+ " query_embedding = text_embedder.embed(query_text)\n",
+ " document_results = hybrid_search.search(\n",
+ " query_vector=query_embedding,\n",
+ " vectors=document_embeddings,\n",
+ " metadata=document_metadata,\n",
+ " vector_ids=document_ids,\n",
+ " k=5\n",
+ " )\n",
+ " results[\"document_results\"] = document_results\n",
+ " \n",
+ " # 3. Query knowledge graph using Semantica\n",
+ " graph_results = graph_analyzer.query_graph(materialized_kg, query_text)\n",
+ " results[\"graph_results\"] = graph_results\n",
+ " \n",
+ " # 4. Build context using Semantica\n",
+ " context_graph = context_graph_builder.build(\n",
+ " entities=medical_entities,\n",
+ " relationships=medical_relationships,\n",
+ " query=query_text\n",
+ " )\n",
+ " results[\"context\"] = context_graph\n",
+ " \n",
+ " # 5. Virtual EHR query (would execute in production)\n",
+ " if patient_id:\n",
+ " # In production: ehr_results = db_ingestor.query(ehr_connection_config, patient_id)\n",
+ " results[\"ehr_results\"] = {\"note\": \"EHR query would execute here in production\"}\n",
+ " \n",
+ " return results\n",
+ "\n",
+ "# Example query\n",
+ "query = \"What are the treatment options for Type 2 diabetes?\"\n",
+ "orchestrated_results = orchestrate_graphrag_query(query)\n",
+ "\n",
+ "print(f\"✓ Implemented GraphRAG query orchestration using Semantica\")\n",
+ "print(f\" - Query: '{query}'\")\n",
+ "print(f\" - Ontology results: {len(orchestrated_results['ontology_results'])}\")\n",
+ "print(f\" - Document results: {len(orchestrated_results['document_results'])}\")\n",
+ "print(f\" - Graph results: {len(orchestrated_results['graph_results'])}\")\n",
+ "print(f\" - Context built: {bool(orchestrated_results['context'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Generate explanation using Semantica\n",
+ "explanation = explanation_generator.generate(\n",
+ " query=query,\n",
+ " results=orchestrated_results,\n",
+ " knowledge_graph=materialized_kg,\n",
+ " context=orchestrated_results['context']\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Generated explainable answer using Semantica\")\n",
+ "print(\"\\nAnswer Explanation:\")\n",
+ "print(f\" {explanation.get('answer', 'Answer generated')}\")\n",
+ "print(f\"\\nSources:\")\n",
+ "print(f\" - Ontology: {len(orchestrated_results['ontology_results'])} results\")\n",
+ "print(f\" - Documents: {len(orchestrated_results['document_results'])} results\")\n",
+ "print(f\" - Knowledge Graph: {len(orchestrated_results['graph_results'])} results\")\n",
+ "print(f\" - Traceability: Enabled via Semantica ContextRetriever\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 12: Visualize Knowledge Graph and Results Using Semantica\n",
+ "\n",
+ "Using Semantica's visualization modules to visualize the knowledge graph and analysis results.\n"
+ ]
+ },
+ {
+ "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",
+ "temporal_visualizer = TemporalVisualizer()\n",
+ "\n",
+ "# Visualize knowledge graph using Semantica\n",
+ "kg_fig = kg_visualizer.visualize_network(\n",
+ " materialized_kg,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize analytics\n",
+ "centrality = graph_analyzer.compute_centrality(materialized_kg, method=\"pagerank\")\n",
+ "analytics_data = {\n",
+ " \"graph\": materialized_kg,\n",
+ " \"centrality\": centrality\n",
+ "}\n",
+ "analytics_fig = analytics_visualizer.visualize_centrality_rankings(\n",
+ " centrality,\n",
+ " centrality_type=\"pagerank\",\n",
+ " top_n=10,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Visualized knowledge graph and analytics using Semantica\")\n",
+ "print(\" - Knowledge graph visualization: Interactive\")\n",
+ "print(\" - Analytics dashboard: Centrality rankings\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 13: Export Results Using Semantica\n",
+ "\n",
+ "Using Semantica's export modules to export the knowledge graph, ontology, and reports.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica exporters\n",
+ "json_exporter = JSONExporter()\n",
+ "rdf_exporter = RDFExporter()\n",
+ "report_generator = ReportGenerator()\n",
+ "\n",
+ "# Export knowledge graph as JSON using Semantica\n",
+ "kg_json_file = os.path.join(temp_dir, \"healthcare_kg.json\")\n",
+ "json_exporter.export(materialized_kg, kg_json_file)\n",
+ "\n",
+ "# Export ontology as RDF using Semantica\n",
+ "ontology_rdf_file = os.path.join(temp_dir, \"healthcare_ontology.rdf\")\n",
+ "rdf_exporter.export(ontology_result, ontology_rdf_file)\n",
+ "\n",
+ "# Generate comprehensive report using Semantica\n",
+ "report_data = {\n",
+ " \"title\": \"Healthcare GraphRAG System Report\",\n",
+ " \"knowledge_graph_metrics\": kg_metrics,\n",
+ " \"query_results\": orchestrated_results,\n",
+ " \"explanation\": explanation\n",
+ "}\n",
+ "report_file = os.path.join(temp_dir, \"healthcare_graphrag_report.html\")\n",
+ "report_generator.generate_report(report_data, report_file, format=\"html\")\n",
+ "\n",
+ "print(\"✓ Exported results using Semantica\")\n",
+ "print(f\" - Knowledge graph JSON: {kg_json_file}\")\n",
+ "print(f\" - Ontology RDF: {ontology_rdf_file}\")\n",
+ "print(f\" - Report HTML: {report_file}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 14: Complete Pipeline Orchestration Using Semantica\n",
+ "\n",
+ "Using Semantica's pipeline module to orchestrate the complete GraphRAG pipeline.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Build complete pipeline using Semantica PipelineBuilder\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "\n",
+ "healthcare_graphrag_pipeline = pipeline_builder \\\n",
+ " .add_step(\"ingest\", \"file_ingest\", source=temp_dir) \\\n",
+ " .add_step(\"parse\", \"structured_parse\", formats=[\"json\"]) \\\n",
+ " .add_step(\"normalize\", \"text_normalize\") \\\n",
+ " .add_step(\"extract\", \"semantic_extract\", entities=True, relations=True) \\\n",
+ " .add_step(\"build_kg\", \"kg_build\") \\\n",
+ " .add_step(\"generate_embeddings\", \"embedding_generate\") \\\n",
+ " .add_step(\"setup_vector_store\", \"vector_store_setup\") \\\n",
+ " .add_step(\"setup_triple_store\", \"triple_store_setup\") \\\n",
+ " .add_step(\"orchestrate_query\", \"graphrag_query\") \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline using Semantica ExecutionEngine\n",
+ "execution_engine = ExecutionEngine()\n",
+ "pipeline_result = execution_engine.execute_pipeline(healthcare_graphrag_pipeline)\n",
+ "\n",
+ "print(\"✓ Built and executed complete GraphRAG pipeline using Semantica\")\n",
+ "print(f\" - Pipeline steps: {len(healthcare_graphrag_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 building a Healthcare GraphRAG system\n",
+ "2. **Materialized Knowledge Graphs**: Semantica's KG modules enable building persistent knowledge graphs from medical ontologies and documents\n",
+ "3. **Virtual Data Integration**: Semantica's DBIngestor allows virtual integration with EHRs without data replication\n",
+ "4. **Hybrid Search**: Semantica's HybridSearch combines vector similarity with knowledge graph queries\n",
+ "5. **Query Orchestration**: Semantica's Reasoning and Triple Store modules enable dynamic query orchestration\n",
+ "6. **Explainability**: Semantica's ExplanationGenerator provides traceable, explainable answers\n",
+ "\n",
+ "### Semantica-Specific Performance Considerations\n",
+ "\n",
+ "- **Vector Store**: Use Semantica's VectorStore with appropriate backend (FAISS for local, Pinecone/Weaviate for cloud)\n",
+ "- **Graph Analytics**: Leverage Semantica's GraphAnalyzer for efficient centrality and community detection\n",
+ "- **Pipeline Execution**: Use Semantica's ExecutionEngine for parallel execution of pipeline steps\n",
+ "- **Caching**: Utilize Semantica's ContextRetriever caching for frequently accessed contexts\n",
+ "\n",
+ "### Deployment Recommendations Using Semantica\n",
+ "\n",
+ "1. **Production Setup**:\n",
+ " - Use Semantica's configuration management for environment-specific settings\n",
+ " - Leverage Semantica's Pipeline module for production workflows\n",
+ " - Use Semantica's export modules for data persistence\n",
+ "\n",
+ "2. **Scalability**:\n",
+ " - Use Semantica's batch processing capabilities for large-scale data ingestion\n",
+ " - Leverage Semantica's vector store adapters for distributed storage\n",
+ " - Utilize Semantica's parallel execution features\n",
+ "\n",
+ "3. **Compliance**:\n",
+ " - Semantica's virtual data integration ensures EHR data remains in original systems\n",
+ " - Use Semantica's audit logging for traceability\n",
+ " - Leverage Semantica's export modules for compliance reporting\n",
+ "\n",
+ "### How Semantica's Architecture Benefits Healthcare GraphRAG\n",
+ "\n",
+ "- **Unified Framework**: Single framework for all operations reduces integration complexity\n",
+ "- **Modular Design**: Semantica's modular architecture allows flexible deployment\n",
+ "- **Extensibility**: Semantica's registry system enables custom method registration\n",
+ "- **Type Safety**: Semantica's structured data models ensure data consistency\n",
+ "- **Performance**: Semantica's optimized algorithms provide efficient graph operations\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/intelligence/Network_Analysis_Intelligence_Reports.ipynb b/cookbook/use_cases/intelligence/Network_Analysis_Intelligence_Reports.ipynb
new file mode 100644
index 00000000..93a1e998
--- /dev/null
+++ b/cookbook/use_cases/intelligence/Network_Analysis_Intelligence_Reports.ipynb
@@ -0,0 +1,779 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Network Analysis and Intelligence Reports with Semantica\n",
+ "\n",
+ "## Overview\n",
+ "\n",
+ "This notebook demonstrates using **Semantica as the core framework** to combine graph analytics with AI to analyze relational data and generate professional intelligence reports for fraud detection, cybersecurity, supply chain analysis, and criminal networks.\n",
+ "\n",
+ "### Why Semantica?\n",
+ "\n",
+ "Semantica provides a complete framework for network analysis and intelligence reporting:\n",
+ "\n",
+ "- **Graph Analytics**: Semantica's GraphAnalyzer provides community detection (Louvain) and centrality measures (PageRank, Betweenness, Closeness, Eigenvector)\n",
+ "- **Association Strength**: Semantica's algorithms calculate co-occurrence networks using association strength\n",
+ "- **Agent Coordination**: Semantica's Pipeline module enables parallel agent coordination for intelligence gathering\n",
+ "- **Pattern Detection**: Semantica's Reasoning modules identify patterns in complex networks\n",
+ "- **Report Generation**: Semantica's ReportGenerator creates professional HTML intelligence reports\n",
+ "- **Entity Resolution**: Semantica's Deduplication modules resolve entities in networks\n",
+ "\n",
+ "### Key Features\n",
+ "\n",
+ "- Transform relational data into co-occurrence networks using Semantica's association strength calculations\n",
+ "- Community detection (Louvain) and centrality measures (PageRank, Betweenness) using Semantica\n",
+ "- Parallel agent coordination using Semantica's Pipeline module\n",
+ "- Systematic prompt engineering techniques\n",
+ "- LLMs-as-judge evaluation systems\n",
+ "- Professional HTML report generation through coordinated AI agents using Semantica\n",
+ "- Graph data science + agentic AI coordination via Semantica\n",
+ "\n",
+ "### Semantica Modules Used (20+)\n",
+ "\n",
+ "- **Ingest**: FileIngestor, DBIngestor, WebIngestor (relational data from various sources)\n",
+ "- **Parse**: StructuredDataParser, CSVParser, JSONParser, DocumentParser (for various data formats)\n",
+ "- **Normalize**: TextNormalizer, DataNormalizer (for data cleaning and standardization)\n",
+ "- **Semantic Extract**: NERExtractor, RelationExtractor, TripleExtractor (relationship extraction, entity extraction)\n",
+ "- **KG**: GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer (network construction and analysis)\n",
+ "- **Graph Analytics**: Use Semantica's GraphAnalyzer for community detection (Louvain), centrality calculations (PageRank, Betweenness, Closeness, Eigenvector)\n",
+ "- **Embeddings**: EmbeddingGenerator, TextEmbedder (for similarity calculations, entity embeddings)\n",
+ "- **Vector Store**: VectorStore, HybridSearch, MetadataFilter (for RAG and similarity search)\n",
+ "- **Reasoning**: InferenceEngine, RuleManager, ExplanationGenerator (for pattern detection, rule-based analysis)\n",
+ "- **Context**: ContextRetriever, ContextGraphBuilder (for contextual intelligence gathering)\n",
+ "- **Pipeline**: PipelineBuilder, ExecutionEngine, ParallelismManager (for orchestrating agent workflows)\n",
+ "- **Export**: ReportGenerator, HTMLExporter, JSONExporter (for professional intelligence reports)\n",
+ "- **Visualization**: KGVisualizer, AnalyticsVisualizer, QualityVisualizer (network visualization, analytics dashboards, report visualizations)\n",
+ "- **Deduplication**: DuplicateDetector, EntityMerger (for entity resolution in networks)\n",
+ "\n",
+ "### Pipeline Overview\n",
+ "\n",
+ "**Relational Data → Parse → Extract Entities/Relationships → Build Network Graph → Graph Analytics → Pattern Detection → Generate Intelligence Report → Visualize**\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\n",
+ "from semantica.parse import StructuredDataParser, CSVParser, JSONParser, DocumentParser\n",
+ "from semantica.normalize import TextNormalizer, DataNormalizer\n",
+ "from semantica.semantic_extract import NERExtractor, RelationExtractor, TripleExtractor\n",
+ "from semantica.kg import GraphBuilder, GraphAnalyzer, ConnectivityAnalyzer\n",
+ "from semantica.embeddings import EmbeddingGenerator, TextEmbedder\n",
+ "from semantica.vector_store import VectorStore, HybridSearch, MetadataFilter\n",
+ "from semantica.reasoning import InferenceEngine, RuleManager, ExplanationGenerator\n",
+ "from semantica.context import ContextRetriever, ContextGraphBuilder\n",
+ "from semantica.pipeline import PipelineBuilder, ExecutionEngine, ParallelismManager\n",
+ "from semantica.export import ReportGenerator, JSONExporter\n",
+ "from semantica.visualization import KGVisualizer, AnalyticsVisualizer, QualityVisualizer\n",
+ "from semantica.deduplication import DuplicateDetector, EntityMerger\n",
+ "\n",
+ "import tempfile\n",
+ "import os\n",
+ "import json\n",
+ "from datetime import datetime\n",
+ "import numpy as np\n",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Using Semantica as the core framework for Network Analysis and Intelligence Reports\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Ingest Relational Data Using Semantica\n",
+ "\n",
+ "Using Semantica's ingest modules to load relational data from various sources (CSV, JSON, databases).\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",
+ "\n",
+ "# Create temporary directory for sample data\n",
+ "temp_dir = tempfile.mkdtemp()\n",
+ "\n",
+ "# Sample relational data (e.g., transaction network, communication network, etc.)\n",
+ "relational_data = {\n",
+ " \"entities\": [\n",
+ " {\"id\": \"E001\", \"name\": \"Entity A\", \"type\": \"Person\", \"attributes\": {\"age\": 35, \"location\": \"City1\"}},\n",
+ " {\"id\": \"E002\", \"name\": \"Entity B\", \"type\": \"Person\", \"attributes\": {\"age\": 42, \"location\": \"City1\"}},\n",
+ " {\"id\": \"E003\", \"name\": \"Entity C\", \"type\": \"Organization\", \"attributes\": {\"location\": \"City2\"}},\n",
+ " {\"id\": \"E004\", \"name\": \"Entity D\", \"type\": \"Person\", \"attributes\": {\"age\": 28, \"location\": \"City2\"}},\n",
+ " {\"id\": \"E005\", \"name\": \"Entity E\", \"type\": \"Person\", \"attributes\": {\"age\": 50, \"location\": \"City1\"}}\n",
+ " ],\n",
+ " \"relationships\": [\n",
+ " {\"source\": \"E001\", \"target\": \"E002\", \"type\": \"communicates_with\", \"frequency\": 15, \"date\": \"2024-01-15\"},\n",
+ " {\"source\": \"E001\", \"target\": \"E003\", \"type\": \"associated_with\", \"frequency\": 8, \"date\": \"2024-02-10\"},\n",
+ " {\"source\": \"E002\", \"target\": \"E003\", \"type\": \"communicates_with\", \"frequency\": 12, \"date\": \"2024-01-20\"},\n",
+ " {\"source\": \"E002\", \"target\": \"E004\", \"type\": \"communicates_with\", \"frequency\": 5, \"date\": \"2024-03-05\"},\n",
+ " {\"source\": \"E003\", \"target\": \"E004\", \"type\": \"associated_with\", \"frequency\": 20, \"date\": \"2024-02-15\"},\n",
+ " {\"source\": \"E004\", \"target\": \"E005\", \"type\": \"communicates_with\", \"frequency\": 3, \"date\": \"2024-03-10\"},\n",
+ " {\"source\": \"E001\", \"target\": \"E005\", \"type\": \"communicates_with\", \"frequency\": 10, \"date\": \"2024-01-25\"}\n",
+ " ]\n",
+ "}\n",
+ "\n",
+ "# Save sample data\n",
+ "relational_file = os.path.join(temp_dir, \"relational_data.json\")\n",
+ "with open(relational_file, 'w') as f:\n",
+ " json.dump(relational_data, f, indent=2)\n",
+ "\n",
+ "# Ingest using Semantica FileIngestor\n",
+ "relational_file_obj = file_ingestor.ingest_file(relational_file, read_content=True)\n",
+ "\n",
+ "print(f\"✓ Ingested relational data using Semantica\")\n",
+ "print(f\" - Entities: {len(relational_data['entities'])}\")\n",
+ "print(f\" - Relationships: {len(relational_data['relationships'])}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Parse and Normalize Data Using Semantica\n",
+ "\n",
+ "Using Semantica's parse and normalize modules to process the relational data.\n"
+ ]
+ },
+ {
+ "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 relational data using Semantica\n",
+ "parsed_data = structured_parser.parse_json(relational_file)\n",
+ "relational_data_parsed = parsed_data.data if hasattr(parsed_data, 'data') else parsed_data\n",
+ "\n",
+ "# Normalize entity names using Semantica\n",
+ "if isinstance(relational_data_parsed, dict):\n",
+ " for entity in relational_data_parsed.get('entities', []):\n",
+ " entity['normalized_name'] = text_normalizer.normalize(entity.get('name', ''))\n",
+ "\n",
+ "print(f\"✓ Parsed relational data using Semantica\")\n",
+ "print(f\" - Entities parsed: {len(relational_data_parsed.get('entities', [])) if isinstance(relational_data_parsed, dict) else 0}\")\n",
+ "print(f\" - Relationships parsed: {len(relational_data_parsed.get('relationships', [])) if isinstance(relational_data_parsed, dict) else 0}\")\n",
+ "print(f\"✓ Normalized entity data using Semantica\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Extract Entities and Relationships Using Semantica\n",
+ "\n",
+ "Using Semantica's semantic extraction modules to extract entities, relationships, and build co-occurrence networks with association strength.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica extractors\n",
+ "ner_extractor = NERExtractor()\n",
+ "relation_extractor = RelationExtractor()\n",
+ "triple_extractor = TripleExtractor()\n",
+ "\n",
+ "# Extract entities and relationships from relational data\n",
+ "network_entities = []\n",
+ "network_relationships = []\n",
+ "\n",
+ "# Process entities using Semantica\n",
+ "if isinstance(relational_data_parsed, dict):\n",
+ " for entity in relational_data_parsed.get('entities', []):\n",
+ " network_entities.append({\n",
+ " \"id\": entity.get('id', ''),\n",
+ " \"type\": entity.get('type', 'Entity'),\n",
+ " \"name\": entity.get('name', ''),\n",
+ " \"properties\": entity.get('attributes', {})\n",
+ " })\n",
+ "\n",
+ "# Process relationships and calculate association strength using Semantica\n",
+ "if isinstance(relational_data_parsed, dict):\n",
+ " # Calculate association strength (frequency-based)\n",
+ " relationship_strength = {}\n",
+ " for rel in relational_data_parsed.get('relationships', []):\n",
+ " source = rel.get('source', '')\n",
+ " target = rel.get('target', '')\n",
+ " rel_type = rel.get('type', 'related_to')\n",
+ " frequency = rel.get('frequency', 1)\n",
+ " \n",
+ " # Association strength calculation (normalized frequency)\n",
+ " key = f\"{source}_{target}_{rel_type}\"\n",
+ " relationship_strength[key] = relationship_strength.get(key, 0) + frequency\n",
+ " \n",
+ " network_relationships.append({\n",
+ " \"source\": source,\n",
+ " \"target\": target,\n",
+ " \"type\": rel_type,\n",
+ " \"properties\": {\n",
+ " \"frequency\": frequency,\n",
+ " \"association_strength\": relationship_strength[key] / max(relationship_strength.values()) if relationship_strength else 1.0,\n",
+ " \"date\": rel.get('date', '')\n",
+ " }\n",
+ " })\n",
+ "\n",
+ "print(f\"✓ Extracted {len(network_entities)} network entities using Semantica\")\n",
+ "print(f\"✓ Extracted {len(network_relationships)} relationships using Semantica\")\n",
+ "print(f\"✓ Calculated association strength for relationships\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Build Network Knowledge Graph Using Semantica\n",
+ "\n",
+ "Using Semantica's KG modules to build the network knowledge graph from extracted entities and relationships.\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 network knowledge graph using Semantica\n",
+ "network_kg = graph_builder.build(network_entities, network_relationships)\n",
+ "\n",
+ "# Analyze the graph using Semantica\n",
+ "kg_metrics = graph_analyzer.compute_metrics(network_kg)\n",
+ "connectivity = connectivity_analyzer.analyze_connectivity(network_kg)\n",
+ "\n",
+ "print(f\"✓ Built network knowledge graph using Semantica\")\n",
+ "print(f\" - Entities: {len(network_kg.get('entities', []))}\")\n",
+ "print(f\" - Relationships: {len(network_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: Perform Graph Analytics Using Semantica\n",
+ "\n",
+ "Using Semantica's GraphAnalyzer to perform community detection (Louvain) and centrality measures (PageRank, Betweenness, Closeness, Eigenvector).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Perform graph analytics using Semantica GraphAnalyzer\n",
+ "\n",
+ "# 1. Community detection using Louvain algorithm (via Semantica)\n",
+ "communities = graph_analyzer.detect_communities(network_kg, method=\"louvain\")\n",
+ "\n",
+ "# 2. Centrality measures using Semantica\n",
+ "pagerank_centrality = graph_analyzer.compute_centrality(network_kg, method=\"pagerank\")\n",
+ "betweenness_centrality = graph_analyzer.compute_centrality(network_kg, method=\"betweenness\")\n",
+ "closeness_centrality = graph_analyzer.compute_centrality(network_kg, method=\"closeness\")\n",
+ "eigenvector_centrality = graph_analyzer.compute_centrality(network_kg, method=\"eigenvector\")\n",
+ "\n",
+ "# 3. Identify key entities (high centrality)\n",
+ "key_entities_pagerank = sorted(\n",
+ " [(node, score) for node, score in pagerank_centrality.items()],\n",
+ " key=lambda x: x[1],\n",
+ " reverse=True\n",
+ ")[:5]\n",
+ "\n",
+ "key_entities_betweenness = sorted(\n",
+ " [(node, score) for node, score in betweenness_centrality.items()],\n",
+ " key=lambda x: x[1],\n",
+ " reverse=True\n",
+ ")[:5]\n",
+ "\n",
+ "print(f\"✓ Performed graph analytics using Semantica\")\n",
+ "print(f\" - Communities detected (Louvain): {communities.get('num_communities', 0)}\")\n",
+ "print(f\" - PageRank centrality computed: {len(pagerank_centrality)} entities\")\n",
+ "print(f\" - Betweenness centrality computed: {len(betweenness_centrality)} entities\")\n",
+ "print(f\" - Closeness centrality computed: {len(closeness_centrality)} entities\")\n",
+ "print(f\" - Eigenvector centrality computed: {len(eigenvector_centrality)} entities\")\n",
+ "print(f\"\\nTop Key Entities (PageRank):\")\n",
+ "for entity_id, score in key_entities_pagerank:\n",
+ " entity_name = next((e.get('name', '') for e in network_entities if e.get('id') == entity_id), 'Unknown')\n",
+ " print(f\" - {entity_name} ({entity_id}): {score:.4f}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 7: Detect Patterns Using Semantica Reasoning\n",
+ "\n",
+ "Using Semantica's reasoning modules to detect patterns in the network.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica reasoning modules\n",
+ "inference_engine = InferenceEngine()\n",
+ "rule_manager = RuleManager()\n",
+ "explanation_generator = ExplanationGenerator()\n",
+ "\n",
+ "# Define pattern detection rules using Semantica\n",
+ "pattern_rules = [\n",
+ " {\n",
+ " \"rule_id\": \"high_centrality_pattern\",\n",
+ " \"condition\": \"IF entity has high_pagerank AND entity has high_betweenness THEN entity is key_player\",\n",
+ " \"action\": \"flag_key_player\"\n",
+ " },\n",
+ " {\n",
+ " \"rule_id\": \"community_pattern\",\n",
+ " \"condition\": \"IF entities in same_community AND high_communication_frequency THEN entities form_cluster\",\n",
+ " \"action\": \"identify_cluster\"\n",
+ " },\n",
+ " {\n",
+ " \"rule_id\": \"bridge_pattern\",\n",
+ " \"condition\": \"IF entity has high_betweenness AND connects_communities THEN entity is_bridge\",\n",
+ " \"action\": \"flag_bridge_entity\"\n",
+ " }\n",
+ "]\n",
+ "\n",
+ "# Add rules using Semantica\n",
+ "for rule in pattern_rules:\n",
+ " rule_manager.add_rule(rule)\n",
+ "\n",
+ "# Apply pattern detection using Semantica InferenceEngine\n",
+ "pattern_results = inference_engine.infer(\n",
+ " knowledge_graph=network_kg,\n",
+ " rules=pattern_rules,\n",
+ " facts={\n",
+ " \"centrality\": pagerank_centrality,\n",
+ " \"communities\": communities,\n",
+ " \"betweenness\": betweenness_centrality\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Detected patterns using Semantica\")\n",
+ "print(f\" - Rules defined: {len(pattern_rules)}\")\n",
+ "print(f\" - Pattern detection results: {len(pattern_results) if isinstance(pattern_results, list) else 1}\")\n",
+ "print(f\" - Key players identified: {len(key_entities_pagerank)}\")\n",
+ "print(f\" - Clusters identified: {communities.get('num_communities', 0)}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 8: Generate Embeddings and Setup Vector Store Using Semantica\n",
+ "\n",
+ "Using Semantica's embedding and vector store modules for similarity search and RAG capabilities.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica embedding and vector store modules\n",
+ "embedding_generator = EmbeddingGenerator()\n",
+ "text_embedder = TextEmbedder()\n",
+ "vector_store = VectorStore(backend=\"faiss\", dimension=768)\n",
+ "hybrid_search = HybridSearch()\n",
+ "\n",
+ "# Generate embeddings for entities using Semantica\n",
+ "entity_embeddings = {}\n",
+ "for entity in network_entities:\n",
+ " entity_text = f\"{entity.get('name', '')} {entity.get('type', '')}\"\n",
+ " embedding = text_embedder.embed(entity_text)\n",
+ " entity_embeddings[entity.get('id', '')] = embedding\n",
+ "\n",
+ "# Store entity embeddings using Semantica\n",
+ "entity_metadata = [{\"entity_id\": eid, \"type\": \"entity\", \"name\": next((e.get('name', '') for e in network_entities if e.get('id') == eid), '')} for eid in entity_embeddings.keys()]\n",
+ "entity_ids = vector_store.store_vectors(\n",
+ " vectors=list(entity_embeddings.values()),\n",
+ " metadata=entity_metadata\n",
+ ")\n",
+ "\n",
+ "print(f\"✓ Generated embeddings using Semantica\")\n",
+ "print(f\" - Entity embeddings: {len(entity_embeddings)}\")\n",
+ "print(f\" - Vectors stored: {len(entity_ids)}\")\n",
+ "print(f\" - Hybrid search ready for intelligence queries\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 9: Orchestrate Agent Workflows Using Semantica Pipeline\n",
+ "\n",
+ "Using Semantica's Pipeline module to coordinate parallel agents for intelligence gathering and analysis.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica pipeline modules\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "execution_engine = ExecutionEngine()\n",
+ "parallelism_manager = ParallelismManager(max_workers=4)\n",
+ "\n",
+ "# Define agent workflows using Semantica Pipeline\n",
+ "# Agent 1: Network Structure Analysis\n",
+ "def agent_network_analysis(graph, analyzer):\n",
+ " \"\"\"Agent for network structure analysis.\"\"\"\n",
+ " metrics = analyzer.compute_metrics(graph)\n",
+ " centrality = analyzer.compute_centrality(graph, method=\"pagerank\")\n",
+ " return {\"metrics\": metrics, \"centrality\": centrality}\n",
+ "\n",
+ "# Agent 2: Community Detection\n",
+ "def agent_community_detection(graph, analyzer):\n",
+ " \"\"\"Agent for community detection.\"\"\"\n",
+ " communities = analyzer.detect_communities(graph, method=\"louvain\")\n",
+ " return {\"communities\": communities}\n",
+ "\n",
+ "# Agent 3: Pattern Detection\n",
+ "def agent_pattern_detection(graph, inference_engine, rules):\n",
+ " \"\"\"Agent for pattern detection.\"\"\"\n",
+ " patterns = inference_engine.infer(knowledge_graph=graph, rules=rules)\n",
+ " return {\"patterns\": patterns}\n",
+ "\n",
+ "# Build parallel agent pipeline using Semantica\n",
+ "intelligence_pipeline = pipeline_builder \\\n",
+ " .add_step(\"network_analysis\", \"custom\", func=agent_network_analysis, args=(network_kg, graph_analyzer)) \\\n",
+ " .add_step(\"community_detection\", \"custom\", func=agent_community_detection, args=(network_kg, graph_analyzer)) \\\n",
+ " .add_step(\"pattern_detection\", \"custom\", func=agent_pattern_detection, args=(network_kg, inference_engine, pattern_rules)) \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline with parallel execution using Semantica\n",
+ "pipeline_result = execution_engine.execute_pipeline(intelligence_pipeline, parallel=True)\n",
+ "\n",
+ "print(\"✓ Orchestrated agent workflows using Semantica Pipeline\")\n",
+ "print(f\" - Pipeline steps: {len(intelligence_pipeline.steps)}\")\n",
+ "print(f\" - Parallel execution: Enabled\")\n",
+ "print(f\" - Execution status: {pipeline_result.success if hasattr(pipeline_result, 'success') else 'Completed'}\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica context modules\n",
+ "context_retriever = ContextRetriever()\n",
+ "context_graph_builder = ContextGraphBuilder()\n",
+ "\n",
+ "# Build contextual intelligence using Semantica\n",
+ "context_graph = context_graph_builder.build(\n",
+ " entities=network_entities,\n",
+ " relationships=network_relationships,\n",
+ " query=\"Network intelligence analysis\"\n",
+ ")\n",
+ "\n",
+ "# Retrieve relevant context using Semantica\n",
+ "intelligence_context = context_retriever.retrieve(\n",
+ " query=\"key entities and relationships\",\n",
+ " knowledge_graph=network_kg,\n",
+ " top_k=10\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Built contextual intelligence using Semantica\")\n",
+ "print(f\" - Context graph built: {bool(context_graph)}\")\n",
+ "print(f\" - Intelligence context retrieved: {len(intelligence_context) if isinstance(intelligence_context, list) else 1} items\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 11: Resolve Entity Duplicates Using Semantica Deduplication\n",
+ "\n",
+ "Using Semantica's deduplication modules to resolve entity duplicates in the network.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica deduplication modules\n",
+ "duplicate_detector = DuplicateDetector()\n",
+ "entity_merger = EntityMerger()\n",
+ "\n",
+ "# Detect duplicates using Semantica\n",
+ "duplicates = duplicate_detector.detect(network_entities, similarity_threshold=0.8)\n",
+ "\n",
+ "# Merge duplicate entities using Semantica\n",
+ "if duplicates:\n",
+ " merged_entities = entity_merger.merge(network_entities, duplicates)\n",
+ " print(f\"✓ Resolved entity duplicates using Semantica\")\n",
+ " print(f\" - Duplicates detected: {len(duplicates)}\")\n",
+ " print(f\" - Merged entities: {len(merged_entities) if merged_entities else len(network_entities)}\")\n",
+ "else:\n",
+ " print(f\"✓ No duplicates detected using Semantica\")\n",
+ " merged_entities = network_entities\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 12: Visualize Network and Analytics Using Semantica\n",
+ "\n",
+ "Using Semantica's visualization modules to visualize the network, communities, and analytics.\n"
+ ]
+ },
+ {
+ "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 network using Semantica\n",
+ "network_fig = kg_visualizer.visualize_network(\n",
+ " network_kg,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize communities using Semantica\n",
+ "communities_fig = kg_visualizer.visualize_communities(\n",
+ " network_kg,\n",
+ " communities,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize centrality rankings using Semantica\n",
+ "centrality_fig = analytics_visualizer.visualize_centrality_rankings(\n",
+ " pagerank_centrality,\n",
+ " centrality_type=\"pagerank\",\n",
+ " top_n=10,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "# Visualize centrality comparison using Semantica\n",
+ "centrality_comparison = {\n",
+ " \"pagerank\": pagerank_centrality,\n",
+ " \"betweenness\": betweenness_centrality,\n",
+ " \"closeness\": closeness_centrality\n",
+ "}\n",
+ "comparison_fig = analytics_visualizer.visualize_centrality_comparison(\n",
+ " centrality_comparison,\n",
+ " top_n=10,\n",
+ " output=\"interactive\"\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Visualized network and analytics using Semantica\")\n",
+ "print(\" - Network visualization: Interactive\")\n",
+ "print(\" - Community visualization: Louvain communities\")\n",
+ "print(\" - Centrality rankings: PageRank\")\n",
+ "print(\" - Centrality comparison: Multi-measure comparison\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Initialize Semantica report generator\n",
+ "report_generator = ReportGenerator()\n",
+ "json_exporter = JSONExporter()\n",
+ "\n",
+ "# Prepare intelligence report data\n",
+ "intelligence_report_data = {\n",
+ " \"title\": \"Network Analysis Intelligence Report\",\n",
+ " \"executive_summary\": \"Analysis of network structure, key entities, communities, and patterns\",\n",
+ " \"knowledge_graph_metrics\": kg_metrics,\n",
+ " \"communities\": communities,\n",
+ " \"key_entities\": {\n",
+ " \"pagerank\": key_entities_pagerank,\n",
+ " \"betweenness\": key_entities_betweenness\n",
+ " },\n",
+ " \"centrality_measures\": {\n",
+ " \"pagerank\": pagerank_centrality,\n",
+ " \"betweenness\": betweenness_centrality,\n",
+ " \"closeness\": closeness_centrality,\n",
+ " \"eigenvector\": eigenvector_centrality\n",
+ " },\n",
+ " \"pattern_detection\": pattern_results,\n",
+ " \"network_structure\": {\n",
+ " \"entities\": len(network_entities),\n",
+ " \"relationships\": len(network_relationships),\n",
+ " \"density\": kg_metrics.get('density', 0),\n",
+ " \"components\": connectivity.get('num_components', 0)\n",
+ " },\n",
+ " \"context\": intelligence_context\n",
+ "}\n",
+ "\n",
+ "# Generate professional HTML report using Semantica\n",
+ "intelligence_report_file = os.path.join(temp_dir, \"intelligence_report.html\")\n",
+ "report_generator.generate_report(\n",
+ " intelligence_report_data,\n",
+ " intelligence_report_file,\n",
+ " format=\"html\"\n",
+ ")\n",
+ "\n",
+ "# Export network data as JSON using Semantica\n",
+ "network_json_file = os.path.join(temp_dir, \"network_data.json\")\n",
+ "json_exporter.export(network_kg, network_json_file)\n",
+ "\n",
+ "print(\"✓ Generated professional intelligence report using Semantica\")\n",
+ "print(f\" - Intelligence report HTML: {intelligence_report_file}\")\n",
+ "print(f\" - Network data JSON: {network_json_file}\")\n",
+ "print(f\" - Report includes: Executive summary, metrics, key entities, communities, patterns\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Build complete pipeline using Semantica PipelineBuilder\n",
+ "pipeline_builder = PipelineBuilder()\n",
+ "\n",
+ "network_analysis_pipeline = pipeline_builder \\\n",
+ " .add_step(\"ingest\", \"file_ingest\", source=temp_dir) \\\n",
+ " .add_step(\"parse\", \"structured_parse\", formats=[\"json\"]) \\\n",
+ " .add_step(\"normalize\", \"data_normalize\") \\\n",
+ " .add_step(\"extract\", \"semantic_extract\", entities=True, relations=True) \\\n",
+ " .add_step(\"build_kg\", \"kg_build\") \\\n",
+ " .add_step(\"graph_analytics\", \"graph_analyze\") \\\n",
+ " .add_step(\"pattern_detection\", \"reasoning_infer\") \\\n",
+ " .add_step(\"generate_embeddings\", \"embedding_generate\") \\\n",
+ " .add_step(\"setup_vector_store\", \"vector_store_setup\") \\\n",
+ " .add_step(\"build_context\", \"context_build\") \\\n",
+ " .add_step(\"deduplication\", \"deduplication_detect\") \\\n",
+ " .add_step(\"visualize\", \"visualize_network\") \\\n",
+ " .add_step(\"generate_report\", \"export_report\") \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline using Semantica ExecutionEngine with parallel execution\n",
+ "execution_engine = ExecutionEngine()\n",
+ "pipeline_result = execution_engine.execute_pipeline(\n",
+ " network_analysis_pipeline,\n",
+ " parallel=True,\n",
+ " max_workers=4\n",
+ ")\n",
+ "\n",
+ "print(\"✓ Built and executed complete network analysis pipeline using Semantica\")\n",
+ "print(f\" - Pipeline steps: {len(network_analysis_pipeline.steps)}\")\n",
+ "print(f\" - Parallel execution: Enabled (4 workers)\")\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 network analysis and intelligence reporting\n",
+ "2. **Graph Analytics**: Semantica's GraphAnalyzer provides comprehensive algorithms (Louvain, PageRank, Betweenness, Closeness, Eigenvector)\n",
+ "3. **Association Strength**: Semantica's algorithms calculate co-occurrence networks using association strength\n",
+ "4. **Agent Coordination**: Semantica's Pipeline module enables parallel agent coordination for intelligence gathering\n",
+ "5. **Pattern Detection**: Semantica's Reasoning modules identify patterns in complex networks\n",
+ "6. **Professional Reports**: Semantica's ReportGenerator creates professional HTML intelligence reports\n",
+ "7. **Entity Resolution**: Semantica's Deduplication modules resolve entities in networks\n",
+ "\n",
+ "### Semantica-Specific Performance Considerations\n",
+ "\n",
+ "- **Graph Analytics**: Use Semantica's GraphAnalyzer for efficient community detection and centrality calculations on large networks\n",
+ "- **Parallel Execution**: Leverage Semantica's ParallelismManager for concurrent agent execution\n",
+ "- **Vector Search**: Use Semantica's HybridSearch for efficient entity similarity search\n",
+ "- **Caching**: Utilize Semantica's ContextRetriever caching for frequently accessed contexts\n",
+ "\n",
+ "### Deployment Recommendations Using Semantica\n",
+ "\n",
+ "1. **Production Setup**:\n",
+ " - Use Semantica's configuration management for data source settings\n",
+ " - Leverage Semantica's Pipeline module for automated intelligence workflows\n",
+ " - Use Semantica's export modules for report persistence\n",
+ "\n",
+ "2. **Scalability**:\n",
+ " - Use Semantica's batch processing for large-scale network data\n",
+ " - Leverage Semantica's graph analytics optimizations\n",
+ " - Utilize Semantica's parallel execution for concurrent analysis\n",
+ "\n",
+ "3. **Quality Assurance**:\n",
+ " - Use Semantica's Deduplication modules for entity resolution\n",
+ " - Leverage Semantica's ExplanationGenerator for report traceability\n",
+ " - Utilize Semantica's quality modules for data validation\n",
+ "\n",
+ "### How Semantica's Architecture Benefits Network Analysis\n",
+ "\n",
+ "- **Comprehensive Analytics**: Semantica's GraphAnalyzer provides all necessary algorithms in one framework\n",
+ "- **Unified Pipeline**: Semantica's Pipeline module orchestrates complex multi-agent workflows\n",
+ "- **Extensibility**: Semantica's registry system enables custom analysis methods\n",
+ "- **Integration**: Semantica's unified framework simplifies integration with existing systems\n",
+ "- **Performance**: Semantica's optimized algorithms handle large-scale network analysis efficiently\n",
+ "- **Explainability**: Semantica's ExplanationGenerator provides traceable intelligence reports\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/cookbook/use_cases/supply_chain/Supply_Chain_Risk_Management.ipynb b/cookbook/use_cases/supply_chain/Supply_Chain_Risk_Management.ipynb
new file mode 100644
index 00000000..1c6a5d33
--- /dev/null
+++ b/cookbook/use_cases/supply_chain/Supply_Chain_Risk_Management.ipynb
@@ -0,0 +1,699 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 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",
+ "### 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, DBIngestor, WebIngestor, StreamIngestor (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**: SeedDataLoader (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 → Parse → Extract Relationships → Build Supply Chain Graph → Analyze Risks → Identify Alternatives → Visualize → Generate Reports**\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 SeedDataLoader\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",
+ "\n",
+ "print(\"✓ All Semantica modules imported successfully\")\n",
+ "print(\"✓ Using Semantica as the core framework for Supply Chain Risk Management\")\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 = SeedDataLoader()\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 SeedDataLoader\n",
+ "supplier_seed_data = seed_loader.load_from_json(supplier_file)\n",
+ "\n",
+ "print(f\"✓ Ingested BOM data: {bom_data['product_name']}\")\n",
+ "print(f\"✓ Ingested supplier data: {len(supplier_data['suppliers'])} suppliers\")\n",
+ "print(f\"✓ Ingested tariff data: {len(tariff_data['tariffs'])} tariffs\")\n",
+ "print(f\"✓ Loaded supplier seed data using Semantica\")\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_json(bom_file)\n",
+ "bom_data_parsed = parsed_bom.data if hasattr(parsed_bom, 'data') else parsed_bom\n",
+ "\n",
+ "# Parse supplier data using Semantica\n",
+ "parsed_suppliers = structured_parser.parse_json(supplier_file)\n",
+ "supplier_data_parsed = parsed_suppliers.data if hasattr(parsed_suppliers, 'data') else parsed_suppliers\n",
+ "\n",
+ "# Parse tariff data using Semantica\n",
+ "parsed_tariffs = structured_parser.parse_json(tariff_file)\n",
+ "tariff_data_parsed = parsed_tariffs.data if hasattr(parsed_tariffs, 'data') 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(supplier.get('name', ''))\n",
+ "\n",
+ "print(f\"✓ Parsed BOM data: {bom_data_parsed.get('product_name', 'N/A')}\")\n",
+ "print(f\"✓ Parsed supplier data: {len(supplier_data_parsed.get('suppliers', [])) if isinstance(supplier_data_parsed, dict) else 0} suppliers\")\n",
+ "print(f\"✓ Parsed tariff data: {len(tariff_data_parsed.get('tariffs', [])) if isinstance(tariff_data_parsed, dict) else 0} tariffs\")\n",
+ "print(f\"✓ Normalized supplier data using Semantica\")\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\"✓ Extracted {len(supply_chain_entities)} supply chain entities\")\n",
+ "print(f\"✓ Extracted {len(supply_chain_relationships)} relationships\")\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\"✓ Built supply chain knowledge graph using Semantica\")\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\"✓ Analyzed supply chain risks using Semantica\")\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\"✓ Implemented risk propagation rules using Semantica\")\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",
+ "\n",
+ "print(\"✓ Visualized supply chain network and risks using Semantica\")\n",
+ "print(\" - Network visualization: Interactive\")\n",
+ "print(\" - Community visualization: Supplier risk clusters\")\n",
+ "print(\" - Centrality rankings: Alternative sourcing options\")\n",
+ "print(\" - Risk dashboard: Overall risk metrics\")\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(\"✓ Generated risk reports using Semantica\")\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",
+ "supply_chain_pipeline = pipeline_builder \\\n",
+ " .add_step(\"ingest\", \"file_ingest\", source=temp_dir) \\\n",
+ " .add_step(\"parse\", \"structured_parse\", formats=[\"json\"]) \\\n",
+ " .add_step(\"normalize\", \"data_normalize\") \\\n",
+ " .add_step(\"extract\", \"relation_extract\") \\\n",
+ " .add_step(\"build_kg\", \"kg_build\") \\\n",
+ " .add_step(\"analyze_risks\", \"graph_analyze\") \\\n",
+ " .add_step(\"propagate_risks\", \"reasoning_infer\") \\\n",
+ " .add_step(\"visualize\", \"visualize_network\") \\\n",
+ " .add_step(\"generate_report\", \"export_report\") \\\n",
+ " .build()\n",
+ "\n",
+ "# Execute pipeline using Semantica ExecutionEngine\n",
+ "execution_engine = ExecutionEngine()\n",
+ "pipeline_result = execution_engine.execute_pipeline(supply_chain_pipeline)\n",
+ "\n",
+ "print(\"✓ Built and executed complete supply chain risk analysis pipeline using Semantica\")\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
+}