-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinteractive_visualization.py
More file actions
2047 lines (1703 loc) · 91.2 KB
/
interactive_visualization.py
File metadata and controls
2047 lines (1703 loc) · 91.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Enhanced Interactive Visualization Module for Large Networks
Features: Advanced interactivity, critical path highlighting, filtering, and zoom-aware labeling
PERFORMANCE OPTIMIZED with caching, threading, and JIT compilation
"""
import plotly.graph_objects as go
import plotly.offline as pyo
import networkx as nx
import numpy as np
from typing import Dict, List, Set, Optional, Tuple
import logging
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QPushButton, QHBoxLayout,
QCheckBox, QSlider, QLabel, QComboBox, QSpinBox,
QGroupBox, QGridLayout, QTextEdit, QSplitter)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import pyqtSignal, QUrl, Qt, QThread, pyqtSlot
import tempfile
import os
import colorsys
import json
from dataclasses import dataclass
from collections import defaultdict
import concurrent.futures
import threading
import time
# JIT compilation for performance
try:
from numba import jit, prange
NUMBA_AVAILABLE = True
except ImportError:
NUMBA_AVAILABLE = False
# Fallback decorator that does nothing
def jit(*args, **kwargs):
def decorator(func):
return func
return decorator
def prange(x):
return range(x)
logger = logging.getLogger(__name__)
@dataclass
class LayoutOptions:
"""Enhanced options for network layout algorithms."""
algorithm: str = "spring_enhanced"
k: float = None # Optimal distance between nodes
iterations: int = 100
seed: int = 42
dimension: int = 2
edge_bundling: bool = False
hierarchical_direction: str = "TB" # Top-Bottom, Left-Right
cluster_separation: float = 1.5
@dataclass
class FilterOptions:
"""Options for filtering network display."""
min_degree: int = 0
max_degree: int = 100
show_routers: bool = True
show_clients: bool = True
show_isolated: bool = True
show_vulnerable: bool = True
highlight_critical_paths: bool = False
edge_weight_threshold: float = 0.0
show_node_labels: bool = True
node_label_size: int = 12
def sanitize_label(label: str) -> str:
"""Remove problematic Unicode characters from labels."""
if not label:
return ""
# Keep only ASCII and basic alphanumeric
return ''.join(char for char in label if ord(char) < 127 or char.isalnum()).strip()
class EnhancedNetworkVisualizer(QWidget):
"""Enhanced interactive network visualization with advanced features and performance optimizations."""
node_clicked = pyqtSignal(str)
node_selected = pyqtSignal(list) # For multiple node selection
def __init__(self, parent=None):
super().__init__(parent)
self.nodes = {}
self.edges = []
self.graph = None
self.pos = None
self.current_html = None
self.critical_paths = []
self.selected_nodes = set()
self.highlight_nodes = set() # Track currently highlighted nodes
# Performance optimizations
self.performance_cache = PerformanceCache()
self.layout_thread = None
self._last_update_hash = None
self._cached_node_traces = None
self._cached_edge_traces = None
# Filter and layout options
self.filter_options = FilterOptions()
self.layout_options = LayoutOptions()
self._init_ui()
def _init_ui(self):
"""Initialize the enhanced UI components."""
main_layout = QHBoxLayout(self)
# Create splitter for resizable panels
splitter = QSplitter(Qt.Orientation.Horizontal)
# Left panel for controls
control_panel = self._create_control_panel()
splitter.addWidget(control_panel)
# Right panel for visualization
viz_panel = self._create_visualization_panel()
splitter.addWidget(viz_panel)
# Set initial sizes (control panel smaller)
splitter.setSizes([300, 1000])
main_layout.addWidget(splitter)
def _create_control_panel(self) -> QWidget:
"""Create the control panel with various options."""
panel = QWidget()
layout = QVBoxLayout(panel)
# Layout controls
layout_group = QGroupBox("Layout Options")
layout_grid = QGridLayout(layout_group)
# Layout algorithm selector
layout_grid.addWidget(QLabel("Algorithm:"), 0, 0)
self.layout_combo = QComboBox()
self.layout_combo.addItems([
"spring_enhanced", "spring_enhanced_fast", "force_atlas", "circular_clustered",
"hierarchical", "edge_bundled", "community_based"
])
self.layout_combo.currentTextChanged.connect(self._on_layout_changed)
layout_grid.addWidget(self.layout_combo, 0, 1)
# Iterations slider
layout_grid.addWidget(QLabel("Iterations:"), 1, 0)
self.iterations_slider = QSlider(Qt.Orientation.Horizontal)
self.iterations_slider.setRange(10, 1000)
self.iterations_slider.setValue(1000)
self.iterations_slider.valueChanged.connect(self._on_iterations_changed)
layout_grid.addWidget(self.iterations_slider, 1, 1)
self.iterations_label = QLabel("1000")
layout_grid.addWidget(self.iterations_label, 1, 2)
# Node separation
layout_grid.addWidget(QLabel("Node Separation:"), 2, 0)
self.separation_slider = QSlider(Qt.Orientation.Horizontal)
self.separation_slider.setRange(50, 3000)
self.separation_slider.setValue(3000)
self.separation_slider.valueChanged.connect(self._on_separation_changed)
layout_grid.addWidget(self.separation_slider, 2, 1)
self.separation_label = QLabel("30.0")
layout_grid.addWidget(self.separation_label, 2, 2)
layout.addWidget(layout_group)
# Filter controls
filter_group = QGroupBox("Display Filters")
filter_grid = QGridLayout(filter_group)
# Node type filters
self.show_routers_cb = QCheckBox("Show Routers")
self.show_routers_cb.setChecked(True)
self.show_routers_cb.toggled.connect(self._on_filter_changed)
filter_grid.addWidget(self.show_routers_cb, 0, 0)
self.show_clients_cb = QCheckBox("Show Clients")
self.show_clients_cb.setChecked(True)
self.show_clients_cb.toggled.connect(self._on_filter_changed)
filter_grid.addWidget(self.show_clients_cb, 0, 1)
self.show_isolated_cb = QCheckBox("Show Isolated")
self.show_isolated_cb.setChecked(True)
self.show_isolated_cb.toggled.connect(self._on_filter_changed)
filter_grid.addWidget(self.show_isolated_cb, 1, 0)
self.show_vulnerable_cb = QCheckBox("Show Vulnerable")
self.show_vulnerable_cb.setChecked(True)
self.show_vulnerable_cb.toggled.connect(self._on_filter_changed)
filter_grid.addWidget(self.show_vulnerable_cb, 1, 1)
# Degree range filter
filter_grid.addWidget(QLabel("Min Connections:"), 2, 0)
self.min_degree_spin = QSpinBox()
self.min_degree_spin.setRange(0, 100)
self.min_degree_spin.valueChanged.connect(self._on_filter_changed)
filter_grid.addWidget(self.min_degree_spin, 2, 1)
filter_grid.addWidget(QLabel("Max Connections:"), 3, 0)
self.max_degree_spin = QSpinBox()
self.max_degree_spin.setRange(1, 100)
self.max_degree_spin.setValue(100)
self.max_degree_spin.valueChanged.connect(self._on_filter_changed)
filter_grid.addWidget(self.max_degree_spin, 3, 1)
# Critical path highlighting
self.highlight_critical_cb = QCheckBox("Highlight Critical Paths")
self.highlight_critical_cb.toggled.connect(self._on_filter_changed)
filter_grid.addWidget(self.highlight_critical_cb, 4, 0, 1, 2)
layout.addWidget(filter_group)
# Node label controls
label_group = QGroupBox("Node Labels")
label_grid = QGridLayout(label_group)
self.show_labels_cb = QCheckBox("Show Node Labels")
self.show_labels_cb.setChecked(True)
self.show_labels_cb.toggled.connect(self._on_filter_changed)
label_grid.addWidget(self.show_labels_cb, 0, 0, 1, 2)
label_grid.addWidget(QLabel("Label Size:"), 1, 0)
self.label_size_slider = QSlider(Qt.Orientation.Horizontal)
self.label_size_slider.setRange(8, 24)
self.label_size_slider.setValue(12)
self.label_size_slider.valueChanged.connect(self._on_label_size_changed)
label_grid.addWidget(self.label_size_slider, 1, 1)
self.label_size_label = QLabel("12")
label_grid.addWidget(self.label_size_label, 1, 2)
layout.addWidget(label_group)
# Action buttons
button_group = QGroupBox("Actions")
button_layout = QVBoxLayout(button_group)
self.recalculate_btn = QPushButton("Recalculate Layout")
self.recalculate_btn.clicked.connect(self._recalculate_layout)
button_layout.addWidget(self.recalculate_btn)
self.find_critical_btn = QPushButton("Find Critical Paths")
self.find_critical_btn.clicked.connect(self._find_critical_paths)
button_layout.addWidget(self.find_critical_btn)
self.center_selected_btn = QPushButton("Center on Selected")
self.center_selected_btn.clicked.connect(self._center_on_selected)
button_layout.addWidget(self.center_selected_btn)
self.export_btn = QPushButton("Export HTML")
self.export_btn.clicked.connect(self._export_html)
button_layout.addWidget(self.export_btn)
layout.addWidget(button_group)
# Node details area
details_group = QGroupBox("Node Details")
details_layout = QVBoxLayout(details_group)
self.node_details = QTextEdit()
self.node_details.setMaximumHeight(200)
self.node_details.setReadOnly(True)
# Fix styling to ensure text is visible
self.node_details.setStyleSheet("""
QTextEdit {
background-color: white;
color: black;
border: 1px solid #ccc;
border-radius: 4px;
padding: 8px;
font-family: 'Courier New', monospace;
font-size: 11px;
}
""")
self.node_details.setPlainText("Click a node to view its details...")
details_layout.addWidget(self.node_details)
layout.addWidget(details_group)
layout.addStretch()
return panel
def _create_visualization_panel(self) -> QWidget:
"""Create the visualization panel."""
panel = QWidget()
layout = QVBoxLayout(panel)
# Web view for Plotly
self.web_view = QWebEngineView()
# Enable JavaScript and local content access
settings = self.web_view.settings()
from PyQt6.QtWebEngineCore import QWebEngineSettings
settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
# Connect title change signal to handle node details updates
self.web_view.titleChanged.connect(self._on_title_changed)
layout.addWidget(self.web_view)
return panel
def update_network(self, nodes: Dict, edges: List[Dict],
highlight_nodes: Optional[Set[str]] = None,
node_scores: Optional[Dict] = None):
"""Update the network visualization with enhanced features and proper synchronization."""
logger.info(f"Updating network with {len(nodes)} nodes and {len(edges)} edges")
self.nodes = nodes
self.edges = edges
self.highlight_nodes = highlight_nodes or set()
self.node_scores = node_scores or {}
# Clear caches when data changes
self.performance_cache.clear()
# Build NetworkX graph
self.graph = nx.Graph()
for node_id, node_data in nodes.items():
self.graph.add_node(node_id, **node_data)
for edge in edges:
if edge['from'] in nodes and edge['to'] in nodes:
# Create a copy of edge data to avoid modifying original
edge_attrs = edge.copy()
# Calculate weight based on SNR if available
weight = edge.get('weight', 1.0)
if 'snr' in edge and edge['snr'] is not None:
# Higher SNR = lower weight (better connection)
weight = max(0.1, 1.0 - (edge['snr'] + 10) / 30)
# Remove weight from attributes to avoid conflict
if 'weight' in edge_attrs:
del edge_attrs['weight']
# Add edge with weight as explicit parameter
self.graph.add_edge(edge['from'], edge['to'], weight=weight, **edge_attrs)
logger.info(f"Built graph with {len(self.graph.nodes())} nodes and {len(self.graph.edges())} edges")
# Calculate layout - this now includes proper validation and fallbacks
self._calculate_enhanced_layout()
# Only proceed with visualization if we have valid positions
if not self.pos or len(self.pos) != len(self.graph.nodes()):
logger.error("Failed to generate valid layout positions, cannot update visualization")
return
# Create the visualization
self._create_enhanced_plotly_figure()
def _calculate_enhanced_layout(self):
"""Calculate node positions using enhanced layout algorithms with performance optimizations."""
if len(self.graph.nodes()) == 0:
self.pos = {}
logger.warning("No nodes in graph for layout calculation")
return
algorithm = self.layout_options.algorithm
logger.info(f"Calculating layout using {algorithm} for {len(self.graph.nodes())} nodes")
# Check cache first - but be more selective about what we cache
graph_hash = f"{len(self.graph.nodes())}_{len(self.graph.edges())}_{algorithm}_{self.layout_options.iterations}"
cached_pos = self.performance_cache.get(f"layout_{graph_hash}")
if cached_pos is not None and len(cached_pos) == len(self.graph.nodes()):
logger.info(f"Using cached layout for {len(self.graph.nodes())} nodes")
self.pos = cached_pos
return
# For better responsiveness, use synchronous calculation for smaller graphs
# or when we need immediate results
if len(self.graph.nodes()) <= 200 or algorithm not in ["spring_enhanced", "spring_enhanced_fast"]:
self._calculate_layout_sync()
else:
# Use background thread only for very large graphs with expensive algorithms
self._calculate_layout_threaded()
def _calculate_layout_threaded(self):
"""Calculate layout in background thread - with proper synchronization."""
if self.layout_thread and self.layout_thread.isRunning():
self.layout_thread.terminate()
self.layout_thread.wait()
# Start with a temporary layout so nodes aren't scattered
logger.info("Generating temporary layout while calculating optimal positions...")
self.pos = nx.spring_layout(self.graph, seed=42, iterations=10) # Quick temporary layout
self.layout_thread = LayoutCalculationThread(
self.graph,
self.layout_options.algorithm,
self.layout_options
)
self.layout_thread.layout_finished.connect(self._on_layout_finished)
self.layout_thread.start()
logger.info("Background layout calculation started...")
@pyqtSlot(dict)
def _on_layout_finished(self, pos):
"""Handle completion of background layout calculation."""
if pos and len(pos) == len(self.graph.nodes()):
logger.info(f"Background layout completed with {len(pos)} node positions")
self.pos = pos
# Cache the result with validation
graph_hash = f"{len(self.graph.nodes())}_{len(self.graph.edges())}_{self.layout_options.algorithm}_{self.layout_options.iterations}"
self.performance_cache.set(f"layout_{graph_hash}", pos)
# Clear node trace cache to force regeneration with new positions
self.performance_cache.clear()
# Update visualization with new positions
self._create_enhanced_plotly_figure()
else:
logger.error(f"Background layout calculation failed or returned invalid positions: {len(pos) if pos else 0} positions for {len(self.graph.nodes())} nodes")
def _calculate_layout_sync(self):
"""Calculate layout synchronously with proper error handling."""
try:
algorithm = self.layout_options.algorithm
start_time = time.time()
if algorithm == "spring_enhanced_fast" and NUMBA_AVAILABLE and len(self.graph.nodes()) > 50:
# Use JIT-optimized spring layout for medium-sized graphs
nodes = list(self.graph.nodes())
n = len(nodes)
# Create adjacency matrix
adj_matrix = nx.adjacency_matrix(self.graph, nodelist=nodes).toarray()
# Initialize positions more thoughtfully
pos_array = np.random.RandomState(42).random((n, 2)) * 10 - 5
# Parameters
k = self.layout_options.cluster_separation / np.sqrt(n) if n > 0 else 1.0
iterations = min(self.layout_options.iterations, 50)
# Optimize
optimized_pos = optimize_spring_layout_step(pos_array, adj_matrix, k, iterations)
# Convert to dict
self.pos = {nodes[i]: (float(optimized_pos[i, 0]), float(optimized_pos[i, 1])) for i in range(n)}
elif algorithm == "spring_enhanced":
# Standard NetworkX spring layout with optimizations
k_value = self.layout_options.cluster_separation / np.sqrt(len(self.graph.nodes()))
self.pos = nx.spring_layout(
self.graph,
k=k_value,
iterations=min(self.layout_options.iterations, 100),
seed=self.layout_options.seed,
weight='weight'
)
elif algorithm == "circular_clustered":
# Optimized circular clustered layout
try:
communities = nx.community.greedy_modularity_communities(self.graph)
self.pos = {}
if len(communities) > 0:
for i, community in enumerate(communities):
subgraph = self.graph.subgraph(community)
angle = 2 * np.pi * i / len(communities)
center_x = 3 * np.cos(angle)
center_y = 3 * np.sin(angle)
if len(community) > 0:
sub_pos = nx.circular_layout(subgraph, scale=0.5)
for node, (x, y) in sub_pos.items():
self.pos[node] = (x + center_x, y + center_y)
else:
# Fallback if no communities found
self.pos = nx.circular_layout(self.graph)
except Exception as e:
logger.warning(f"Circular clustered layout failed: {e}, using fallback")
self.pos = nx.circular_layout(self.graph)
elif algorithm == "force_atlas":
# Force Atlas style layout
self.pos = nx.spring_layout(
self.graph,
k=2/np.sqrt(len(self.graph.nodes())),
iterations=min(self.layout_options.iterations * 2, 200),
seed=self.layout_options.seed,
weight='weight'
)
elif algorithm == "community_based":
# Layout based on community detection
try:
communities = nx.community.greedy_modularity_communities(self.graph)
self.pos = {}
if len(communities) > 0:
# Position communities in a grid
grid_size = int(np.ceil(np.sqrt(len(communities))))
for i, community in enumerate(communities):
if len(community) == 0:
continue
grid_x = (i % grid_size) * 4
grid_y = (i // grid_size) * 4
subgraph = self.graph.subgraph(community)
sub_pos = nx.spring_layout(subgraph, scale=1.5, seed=42)
for node, (x, y) in sub_pos.items():
self.pos[node] = (x + grid_x, y + grid_y)
else:
self.pos = nx.spring_layout(self.graph, seed=42)
except Exception as e:
logger.warning(f"Community-based layout failed: {e}, using fallback")
self.pos = nx.spring_layout(self.graph, seed=42)
else:
# Default fallback - always works
self.pos = nx.spring_layout(
self.graph,
seed=self.layout_options.seed,
iterations=min(self.layout_options.iterations, 100)
)
# Validate positions
if not self.pos or len(self.pos) != len(self.graph.nodes()):
logger.error(f"Layout calculation produced invalid positions: {len(self.pos) if self.pos else 0} for {len(self.graph.nodes())} nodes")
# Emergency fallback
self.pos = nx.spring_layout(self.graph, seed=42, iterations=30)
# Cache the result with validation
if self.pos and len(self.pos) == len(self.graph.nodes()):
graph_hash = f"{len(self.graph.nodes())}_{len(self.graph.edges())}_{algorithm}_{self.layout_options.iterations}"
self.performance_cache.set(f"layout_{graph_hash}", self.pos)
calc_time = time.time() - start_time
logger.info(f"Layout calculation complete in {calc_time:.2f}s. Generated positions for {len(self.pos)} nodes")
except Exception as e:
logger.error(f"Error calculating layout with {algorithm}: {e}")
# Emergency fallback to ensure we always have valid positions
try:
self.pos = nx.spring_layout(self.graph, seed=42, iterations=30)
logger.info(f"Used emergency fallback layout for {len(self.pos)} nodes")
except Exception as e2:
logger.error(f"Even fallback layout failed: {e2}")
# Last resort: random positions
self.pos = {node: (np.random.random(), np.random.random()) for node in self.graph.nodes()}
def _create_enhanced_plotly_figure(self):
"""Create an enhanced Plotly figure with advanced interactivity."""
if not self.graph or not self.pos:
logger.warning("Cannot create figure: missing graph or position data")
return
# Validate that we have positions for all nodes
if len(self.pos) != len(self.graph.nodes()):
logger.error(f"Position mismatch: {len(self.pos)} positions for {len(self.graph.nodes())} nodes")
# Force recalculation of layout
self._calculate_enhanced_layout()
if not self.pos or len(self.pos) != len(self.graph.nodes()):
logger.error("Failed to generate valid positions, aborting figure creation")
return
# Apply filters
filtered_nodes = self._get_filtered_nodes()
if len(filtered_nodes) == 0:
logger.warning("No nodes to display after filtering")
return
logger.info(f"Creating figure with {len(filtered_nodes)} filtered nodes out of {len(self.graph.nodes())} total")
# Store the currently selected node if any, so we can restore it
previously_selected = getattr(self, 'currently_selected_node', None)
# Create traces
traces = []
# Enhanced edge traces with weight-based styling
edge_traces = self._create_edge_traces(filtered_nodes)
traces.extend(edge_traces)
# Enhanced node traces with better labeling
node_traces = self._create_node_traces(filtered_nodes)
traces.extend(node_traces)
if not traces:
logger.error("No traces created, cannot generate figure")
return
# Create figure
fig = go.Figure(data=traces)
# Enhanced layout
self._configure_enhanced_layout(fig, filtered_nodes)
# Generate HTML with enhanced JavaScript
self._generate_enhanced_html(fig, previously_selected)
def _get_filtered_nodes(self) -> Set[str]:
"""Get nodes that pass current filters."""
filtered = set()
logger.info(f"Filtering {len(self.nodes)} nodes with filters: "
f"routers={self.filter_options.show_routers}, "
f"clients={self.filter_options.show_clients}, "
f"isolated={self.filter_options.show_isolated}, "
f"vulnerable={self.filter_options.show_vulnerable}, "
f"min_degree={self.filter_options.min_degree}, "
f"max_degree={self.filter_options.max_degree}")
for node_id, node_data in self.nodes.items():
degree = self.graph.degree(node_id)
# Degree filter
if not (self.filter_options.min_degree <= degree <= self.filter_options.max_degree):
continue
# Node type filters - be more permissive about router detection
is_router = node_data.get('is_router', False) or node_data.get('role') == 'ROUTER'
if is_router and not self.filter_options.show_routers:
continue
if not is_router and not self.filter_options.show_clients:
continue
# Special cases
if degree == 0 and not self.filter_options.show_isolated:
continue
if degree == 1 and not self.filter_options.show_vulnerable:
continue
filtered.add(node_id)
logger.info(f"After filtering: {len(filtered)} nodes will be displayed")
return filtered
def _create_edge_traces(self, filtered_nodes: Set[str]) -> List:
"""Create enhanced edge traces with weight-based styling."""
if not filtered_nodes or not self.pos:
logger.warning("Cannot create edge traces: no filtered nodes or positions")
return []
traces = []
# Regular edges
edge_x, edge_y = [], []
critical_edge_x, critical_edge_y = [], []
edges_processed = 0
for edge in self.edges:
if edge['from'] not in filtered_nodes or edge['to'] not in filtered_nodes:
continue
if edge['from'] not in self.pos or edge['to'] not in self.pos:
continue
try:
x0, y0 = self.pos[edge['from']]
x1, y1 = self.pos[edge['to']]
# Convert to float to ensure compatibility
x0, y0, x1, y1 = float(x0), float(y0), float(x1), float(y1)
edges_processed += 1
# Check if this is a critical edge
is_critical = self._is_critical_edge(edge['from'], edge['to'])
if is_critical and self.filter_options.highlight_critical_paths:
critical_edge_x.extend([x0, x1, None])
critical_edge_y.extend([y0, y1, None])
else:
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
except (TypeError, ValueError) as e:
logger.debug(f"Invalid position data for edge {edge['from']}-{edge['to']}: {e}")
continue
logger.info(f"Processed {edges_processed} edges for visualization")
# Regular edges trace
if edge_x:
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
mode='lines',
line=dict(width=1, color='rgba(150,150,150,0.6)'),
hoverinfo='none',
name='Connections',
showlegend=True
)
traces.append(edge_trace)
# Critical edges trace
if critical_edge_x:
critical_trace = go.Scatter(
x=critical_edge_x, y=critical_edge_y,
mode='lines',
line=dict(width=3, color='rgba(255,69,0,0.8)'),
hoverinfo='none',
name='Critical Paths',
showlegend=True
)
traces.append(critical_trace)
return traces
def _create_node_traces(self, filtered_nodes: Set[str]) -> List:
"""Create enhanced node traces with detailed information - PERFORMANCE OPTIMIZED."""
start_time = time.time()
# Validate inputs first
if not filtered_nodes or not self.pos:
logger.warning("Cannot create node traces: no filtered nodes or positions")
return []
# Check if all filtered nodes have positions
nodes_with_positions = [node for node in filtered_nodes if node in self.pos]
if len(nodes_with_positions) != len(filtered_nodes):
logger.warning(f"Some filtered nodes missing positions: {len(nodes_with_positions)}/{len(filtered_nodes)}")
filtered_nodes = set(nodes_with_positions)
if not filtered_nodes:
logger.warning("No nodes have positions available")
return []
# Create a more specific cache key that includes position data hash
try:
# Convert positions to a hashable format
pos_items = [(node, (float(x), float(y))) for node, (x, y) in sorted(self.pos.items())]
pos_hash = hash(tuple(pos_items))
except (TypeError, ValueError):
# Fallback if positions contain unhashable types
pos_hash = len(self.pos)
current_hash = self._generate_data_hash()
cache_key = f"node_traces_{current_hash}_{len(filtered_nodes)}_{pos_hash}"
# Only use cache if we have substantial nodes to avoid caching empty results
if len(filtered_nodes) > 10:
cached_traces = self.performance_cache.get(cache_key)
if cached_traces is not None and len(cached_traces) > 0:
logger.info(f"Using cached node traces ({len(cached_traces)} traces)")
return cached_traces
logger.info(f"Creating optimized node traces for {len(filtered_nodes)} filtered nodes")
# Pre-allocate data structures for better performance
node_groups = {
'router': {'x': [], 'y': [], 'text': [], 'customdata': [], 'size': [], 'color': []},
'client': {'x': [], 'y': [], 'text': [], 'customdata': [], 'size': [], 'color': []},
'isolated': {'x': [], 'y': [], 'text': [], 'customdata': [], 'size': [], 'color': []},
'vulnerable': {'x': [], 'y': [], 'text': [], 'customdata': [], 'size': [], 'color': []},
'highlighted': {'x': [], 'y': [], 'text': [], 'customdata': [], 'size': [], 'color': []}
}
# Process nodes directly instead of using threading for better reliability
nodes_with_positions = 0
for node_id in filtered_nodes:
if node_id not in self.pos:
continue
nodes_with_positions += 1
node_data = self.nodes[node_id]
x, y = self.pos[node_id]
# Create optimized hover text (simplified for performance)
hover_text = self._create_fast_hover_text(node_id, node_data)
# Determine node size based on importance (optimized)
degree = self.graph.degree(node_id)
base_size = 12
size_bonus = min(degree * 2, 20)
node_size = base_size + size_bonus
# Determine node group
group = self._get_node_group(node_id, node_data, degree)
# Add to group
node_groups[group]['x'].append(x)
node_groups[group]['y'].append(y)
node_groups[group]['text'].append(hover_text)
node_groups[group]['customdata'].append(node_id)
node_groups[group]['size'].append(node_size)
node_groups[group]['color'].append('#000000') # Placeholder
processing_time = time.time() - start_time
logger.info(f"Processed {nodes_with_positions} nodes with valid positions in {processing_time:.2f}s")
# Create traces for each group - optimized
traces = []
group_config = {
'router': {'color': '#1E88E5', 'name': 'Routers'},
'client': {'color': '#43A047', 'name': 'Clients'},
'isolated': {'color': '#E53935', 'name': 'Isolated'},
'vulnerable': {'color': '#FDD835', 'name': 'Vulnerable'},
'highlighted': {'color': '#FF6F00', 'name': 'Highlighted'}
}
total_nodes_in_traces = 0
for group, data in node_groups.items():
if not data['x']:
continue
total_nodes_in_traces += len(data['x'])
config = group_config[group]
# Generate node labels
node_labels = [self._get_node_label(cdata) for cdata in data['customdata']]
# Create optimized trace with pre-computed data
node_trace = go.Scatter(
x=data['x'], y=data['y'],
mode='markers+text' if self.filter_options.show_node_labels else 'markers',
marker=dict(
size=data['size'],
color=config['color'],
line=dict(width=2, color='white'),
opacity=0.8
),
text=node_labels,
textposition="middle center",
textfont=dict(
size=self.filter_options.node_label_size,
color='white',
family='Arial, sans-serif'
),
hovertext=data['text'],
hoverinfo='text',
customdata=data['customdata'],
name=config['name'],
showlegend=True
)
traces.append(node_trace)
logger.info(f"Created {group} trace with {len(data['x'])} nodes")
total_time = time.time() - start_time
logger.info(f"Created {len(traces)} node traces with {total_nodes_in_traces} total nodes in {total_time:.2f}s")
# Only cache if we have substantial results
if len(traces) > 0 and total_nodes_in_traces > 10:
self.performance_cache.set(cache_key, traces)
return traces
def _create_fast_hover_text(self, node_id: str, node_data: Dict) -> str:
"""Create optimized hover text for performance."""
# Simplified hover text for better performance
hex_name = node_data.get('hex_name', node_id)
short_name = node_data.get('short_name', '')
hardware = node_data.get('hardware', '')
degree = self.graph.degree(node_id)
# Build text efficiently
parts = [f"<b>{hex_name}</b>"]
if short_name and short_name.strip():
parts.append(f"Name: {short_name}")
if hardware:
parts.append(f"HW: {hardware}")
parts.append(f"Connections: {degree}")
# Add neighbor count only (not full list for performance)
if degree > 0:
parts.append(f"Neighbors: {degree}")
return "<br>".join(parts)
def _create_node_hover_text(self, node_id: str, node_data: Dict) -> str:
"""Create detailed hover text for a node."""
# Use hex_name for display if available
hex_name = node_data.get('hex_name', node_id)
original_name = node_data.get('original_name', '')
# Create title with hex name
text = f"<b>{hex_name}</b><br>"
# Show original numeric name if different
if original_name and original_name != hex_name:
text += f"<b>Original ID:</b> {original_name}<br>"
# Basic node info
short_name = node_data.get('short_name', '')
long_name = node_data.get('long_name', '')
if short_name and short_name.strip():
text += f"<b>Short Name:</b> {short_name}<br>"
if long_name and long_name.strip() and long_name != short_name:
text += f"<b>Long Name:</b> {sanitize_label(long_name)}<br>"
# Node type
is_router = node_data.get('is_router', False) or node_data.get('role') == 'ROUTER'
text += f"<b>Type:</b> {'Router' if is_router else 'Client'}<br>"
# Hardware and channel info
hardware = node_data.get('hardware', '')
if hardware:
text += f"<b>Hardware:</b> {hardware}<br>"
channel = node_data.get('channel', '')
if channel:
text += f"<b>Channel:</b> {channel}<br>"
# Connection info
degree = self.graph.degree(node_id)
text += f"<b>Connections:</b> {degree}<br>"
# Neighbor information with quality
neighbors = list(self.graph.neighbors(node_id))
if neighbors:
text += f"<b>Connected to:</b><br>"
for i, n_id in enumerate(neighbors[:5]): # Show first 5
n_data = self.nodes.get(n_id, {})
n_hex_name = n_data.get('hex_name', n_id)
n_short_name = n_data.get('short_name', '')
# Use short name if available, otherwise hex name
display_name = n_short_name if n_short_name and n_short_name.strip() else n_hex_name[:8]
# Get edge weight/SNR if available
edge_data = self.graph.get_edge_data(node_id, n_id, {})
snr = edge_data.get('snr')
if snr is not None:
text += f" • {display_name} (SNR: {snr:.1f})<br>"
else:
text += f" • {display_name}<br>"
if len(neighbors) > 5:
text += f" • ... and {len(neighbors) - 5} more<br>"
# Optimization scores
if self.node_scores and node_id in self.node_scores:
score = self.node_scores[node_id]
text += f"<br><b>Optimization Scores:</b><br>"
text += f" Total: {score.total_score:.3f}<br>"
text += f" Coverage: {score.coverage_score:.3f}<br>"
text += f" Centrality: {score.centrality_score:.3f}<br>"
text += f" Redundancy: {score.redundancy_score:.3f}<br>"
# Network metrics
if nx.is_connected(self.graph):
try:
centrality = nx.betweenness_centrality(self.graph).get(node_id, 0)
text += f"<br><b>Betweenness Centrality:</b> {centrality:.3f}<br>"
except:
pass
return text
def _get_node_label(self, node_id: str) -> str:
"""Get display label for a node."""
if not self.filter_options.show_node_labels:
return ""
node_data = self.nodes.get(node_id, {})
# Use hex_name if available, otherwise use short_name or the node_id itself
hex_name = node_data.get('hex_name', node_id)
short_name = node_data.get('short_name', '')
# Prefer short_name if it exists and is meaningful, otherwise use hex
if short_name and short_name.strip() and short_name != 'Meshtastic':
# For display, show short name with hex in parentheses
return f"{short_name[:6]}"
else:
# Show hex name, truncated for display
return hex_name[:8] if len(hex_name) > 8 else hex_name
def _get_node_group(self, node_id: str, node_data: Dict, degree: int) -> str:
"""Determine which group a node belongs to for styling."""
if node_id in self.highlight_nodes:
return 'highlighted'
elif degree == 0:
return 'isolated'
elif degree == 1:
return 'vulnerable'
elif node_data.get('is_router'):
return 'router'
else:
return 'client'
def _is_critical_edge(self, node1: str, node2: str) -> bool:
"""Check if an edge is on a critical path."""
if not self.critical_paths:
return False
for path in self.critical_paths:
for i in range(len(path) - 1):
if (path[i] == node1 and path[i+1] == node2) or \
(path[i] == node2 and path[i+1] == node1):