-
Notifications
You must be signed in to change notification settings - Fork 3
/
GAD.py
183 lines (128 loc) · 4.49 KB
/
GAD.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
from __future__ import division
from numpy import linalg as LA
import numpy as np
np.set_printoptions(threshold=np.inf)
import sys
import librosa
import matplotlib.pyplot as plt
def buffer(signal, L, M):
if M >= L:
print ('Error: Overlapping windows cannot be larger than frame length!')
sys.exit()
len_signal = len(signal)
print ('The signal length is %s: ' % (len_signal))
K = np.ceil(len_signal / L).astype('int') # num_frames
print ('The number of frames \'K\' is %s: ' % (K))
print ('The length of each frame \'L\' is %s: ' % (L))
X_tmp = []
k = 1
while (True):
start_ind = ((k - 1) * (L - M) + 1) - 1
end_ind = ((k * L) - (k - 1) * M)
if start_ind == len_signal:
break
elif (end_ind > len_signal):
# print ('k=%s, [%s, %s] ' % (k, start_ind, end_ind - 1))
val_in = len_signal - start_ind
tmp_seg = np.zeros(L)
tmp_seg[:val_in] = signal[start_ind:]
X_tmp.append(tmp_seg)
break
else:
# print ('k=%s, [%s, %s] ' % (k, start_ind, end_ind - 1))
X_tmp.append(signal[start_ind:end_ind])
k += 1
return X_tmp
def unbuffer(X, hop):
N, L = X.shape
T = N + L * hop
K = np.arange(0, N)
x = np.zeros(T)
H = np.hanning(N)
for k in xrange(0, L):
x[K] = x[K] + np.multiply(H, X[:, k])
K = K + hop
return x
class GAD():
def __init__(self, X, params):
self.X = X
self.D = []
self.params = params
self.n_iter = self.params['rule_1']['n_iter'] # num_iterations
self.verbose = self.params['verbose']
self.K = self.X.shape[0] # sample length
self.L = self.X.shape[1] # maximum atoms to be learned
self.I = np.arange(0, self.L)
self.set_ind = []
def findResidualColumn(self):
# Find residual column of R^l with lowest l1- to l2-norm ration
tmp = []
# COMPACT WAY TO DO IT
# tmp2 = np.sum(np.abs(self.R),axis=0)/np.sqrt(np.sum(np.power(np.abs(self.R),2),axis=0))
for k in self.I:
r_k = self.R[:, k]
tmp.append(LA.norm(r_k, 1) / LA.norm(r_k, 2))
ind_k_min = np.nanargmin(tmp) # nanargmin, nanmin
k_min = tmp[ind_k_min]
r_k_min = self.R[:, self.I[ind_k_min]]
# Set the l-th atom to equal to normalized r_k
psi = r_k_min / LA.norm(r_k_min, 2)
# Add to the dictionary D and its index and shrinking set I
self.D.append(psi)
self.set_ind.append(self.I[ind_k_min])
# COMPACT WAY TO DO IT
# self.R = self.R - np.dot(np.outer(psi, psi), self.R)
# self.R = np.delete(self.R, (ind_k_min), axis=1)
# Compute the new residual for all columns k
for k in self.I:
r_k = self.R[:, k]
alpha = np.dot(r_k, psi)
self.R[:, k] = r_k - np.dot(psi, alpha)
self.I = np.delete(self.I, ind_k_min)
def iterative_GAD(self):
# X columns w/ unit L2-norm
# for k in xrange(0,self.X.shape[1]):
# self.X[:,k] = np.divide(self.X[:,k],LA.norm(self.X[:,k],2))
if self.n_iter > self.L:
print ('Cannot be learned more than %d atom!' % (self.L))
sys.exit()
# Initializating the residual matrix 'R' by using 'X'
self.R = self.X.copy()
print self.I.shape
for l in xrange(0, self.n_iter):
if self.verbose == True:
print 'GAD iteration: ', l + 1
self.findResidualColumn()
self.D = np.vstack(self.D).T
return self.D, self.set_ind
if __name__ == '__main__':
L = 512 # frame length
M = 500 # overlapping windows
params = {
'rule_1': {
'n_iter': 10 # n_iter
},
'rule_2': {
'error': 10 ** -7
},
'verbose': True
}
signal, fs = librosa.core.load('./dataset/source1.wav')
X_tmp = buffer(signal, L, M)
# new matrix LxK
X = np.vstack(X_tmp).T.astype('float')
# ???
# if X.shape[1] < L:
# print 'The number of frames %s has to be greater than its own length %s'%(X.shape[1],X.shape[0])
# sys.exit()
alg = GAD(X, params)
D, I = alg.iterative_GAD()
X_t = np.dot(np.dot(D, D.T), X)
s_rec = unbuffer(X_t, L - M)
plt.figure(1)
plt.title('Original signal')
plt.plot(signal)
plt.figure(2)
plt.title('Reconstructed signal')
plt.plot(s_rec)
plt.show()