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 scipy.linalg import inv
24
from filterpy.kalman import KalmanFilter, InformationFilter
25
26
27
DO_PLOT = False
28
def test_1d_0P():
29
f = KalmanFilter (dim_x=2, dim_z=1)
30
inf = InformationFilter (dim_x=2, dim_z=1)
31
32
f.x = np.array([[2.],
33
[0.]]) # initial state (location and velocity)
34
35
inf.x = f.x.copy()
36
f.F = (np.array([[1.,1.],
37
[0.,1.]])) # state transition matrix
38
39
inf.F = f.F.copy()
40
f.H = np.array([[1.,0.]]) # Measurement function
41
inf.H = np.array([[1.,0.]]) # Measurement function
42
f.R = 5. # state uncertainty
43
inf.R_inv = 1./5 # state uncertainty
44
f.Q = 0.0001 # process uncertainty
45
inf.Q = 0.0001
46
f.P *= 20
47
inf.P_inv = 0
48
#inf.P_inv = inv(f.P)
49
50
m = []
51
r = []
52
r2 = []
53
54
55
zs = []
56
for t in range (100):
57
# create measurement = t plus white noise
58
z = t + random.randn()*20
59
zs.append(z)
60
61
# perform kalman filtering
62
f.predict()
63
f.update(z)
64
65
inf.predict()
66
inf.update(z)
67
68
# save data
69
r.append (f.x[0,0])
70
r2.append (inf.x[0,0])
71
m.append(z)
72
73
#assert abs(f.x[0,0] - inf.x[0,0]) < 1.e-12
74
75
if DO_PLOT:
76
plt.plot(m)
77
plt.plot(r)
78
plt.plot(r2)
79
80
81
82
def test_1d():
83
f = KalmanFilter (dim_x=2, dim_z=1)
84
inf = InformationFilter (dim_x=2, dim_z=1)
85
86
f.x = np.array([[2.],
87
[0.]]) # initial state (location and velocity)
88
89
inf.x = f.x.copy()
90
f.F = (np.array([[1.,1.],
91
[0.,1.]])) # state transition matrix
92
93
inf.F = f.F.copy()
94
f.H = np.array([[1.,0.]]) # Measurement function
95
inf.H = np.array([[1.,0.]]) # Measurement function
96
f.R = 5. # state uncertainty
97
inf.R_inv = 1./5 # state uncertainty
98
f.Q = 0.0001 # process uncertainty
99
inf.Q = 0.0001
100
101
m = []
102
r = []
103
r2 = []
104
105
106
zs = []
107
for t in range (100):
108
# create measurement = t plus white noise
109
z = t + random.randn()*20
110
zs.append(z)
111
112
# perform kalman filtering
113
f.update(z)
114
f.predict()
115
116
inf.update(z)
117
inf.predict()
118
119
# save data
120
r.append (f.x[0,0])
121
r2.append (inf.x[0,0])
122
m.append(z)
123
124
assert abs(f.x[0,0] - inf.x[0,0]) < 1.e-12
125
126
if DO_PLOT:
127
plt.plot(m)
128
plt.plot(r)
129
plt.plot(r2)
130
131
132
if __name__ == "__main__":
133
DO_PLOT = True
134
test_1d()
135
136