-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSpectrograms.py
2125 lines (1678 loc) · 89.8 KB
/
Spectrograms.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
from torch.nn.functional import conv1d, conv2d
import numpy as np
from time import time
from scipy.signal import get_window
from scipy import signal
from scipy import fft
import warnings
# from librosa_filters import * # Use it for PyPip, and PyTest
# from librosa_filters import * # Use it for debug
from librosa.filters import *
from librosa.util import *
sz_float = 4 # size of a float
epsilon = 10e-8 # fudge factor for normalization
## --------------------------- Filter Design ---------------------------##
def create_lowpass_filter(band_center=0.5, kernelLength=256, transitionBandwidth=0.03):
"""
Calculate the highest frequency we need to preserve and the lowest frequency we allow
to pass through.
Note that frequency is on a scale from 0 to 1 where 0 is 0 and 1 is Nyquist frequency of
the signal BEFORE downsampling.
"""
# transitionBandwidth = 0.03
passbandMax = band_center / (1 + transitionBandwidth)
stopbandMin = band_center * (1 + transitionBandwidth)
# Unlike the filter tool we used online yesterday, this tool does
# not allow us to specify how closely the filter matches our
# specifications. Instead, we specify the length of the kernel.
# The longer the kernel is, the more precisely it will match.
# kernelLength = 256
# We specify a list of key frequencies for which we will require
# that the filter match a specific output gain.
# From [0.0 to passbandMax] is the frequency range we want to keep
# untouched and [stopbandMin, 1.0] is the range we want to remove
keyFrequencies = [0.0, passbandMax, stopbandMin, 1.0]
# We specify a list of output gains to correspond to the key
# frequencies listed above.
# The first two gains are 1.0 because they correspond to the first
# two key frequencies. the second two are 0.0 because they
# correspond to the stopband frequencies
gainAtKeyFrequencies = [1.0, 1.0, 0.0, 0.0]
# This command produces the filter kernel coefficients
filterKernel = signal.firwin2(kernelLength, keyFrequencies, gainAtKeyFrequencies)
return filterKernel.astype(np.float32)
def downsampling_by_n(x, filterKernel, n):
"""A helper function that downsamples the audio by a arbitary factor n.
It is used in CQT2010 and CQT2010v2.
Parameters
----------
x : torch.Tensor
The input waveform in ``torch.Tensor`` type with shape ``(batch, 1, len_audio)``
filterKernel : str
Filter kernel in ``torch.Tensor`` type with shape ``(1, 1, len_kernel)``
n : int
The downsampling factor
Returns
-------
torch.Tensor
The downsampled waveform
Examples
--------
>>> x_down = downsampling_by_n(x, filterKernel)
"""
x = conv1d(x, filterKernel, stride=n, padding=(filterKernel.shape[-1] - 1) // 2)
return x
def downsampling_by_2(x, filterKernel):
"""A helper function that downsamples the audio by half. It is used in CQT2010 and CQT2010v2
Parameters
----------
x : torch.Tensor
The input waveform in ``torch.Tensor`` type with shape ``(batch, 1, len_audio)``
filterKernel : str
Filter kernel in ``torch.Tensor`` type with shape ``(1, 1, len_kernel)``
Returns
-------
torch.Tensor
The downsampled waveform
Examples
--------
>>> x_down = downsampling_by_2(x, filterKernel)
"""
x = conv1d(x, filterKernel, stride=2, padding=(filterKernel.shape[-1] - 1) // 2)
return x
## Basic tools for computation ##
def nextpow2(A):
"""A helper function to calculate the next nearest number to the power of 2.
Parameters
----------
A : float
A float number that is going to be rounded up to the nearest power of 2
Returns
-------
int
The nearest power of 2 to the input number ``A``
Examples
--------
>>> nextpow2(6)
3
"""
return int(np.ceil(np.log2(A)))
## Basic tools for computation ##
def prepow2(A):
"""A helper function to calculate the next nearest number to the power of 2.
Parameters
----------
A : float
A float number that is going to be rounded up to the nearest power of 2
Returns
-------
int
The nearest power of 2 to the input number ``A``
Examples
--------
>>> nextpow2(6)
3
"""
return int(np.floor(np.log2(A)))
def complex_mul(cqt_filter, stft):
"""Since PyTorch does not support complex numbers and its operation.
We need to write our own complex multiplication function. This one is specially
designed for CQT usage.
Parameters
----------
cqt_filter : tuple of torch.Tensor
The tuple is in the format of ``(real_torch_tensor, imag_torch_tensor)``
Returns
-------
tuple of torch.Tensor
The output is in the format of ``(real_torch_tensor, imag_torch_tensor)``
"""
cqt_filter_real = cqt_filter[0]
cqt_filter_imag = cqt_filter[1]
fourier_real = stft[0]
fourier_imag = stft[1]
CQT_real = torch.matmul(cqt_filter_real, fourier_real) - torch.matmul(cqt_filter_imag, fourier_imag)
CQT_imag = torch.matmul(cqt_filter_real, fourier_imag) + torch.matmul(cqt_filter_imag, fourier_real)
return CQT_real, CQT_imag
def broadcast_dim(x):
"""
Auto broadcast input so that it can fits into a Conv1d
"""
if x.dim() == 2:
x = x[:, None, :]
elif x.dim() == 1:
# If nn.DataParallel is used, this broadcast doesn't work
x = x[None, None, :]
elif x.dim() == 3:
pass
else:
raise ValueError("Only support input with shape = (batch, len) or shape = (len)")
return x
def broadcast_dim_conv2d(x):
"""
Auto broadcast input so that it can fits into a Conv2d
"""
if x.dim() == 3:
x = x[:, None, :, :]
else:
raise ValueError("Only support input with shape = (batch, len) or shape = (len)")
return x
## Kernal generation functions ##
def create_fourier_kernels(n_fft, win_length=None, freq_bins=None, fmin=50, fmax=6000, sr=44100,
freq_scale='linear', window='hann', verbose=True):
""" This function creates the Fourier Kernel for STFT, Melspectrogram and CQT.
Most of the parameters follow librosa conventions. Part of the code comes from
pytorch_musicnet. https://github.com/jthickstun/pytorch_musicnet
Parameters
----------
n_fft : int
The window size
freq_bins : int
Number of frequency bins. Default is ``None``, which means ``n_fft//2+1`` bins
fmin : int
The starting frequency for the lowest frequency bin.
If freq_scale is ``no``, this argument does nothing.
fmax : int
The ending frequency for the highest frequency bin.
If freq_scale is ``no``, this argument does nothing.
sr : int
The sampling rate for the input audio. It is used to calculate the correct ``fmin`` and ``fmax``.
Setting the correct sampling rate is very important for calculating the correct frequency.
freq_scale: 'linear', 'log', or 'no'
Determine the spacing between each frequency bin.
When 'linear' or 'log' is used, the bin spacing can be controlled by ``fmin`` and ``fmax``.
If 'no' is used, the bin will start at 0Hz and end at Nyquist frequency with linear spacing.
Returns
-------
wsin : numpy.array
Imaginary Fourier Kernel with the shape ``(freq_bins, 1, n_fft)``
wcos : numpy.array
Real Fourier Kernel with the shape ``(freq_bins, 1, n_fft)``
bins2freq : list
Mapping each frequency bin to frequency in Hz.
binslist : list
The normalized frequency ``k`` in digital domain.
This ``k`` is in the Discrete Fourier Transform equation $$
"""
if freq_bins == None: freq_bins = n_fft // 2 + 1
if win_length == None: win_length = n_fft
s = np.arange(0, n_fft, 1.)
wsin = np.empty((freq_bins, 1, n_fft))
wcos = np.empty((freq_bins, 1, n_fft))
start_freq = fmin
end_freq = fmax
bins2freq = []
binslist = []
# num_cycles = start_freq*d/44000.
# scaling_ind = np.log(end_freq/start_freq)/k
# Choosing window shape
window_mask = get_window(window, int(win_length), fftbins=True)
window_mask = pad_center(window_mask, n_fft)
if freq_scale == 'linear':
if verbose == True:
print(f"sampling rate = {sr}. Please make sure the sampling rate is correct in order to"
f"get a valid freq range")
start_bin = start_freq * n_fft / sr
scaling_ind = (end_freq - start_freq) * (n_fft / sr) / freq_bins
for k in range(freq_bins): # Only half of the bins contain useful info
# print("linear freq = {}".format((k*scaling_ind+start_bin)*sr/n_fft))
bins2freq.append((k * scaling_ind + start_bin) * sr / n_fft)
binslist.append((k * scaling_ind + start_bin))
wsin[k, 0, :] = window_mask * np.sin(2 * np.pi * (k * scaling_ind + start_bin) * s / n_fft)
wcos[k, 0, :] = window_mask * np.cos(2 * np.pi * (k * scaling_ind + start_bin) * s / n_fft)
elif freq_scale == 'log':
if verbose == True:
print(f"sampling rate = {sr}. Please make sure the sampling rate is correct in order to"
f"get a valid freq range")
start_bin = start_freq * n_fft / sr
scaling_ind = np.log(end_freq / start_freq) / freq_bins
for k in range(freq_bins): # Only half of the bins contain useful info
# print("log freq = {}".format(np.exp(k*scaling_ind)*start_bin*sr/n_fft))
bins2freq.append(np.exp(k * scaling_ind) * start_bin * sr / n_fft)
binslist.append((np.exp(k * scaling_ind) * start_bin))
wsin[k, 0, :] = window_mask * np.sin(2 * np.pi * (np.exp(k * scaling_ind) * start_bin) * s / n_fft)
wcos[k, 0, :] = window_mask * np.cos(2 * np.pi * (np.exp(k * scaling_ind) * start_bin) * s / n_fft)
elif freq_scale == 'no':
for k in range(freq_bins): # Only half of the bins contain useful info
bins2freq.append(k * sr / n_fft)
binslist.append(k)
wsin[k, 0, :] = window_mask * np.sin(2 * np.pi * k * s / n_fft)
wcos[k, 0, :] = window_mask * np.cos(2 * np.pi * k * s / n_fft)
else:
print("Please select the correct frequency scale, 'linear' or 'log'")
return wsin.astype(np.float32), wcos.astype(np.float32), bins2freq, binslist, window_mask
def create_cqt_kernels(Q, fs, fmin, n_bins=84, bins_per_octave=12, norm=1,
window='hann', fmax=None, topbin_check=True):
"""
Automatically create CQT kernels and convert it to frequency domain
"""
# norm arg is not functioning
fftLen = 2 ** nextpow2(np.ceil(Q * fs / fmin))
# minWin = 2**nextpow2(np.ceil(Q * fs / fmax))
if (fmax != None) and (n_bins == None):
n_bins = np.ceil(bins_per_octave * np.log2(fmax / fmin)) # Calculate the number of bins
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
elif (fmax == None) and (n_bins != None):
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
else:
warnings.warn('If fmax is given, n_bins will be ignored', SyntaxWarning)
n_bins = np.ceil(bins_per_octave * np.log2(fmax / fmin)) # Calculate the number of bins
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
if np.max(freqs) > fs / 2 and topbin_check == True:
raise ValueError('The top bin {}Hz has exceeded the Nyquist frequency, \
please reduce the n_bins'.format(np.max(freqs)))
tempKernel = np.zeros((int(n_bins), int(fftLen)), dtype=np.complex64)
specKernel = np.zeros((int(n_bins), int(fftLen)), dtype=np.complex64)
for k in range(0, int(n_bins)):
freq = freqs[k]
l = np.ceil(Q * fs / freq)
lenghts = np.ceil(Q * fs / freqs)
# Centering the kernels
if l % 2 == 1: # pad more zeros on RHS
start = int(np.ceil(fftLen / 2.0 - l / 2.0)) - 1
else:
start = int(np.ceil(fftLen / 2.0 - l / 2.0))
sig = get_window(window, int(l), fftbins=True) * np.exp(np.r_[-l // 2:l // 2] * 1j * 2 * np.pi * freq / fs) / l
if norm: # Normalizing the filter # Trying to normalize like librosa
tempKernel[k, start:start + int(l)] = sig / np.linalg.norm(sig, norm)
else:
tempKernel[k, start:start + int(l)] = sig
# specKernel[k, :] = fft(tempKernel[k])
# return specKernel[:,:fftLen//2+1], fftLen, torch.tensor(lenghts).float()
return tempKernel, fftLen, torch.tensor(lenghts).float()
def create_cqt_kernels_t(Q, fs, fmin, n_bins=84, bins_per_octave=12, norm=1,
window='hann', fmax=None):
"""
Create cqt kernels in time-domain
"""
# norm arg is not functioning
fftLen = 2 ** nextpow2(np.ceil(Q * fs / fmin))
# minWin = 2**nextpow2(np.ceil(Q * fs / fmax))
if (fmax != None) and (n_bins == None):
n_bins = np.ceil(bins_per_octave * np.log2(fmax / fmin)) # Calculate the number of bins
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
elif (fmax == None) and (n_bins != None):
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
else:
warnings.warn('If fmax is given, n_bins will be ignored', SyntaxWarning)
n_bins = np.ceil(bins_per_octave * np.log2(fmax / fmin)) # Calculate the number of bins
freqs = fmin * 2.0 ** (np.r_[0:n_bins] / np.float(bins_per_octave))
if np.max(freqs) > fs / 2:
raise ValueError('The top bin {}Hz has exceeded the Nyquist frequency, \
please reduce the n_bins'.format(np.max(freqs)))
tempKernel = np.zeros((int(n_bins), int(fftLen)), dtype=np.complex64)
specKernel = np.zeros((int(n_bins), int(fftLen)), dtype=np.complex64)
for k in range(0, int(n_bins)):
freq = freqs[k]
l = np.ceil(Q * fs / freq)
lenghts = np.ceil(Q * fs / freqs)
# Centering the kernels
if l % 2 == 1: # pad more zeros on RHS
start = int(np.ceil(fftLen / 2.0 - l / 2.0)) - 1
else:
start = int(np.ceil(fftLen / 2.0 - l / 2.0))
sig = get_window(window, int(l), fftbins=True) * np.exp(np.r_[-l // 2:l // 2] * 1j * 2 * np.pi * freq / fs) / l
if norm: # Normalizing the filter # Trying to normalize like librosa
tempKernel[k, start:start + int(l)] = sig / np.linalg.norm(sig, norm)
else:
tempKernel[k, start:start + int(l)] = sig
# specKernel[k, :]=fft(conj(tempKernel[k, :]))
return tempKernel, fftLen, torch.tensor(lenghts).float()
### --------------------------- Spectrogram Classes ---------------------------###
class STFT(torch.nn.Module):
"""This function is to calculate the short-time Fourier transform (STFT) of the input signal.
Input signal should be in either of the following shapes.
1. ``(len_audio)``
2. ``(num_audio, len_audio)``
3. ``(num_audio, 1, len_audio)``
The correct shape will be inferred automatically if the input follows these 3 shapes.
Most of the arguments follow the convention from librosa.
This class inherits from ``torch.nn.Module``, therefore, the usage is same as ``torch.nn.Module``.
Parameters
----------
n_fft : int
The window size. Default value is 2048.
freq_bins : int
Number of frequency bins. Default is ``None``, which means ``n_fft//2+1`` bins
hop_length : int
The hop (or stride) size. Default value is 512.
window : str
The windowing function for STFT. It uses ``scipy.signal.get_window``, please refer to
scipy documentation for possible windowing functions. The default value is 'hann'.
freq_scale : 'linear', 'log', or 'no'
Determine the spacing between each frequency bin. When `linear` or `log` is used,
the bin spacing can be controlled by ``fmin`` and ``fmax``. If 'no' is used, the bin will
start at 0Hz and end at Nyquist frequency with linear spacing.
center : bool
Putting the STFT keneral at the center of the time-step or not. If ``False``, the time
index is the beginning of the STFT kernel, if ``True``, the time index is the center of
the STFT kernel. Default value if ``True``.
pad_mode : str
The padding method. Default value is 'reflect'.
fmin : int
The starting frequency for the lowest frequency bin. If freq_scale is ``no``, this argument
does nothing.
fmax : int
The ending frequency for the highest frequency bin. If freq_scale is ``no``, this argument
does nothing.
sr : int
The sampling rate for the input audio. It is used to calucate the correct ``fmin`` and ``fmax``.
Setting the correct sampling rate is very important for calculating the correct frequency.
trainable : bool
Determine if the STFT kenrels are trainable or not. If ``True``, the gradients for STFT
kernels will also be caluclated and the STFT kernels will be updated during model training.
Default value is ``False``
verbose : bool
If ``True``, it shows layer information. If ``False``, it suppresses all prints
device : str
Choose which device to initialize this layer. Default value is 'cuda:0'
Returns
-------
spectrogram : torch.tensor
It returns a tensor of spectrograms.
shape = ``(num_samples, freq_bins,time_steps)`` if ``output_format``='Magnitude';
shape = ``(num_samples, freq_bins,time_steps, 2)`` if ``output_format``='Complex' or 'Phase';
Examples
--------
>>> spec_layer = Spectrogram.STFT()
>>> specs = spec_layer(x)
"""
def __init__(self, n_fft=2048, win_length=None, freq_bins=None, hop_length=None, window='hann',
freq_scale='no', center=True, pad_mode='reflect',
fmin=50, fmax=6000, sr=22050, trainable=False,
verbose=True, device='cuda:0'):
super(STFT, self).__init__()
# Trying to make the default setting same as librosa
if win_length == None: win_length = n_fft
if hop_length == None: hop_length = int(win_length // 4)
self.trainable = trainable
self.stride = hop_length
self.center = center
self.pad_mode = pad_mode
self.n_fft = n_fft
self.freq_bins = freq_bins
self.trainable = trainable
self.device = device
self.pad_amount = self.n_fft // 2
self.window = window
self.win_length = win_length
start = time()
# Create filter windows for stft
wsin, wcos, self.bins2freq, self.bin_list, window_mask = create_fourier_kernels(n_fft,
win_length=win_length,
freq_bins=freq_bins,
window=window,
freq_scale=freq_scale,
fmin=fmin,
fmax=fmax,
sr=sr,
verbose=verbose)
# Create filter windows for inverse
wsin_inv, wcos_inv, _, _, _ = create_fourier_kernels(n_fft,
win_length=win_length,
freq_bins=n_fft,
window='ones',
freq_scale=freq_scale,
fmin=fmin,
fmax=fmax,
sr=sr,
verbose=False)
self.wsin = torch.tensor(wsin, dtype=torch.float, device=self.device)
self.wcos = torch.tensor(wcos, dtype=torch.float, device=self.device)
self.wsin_inv = torch.tensor(wsin_inv, dtype=torch.float, device=self.device)
self.wcos_inv = torch.tensor(wcos_inv, dtype=torch.float, device=self.device)
# Making all these variables nn.Parameter, so that the model can be used with nn.Parallel
self.wsin = torch.nn.Parameter(self.wsin, requires_grad=self.trainable)
self.wcos = torch.nn.Parameter(self.wcos, requires_grad=self.trainable)
self.wsin_inv = torch.nn.Parameter(self.wsin_inv, requires_grad=self.trainable)
self.wcos_inv = torch.nn.Parameter(self.wcos_inv, requires_grad=self.trainable)
self.window_mask = torch.tensor(window_mask, device=self.device).unsqueeze(0).unsqueeze(-1)
if verbose == True:
print("STFT kernels created, time used = {:.4f} seconds".format(time() - start))
else:
pass
def forward(self, x, output_format='Complex'):
self.output_format = output_format
self.num_samples = x.shape[-1]
x = broadcast_dim(x)
if self.center:
if self.pad_mode == 'constant':
padding = nn.ConstantPad1d(self.pad_amount, 0)
elif self.pad_mode == 'reflect':
if self.num_samples < self.pad_amount:
raise AssertionError("Signal length shorter than reflect padding length (n_fft // 2).")
padding = nn.ReflectionPad1d(self.pad_amount)
x = padding(x)
spec_imag = conv1d(x, self.wsin, stride=self.stride)
spec_real = conv1d(x, self.wcos, stride=self.stride) # Doing STFT by using conv1d
# remove redundant parts
spec_real = spec_real[:, :self.freq_bins, :]
spec_imag = spec_imag[:, :self.freq_bins, :]
if output_format == 'Magnitude':
self.output_format = 'Magnitude'
spec = spec_real.pow(2) + spec_imag.pow(2)
if self.trainable == True:
return torch.sqrt(spec + 1e-8) # prevent Nan gradient when sqrt(0) due to output=0
else:
return torch.sqrt(spec + 1e-8)
elif output_format == 'Complex':
self.output_format = 'Complex'
return torch.stack((spec_real, -spec_imag), -1) # Remember the minus sign for imaginary part
elif output_format == 'Phase':
self.output_format = 'Phase'
return torch.atan2(-spec_imag + 0.0,
spec_real) # +0.0 removes -0.0 elements, which leads to error in calculating phase
def inverse(self, X, num_samples=-1):
if len(X.shape) == 3 and self.output_format == 'Magnitude':
return self.griffin_lim(X)
elif len(X.shape) == 4 and self.output_format == "Complex":
return self.__inverse(X, num_samples=num_samples)
else:
raise AssertionError("Only perform inverse function on Magnitude or Complex spectrogram.")
def __inverse(self, X, is_window_normalized=True, num_samples=None):
X_real, X_imag = X[:, :, :, 0], X[:, :, :, 1]
# flip and extend beyond Nyquist frequency
X_real_nyquist = torch.flip(X_real, [1])
X_imag_nyquist = torch.flip(X_imag, [1])
X_real_nyquist = X_real_nyquist[:, 1:-1, :]
X_imag_nyquist = -X_imag_nyquist[:, 1:-1, :]
X_real = torch.cat([X_real, X_real_nyquist], axis=1)
X_imag = torch.cat([X_imag, X_imag_nyquist], axis=1)
# broadcast dimensions to support 2D convolution
X_real_bc = X_real.unsqueeze(1)
X_imag_bc = X_imag.unsqueeze(1)
wsin_bc = self.wsin_inv.unsqueeze(-1)
wcos_bc = self.wcos_inv.unsqueeze(-1)
a1 = conv2d(X_real_bc, wcos_bc, stride=(1, 1))
b2 = conv2d(X_imag_bc, wsin_bc, stride=(1, 1))
# compute real and imag part. signal lies in the real part
real = a1 - b2
real = real.squeeze(-2)
# each time step contains reconstructed signal, hence we stitch them together and remove
# the repeated segments due to overlapping windows during STFT when hop_size < n_fft
if is_window_normalized:
# nonzero_indices = self.window_mask[0,:,0]>1e-6 # it doesn't work
real /= self.window_mask
real /= self.n_fft
# It doesn't work if we keep the last time-step as a whole.
# Since the erroneous part is on the LHS of the window, we better chop them out
real_first = real[:, :, 0] # get the complet first frame
real_split = real[:, -self.stride:, 1:] # remove redundant samples at overlapped parts
# reshape output signal to 1D
output_signal = torch.reshape(torch.transpose(real_split, 2, 1), (real_split.shape[0], -1))
output_signal = torch.cat([real_first, output_signal], dim=-1) # stich the first signal back
output_signal = output_signal[:, self.pad_amount:] # remove padding on LHS
if num_samples:
output_signal = output_signal[:, :num_samples]
else:
output_signal = output_signal[:, :-self.pad_amount]
return output_signal
def griffin_lim(self, X, maxiter=32, tol=1e-6, alpha=0.99, verbose=False, phase=None):
# only use griffin lim when X is not in complex form
if phase is None:
phase = torch.rand_like(X) * 2 - 1
phase = phase * np.pi
phase[:, 0, :] = 0.0
phase = nn.Parameter(phase)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam([phase], lr=9e-1)
for idx in range(maxiter):
optimizer.zero_grad()
X_real, X_imag = X * torch.cos(phase), X * torch.sin(phase)
X_cur = torch.stack([X_real, X_imag], dim=-1)
inverse_signal = self.__inverse(X_cur, is_window_normalized=False)
# Rebuild the spectrogram
rebuilt_mag = self.forward(inverse_signal, output_format="Complex")
rebuilt_mag = torch.sqrt(rebuilt_mag[:, :, :, 0].pow(2) + rebuilt_mag[:, :, :, 1].pow(2))
loss = criterion(rebuilt_mag, X)
loss.backward()
optimizer.step()
if verbose:
print("Run: {}/{} MSE: {:.4}".format(idx + 1, maxiter, criterion(rebuilt_mag, X).item()))
# Return the final phase estimates
X_real, X_imag = X * torch.cos(phase), X * torch.sin(phase)
X_cur = torch.stack([X_real, X_imag], dim=-1)
return self.__inverse(X_cur, is_window_normalized=False)
class MelSpectrogram(torch.nn.Module):
"""This function is to calculate the Melspectrogram of the input signal.
Input signal should be in either of the following shapes.
1. ``(len_audio)``
2. ``(num_audio, len_audio)``
3. ``(num_audio, 1, len_audio)``.
The correct shape will be inferred automatically if the input follows these 3 shapes.
Most of the arguments follow the convention from librosa.
This class inherits from ``torch.nn.Module``, therefore, the usage is same as ``torch.nn.Module``.
Parameters
----------
sr : int
The sampling rate for the input audio.
It is used to calculate the correct ``fmin`` and ``fmax``.
Setting the correct sampling rate is very important for calculating the correct frequency.
n_fft : int
The window size for the STFT. Default value is 2048
n_mels : int
The number of Mel filter banks. The filter banks maps the n_fft to mel bins.
Default value is 128.
hop_length : int
The hop (or stride) size. Default value is 512.
window : str
The windowing function for STFT. It uses ``scipy.signal.get_window``, please refer to
scipy documentation for possible windowing functions. The default value is 'hann'.
center : bool
Putting the STFT keneral at the center of the time-step or not. If ``False``,
the time index is the beginning of the STFT kernel, if ``True``, the time index is the
center of the STFT kernel. Default value if ``True``.
pad_mode : str
The padding method. Default value is 'reflect'.
htk : bool
When ``False`` is used, the Mel scale is quasi-logarithmic. When ``True`` is used, the
Mel scale is logarithmic. The default value is ``False``.
fmin : int
The starting frequency for the lowest Mel filter bank.
fmax : int
The ending frequency for the highest Mel filter bank.
trainable_mel : bool
Determine if the Mel filter banks are trainable or not. If ``True``, the gradients for Mel
filter banks will also be calculated and the Mel filter banks will be updated during model
training. Default value is ``False``.
trainable_STFT : bool
Determine if the STFT kenrels are trainable or not. If ``True``, the gradients for STFT
kernels will also be caluclated and the STFT kernels will be updated during model training.
Default value is ``False``.
verbose : bool
If ``True``, it shows layer information. If ``False``, it suppresses all prints.
device : str
Choose which device to initialize this layer. Default value is 'cuda:0'.
Returns
-------
spectrogram : torch.tensor
It returns a tensor of spectrograms. shape = ``(num_samples, freq_bins,time_steps)``.
Examples
--------
>>> spec_layer = Spectrogram.MelSpectrogram()
>>> specs = spec_layer(x)
"""
def __init__(self, sr=22050, n_fft=2048, n_mels=128, hop_length=512,
window='hann', center=True, pad_mode='reflect', power=2.0, htk=False,
fmin=0.0, fmax=None, norm=1, trainable_mel=False, trainable_STFT=False,
verbose=True, device='cuda:0'):
super(MelSpectrogram, self).__init__()
self.stride = hop_length
self.center = center
self.pad_mode = pad_mode
self.n_fft = n_fft
self.device = device
self.power = power
# Create filter windows for stft
start = time()
wsin, wcos, self.bins2freq, _, _ = create_fourier_kernels(n_fft=n_fft,
freq_bins=None,
window=window,
freq_scale='no',
sr=sr)
self.wsin = torch.tensor(wsin, dtype=torch.float, device=self.device)
self.wcos = torch.tensor(wcos, dtype=torch.float, device=self.device)
# Creating kernel for mel spectrogram
start = time()
mel_basis = mel(sr, n_fft, n_mels, fmin, fmax, htk=htk, norm=norm)
self.mel_basis = torch.tensor(mel_basis, device=self.device)
if verbose == True:
print("STFT filter created, time used = {:.4f} seconds".format(time() - start))
print("Mel filter created, time used = {:.4f} seconds".format(time() - start))
else:
pass
# Making everything nn.Parameter, so that this model can support nn.DataParallel
self.mel_basis = torch.nn.Parameter(self.mel_basis, requires_grad=trainable_mel)
self.wsin = torch.nn.Parameter(self.wsin, requires_grad=trainable_STFT)
self.wcos = torch.nn.Parameter(self.wcos, requires_grad=trainable_STFT)
# if trainable_mel==True:
# self.mel_basis = torch.nn.Parameter(self.mel_basis)
# if trainable_STFT==True:
# self.wsin = torch.nn.Parameter(self.wsin)
# self.wcos = torch.nn.Parameter(self.wcos)
def forward(self, x):
x = broadcast_dim(x)
if self.center:
if self.pad_mode == 'constant':
padding = nn.ConstantPad1d(self.n_fft // 2, 0)
elif self.pad_mode == 'reflect':
padding = nn.ReflectionPad1d(self.n_fft // 2)
x = padding(x)
spec = torch.sqrt(conv1d(x, self.wsin, stride=self.stride).pow(2) \
+ conv1d(x, self.wcos, stride=self.stride).pow(2)) ** self.power # Doing STFT by using conv1d
melspec = torch.matmul(self.mel_basis.float(), spec.float())
return melspec
class MFCC(torch.nn.Module):
"""This function is to calculate the Mel-frequency cepstral coefficients (MFCCs) of the input signal.
It only support type-II DCT at the moment. Input signal should be in either of the following shapes.
1. ``(len_audio)``
2. ``(num_audio, len_audio)``
3. ``(num_audio, 1, len_audio)``
The correct shape will be inferred autommatically if the input follows these 3 shapes.
Most of the arguments follow the convention from librosa.
This class inherits from ``torch.nn.Module``, therefore, the usage is same as ``torch.nn.Module``.
Parameters
----------
sr : int
The sampling rate for the input audio. It is used to calculate the correct ``fmin`` and ``fmax``.
Setting the correct sampling rate is very important for calculating the correct frequency.
n_mfcc : int
The number of Mel-frequency cepstral coefficients
norm : string
The default value is 'ortho'. Normalization for DCT basis
**kwargs
Other arguments for Melspectrogram such as n_fft, n_mels, hop_length, and window
Returns
-------
MFCCs : torch.tensor
It returns a tensor of MFCCs. shape = ``(num_samples, n_mfcc, time_steps)``.
Examples
--------
>>> spec_layer = Spectrogram.MFCC()
>>> mfcc = spec_layer(x)
"""
def __init__(self, sr=22050, n_mfcc=20, norm='ortho', device='cuda:0', verbose=True, **kwargs):
super(MFCC, self).__init__()
self.melspec_layer = MelSpectrogram(sr=sr, verbose=verbose, device=device, **kwargs)
self.p2d = self.power_to_db(device=device)
self.m_mfcc = n_mfcc
def forward(self, x):
x = self.melspec_layer(x)
x = self.p2d.forward(x)
x = self.dct(x, norm='ortho')[:, :self.m_mfcc, :]
return x
class power_to_db():
'''
Refer to https://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#power_to_db
for the original implmentation.
'''
def __init__(self, ref=1.0, amin=1e-10, top_db=80.0, device='cuda:0'):
if amin <= 0:
raise ParameterError('amin must be strictly positive')
self.amin = torch.tensor([amin], device=device)
self.ref = torch.abs(torch.tensor([ref], device=device))
self.top_db = top_db
def forward(self, S):
log_spec = 10.0 * torch.log10(torch.max(S, self.amin))
log_spec -= 10.0 * torch.log10(torch.max(self.amin, self.ref))
if self.top_db is not None:
if self.top_db < 0:
raise ParameterError('top_db must be non-negative')
# make the dim same as log_spec so that it can be broadcasted
batch_wise_max = log_spec.flatten(1).max(1)[0].unsqueeze(1).unsqueeze(1)
log_spec = torch.max(log_spec, batch_wise_max - self.top_db)
return log_spec
def dct(self, x, norm=None):
'''
Refer to https://github.com/zh217/torch-dct for the original implmentation.
'''
x = x.permute(0, 2, 1) # make freq the last axis, since dct applies to the frequency axis
x_shape = x.shape
N = x_shape[-1]
v = torch.cat([x[:, :, ::2], x[:, :, 1::2].flip([2])], dim=2)
Vc = torch.rfft(v, 1, onesided=False)
k = - torch.arange(N, dtype=x.dtype, device=x.device)[None, :] * np.pi / (2 * N)
W_r = torch.cos(k)
W_i = torch.sin(k)
V = Vc[:, :, :, 0] * W_r - Vc[:, :, :, 1] * W_i
if norm == 'ortho':
V[:, :, 0] /= np.sqrt(N) * 2
V[:, :, 1:] /= np.sqrt(N / 2) * 2
V = 2 * V
return V.permute(0, 2, 1) # swapping back the time axis and freq axis
class CQT1992(torch.nn.Module):
def __init__(self, sr=22050, hop_length=512, fmin=220, fmax=None, n_bins=84,
bins_per_octave=12, norm=1, window='hann', center=True, pad_mode='reflect',
device="cuda:0"):
super(CQT1992, self).__init__()
# norm arg is not functioning
self.hop_length = hop_length
self.center = center
self.pad_mode = pad_mode
self.norm = norm
self.device = device
# creating kernels for CQT
Q = 1 / (2 ** (1 / bins_per_octave) - 1)
print("Creating CQT kernels ...", end='\r')
start = time()
self.cqt_kernels, self.kernal_width, self.lenghts = create_cqt_kernels(Q,
sr,
fmin,
n_bins,
bins_per_octave,
norm,
window,
fmax)
self.lenghts = self.lenghts.to(device)
self.cqt_kernels = fft(self.cqt_kernels)[:, :self.kernal_width // 2 + 1]
self.cqt_kernels_real = torch.tensor(self.cqt_kernels.real.astype(np.float32), device=device)
self.cqt_kernels_imag = torch.tensor(self.cqt_kernels.imag.astype(np.float32), device=device)
print("CQT kernels created, time used = {:.4f} seconds".format(time() - start))
# creating kernels for stft
# self.cqt_kernels_real*=lenghts.unsqueeze(1)/self.kernal_width # Trying to normalize as librosa
# self.cqt_kernels_imag*=lenghts.unsqueeze(1)/self.kernal_width
print("Creating STFT kernels ...", end='\r')
start = time()
wsin, wcos, self.bins2freq, _ = create_fourier_kernels(self.kernal_width,
window='ones',
freq_scale='no')
self.wsin = torch.tensor(wsin, device=device)
self.wcos = torch.tensor(wcos, device=device)
print("STFT kernels created, time used = {:.4f} seconds".format(time() - start))
def forward(self, x):
x = broadcast_dim(x)
if self.center:
if self.pad_mode == 'constant':
padding = nn.ConstantPad1d(self.kernal_width // 2, 0)
elif self.pad_mode == 'reflect':
padding = nn.ReflectionPad1d(self.kernal_width // 2)
x = padding(x)
# STFT
fourier_real = conv1d(x, self.wcos, stride=self.hop_length)
fourier_imag = conv1d(x, self.wsin, stride=self.hop_length)
# CQT
CQT_real, CQT_imag = complex_mul((self.cqt_kernels_real, self.cqt_kernels_imag),
(fourier_real, fourier_imag))