forked from Js-Mim/ASP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTFMethods.py
1336 lines (1105 loc) · 51.5 KB
/
TFMethods.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
# -*- coding: utf-8 -*-
__author__ = 'S.I. Mimilakis'
__copyright__ = 'MacSeNet'
import math, sys, os
import numpy as np
from scipy.fftpack import fft, ifft, dct, dst
from scipy.signal import firwin2, freqz, cosine, hanning, hamming, fftconvolve
from scipy.interpolate import InterpolatedUnivariateSpline as uspline
try :
from QMF import qmf_realtime_class as qrf
except ImportError :
print('PQMF class was not found. ')
eps = np.finfo(np.float32).tiny
class TimeFrequencyDecomposition:
""" A Class that performs time-frequency decompositions by means of a
Discrete Fourier Transform, using Fast Fourier Transform algorithm
by SciPy, MDCT with modified type IV bases, PQMF,
and Fractional Fast Fourier Transform.
"""
@staticmethod
def DFT(x, w, N):
""" Discrete Fourier Transformation(Analysis) of a given real input signal
via an FFT implementation from scipy. Single channel is being supported.
Args:
x : (array) Real time domain input signal
w : (array) Desired windowing function
N : (int) FFT size
Returns:
magX : (2D ndarray) Magnitude Spectrum
phsX : (2D ndarray) Phase Spectrum
"""
# Half spectrum size containing DC component
hlfN = (N/2)+1
# Half window size. Two parameters to perform zero-phase windowing technique
hw1 = int(math.floor((w.size+1)/2))
hw2 = int(math.floor(w.size/2))
# Window the input signal
winx = x*w
# Initialize FFT buffer with zeros and perform zero-phase windowing
fftbuffer = np.zeros(N)
fftbuffer[:hw1] = winx[hw2:]
fftbuffer[-hw2:] = winx[:hw2]
# Compute DFT via scipy's FFT implementation
X = fft(fftbuffer)
# Acquire magnitude and phase spectrum
magX = (np.abs(X[:hlfN]))
phsX = (np.angle(X[:hlfN]))
return magX, phsX
@staticmethod
def iDFT(magX, phsX, wsz):
""" Discrete Fourier Transformation(Synthesis) of a given spectral analysis
via an inverse FFT implementation from scipy.
Args:
magX : (2D ndarray) Magnitude Spectrum
phsX : (2D ndarray) Phase Spectrum
wsz : (int) Synthesis window size
Returns:
y : (array) Real time domain output signal
"""
# Get FFT Size
hlfN = magX.size;
N = (hlfN-1)*2
# Half of window size parameters
hw1 = int(math.floor((wsz+1)/2))
hw2 = int(math.floor(wsz/2))
# Initialise synthesis buffer with zeros
fftbuffer = np.zeros(N)
# Initialise output spectrum with zeros
Y = np.zeros(N, dtype = complex)
# Initialise output array with zeros
y = np.zeros(wsz)
# Compute complex spectrum(both sides) in two steps
Y[0:hlfN] = magX * np.exp(1j*phsX)
Y[hlfN:] = magX[-2:0:-1] * np.exp(-1j*phsX[-2:0:-1])
# Perform the iDFT
fftbuffer = np.real(ifft(Y))
# Roll-back the zero-phase windowing technique
y[:hw2] = fftbuffer[-hw2:]
y[hw2:] = fftbuffer[:hw1]
return y
@staticmethod
def STFT(x, w, N, hop):
""" Short Time Fourier Transform analysis of a given real input signal,
via the above DFT method.
Args:
x : (array) Time-domain signal
w : (array) Desired windowing function
N : (int) FFT size
hop : (int) Hop size
Returns:
sMx : (2D ndarray) Stacked arrays of magnitude spectra
sPx : (2D ndarray) Stacked arrays of phase spectra
"""
# Analysis Parameters
wsz = w.size
# Add some zeros at the start and end of the signal to avoid window smearing
x = np.append(np.zeros(3*hop),x)
x = np.append(x, np.zeros(3*hop))
# Initialize sound pointers
pin = 0
pend = x.size - wsz
indx = 0
# Normalise windowing function
if np.sum(w)!= 0. :
w = w / np.sum(w)
# Initialize storing matrix
xmX = np.zeros((len(x)/hop, N/2 + 1), dtype = np.float32)
xpX = np.zeros((len(x)/hop, N/2 + 1), dtype = np.float32)
# Analysis Loop
while pin <= pend:
# Acquire Segment
xSeg = x[pin:pin+wsz]
# Perform DFT on segment
mcX, pcX = TimeFrequencyDecomposition.DFT(xSeg, w, N)
xmX[indx, :] = mcX
xpX[indx, :] = pcX
# Update pointers and indices
pin += hop
indx += 1
return xmX, xpX
@staticmethod
def GLA(wsz, hop):
""" LSEE-MSTFT algorithm for computing the synthesis window used in
inverse STFT method below.
Args:
wsz : (int) Synthesis window size
hop : (int) Hop size
Returns :
symw: (array) Synthesised windowing function
References :
[1] Daniel W. Griffin and Jae S. Lim, ``Signal estimation from modified short-time
Fourier transform,'' IEEE Transactions on Acoustics, Speech and Signal Processing,
vol. 32, no. 2, pp. 236-243, Apr 1984.
"""
synw = hamming(wsz)/np.sum(hamming(wsz))
synwProd = synw ** 2.
synwProd.shape = (wsz, 1)
redundancy = wsz/hop
env = np.zeros((wsz, 1))
for k in xrange(-redundancy, redundancy + 1):
envInd = (hop*k)
winInd = np.arange(1, wsz+1)
envInd += winInd
valid = np.where((envInd > 0) & (envInd <= wsz))
envInd = envInd[valid] - 1
winInd = winInd[valid] - 1
env[envInd] += synwProd[winInd]
synw = synw/env[:, 0]
return synw
@staticmethod
def iSTFT(xmX, xpX, wsz, hop, smt = False) :
""" Short Time Fourier Transform synthesis of given magnitude and phase spectra,
via the above iDFT method.
Args:
xmX : (2D ndarray) Magnitude spectrum
xpX : (2D ndarray) Phase spectrum
wsz : (int) Synthesis window size
hop : (int) Hop size
smt : (bool) Whether or not use a post-processing step in time domain
signal recovery, using synthesis windows.
Returns :
y : (array) Synthesised time-domain real signal.
"""
# GL-Algorithm or simple OLA
if smt == True:
rs = TimeFrequencyDecomposition.GLA(wsz, hop)
else :
rs = hop
# Acquire half window sizes
hw1 = int(math.floor((wsz+1)/2))
hw2 = int(math.floor(wsz/2))
# Acquire the number of STFT frames
numFr = xmX.shape[0]
# Initialise output array with zeros
y = np.zeros(numFr * hop + hw1 + hw2)
# Initialise sound pointer
pin = 0
# Main Synthesis Loop
for indx in range(numFr):
# Inverse Discrete Fourier Transform
ybuffer = TimeFrequencyDecomposition.iDFT(xmX[indx, :], xpX[indx, :], wsz)
# Overlap and Add
y[pin:pin+wsz] += ybuffer*rs
# Advance pointer
pin += hop
# Delete the extra zeros that the analysis had placed
y = np.delete(y, range(3*hop))
y = np.delete(y, range(y.size-(3*hop + 1), y.size))
return y
@staticmethod
def MCSTFT(x, w, N, hop):
""" Short Time Fourier Transform analysis of a given real input signal,
over multiple channels.
Args:
x : (2D array) Multichannel time-domain signal (nsamples x nchannels)
w : (array) Desired windowing function
N : (int) FFT size
hop : (int) Hop size
Returns:
sMx : (3D ndarray) Stacked arrays of magnitude spectra
sPx : (3D ndarray) Stacked arrays of phase spectra
Of the shape (Channels x Frequency-samples x Time-frames)
"""
M = x.shape[1] # Number of channels
# Analyse the first incoming channel to acquire the dimensions
mX, pX = TimeFrequencyDecomposition.STFT(x[:, 0], w, N, hop)
smX = np.zeros((M, mX.shape[1], mX.shape[0]), dtype = np.float32)
spX = np.zeros((M, pX.shape[1], pX.shape[0]), dtype = np.float32)
# Storing it to the actual return and free up some memory
smX[0, :, :] = mX.T
spX[0, :, :] = pX.T
del mX, pX
for channel in xrange(1, M):
mX, pX = TimeFrequencyDecomposition.STFT(x[:, channel], w, N, hop)
smX[channel, :, :] = mX.T
spX[channel, :, :] = pX.T
del mX, pX
return smX, spX
@staticmethod
def MCiSTFT(xmX, xpX, wsz, hop, smt = False):
""" Short Time Fourier Transform synthesis of given magnitude and phase spectra
over multiple channels.
Args:
xMx : (3D ndarray) Stacked arrays of magnitude spectra
xPx : (3D ndarray) Stacked arrays of phase spectra
Of the shape (Channels x Frequency samples x Time-frames)
wsz : (int) Synthesis Window size
hop : (int) Hop size
smt : (bool) Whether or not use a post-processing step in time domain
signal recovery, using synthesis windows
Returns :
y : (2D array) Synthesised time-domain real signal of the shape (nsamples x nchannels)
"""
M = xmX.shape[0] # Number of channels
F = xmX.shape[1] # Number of frequency samples
T = xmX.shape[2] # Number of time-frames
# Synthesize the first incoming channel to acquire the dimensions
y = TimeFrequencyDecomposition.iSTFT(xmX[0, :, :].T, xpX[0, :, :].T, wsz, hop, smt)
yout = np.zeros((len(y), M), dtype = np.float32)
# Storing it to the actual return and free up some memory
yout[:, 0] = y
del y
for channel in xrange(1, M):
y = TimeFrequencyDecomposition.iSTFT(xmX[channel, :, :].T, xpX[channel, :, :].T, wsz, hop, smt)
yout[:, channel] = y
del y
return yout
@staticmethod
def nuttall4b(M, sym=False):
"""
Returns a minimum 4-term Blackman-Harris window according to Nuttall.
The typical Blackman window famlity define via "alpha" is continuous
with continuous derivative at the edge. This will cause some errors
to short time analysis, using odd length windows.
Args :
M : (int) Number of points in the output window.
sym : (array) Synthesised time-domain real signal.
Returns :
w : (ndarray) The windowing function
References :
[1] Heinzel, G.; Rüdiger, A.; Schilling, R. (2002). Spectrum and spectral density
estimation by the Discrete Fourier transform (DFT), including a comprehensive
list of window functions and some new flat-top windows (Technical report).
Max Planck Institute (MPI) für Gravitationsphysik / Laser Interferometry &
Gravitational Wave Astronomy, 395068.0
[2] Nuttall A.H. (1981). Some windows with very good sidelobe behaviour. IEEE
Transactions on Acoustics, Speech and Signal Processing, Vol. ASSP-29(1):
84-91.
"""
if M < 1:
return np.array([])
if M == 1:
return np.ones(1, 'd')
if not sym :
M = M + 1
a = [0.355768, 0.487396, 0.144232, 0.012604]
n = np.arange(0, M)
fac = n * 2 * np.pi / (M - 1.0)
w = (a[0] - a[1] * np.cos(fac) +
a[2] * np.cos(2 * fac) - a[3] * np.cos(3 * fac))
if not sym:
w = w[:-1]
return w
@staticmethod
def pqmf_analysis(x):
"""
Method to analyse an input time-domain signal using PQMF.
See QMF class for more information.
Arguments :
x : (1D Array) Input signal
Returns :
ms : (2D Array) Analysed time-frequency representation by means of PQMF analysis.
"""
# Parameters
N = 1024
nTimeSlots = len(x) / N
# Initialization
ms = np.zeros((nTimeSlots, N), dtype=np.float32)
qrf.reset_rt()
# Perform Analysis
for m in xrange(nTimeSlots):
ms[m, :] = qrf.PQMFAnalysis.analysisqmf_realtime(x[m*N:(m+1)*N], N)
return ms
@staticmethod
def pqmf_synthesis(ms):
"""
Method to synthesise a time-domain signal using PQMF.
See QMF class for more information.
Arguments :
ms : (2D Array) Analysed time-frequency representation by means of PQMF analysis.
Returns :
xrec : (1D Array) Reconstructed signal
"""
# Parameters
N = 1024
nTimeSlots = ms.shape[0]
# Initialization
xrec = np.zeros((nTimeSlots * N), dtype=np.float32)
qrf.reset_rt()
# Perform Analysis
for m in xrange(nTimeSlots):
xrec[m * N: (m + 1) * N] = qrf.PQMFSynthesis.synthesisqmf_realtime(ms[m, :], N)
return xrec
@staticmethod
def coreModulation(win, N, type = 'MDCT'):
"""
Method to produce Analysis and Synthesis matrices for the offline
PQMF class, using polyphase matrices.
Arguments :
win : (1D Array) Windowing function
N : (int) Number of subbands
type : (str) Selection between 'MDCT' or 'PQMF' basis functions
Returns :
Cos : (2D Array) Cosine Modulated Polyphase Matrix
Sin : (2D Array) Sine Modulated Polyphase Matrix
"""
global Cos
lfb = len(win)
# Initialize Storing Variables
Cos = np.zeros((N,lfb), dtype = np.float32)
#Sin = np.zeros((N,lfb), dtype = np.float32)
# Generate Matrices
if type == 'MDCT' :
print('MDCT')
for k in xrange(0, N):
for n in xrange(0, lfb):
Cos[k, n] = win[n] * np.cos(np.pi/N * (k + 0.5) * (n + 0.5 + N/2)) * np.sqrt(2. / N)
#Sin[k, n] = win[n] * np.sin(np.pi/N * (k + 0.5) * (n + 0.5 + N/2)) * np.sqrt(2. / N)
elif type == 'PQMF-polyphase' :
print('PQMF-polyphase')
for k in xrange(0, N):
for n in xrange(0, lfb):
Cos[k, n] = win[n] * np.cos(np.pi/N * (k + 0.5) * (n + 0.5)) * np.sqrt(2. / N)
#Sin[k, n] = win[n] * np.sin(np.pi/N * (k + 0.5) * (n + 0.5)) * np.sqrt(2. / N)
else :
assert('Unknown type')
return Cos
@staticmethod
def real_analysis(x, N = 1024):
"""
Method to compute the subband samples from time domain signal x.
A real valued output matrix will be computed using DCT.
Arguments :
x : (1D Array) Input signal
N : (int) Number of sub-bands
Returns :
y : (2D Array) Real valued output of the analysis
"""
# Parameters and windowing function design
win = cosine(2*N, True)
lfb = len(win)
nTimeSlots = len(x)/N - 2
# Initialization
ycos = np.zeros((len(x)/N, N), dtype = np.float32)
ysin = np.zeros((len(x)/N, N), dtype = np.float32)
# Check global variables in order to avoid
# computing over and over again the transformation matrices.
glvars = globals()
if 'Cos' in glvars and ((glvars['Cos'].T).shape[1] == N):
print('... using pre-computed transformation matrices')
global Cos
# Perform Analysis
for m in xrange(0, nTimeSlots):
ycos[m, :] = np.dot(x[m * N: m * N + lfb], Cos.T)
else :
print('... computing transformation matrices')
# Analysis Matrix
Cos = TimeFrequencyDecomposition.coreModulation(win, N)
# Perform Analysis
for m in xrange(0, nTimeSlots):
ycos[m, :] = np.dot(x[m * N: m * N + lfb], Cos.T)
return ycos
@staticmethod
def real_synthesis(y):
"""
Method to compute the resynthesis of the MDCT.
A real valued input matrix is asummed as input, derived from DCT typeIV.
Arguments :
y : (2D Array) Real Representation (time frames x frequency sub-bands (N))
Returns :
xrec : (1D Array) Time domain reconstruction
"""
# Parameters and windowing function design
N = y.shape[1]
win = cosine(2*N, True)
lfb = len(win)
nTimeSlots = y.shape[0]
SignalLength = nTimeSlots * N + 2 * N
# Check global variables in order to avoid
# computing over and over again the transformation matrices.
glvars = globals()
if 'Cos' in glvars and ((glvars['Cos'].T).shape[1] == N):
print('... using pre-computed transformation matrix')
global Cos
# Initialization
zcos = np.zeros((1, SignalLength), dtype=np.float32)
# Perform Synthesis
for m in xrange(0, nTimeSlots):
zcos[0, m * N: m * N + lfb] += np.dot((y[m, :]).T, Cos)
else:
print('... computing transformation matrix')
# Synthesis marix
Cos = TimeFrequencyDecomposition.coreModulation(win, N)
# Initialization
zcos = np.zeros((1, SignalLength), dtype=np.float32)
# Perform Synthesis
for m in xrange(0, nTimeSlots):
zcos[0, m * N: m * N + lfb] += np.dot((y[m, :]).T, Cos)
return zcos.T
@staticmethod
def frft(f, a):
"""
Fractional Fourier transform. As appears in :
-https://nalag.cs.kuleuven.be/research/software/FRFT/
-https://github.com/audiolabs/frft/
Args:
f : (array) Input data
a : (float) Alpha factor
Returns:
ret : (array) Complex valued analysed data
"""
ret = np.zeros_like(f, dtype=np.complex)
f = f.copy().astype(np.complex)
N = len(f)
shft = np.fmod(np.arange(N) + np.fix(N / 2), N).astype(int)
sN = np.sqrt(N)
a = np.remainder(a, 4.0)
# Special cases
if a == 0.0:
return f
if a == 2.0:
return np.flipud(f)
if a == 1.0:
ret[shft] = np.fft.fft(f[shft]) / sN
return ret
if a == 3.0:
ret[shft] = np.fft.ifft(f[shft]) * sN
return ret
# reduce to interval 0.5 < a < 1.5
if a > 2.0:
a = a - 2.0
f = np.flipud(f)
if a > 1.5:
a = a - 1
f[shft] = np.fft.fft(f[shft]) / sN
if a < 0.5:
a = a + 1
f[shft] = np.fft.ifft(f[shft]) * sN
# the general case for 0.5 < a < 1.5
alpha = a * np.pi / 2
tana2 = np.tan(alpha / 2)
sina = np.sin(alpha)
f = np.hstack((np.zeros(N - 1), TimeFrequencyDecomposition.sincinterp(f), np.zeros(N - 1))).T
# chirp premultiplication
chrp = np.exp(-1j * np.pi / N * tana2 / 4 * np.arange(-2 * N + 2, 2 * N - 1).T ** 2)
f = chrp * f
# chirp convolution
c = np.pi / N / sina / 4
ret = fftconvolve(np.exp(1j * c * np.arange(-(4 * N - 4), 4 * N - 3).T ** 2), f)
ret = ret[4 * N - 4:8 * N - 7] * np.sqrt(c / np.pi)
# chirp post multiplication
ret = chrp * ret
# normalizing constant
ret = np.exp(-1j * (1 - a) * np.pi / 4) * ret[N - 1:-N + 1:2]
return ret
@staticmethod
def ifrft(f, a):
"""
Inverse fractional Fourier transform. As appears in :
-https://nalag.cs.kuleuven.be/research/software/FRFT/
-https://github.com/audiolabs/frft/
----------
Args:
f : (array) Complex valued input array
a : (float) Alpha factor
Returns:
ret : (array) Real valued synthesised data
"""
return TimeFrequencyDecomposition.frft(f, -a)
@staticmethod
def sincinterp(x):
"""
Sinc interpolation for computation of fractional transformations.
As appears in :
-https://github.com/audiolabs/frft/
----------
Args:
f : (array) Complex valued input array
a : (float) Alpha factor
Returns:
ret : (array) Real valued synthesised data
"""
N = len(x)
y = np.zeros(2 * N - 1, dtype=x.dtype)
y[:2 * N:2] = x
xint = fftconvolve( y[:2 * N], np.sinc(np.arange(-(2 * N - 3), (2 * N - 2)).T / 2),)
return xint[2 * N - 3: -2 * N + 3]
@staticmethod
def stfrft(x, w, hop, a):
""" Short Time Fractional Fourier Transform analysis of a given real input signal,
via the above DFT method.
Args:
x : (array) Magnitude Spectrum
w : (array) Desired windowing function determining the analysis size
hop : (int) Hop size
a : (float) Alpha factor
Returns:
sMx : (2D ndarray) Stacked arrays of magnitude spectra
sPx : (2D ndarray) Stacked arrays of phase spectra
"""
# Analysis Parameters
wsz = w.size
# Add some zeros at the start and end of the signal to avoid window smearing
x = np.append(np.zeros(3*hop),x)
x = np.append(x, np.zeros(3*hop))
# Initialize sound pointers
pin = 0
pend = x.size - wsz
indx = 0
# Initialize storing matrix
xmX = np.zeros((len(x)/hop, wsz), dtype = np.float32)
xpX = np.zeros((len(x)/hop, wsz), dtype = np.float32)
# Analysis Loop
while pin <= pend:
# Acquire Segment
xSeg = x[pin:pin+wsz] * w
# Perform frFT on segment
cX = TimeFrequencyDecomposition.frft(xSeg, a)
xmX[indx, :] = np.abs(cX)
xpX[indx, :] = np.angle(cX)
# Update pointers and indices
pin += hop
indx += 1
return xmX, xpX
@staticmethod
def istfrft(xmX, xpX, hop, a):
""" Inverse Short Time Fractional Fourier Transform synthesis of given magnitude and phase spectra.
Args:
xmX : (2D ndarray) Magnitude Spectrum
xpX : (2D ndarray) Phase Spectrum
hop : (int) Hop Size
a : (float) Alpha factor
Returns :
y : (array) Synthesised time-domain real signal.
"""
# Acquire the number of frames
numFr = xmX.shape[0]
# Amount of samples
wsz = xmX.shape[1]
# Initialise output array with zeros
y = np.zeros(numFr * hop + wsz)
# Initialise sound pointer
pin = 0
# Main Synthesis Loop
for indx in range(numFr):
# Inverse FrFT
cX = xmX[indx, :] * np.exp(1j*xpX[indx, :])
ybuffer = TimeFrequencyDecomposition.ifrft(cX, a)
# Overlap and Add
y[pin:pin+wsz] += np.real(ybuffer)
# Advance pointer
pin += hop
# Delete the extra zeros that the analysis had placed
y = np.delete(y, range(3*hop))
y = np.delete(y, range(y.size-(3*hop + 1), y.size))
return y
class CepstralDecomposition:
""" A Class that performs a cepstral decomposition based on the
logarithmic observed magnitude spectrogram. As appears in:
"A Novel Cepstral Representation for Timbre Modelling of
Sound Sources in Polyphonic Mixtures", Z.Duan, B.Pardo, L. Daudet.
"""
@staticmethod
def computeUDCcoefficients(freqPoints = 2049, points = 2049, fs = 44100, melOption = False):
""" Computation of M matrix that contains the coefficients for
cepstral modelling architecture.
Args:
freqPoints : (int) Number of frequencies to model
points : (int) The cepstum order (number of coefficients)
fs : (int) Sampling frequency
melOption : (bool) Compute Mel-uniform discrete cepstrum
Returns:
M : (ndarray) Matrix containing the coefficients
"""
M = np.empty((freqPoints, points), dtype = np.float32)
# Array obtained by the order number of cepstrum
p = np.arange(points)
# Array with frequncy bin indices
f = np.arange(freqPoints)
if (freqPoints % 2 == 0):
fftsize = (freqPoints)*2
else :
fftsize = (freqPoints-1)*2
# Creation of frequencies from frequency bins
farray = f * float(fs) / fftsize
if (melOption):
melf = 2595.0 * np.log10(1.0 + farray * fs/700.0)
melHsr = 2595.0 * np.log10(1.0 + (fs/2.0) * fs/700.0)
farray = (0.5 * melf) / (melHsr)
else:
farray = farray/(fs)
twoSqrt = np.sqrt(2.0)
for indx in range(M.shape[0]):
M[indx, :] = (np.cos(2.0 * np.pi * p * farray[indx]))
M[indx, 1:] *= twoSqrt
return M
class PsychoacousticModel:
""" Class that performs a very basic psychoacoustic model.
- Bark scaling is based on Perceptual-Coding-In-Python, [Online] :
https://github.com/stephencwelch/Perceptual-Coding-In-Python
- Perceptual filters and correction based on :
A. Härmä, and K. Palomäki, ''HUTear – a free Matlab toolbox for modeling of human hearing'',
in Proceedings of the Matlab DSP Conference, pp 96-99, Espoo, Finland 1999.
"""
def __init__(self, N = 4096, fs = 44100, nfilts=24, type = 'rasta', width = 1.0, minfreq=0, maxfreq=22050):
self.nfft = N
self.fs = fs
self.nfilts = nfilts
self.width = width
self.min_freq = minfreq
self.max_freq = maxfreq
self.max_freq = fs/2
self.nfreqs = N/2
self._LTeq = np.zeros(nfilts, dtype = np.float32)
# Non-linear superposition parameters
self._alpha = 0.9 # Exponent alpha
self._maxb = 1./self.nfilts # Bark-band normalization
self._fa = 1./(10 ** (14.5/20.) * 10 ** (12.5/20.)) # Tone masking approximation
self._fb = 1./(10**(7.5/20.)) # Upper slope of spreading function
self._fbb = 1./(10**(26./20.)) # Lower slope of spreading function
self._fd = 1./self._alpha # One over alpha exponent
# Type of transformation
self.type = type
# Computing the matrix for forward Bark transformation
self.W = self.mX2Bark(type)
# Computing the inverse matrix for backward Bark transformation
self.W_inv = self.bark2mX()
def mX2Bark(self, type):
""" Method to perform the transofrmation.
Args :
type : (str) String denoting the type of transformation. Can be either
'rasta' or 'peaq'.
Returns :
W : (ndarray) The transformation matrix.
"""
if type == 'rasta':
W = self.fft2bark_rasta()
elif type == 'peaq':
W = self.fft2bark_peaq()
else:
assert('Unknown method')
return W
def fft2bark_peaq(self):
""" Method construct the weight matrix.
Returns :
W : (ndarray) The transformation matrix, used in PEAQ evaluation.
"""
nfft = self.nfft
nfilts = self.nfilts
fs = self.fs
# Acquire frequency analysis
df = float(fs)/nfft
# Acquire filter responses
fc, fl, fu = self.CB_filters()
W = np.zeros((nfilts, nfft))
for k in range(nfft/2+1):
for i in range(nfilts):
temp = (np.amin([fu[i], (k+0.5)*df]) - np.amax([fl[i], (k-0.5)*df])) / df
W[i,k] = np.amax([0, temp])
return W
def fft2bark_rasta(self):
""" Method construct the weight matrix.
Returns :
W : (ndarray) The transformation matrix, used in PEAQ evaluation.
"""
minfreq = self.min_freq
maxfreq = self.max_freq
nfilts = self.nfilts
nfft = self.nfft
fs = self.fs
width = self.width
min_bark = self.hz2bark(minfreq)
nyqbark = self.hz2bark(maxfreq) - min_bark
if (nfilts == 0):
nfilts = np.ceil(nyqbark)+1
W = np.zeros((nfilts, nfft))
# Bark per filter
step_barks = nyqbark/(nfilts-1)
# Frequency of each FFT bin in Bark
binbarks = self.hz2bark(np.linspace(0,(nfft/2),(nfft/2)+1)*fs/nfft)
for i in xrange(nfilts):
f_bark_mid = min_bark + (i)*step_barks
# Compute the absolute threshold
self._LTeq[i] = 3.64 * (self.bark2hz(f_bark_mid + 1) / 1000.) ** -0.8 - \
6.5*np.exp( -0.6 * (self.bark2hz(f_bark_mid + 1) / 1000. - 3.3) ** 2.) + \
1e-3*((self.bark2hz(f_bark_mid + 1) / 1000.) ** 4.)
W[i,0:(nfft/2)+1] = (np.round(binbarks/step_barks)== i)
return W
def bark2mX(self):
""" Method construct the inverse weight matrix, to map back to FT domain.
Returns :
W : (ndarray) The inverse transformation matrix.
"""
W_inv= np.dot(np.diag((1.0/np.sum(self.W[:,0:self.nfreqs + 1], 1)) ** 0.5),
self.W[:, 0:self.nfreqs + 1]).T
return W_inv
def hz2bark(self, f):
""" Method to compute Bark from Hz.
Args :
f : (ndarray) Array containing frequencies in Hz.
Returns :
Brk : (ndarray) Array containing Bark scaled values.
"""
Brk = 6. * np.arcsinh(f/600.) # Method from RASTA model and computable inverse function.
#Brk = 13. * np.arctan(0.76*f/1000.) + 3.5 * np.arctan(f / (1000 * 7.5)) ** 2.
return Brk
def bark2hz(self, Brk):
""" Method to compute Hz from Bark scale.
Args :
Brk : (ndarray) Array containing Bark scaled values.
Returns :
Fhz : (ndarray) Array containing frequencies in Hz.
"""
Fhz = 650. * np.sinh(Brk/7.)
return Fhz
def CB_filters(self):
""" Method to acquire critical band filters for creation of the PEAQ FFT model.
Returns :
fc, fl, fu : (ndarray) Arrays containing the values in Hz for the
bandwidth and centre frequencies used in creation
of the transformation matrix.
"""
fl = np.array([ 80.000, 103.445, 127.023, 150.762, 174.694, \
198.849, 223.257, 247.950, 272.959, 298.317, \
324.055, 350.207, 376.805, 403.884, 431.478, \
459.622, 488.353, 517.707, 547.721, 578.434, \
609.885, 642.114, 675.161, 709.071, 743.884, \
779.647, 816.404, 854.203, 893.091, 933.119, \
974.336, 1016.797, 1060.555, 1105.666, 1152.187, \
1200.178, 1249.700, 1300.816, 1353.592, 1408.094, \
1464.392, 1522.559, 1582.668, 1644.795, 1709.021, \
1775.427, 1844.098, 1915.121, 1988.587, 2064.590, \
2143.227, 2224.597, 2308.806, 2395.959, 2486.169, \
2579.551, 2676.223, 2776.309, 2879.937, 2987.238, \
3098.350, 3213.415, 3332.579, 3455.993, 3583.817, \
3716.212, 3853.817, 3995.399, 4142.547, 4294.979, \
4452.890, 4616.482, 4785.962, 4961.548, 5143.463, \
5331.939, 5527.217, 5729.545, 5939.183, 6156.396, \
6381.463, 6614.671, 6856.316, 7106.708, 7366.166, \
7635.020, 7913.614, 8202.302, 8501.454, 8811.450, \
9132.688, 9465.574, 9810.536, 10168.013, 10538.460, \
10922.351, 11320.175, 11732.438, 12159.670, 12602.412, \
13061.229, 13536.710, 14029.458, 14540.103, 15069.295, \
15617.710, 16186.049, 16775.035, 17385.420 ])
fc = np.array([ 91.708, 115.216, 138.870, 162.702, 186.742, \
211.019, 235.566, 260.413, 285.593, 311.136, \
337.077, 363.448, 390.282, 417.614, 445.479, \
473.912, 502.950, 532.629, 562.988, 594.065, \
625.899, 658.533, 692.006, 726.362, 761.644, \
797.898, 835.170, 873.508, 912.959, 953.576, \
995.408, 1038.511, 1082.938, 1128.746, 1175.995, \
1224.744, 1275.055, 1326.992, 1380.623, 1436.014, \
1493.237, 1552.366, 1613.474, 1676.641, 1741.946, \
1809.474, 1879.310, 1951.543, 2026.266, 2103.573, \
2183.564, 2266.340, 2352.008, 2440.675, 2532.456, \
2627.468, 2725.832, 2827.672, 2933.120, 3042.309, \
3155.379, 3272.475, 3393.745, 3519.344, 3649.432, \
3784.176, 3923.748, 4068.324, 4218.090, 4373.237, \
4533.963, 4700.473, 4872.978, 5051.700, 5236.866, \
5428.712, 5627.484, 5833.434, 6046.825, 6267.931, \
6497.031, 6734.420, 6980.399, 7235.284, 7499.397, \
7773.077, 8056.673, 8350.547, 8655.072, 8970.639, \
9297.648, 9636.520, 9987.683, 10351.586, 10728.695, \
11119.490, 11524.470, 11944.149, 12379.066, 12829.775, \
13294.850, 13780.887, 14282.503, 14802.338, 15341.057, \
15899.345, 16477.914, 17077.504, 17690.045 ])
fu = np.array([ 103.445, 127.023, 150.762, 174.694, 198.849, \
223.257, 247.950, 272.959, 298.317, 324.055, \
350.207, 376.805, 403.884, 431.478, 459.622, \
488.353, 517.707, 547.721, 578.434, 609.885, \
642.114, 675.161, 709.071, 743.884, 779.647, \
816.404, 854.203, 893.091, 933.113, 974.336, \
1016.797, 1060.555, 1105.666, 1152.187, 1200.178, \
1249.700, 1300.816, 1353.592, 1408.094, 1464.392, \
1522.559, 1582.668, 1644.795, 1709.021, 1775.427, \
1844.098, 1915.121, 1988.587, 2064.590, 2143.227, \
2224.597, 2308.806, 2395.959, 2486.169, 2579.551, \
2676.223, 2776.309, 2879.937, 2987.238, 3098.350, \
3213.415, 3332.579, 3455.993, 3583.817, 3716.212, \
3853.348, 3995.399, 4142.547, 4294.979, 4452.890, \
4643.482, 4785.962, 4961.548, 5143.463, 5331.939, \
5527.217, 5729.545, 5939.183, 6156.396, 6381.463, \
6614.671, 6856.316, 7106.708, 7366.166, 7635.020, \
7913.614, 8202.302, 8501.454, 8811.450, 9132.688, \
9465.574, 9810.536, 10168.013, 10538.460, 10922.351, \
11320.175, 11732.438, 12159.670, 12602.412, 13061.229, \
13536.710, 14029.458, 14540.103, 15069.295, 15617.710, \
16186.049, 16775.035, 17385.420, 18000.000 ])
return fc, fl, fu
def forward(self, spc):
""" Method to transform FT domain to Bark.
Args :