Nathan Leong | dd72800 | 2024-02-03 15:26:53 -0800 | [diff] [blame] | 1 | #include "Eigen/Dense" |
| 2 | #include "Eigen/Sparse" |
Austin Schuh | 99f7c6a | 2024-06-25 22:07:44 -0700 | [diff] [blame^] | 3 | #include "absl/log/check.h" |
| 4 | #include "absl/log/log.h" |
Nathan Leong | dd72800 | 2024-02-03 15:26:53 -0800 | [diff] [blame] | 5 | |
| 6 | #include "aos/realtime.h" |
| 7 | #include "aos/time/time.h" |
| 8 | #include "osqp++.h" |
| 9 | #include "osqp.h" |
| 10 | |
| 11 | namespace frc971 { |
| 12 | namespace control_loops { |
| 13 | namespace catapult { |
| 14 | |
| 15 | // MPC problem for a specified horizon. This contains all the state for the |
| 16 | // solver, setters to modify the current and target state, and a way to fetch |
| 17 | // the solution. |
| 18 | class MPCProblem { |
| 19 | public: |
| 20 | MPCProblem(size_t horizon, |
| 21 | Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P, |
| 22 | Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q, |
| 23 | Eigen::Matrix<double, 2, 2> Af, |
| 24 | Eigen::Matrix<double, Eigen::Dynamic, 2> final_q); |
| 25 | |
| 26 | MPCProblem(MPCProblem const &) = delete; |
| 27 | void operator=(MPCProblem const &x) = delete; |
| 28 | |
| 29 | // Sets the current and final state. This keeps the problem in tact and |
| 30 | // doesn't recreate it, so it will be fast. |
| 31 | void SetState(Eigen::Matrix<double, 2, 1> X_initial, |
| 32 | Eigen::Matrix<double, 2, 1> X_final); |
| 33 | |
| 34 | // Solves our problem. |
| 35 | bool Solve(); |
| 36 | |
| 37 | double solve_time() const { return solve_time_; } |
| 38 | |
| 39 | // Returns the solution that the solver found when Solve was last called. |
| 40 | double U(size_t i) const { return solver_.primal_solution()(i); } |
| 41 | |
| 42 | // Returns the number of U's to be solved. |
| 43 | size_t horizon() const { return horizon_; } |
| 44 | |
| 45 | // Warm starts the optimizer with the provided solution to make it solve |
| 46 | // faster. |
| 47 | void WarmStart(const MPCProblem &p); |
| 48 | |
| 49 | private: |
| 50 | // The number of u's to solve for. |
| 51 | const size_t horizon_; |
| 52 | |
| 53 | // The problem statement variables needed by SetState to update q. |
| 54 | const Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q_; |
| 55 | const Eigen::Matrix<double, 2, 2> Af_; |
| 56 | const Eigen::Matrix<double, Eigen::Dynamic, 2> final_q_; |
| 57 | |
| 58 | Eigen::Matrix<double, 2, 1> X_initial_; |
| 59 | Eigen::Matrix<double, 2, 1> X_final_; |
| 60 | |
| 61 | Eigen::Matrix<double, Eigen::Dynamic, 1> objective_vector_; |
| 62 | |
| 63 | // Solver state. |
| 64 | osqp::OsqpInstance instance_; |
| 65 | osqp::OsqpSolver solver_; |
| 66 | osqp::OsqpSettings settings_; |
| 67 | |
| 68 | double solve_time_ = 0; |
| 69 | }; |
| 70 | |
| 71 | } // namespace catapult |
| 72 | } // namespace control_loops |
| 73 | } // namespace frc971 |