Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: Add comprehensive visualization module
KaifAhmad1bf279e034194
diff --git a/libs/README.md b/libs/README.mdindex fd97d106..85cc16e8 100644--- a/libs/README.md+++ b/libs/README.md@@ -835,6 +835,282 @@ print(f"Total entities: {len(graph.entities)}")print(f"Total relationships: {len(graph.relationships)}")```+### 9. Visualization Examples++#### Knowledge Graph Visualization+```python+from semantica.visualization import KGVisualizer++# Initialize KG visualizer+kg_viz = KGVisualizer(layout="force", color_scheme="vibrant")++# Visualize network graph+graph = {+ "entities": all_entities,+ "relationships": all_relationships+}++# Interactive network visualization+fig = kg_viz.visualize_network(graph, output="interactive")+fig.show()++# Save to HTML+kg_viz.visualize_network(graph, output="html", file_path="kg_network.html")++# Visualize with community coloring+from semantica.kg import CommunityDetector+community_detector = CommunityDetector()+communities = community_detector.detect_communities(graph, algorithm="louvain")+kg_viz.visualize_communities(graph, communities, output="html", file_path="kg_communities.html")++# Visualize with centrality+from semantica.kg import CentralityCalculator+centrality_calc = CentralityCalculator()+centrality = centrality_calc.calculate_all_centrality(graph, centrality_types=["degree"])+kg_viz.visualize_centrality(graph, centrality, centrality_type="degree",+ output="html", file_path="kg_centrality.html")++# Entity type distribution+kg_viz.visualize_entity_types(graph, output="html", file_path="entity_types.html")++# Relationship matrix+kg_viz.visualize_relationship_matrix(graph, output="html", file_path="relationship_matrix.html")+```++#### Ontology Visualization+```python+from semantica.visualization import OntologyVisualizer++# Initialize ontology visualizer+onto_viz = OntologyVisualizer(color_scheme="default")++# Visualize class hierarchy+ontology = {+ "classes": classes,+ "properties": properties+}++# Hierarchy tree visualization+onto_viz.visualize_hierarchy(ontology, output="html", file_path="ontology_hierarchy.html")++# Property graph visualization+onto_viz.visualize_properties(ontology, output="html", file_path="ontology_properties.html")++# Ontology structure network+onto_viz.visualize_structure(ontology, output="html", file_path="ontology_structure.html")++# Class-property matrix+onto_viz.visualize_class_property_matrix(ontology, output="html", file_path="class_property_matrix.html")++# Ontology metrics dashboard+onto_viz.visualize_metrics(ontology, output="html", file_path="ontology_metrics.html")+```++#### Embedding Visualization+```python+from semantica.visualization import EmbeddingVisualizer+import numpy as np++# Initialize embedding visualizer+emb_viz = EmbeddingVisualizer(point_size=8)++# 2D projection using UMAP+embeddings = np.array([...]) # Your embeddings array+fig = emb_viz.visualize_2d_projection(+ embeddings,+ labels=["Entity 1", "Entity 2", ...],+ method="umap",+ output="interactive"+)+fig.show()++# 3D projection+emb_viz.visualize_3d_projection(embeddings, method="pca",+ output="html", file_path="embeddings_3d.html")++# Similarity heatmap+emb_viz.visualize_similarity_heatmap(embeddings,+ output="html", file_path="similarity_heatmap.html")++# Clustering visualization+from sklearn.cluster import KMeans+kmeans = KMeans(n_clusters=5)+cluster_labels = kmeans.fit_predict(embeddings)+emb_viz.visualize_clustering(embeddings, cluster_labels, method="umap",+ output="html", file_path="embedding_clusters.html")++# Multi-modal comparison+text_embeddings = np.array([...])+image_embeddings = np.array([...])+emb_viz.visualize_multimodal_comparison(+ text_embeddings=text_embeddings,+ image_embeddings=image_embeddings,+ output="html",+ file_path="multimodal_comparison.html"+)++# Quality metrics+emb_viz.visualize_quality_metrics(embeddings, output="html", file_path="embedding_quality.html")+```++#### Semantic Network Visualization+```python+from semantica.visualization import SemanticNetworkVisualizer++# Initialize semantic network visualizer+sem_net_viz = SemanticNetworkVisualizer()++# Visualize semantic network+from semantica.semantic_extract import SemanticNetworkExtractor+extractor = SemanticNetworkExtractor()+semantic_network = extractor.extract_network(text)++# Network graph+sem_net_viz.visualize_network(semantic_network, output="html", file_path="semantic_network.html")++# Node type distribution+sem_net_viz.visualize_node_types(semantic_network, output="html", file_path="node_types.html")++# Edge type distribution+sem_net_viz.visualize_edge_types(semantic_network, output="html", file_path="edge_types.html")+```++#### Quality Metrics Visualization+```python+from semantica.visualization import QualityVisualizer++# Initialize quality visualizer+quality_viz = QualityVisualizer()++# Quality dashboard+from semantica.kg_qa import KGQualityAssessor+quality_assessor = KGQualityAssessor()+quality_report = quality_assessor.generate_quality_report(graph)++quality_viz.visualize_dashboard(quality_report, output="html", file_path="quality_dashboard.html")++# Quality score distribution+quality_scores = [0.85, 0.92, 0.78, 0.95, ...] # Your quality scores+quality_viz.visualize_score_distribution(quality_scores,+ output="html", file_path="score_distribution.html")++# Quality issues+quality_viz.visualize_issues(quality_report, output="html", file_path="quality_issues.html")++# Completeness metrics+from semantica.kg_qa import CompletenessMetrics+completeness_metrics = CompletenessMetrics()+completeness_data = completeness_metrics.calculate_entity_completeness(entities, schema)+quality_viz.visualize_completeness_metrics(completeness_data,+ output="html", file_path="completeness.html")++# Consistency heatmap+from semantica.kg_qa import ConsistencyMetrics+consistency_metrics = ConsistencyMetrics()+consistency_data = consistency_metrics.calculate_logical_consistency(graph)+quality_viz.visualize_consistency_heatmap(consistency_data,+ output="html", file_path="consistency_heatmap.html")+```++#### Graph Analytics Visualization+```python+from semantica.visualization import AnalyticsVisualizer++# Initialize analytics visualizer+analytics_viz = AnalyticsVisualizer()++# Centrality rankings+from semantica.kg import CentralityCalculator+centrality_calc = CentralityCalculator()+centrality = centrality_calc.calculate_all_centrality(graph, centrality_types=["degree", "betweenness"])++analytics_viz.visualize_centrality_rankings(centrality, centrality_type="degree", top_n=20,+ output="html", file_path="centrality_rankings.html")++# Community structure+from semantica.kg import CommunityDetector+community_detector = CommunityDetector()+communities = community_detector.detect_communities(graph)+analytics_viz.visualize_community_structure(graph, communities,+ output="html", file_path="communities.html")++# Connectivity analysis+from semantica.kg import ConnectivityAnalyzer+connectivity_analyzer = ConnectivityAnalyzer()+connectivity = connectivity_analyzer.analyze_connectivity(graph)+analytics_viz.visualize_connectivity(connectivity, output="html", file_path="connectivity.html")++# Degree distribution+analytics_viz.visualize_degree_distribution(graph, output="html", file_path="degree_distribution.html")++# Metrics dashboard+from semantica.kg import GraphAnalyzer+analyzer = GraphAnalyzer()+metrics = analyzer.compute_metrics(graph)+analytics_viz.visualize_metrics_dashboard(metrics, output="html", file_path="metrics_dashboard.html")++# Centrality comparison+degree_centrality = centrality_calc.calculate_degree_centrality(graph)+betweenness_centrality = centrality_calc.calculate_betweenness_centrality(graph)+centrality_results = {+ "degree": degree_centrality,+ "betweenness": betweenness_centrality+}+analytics_viz.visualize_centrality_comparison(centrality_results, top_n=10,+ output="html", file_path="centrality_comparison.html")+```++#### Temporal Graph Visualization+```python+from semantica.visualization import TemporalVisualizer++# Initialize temporal visualizer+temporal_viz = TemporalVisualizer()++# Timeline visualization+temporal_data = {+ "events": [+ {"timestamp": "2023-01-15", "type": "entity_added", "entity": "Entity1"},+ {"timestamp": "2023-02-20", "type": "relationship_added", "entity": "Entity2"},+ ]+}+temporal_viz.visualize_timeline(temporal_data, output="html", file_path="timeline.html")++# Temporal patterns+from semantica.kg import TemporalPatternDetector+pattern_detector = TemporalPatternDetector()+patterns = pattern_detector.detect_patterns(temporal_graph)+temporal_viz.visualize_temporal_patterns(patterns, output="html", file_path="temporal_patterns.html")++# Snapshot comparison+from semantica.kg import TemporalVersionManager+version_manager = TemporalVersionManager()+snapshots = {+ "2023-01-01": version_manager.get_snapshot("2023-01-01"),+ "2023-06-01": version_manager.get_snapshot("2023-06-01"),+ "2023-12-01": version_manager.get_snapshot("2023-12-01")+}+temporal_viz.visualize_snapshot_comparison(snapshots, output="html", file_path="snapshot_comparison.html")++# Version history+version_history = [+ {"version": "v1.0", "date": "2023-01-01", "changes": "Initial version"},+ {"version": "v1.1", "date": "2023-06-01", "changes": "Added new classes"},+ {"version": "v2.0", "date": "2023-12-01", "changes": "Major refactoring"}+]+temporal_viz.visualize_version_history(version_history, output="html", file_path="version_history.html")++# Metrics evolution+metrics_history = {+ "num_entities": [100, 150, 200, 250],+ "num_relationships": [200, 300, 400, 500],+ "density": [0.1, 0.12, 0.15, 0.18]+}+timestamps = ["2023-01-01", "2023-06-01", "2023-09-01", "2023-12-01"]+temporal_viz.visualize_metrics_evolution(metrics_history, timestamps,+ output="html", file_path="metrics_evolution.html")+```+## 🔧 Configuration### Basic Configurationdiff --git a/libs/pyproject.toml b/libs/pyproject.tomlindex 7592bc5c..35ea4dbc 100644--- a/libs/pyproject.toml+++ b/libs/pyproject.toml@@ -116,6 +116,11 @@ dev = ["ipykernel>=6.15.0","notebook>=6.4.0"]+viz = [+ "pyvis>=0.3.0",+ "graphviz>=0.20.0",+ "umap-learn>=0.5.0"+]gpu = ["torch>=1.12.0+cu116","faiss-gpu>=1.7.0",diff --git a/libs/semantica/__init__.py b/libs/semantica/__init__.pyindex e0757459..90532bf2 100644--- a/libs/semantica/__init__.py+++ b/libs/semantica/__init__.py@@ -46,6 +46,17 @@ from .kg_qa import (AutoResolver,)+# Visualization+from .visualization import (+ KGVisualizer,+ OntologyVisualizer,+ EmbeddingVisualizer,+ SemanticNetworkVisualizer,+ QualityVisualizer,+ AnalyticsVisualizer,+ TemporalVisualizer,+)+__all__ = [# Core"Semantica",@@ -76,5 +87,13 @@ __all__ = ["AutomatedFixer","AutoMerger","AutoResolver",+ # Visualization+ "KGVisualizer",+ "OntologyVisualizer",+ "EmbeddingVisualizer",+ "SemanticNetworkVisualizer",+ "QualityVisualizer",+ "AnalyticsVisualizer",+ "TemporalVisualizer",]diff --git a/libs/semantica/visualization/__init__.py b/libs/semantica/visualization/__init__.pynew file mode 100644index 00000000..a3b20b5b--- /dev/null+++ b/libs/semantica/visualization/__init__.py@@ -0,0 +1,35 @@+"""+Visualization Module for Semantica Framework++This module provides comprehensive visualization capabilities for all knowledge artifacts+created by Semantica, including knowledge graphs, ontologies, embeddings, semantic networks,+quality metrics, and analytics results.++Exports:+ - KGVisualizer: Knowledge graph visualizations+ - OntologyVisualizer: Ontology hierarchy visualizations+ - EmbeddingVisualizer: Vector embedding visualizations+ - SemanticNetworkVisualizer: Semantic network visualizations+ - QualityVisualizer: Quality metrics visualizations+ - AnalyticsVisualizer: Graph analytics visualizations+ - TemporalVisualizer: Temporal graph visualizations+"""++from .kg_visualizer import KGVisualizer+from .ontology_visualizer import OntologyVisualizer+from .embedding_visualizer import EmbeddingVisualizer+from .semantic_network_visualizer import SemanticNetworkVisualizer+from .quality_visualizer import QualityVisualizer+from .analytics_visualizer import AnalyticsVisualizer+from .temporal_visualizer import TemporalVisualizer++__all__ = [+ "KGVisualizer",+ "OntologyVisualizer",+ "EmbeddingVisualizer",+ "SemanticNetworkVisualizer",+ "QualityVisualizer",+ "AnalyticsVisualizer",+ "TemporalVisualizer",+]+diff --git a/libs/semantica/visualization/analytics_visualizer.py b/libs/semantica/visualization/analytics_visualizer.pynew file mode 100644index 00000000..0e143b82--- /dev/null+++ b/libs/semantica/visualization/analytics_visualizer.py@@ -0,0 +1,441 @@+"""+Graph Analytics Visualizer++This module provides visualization capabilities for graph analytics including+centrality rankings, community structures, connectivity analysis, and graph metrics.+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++import numpy as np+import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure+++class AnalyticsVisualizer:+ """+ Graph analytics visualizer.++ Provides visualization methods for graph analytics including:+ - Centrality rankings+ - Community structures+ - Connectivity analysis+ - Graph metrics dashboards+ """++ def __init__(self, **config):+ """Initialize analytics visualizer."""+ self.logger = get_logger("analytics_visualizer")+ self.config = config+ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT++ def visualize_centrality_rankings(+ self,+ centrality: Dict[str, Any],+ centrality_type: str = "degree",+ top_n: int = 20,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize centrality rankings.++ Args:+ centrality: Centrality calculation results+ centrality_type: Type of centrality+ top_n: Number of top nodes to show+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info(f"Visualizing {centrality_type} centrality rankings")++ # Get rankings+ rankings = centrality.get("rankings", [])+ if not rankings:+ # Try to get from centrality scores+ centrality_scores = centrality.get("centrality", {})+ rankings = [{"node": node, "score": score} for node, score in centrality_scores.items()]+ rankings.sort(key=lambda x: x["score"], reverse=True)++ # Get top N+ top_rankings = rankings[:top_n]++ nodes = [r["node"] for r in top_rankings]+ scores = [r["score"] for r in top_rankings]++ fig = go.Figure(data=[go.Bar(+ x=nodes,+ y=scores,+ marker_color='lightblue',+ text=[f"{s:.3f}" for s in scores],+ textposition='auto'+ )])++ fig.update_layout(+ title=f"Top {top_n} Nodes by {centrality_type.capitalize()} Centrality",+ xaxis_title="Node",+ yaxis_title="Centrality Score",+ xaxis={'tickangle': -45},+ width=1000,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_community_structure(+ self,+ graph: Dict[str, Any],+ communities: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize community structure in graph.++ Args:+ graph: Knowledge graph dictionary+ communities: Community detection results+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing community structure")++ # Use KG visualizer for community visualization+ from .kg_visualizer import KGVisualizer+ kg_viz = KGVisualizer(**self.config)+ return kg_viz.visualize_communities(graph, communities, output, file_path, **options)++ def visualize_connectivity(+ self,+ connectivity: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize connectivity analysis results.++ Args:+ connectivity: Connectivity analysis results+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing connectivity analysis")++ # Extract metrics+ is_connected = connectivity.get("is_connected", False)+ num_components = connectivity.get("num_components", 1)+ component_sizes = connectivity.get("component_sizes", [])++ # Create visualization+ fig = make_subplots(+ rows=1, cols=2,+ subplot_titles=("Connectivity Status", "Component Sizes"),+ specs=[[{"type": "indicator"}, {"type": "bar"}]]+ )++ # Connectivity status+ status_text = "Connected" if is_connected else "Disconnected"+ status_color = "green" if is_connected else "red"++ fig.add_trace(go.Indicator(+ mode="number+delta",+ value=num_components,+ title={"text": f"Components<br>{status_text}"},+ delta={"reference": 1, "valueformat": ".0f"},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=1, col=1)++ # Component sizes+ if component_sizes:+ fig.add_trace(go.Bar(+ x=[f"Component {i+1}" for i in range(len(component_sizes))],+ y=component_sizes,+ marker_color='lightgreen',+ text=component_sizes,+ textposition='auto'+ ), row=1, col=2)++ fig.update_layout(title="Connectivity Analysis")++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_degree_distribution(+ self,+ graph: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize node degree distribution.++ Args:+ graph: Knowledge graph dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing degree distribution")++ # Calculate degrees+ relationships = graph.get("relationships", [])+ entities = graph.get("entities", [])++ degrees = {}+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id", "")+ degrees[entity_id] = 0++ for rel in relationships:+ source_id = rel.get("source") or rel.get("subject", "")+ target_id = rel.get("target") or rel.get("object", "")++ if source_id in degrees:+ degrees[source_id] += 1+ if target_id in degrees:+ degrees[target_id] += 1++ degree_values = list(degrees.values())++ fig = go.Figure(data=[go.Histogram(+ x=degree_values,+ nbinsx=30,+ marker_color='lightblue',+ marker_line_color='darkblue',+ marker_line_width=1+ )])++ fig.update_layout(+ title="Node Degree Distribution",+ xaxis_title="Degree",+ yaxis_title="Frequency",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_metrics_dashboard(+ self,+ metrics: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize comprehensive graph metrics dashboard.++ Args:+ metrics: Graph metrics dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing graph metrics dashboard")++ # Extract key metrics+ num_nodes = metrics.get("num_nodes", metrics.get("total_nodes", 0))+ num_edges = metrics.get("num_edges", metrics.get("total_edges", 0))+ density = metrics.get("density", 0.0)+ avg_path_length = metrics.get("avg_path_length", metrics.get("average_path_length", 0.0))+ diameter = metrics.get("diameter", 0)++ # Create dashboard+ fig = make_subplots(+ rows=2, cols=3,+ subplot_titles=("Nodes", "Edges", "Density", "Avg Path Length", "Diameter", "Summary"),+ specs=[[{"type": "indicator"}, {"type": "indicator"}, {"type": "indicator"}],+ [{"type": "indicator"}, {"type": "indicator"}, {"type": "bar"}]]+ )++ # Nodes+ fig.add_trace(go.Indicator(+ mode="number",+ value=num_nodes,+ title={"text": "Nodes"},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=1, col=1)++ # Edges+ fig.add_trace(go.Indicator(+ mode="number",+ value=num_edges,+ title={"text": "Edges"},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=1, col=2)++ # Density+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=density * 100,+ title={"text": "Density (%)"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkblue"}},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=1, col=3)++ # Avg path length+ fig.add_trace(go.Indicator(+ mode="number",+ value=avg_path_length,+ title={"text": "Avg Path Length"},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=2, col=1)++ # Diameter+ fig.add_trace(go.Indicator(+ mode="number",+ value=diameter,+ title={"text": "Diameter"},+ domain={'x': [0, 1], 'y': [0, 1]}+ ), row=2, col=2)++ # Summary bar chart+ summary_metrics = {+ "Nodes": num_nodes,+ "Edges": num_edges,+ "Density": density * 100+ }++ fig.add_trace(go.Bar(+ x=list(summary_metrics.keys()),+ y=list(summary_metrics.values()),+ marker_color='lightblue'+ ), row=2, col=3)++ fig.update_layout(+ title="Graph Metrics Dashboard",+ height=800+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_centrality_comparison(+ self,+ centrality_results: Dict[str, Dict[str, Any]],+ top_n: int = 10,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize comparison of multiple centrality measures.++ Args:+ centrality_results: Dictionary of centrality type to results+ top_n: Number of top nodes to compare+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing centrality comparison")++ # Extract top nodes for each centrality type+ centrality_types = list(centrality_results.keys())+ all_top_nodes = set()++ for cent_type, results in centrality_results.items():+ rankings = results.get("rankings", [])+ top_nodes = [r["node"] for r in rankings[:top_n]]+ all_top_nodes.update(top_nodes)++ all_top_nodes = sorted(list(all_top_nodes))[:top_n]++ # Build comparison data+ comparison_data = {cent_type: [] for cent_type in centrality_types}++ for node in all_top_nodes:+ for cent_type, results in centrality_results.items():+ centrality_scores = results.get("centrality", {})+ score = centrality_scores.get(node, 0.0)++ # Try rankings if centrality dict not available+ if score == 0.0:+ rankings = results.get("rankings", [])+ for r in rankings:+ if r.get("node") == node:+ score = r.get("score", 0.0)+ break++ comparison_data[cent_type].append(score)++ # Create grouped bar chart+ fig = go.Figure()++ colors = ColorPalette.get_colors(self.color_scheme, len(centrality_types))++ for i, cent_type in enumerate(centrality_types):+ fig.add_trace(go.Bar(+ name=cent_type.capitalize(),+ x=all_top_nodes,+ y=comparison_data[cent_type],+ marker_color=colors[i]+ ))++ fig.update_layout(+ title=f"Top {top_n} Nodes - Centrality Comparison",+ xaxis_title="Node",+ yaxis_title="Centrality Score",+ barmode='group',+ xaxis={'tickangle': -45},+ width=1200,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/embedding_visualizer.py b/libs/semantica/visualization/embedding_visualizer.pynew file mode 100644index 00000000..314bcac3--- /dev/null+++ b/libs/semantica/visualization/embedding_visualizer.py@@ -0,0 +1,517 @@+"""+Embedding Visualizer++This module provides visualization capabilities for embeddings including+2D/3D projections, similarity heatmaps, clustering visualizations, and multi-modal comparisons.+"""++from typing import Any, Dict, List, Optional, Union, Tuple+from pathlib import Path++import numpy as np+import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots+import matplotlib.pyplot as plt+import seaborn as sns+from sklearn.decomposition import PCA+from sklearn.manifold import TSNE++try:+ import umap+except ImportError:+ umap = None++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure, export_matplotlib_figure+++class EmbeddingVisualizer:+ """+ Embedding visualizer.++ Provides visualization methods for embeddings including:+ - 2D/3D dimensionality reduction projections+ - Similarity heatmaps+ - Clustering visualizations+ - Multi-modal embedding comparisons+ """++ def __init__(self, **config):+ """+ Initialize embedding visualizer.++ Args:+ **config: Configuration options:+ - color_scheme: Color scheme name+ - point_size: Point size for scatter plots+ """+ self.logger = get_logger("embedding_visualizer")+ self.config = config++ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT+ self.point_size = config.get("point_size", 5)++ def visualize_2d_projection(+ self,+ embeddings: np.ndarray,+ labels: Optional[List[str]] = None,+ method: str = "umap",+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize embeddings in 2D using dimensionality reduction.++ Args:+ embeddings: Embedding matrix (n_samples, n_features)+ labels: Optional labels for coloring points+ method: Reduction method ("umap", "tsne", "pca")+ output: Output type ("interactive", "html", "png", "svg")+ file_path: Output file path+ **options: Additional options:+ - n_components: Number of components (default: 2)+ - perplexity: Perplexity for t-SNE+ - n_neighbors: Number of neighbors for UMAP++ Returns:+ Visualization figure or None+ """+ self.logger.info(f"Visualizing 2D projection using {method}")++ if embeddings.shape[1] <= 2:+ # Already 2D or less, use directly+ projected = embeddings[:, :2]+ else:+ projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)++ return self._visualize_2d_plotly(projected, labels, output, file_path, **options)++ def visualize_3d_projection(+ self,+ embeddings: np.ndarray,+ labels: Optional[List[str]] = None,+ method: str = "umap",+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize embeddings in 3D using dimensionality reduction.++ Args:+ embeddings: Embedding matrix (n_samples, n_features)+ labels: Optional labels for coloring points+ method: Reduction method ("umap", "tsne", "pca")+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info(f"Visualizing 3D projection using {method}")++ if embeddings.shape[1] <= 3:+ projected = embeddings[:, :3]+ else:+ projected = self._reduce_dimensions(embeddings, method=method, n_components=3, **options)++ return self._visualize_3d_plotly(projected, labels, output, file_path, **options)++ def visualize_similarity_heatmap(+ self,+ embeddings: np.ndarray,+ labels: Optional[List[str]] = None,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize similarity heatmap between embeddings.++ Args:+ embeddings: Embedding matrix+ labels: Optional labels for axis+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing similarity heatmap")++ # Calculate cosine similarity+ # Normalize embeddings+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)+ norms[norms == 0] = 1 # Avoid division by zero+ normalized = embeddings / norms++ # Calculate similarity matrix+ similarity_matrix = np.dot(normalized, normalized.T)++ fig = go.Figure(data=go.Heatmap(+ z=similarity_matrix,+ colorscale='Viridis',+ text=similarity_matrix,+ texttemplate='%{text:.2f}',+ textfont={"size": 8}+ ))++ if labels:+ fig.update_layout(+ xaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels),+ yaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels)+ )++ fig.update_layout(+ title="Embedding Similarity Heatmap",+ xaxis_title="Embedding Index",+ yaxis_title="Embedding Index",+ width=800,+ height=800+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_clustering(+ self,+ embeddings: np.ndarray,+ cluster_labels: np.ndarray,+ method: str = "umap",+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize embeddings with cluster coloring.++ Args:+ embeddings: Embedding matrix+ cluster_labels: Cluster assignments for each embedding+ method: Reduction method for 2D projection+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing embedding clusters")++ # Project to 2D+ if embeddings.shape[1] <= 2:+ projected = embeddings[:, :2]+ else:+ projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)++ num_clusters = len(set(cluster_labels))+ cluster_colors = ColorPalette.get_community_colors(num_clusters, self.color_scheme)++ colors = [cluster_colors[label % num_clusters] for label in cluster_labels]++ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers',+ marker=dict(+ size=self.point_size,+ color=colors,+ line=dict(width=1, color='black')+ ),+ text=[f"Cluster {label}" for label in cluster_labels],+ hovertemplate='%{text}<extra></extra>'+ ))++ fig.update_layout(+ title="Embedding Clusters",+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_multimodal_comparison(+ self,+ text_embeddings: Optional[np.ndarray] = None,+ image_embeddings: Optional[np.ndarray] = None,+ audio_embeddings: Optional[np.ndarray] = None,+ method: str = "umap",+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize multi-modal embeddings side by side.++ Args:+ text_embeddings: Text embeddings+ image_embeddings: Image embeddings+ audio_embeddings: Audio embeddings+ method: Reduction method+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing multi-modal embedding comparison")++ # Collect embeddings and labels+ all_embeddings = []+ all_labels = []+ all_types = []++ if text_embeddings is not None:+ all_embeddings.append(text_embeddings)+ all_labels.extend([f"Text {i}" for i in range(len(text_embeddings))])+ all_types.extend(["text"] * len(text_embeddings))++ if image_embeddings is not None:+ all_embeddings.append(image_embeddings)+ all_labels.extend([f"Image {i}" for i in range(len(image_embeddings))])+ all_types.extend(["image"] * len(image_embeddings))++ if audio_embeddings is not None:+ all_embeddings.append(audio_embeddings)+ all_labels.extend([f"Audio {i}" for i in range(len(audio_embeddings))])+ all_types.extend(["audio"] * len(audio_embeddings))++ if not all_embeddings:+ raise ProcessingError("No embeddings provided")++ # Concatenate embeddings+ combined_embeddings = np.vstack(all_embeddings)++ # Project to 2D+ if combined_embeddings.shape[1] <= 2:+ projected = combined_embeddings[:, :2]+ else:+ projected = self._reduce_dimensions(combined_embeddings, method=method, n_components=2, **options)++ # Color by type+ type_colors = {"text": "#1f77b4", "image": "#ff7f0e", "audio": "#2ca02c"}+ colors = [type_colors.get(t, "#888") for t in all_types]++ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers',+ marker=dict(+ size=self.point_size,+ color=colors,+ line=dict(width=1, color='black')+ ),+ text=all_labels,+ hovertemplate='%{text}<extra></extra>'+ ))++ fig.update_layout(+ title="Multi-Modal Embedding Comparison",+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_quality_metrics(+ self,+ embeddings: np.ndarray,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize embedding quality metrics (norms, distributions).++ Args:+ embeddings: Embedding matrix+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing embedding quality metrics")++ # Calculate norms+ norms = np.linalg.norm(embeddings, axis=1)++ fig = make_subplots(+ rows=1, cols=2,+ subplot_titles=("Embedding Norm Distribution", "Norm Statistics"),+ specs=[[{"type": "histogram"}, {"type": "bar"}]]+ )++ # Norm distribution+ fig.add_trace(+ go.Histogram(x=norms, nbinsx=30, name="Norm Distribution"),+ row=1, col=1+ )++ # Statistics+ stats = {+ "Mean": np.mean(norms),+ "Std": np.std(norms),+ "Min": np.min(norms),+ "Max": np.max(norms)+ }++ fig.add_trace(+ go.Bar(x=list(stats.keys()), y=list(stats.values()), name="Statistics"),+ row=1, col=2+ )++ fig.update_layout(title="Embedding Quality Metrics")++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def _reduce_dimensions(+ self,+ embeddings: np.ndarray,+ method: str = "umap",+ n_components: int = 2,+ **options+ ) -> np.ndarray:+ """Reduce embedding dimensions using specified method."""+ if method == "pca":+ pca = PCA(n_components=n_components, **options)+ return pca.fit_transform(embeddings)++ elif method == "tsne":+ perplexity = options.get("perplexity", min(30, len(embeddings) - 1))+ tsne = TSNE(n_components=n_components, perplexity=perplexity, random_state=42, **options)+ return tsne.fit_transform(embeddings)++ elif method == "umap":+ if umap is not None:+ n_neighbors = options.get("n_neighbors", min(15, len(embeddings) - 1))+ reducer = umap.UMAP(n_components=n_components, n_neighbors=n_neighbors, **options)+ return reducer.fit_transform(embeddings)+ else:+ # Fallback to PCA if UMAP not available+ self.logger.warning("UMAP not available, using PCA. Install with: pip install umap-learn")+ pca = PCA(n_components=n_components)+ return pca.fit_transform(embeddings)++ else:+ # Fallback to PCA+ self.logger.warning(f"Method {method} not available, using PCA")+ pca = PCA(n_components=n_components)+ return pca.fit_transform(embeddings)++ def _visualize_2d_plotly(+ self,+ projected: np.ndarray,+ labels: Optional[List[str]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create 2D Plotly visualization."""+ if labels:+ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers+text',+ text=labels,+ textposition="top center",+ marker=dict(size=self.point_size, color='lightblue', line=dict(width=1, color='darkblue'))+ ))+ else:+ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers',+ marker=dict(size=self.point_size, color='lightblue', line=dict(width=1, color='darkblue'))+ ))++ fig.update_layout(+ title="Embedding 2D Projection",+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def _visualize_3d_plotly(+ self,+ projected: np.ndarray,+ labels: Optional[List[str]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create 3D Plotly visualization."""+ if labels:+ fig = go.Figure(data=go.Scatter3d(+ x=projected[:, 0],+ y=projected[:, 1],+ z=projected[:, 2],+ mode='markers+text',+ text=labels,+ textposition="top center",+ marker=dict(size=self.point_size, color='lightblue', line=dict(width=1, color='darkblue'))+ ))+ else:+ fig = go.Figure(data=go.Scatter3d(+ x=projected[:, 0],+ y=projected[:, 1],+ z=projected[:, 2],+ mode='markers',+ marker=dict(size=self.point_size, color='lightblue', line=dict(width=1, color='darkblue'))+ ))++ fig.update_layout(+ title="Embedding 3D Projection",+ scene=dict(+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ zaxis_title="Dimension 3"+ ),+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/kg_visualizer.py b/libs/semantica/visualization/kg_visualizer.pynew file mode 100644index 00000000..9e42a92f--- /dev/null+++ b/libs/semantica/visualization/kg_visualizer.py@@ -0,0 +1,418 @@+"""+Knowledge Graph Visualizer++This module provides visualization capabilities for knowledge graphs including+network graphs, community views, centrality visualizations, and entity/relationship analysis.+"""++from typing import Any, Dict, List, Optional, Union, Tuple+from pathlib import Path++import numpy as np+import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots+import matplotlib.pyplot as plt+import matplotlib.patches as mpatches++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.layout_algorithms import ForceDirectedLayout, HierarchicalLayout, CircularLayout+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure, export_matplotlib_figure, save_html+++class KGVisualizer:+ """+ Knowledge graph visualizer.++ Provides various visualization methods for knowledge graphs including:+ - Interactive network graphs+ - Community visualizations+ - Centrality visualizations+ - Entity/relationship distribution charts+ """++ def __init__(self, **config):+ """+ Initialize knowledge graph visualizer.++ Args:+ **config: Configuration options:+ - layout: Layout algorithm ("force", "hierarchical", "circular")+ - color_scheme: Color scheme name+ - node_size: Base node size+ - edge_width: Edge width+ """+ self.logger = get_logger("kg_visualizer")+ self.config = config++ self.layout_type = config.get("layout", "force")+ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT+ self.node_size = config.get("node_size", 10)+ self.edge_width = config.get("edge_width", 1)++ # Initialize layout algorithms+ self.force_layout = ForceDirectedLayout(**config)+ self.hierarchical_layout = HierarchicalLayout(**config)+ self.circular_layout = CircularLayout(**config)++ def visualize_network(+ self,+ graph: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize knowledge graph as interactive network.++ Args:+ graph: Knowledge graph dictionary with entities and relationships+ output: Output type ("interactive", "html", "png", "svg")+ file_path: Output file path (required for non-interactive)+ **options: Additional visualization options++ Returns:+ Plotly figure (if interactive) or None+ """+ self.logger.info("Visualizing knowledge graph network")++ # Extract entities and relationships+ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ if not entities:+ raise ProcessingError("No entities found in graph")++ # Build node and edge lists+ nodes = self._extract_nodes(entities)+ edges = self._extract_edges(relationships, entities)++ return self._visualize_network_plotly(nodes, edges, output, file_path, **options)++ def visualize_communities(+ self,+ graph: Dict[str, Any],+ communities: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize knowledge graph with community coloring.++ Args:+ graph: Knowledge graph dictionary+ communities: Community detection results with node_assignments+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing knowledge graph communities")++ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ # Get community assignments+ node_assignments = communities.get("node_assignments", {})+ num_communities = communities.get("num_communities", len(set(node_assignments.values())))++ # Get colors for communities+ community_colors = ColorPalette.get_community_colors(num_communities, self.color_scheme)++ # Build nodes with community colors+ nodes = self._extract_nodes(entities)+ for node in nodes:+ entity_id = node.get("id", "")+ community_id = node_assignments.get(entity_id, 0)+ node["community"] = community_id+ node["color"] = community_colors[community_id % len(community_colors)]++ edges = self._extract_edges(relationships, entities)++ return self._visualize_network_plotly(nodes, edges, output, file_path, community_colors=community_colors, **options)++ def visualize_centrality(+ self,+ graph: Dict[str, Any],+ centrality: Dict[str, Any],+ centrality_type: str = "degree",+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize knowledge graph with centrality-based node sizing/coloring.++ Args:+ graph: Knowledge graph dictionary+ centrality: Centrality calculation results+ centrality_type: Type of centrality ("degree", "betweenness", "closeness", "eigenvector")+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info(f"Visualizing knowledge graph with {centrality_type} centrality")++ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ # Get centrality scores+ centrality_scores = centrality.get("centrality", {})+ if not centrality_scores:+ # Try to get from rankings+ rankings = centrality.get("rankings", [])+ centrality_scores = {r["node"]: r["score"] for r in rankings}++ # Build nodes with centrality information+ nodes = self._extract_nodes(entities)+ max_centrality = max(centrality_scores.values()) if centrality_scores else 1.0++ for node in nodes:+ entity_id = node.get("id", "")+ score = centrality_scores.get(entity_id, 0.0)+ node["centrality"] = score+ node["size"] = self.node_size * (1 + 5 * (score / max_centrality)) if max_centrality > 0 else self.node_size++ edges = self._extract_edges(relationships, entities)++ return self._visualize_network_plotly(nodes, edges, output, file_path, size_by_centrality=True, **options)++ def visualize_entity_types(+ self,+ graph: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize entity type distribution.++ Args:+ graph: Knowledge graph dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing entity type distribution")++ entities = graph.get("entities", [])++ # Count entity types+ type_counts = {}+ for entity in entities:+ entity_type = entity.get("type") or entity.get("entity_type") or "Unknown"+ type_counts[entity_type] = type_counts.get(entity_type, 0) + 1++ fig = px.bar(+ x=list(type_counts.keys()),+ y=list(type_counts.values()),+ labels={"x": "Entity Type", "y": "Count"},+ title="Entity Type Distribution"+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_relationship_matrix(+ self,+ graph: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize relationship frequency matrix between entity types.++ Args:+ graph: Knowledge graph dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing relationship matrix")++ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ # Build entity type map+ entity_type_map = {}+ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id", "")+ entity_type = entity.get("type") or entity.get("entity_type", "Unknown")+ entity_type_map[entity_id] = entity_type++ # Count relationships between types+ type_matrix = {}+ for rel in relationships:+ source_id = rel.get("source") or rel.get("subject", "")+ target_id = rel.get("target") or rel.get("object", "")++ source_type = entity_type_map.get(source_id, "Unknown")+ target_type = entity_type_map.get(target_id, "Unknown")++ key = (source_type, target_type)+ type_matrix[key] = type_matrix.get(key, 0) + 1++ # Convert to matrix format+ source_types = sorted(set(t[0] for t in type_matrix.keys()))+ target_types = sorted(set(t[1] for t in type_matrix.keys()))++ matrix = np.zeros((len(source_types), len(target_types)))+ for i, source_type in enumerate(source_types):+ for j, target_type in enumerate(target_types):+ matrix[i, j] = type_matrix.get((source_type, target_type), 0)++ fig = go.Figure(data=go.Heatmap(+ z=matrix,+ x=target_types,+ y=source_types,+ colorscale='Viridis',+ text=matrix,+ texttemplate='%{text}',+ textfont={"size": 10}+ ))+ fig.update_layout(+ title="Relationship Frequency Matrix",+ xaxis_title="Target Entity Type",+ yaxis_title="Source Entity Type"+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def _extract_nodes(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Extract nodes from entities."""+ nodes = []+ for entity in entities:+ node = {+ "id": entity.get("id") or entity.get("entity_id", ""),+ "label": entity.get("text") or entity.get("label") or entity.get("name", ""),+ "type": entity.get("type") or entity.get("entity_type", "entity"),+ "metadata": entity.get("metadata", {})+ }+ nodes.append(node)+ return nodes++ def _extract_edges(self, relationships: List[Dict[str, Any]], entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Extract edges from relationships."""+ edges = []+ entity_map = {e.get("id") or e.get("entity_id", ""): e for e in entities}++ for rel in relationships:+ source_id = rel.get("source") or rel.get("subject", "")+ target_id = rel.get("target") or rel.get("object", "")++ if source_id in entity_map and target_id in entity_map:+ edge = {+ "source": source_id,+ "target": target_id,+ "label": rel.get("type") or rel.get("relationship_type") or rel.get("predicate", ""),+ "metadata": rel.get("metadata", {})+ }+ edges.append(edge)++ return edges++ def _visualize_network_plotly(+ self,+ nodes: List[Dict[str, Any]],+ edges: List[Dict[str, Any]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create Plotly network visualization."""+ # Compute layout+ node_ids = [n["id"] for n in nodes]+ edge_tuples = [(e["source"], e["target"]) for e in edges]++ if self.layout_type == "hierarchical":+ pos = self.hierarchical_layout.compute_layout(node_ids, edge_tuples, **options)+ elif self.layout_type == "circular":+ pos = self.circular_layout.compute_layout(node_ids, edge_tuples, **options)+ else:+ pos = self.force_layout.compute_layout(node_ids, edge_tuples, **options)++ # Get entity type colors+ entity_types = list(set(n.get("type", "entity") for n in nodes))+ type_colors = ColorPalette.get_entity_type_colors(entity_types, self.color_scheme)++ # Prepare edge traces+ edge_x = []+ edge_y = []+ for edge in edges:+ source_pos = pos.get(edge["source"])+ target_pos = pos.get(edge["target"])+ if source_pos and target_pos:+ edge_x.extend([source_pos[0], target_pos[0], None])+ edge_y.extend([source_pos[1], target_pos[1], None])++ edge_trace = go.Scatter(+ x=edge_x, y=edge_y,+ line=dict(width=self.edge_width, color='#888'),+ hoverinfo='none',+ mode='lines'+ )++ # Prepare node traces+ node_x = [pos[n["id"]][0] for n in nodes if n["id"] in pos]+ node_y = [pos[n["id"]][1] for n in nodes if n["id"] in pos]+ node_text = [n["label"] for n in nodes if n["id"] in pos]+ node_colors = [type_colors.get(n.get("type", "entity"), "#888") for n in nodes if n["id"] in pos]+ node_sizes = [n.get("size", self.node_size) for n in nodes if n["id"] in pos]++ node_trace = go.Scatter(+ x=node_x, y=node_y,+ mode='markers+text',+ hoverinfo='text',+ text=node_text,+ textposition="middle center",+ marker=dict(+ size=node_sizes,+ color=node_colors,+ line=dict(width=2, color='white')+ )+ )++ fig = go.Figure(+ data=[edge_trace, node_trace],+ layout=go.Layout(+ title='Knowledge Graph Network',+ showlegend=False,+ hovermode='closest',+ margin=dict(b=20, l=5, r=5, t=40),+ xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)+ )+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/ontology_visualizer.py b/libs/semantica/visualization/ontology_visualizer.pynew file mode 100644index 00000000..591a06e8--- /dev/null+++ b/libs/semantica/visualization/ontology_visualizer.py@@ -0,0 +1,537 @@+"""+Ontology Visualizer++This module provides visualization capabilities for ontologies including+class hierarchies, property graphs, and ontology structure visualizations.+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots+import matplotlib.pyplot as plt+import matplotlib.patches as mpatches+from matplotlib.patches import FancyBboxPatch++try:+ import graphviz+except ImportError:+ graphviz = None++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.layout_algorithms import HierarchicalLayout+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure, export_matplotlib_figure, save_html+++class OntologyVisualizer:+ """+ Ontology visualizer.++ Provides visualization methods for ontologies including:+ - Class hierarchy trees+ - Property graphs+ - Ontology structure networks+ - Class-property matrices+ """++ def __init__(self, **config):+ """+ Initialize ontology visualizer.++ Args:+ **config: Configuration options:+ - color_scheme: Color scheme name+ - node_size: Base node size+ """+ self.logger = get_logger("ontology_visualizer")+ self.config = config++ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT+ self.node_size = config.get("node_size", 15)++ def visualize_hierarchy(+ self,+ ontology: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize class hierarchy as tree.++ Args:+ ontology: Ontology dictionary with classes+ output: Output type ("interactive", "html", "png", "svg", "dot")+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing ontology class hierarchy")++ classes = ontology.get("classes", [])++ if not classes:+ raise ProcessingError("No classes found in ontology")++ # If output is dot and graphviz is available, use it+ if output == "dot" and graphviz is not None and file_path:+ return self._visualize_hierarchy_graphviz(classes, file_path, **options)++ # Build hierarchy tree+ hierarchy = self._build_hierarchy_tree(classes)++ return self._visualize_hierarchy_plotly(hierarchy, classes, output, file_path, **options)++ def visualize_properties(+ self,+ ontology: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize property graph showing properties and their domains/ranges.++ Args:+ ontology: Ontology dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing ontology properties")++ properties = ontology.get("properties", [])+ classes = ontology.get("classes", [])++ if not properties:+ raise ProcessingError("No properties found in ontology")++ return self._visualize_properties_plotly(properties, classes, output, file_path, **options)++ def visualize_structure(+ self,+ ontology: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize ontology structure as network.++ Args:+ ontology: Ontology dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing ontology structure")++ classes = ontology.get("classes", [])+ properties = ontology.get("properties", [])++ # Build nodes and edges+ nodes = []+ edges = []++ # Add class nodes+ for cls in classes:+ nodes.append({+ "id": cls.get("name") or cls.get("uri", ""),+ "label": cls.get("label") or cls.get("name", ""),+ "type": "class"+ })++ # Add hierarchy edges+ parent = cls.get("parent") or cls.get("subClassOf")+ if parent:+ edges.append({+ "source": cls.get("name") or cls.get("uri", ""),+ "target": parent,+ "type": "subClassOf"+ })++ # Add property nodes+ for prop in properties:+ prop_name = prop.get("name") or prop.get("uri", "")+ nodes.append({+ "id": prop_name,+ "label": prop.get("label") or prop.get("name", ""),+ "type": "property"+ })++ # Add domain edges+ domain = prop.get("domain")+ if domain:+ edges.append({+ "source": prop_name,+ "target": domain,+ "type": "domain"+ })++ # Add range edges+ range_val = prop.get("range")+ if range_val:+ edges.append({+ "source": prop_name,+ "target": range_val,+ "type": "range"+ })++ return self._visualize_structure_plotly(nodes, edges, output, file_path, **options)++ def visualize_class_property_matrix(+ self,+ ontology: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize class-property matrix showing which properties belong to which classes.++ Args:+ ontology: Ontology dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing class-property matrix")++ classes = ontology.get("classes", [])+ properties = ontology.get("properties", [])++ # Build matrix+ class_names = [cls.get("name") or cls.get("label", "") for cls in classes]+ property_names = [prop.get("name") or prop.get("label", "") for prop in properties]++ matrix = []+ for cls in classes:+ row = []+ cls_props = cls.get("properties", [])+ for prop in properties:+ prop_name = prop.get("name") or prop.get("uri", "")+ # Check if property belongs to class (via domain or direct property list)+ domain = prop.get("domain")+ has_prop = prop_name in cls_props or domain == cls.get("name")+ row.append(1 if has_prop else 0)+ matrix.append(row)++ fig = go.Figure(data=go.Heatmap(+ z=matrix,+ x=property_names,+ y=class_names,+ colorscale='Blues',+ text=matrix,+ texttemplate='%{text}',+ textfont={"size": 8}+ ))+ fig.update_layout(+ title="Class-Property Matrix",+ xaxis_title="Properties",+ yaxis_title="Classes",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_metrics(+ self,+ ontology: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize ontology metrics dashboard.++ Args:+ ontology: Ontology dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing ontology metrics")++ classes = ontology.get("classes", [])+ properties = ontology.get("properties", [])++ # Calculate metrics+ num_classes = len(classes)+ num_properties = len(properties)++ # Calculate hierarchy depth+ max_depth = 0+ for cls in classes:+ depth = self._calculate_class_depth(cls, classes)+ max_depth = max(max_depth, depth)++ fig = make_subplots(+ rows=1, cols=3,+ subplot_titles=("Class Count", "Property Count", "Max Depth"),+ specs=[[{"type": "indicator"}, {"type": "indicator"}, {"type": "indicator"}]]+ )++ fig.add_trace(go.Indicator(+ mode="number",+ value=num_classes,+ title={"text": "Classes"},+ domain={'x': [0, 0.33], 'y': [0, 1]}+ ), row=1, col=1)++ fig.add_trace(go.Indicator(+ mode="number",+ value=num_properties,+ title={"text": "Properties"},+ domain={'x': [0.33, 0.66], 'y': [0, 1]}+ ), row=1, col=2)++ fig.add_trace(go.Indicator(+ mode="number",+ value=max_depth,+ title={"text": "Max Depth"},+ domain={'x': [0.66, 1], 'y': [0, 1]}+ ), row=1, col=3)++ fig.update_layout(title="Ontology Metrics Dashboard")++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def _build_hierarchy_tree(self, classes: List[Dict[str, Any]]) -> Dict[str, List[str]]:+ """Build hierarchy tree structure."""+ tree = {}+ root_classes = []++ for cls in classes:+ cls_name = cls.get("name") or cls.get("uri", "")+ parent = cls.get("parent") or cls.get("subClassOf")++ if parent:+ if parent not in tree:+ tree[parent] = []+ tree[parent].append(cls_name)+ else:+ root_classes.append(cls_name)++ if cls_name not in tree:+ tree[cls_name] = []++ return tree++ def _calculate_class_depth(self, cls: Dict[str, Any], all_classes: List[Dict[str, Any]]) -> int:+ """Calculate depth of class in hierarchy."""+ parent = cls.get("parent") or cls.get("subClassOf")+ if not parent:+ return 1++ # Find parent class+ for p_cls in all_classes:+ if (p_cls.get("name") or p_cls.get("uri", "")) == parent:+ return 1 + self._calculate_class_depth(p_cls, all_classes)++ return 1++ def _visualize_hierarchy_plotly(+ self,+ hierarchy: Dict[str, List[str]],+ classes: List[Dict[str, Any]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create Plotly hierarchy visualization."""+ # Build tree structure for plotly+ # This is a simplified tree visualization+ # For full tree, would need more complex layout++ # Get root classes+ all_class_names = {cls.get("name") or cls.get("uri", ""): cls for cls in classes}+ root_classes = [name for name in all_class_names.keys() if name not in [c for children in hierarchy.values() for c in children]]++ if not root_classes:+ root_classes = list(all_class_names.keys())[:1] if all_class_names else []++ # Build node and edge lists for tree+ nodes = []+ edges = []++ def add_node_and_children(cls_name, level=0, x_offset=0):+ nodes.append({+ "name": cls_name,+ "level": level,+ "x": x_offset,+ "y": -level+ })++ children = hierarchy.get(cls_name, [])+ child_width = 1.0 / max(len(children), 1)+ for i, child in enumerate(children):+ child_x = x_offset - 0.5 + (i + 0.5) * child_width+ edges.append({+ "source": cls_name,+ "target": child+ })+ add_node_and_children(child, level + 1, child_x)++ # Start from root+ root_x = 0.5+ root_width = 1.0 / max(len(root_classes), 1)+ for i, root in enumerate(root_classes):+ root_x = (i + 0.5) * root_width+ add_node_and_children(root, 0, root_x)++ # Create visualization+ edge_x = []+ edge_y = []+ node_positions = {n["name"]: (n["x"], n["y"]) for n in nodes}++ for edge in edges:+ source_pos = node_positions.get(edge["source"])+ target_pos = node_positions.get(edge["target"])+ if source_pos and target_pos:+ edge_x.extend([source_pos[0], target_pos[0], None])+ edge_y.extend([source_pos[1], target_pos[1], None])++ edge_trace = go.Scatter(+ x=edge_x, y=edge_y,+ line=dict(width=2, color='#888'),+ hoverinfo='none',+ mode='lines'+ )++ node_x = [n["x"] for n in nodes]+ node_y = [n["y"] for n in nodes]+ node_text = [n["name"] for n in nodes]++ node_trace = go.Scatter(+ x=node_x, y=node_y,+ mode='markers+text',+ text=node_text,+ textposition="middle center",+ marker=dict(size=self.node_size*10, color='lightblue', line=dict(width=2, color='darkblue'))+ )++ fig = go.Figure(+ data=[edge_trace, node_trace],+ layout=go.Layout(+ title='Ontology Class Hierarchy',+ showlegend=False,+ hovermode='closest',+ margin=dict(b=20, l=5, r=5, t=40),+ xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)+ )+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def _visualize_hierarchy_graphviz(+ self,+ classes: List[Dict[str, Any]],+ file_path: Path,+ **options+ ) -> None:+ """Create Graphviz hierarchy visualization."""+ if graphviz is None:+ raise ProcessingError("Graphviz not available. Install with: pip install graphviz")++ dot = graphviz.Digraph(comment='Ontology Hierarchy')++ # Add nodes+ for cls in classes:+ cls_name = cls.get("name") or cls.get("label", "")+ dot.node(cls_name, cls_name)++ # Add edges+ for cls in classes:+ cls_name = cls.get("name") or cls.get("label", "")+ parent = cls.get("parent") or cls.get("subClassOf")+ if parent:+ dot.edge(parent, cls_name)++ dot.render(str(file_path), format='svg', cleanup=True)+ self.logger.info(f"Saved Graphviz hierarchy to {file_path}")++ def _visualize_properties_plotly(+ self,+ properties: List[Dict[str, Any]],+ classes: List[Dict[str, Any]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create Plotly property visualization."""+ # Build property graph+ nodes = []+ edges = []++ # Add class nodes+ for cls in classes:+ cls_name = cls.get("name") or cls.get("uri", "")+ nodes.append({"id": cls_name, "label": cls.get("label") or cls_name, "type": "class"})++ # Add property nodes and edges+ for prop in properties:+ prop_name = prop.get("name") or prop.get("uri", "")+ nodes.append({"id": prop_name, "label": prop.get("label") or prop_name, "type": "property"})++ domain = prop.get("domain")+ if domain:+ edges.append({"source": prop_name, "target": domain, "type": "domain"})++ range_val = prop.get("range")+ if range_val:+ edges.append({"source": prop_name, "target": range_val, "type": "range"})++ # Use similar approach as KG visualizer+ from .kg_visualizer import KGVisualizer+ kg_viz = KGVisualizer(**self.config)+ return kg_viz._visualize_network_plotly(nodes, edges, output, file_path, **options)++ def _visualize_structure_plotly(+ self,+ nodes: List[Dict[str, Any]],+ edges: List[Dict[str, Any]],+ output: str,+ file_path: Optional[Path],+ **options+ ) -> Optional[Any]:+ """Create Plotly structure visualization."""+ from .kg_visualizer import KGVisualizer+ kg_viz = KGVisualizer(**self.config)+ return kg_viz._visualize_network_plotly(nodes, edges, output, file_path, **options)+diff --git a/libs/semantica/visualization/quality_visualizer.py b/libs/semantica/visualization/quality_visualizer.pynew file mode 100644index 00000000..3b6d8a97--- /dev/null+++ b/libs/semantica/visualization/quality_visualizer.py@@ -0,0 +1,379 @@+"""+Quality Metrics Visualizer++This module provides visualization capabilities for knowledge graph quality metrics,+including quality dashboards, completeness metrics, consistency analysis, and issue tracking.+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.color_schemes import ColorScheme+from .utils.export_formats import export_plotly_figure+++class QualityVisualizer:+ """+ Quality metrics visualizer.++ Provides visualization methods for quality metrics including:+ - Quality dashboards+ - Completeness metrics+ - Consistency analysis+ - Issue tracking+ """++ def __init__(self, **config):+ """Initialize quality visualizer."""+ self.logger = get_logger("quality_visualizer")+ self.config = config+ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT++ def visualize_dashboard(+ self,+ quality_report: Any,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize comprehensive quality dashboard.++ Args:+ quality_report: QualityReport object or dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing quality dashboard")++ # Extract metrics+ if hasattr(quality_report, "overall_score"):+ overall_score = quality_report.overall_score+ consistency_score = quality_report.consistency_score+ completeness_score = quality_report.completeness_score+ elif isinstance(quality_report, dict):+ overall_score = quality_report.get("overall_score", 0.0)+ consistency_score = quality_report.get("consistency_score", 0.0)+ completeness_score = quality_report.get("completeness_score", 0.0)+ else:+ overall_score = 0.0+ consistency_score = 0.0+ completeness_score = 0.0++ # Create dashboard+ fig = make_subplots(+ rows=2, cols=2,+ subplot_titles=("Overall Quality Score", "Consistency Score", "Completeness Score", "Quality Breakdown"),+ specs=[[{"type": "indicator"}, {"type": "indicator"}],+ [{"type": "indicator"}, {"type": "bar"}]]+ )++ # Overall score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=overall_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Overall Quality"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkblue"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=1, col=1)++ # Consistency score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=consistency_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Consistency"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkgreen"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=1, col=2)++ # Completeness score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=completeness_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Completeness"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkorange"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=2, col=1)++ # Quality breakdown+ metrics = {+ "Overall": overall_score * 100,+ "Consistency": consistency_score * 100,+ "Completeness": completeness_score * 100+ }++ fig.add_trace(go.Bar(+ x=list(metrics.keys()),+ y=list(metrics.values()),+ marker_color='lightblue'+ ), row=2, col=2)++ fig.update_layout(+ title="Knowledge Graph Quality Dashboard",+ height=800+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_score_distribution(+ self,+ quality_scores: List[float],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize quality score distribution.++ Args:+ quality_scores: List of quality scores+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing quality score distribution")++ fig = go.Figure(data=[go.Histogram(+ x=quality_scores,+ nbinsx=30,+ marker_color='lightblue',+ marker_line_color='darkblue',+ marker_line_width=1+ )])++ fig.update_layout(+ title="Quality Score Distribution",+ xaxis_title="Quality Score",+ yaxis_title="Frequency",+ width=800,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_issues(+ self,+ quality_report: Any,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize quality issues.++ Args:+ quality_report: QualityReport with issues+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing quality issues")++ # Extract issues+ issues = []+ if hasattr(quality_report, "issues"):+ issues = quality_report.issues+ elif isinstance(quality_report, dict):+ issues = quality_report.get("issues", [])++ if not issues:+ self.logger.warning("No issues found in quality report")+ return None++ # Count issues by type and severity+ issue_counts = {}+ severity_counts = {}++ for issue in issues:+ issue_type = issue.type if hasattr(issue, "type") else issue.get("type", "Unknown")+ severity = issue.severity if hasattr(issue, "severity") else issue.get("severity", "Unknown")++ issue_counts[issue_type] = issue_counts.get(issue_type, 0) + 1+ severity_counts[severity] = severity_counts.get(severity, 0) + 1++ # Create subplots+ fig = make_subplots(+ rows=1, cols=2,+ subplot_titles=("Issues by Type", "Issues by Severity"),+ specs=[[{"type": "bar"}, {"type": "pie"}]]+ )++ # Issues by type+ fig.add_trace(go.Bar(+ x=list(issue_counts.keys()),+ y=list(issue_counts.values()),+ marker_color='lightcoral',+ name="Issues"+ ), row=1, col=1)++ # Issues by severity+ fig.add_trace(go.Pie(+ labels=list(severity_counts.keys()),+ values=list(severity_counts.values()),+ name="Severity"+ ), row=1, col=2)++ fig.update_layout(+ title="Quality Issues Analysis",+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_completeness_metrics(+ self,+ completeness_metrics: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize completeness metrics.++ Args:+ completeness_metrics: Completeness metrics dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing completeness metrics")++ # Extract metrics+ entity_completeness = completeness_metrics.get("entity_completeness", 0.0)+ property_completeness = completeness_metrics.get("property_completeness", 0.0)+ relationship_completeness = completeness_metrics.get("relationship_completeness", 0.0)++ metrics = {+ "Entity Completeness": entity_completeness * 100,+ "Property Completeness": property_completeness * 100,+ "Relationship Completeness": relationship_completeness * 100+ }++ fig = go.Figure(data=[go.Bar(+ x=list(metrics.keys()),+ y=list(metrics.values()),+ marker_color='lightgreen',+ text=[f"{v:.1f}%" for v in metrics.values()],+ textposition='auto'+ )])++ fig.update_layout(+ title="Completeness Metrics",+ xaxis_title="Metric",+ yaxis_title="Completeness (%)",+ yaxis_range=[0, 100],+ width=800,+ height=500+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_consistency_heatmap(+ self,+ consistency_data: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize consistency heatmap.++ Args:+ consistency_data: Consistency data dictionary+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing consistency heatmap")++ # Extract consistency matrix+ matrix = consistency_data.get("consistency_matrix", [])+ labels = consistency_data.get("labels", [])++ if not matrix:+ raise ProcessingError("No consistency matrix found")++ import numpy as np+ matrix = np.array(matrix)++ fig = go.Figure(data=go.Heatmap(+ z=matrix,+ x=labels if labels else None,+ y=labels if labels else None,+ colorscale='RdYlGn',+ text=matrix,+ texttemplate='%{text:.2f}',+ textfont={"size": 8}+ ))++ fig.update_layout(+ title="Consistency Heatmap",+ xaxis_title="Entity/Type",+ yaxis_title="Entity/Type",+ width=800,+ height=800+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/semantic_network_visualizer.py b/libs/semantica/visualization/semantic_network_visualizer.pynew file mode 100644index 00000000..084c456b--- /dev/null+++ b/libs/semantica/visualization/semantic_network_visualizer.py@@ -0,0 +1,194 @@+"""+Semantic Network Visualizer++This module provides visualization capabilities for semantic networks.+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++import plotly.graph_objects as go+import plotly.express as px++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.layout_algorithms import ForceDirectedLayout+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure+++class SemanticNetworkVisualizer:+ """+ Semantic network visualizer.++ Provides visualization methods for semantic networks.+ """++ def __init__(self, **config):+ """Initialize semantic network visualizer."""+ self.logger = get_logger("semantic_network_visualizer")+ self.config = config+ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT++ def visualize_network(+ self,+ semantic_network: Any,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize semantic network.++ Args:+ semantic_network: SemanticNetwork object+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing semantic network")++ # Extract nodes and edges from semantic network+ nodes = []+ if hasattr(semantic_network, "nodes"):+ for node in semantic_network.nodes:+ nodes.append({+ "id": node.id,+ "label": node.label,+ "type": node.type,+ "metadata": node.metadata+ })+ elif isinstance(semantic_network, dict):+ for node in semantic_network.get("nodes", []):+ nodes.append({+ "id": node.get("id", ""),+ "label": node.get("label", ""),+ "type": node.get("type", ""),+ "metadata": node.get("metadata", {})+ })++ edges = []+ if hasattr(semantic_network, "edges"):+ for edge in semantic_network.edges:+ edges.append({+ "source": edge.source,+ "target": edge.target,+ "label": edge.label,+ "metadata": edge.metadata+ })+ elif isinstance(semantic_network, dict):+ for edge in semantic_network.get("edges", []):+ edges.append({+ "source": edge.get("source", ""),+ "target": edge.get("target", ""),+ "label": edge.get("label", ""),+ "metadata": edge.get("metadata", {})+ })++ # Use KG visualizer for network visualization+ from .kg_visualizer import KGVisualizer+ graph = {"entities": nodes, "relationships": edges}+ kg_viz = KGVisualizer(**self.config)+ return kg_viz.visualize_network(graph, output, file_path, **options)++ def visualize_node_types(+ self,+ semantic_network: Any,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize node type distribution.++ Args:+ semantic_network: SemanticNetwork object+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing semantic network node types")++ # Extract nodes+ nodes = []+ if hasattr(semantic_network, "nodes"):+ nodes = semantic_network.nodes+ elif isinstance(semantic_network, dict):+ nodes = semantic_network.get("nodes", [])++ # Count node types+ type_counts = {}+ for node in nodes:+ node_type = node.type if hasattr(node, "type") else node.get("type", "Unknown")+ type_counts[node_type] = type_counts.get(node_type, 0) + 1++ fig = px.bar(+ x=list(type_counts.keys()),+ y=list(type_counts.values()),+ labels={"x": "Node Type", "y": "Count"},+ title="Semantic Network Node Type Distribution"+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_edge_types(+ self,+ semantic_network: Any,+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize edge type distribution.++ Args:+ semantic_network: SemanticNetwork object+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing semantic network edge types")++ # Extract edges+ edges = []+ if hasattr(semantic_network, "edges"):+ edges = semantic_network.edges+ elif isinstance(semantic_network, dict):+ edges = semantic_network.get("edges", [])++ # Count edge types+ type_counts = {}+ for edge in edges:+ edge_type = edge.label if hasattr(edge, "label") else edge.get("label", "Unknown")+ type_counts[edge_type] = type_counts.get(edge_type, 0) + 1++ fig = px.bar(+ x=list(type_counts.keys()),+ y=list(type_counts.values()),+ labels={"x": "Edge Type", "y": "Count"},+ title="Semantic Network Edge Type Distribution"+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/temporal_visualizer.py b/libs/semantica/visualization/temporal_visualizer.pynew file mode 100644index 00000000..6eacc872--- /dev/null+++ b/libs/semantica/visualization/temporal_visualizer.py@@ -0,0 +1,383 @@+"""+Temporal Graph Visualizer++This module provides visualization capabilities for temporal knowledge graphs including+timeline views, temporal network animations, snapshot comparisons, and temporal pattern visualizations.+"""++from typing import Any, Dict, List, Optional, Union+from pathlib import Path++import plotly.graph_objects as go+import plotly.express as px+from plotly.subplots import make_subplots++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError+from .utils.color_schemes import ColorPalette, ColorScheme+from .utils.export_formats import export_plotly_figure+++class TemporalVisualizer:+ """+ Temporal graph visualizer.++ Provides visualization methods for temporal graphs including:+ - Timeline views+ - Temporal network animations+ - Snapshot comparisons+ - Temporal pattern visualizations+ """++ def __init__(self, **config):+ """Initialize temporal visualizer."""+ self.logger = get_logger("temporal_visualizer")+ self.config = config+ color_scheme_name = config.get("color_scheme", "default")+ try:+ self.color_scheme = ColorScheme[color_scheme_name.upper()]+ except (KeyError, AttributeError):+ self.color_scheme = ColorScheme.DEFAULT++ def visualize_timeline(+ self,+ temporal_data: Dict[str, Any],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize timeline of entity/relationship changes.++ Args:+ temporal_data: Temporal data dictionary with timestamps and changes+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing temporal timeline")++ # Extract timeline data+ events = temporal_data.get("events", [])+ timestamps = temporal_data.get("timestamps", [])++ if not events:+ raise ProcessingError("No temporal events found")++ # Build timeline+ event_types = []+ event_times = []+ event_labels = []++ for event in events:+ event_time = event.get("timestamp") or event.get("time", "")+ event_type = event.get("type") or event.get("event_type", "change")+ event_label = event.get("label") or event.get("entity", "")++ event_times.append(event_time)+ event_types.append(event_type)+ event_labels.append(event_label)++ # Create Gantt chart style timeline+ fig = go.Figure()++ # Group by type+ type_colors = {}+ unique_types = list(set(event_types))+ colors = ColorPalette.get_colors(self.color_scheme, len(unique_types))+ for i, t in enumerate(unique_types):+ type_colors[t] = colors[i]++ for event_type in unique_types:+ mask = [t == event_type for t in event_types]+ type_times = [event_times[i] for i in range(len(event_times)) if mask[i]]+ type_labels = [event_labels[i] for i in range(len(event_labels)) if mask[i]]++ fig.add_trace(go.Scatter(+ x=type_times,+ y=[event_type] * len(type_times),+ mode='markers',+ name=event_type,+ marker=dict(size=10, color=type_colors[event_type]),+ text=type_labels,+ hovertemplate='%{text}<br>Time: %{x}<extra></extra>'+ ))++ fig.update_layout(+ title="Temporal Timeline",+ xaxis_title="Time",+ yaxis_title="Event Type",+ width=1200,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_temporal_patterns(+ self,+ patterns: List[Dict[str, Any]],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize detected temporal patterns.++ Args:+ patterns: List of temporal patterns+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing temporal patterns")++ if not patterns:+ raise ProcessingError("No temporal patterns found")++ # Extract pattern data+ pattern_types = [p.get("pattern_type", "Unknown") for p in patterns]+ start_times = [p.get("start_time", "") for p in patterns]+ end_times = [p.get("end_time", "") for p in patterns]+ entities = [p.get("entities", []) for p in patterns]++ # Create timeline visualization+ fig = go.Figure()++ for i, pattern in enumerate(patterns):+ pattern_type = pattern.get("pattern_type", "Unknown")+ start_time = pattern.get("start_time", "")+ end_time = pattern.get("end_time", "")+ pattern_entities = pattern.get("entities", [])++ # Create a bar for the pattern duration+ fig.add_trace(go.Scatter(+ x=[start_time, end_time],+ y=[i, i],+ mode='lines+markers',+ name=pattern_type,+ line=dict(width=10, color=ColorPalette.get_color_by_index(self.color_scheme, i)),+ text=f"{pattern_type}: {len(pattern_entities)} entities",+ hovertemplate='%{text}<br>Start: %{x}<extra></extra>'+ ))++ fig.update_layout(+ title="Temporal Patterns",+ xaxis_title="Time",+ yaxis_title="Pattern",+ width=1200,+ height=max(400, len(patterns) * 50)+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_snapshot_comparison(+ self,+ snapshots: Dict[str, Dict[str, Any]],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize comparison of graph snapshots at different times.++ Args:+ snapshots: Dictionary mapping timestamps to graph snapshots+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing snapshot comparison")++ timestamps = sorted(snapshots.keys())++ # Extract metrics for each snapshot+ metrics_over_time = {+ "entities": [],+ "relationships": [],+ "density": []+ }++ for timestamp in timestamps:+ snapshot = snapshots[timestamp]+ entities = snapshot.get("entities", [])+ relationships = snapshot.get("relationships", [])++ metrics_over_time["entities"].append(len(entities))+ metrics_over_time["relationships"].append(len(relationships))++ # Calculate density+ num_nodes = len(entities)+ num_edges = len(relationships)+ max_edges = num_nodes * (num_nodes - 1) / 2 if num_nodes > 1 else 0+ density = num_edges / max_edges if max_edges > 0 else 0+ metrics_over_time["density"].append(density)++ # Create line chart+ fig = go.Figure()++ fig.add_trace(go.Scatter(+ x=timestamps,+ y=metrics_over_time["entities"],+ mode='lines+markers',+ name='Entities',+ line=dict(color='blue', width=2)+ ))++ fig.add_trace(go.Scatter(+ x=timestamps,+ y=metrics_over_time["relationships"],+ mode='lines+markers',+ name='Relationships',+ line=dict(color='red', width=2)+ ))++ fig.add_trace(go.Scatter(+ x=timestamps,+ y=metrics_over_time["density"],+ mode='lines+markers',+ name='Density',+ line=dict(color='green', width=2),+ yaxis='y2'+ ))++ fig.update_layout(+ title="Graph Evolution Over Time",+ xaxis_title="Time",+ yaxis_title="Count",+ yaxis2=dict(title="Density", overlaying='y', side='right'),+ width=1200,+ height=600+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_version_history(+ self,+ version_history: List[Dict[str, Any]],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize version history tree.++ Args:+ version_history: List of version information+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing version history")++ # Build tree structure+ versions = sorted(version_history, key=lambda v: v.get("version", ""))++ # Create timeline+ version_names = [v.get("version", f"v{i}") for i, v in enumerate(versions)]+ version_dates = [v.get("date", v.get("timestamp", "")) for v in versions]+ version_changes = [v.get("changes", v.get("description", "")) for v in versions]++ fig = go.Figure()++ fig.add_trace(go.Scatter(+ x=version_dates,+ y=[i for i in range(len(versions))],+ mode='lines+markers+text',+ text=version_names,+ textposition="middle right",+ line=dict(color='blue', width=2),+ marker=dict(size=10, color='red'),+ hovertemplate='Version: %{text}<br>Date: %{x}<extra></extra>'+ ))++ fig.update_layout(+ title="Version History",+ xaxis_title="Date",+ yaxis_title="Version",+ yaxis=dict(tickmode='array', tickvals=list(range(len(versions))), ticktext=version_names),+ width=1200,+ height=max(400, len(versions) * 50)+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None++ def visualize_metrics_evolution(+ self,+ metrics_history: Dict[str, List[float]],+ timestamps: List[str],+ output: str = "interactive",+ file_path: Optional[Union[str, Path]] = None,+ **options+ ) -> Optional[Any]:+ """+ Visualize metrics evolution over time.++ Args:+ metrics_history: Dictionary mapping metric names to time series+ timestamps: List of timestamps+ output: Output type+ file_path: Output file path+ **options: Additional options++ Returns:+ Visualization figure or None+ """+ self.logger.info("Visualizing metrics evolution")++ fig = go.Figure()++ colors = ColorPalette.get_colors(self.color_scheme, len(metrics_history))++ for i, (metric_name, values) in enumerate(metrics_history.items()):+ fig.add_trace(go.Scatter(+ x=timestamps,+ y=values,+ mode='lines+markers',+ name=metric_name,+ line=dict(color=colors[i], width=2),+ marker=dict(size=6)+ ))++ fig.update_layout(+ title="Metrics Evolution Over Time",+ xaxis_title="Time",+ yaxis_title="Metric Value",+ width=1200,+ height=600,+ hovermode='x unified'+ )++ if output == "interactive":+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ return None+diff --git a/libs/semantica/visualization/utils/__init__.py b/libs/semantica/visualization/utils/__init__.pynew file mode 100644index 00000000..143735a5--- /dev/null+++ b/libs/semantica/visualization/utils/__init__.py@@ -0,0 +1,23 @@+"""+Visualization Utilities Module++Utility functions and classes for visualization operations.+"""++from .layout_algorithms import LayoutAlgorithm, ForceDirectedLayout, HierarchicalLayout, CircularLayout+from .color_schemes import ColorScheme, get_color_scheme, ColorPalette+from .export_formats import export_plotly_figure, export_matplotlib_figure, save_html++__all__ = [+ "LayoutAlgorithm",+ "ForceDirectedLayout",+ "HierarchicalLayout",+ "CircularLayout",+ "ColorScheme",+ "get_color_scheme",+ "ColorPalette",+ "export_plotly_figure",+ "export_matplotlib_figure",+ "save_html",+]+diff --git a/libs/semantica/visualization/utils/color_schemes.py b/libs/semantica/visualization/utils/color_schemes.pynew file mode 100644index 00000000..bf33cffd--- /dev/null+++ b/libs/semantica/visualization/utils/color_schemes.py@@ -0,0 +1,135 @@+"""+Color schemes for visualizations.++This module provides color schemes and palettes for consistent visualization styling.+"""++from typing import List, Dict, Optional+from enum import Enum+++class ColorScheme(Enum):+ """Predefined color schemes."""+ DEFAULT = "default"+ VIBRANT = "vibrant"+ PASTEL = "pastel"+ DARK = "dark"+ LIGHT = "light"+ COLORBLIND = "colorblind"+++class ColorPalette:+ """Color palette manager."""++ # Default color schemes+ SCHEMES = {+ ColorScheme.DEFAULT: [+ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",+ "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"+ ],+ ColorScheme.VIBRANT: [+ "#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8",+ "#F7DC6F", "#BB8FCE", "#85C1E2", "#F8B739", "#6C5CE7"+ ],+ ColorScheme.PASTEL: [+ "#FFB3BA", "#BAFFC9", "#BAE1FF", "#FFFFBA", "#FFDFBA",+ "#E0BBE4", "#FEC8C1", "#FFCCCB", "#DDA0DD", "#B0E0E6"+ ],+ ColorScheme.DARK: [+ "#2C3E50", "#34495E", "#7F8C8D", "#95A5A6", "#BDC3C7",+ "#ECF0F1", "#3498DB", "#E74C3C", "#F39C12", "#9B59B6"+ ],+ ColorScheme.LIGHT: [+ "#FFFFFF", "#F8F9FA", "#E9ECEF", "#DEE2E6", "#CED4DA",+ "#ADB5BD", "#6C757D", "#495057", "#343A40", "#212529"+ ],+ ColorScheme.COLORBLIND: [+ "#006BA4", "#FF800E", "#ABABAB", "#595959", "#5F9ED1",+ "#C85200", "#898989", "#A2C8EC", "#FFBC79", "#CFCFCF"+ ],+ }++ @classmethod+ def get_colors(cls, scheme: ColorScheme = ColorScheme.DEFAULT, count: int = 10) -> List[str]:+ """+ Get color list for a scheme.++ Args:+ scheme: Color scheme to use+ count: Number of colors needed++ Returns:+ List of color hex codes+ """+ base_colors = cls.SCHEMES.get(scheme, cls.SCHEMES[ColorScheme.DEFAULT])++ if count <= len(base_colors):+ return base_colors[:count]++ # Repeat colors if more needed+ colors = []+ for i in range(count):+ colors.append(base_colors[i % len(base_colors)])++ return colors++ @classmethod+ def get_color_by_index(cls, scheme: ColorScheme, index: int) -> str:+ """+ Get a single color by index.++ Args:+ scheme: Color scheme to use+ index: Color index++ Returns:+ Color hex code+ """+ colors = cls.SCHEMES.get(scheme, cls.SCHEMES[ColorScheme.DEFAULT])+ return colors[index % len(colors)]++ @classmethod+ def get_entity_type_colors(cls, entity_types: List[str], scheme: ColorScheme = ColorScheme.DEFAULT) -> Dict[str, str]:+ """+ Get color mapping for entity types.++ Args:+ entity_types: List of unique entity types+ scheme: Color scheme to use++ Returns:+ Dictionary mapping entity types to colors+ """+ colors = cls.get_colors(scheme, len(entity_types))+ return {entity_type: colors[i] for i, entity_type in enumerate(entity_types)}++ @classmethod+ def get_community_colors(cls, num_communities: int, scheme: ColorScheme = ColorScheme.DEFAULT) -> List[str]:+ """+ Get colors for communities.++ Args:+ num_communities: Number of communities+ scheme: Color scheme to use++ Returns:+ List of colors for each community+ """+ return cls.get_colors(scheme, num_communities)+++def get_color_scheme(scheme_name: str) -> ColorScheme:+ """+ Get color scheme by name.++ Args:+ scheme_name: Name of the color scheme++ Returns:+ ColorScheme enum value+ """+ try:+ return ColorScheme[scheme_name.upper()]+ except KeyError:+ return ColorScheme.DEFAULT+diff --git a/libs/semantica/visualization/utils/export_formats.py b/libs/semantica/visualization/utils/export_formats.pynew file mode 100644index 00000000..d483b0a6--- /dev/null+++ b/libs/semantica/visualization/utils/export_formats.py@@ -0,0 +1,99 @@+"""+Export utilities for visualizations.++This module provides functions for exporting visualizations to various formats.+"""++from typing import Optional, Union+from pathlib import Path++from ...utils.logging import get_logger+from ...utils.exceptions import ProcessingError+++def export_plotly_figure(fig, file_path: Union[str, Path], format: str = "html", **options) -> None:+ """+ Export Plotly figure to file.++ Args:+ fig: Plotly figure object+ file_path: Output file path+ format: Export format ("html", "png", "svg", "pdf", "json")+ **options: Additional export options+ """+ logger = get_logger("export_plotly")+ file_path = Path(file_path)++ try:+ if format == "html":+ fig.write_html(str(file_path), **options)+ elif format == "png":+ fig.write_image(str(file_path), **options)+ elif format == "svg":+ fig.write_image(str(file_path), format="svg", **options)+ elif format == "pdf":+ fig.write_image(str(file_path), format="pdf", **options)+ elif format == "json":+ fig.write_json(str(file_path), **options)+ else:+ raise ProcessingError(f"Unsupported export format: {format}")++ logger.info(f"Exported Plotly figure to {file_path}")+ except Exception as e:+ logger.error(f"Failed to export Plotly figure: {e}")+ raise ProcessingError(f"Failed to export Plotly figure: {e}")+++def export_matplotlib_figure(fig, file_path: Union[str, Path], format: str = "png", **options) -> None:+ """+ Export Matplotlib figure to file.++ Args:+ fig: Matplotlib figure object+ file_path: Output file path+ format: Export format ("png", "svg", "pdf", "jpg")+ **options: Additional export options (dpi, bbox_inches, etc.)+ """+ logger = get_logger("export_matplotlib")+ file_path = Path(file_path)++ try:+ dpi = options.get("dpi", 300)+ bbox_inches = options.get("bbox_inches", "tight")++ fig.savefig(+ str(file_path),+ format=format,+ dpi=dpi,+ bbox_inches=bbox_inches,+ **{k: v for k, v in options.items() if k not in ["dpi", "bbox_inches"]}+ )++ logger.info(f"Exported Matplotlib figure to {file_path}")+ except Exception as e:+ logger.error(f"Failed to export Matplotlib figure: {e}")+ raise ProcessingError(f"Failed to export Matplotlib figure: {e}")+++def save_html(html_content: str, file_path: Union[str, Path]) -> None:+ """+ Save HTML content to file.++ Args:+ html_content: HTML content string+ file_path: Output file path+ """+ logger = get_logger("save_html")+ file_path = Path(file_path)++ try:+ file_path.parent.mkdir(parents=True, exist_ok=True)++ with open(file_path, "w", encoding="utf-8") as f:+ f.write(html_content)++ logger.info(f"Saved HTML to {file_path}")+ except Exception as e:+ logger.error(f"Failed to save HTML: {e}")+ raise ProcessingError(f"Failed to save HTML: {e}")+diff --git a/libs/semantica/visualization/utils/layout_algorithms.py b/libs/semantica/visualization/utils/layout_algorithms.pynew file mode 100644index 00000000..3940a765--- /dev/null+++ b/libs/semantica/visualization/utils/layout_algorithms.py@@ -0,0 +1,287 @@+"""+Graph layout algorithms for visualization.++This module provides various layout algorithms for positioning nodes in graph visualizations.+"""++from typing import Any, Dict, List, Optional, Tuple+from abc import ABC, abstractmethod++import numpy as np+import networkx as nx++from ...utils.logging import get_logger+++class LayoutAlgorithm(ABC):+ """Abstract base class for graph layout algorithms."""++ @abstractmethod+ def compute_layout(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]],+ **options+ ) -> Dict[str, Tuple[float, float]]:+ """+ Compute node positions for graph layout.++ Args:+ nodes: List of node identifiers+ edges: List of (source, target) edge tuples+ **options: Layout-specific options++ Returns:+ Dictionary mapping node IDs to (x, y) coordinates+ """+ pass+++class ForceDirectedLayout(LayoutAlgorithm):+ """+ Force-directed layout algorithm (spring layout).++ Uses force-directed positioning to create visually appealing graph layouts.+ """++ def __init__(self, **config):+ """Initialize force-directed layout."""+ self.logger = get_logger("force_directed_layout")+ self.config = config+ self.k = config.get("k", 1.0) # Optimal distance between nodes+ self.iterations = config.get("iterations", 50)+ self.temperature = config.get("temperature", 1.0)+ self.cooling_factor = config.get("cooling_factor", 0.95)++ def compute_layout(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]],+ **options+ ) -> Dict[str, Tuple[float, float]]:+ """Compute force-directed layout."""+ if len(nodes) > 0:+ try:+ # Create NetworkX graph+ G = nx.Graph()+ G.add_nodes_from(nodes)+ G.add_edges_from(edges)++ # Use NetworkX spring layout+ pos = nx.spring_layout(+ G,+ k=self.k,+ iterations=self.iterations,+ **options+ )++ return {node: (float(pos[node][0]), float(pos[node][1])) for node in nodes}+ except Exception as e:+ self.logger.warning(f"NetworkX layout failed: {e}, using basic implementation")++ # Basic force-directed implementation+ return self._basic_force_directed(nodes, edges)++ def _basic_force_directed(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]]+ ) -> Dict[str, Tuple[float, float]]:+ """Basic force-directed layout implementation."""+ n = len(nodes)+ if n == 0:+ return {}++ # Initialize positions randomly+ pos = {node: (np.random.random(), np.random.random()) for node in nodes}++ # Build adjacency+ adjacency = {node: [] for node in nodes}+ for source, target in edges:+ if source in adjacency and target in adjacency:+ adjacency[source].append(target)+ adjacency[target].append(source)++ # Iterative force-directed positioning+ temp = self.temperature+ for _ in range(self.iterations):+ forces = {node: np.array([0.0, 0.0]) for node in nodes}++ # Repulsive forces (all nodes repel each other)+ for i, node1 in enumerate(nodes):+ for node2 in nodes[i+1:]:+ dx = pos[node2][0] - pos[node1][0]+ dy = pos[node2][1] - pos[node1][1]+ dist_sq = dx*dx + dy*dy + 0.01 # Avoid division by zero+ dist = np.sqrt(dist_sq)++ force = self.k * self.k / dist_sq+ forces[node1] += np.array([-force * dx / dist, -force * dy / dist])+ forces[node2] += np.array([force * dx / dist, force * dy / dist])++ # Attractive forces (connected nodes attract)+ for source, target in edges:+ if source in pos and target in pos:+ dx = pos[target][0] - pos[source][0]+ dy = pos[target][1] - pos[source][1]+ dist_sq = dx*dx + dy*dy + 0.01+ dist = np.sqrt(dist_sq)++ force = dist * dist / self.k+ forces[source] += np.array([force * dx / dist, force * dy / dist])+ forces[target] += np.array([-force * dx / dist, -force * dy / dist])++ # Update positions+ for node in nodes:+ force = forces[node]+ force_mag = np.linalg.norm(force)+ if force_mag > temp:+ force = force * temp / force_mag++ pos[node] = (pos[node][0] + force[0], pos[node][1] + force[1])++ # Cool down+ temp *= self.cooling_factor++ return pos+++class HierarchicalLayout(LayoutAlgorithm):+ """+ Hierarchical/tree layout algorithm.++ Positions nodes in a hierarchical tree structure.+ """++ def __init__(self, **config):+ """Initialize hierarchical layout."""+ self.logger = get_logger("hierarchical_layout")+ self.config = config+ self.vertical_spacing = config.get("vertical_spacing", 2.0)+ self.horizontal_spacing = config.get("horizontal_spacing", 1.0)++ def compute_layout(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]],+ root: Optional[str] = None,+ **options+ ) -> Dict[str, Tuple[float, float]]:+ """Compute hierarchical layout."""+ if len(nodes) > 0:+ try:+ G = nx.DiGraph()+ G.add_nodes_from(nodes)+ G.add_edges_from(edges)++ # Find root if not provided+ if root is None:+ roots = [n for n in G.nodes() if G.in_degree(n) == 0]+ root = roots[0] if roots else nodes[0]++ # Try NetworkX hierarchical layout (requires graphviz)+ try:+ pos = nx.nx_agraph.graphviz_layout(G, prog='dot', root=root)+ if pos:+ return {node: (float(pos[node][0]), float(pos[node][1])) for node in nodes}+ except Exception:+ pass # Fall through to simple hierarchical layout+ except Exception as e:+ self.logger.warning(f"NetworkX hierarchical layout failed: {e}, using basic implementation")++ root = root or nodes[0] if nodes else None+ return self._simple_hierarchical(nodes, edges, root)++ def _simple_hierarchical(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]],+ root: Optional[str]+ ) -> Dict[str, Tuple[float, float]]:+ """Simple hierarchical layout implementation."""+ if not nodes:+ return {}++ if root is None:+ root = nodes[0]++ # Build tree structure+ children = {node: [] for node in nodes}+ parents = {node: None for node in nodes}++ for source, target in edges:+ if source in children and target in children:+ children[source].append(target)+ parents[target] = source++ # Assign levels (BFS)+ levels = {root: 0}+ queue = [root]++ while queue:+ node = queue.pop(0)+ for child in children.get(node, []):+ if child not in levels:+ levels[child] = levels[node] + 1+ queue.append(child)++ # Position nodes+ pos = {}+ level_nodes = {}+ for node, level in levels.items():+ if level not in level_nodes:+ level_nodes[level] = []+ level_nodes[level].append(node)++ for level, nodes_at_level in sorted(level_nodes.items()):+ y = -level * self.vertical_spacing+ x_spacing = self.horizontal_spacing+ start_x = -(len(nodes_at_level) - 1) * x_spacing / 2++ for i, node in enumerate(nodes_at_level):+ x = start_x + i * x_spacing+ pos[node] = (x, y)++ # Position unconnected nodes+ for node in nodes:+ if node not in pos:+ pos[node] = (0, 0)++ return pos+++class CircularLayout(LayoutAlgorithm):+ """+ Circular layout algorithm.++ Positions nodes in a circle.+ """++ def __init__(self, **config):+ """Initialize circular layout."""+ self.logger = get_logger("circular_layout")+ self.config = config+ self.radius = config.get("radius", 1.0)++ def compute_layout(+ self,+ nodes: List[str],+ edges: List[Tuple[str, str]],+ **options+ ) -> Dict[str, Tuple[float, float]]:+ """Compute circular layout."""+ if not nodes:+ return {}++ n = len(nodes)+ angle_step = 2 * np.pi / n++ pos = {}+ for i, node in enumerate(nodes):+ angle = i * angle_step+ x = self.radius * np.cos(angle)+ y = self.radius * np.sin(angle)+ pos[node] = (float(x), float(y))++ return pos+