-
Notifications
You must be signed in to change notification settings - Fork 1
/
filter_comparison.py
352 lines (290 loc) · 12 KB
/
filter_comparison.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
import matplotlib.pyplot as plt
import extended_kalman_filter as ekf
import trajectory_generator
import unscented_kalman_filter as ukf
import particle_filter as pf
import kalman_filter as kf
import models
import jax
import datetime
jax.config.update('jax_platform_name', 'cpu')
import numpy as np
import os
import time
def plot_results(t, trajectory, ekf_est, ukf_est, pf_est, save_plot=False):
# Turn interactive plotting off
plt.ioff()
num_states = trajectory.shape[1]
symb = ['sx [m]', 'vx [ms^-1]', 'ax [ms^-2] ', 'sy [m]', 'vy [ms^-1]', 'ay [ms^-2]', r'theta [rad]']
file_symb = ['sx', 'vx', 'ax ', 'sy', 'vy', 'ay', r'theta']
# Generate a timestamp for unique filenames
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
for state_idx in range(num_states):
if state_idx == 0 or state_idx == 3 or state_idx == 6:
plt.figure(figsize=(8, 4))
plt.plot(t, trajectory[:, state_idx], 'k-', label='trajektorija')
plt.plot(t, ekf_est[:, state_idx], 'b--', marker='o', markevery=50, label='prošireni KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, ukf_est[:, state_idx], 'g-.', marker='s', markevery=50, label='neosetljiv KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, pf_est[:, state_idx], 'r:', marker='^', markevery=50, label='čestični filtar')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if save_plot:
nm = os.path.join('figures', f'all_{file_symb[state_idx]}.png')
plt.savefig(nm, dpi=600)
if state_idx == 1 or state_idx == 2:
th = trajectory[:, 6]
plt.figure(figsize=(8, 4))
plt.plot(t, np.cos(th)*trajectory[:, state_idx] - np.sin(th)*trajectory[:, state_idx+3], 'k-', label='trajektorija')
plt.plot(t, np.cos(th)*ekf_est[:, state_idx] - np.sin(th)*ekf_est[:, state_idx+3], 'b--', marker='o', markevery=50, label='prošireni KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, np.cos(th)*ukf_est[:, state_idx] - np.sin(th)*ukf_est[:, state_idx+3], 'g-.', marker='s', markevery=50, label='neosetljiv KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, np.cos(th)*pf_est[:, state_idx] - np.sin(th)*pf_est[:, state_idx+3], 'r:', marker='^', markevery=50, label='čestični filtar')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if save_plot:
nm = os.path.join('figures', f'all_{file_symb[state_idx]}.png')
plt.savefig(nm, dpi=600)
if state_idx == 4 or state_idx == 5:
th = trajectory[:, 6]
plt.figure(figsize=(8, 4))
plt.plot(t, np.cos(th) * trajectory[:, state_idx] + np.sin(th) * trajectory[:, state_idx - 3], 'k-',
label='trajektorija')
plt.plot(t, np.cos(th) * ekf_est[:, state_idx] + np.sin(th) * ekf_est[:, state_idx - 3], 'b--', marker='o',
markevery=50, label='prošireni KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, np.cos(th) * ukf_est[:, state_idx] + np.sin(th) * ukf_est[:, state_idx - 3],
'g-.', marker = 's', markevery = 50, label = 'neosetljiv KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
plt.plot(t, np.cos(th) * pf_est[:, state_idx] + np.sin(th) * pf_est[:, state_idx - 3], 'r:', marker='^',
markevery=50, label='čestični filtar')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if save_plot:
nm = os.path.join('figures', f'all_{file_symb[state_idx]}.png')
plt.savefig(nm, dpi=600)
plt.close('all')
def param_init(x0=np.zeros((7, ))):
dt = 0.05
N = 101
t_end = (N-1)*dt
t = np.linspace(0, t_end, N)
trajectory = trajectory_generator.generate_trajectory(t)
z = trajectory_generator.measure_full_trajectory(trajectory)
x0 = x0
R = (np.diag([.1, 0.1, .1, 0.1, 0.1])**2)
Q = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0.1 ** 2 * dt, 0, 0, 0, 0],
[0, 0.1 ** 2 * dt, 0.1 ** 2, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0.1 ** 2 * dt, 0],
[0, 0, 0, 0, 0.1 ** 2 * dt, 0.1 ** 2, 0],
[0, 0, 0, 0, 0, 0, 0.1 ** 2]]
)
P = np.eye(7)
return t, trajectory, z, x0, R, Q, P
def ekf_init(x0, R, Q, P):
f = lambda x: models.proces_model(x)
h = lambda z: models.measurement_model(z)
Jf = jax.jacobian(f)
Jh = jax.jacobian(h)
ekf_1 = ekf.ExtendedKalmanFilter(dim_x=7, dim_z=5)
ekf_1.Q = Q
ekf_1.dxh = Jh
ekf_1.R = R
ekf_1.dxf = Jf
ekf_1.f = models.proces_model
ekf_1.h = models.measurement_model
ekf_1.P = P
ekf_1.x = x0
return ekf_1
def ukf_init(x0, R, Q, P):
ukf_1 = ukf.UnscentedKalmanFilter(dim_x=7, dim_z=5)
ukf_1.h = models.measurement_model_ukf
ukf_1.f = models.proces_model_ukf
ukf_1.P = P
ukf_1.x = x0
ukf_1.R = R
ukf_1.Q = Q
return ukf_1
def pf_init(z, t):
sensor_data = [z[idx, :] for idx in range(len(t))]
pf_1 = pf.particle_filter(sensor_data=sensor_data, N_particles=20000, algorithm="dynamic_resampling")
return pf_1
def run_comparison(x0, plot=False, save_plot=False):
t, trajectory, z, x0, R, Q, P = param_init(x0)
dt = t[1] - t[0]
ekf = ekf_init(x0, R, Q, P)
ekf_est = np.zeros(trajectory.shape)
start = time.time()
for idx, i in enumerate(t):
ekf.update(z=z[idx, :])
ekf_est[idx, :] = np.array(ekf.x)
ekf.predict()
t_ekf = time.time()-start
ukf = ukf_init(x0, R, Q, P)
ukf_est = np.zeros(trajectory.shape)
start = time.time()
for idx, i in enumerate(t):
ukf.update(z=z[idx, :])
ukf_est[idx, :] = np.array(ukf.x)
ukf.prediction()
t_ukf = time.time() - start
pf = pf_init(z, t)
pf_est = np.zeros(trajectory.shape)
start = time.time()
for idx, i in enumerate(t):
pf_est[idx, :] = pf.particle_filtering()
t_pf = time.time()-start
if plot:
plot_results(t, trajectory, ekf_est, ukf_est, pf_est, save_plot)
rms_ekf = np.sqrt(np.mean((ekf_est - trajectory) ** 2, axis=0))
rms_ukf = np.sqrt(np.mean((ukf_est - trajectory) ** 2, axis=0))
rms_pf = np.sqrt(np.mean((pf_est - trajectory) ** 2, axis=0))
kf_est = np.zeros((trajectory.shape[0], 4))
rms_calc = np.zeros((trajectory.shape[0], 4))
kf_est[:, 0] = z[:, 0]
kf_est[:, 2] = z[:, 1]
kf_est[:, 1] = np.cos(trajectory[:, 6]) * z[:, 1] - np.sin(trajectory[:, 6]) * z[:, 3]
kf_est[:, 3] = np.cos(trajectory[:, 6]) * z[:, 3] + np.sin(trajectory[:, 6]) * z[:, 1]
rms_calc[:, 0] = trajectory[:, 0]
rms_calc[:, 1] = np.cos(trajectory[:, 6]) * trajectory[:, 1] - np.sin(trajectory[:, 6]) * trajectory[:, 4]
rms_calc[:, 2] = trajectory[:, 3]
rms_calc[:, 3] = np.cos(trajectory[:, 6]) * trajectory[:, 4] + np.sin(trajectory[:, 6]) * trajectory[:, 1]
rms = np.sqrt(np.mean((kf_est - rms_calc) ** 2, axis=0))
return rms_ekf, rms_ukf, rms_pf, t_ekf, t_ukf, t_pf, rms
def param_init_kalman(x0):
dt = 0.05
N = 101
t_end = (N - 1) * dt
t = np.linspace(0, t_end, N)
trajectory = trajectory_generator.generate_trajectory(t)
z = trajectory_generator.measure_full_trajectory_kalman(trajectory)
x0 = x0
R = np.diag([.1, .1])**2
Q = np.array([[0, 0.1**2*dt, 0, 0],
[0.1**2*dt, 0.1**2, 0, 0],
[0, 0, 0, 0.1**2*dt],
[0, 0, 0.1**2*dt, 0.1**2]])
P = np.eye(4)
return t, trajectory, z, x0, R, Q, P
def kf_init(x0, R, Q, P):
dt = 0.05
kf_1 = kf.KalmanFilter(4, 2)
kf_1.P = P
kf_1.R = R
kf_1.Q = Q
kf_1.x = x0
kf_1.H = np.array([[1, 0, 0, 0], [0, 0, 1, 0]])
kf_1.F = np.array([[1, dt, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, dt],
[0, 0, 0, 1]])
return kf_1
def plot_kalman(t, trajectory, kf_est, save_plot=False):
# Turn interactive plotting off
plt.ioff()
num_states = kf_est.shape[1]
symb = ['sx [m]', 'vx [ms^-1]', 'sy [m]', 'vy [ms^-1]']
file_symb = ['sx', 'vx', 'sy', 'vy']
# Generate a timestamp for unique filenames
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
for state_idx in range(num_states):
if state_idx == 0:
plt.figure(figsize=(8, 4))
plt.plot(t, trajectory[:, state_idx], 'k-', label='trajektorija')
plt.plot(t, kf_est[:, state_idx], 'b--', marker='o', markevery=50, label='KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if state_idx==1:
plt.figure(figsize=(8, 4))
v = np.cos(trajectory[:, 6])*trajectory[:, 1] - np.sin(trajectory[:, 6])*trajectory[:, 4]
plt.plot(t, v, 'k-', label='trajektorija')
plt.plot(t, kf_est[:, state_idx], 'b--', marker='o', markevery=50, label='KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if state_idx==3:
plt.figure(figsize=(8, 4))
v = np.cos(trajectory[:, 6])*trajectory[:, 4] + np.sin(trajectory[:, 6])*trajectory[:, 1]
plt.plot(t, v, 'k-', label='trajektorija')
plt.plot(t, kf_est[:, state_idx], 'b--', marker='o', markevery=50, label='KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if state_idx == 2:
plt.figure(figsize=(8, 4))
plt.plot(t, trajectory[:, state_idx+1], 'k-', label='trajektorija')
plt.plot(t, kf_est[:, state_idx], 'b--', marker='o', markevery=50, label='KF')
plt.grid(True)
plt.legend()
plt.xlabel('t [s]')
plt.ylabel(symb[state_idx])
plt.tight_layout()
if save_plot:
nm = os.path.join('figures', f'kf_{file_symb[state_idx]}.png')
plt.savefig(nm, dpi=600)
def only_kalman(x0, plot=False, save_plot=False):
t, trajectory, z, x0, R, Q, P = param_init_kalman(x0)
kf = kf_init(x0, R, Q, P)
kf_est = np.zeros((trajectory.shape[0], 4))
start_time = time.time()
for idx, i in enumerate(t):
kf.update(z=z[idx, :])
kf_est[idx, :] = np.array(kf.x)
kf.predict()
runtime = time.time()-start_time
if plot:
plot_kalman(t, trajectory, kf_est, save_plot)
rms_calc = np.zeros((trajectory.shape[0], 4))
rms_calc[:, 0] = trajectory[:, 0]
rms_calc[:, 1] = np.cos(trajectory[:, 6])*trajectory[:, 1] - np.sin(trajectory[:, 6])*trajectory[:, 4]
rms_calc[:, 2] = trajectory[:, 3]
rms_calc[:, 3] = np.cos(trajectory[:, 6])*trajectory[:, 4] + np.sin(trajectory[:, 6])*trajectory[:, 1]
rms = np.sqrt(np.mean((kf_est - rms_calc)**2, axis=0))
kf_est[:, 0] = z[:, 0]
kf_est[:, 2] = z[:, 1]
rms_true = np.sqrt(np.mean((kf_est - rms_calc)**2, axis=0))
return rms, rms_true, runtime