Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
96129 views
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Sun May 18 11:09:23 2014
4
5
@author: rlabbe
6
"""
7
8
from __future__ import division
9
10
from filterpy.stats import multivariate_gaussian
11
from matplotlib import cm
12
import matplotlib.pyplot as plt
13
from mpl_toolkits.mplot3d import Axes3D
14
import numpy as np
15
from numpy.random import normal, multivariate_normal
16
import scipy.stats
17
18
def plot_nonlinear_func(data, f, gaussian, num_bins=300):
19
20
# linearize at mean to simulate EKF
21
#x = gaussian[0]
22
23
# equation of linearization
24
#m = df(x)
25
#b = f(x) - x*m
26
27
# compute new mean and variance based on EKF equations
28
ys = f(data)
29
x0 = gaussian[0]
30
in_std = np.sqrt(gaussian[1])
31
y = f(x0)
32
std = np.std(ys)
33
34
in_lims = [x0-in_std*3, x0+in_std*3]
35
out_lims = [y-std*3, y+std*3]
36
37
38
#plot output
39
h = np.histogram(ys, num_bins, density=False)
40
plt.subplot(2,2,4)
41
plt.plot(h[0], h[1][1:], lw=4, alpha=0.5)
42
plt.ylim(out_lims[1], out_lims[0])
43
plt.gca().xaxis.set_ticklabels([])
44
plt.title('output')
45
46
plt.axhline(np.mean(ys), ls='--', lw=2)
47
plt.axhline(f(x0), lw=1)
48
49
50
norm = scipy.stats.norm(y, in_std)
51
52
'''min_x = norm.ppf(0.001)
53
max_x = norm.ppf(0.999)
54
xs = np.arange(min_x, max_x, (max_x - min_x) / 1000)
55
pdf = norm.pdf(xs)
56
plt.plot(pdf * max(h[0])/max(pdf), xs, lw=1, color='k')
57
print(max(norm.pdf(xs)))'''
58
59
# plot transfer function
60
plt.subplot(2,2,3)
61
x = np.arange(in_lims[0], in_lims[1], 0.1)
62
y = f(x)
63
plt.plot (x,y, 'k')
64
isct = f(x0)
65
plt.plot([x0, x0, in_lims[1]], [out_lims[1], isct, isct], color='r', lw=1)
66
plt.xlim(in_lims)
67
plt.ylim(out_lims)
68
#plt.axis('equal')
69
plt.title('function')
70
71
# plot input
72
h = np.histogram(data, num_bins, density=True)
73
74
plt.subplot(2,2,1)
75
plt.plot(h[1][1:], h[0], lw=4)
76
plt.xlim(in_lims)
77
plt.gca().yaxis.set_ticklabels([])
78
plt.title('input')
79
80
plt.show()
81
82
83
import math
84
def plot_ekf_vs_mc():
85
86
def fx(x):
87
return x**3
88
89
def dfx(x):
90
return 3*x**2
91
92
mean = 1
93
var = .1
94
std = math.sqrt(var)
95
96
data = normal(loc=mean, scale=std, size=50000)
97
d_t = fx(data)
98
99
mean_ekf = fx(mean)
100
101
slope = dfx(mean)
102
std_ekf = abs(slope*std)
103
104
105
norm = scipy.stats.norm(mean_ekf, std_ekf)
106
xs = np.linspace(-3, 5, 200)
107
plt.plot(xs, norm.pdf(xs), lw=2, ls='--', color='b')
108
plt.hist(d_t, bins=200, normed=True, histtype='step', lw=2, color='g')
109
110
actual_mean = d_t.mean()
111
plt.axvline(actual_mean, lw=2, color='g', label='Monte Carlo')
112
plt.axvline(mean_ekf, lw=2, ls='--', color='b', label='EKF')
113
plt.legend()
114
plt.show()
115
116
print('actual mean={:.2f}, std={:.2f}'.format(d_t.mean(), d_t.std()))
117
print('EKF mean={:.2f}, std={:.2f}'.format(mean_ekf, std_ekf))
118
119
120
from filterpy.kalman import MerweScaledSigmaPoints, unscented_transform
121
122
def plot_ukf_vs_mc(alpha=0.001, beta=3., kappa=1.):
123
124
def fx(x):
125
return x**3
126
127
def dfx(x):
128
return 3*x**2
129
130
mean = 1
131
var = .1
132
std = math.sqrt(var)
133
134
data = normal(loc=mean, scale=std, size=50000)
135
d_t = fx(data)
136
137
138
points = MerweScaledSigmaPoints(1, alpha, beta, kappa)
139
Wm, Wc = points.weights()
140
sigmas = points.sigma_points(mean, var)
141
142
sigmas_f = np.zeros((3, 1))
143
for i in range(3):
144
sigmas_f[i] = fx(sigmas[i, 0])
145
146
### pass through unscented transform
147
ukf_mean, ukf_cov = unscented_transform(sigmas_f, Wm, Wc)
148
ukf_mean = ukf_mean[0]
149
ukf_std = math.sqrt(ukf_cov[0])
150
151
norm = scipy.stats.norm(ukf_mean, ukf_std)
152
xs = np.linspace(-3, 5, 200)
153
plt.plot(xs, norm.pdf(xs), ls='--', lw=1, color='b')
154
plt.hist(d_t, bins=200, normed=True, histtype='step', lw=1, color='g')
155
156
actual_mean = d_t.mean()
157
plt.axvline(actual_mean, lw=1, color='g', label='Monte Carlo')
158
plt.axvline(ukf_mean, lw=1, ls='--', color='b', label='UKF')
159
plt.legend()
160
plt.show()
161
162
print('actual mean={:.2f}, std={:.2f}'.format(d_t.mean(), d_t.std()))
163
print('UKF mean={:.2f}, std={:.2f}'.format(ukf_mean, ukf_std))
164
165
166
167
def test_plot():
168
import math
169
from numpy.random import normal
170
from scipy import stats
171
global data
172
173
def f(x):
174
return 2*x + 1
175
176
mean = 2
177
var = 3
178
std = math.sqrt(var)
179
180
data = normal(loc=2, scale=std, size=50000)
181
182
d2 = f(data)
183
n = scipy.stats.norm(mean, std)
184
185
kde1 = stats.gaussian_kde(data, bw_method='silverman')
186
kde2 = stats.gaussian_kde(d2, bw_method='silverman')
187
xs = np.linspace(-10, 10, num=200)
188
189
#plt.plot(data)
190
plt.plot(xs, kde1(xs))
191
plt.plot(xs, kde2(xs))
192
plt.plot(xs, n.pdf(xs), color='k')
193
194
num_bins=100
195
h = np.histogram(data, num_bins, density=True)
196
plt.plot(h[1][1:], h[0], lw=4)
197
198
h = np.histogram(d2, num_bins, density=True)
199
plt.plot(h[1][1:], h[0], lw=4)
200
201
202
203
def plot_bivariate_colormap(xs, ys):
204
xs = np.asarray(xs)
205
ys = np.asarray(ys)
206
xmin = xs.min()
207
xmax = xs.max()
208
ymin = ys.min()
209
ymax = ys.max()
210
values = np.vstack([xs, ys])
211
kernel = scipy.stats.gaussian_kde(values)
212
X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
213
positions = np.vstack([X.ravel(), Y.ravel()])
214
215
Z = np.reshape(kernel.evaluate(positions).T, X.shape)
216
plt.gca().imshow(np.rot90(Z), cmap=plt.cm.Greys,
217
extent=[xmin, xmax, ymin, ymax])
218
219
220
221
def plot_monte_carlo_mean(xs, ys, f, mean_fx, label, plot_colormap=True):
222
fxs, fys = f(xs, ys)
223
224
computed_mean_x = np.average(fxs)
225
computed_mean_y = np.average(fys)
226
227
plt.subplot(121)
228
plt.gca().grid(b=False)
229
230
plot_bivariate_colormap(xs, ys)
231
232
plt.scatter(xs, ys, marker='.', alpha=0.02, color='k')
233
plt.xlim(-20, 20)
234
plt.ylim(-20, 20)
235
236
plt.subplot(122)
237
plt.gca().grid(b=False)
238
239
plt.scatter(fxs, fys, marker='.', alpha=0.02, color='k')
240
plt.scatter(mean_fx[0], mean_fx[1],
241
marker='v', s=300, c='r', label='Linearized Mean')
242
plt.scatter(computed_mean_x, computed_mean_y,
243
marker='*',s=120, c='r', label='Computed Mean')
244
245
plot_bivariate_colormap(fxs, fys)
246
plt.ylim([-10, 200])
247
plt.xlim([-100, 100])
248
plt.legend(loc='best', scatterpoints=1)
249
print ('Difference in mean x={:.3f}, y={:.3f}'.format(
250
computed_mean_x-mean_fx[0], computed_mean_y-mean_fx[1]))
251
252
253
254
def plot_cov_ellipse_colormap(cov=[[1,1],[1,1]]):
255
side = np.linspace(-3,3,24)
256
X,Y = np.meshgrid(side,side)
257
258
pos = np.empty(X.shape + (2,))
259
pos[:, :, 0] = X;
260
pos[:, :, 1] = Y
261
plt.axes(xticks=[], yticks=[], frameon=True)
262
rv = scipy.stats.multivariate_normal((0,0), cov)
263
plt.gca().grid(b=False)
264
plt.gca().imshow(rv.pdf(pos), cmap=plt.cm.Greys, origin='lower')
265
plt.show()
266
267
268
269
def plot_multiple_gaussians(xs, ps, x_range, y_range, N):
270
""" given a list of 2d states (x,y) and 2x2 covariance matrices, produce
271
a surface plot showing all of the gaussians"""
272
273
274
xs = np.asarray(xs)
275
x = np.linspace (x_range[0], x_range[1], N)
276
y = np.linspace (y_range[0], y_range[1], N)
277
xx, yy = np.meshgrid(x, y)
278
zv = np.zeros((N, N))
279
280
for mean, cov in zip(xs, ps):
281
zs = np.array([multivariate_gaussian(np.array([i ,j]), mean, cov)
282
for i, j in zip(np.ravel(xx), np.ravel(yy))])
283
zv += zs.reshape(xx.shape)
284
285
ax = plt.figure().add_subplot(111, projection='3d')
286
ax.plot_surface(xx, yy, zv, rstride=1, cstride=1, lw=.5, edgecolors='#191919',
287
antialiased=True, shade=True, cmap=cm.autumn)
288
ax.view_init(elev=40., azim=250)
289
290
291
if __name__ == "__main__":
292
plot_cov_ellipse_colormap(cov=[[2, 1.2], [1.2, 2]])
293
'''
294
from numpy.random import normal
295
import numpy as np
296
297
plot_ukf_vs_mc()'''
298
299
'''x0 = (1, 1)
300
data = normal(loc=x0[0], scale=x0[1], size=500000)
301
302
def g(x):
303
return x*x
304
return (np.cos(3*(x/2+0.7)))*np.sin(0.7*x)-1.6*x
305
return -2*x
306
307
308
#plot_transfer_func (data, g, lims=(-3,3), num_bins=100)
309
plot_nonlinear_func (data, g, gaussian=x0,
310
num_bins=100)
311
'''
312