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.
- intan/__init__.py +46 -33
- intan/_cli.py +21 -0
- intan/applications/__init__.py +22 -0
- intan/applications/_emg_trial_selector.py +430 -0
- intan/applications/_emg_viewer.py +2052 -0
- intan/applications/_launcher.py +36 -0
- intan/decomposition/__init__.py +12 -0
- intan/decomposition/_cfica.py +183 -0
- intan/decomposition/_pca.py +42 -0
- intan/interface/__init__.py +24 -0
- intan/interface/_device_utils.py +173 -0
- intan/interface/_lsl_client.py +343 -0
- intan/interface/_lsl_options.py +15 -0
- intan/interface/_lsl_publisher.py +139 -0
- intan/interface/_lsl_subscriber.py +408 -0
- intan/interface/_messaging.py +81 -0
- intan/{control/_messaging.py → interface/_pico.py} +1 -81
- intan/interface/_playback_options.py +29 -0
- intan/interface/_rhx_config.py +333 -0
- intan/interface/_rhx_device.py +498 -0
- intan/io/__init__.py +109 -20
- intan/io/_canonicalizer.py +82 -0
- intan/io/_config_utils.py +281 -0
- intan/io/_csv_utils.py +247 -0
- intan/io/_dataset_utils.py +267 -0
- intan/io/_exceptions.py +30 -1
- intan/io/_file_utils.py +586 -35
- intan/io/_grid_utils.py +280 -0
- intan/io/_io_optimized.py +310 -0
- intan/io/_npz_utils.py +745 -0
- intan/io/{_block_parser.py → _rhd_block_parser.py} +129 -6
- intan/io/{_channel_utils.py → _rhd_channel_utils.py} +26 -1
- intan/io/_rhd_header_parsing.py +791 -0
- intan/io/_rhd_loader.py +595 -71
- intan/io/_utilities.py +995 -0
- intan/ml/__init__.py +47 -0
- intan/ml/_evaluation.py +305 -0
- intan/ml/_ml_utilities.py +155 -0
- intan/ml/_model_manager.py +547 -0
- intan/ml/_models.py +143 -0
- intan/ml/_prediction_modes.py +478 -0
- intan/ml/_prediction_utils.py +199 -0
- intan/plotting/__init__.py +30 -2
- intan/plotting/_realtime_plotter.py +105 -0
- intan/plotting/_stacked_plot.py +385 -0
- intan/plotting/_waterfall.py +38 -17
- intan/processing/__init__.py +40 -8
- intan/processing/_channel_qc.py +253 -0
- intan/processing/_data_processing.py +21 -0
- intan/processing/_features.py +460 -0
- intan/processing/_fill.py +309 -0
- intan/processing/_filters.py +127 -437
- intan/processing/_imu_features.py +195 -0
- intan/processing/_metrics_utils.py +44 -56
- intan/processing/_preprocessing.py +208 -0
- intan/processing/_realtime_filter.py +298 -0
- intan/processing/_sync.py +292 -0
- intan/processing/_temporal_filters.py +289 -0
- intan/processing/_transformations.py +168 -0
- intan/samples/__init__.py +1 -0
- intan/samples/_find_file.py +35 -0
- intan/ui/__init__.py +31 -0
- intan/ui/_helpers.py +109 -0
- python_intan-0.2.3.dist-info/METADATA +230 -0
- python_intan-0.2.3.dist-info/RECORD +69 -0
- {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/WHEEL +1 -1
- python_intan-0.2.3.dist-info/entry_points.txt +3 -0
- intan/control/__init__.py +0 -1
- intan/io/_data_processing.py +0 -193
- intan/io/_header_parsing.py +0 -383
- intan/io/_metadata_utils.py +0 -150
- intan/plotting/_emg_plots.py +0 -245
- python_intan-0.0.2.dist-info/METADATA +0 -185
- python_intan-0.0.2.dist-info/RECORD +0 -23
- {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/licenses/LICENSE +0 -0
- {python_intan-0.0.2.dist-info → python_intan-0.2.3.dist-info}/top_level.txt +0 -0
intan/__init__.py
CHANGED
|
@@ -1,42 +1,55 @@
|
|
|
1
1
|
"""
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
Intan: Python interface for reading, processing, and visualizing data
|
|
3
|
+
from Intan Technologies' RHD2000 and RHS2000 acquisition systems.
|
|
4
|
+
|
|
5
|
+
This package includes modules for:
|
|
6
|
+
- Reading and parsing `.rhd` and `.rhs` files
|
|
7
|
+
- Streamed acquisition via TCP/IP from the Intan RHX software
|
|
8
|
+
- Visualization of high-density EMG or LFP signals
|
|
9
|
+
- Configuration and device control
|
|
10
10
|
"""
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
12
|
+
__version__ = "0.2.3"
|
|
13
|
+
__author__ = "Jonathan Shulgach"
|
|
14
|
+
__email__ = "jshulgac@andrew.cmu.edu"
|
|
15
|
+
__license__ = "MIT"
|
|
16
|
+
__url__ = "https://github.com/Neuro-Mechatronics-Interfaces/python-intan"
|
|
17
|
+
__description__ = "Python interface for streaming, parsing, and analyzing Intan Technologies RHX files"
|
|
18
|
+
|
|
19
|
+
from importlib import import_module as _import_module
|
|
20
|
+
|
|
21
|
+
submodules = [
|
|
22
|
+
'applications',
|
|
23
|
+
'decomposition',
|
|
24
|
+
'io',
|
|
25
|
+
'ml',
|
|
26
|
+
'plotting',
|
|
27
|
+
'processing',
|
|
28
|
+
'interface',
|
|
29
|
+
'samples',
|
|
30
|
+
'ui',
|
|
31
|
+
]
|
|
20
32
|
|
|
21
33
|
__all__ = submodules + [
|
|
22
|
-
'LowLevelCallable',
|
|
23
|
-
'
|
|
24
|
-
'show_config',
|
|
34
|
+
#'LowLevelCallable',
|
|
35
|
+
#'tests',
|
|
36
|
+
#'show_config',
|
|
25
37
|
'__version__',
|
|
26
38
|
]
|
|
27
39
|
|
|
28
40
|
|
|
29
|
-
def __dir__():
|
|
30
|
-
return __all__
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
def __getattr__(name):
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
def __dir__():
|
|
42
|
+
return __all__
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def __getattr__(name):
|
|
46
|
+
"""Import public subpackages on first access.
|
|
47
|
+
|
|
48
|
+
This keeps ``import intan`` lightweight while supporting the documented
|
|
49
|
+
``intan.io`` and ``intan.processing`` attribute style.
|
|
50
|
+
"""
|
|
51
|
+
if name in submodules:
|
|
52
|
+
module = _import_module(f"{__name__}.{name}")
|
|
53
|
+
globals()[name] = module
|
|
54
|
+
return module
|
|
55
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
intan/_cli.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Console entry points for the optional GUI applications."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _parser(description: str) -> argparse.ArgumentParser:
|
|
7
|
+
return argparse.ArgumentParser(description=description)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def emg_viewer_main() -> None:
|
|
11
|
+
_parser("Launch the python-intan EMG viewer.").parse_args()
|
|
12
|
+
from intan.applications import launch_emg_viewer
|
|
13
|
+
|
|
14
|
+
launch_emg_viewer()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def trial_selector_main() -> None:
|
|
18
|
+
_parser("Launch the python-intan EMG trial selector.").parse_args()
|
|
19
|
+
from intan.applications import launch_emg_trial_selector
|
|
20
|
+
|
|
21
|
+
launch_emg_trial_selector()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Lightweight package exports for intan.applications.
|
|
2
|
+
|
|
3
|
+
Make imports lazy/guarded so importing the package doesn't pull optional GUI,
|
|
4
|
+
SciPy, or pandas dependencies during CLI or test runs.
|
|
5
|
+
"""
|
|
6
|
+
try:
|
|
7
|
+
from ._emg_viewer import EMGViewer
|
|
8
|
+
except Exception:
|
|
9
|
+
EMGViewer = None
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from ._launcher import launch_emg_viewer, launch_emg_trial_selector
|
|
13
|
+
except Exception:
|
|
14
|
+
def launch_emg_viewer(*a, **k):
|
|
15
|
+
raise RuntimeError('launch_emg_viewer is unavailable (import failed)')
|
|
16
|
+
def launch_emg_trial_selector(*a, **k):
|
|
17
|
+
raise RuntimeError('launch_emg_trial_selector is unavailable (import failed)')
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
from ._emg_trial_selector import EMGTrialSelector
|
|
21
|
+
except Exception:
|
|
22
|
+
EMGTrialSelector = None
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intan.processing._emg_trial_selector
|
|
3
|
+
|
|
4
|
+
Graphical tool for interactively labeling trial events on EMG recordings.
|
|
5
|
+
|
|
6
|
+
This GUI allows researchers to:
|
|
7
|
+
- Load and visualize EMG signals from `.rhd` files
|
|
8
|
+
- Select individual channels
|
|
9
|
+
- Click to mark trial onset points
|
|
10
|
+
- Assign labels to each indexed event
|
|
11
|
+
- Append new recordings for multi-session review
|
|
12
|
+
- Export trial events to a timestamped CSV or TXT file
|
|
13
|
+
|
|
14
|
+
Clicking the signal while "Set Trial Index" is enabled will add a labeled marker.
|
|
15
|
+
This tool is useful for supervised training of gesture classifiers, post-hoc annotation,
|
|
16
|
+
or protocol validation in EMG experiments.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import tkinter as tk
|
|
20
|
+
from tkinter import filedialog, messagebox, ttk, Scrollbar, VERTICAL
|
|
21
|
+
import numpy as np
|
|
22
|
+
import datetime
|
|
23
|
+
import matplotlib.pyplot as plt
|
|
24
|
+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class EMGTrialSelector:
|
|
28
|
+
"""
|
|
29
|
+
Tkinter-based application for manual EMG trial indexing.
|
|
30
|
+
|
|
31
|
+
Attributes:
|
|
32
|
+
emg_data (np.ndarray): EMG signal matrix (channels × samples)
|
|
33
|
+
time_vector (np.ndarray): Time vector aligned with EMG samples
|
|
34
|
+
sampling_rate (float): Sampling rate of amplifier
|
|
35
|
+
current_channel (int): Channel index currently displayed
|
|
36
|
+
indexing_enabled (bool): If True, allows user to click to insert marker
|
|
37
|
+
"""
|
|
38
|
+
def __init__(self, root):
|
|
39
|
+
self.root = root
|
|
40
|
+
self.root.title("EMG Trial Selector")
|
|
41
|
+
|
|
42
|
+
self.emg_data = None
|
|
43
|
+
self.time_vector = None
|
|
44
|
+
self.sampling_rate = None
|
|
45
|
+
self.current_channel = 0
|
|
46
|
+
self.indexing_enabled = False
|
|
47
|
+
|
|
48
|
+
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
|
|
49
|
+
|
|
50
|
+
# --- Top Controls Frame ---
|
|
51
|
+
control_frame = tk.Frame(root)
|
|
52
|
+
control_frame.pack(side="top", fill="x", pady=5)
|
|
53
|
+
|
|
54
|
+
tk.Button(control_frame, text="Load EMG File", command=self.load_file).pack(side="left", padx=5)
|
|
55
|
+
tk.Button(control_frame, text="Set Trial Index", command=self.enable_indexing).pack(side="left", padx=5)
|
|
56
|
+
tk.Button(control_frame, text="Append EMG File", command=self.append_file).pack(side="left", padx=5)
|
|
57
|
+
|
|
58
|
+
# --- Main Frame (Canvas + Sidebar) ---
|
|
59
|
+
main_frame = tk.Frame(root)
|
|
60
|
+
main_frame.pack(side="top", fill="both", expand=True)
|
|
61
|
+
|
|
62
|
+
# === Plot Area ===
|
|
63
|
+
self.figure, self.ax = plt.subplots(figsize=(10, 4))
|
|
64
|
+
self.canvas = FigureCanvasTkAgg(self.figure, master=main_frame)
|
|
65
|
+
self.canvas_widget = self.canvas.get_tk_widget()
|
|
66
|
+
self.canvas_widget.pack(side="left", fill="both", expand=True)
|
|
67
|
+
|
|
68
|
+
# === Sidebar Frame ===
|
|
69
|
+
sidebar_frame = tk.Frame(main_frame)
|
|
70
|
+
sidebar_frame.pack(side="right", fill="y", padx=10)
|
|
71
|
+
|
|
72
|
+
# --- Channel Selector ---
|
|
73
|
+
tk.Label(sidebar_frame, text="Channel:").pack(anchor="w")
|
|
74
|
+
self.channel_selector = ttk.Combobox(sidebar_frame, state="readonly")
|
|
75
|
+
self.channel_selector.bind("<<ComboboxSelected>>", self.update_channel)
|
|
76
|
+
self.channel_selector.pack(fill="x", pady=5)
|
|
77
|
+
|
|
78
|
+
# --- Label Entry Field ---
|
|
79
|
+
tk.Label(sidebar_frame, text="Custom Label:").pack(anchor="w")
|
|
80
|
+
self.label_entry = tk.Entry(sidebar_frame)
|
|
81
|
+
self.label_entry.pack(fill="x", pady=5)
|
|
82
|
+
self.label_entry.insert(0, "Label") # Default text
|
|
83
|
+
|
|
84
|
+
# --- Table ---
|
|
85
|
+
self.table = ttk.Treeview(sidebar_frame, columns=("Sample Index", "Label"), show="headings", height=20)
|
|
86
|
+
self.table.heading("Sample Index", text="Sample Index")
|
|
87
|
+
self.table.heading("Label", text="Label")
|
|
88
|
+
self.table.column("Sample Index", width=100)
|
|
89
|
+
self.table.column("Label", width=100)
|
|
90
|
+
self.table.pack(side="top", fill="y")
|
|
91
|
+
|
|
92
|
+
scrollbar = Scrollbar(sidebar_frame, orient=VERTICAL, command=self.table.yview)
|
|
93
|
+
self.table.configure(yscrollcommand=scrollbar.set)
|
|
94
|
+
scrollbar.pack(side="right", fill="y")
|
|
95
|
+
|
|
96
|
+
# --- Save & Delete Buttons ---
|
|
97
|
+
button_frame = tk.Frame(sidebar_frame)
|
|
98
|
+
button_frame.pack(side="bottom", pady=10)
|
|
99
|
+
tk.Button(button_frame, text="Save", command=self.save_table).pack(side="left", padx=5)
|
|
100
|
+
tk.Button(button_frame, text="Delete", command=self.delete_selected).pack(side="left", padx=5)
|
|
101
|
+
|
|
102
|
+
# Track drawn marker artists so we can clear them
|
|
103
|
+
self._marker_artists = []
|
|
104
|
+
|
|
105
|
+
# --- Edge Extraction Controls ---
|
|
106
|
+
tk.Label(sidebar_frame, text="Edge detect (selected chan)").pack(anchor="w", pady=(12, 0))
|
|
107
|
+
|
|
108
|
+
edge_frame = tk.Frame(sidebar_frame)
|
|
109
|
+
edge_frame.pack(fill="x", pady=4)
|
|
110
|
+
|
|
111
|
+
tk.Label(edge_frame, text="Threshold").grid(row=0, column=0, sticky="w")
|
|
112
|
+
self.edge_threshold_entry = tk.Entry(edge_frame, width=10)
|
|
113
|
+
self.edge_threshold_entry.grid(row=0, column=1, sticky="w", padx=4)
|
|
114
|
+
self.edge_threshold_entry.insert(0, "0.5") # default threshold
|
|
115
|
+
|
|
116
|
+
tk.Label(edge_frame, text="Type").grid(row=1, column=0, sticky="w")
|
|
117
|
+
self.edge_type_combo = ttk.Combobox(edge_frame, state="readonly", width=12,
|
|
118
|
+
values=["rising", "falling"])
|
|
119
|
+
self.edge_type_combo.grid(row=1, column=1, sticky="w", padx=4)
|
|
120
|
+
self.edge_type_combo.current(0)
|
|
121
|
+
|
|
122
|
+
tk.Label(edge_frame, text="Min gap (ms)").grid(row=2, column=0, sticky="w")
|
|
123
|
+
self.edge_mingap_entry = tk.Entry(edge_frame, width=10)
|
|
124
|
+
self.edge_mingap_entry.grid(row=2, column=1, sticky="w", padx=4)
|
|
125
|
+
self.edge_mingap_entry.insert(0, "50") # debounce gap
|
|
126
|
+
|
|
127
|
+
btns = tk.Frame(sidebar_frame)
|
|
128
|
+
btns.pack(fill="x", pady=4)
|
|
129
|
+
tk.Button(btns, text="Extract Edges", command=self.extract_edges).pack(side="left", padx=3)
|
|
130
|
+
tk.Button(btns, text="Clear Indices", command=self.clear_indices).pack(side="left", padx=3)
|
|
131
|
+
|
|
132
|
+
self.canvas.mpl_connect("button_press_event", self.on_click)
|
|
133
|
+
|
|
134
|
+
def load_file(self):
|
|
135
|
+
"""
|
|
136
|
+
Load EMG data from a .rhd file and initialize the GUI with the first channel.
|
|
137
|
+
"""
|
|
138
|
+
from intan.io import load_rhd_file, load_csv_file
|
|
139
|
+
|
|
140
|
+
path = filedialog.askopenfilename(filetypes=[
|
|
141
|
+
("RHD files", "*.rhd"),
|
|
142
|
+
("NPZ Files", "*.npz"),
|
|
143
|
+
("CSV Files", "*.csv"),
|
|
144
|
+
("All files", "*.*")])
|
|
145
|
+
if not path:
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
if path.endswith('.csv'):
|
|
149
|
+
# Load CSV file. first column has timestamp data in milliseconds elapsed, the rest are EMG channels if
|
|
150
|
+
# they have "EMG" in the name. The first row has only header information
|
|
151
|
+
# data = np.loadtxt(path, delimiter=',', skiprows=1)
|
|
152
|
+
data = load_csv_file(path)
|
|
153
|
+
self.time_vector = data['t_amplifier']
|
|
154
|
+
self.emg_data = data["amplifier_data"]
|
|
155
|
+
# append imu data if present
|
|
156
|
+
imu = data.get("board_adc_data", None)
|
|
157
|
+
self.emg_data = self.emg_data.astype(float, copy=False)
|
|
158
|
+
if imu is not None:
|
|
159
|
+
imu = imu.astype(float, copy=False)
|
|
160
|
+
self.emg_data = np.vstack((self.emg_data, imu))
|
|
161
|
+
|
|
162
|
+
# dt = float(self.time_vector[1] - self.time_vector[0])
|
|
163
|
+
# if dt <= 0:
|
|
164
|
+
# messagebox.showerror("Error", "Non-positive timestep in CSV.")
|
|
165
|
+
# return
|
|
166
|
+
# self.sampling_rate = 1.0 / dt # Hz (seconds already)
|
|
167
|
+
self.sampling_rate = float(data['frequency_parameters']['amplifier_sample_rate'])
|
|
168
|
+
|
|
169
|
+
elif path.endswith('.npz'):
|
|
170
|
+
# Load NPZ file. Should have 'emg_data' or 'emg', 'time_vector' or 't', and 'sampling_rate' or 'fs' keys
|
|
171
|
+
data = np.load(path)
|
|
172
|
+
self.emg_data = data['emg_data'] if 'emg_data' in data else data['emg']
|
|
173
|
+
self.time_vector = data['time_vector'] if 'time_vector' in data else data['t']
|
|
174
|
+
self.sampling_rate = float(data['sampling_rate'] if 'sampling_rate' in data else data['fs'])
|
|
175
|
+
|
|
176
|
+
else:
|
|
177
|
+
# Load RHD file. Should have dedicated structure
|
|
178
|
+
result = load_rhd_file(path)
|
|
179
|
+
self.emg_data = result["amplifier_data"]
|
|
180
|
+
self.time_vector = result["t_amplifier"]
|
|
181
|
+
self.sampling_rate = result["frequency_parameters"]["amplifier_sample_rate"]
|
|
182
|
+
|
|
183
|
+
self.channel_selector['values'] = [f"Channel {i}" for i in range(self.emg_data.shape[0])]
|
|
184
|
+
self.channel_selector.current(0)
|
|
185
|
+
self.current_channel = 0
|
|
186
|
+
self.plot_channel()
|
|
187
|
+
|
|
188
|
+
def append_file(self):
|
|
189
|
+
"""
|
|
190
|
+
Append EMG data from another .rhd file to the current data.
|
|
191
|
+
"""
|
|
192
|
+
from intan.io import load_rhd_file
|
|
193
|
+
|
|
194
|
+
path = filedialog.askopenfilename(filetypes=[("RHD files", "*.rhd"), ("All files", "*.*")])
|
|
195
|
+
if not path:
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
result = load_rhd_file(path)
|
|
199
|
+
new_emg = result["amplifier_data"]
|
|
200
|
+
new_time = result["t_amplifier"]
|
|
201
|
+
new_rate = result["frequency_parameters"]["amplifier_sample_rate"]
|
|
202
|
+
|
|
203
|
+
if self.emg_data is None:
|
|
204
|
+
# If no prior data, treat this like a fresh load
|
|
205
|
+
self.emg_data = new_emg
|
|
206
|
+
self.time_vector = new_time
|
|
207
|
+
self.sampling_rate = new_rate
|
|
208
|
+
self.channel_selector['values'] = [f"Channel {i}" for i in range(self.emg_data.shape[0])]
|
|
209
|
+
self.channel_selector.current(0)
|
|
210
|
+
self.current_channel = 0
|
|
211
|
+
self.plot_channel()
|
|
212
|
+
return
|
|
213
|
+
|
|
214
|
+
# Sanity check: channel count and sampling rate must match
|
|
215
|
+
if new_emg.shape[0] != self.emg_data.shape[0] or new_rate != self.sampling_rate:
|
|
216
|
+
messagebox.showerror("Error", "Appended file must have same channel count and sampling rate.")
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
# Offset time vector based on last timestamp
|
|
220
|
+
last_time = self.time_vector[-1]
|
|
221
|
+
offset_time = new_time
|
|
222
|
+
|
|
223
|
+
self.emg_data = np.concatenate((self.emg_data, new_emg), axis=1)
|
|
224
|
+
self.time_vector = np.concatenate((self.time_vector, offset_time))
|
|
225
|
+
self.plot_channel()
|
|
226
|
+
|
|
227
|
+
def sample_index_to_timestamp(self, index):
|
|
228
|
+
"""
|
|
229
|
+
Convert a sample index to a timestamp string.
|
|
230
|
+
|
|
231
|
+
Parameters:
|
|
232
|
+
index (int): Sample index to convert.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
str: Formatted timestamp string (HH:MM:SS).
|
|
236
|
+
"""
|
|
237
|
+
seconds = index / self.sampling_rate
|
|
238
|
+
return str(datetime.timedelta(seconds=int(seconds)))
|
|
239
|
+
|
|
240
|
+
def save_table(self):
|
|
241
|
+
"""
|
|
242
|
+
Save the trial markers to a text file with sample index and timestamp.
|
|
243
|
+
"""
|
|
244
|
+
path = filedialog.asksaveasfilename(
|
|
245
|
+
defaultextension=".txt",
|
|
246
|
+
filetypes=[("Text Files", "*.txt")],
|
|
247
|
+
title="Save Trial Markers"
|
|
248
|
+
)
|
|
249
|
+
if not path:
|
|
250
|
+
return
|
|
251
|
+
|
|
252
|
+
# Collect and sort table data by sample index
|
|
253
|
+
rows = []
|
|
254
|
+
for row in self.table.get_children():
|
|
255
|
+
sample_index, label = self.table.item(row)["values"]
|
|
256
|
+
sample_index = int(sample_index)
|
|
257
|
+
timestamp = self.sample_index_to_timestamp(sample_index)
|
|
258
|
+
rows.append((sample_index, timestamp, label))
|
|
259
|
+
|
|
260
|
+
rows.sort(key=lambda x: x[0]) # Sort by sample index
|
|
261
|
+
|
|
262
|
+
# Write to text file
|
|
263
|
+
with open(path, "w") as f:
|
|
264
|
+
f.write("Sample Index,Timestamp,Label\n")
|
|
265
|
+
for sample_index, timestamp, label in rows:
|
|
266
|
+
f.write(f"{sample_index},{timestamp},{label}\n")
|
|
267
|
+
|
|
268
|
+
messagebox.showinfo("Saved", f"Trial markers saved to:\n{path}")
|
|
269
|
+
|
|
270
|
+
def delete_selected(self):
|
|
271
|
+
"""
|
|
272
|
+
Delete selected rows from the table.
|
|
273
|
+
"""
|
|
274
|
+
selected = self.table.selection()
|
|
275
|
+
for item in selected:
|
|
276
|
+
self.table.delete(item)
|
|
277
|
+
|
|
278
|
+
def _detect_edges(self, x: np.ndarray, threshold: float, edge_type: str, min_gap_samples: int) -> np.ndarray:
|
|
279
|
+
"""
|
|
280
|
+
Return sample indices where the signal crosses the threshold with a specified edge type.
|
|
281
|
+
|
|
282
|
+
x: 1D array (samples)
|
|
283
|
+
threshold: float
|
|
284
|
+
edge_type: 'rising' or 'falling'
|
|
285
|
+
min_gap_samples: minimum spacing between returned indices
|
|
286
|
+
"""
|
|
287
|
+
if edge_type == "rising":
|
|
288
|
+
crossings = np.where((x[:-1] < threshold) & (x[1:] >= threshold))[0] + 1
|
|
289
|
+
elif edge_type == "falling":
|
|
290
|
+
crossings = np.where((x[:-1] > threshold) & (x[1:] <= threshold))[0] + 1
|
|
291
|
+
else:
|
|
292
|
+
crossings = np.array([], dtype=int)
|
|
293
|
+
|
|
294
|
+
# Debounce / min gap
|
|
295
|
+
if crossings.size == 0 or min_gap_samples <= 1:
|
|
296
|
+
return crossings
|
|
297
|
+
|
|
298
|
+
keep = [crossings[0]]
|
|
299
|
+
last = crossings[0]
|
|
300
|
+
for ix in crossings[1:]:
|
|
301
|
+
if ix - last >= min_gap_samples:
|
|
302
|
+
keep.append(ix)
|
|
303
|
+
last = ix
|
|
304
|
+
return np.asarray(keep, dtype=int)
|
|
305
|
+
|
|
306
|
+
def _add_marker_line(self, t_val: float, y_val: float | None = None):
|
|
307
|
+
"""Draw and remember marker lines so we can clear them later."""
|
|
308
|
+
v = self.ax.axvline(x=t_val, color='blue', linestyle='--', alpha=0.8)
|
|
309
|
+
self._marker_artists.append(v)
|
|
310
|
+
if y_val is not None:
|
|
311
|
+
h = self.ax.axhline(y=y_val, color='red', linestyle='--', alpha=0.4)
|
|
312
|
+
self._marker_artists.append(h)
|
|
313
|
+
|
|
314
|
+
def extract_edges(self):
|
|
315
|
+
if self.emg_data is None or self.time_vector is None or self.sampling_rate is None:
|
|
316
|
+
return
|
|
317
|
+
|
|
318
|
+
try:
|
|
319
|
+
thr = float(self.edge_threshold_entry.get())
|
|
320
|
+
except Exception:
|
|
321
|
+
messagebox.showerror("Error", "Threshold must be a number.")
|
|
322
|
+
return
|
|
323
|
+
|
|
324
|
+
# Use the combobox value for detection type:
|
|
325
|
+
edge_kind = self.edge_type_combo.get() # "rising" or "falling"
|
|
326
|
+
|
|
327
|
+
# Use the text entry as the saved label:
|
|
328
|
+
label = self.label_entry.get().strip() or edge_kind
|
|
329
|
+
|
|
330
|
+
try:
|
|
331
|
+
min_gap_ms = float(self.edge_mingap_entry.get())
|
|
332
|
+
except Exception:
|
|
333
|
+
messagebox.showerror("Error", "Min gap must be a number (ms).")
|
|
334
|
+
return
|
|
335
|
+
|
|
336
|
+
min_gap_samples = max(1, int((min_gap_ms / 1000.0) * float(self.sampling_rate)))
|
|
337
|
+
|
|
338
|
+
chan = self.current_channel
|
|
339
|
+
x = self.emg_data[chan].astype(float, copy=False)
|
|
340
|
+
|
|
341
|
+
idxs = self._detect_edges(x, thr, edge_kind, min_gap_samples)
|
|
342
|
+
if idxs.size == 0:
|
|
343
|
+
messagebox.showinfo("Edges", "No edges found with current parameters.")
|
|
344
|
+
return
|
|
345
|
+
|
|
346
|
+
added = 0
|
|
347
|
+
for idx in idxs:
|
|
348
|
+
t = idx / float(self.sampling_rate)
|
|
349
|
+
self.table.insert("", "end", values=(int(idx), label))
|
|
350
|
+
self._add_marker_line(t_val=t, y_val=None)
|
|
351
|
+
added += 1
|
|
352
|
+
|
|
353
|
+
self.canvas.draw()
|
|
354
|
+
messagebox.showinfo("Edges", f"Added {added} edge(s) labeled '{label}'.")
|
|
355
|
+
|
|
356
|
+
def clear_indices(self):
|
|
357
|
+
"""Clear all rows in the table and remove drawn marker lines."""
|
|
358
|
+
# Clear table
|
|
359
|
+
for item in self.table.get_children():
|
|
360
|
+
self.table.delete(item)
|
|
361
|
+
# Remove marker artists
|
|
362
|
+
try:
|
|
363
|
+
for art in self._marker_artists:
|
|
364
|
+
art.remove()
|
|
365
|
+
except Exception:
|
|
366
|
+
pass
|
|
367
|
+
self._marker_artists.clear()
|
|
368
|
+
self.canvas.draw()
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def update_channel(self, event=None):
|
|
372
|
+
"""
|
|
373
|
+
Update the current channel based on the selection from the dropdown.
|
|
374
|
+
"""
|
|
375
|
+
if self.emg_data is None:
|
|
376
|
+
return
|
|
377
|
+
self.current_channel = self.channel_selector.current()
|
|
378
|
+
self.plot_channel()
|
|
379
|
+
|
|
380
|
+
def enable_indexing(self):
|
|
381
|
+
"""
|
|
382
|
+
Enable the indexing mode to allow trial marking on the plot.
|
|
383
|
+
"""
|
|
384
|
+
self.indexing_enabled = True
|
|
385
|
+
|
|
386
|
+
def on_click(self, event):
|
|
387
|
+
"""
|
|
388
|
+
Handle mouse click events on the plot to mark trial onset points.
|
|
389
|
+
|
|
390
|
+
Parameters:
|
|
391
|
+
event (matplotlib.backend_bases.Event): The mouse event.
|
|
392
|
+
"""
|
|
393
|
+
if not self.indexing_enabled or event.inaxes != self.ax:
|
|
394
|
+
return
|
|
395
|
+
|
|
396
|
+
time_clicked = event.xdata
|
|
397
|
+
amp_clicked = event.ydata
|
|
398
|
+
if time_clicked is None:
|
|
399
|
+
return
|
|
400
|
+
|
|
401
|
+
sample_index = max(0, int(time_clicked * self.sampling_rate))
|
|
402
|
+
#self.ax.axvline(x=time_clicked, color='blue', linestyle='--')
|
|
403
|
+
#self.ax.axhline(y=amp_clicked, color='red', linestyle='--')
|
|
404
|
+
self._add_marker_line(t_val=time_clicked, y_val=amp_clicked)
|
|
405
|
+
self.canvas.draw()
|
|
406
|
+
|
|
407
|
+
# Insert editable row into the table
|
|
408
|
+
label = self.label_entry.get()
|
|
409
|
+
self.table.insert("", "end", values=(sample_index, label))
|
|
410
|
+
self.indexing_enabled = False
|
|
411
|
+
|
|
412
|
+
def plot_channel(self):
|
|
413
|
+
"""
|
|
414
|
+
Plot the currently selected EMG channel.
|
|
415
|
+
"""
|
|
416
|
+
self.ax.clear()
|
|
417
|
+
self.ax.plot(self.time_vector, self.emg_data[self.current_channel], label=f"Channel {self.current_channel}")
|
|
418
|
+
self.ax.set_xlabel("Time (s)")
|
|
419
|
+
self.ax.set_ylabel("Amplitude (µV)")
|
|
420
|
+
self.ax.set_title("EMG Signal")
|
|
421
|
+
self.ax.legend()
|
|
422
|
+
self.canvas.draw()
|
|
423
|
+
|
|
424
|
+
def on_closing(self):
|
|
425
|
+
self.root.quit()
|
|
426
|
+
|
|
427
|
+
if __name__ == "__main__":
|
|
428
|
+
root = tk.Tk()
|
|
429
|
+
app = EMGTrialSelector(root)
|
|
430
|
+
root.mainloop()
|