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 FadingKalmanFilter
24
25
DO_PLOT = False
26
def test_noisy_1d():
27
f = FadingKalmanFilter (5., 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
measurements = []
41
results = []
42
43
zs = []
44
for t in range (100):
45
# create measurement = t plus white noise
46
z = t + random.randn()*20
47
zs.append(z)
48
49
# perform kalman filtering
50
f.update(z)
51
f.predict()
52
53
# save data
54
results.append (f.X[0,0])
55
measurements.append(z)
56
57
58
# now do a batch run with the stored z values so we can test that
59
# it is working the same as the recursive implementation.
60
# give slightly different P so result is slightly different
61
f.X = np.array([[2.,0]]).T
62
f.P = np.eye(2)*100.
63
m,c,_,_ = f.batch_filter(zs,update_first=False)
64
65
# plot data
66
if DO_PLOT:
67
p1, = plt.plot(measurements,'r', alpha=0.5)
68
p2, = plt.plot (results,'b')
69
p4, = plt.plot(m[:,0], 'm')
70
p3, = plt.plot ([0,100],[0,100], 'g') # perfect result
71
plt.legend([p1,p2, p3, p4],
72
["noisy measurement", "KF output", "ideal", "batch"], loc=4)
73
74
75
plt.show()
76
77
78
if __name__ == "__main__":
79
DO_PLOT = True
80
test_noisy_1d()
81