blob: cdffecdbf9d35729600d66c5409c1e93f07bbafe [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 Schuh75db4e82022-11-04 18:45:13 -070070 // If we mark this noalias(), it won't re-allocate the vector each time.
71 objective_vector_.noalias() =
Austin Schuh1d731362022-02-22 13:57:55 -080072 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
73
Austin Schuh39f26f62022-02-24 21:34:46 -080074 auto status = solver_.SetObjectiveVector(objective_vector_);
Austin Schuh1d731362022-02-22 13:57:55 -080075 CHECK(status.ok()) << status;
76}
77
78bool MPCProblem::Solve() {
79 const aos::monotonic_clock::time_point start_time =
80 aos::monotonic_clock::now();
81 osqp::OsqpExitCode exit_code = solver_.Solve();
82 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
83 VLOG(1) << "OSQP solved in "
84 << std::chrono::duration<double>(end_time - start_time).count();
85 solve_time_ = std::chrono::duration<double>(end_time - start_time).count();
86 // TODO(austin): Dump the exit codes out as an enum for logging.
87 //
88 // TODO(austin): The dual problem doesn't appear to be converging on all
89 // problems. Are we phrasing something wrong?
90
91 // TODO(austin): Set a time limit so we can't run forever, and signal back
92 // when we hit our limit.
93 return exit_code == osqp::OsqpExitCode::kOptimal;
94}
95
96void MPCProblem::WarmStart(const MPCProblem &p) {
97 CHECK_GE(p.horizon(), horizon())
98 << ": Can only copy a bigger problem's solution into a smaller problem.";
99 auto status = solver_.SetPrimalWarmStart(p.solver_.primal_solution().block(
100 p.horizon() - horizon(), 0, horizon(), 1));
101 CHECK(status.ok()) << status;
102 status = solver_.SetDualWarmStart(p.solver_.dual_solution().block(
103 p.horizon() - horizon(), 0, horizon(), 1));
104 CHECK(status.ok()) << status;
105}
106
107CatapultProblemGenerator::CatapultProblemGenerator(size_t horizon)
108 : plant_(MakeCatapultPlant()),
109 horizon_(horizon),
110 Q_final_(
111 (Eigen::DiagonalMatrix<double, 2>().diagonal() << 10000.0, 10000.0)
112 .finished()),
113 As_(MakeAs()),
114 Bs_(MakeBs()),
115 m_(Makem()),
116 M_(MakeM()),
117 W_(MakeW()),
118 w_(Makew()),
119 Pi_(MakePi()),
120 WM_(W_ * M_),
121 Wmpw_(W_ * m_ + w_) {}
122
123std::unique_ptr<MPCProblem> CatapultProblemGenerator::MakeProblem(
124 size_t horizon) {
125 return std::make_unique<MPCProblem>(
126 horizon, P(horizon), accel_q(horizon), Af(horizon),
127 (2.0 * Q_final_ * Bf(horizon)).transpose());
128}
129
130const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
131CatapultProblemGenerator::P(size_t horizon) {
132 CHECK_GT(horizon, 0u);
133 CHECK_LE(horizon, horizon_);
134 return 2.0 * (WM_.block(0, 0, horizon, horizon).transpose() * Pi(horizon) *
135 WM_.block(0, 0, horizon, horizon) +
136 Bf(horizon).transpose() * Q_final_ * Bf(horizon));
137}
138
139const Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::q(
Austin Schuh39f26f62022-02-24 21:34:46 -0800140 size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
141 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -0800142 CHECK_GT(horizon, 0u);
143 CHECK_LE(horizon, horizon_);
144 return 2.0 * X_initial(1, 0) * accel_q(horizon) +
145 2.0 * ((Af(horizon) * X_initial - X_final).transpose() * Q_final_ *
146 Bf(horizon))
147 .transpose();
148}
149
150const Eigen::Matrix<double, Eigen::Dynamic, 1>
151CatapultProblemGenerator::accel_q(size_t horizon) {
152 return 2.0 * ((Wmpw_.block(0, 0, horizon, 1)).transpose() * Pi(horizon) *
153 WM_.block(0, 0, horizon, horizon))
154 .transpose();
155}
156
157const Eigen::Matrix<double, 2, 2> CatapultProblemGenerator::Af(size_t horizon) {
158 CHECK_GT(horizon, 0u);
159 CHECK_LE(horizon, horizon_);
160 return As_.block<2, 2>(2 * (horizon - 1), 0);
161}
162
163const Eigen::Matrix<double, 2, Eigen::Dynamic> CatapultProblemGenerator::Bf(
164 size_t horizon) {
165 CHECK_GT(horizon, 0u);
166 CHECK_LE(horizon, horizon_);
167 return Bs_.block(2 * (horizon - 1), 0, 2, horizon);
168}
169
170const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
171CatapultProblemGenerator::Pi(size_t horizon) {
172 CHECK_GT(horizon, 0u);
173 CHECK_LE(horizon, horizon_);
174 return Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(Pi_).block(
175 horizon_ - horizon, horizon_ - horizon, horizon, horizon);
176}
177
178Eigen::Matrix<double, Eigen::Dynamic, 2> CatapultProblemGenerator::MakeAs() {
179 Eigen::Matrix<double, Eigen::Dynamic, 2> As =
180 Eigen::Matrix<double, Eigen::Dynamic, 2>::Zero(horizon_ * 2, 2);
181 for (size_t i = 0; i < horizon_; ++i) {
182 if (i == 0) {
183 As.block<2, 2>(0, 0) = plant_.A();
184 } else {
185 As.block<2, 2>(i * 2, 0) = plant_.A() * As.block<2, 2>((i - 1) * 2, 0);
186 }
187 }
188 return As;
189}
190
191Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
192CatapultProblemGenerator::MakeBs() {
193 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs =
194 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_ * 2,
195 horizon_);
196 for (size_t i = 0; i < horizon_; ++i) {
197 for (size_t j = 0; j < i + 1; ++j) {
198 if (i == j) {
199 Bs.block<2, 1>(i * 2, j) = plant_.B();
200 } else {
201 Bs.block<2, 1>(i * 2, j) =
202 As_.block<2, 2>((i - j - 1) * 2, 0) * plant_.B();
203 }
204 }
205 }
206 return Bs;
207}
208
209Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makem() {
210 Eigen::Matrix<double, Eigen::Dynamic, 1> m =
211 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
212 for (size_t i = 0; i < horizon_; ++i) {
213 m(i, 0) = As_(1 + 2 * i, 1);
214 }
215 return m;
216}
217
218Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
219CatapultProblemGenerator::MakeM() {
220 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M =
221 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_,
222 horizon_);
223 for (size_t i = 0; i < horizon_; ++i) {
224 for (size_t j = 0; j < horizon_; ++j) {
225 M(i, j) = Bs_(2 * i + 1, j);
226 }
227 }
228 return M;
229}
230
231Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
232CatapultProblemGenerator::MakeW() {
233 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W =
234 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(horizon_,
235 horizon_);
236 for (size_t i = 0; i < horizon_ - 1; ++i) {
237 W(i + 1, i) = -1.0;
238 }
239 W /= std::chrono::duration<double>(plant_.dt()).count();
240 return W;
241}
242
243Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makew() {
244 Eigen::Matrix<double, Eigen::Dynamic, 1> w =
245 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
246 w(0, 0) = -1.0 / std::chrono::duration<double>(plant_.dt()).count();
247 return w;
248}
249
250Eigen::DiagonalMatrix<double, Eigen::Dynamic>
251CatapultProblemGenerator::MakePi() {
252 Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi(horizon_);
253 for (size_t i = 0; i < horizon_; ++i) {
254 Pi.diagonal()(i) =
255 std::pow(0.01, 2.0) +
256 std::pow(0.02 * std::max(0.0, (20 - ((int)horizon_ - (int)i)) / 20.),
257 2.0);
258 }
259 return Pi;
260}
261
262Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
263CatapultProblemGenerator::MakeP() {
264 return 2.0 * (M_.transpose() * W_.transpose() * Pi_ * W_ * M_ +
265 Bf(horizon_).transpose() * Q_final_ * Bf(horizon_));
266}
267
Austin Schuh39f26f62022-02-24 21:34:46 -0800268CatapultController::CatapultController(size_t horizon) : generator_(horizon) {
269 problems_.reserve(generator_.horizon());
270 for (size_t i = generator_.horizon(); i > 0; --i) {
271 problems_.emplace_back(generator_.MakeProblem(i));
272 }
273
274 Reset();
275}
276
277void CatapultController::Reset() {
278 current_controller_ = 0;
279 solve_time_ = 0.0;
280}
281
282void CatapultController::SetState(Eigen::Matrix<double, 2, 1> X_initial,
283 Eigen::Matrix<double, 2, 1> X_final) {
284 if (current_controller_ >= problems_.size()) {
285 return;
286 }
287 problems_[current_controller_]->SetState(X_initial, X_final);
288}
289
290bool CatapultController::Solve() {
291 if (current_controller_ >= problems_.size()) {
292 return true;
293 }
294 const bool result = problems_[current_controller_]->Solve();
295 solve_time_ = problems_[current_controller_]->solve_time();
296 return result;
297}
298
299std::optional<double> CatapultController::Next() {
300 if (current_controller_ >= problems_.size()) {
301 return std::nullopt;
302 }
303
Austin Schuh41472552022-03-13 18:09:41 -0700304 double u;
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700305 size_t solution_number = 0;
Austin Schuh41472552022-03-13 18:09:41 -0700306 if (current_controller_ == 0u) {
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700307 while (solution_number < problems_[current_controller_]->horizon() &&
308 problems_[current_controller_]->U(solution_number) < 0.01) {
309 u = problems_[current_controller_]->U(solution_number);
310 ++solution_number;
Austin Schuh41472552022-03-13 18:09:41 -0700311 }
Austin Schuh41472552022-03-13 18:09:41 -0700312 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700313 u = problems_[current_controller_]->U(solution_number);
Austin Schuh39f26f62022-02-24 21:34:46 -0800314
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700315 if (current_controller_ + 1u + solution_number < problems_.size()) {
316 problems_[current_controller_ + solution_number + 1]->WarmStart(
Austin Schuh39f26f62022-02-24 21:34:46 -0800317 *problems_[current_controller_]);
318 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700319 current_controller_ += 1u + solution_number;
Austin Schuh39f26f62022-02-24 21:34:46 -0800320 return u;
321}
322
323const flatbuffers::Offset<
324 frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
Ravago Jones3283ce02022-03-09 19:31:29 -0800325Catapult::Iterate(const CatapultGoal *catapult_goal, const Position *position,
Austin Schuh97410d72022-03-12 15:37:23 -0800326 double battery_voltage, double *catapult_voltage, bool fire,
Austin Schuh39f26f62022-02-24 21:34:46 -0800327 flatbuffers::FlatBufferBuilder *fbb) {
328 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
Ravago Jones3283ce02022-03-09 19:31:29 -0800329 *return_goal =
330 catapult_goal != nullptr && catapult_goal->has_return_position()
331 ? catapult_goal->return_position()
332 : nullptr;
Austin Schuh39f26f62022-02-24 21:34:46 -0800333
334 const bool catapult_disabled = catapult_.Correct(
Ravago Jones3283ce02022-03-09 19:31:29 -0800335 return_goal, position->catapult(), catapult_voltage == nullptr);
Austin Schuh39f26f62022-02-24 21:34:46 -0800336
337 if (catapult_disabled) {
338 catapult_state_ = CatapultState::PROFILE;
Ravago Jones3283ce02022-03-09 19:31:29 -0800339 } else if (catapult_.running() && catapult_goal != nullptr && fire &&
340 !last_firing_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800341 catapult_state_ = CatapultState::FIRING;
Ravago Jones3283ce02022-03-09 19:31:29 -0800342 latched_shot_position = catapult_goal->shot_position();
343 latched_shot_velocity = catapult_goal->shot_velocity();
Austin Schuh39f26f62022-02-24 21:34:46 -0800344 }
345
Milind Upadhyay058e64c2022-04-01 17:41:46 -0700346 // Don't update last_firing_ if the catapult is disabled, so that we actually
347 // end up firing once it's enabled
348 if (catapult_.running() && !catapult_disabled) {
Ravago Jones5da06352022-03-04 20:26:24 -0800349 last_firing_ = fire;
Austin Schuh39f26f62022-02-24 21:34:46 -0800350 }
351
352 use_profile_ = true;
353
354 switch (catapult_state_) {
355 case CatapultState::FIRING: {
356 // Select the ball controller. We should only be firing if we have a
357 // ball, or at least should only care about the shot accuracy.
358 catapult_.set_controller_index(0);
359 // Ok, so we've now corrected. Next step is to run the MPC.
360 //
361 // Since there is a unit delay between when we ask for a U and the
362 // hardware applies it, we need to run the optimizer for the position at
363 // the *next* control loop cycle.
364
Austin Schuhb39f4522022-03-27 13:29:42 -0700365 Eigen::Vector3d next_X = catapult_.estimated_state();
366 for (int i = catapult_.controller().plant().coefficients().delayed_u;
367 i > 1; --i) {
368 next_X = catapult_.controller().plant().A() * next_X +
369 catapult_.controller().plant().B() *
370 catapult_.controller().observer().last_U(i - 1);
371 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800372
373 catapult_mpc_.SetState(
374 next_X.block<2, 1>(0, 0),
Ravago Jones3283ce02022-03-09 19:31:29 -0800375 Eigen::Vector2d(latched_shot_position, latched_shot_velocity));
Austin Schuh39f26f62022-02-24 21:34:46 -0800376
377 const bool solved = catapult_mpc_.Solve();
Austin Schuh41472552022-03-13 18:09:41 -0700378 current_horizon_ = catapult_mpc_.current_horizon();
379 const bool started = catapult_mpc_.started();
380 if (solved || started) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800381 std::optional<double> solution = catapult_mpc_.Next();
382
383 if (!solution.has_value()) {
384 CHECK_NOTNULL(catapult_voltage);
385 *catapult_voltage = 0.0;
386 if (catapult_mpc_.started()) {
Austin Schuh80fc2752022-02-25 13:33:56 -0800387 ++shot_count_;
Austin Schuh39f26f62022-02-24 21:34:46 -0800388 // Finished the catapult, time to fire.
389 catapult_state_ = CatapultState::RESETTING;
390 }
391 } else {
392 // TODO(austin): Voltage error?
393 CHECK_NOTNULL(catapult_voltage);
Austin Schuh9628b8b2022-04-16 10:18:59 -0700394 if (current_horizon_ == 1) {
395 battery_voltage = 12.0;
396 }
Austin Schuh97410d72022-03-12 15:37:23 -0800397 *catapult_voltage = std::max(
398 0.0, std::min(12.0, (*solution - 0.0 * next_X(2, 0)) * 12.0 /
399 std::max(battery_voltage, 8.0)));
Austin Schuh39f26f62022-02-24 21:34:46 -0800400 use_profile_ = false;
401 }
402 } else {
Ravago Jones3283ce02022-03-09 19:31:29 -0800403 if (!fire) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800404 // Eh, didn't manage to solve before it was time to fire. Give up.
405 catapult_state_ = CatapultState::PROFILE;
406 }
407 }
408
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800409 if (!use_profile_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800410 catapult_.ForceGoal(catapult_.estimated_position(),
411 catapult_.estimated_velocity());
412 }
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800413 }
414 if (catapult_state_ != CatapultState::RESETTING) {
415 break;
416 } else {
417 [[fallthrough]];
418 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800419
420 case CatapultState::RESETTING:
Austin Schuh17be41d2022-03-12 16:11:39 -0800421 if (catapult_.controller().R(1, 0) > 7.0) {
422 catapult_.AdjustProfile(7.0, 2000.0);
423 } else if (catapult_.controller().R(1, 0) > 0.0) {
424 catapult_.AdjustProfile(7.0, 1000.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800425 } else {
426 catapult_state_ = CatapultState::PROFILE;
427 }
428 [[fallthrough]];
429
430 case CatapultState::PROFILE:
431 break;
432 }
433
434 if (use_profile_) {
435 if (catapult_state_ != CatapultState::FIRING) {
436 catapult_mpc_.Reset();
437 }
438 // Select the controller designed for when we have no ball.
439 catapult_.set_controller_index(1);
440
Austin Schuh41472552022-03-13 18:09:41 -0700441 current_horizon_ = 0u;
Austin Schuh39f26f62022-02-24 21:34:46 -0800442 const double output_voltage = catapult_.UpdateController(catapult_disabled);
443 if (catapult_voltage != nullptr) {
444 *catapult_voltage = output_voltage;
445 }
446 }
447
Austin Schuh97410d72022-03-12 15:37:23 -0800448 catapult_.UpdateObserver(catapult_voltage != nullptr
449 ? (*catapult_voltage * battery_voltage / 12.0)
450 : 0.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800451
452 return catapult_.MakeStatus(fbb);
453}
454
Austin Schuh1d731362022-02-22 13:57:55 -0800455} // namespace catapult
456} // namespace superstructure
457} // namespace control_loops
458} // namespace y2022