CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download
Project: test
Views: 91872
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Thu May 1 16:56:49 2014
4
5
@author: rlabbe
6
"""
7
import filterpy.stats as stats
8
from filterpy.stats import plot_covariance_ellipse
9
import numpy as np
10
from matplotlib.patches import Ellipse
11
import matplotlib.pyplot as plt
12
from matplotlib import cm
13
from mpl_toolkits.mplot3d import Axes3D
14
from numpy.random import multivariate_normal
15
16
def show_residual_chart():
17
est_y = ((164.2-158)*.8 + 158)
18
19
ax = plt.axes(xticks=[], yticks=[], frameon=False)
20
ax.annotate('', xy=[1,159], xytext=[0,158],
21
arrowprops=dict(arrowstyle='->',
22
ec='r', lw=3, shrinkA=6, shrinkB=5))
23
24
ax.annotate('', xy=[1,159], xytext=[1,164.2],
25
arrowprops=dict(arrowstyle='-',
26
ec='k', lw=1, shrinkA=8, shrinkB=8))
27
28
ax.annotate('', xy=(1., est_y), xytext=(0.9, est_y),
29
arrowprops=dict(arrowstyle='->', ec='#004080',
30
lw=2,
31
shrinkA=3, shrinkB=4))
32
33
34
plt.scatter ([0,1], [158.0,est_y], c='k',s=128)
35
plt.scatter ([1], [164.2], c='b',s=128)
36
plt.scatter ([1], [159], c='r', s=128)
37
plt.text (1.0, 158.8, "prediction ($x_t)$", ha='center',va='top',fontsize=18,color='red')
38
plt.text (1.0, 164.4, "measurement ($z$)",ha='center',va='bottom',fontsize=18,color='blue')
39
plt.text (0, 157.8, "prior estimate ($\hat{x}_{t-1}$)", ha='center', va='top',fontsize=18)
40
plt.text (1.02, est_y-1.5, "residual", ha='left', va='center',fontsize=18)
41
plt.text (0.9, est_y, "new estimate ($\hat{x}_{t}$)", ha='right', va='center',fontsize=18)
42
plt.xlabel('time')
43
ax.yaxis.set_label_position("right")
44
plt.ylabel('state')
45
plt.xlim(-0.5, 1.5)
46
plt.show()
47
48
49
def plot_gaussian_multiply():
50
xs = np.arange(-5, 10, 0.1)
51
52
mean1, var1 = 0, 5
53
mean2, var2 = 5, 1
54
mean, var = stats.mul(mean1, var1, mean2, var2)
55
56
ys = [stats.gaussian(x, mean1, var1) for x in xs]
57
plt.plot(xs, ys, label='M1')
58
59
ys = [stats.gaussian(x, mean2, var2) for x in xs]
60
plt.plot(xs, ys, label='M2')
61
62
ys = [stats.gaussian(x, mean, var) for x in xs]
63
plt.plot(xs, ys, label='M1 x M2')
64
plt.legend()
65
plt.show()
66
67
68
def show_position_chart():
69
""" Displays 3 measurements at t=1,2,3, with x=1,2,3"""
70
71
plt.scatter ([1,2,3], [1,2,3], s=128, color='#004080')
72
plt.xlim([0,4]);
73
plt.ylim([0,4])
74
75
plt.annotate('t=1', xy=(1,1), xytext=(0,-10),
76
textcoords='offset points', ha='center', va='top')
77
78
plt.annotate('t=2', xy=(2,2), xytext=(0,-10),
79
textcoords='offset points', ha='center', va='top')
80
81
plt.annotate('t=3', xy=(3,3), xytext=(0,-10),
82
textcoords='offset points', ha='center', va='top')
83
84
plt.xlabel("X")
85
plt.ylabel("Y")
86
87
plt.xticks(np.arange(1,4,1))
88
plt.yticks(np.arange(1,4,1))
89
plt.show()
90
91
92
def show_position_prediction_chart():
93
""" displays 3 measurements, with the next position predicted"""
94
95
plt.scatter ([1,2,3], [1,2,3], s=128, color='#004080')
96
97
plt.annotate('t=1', xy=(1,1), xytext=(0,-10),
98
textcoords='offset points', ha='center', va='top')
99
100
plt.annotate('t=2', xy=(2,2), xytext=(0,-10),
101
textcoords='offset points', ha='center', va='top')
102
103
plt.annotate('t=3', xy=(3,3), xytext=(0,-10),
104
textcoords='offset points', ha='center', va='top')
105
106
plt.xlim([0,5])
107
plt.ylim([0,5])
108
109
plt.xlabel("Position")
110
plt.ylabel("Time")
111
112
plt.xticks(np.arange(1,5,1))
113
plt.yticks(np.arange(1,5,1))
114
115
plt.scatter ([4], [4], c='g',s=128, color='#8EBA42')
116
ax = plt.axes()
117
ax.annotate('', xy=(4,4), xytext=(3,3),
118
arrowprops=dict(arrowstyle='->',
119
ec='g',
120
shrinkA=6, shrinkB=5,
121
lw=3))
122
plt.show()
123
124
125
def show_x_error_chart(count):
126
""" displays x=123 with covariances showing error"""
127
128
plt.cla()
129
plt.gca().autoscale(tight=True)
130
131
cov = np.array([[0.03,0], [0,8]])
132
e = stats.covariance_ellipse (cov)
133
134
cov2 = np.array([[0.03,0], [0,4]])
135
e2 = stats.covariance_ellipse (cov2)
136
137
cov3 = np.array([[12,11.95], [11.95,12]])
138
e3 = stats.covariance_ellipse (cov3)
139
140
141
sigma=[1, 4, 9]
142
143
if count >= 1:
144
stats.plot_covariance_ellipse ((0,0), ellipse=e, variance=sigma)
145
146
if count == 2 or count == 3:
147
148
stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma)
149
150
if count == 3:
151
152
stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma,
153
edgecolor='r')
154
155
if count == 4:
156
M1 = np.array([[5, 5]]).T
157
m4, cov4 = stats.multivariate_multiply(M1, cov2, M1, cov3)
158
e4 = stats.covariance_ellipse (cov4)
159
160
stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma,
161
alpha=0.25)
162
163
stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma,
164
edgecolor='r', alpha=0.25)
165
stats.plot_covariance_ellipse (m4[:,0], ellipse=e4, variance=sigma)
166
167
#plt.ylim([0,11])
168
#plt.xticks(np.arange(1,4,1))
169
170
plt.xlabel("Position")
171
plt.ylabel("Velocity")
172
173
plt.show()
174
175
176
def show_x_with_unobserved():
177
""" shows x=1,2,3 with velocity superimposed on top """
178
179
# plot velocity
180
sigma=[0.5,1.,1.5,2]
181
cov = np.array([[1,1],[1,1.1]])
182
stats.plot_covariance_ellipse ((2,2), cov=cov, variance=sigma, axis_equal=False)
183
184
# plot positions
185
cov = np.array([[0.003,0], [0,12]])
186
sigma=[0.5,1.,1.5,2]
187
e = stats.covariance_ellipse (cov)
188
189
stats.plot_covariance_ellipse ((1,1), ellipse=e, variance=sigma, axis_equal=False)
190
stats.plot_covariance_ellipse ((2,1), ellipse=e, variance=sigma, axis_equal=False)
191
stats.plot_covariance_ellipse ((3,1), ellipse=e, variance=sigma, axis_equal=False)
192
193
# plot intersection cirle
194
isct = Ellipse(xy=(2,2), width=.2, height=1.2, edgecolor='r', fc='None', lw=4)
195
plt.gca().add_artist(isct)
196
197
plt.ylim([0,11])
198
plt.xlim([0,4])
199
plt.xticks(np.arange(1,4,1))
200
201
plt.xlabel("Position")
202
plt.ylabel("Time")
203
204
plt.show()
205
206
207
208
def plot_3d_covariance(mean, cov):
209
""" plots a 2x2 covariance matrix positioned at mean. mean will be plotted
210
in x and y, and the probability in the z axis.
211
212
Parameters
213
----------
214
mean : 2x1 tuple-like object
215
mean for x and y coordinates. For example (2.3, 7.5)
216
217
cov : 2x2 nd.array
218
the covariance matrix
219
220
"""
221
222
# compute width and height of covariance ellipse so we can choose
223
# appropriate ranges for x and y
224
o,w,h = stats.covariance_ellipse(cov,3)
225
# rotate width and height to x,y axis
226
wx = abs(w*np.cos(o) + h*np.sin(o))*1.2
227
wy = abs(h*np.cos(o) - w*np.sin(o))*1.2
228
229
230
# ensure axis are of the same size so everything is plotted with the same
231
# scale
232
if wx > wy:
233
w = wx
234
else:
235
w = wy
236
237
minx = mean[0] - w
238
maxx = mean[0] + w
239
miny = mean[1] - w
240
maxy = mean[1] + w
241
242
xs = np.arange(minx, maxx, (maxx-minx)/40.)
243
ys = np.arange(miny, maxy, (maxy-miny)/40.)
244
xv, yv = np.meshgrid (xs, ys)
245
246
zs = np.array([100.* stats.multivariate_gaussian(np.array([x,y]),mean,cov) \
247
for x,y in zip(np.ravel(xv), np.ravel(yv))])
248
zv = zs.reshape(xv.shape)
249
250
ax = plt.figure().add_subplot(111, projection='3d')
251
ax.plot_surface(xv, yv, zv, rstride=1, cstride=1, cmap=cm.autumn)
252
253
ax.set_xlabel('X')
254
ax.set_ylabel('Y')
255
256
ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn)
257
ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)
258
259
260
def plot_3d_sampled_covariance(mean, cov):
261
""" plots a 2x2 covariance matrix positioned at mean. mean will be plotted
262
in x and y, and the probability in the z axis.
263
264
Parameters
265
----------
266
mean : 2x1 tuple-like object
267
mean for x and y coordinates. For example (2.3, 7.5)
268
269
cov : 2x2 nd.array
270
the covariance matrix
271
272
"""
273
274
# compute width and height of covariance ellipse so we can choose
275
# appropriate ranges for x and y
276
o,w,h = stats.covariance_ellipse(cov,3)
277
# rotate width and height to x,y axis
278
wx = abs(w*np.cos(o) + h*np.sin(o))*1.2
279
wy = abs(h*np.cos(o) - w*np.sin(o))*1.2
280
281
282
# ensure axis are of the same size so everything is plotted with the same
283
# scale
284
if wx > wy:
285
w = wx
286
else:
287
w = wy
288
289
minx = mean[0] - w
290
maxx = mean[0] + w
291
miny = mean[1] - w
292
maxy = mean[1] + w
293
294
count = 1000
295
x,y = multivariate_normal(mean=mean, cov=cov, size=count).T
296
297
xs = np.arange(minx, maxx, (maxx-minx)/40.)
298
ys = np.arange(miny, maxy, (maxy-miny)/40.)
299
xv, yv = np.meshgrid (xs, ys)
300
301
zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \
302
for xx,yy in zip(np.ravel(xv), np.ravel(yv))])
303
zv = zs.reshape(xv.shape)
304
305
ax = plt.figure().add_subplot(111, projection='3d')
306
ax.scatter(x,y, [0]*count, marker='.')
307
308
ax.set_xlabel('X')
309
ax.set_ylabel('Y')
310
311
ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn)
312
ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)
313
314
315
def plot_3_covariances():
316
317
P = [[2, 0], [0, 2]]
318
plt.subplot(131)
319
plot_covariance_ellipse((2, 7), cov=P, facecolor='g', alpha=0.2,
320
title='|2 0|\n|0 2|', axis_equal=False)
321
plt.ylim((4, 10))
322
plt.gca().set_aspect('equal', adjustable='box')
323
324
plt.subplot(132)
325
P = [[2, 0], [0, 9]]
326
plt.ylim((4, 10))
327
plt.gca().set_aspect('equal', adjustable='box')
328
plot_covariance_ellipse((2, 7), P, facecolor='g', alpha=0.2,
329
axis_equal=False, title='|2 0|\n|0 9|')
330
331
plt.subplot(133)
332
P = [[2, 1.2], [1.2, 2]]
333
plt.ylim((4, 10))
334
plt.gca().set_aspect('equal', adjustable='box')
335
plot_covariance_ellipse((2, 7), P, facecolor='g', alpha=0.2,
336
axis_equal=False,
337
title='|2 1.2|\n|1.2 2|')
338
339
plt.tight_layout()
340
plt.show()
341
342
343
def plot_correlation_covariance():
344
P = [[4, 3.9], [3.9, 4]]
345
plot_covariance_ellipse((5, 10), P, edgecolor='k',
346
variance=[1, 2**2, 3**2])
347
plt.xlabel('X')
348
plt.ylabel('Y')
349
plt.gca().autoscale(tight=True)
350
plt.axvline(7.5, ls='--', lw=1)
351
plt.axhline(12.5, ls='--', lw=1)
352
plt.scatter(7.5, 12.5, s=2000, alpha=0.5)
353
plt.title('|4.0 3.9|\n|3.9 4.0|')
354
plt.show()
355
356
357
import book_plots as bp
358
def plot_track(ps, zs, cov, std_scale=1,
359
plot_P=True, y_lim=None,
360
title='Kalman Filter'):
361
362
count = len(zs)
363
actual = np.linspace(0, count - 1, count)
364
cov = np.asarray(cov)
365
std = std_scale*np.sqrt(cov[:,0,0])
366
std_top = np.minimum(actual+std, [count + 10])
367
std_btm = np.maximum(actual-std, [-50])
368
369
std_top = actual+std
370
std_btm = actual-std
371
372
bp.plot_track(actual,c='k')
373
bp.plot_measurements(range(1, count + 1), zs)
374
bp.plot_filter(range(1, count + 1), ps)
375
376
plt.plot(std_top, linestyle=':', color='k', lw=1, alpha=0.4)
377
plt.plot(std_btm, linestyle=':', color='k', lw=1, alpha=0.4)
378
plt.fill_between(range(len(std_top)), std_top, std_btm,
379
facecolor='yellow', alpha=0.2, interpolate=True)
380
plt.legend(loc=4)
381
if y_lim is not None:
382
plt.ylim(y_lim)
383
else:
384
plt.ylim((-50, count + 10))
385
386
plt.xlim((0,count))
387
plt.title(title)
388
plt.show()
389
390
if plot_P:
391
ax = plt.subplot(121)
392
ax.set_title("$\sigma^2_x$")
393
plot_covariance(cov, (0, 0))
394
ax = plt.subplot(122)
395
ax.set_title("$\sigma^2_y$")
396
plot_covariance(cov, (1, 1))
397
plt.show()
398
399
def plot_covariance(P, index=(0, 0)):
400
ps = []
401
for p in P:
402
ps.append(p[index[0], index[1]])
403
plt.plot(ps)
404
405
406
407
if __name__ == "__main__":
408
pass
409
#show_position_chart()
410
#plot_3d_covariance((2,7), np.array([[8.,0],[0,4.]]))
411
#plot_3d_sampled_covariance([2,7], [[8.,0],[0,4.]])
412
#show_residual_chart()
413
414
#show_position_chart()
415
#show_x_error_chart(4)
416
417
418