-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
295 lines (217 loc) · 7.99 KB
/
utils.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
286
287
288
289
290
291
292
293
294
295
""" utils.py """
from __future__ import division
from __future__ import print_function
if __name__ == '__main__':
raise Exception('This file is not executable. Use birdsong.py')
import os
try:
import cPickle as pkl
except ImportError:
import pickle as pkl
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import scipy.signal as scipy_signal
import scipy.io as sio
import scipy.io.wavfile as wavfile
# Default spectrogram parameters.
NFFT = 256
NOVERLAP = 128
DOWNSAMPLE = 0
CLIP_BOTTOM = 20 # Clip the bottom frequencies.
def downsample_arr(x):
"""Takes average between four points to get one point."""
ndim = len(x.shape)
if ndim == 1:
if x.shape[0] % 2:
x = x[:-1]
return (x[::2] + x[1::2]) / 2
elif ndim == 2:
if x.shape[0] % 2:
x = x[:-1, :]
if x.shape[1] % 2:
x = x[:, :-1]
return (x[::2, ::2] + x[::2, 1::2] +
x[1::2, ::2] + x[1::2, 1::2]) / 4
else: # Batch-wise.
if x.shape[1] % 2:
x = x[:, :-1, :]
if x.shape[2] % 2:
x = x[:, :, :-1]
return (x[:, ::2, ::2] + x[:, ::2, 1::2] +
x[:, 1::2, ::2] + x[:, 1::2, 1::2]) / 4
def plot_as_gif(x,
interval=50,
save_path='/tmp/generated.gif',
normalize=False):
"""Plots data as a gif.
Args:
x: numpy array with shape (gif_length, time, freq).
interval: int, the time between frames in milliseconds.
save_path: str, where to save the resulting gif.
normalize: bool, if set, normalize the spectrogram intensities.
"""
# Gets the axis labels.
flabels, tlabels = get_freq_time_labels(x.shape[1])
extent = [tlabels[0] * 1000, tlabels[-1] * 1000,
flabels[-1] / 1000, flabels[0] / 1000]
if normalize:
x = np.power(x, 0.45)
# Plots the first sample.
fig, ax = plt.subplots()
im = plt.imshow(x[0].T,
interpolation='none',
aspect='auto',
animated=True,
vmin=0,
vmax=1,
extent=extent)
# Fixes the dimensions.
ax.invert_yaxis()
ax.set_xlabel('Time (msec)')
ax.set_ylabel('Freq (kHz)')
def updatefig(i, *args):
im.set_array(x[i].T)
return im,
anim = FuncAnimation(fig, updatefig,
frames=np.arange(0, x.shape[0]),
interval=interval)
anim.save(save_path, dpi=80, writer='imagemagick')
print('Saved gif to "%s".' % save_path)
plt.show()
def plot_sample(x,
title,
width=3,
height=2,
shuffle=True,
vmin=0,
vmax=1,
normalize=False):
"""Plots a sample of the data.
Args:
x: numpy array with shape (batch_size, time, freq).
title: str, the title of the plot.
width: int, the number of images wide.
height: int, the number of images tall.
vmin: float or None, the min of imshow.
vmax: float or None, the max of imshow.
shuffle: bool, if set, select randomly, otherwise select in order.
normalize: bool, if set, increase the small values.
"""
n = width * height
# Gets the frequency and time labels.
time_length = x.shape[1]
flabels, tlabels = get_freq_time_labels(time_length)
# Limits tlabels to the number of time steps in x.
tlabels = tlabels[:x.shape[1]]
if shuffle:
idx = np.random.choice(np.arange(x.shape[0]), n)
data = x[idx]
else:
data = x[:n]
extent = [tlabels[0] * 1000, tlabels[-1] * 1000,
flabels[-1] / 1000, flabels[0] / 1000]
plt.figure(figsize=(width * 5, height * 5))
for i in range(n):
d = data[i].T
if normalize:
d = np.power(d, 0.45)
ax = plt.subplot(height, width, i + 1)
ax.imshow(d,
interpolation='none',
aspect='auto',
vmin=vmin,
vmax=vmax,
extent=extent)
ax.invert_yaxis()
ax.set_xlabel('Time (msec)')
ax.set_ylabel('Freq (kHz)')
plt.suptitle(title)
plt.show()
def get_spectrogram(signal, fs):
"""Gets spectrogram with the default parameters."""
freq, time, data = scipy_signal.spectrogram(signal,
fs=fs,
# window=('gaussian', 0.1),
nperseg=NFFT,
noverlap=NOVERLAP,
nfft=NFFT)
# Clips the bottom part.
data = data[CLIP_BOTTOM:]
freq = freq[CLIP_BOTTOM:]
time = time[CLIP_BOTTOM:]
for i in range(DOWNSAMPLE):
freq = downsample_arr(freq)
time = downsample_arr(time)
data = downsample_arr(data)
return data, (freq, time)
def get_data_path():
"""Gets the path to the data as a string, safely."""
if 'DATA_PATH' not in os.environ:
os.environ['DATA_PATH'] = 'data'
DATA_PATH = os.environ['DATA_PATH']
if not os.path.isdir(DATA_PATH):
raise RuntimeError('No data directory found at "%s". Make sure '
'the DATA_PATH environment variable is set to '
'point at the correct directory.' % DATA_PATH)
return DATA_PATH
def get_directory(directory):
"""Gets a subdirectory of the datapath, safely."""
d = os.path.join(get_data_path(), directory)
if not os.path.isdir(d):
raise RuntimeError('No directory found at "%s".' % d)
return d
# Some important directories.
WAV_SEGMENTS = get_directory('USV_Segments/WAV')
def get_freq_time_labels(time_length):
"""Gets the frequency and time labels for the default settings."""
fname = os.listdir(WAV_SEGMENTS)[0]
fpath = os.path.join(WAV_SEGMENTS, fname)
fs, data = wavfile.read(fpath) # fs usually ~250,000
_, (freq, time) = get_spectrogram(data, fs)
return freq, time[:time_length]
def get_all_spectrograms(time_length,
cache='/tmp/spectrograms.npy',
rebuild=False):
"""Returns a Numpy array with shape (batch_size, time_length, freq).
Args:
time_length: int, number of time steps per spectrogram. Each step is
about 1/100 ms. Using ~300 seems to look good.
cache: str, where to cache the array to avoid regenerating every time
the method is called.
rebuild: bool, if set, the dataset is rebuilt (useful if changes are
made to the spectrogram parameters, for example).
Returns:
Numpy array with shape (batch_size, time_length, freq), the stacked
spectrograms.
"""
if not rebuild and os.path.exists(cache):
all_sgrams = np.load(cache)
else:
all_sgrams = []
fnames = os.listdir(WAV_SEGMENTS)
def _check(sgram):
"""Makes sure the spectrogram is something we want to use."""
if np.max(sgram) < 0.4:
return False
return True
for fname_nb, fname in enumerate(fnames):
if not fname.endswith('wav'):
continue
fpath = os.path.join(WAV_SEGMENTS, fname)
fs, data = wavfile.read(fpath)
sgram, _ = get_spectrogram(data, fs) # (freq, time)
# Scales the spectrogram to something reasonable.
sgram *= 1e5
# Gets the pixel dimensions of the spectrogram.
nb_time = sgram.shape[1]
# Adds spectrogram segments which satisfy the check from above.
all_sgrams += [sgram[:, i - time_length:i]
for i in range(time_length, nb_time, time_length // 2)
if _check(sgram[:, i - time_length:i])]
print('Processed %d / %d' % (fname_nb, len(fnames)), end='\r')
# Concatenates all samples and puts in order (batch_size, time, freq).
all_sgrams = np.stack(all_sgrams).transpose(0, 2, 1)
np.save(cache, all_sgrams)
print('%d spectrograms of length %d' % (len(all_sgrams), time_length))
return all_sgrams