This repository has been archived by the owner on Apr 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfeature_extraction.py
285 lines (221 loc) · 8.21 KB
/
feature_extraction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import pywt
def features_estimation(signal, channel_name, fs, frame, step, plot=True):
"""
Compute time, frequency and time-frequency features from signal.
:param signal: numpy array signal.
:param channel_name: string variable with the EMG channel name in analysis.
:param fs: int variable with the sampling frequency used to acquire the signal
:param frame: sliding window size
:param step: sliding window step size
:param plot: boolean variable to plot estimated features.
:return: total_feature_matrix -- python Data-frame with.
:return: features_names -- python list with
"""
features_names = ['VAR', 'RMS', 'IEMG', 'MAV', 'LOG', 'WL', 'ACC', 'DASDV', 'ZC', 'WAMP', 'MYOP', "FR", "MNP", "TP",
"MNF", "MDF", "PKF", "WENT"]
time_matrix = time_features_estimation(signal, frame, step)
frequency_matrix = frequency_features_estimation(signal, fs, frame, step)
time_frequency_matrix = time_frequency_features_estimation(signal, frame, step)
total_feature_matrix = pd.DataFrame(np.column_stack((time_matrix, frequency_matrix, time_frequency_matrix)).T,
index=features_names)
print('EMG features were from channel {} extracted successfully'.format(channel_name))
if plot:
plot_features(signal, channel_name, fs, total_feature_matrix, step)
return total_feature_matrix, features_names
def time_features_estimation(signal, frame, step):
"""
Compute time features from signal using sliding window method.
:param signal: numpy array signal.
:param frame: sliding window size.
:param step: sliding window step size.
:return: time_features_matrix: narray matrix with the time features stacked by columns.
"""
variance = []
rms = []
iemg = []
mav = []
log_detector = []
wl = []
aac = []
dasdv = []
zc = []
wamp = []
myop = []
th = np.mean(signal) + 3 * np.std(signal)
for i in range(frame, signal.size, step):
x = signal[i - frame:i]
variance.append(np.var(x))
rms.append(np.sqrt(np.mean(x ** 2)))
iemg.append(np.sum(abs(x))) # Integral
mav.append(np.sum(np.absolute(x)) / frame) # Mean Absolute Value
log_detector.append(np.exp(np.sum(np.log10(np.absolute(x))) / frame))
wl.append(np.sum(abs(np.diff(x)))) # Wavelength
aac.append(np.sum(abs(np.diff(x))) / frame) # Average Amplitude Change
dasdv.append(
math.sqrt((1 / (frame - 1)) * np.sum((np.diff(x)) ** 2))) # Difference absolute standard deviation value
zc.append(zcruce(x, th)) # Zero-Crossing
wamp.append(wilson_amplitude(x, th)) # Willison amplitude
myop.append(myopulse(x, th)) # Myopulse percentage rate
time_features_matrix = np.column_stack((variance, rms, iemg, mav, log_detector, wl, aac, dasdv, zc, wamp, myop))
return time_features_matrix
def frequency_features_estimation(signal, fs, frame, step):
"""
Compute frequency features from signal using sliding window method.
:param signal: numpy array signal.
:param fs: sampling frequency of the signal.
:param frame: sliding window size
:param step: sliding window step size
:return: frequency_features_matrix: narray matrix with the frequency features stacked by columns.
"""
fr = []
mnp = []
tot = []
mnf = []
mdf = []
pkf = []
for i in range(frame, signal.size, step):
x = signal[i - frame:i]
frequency, power = spectrum(x, fs)
fr.append(frequency_ratio(frequency, power)) # Frequency ratio
mnp.append(np.sum(power) / len(power)) # Mean power
tot.append(np.sum(power)) # Total power
mnf.append(mean_freq(frequency, power)) # Mean frequency
mdf.append(median_freq(frequency, power)) # Median frequency
pkf.append(frequency[power.argmax()]) # Peak frequency
frequency_features_matrix = np.column_stack((fr, mnp, tot, mnf, mdf, pkf))
return frequency_features_matrix
def time_frequency_features_estimation(signal, frame, step):
"""
Compute time-frequency features from signal using sliding window method.
:param signal: numpy array signal.
:param frame: sliding window size
:param step: sliding window step size
:return: h_wavelet: list
"""
h_wavelet = []
for i in range(frame, signal.size, step):
x = signal[i - frame:i]
E_a, E = wavelet_energy(x, 'db2', 4)
E.insert(0, E_a)
E = np.asarray(E) / 100
h_wavelet.append(-np.sum(E * np.log2(E)))
return h_wavelet
def wilson_amplitude(signal, th):
x = abs(np.diff(signal))
umbral = x >= th
return np.sum(umbral)
def myopulse(signal, th):
umbral = signal >= th
return np.sum(umbral) / len(signal)
def spectrum(signal, fs):
m = len(signal)
n = next_power_of_2(m)
y = np.fft.fft(signal, n)
yh = y[0:int(n / 2 - 1)]
fh = (fs / n) * np.arange(0, n / 2 - 1, 1)
power = np.real(yh * np.conj(yh) / n)
return fh, power
def frequency_ratio(frequency, power):
power_low = power[(frequency >= 30) & (frequency <= 250)]
power_high = power[(frequency > 250) & (frequency <= 500)]
ULC = np.sum(power_low)
UHC = np.sum(power_high)
return ULC / UHC
def shannon(x):
n = len(x)
nb = 19
hist, bin_edges = np.histogram(x, bins=nb)
counts = hist / n
nz = np.nonzero(counts)
return np.sum(counts[nz] * np.log(counts[nz]) / np.log(2))
def zcruce(X, th):
th = 0
cruce = 0
for cont in range(len(X) - 1):
can = X[cont] * X[cont + 1]
can2 = abs(X[cont] - X[cont + 1])
if can < 0 and can2 > th:
cruce = cruce + 1
return cruce
def mean_freq(frequency, power):
num = 0
den = 0
for i in range(int(len(power) / 2)):
num += frequency[i] * power[i]
den += power[i]
return num / den
def median_freq(frequency, power):
power_total = np.sum(power) / 2
temp = 0
tol = 0.01
errel = 1
i = 0
while abs(errel) > tol:
temp += power[i]
errel = (power_total - temp) / power_total
i += 1
if errel < 0:
errel = 0
i -= 1
return frequency[i]
def wavelet_energy(x, mother, nivel):
coeffs = pywt.wavedecn(x, wavelet=mother, level=nivel)
arr, _ = pywt.coeffs_to_array(coeffs)
et = np.sum(arr ** 2)
ca = coeffs[0]
ea = 100 * np.sum(ca ** 2) / et
ed = []
for k in range(1, len(coeffs)):
cd = list(coeffs[k].values())
cd = np.asarray(cd)
ed.append(100 * np.sum(cd ** 2) / et)
return ea, ed
def next_power_of_2(x):
return 1 if x == 0 else 2 ** (x - 1).bit_length()
def med_freq(f, P):
plot = np.sum(P) / 2
temp = 0
tol = 0.01
errel = 1
i = 0
while abs(errel) > tol:
temp += P[i]
errel = (plot - temp) / plot
i += 1
if errel < 0:
errel = 0
i -= 1
return f[i]
def plot_features(signal, channel_name, fs, feature_matrix, step):
"""
Argument:
signal -- python numpy array representing recording of a signal.
channel_name -- string variable with the EMG channel name in analysis (Title).
fs -- int variable with the sampling frequency used to acquire the signal.
feature_matrix -- python Dataframe.
step -- int variable with the step size used in the sliding window method.
"""
ts = np.arange(0, len(signal) / fs, 1 / fs)
# for idx, f in enumerate(tfeatures.T):
for key in feature_matrix.T:
tf = step * (np.arange(0, len(feature_matrix.T[key]) / fs, 1 / fs))
fig = plt.figure()
ax = fig.add_subplot(111, label="1")
ax2 = fig.add_subplot(111, label="2", frame_on=False)
ax.plot(ts, signal, color="C0")
ax.autoscale(tight=True)
plt.title(channel_name + ": " + key)
ax.set_xlabel("Time")
ax.set_ylabel("mV")
ax2.plot(tf, feature_matrix.T[key], color="red")
ax2.yaxis.tick_right()
ax2.autoscale(tight=True)
ax2.set_xticks([])
ax2.set_yticks([])
# mng = plt.get_current_fig_manager()
# mng.window.state('zoomed')
plt.show()