python-intan 0.0.2__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. intan/__init__.py +46 -33
  2. intan/_cli.py +21 -0
  3. intan/applications/__init__.py +22 -0
  4. intan/applications/_emg_trial_selector.py +430 -0
  5. intan/applications/_emg_viewer.py +2052 -0
  6. intan/applications/_launcher.py +36 -0
  7. intan/decomposition/__init__.py +12 -0
  8. intan/decomposition/_cfica.py +183 -0
  9. intan/decomposition/_pca.py +42 -0
  10. intan/interface/__init__.py +24 -0
  11. intan/interface/_device_utils.py +173 -0
  12. intan/interface/_lsl_client.py +343 -0
  13. intan/interface/_lsl_options.py +15 -0
  14. intan/interface/_lsl_publisher.py +139 -0
  15. intan/interface/_lsl_subscriber.py +408 -0
  16. intan/interface/_messaging.py +81 -0
  17. intan/{control/_messaging.py → interface/_pico.py} +1 -81
  18. intan/interface/_playback_options.py +29 -0
  19. intan/interface/_rhx_config.py +333 -0
  20. intan/interface/_rhx_device.py +498 -0
  21. intan/io/__init__.py +109 -20
  22. intan/io/_canonicalizer.py +82 -0
  23. intan/io/_config_utils.py +281 -0
  24. intan/io/_csv_utils.py +247 -0
  25. intan/io/_dataset_utils.py +267 -0
  26. intan/io/_exceptions.py +30 -1
  27. intan/io/_file_utils.py +586 -35
  28. intan/io/_grid_utils.py +280 -0
  29. intan/io/_io_optimized.py +310 -0
  30. intan/io/_npz_utils.py +745 -0
  31. intan/io/{_block_parser.py → _rhd_block_parser.py} +129 -6
  32. intan/io/{_channel_utils.py → _rhd_channel_utils.py} +26 -1
  33. intan/io/_rhd_header_parsing.py +791 -0
  34. intan/io/_rhd_loader.py +595 -71
  35. intan/io/_utilities.py +995 -0
  36. intan/ml/__init__.py +47 -0
  37. intan/ml/_evaluation.py +305 -0
  38. intan/ml/_ml_utilities.py +155 -0
  39. intan/ml/_model_manager.py +547 -0
  40. intan/ml/_models.py +143 -0
  41. intan/ml/_prediction_modes.py +478 -0
  42. intan/ml/_prediction_utils.py +199 -0
  43. intan/plotting/__init__.py +30 -2
  44. intan/plotting/_realtime_plotter.py +105 -0
  45. intan/plotting/_stacked_plot.py +385 -0
  46. intan/plotting/_waterfall.py +38 -17
  47. intan/processing/__init__.py +40 -8
  48. intan/processing/_channel_qc.py +253 -0
  49. intan/processing/_data_processing.py +21 -0
  50. intan/processing/_features.py +460 -0
  51. intan/processing/_fill.py +309 -0
  52. intan/processing/_filters.py +127 -437
  53. intan/processing/_imu_features.py +195 -0
  54. intan/processing/_metrics_utils.py +44 -56
  55. intan/processing/_preprocessing.py +208 -0
  56. intan/processing/_realtime_filter.py +298 -0
  57. intan/processing/_sync.py +292 -0
  58. intan/processing/_temporal_filters.py +289 -0
  59. intan/processing/_transformations.py +168 -0
  60. intan/samples/__init__.py +1 -0
  61. intan/samples/_find_file.py +35 -0
  62. intan/ui/__init__.py +31 -0
  63. intan/ui/_helpers.py +109 -0
  64. python_intan-0.2.3.dist-info/METADATA +230 -0
  65. python_intan-0.2.3.dist-info/RECORD +69 -0
  66. {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/WHEEL +1 -1
  67. python_intan-0.2.3.dist-info/entry_points.txt +3 -0
  68. intan/control/__init__.py +0 -1
  69. intan/io/_data_processing.py +0 -193
  70. intan/io/_header_parsing.py +0 -383
  71. intan/io/_metadata_utils.py +0 -150
  72. intan/plotting/_emg_plots.py +0 -245
  73. python_intan-0.0.2.dist-info/METADATA +0 -185
  74. python_intan-0.0.2.dist-info/RECORD +0 -23
  75. {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/licenses/LICENSE +0 -0
  76. {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2052 @@
1
+ """
2
+ intan.processing._emg_viewer_gui
3
+
4
+ Graphical User Interface (GUI) for loading and visualizing EMG data.
5
+
6
+ The EMGViewer provides an interactive interface for exploring high-density EMG signals
7
+ from Intan `.rhd` recordings. It supports:
8
+ - Channel selection
9
+ - Segment visualization
10
+ - Preprocessing
11
+ - Trigger-based analysis (if available)
12
+
13
+ Typically launched via `_emg_launcher.py`.
14
+ """
15
+
16
+ import os
17
+ import numpy as np
18
+ try:
19
+ import pandas as pd
20
+ except Exception:
21
+ pd = None
22
+ try:
23
+ from tqdm import tqdm
24
+ except Exception:
25
+ tqdm = None
26
+ try:
27
+ from scipy.signal import spectrogram, butter, filtfilt, iirnotch
28
+ except Exception:
29
+ spectrogram = butter = filtfilt = iirnotch = None
30
+ try:
31
+ import tkinter as tk
32
+ from tkinter import filedialog, ttk
33
+ except Exception:
34
+ tk = None
35
+ filedialog = None
36
+ ttk = None
37
+
38
+ try:
39
+ from intan.io import load_rhd_file
40
+ except Exception:
41
+ load_rhd_file = None
42
+
43
+ try:
44
+ from intan.processing import (
45
+ bandpass_filter,
46
+ lowpass_filter,
47
+ notch_filter,
48
+ rectify,
49
+ window_rms,
50
+ extract_features,
51
+ common_average_reference,
52
+ envelope_extraction,
53
+ )
54
+ except Exception:
55
+ bandpass_filter = lowpass_filter = notch_filter = rectify = None
56
+ window_rms = extract_features = common_average_reference = envelope_extraction = None
57
+
58
+ # Visualization libraries (guarded)
59
+ try:
60
+ import matplotlib.pyplot as plt
61
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
62
+ except Exception:
63
+ plt = None
64
+ FigureCanvasTkAgg = None
65
+ NavigationToolbar2Tk = None
66
+
67
+ # Try to provide a PyQt5-based viewer as modern alternative; fall back to Tkinter below
68
+ try:
69
+ from PyQt5 import QtWidgets, QtCore
70
+ from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvasQt
71
+ from matplotlib.figure import Figure as MplFigure
72
+ _HAS_PYQT = True
73
+ except Exception:
74
+ _HAS_PYQT = False
75
+
76
+ def _downsample_for_plot(y, max_points=2000):
77
+ import math
78
+ n = len(y)
79
+ if n <= max_points:
80
+ return y
81
+ binsize = int(math.ceil(n / float(max_points)))
82
+ n_out = int(math.ceil(n / float(binsize)))
83
+ mins = np.empty(n_out)
84
+ maxs = np.empty(n_out)
85
+ for i in range(n_out):
86
+ s = i * binsize
87
+ e = min(n, (i + 1) * binsize)
88
+ seg = y[s:e]
89
+ mins[i] = np.min(seg)
90
+ maxs[i] = np.max(seg)
91
+ y_ds = np.empty(n_out * 2)
92
+ y_ds[0::2] = mins
93
+ y_ds[1::2] = maxs
94
+ return y_ds
95
+
96
+
97
+ # --- IO helper utilities usable without GUI ---
98
+ def save_model_obj(obj, path):
99
+ """Save a model object with joblib or pickle."""
100
+ try:
101
+ if path.lower().endswith('.joblib') and joblib is not None:
102
+ joblib.dump(obj, path); return
103
+ except Exception:
104
+ pass
105
+ import pickle
106
+ with open(path, 'wb') as f:
107
+ pickle.dump(obj, f)
108
+
109
+
110
+ def load_model_obj(path):
111
+ """Load a model object with joblib or pickle."""
112
+ try:
113
+ if path.lower().endswith('.joblib') and joblib is not None:
114
+ return joblib.load(path)
115
+ except Exception:
116
+ pass
117
+ import pickle
118
+ with open(path, 'rb') as f:
119
+ return pickle.load(f)
120
+
121
+
122
+ def save_trials_csv(trials, path):
123
+ import csv
124
+ with open(path, 'w', newline='') as f:
125
+ w = csv.writer(f)
126
+ w.writerow(['start_sample', 'end_sample'])
127
+ for s, e in trials:
128
+ w.writerow([int(s), int(e)])
129
+
130
+
131
+ def load_trials_csv(path):
132
+ import csv
133
+ out = []
134
+ with open(path, 'r', newline='') as f:
135
+ rdr = csv.reader(f)
136
+ hdr = next(rdr, None)
137
+ for row in rdr:
138
+ if not row: continue
139
+ try:
140
+ s = int(row[0]); e = int(row[1])
141
+ except Exception:
142
+ continue
143
+ out.append((s, e))
144
+ return out
145
+
146
+
147
+ def save_features_npz(features, path):
148
+ np.savez_compressed(path, features=features)
149
+
150
+
151
+ def load_features_npz(path):
152
+ d = np.load(path, allow_pickle=True)
153
+ if 'features' in d:
154
+ return d['features']
155
+ # try common keys
156
+ for k in d.files:
157
+ return d[k]
158
+ return None
159
+
160
+ if _HAS_PYQT:
161
+ class EMGViewerQt(QtWidgets.QMainWindow):
162
+ """Minimal PyQt5-based EMG viewer to mirror Tk viewer functionality.
163
+
164
+ This provides a lightweight, modern GUI using matplotlib's Qt backend.
165
+ """
166
+ def __init__(self, parent=None, num_channels=None, sample_rate=None):
167
+ super().__init__(parent)
168
+ self.setWindowTitle('EMG Viewer (PyQt)')
169
+ self.data = None
170
+ self.fs = float(sample_rate) if sample_rate is not None else 2000.0
171
+ self.current_pos = 0
172
+ self.playing = False
173
+ self.max_points = 2000
174
+
175
+ central = QtWidgets.QWidget()
176
+ self.setCentralWidget(central)
177
+ vlay = QtWidgets.QVBoxLayout(central)
178
+
179
+ # Create tabbed control area so we can port Tk tabs into PyQt
180
+ tabs = QtWidgets.QTabWidget()
181
+
182
+ # --- Acquisition tab (simple open/play controls) ---
183
+ acq_tab = QtWidgets.QWidget()
184
+ acq_layout = QtWidgets.QHBoxLayout(acq_tab)
185
+ btn_open = QtWidgets.QPushButton('Open')
186
+ btn_open.clicked.connect(self.open_file)
187
+ acq_layout.addWidget(btn_open)
188
+ self.btn_play = QtWidgets.QPushButton('Play')
189
+ self.btn_play.clicked.connect(self._toggle_play)
190
+ acq_layout.addWidget(self.btn_play)
191
+ tabs.addTab(acq_tab, 'Acquisition')
192
+
193
+ # --- Filtering tab ---
194
+ filt_tab = QtWidgets.QWidget()
195
+ filt_layout = QtWidgets.QHBoxLayout(filt_tab)
196
+ filt_layout.addWidget(QtWidgets.QLabel('HP (Hz)'))
197
+ self.spin_hp = QtWidgets.QDoubleSpinBox(); self.spin_hp.setRange(0.0, 1000.0); self.spin_hp.setValue(10.0)
198
+ filt_layout.addWidget(self.spin_hp)
199
+ filt_layout.addWidget(QtWidgets.QLabel('LP (Hz)'))
200
+ self.spin_lp = QtWidgets.QDoubleSpinBox(); self.spin_lp.setRange(0.0, 10000.0); self.spin_lp.setValue(500.0)
201
+ filt_layout.addWidget(self.spin_lp)
202
+ filt_layout.addWidget(QtWidgets.QLabel('Notch'))
203
+ self.combo_notch = QtWidgets.QComboBox(); self.combo_notch.addItems(['None', '50', '60'])
204
+ filt_layout.addWidget(self.combo_notch)
205
+ self.btn_apply_filters = QtWidgets.QPushButton('Apply Filters')
206
+ self.btn_apply_filters.clicked.connect(self.apply_filters)
207
+ filt_layout.addWidget(self.btn_apply_filters)
208
+ filt_layout.addWidget(QtWidgets.QLabel('Channel'))
209
+ self.chan_selector = QtWidgets.QSpinBox(); self.chan_selector.setRange(1,256); self.chan_selector.setValue(1)
210
+ self.chan_selector.valueChanged.connect(self.plot_waveforms)
211
+ filt_layout.addWidget(self.chan_selector)
212
+ filt_layout.addWidget(QtWidgets.QLabel('FS'))
213
+ self.spin_fs = QtWidgets.QSpinBox(); self.spin_fs.setRange(1,100000); self.spin_fs.setValue(int(self.fs))
214
+ self.spin_fs.valueChanged.connect(self._on_fs_changed)
215
+ filt_layout.addWidget(self.spin_fs)
216
+ filt_layout.addWidget(QtWidgets.QLabel('Window (s)'))
217
+ self.window_sec = QtWidgets.QDoubleSpinBox(); self.window_sec.setRange(0.01,60.0); self.window_sec.setValue(0.2)
218
+ self.window_sec.valueChanged.connect(self.plot_waveforms)
219
+ filt_layout.addWidget(self.window_sec)
220
+ filt_layout.addWidget(QtWidgets.QLabel('Downsample'))
221
+ self.spin_max_points = QtWidgets.QSpinBox(); self.spin_max_points.setRange(100,200000); self.spin_max_points.setValue(self.max_points)
222
+ self.spin_max_points.valueChanged.connect(self._on_max_points_changed)
223
+ filt_layout.addWidget(self.spin_max_points)
224
+ filt_layout.addWidget(QtWidgets.QLabel('RMS win (s)'))
225
+ self.rms_window_sec = QtWidgets.QDoubleSpinBox(); self.rms_window_sec.setRange(0.01,10.0); self.rms_window_sec.setSingleStep(0.01); self.rms_window_sec.setValue(0.05)
226
+ filt_layout.addWidget(self.rms_window_sec)
227
+ self.heat_live_checkbox = QtWidgets.QCheckBox('Heat Live'); self.heat_live_checkbox.setChecked(True)
228
+ filt_layout.addWidget(self.heat_live_checkbox)
229
+ tabs.addTab(filt_tab, 'Filtering')
230
+
231
+ # --- Trials tab (placeholder, will implement segmentation/visualization) ---
232
+ trials_tab = QtWidgets.QWidget()
233
+ trials_layout = QtWidgets.QVBoxLayout(trials_tab)
234
+ h = QtWidgets.QHBoxLayout()
235
+ btn_detect = QtWidgets.QPushButton('Detect Trials')
236
+ btn_detect.clicked.connect(self.detect_trials)
237
+ h.addWidget(btn_detect)
238
+ btn_load_events = QtWidgets.QPushButton('Load Events')
239
+ btn_load_events.clicked.connect(self.load_events)
240
+ h.addWidget(btn_load_events)
241
+ trials_layout.addLayout(h)
242
+ tabs.addTab(trials_tab, 'Trials')
243
+
244
+ # --- Feature dataset tab (placeholder) ---
245
+ feat_tab = QtWidgets.QWidget()
246
+ feat_layout = QtWidgets.QHBoxLayout(feat_tab)
247
+ btn_extract = QtWidgets.QPushButton('Extract Features')
248
+ btn_extract.clicked.connect(self.extract_features_action)
249
+ feat_layout.addWidget(btn_extract)
250
+ btn_rms = QtWidgets.QPushButton('Compute RMS')
251
+ btn_rms.clicked.connect(self.compute_rms_action)
252
+ feat_layout.addWidget(btn_rms)
253
+ btn_spec = QtWidgets.QPushButton('Show Spectrogram')
254
+ btn_spec.clicked.connect(self.show_spectrogram_action)
255
+ feat_layout.addWidget(btn_spec)
256
+ btn_save_feat = QtWidgets.QPushButton('Save Features')
257
+ btn_save_feat.clicked.connect(self.save_features)
258
+ feat_layout.addWidget(btn_save_feat)
259
+ tabs.addTab(feat_tab, 'Feature Dataset')
260
+
261
+ vlay.addWidget(tabs)
262
+
263
+ # Make waveform view taller by increasing figure height and stretch
264
+ # plot area: waveform and RMS tabs
265
+ self.plot_tabs = QtWidgets.QTabWidget()
266
+
267
+ # waveform tab
268
+ wave_w = QtWidgets.QWidget()
269
+ wave_layout = QtWidgets.QVBoxLayout(wave_w)
270
+ self.fig = MplFigure(figsize=(10, 4))
271
+ self.canvas = FigureCanvasQt(self.fig)
272
+ wave_layout.addWidget(self.canvas, 1)
273
+ self.plot_tabs.addTab(wave_w, 'Waveform')
274
+
275
+ # RMS heatmap tab
276
+ heat_w = QtWidgets.QWidget()
277
+ heat_layout = QtWidgets.QVBoxLayout(heat_w)
278
+ self.fig_rms = MplFigure(figsize=(10, 4))
279
+ self.canvas_rms = FigureCanvasQt(self.fig_rms)
280
+ heat_layout.addWidget(self.canvas_rms, 1)
281
+ self.plot_tabs.addTab(heat_w, 'RMS Heatmap')
282
+
283
+ vlay.addWidget(self.plot_tabs, 3)
284
+
285
+ self.scrub_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
286
+ self.scrub_slider.setMinimum(0); self.scrub_slider.setMaximum(0)
287
+ self.scrub_slider.valueChanged.connect(self._on_slider_moved)
288
+ try:
289
+ self.scrub_slider.sliderPressed.connect(self._on_scrub_pressed)
290
+ self.scrub_slider.sliderReleased.connect(self._on_scrub_released)
291
+ except Exception:
292
+ pass
293
+ vlay.addWidget(self.scrub_slider)
294
+
295
+ self.play_timer = QtCore.QTimer(); self.play_timer.setInterval(50); self.play_timer.timeout.connect(self._on_timer_tick)
296
+ self._was_playing_on_scrub = False
297
+
298
+ self.resize(1000,600)
299
+
300
+ def _on_fs_changed(self, val): self.fs = float(val)
301
+ def _on_max_points_changed(self, val): self.max_points = int(val); self.plot_waveforms()
302
+
303
+ def open_file(self):
304
+ path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open EMG file', '', 'EMG Files (*.npz *.npy *.csv *.dat *.rhd);;RHD Files (*.rhd);;All Files (*)')
305
+ if not path: return
306
+ try:
307
+ data = np.load(path) if path.lower().endswith('.npy') else np.loadtxt(path, delimiter=',')
308
+ except Exception:
309
+ try:
310
+ data = np.loadtxt(path)
311
+ except Exception as e:
312
+ QtWidgets.QMessageBox.critical(self, 'Error', str(e))
313
+ return
314
+ data = np.asarray(data)
315
+ if data.ndim == 1: data = data[:,None]
316
+ self.data = data
317
+ self.chan_selector.setMaximum(max(1, self.data.shape[1]))
318
+ self.scrub_slider.setMaximum(max(0, self.data.shape[0]-1))
319
+ self.current_pos = 0
320
+ self.plot_waveforms()
321
+
322
+ def plot_waveforms(self):
323
+ # draw on waveform figure/canvas
324
+ self.fig.clear()
325
+ ax = self.fig.add_subplot(111)
326
+ if self.data is None:
327
+ ax.text(0.5,0.5,'Open a file to begin',ha='center',va='center')
328
+ self.canvas.draw_idle(); return
329
+ ch = int(self.chan_selector.value())-1
330
+ fs = max(1.0, float(self.spin_fs.value()))
331
+ window_s = float(self.window_sec.value())
332
+ window_samples = max(1, int(window_s * fs))
333
+ start = int(self.current_pos); end = min(self.data.shape[0], start + window_samples)
334
+ t = np.arange(start, end) / fs
335
+ y = self.data[start:end, ch]
336
+ if len(y)==0:
337
+ ax.text(0.5,0.5,'No data in window',ha='center',va='center'); self.canvas.draw_idle(); return
338
+ # downsample by envelope
339
+ ty = _downsample_for_plot(y, max_points=self.max_points)
340
+ # If downsample returns an interleaved min/max envelope (length != t), build matching tx
341
+ if ty is None:
342
+ ax.plot(t, y, lw=0.8)
343
+ elif len(ty) == len(t):
344
+ ax.plot(t, ty, lw=0.8)
345
+ else:
346
+ # assume ty is interleaved min/max of length 2*n_out
347
+ n_out = len(ty) // 2
348
+ if n_out > 0:
349
+ binsize = int(np.ceil(len(y) / float(n_out)))
350
+ centers = np.empty(n_out)
351
+ for i in range(n_out):
352
+ s = i * binsize
353
+ e = min(len(y), (i+1)*binsize)
354
+ idx = s + (e - s) // 2
355
+ centers[i] = float((start + idx) / fs)
356
+ tx_ds = np.empty(n_out*2)
357
+ tx_ds[0::2] = centers
358
+ tx_ds[1::2] = centers
359
+ ax.plot(tx_ds, ty, lw=0.8)
360
+ else:
361
+ ax.plot(t, y, lw=0.8)
362
+ ax.set_xlabel('Time (s)'); ax.set_title(f'Channel {ch+1} [{start}:{end}]')
363
+ self.fig.tight_layout(); self.canvas.draw_idle()
364
+
365
+ def apply_filters(self):
366
+ if self.data is None:
367
+ QtWidgets.QMessageBox.warning(self, 'Filters', 'No data loaded')
368
+ return
369
+ hp = float(self.spin_hp.value())
370
+ lp = float(self.spin_lp.value())
371
+ notch_text = self.combo_notch.currentText()
372
+ notch = None if notch_text == 'None' else float(notch_text)
373
+ # Use scipy if available
374
+ if butter is None or filtfilt is None:
375
+ QtWidgets.QMessageBox.information(self, 'Filters', 'SciPy not available; skipping filter')
376
+ return
377
+ try:
378
+ nyq = 0.5 * float(self.spin_fs.value())
379
+ b, a = butter(4, [max(0.0001, hp/nyq), min(0.9999, lp/nyq)], btype='band')
380
+ # apply along axis 0 (samples)
381
+ self.data = filtfilt(b, a, self.data, axis=0)
382
+ if notch is not None:
383
+ w0 = notch / nyq
384
+ bn, an = iirnotch(w0, 30)
385
+ self.data = filtfilt(bn, an, self.data, axis=0)
386
+ except Exception as e:
387
+ QtWidgets.QMessageBox.warning(self, 'Filter error', str(e))
388
+ return
389
+ self.plot_waveforms()
390
+
391
+ def plot_heatmap(self):
392
+ # draw RMS heatmap into RMS figure/canvas
393
+ if self.data is None:
394
+ return
395
+ rms_mean = np.sqrt(np.mean(self.data**2, axis=0))
396
+ rows, cols = 8, 8
397
+ grid = np.full((rows, cols), np.nan)
398
+ nch = self.data.shape[1]
399
+ for i in range(min(nch, rows*cols)):
400
+ r = i // cols; c = i % cols; grid[r,c] = float(rms_mean[i])
401
+ self.fig_rms.clear(); ax = self.fig_rms.add_subplot(111); im = ax.imshow(grid, cmap='inferno', aspect='auto')
402
+ self.fig_rms.colorbar(im); self.canvas_rms.draw_idle()
403
+
404
+ def _on_timer_tick(self):
405
+ if self.data is None: return
406
+ fs = float(max(1.0, float(self.spin_fs.value())))
407
+ dt = self.play_timer.interval() / 1000.0
408
+ step = max(1, int(fs * dt))
409
+ self.current_pos = int(self.current_pos) + step
410
+ window_s = float(self.window_sec.value())
411
+ window_samples = max(1, int(window_s * fs))
412
+ max_pos = max(0, self.data.shape[0] - window_samples)
413
+ if self.current_pos >= max_pos:
414
+ self.current_pos = max_pos
415
+ self.play_timer.stop(); self.playing = False; self.btn_play.setText('Play')
416
+ # update scrub slider without triggering extra updates
417
+ try:
418
+ self.scrub_slider.blockSignals(True)
419
+ self.scrub_slider.setValue(int(self.current_pos))
420
+ finally:
421
+ try: self.scrub_slider.blockSignals(False)
422
+ except Exception: pass
423
+ self.plot_waveforms()
424
+
425
+ def _toggle_play(self):
426
+ if self.data is None:
427
+ QtWidgets.QMessageBox.information(self, 'Play', 'No data loaded')
428
+ return
429
+ if self.playing:
430
+ self.play_timer.stop(); self.playing = False; self.btn_play.setText('Play')
431
+ else:
432
+ # ensure slider maximum is set
433
+ try:
434
+ self.scrub_slider.setMaximum(max(0, self.data.shape[0]-1))
435
+ except Exception:
436
+ pass
437
+ self.play_timer.start(); self.playing = True; self.btn_play.setText('Pause')
438
+
439
+ def _on_slider_moved(self, value):
440
+ self.current_pos = int(value)
441
+ self.plot_waveforms()
442
+
443
+ def _on_scrub_pressed(self):
444
+ # pause playback while user scrubs
445
+ self._was_playing_on_scrub = self.playing
446
+ if self.playing:
447
+ self.play_timer.stop(); self.playing = False; self.btn_play.setText('Play')
448
+
449
+ def _on_scrub_released(self):
450
+ # resume if it was playing
451
+ if getattr(self, '_was_playing_on_scrub', False):
452
+ self.play_timer.start(); self.playing = True; self.btn_play.setText('Pause')
453
+
454
+ # --- Placeholder actions for tabs ported from Tk viewer ---
455
+ def detect_trials(self):
456
+ if self.data is None:
457
+ QtWidgets.QMessageBox.information(self, 'Detect Trials', 'No data loaded')
458
+ return
459
+ ch = int(getattr(self, 'chan_selector', QtWidgets.QSpinBox()).value()) - 1
460
+ if ch < 0 or ch >= self.data.shape[1]:
461
+ QtWidgets.QMessageBox.information(self, 'Detect Trials', 'Invalid channel selected')
462
+ return
463
+ sig = self.data[:, ch].astype(float)
464
+ fs = float(getattr(self, 'spin_fs', QtWidgets.QSpinBox()).value()) if hasattr(self, 'spin_fs') else self.fs
465
+ win_s = float(getattr(self, 'rms_window_sec', QtWidgets.QDoubleSpinBox()).value()) if hasattr(self, 'rms_window_sec') else 0.05
466
+ win = max(1, int(win_s * fs))
467
+ # moving RMS
468
+ try:
469
+ kernel = np.ones(win) / float(win)
470
+ rms = np.sqrt(np.convolve(sig**2, kernel, mode='same'))
471
+ except Exception:
472
+ rms = np.abs(sig)
473
+ thresh = float(np.mean(rms) + 2.0 * np.std(rms))
474
+ mask = rms > thresh
475
+ # detect rising/falling edges
476
+ d = np.diff(mask.astype(int))
477
+ starts = list(np.where(d == 1)[0] + 1)
478
+ ends = list(np.where(d == -1)[0] + 1)
479
+ # handle edge cases
480
+ if mask[0]:
481
+ starts.insert(0, 0)
482
+ if mask[-1]:
483
+ ends.append(len(mask))
484
+ trials = []
485
+ for s, e in zip(starts, ends):
486
+ trials.append((int(s), int(e)))
487
+ self.trials = trials
488
+ # show dialog with table of trials
489
+ dlg = QtWidgets.QDialog(self)
490
+ dlg.setWindowTitle('Detected Trials')
491
+ dl = QtWidgets.QVBoxLayout(dlg)
492
+ tbl = QtWidgets.QTableWidget()
493
+ tbl.setColumnCount(3)
494
+ tbl.setHorizontalHeaderLabels(['Index', 'Start (s)', 'End (s)'])
495
+ tbl.setRowCount(len(trials))
496
+ for i, (s, e) in enumerate(trials):
497
+ tbl.setItem(i, 0, QtWidgets.QTableWidgetItem(str(i)))
498
+ tbl.setItem(i, 1, QtWidgets.QTableWidgetItem(f"{s/float(fs):.3f}"))
499
+ tbl.setItem(i, 2, QtWidgets.QTableWidgetItem(f"{e/float(fs):.3f}"))
500
+ tbl.cellDoubleClicked.connect(lambda r, c: self._jump_to_trial_row(r, dlg))
501
+ dl.addWidget(tbl)
502
+ btns = QtWidgets.QHBoxLayout()
503
+ save_btn = QtWidgets.QPushButton('Save CSV')
504
+ def _save():
505
+ path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Trials', '', 'CSV Files (*.csv);;All Files (*)')
506
+ if not path:
507
+ return
508
+ try:
509
+ import csv
510
+ with open(path, 'w', newline='') as f:
511
+ w = csv.writer(f)
512
+ w.writerow(['start_sample', 'end_sample'])
513
+ for s, e in trials:
514
+ w.writerow([s, e])
515
+ QtWidgets.QMessageBox.information(self, 'Save Trials', f'Saved {len(trials)} trials to {path}')
516
+ except Exception as ex:
517
+ QtWidgets.QMessageBox.warning(self, 'Save Trials', str(ex))
518
+ save_btn.clicked.connect(_save)
519
+ btns.addWidget(save_btn)
520
+ close_btn = QtWidgets.QPushButton('Close')
521
+ close_btn.clicked.connect(dlg.accept)
522
+ btns.addWidget(close_btn)
523
+ dl.addLayout(btns)
524
+ dlg.resize(400, 300)
525
+ dlg.exec_()
526
+
527
+ def load_events(self):
528
+ path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Events', '', 'CSV Files (*.csv);;All Files (*)')
529
+ if not path:
530
+ return
531
+ try:
532
+ import csv
533
+ ev = []
534
+ with open(path, 'r', newline='') as f:
535
+ rdr = csv.reader(f)
536
+ for row in rdr:
537
+ ev.append(row)
538
+ self.events = ev
539
+ QtWidgets.QMessageBox.information(self, 'Events', f'Loaded {len(ev)} event rows')
540
+ except Exception as e:
541
+ QtWidgets.QMessageBox.warning(self, 'Load Events', str(e))
542
+
543
+ def _jump_to_trial_row(self, row, dlg=None):
544
+ if not hasattr(self, 'trials') or row < 0 or row >= len(self.trials):
545
+ return
546
+ s, e = self.trials[row]
547
+ self.current_pos = int(s)
548
+ try:
549
+ self.scrub_slider.setValue(int(s))
550
+ except Exception:
551
+ pass
552
+ self.plot_waveforms()
553
+ if dlg is not None:
554
+ dlg.accept()
555
+
556
+ def load_trials(self):
557
+ path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Trials', '', 'CSV Files (*.csv);;All Files (*)')
558
+ if not path:
559
+ return
560
+ try:
561
+ import csv
562
+ trials = []
563
+ with open(path, 'r', newline='') as f:
564
+ rdr = csv.reader(f)
565
+ hdr = next(rdr, None)
566
+ for row in rdr:
567
+ if not row: continue
568
+ try:
569
+ s = int(row[0]); e = int(row[1])
570
+ except Exception:
571
+ continue
572
+ trials.append((s, e))
573
+ self.trials = trials
574
+ QtWidgets.QMessageBox.information(self, 'Load Trials', f'Loaded {len(trials)} trials')
575
+ except Exception as e:
576
+ QtWidgets.QMessageBox.warning(self, 'Load Trials', str(e))
577
+
578
+ def save_model(self):
579
+ # Save the last trained model if present
580
+ if not hasattr(self, 'trained_model') or self.trained_model is None:
581
+ QtWidgets.QMessageBox.information(self, 'Save Model', 'No trained model to save')
582
+ return
583
+ path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
584
+ if not path:
585
+ return
586
+ try:
587
+ if path.lower().endswith('.joblib') and joblib is not None:
588
+ joblib.dump(self.trained_model, path)
589
+ else:
590
+ import pickle
591
+ with open(path, 'wb') as f:
592
+ pickle.dump(self.trained_model, f)
593
+ QtWidgets.QMessageBox.information(self, 'Save Model', f'Model saved to {path}')
594
+ except Exception as e:
595
+ QtWidgets.QMessageBox.warning(self, 'Save Model', str(e))
596
+
597
+ def load_model(self):
598
+ path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Load Model', '', 'Joblib (*.joblib);;Pickle (*.pkl);;All Files (*)')
599
+ if not path:
600
+ return
601
+ try:
602
+ if path.lower().endswith('.joblib') and joblib is not None:
603
+ model = joblib.load(path)
604
+ else:
605
+ import pickle
606
+ with open(path, 'rb') as f:
607
+ model = pickle.load(f)
608
+ self.trained_model = model
609
+ QtWidgets.QMessageBox.information(self, 'Load Model', f'Loaded model from {path}')
610
+ except Exception as e:
611
+ QtWidgets.QMessageBox.warning(self, 'Load Model', str(e))
612
+
613
+ def extract_features_action(self):
614
+ if self.data is None:
615
+ QtWidgets.QMessageBox.information(self, 'Features', 'No data loaded')
616
+ return
617
+ if extract_features is None:
618
+ QtWidgets.QMessageBox.information(self, 'Features', 'Feature extraction function not available')
619
+ return
620
+ try:
621
+ # expect data shape (samples, channels) -> extract_features handles shapes internally
622
+ feats = extract_features(self.data, fs=self.fs)
623
+ self.last_features = feats
624
+ QtWidgets.QMessageBox.information(self, 'Features', f'Extracted features shape: {getattr(feats, "shape", "unknown")}')
625
+ except Exception as e:
626
+ QtWidgets.QMessageBox.warning(self, 'Features', str(e))
627
+
628
+ def save_features(self):
629
+ if not hasattr(self, 'last_features'):
630
+ QtWidgets.QMessageBox.information(self, 'Save Features', 'No features to save')
631
+ return
632
+ path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Features', '', 'NumPy (.npz);;All Files (*)')
633
+ if not path:
634
+ return
635
+ try:
636
+ np.savez_compressed(path, features=self.last_features)
637
+ QtWidgets.QMessageBox.information(self, 'Save Features', f'Saved features to {path}')
638
+ except Exception as e:
639
+ QtWidgets.QMessageBox.warning(self, 'Save Features', str(e))
640
+
641
+ def compute_rms_action(self):
642
+ if self.data is None:
643
+ QtWidgets.QMessageBox.information(self, 'RMS', 'No data loaded')
644
+ return
645
+ ch = int(getattr(self, 'chan_selector', QtWidgets.QSpinBox()).value()) - 1
646
+ if ch < 0 or ch >= self.data.shape[1]:
647
+ QtWidgets.QMessageBox.information(self, 'RMS', 'Invalid channel selected')
648
+ return
649
+ sig = self.data[:, ch].astype(float)
650
+ fs = float(getattr(self, 'spin_fs', QtWidgets.QSpinBox()).value()) if hasattr(self, 'spin_fs') else self.fs
651
+ win_s = float(getattr(self, 'rms_window_sec', QtWidgets.QDoubleSpinBox()).value()) if hasattr(self, 'rms_window_sec') else 0.05
652
+ win = max(1, int(win_s * fs))
653
+ kernel = np.ones(win) / float(win)
654
+ try:
655
+ rms = np.sqrt(np.convolve(sig**2, kernel, mode='same'))
656
+ except Exception:
657
+ rms = np.abs(sig)
658
+ self.last_rms = rms
659
+ t = np.arange(len(rms)) / float(fs)
660
+ self.fig.clear(); ax = self.fig.add_subplot(111)
661
+ ax.plot(t, rms, lw=0.8)
662
+ ax.set_title(f'RMS (ch {ch+1})')
663
+ ax.set_xlabel('Time (s)')
664
+ self.fig.tight_layout(); self.canvas.draw_idle()
665
+
666
+ def show_spectrogram_action(self):
667
+ if self.data is None:
668
+ QtWidgets.QMessageBox.information(self, 'Spectrogram', 'No data loaded')
669
+ return
670
+ if spectrogram is None:
671
+ QtWidgets.QMessageBox.information(self, 'Spectrogram', 'SciPy not available; cannot compute spectrogram')
672
+ return
673
+ ch = int(getattr(self, 'chan_selector', QtWidgets.QSpinBox()).value()) - 1
674
+ sig = self.data[:, ch].astype(float)
675
+ fs = float(getattr(self, 'spin_fs', QtWidgets.QSpinBox()).value()) if hasattr(self, 'spin_fs') else self.fs
676
+ try:
677
+ f, t, Sxx = spectrogram(sig, fs=fs, nperseg=256, noverlap=128)
678
+ self.fig.clear(); ax = self.fig.add_subplot(111)
679
+ im = ax.pcolormesh(t, f, 10 * np.log10(Sxx + 1e-12), shading='auto')
680
+ ax.set_ylabel('Frequency [Hz]'); ax.set_xlabel('Time [s]')
681
+ self.fig.colorbar(im)
682
+ self.fig.tight_layout(); self.canvas.draw_idle()
683
+ except Exception as e:
684
+ QtWidgets.QMessageBox.warning(self, 'Spectrogram', str(e))
685
+
686
+ # TO-DO: implement this into a separate intan module
687
+ try:
688
+ import joblib
689
+ except Exception:
690
+ joblib = None
691
+
692
+ try:
693
+ from sklearn.decomposition import PCA
694
+ from sklearn.preprocessing import LabelEncoder
695
+ from sklearn.model_selection import train_test_split
696
+ _HAS_SKLEARN = True
697
+ except Exception:
698
+ PCA = None
699
+ LabelEncoder = None
700
+ train_test_split = None
701
+ _HAS_SKLEARN = False
702
+
703
+ class EMGViewerTk:
704
+ def __init__(self, root):
705
+ self.root = root
706
+ self.root.title("EMG Data Viewer")
707
+
708
+ # === Initialize variables ===
709
+ # EMG data (channels x samples)
710
+ self.emg_data_raw = None
711
+ self.segment_data = None
712
+ self.segment_fs = None
713
+ self.sampling_rate = None
714
+ self.time_vector = None
715
+ self.current_channel = 0
716
+
717
+ # UI control variables
718
+ self.domain_mode = tk.StringVar(value="Time")
719
+ self.notch_enabled = tk.BooleanVar(value=True)
720
+ self.show_lines = tk.BooleanVar(value=True)
721
+ self.car_enabled = tk.BooleanVar(value=False)
722
+ self.xlim = None
723
+ self.ylim = None
724
+ #self.data_viewer_file_path = None
725
+
726
+ # Filtering tab entries
727
+ self.low_cut = tk.StringVar(value="20")
728
+ self.high_cut = tk.StringVar(value="450")
729
+ self.filter_order = tk.StringVar(value="4")
730
+
731
+ # Training/feature extraction controls (example)
732
+ self.training_features = {
733
+ "bandpass": tk.BooleanVar(value=True),
734
+ "notch": tk.BooleanVar(value=True),
735
+ "rectify": tk.BooleanVar(value=False),
736
+ "envelop_smooth": tk.BooleanVar(value=False),
737
+ "car": tk.BooleanVar(value=False),
738
+ # Feature toggles:
739
+ "mean_absolute_value": tk.BooleanVar(value=True),
740
+ "zero_crossings": tk.BooleanVar(value=False),
741
+ "slope_sign_changes": tk.BooleanVar(value=False),
742
+ "waveform_length": tk.BooleanVar(value=False),
743
+ "rms": tk.BooleanVar(value=True),
744
+ }
745
+
746
+ self.feature_controls = {
747
+ "zero_crossings": {"threshold": tk.StringVar(value="0.01")},
748
+ "slope_sign_changes": {"delta_threshold": tk.StringVar(value="0.01")},
749
+ "waveform_length": {"window_ms": tk.StringVar(value="200")},
750
+ }
751
+ self.smooth_f_entry = tk.StringVar(value="5.0") # Envelope smoothing freq (Hz)
752
+
753
+ self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
754
+ self.build_layout()
755
+
756
+ def build_layout(self):
757
+ # === Top Frame for Tabs + Sidebar ===
758
+ top_frame = ttk.Frame(self.root)
759
+ top_frame.pack(side="top", fill="both", expand=True)
760
+
761
+ # === Tabs ===
762
+ #self.tabs = ttk.Notebook(self.root)
763
+ self.tabs = ttk.Notebook(top_frame)
764
+ self.tabs.pack(side="left", fill="both", expand=True)
765
+
766
+ self.tab_acquisition = ttk.Frame(self.tabs)
767
+ self.tab_filtering = ttk.Frame(self.tabs)
768
+ self.tab_trials = ttk.Frame(self.tabs)
769
+ self.tab_training = ttk.Frame(self.tabs)
770
+
771
+ self.tabs.add(self.tab_acquisition, text="Data Acquisition")
772
+ self.tabs.add(self.tab_filtering, text="Filtering")
773
+ self.tabs.add(self.tab_trials, text="Trial Utilities")
774
+ self.tabs.add(self.tab_training, text="Feature Dataset")
775
+
776
+ # === Plotting Area ===
777
+ bottom_frame = ttk.Frame(self.root)
778
+ bottom_frame.pack(side="bottom", fill="both", expand=True)
779
+
780
+ plot_frame = ttk.Frame(bottom_frame)
781
+ plot_frame.pack(side="left", fill="both", expand=True)
782
+
783
+ # Plot canvas
784
+ self.figure, self.ax = plt.subplots(figsize=(10, 4))
785
+ self.canvas = FigureCanvasTkAgg(self.figure, master=plot_frame)
786
+ self.canvas.draw()
787
+ self.canvas.get_tk_widget().pack(side="top", fill="both", expand=True)
788
+
789
+ # Toolbar (now visually docked into the plot area)
790
+ self.toolbar = NavigationToolbar2Tk(self.canvas, plot_frame)
791
+ self.toolbar.update()
792
+ self.toolbar.pack(side="top", fill="x")
793
+
794
+ self.scroll = tk.Scrollbar(bottom_frame, orient="horizontal", command=self.scroll_plot)
795
+ self.scroll.pack(side="bottom", fill="x")
796
+
797
+ # === Sidebar for Channel Controls
798
+ side_controls = ttk.Frame(bottom_frame)
799
+ side_controls.pack(side="right", fill="y", padx=10)
800
+
801
+ ttk.Label(side_controls, text="Channel:").pack(anchor="w")
802
+ self.channel_selector = ttk.Combobox(side_controls, state="readonly", width=10)
803
+ self.channel_selector.bind("<<ComboboxSelected>>", self.update_channel)
804
+ self.channel_selector.pack(fill="x", pady=5)
805
+
806
+ ttk.Label(side_controls, text="Domain:").pack(anchor="w")
807
+ self.domain_dropdown = ttk.Combobox(side_controls, state="readonly", textvariable=self.domain_mode,
808
+ values=["Time", "PSD", "Spectrogram", "Waterfall", "Features"], width=10)
809
+ self.domain_dropdown.bind("<<ComboboxSelected>>", self.plot_channel)
810
+ self.domain_dropdown.pack(pady=5)
811
+
812
+ # Create the individual tabs
813
+ self.build_acquisition_tab()
814
+ self.build_filtering_tab()
815
+ self.build_trials_tab()
816
+ self.build_training_tab()
817
+
818
+ def build_acquisition_tab(self):
819
+ frame = ttk.Frame(self.tab_acquisition)
820
+ frame.pack(fill="x", pady=5)
821
+
822
+ ttk.Button(frame, text="Load File", command=self.load_file).pack(side="left", padx=5)
823
+
824
+ control_frame = ttk.Frame(self.tab_acquisition)
825
+ control_frame.pack(fill="x", pady=5)
826
+
827
+ ttk.Label(control_frame, text="Waterfall Channels:").pack(anchor="w")
828
+ self.channel_range_entry = ttk.Entry(control_frame, width=15)
829
+ self.channel_range_entry.insert(0, "0-15") # default view
830
+ self.channel_range_entry.pack(pady=5)
831
+
832
+ def build_trials_tab(self):
833
+
834
+ # === Left controls ====
835
+ container = ttk.Frame(self.tab_trials)
836
+ container.pack(fill="both", expand=True)
837
+
838
+ left_panel = ttk.Frame(container)
839
+ left_panel.pack(side="left", fill="y", padx=10, pady=10)
840
+
841
+ ttk.Label(left_panel, text="Custom Label:").pack(anchor="w")
842
+ self.label_entry = ttk.Entry(left_panel)
843
+ self.label_entry.insert(0, "Label")
844
+ self.label_entry.pack(fill="x", pady=5)
845
+
846
+ ttk.Checkbutton(left_panel, text="Show Trial Markers", variable=self.show_lines,
847
+ command=self.plot_channel).pack(anchor="w", pady=5)
848
+ ttk.Button(left_panel, text="Enable Indexing", command=self.enable_indexing).pack(anchor="w", pady=5)
849
+
850
+ # === Right side: trial label table ===
851
+ right_panel = ttk.Frame(container)
852
+ right_panel.pack(side="right", fill="both", expand=True)
853
+
854
+ self.table = ttk.Treeview(right_panel, columns=("Sample Index", "Label"), show="headings", height=10)
855
+ self.table.heading("Sample Index", text="Sample Index")
856
+ self.table.heading("Label", text="Label")
857
+ self.table.pack(fill="x", pady=5, expand=True)
858
+
859
+ button_frame = ttk.Frame(right_panel)
860
+ button_frame.pack(pady=5)
861
+ ttk.Button(button_frame, text="Save", command=self.save_table).pack(side="left", padx=5)
862
+ ttk.Button(button_frame, text="Load", command=self.load_table).pack(side="left", padx=5)
863
+ ttk.Button(button_frame, text="Delete", command=self.delete_selected).pack(side="left", padx=5)
864
+
865
+ ttk.Button(right_panel, text="Run Trial Segmentation", command=self.run_trial_segmentation).pack(pady=5)
866
+ ttk.Button(right_panel, text="Build Training Set", command=self.build_training_dataset).pack(pady=5)
867
+
868
+ self.canvas.mpl_connect("button_press_event", self.on_click)
869
+ self.indexing_enabled = False
870
+
871
+ def build_filtering_tab(self):
872
+
873
+ # === Top-level horizontal frame for grouping ===
874
+ settings_container = ttk.Frame(self.tab_filtering)
875
+ settings_container.pack(fill="x", padx=5, pady=5)
876
+
877
+ # ===== Filter settings ===========
878
+ control_frame = ttk.LabelFrame(settings_container, text="Filter Settings")
879
+ control_frame.pack(side="left", padx=5, pady=5, anchor="n")
880
+
881
+ ttk.Label(control_frame, text="Filter Type:").grid(row=0, column=0)
882
+ self.filter_type = ttk.Combobox(control_frame, values=["bandpass"], state="readonly")
883
+ self.filter_type.current(0)
884
+ self.filter_type.grid(row=0, column=1)
885
+
886
+ ttk.Label(control_frame, text="Low Cut (Hz):").grid(row=1, column=0)
887
+ self.low_cut = ttk.Entry(control_frame)
888
+ self.low_cut.insert(0, "120")
889
+ self.low_cut.grid(row=1, column=1)
890
+ self.low_cut.bind("<Return>", lambda e: self.plot_channel())
891
+ self.low_cut.bind("<FocusOut>", lambda e: self.plot_channel())
892
+
893
+ ttk.Label(control_frame, text="High Cut (Hz):").grid(row=2, column=0)
894
+ self.high_cut = ttk.Entry(control_frame)
895
+ self.high_cut.insert(0, "1000")
896
+ self.high_cut.grid(row=2, column=1)
897
+ self.high_cut.bind("<Return>", lambda e: self.plot_channel())
898
+ self.high_cut.bind("<FocusOut>", lambda e: self.plot_channel())
899
+
900
+ ttk.Label(control_frame, text="Order:").grid(row=3, column=0)
901
+ self.filter_order = ttk.Entry(control_frame)
902
+ self.filter_order.insert(0, "4")
903
+ self.filter_order.grid(row=3, column=1)
904
+ self.filter_order.bind("<Return>", lambda e: self.plot_channel())
905
+ self.filter_order.bind("<FocusOut>", lambda e: self.plot_channel())
906
+
907
+ self.notch_check = ttk.Checkbutton(control_frame, text="60Hz Notch Filter", variable=self.notch_enabled)
908
+ self.notch_check.grid(row=4, column=0, columnspan=2)
909
+ self.notch_check = ttk.Checkbutton(control_frame, text="60Hz Notch Filter", variable=self.notch_enabled,
910
+ command=self.plot_channel)
911
+
912
+ # === CAR CHECKBOX ===
913
+ self.car_check = ttk.Checkbutton(control_frame, text="Enable Common Avg Reference", variable=self.car_enabled,
914
+ command=self.plot_channel)
915
+ self.car_check.grid(row=5, column=0, columnspan=2, sticky='w')
916
+
917
+ #ttk.Button(control_frame, text="Apply Filter", command=self.plot_channel()).grid(row=5, column=0, columnspan=2, pady=5)
918
+
919
+ # ===== PSD Settings ===========
920
+ psd_frame = ttk.LabelFrame(settings_container, text="PSD Settings")
921
+ psd_frame.pack(side="left", padx=5, pady=5, anchor="n")
922
+
923
+ ttk.Label(psd_frame, text="NperSeg:").grid(row=0, column=0)
924
+ self.nperseg_entry = ttk.Entry(psd_frame)
925
+ self.nperseg_entry.insert(0, "256")
926
+ self.nperseg_entry.grid(row=0, column=1)
927
+ self.nperseg_entry.bind("<FocusOut>", lambda e: self.plot_channel())
928
+ self.nperseg_entry.bind("<Return>", lambda e: self.plot_channel())
929
+
930
+ ttk.Label(psd_frame, text="Min Freq (Hz):").grid(row=0, column=0)
931
+ self.psd_min_freq = ttk.Entry(psd_frame)
932
+ self.psd_min_freq.insert(0, "0")
933
+ self.psd_min_freq.grid(row=0, column=1)
934
+ self.psd_min_freq.bind("<FocusOut>", lambda e: self.plot_channel())
935
+ self.psd_min_freq.bind("<Return>", lambda e: self.plot_channel())
936
+
937
+ ttk.Label(psd_frame, text="Max Freq (Hz):").grid(row=1, column=0)
938
+ self.psd_max_freq = ttk.Entry(psd_frame)
939
+ self.psd_max_freq.insert(0, "1000")
940
+ self.psd_max_freq.grid(row=1, column=1)
941
+ self.psd_max_freq.bind("<FocusOut>", lambda e: self.plot_channel())
942
+ self.psd_max_freq.bind("<Return>", lambda e: self.plot_channel())
943
+
944
+
945
+ # ======= Spectrogram Settings ===========
946
+ spec_frame = ttk.LabelFrame(settings_container, text="Spectrogram Settings")
947
+ spec_frame.pack(side="left", padx=5, pady=5, anchor="n")
948
+
949
+ ttk.Label(spec_frame, text="NFFT:").grid(row=0, column=0)
950
+ self.nfft_entry = ttk.Entry(spec_frame)
951
+ self.nfft_entry.insert(0, "256")
952
+ self.nfft_entry.grid(row=0, column=1)
953
+ self.nfft_entry.bind("<FocusOut>", lambda e: self.plot_channel())
954
+ self.nfft_entry.bind("<Return>", lambda e: self.plot_channel())
955
+
956
+ ttk.Label(spec_frame, text="No. Overlap:").grid(row=1, column=0)
957
+ self.noverlap_entry = ttk.Entry(spec_frame)
958
+ self.noverlap_entry.insert(0, "128")
959
+ self.noverlap_entry.grid(row=1, column=1)
960
+ self.noverlap_entry.bind("<FocusOut>", lambda e: self.plot_channel())
961
+ self.noverlap_entry.bind("<Return>", lambda e: self.plot_channel())
962
+
963
+ self.cmap_entry = ttk.Entry(spec_frame)
964
+ self.cmap_entry.insert(0, "viridis")
965
+ ttk.Label(spec_frame, text="Colormap:").grid(row=6, column=0)
966
+ self.cmap_entry.grid(row=6, column=1)
967
+ self.cmap_entry.bind("<FocusOut>", lambda e: self.plot_channel())
968
+ self.cmap_entry.bind("<Return>", lambda e: self.plot_channel())
969
+
970
+ # Set the frequency range limits to view as min/max
971
+ self.spec_freq_min = ttk.Entry(spec_frame)
972
+ self.spec_freq_min.insert(0, "0")
973
+ ttk.Label(spec_frame, text="Freq Min (Hz):").grid(row=7, column=0)
974
+ self.spec_freq_min.grid(row=7, column=1)
975
+ self.spec_freq_min.bind("<FocusOut>", lambda e: self.plot_channel())
976
+ self.spec_freq_min.bind("<Return>", lambda e: self.plot_channel())
977
+
978
+ self.spec_freq_max = ttk.Entry(spec_frame)
979
+ self.spec_freq_max.insert(0, "1000")
980
+ ttk.Label(spec_frame, text="Freq Max (Hz):").grid(row=8, column=0)
981
+ self.spec_freq_max.grid(row=8, column=1)
982
+ self.spec_freq_max.bind("<FocusOut>", lambda e: self.plot_channel())
983
+ self.spec_freq_max.bind("<Return>", lambda e: self.plot_channel())
984
+
985
+ # Time Range: # to #
986
+ self.spec_time_range_min = ttk.Entry(spec_frame)
987
+ self.spec_time_range_min.insert(0, "0")
988
+ ttk.Label(spec_frame, text="Time Min (s):").grid(row=9, column=0)
989
+ self.spec_time_range_min.grid(row=9, column=1)
990
+ self.spec_time_range_min.bind("<FocusOut>", lambda e: self.plot_channel())
991
+ self.spec_time_range_min.bind("<Return>", lambda e: self.plot_channel())
992
+
993
+ self.spec_time_range_max = ttk.Entry(spec_frame)
994
+ self.spec_time_range_max.insert(0, "10")
995
+ ttk.Label(spec_frame, text="Time Max (s):").grid(row=10, column=0)
996
+ self.spec_time_range_max.grid(row=10, column=1)
997
+ self.spec_time_range_max.bind("<FocusOut>", lambda e: self.plot_channel())
998
+ self.spec_time_range_max.bind("<Return>", lambda e: self.plot_channel())
999
+
1000
+ def build_training_tab(self):
1001
+ container = ttk.Frame(self.tab_training)
1002
+ container.pack(fill="both", expand=True, padx=10, pady=10)
1003
+
1004
+ # === Left: Directory Table ===
1005
+ left_panel = ttk.Frame(container)
1006
+ left_panel.pack(side="left", fill="both", expand=True, padx=(0, 10))
1007
+
1008
+ # Scrollable Treeview Frame
1009
+ treeview_frame = ttk.Frame(left_panel)
1010
+ treeview_frame.pack(fill="both", expand=True)
1011
+
1012
+ # Treeview
1013
+ self.training_dir_table = ttk.Treeview(treeview_frame, columns=["Path"], show="headings", height=10)
1014
+ self.training_dir_table.heading("Path", text="Path")
1015
+ self.training_dir_table.pack(side="left", fill="both", expand=True)
1016
+
1017
+ # Scrollbar
1018
+ scrollbar = ttk.Scrollbar(treeview_frame, orient="vertical", command=self.training_dir_table.yview)
1019
+ scrollbar.pack(side="right", fill="y")
1020
+ self.training_dir_table.configure(yscrollcommand=scrollbar.set)
1021
+
1022
+ button_frame = ttk.Frame(left_panel)
1023
+ button_frame.pack(pady=5, fill="x")
1024
+ ttk.Button(button_frame, text="Add Directory", command=self.add_training_directory).pack(side="left", padx=(0, 5))
1025
+ ttk.Button(button_frame, text="Remove Directory", command=self.remove_training_directory).pack(side="left")
1026
+ ttk.Button(button_frame, text="Load Segment", command=self.load_segment_and_visualize).pack(side="left",
1027
+ padx=(5, 0))
1028
+
1029
+ # === Middle: Label Viewer ===
1030
+ middle_panel = ttk.Frame(container)
1031
+ middle_panel.pack(side="left", fill="y", padx=(5, 10))
1032
+
1033
+ ttk.Label(middle_panel, text="Detected Labels:").pack(anchor="w")
1034
+ self.training_labels_listbox = tk.Listbox(middle_panel, height=20, exportselection=False)
1035
+ self.training_labels_listbox.pack(pady=5, expand=True)
1036
+
1037
+ label_button_frame = ttk.Frame(middle_panel)
1038
+ label_button_frame.pack(pady=5, fill="x")
1039
+ ttk.Button(label_button_frame, text="Refresh Labels", command=self.refresh_labels_list).pack(side="left",
1040
+ padx=(0, 5))
1041
+ ttk.Button(label_button_frame, text="Remove Label", command=self.remove_selected_label).pack(side="left")
1042
+
1043
+ # === Right: Feature + Preprocessing Settings ===
1044
+ right_panel = ttk.Frame(container)
1045
+ right_panel.pack(side="left", fill="y")
1046
+
1047
+ # === Preprocessing Settings ===
1048
+ pre_frame = ttk.LabelFrame(right_panel, text="Preprocessing", padding=(5, 5))
1049
+ pre_frame.pack(fill="x", pady=(0, 10))
1050
+
1051
+ self.training_features = {}
1052
+ self.feature_controls = {}
1053
+
1054
+ ttk.Button(pre_frame, text="Copy Display Filter Settings", command=self.copy_display_to_training_filters).pack(
1055
+ anchor="w")
1056
+
1057
+ self.training_features["notch"] = tk.BooleanVar(value=True)
1058
+ ttk.Checkbutton(pre_frame, text="Notch Filter (60 Hz)", variable=self.training_features["notch"]).pack(
1059
+ anchor="w")
1060
+
1061
+ self.training_features["bandpass"] = tk.BooleanVar(value=True)
1062
+ ttk.Checkbutton(pre_frame, text="Bandpass Filter", variable=self.training_features["bandpass"]).pack(anchor="w")
1063
+
1064
+ self.training_features["rectify"] = tk.BooleanVar(value=True)
1065
+ ttk.Checkbutton(pre_frame, text="Rectify Signal", variable=self.training_features["rectify"]).pack(anchor="w")
1066
+
1067
+ self.training_features["envelop_smooth"] = tk.BooleanVar(value=True)
1068
+ ttk.Checkbutton(pre_frame, text="Envelope Smooth", variable=self.training_features["envelop_smooth"]).pack(
1069
+ anchor="w")
1070
+
1071
+ ttk.Label(pre_frame, text="Envelope LF (Hz):").pack(anchor="w")
1072
+ self.smooth_f_entry = ttk.Entry(pre_frame, width=10)
1073
+ self.smooth_f_entry.insert(0, "5")
1074
+ self.smooth_f_entry.pack(anchor="w", pady=(0, 5))
1075
+
1076
+ # === Feature Extraction Settings ===
1077
+ feat_frame = ttk.LabelFrame(right_panel, text="Feature Extraction", padding=(5, 5))
1078
+ feat_frame.pack(fill="x", pady=(0, 10))
1079
+
1080
+ self.training_features["use_sliding_window"] = tk.BooleanVar(value=True)
1081
+ ttk.Checkbutton(feat_frame, text="Use Sliding Window",
1082
+ variable=self.training_features["use_sliding_window"]).pack(anchor="w")
1083
+
1084
+ ttk.Label(feat_frame, text="Window Size (ms):").pack(anchor="w")
1085
+ self.window_size_entry = ttk.Entry(feat_frame, width=10)
1086
+ self.window_size_entry.insert(0, "250")
1087
+ self.window_size_entry.pack(anchor="w")
1088
+ ttk.Label(feat_frame, text="Step Size (ms):").pack(anchor="w")
1089
+ self.step_size_entry = ttk.Entry(feat_frame, width=10)
1090
+ self.step_size_entry.insert(0, "50")
1091
+ self.step_size_entry.pack(anchor="w")
1092
+
1093
+ self.training_features["rms"] = tk.BooleanVar(value=True)
1094
+ ttk.Checkbutton(feat_frame, text="RMS", variable=self.training_features["rms"]).pack(anchor="w")
1095
+
1096
+ self.training_features["mean_absolute_value"] = tk.BooleanVar(value=True)
1097
+ ttk.Checkbutton(feat_frame, text="Mean Absolute Value",
1098
+ variable=self.training_features["mean_absolute_value"]).pack(anchor="w")
1099
+
1100
+ self.training_features["zero_crossings"] = tk.BooleanVar(value=True)
1101
+ frame_zc = ttk.Frame(feat_frame)
1102
+ frame_zc.pack(anchor="w", fill="x")
1103
+ ttk.Checkbutton(frame_zc, text="Zero Crossings", variable=self.training_features["zero_crossings"]).pack(
1104
+ side="left")
1105
+ ttk.Label(frame_zc, text="Thresh:").pack(side="left")
1106
+ zc_thresh = ttk.Entry(frame_zc, width=6)
1107
+ zc_thresh.insert(0, "0.01")
1108
+ zc_thresh.pack(side="left")
1109
+ self.feature_controls["zero_crossings"] = {"threshold": zc_thresh}
1110
+
1111
+ self.training_features["slope_sign_changes"] = tk.BooleanVar(value=True)
1112
+ frame_ssc = ttk.Frame(feat_frame)
1113
+ frame_ssc.pack(anchor="w", fill="x")
1114
+ ttk.Checkbutton(frame_ssc, text="Slope Sign Changes",
1115
+ variable=self.training_features["slope_sign_changes"]).pack(side="left")
1116
+ ttk.Label(frame_ssc, text="ΔThresh:").pack(side="left")
1117
+ ssc_thresh = ttk.Entry(frame_ssc, width=6)
1118
+ ssc_thresh.insert(0, "0.01")
1119
+ ssc_thresh.pack(side="left")
1120
+ self.feature_controls["slope_sign_changes"] = {"delta_threshold": ssc_thresh}
1121
+
1122
+ self.training_features["waveform_length"] = tk.BooleanVar(value=True)
1123
+ frame_wl = ttk.Frame(feat_frame)
1124
+ frame_wl.pack(anchor="w", fill="x")
1125
+ ttk.Checkbutton(frame_wl, text="Waveform Length", variable=self.training_features["waveform_length"]).pack(
1126
+ side="left")
1127
+ ttk.Label(frame_wl, text="Window (ms):").pack(side="left")
1128
+ wl_window_entry = ttk.Entry(frame_wl, width=6)
1129
+ wl_window_entry.insert(0, "200")
1130
+ wl_window_entry.pack(side="left")
1131
+ self.feature_controls["waveform_length"] = {"window_ms": wl_window_entry}
1132
+
1133
+ # === PCA Components ===
1134
+ ttk.Label(right_panel, text="PCA Components:").pack(anchor="w", pady=(10, 0))
1135
+ self.pca_components_entry = ttk.Entry(right_panel, width=10)
1136
+ self.pca_components_entry.insert(0, "50")
1137
+ self.pca_components_entry.pack(anchor="w", pady=(0, 10))
1138
+
1139
+ ttk.Button(right_panel, text="Build Training Set", command=self.build_training_dataset).pack(pady=15)
1140
+
1141
+ def add_feature_directory(self):
1142
+ path = filedialog.askdirectory(title="Select EMG Segment Directory")
1143
+ if path:
1144
+ self.features_dir_listbox.insert("end", path)
1145
+
1146
+ def add_training_directory(self):
1147
+ folder_path = filedialog.askdirectory(title="Select EMG Segment Directory")
1148
+ if not folder_path:
1149
+ return
1150
+
1151
+ for fname in sorted(os.listdir(folder_path)):
1152
+ if fname.endswith(".npz"):
1153
+ full_path = os.path.join(folder_path, fname)
1154
+ self.training_dir_table.insert("", "end", values=[full_path])
1155
+ self.update_training_labels_from_filename(fname)
1156
+
1157
+ def apply_visualization_filters(self, signal):
1158
+ """
1159
+ Filtering for visualization using Filtering Tab controls.
1160
+ """
1161
+ x = np.atleast_2d(signal)
1162
+ if x.shape[0] > x.shape[1]:
1163
+ x = x.T # (channels, samples)
1164
+ fs = self.sampling_rate or 2000
1165
+
1166
+ # CAR (display)
1167
+ if self.car_enabled.get() and x.shape[0] > 1:
1168
+ x = common_average_reference(x)
1169
+
1170
+ # Bandpass (display)
1171
+ try:
1172
+ low = float(self.low_cut.get())
1173
+ high = float(self.high_cut.get())
1174
+ order = int(self.filter_order.get())
1175
+ if fs/2 > high > low > 0:
1176
+ x = bandpass_filter(x, lowcut=low, highcut=high, fs=fs, order=order, axis=1)
1177
+ except Exception as e:
1178
+ print(f"[Visualization bandpass error] {e}")
1179
+
1180
+ # Notch (display)
1181
+ if hasattr(self, 'notch_enabled') and self.notch_enabled.get():
1182
+ try:
1183
+ x = notch_filter(x, fs=fs, f0=60, Q=30, axis=1)
1184
+ except Exception as e:
1185
+ print(f"[Visualization notch error] {e}")
1186
+
1187
+ return np.squeeze(x)
1188
+
1189
+ def copy_display_to_training_filters(self):
1190
+ # If you have dedicated bandpass entries for training filters
1191
+ self.bp_low_entry.delete(0, 'end')
1192
+ self.bp_low_entry.insert(0, self.low_cut.get())
1193
+ self.bp_high_entry.delete(0, 'end')
1194
+ self.bp_high_entry.insert(0, self.high_cut.get())
1195
+ self.bp_order_entry.delete(0, 'end')
1196
+ self.bp_order_entry.insert(0, self.filter_order.get())
1197
+ self.training_features["notch"].set(self.notch_enabled.get())
1198
+ self.training_features["car"].set(self.car_enabled.get())
1199
+
1200
+ def load_feature_segments(self):
1201
+ self.features_segment_listbox.delete(0, "end")
1202
+ for i in range(self.features_dir_listbox.size()):
1203
+ dir_path = self.features_dir_listbox.get(i)
1204
+ if os.path.exists(dir_path):
1205
+ for fname in sorted(os.listdir(dir_path)):
1206
+ if fname.endswith(".npz"):
1207
+ full_path = os.path.join(dir_path, fname)
1208
+ self.features_segment_listbox.insert("end", full_path)
1209
+
1210
+ def load_segment_and_visualize(self):
1211
+ selection = self.training_dir_table.selection()
1212
+ if not selection:
1213
+ print("No segment file selected.")
1214
+ return
1215
+
1216
+ path = self.training_dir_table.item(selection[0])["values"][0]
1217
+ if not os.path.exists(path):
1218
+ print(f"Segment file not found: {path}")
1219
+ return
1220
+
1221
+ # Load EMG data
1222
+ data = np.load(path, allow_pickle=True)
1223
+ emg = data["emg"]
1224
+ fs = float(data.get("fs", self.sampling_rate or 2000))
1225
+
1226
+ # Store for later plotting
1227
+ emg = self.apply_training_filters(emg)
1228
+
1229
+ self.segment_data = emg
1230
+ self.segment_fs = fs
1231
+
1232
+ # Update channel selector to reflect segment shape
1233
+ self.channel_selector["values"] = [f"Ch {i}" for i in range(emg.shape[0])]
1234
+ self.channel_selector.current(0)
1235
+ self.current_channel = 0
1236
+
1237
+ # Force plot update
1238
+ self.domain_mode.set("Features")
1239
+ self.plot_channel()
1240
+ print("Segment loaded and visualized.")
1241
+
1242
+ def load_file(self):
1243
+ """ Load a .rhd file and plot the first channel."""
1244
+ path = filedialog.askopenfilename(filetypes=[
1245
+ ("RHD files", "*.rhd"),
1246
+ ("CSV Files", "*.csv"),
1247
+ ])
1248
+ if not path:
1249
+ return
1250
+ if path.endswith('.csv'):
1251
+ # Load CSV file. first column has timestamp data in milliseconds elapsed, the rest are EMG channels if
1252
+ # they have "EMG" in the name. The first row has only header information
1253
+ data = np.loadtxt(path, delimiter=',', skiprows=1)
1254
+ self.time_vector = data[:, 0] / 1000.0
1255
+
1256
+ # Find the columns that contain "EMG" in their header
1257
+ with open(path, 'r') as f:
1258
+ header = f.readline().strip().split(',')
1259
+ emg_columns = [i for i, col in enumerate(header) if "EMG" in col]
1260
+ self.emg_data = data[:, emg_columns].T
1261
+
1262
+ self.sampling_rate = 1000.0 / (self.time_vector[1] - self.time_vector[0]) # Assuming uniform sampling
1263
+ elif path.endswith('.rhd') and load_rhd_file is not None:
1264
+ try:
1265
+ result = load_rhd_file(path)
1266
+ self.emg_data = result.get("amplifier_data") or result.get('data')
1267
+ # fallback keys
1268
+ self.time_vector = result.get("t_amplifier") or result.get('t')
1269
+ self.sampling_rate = result.get("frequency_parameters", {}).get("amplifier_sample_rate")
1270
+ except Exception as e:
1271
+ print(f"Failed to load .rhd with intan.io: {e}")
1272
+ return
1273
+ else:
1274
+ # fallback: try csv or numpy loader
1275
+ try:
1276
+ if path.endswith('.npy') or path.endswith('.npz'):
1277
+ arr = np.load(path)
1278
+ if isinstance(arr, np.lib.npyio.NpzFile):
1279
+ self.emg_data = arr[arr.files[0]]
1280
+ else:
1281
+ self.emg_data = arr
1282
+ else:
1283
+ data = np.loadtxt(path, delimiter=',')
1284
+ # assume first column may be time
1285
+ if data.ndim > 1 and data.shape[1] > 1:
1286
+ self.time_vector = data[:, 0] / 1000.0
1287
+ self.emg_data = data[:, 1:].T
1288
+ else:
1289
+ self.emg_data = data.T
1290
+ except Exception as e:
1291
+ print(f"Failed to load file: {e}")
1292
+ return
1293
+
1294
+ self.data_viewer_file_path = path
1295
+ self.channel_selector["values"] = [f"Ch {i}" for i in range(self.emg_data.shape[0])]
1296
+ self.channel_selector.current(0)
1297
+ self.current_channel = 0
1298
+ self.plot_channel()
1299
+
1300
+ def update_training_labels_from_directory(self):
1301
+ """ Helper function to refresh the training labels listbox with all the labels detected from the current directories"""
1302
+ # Delete all labels from the listbox
1303
+ self.training_labels_listbox.delete(0, "end")
1304
+
1305
+ # Iterate through each directory in training_dir_table
1306
+ for item in self.training_dir_table.get_children():
1307
+ path = self.training_dir_table.item(item)["values"][0]
1308
+ if os.path.exists(path):
1309
+ self.update_training_labels_from_filename(path)
1310
+
1311
+ def remove_training_directory(self):
1312
+ selected = self.training_dir_table.selection()
1313
+ for item in selected:
1314
+ self.training_dir_table.delete(item)
1315
+ self.refresh_labels_list()
1316
+
1317
+ def remove_selected_label(self):
1318
+ selection = self.training_labels_listbox.curselection()
1319
+ if selection:
1320
+ self.training_labels_listbox.delete(selection[0])
1321
+ else:
1322
+ print("Please select a label to remove.")
1323
+
1324
+ def visualize_selected_segment(self):
1325
+ selection = self.features_segment_listbox.curselection()
1326
+ if not selection:
1327
+ print("Please select a segment file to view.")
1328
+ return
1329
+
1330
+ path = self.features_segment_listbox.get(selection[0])
1331
+ if not os.path.exists(path):
1332
+ print(f"File not found: {path}")
1333
+ return
1334
+
1335
+ data = np.load(path, allow_pickle=True)
1336
+ emg = data["emg"]
1337
+ fs = data.get("fs", self.sampling_rate or 2000)
1338
+
1339
+ # Apply preprocessing
1340
+ if self.features_filters["bandpass"].get():
1341
+ b, a = butter(4, [20, 450], btype="band", fs=fs)
1342
+ emg = filtfilt(b, a, emg, axis=1)
1343
+ if self.features_filters["notch"].get():
1344
+ b, a = iirnotch(60, 30, fs)
1345
+ emg = filtfilt(b, a, emg, axis=1)
1346
+ if self.features_filters["rectify"].get():
1347
+ emg = np.abs(emg)
1348
+ if self.features_filters["smooth_rms"].get():
1349
+ kernel = np.ones(int(0.2 * fs)) / int(0.2 * fs)
1350
+ emg = np.apply_along_axis(lambda x: np.convolve(x, kernel, mode="same"), axis=1, arr=emg)
1351
+
1352
+ self.ax.clear()
1353
+
1354
+ # Plot preprocessed EMG (all channels with offset)
1355
+ offset = 0
1356
+ for i, ch in enumerate(emg):
1357
+ self.ax.plot(np.arange(len(ch)) / fs, ch + offset, label=f"Ch {i}", linewidth=0.6)
1358
+ offset += np.max(np.abs(ch)) * 2 # dynamic spacing
1359
+
1360
+ self.ax.set_title("Segment with Preprocessing")
1361
+ self.ax.set_xlabel("Time (s)")
1362
+ self.ax.set_ylabel("Amplitude + offset")
1363
+ self.ax.grid(True)
1364
+
1365
+ self.canvas.draw()
1366
+ print("Segment visualization updated.")
1367
+
1368
+ def run_pca_visualization(self):
1369
+ path = filedialog.askopenfilename(title="Select Feature CSV Dataset", filetypes=[("CSV Files", "*.csv")])
1370
+ if not path or not os.path.exists(path):
1371
+ print("No dataset selected or file does not exist.")
1372
+ return
1373
+
1374
+ df = pd.read_csv(path)
1375
+ if "Label" not in df.columns:
1376
+ print("No 'Label' column found in dataset.")
1377
+ return
1378
+
1379
+ features = df.drop(columns=["Label"]).values
1380
+ labels = df["Label"].values
1381
+
1382
+ # Encode labels if necessary
1383
+ le = LabelEncoder()
1384
+ labels_encoded = le.fit_transform(labels)
1385
+
1386
+ # Apply PCA
1387
+ pca = PCA(n_components=2)
1388
+ reduced = pca.fit_transform(features)
1389
+
1390
+ # Plot results
1391
+ self.ax.clear()
1392
+ for i, label in enumerate(np.unique(labels_encoded)):
1393
+ idx = labels_encoded == label
1394
+ self.ax.scatter(reduced[idx, 0], reduced[idx, 1], label=le.classes_[i], alpha=0.6)
1395
+ self.ax.set_title("2D PCA of EMG Features")
1396
+ self.ax.set_xlabel("PC1")
1397
+ self.ax.set_ylabel("PC2")
1398
+ self.ax.legend()
1399
+ self.canvas.draw()
1400
+
1401
+ def refresh_labels_list(self):
1402
+ """
1403
+ Clear and rebuild the labels list from all currently listed directories.
1404
+ """
1405
+ self.training_labels_listbox.delete(0, "end")
1406
+ for item in self.training_dir_table.get_children():
1407
+ path = self.training_dir_table.item(item)["values"][0]
1408
+ self.update_training_labels_from_directory(path)
1409
+
1410
+ def update_training_labels_from_filename(self, fname):
1411
+ """
1412
+ Extract label from filename and add to label list if not already present.
1413
+ Assumes filenames like: participant_label_0.npz
1414
+ """
1415
+ parts = fname.replace(".npz", "").split("_")
1416
+ if len(parts) >= 2:
1417
+ label = parts[-2].strip().lower()
1418
+ if label and label not in self.training_labels_listbox.get(0, "end"):
1419
+ self.training_labels_listbox.insert("end", label)
1420
+
1421
+ def run_trial_segmentation(self):
1422
+ """
1423
+ Segment the EMG data into trials based on manual indices or notes files.
1424
+ Saves each segment as a compressed .npz file (with 'emg' data and 'label') in an 'emg' subfolder.
1425
+ """
1426
+ from intan.io import load_rhd_file, load_labeled_file
1427
+ # Determine output directory for segmented files
1428
+ if self.data_viewer_file_path:
1429
+ # If a file is currently loaded in the viewer, use its directory
1430
+ raw_folder = os.path.dirname(self.data_viewer_file_path)
1431
+ else:
1432
+ # Otherwise, ask the user to select the top-level raw data directory
1433
+ raw_folder = filedialog.askdirectory(title="Select Raw Data Directory")
1434
+ if not raw_folder:
1435
+ return # user canceled
1436
+
1437
+ out_dir = os.path.join(os.path.dirname(raw_folder), "emg") # output subdirectory for segments
1438
+ os.makedirs(out_dir, exist_ok=True)
1439
+
1440
+ # If manual markers exist in the table and an EMG file is loaded, segment using those
1441
+ if self.emg_data is not None and len(self.table.get_children()) > 0:
1442
+ # Get all markers from the table
1443
+ markers = []
1444
+ for row in self.table.get_children():
1445
+ sample_idx, label = self.table.item(row)["values"]
1446
+ markers.append((int(sample_idx), str(label)))
1447
+ # Sort markers by sample index
1448
+ markers.sort(key=lambda x: x[0])
1449
+ # Convert to DataFrame for consistency
1450
+ notes_df = pd.DataFrame(markers, columns=["Sample", "Label"])
1451
+ # Add a final marker at end of recording to segment the last trial (if not already present)
1452
+ total_samples = self.emg_data.shape[1]
1453
+ if notes_df.iloc[-1]["Sample"] != total_samples:
1454
+ notes_df = pd.concat([notes_df, pd.DataFrame([[total_samples, ""]], columns=["Sample", "Label"])],
1455
+ ignore_index=True)
1456
+ # Use the loaded EMG data and manual markers for segmentation
1457
+ trial_name = os.path.basename(raw_folder) # use folder name as trial identifier
1458
+ for i in range(len(notes_df) - 1):
1459
+ label = notes_df.loc[i, "Label"]
1460
+ if str(label).strip() == "" or str(label).lower() == "nan":
1461
+ continue # skip empty labels (if any)
1462
+ start_idx = notes_df.loc[i, "Sample"]
1463
+ end_idx = notes_df.loc[i + 1, "Sample"]
1464
+ segment = self.emg_data[:, start_idx:end_idx]
1465
+ # Safe label for filename (no spaces, lowercase)
1466
+ label_safe = str(label).strip().replace(" ", "_").lower()
1467
+ file_name = f"{trial_name}_{label_safe}_{i}.npz"
1468
+ save_path = os.path.join(out_dir, file_name)
1469
+ # Save segment with label and include sampling rate for reference
1470
+ np.savez_compressed(save_path, emg=segment, label=label, fs=self.sampling_rate)
1471
+ print(f"Saved: {save_path}")
1472
+ print(f"Segments saved to {out_dir}")
1473
+ return
1474
+
1475
+ # Otherwise, process notes files in the selected directory (batch mode for multiple trials)
1476
+ # If the selected raw_folder itself contains an RHD file and a notes file, process it as one trial
1477
+ main_notes_path = os.path.join(raw_folder, "notes.txt")
1478
+ processed_any = False
1479
+ if os.path.isfile(main_notes_path):
1480
+ # Find an RHD file in this folder (assuming one RHD per folder)
1481
+ rhd_files = [f for f in os.listdir(raw_folder) if f.endswith(".rhd")]
1482
+ if rhd_files:
1483
+ rhd_path = os.path.join(raw_folder, rhd_files[0])
1484
+ notes_df = load_labeled_file(path=main_notes_path)
1485
+ trial_name = os.path.basename(raw_folder)
1486
+ result = load_rhd_file(rhd_path)
1487
+ emg_data = result["amplifier_data"]
1488
+ fs = result["frequency_parameters"]["amplifier_sample_rate"]
1489
+ # Segment this single trial folder
1490
+ for i in range(len(notes_df) - 1):
1491
+ label = notes_df.loc[i, "Label"]
1492
+ if str(label).strip() == "" or str(label).lower() == "nan":
1493
+ continue
1494
+ start_idx = notes_df.loc[i, "Sample"]
1495
+ end_idx = notes_df.loc[i + 1, "Sample"]
1496
+ segment = emg_data[:, start_idx:end_idx]
1497
+ label_safe = str(label).strip().replace(" ", "_").lower()
1498
+ save_path = os.path.join(out_dir, f"{trial_name}_{label_safe}_{i}.npz")
1499
+ np.savez_compressed(save_path, emg=segment, label=label, fs=fs)
1500
+ print(f"Saved: {save_path}")
1501
+ processed_any = True
1502
+
1503
+ # Process all subfolders in raw_folder (each subfolder is a trial folder)
1504
+ for folder_name in os.listdir(raw_folder):
1505
+ folder_path = os.path.join(raw_folder, folder_name)
1506
+ if not os.path.isdir(folder_path):
1507
+ continue
1508
+ rhd_file = os.path.join(folder_path, f"{folder_name}.rhd")
1509
+ notes_file = os.path.join(folder_path, "notes.txt")
1510
+ if os.path.exists(rhd_file) and os.path.exists(notes_file):
1511
+ # Load data and notes for this trial
1512
+ print("file found containing labeled time indices. Processing:", folder_name)
1513
+ result = load_rhd_file(rhd_file)
1514
+ emg_data = result["amplifier_data"]
1515
+ fs = result["frequency_parameters"]["amplifier_sample_rate"]
1516
+ notes_df = load_labeled_file(path=notes_file)
1517
+ # Segment the trial data using note indices
1518
+ for i in range(len(notes_df) - 1):
1519
+ label = notes_df.loc[i, "Label"]
1520
+ if str(label).strip() == "" or str(label).lower() == "nan":
1521
+ continue
1522
+ start_idx = notes_df.loc[i, "Sample"]
1523
+ end_idx = notes_df.loc[i + 1, "Sample"]
1524
+ segment = emg_data[:, start_idx:end_idx]
1525
+ label_safe = str(label).strip().replace(" ", "_").lower()
1526
+ save_path = os.path.join(out_dir, f"{folder_name}_{label_safe}_{i}.npz")
1527
+ np.savez_compressed(save_path, emg=segment, label=label, fs=fs)
1528
+ print(f"Saved: {save_path}")
1529
+ processed_any = True
1530
+
1531
+ if processed_any:
1532
+ print("Segmentation Complete", f"Segments saved to {out_dir}")
1533
+ else:
1534
+ print("No Segmentation Performed", "No .rhd and notes.txt pairs were found to segment.")
1535
+
1536
+ def enable_indexing(self):
1537
+ self.indexing_enabled = True
1538
+
1539
+ def scroll_plot(self, *args):
1540
+ if self.emg_data is None:
1541
+ return
1542
+ start_idx = int(float(args[1]) * len(self.time_vector))
1543
+ end_idx = start_idx + int(self.sampling_rate * 1) # ~1s window
1544
+ self.ax.set_xlim(self.time_vector[start_idx], self.time_vector[min(end_idx, len(self.time_vector) - 1)])
1545
+ self.canvas.draw()
1546
+
1547
+ def on_click(self, event):
1548
+ if not self.indexing_enabled or event.inaxes != self.ax:
1549
+ return
1550
+ sample_index = int(event.xdata * self.sampling_rate)
1551
+ label = self.label_entry.get()
1552
+ self.table.insert("", "end", values=(sample_index, label))
1553
+ self.ax.axvline(x=event.xdata, color='blue', linestyle='--')
1554
+ self.canvas.draw()
1555
+ self.indexing_enabled = False
1556
+
1557
+ def save_table(self):
1558
+ path = filedialog.asksaveasfilename(defaultextension=".txt")
1559
+ if not path:
1560
+ return
1561
+ with open(path, "w") as f:
1562
+ f.write("Sample Index,Label\n")
1563
+ for row in self.table.get_children():
1564
+ sample_index, label = self.table.item(row)["values"]
1565
+ f.write(f"{sample_index},{label}\n")
1566
+ print(f"Saved to {path}")
1567
+
1568
+ def parse_channel_range(self, text):
1569
+ try:
1570
+ indices = []
1571
+ parts = text.split(',')
1572
+ for part in parts:
1573
+ part = part.strip()
1574
+ if '-' in part:
1575
+ start, end = map(int, part.split('-'))
1576
+ indices.extend(range(start, end + 1))
1577
+ else:
1578
+ indices.append(int(part))
1579
+ return sorted(set(indices))
1580
+ except Exception as e:
1581
+ print(f"Error parsing channel range: {e}")
1582
+ return list(range(16)) # fallback
1583
+
1584
+ def load_table(self):
1585
+
1586
+ from intan.io import load_labeled_file
1587
+ df_sorted = load_labeled_file()
1588
+
1589
+ # Update the table with the loaded data
1590
+ for row in self.table.get_children():
1591
+ self.table.delete(row)
1592
+ for _, row in df_sorted.iterrows():
1593
+ self.table.insert("", "end", values=(row["Sample"], row["Label"]))
1594
+ self.plot_channel()
1595
+
1596
+ def delete_selected(self):
1597
+ for item in self.table.selection():
1598
+ self.table.delete(item)
1599
+
1600
+ def update_channel(self, event=None):
1601
+ self.xlim = self.ax.get_xlim()
1602
+ self.ylim = self.ax.get_ylim()
1603
+ self.current_channel = self.channel_selector.current()
1604
+ self.plot_channel()
1605
+
1606
+ def plot_channel(self, event=None):
1607
+
1608
+ self.ax.clear()
1609
+ if self.emg_data_raw is None:
1610
+ self.canvas.draw()
1611
+ return
1612
+
1613
+ if self.domain_mode.get() == "Features":
1614
+ if self.segment_data is None:
1615
+ print("No segment loaded for 'Features' mode.")
1616
+ return
1617
+
1618
+ ch_data = self.segment_data[self.current_channel]
1619
+ fs = self.segment_fs or 2000
1620
+ time = np.arange(len(ch_data)) / fs
1621
+
1622
+ ch_data = self.apply_training_filters(ch_data)
1623
+
1624
+ self.ax.plot(time, ch_data, label="Segment Ch {}".format(self.current_channel))
1625
+
1626
+ # Overlay selected features (as text)
1627
+ features = self.extract_td_features(self.segment_data)
1628
+ text_lines = []
1629
+ if self.training_features["mean_absolute_value"].get():
1630
+ text_lines.append(f"MAV: {features[0]:.2f}")
1631
+ if self.training_features["zero_crossings"].get():
1632
+ zc_idx = 1 if "mean_absolute_value" in self.training_features and self.training_features[
1633
+ "mean_absolute_value"].get() else 0
1634
+ text_lines.append(f"ZC: {features[zc_idx]:.0f}")
1635
+
1636
+ self.ax.set_title("Features: " + ", ".join(text_lines))
1637
+ self.ax.set_xlabel("Time (s)")
1638
+ self.ax.set_ylabel("Amplitude (µV)")
1639
+ self.ax.grid(True)
1640
+ self.canvas.draw()
1641
+ return
1642
+
1643
+ signal = self.emg_data_raw[self.current_channel]
1644
+ #signal = self.apply_visualization_filters(signal)
1645
+ if np.any(np.isnan(signal)) or np.any(np.isinf(signal)):
1646
+ print("Warning: filtered signal contains NaN or Inf values. They will be replaced with 0 for display.")
1647
+ signal = np.nan_to_num(signal)
1648
+
1649
+ if self.domain_mode.get() == "Time":
1650
+ self.ax.plot(self.time_vector, signal, label=f"Ch {self.current_channel}")
1651
+ self.ax.set_xlabel("Time (s)")
1652
+ self.ax.set_ylabel("Amplitude (µV)")
1653
+ self.ax.set_title("EMG Time Domain")
1654
+
1655
+ # === Draw vertical lines for labeled trials ===
1656
+ if self.show_lines.get():
1657
+ for row in self.table.get_children():
1658
+ sample_index, label = self.table.item(row)["values"]
1659
+ t = sample_index / self.sampling_rate
1660
+ self.ax.axvline(x=t, color="red", linestyle="--", linewidth=1)
1661
+ self.ax.text(t + 0.05, self.ax.get_ylim()[1], label,
1662
+ rotation=90, verticalalignment="top", fontsize=8, color="red")
1663
+
1664
+ if self.xlim:
1665
+ self.ax.set_xlim(self.xlim)
1666
+ if self.ylim:
1667
+ self.ax.set_ylim(self.ylim)
1668
+
1669
+ elif self.domain_mode.get() == "PSD":
1670
+ N = len(signal)
1671
+ fs = self.sampling_rate
1672
+ frequencies = np.fft.rfftfreq(N, d=1 / fs)
1673
+ fft_magnitude = np.abs(np.fft.rfft(signal)) / N # normalized magnitude
1674
+ self.ax.plot(frequencies, fft_magnitude)
1675
+ self.ax.set_ylabel("Magnitude")
1676
+ self.ax.set_title("EMG Power Spectral Density")
1677
+ self.ax.set_xlabel("Frequency (Hz)")
1678
+ self.ax.set_xlim(float(self.psd_min_freq.get()), float(self.psd_max_freq.get()))
1679
+
1680
+ elif self.domain_mode.get() == "Spectrogram":
1681
+ try:
1682
+ nfft = int(self.nfft_entry.get())
1683
+ noverlap = int(self.noverlap_entry.get())
1684
+ cmap = self.cmap_entry.get()
1685
+ fs = self.sampling_rate
1686
+
1687
+ # parse the signal with the time limits
1688
+ time_min = float(self.spec_time_range_min.get())
1689
+ time_max = float(self.spec_time_range_max.get())
1690
+ time_min_idx = int(time_min * fs)
1691
+ time_max_idx = int(time_max * fs)
1692
+ signal = signal[time_min_idx:time_max_idx]
1693
+
1694
+ f, t, Sxx = spectrogram(signal, fs=fs, nperseg=nfft, noverlap=noverlap)
1695
+ self.ax.pcolormesh(t, f, 10 * np.log10(Sxx), shading='gouraud', cmap=cmap)
1696
+ self.ax.set_ylabel("Frequency (Hz)")
1697
+ self.ax.set_xlabel("Time (s)")
1698
+ self.ax.set_title("EMG Spectrogram")
1699
+ self.ax.set_ylim(float(self.spec_freq_min.get()), float(self.spec_freq_max.get()))
1700
+
1701
+ except Exception as e:
1702
+ self.ax.text(0.5, 0.5, f"Spectrogram error: {str(e)}", ha="center")
1703
+
1704
+ elif self.domain_mode.get() == "Waterfall":
1705
+ ch_range_str = self.channel_range_entry.get()
1706
+ channel_indices = self.parse_channel_range(ch_range_str)
1707
+ self.waterfall_gui_plot(channel_indices)
1708
+
1709
+ else:
1710
+ raise ValueError("Invalid domain mode selected.")
1711
+
1712
+ self.canvas.draw()
1713
+
1714
+ def extract_features_from_directories(self):
1715
+ """
1716
+ Iterate over each selected directory of segmented trials, apply filters,
1717
+ extract features, and aggregate the results. Saves individual feature files and builds a dataset.
1718
+ """
1719
+ all_features = [] # will collect feature vectors for dataset
1720
+ all_labels = [] # will collect corresponding labels
1721
+
1722
+ # Loop through each directory added in the Training tab's directory list
1723
+ for item in self.dir_table.get_children():
1724
+ dir_path = self.dir_table.item(item)["values"][0]
1725
+ # Process each segmented .npz file in the directory
1726
+ for fname in os.listdir(dir_path):
1727
+ if not fname.endswith(".npz"):
1728
+ continue
1729
+ file_path = os.path.join(dir_path, fname)
1730
+ data = np.load(file_path, allow_pickle=True)
1731
+ emg = data["emg"] # segmented EMG data (channels x samples)
1732
+ label = data.get("label", "unknown").item() # segment label
1733
+
1734
+ # Use sampling rate from file if available, otherwise fallback to a default
1735
+ fs = data.get("fs", None)
1736
+ if fs is None:
1737
+ fs = self.sampling_rate or 2000 # default to 2000 Hz if not specified
1738
+
1739
+ # --- Apply selected preprocessing filters ---
1740
+ if self.filters["bandpass"].get():
1741
+ # Bandpass filter (20-450 Hz) to remove motion artifacts and noise
1742
+ #b, a = butter(4, [20, 450], btype="band", fs=fs)
1743
+ #emg = filtfilt(b, a, emg, axis=1)
1744
+ emg = bandpass_filter(emg, lowcut=20, highcut=450, fs=fs, order=4)
1745
+ if self.filters["notch"].get():
1746
+ # Notch filter at 60 Hz to remove powerline interference
1747
+ #b, a = iirnotch(60, Q=30, fs=fs)
1748
+ #emg = filtfilt(b, a, emg, axis=1)
1749
+ emg = notch_filter(emg, freq=60, fs=fs, Q=30)
1750
+ if self.filters["rectify"].get():
1751
+ # Rectification (absolute value of the signal)
1752
+ emg = np.abs(emg)
1753
+ if self.filters["smooth_rms"].get():
1754
+ # Smoothing via moving window (200 ms RMS)
1755
+ window_len = int(0.2 * fs) # 200 ms window length in samples
1756
+ if window_len > 1:
1757
+ kernel = np.ones(window_len) / window_len
1758
+ # Apply convolution along each channel (moving average = rough RMS)
1759
+ emg = np.apply_along_axis(lambda x: np.convolve(x, kernel, mode='same'), axis=1, arr=emg)
1760
+
1761
+ # --- Extract selected features from the entire segment ---
1762
+ feature_vector = self.extract_td_features(emg)
1763
+ all_features.append(feature_vector)
1764
+ all_labels.append(label)
1765
+
1766
+ # Save feature vector to a file (optional, for inspection or later use)
1767
+ feat_filename = os.path.join(dir_path, f"{os.path.splitext(fname)[0]}_feat.npy")
1768
+ np.save(feat_filename, feature_vector)
1769
+ # Note: We save as .npy (features only). The label is tracked separately in all_labels.
1770
+
1771
+ # After processing all directories, build a combined dataset (features + labels)
1772
+ if not all_features:
1773
+ print("Warning: No features were extracted (check directory contents).")
1774
+ return
1775
+
1776
+ features_array = np.vstack(all_features) # shape: (num_samples, num_features)
1777
+ labels_array = np.array(all_labels, dtype=str) # shape: (num_samples,)
1778
+
1779
+ # Save the combined dataset to a CSV for easy viewing (features and label column)
1780
+ df = pd.DataFrame(features_array)
1781
+ df["Label"] = labels_array
1782
+ save_path = filedialog.asksaveasfilename(title="Save Training Dataset", defaultextension=".csv",
1783
+ filetypes=[("CSV files", "*.csv")])
1784
+ if save_path:
1785
+ df.to_csv(save_path, index=False)
1786
+ print(f"Training dataset saved to {save_path}")
1787
+ else:
1788
+ # If user cancels save, still store the dataset in memory (e.g., as attributes)
1789
+ self.training_features = features_array
1790
+ self.training_labels = labels_array
1791
+ print("Training dataset has been created in memory.")
1792
+
1793
+ def extract_td_features(self, segment):
1794
+ """ Computes a variety of unique features from segmented EMG data. Input shape expects (channels x samples). """
1795
+ features = []
1796
+ fs = self.segment_fs or self.sampling_rate or 2000
1797
+
1798
+ for ch_data in segment:
1799
+ ch_features = []
1800
+
1801
+ # Mean Absolute Value (MAV)
1802
+ if self.training_features.get("mean_absolute_value", tk.BooleanVar()).get():
1803
+ ch_features.append(np.mean(np.abs(ch_data)))
1804
+
1805
+ # Zero Crossings (ZC)
1806
+ if self.training_features.get("zero_crossings", tk.BooleanVar()).get():
1807
+ try:
1808
+ thresh = float(self.feature_controls["zero_crossings"]["threshold"].get())
1809
+ except (KeyError, ValueError):
1810
+ thresh = 0.01
1811
+ zc = np.sum((np.diff(np.sign(ch_data)) != 0) & (np.abs(np.diff(ch_data)) > thresh))
1812
+ ch_features.append(zc)
1813
+
1814
+ # Slope Sign Changes (SSC)
1815
+ if self.training_features.get("slope_sign_changes", tk.BooleanVar()).get():
1816
+ try:
1817
+ delta_thresh = float(self.feature_controls["slope_sign_changes"]["delta_threshold"].get())
1818
+ except (KeyError, ValueError):
1819
+ delta_thresh = 0.01
1820
+ diff = np.diff(ch_data)
1821
+ ssc = np.sum((np.diff(np.sign(diff)) != 0) & (np.abs(np.diff(diff)) > delta_thresh))
1822
+ ch_features.append(ssc)
1823
+
1824
+ # Waveform Length (WL) - supports sub-windowed WL if segment is longer than window
1825
+ if self.training_features.get("waveform_length", tk.BooleanVar()).get():
1826
+ try:
1827
+ window_ms = float(self.feature_controls["waveform_length"]["window_ms"].get())
1828
+ except (KeyError, ValueError):
1829
+ window_ms = 200
1830
+ window_len = int((window_ms / 1000.0) * fs)
1831
+
1832
+ if len(ch_data) < window_len:
1833
+ wl = np.sum(np.abs(np.diff(ch_data)))
1834
+ else:
1835
+ wl_vals = []
1836
+ for start in range(0, len(ch_data) - window_len + 1, window_len):
1837
+ sub_window = ch_data[start:start + window_len]
1838
+ wl_vals.append(np.sum(np.abs(np.diff(sub_window))))
1839
+ wl = np.mean(wl_vals)
1840
+ ch_features.append(wl)
1841
+
1842
+ # RMS (used in Jehan Yang paper)
1843
+ if self.training_features.get("rms", tk.BooleanVar()).get():
1844
+ rms = np.sqrt(np.mean(ch_data ** 2))
1845
+ ch_features.append(rms)
1846
+
1847
+ features.extend(ch_features)
1848
+
1849
+ return np.array(features)
1850
+
1851
+ def apply_training_filters(self, emg):
1852
+ """Applies selected filters to the EMG data. Handles both 1D (single channel) and 2D arrays."""
1853
+ fs = self.sampling_rate or 2000
1854
+ x = np.atleast_2d(emg)
1855
+ if x.shape[0] > x.shape[1]:
1856
+ x = x.T # (channels, samples)
1857
+
1858
+ if self.training_features.get("car", tk.BooleanVar(value=False)).get() and x.shape[0] > 1:
1859
+ x = common_average_reference(x)
1860
+ if self.training_features["bandpass"].get():
1861
+ x = bandpass_filter(x, lowcut=float(self.low_cut.get()), highcut=float(self.high_cut.get()),
1862
+ fs=fs, order=int(self.filter_order.get()))
1863
+ if self.training_features["notch"].get():
1864
+ x = notch_filter(x, fs=fs, f0=60, Q=30, axis=1)
1865
+ if self.training_features["rectify"].get():
1866
+ x = rectify(x)
1867
+ if self.training_features["envelop_smooth"].get():
1868
+ try:
1869
+ envelop_f = float(self.smooth_f_entry.get())
1870
+ except ValueError:
1871
+ envelop_f = 5.0
1872
+ win_len = int(fs // envelop_f)
1873
+ if win_len > 1:
1874
+ x = window_rms(x, window_size=win_len)
1875
+ return np.squeeze(x)
1876
+
1877
+ def add_scalebars(self, ax, scale_time=5, scale_voltage=10):
1878
+ ax.plot([0, scale_time], [-1000, -1000], color='gray', lw=3)
1879
+ ax.text(scale_time / 2, -1500, '5 sec', va='center', ha='center', fontsize=10, color='gray')
1880
+ ax.plot([0, 0], [-1000, -1000 + scale_voltage * 10], color='gray', lw=3)
1881
+ ax.text(-0.5, -500, '10 mV', va='center', ha='center', rotation='vertical', fontsize=10, color='gray')
1882
+
1883
+ def insert_channel_labels(self, ax, time_vector, num_channels, num_labels=2, font_size=8):
1884
+ x_pos = time_vector[-1] + 1
1885
+ y_offsets = np.linspace(200, 25500, num_channels)
1886
+ ch_indices = np.linspace(0, num_channels - 1, num_labels, dtype=int)
1887
+ for ch in ch_indices:
1888
+ ax.text(x_pos, y_offsets[ch], f"Channel {ch}", fontsize=font_size, va='center',
1889
+ ha='left', color='black', fontweight='bold')
1890
+
1891
+ def insert_vertical_labels(self, ax):
1892
+ ax.text(-1, 5000, 'Extensor', fontsize=12, va='center', ha='center', color='black', rotation='vertical')
1893
+ ax.text(-1, 22000, 'Flexor', fontsize=12, va='center', ha='center', color='black', rotation='vertical')
1894
+
1895
+ def build_training_dataset(self):
1896
+ # === Ask user for save location ===
1897
+ save_path = filedialog.asksaveasfilename(
1898
+ title="Save Training Dataset As",
1899
+ defaultextension=".npz",
1900
+ filetypes=[("NumPy Compressed", "*.npz")],
1901
+ initialfile="training_data.npz"
1902
+ )
1903
+ if not save_path:
1904
+ print("Dataset save cancelled.")
1905
+ return
1906
+ # Automatically derive PCA save path from dataset path
1907
+ pca_save_path = save_path.replace(".npz", "_pca.pkl")
1908
+
1909
+ X = [] # Will hold the data features
1910
+ y = [] # Labels for the data
1911
+ fs = self.sampling_rate or 2000
1912
+ label_encoder = LabelEncoder()
1913
+
1914
+ # === Loop over training_dir_table entries ===
1915
+ training_files = self.training_dir_table.get_children()
1916
+ for item in tqdm(training_files, desc="Extracting Features", position=0):
1917
+ file_path = self.training_dir_table.item(item)["values"][0]
1918
+ if not file_path.endswith(".npz") or not os.path.exists(file_path):
1919
+ continue
1920
+
1921
+ # === Load the EMG data ===
1922
+ try:
1923
+ data = np.load(file_path)
1924
+ emg = data["emg"]
1925
+ label = data["label"].item() if "label" in data else "unknown"
1926
+ except Exception as e:
1927
+ print(f"Skipped {file_path}: could not load ({e})")
1928
+ continue
1929
+
1930
+ # === Skip segments that are too short for filtering ===
1931
+ if emg.shape[1] < 27:
1932
+ print(f"Skipped {file_path}: segment too short ({emg.shape[1]} samples)")
1933
+ continue
1934
+
1935
+ #print(f"Processing {file_path} with label: {label}")
1936
+ # === Apply training filters ======
1937
+ emg = self.apply_training_filters(emg)
1938
+
1939
+ #print(f"\nEMG data shape: {emg.shape}")
1940
+
1941
+ # === Extract features from the segment ===
1942
+ if self.training_features["use_sliding_window"].get():
1943
+ # Sliding window feature extraction
1944
+ window_size = int(self.window_size_entry.get())
1945
+ step_size = int(self.step_size_entry.get())
1946
+
1947
+ if window_size <= 0 or step_size <= 0:
1948
+ print("Error: Window and step size must be positive.")
1949
+ return
1950
+
1951
+ num_windows = (emg.shape[1] - window_size) // step_size + 1
1952
+
1953
+ #print(f"Sliding window selected, number of window segments: {num_windows}")
1954
+ for i in tqdm(range(num_windows),
1955
+ desc=f"{os.path.basename(file_path)}",
1956
+ position=1, leave=False):
1957
+ start = i * step_size
1958
+ end = start + window_size
1959
+ if end > emg.shape[1]:
1960
+ break
1961
+ segment = emg[:, start:end]
1962
+ if segment.shape[1] != window_size:
1963
+ continue
1964
+
1965
+ # Extract features from the segment
1966
+ X.append(self.extract_td_features(segment))
1967
+ y.append(label)
1968
+
1969
+ else:
1970
+ # Single-segment feature extraction (entire EMG segment)
1971
+ X.append(self.extract_td_features(emg))
1972
+ y.append(label)
1973
+
1974
+ #print(f"Current data size: {len(X)} segments")
1975
+
1976
+
1977
+ if not X:
1978
+ print("Error: No valid segments were processed.")
1979
+ return
1980
+
1981
+ X = np.array(X)
1982
+ print("Shape of feature vectors:", X.shape)
1983
+ y_encoded = label_encoder.fit_transform(y)
1984
+
1985
+ # === Normalize features ===
1986
+ mean = X.mean(axis=0)
1987
+ std = X.std(axis=0)
1988
+ std[std == 0] = 1 # Avoid division by zero for constant features
1989
+ X = (X - mean) / std
1990
+ norm_save_path = save_path.replace(".npz", "_norm.npz")
1991
+ np.savez(norm_save_path, mean=mean, std=std)
1992
+
1993
+ if X.shape[1] == 0:
1994
+ print("Error: Feature vectors are empty. Did you select any features?")
1995
+ return
1996
+
1997
+ if not any(var.get() for var in self.training_features.values()):
1998
+ print("Warning: No features selected in GUI.")
1999
+
2000
+ # === Apply PCA dimensionality reduction ===
2001
+ n_components = int(self.pca_components_entry.get()) if self.pca_components_entry.get().isdigit() else 50
2002
+ pca = PCA(n_components=n_components)
2003
+
2004
+ pca.fit(X)
2005
+ joblib.dump(pca, pca_save_path)
2006
+ print(f"PCA model saved to: {pca_save_path}")
2007
+ X = pca.transform(X) # now transform with saved-fit PCA
2008
+
2009
+ print(f"New shape of feature vectors after PCA: {X.shape}")
2010
+
2011
+ np.savez_compressed(save_path, features=X, labels=y_encoded, label_names=label_encoder.classes_)
2012
+ print(f"Training dataset saved to: {save_path}")
2013
+
2014
+ def waterfall_gui_plot(self, channel_indices):
2015
+ signal = self.emg_data
2016
+ time_vector = self.time_vector
2017
+ ax = self.ax
2018
+ ax.clear()
2019
+
2020
+ offset = 0
2021
+ offset_increment = 200
2022
+ cmap = plt.get_cmap("rainbow")
2023
+ num_channels = len(channel_indices)
2024
+ downsampling_factor = 1
2025
+
2026
+ signal = signal[:, ::downsampling_factor]
2027
+ time_vector = time_vector[::downsampling_factor]
2028
+
2029
+ for i, channel_idx in enumerate(channel_indices):
2030
+ if channel_idx < signal.shape[0]:
2031
+ channel_data = self.apply_training_filters(signal[channel_idx])
2032
+ color = cmap(i / num_channels)
2033
+ ax.plot(time_vector, channel_data + offset, color=color, linewidth=0.2)
2034
+ offset += offset_increment
2035
+
2036
+ self.add_scalebars(ax)
2037
+ self.insert_vertical_labels(ax)
2038
+ self.insert_channel_labels(ax, time_vector, num_channels)
2039
+
2040
+ ax.set_title("Waterfall Plot", fontsize=12, fontweight="bold")
2041
+ ax.set_xticks([])
2042
+ ax.set_yticks([])
2043
+ for spine in ax.spines.values():
2044
+ spine.set_visible(False)
2045
+
2046
+ def on_closing(self):
2047
+ self.root.quit()
2048
+
2049
+
2050
+ # Prefer the Qt implementation when the GUI extra is installed while keeping
2051
+ # the Tk implementation available to callers that rely on it.
2052
+ EMGViewer = EMGViewerQt if _HAS_PYQT else EMGViewerTk