-
Notifications
You must be signed in to change notification settings - Fork 19
/
util.py
375 lines (335 loc) · 12.7 KB
/
util.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import sys
sys.setrecursionlimit(10000)
import cPickle
import gzip
import pdb
import numpy as np
import argparse, timeit
import os
import fnmatch
import scipy
import scipy.signal
import scipy.io.wavfile
import librosa
import six
import librosa.util as util
import scipy.fftpack as fft
def masked_seqs_to_frames(x, mask):
(n_examples, time_steps, n_feature) = x.shape
x=x.transpose((2,0,1)) #shape (n_feature,n_examples,time_steps)
x_reshape = np.reshape(x, (n_feature, n_examples*time_steps))
mask = mask.transpose((2,0,1)) #shape (1,n_examples,time_steps)
mask_reshape = np.reshape(mask, (n_examples*time_steps,))
idx_of_mask = np.where(mask_reshape==mask_reshape[0])[0]
x_reshape = x_reshape[:, idx_of_mask]
return x_reshape
def wavread(wavfile):
if isinstance(wavfile,list):
wavfile=wavfile[0]
fs,x=scipy.io.wavfile.read(wavfile) #x will be nsampl x nch
x=np.transpose(x).astype(np.float32) #convert x to float32, transpose to nch x nsampl
x=x/32768.0
return x
def wavwrite(wavfile,fs,x):
# x should be nsampl x nch
if x.dtype==np.float32:
#convert float32 data to int16
xMaxAbs=np.max(np.abs(x))
if xMaxAbs>1:
x=x/xMaxAbs
x=np.int16(x*32767.0)
scipy.io.wavfile.write(wavfile,fs,x.T)
def istft_noDiv(stft_matrix, hop_length=None, win_length=None, window=None,
center=True, dtype=np.float32):
"""
#Copied from librosa's spectrum.py file, removing division by squared
window, which shouldn't be necessary and can cause problems in recon.
Inverse short-time Fourier transform (ISTFT).
Converts a complex-valued spectrogram `stft_matrix` to time-series `y`
by minimizing the mean squared error between `stft_matrix` and STFT of
`y` as described in [1]_.
In general, window function, hop length and other parameters should be same
as in stft, which mostly leads to perfect reconstruction of a signal from
unmodified `stft_matrix`.
Parameters
----------
stft_matrix : np.ndarray [shape=(1 + n_fft/2, t)]
STFT matrix from `stft`
hop_length : int > 0 [scalar]
Number of frames between STFT columns.
If unspecified, defaults to `win_length / 4`.
win_length : int <= n_fft = 2 * (stft_matrix.shape[0] - 1)
When reconstructing the time series, each frame is windowed
and each sample is normalized by the sum of squared window
according to the `window` function (see below).
If unspecified, defaults to `n_fft`.
window : None, function, np.ndarray [shape=(n_fft,)]
- None (default): use an asymmetric Hann window
- a window function, such as `scipy.signal.hanning`
- a user-specified window vector of length `n_fft`
center : boolean
- If `True`, `D` is assumed to have centered frames.
- If `False`, `D` is assumed to have left-aligned frames.
dtype : numeric type
Real numeric type for `y`. Default is 32-bit float.
Returns
-------
y : np.ndarray [shape=(n,)]
time domain signal reconstructed from `stft_matrix`
Raises
------
ParameterError
If `window` is supplied as a vector of length `n_fft`
See Also
--------
stft : Short-time Fourier Transform
Examples
--------
>>> y, sr = librosa.load(librosa.util.example_audio_file())
>>> D = librosa.stft(y)
>>> y_hat = librosa.istft(D)
>>> y_hat
array([ -4.812e-06, -4.267e-06, ..., 6.271e-06, 2.827e-07], dtype=float32)
Exactly preserving length of the input signal requires explicit padding.
Otherwise, a partial frame at the end of `y` will not be represented.
>>> n = len(y)
>>> n_fft = 2048
>>> y_pad = librosa.util.fix_length(y, n + n_fft // 2)
>>> D = librosa.stft(y_pad, n_fft=n_fft)
>>> y_out = librosa.util.fix_length(librosa.istft(D), n)
>>> np.max(np.abs(y - y_out))
1.4901161e-07
"""
n_fft = 2 * (stft_matrix.shape[0] - 1)
# By default, use the entire frame
if win_length is None:
win_length = n_fft
# Set the default hop, if it's not already specified
if hop_length is None:
hop_length = int(win_length / 4)
if window is None:
# Default is an asymmetric Hann window.
ifft_window = scipy.signal.hann(win_length, sym=False)
elif six.callable(window):
# User supplied a windowing function
ifft_window = window(win_length)
else:
# User supplied a window vector.
# Make it into an array
ifft_window = np.asarray(window)
# Verify that the shape matches
if ifft_window.size != n_fft:
raise ParameterError('Size mismatch between n_fft and window size')
# Pad out to match n_fft
ifft_window = util.pad_center(ifft_window, n_fft)
# scale the window
ifft_window = ifft_window*(2.0/(win_length/hop_length))
n_frames = stft_matrix.shape[1]
expected_signal_len = n_fft + hop_length * (n_frames - 1)
y = np.zeros(expected_signal_len, dtype=dtype)
ifft_window_sum = np.zeros(expected_signal_len, dtype=dtype)
ifft_window_square = ifft_window * ifft_window
for i in range(n_frames):
sample = i * hop_length
spec = stft_matrix[:, i].flatten()
spec = np.concatenate((spec.conj(), spec[-2:0:-1]), 0)
ytmp = ifft_window * fft.ifft(spec).real
y[sample:(sample + n_fft)] = y[sample:(sample + n_fft)] + ytmp
# shouldn't need to do this sum of the squared window:
#ifft_window_sum[sample:(sample + n_fft)] += ifft_window_square
# don't do this:
## Normalize by sum of squared window
#approx_nonzero_indices = ifft_window_sum > util.SMALL_FLOAT
#y[approx_nonzero_indices] /= ifft_window_sum[approx_nonzero_indices]
if center:
y = y[int(n_fft // 2):-int(n_fft // 2)]
return y
def stft_mc(x,N=1024,hop=None,window=None):
# N=1024
if hop is None:
hop=N/2
S=x.shape
if len(S)==1:
nch=1
nsampl=len(x)
x=np.reshape(x,(1,nsampl))
else:
nch=S[0]
nsampl=S[1]
xdtype=x.dtype
nfram=int(scipy.ceil(float(nsampl)/float(hop)))
npad=int(nfram)*hop-nsampl
pad=np.zeros((nch,npad)).astype(xdtype)
x=np.concatenate((x,pad),axis=1)
#pad the edges to avoid window taper effects
pad=np.zeros((nch,N)).astype(xdtype)
x=np.concatenate((pad,x,pad),axis=1)
for ich in range(0,nch):
x0=x[ich,:]
if not x0.flags.c_contiguous:
x0=x0.copy(order='C')
X0=librosa.core.stft(x0,n_fft=N,hop_length=hop,window=window,center=False,dtype=np.complex64)
if ich==0:
X=np.zeros((N/2+1,X0.shape[1],nch)).astype(np.complex64)
X[:,:,0]=X0
else:
X[:,:,ich]=X0
return X
def istft_mc(X,hop,dtype=np.float32,nsampl=None,flag_noDiv=0,window=None):
#assumes X is of shape F x nfram x nch, where F=Nwin/2+1
#returns xr of shape nch x nsampl
N=2*(X.shape[0]-1)
nch=X.shape[2]
for ich in range(0,nch):
X0=X[:,:,ich]
if flag_noDiv:
x0r=istft_noDiv(X0,hop_length=hop,center=False,window=window,dtype=dtype)
else:
x0r=librosa.core.istft(X0,hop_length=hop,center=False,window=window,dtype=dtype)
if ich==0:
xr=np.zeros((nch,len(x0r))).astype(dtype)
xr[0,:]=x0r
else:
xr[ich,:]=x0r
#trim off extra zeros
nfram=xr.shape[1]
xr=xr[:,0:(nfram-N)]
nfram=xr.shape[1]
xr=xr[:,N:]
if not nsampl is None:
xr=xr[:,0:nsampl]
return xr, N
def AugSTFT(x,N,hop,flag_unwrap_phase,window=None):
F=N/2+1
Xf=stft_mc(x,N,hop=hop,window=window)
Xf=Xf[:,:,0] # take first channel
nfram=Xf.shape[1]
if flag_unwrap_phase:
# remove window hop phases:
Xphase=np.float32(np.unwrap(np.angle(Xf),axis=1))
Xphase_err=np.angle(np.exp(1j*Xphase))-np.angle(Xf)
Xphase=Xphase-Xphase_err #adjust Xphase to minimize errors after wrapping again
frange=np.arange(0,F,dtype=np.float32)/N
trange=np.arange(0,nfram,dtype=np.float32)*hop
Xphase=Xphase-2*np.pi*np.outer(frange,trange)
Xf=np.abs(Xf)*np.exp(1j*Xphase)
Xaug=np.concatenate((np.real(Xf),np.imag(Xf)),axis=0)
return Xaug
def iAugSTFT(X,F,nsrc,flag_unwrap_phase,flag_noDiv=0,window=None,hop=None):
#reconstructs a time series from augmented STFT
#assumes the augmented STFT X is of shape 2*nsrc*nch*F x nfram
#returns xr of shape nsrc x nsampl x nch
Nwin=2*(F-1)
if hop is None:
hop=Nwin/2
n_tot = X.shape[0]
nfram = X.shape[1]
n_reim = n_tot/2
# convert X to complex
Xc = X[:n_reim,:] + 1j*X[n_reim:,:]
nch = Xc.shape[0]/(nsrc*F)
for isrc in range(nsrc):
Xc_src = Xc[(isrc*nch*F):((isrc+1)*nch*F),:]
#Xc_src is nch*F x nfram
Xc_cur = np.reshape(Xc_src,(F,nch,nfram),order='F')
#Xc_cur is now F x nch x nfram
Xc_cur = np.transpose(Xc_cur,(0,2,1))
#Xc_cur is now F x nfram x nch
if flag_unwrap_phase:
# add window hop phases:
Xphase=np.float32( np.angle(Xc_cur) )
frange=np.arange(0,F,dtype=np.float32)/Nwin
trange=np.arange(0,nfram,dtype=np.float32)*np.float32(hop)
Xphase=Xphase+2*np.pi*np.reshape(np.outer(frange,trange),[F,nfram,1])
Xc_cur=np.abs(Xc_cur)*np.exp(1j*Xphase)
xr_cur = istft_mc(Xc_cur,hop,flag_noDiv=flag_noDiv,window=window)
xr_cur = xr_cur[0]
#xr_cur is nch x nsampl
nsampl = xr_cur.shape[1]
if isrc==0:
xr = np.zeros((nsrc,nsampl,nch),dtype=np.float32)
xr[isrc,:,:]=np.transpose(xr_cur,(1,0))
return xr
def load_wavfiles_names(path):
wavfiles=list()
if not isinstance(path,list):
path=[path]
for i in range(len(path)):
path_cur=path[i]
for root, dirs, files in os.walk(path_cur):
for file in files:
if file.endswith(('.wav')):
wavfile=os.path.join(root,file)
wavfiles.append(wavfile)
return wavfiles
def load_files_names(path,pattern):
files_names=list()
if not isinstance(path,list):
path=[path]
for i in range(len(path)):
path_cur=path[i]
for root, dirs, files in os.walk(path_cur):
for file in fnmatch.filter(files,pattern):
file_cur=os.path.join(root,file)
files_names.append(file_cur)
return files_names
def compute_STFTs(wavfiles,params_stft,flag_unwrap_phase=False):
N=params_stft['N']
hop=params_stft['hop']
nch=params_stft['nch']
window=params_stft['window']
F=N/2+1
# initialize matrices to hold concatenated STFTs
#Y=np.zeros((nch*F,0)).astype(np.complex64)
Y=np.zeros((nch*F,2000*len(wavfiles))).astype(np.complex64)
# initialize frame indices for individual files
fidx=np.zeros((len(wavfiles),2)).astype(np.int32)
ifidx=0
ifile=0
for wavfile in wavfiles:
print "Computing STFT for file %d of %d total: %s" % (ifile+1,len(wavfiles),wavfile)
# read in desired output texture
y=wavread(wavfile)
Ycur=stft_mc(y,N,hop,window)
Ycur=Ycur[:,:,:nch] #restrict to desired number of channels
Ycur=np.transpose(Ycur,(0,2,1)) #is now F x nch x nfram
Ycur=np.reshape(Ycur,(nch*F,Ycur.shape[2]),order='F') #stack multiple channels in first dimension
# update frame indices for this file
nfram=Ycur.shape[1]
fidx[ifile,0]=ifidx
ifidx+=nfram
fidx[ifile,1]=ifidx
if flag_unwrap_phase:
# remove window hop phases:
Yphase=np.float32(np.unwrap(np.angle(Ycur),axis=1))
frange=np.arange(0,F,dtype=np.float32)/N
trange=np.arange(0,nfram,dtype=np.float32)*hop
Yphase=Yphase-2*np.pi*np.outer(frange,trange)
Ycur=np.abs(Ycur)*np.exp(1j*Yphase)
# add Y to total data
#Y=np.concatenate((Y,Ycur),axis=1)
Y[:,fidx[ifile,0]:fidx[ifile,1]]=Ycur
ifile+=1
Y=Y[:,0:fidx[-1,1]]
Yaug=np.concatenate((np.real(Y),np.imag(Y)),axis=0)
return Yaug,fidx
def pad_axis_toN_with_constant(x,axis,N,constant):
# build the spec and consts tuples, with elements (0,0)
# except at index 'axis'
spec=[]
consts=[]
ndim=len(x.shape)
for i in range(ndim):
if (i==axis):
spec.append((0,N-x.shape[axis]))
consts.append((0,constant))
else:
spec.append((0,0))
consts.append((0,0))
spec=tuple(spec)
consts=tuple(consts)
#necessary to avoid "'tuple' object has no attribute 'tolist'" error
# https://github.com/numpy/numpy/issues/7353
consts=np.array(consts)
# do the padding the return the result
return np.pad( x,spec,mode='constant',constant_values=consts)