emg-tools 2.0.0__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.
- emg_tools/__init__.py +1 -0
- emg_tools/feats.py +68 -0
- emg_tools/freq.py +71 -0
- emg_tools/plots.py +362 -0
- emg_tools/prepro.py +153 -0
- emg_tools/tools.py +159 -0
- emg_tools-2.0.0.dist-info/METADATA +131 -0
- emg_tools-2.0.0.dist-info/RECORD +11 -0
- emg_tools-2.0.0.dist-info/WHEEL +5 -0
- emg_tools-2.0.0.dist-info/licenses/LICENSE +21 -0
- emg_tools-2.0.0.dist-info/top_level.txt +1 -0
emg_tools/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.0.0"
|
emg_tools/feats.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Amplitude features of EMG signals."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional, Tuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.interpolate import Akima1DInterpolator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def compute_rms(
|
|
10
|
+
data: np.ndarray,
|
|
11
|
+
timestamps: np.ndarray,
|
|
12
|
+
win_len_s: Optional[float] = 0.1,
|
|
13
|
+
win_step_s: Optional[float] = 0.1,
|
|
14
|
+
fs: Optional[int] = 2048
|
|
15
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
16
|
+
|
|
17
|
+
"""Compute the moving-window Root Mean Square (RMS) of the data.
|
|
18
|
+
|
|
19
|
+
The RMS is computed per window and interpolated (Akima) back to the input
|
|
20
|
+
timestamps. Before the first and after the last window centre the edge values
|
|
21
|
+
are held.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
25
|
+
timestamps (np.ndarray): Time of each sample in seconds, with shape (samples,).
|
|
26
|
+
win_len_s (float, optional): Window length in seconds. Default is 0.1.
|
|
27
|
+
win_step_s (float, optional): Window step in seconds. Default is 0.1.
|
|
28
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
rms (np.ndarray): RMS interpolated to the input timestamps, with shape
|
|
32
|
+
(samples, chs).
|
|
33
|
+
timestamps_win (np.ndarray): Time of each window centre in seconds, with
|
|
34
|
+
shape (windows,).
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
# Initialise variables
|
|
38
|
+
samples, chs = data.shape
|
|
39
|
+
win_len = min(np.round( win_len_s * fs ).astype(int), samples)
|
|
40
|
+
win_step = np.round( win_step_s * fs ).astype(int)
|
|
41
|
+
|
|
42
|
+
win_num = np.round( (samples - win_len)/win_step ).astype(int) + 1
|
|
43
|
+
|
|
44
|
+
timestamps_aux = np.zeros(win_num)
|
|
45
|
+
rms_aux = np.zeros((win_num, chs))
|
|
46
|
+
|
|
47
|
+
# Compute RMS
|
|
48
|
+
for win in range(win_num):
|
|
49
|
+
mask = np.arange(
|
|
50
|
+
0 + win_step * win,
|
|
51
|
+
np.amin([win_len + win_step * win, samples])
|
|
52
|
+
).astype(int)
|
|
53
|
+
rms_aux[win] = np.sqrt(np.mean(data[mask]**2, axis=0))
|
|
54
|
+
timestamps_aux[win] = np.mean(timestamps[mask])
|
|
55
|
+
|
|
56
|
+
# Single window, no interpolation possible
|
|
57
|
+
if win_num < 2:
|
|
58
|
+
rms = np.tile(rms_aux, (samples, 1))
|
|
59
|
+
return rms, timestamps_aux
|
|
60
|
+
|
|
61
|
+
# Interpolate RMS to match data signals, holding the edge values before
|
|
62
|
+
# the first and after the last window centre
|
|
63
|
+
timestamps_interp = np.clip(timestamps, timestamps_aux[0], timestamps_aux[-1])
|
|
64
|
+
rms = np.zeros_like(data, dtype=float)
|
|
65
|
+
for ch in range(chs):
|
|
66
|
+
rms[:, ch] = Akima1DInterpolator(timestamps_aux, rms_aux[:, ch])(timestamps_interp)
|
|
67
|
+
|
|
68
|
+
return rms, timestamps_aux
|
emg_tools/freq.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Frequency-domain analysis of EMG signals."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional, Tuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy import fft, signal
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_spectrum(
|
|
10
|
+
data: np.ndarray,
|
|
11
|
+
fs: Optional[int] = 2048,
|
|
12
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
13
|
+
|
|
14
|
+
"""Compute the single-sided amplitude spectrum of the input data.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
data (np.ndarray): Input data with shape (samples, channels).
|
|
18
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
spectrum (np.ndarray): Amplitude spectrum of the input data with shape
|
|
22
|
+
(samples//2, channels), in the same units as the data, where the
|
|
23
|
+
first dimension corresponds to the positive frequencies.
|
|
24
|
+
xf (np.ndarray): Frequency axis in Hz, with shape (samples//2,).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# Initialise variables
|
|
28
|
+
samples, chs = data.shape
|
|
29
|
+
|
|
30
|
+
# Compute amplitude spectrum
|
|
31
|
+
yf = fft.fft(data, axis=0)
|
|
32
|
+
xf = fft.fftfreq(samples, 1/fs)[:samples//2]
|
|
33
|
+
spectrum = 2/samples * np.abs(yf[0:samples//2])
|
|
34
|
+
spectrum[0] /= 2 # DC component is not mirrored
|
|
35
|
+
|
|
36
|
+
return spectrum, xf
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_psd(
|
|
40
|
+
data: np.ndarray,
|
|
41
|
+
fs: Optional[int] = 2048,
|
|
42
|
+
*,
|
|
43
|
+
welch: Optional[bool] = False,
|
|
44
|
+
nperseg: Optional[int] = None,
|
|
45
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
46
|
+
|
|
47
|
+
"""Compute the one-sided Power Spectral Density (PSD) of the input data.
|
|
48
|
+
|
|
49
|
+
By default the periodogram is used. Welch's method can be requested instead.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
data (np.ndarray): Input data with shape (samples, channels).
|
|
53
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
54
|
+
welch (bool, optional): If True, the PSD is estimated with Welch's
|
|
55
|
+
method. Default is False (periodogram).
|
|
56
|
+
nperseg (int, optional): Length of each segment in samples, only used
|
|
57
|
+
if welch is True. Default is None, which uses scipy's default (256).
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
psd (np.ndarray): One-sided PSD of the input data with shape
|
|
61
|
+
(freqs, channels), in units of data^2/Hz.
|
|
62
|
+
xf (np.ndarray): Frequency axis in Hz, with shape (freqs,).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
# Compute PSD
|
|
66
|
+
if welch:
|
|
67
|
+
xf, psd = signal.welch(data, fs=fs, nperseg=nperseg, axis=0)
|
|
68
|
+
else:
|
|
69
|
+
xf, psd = signal.periodogram(data, fs=fs, axis=0)
|
|
70
|
+
|
|
71
|
+
return psd, xf
|
emg_tools/plots.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Plot EMG signals in time and frequency.
|
|
2
|
+
|
|
3
|
+
PSD axes are labelled in mV^2/Hz, which assumes the data is in mV.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from copy import copy
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
import matplotlib.colors as colors
|
|
10
|
+
import matplotlib.pyplot as plt
|
|
11
|
+
import numpy as np
|
|
12
|
+
import seaborn as sns
|
|
13
|
+
from matplotlib.patches import Rectangle
|
|
14
|
+
from scipy import signal
|
|
15
|
+
|
|
16
|
+
from emg_tools.freq import get_psd
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _min_positive(x: np.ndarray) -> float:
|
|
20
|
+
"""Smallest strictly positive value of x, used as default log-scale vmin"""
|
|
21
|
+
positive = x[x > 0]
|
|
22
|
+
return positive.min() if positive.size else np.finfo(float).tiny
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def plot_ch(
|
|
26
|
+
data: np.ndarray,
|
|
27
|
+
timestamps: np.ndarray,
|
|
28
|
+
delta: Optional[int] = 5,
|
|
29
|
+
ax: Optional[plt.Axes] = None,
|
|
30
|
+
palette_name: Optional[str] = "viridis",
|
|
31
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
32
|
+
)-> plt.Axes:
|
|
33
|
+
|
|
34
|
+
"""Plot all channels stacked vertically in a single axes.
|
|
35
|
+
|
|
36
|
+
Each channel is shifted up by `max(data) / delta` times its index. Every fifth
|
|
37
|
+
channel is labelled on the y axis.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
data (np.ndarray): Float data with shape (samples, chs).
|
|
41
|
+
timestamps (np.ndarray): Time of each sample in seconds, with shape (samples,).
|
|
42
|
+
delta (int, optional): Divisor of the data maximum that sets the spacing
|
|
43
|
+
between channels. Larger values bring channels closer. Default is 5.
|
|
44
|
+
ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
|
|
45
|
+
new figure.
|
|
46
|
+
palette_name (str, optional): Name of the seaborn palette used to colour
|
|
47
|
+
the channels. Default is "viridis".
|
|
48
|
+
**kwarg: Additional keyword arguments passed to `matplotlib.axes.Axes.plot`.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
plt.Axes: Axes where the data is plotted.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
# Data size
|
|
55
|
+
chs = data.shape[1]
|
|
56
|
+
|
|
57
|
+
# Compute channel offset
|
|
58
|
+
max_val = np.nanmax(data)
|
|
59
|
+
offset = max_val/delta
|
|
60
|
+
|
|
61
|
+
# Apply offset to signals
|
|
62
|
+
data_plot = copy(data)
|
|
63
|
+
data_plot += range(0,chs) * offset
|
|
64
|
+
|
|
65
|
+
# Plot signals
|
|
66
|
+
if ax is None:
|
|
67
|
+
_, ax = plt.subplots()
|
|
68
|
+
|
|
69
|
+
# Create color palette and assign it to the axis cycle
|
|
70
|
+
color_palette = sns.color_palette(palette_name, chs).as_hex()
|
|
71
|
+
ax.set_prop_cycle(color=color_palette)
|
|
72
|
+
|
|
73
|
+
ax.plot(timestamps, data_plot, **kwarg)
|
|
74
|
+
ax.margins(0) # padding for each limit of the axis
|
|
75
|
+
ax.set_xlabel('Time (s)')
|
|
76
|
+
ax.set_ylabel('Channels')
|
|
77
|
+
ax.grid(True, axis='x')
|
|
78
|
+
ch_ticks = np.linspace(0, (chs -1) * offset, chs)
|
|
79
|
+
sel_chs = np.arange(0, chs, 5)
|
|
80
|
+
ax.set_yticks(ch_ticks[sel_chs], sel_chs)
|
|
81
|
+
|
|
82
|
+
return ax
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def plot_ch_map(
|
|
86
|
+
values: np.ndarray,
|
|
87
|
+
ch_map: np.ndarray,
|
|
88
|
+
bad_ch: Optional[np.ndarray] = None,
|
|
89
|
+
ax: Optional[plt.Axes] = None,
|
|
90
|
+
palette_name: Optional[str] = "viridis",
|
|
91
|
+
cbar_label: Optional[str] = None,
|
|
92
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
93
|
+
) -> plt.Axes:
|
|
94
|
+
|
|
95
|
+
"""Plot one value per channel on the electrode grid, annotated with channel
|
|
96
|
+
numbers.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
values (np.ndarray): Value per channel with shape (channels,).
|
|
100
|
+
ch_map (np.ndarray): Channel map with shape (rows, cols). Empty cells
|
|
101
|
+
(-1) are left blank.
|
|
102
|
+
bad_ch (np.ndarray, optional): Channels outlined in red. Default is None.
|
|
103
|
+
ax (plt.Axes, optional): Axes to plot the map. Default is None.
|
|
104
|
+
palette_name (str, optional): Name of the colormap. Default is "viridis".
|
|
105
|
+
cbar_label (str, optional): Colorbar label. Default is None.
|
|
106
|
+
**kwarg: Additional keyword arguments to be passed to the `heatmap`
|
|
107
|
+
function of seaborn.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
plt.Axes: Axes where the map is plotted.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
if ax is None:
|
|
114
|
+
_, ax = plt.subplots()
|
|
115
|
+
|
|
116
|
+
# Arrange values on the grid, leaving empty cells blank
|
|
117
|
+
values_map = np.where(ch_map >= 0, values[ch_map], np.nan)
|
|
118
|
+
|
|
119
|
+
sns.heatmap(
|
|
120
|
+
values_map, annot=ch_map, fmt="d", annot_kws={"fontsize": 6},
|
|
121
|
+
cmap=palette_name, square=True, xticklabels=False, yticklabels=False,
|
|
122
|
+
cbar_kws={"label": cbar_label}, ax=ax, **kwarg
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Outline bad channels
|
|
126
|
+
if bad_ch is not None:
|
|
127
|
+
for row, col in np.argwhere(np.isin(ch_map, bad_ch)):
|
|
128
|
+
ax.add_patch(Rectangle((col, row), 1, 1, fill=False, edgecolor="red", lw=1.5))
|
|
129
|
+
|
|
130
|
+
return ax
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def plot_psd(
|
|
134
|
+
data: np.ndarray,
|
|
135
|
+
fs: Optional[int] = 2048,
|
|
136
|
+
ax: Optional[plt.Axes] = None,
|
|
137
|
+
palette_name: Optional[str] = "viridis",
|
|
138
|
+
log_scale: Optional[bool] = False,
|
|
139
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
140
|
+
) -> plt.Axes:
|
|
141
|
+
|
|
142
|
+
"""Plot the periodogram PSD of each channel as one line per channel.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
146
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
147
|
+
ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
|
|
148
|
+
new figure.
|
|
149
|
+
palette_name (str, optional): Name of the seaborn palette used to colour
|
|
150
|
+
the channels. Default is "viridis".
|
|
151
|
+
log_scale (bool, optional): If True, the PSD axis is logarithmic. Default
|
|
152
|
+
is False.
|
|
153
|
+
**kwarg: Additional keyword arguments passed to `matplotlib.axes.Axes.plot`.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
plt.Axes: Axes where the PSD is plotted.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
# Initialise variables
|
|
160
|
+
chs = data.shape[1]
|
|
161
|
+
|
|
162
|
+
# Define axis if None
|
|
163
|
+
if ax is None:
|
|
164
|
+
_, ax = plt.subplots(1, 1, figsize=(10,5), layout='tight')
|
|
165
|
+
|
|
166
|
+
# Create color palette and assign it to the axis cycle
|
|
167
|
+
color_palette = sns.color_palette(palette_name, chs).as_hex()
|
|
168
|
+
ax.set_prop_cycle(color=color_palette)
|
|
169
|
+
|
|
170
|
+
# Plot PSD
|
|
171
|
+
psd, xf = get_psd(data, fs)
|
|
172
|
+
|
|
173
|
+
if log_scale:
|
|
174
|
+
ax.semilogy(xf, psd, **kwarg)
|
|
175
|
+
ax.set_ylabel('PSD (mV^2/Hz)')
|
|
176
|
+
else:
|
|
177
|
+
ax.plot(xf, psd, **kwarg)
|
|
178
|
+
ax.set_ylabel('PSD (mV^2/Hz)')
|
|
179
|
+
ax.set_xlabel('Frequency (Hz)')
|
|
180
|
+
|
|
181
|
+
return ax
|
|
182
|
+
|
|
183
|
+
def plot_psd_map(
|
|
184
|
+
data: np.ndarray,
|
|
185
|
+
fs: Optional[int] = 2048,
|
|
186
|
+
ax: Optional[plt.Axes] = None,
|
|
187
|
+
log_scale: Optional[bool] = False,
|
|
188
|
+
eps: Optional[float] = None,
|
|
189
|
+
palette_name: Optional[str] = "viridis",
|
|
190
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
191
|
+
) -> plt.Axes:
|
|
192
|
+
|
|
193
|
+
"""Plot the periodogram PSD as a heatmap of frequency against channel.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
197
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
198
|
+
ax (plt.Axes, optional): Axes to plot on. Default is None, which creates a
|
|
199
|
+
new figure.
|
|
200
|
+
log_scale (bool, optional): If True, the colour scale is logarithmic. Default
|
|
201
|
+
is False.
|
|
202
|
+
eps (float, optional): Lower limit of the log colour scale, to avoid log(0).
|
|
203
|
+
Only used if log_scale is True. Default is None, which uses the smallest
|
|
204
|
+
positive PSD value.
|
|
205
|
+
palette_name (str, optional): Name of the matplotlib colormap. Default is
|
|
206
|
+
"viridis".
|
|
207
|
+
**kwarg: Additional keyword arguments passed to
|
|
208
|
+
`matplotlib.axes.Axes.pcolormesh`.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
plt.Axes: Axes where the PSD is plotted.
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
# Initialise variables
|
|
215
|
+
samples, chs = data.shape
|
|
216
|
+
|
|
217
|
+
# Plot PSD
|
|
218
|
+
psd, xf = get_psd(data, fs)
|
|
219
|
+
|
|
220
|
+
# Plot PSD
|
|
221
|
+
if ax is None:
|
|
222
|
+
_, ax = plt.subplots(1, 1, figsize=(10,5), layout='tight')
|
|
223
|
+
if log_scale:
|
|
224
|
+
if eps is None:
|
|
225
|
+
eps = _min_positive(psd)
|
|
226
|
+
norm=colors.LogNorm(vmin=eps, vmax=psd.max())
|
|
227
|
+
cbar_label = 'PSD (mV^2/Hz)'
|
|
228
|
+
else:
|
|
229
|
+
norm=None
|
|
230
|
+
cbar_label = 'PSD (mV^2/Hz)'
|
|
231
|
+
im = ax.pcolormesh(
|
|
232
|
+
np.arange(chs), xf, psd,
|
|
233
|
+
shading='gouraud', cmap=palette_name, norm=norm,
|
|
234
|
+
**kwarg
|
|
235
|
+
)
|
|
236
|
+
cbar = ax.figure.colorbar(im, ax=ax)
|
|
237
|
+
cbar.set_label(cbar_label, rotation=90)
|
|
238
|
+
ax.grid(False)
|
|
239
|
+
ax.set_ylabel('Frequency (Hz)')
|
|
240
|
+
ax.set_xlabel('Channels')
|
|
241
|
+
|
|
242
|
+
return ax
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def plot_comp_spectrogram(
|
|
246
|
+
data: np.ndarray,
|
|
247
|
+
fs: Optional[int] = 2048,
|
|
248
|
+
ax: Optional[Union[plt.Axes, np.ndarray]] = None,
|
|
249
|
+
log_scale: Optional[bool] = False,
|
|
250
|
+
eps: Optional[float] = None,
|
|
251
|
+
palette_name: Optional[str] = "viridis",
|
|
252
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
253
|
+
) -> np.ndarray:
|
|
254
|
+
|
|
255
|
+
"""Compute the spectrogram of each channel and plot it with `plot_spectrogram`.
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
data (np.ndarray): Input data with shape (samples, chs) or (samples,).
|
|
259
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
260
|
+
ax (plt.Axes or np.ndarray, optional): Axes to plot on, one per channel.
|
|
261
|
+
Default is None, which creates one row of axes per channel.
|
|
262
|
+
log_scale (bool, optional): If True, the colour scale is logarithmic. Default
|
|
263
|
+
is False.
|
|
264
|
+
eps (float, optional): Lower limit of the colour scale. Default is None, which
|
|
265
|
+
uses the smallest positive value in log scale and the minimum otherwise.
|
|
266
|
+
palette_name (str, optional): Name of the matplotlib colormap. Default is
|
|
267
|
+
"viridis".
|
|
268
|
+
**kwarg: Additional keyword arguments passed to
|
|
269
|
+
`matplotlib.axes.Axes.pcolormesh`.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
np.ndarray: Array of axes where the spectrogram of each channel is plotted.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
# Compute spectrogram (one sided) with shape (freqs, chs, times)
|
|
276
|
+
f, t, sxx = signal.spectrogram(data, fs, axis=0)
|
|
277
|
+
|
|
278
|
+
# Rearrange to (freqs, times, chs)
|
|
279
|
+
if sxx.ndim == 3:
|
|
280
|
+
sxx = np.moveaxis(sxx, 1, -1)
|
|
281
|
+
|
|
282
|
+
return plot_spectrogram(
|
|
283
|
+
f, t, sxx, ax=ax, palette_name=palette_name,
|
|
284
|
+
log_scale=log_scale, eps=eps, **kwarg
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def plot_spectrogram(
|
|
288
|
+
f: np.ndarray,
|
|
289
|
+
t: np.ndarray,
|
|
290
|
+
sxx: np.ndarray,
|
|
291
|
+
ax: Optional[Union[plt.Axes, np.ndarray]] = None,
|
|
292
|
+
palette_name: Optional[str] = "magma",
|
|
293
|
+
log_scale: Optional[bool] = False,
|
|
294
|
+
eps: Optional[float] = None,
|
|
295
|
+
**kwarg: Optional[Union[str, int, float]]
|
|
296
|
+
) -> np.ndarray:
|
|
297
|
+
|
|
298
|
+
"""Plot a precomputed spectrogram, one axes per signal.
|
|
299
|
+
|
|
300
|
+
All signals share the same colour scale.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
f (np.ndarray): Frequencies in Hz, with shape (freqs,).
|
|
304
|
+
t (np.ndarray): Times in seconds, with shape (times,).
|
|
305
|
+
sxx (np.ndarray): Spectrogram with shape (freqs, times, signals), or
|
|
306
|
+
(freqs, times) for a single signal.
|
|
307
|
+
ax (plt.Axes or np.ndarray, optional): Axes to plot on, one per signal.
|
|
308
|
+
Default is None, which creates one row of axes per signal.
|
|
309
|
+
palette_name (str, optional): Name of the matplotlib colormap. Default is
|
|
310
|
+
"magma".
|
|
311
|
+
log_scale (bool, optional): If True, the colour scale is logarithmic. Default
|
|
312
|
+
is False.
|
|
313
|
+
eps (float, optional): Lower limit of the colour scale. Default is None, which
|
|
314
|
+
uses the smallest positive value in log scale and the minimum otherwise.
|
|
315
|
+
**kwarg: Additional keyword arguments passed to
|
|
316
|
+
`matplotlib.axes.Axes.pcolormesh`.
|
|
317
|
+
|
|
318
|
+
Returns:
|
|
319
|
+
np.ndarray: Array of axes where the spectrogram of each signal is plotted.
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
# Normalise spectrogram if log scale
|
|
323
|
+
if log_scale:
|
|
324
|
+
if eps is None:
|
|
325
|
+
eps = _min_positive(sxx)
|
|
326
|
+
norm=colors.LogNorm(vmin=eps, vmax=sxx.max())
|
|
327
|
+
cbar_label = 'PSD (mV^2/Hz)'
|
|
328
|
+
else:
|
|
329
|
+
if eps is None:
|
|
330
|
+
eps = sxx.min()
|
|
331
|
+
norm=colors.Normalize(vmin=eps, vmax=sxx.max())
|
|
332
|
+
cbar_label = 'PSD (mV^2/Hz)'
|
|
333
|
+
|
|
334
|
+
# Plot spectrogram per signal
|
|
335
|
+
if len(sxx.shape) == 2:
|
|
336
|
+
sxx = np.expand_dims(sxx, axis=-1)
|
|
337
|
+
nsig = sxx.shape[-1]
|
|
338
|
+
|
|
339
|
+
if ax is None:
|
|
340
|
+
cols = 1
|
|
341
|
+
rows = np.round(nsig/cols).astype(int)
|
|
342
|
+
|
|
343
|
+
fig, ax = plt.subplots(
|
|
344
|
+
rows, cols, figsize=(12, 6),
|
|
345
|
+
sharex=True, sharey=True, layout='constrained', squeeze=False
|
|
346
|
+
)
|
|
347
|
+
ax = np.atleast_1d(ax).flatten()
|
|
348
|
+
|
|
349
|
+
for i in range(nsig):
|
|
350
|
+
# Plot spectrogram
|
|
351
|
+
im = ax[i].pcolormesh(
|
|
352
|
+
t, f, sxx[:,:,i],
|
|
353
|
+
shading='gouraud', cmap=palette_name, norm=norm,
|
|
354
|
+
**kwarg
|
|
355
|
+
)
|
|
356
|
+
cbar = ax[i].figure.colorbar(im, ax=ax[i])
|
|
357
|
+
cbar.set_label(cbar_label, rotation=90)
|
|
358
|
+
ax[i].set_ylabel('Frequency (Hz)')
|
|
359
|
+
ax[i].set_xlabel('Time (s)')
|
|
360
|
+
ax[i].set_title(f'Channel {i}')
|
|
361
|
+
|
|
362
|
+
return ax
|
emg_tools/prepro.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Butterworth filters for EMG preprocessing.
|
|
2
|
+
|
|
3
|
+
All filters work along `axis=0`, so data has shape (samples, chs) or (samples,).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from scipy import signal
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def bandpass_filter(
|
|
13
|
+
data: np.ndarray,
|
|
14
|
+
fs: Optional[int] = 2048,
|
|
15
|
+
cutoff: Optional[list] = None,
|
|
16
|
+
order: Optional[int] = 4,
|
|
17
|
+
filtfilt: Optional[bool] = True,
|
|
18
|
+
) -> np.ndarray:
|
|
19
|
+
|
|
20
|
+
"""Apply a Butterworth bandpass filter.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
24
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
25
|
+
cutoff (list, optional): Low and high cutoff frequencies in Hz.
|
|
26
|
+
Default is None, which uses [20, 500].
|
|
27
|
+
order (int, optional): Filter order. Default is 4.
|
|
28
|
+
filtfilt (bool, optional): If True, filter forward and backward (zero phase,
|
|
29
|
+
doubled effective order). If False, filter forward only. Default is True.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
np.ndarray: Filtered data, same shape as the input.
|
|
33
|
+
"""
|
|
34
|
+
# Define cutoff frequencies
|
|
35
|
+
if cutoff is None:
|
|
36
|
+
cutoff = [20, 500]
|
|
37
|
+
|
|
38
|
+
# Define filter
|
|
39
|
+
sos = signal.butter(order, cutoff, btype='band', fs=fs, output='sos')
|
|
40
|
+
|
|
41
|
+
# Apply filter
|
|
42
|
+
if filtfilt:
|
|
43
|
+
out = signal.sosfiltfilt(sos, data, axis=0)
|
|
44
|
+
else:
|
|
45
|
+
out = signal.sosfilt(sos, data, axis=0)
|
|
46
|
+
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def highpass_filter(
|
|
51
|
+
data: np.ndarray,
|
|
52
|
+
fs: Optional[int] = 2048,
|
|
53
|
+
cutoff: Optional[float] = 20,
|
|
54
|
+
order: Optional[int] = 2,
|
|
55
|
+
filtfilt: Optional[bool] = True,
|
|
56
|
+
) -> np.ndarray:
|
|
57
|
+
|
|
58
|
+
"""Apply a Butterworth highpass filter.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
62
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
63
|
+
cutoff (float, optional): Cutoff frequency in Hz. Default is 20.
|
|
64
|
+
order (int, optional): Filter order. Default is 2.
|
|
65
|
+
filtfilt (bool, optional): If True, filter forward and backward (zero phase,
|
|
66
|
+
doubled effective order). If False, filter forward only. Default is True.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
np.ndarray: Filtered data, same shape as the input.
|
|
70
|
+
"""
|
|
71
|
+
# Define filter
|
|
72
|
+
sos = signal.butter(order, cutoff, btype='high', fs=fs, output='sos')
|
|
73
|
+
|
|
74
|
+
# Apply filter
|
|
75
|
+
if filtfilt:
|
|
76
|
+
out = signal.sosfiltfilt(sos, data, axis=0)
|
|
77
|
+
else:
|
|
78
|
+
out = signal.sosfilt(sos, data, axis=0)
|
|
79
|
+
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def lowpass_filter(
|
|
84
|
+
data: np.ndarray,
|
|
85
|
+
fs: Optional[int] = 2048,
|
|
86
|
+
cutoff: Optional[float] = 500,
|
|
87
|
+
order: Optional[int] = 2,
|
|
88
|
+
filtfilt: Optional[bool] = True,
|
|
89
|
+
) -> np.ndarray:
|
|
90
|
+
|
|
91
|
+
"""Apply a Butterworth lowpass filter.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
95
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
96
|
+
cutoff (float, optional): Cutoff frequency in Hz. Default is 500.
|
|
97
|
+
order (int, optional): Filter order. Default is 2.
|
|
98
|
+
filtfilt (bool, optional): If True, filter forward and backward (zero phase,
|
|
99
|
+
doubled effective order). If False, filter forward only. Default is True.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
np.ndarray: Filtered data, same shape as the input.
|
|
103
|
+
"""
|
|
104
|
+
# Define filter
|
|
105
|
+
sos = signal.butter(order, cutoff, btype='low', fs=fs, output='sos')
|
|
106
|
+
|
|
107
|
+
# Apply filter
|
|
108
|
+
if filtfilt:
|
|
109
|
+
out = signal.sosfiltfilt(sos, data, axis=0)
|
|
110
|
+
else:
|
|
111
|
+
out = signal.sosfilt(sos, data, axis=0)
|
|
112
|
+
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def remove_powerline(
|
|
117
|
+
data: np.ndarray,
|
|
118
|
+
fs: Optional[int] = 2048,
|
|
119
|
+
cutoff: Optional[float] = 50,
|
|
120
|
+
width: Optional[float] = 1,
|
|
121
|
+
order: Optional[int] = 2,
|
|
122
|
+
filtfilt: Optional[bool] = True,
|
|
123
|
+
) -> np.ndarray:
|
|
124
|
+
|
|
125
|
+
"""Remove powerline noise with a Butterworth bandstop filter.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
129
|
+
fs (int, optional): Sampling frequency in Hz. Default is 2048.
|
|
130
|
+
cutoff (float, optional): Powerline frequency in Hz. Default is 50.
|
|
131
|
+
width (float, optional): Width of the stop band in Hz, centred on cutoff.
|
|
132
|
+
Default is 1.
|
|
133
|
+
order (int, optional): Filter order. Default is 2.
|
|
134
|
+
filtfilt (bool, optional): If True, filter forward and backward (zero phase,
|
|
135
|
+
doubled effective order). If False, filter forward only. Default is True.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
np.ndarray: Filtered data, same shape as the input.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
# Build cutoff
|
|
142
|
+
cutoff = [cutoff - width/2, cutoff + width/2]
|
|
143
|
+
|
|
144
|
+
# Define filter
|
|
145
|
+
sos = signal.butter(order, cutoff, btype='bandstop', fs=fs, output='sos')
|
|
146
|
+
|
|
147
|
+
# Apply filter
|
|
148
|
+
if filtfilt:
|
|
149
|
+
out = signal.sosfiltfilt(sos, data, axis=0)
|
|
150
|
+
else:
|
|
151
|
+
out = signal.sosfilt(sos, data, axis=0)
|
|
152
|
+
|
|
153
|
+
return out
|
emg_tools/tools.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Rearrange EMG channels on an electrode grid and replace bad channels."""
|
|
2
|
+
|
|
3
|
+
from copy import copy
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def arrange_data_spatially(
|
|
10
|
+
data: np.ndarray,
|
|
11
|
+
ch_map: np.ndarray
|
|
12
|
+
) -> np.ndarray:
|
|
13
|
+
|
|
14
|
+
"""Arrange (samples, chs) data on the electrode grid given by the channel map.
|
|
15
|
+
|
|
16
|
+
Grid positions with a negative or out-of-range channel index are filled with zeros.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
data (np.ndarray): Input data with shape (samples, chs).
|
|
20
|
+
ch_map (np.ndarray): Channel map with shape (rows, cols) holding the 0-based
|
|
21
|
+
channel index of each electrode, and -1 for empty positions.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
np.ndarray: Spatially arranged data with shape (rows, cols, samples).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
rows, cols = ch_map.shape
|
|
28
|
+
samples, chs = data.shape
|
|
29
|
+
data_spatial = np.zeros((rows, cols, samples))
|
|
30
|
+
|
|
31
|
+
for row, col in np.ndindex(ch_map.shape):
|
|
32
|
+
ch = ch_map[row, col]
|
|
33
|
+
if (ch < 0) or (ch >= chs):
|
|
34
|
+
continue
|
|
35
|
+
data_spatial[row, col] = data[:, ch]
|
|
36
|
+
|
|
37
|
+
return data_spatial
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def flatten_data_spatially(
|
|
41
|
+
data: np.ndarray,
|
|
42
|
+
ch_map: np.ndarray
|
|
43
|
+
) -> np.ndarray:
|
|
44
|
+
|
|
45
|
+
"""Flatten (rows, cols, samples) grid data back to (samples, chs).
|
|
46
|
+
|
|
47
|
+
Inverse of `arrange_data_spatially`. Channels missing from the map are filled with zeros.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
data (np.ndarray): Input data with shape (rows, cols, samples).
|
|
51
|
+
ch_map (np.ndarray): Channel map with shape (rows, cols) holding the 0-based
|
|
52
|
+
channel index of each electrode, and -1 for empty positions.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
np.ndarray: Flattened data with shape (samples, chs), where chs is
|
|
56
|
+
`ch_map.max() + 1`.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
samples = data.shape[-1]
|
|
60
|
+
chs = np.amax(ch_map) + 1
|
|
61
|
+
|
|
62
|
+
data_flat = np.zeros((samples, chs))
|
|
63
|
+
|
|
64
|
+
for ch in range(chs):
|
|
65
|
+
idx = np.where(ch_map == ch)
|
|
66
|
+
if len(idx[0]):
|
|
67
|
+
data_flat[:, ch] = data[idx[0], idx[1]]
|
|
68
|
+
|
|
69
|
+
return data_flat
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def replace_bad_ch(
|
|
73
|
+
data: np.ndarray,
|
|
74
|
+
bad_ch: Union[list, np.ndarray],
|
|
75
|
+
ch_map: np.ndarray,
|
|
76
|
+
) -> np.ndarray:
|
|
77
|
+
|
|
78
|
+
"""Replace bad channels with the mean of their good neighbouring channels.
|
|
79
|
+
|
|
80
|
+
Neighbours are the up to 8 surrounding electrodes on the grid. Bad channels are
|
|
81
|
+
replaced in the given order, so a replaced channel can serve as a neighbour for the
|
|
82
|
+
next ones. Bad channels without good neighbours are set to zero.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
data (np.ndarray): Input data with shape (samples, chs) or (rows, cols, samples).
|
|
86
|
+
bad_ch (Union[list, np.ndarray]): 0-based indices of the bad channels.
|
|
87
|
+
ch_map (np.ndarray): Channel map with shape (rows, cols) holding the 0-based
|
|
88
|
+
channel index of each electrode, and -1 for empty positions.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
np.ndarray: Copy of the data, same shape as the input, with the bad channels replaced.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
# Initialise variables
|
|
95
|
+
rows, cols = ch_map.shape
|
|
96
|
+
data_out = copy(data)
|
|
97
|
+
if isinstance(bad_ch, list):
|
|
98
|
+
bad_ch_out = copy(bad_ch)
|
|
99
|
+
else:
|
|
100
|
+
bad_ch_out = copy(bad_ch).tolist()
|
|
101
|
+
|
|
102
|
+
# Substitute bad channels until there are no more bad channels left
|
|
103
|
+
while len(bad_ch_out) > 0:
|
|
104
|
+
|
|
105
|
+
# Set updated bad channels to -1
|
|
106
|
+
ch_map_out = copy(ch_map)
|
|
107
|
+
for ch in bad_ch_out:
|
|
108
|
+
ch_map_out[ ch_map == ch ] = -1
|
|
109
|
+
|
|
110
|
+
# Get first bad channel
|
|
111
|
+
curr_bad_ch = bad_ch_out.pop(0)
|
|
112
|
+
|
|
113
|
+
# Find coordinates of the current bad channel
|
|
114
|
+
[x, y] = np.where(ch_map == curr_bad_ch)
|
|
115
|
+
x = x[0]
|
|
116
|
+
y = y[0]
|
|
117
|
+
|
|
118
|
+
# # Define mask
|
|
119
|
+
neigh_mask = np.array([
|
|
120
|
+
[x, y + 1],
|
|
121
|
+
[x, y - 1],
|
|
122
|
+
[x + 1, y],
|
|
123
|
+
[x - 1, y],
|
|
124
|
+
[x + 1, y + 1],
|
|
125
|
+
[x + 1, y - 1],
|
|
126
|
+
[x - 1, y + 1],
|
|
127
|
+
[x - 1, y - 1]
|
|
128
|
+
])
|
|
129
|
+
|
|
130
|
+
# Remove neighbours out of bounds
|
|
131
|
+
in_range = np.logical_and(
|
|
132
|
+
np.logical_and( neigh_mask[:,0] > -1, neigh_mask[:,0] < rows),
|
|
133
|
+
np.logical_and( neigh_mask[:,1] > -1, neigh_mask[:,1] < cols)
|
|
134
|
+
)
|
|
135
|
+
neigh_mask = neigh_mask[in_range]
|
|
136
|
+
in_range = in_range[in_range]
|
|
137
|
+
|
|
138
|
+
# Check for good neighbours
|
|
139
|
+
for i in range(neigh_mask.shape[0]):
|
|
140
|
+
if (ch_map_out[ neigh_mask[i,0], neigh_mask[i,1] ] < 0):
|
|
141
|
+
in_range[i] = False
|
|
142
|
+
|
|
143
|
+
# Get the actual neighbouring channels
|
|
144
|
+
neigh_mask = neigh_mask[in_range, :]
|
|
145
|
+
neigh_chs = ch_map[neigh_mask[:,0], neigh_mask[:,1]]
|
|
146
|
+
|
|
147
|
+
# Substitue channels (set to zero if there are no good neighbours)
|
|
148
|
+
if len(data_out.shape) == 2: # (samples, chs) format
|
|
149
|
+
if len(neigh_chs) == 0:
|
|
150
|
+
data_out[:, curr_bad_ch] = 0
|
|
151
|
+
else:
|
|
152
|
+
data_out[:, curr_bad_ch] = np.mean( data_out[:, neigh_chs], axis=-1)
|
|
153
|
+
elif len(data_out.shape) == 3: # (ch_rows, ch_cols, samples) format
|
|
154
|
+
if len(neigh_chs) == 0:
|
|
155
|
+
data_out[x,y] = 0
|
|
156
|
+
else:
|
|
157
|
+
data_out[x,y] = np.mean( data_out[neigh_mask[:,0], neigh_mask[:,1]], axis=0)
|
|
158
|
+
|
|
159
|
+
return data_out
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: emg-tools
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Preprocess, analyse and plot EMG signals
|
|
5
|
+
Author: Irene Mendez Guerra
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://imendezguerra.github.io/emg-tools/
|
|
8
|
+
Project-URL: Documentation, https://imendezguerra.github.io/emg-tools/
|
|
9
|
+
Project-URL: Source, https://github.com/imendezguerra/emg-tools
|
|
10
|
+
Project-URL: Issues, https://github.com/imendezguerra/emg-tools/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/imendezguerra/emg-tools/releases
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: numpy>=1.22
|
|
21
|
+
Requires-Dist: scipy>=1.8
|
|
22
|
+
Requires-Dist: matplotlib>=3.5
|
|
23
|
+
Requires-Dist: seaborn>=0.11
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest-cov>=4; extra == "dev"
|
|
27
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
28
|
+
Requires-Dist: pre-commit>=3; extra == "dev"
|
|
29
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
30
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
31
|
+
Provides-Extra: docs
|
|
32
|
+
Requires-Dist: mkdocs<2,>=1.6; extra == "docs"
|
|
33
|
+
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
|
|
34
|
+
Requires-Dist: mkdocstrings[python]>=0.26; extra == "docs"
|
|
35
|
+
Requires-Dist: markdown-exec>=1.9; extra == "docs"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# EMG Toolbox
|
|
39
|
+
|
|
40
|
+
[](https://pypi.org/project/emg-tools/)
|
|
41
|
+
[](https://pypi.org/project/emg-tools/)
|
|
42
|
+
[](https://github.com/imendezguerra/emg-tools/actions/workflows/ci.yml)
|
|
43
|
+
[](https://imendezguerra.github.io/emg-tools/)
|
|
44
|
+
|
|
45
|
+
## Overview
|
|
46
|
+
<!-- --8<-- [start:overview] -->
|
|
47
|
+
EMG Toolbox is a Python package to preprocess, analyse and plot electromyography (EMG) signals, including high-density recordings from electrode grids.
|
|
48
|
+
|
|
49
|
+
The package is composed of the following modules:
|
|
50
|
+
|
|
51
|
+
- `tools`: rearrange channels between `(samples, channels)` and grid `(rows, cols, samples)` formats, and replace bad channels with the mean of their neighbours.
|
|
52
|
+
- `prepro`: Butterworth bandpass, highpass, lowpass and powerline (bandstop) filters.
|
|
53
|
+
- `feats`: amplitude features such as the moving-window root mean square (RMS).
|
|
54
|
+
- `freq`: amplitude spectrum and power spectral density (periodogram or Welch).
|
|
55
|
+
- `plots`: plot channels over time, PSDs, PSD maps across channels, and spectrograms.
|
|
56
|
+
<!-- --8<-- [end:overview] -->
|
|
57
|
+
|
|
58
|
+
## Table of Contents
|
|
59
|
+
- [Installation](#installation)
|
|
60
|
+
- [Quick start](#quick-start)
|
|
61
|
+
- [Documentation](#documentation)
|
|
62
|
+
- [Contributing](#contributing)
|
|
63
|
+
- [License](#license)
|
|
64
|
+
- [Citation](#citation)
|
|
65
|
+
- [Contact](#contact)
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
<!-- --8<-- [start:install] -->
|
|
69
|
+
Install the latest release from PyPI (Python 3.10 or newer):
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
pip install emg-tools
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The package is imported as `emg_tools`.
|
|
76
|
+
<!-- --8<-- [end:install] -->
|
|
77
|
+
|
|
78
|
+
To work on the code itself, see the development setup in [CONTRIBUTING.md](https://github.com/imendezguerra/emg-tools/blob/main/CONTRIBUTING.md#development-setup).
|
|
79
|
+
|
|
80
|
+
## Quick start
|
|
81
|
+
<!-- --8<-- [start:quickstart] -->
|
|
82
|
+
EMG data is an array of shape `(samples, channels)`. The example below filters a synthetic 16-channel recording and computes its RMS envelope:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import numpy as np
|
|
86
|
+
|
|
87
|
+
from emg_tools import feats, prepro
|
|
88
|
+
|
|
89
|
+
fs = 2048 # sampling frequency (Hz)
|
|
90
|
+
timestamps = np.arange(5 * fs) / fs # 5 s recording
|
|
91
|
+
rng = np.random.default_rng(0)
|
|
92
|
+
emg = rng.standard_normal((timestamps.size, 16)) # (samples, channels)
|
|
93
|
+
emg += 0.5 * np.sin(2 * np.pi * 50 * timestamps)[:, None] # powerline noise
|
|
94
|
+
|
|
95
|
+
emg_filt = prepro.remove_powerline(emg, fs=fs, cutoff=50)
|
|
96
|
+
emg_filt = prepro.bandpass_filter(emg_filt, fs=fs, cutoff=[20, 500])
|
|
97
|
+
|
|
98
|
+
rms, t_win = feats.compute_rms(emg_filt, timestamps, win_len_s=0.25, win_step_s=0.125, fs=fs)
|
|
99
|
+
rms.shape # (10240, 16): one RMS value per sample and channel
|
|
100
|
+
```
|
|
101
|
+
<!-- --8<-- [end:quickstart] -->
|
|
102
|
+
|
|
103
|
+
## Documentation
|
|
104
|
+
The full documentation, with a worked example and the API reference, is at
|
|
105
|
+
[imendezguerra.github.io/emg-tools](https://imendezguerra.github.io/emg-tools/).
|
|
106
|
+
|
|
107
|
+
## Contributing
|
|
108
|
+
Contributions are welcome! [CONTRIBUTING.md](https://github.com/imendezguerra/emg-tools/blob/main/CONTRIBUTING.md) explains how to set up a development environment, run the tests, preview the docs, and what the automated checks (pre-commit and CI) do.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
This project is licensed under the [MIT License](https://github.com/imendezguerra/emg-tools/blob/main/LICENSE).
|
|
112
|
+
|
|
113
|
+
## Citation
|
|
114
|
+
|
|
115
|
+
If you use this code in your research, please cite this repository:
|
|
116
|
+
|
|
117
|
+
```sh
|
|
118
|
+
@software{Mendez_Guerra_EMG_Toolbox,
|
|
119
|
+
author = {Mendez Guerra, Irene},
|
|
120
|
+
title = {{EMG Toolbox}},
|
|
121
|
+
url = {https://github.com/imendezguerra/emg-tools},
|
|
122
|
+
version = {2.0.0}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
## Contact
|
|
126
|
+
|
|
127
|
+
For any questions or inquiries, please contact us at:
|
|
128
|
+
```sh
|
|
129
|
+
Irene Mendez Guerra
|
|
130
|
+
irene.mendez17@imperial.ac.uk
|
|
131
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
emg_tools/__init__.py,sha256=_7OlQdbVkK4jad0CLdpI0grT-zEAb-qgFmH5mFzDXiA,22
|
|
2
|
+
emg_tools/feats.py,sha256=a6A4v8o0LzEWZy7MFirmEVXyOllHaeSWN5zRMgCkQas,2430
|
|
3
|
+
emg_tools/freq.py,sha256=UfB5XBFUTi7LYnKd5PaWvczC1oRzPWCUyhjEGMyqTcE,2267
|
|
4
|
+
emg_tools/plots.py,sha256=YRXXdm91qbl-FayEVkbaqdva1MQq4hvK_owHgvSR6Bw,12089
|
|
5
|
+
emg_tools/prepro.py,sha256=Fw2EWMtj_TfgvcunK8p5TjLLbNgjZa_pMZE6vmaLtnM,4704
|
|
6
|
+
emg_tools/tools.py,sha256=KP4PX9Ab7JdJC0tBKeIBEcIj8LylvgivWVC2c9Do0v8,5070
|
|
7
|
+
emg_tools-2.0.0.dist-info/licenses/LICENSE,sha256=br1f1_jBcTf89JVMbr0sd6YwqbElROVGeK_wpEz3u0U,1076
|
|
8
|
+
emg_tools-2.0.0.dist-info/METADATA,sha256=INwmxElYCZtrqHUe4jaatZYLGLgLjdnkSUjuFtQJQcM,5266
|
|
9
|
+
emg_tools-2.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
emg_tools-2.0.0.dist-info/top_level.txt,sha256=k8Sbe-8PNT1P_i_eWIp8Aa0R84kufomN4yf015URefY,10
|
|
11
|
+
emg_tools-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Irene Mendez Guerra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
emg_tools
|