MUQ  0.4.3
KalmanFilter.cpp
Go to the documentation of this file.
2 
4 
5 #include <Eigen/Dense>
6 
7 using namespace muq::Modeling;
8 using namespace muq::Inference;
9 
10 
11 Eigen::MatrixXd KalmanFilter::ComputeGain(Eigen::MatrixXd const& HP,
12  std::shared_ptr<muq::Modeling::LinearOperator> H,
13  Eigen::Ref<const Eigen::MatrixXd> const& obsCov)
14 {
15 
16  Eigen::MatrixXd S = H->Apply( HP.transpose() );
17 
18  if((obsCov.rows()==1)||(obsCov.cols()==1)){
19  S += obsCov.asDiagonal();
20  }else{
21  S += obsCov;
22  }
23 
24  Eigen::LDLT<Eigen::MatrixXd> solver(S); // <- In place Cholesky decomposition
25  Eigen::MatrixXd K = solver.solve( HP ).transpose();
26 
27  return K;
28 }
29 
30 
31 
32 std::pair<Eigen::VectorXd, Eigen::MatrixXd> KalmanFilter::Analyze(std::pair<Eigen::VectorXd, Eigen::MatrixXd> const& dist,
33  std::shared_ptr<muq::Modeling::LinearOperator> H,
34  Eigen::Ref<const Eigen::VectorXd> const& obsMean,
35  Eigen::Ref<const Eigen::MatrixXd> const& obsCov)
36 {
37 
38 
39  const int obsDim = std::max(obsCov.rows(), obsCov.cols());
40  if(H->rows() != obsDim)
41  throw muq::WrongSizeError("In KalmanFilter::Analyze: The size of the observation noise covariance does not match the size of the observation operator. The observation operator returns a vector with " + std::to_string(H->rows()) + " components, but the noise covariance is a " + std::to_string(obsDim) + "x" + std::to_string(obsDim) + " matrix.");
42 
43  if(H->cols() != dist.first.rows())
44  throw muq::WrongSizeError("In KalmanFilter::Analyze: The size of the observation operator (" + std::to_string(H->rows()) + "x" + std::to_string(H->cols()) + ") does not match the size of the prior mean (" + std::to_string(dist.first.rows()) + ").");
45 
46  Eigen::VectorXd y = obsMean - H->Apply(dist.first);
47 
48  Eigen::MatrixXd HP = H->Apply(dist.second);
49 
50  // Compute the Kalman Gain
51  Eigen::MatrixXd K = ComputeGain(HP, H, obsCov);
52 
53  // Posterior Mean and Covariance
54  std::pair<Eigen::VectorXd, Eigen::MatrixXd> output;
55 
56  output.first = dist.first + K*y;
57 
58  output.second = dist.second - K*HP;
59 
60  return output;
61 }
Exception to throw when matrices, vectors, or arrays are the wrong size.
Definition: Exceptions.h:58
NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL &j)
user-defined to_string function for JSON values
Definition: json.h:25172