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 Created on Sep 27, 2010
36
37 @author: bolme
38 '''
39
40 import numpy as np
41
43
44 - def __init__(self,x_0,P_0,F,Q,H,R,B=None):
45 '''
46 Based on wikipedia.
47
48 Warning: Controls have not been tested.
49
50 @param x_0: initial state
51 @param P_0: initial state covariance estimate
52 @param F: the state transistion model
53 @param B: control input model
54 @param Q: process noise covariance
55 @param z_k: measurement
56 @param H: observation model - transform state to observation
57 @param R: measurement noise covariance
58 not needed
59 @param w: process noise
60 @param v_k: measurement noise
61 '''
62
63 self.F = np.array(F,dtype=np.float64)
64 d = self.F.shape[0]
65 assert self.F.shape == (d,d)
66
67 self.P_k = np.array(P_0,dtype=np.float64)
68 assert self.P_k.shape == (d,d)
69
70 if B == None:
71 B = np.zeros((d,1))
72 self.B = np.array(B,dtype=np.float64)
73 b = self.B.shape[1]
74 assert self.B.shape == (d,b)
75
76 self.Q = np.array(Q,dtype=np.float64)
77 assert self.Q.shape == (d,d)
78
79 self.H = np.array(H,dtype=np.float64)
80 m = self.H.shape[0]
81 assert self.H.shape == (m,d)
82
83 self.R = np.array(R,dtype=np.float64)
84 assert self.R.shape == (m,m)
85
86 self.x_k = np.array(x_0,dtype=np.float64).reshape(d,1)
87
88 self.d = d
89 self.b = b
90 self.m = m
91
92
93
94
96
97
98 b = self.b
99
100
101 if u == None:
102 u = np.zeros((b,))
103 u = np.array(u,dtype=np.float64).reshape(b,1)
104
105 x_k = np.dot(self.F,self.x_k) + np.dot(self.B,u)
106 return x_k
107
108
109 - def update(self, z=None, u=None):
110 '''
111 @param z: measurement
112 @param u: control
113 '''
114
115 m = self.m
116 b = self.b
117 d = self.d
118
119
120 if u == None:
121 u = np.zeros((b,))
122 u = np.array(u,dtype=np.float64).reshape(b,1)
123
124
125 x_k = np.dot(self.F,self.x_k) + np.dot(self.B,u)
126
127
128 P_k = np.dot(np.dot(self.F,self.P_k),self.F.T) + self.Q
129
130
131 if z == None:
132 self.x_k = x_k
133 self.P_k = P_k
134 return self.x_k
135
136 z = np.array(z,dtype=np.float64).reshape(m,1)
137
138
139 y_k = z - np.dot(self.H,x_k)
140
141
142 S_k = np.dot(np.dot(self.H,P_k),self.H.T) + self.R
143
144
145 K = np.dot(np.dot(P_k,self.H.T),np.linalg.inv(S_k))
146
147
148 x_k = x_k + np.dot(K,y_k)
149
150
151 P_k = np.dot(np.eye(d) - np.dot(K,self.H),P_k)
152
153
154 self.x_k = x_k
155 self.P_k = P_k
156
157 return self.x_k
158
160 ''' Return the current estimate of state. '''
161 return self.x_k
162
164 self.x_k = np.array(x_k,np.float64)
165
167 return "KalmanFilter<%s>"%self.state().flatten()
168