python-intan 0.0.2__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 +42 -0
- intan/control/__init__.py +1 -0
- intan/control/_messaging.py +171 -0
- intan/io/__init__.py +64 -0
- intan/io/_block_parser.py +253 -0
- intan/io/_channel_utils.py +86 -0
- intan/io/_data_processing.py +193 -0
- intan/io/_exceptions.py +37 -0
- intan/io/_file_utils.py +110 -0
- intan/io/_header_parsing.py +383 -0
- intan/io/_metadata_utils.py +150 -0
- intan/io/_rhd_loader.py +199 -0
- intan/plotting/__init__.py +2 -0
- intan/plotting/_emg_plots.py +245 -0
- intan/plotting/_waterfall.py +132 -0
- intan/processing/__init__.py +20 -0
- intan/processing/_filters.py +569 -0
- intan/processing/_metrics_utils.py +84 -0
- python_intan-0.0.2.dist-info/METADATA +185 -0
- python_intan-0.0.2.dist-info/RECORD +23 -0
- python_intan-0.0.2.dist-info/WHEEL +5 -0
- python_intan-0.0.2.dist-info/licenses/LICENSE +21 -0
- python_intan-0.0.2.dist-info/top_level.txt +1 -0
intan/io/_rhd_loader.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
import tkinter as tk
|
|
4
|
+
from tkinter import filedialog
|
|
5
|
+
import numpy as np
|
|
6
|
+
from intan.io._header_parsing import read_header, header_to_result, data_to_result
|
|
7
|
+
from intan.io._metadata_utils import calculate_data_size
|
|
8
|
+
from intan.io._block_parser import read_all_data_blocks
|
|
9
|
+
from intan.io._file_utils import check_end_of_file, print_progress, get_rhd_file_paths
|
|
10
|
+
from intan.io._data_processing import parse_data, apply_notch_filter
|
|
11
|
+
|
|
12
|
+
def load_rhd_file(filepath=None, verbose=True):
|
|
13
|
+
"""Loads .rhd file with provided filename, returning 'result' dict and
|
|
14
|
+
'data_present' Boolean.
|
|
15
|
+
"""
|
|
16
|
+
if not filepath:
|
|
17
|
+
root = tk.Tk()
|
|
18
|
+
root.withdraw() # Hide the main window
|
|
19
|
+
filepath = filedialog.askopenfilename()
|
|
20
|
+
if not filepath:
|
|
21
|
+
print("No file selected, returning.")
|
|
22
|
+
return None, False
|
|
23
|
+
|
|
24
|
+
# Start timing
|
|
25
|
+
tic = time.time()
|
|
26
|
+
|
|
27
|
+
# Open file
|
|
28
|
+
fid = open(filepath, 'rb')
|
|
29
|
+
filesize = os.path.getsize(filepath)
|
|
30
|
+
|
|
31
|
+
# Read file header
|
|
32
|
+
header = read_header(fid)
|
|
33
|
+
|
|
34
|
+
# Calculate how much data is present and summarize to console.
|
|
35
|
+
data_present, filesize, num_blocks, num_samples = (
|
|
36
|
+
calculate_data_size(header, filepath, fid, verbose))
|
|
37
|
+
|
|
38
|
+
# If .rhd file contains data, read all present data blocks into 'data'
|
|
39
|
+
# dict, and verify the amount of data read.
|
|
40
|
+
if data_present:
|
|
41
|
+
data = read_all_data_blocks(header, num_samples, num_blocks, fid, verbose)
|
|
42
|
+
check_end_of_file(filesize, fid)
|
|
43
|
+
|
|
44
|
+
# Save information in 'header' to 'result' dict.
|
|
45
|
+
result = {}
|
|
46
|
+
header_to_result(header, result)
|
|
47
|
+
|
|
48
|
+
# If .rhd file contains data, parse data into readable forms and, if
|
|
49
|
+
# necessary, apply the same notch filter that was active during recording.
|
|
50
|
+
if data_present:
|
|
51
|
+
parse_data(header, data)
|
|
52
|
+
apply_notch_filter(header, data)
|
|
53
|
+
|
|
54
|
+
# Save recorded data in 'data' to 'result' dict.
|
|
55
|
+
data_to_result(header, data, result)
|
|
56
|
+
|
|
57
|
+
# Otherwise (.rhd file is just a header for One File Per Signal Type or
|
|
58
|
+
# One File Per Channel data formats, in which actual data is saved in
|
|
59
|
+
# separate .dat files), just return data as an empty list.
|
|
60
|
+
else:
|
|
61
|
+
data = []
|
|
62
|
+
|
|
63
|
+
# Report how long read took.
|
|
64
|
+
print('Done! Elapsed time: {0:0.1f} seconds'.format(time.time() - tic))
|
|
65
|
+
|
|
66
|
+
# Return 'result' dict.
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
def read_time_file(path):
|
|
70
|
+
"""Reads int32 timestamp values from a time.dat file."""
|
|
71
|
+
with open(path, 'rb') as f:
|
|
72
|
+
time_data = np.fromfile(f, dtype=np.int32)
|
|
73
|
+
return time_data
|
|
74
|
+
|
|
75
|
+
def read_amplifier_file(path, num_channels):
|
|
76
|
+
"""Reads amplifier data from a .dat file (int16 format) and reshapes it."""
|
|
77
|
+
with open(path, 'rb') as f:
|
|
78
|
+
data = np.fromfile(f, dtype=np.int16)
|
|
79
|
+
reshaped = data.reshape((-1, num_channels)).T
|
|
80
|
+
return reshaped * 0.195 # Convert to microvolts
|
|
81
|
+
|
|
82
|
+
def read_auxiliary_file(path, num_channels, scale=0.0000374):
|
|
83
|
+
"""Reads auxiliary channel data (uint16) and applies scaling."""
|
|
84
|
+
with open(path, 'rb') as f:
|
|
85
|
+
data = np.fromfile(f, dtype=np.uint16)
|
|
86
|
+
reshaped = data.reshape((-1, num_channels)).T
|
|
87
|
+
return reshaped * scale
|
|
88
|
+
|
|
89
|
+
def read_adc_file(path, num_channels, scale=0.000050354):
|
|
90
|
+
"""Reads board ADC data (uint16) and applies default scaling."""
|
|
91
|
+
with open(path, 'rb') as f:
|
|
92
|
+
data = np.fromfile(f, dtype=np.uint16)
|
|
93
|
+
reshaped = data.reshape((-1, num_channels)).T
|
|
94
|
+
return reshaped * scale
|
|
95
|
+
|
|
96
|
+
def load_dat_file(root_dir):
|
|
97
|
+
# Read the header information from the .rhd file
|
|
98
|
+
file_name = os.path.join(root_dir, 'info.rhd')
|
|
99
|
+
|
|
100
|
+
# Load the header information
|
|
101
|
+
header = load_rhd_file(file_name, verbose=False)
|
|
102
|
+
|
|
103
|
+
# Now load the associated .dat files (One File Per Signal Type format)
|
|
104
|
+
result = load_per_signal_files(root_dir, header)
|
|
105
|
+
|
|
106
|
+
# Add header keys to the result
|
|
107
|
+
for key in header.keys():
|
|
108
|
+
if key not in result:
|
|
109
|
+
result[key] = header[key]
|
|
110
|
+
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
def load_per_signal_files(folder_path, header):
|
|
114
|
+
|
|
115
|
+
result = {}
|
|
116
|
+
|
|
117
|
+
file_tasks = [
|
|
118
|
+
('t_amplifier', "time.dat", read_time_file, None),
|
|
119
|
+
('amplifier_data', "amplifier.dat", read_amplifier_file, len(header['amplifier_channels'])),
|
|
120
|
+
('aux_input_data', "auxiliary.dat", read_auxiliary_file, len(header['aux_input_channels'])),
|
|
121
|
+
]
|
|
122
|
+
if 'board_acd_channels' in header:
|
|
123
|
+
file_tasks.append(('board_adc_data', "board_adc.dat", read_adc_file,
|
|
124
|
+
len(header['board_adc_channels']))) if 'board_adc_channels' in header else None
|
|
125
|
+
|
|
126
|
+
num_files = len(file_tasks)
|
|
127
|
+
print("Reading .dat files...")
|
|
128
|
+
print_step = 10
|
|
129
|
+
percent_done = print_step
|
|
130
|
+
|
|
131
|
+
# Loop through each task
|
|
132
|
+
for i, (key, filename, read_function, channels) in enumerate(file_tasks):
|
|
133
|
+
filepath = os.path.join(folder_path, filename)
|
|
134
|
+
if channels is not None:
|
|
135
|
+
result[key] = read_function(filepath, channels)
|
|
136
|
+
else:
|
|
137
|
+
result[key] = read_function(filepath)
|
|
138
|
+
|
|
139
|
+
# Progress print
|
|
140
|
+
percent_done = print_progress(i+1, num_files, print_step, percent_done)
|
|
141
|
+
|
|
142
|
+
# Add time vectors
|
|
143
|
+
result['amplifier_channels'] = header['amplifier_channels']
|
|
144
|
+
result['t_aux_input'] = result['t_amplifier'][::4]
|
|
145
|
+
result['t_board_adc'] = result['t_amplifier']
|
|
146
|
+
|
|
147
|
+
# Frequency parameters
|
|
148
|
+
result['frequency_parameters'] = header['frequency_parameters']
|
|
149
|
+
|
|
150
|
+
return result
|
|
151
|
+
|
|
152
|
+
def load_files_from_path(folder_path=None, concatenate=False):
|
|
153
|
+
""" Loads all .rhd files from a specified path or using a file dialog. Concatenates teh data if specified.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
folder_path: The path to the folder containing the .rhd files.
|
|
157
|
+
concatenate: Boolean indicating if the data from all files should be concatenated.
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
all_results: A list of 'result' dictionaries if concatenate is False, otherwise a single 'result' dictionary.
|
|
161
|
+
success: Boolean indicating if the files were loaded successfully.
|
|
162
|
+
"""
|
|
163
|
+
if folder_path is None:
|
|
164
|
+
root = tk.Tk()
|
|
165
|
+
root.withdraw() # Hide the main window
|
|
166
|
+
folder_path = filedialog.askdirectory()
|
|
167
|
+
if not folder_path:
|
|
168
|
+
print("No file selected, returning.")
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
# Get the absolute paths of all files locates in the directory
|
|
172
|
+
file_list = get_rhd_file_paths(folder_path)
|
|
173
|
+
all_results = None
|
|
174
|
+
for file in file_list:
|
|
175
|
+
result = load_rhd_file(file, verbose=False)
|
|
176
|
+
if not result:
|
|
177
|
+
continue
|
|
178
|
+
|
|
179
|
+
if concatenate:
|
|
180
|
+
if all_results is None:
|
|
181
|
+
all_results = result
|
|
182
|
+
else:
|
|
183
|
+
# Assuming all_results has the same fields, update the specific ones
|
|
184
|
+
keys = ['t_aux_input', 'aux_input_data', 't_amplifier', 'amplifier_data', 't_board_adc','board_adc_data', ]
|
|
185
|
+
for key in keys:
|
|
186
|
+
original_data = all_results[key]
|
|
187
|
+
new_data = result[key]
|
|
188
|
+
# If there is more than oen column, concatenate along axis=1, otherwise axis=0
|
|
189
|
+
if len(original_data.shape) > 1:
|
|
190
|
+
all_results[key] = np.concatenate((original_data, new_data), axis=1)
|
|
191
|
+
else:
|
|
192
|
+
all_results[key] = np.concatenate((original_data, new_data), axis=0)
|
|
193
|
+
else:
|
|
194
|
+
if all_results is None:
|
|
195
|
+
all_results = [result]
|
|
196
|
+
else:
|
|
197
|
+
all_results.append(result)
|
|
198
|
+
|
|
199
|
+
return all_results
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
""" Plotting functions for visualizing EMG data and features.
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
#import pywt
|
|
6
|
+
#import numpy as np
|
|
7
|
+
#import seaborn as sns
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
from intan.io._exceptions import ChannelNotFoundError
|
|
10
|
+
from intan.io._channel_utils import find_channel_in_header
|
|
11
|
+
#from matplotlib.collections import LineCollection
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def plot_channel_by_name(channel_name, result):
|
|
16
|
+
"""Plots all data associated with channel specified as 'channel_name' in
|
|
17
|
+
'result' dict.
|
|
18
|
+
"""
|
|
19
|
+
# Find channel that corresponds to this name
|
|
20
|
+
channel_found, signal_type, signal_index = find_channel_in_header(
|
|
21
|
+
channel_name, result)
|
|
22
|
+
|
|
23
|
+
# Plot this channel
|
|
24
|
+
if channel_found:
|
|
25
|
+
_, ax = plt.subplots()
|
|
26
|
+
# fig, ax = plt.subplots()
|
|
27
|
+
ax.set_title(channel_name)
|
|
28
|
+
ax.set_xlabel('Time (s)')
|
|
29
|
+
|
|
30
|
+
if signal_type == 'amplifier_channels':
|
|
31
|
+
ylabel = 'Voltage (microVolts)'
|
|
32
|
+
signal_data_name = 'amplifier_data'
|
|
33
|
+
t_vector = result['t_amplifier']
|
|
34
|
+
|
|
35
|
+
elif signal_type == 'aux_input_channels':
|
|
36
|
+
ylabel = 'Voltage (Volts)'
|
|
37
|
+
signal_data_name = 'aux_input_data'
|
|
38
|
+
t_vector = result['t_aux_input']
|
|
39
|
+
|
|
40
|
+
elif signal_type == 'supply_voltage_channels':
|
|
41
|
+
ylabel = 'Voltage (Volts)'
|
|
42
|
+
signal_data_name = 'supply_voltage_data'
|
|
43
|
+
t_vector = result['t_supply_voltage']
|
|
44
|
+
|
|
45
|
+
elif signal_type == 'board_adc_channels':
|
|
46
|
+
ylabel = 'Voltage (Volts)'
|
|
47
|
+
signal_data_name = 'board_adc_data'
|
|
48
|
+
t_vector = result['t_board_adc']
|
|
49
|
+
|
|
50
|
+
elif signal_type == 'board_dig_in_channels':
|
|
51
|
+
ylabel = 'Digital In Events (High or Low)'
|
|
52
|
+
signal_data_name = 'board_dig_in_data'
|
|
53
|
+
t_vector = result['t_dig']
|
|
54
|
+
|
|
55
|
+
elif signal_type == 'board_dig_out_channels':
|
|
56
|
+
ylabel = 'Digital Out Events (High or Low)'
|
|
57
|
+
signal_data_name = 'board_dig_out_data'
|
|
58
|
+
t_vector = result['t_dig']
|
|
59
|
+
|
|
60
|
+
else:
|
|
61
|
+
raise ChannelNotFoundError(
|
|
62
|
+
'Plotting failed; signal type ', signal_type, ' not found')
|
|
63
|
+
|
|
64
|
+
ax.set_ylabel(ylabel)
|
|
65
|
+
ax.plot(t_vector, result[signal_data_name][signal_index, :])
|
|
66
|
+
ax.margins(x=0, y=0)
|
|
67
|
+
|
|
68
|
+
print("Plotting channel: ", channel_name)
|
|
69
|
+
plt.show()
|
|
70
|
+
|
|
71
|
+
else:
|
|
72
|
+
raise ChannelNotFoundError(
|
|
73
|
+
'Plotting failed; channel ', channel_name, ' not found')
|
|
74
|
+
|
|
75
|
+
def plot_channel_by_index(channel_index, result):
|
|
76
|
+
"""Plots all data associated with channel specified as 'channel_index' in
|
|
77
|
+
'result' dict.
|
|
78
|
+
"""
|
|
79
|
+
N_channels = len(result['amplifier_channels'])
|
|
80
|
+
if channel_index >= N_channels:
|
|
81
|
+
raise ChannelNotFoundError(
|
|
82
|
+
'Plotting failed; channel index ', channel_index, ' not found')
|
|
83
|
+
else:
|
|
84
|
+
_, ax = plt.subplots()
|
|
85
|
+
ax.set_title(result['amplifier_channels'][channel_index]['custom_channel_name'])
|
|
86
|
+
ax.set_xlabel('Time (s)')
|
|
87
|
+
ax.set_ylabel('Voltage (microVolts)')
|
|
88
|
+
ax.plot(result['t_amplifier'], result['amplifier_data'][channel_index, :])
|
|
89
|
+
ax.margins(x=0, y=0)
|
|
90
|
+
|
|
91
|
+
print("Plotting channel: ", result['amplifier_channels'][channel_index]['custom_channel_name'])
|
|
92
|
+
plt.show()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# def plot_time_domain_features(emg_signal, sample_rate=4000, window_size=400, overlap=200):
|
|
96
|
+
# """
|
|
97
|
+
# Plots time-domain features of EMG signals over time.
|
|
98
|
+
#
|
|
99
|
+
# Args:
|
|
100
|
+
# emg_signal: Raw EMG signal (1D array).
|
|
101
|
+
# sample_rate: Sampling rate of the EMG signal (default: 4000 Hz).
|
|
102
|
+
# window_size: Number of samples per window (default: 400).
|
|
103
|
+
# overlap: Number of overlapping samples (default: 200).
|
|
104
|
+
# """
|
|
105
|
+
# # Preprocess EMG signal (windowing)
|
|
106
|
+
# windows = rhd_utils.window_data(emg_signal, window_size=window_size, overlap=overlap)
|
|
107
|
+
#
|
|
108
|
+
# # Extract time-domain features for each window
|
|
109
|
+
# time_features = np.array([rhd_utils.extract_time_domain_features(window) for window in windows])
|
|
110
|
+
#
|
|
111
|
+
# # Plot each time-domain feature
|
|
112
|
+
# time_axis = np.arange(0, len(windows) * (window_size - overlap), window_size - overlap) / sample_rate
|
|
113
|
+
#
|
|
114
|
+
# fig, ax = plt.subplots(6, 1, figsize=(10, 12))
|
|
115
|
+
# feature_names = ['IEMG', 'MAV', 'SSI', 'RMS', 'VAR', 'MYOP']
|
|
116
|
+
#
|
|
117
|
+
# for i in range(6):
|
|
118
|
+
# ax[i].plot(time_axis, time_features[:, i])
|
|
119
|
+
# ax[i].set_title(feature_names[i])
|
|
120
|
+
# ax[i].set_xlabel('Time (s)')
|
|
121
|
+
# ax[i].set_ylabel('Amplitude')
|
|
122
|
+
#
|
|
123
|
+
# plt.tight_layout()
|
|
124
|
+
# plt.show()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# def plot_wavelet_features(emg_signal, wavelet='db1', sample_rate=4000, window_size=400, overlap=200):
|
|
128
|
+
# """
|
|
129
|
+
# Plots wavelet features of EMG signals.
|
|
130
|
+
#
|
|
131
|
+
# Args:
|
|
132
|
+
# emg_signal: Raw EMG signal (1D array).
|
|
133
|
+
# wavelet: Type of wavelet to use for wavelet transform.
|
|
134
|
+
# sample_rate: Sampling rate of the EMG signal (default: 4000 Hz).
|
|
135
|
+
# window_size: Number of samples per window (default: 400).
|
|
136
|
+
# overlap: Number of overlapping samples (default: 200).
|
|
137
|
+
#
|
|
138
|
+
# Example usage with a sample EMG signal:
|
|
139
|
+
# plot_wavelet_features(emg_signal)
|
|
140
|
+
#
|
|
141
|
+
# """
|
|
142
|
+
# # Preprocess EMG signal (windowing)
|
|
143
|
+
# windows = rhd_utils.window_data(emg_signal, window_size=window_size, overlap=overlap)
|
|
144
|
+
#
|
|
145
|
+
# # Plot the wavelet decomposition coefficients for the first window as an example
|
|
146
|
+
# example_window = windows[0]
|
|
147
|
+
# coeffs = pywt.wavedec(example_window, wavelet, level=2)
|
|
148
|
+
#
|
|
149
|
+
# fig, ax = plt.subplots(len(coeffs), 1, figsize=(10, 8))
|
|
150
|
+
#
|
|
151
|
+
# for i, coeff in enumerate(coeffs):
|
|
152
|
+
# ax[i].plot(coeff)
|
|
153
|
+
# ax[i].set_title(f'Wavelet Coefficients Level {i + 1}')
|
|
154
|
+
#
|
|
155
|
+
# plt.tight_layout()
|
|
156
|
+
# plt.show()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# def plot_feature_correlation(emg_signal, sample_rate=4000, window_size=400, overlap=200):
|
|
160
|
+
# """
|
|
161
|
+
# Plots a heatmap showing the correlation between different EMG features.
|
|
162
|
+
#
|
|
163
|
+
# Args:
|
|
164
|
+
# emg_signal: Raw EMG signal (1D array).
|
|
165
|
+
# sample_rate: Sampling rate of the EMG signal (default: 4000 Hz).
|
|
166
|
+
# window_size: Number of samples per window (default: 400).
|
|
167
|
+
# overlap: Number of overlapping samples (default: 200).
|
|
168
|
+
#
|
|
169
|
+
# Example usage with a sample EMG signal:
|
|
170
|
+
# plot_feature_correlation(emg_signal)
|
|
171
|
+
#
|
|
172
|
+
# """
|
|
173
|
+
# # Preprocess EMG signal (windowing)
|
|
174
|
+
# windows = rhd_utils.window_data(emg_signal, window_size=window_size, overlap=overlap)
|
|
175
|
+
#
|
|
176
|
+
# # Extract features for each window
|
|
177
|
+
# feature_matrix = np.array([rhd_utils.extract_features_from_window(window) for window in windows])
|
|
178
|
+
#
|
|
179
|
+
# # Compute the correlation matrix
|
|
180
|
+
# correlation_matrix = np.corrcoef(feature_matrix.T)
|
|
181
|
+
#
|
|
182
|
+
# # Plot heatmap
|
|
183
|
+
# plt.figure(figsize=(10, 8))
|
|
184
|
+
# sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f')
|
|
185
|
+
# plt.title('Feature Correlation Heatmap')
|
|
186
|
+
# plt.show()
|
|
187
|
+
|
|
188
|
+
def plot_figure(y, x, title='Example Plot', x_label='time (s)', y_label='Y-axis', legend=True, fig_size=(10, 6)):
|
|
189
|
+
"""
|
|
190
|
+
"""
|
|
191
|
+
# Create a figure and axis
|
|
192
|
+
fig, ax = plt.subplots(figsize=fig_size)
|
|
193
|
+
|
|
194
|
+
# Plot the data
|
|
195
|
+
ax.plot(x, y, label='Data')
|
|
196
|
+
|
|
197
|
+
# Add a title and labels
|
|
198
|
+
ax.set_title(title)
|
|
199
|
+
ax.set_xlabel(x_label)
|
|
200
|
+
ax.set_ylabel(y_label)
|
|
201
|
+
|
|
202
|
+
# Add a legend
|
|
203
|
+
if legend:
|
|
204
|
+
ax.legend()
|
|
205
|
+
|
|
206
|
+
# Show the plot
|
|
207
|
+
plt.show()
|
|
208
|
+
|
|
209
|
+
def _add_scalebars(ax, scale_time=0.1, scale_amp=10):
|
|
210
|
+
ax.annotate('', xy=(0, scale_amp), xytext=(0, 0),
|
|
211
|
+
arrowprops=dict(arrowstyle='-', lw=2))
|
|
212
|
+
ax.annotate('', xy=(scale_time, 0), xytext=(0, 0),
|
|
213
|
+
arrowprops=dict(arrowstyle='-', lw=2))
|
|
214
|
+
|
|
215
|
+
def _insert_channel_labels(ax, channel_labels, y_offsets):
|
|
216
|
+
for label, y in zip(channel_labels, y_offsets):
|
|
217
|
+
ax.text(-0.05, y, label, va='center', ha='right')
|
|
218
|
+
|
|
219
|
+
def _insert_vertical_labels(ax, labels, x_positions):
|
|
220
|
+
for label, x in zip(labels, x_positions):
|
|
221
|
+
ax.axvline(x, color='gray', linestyle='--')
|
|
222
|
+
ax.text(x, ax.get_ylim()[1], label, rotation=90, va='bottom', ha='center')
|
|
223
|
+
|
|
224
|
+
def plot_figure(y, x, title='Example Plot', x_label='time (s)', y_label='Y-axis', legend=True, fig_size=(10, 6)):
|
|
225
|
+
"""
|
|
226
|
+
"""
|
|
227
|
+
# Create a figure and axis
|
|
228
|
+
fig, ax = plt.subplots(figsize=fig_size)
|
|
229
|
+
|
|
230
|
+
# Plot the data
|
|
231
|
+
ax.plot(x, y, label='Data')
|
|
232
|
+
|
|
233
|
+
# Add a title and labels
|
|
234
|
+
ax.set_title(title)
|
|
235
|
+
ax.set_xlabel(x_label)
|
|
236
|
+
ax.set_ylabel(y_label)
|
|
237
|
+
|
|
238
|
+
# Add a legend
|
|
239
|
+
if legend:
|
|
240
|
+
ax.legend()
|
|
241
|
+
|
|
242
|
+
# Show the plot
|
|
243
|
+
plt.show()
|
|
244
|
+
|
|
245
|
+
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
def waterfall(data, channel_indices, time_vector, edges=[], plot_title="", line_width=0.2, colormap='rainbow', downsampling_factor=1, verbose=False):
|
|
5
|
+
"""
|
|
6
|
+
Creates a waterfall plot for the specified channels with a user-defined title,
|
|
7
|
+
custom color styling, and scale bars for time and voltage.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
data: The numpy array containing the EMG data.
|
|
11
|
+
channel_indices: The indices of the channels to be plotted.
|
|
12
|
+
time_vector: The time vector for the x-axis
|
|
13
|
+
plot_title: (Optional) Title for the plot provided by the user.
|
|
14
|
+
"""
|
|
15
|
+
fig, ax = plt.subplots(figsize=(10, 12))
|
|
16
|
+
|
|
17
|
+
offset = 0 # Start with no offset
|
|
18
|
+
offset_increment = 200 # Increment for each row (adjust this based on data scale)
|
|
19
|
+
cmap = plt.get_cmap(colormap) # You can also experiment with other color maps like 'jet', 'viridis', etc.
|
|
20
|
+
num_channels = len(channel_indices)
|
|
21
|
+
|
|
22
|
+
# Downsample the data by the specified factor
|
|
23
|
+
data = data[:, ::downsampling_factor]
|
|
24
|
+
time_vector = time_vector[::downsampling_factor]
|
|
25
|
+
|
|
26
|
+
for i, channel_idx in enumerate(channel_indices):
|
|
27
|
+
channel_data = data[channel_idx, :]
|
|
28
|
+
# Use colormap to assign a color based on channel index
|
|
29
|
+
color = cmap(i / num_channels)
|
|
30
|
+
ax.plot(time_vector, channel_data + offset, color=color, linewidth=line_width)
|
|
31
|
+
offset += offset_increment
|
|
32
|
+
|
|
33
|
+
# If edges are provided, plot them as vertical lines
|
|
34
|
+
for edge in edges:
|
|
35
|
+
ax.axvline(x=edge, color='red', linestyle='--', linewidth=1)
|
|
36
|
+
|
|
37
|
+
# Labeling and visualization
|
|
38
|
+
#ax.set_xlabel('Time (s)')
|
|
39
|
+
#ax.set_ylabel('Amplitude + Offset')
|
|
40
|
+
ax.set_title(plot_title, fontsize=14, fontweight='bold')
|
|
41
|
+
|
|
42
|
+
# Custom scale bar
|
|
43
|
+
add_scalebars(ax)
|
|
44
|
+
|
|
45
|
+
# Turn off x and y axis numbers
|
|
46
|
+
ax.set_xticks([])
|
|
47
|
+
ax.set_yticks([])
|
|
48
|
+
|
|
49
|
+
# Remove the black box around the plot
|
|
50
|
+
for spine in ax.spines.values():
|
|
51
|
+
spine.set_visible(False)
|
|
52
|
+
|
|
53
|
+
# Insert text labels for channel 0 and channel 128
|
|
54
|
+
insert_channel_labels(ax, time_vector, num_channels)
|
|
55
|
+
|
|
56
|
+
# Insert vertical labels for "Extensor" and "Flexor"
|
|
57
|
+
insert_vertical_labels(ax)
|
|
58
|
+
|
|
59
|
+
plt.show()
|
|
60
|
+
|
|
61
|
+
def add_scalebars(ax, scale_time=5, scale_voltage=10):
|
|
62
|
+
"""
|
|
63
|
+
Adds time and voltage scale bars to the plot in the lower left corner.
|
|
64
|
+
"""
|
|
65
|
+
# Add horizontal time scale bar (5 sec)
|
|
66
|
+
ax.plot([0, scale_time], [-1000, -1000], color='gray', lw=3)
|
|
67
|
+
ax.text(scale_time / 2, -1500, '5 sec', va='center', ha='center', fontsize=12, color='gray')
|
|
68
|
+
|
|
69
|
+
# Add vertical voltage scale bar (10 mV)
|
|
70
|
+
ax.plot([0, 0], [-1000, -1000 + scale_voltage * 10], color='gray', lw=3)
|
|
71
|
+
ax.text(-0.5, -500, '10 mV', va='center', ha='center', rotation='vertical', fontsize=12, color='gray')
|
|
72
|
+
#ax.text(-0.5, voltage_scale_length / 2 - 1000, '10 mV', va='center', ha='center', rotation='vertical', fontsize=12, color='gray')
|
|
73
|
+
|
|
74
|
+
# def insert_channel_labels(ax, time_vector, num_channels):
|
|
75
|
+
# """
|
|
76
|
+
# Inserts text labels to indicate specific channels on the plot.
|
|
77
|
+
#
|
|
78
|
+
# Args:
|
|
79
|
+
# ax: The plot axes to add the text to.
|
|
80
|
+
# time_vector: The time vector for placing the text appropriately.
|
|
81
|
+
# num_channels: Total number of channels being plotted.
|
|
82
|
+
# """
|
|
83
|
+
# # Position the text for Channel 0 (near the bottom)
|
|
84
|
+
# x_pos = time_vector[-1] # Position at the end of the time range
|
|
85
|
+
# ax.text(x_pos + 1, 200, 'Channel 0', fontsize=8, va='center', ha='left', color='black', fontweight='bold')
|
|
86
|
+
#
|
|
87
|
+
# # Position the text for Channel 128 (near the top)
|
|
88
|
+
# ax.text(x_pos + 1, 25500, 'Channel 128', fontsize=8, va='center', ha='left', color='black', fontweight='bold')
|
|
89
|
+
|
|
90
|
+
def insert_channel_labels(ax, time_vector, num_channels, num_labels=2, label_color='black', font_size=8):
|
|
91
|
+
"""
|
|
92
|
+
Inserts evenly spaced text labels on a multi-channel plot to indicate selected channels.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
ax: Matplotlib Axes object.
|
|
96
|
+
time_vector: Time vector (used for x position of labels).
|
|
97
|
+
num_channels: Total number of channels plotted vertically.
|
|
98
|
+
num_labels: Number of labels to insert (default is 2).
|
|
99
|
+
label_color: Text color.
|
|
100
|
+
font_size: Size of the text.
|
|
101
|
+
"""
|
|
102
|
+
if num_labels > num_channels:
|
|
103
|
+
raise ValueError("Number of labels cannot exceed total number of channels.")
|
|
104
|
+
|
|
105
|
+
x_pos = time_vector[-1] + 1 # Place labels slightly past the right edge
|
|
106
|
+
|
|
107
|
+
# Evenly space label positions from bottom to top
|
|
108
|
+
channel_indices = np.linspace(0, num_channels - 1, num_labels, dtype=int)
|
|
109
|
+
y_offsets = np.linspace(200, 25500, num_channels) # Example scaling (adjust if needed)
|
|
110
|
+
|
|
111
|
+
for ch in channel_indices:
|
|
112
|
+
y = y_offsets[ch]
|
|
113
|
+
ax.text(x_pos, y, f"Channel {ch}", fontsize=font_size, va='center',
|
|
114
|
+
ha='left', color=label_color, fontweight='bold')
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def insert_vertical_labels(ax):
|
|
118
|
+
"""
|
|
119
|
+
Inserts vertical labels "Extensor" and "Flexor" for the two groups of channels.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
ax: The plot axes to add the text to.
|
|
123
|
+
"""
|
|
124
|
+
# Insert "Extensor" label vertically for the first 64 channels (left side)
|
|
125
|
+
ax.text(-1, 5000, 'Extensor', fontsize=12, va='center', ha='center', color='black', rotation='vertical',
|
|
126
|
+
fontweight='bold')
|
|
127
|
+
|
|
128
|
+
# Insert "Flexor" label vertically for channels 65-128 (left side)
|
|
129
|
+
ax.text(-1, 22000, 'Flexor', fontsize=12, va='center', ha='center', color='black', rotation='vertical',
|
|
130
|
+
fontweight='bold')
|
|
131
|
+
|
|
132
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from ._metrics_utils import read_config_file, get_file_paths, load_metrics_data
|
|
2
|
+
from ._filters import (
|
|
3
|
+
notch_filter,
|
|
4
|
+
butter_bandpass,
|
|
5
|
+
butter_lowpass,
|
|
6
|
+
butter_lowpass_filter,
|
|
7
|
+
butter_bandpass_filter,
|
|
8
|
+
filter_emg,
|
|
9
|
+
rectify,
|
|
10
|
+
window_rms,
|
|
11
|
+
window_rms_1D,
|
|
12
|
+
compute_rms,
|
|
13
|
+
downsample,
|
|
14
|
+
common_average_reference,
|
|
15
|
+
compute_grid_average,
|
|
16
|
+
z_score_norm,
|
|
17
|
+
apply_pca,
|
|
18
|
+
orthogonalize,
|
|
19
|
+
normalize
|
|
20
|
+
)
|