Repository navigation
Expand file tree
/
Copy pathStabilEdge_GUI.py
More file actions
1882 lines (1598 loc) · 77.2 KB
/
Copy pathStabilEdge_GUI.py
File metadata and controls
1882 lines (1598 loc) · 77.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
#!/usr/bin/env python3
import os
import sys
import gc
import time
from threading import Thread
if __name__ == "__main__" and sys.argv[0].endswith("run_gui.sh"):
os.execvp(sys.executable, [sys.executable] + sys.argv[1:])
# ─── 1) High-DPI ENVIRONMENT (must come before any Qt import) ────────────────
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
# ─── 1a) Fix Qt plugin path (before any PyQt5 import) ───────────────────────
from PyQt5.QtCore import QLibraryInfo
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(
QLibraryInfo.location(QLibraryInfo.PluginsPath), "platforms"
)
# ─── 2) Qt Attributes for High-DPI (before any other Qt imports) ───────────
from PyQt5.QtCore import QCoreApplication, Qt
QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
QCoreApplication.setAttribute(Qt.AA_UseOpenGLES)
# ─── 3) Standard imports ───────────────────────────────────────────────────
import json
import tempfile
import glob
import collections
import subprocess
import onnx
import socket
import traceback
import io, contextlib
import re
from PIL import Image
from typing import Optional, List, Tuple, Set, Deque, Dict, Any, Callable
from PyQt5.QtCore import pyqtSignal, QThread, QUrl, QProcess, pyqtSlot
from PyQt5.QtGui import QIcon, QFont, QColor, QLinearGradient
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QPushButton, QLabel, QComboBox,
QCheckBox, QTreeWidget, QTreeWidgetItem,
QMessageBox, QFileDialog, QPlainTextEdit, QSplitter,
QSpinBox, QDoubleSpinBox, QTabWidget, QGridLayout, QMenu, QAction, QToolButton, QWidgetAction,
QSizePolicy, QProgressBar, QGraphicsDropShadowEffect, QStackedWidget
)
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QTimer
import matplotlib
matplotlib.use("Qt5Agg")
#matplotlib.use("Agg")
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from matplotlib.backends.backend_qt5agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar
)
import pyqtgraph as pg # Import PyQtGraph for plotting
# Chromium flags (if needed)
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = (
"--disable-gpu "
"--disable-software-rasterizer "
"--disable-extensions "
"--disable-plugins "
"--disable-translate "
"--disable-sync "
"--disable-background-timer-throttling "
"--disable-renderer-backgrounding "
"--disable-dev-shm-usage "
"--no-sandbox "
"--disable-web-security "
"--force-dark-mode --enable-features=WebContentsForceDark "
"--log-level=3"
)
import netron
from verification.registry import ENGINES, create_marabou_worker
from verification.transformer_panel import TransformerPanel
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_MAP = {
"ITD": os.path.join(BASE_DIR, "ITD_features.json"),
"TOF": os.path.join(BASE_DIR, "TOF_features.json"),
"Jena": os.path.join(BASE_DIR, "Jena_features.json"),
}
def _get_input_indices(feature_props):
"""Get input indices from feature properties, supporting both old and new naming."""
# Try new naming first, fall back to old naming for backward compatibility
return feature_props.get("input_indices") or feature_props.get("starting_indexes", [])
class MainWindow(QMainWindow):
progress = pyqtSignal(float, int, int, int, int, int, float)
def __init__(self):
super().__init__()
self.setWindowTitle("StabilEdge")
self._netron_server = None
self.threads: List[QThread] = []
self.feature_cfg = None
self.has_multiclass = False
self.input_shape = None # (rows,cols) once input is loaded
self.pipeline: Optional[str] = None
self.progress.connect(self._update_progress)
# Add timer tracking variables
self._run_start_time = None
self._elapsed_timer = QTimer()
self._elapsed_timer.timeout.connect(self._update_elapsed_time)
self._current_elapsed = 0
# ─── pixel‐grid setup (must be before build_ui) ─────────────────
self.gridWidget = QWidget()
self.gridLayout = QGridLayout(self.gridWidget)
self.selected_pixels: Set[int] = set()
# Initialize pixel_controls to None first
self.pixel_controls = None
# ─── now build the rest of the UI ─────────────────────────────
self._build_ui()
self._connect_signals()
def _on_plot_toggle(self, checked: bool):
self.pgPlot.setVisible(checked)
if checked:
# Force an immediate update of the plot with the current progress data
if hasattr(self, '_latest_progress'):
self._update_progress(*self._latest_progress)
else:
# default zero values if no progress yet - use correct number of args including elapsed time
self._update_progress(0.0, 0, 0, 0, 0, 0, 0.0)
else:
# Optionally clear plot when hiding
self.pgPlot.clear()
def _build_ui(self):
# ─── Fix Qt plugin path ──────────────────────────────────
qt_plug = QLibraryInfo.location(QLibraryInfo.PluginsPath)
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(qt_plug, "platforms")
# ─── Top row: Model & Input ─────────────────────────────
self.leModel, self.btnModel = QLineEdit(), QPushButton("Import ONNX…")
self.leInput, self.btnInput = QLineEdit(), QPushButton("Import Input…")
self.btnJson = QPushButton("Import Features JSON…")
self.btnExportConfig = QPushButton("Export Config…")
self.btnImportConfig = QPushButton("Import Config…")
self.btnExportConfig.setEnabled(False) # Enable only when selections exist
self.btnImportConfig.setEnabled(True)
# ─── Class-selector menu button (hidden until needed) ─────────
self.btnClassMenu = QToolButton(self)
self.btnClassMenu.setText("Select Classes")
self.btnClassMenu.setPopupMode(QToolButton.InstantPopup)
self.btnClassMenu.hide()
# ─── build a little vertical sub-layout just for the Input column
input_col = QVBoxLayout()
input_col.setContentsMargins(0,0,0,0)
input_col.setSpacing(2)
input_col.addWidget(self.leInput)
input_col.addWidget(self.btnClassMenu, alignment=Qt.AlignLeft)
file_row = QHBoxLayout()
file_row.addWidget(QLabel("ONNX Model:"))
file_row.addWidget(self.leModel)
file_row.addWidget(self.btnModel)
file_row.addStretch(1)
# ← use the nested column here
file_row.addWidget(QLabel("Input:"))
file_row.addLayout(input_col) # ← stacked under leInput
file_row.addWidget(self.btnInput)
file_row.addWidget(self.btnJson)
file_row.addWidget(self.btnExportConfig)
file_row.addWidget(self.btnImportConfig)
# ─── Class-selector grid (multi-select) ────────────────
self.classGridWidget = QWidget()
self.classGridLayout = QGridLayout(self.classGridWidget)
self.classGridLayout.setContentsMargins(0,0,0,0)
self.classGridLayout.setHorizontalSpacing(8)
self.classGridLayout.setVerticalSpacing(8)
self.selected_classes = set()
# hidden until populated in _pick_model & Targeted mode
self.classGridWidget.hide()
# ─── Controls row ───────────────────────────────────────
ctl = QHBoxLayout()
self.comboVT = QComboBox()
self.comboVT.addItems([
"Local Robustness", "Targeted Robustness",
"Local Sensitivity", "Targeted Sensitivity"
])
ctl.addWidget(QLabel("Verification:"))
ctl.addWidget(self.comboVT)
self.leDeltas = QLineEdit(); self.leDeltas.setPlaceholderText("e.g. 0.1,0.2,0.4")
ctl.addWidget(QLabel("δs:")); ctl.addWidget(self.leDeltas)
self.lblEpsilons = QLabel("εs:")
self.leEpsilons = QLineEdit()
self.leEpsilons.setPlaceholderText("e.g. 0.025,0.03")
ctl.addWidget(self.lblEpsilons)
ctl.addWidget(self.leEpsilons)
self.chkPlot = QCheckBox("Enable Plotting"); self.chkPlot.setChecked(True)
ctl.addWidget(self.chkPlot)
self.spinVerb = QSpinBox(); self.spinVerb.setRange(0,2)
self.spinVerb.setValue(0) # Default to API-only mode
# Tell users in the tooltip or label that 2 is required for progress notifications.
self.spinVerb.setToolTip(
"0 = Silent (API stats only - RECOMMENDED, prevents text overflow)\n"
"1 = Minimal output\n"
"2 = Full logs (may slow GUI with high output volume)\n\n"
"💡 All statistics available via Python API regardless of verbosity"
)
ctl.addWidget(QLabel("Verbosity:")); ctl.addWidget(self.spinVerb)
self.chkEnableTimeout = QCheckBox("Enable timeout")
ctl.addWidget(self.chkEnableTimeout)
# single-value fallback
self.spinTimeout = QSpinBox()
self.spinTimeout.setRange(0, 24*3600)
self.spinTimeout.setSuffix(" s")
self.spinTimeout.setEnabled(False)
ctl.addWidget(self.spinTimeout)
# if the user wants per-δ timeouts
self.chkMultiTimeout = QCheckBox("Separate timeouts for each δ")
self.chkMultiTimeout.setEnabled(False)
ctl.addWidget(self.chkMultiTimeout)
self.leTimeouts = QLineEdit()
self.leTimeouts.setPlaceholderText("e.g. 0,5,10 (0=no limit)")
self.leTimeouts.setEnabled(False)
ctl.addWidget(self.leTimeouts)
self.spinThreshold = QDoubleSpinBox()
self.spinThreshold.setRange(0.0, 1.0)
self.spinThreshold.setSingleStep(0.05)
self.spinThreshold.setValue(0.8)
self.spinThreshold.setToolTip("When to suggest extending timeout (fraction of limit)")
# ─── NEW: progress-bar and toggle ─────────────────────
self.chkShowProgress = QCheckBox("Show progress")
self.chkShowProgress.setChecked(False)
ctl.addWidget(self.chkShowProgress)
# Optional: add a stretch after the progress bar so buttons don't squeeze it
ctl.addStretch(1)
self.btnRun, self.btnStop = QPushButton("Run"), QPushButton("Stop")
self.btnStop.setEnabled(False)
ctl.addWidget(self.btnRun); ctl.addWidget(self.btnStop)
# ─── Jena tree (hidden unless pipeline == "Jena") ────────
self.tree = QTreeWidget()
self.tree.setHeaderHidden(True)
self.tree.hide()
# ─── Tabs: Outline + Netron ─────────────────────────────
self.tab_widget = QTabWidget()
self.modelTree = QTreeWidget()
self.modelTree.setHeaderLabels(["ONNX Graph"])
self.tab_widget.addTab(self.modelTree, "Outline")
self.netron_view = QWebEngineView()
self.tab_widget.addTab(self.netron_view, "Netron")
self.resultTree = QTreeWidget()
self.resultTree.setHeaderLabels(["Sample", "Status", "δ", "Details"])
self.tab_widget.addTab(self.resultTree, "Verification results")
self.tab_widget.setMinimumWidth(300)
# ─── Console ────────────────────────────────────────────
self.console = QPlainTextEdit()
self.console.setReadOnly(True)
# let it expand when its splitter grows
self.console.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.console.setMinimumHeight(100) # sensible default floor
# ─── Plot & Toolbar ─────────────────────────────────────
self.fig = Figure(figsize=(5,5))
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.navbar = NavigationToolbar(self.canvas, self)
# Create PyQtGraph PlotWidget for real-time updates
self.pgPlot = pg.PlotWidget()
self.pgPlot.setMinimumHeight(500)
self.pgPlot.showGrid(x=False, y=False) # Disable all grid lines for cleaner look
# Add modern styling to the plot widget
self.pgPlot.setBackground('w') # White background for better visibility
# Add subtle glow effect to the plot widget
shadow = QGraphicsDropShadowEffect()
shadow.setBlurRadius(20)
shadow.setColor(QColor(100, 200, 255, 80))
shadow.setOffset(0, 0)
self.pgPlot.setGraphicsEffect(shadow)
# ─── Pixel-selection controls (for Sensitivity modes) ──────────
self.pixel_controls = QWidget()
pixel_layout = QHBoxLayout(self.pixel_controls)
pixel_layout.setContentsMargins(0, 0, 0, 0)
self.btnMeaningfulPixels = QPushButton("Select Meaningful Pixels")
self.btnMeaningfulPixels.setToolTip("Use Otsu threshold to select meaningful pixels automatically")
self.btnClearPixels = QPushButton("Clear Selection")
self.btnClearPixels.setToolTip("Clear all selected pixels")
pixel_layout.addWidget(self.btnMeaningfulPixels)
pixel_layout.addWidget(self.btnClearPixels)
pixel_layout.addStretch()
self.pixel_controls.hide() # Hidden until Sensitivity mode
# ─── Feature-tree & Pixel-grid ──────────────────────────
self.tree = QTreeWidget()
self.tree.hide()
self.gridWidget = QWidget()
self.gridLayout = QGridLayout(self.gridWidget)
self.gridWidget.hide()
# (you already set spacing & policies on these elsewhere)
# ─── Build a vertical splitter for right side ──────────
right_splitter = QSplitter(Qt.Vertical)
# top container: tree → pixel_controls → grid → toolbar → canvas
top = QWidget()
top_layout = QVBoxLayout(top)
top_layout.setContentsMargins(0,0,0,0)
top_layout.setSpacing(0)
top_layout.addWidget(self.tree, stretch=1)
top_layout.addWidget(self.pixel_controls, stretch=0) # Add pixel controls
top_layout.addWidget(self.gridWidget, stretch=1)
top_layout.addWidget(self.navbar, stretch=0)
top_layout.addWidget(self.canvas, stretch=3)
top_layout.addWidget(self.pgPlot, stretch=1)
self.canvas.hide() # optionally hide matplotlib canvas by default
right_splitter.addWidget(top)
right_splitter.addWidget(self.console)
# proportions: top takes 3× height, console 1×
right_splitter.setStretchFactor(0, 3)
right_splitter.setStretchFactor(1, 1)
# ─── Main horizontal splitter ──────────────────────────
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.tab_widget)
splitter.addWidget(right_splitter)
# proportions: tabs 1×, right side 4×
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 4)
# ─── Assemble main window ───────────────────────────────
central = QWidget()
vlay = QVBoxLayout(central)
vlay.addLayout(file_row)
vlay.addWidget(self.classGridWidget)
vlay.addLayout(ctl)
vlay.addWidget(splitter, stretch=4)
self.engineSelector = QComboBox()
for engine in ENGINES:
self.engineSelector.addItem(engine.name, engine.id)
self.engineSelector.setToolTip("Choose the verification backend. Each backend exposes its supported model and input types.")
engine_row = QHBoxLayout()
engine_row.addWidget(QLabel("Verification engine:"))
engine_row.addWidget(self.engineSelector)
engine_row.addStretch()
self.enginePages = QStackedWidget()
self.enginePages.addWidget(central)
self.transformerPanel = TransformerPanel(self)
self.enginePages.addWidget(self.transformerPanel)
outer = QWidget()
outer_layout = QVBoxLayout(outer)
outer_layout.addLayout(engine_row)
outer_layout.addWidget(self.enginePages)
self.engineSelector.currentIndexChanged.connect(self.enginePages.setCurrentIndex)
self.transformerPanel.running_changed.connect(lambda running: self.engineSelector.setEnabled(not running))
self.setCentralWidget(outer)
def _connect_signals(self):
self.btnModel.clicked.connect(self._pick_model)
self.btnInput.clicked.connect(self._pick_input)
self.btnJson.clicked.connect(self._pick_json)
self.btnExportConfig.clicked.connect(self._export_config)
self.btnImportConfig.clicked.connect(self._import_config)
self.comboVT.currentTextChanged.connect(self._on_vt_changed)
self.btnRun.clicked.connect(self._start)
self.btnStop.clicked.connect(self._stop)
self.btnMeaningfulPixels.clicked.connect(self._select_meaningful_pixels)
self.btnClearPixels.clicked.connect(self._clear_pixel_selection)
self.chkEnableTimeout.toggled.connect(self.spinTimeout.setEnabled)
self.chkEnableTimeout.toggled.connect(self.chkMultiTimeout.setEnabled)
self.chkMultiTimeout.toggled.connect(self.leTimeouts.setEnabled)
self.chkMultiTimeout.toggled.connect(lambda checked: self.spinTimeout.setEnabled(not checked))
# initialize ε-field enable/disable
self._on_vt_changed(self.comboVT.currentText())
# Connect progress visibility toggles
self.chkPlot.toggled.connect(lambda _: self._toggle_progress_visibility(self.chkShowProgress.isChecked()))
self.chkShowProgress.toggled.connect(self._toggle_progress_visibility)
# Set initial progress widget visibility
self._toggle_progress_visibility(self.chkShowProgress.isChecked())
def _handle_log(self, msg: str):
if msg.startswith("__PLOT__:"):
_, png = msg.split(":",1)
self._display_plot(png)
else:
# Batch console updates to reduce GUI freezing with high verbosity
cursor = self.console.textCursor()
cursor.movePosition(cursor.End)
cursor.insertText(msg + '\n')
# Only auto-scroll if already at bottom
scrollbar = self.console.verticalScrollBar()
if scrollbar.value() >= scrollbar.maximum() - 10:
self.console.setTextCursor(cursor)
self.console.ensureCursorVisible()
def _toggle_progress_visibility(self, checked: bool):
if checked and self.chkPlot.isChecked():
self.pgPlot.show()
# Hide pixel controls and grids when progress bar enabled
self.gridWidget.hide()
if hasattr(self, 'pixel_controls') and self.pixel_controls is not None:
self.pixel_controls.hide()
# Force immediate redraw with latest known progress (if any)
if hasattr(self, '_latest_progress'):
self._update_progress(*self._latest_progress)
else:
self.pgPlot.hide()
# Show grids and controls again when progress bar is disabled
# Only show if current VT mode is Sensitivity (same as original logic)
if self.comboVT.currentText().endswith("Sensitivity") and hasattr(self, 'feature_cfg'):
# We need to decide which grid to show based on JSON features
px_feats = [
f for f in self.feature_cfg.get("features", [])
if "pixel" in f.get("name", "").lower()
]
if px_feats and self.input_shape:
rows, cols = self.input_shape
self._build_pixel_grid(rows, cols)
if hasattr(self, 'pixel_controls') and self.pixel_controls is not None:
self.pixel_controls.show() # Show pixel controls
else:
self._build_feature_timestep_grid()
if hasattr(self, 'pixel_controls') and self.pixel_controls is not None:
self.pixel_controls.hide() # Hide for non-pixel features
else:
# Hide grid and controls if not Sensitivity mode or no feature config
self.gridWidget.hide()
if hasattr(self, 'pixel_controls') and self.pixel_controls is not None:
self.pixel_controls.hide()
def _display_plot(self, png_path: str):
# collapse the feature‐tree and grid so our canvas can fill the space
self.tree.hide()
self.gridWidget.hide()
# now load & render the heatmap PNG
img = plt.imread(png_path)
self.canvas.figure.clear()
ax = self.canvas.figure.add_axes([0,0,1,1], frameon=False)
ax.imshow(img, aspect="auto")
ax.set_axis_off()
self.canvas.draw()
# clean up
try: os.unlink(png_path)
except: pass
def _pick_model(self):
"""
Choose an ONNX model, populate the 'Outline' tree, embed Netron,
and—if it's a multi-class classifier—prepare the class-selector menu.
"""
# ── 0) Shut down any previous Netron instance
if self._netron_server:
try:
self._netron_server.shutdown()
self._netron_server.server_close()
except Exception:
pass
self._netron_server = None
# ── 1) UI reset
self.modelTree.clear()
self.tree.clear()
# hide/clear any old class-selection UI
self.classGridWidget.hide()
self.btnClassMenu.hide()
self.btnClassMenu.setMenu(None)
self.selected_classes.clear()
self.has_multiclass = False
# ── 2) Ask for a *.onnx file
fn, _ = QFileDialog.getOpenFileName(
self, "Select ONNX Model", "", "ONNX Files (*.onnx)"
)
if not fn:
return
self.leModel.setText(fn)
# ── 3) Helper for attrs
def _pretty_attr(attr):
if attr.HasField("f"):
return attr.f
if attr.HasField("i"):
return attr.i
if attr.HasField("s"):
try:
return attr.s.decode("utf-8")
except UnicodeDecodeError:
blob = attr.s
return f"0x{blob[:32].hex()}{'…' if len(blob) > 32 else ''}"
return "<complex>"
# ── 4) Load the model
try:
model = onnx.load(fn)
except Exception as e:
QMessageBox.critical(self, "ONNX load error", str(e))
return
# ── 5) Populate Outline tree
inputs_item = QTreeWidgetItem(["Graph Inputs"])
for inp in model.graph.input:
inputs_item.addChild(QTreeWidgetItem([inp.name]))
self.modelTree.addTopLevelItem(inputs_item)
outputs_item = QTreeWidgetItem(["Graph Outputs"])
for out in model.graph.output:
outputs_item.addChild(QTreeWidgetItem([out.name]))
self.modelTree.addTopLevelItem(outputs_item)
for node in model.graph.node:
label = node.name or f"<{node.op_type}>"
parent = QTreeWidgetItem([f"{label} ({node.op_type})"])
for inp in node.input:
parent.addChild(QTreeWidgetItem([f"⟵ input: {inp}"]))
for out in node.output:
parent.addChild(QTreeWidgetItem([f"output: {out} ⟶"]))
for attr in node.attribute:
parent.addChild(
QTreeWidgetItem([f" • {attr.name} = {_pretty_attr(attr)}"])
)
self.modelTree.addTopLevelItem(parent)
self.modelTree.expandAll()
# ── 6) Spin up Netron
sock = socket.socket()
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
self._netron_server = netron.start(fn, address=("127.0.0.1", port), browse=False)
self.netron_view.load(QUrl(f"http://127.0.0.1:{port}"))
self.tab_widget.setCurrentWidget(self.netron_view)
# ── 7) Detect multiclass (>2 classes)
out_type = model.graph.output[0].type.tensor_type
dims = [d.dim_value for d in out_type.shape.dim if d.dim_value > 0]
num_classes = dims[-1] if dims else 0
self.has_multiclass = (num_classes > 2)
# clear any old menu so nothing lingers
self.btnClassMenu.setMenu(None)
if self.has_multiclass:
menu = QMenu(self.btnClassMenu)
class_checkboxes = []
# “All classes”
all_cb = QCheckBox("All classes")
all_act = QWidgetAction(menu)
all_act.setDefaultWidget(all_cb)
menu.addAction(all_act)
for i in range(num_classes):
cb = QCheckBox(f"Class {i}")
cb.toggled.connect(lambda checked, idx=i: (
self.selected_classes.add(idx) if checked
else self.selected_classes.discard(idx),
self._update_export_button_state()
))
act = QWidgetAction(menu)
act.setDefaultWidget(cb)
menu.addAction(act)
class_checkboxes.append(cb)
all_cb.toggled.connect(lambda checked: [
cb.setChecked(checked) for cb in class_checkboxes
])
self.btnClassMenu.setMenu(menu)
else:
# explicitly hide and clear for 0–2 classes
self.btnClassMenu.hide()
self.selected_classes.clear()
# ── 8) Re-apply the VT‐mode rules so only Targeted+3+ actually shows it
self._on_vt_changed(self.comboVT.currentText())
def _pick_input(self):
"""
1) Let the user choose an image / CSV / NumPy array.
2) Record its shape in self.input_shape.
3) Keep the grid hidden until JSON arrives.
"""
filter_str = (
"All Supported (*.png *.jpg *.jpeg *.csv *.npy);;"
"Images (*.png *.jpg *.jpeg);;"
"CSV (*.csv);;"
"NumPy Array (*.npy)"
)
fn, _ = QFileDialog.getOpenFileName(
self,
"Select Input File",
"",
filter_str
)
if not fn:
return
self.leInput.setText(fn)
ext = os.path.splitext(fn)[1].lower()
# determine shape
if ext in ('.png', '.jpg', '.jpeg'):
from PIL import Image
import numpy as np
arr = np.array(Image.open(fn).convert('L'))
rows, cols = arr.shape[:2]
elif ext == '.csv':
import numpy as np
import pandas as pd
import re
# 1) Peek at the first line to see if it’s a header
with open(fn, 'r') as f:
first = f.readline().strip()
tokens = first.split(',')
# if any token isn’t a pure float syntax, treat as header
float_re = re.compile(r'^-?\d+\.?\d*(?:[eE][-+]?\d+)?$')
has_header = any(not float_re.match(tok.strip()) for tok in tokens)
# 2) Read with pandas, skipping header if needed
if has_header:
df = pd.read_csv(fn, header=0) # skip first line
else:
df = pd.read_csv(fn, header=None)
# 3) Flatten to 1D float array
try:
flat = df.to_numpy(dtype=float).flatten()
except ValueError as e:
QMessageBox.warning(
self, "Error loading CSV",
f"Non-numeric data found:\n{e}"
)
return
total = flat.size
side = int(np.sqrt(total))
if side*side != total:
QMessageBox.warning(
self, "Invalid Image Size",
f"CSV contains {total} pixels which is not a perfect square."
)
return
# 4) Reshape, stash shape & return
img_arr = flat.reshape(side, side)
self.input_shape = (side, side)
self.image_array = img_arr # if you want to display it later
self.gridWidget.hide()
return
elif ext == '.npy':
import numpy as np
try:
arr = np.load(fn)
except Exception as e:
QMessageBox.warning(self, "Error", f"Could not load .npy file:\n{e}")
return
if arr.ndim < 2:
QMessageBox.warning(self, "Error", "NumPy array must have at least 2 dimensions")
return
rows, cols = arr.shape[:2]
else:
QMessageBox.warning(self, "Error", "Unsupported input format")
return
# stash shape but keep grid hidden until JSON arrives
self.input_shape = (rows, cols)
self.gridWidget.hide()
def _pick_json(self):
fn, _ = QFileDialog.getOpenFileName(
self, "Select Features JSON", "", "JSON Files (*.json)"
)
if not fn:
return
# 1) Ensure an input is loaded first
if not hasattr(self, 'input_shape') or not self.leInput.text().strip():
QMessageBox.information(
self, "Load Input First",
"Please import an input file before loading the JSON."
)
return
# 2) Load & parse JSON
try:
with open(fn, 'r', encoding='utf-8') as f:
cfg = json.load(f)
except json.JSONDecodeError as e:
QMessageBox.critical(
self, "JSON Parse Error",
f"Could not parse JSON:\n{e}"
)
return
# 3) Stash the config for later
self.feature_cfg = cfg
self.json_path = fn
# Prefer explicit configuration fields; retain legacy filenames.
base = os.path.basename(fn)
configured = str(cfg.get("pipeline", cfg.get("name", ""))).upper()
if configured in ("ITD", "TOF", "JENA"):
self.pipeline = "Jena" if configured == "JENA" else configured
elif cfg.get("task") == "regression":
self.pipeline = "Jena"
elif base == "ITD_features.json":
self.pipeline = "ITD"
elif base == "TOF_features.json":
self.pipeline = "TOF"
elif base == "Jena_features.json":
self.pipeline = "Jena"
else:
QMessageBox.warning(
self, "Unknown JSON",
f"Unrecognized JSON {base}, defaulting to ITD."
)
self.pipeline = "ITD"
# Disable/enable ε-input
is_jena = (self.pipeline == "Jena")
self.lblEpsilons.setEnabled(is_jena)
self.leEpsilons.setEnabled(is_jena)
# 5) Input vs JSON compatibility
ext = os.path.splitext(self.leInput.text().lower())[1]
px_feats = [
f for f in cfg.get("features", [])
if "pixel" in f.get("name", "").lower()
]
# —— new .npy handling block ——
if ext == '.npy':
try:
arr = np.load(self.leInput.text())
except Exception as e:
QMessageBox.warning(self, "Error", f"Could not load .npy file:\n{e}")
return # still bail if we can’t even load
if px_feats:
# JSON expects pixel input → must be 2D image
if arr.ndim != 2:
QMessageBox.warning(
self, "Unsupported Input",
f"JSON defines pixel features but .npy has ndim={arr.ndim}; expected 2."
)
return # bail on truly invalid shape
# OK: record image shape (2D)
self.input_shape = (arr.shape[0], arr.shape[1])
# <— no return here, let the grid-builder run below
else:
# JSON expects time-series → accept 1D or 2D
if arr.ndim == 0:
QMessageBox.warning(
self, "Unsupported Input",
".npy must contain at least one time-series sample."
)
return # bail on truly invalid shape
# OK: no per-pixel grid for time-series
self.input_shape = None
# 5b) Existing checks for CSV / image files
allowed_px = {'.png', '.jpg', '.jpeg', '.csv'}
if px_feats and ext not in allowed_px.union({'.npy'}):
QMessageBox.warning(
self, "Unsupported Input",
"JSON defines pixel features but input isn’t image/CSV/NPY."
)
return
if not px_feats and ext != '.npy':
QMessageBox.warning(
self, "Unsupported Input",
"JSON defines time-series features but input isn’t an .npy."
)
return
# 6) Build the grid only for Sensitivity modes
if self.comboVT.currentText().endswith("Sensitivity"):
if px_feats:
rows, cols = self.input_shape
self._build_pixel_grid(rows, cols)
else:
self._build_feature_timestep_grid()
else:
self.gridWidget.hide()
def _build_feature_timestep_grid(self):
# clear old
for i in reversed(range(self.gridLayout.count())):
w = self.gridLayout.itemAt(i).widget()
if w:
w.setParent(None)
self.selected_pixels.clear()
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setHorizontalSpacing(8)
self.gridLayout.setVerticalSpacing(8)
self.gridLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
feats = self.feature_cfg["features"]
# T = number of positions/timesteps per feature in the flattened input vector
# These positions represent where this feature's data appears in the input array
T = len(_get_input_indices(feats[0]["properties"]))
# headers
self.gridLayout.addWidget(QLabel(""), 0, 0)
for col in range(T):
lbl = QLabel(f"t{col}")
lbl.setAlignment(Qt.AlignCenter)
self.gridLayout.addWidget(lbl, 0, col+1)
all_hdr = QLabel("All")
all_hdr.setAlignment(Qt.AlignCenter)
self.gridLayout.addWidget(all_hdr, 0, T+1)
# feature rows
for row, feat in enumerate(feats, start=1):
name_lbl = QLabel(feat["name"])
name_lbl.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
self.gridLayout.addWidget(name_lbl, row, 0)
row_buttons = []
# Create button for each position this feature occupies in the flattened input
# idx = position in the input vector, col = visual column (timestep) in the grid
for col, idx in enumerate(_get_input_indices(feat["properties"]), start=1):
btn = QPushButton()
btn.setCheckable(True)
btn.setMinimumSize(30, 30)
btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
btn.setStyleSheet("""
QPushButton { }
QPushButton:checked { background-color: red; }
""")
btn.toggled.connect(
lambda checked, i=idx: (
self.selected_pixels.add(i) if checked
else self.selected_pixels.discard(i),
self._update_export_button_state()
)
)
self.gridLayout.addWidget(btn, row, col)
row_buttons.append(btn)
select_all = QPushButton("▢")
select_all.setCheckable(True)
select_all.setMinimumSize(30, 30)
select_all.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
select_all.setToolTip("Select/clear all time steps in this row")
select_all.toggled.connect(
lambda checked, buttons=row_buttons: [
b.setChecked(checked) for b in buttons
]
)
self.gridLayout.addWidget(select_all, row, T+1)
# stretch every column and row equally
for col in range(T+2): # +2 for the feature‐name and "All" columns
self.gridLayout.setColumnStretch(col, 1)
for row in range(len(feats)+1): # +1 for the header row
self.gridLayout.setRowStretch(row, 1)
# grid itself can expand
self.gridWidget.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.gridWidget.show()
def _on_vt_changed(self, vt: str):
"""
Handles switching between Local/Targeted and Robustness/Sensitivity.
Ensures ε-field is visible but only enabled for Jena, and also
toggles the grid & class-menu as before.
"""
pipeline = getattr(self, "pipeline", None)
sens_mode = vt.endswith("Sensitivity")
targeted_mode = vt.startswith("Targeted ")
# ── Epsilon ALWAYS visible, but only editable for Jena ───────
self.lblEpsilons.setVisible(True)
self.leEpsilons.setVisible(True)
self.leEpsilons.setEnabled(pipeline == "Jena")
# ── grid and pixel controls only in Sensitivity ────────────────
self.gridWidget.setVisible(sens_mode)
# FIX: Check if pixel_controls exists and properly evaluate input_shape
if hasattr(self, 'pixel_controls') and self.pixel_controls is not None:
should_show = sens_mode and hasattr(self, 'input_shape') and self.input_shape is not None
self.pixel_controls.setVisible(should_show)
# ── class-menu only in Targeted & multiclass ───────────────
if targeted_mode and self.has_multiclass:
self.btnClassMenu.show()
else:
self.btnClassMenu.hide()
self.selected_classes.clear()
def _on_pipeline_changed(self, pipe: str):
if pipe == "Jena":
cfg = json.load(open(CONFIG_MAP["Jena"], "r"))
self.tree.clear()
for feat in cfg["features"]:
parent = QTreeWidgetItem([feat["name"]])
parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
parent.setCheckState(0, Qt.Unchecked)
# Add child items for each input position this feature occupies
for idx in _get_input_indices(feat["properties"]):
child = QTreeWidgetItem([str(idx)])
child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
child.setCheckState(0, Qt.Unchecked)
parent.addChild(child)
self.tree.addTopLevelItem(parent)
self.tree.show()
else:
self.tree.hide()
def _build_pixel_grid(self, rows: int, cols: int):
# clear any old cells
for i in reversed(range(self.gridLayout.count())):
w = self.gridLayout.itemAt(i).widget()
if w:
w.setParent(None)
self.selected_pixels.clear()
# spacing
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setHorizontalSpacing(8)
self.gridLayout.setVerticalSpacing(8)
# create buttons
for row in range(rows):
for col in range(cols):
idx = row * cols + col
btn = QPushButton()
btn.setCheckable(True)
btn.setMinimumSize(30, 30)
btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
btn.setStyleSheet("""
QPushButton { /* normal */ }
QPushButton:checked { background-color: red; }
""")