- 3.0.2 optimal control module.
LQR-impl.hpp
Go to the documentation of this file.
1 /**********************************************************************************************************************
2 This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.
3 Licensed under the BSD-2 license (see LICENSE file in main directory)
4 **********************************************************************************************************************/
5 
6 #pragma once
7 
8 #ifdef USE_MATLAB_CPP_INTERFACE
9 #include <matlabCppInterface/Engine.hpp>
10 #endif
11 
12 namespace ct {
13 namespace optcon {
14 
15 template <size_t STATE_DIM, size_t CONTROL_DIM>
17  const control_matrix_t& R,
18  const state_matrix_t& A,
19  const control_gain_matrix_t& B,
21  bool RisDiagonal,
22  bool solveRiccatiIteratively)
23 {
24  control_matrix_t R_inverse;
26 
27  bool success = care_.solve(Q, R, A, B, P, RisDiagonal, R_inverse, solveRiccatiIteratively);
28 
29  K = (R_inverse * (B.transpose() * P));
30 
31  return success;
32 }
33 
34 #ifdef USE_MATLAB_CPP_INTERFACE
35 template <size_t STATE_DIM, size_t CONTROL_DIM>
37  const control_matrix_t& R,
38  const state_matrix_t& A,
39  const control_gain_matrix_t& B,
41  bool checkControllability)
42 {
43  if (!matlabEngine_.isInitialized())
44  matlabEngine_.initialize();
45 
46  matlabEngine_.put("Q", Q);
47  matlabEngine_.put("R", R);
48  matlabEngine_.put("A", A);
49  matlabEngine_.put("B", B);
50 
51  if (checkControllability)
52  {
53  matlabEngine_.executeCommand("Co=ctrb(A,B);");
54  matlabEngine_.executeCommand("unco=length(A)-rank(Co);");
55  int uncontrollableStates = 0;
56  matlabEngine_.get("unco", uncontrollableStates);
57 
58  if (uncontrollableStates > 0)
59  {
60  std::cout << "System is not controllable, # uncontrollable states: " << uncontrollableStates << std::endl;
61  }
62  }
63 
64  matlabEngine_.executeCommand("[K,~,~] = lqr(A,B,Q,R);");
65 
66  Eigen::MatrixXd Kmatlab;
67  matlabEngine_.get("K", Kmatlab);
68 
69  K = Kmatlab;
70 
71  return true;
72 }
73 #endif //USE_MATLAB_CPP_INTERFACE
74 
75 
76 } // namespace optcon
77 } // namespace ct
Eigen::Matrix< double, STATE_DIM, CONTROL_DIM > control_gain_matrix_t
Definition: LQR.hpp:40
continuous-time infinite-horizon LQR
Definition: LQR.hpp:32
Eigen::Matrix< double, CONTROL_DIM, CONTROL_DIM > control_matrix_t
Definition: LQR.hpp:38
bool compute(const state_matrix_t &Q, const control_matrix_t &R, const state_matrix_t &A, const control_gain_matrix_t &B, control_feedback_t &K, bool RisDiagonal=false, bool solveRiccatiIteratively=false)
design the infinite-horizon LQR controller.
Definition: LQR-impl.hpp:16
Eigen::Matrix< double, nStates, nStates > state_matrix_t
Eigen::Matrix< double, CONTROL_DIM, STATE_DIM > control_feedback_t
Definition: LQR.hpp:41