blob: 493bb46612f06a490cf25be88f4c59d5089f8591 [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"
Philipp Schrader790cb542023-07-05 21:06:52 -07005#include "glog/logging.h"
6
Austin Schuh1d731362022-02-22 13:57:55 -08007#include "aos/realtime.h"
8#include "aos/time/time.h"
Austin Schuh1d731362022-02-22 13:57:55 -08009#include "osqp++.h"
10#include "osqp.h"
11#include "y2022/control_loops/superstructure/catapult/catapult_plant.h"
12
Stephan Pleinesf63bde82024-01-13 15:59:33 -080013namespace y2022::control_loops::superstructure::catapult {
Austin Schuh1d731362022-02-22 13:57:55 -080014namespace chrono = std::chrono;
15
16namespace {
17osqp::OsqpInstance MakeInstance(
18 size_t horizon, Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P) {
19 osqp::OsqpInstance instance;
Austin Schuh39f26f62022-02-24 21:34:46 -080020 instance.objective_matrix = P.sparseView();
Austin Schuh1d731362022-02-22 13:57:55 -080021
22 instance.constraint_matrix =
Austin Schuh39f26f62022-02-24 21:34:46 -080023 Eigen::SparseMatrix<double, Eigen::ColMajor, osqp::c_int>(horizon,
Ravago Jones5da06352022-03-04 20:26:24 -080024 horizon);
Austin Schuh1d731362022-02-22 13:57:55 -080025 instance.constraint_matrix.setIdentity();
26
27 instance.lower_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080028 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon, 1);
Austin Schuh1d731362022-02-22 13:57:55 -080029 instance.upper_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080030 Eigen::Matrix<double, Eigen::Dynamic, 1>::Ones(horizon, 1) * 12.0;
Austin Schuh1d731362022-02-22 13:57:55 -080031 return instance;
32}
33} // namespace
34
35MPCProblem::MPCProblem(size_t horizon,
36 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P,
37 Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q,
38 Eigen::Matrix<double, 2, 2> Af,
39 Eigen::Matrix<double, Eigen::Dynamic, 2> final_q)
40 : horizon_(horizon),
Austin Schuh39f26f62022-02-24 21:34:46 -080041 accel_q_(std::move(accel_q)),
42 Af_(std::move(Af)),
43 final_q_(std::move(final_q)),
Austin Schuh1d731362022-02-22 13:57:55 -080044 instance_(MakeInstance(horizon, std::move(P))) {
Austin Schuh39f26f62022-02-24 21:34:46 -080045 // Start with a representative problem.
46 Eigen::Matrix<double, 2, 1> X_initial(0.0, 0.0);
47 Eigen::Matrix<double, 2, 1> X_final(2.0, 25.0);
48
49 objective_vector_ =
50 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
51 instance_.objective_vector = objective_vector_;
Austin Schuh1d731362022-02-22 13:57:55 -080052 settings_.max_iter = 25;
Austin Schuh39f26f62022-02-24 21:34:46 -080053 settings_.check_termination = 5;
54 settings_.warm_start = 1;
55 // TODO(austin): Do we need this scaling thing? It makes it not solve
56 // sometimes... I'm pretty certain by giving it a decently formed problem to
57 // initialize with, it will not try doing crazy things with the scaling
58 // internally.
59 settings_.scaling = 0;
Austin Schuh1d731362022-02-22 13:57:55 -080060 auto status = solver_.Init(instance_, settings_);
61 CHECK(status.ok()) << status;
62}
63
Austin Schuh39f26f62022-02-24 21:34:46 -080064void MPCProblem::SetState(Eigen::Matrix<double, 2, 1> X_initial,
65 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -080066 X_initial_ = X_initial;
67 X_final_ = X_final;
Austin Schuh75db4e82022-11-04 18:45:13 -070068 // If we mark this noalias(), it won't re-allocate the vector each time.
69 objective_vector_.noalias() =
Austin Schuh1d731362022-02-22 13:57:55 -080070 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
71
Austin Schuh39f26f62022-02-24 21:34:46 -080072 auto status = solver_.SetObjectiveVector(objective_vector_);
Austin Schuh1d731362022-02-22 13:57:55 -080073 CHECK(status.ok()) << status;
74}
75
76bool MPCProblem::Solve() {
77 const aos::monotonic_clock::time_point start_time =
78 aos::monotonic_clock::now();
79 osqp::OsqpExitCode exit_code = solver_.Solve();
80 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
81 VLOG(1) << "OSQP solved in "
82 << std::chrono::duration<double>(end_time - start_time).count();
83 solve_time_ = std::chrono::duration<double>(end_time - start_time).count();
84 // TODO(austin): Dump the exit codes out as an enum for logging.
85 //
86 // TODO(austin): The dual problem doesn't appear to be converging on all
87 // problems. Are we phrasing something wrong?
88
89 // TODO(austin): Set a time limit so we can't run forever, and signal back
90 // when we hit our limit.
91 return exit_code == osqp::OsqpExitCode::kOptimal;
92}
93
94void MPCProblem::WarmStart(const MPCProblem &p) {
95 CHECK_GE(p.horizon(), horizon())
96 << ": Can only copy a bigger problem's solution into a smaller problem.";
97 auto status = solver_.SetPrimalWarmStart(p.solver_.primal_solution().block(
98 p.horizon() - horizon(), 0, horizon(), 1));
99 CHECK(status.ok()) << status;
100 status = solver_.SetDualWarmStart(p.solver_.dual_solution().block(
101 p.horizon() - horizon(), 0, horizon(), 1));
102 CHECK(status.ok()) << status;
103}
104
105CatapultProblemGenerator::CatapultProblemGenerator(size_t horizon)
106 : plant_(MakeCatapultPlant()),
107 horizon_(horizon),
108 Q_final_(
109 (Eigen::DiagonalMatrix<double, 2>().diagonal() << 10000.0, 10000.0)
110 .finished()),
111 As_(MakeAs()),
112 Bs_(MakeBs()),
113 m_(Makem()),
114 M_(MakeM()),
115 W_(MakeW()),
116 w_(Makew()),
117 Pi_(MakePi()),
118 WM_(W_ * M_),
119 Wmpw_(W_ * m_ + w_) {}
120
121std::unique_ptr<MPCProblem> CatapultProblemGenerator::MakeProblem(
122 size_t horizon) {
123 return std::make_unique<MPCProblem>(
124 horizon, P(horizon), accel_q(horizon), Af(horizon),
125 (2.0 * Q_final_ * Bf(horizon)).transpose());
126}
127
128const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
129CatapultProblemGenerator::P(size_t horizon) {
130 CHECK_GT(horizon, 0u);
131 CHECK_LE(horizon, horizon_);
132 return 2.0 * (WM_.block(0, 0, horizon, horizon).transpose() * Pi(horizon) *
133 WM_.block(0, 0, horizon, horizon) +
134 Bf(horizon).transpose() * Q_final_ * Bf(horizon));
135}
136
137const Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::q(
Austin Schuh39f26f62022-02-24 21:34:46 -0800138 size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
139 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -0800140 CHECK_GT(horizon, 0u);
141 CHECK_LE(horizon, horizon_);
142 return 2.0 * X_initial(1, 0) * accel_q(horizon) +
143 2.0 * ((Af(horizon) * X_initial - X_final).transpose() * Q_final_ *
144 Bf(horizon))
145 .transpose();
146}
147
148const Eigen::Matrix<double, Eigen::Dynamic, 1>
149CatapultProblemGenerator::accel_q(size_t horizon) {
150 return 2.0 * ((Wmpw_.block(0, 0, horizon, 1)).transpose() * Pi(horizon) *
151 WM_.block(0, 0, horizon, horizon))
152 .transpose();
153}
154
155const Eigen::Matrix<double, 2, 2> CatapultProblemGenerator::Af(size_t horizon) {
156 CHECK_GT(horizon, 0u);
157 CHECK_LE(horizon, horizon_);
158 return As_.block<2, 2>(2 * (horizon - 1), 0);
159}
160
161const Eigen::Matrix<double, 2, Eigen::Dynamic> CatapultProblemGenerator::Bf(
162 size_t horizon) {
163 CHECK_GT(horizon, 0u);
164 CHECK_LE(horizon, horizon_);
165 return Bs_.block(2 * (horizon - 1), 0, 2, horizon);
166}
167
168const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
169CatapultProblemGenerator::Pi(size_t horizon) {
170 CHECK_GT(horizon, 0u);
171 CHECK_LE(horizon, horizon_);
172 return Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(Pi_).block(
173 horizon_ - horizon, horizon_ - horizon, horizon, horizon);
174}
175
176Eigen::Matrix<double, Eigen::Dynamic, 2> CatapultProblemGenerator::MakeAs() {
177 Eigen::Matrix<double, Eigen::Dynamic, 2> As =
178 Eigen::Matrix<double, Eigen::Dynamic, 2>::Zero(horizon_ * 2, 2);
179 for (size_t i = 0; i < horizon_; ++i) {
180 if (i == 0) {
181 As.block<2, 2>(0, 0) = plant_.A();
182 } else {
183 As.block<2, 2>(i * 2, 0) = plant_.A() * As.block<2, 2>((i - 1) * 2, 0);
184 }
185 }
186 return As;
187}
188
189Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
190CatapultProblemGenerator::MakeBs() {
191 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs =
192 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_ * 2,
193 horizon_);
194 for (size_t i = 0; i < horizon_; ++i) {
195 for (size_t j = 0; j < i + 1; ++j) {
196 if (i == j) {
197 Bs.block<2, 1>(i * 2, j) = plant_.B();
198 } else {
199 Bs.block<2, 1>(i * 2, j) =
200 As_.block<2, 2>((i - j - 1) * 2, 0) * plant_.B();
201 }
202 }
203 }
204 return Bs;
205}
206
207Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makem() {
208 Eigen::Matrix<double, Eigen::Dynamic, 1> m =
209 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
210 for (size_t i = 0; i < horizon_; ++i) {
211 m(i, 0) = As_(1 + 2 * i, 1);
212 }
213 return m;
214}
215
216Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
217CatapultProblemGenerator::MakeM() {
218 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M =
219 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_,
220 horizon_);
221 for (size_t i = 0; i < horizon_; ++i) {
222 for (size_t j = 0; j < horizon_; ++j) {
223 M(i, j) = Bs_(2 * i + 1, j);
224 }
225 }
226 return M;
227}
228
229Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
230CatapultProblemGenerator::MakeW() {
231 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W =
232 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(horizon_,
233 horizon_);
234 for (size_t i = 0; i < horizon_ - 1; ++i) {
235 W(i + 1, i) = -1.0;
236 }
237 W /= std::chrono::duration<double>(plant_.dt()).count();
238 return W;
239}
240
241Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makew() {
242 Eigen::Matrix<double, Eigen::Dynamic, 1> w =
243 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
244 w(0, 0) = -1.0 / std::chrono::duration<double>(plant_.dt()).count();
245 return w;
246}
247
248Eigen::DiagonalMatrix<double, Eigen::Dynamic>
249CatapultProblemGenerator::MakePi() {
250 Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi(horizon_);
251 for (size_t i = 0; i < horizon_; ++i) {
252 Pi.diagonal()(i) =
253 std::pow(0.01, 2.0) +
254 std::pow(0.02 * std::max(0.0, (20 - ((int)horizon_ - (int)i)) / 20.),
255 2.0);
256 }
257 return Pi;
258}
259
260Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
261CatapultProblemGenerator::MakeP() {
262 return 2.0 * (M_.transpose() * W_.transpose() * Pi_ * W_ * M_ +
263 Bf(horizon_).transpose() * Q_final_ * Bf(horizon_));
264}
265
Austin Schuh39f26f62022-02-24 21:34:46 -0800266CatapultController::CatapultController(size_t horizon) : generator_(horizon) {
267 problems_.reserve(generator_.horizon());
268 for (size_t i = generator_.horizon(); i > 0; --i) {
269 problems_.emplace_back(generator_.MakeProblem(i));
270 }
271
272 Reset();
273}
274
275void CatapultController::Reset() {
276 current_controller_ = 0;
277 solve_time_ = 0.0;
278}
279
280void CatapultController::SetState(Eigen::Matrix<double, 2, 1> X_initial,
281 Eigen::Matrix<double, 2, 1> X_final) {
282 if (current_controller_ >= problems_.size()) {
283 return;
284 }
285 problems_[current_controller_]->SetState(X_initial, X_final);
286}
287
288bool CatapultController::Solve() {
289 if (current_controller_ >= problems_.size()) {
290 return true;
291 }
292 const bool result = problems_[current_controller_]->Solve();
293 solve_time_ = problems_[current_controller_]->solve_time();
294 return result;
295}
296
297std::optional<double> CatapultController::Next() {
298 if (current_controller_ >= problems_.size()) {
299 return std::nullopt;
300 }
301
Austin Schuh41472552022-03-13 18:09:41 -0700302 double u;
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700303 size_t solution_number = 0;
Austin Schuh41472552022-03-13 18:09:41 -0700304 if (current_controller_ == 0u) {
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700305 while (solution_number < problems_[current_controller_]->horizon() &&
306 problems_[current_controller_]->U(solution_number) < 0.01) {
307 u = problems_[current_controller_]->U(solution_number);
308 ++solution_number;
Austin Schuh41472552022-03-13 18:09:41 -0700309 }
Austin Schuh41472552022-03-13 18:09:41 -0700310 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700311 u = problems_[current_controller_]->U(solution_number);
Austin Schuh39f26f62022-02-24 21:34:46 -0800312
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700313 if (current_controller_ + 1u + solution_number < problems_.size()) {
314 problems_[current_controller_ + solution_number + 1]->WarmStart(
Austin Schuh39f26f62022-02-24 21:34:46 -0800315 *problems_[current_controller_]);
316 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700317 current_controller_ += 1u + solution_number;
Austin Schuh39f26f62022-02-24 21:34:46 -0800318 return u;
319}
320
321const flatbuffers::Offset<
322 frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
Ravago Jones3283ce02022-03-09 19:31:29 -0800323Catapult::Iterate(const CatapultGoal *catapult_goal, const Position *position,
Austin Schuh97410d72022-03-12 15:37:23 -0800324 double battery_voltage, double *catapult_voltage, bool fire,
Austin Schuh39f26f62022-02-24 21:34:46 -0800325 flatbuffers::FlatBufferBuilder *fbb) {
326 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
Ravago Jones3283ce02022-03-09 19:31:29 -0800327 *return_goal =
328 catapult_goal != nullptr && catapult_goal->has_return_position()
329 ? catapult_goal->return_position()
330 : nullptr;
Austin Schuh39f26f62022-02-24 21:34:46 -0800331
332 const bool catapult_disabled = catapult_.Correct(
Ravago Jones3283ce02022-03-09 19:31:29 -0800333 return_goal, position->catapult(), catapult_voltage == nullptr);
Austin Schuh39f26f62022-02-24 21:34:46 -0800334
335 if (catapult_disabled) {
336 catapult_state_ = CatapultState::PROFILE;
Ravago Jones3283ce02022-03-09 19:31:29 -0800337 } else if (catapult_.running() && catapult_goal != nullptr && fire &&
338 !last_firing_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800339 catapult_state_ = CatapultState::FIRING;
Ravago Jones3283ce02022-03-09 19:31:29 -0800340 latched_shot_position = catapult_goal->shot_position();
341 latched_shot_velocity = catapult_goal->shot_velocity();
Austin Schuh39f26f62022-02-24 21:34:46 -0800342 }
343
Milind Upadhyay058e64c2022-04-01 17:41:46 -0700344 // Don't update last_firing_ if the catapult is disabled, so that we actually
345 // end up firing once it's enabled
346 if (catapult_.running() && !catapult_disabled) {
Ravago Jones5da06352022-03-04 20:26:24 -0800347 last_firing_ = fire;
Austin Schuh39f26f62022-02-24 21:34:46 -0800348 }
349
350 use_profile_ = true;
351
352 switch (catapult_state_) {
353 case CatapultState::FIRING: {
354 // Select the ball controller. We should only be firing if we have a
355 // ball, or at least should only care about the shot accuracy.
356 catapult_.set_controller_index(0);
357 // Ok, so we've now corrected. Next step is to run the MPC.
358 //
359 // Since there is a unit delay between when we ask for a U and the
360 // hardware applies it, we need to run the optimizer for the position at
361 // the *next* control loop cycle.
362
Austin Schuhb39f4522022-03-27 13:29:42 -0700363 Eigen::Vector3d next_X = catapult_.estimated_state();
364 for (int i = catapult_.controller().plant().coefficients().delayed_u;
365 i > 1; --i) {
366 next_X = catapult_.controller().plant().A() * next_X +
367 catapult_.controller().plant().B() *
368 catapult_.controller().observer().last_U(i - 1);
369 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800370
371 catapult_mpc_.SetState(
372 next_X.block<2, 1>(0, 0),
Ravago Jones3283ce02022-03-09 19:31:29 -0800373 Eigen::Vector2d(latched_shot_position, latched_shot_velocity));
Austin Schuh39f26f62022-02-24 21:34:46 -0800374
375 const bool solved = catapult_mpc_.Solve();
Austin Schuh41472552022-03-13 18:09:41 -0700376 current_horizon_ = catapult_mpc_.current_horizon();
377 const bool started = catapult_mpc_.started();
378 if (solved || started) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800379 std::optional<double> solution = catapult_mpc_.Next();
380
381 if (!solution.has_value()) {
382 CHECK_NOTNULL(catapult_voltage);
383 *catapult_voltage = 0.0;
384 if (catapult_mpc_.started()) {
Austin Schuh80fc2752022-02-25 13:33:56 -0800385 ++shot_count_;
Austin Schuh39f26f62022-02-24 21:34:46 -0800386 // Finished the catapult, time to fire.
387 catapult_state_ = CatapultState::RESETTING;
388 }
389 } else {
390 // TODO(austin): Voltage error?
391 CHECK_NOTNULL(catapult_voltage);
Austin Schuh9628b8b2022-04-16 10:18:59 -0700392 if (current_horizon_ == 1) {
393 battery_voltage = 12.0;
394 }
Austin Schuh97410d72022-03-12 15:37:23 -0800395 *catapult_voltage = std::max(
396 0.0, std::min(12.0, (*solution - 0.0 * next_X(2, 0)) * 12.0 /
397 std::max(battery_voltage, 8.0)));
Austin Schuh39f26f62022-02-24 21:34:46 -0800398 use_profile_ = false;
399 }
400 } else {
Ravago Jones3283ce02022-03-09 19:31:29 -0800401 if (!fire) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800402 // Eh, didn't manage to solve before it was time to fire. Give up.
403 catapult_state_ = CatapultState::PROFILE;
404 }
405 }
406
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800407 if (!use_profile_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800408 catapult_.ForceGoal(catapult_.estimated_position(),
409 catapult_.estimated_velocity());
410 }
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800411 }
412 if (catapult_state_ != CatapultState::RESETTING) {
413 break;
414 } else {
415 [[fallthrough]];
416 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800417
418 case CatapultState::RESETTING:
Austin Schuh17be41d2022-03-12 16:11:39 -0800419 if (catapult_.controller().R(1, 0) > 7.0) {
420 catapult_.AdjustProfile(7.0, 2000.0);
421 } else if (catapult_.controller().R(1, 0) > 0.0) {
422 catapult_.AdjustProfile(7.0, 1000.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800423 } else {
424 catapult_state_ = CatapultState::PROFILE;
425 }
426 [[fallthrough]];
427
428 case CatapultState::PROFILE:
429 break;
430 }
431
432 if (use_profile_) {
433 if (catapult_state_ != CatapultState::FIRING) {
434 catapult_mpc_.Reset();
435 }
436 // Select the controller designed for when we have no ball.
437 catapult_.set_controller_index(1);
438
Austin Schuh41472552022-03-13 18:09:41 -0700439 current_horizon_ = 0u;
Austin Schuh39f26f62022-02-24 21:34:46 -0800440 const double output_voltage = catapult_.UpdateController(catapult_disabled);
441 if (catapult_voltage != nullptr) {
442 *catapult_voltage = output_voltage;
443 }
444 }
445
Austin Schuh97410d72022-03-12 15:37:23 -0800446 catapult_.UpdateObserver(catapult_voltage != nullptr
447 ? (*catapult_voltage * battery_voltage / 12.0)
448 : 0.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800449
450 return catapult_.MakeStatus(fbb);
451}
452
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800453} // namespace y2022::control_loops::superstructure::catapult