forked from JunshengFu/tracking-with-Extended-Kalman-Filter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kalman_filter.cpp
114 lines (90 loc) · 2.44 KB
/
kalman_filter.cpp
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
#include <math.h>
#include "kalman_filter.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
const float PI2 = 2 * M_PI;
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in,
MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) {
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
void KalmanFilter::Predict() {
/**
TODO:
* predict the state
*/
x_ = F_ * x_;
MatrixXd Ft = F_.transpose();
P_ = F_ * P_ * Ft + Q_;
}
void KalmanFilter::Update(const VectorXd &z) {
/**
TODO:
* update the state by using Kalman Filter equations
*/
VectorXd z_pred = H_ * x_;
VectorXd y = z - z_pred;
MatrixXd Ht = H_.transpose();
MatrixXd PHt = P_ * Ht;
MatrixXd S = H_ * PHt + R_;
MatrixXd Si = S.inverse();
MatrixXd K = PHt * Si;
//new estimate
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}
VectorXd RadarCartesianToPolar(const VectorXd &x_state){
/*
* convert radar measurements from cartesian coordinates (x, y, vx, vy) to
* polar (rho, phi, rho_dot) coordinates
*/
float px, py, vx, vy;
px = x_state[0];
py = x_state[1];
vx = x_state[2];
vy = x_state[3];
float rho, phi, rho_dot;
rho = sqrt(px*px + py*py);
phi = atan2(py, px); // returns values between -pi and pi
// if rho is very small, set it to 0.0001 to avoid division by 0 in computing rho_dot
if(rho < 0.000001)
rho = 0.000001;
rho_dot = (px * vx + py * vy) / rho;
VectorXd z_pred = VectorXd(3);
z_pred << rho, phi, rho_dot;
return z_pred;
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
/**
* update the state by using Extended Kalman Filter equations
*/
// convert radar measurements from cartesian coordinates (x, y, vx, vy) to polar (rho, phi, rho_dot).
VectorXd z_pred = RadarCartesianToPolar(x_);
VectorXd y = z - z_pred;
// normalize the angle between -pi to pi
while(y(1) > M_PI){
y(1) -= PI2;
}
while(y(1) < -M_PI){
y(1) += PI2;
}
// following is exact the same as in the function of KalmanFilter::Update()
MatrixXd Ht = H_.transpose();
MatrixXd PHt = P_ * Ht;
MatrixXd S = H_ * PHt + R_;
MatrixXd Si = S.inverse();
MatrixXd K = PHt * Si;
//new estimate
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}