blob: 612a17a1d8c70a99fad89a8c84729ad1e5b44a3c [file] [log] [blame]
Austin Schuh1d731362022-02-22 13:57:55 -08001#include "y2022/control_loops/superstructure/catapult/catapult.h"
2
3#include "Eigen/Dense"
4#include "Eigen/Sparse"
5#include "aos/realtime.h"
6#include "aos/time/time.h"
7#include "glog/logging.h"
8#include "osqp++.h"
9#include "osqp.h"
10#include "y2022/control_loops/superstructure/catapult/catapult_plant.h"
11
12namespace y2022 {
13namespace control_loops {
14namespace superstructure {
15namespace catapult {
16namespace chrono = std::chrono;
17
18namespace {
19osqp::OsqpInstance MakeInstance(
20 size_t horizon, Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P) {
21 osqp::OsqpInstance instance;
Austin Schuh39f26f62022-02-24 21:34:46 -080022 instance.objective_matrix = P.sparseView();
Austin Schuh1d731362022-02-22 13:57:55 -080023
24 instance.constraint_matrix =
Austin Schuh39f26f62022-02-24 21:34:46 -080025 Eigen::SparseMatrix<double, Eigen::ColMajor, osqp::c_int>(horizon,
Ravago Jones5da06352022-03-04 20:26:24 -080026 horizon);
Austin Schuh1d731362022-02-22 13:57:55 -080027 instance.constraint_matrix.setIdentity();
28
29 instance.lower_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080030 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon, 1);
Austin Schuh1d731362022-02-22 13:57:55 -080031 instance.upper_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080032 Eigen::Matrix<double, Eigen::Dynamic, 1>::Ones(horizon, 1) * 12.0;
Austin Schuh1d731362022-02-22 13:57:55 -080033 return instance;
34}
35} // namespace
36
37MPCProblem::MPCProblem(size_t horizon,
38 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P,
39 Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q,
40 Eigen::Matrix<double, 2, 2> Af,
41 Eigen::Matrix<double, Eigen::Dynamic, 2> final_q)
42 : horizon_(horizon),
Austin Schuh39f26f62022-02-24 21:34:46 -080043 accel_q_(std::move(accel_q)),
44 Af_(std::move(Af)),
45 final_q_(std::move(final_q)),
Austin Schuh1d731362022-02-22 13:57:55 -080046 instance_(MakeInstance(horizon, std::move(P))) {
Austin Schuh39f26f62022-02-24 21:34:46 -080047 // Start with a representative problem.
48 Eigen::Matrix<double, 2, 1> X_initial(0.0, 0.0);
49 Eigen::Matrix<double, 2, 1> X_final(2.0, 25.0);
50
51 objective_vector_ =
52 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
53 instance_.objective_vector = objective_vector_;
Austin Schuh1d731362022-02-22 13:57:55 -080054 settings_.max_iter = 25;
Austin Schuh39f26f62022-02-24 21:34:46 -080055 settings_.check_termination = 5;
56 settings_.warm_start = 1;
57 // TODO(austin): Do we need this scaling thing? It makes it not solve
58 // sometimes... I'm pretty certain by giving it a decently formed problem to
59 // initialize with, it will not try doing crazy things with the scaling
60 // internally.
61 settings_.scaling = 0;
Austin Schuh1d731362022-02-22 13:57:55 -080062 auto status = solver_.Init(instance_, settings_);
63 CHECK(status.ok()) << status;
64}
65
Austin Schuh39f26f62022-02-24 21:34:46 -080066void MPCProblem::SetState(Eigen::Matrix<double, 2, 1> X_initial,
67 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -080068 X_initial_ = X_initial;
69 X_final_ = X_final;
Austin Schuh39f26f62022-02-24 21:34:46 -080070 objective_vector_ =
Austin Schuh1d731362022-02-22 13:57:55 -080071 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
72
Austin Schuh39f26f62022-02-24 21:34:46 -080073 auto status = solver_.SetObjectiveVector(objective_vector_);
Austin Schuh1d731362022-02-22 13:57:55 -080074 CHECK(status.ok()) << status;
75}
76
77bool MPCProblem::Solve() {
78 const aos::monotonic_clock::time_point start_time =
79 aos::monotonic_clock::now();
80 osqp::OsqpExitCode exit_code = solver_.Solve();
81 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
82 VLOG(1) << "OSQP solved in "
83 << std::chrono::duration<double>(end_time - start_time).count();
84 solve_time_ = std::chrono::duration<double>(end_time - start_time).count();
85 // TODO(austin): Dump the exit codes out as an enum for logging.
86 //
87 // TODO(austin): The dual problem doesn't appear to be converging on all
88 // problems. Are we phrasing something wrong?
89
90 // TODO(austin): Set a time limit so we can't run forever, and signal back
91 // when we hit our limit.
92 return exit_code == osqp::OsqpExitCode::kOptimal;
93}
94
95void MPCProblem::WarmStart(const MPCProblem &p) {
96 CHECK_GE(p.horizon(), horizon())
97 << ": Can only copy a bigger problem's solution into a smaller problem.";
98 auto status = solver_.SetPrimalWarmStart(p.solver_.primal_solution().block(
99 p.horizon() - horizon(), 0, horizon(), 1));
100 CHECK(status.ok()) << status;
101 status = solver_.SetDualWarmStart(p.solver_.dual_solution().block(
102 p.horizon() - horizon(), 0, horizon(), 1));
103 CHECK(status.ok()) << status;
104}
105
106CatapultProblemGenerator::CatapultProblemGenerator(size_t horizon)
107 : plant_(MakeCatapultPlant()),
108 horizon_(horizon),
109 Q_final_(
110 (Eigen::DiagonalMatrix<double, 2>().diagonal() << 10000.0, 10000.0)
111 .finished()),
112 As_(MakeAs()),
113 Bs_(MakeBs()),
114 m_(Makem()),
115 M_(MakeM()),
116 W_(MakeW()),
117 w_(Makew()),
118 Pi_(MakePi()),
119 WM_(W_ * M_),
120 Wmpw_(W_ * m_ + w_) {}
121
122std::unique_ptr<MPCProblem> CatapultProblemGenerator::MakeProblem(
123 size_t horizon) {
124 return std::make_unique<MPCProblem>(
125 horizon, P(horizon), accel_q(horizon), Af(horizon),
126 (2.0 * Q_final_ * Bf(horizon)).transpose());
127}
128
129const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
130CatapultProblemGenerator::P(size_t horizon) {
131 CHECK_GT(horizon, 0u);
132 CHECK_LE(horizon, horizon_);
133 return 2.0 * (WM_.block(0, 0, horizon, horizon).transpose() * Pi(horizon) *
134 WM_.block(0, 0, horizon, horizon) +
135 Bf(horizon).transpose() * Q_final_ * Bf(horizon));
136}
137
138const Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::q(
Austin Schuh39f26f62022-02-24 21:34:46 -0800139 size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
140 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -0800141 CHECK_GT(horizon, 0u);
142 CHECK_LE(horizon, horizon_);
143 return 2.0 * X_initial(1, 0) * accel_q(horizon) +
144 2.0 * ((Af(horizon) * X_initial - X_final).transpose() * Q_final_ *
145 Bf(horizon))
146 .transpose();
147}
148
149const Eigen::Matrix<double, Eigen::Dynamic, 1>
150CatapultProblemGenerator::accel_q(size_t horizon) {
151 return 2.0 * ((Wmpw_.block(0, 0, horizon, 1)).transpose() * Pi(horizon) *
152 WM_.block(0, 0, horizon, horizon))
153 .transpose();
154}
155
156const Eigen::Matrix<double, 2, 2> CatapultProblemGenerator::Af(size_t horizon) {
157 CHECK_GT(horizon, 0u);
158 CHECK_LE(horizon, horizon_);
159 return As_.block<2, 2>(2 * (horizon - 1), 0);
160}
161
162const Eigen::Matrix<double, 2, Eigen::Dynamic> CatapultProblemGenerator::Bf(
163 size_t horizon) {
164 CHECK_GT(horizon, 0u);
165 CHECK_LE(horizon, horizon_);
166 return Bs_.block(2 * (horizon - 1), 0, 2, horizon);
167}
168
169const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
170CatapultProblemGenerator::Pi(size_t horizon) {
171 CHECK_GT(horizon, 0u);
172 CHECK_LE(horizon, horizon_);
173 return Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(Pi_).block(
174 horizon_ - horizon, horizon_ - horizon, horizon, horizon);
175}
176
177Eigen::Matrix<double, Eigen::Dynamic, 2> CatapultProblemGenerator::MakeAs() {
178 Eigen::Matrix<double, Eigen::Dynamic, 2> As =
179 Eigen::Matrix<double, Eigen::Dynamic, 2>::Zero(horizon_ * 2, 2);
180 for (size_t i = 0; i < horizon_; ++i) {
181 if (i == 0) {
182 As.block<2, 2>(0, 0) = plant_.A();
183 } else {
184 As.block<2, 2>(i * 2, 0) = plant_.A() * As.block<2, 2>((i - 1) * 2, 0);
185 }
186 }
187 return As;
188}
189
190Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
191CatapultProblemGenerator::MakeBs() {
192 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs =
193 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_ * 2,
194 horizon_);
195 for (size_t i = 0; i < horizon_; ++i) {
196 for (size_t j = 0; j < i + 1; ++j) {
197 if (i == j) {
198 Bs.block<2, 1>(i * 2, j) = plant_.B();
199 } else {
200 Bs.block<2, 1>(i * 2, j) =
201 As_.block<2, 2>((i - j - 1) * 2, 0) * plant_.B();
202 }
203 }
204 }
205 return Bs;
206}
207
208Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makem() {
209 Eigen::Matrix<double, Eigen::Dynamic, 1> m =
210 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
211 for (size_t i = 0; i < horizon_; ++i) {
212 m(i, 0) = As_(1 + 2 * i, 1);
213 }
214 return m;
215}
216
217Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
218CatapultProblemGenerator::MakeM() {
219 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M =
220 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_,
221 horizon_);
222 for (size_t i = 0; i < horizon_; ++i) {
223 for (size_t j = 0; j < horizon_; ++j) {
224 M(i, j) = Bs_(2 * i + 1, j);
225 }
226 }
227 return M;
228}
229
230Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
231CatapultProblemGenerator::MakeW() {
232 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W =
233 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(horizon_,
234 horizon_);
235 for (size_t i = 0; i < horizon_ - 1; ++i) {
236 W(i + 1, i) = -1.0;
237 }
238 W /= std::chrono::duration<double>(plant_.dt()).count();
239 return W;
240}
241
242Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makew() {
243 Eigen::Matrix<double, Eigen::Dynamic, 1> w =
244 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
245 w(0, 0) = -1.0 / std::chrono::duration<double>(plant_.dt()).count();
246 return w;
247}
248
249Eigen::DiagonalMatrix<double, Eigen::Dynamic>
250CatapultProblemGenerator::MakePi() {
251 Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi(horizon_);
252 for (size_t i = 0; i < horizon_; ++i) {
253 Pi.diagonal()(i) =
254 std::pow(0.01, 2.0) +
255 std::pow(0.02 * std::max(0.0, (20 - ((int)horizon_ - (int)i)) / 20.),
256 2.0);
257 }
258 return Pi;
259}
260
261Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
262CatapultProblemGenerator::MakeP() {
263 return 2.0 * (M_.transpose() * W_.transpose() * Pi_ * W_ * M_ +
264 Bf(horizon_).transpose() * Q_final_ * Bf(horizon_));
265}
266
Austin Schuh39f26f62022-02-24 21:34:46 -0800267CatapultController::CatapultController(size_t horizon) : generator_(horizon) {
268 problems_.reserve(generator_.horizon());
269 for (size_t i = generator_.horizon(); i > 0; --i) {
270 problems_.emplace_back(generator_.MakeProblem(i));
271 }
272
273 Reset();
274}
275
276void CatapultController::Reset() {
277 current_controller_ = 0;
278 solve_time_ = 0.0;
279}
280
281void CatapultController::SetState(Eigen::Matrix<double, 2, 1> X_initial,
282 Eigen::Matrix<double, 2, 1> X_final) {
283 if (current_controller_ >= problems_.size()) {
284 return;
285 }
286 problems_[current_controller_]->SetState(X_initial, X_final);
287}
288
289bool CatapultController::Solve() {
290 if (current_controller_ >= problems_.size()) {
291 return true;
292 }
293 const bool result = problems_[current_controller_]->Solve();
294 solve_time_ = problems_[current_controller_]->solve_time();
295 return result;
296}
297
298std::optional<double> CatapultController::Next() {
299 if (current_controller_ >= problems_.size()) {
300 return std::nullopt;
301 }
302
Austin Schuh41472552022-03-13 18:09:41 -0700303 double u;
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700304 size_t solution_number = 0;
Austin Schuh41472552022-03-13 18:09:41 -0700305 if (current_controller_ == 0u) {
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700306 while (solution_number < problems_[current_controller_]->horizon() &&
307 problems_[current_controller_]->U(solution_number) < 0.01) {
308 u = problems_[current_controller_]->U(solution_number);
309 ++solution_number;
Austin Schuh41472552022-03-13 18:09:41 -0700310 }
Austin Schuh41472552022-03-13 18:09:41 -0700311 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700312 u = problems_[current_controller_]->U(solution_number);
Austin Schuh39f26f62022-02-24 21:34:46 -0800313
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700314 if (current_controller_ + 1u + solution_number < problems_.size()) {
315 problems_[current_controller_ + solution_number + 1]->WarmStart(
Austin Schuh39f26f62022-02-24 21:34:46 -0800316 *problems_[current_controller_]);
317 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700318 current_controller_ += 1u + solution_number;
Austin Schuh39f26f62022-02-24 21:34:46 -0800319 return u;
320}
321
322const flatbuffers::Offset<
323 frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
Ravago Jones3283ce02022-03-09 19:31:29 -0800324Catapult::Iterate(const CatapultGoal *catapult_goal, const Position *position,
Austin Schuh97410d72022-03-12 15:37:23 -0800325 double battery_voltage, double *catapult_voltage, bool fire,
Austin Schuh39f26f62022-02-24 21:34:46 -0800326 flatbuffers::FlatBufferBuilder *fbb) {
327 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
Ravago Jones3283ce02022-03-09 19:31:29 -0800328 *return_goal =
329 catapult_goal != nullptr && catapult_goal->has_return_position()
330 ? catapult_goal->return_position()
331 : nullptr;
Austin Schuh39f26f62022-02-24 21:34:46 -0800332
333 const bool catapult_disabled = catapult_.Correct(
Ravago Jones3283ce02022-03-09 19:31:29 -0800334 return_goal, position->catapult(), catapult_voltage == nullptr);
Austin Schuh39f26f62022-02-24 21:34:46 -0800335
336 if (catapult_disabled) {
337 catapult_state_ = CatapultState::PROFILE;
Ravago Jones3283ce02022-03-09 19:31:29 -0800338 } else if (catapult_.running() && catapult_goal != nullptr && fire &&
339 !last_firing_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800340 catapult_state_ = CatapultState::FIRING;
Ravago Jones3283ce02022-03-09 19:31:29 -0800341 latched_shot_position = catapult_goal->shot_position();
342 latched_shot_velocity = catapult_goal->shot_velocity();
Austin Schuh39f26f62022-02-24 21:34:46 -0800343 }
344
Milind Upadhyay058e64c2022-04-01 17:41:46 -0700345 // Don't update last_firing_ if the catapult is disabled, so that we actually
346 // end up firing once it's enabled
347 if (catapult_.running() && !catapult_disabled) {
Ravago Jones5da06352022-03-04 20:26:24 -0800348 last_firing_ = fire;
Austin Schuh39f26f62022-02-24 21:34:46 -0800349 }
350
351 use_profile_ = true;
352
353 switch (catapult_state_) {
354 case CatapultState::FIRING: {
355 // Select the ball controller. We should only be firing if we have a
356 // ball, or at least should only care about the shot accuracy.
357 catapult_.set_controller_index(0);
358 // Ok, so we've now corrected. Next step is to run the MPC.
359 //
360 // Since there is a unit delay between when we ask for a U and the
361 // hardware applies it, we need to run the optimizer for the position at
362 // the *next* control loop cycle.
363
Austin Schuhb39f4522022-03-27 13:29:42 -0700364 Eigen::Vector3d next_X = catapult_.estimated_state();
365 for (int i = catapult_.controller().plant().coefficients().delayed_u;
366 i > 1; --i) {
367 next_X = catapult_.controller().plant().A() * next_X +
368 catapult_.controller().plant().B() *
369 catapult_.controller().observer().last_U(i - 1);
370 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800371
372 catapult_mpc_.SetState(
373 next_X.block<2, 1>(0, 0),
Ravago Jones3283ce02022-03-09 19:31:29 -0800374 Eigen::Vector2d(latched_shot_position, latched_shot_velocity));
Austin Schuh39f26f62022-02-24 21:34:46 -0800375
376 const bool solved = catapult_mpc_.Solve();
Austin Schuh41472552022-03-13 18:09:41 -0700377 current_horizon_ = catapult_mpc_.current_horizon();
378 const bool started = catapult_mpc_.started();
379 if (solved || started) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800380 std::optional<double> solution = catapult_mpc_.Next();
381
382 if (!solution.has_value()) {
383 CHECK_NOTNULL(catapult_voltage);
384 *catapult_voltage = 0.0;
385 if (catapult_mpc_.started()) {
Austin Schuh80fc2752022-02-25 13:33:56 -0800386 ++shot_count_;
Austin Schuh39f26f62022-02-24 21:34:46 -0800387 // Finished the catapult, time to fire.
388 catapult_state_ = CatapultState::RESETTING;
389 }
390 } else {
391 // TODO(austin): Voltage error?
392 CHECK_NOTNULL(catapult_voltage);
Austin Schuh9628b8b2022-04-16 10:18:59 -0700393 if (current_horizon_ == 1) {
394 battery_voltage = 12.0;
395 }
Austin Schuh97410d72022-03-12 15:37:23 -0800396 *catapult_voltage = std::max(
397 0.0, std::min(12.0, (*solution - 0.0 * next_X(2, 0)) * 12.0 /
398 std::max(battery_voltage, 8.0)));
Austin Schuh39f26f62022-02-24 21:34:46 -0800399 use_profile_ = false;
400 }
401 } else {
Ravago Jones3283ce02022-03-09 19:31:29 -0800402 if (!fire) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800403 // Eh, didn't manage to solve before it was time to fire. Give up.
404 catapult_state_ = CatapultState::PROFILE;
405 }
406 }
407
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800408 if (!use_profile_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800409 catapult_.ForceGoal(catapult_.estimated_position(),
410 catapult_.estimated_velocity());
411 }
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800412 }
413 if (catapult_state_ != CatapultState::RESETTING) {
414 break;
415 } else {
416 [[fallthrough]];
417 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800418
419 case CatapultState::RESETTING:
Austin Schuh17be41d2022-03-12 16:11:39 -0800420 if (catapult_.controller().R(1, 0) > 7.0) {
421 catapult_.AdjustProfile(7.0, 2000.0);
422 } else if (catapult_.controller().R(1, 0) > 0.0) {
423 catapult_.AdjustProfile(7.0, 1000.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800424 } else {
425 catapult_state_ = CatapultState::PROFILE;
426 }
427 [[fallthrough]];
428
429 case CatapultState::PROFILE:
430 break;
431 }
432
433 if (use_profile_) {
434 if (catapult_state_ != CatapultState::FIRING) {
435 catapult_mpc_.Reset();
436 }
437 // Select the controller designed for when we have no ball.
438 catapult_.set_controller_index(1);
439
Austin Schuh41472552022-03-13 18:09:41 -0700440 current_horizon_ = 0u;
Austin Schuh39f26f62022-02-24 21:34:46 -0800441 const double output_voltage = catapult_.UpdateController(catapult_disabled);
442 if (catapult_voltage != nullptr) {
443 *catapult_voltage = output_voltage;
444 }
445 }
446
Austin Schuh97410d72022-03-12 15:37:23 -0800447 catapult_.UpdateObserver(catapult_voltage != nullptr
448 ? (*catapult_voltage * battery_voltage / 12.0)
449 : 0.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800450
451 return catapult_.MakeStatus(fbb);
452}
453
Austin Schuh1d731362022-02-22 13:57:55 -0800454} // namespace catapult
455} // namespace superstructure
456} // namespace control_loops
457} // namespace y2022