-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_LMS.py
301 lines (247 loc) · 8.19 KB
/
test_LMS.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
'''
Test file for LMS.py
'''
import numpy as np
import math
from matplotlib import pyplot as plt
from scipy.signal import lfilter
from scipy.stats import norm as gaussian
from LMS import LMS, LMS_Normalized, LMS_ZA, LMS_RZA
from setup_helpers import \
system_identification_setup,\
one_step_pred_setup,\
equalizer_setup
def system_identification1():
'''
Runs an example of LMS filtering for 1 step prediction on a WSS
process. We plot the actual result, the errors, as well as the
convergence to the "correct" parameters. This is essentially
doint system identification.
'''
np.random.seed(2718)
N = 5000 #Length of data
mu = .02 #Step size
p = 2 #Filter order
#Filter for generating d(n)
b = [1.]
a = [1, -0.1, -0.8, 0.2]
sv2 = .25 #Innovations noise variance
#scale specifies standard deviation sqrt(sv2)
v = gaussian.rvs(size = N, scale = math.sqrt(sv2)) #Innovations
d = lfilter(b, a, v) #Desired process
#Initialize LMS filter and then
F = LMS(mu = mu, p = p) #Vanilla
# F = LMS_Normalized(p = p, beta = 0.02) #Normalized
# F = LMS_Sparse(p = p, mu = mu, g = 1.) #Sparse
ff_fb = system_identification_setup(F)
#Run it through the filter and get the error
#Pay attention to the offsets. d_hat[0] is a prediction of d[1].
#We implicitly predict d[0] = 0
w = np.array([ff_fb(di) for di in d])
w = np.array(w)
plt.plot(range(N), w[:,0], linewidth = 2, label = '$w[0]$')
plt.plot(range(N), w[:,1], linewidth = 2, label = '$w[1]$')
plt.plot(range(N), w[:,2], linewidth = 2, label = '$w[2]$')
plt.hlines(-a[1], 0, N, linestyle = ':', label = '$-a[1]$')
plt.hlines(-a[2], 0, N, linestyle = ':', label = '$-a[2]$')
plt.hlines(-a[3], 0, N, linestyle = ':', label = '$-a[3]$')
plt.legend()
plt.ylim((-.5, 1))
plt.xlabel('$n$')
plt.ylabel('$w$')
plt.title('System Identification')
plt.show()
return
def system_identification2():
'''
Runs an example of Sparse LMS filtering for 1 step prediction on a
WSS process. We plot the actual result, the errors, as well as the
convergence to the "correct" parameters. This is essentially doing
system identification.
The point of this is to compare the sparse vs non sparse LMS
'''
np.random.seed(2718)
N = 5000 #Length of data
mu = .005 #Step size
p = 9 #Filter order
#Filter for generating d(n)
b = [1.]
a = [1, -0.1, 0., 0., 0.3, 0., 0.2, 0., 0., 0., -0.3]
sv2 = .25 #Innovations noise variance
#scale specifies standard deviation sqrt(sv2)
v = gaussian.rvs(size = N, scale = math.sqrt(sv2)) #Innovations
d = lfilter(b, a, v) #Desired process
#Initialize LMS filter and then
# F = LMS_ZA(p = p, mu = mu, g = 0.01) #Sparse
F = LMS_RZA(p = p, mu = mu, g = 0.05, eps = 10) #Reweighted Sparse
ff_fb = system_identification_setup(F)
#Run it through the filter and get the error
#Pay attention to the offsets. d_hat[0] is a prediction of d[1].
#We implicitly predict d[0] = 0
w = np.array([ff_fb(di) for di in d])
w = np.array(w)
for i in range(p):
plt.plot(range(N), w[:, i], linewidth = 2)
plt.hlines(-a[i + 1], 0, N, linestyle = ':')
plt.ylim((-.5, 1))
plt.xlabel('$n$')
plt.ylabel('$w$')
plt.title('Sparse System Identification')
plt.show()
return
def tracking_example1():
'''
Shows the LMS algorithm tracking a time varying process.
'''
np.random.seed(314)
N = 500 #Length of data
beta = 0.4 #Step size modifier
p = 6 #Filter order
#Filter for generating d(n)
b = [1, -0.5, .3]
a = [1, 0.2, 0.16, -0.21, -0.0225]
sv2 = .25 #Innovations noise variance
#Track a time varying process
t = np.linspace(0, 1, N)
f = 2
v = 4*np.sin(2*np.pi*f*t) + \
gaussian.rvs(size = N, scale = math.sqrt(sv2)) #Innovations
d = lfilter(b, a, v) #Desired process
#Initialize LMS filter and then
#Get function closure implementing 1 step prediction
F = LMS_Normalized(p = p, beta = beta)
ff_fb = one_step_pred_setup(F)
#Run it through the filter and get the error
d_hat = np.array([0] + [ff_fb(di) for di in d])[:-1]
err = (d - d_hat)
plt.subplot(2,1,1)
plt.plot(range(N), d, linewidth = 2, linestyle = ':',
label = 'True Process')
plt.plot(range(N), d_hat, linewidth = 2, label = 'Prediction')
plt.legend()
plt.xlabel('$n$')
plt.ylabel('Process Value')
plt.title('LMS_Normalized tracking a process' \
'$\\beta = %s$, $p = %d$' % (beta, p))
plt.subplot(2,1,2)
plt.plot(range(N), err, linewidth = 2)
plt.xlabel('$n$')
plt.ylabel('Error')
plt.title('Prediction Error')
plt.show()
return
def tracking_example2():
'''
Tracking a brownian motion process
'''
from scipy.stats import multivariate_normal as norm
#Brownian motion kernel
def K_brownian(tx, ty, sigma2):
return (sigma2)*np.minimum(tx, ty)
def sample_gp(t, cov_func):
'''
Draws samples from a gaussian process with covariance given by cov_func.
cov_func should be a function of 2 variables e.g. cov_func(tx, ty). For
the x,y coordinates of the matrix. If the underlying covariance function
requires more than 2 arguments, then they should be passed via a lambda
function.
'''
tx, ty = np.meshgrid(t, t)
cov = cov_func(tx, ty)
return norm.rvs(cov = np.array(cov))
np.random.seed(4)
N = 800 #Length of data
beta = 0.4 #Step size modifier
p = 6 #Filter order
sd2 = 2
d = sample_gp(range(N), lambda tx, ty: K_brownian(tx, ty, sd2))
#Initialize LMS filter and then
#Get function closure implementing 1 step prediction
F = LMS_Normalized(p = p)
ff_fb = one_step_pred_setup(F)
#Run it through the filter and get the error
d_hat = np.array([0] + [ff_fb(di) for di in d])[:-1]
err = (d - d_hat)
plt.subplot(2,1,1)
plt.plot(range(N), d, linewidth = 2, linestyle = ':',
label = 'True Process')
plt.plot(range(N), d_hat, linewidth = 2, label = 'Prediction')
plt.legend()
plt.xlabel('$n$')
plt.ylabel('Process Value')
plt.title('LMS_Normalized tracking a process, '\
'$\\beta = %s$, $p = %d$' % (beta, p))
plt.subplot(2,1,2)
plt.plot(range(N), err, linewidth = 2)
plt.xlabel('$n$')
plt.ylabel('Error')
plt.title('Prediction Error')
plt.show()
return
def channel_equalization():
'''
Shows an example of channel equalization. We train the LMS
algorithm with an aprior known sequence, then use decision feedback
equalization.
'''
from scipy.stats import bernoulli
np.random.seed(13)
#Channel impulse response
h = [0, .05, 0.15, 0.5, 0.15, .05]
a = [1.]
rx_delay = 10
beta = 0.5
p = 15 #Filter order
N = 1000 #Length of all data
t_N = N/8 #Length of training sequence
d_N = N - t_N #Length of "real data" sequence
sv2 = 0.01 #noise variance
k = -1 + 2*bernoulli.rvs(0.5, size = N) #All data
v = gaussian.rvs(size = N, scale = math.sqrt(sv2)) #Noise
x = lfilter(h, a, k) + v #Signal after the channel
t = k[:t_N] #Training sequence
rx_t = x[:t_N] #Received training sequence
d = k[t_N:] #Data sequence
rx_d = x[t_N:] #Received data sequence
plt.plot(range(t_N), rx_t, label = 'noisy rx')
plt.plot(range(t_N), rx_t - v[:t_N], label = 'non noisy rx')
plt.plot(range(t_N), t, label = 'training sequence')
plt.ylim((-1.5, 1.5))
plt.legend()
plt.title('Training Phase')
plt.xlabel('$n$')
plt.show()
#Setup an equalization LMS filter
F = LMS_Normalized(beta = 0.6, p = p)
ff_fb = equalizer_setup(F, rx_delay)
#Train the equalizer
W = np.array([ff_fb(rx_ti, ti) for (rx_ti, ti) in zip(rx_t, t)])
eq_h = np.convolve(F.w, h) #Equalized channel response
plt.subplot(2,1,1)
plt.stem(range(len(h)), h)
plt.title('Channel Response')
plt.xlim((0, len(h) + 2))
plt.xlabel('$n$')
plt.ylabel('$h[n]$')
plt.subplot(2,1,2)
plt.stem(range(len(eq_h)), eq_h)
plt.title('Equalized Response')
plt.xlabel('$n$')
plt.ylabel('$(h*w)[n]$')
plt.show()
#now use the equalizer with decision directed feedback
d_hat = np.array([ff_fb(rx_di) for rx_di in rx_d])
#Need to synchronize
err = d[:-rx_delay] != d_hat[rx_delay:]
plt.stem(range(d_N - rx_delay), err)
plt.title('Errors')
plt.xlabel('$n$')
plt.ylabel('$e[n]$')
plt.show()
return
if __name__ == '__main__':
system_identification1()
system_identification2()
tracking_example1()
tracking_example2()
channel_equalization()