-
Notifications
You must be signed in to change notification settings - Fork 7
/
transform.py
277 lines (233 loc) · 10.1 KB
/
transform.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
import numpy as np
import torch
from scipy import signal
import math
import cv2
import random
class Transform:
def __init__(self):
pass
def add_noise(self, signal, noise_amount):
"""
adding noise
"""
signal = signal.T
noise = (0.4 ** 0.5) * np.random.normal(1, noise_amount, np.shape(signal)[0])
noise = noise[:,None]
noised_signal = signal + noise
noised_signal = noised_signal.T
# print(noised_signal.shape)
return noised_signal
def add_noise_with_SNR(self,signal, noise_amount):
"""
adding noise
created using: https://stackoverflow.com/a/53688043/10700812
"""
signal = signal[0]
target_snr_db = noise_amount # 20
x_watts = signal ** 2 # Calculate signal power and convert to dB
sig_avg_watts = np.mean(x_watts)
sig_avg_db = 10 * np.log10(sig_avg_watts) # Calculate noise then convert to watts
noise_avg_db = sig_avg_db - target_snr_db
noise_avg_watts = 10 ** (noise_avg_db / 10)
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts),
len(x_watts)) # Generate an sample of white noise
noised_signal = signal + noise_volts # noise added signal
noised_signal = noised_signal[None,:]
# print(noised_signal.shape)
return noised_signal
def scaled(self,signal, factor_list):
""""
scale the signal
"""
factor = round(np.random.uniform(factor_list[0],factor_list[1]),2)
signal[0] = 1 / (1 + np.exp(-signal[0]))
# print(signal.max())
return signal
def negate(self,signal):
"""
negate the signal
"""
signal[0] = signal[0] * (-1)
return signal
def hor_filp(self,signal):
"""
flipped horizontally
"""
hor_flipped = np.flip(signal,axis=1)
return hor_flipped
def permute(self,signal, pieces):
"""
signal: numpy array (batch x window)
pieces: number of segments along time
"""
signal = signal.T
pieces = int(np.ceil(np.shape(signal)[0] / (np.shape(signal)[0] // pieces)).tolist()) #向上取整
piece_length = int(np.shape(signal)[0] // pieces)
sequence = list(range(0, pieces))
np.random.shuffle(sequence)
permuted_signal = np.reshape(signal[:(np.shape(signal)[0] // pieces * pieces)],
(pieces, piece_length)).tolist()
tail = signal[(np.shape(signal)[0] // pieces * pieces):]
permuted_signal = np.asarray(permuted_signal)[sequence]
permuted_signal = np.concatenate(permuted_signal, axis=0)
permuted_signal = np.concatenate((permuted_signal,tail[:,0]), axis=0)
permuted_signal = permuted_signal[:,None]
permuted_signal = permuted_signal.T
return permuted_signal
def cutout_resize(self,signal,pieces):
"""
signal: numpy array (batch x window)
pieces: number of segments along time
cutout 1 piece
"""
signal = signal.T
pieces = int(np.ceil(np.shape(signal)[0] / (np.shape(signal)[0] // pieces)).tolist()) # 向上取整
piece_length = int(np.shape(signal)[0] // pieces)
import random
sequence = []
cutout = random.randint(0, pieces)
# print(cutout)
# sequence1 = list(range(0, cutout))
# sequence2 = list(range(int(cutout + 1), pieces))
# sequence = np.hstack((sequence1, sequence2))
for i in range(pieces):
if i == cutout:
pass
else:
sequence.append(i)
# print(sequence)
cutout_signal = np.reshape(signal[:(np.shape(signal)[0] // pieces * pieces)],
(pieces, piece_length)).tolist()
tail = signal[(np.shape(signal)[0] // pieces * pieces):]
cutout_signal = np.asarray(cutout_signal)[sequence]
cutout_signal = np.hstack(cutout_signal)
cutout_signal = np.concatenate((cutout_signal, tail[:, 0]), axis=0)
cutout_signal = cv2.resize(cutout_signal, (1, 3072), interpolation=cv2.INTER_LINEAR)
cutout_signal = cutout_signal.T
return cutout_signal
def cutout_zero(self,signal,pieces):
"""
signal: numpy array (batch x window)
pieces: number of segments along time
cutout 1 piece
"""
signal = signal.T
ones = np.ones((np.shape(signal)[0],np.shape(signal)[1]))
# print(ones.shape)
# assert False
pieces = int(np.ceil(np.shape(signal)[0] / (np.shape(signal)[0] // pieces)).tolist()) # 向上取整
piece_length = int(np.shape(signal)[0] // pieces)
cutout = random.randint(1, pieces)
cutout_signal = np.reshape(signal[:(np.shape(signal)[0] // pieces * pieces)],
(pieces, piece_length)).tolist()
ones_pieces = np.reshape(ones[:(np.shape(signal)[0] // pieces * pieces)],
(pieces, piece_length)).tolist()
tail = signal[(np.shape(signal)[0] // pieces * pieces):]
cutout_signal = np.asarray(cutout_signal)
ones_pieces = np.asarray(ones_pieces)
for i in range(pieces):
if i == cutout:
ones_pieces[i]*=0
cutout_signal = cutout_signal * ones_pieces
cutout_signal = np.hstack(cutout_signal)
cutout_signal = np.concatenate((cutout_signal, tail[:, 0]), axis=0)
cutout_signal = cutout_signal[:,None]
cutout_signal = cutout_signal.T
return cutout_signal
# mic
def crop_resize(self, signal, size):
signal = signal.T
size = signal.shape[0] * size
size = int(size)
start = random.randint(0, signal.shape[0]-size)
crop_signal = signal[start:start + size,:]
# print(crop_signal.shape)
crop_signal = cv2.resize(crop_signal, (1, 3072), interpolation=cv2.INTER_LINEAR)
# print(crop_signal.shape)
crop_signal = crop_signal.T
return crop_signal
def move_avg(self,a,n, mode="same"):
# a = a.T
result = np.convolve(a[0], np.ones((n,)) / n, mode=mode)
return result[None,:]
def bandpass_filter(self, x, order, cutoff, fs=100):
result = np.zeros((x.shape[0], x.shape[1]))
w1 = 2 * cutoff[0] / int(fs)
w2 = 2 * cutoff[1] / int(fs)
b, a = signal.butter(order, [w1, w2], btype='bandpass') # 配置滤波器 8 表示滤波器的阶数
result = signal.filtfilt(b, a, x, axis=1)
# print(result.shape)
return result
def lowpass_filter(self, x, order, cutoff, fs=100):
result = np.zeros((x.shape[0], x.shape[1]))
w1 = 2 * cutoff[0] / int(fs)
# w2 = 2 * cutoff[1] / fs
b, a = signal.butter(order, w1, btype='lowpass') # 配置滤波器 8 表示滤波器的阶数
result = signal.filtfilt(b, a, x, axis=1)
# print(result.shape)
return result
def highpass_filter(self, x, order, cutoff, fs=100):
result = np.zeros((x.shape[0], x.shape[1]))
w1 = 2 * cutoff[0] / int(fs)
# w2 = 2 * cutoff[1] / fs
b, a = signal.butter(order, w1, btype='highpass') # 配置滤波器 8 表示滤波器的阶数
result = signal.filtfilt(b, a, x, axis=1)
# print(result.shape)
return result
def time_warp(self,signal, sampling_freq, pieces, stretch_factor, squeeze_factor):
"""
signal: numpy array (batch x window)
sampling freq
pieces: number of segments along time
stretch factor
squeeze factor
"""
signal = signal.T
total_time = np.shape(signal)[0] // sampling_freq
segment_time = total_time / pieces
sequence = list(range(0, pieces))
stretch = np.random.choice(sequence, math.ceil(len(sequence) / 2), replace=False)
squeeze = list(set(sequence).difference(set(stretch)))
initialize = True
for i in sequence:
orig_signal = signal[int(i * np.floor(segment_time * sampling_freq)):int(
(i + 1) * np.floor(segment_time * sampling_freq))]
orig_signal = orig_signal.reshape(np.shape(orig_signal)[0], 1)
if i in stretch:
output_shape = int(np.ceil(np.shape(orig_signal)[0] * stretch_factor))
new_signal = cv2.resize(orig_signal, (1, output_shape), interpolation=cv2.INTER_LINEAR)
if initialize == True:
time_warped = new_signal
initialize = False
else:
time_warped = np.vstack((time_warped, new_signal))
elif i in squeeze:
output_shape = int(np.ceil(np.shape(orig_signal)[0] * squeeze_factor))
new_signal = cv2.resize(orig_signal, (1, output_shape), interpolation=cv2.INTER_LINEAR)
if initialize == True:
time_warped = new_signal
initialize = False
else:
time_warped = np.vstack((time_warped, new_signal))
time_warped = cv2.resize(time_warped, (1,3072), interpolation=cv2.INTER_LINEAR)
time_warped = time_warped.T
return time_warped
if __name__ == '__main__':
from transform import Transform
import matplotlib.pyplot as plt
Trans = Transform()
input = np.zeros((1,3072))
input = Trans.add_noise(input,10)
plt.subplot(211)
plt.plot(input[0])
# print(input.shape)
# output = Trans.cutout_resize(input,10)
order = random.randint(3, 10)
cutoff = random.uniform(5, 20)
output = Trans.filter(input, order, [2,15], mode='lowpass')
plt.subplot(212)
plt.plot(output[0])
plt.savefig('filter.png')
# print(output.shape)