Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
96131 views
1
# -*- coding: utf-8 -*-
2
"""Copyright 2015 Roger R Labbe Jr.
3
4
FilterPy library.
5
http://github.com/rlabbe/filterpy
6
7
Documentation at:
8
https://filterpy.readthedocs.org
9
10
Supporting book at:
11
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
12
13
This is licensed under an MIT license. See the readme.MD file
14
for more information.
15
"""
16
17
from __future__ import (absolute_import, division, print_function,
18
unicode_literals)
19
20
import numpy.random as random
21
import numpy as np
22
import matplotlib.pyplot as plt
23
from filterpy.kalman import SquareRootKalmanFilter, KalmanFilter
24
25
DO_PLOT = False
26
def test_noisy_1d():
27
f = KalmanFilter (dim_x=2, dim_z=1)
28
29
f.x = np.array([[2.],
30
[0.]]) # initial state (location and velocity)
31
32
f.F = np.array([[1.,1.],
33
[0.,1.]]) # state transition matrix
34
35
f.H = np.array([[1.,0.]]) # Measurement function
36
f.P *= 1000. # covariance matrix
37
f.R = 5 # state uncertainty
38
f.Q = 0.0001 # process uncertainty
39
40
fsq = SquareRootKalmanFilter (dim_x=2, dim_z=1)
41
42
fsq.x = np.array([[2.],
43
[0.]]) # initial state (location and velocity)
44
45
fsq.F = np.array([[1.,1.],
46
[0.,1.]]) # state transition matrix
47
48
fsq.H = np.array([[1.,0.]]) # Measurement function
49
fsq.P = np.eye(2) * 1000. # covariance matrix
50
fsq.R = 5 # state uncertainty
51
fsq.Q = 0.0001 # process uncertainty
52
53
measurements = []
54
results = []
55
56
zs = []
57
for t in range (100):
58
# create measurement = t plus white noise
59
z = t + random.randn()*20
60
zs.append(z)
61
62
# perform kalman filtering
63
f.update(z)
64
f.predict()
65
66
fsq.update(z)
67
fsq.predict()
68
69
assert abs(f.x[0,0] - fsq.x[0,0]) < 1.e-12
70
assert abs(f.x[1,0] - fsq.x[1,0]) < 1.e-12
71
72
# save data
73
results.append (f.x[0,0])
74
measurements.append(z)
75
76
77
p = f.P - fsq.P
78
print(f.P)
79
print(fsq.P)
80
81
for i in range(f.P.shape[0]):
82
assert abs(f.P[i,i] - fsq.P[i,i]) < 0.01
83
84
85
# now do a batch run with the stored z values so we can test that
86
# it is working the same as the recursive implementation.
87
# give slightly different P so result is slightly different
88
f.x = np.array([[2.,0]]).T
89
f.P = np.eye(2)*100.
90
m,c,_,_ = f.batch_filter(zs,update_first=False)
91
92
# plot data
93
if DO_PLOT:
94
p1, = plt.plot(measurements,'r', alpha=0.5)
95
p2, = plt.plot (results,'b')
96
p4, = plt.plot(m[:,0], 'm')
97
p3, = plt.plot ([0,100],[0,100], 'g') # perfect result
98
plt.legend([p1,p2, p3, p4],
99
["noisy measurement", "KF output", "ideal", "batch"], 4)
100
101
102
plt.show()
103
104
105
if __name__ == "__main__":
106
DO_PLOT = True
107
test_noisy_1d()
108