blob: b0ec6fda895ac462649ed3973d80afc55700cbc9 [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
13namespace y2022 {
14namespace control_loops {
15namespace superstructure {
16namespace catapult {
17namespace chrono = std::chrono;
18
19namespace {
20osqp::OsqpInstance MakeInstance(
21 size_t horizon, Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P) {
22 osqp::OsqpInstance instance;
Austin Schuh39f26f62022-02-24 21:34:46 -080023 instance.objective_matrix = P.sparseView();
Austin Schuh1d731362022-02-22 13:57:55 -080024
25 instance.constraint_matrix =
Austin Schuh39f26f62022-02-24 21:34:46 -080026 Eigen::SparseMatrix<double, Eigen::ColMajor, osqp::c_int>(horizon,
Ravago Jones5da06352022-03-04 20:26:24 -080027 horizon);
Austin Schuh1d731362022-02-22 13:57:55 -080028 instance.constraint_matrix.setIdentity();
29
30 instance.lower_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080031 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon, 1);
Austin Schuh1d731362022-02-22 13:57:55 -080032 instance.upper_bounds =
Austin Schuh39f26f62022-02-24 21:34:46 -080033 Eigen::Matrix<double, Eigen::Dynamic, 1>::Ones(horizon, 1) * 12.0;
Austin Schuh1d731362022-02-22 13:57:55 -080034 return instance;
35}
36} // namespace
37
38MPCProblem::MPCProblem(size_t horizon,
39 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P,
40 Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q,
41 Eigen::Matrix<double, 2, 2> Af,
42 Eigen::Matrix<double, Eigen::Dynamic, 2> final_q)
43 : horizon_(horizon),
Austin Schuh39f26f62022-02-24 21:34:46 -080044 accel_q_(std::move(accel_q)),
45 Af_(std::move(Af)),
46 final_q_(std::move(final_q)),
Austin Schuh1d731362022-02-22 13:57:55 -080047 instance_(MakeInstance(horizon, std::move(P))) {
Austin Schuh39f26f62022-02-24 21:34:46 -080048 // Start with a representative problem.
49 Eigen::Matrix<double, 2, 1> X_initial(0.0, 0.0);
50 Eigen::Matrix<double, 2, 1> X_final(2.0, 25.0);
51
52 objective_vector_ =
53 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
54 instance_.objective_vector = objective_vector_;
Austin Schuh1d731362022-02-22 13:57:55 -080055 settings_.max_iter = 25;
Austin Schuh39f26f62022-02-24 21:34:46 -080056 settings_.check_termination = 5;
57 settings_.warm_start = 1;
58 // TODO(austin): Do we need this scaling thing? It makes it not solve
59 // sometimes... I'm pretty certain by giving it a decently formed problem to
60 // initialize with, it will not try doing crazy things with the scaling
61 // internally.
62 settings_.scaling = 0;
Austin Schuh1d731362022-02-22 13:57:55 -080063 auto status = solver_.Init(instance_, settings_);
64 CHECK(status.ok()) << status;
65}
66
Austin Schuh39f26f62022-02-24 21:34:46 -080067void MPCProblem::SetState(Eigen::Matrix<double, 2, 1> X_initial,
68 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -080069 X_initial_ = X_initial;
70 X_final_ = X_final;
Austin Schuh75db4e82022-11-04 18:45:13 -070071 // If we mark this noalias(), it won't re-allocate the vector each time.
72 objective_vector_.noalias() =
Austin Schuh1d731362022-02-22 13:57:55 -080073 X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
74
Austin Schuh39f26f62022-02-24 21:34:46 -080075 auto status = solver_.SetObjectiveVector(objective_vector_);
Austin Schuh1d731362022-02-22 13:57:55 -080076 CHECK(status.ok()) << status;
77}
78
79bool MPCProblem::Solve() {
80 const aos::monotonic_clock::time_point start_time =
81 aos::monotonic_clock::now();
82 osqp::OsqpExitCode exit_code = solver_.Solve();
83 const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
84 VLOG(1) << "OSQP solved in "
85 << std::chrono::duration<double>(end_time - start_time).count();
86 solve_time_ = std::chrono::duration<double>(end_time - start_time).count();
87 // TODO(austin): Dump the exit codes out as an enum for logging.
88 //
89 // TODO(austin): The dual problem doesn't appear to be converging on all
90 // problems. Are we phrasing something wrong?
91
92 // TODO(austin): Set a time limit so we can't run forever, and signal back
93 // when we hit our limit.
94 return exit_code == osqp::OsqpExitCode::kOptimal;
95}
96
97void MPCProblem::WarmStart(const MPCProblem &p) {
98 CHECK_GE(p.horizon(), horizon())
99 << ": Can only copy a bigger problem's solution into a smaller problem.";
100 auto status = solver_.SetPrimalWarmStart(p.solver_.primal_solution().block(
101 p.horizon() - horizon(), 0, horizon(), 1));
102 CHECK(status.ok()) << status;
103 status = solver_.SetDualWarmStart(p.solver_.dual_solution().block(
104 p.horizon() - horizon(), 0, horizon(), 1));
105 CHECK(status.ok()) << status;
106}
107
108CatapultProblemGenerator::CatapultProblemGenerator(size_t horizon)
109 : plant_(MakeCatapultPlant()),
110 horizon_(horizon),
111 Q_final_(
112 (Eigen::DiagonalMatrix<double, 2>().diagonal() << 10000.0, 10000.0)
113 .finished()),
114 As_(MakeAs()),
115 Bs_(MakeBs()),
116 m_(Makem()),
117 M_(MakeM()),
118 W_(MakeW()),
119 w_(Makew()),
120 Pi_(MakePi()),
121 WM_(W_ * M_),
122 Wmpw_(W_ * m_ + w_) {}
123
124std::unique_ptr<MPCProblem> CatapultProblemGenerator::MakeProblem(
125 size_t horizon) {
126 return std::make_unique<MPCProblem>(
127 horizon, P(horizon), accel_q(horizon), Af(horizon),
128 (2.0 * Q_final_ * Bf(horizon)).transpose());
129}
130
131const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
132CatapultProblemGenerator::P(size_t horizon) {
133 CHECK_GT(horizon, 0u);
134 CHECK_LE(horizon, horizon_);
135 return 2.0 * (WM_.block(0, 0, horizon, horizon).transpose() * Pi(horizon) *
136 WM_.block(0, 0, horizon, horizon) +
137 Bf(horizon).transpose() * Q_final_ * Bf(horizon));
138}
139
140const Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::q(
Austin Schuh39f26f62022-02-24 21:34:46 -0800141 size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
142 Eigen::Matrix<double, 2, 1> X_final) {
Austin Schuh1d731362022-02-22 13:57:55 -0800143 CHECK_GT(horizon, 0u);
144 CHECK_LE(horizon, horizon_);
145 return 2.0 * X_initial(1, 0) * accel_q(horizon) +
146 2.0 * ((Af(horizon) * X_initial - X_final).transpose() * Q_final_ *
147 Bf(horizon))
148 .transpose();
149}
150
151const Eigen::Matrix<double, Eigen::Dynamic, 1>
152CatapultProblemGenerator::accel_q(size_t horizon) {
153 return 2.0 * ((Wmpw_.block(0, 0, horizon, 1)).transpose() * Pi(horizon) *
154 WM_.block(0, 0, horizon, horizon))
155 .transpose();
156}
157
158const Eigen::Matrix<double, 2, 2> CatapultProblemGenerator::Af(size_t horizon) {
159 CHECK_GT(horizon, 0u);
160 CHECK_LE(horizon, horizon_);
161 return As_.block<2, 2>(2 * (horizon - 1), 0);
162}
163
164const Eigen::Matrix<double, 2, Eigen::Dynamic> CatapultProblemGenerator::Bf(
165 size_t horizon) {
166 CHECK_GT(horizon, 0u);
167 CHECK_LE(horizon, horizon_);
168 return Bs_.block(2 * (horizon - 1), 0, 2, horizon);
169}
170
171const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
172CatapultProblemGenerator::Pi(size_t horizon) {
173 CHECK_GT(horizon, 0u);
174 CHECK_LE(horizon, horizon_);
175 return Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(Pi_).block(
176 horizon_ - horizon, horizon_ - horizon, horizon, horizon);
177}
178
179Eigen::Matrix<double, Eigen::Dynamic, 2> CatapultProblemGenerator::MakeAs() {
180 Eigen::Matrix<double, Eigen::Dynamic, 2> As =
181 Eigen::Matrix<double, Eigen::Dynamic, 2>::Zero(horizon_ * 2, 2);
182 for (size_t i = 0; i < horizon_; ++i) {
183 if (i == 0) {
184 As.block<2, 2>(0, 0) = plant_.A();
185 } else {
186 As.block<2, 2>(i * 2, 0) = plant_.A() * As.block<2, 2>((i - 1) * 2, 0);
187 }
188 }
189 return As;
190}
191
192Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
193CatapultProblemGenerator::MakeBs() {
194 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs =
195 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_ * 2,
196 horizon_);
197 for (size_t i = 0; i < horizon_; ++i) {
198 for (size_t j = 0; j < i + 1; ++j) {
199 if (i == j) {
200 Bs.block<2, 1>(i * 2, j) = plant_.B();
201 } else {
202 Bs.block<2, 1>(i * 2, j) =
203 As_.block<2, 2>((i - j - 1) * 2, 0) * plant_.B();
204 }
205 }
206 }
207 return Bs;
208}
209
210Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makem() {
211 Eigen::Matrix<double, Eigen::Dynamic, 1> m =
212 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
213 for (size_t i = 0; i < horizon_; ++i) {
214 m(i, 0) = As_(1 + 2 * i, 1);
215 }
216 return m;
217}
218
219Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
220CatapultProblemGenerator::MakeM() {
221 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M =
222 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_,
223 horizon_);
224 for (size_t i = 0; i < horizon_; ++i) {
225 for (size_t j = 0; j < horizon_; ++j) {
226 M(i, j) = Bs_(2 * i + 1, j);
227 }
228 }
229 return M;
230}
231
232Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
233CatapultProblemGenerator::MakeW() {
234 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W =
235 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(horizon_,
236 horizon_);
237 for (size_t i = 0; i < horizon_ - 1; ++i) {
238 W(i + 1, i) = -1.0;
239 }
240 W /= std::chrono::duration<double>(plant_.dt()).count();
241 return W;
242}
243
244Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makew() {
245 Eigen::Matrix<double, Eigen::Dynamic, 1> w =
246 Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
247 w(0, 0) = -1.0 / std::chrono::duration<double>(plant_.dt()).count();
248 return w;
249}
250
251Eigen::DiagonalMatrix<double, Eigen::Dynamic>
252CatapultProblemGenerator::MakePi() {
253 Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi(horizon_);
254 for (size_t i = 0; i < horizon_; ++i) {
255 Pi.diagonal()(i) =
256 std::pow(0.01, 2.0) +
257 std::pow(0.02 * std::max(0.0, (20 - ((int)horizon_ - (int)i)) / 20.),
258 2.0);
259 }
260 return Pi;
261}
262
263Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
264CatapultProblemGenerator::MakeP() {
265 return 2.0 * (M_.transpose() * W_.transpose() * Pi_ * W_ * M_ +
266 Bf(horizon_).transpose() * Q_final_ * Bf(horizon_));
267}
268
Austin Schuh39f26f62022-02-24 21:34:46 -0800269CatapultController::CatapultController(size_t horizon) : generator_(horizon) {
270 problems_.reserve(generator_.horizon());
271 for (size_t i = generator_.horizon(); i > 0; --i) {
272 problems_.emplace_back(generator_.MakeProblem(i));
273 }
274
275 Reset();
276}
277
278void CatapultController::Reset() {
279 current_controller_ = 0;
280 solve_time_ = 0.0;
281}
282
283void CatapultController::SetState(Eigen::Matrix<double, 2, 1> X_initial,
284 Eigen::Matrix<double, 2, 1> X_final) {
285 if (current_controller_ >= problems_.size()) {
286 return;
287 }
288 problems_[current_controller_]->SetState(X_initial, X_final);
289}
290
291bool CatapultController::Solve() {
292 if (current_controller_ >= problems_.size()) {
293 return true;
294 }
295 const bool result = problems_[current_controller_]->Solve();
296 solve_time_ = problems_[current_controller_]->solve_time();
297 return result;
298}
299
300std::optional<double> CatapultController::Next() {
301 if (current_controller_ >= problems_.size()) {
302 return std::nullopt;
303 }
304
Austin Schuh41472552022-03-13 18:09:41 -0700305 double u;
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700306 size_t solution_number = 0;
Austin Schuh41472552022-03-13 18:09:41 -0700307 if (current_controller_ == 0u) {
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700308 while (solution_number < problems_[current_controller_]->horizon() &&
309 problems_[current_controller_]->U(solution_number) < 0.01) {
310 u = problems_[current_controller_]->U(solution_number);
311 ++solution_number;
Austin Schuh41472552022-03-13 18:09:41 -0700312 }
Austin Schuh41472552022-03-13 18:09:41 -0700313 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700314 u = problems_[current_controller_]->U(solution_number);
Austin Schuh39f26f62022-02-24 21:34:46 -0800315
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700316 if (current_controller_ + 1u + solution_number < problems_.size()) {
317 problems_[current_controller_ + solution_number + 1]->WarmStart(
Austin Schuh39f26f62022-02-24 21:34:46 -0800318 *problems_[current_controller_]);
319 }
Austin Schuh9d5c3eb2022-03-16 19:33:25 -0700320 current_controller_ += 1u + solution_number;
Austin Schuh39f26f62022-02-24 21:34:46 -0800321 return u;
322}
323
324const flatbuffers::Offset<
325 frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
Ravago Jones3283ce02022-03-09 19:31:29 -0800326Catapult::Iterate(const CatapultGoal *catapult_goal, const Position *position,
Austin Schuh97410d72022-03-12 15:37:23 -0800327 double battery_voltage, double *catapult_voltage, bool fire,
Austin Schuh39f26f62022-02-24 21:34:46 -0800328 flatbuffers::FlatBufferBuilder *fbb) {
329 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
Ravago Jones3283ce02022-03-09 19:31:29 -0800330 *return_goal =
331 catapult_goal != nullptr && catapult_goal->has_return_position()
332 ? catapult_goal->return_position()
333 : nullptr;
Austin Schuh39f26f62022-02-24 21:34:46 -0800334
335 const bool catapult_disabled = catapult_.Correct(
Ravago Jones3283ce02022-03-09 19:31:29 -0800336 return_goal, position->catapult(), catapult_voltage == nullptr);
Austin Schuh39f26f62022-02-24 21:34:46 -0800337
338 if (catapult_disabled) {
339 catapult_state_ = CatapultState::PROFILE;
Ravago Jones3283ce02022-03-09 19:31:29 -0800340 } else if (catapult_.running() && catapult_goal != nullptr && fire &&
341 !last_firing_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800342 catapult_state_ = CatapultState::FIRING;
Ravago Jones3283ce02022-03-09 19:31:29 -0800343 latched_shot_position = catapult_goal->shot_position();
344 latched_shot_velocity = catapult_goal->shot_velocity();
Austin Schuh39f26f62022-02-24 21:34:46 -0800345 }
346
Milind Upadhyay058e64c2022-04-01 17:41:46 -0700347 // Don't update last_firing_ if the catapult is disabled, so that we actually
348 // end up firing once it's enabled
349 if (catapult_.running() && !catapult_disabled) {
Ravago Jones5da06352022-03-04 20:26:24 -0800350 last_firing_ = fire;
Austin Schuh39f26f62022-02-24 21:34:46 -0800351 }
352
353 use_profile_ = true;
354
355 switch (catapult_state_) {
356 case CatapultState::FIRING: {
357 // Select the ball controller. We should only be firing if we have a
358 // ball, or at least should only care about the shot accuracy.
359 catapult_.set_controller_index(0);
360 // Ok, so we've now corrected. Next step is to run the MPC.
361 //
362 // Since there is a unit delay between when we ask for a U and the
363 // hardware applies it, we need to run the optimizer for the position at
364 // the *next* control loop cycle.
365
Austin Schuhb39f4522022-03-27 13:29:42 -0700366 Eigen::Vector3d next_X = catapult_.estimated_state();
367 for (int i = catapult_.controller().plant().coefficients().delayed_u;
368 i > 1; --i) {
369 next_X = catapult_.controller().plant().A() * next_X +
370 catapult_.controller().plant().B() *
371 catapult_.controller().observer().last_U(i - 1);
372 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800373
374 catapult_mpc_.SetState(
375 next_X.block<2, 1>(0, 0),
Ravago Jones3283ce02022-03-09 19:31:29 -0800376 Eigen::Vector2d(latched_shot_position, latched_shot_velocity));
Austin Schuh39f26f62022-02-24 21:34:46 -0800377
378 const bool solved = catapult_mpc_.Solve();
Austin Schuh41472552022-03-13 18:09:41 -0700379 current_horizon_ = catapult_mpc_.current_horizon();
380 const bool started = catapult_mpc_.started();
381 if (solved || started) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800382 std::optional<double> solution = catapult_mpc_.Next();
383
384 if (!solution.has_value()) {
385 CHECK_NOTNULL(catapult_voltage);
386 *catapult_voltage = 0.0;
387 if (catapult_mpc_.started()) {
Austin Schuh80fc2752022-02-25 13:33:56 -0800388 ++shot_count_;
Austin Schuh39f26f62022-02-24 21:34:46 -0800389 // Finished the catapult, time to fire.
390 catapult_state_ = CatapultState::RESETTING;
391 }
392 } else {
393 // TODO(austin): Voltage error?
394 CHECK_NOTNULL(catapult_voltage);
Austin Schuh9628b8b2022-04-16 10:18:59 -0700395 if (current_horizon_ == 1) {
396 battery_voltage = 12.0;
397 }
Austin Schuh97410d72022-03-12 15:37:23 -0800398 *catapult_voltage = std::max(
399 0.0, std::min(12.0, (*solution - 0.0 * next_X(2, 0)) * 12.0 /
400 std::max(battery_voltage, 8.0)));
Austin Schuh39f26f62022-02-24 21:34:46 -0800401 use_profile_ = false;
402 }
403 } else {
Ravago Jones3283ce02022-03-09 19:31:29 -0800404 if (!fire) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800405 // Eh, didn't manage to solve before it was time to fire. Give up.
406 catapult_state_ = CatapultState::PROFILE;
407 }
408 }
409
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800410 if (!use_profile_) {
Austin Schuh39f26f62022-02-24 21:34:46 -0800411 catapult_.ForceGoal(catapult_.estimated_position(),
412 catapult_.estimated_velocity());
413 }
Austin Schuhdfeb83c2022-03-12 13:17:49 -0800414 }
415 if (catapult_state_ != CatapultState::RESETTING) {
416 break;
417 } else {
418 [[fallthrough]];
419 }
Austin Schuh39f26f62022-02-24 21:34:46 -0800420
421 case CatapultState::RESETTING:
Austin Schuh17be41d2022-03-12 16:11:39 -0800422 if (catapult_.controller().R(1, 0) > 7.0) {
423 catapult_.AdjustProfile(7.0, 2000.0);
424 } else if (catapult_.controller().R(1, 0) > 0.0) {
425 catapult_.AdjustProfile(7.0, 1000.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800426 } else {
427 catapult_state_ = CatapultState::PROFILE;
428 }
429 [[fallthrough]];
430
431 case CatapultState::PROFILE:
432 break;
433 }
434
435 if (use_profile_) {
436 if (catapult_state_ != CatapultState::FIRING) {
437 catapult_mpc_.Reset();
438 }
439 // Select the controller designed for when we have no ball.
440 catapult_.set_controller_index(1);
441
Austin Schuh41472552022-03-13 18:09:41 -0700442 current_horizon_ = 0u;
Austin Schuh39f26f62022-02-24 21:34:46 -0800443 const double output_voltage = catapult_.UpdateController(catapult_disabled);
444 if (catapult_voltage != nullptr) {
445 *catapult_voltage = output_voltage;
446 }
447 }
448
Austin Schuh97410d72022-03-12 15:37:23 -0800449 catapult_.UpdateObserver(catapult_voltage != nullptr
450 ? (*catapult_voltage * battery_voltage / 12.0)
451 : 0.0);
Austin Schuh39f26f62022-02-24 21:34:46 -0800452
453 return catapult_.MakeStatus(fbb);
454}
455
Austin Schuh1d731362022-02-22 13:57:55 -0800456} // namespace catapult
457} // namespace superstructure
458} // namespace control_loops
459} // namespace y2022