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