blob: 00bb3b37136cef2408cf7c80ed36cf623d60975e [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,
Austin Schuh1d731362022-02-22 13:57:55 -080026 horizon);
27 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
303 const double u = problems_[current_controller_]->U(0);
304
305 if (current_controller_ + 1u < problems_.size()) {
306 problems_[current_controller_ + 1]->WarmStart(
307 *problems_[current_controller_]);
308 }
309 ++current_controller_;
310 return u;
311}
312
313const flatbuffers::Offset<
314 frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
315Catapult::Iterate(const Goal *unsafe_goal, const Position *position,
316 double *catapult_voltage,
317 flatbuffers::FlatBufferBuilder *fbb) {
318 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
319 *catapult_goal = unsafe_goal != nullptr && unsafe_goal->has_catapult()
320 ? (unsafe_goal->catapult()->return_position())
321 : nullptr;
322
323 const bool catapult_disabled = catapult_.Correct(
324 catapult_goal, position->catapult(), catapult_voltage == nullptr);
325
326 if (catapult_disabled) {
327 catapult_state_ = CatapultState::PROFILE;
328 } else if (catapult_.running() && unsafe_goal &&
329 unsafe_goal->has_catapult() && unsafe_goal->catapult()->fire() &&
330 !last_firing_) {
331 catapult_state_ = CatapultState::FIRING;
332 }
333
334 if (catapult_.running() && unsafe_goal && unsafe_goal->has_catapult()) {
335 last_firing_ = unsafe_goal->catapult()->fire();
336 }
337
338 use_profile_ = true;
339
340 switch (catapult_state_) {
341 case CatapultState::FIRING: {
342 // Select the ball controller. We should only be firing if we have a
343 // ball, or at least should only care about the shot accuracy.
344 catapult_.set_controller_index(0);
345 // Ok, so we've now corrected. Next step is to run the MPC.
346 //
347 // Since there is a unit delay between when we ask for a U and the
348 // hardware applies it, we need to run the optimizer for the position at
349 // the *next* control loop cycle.
350
351 const Eigen::Vector3d next_X =
352 catapult_.controller().plant().A() * catapult_.estimated_state() +
353 catapult_.controller().plant().B() *
354 catapult_.controller().observer().last_U();
355
356 catapult_mpc_.SetState(
357 next_X.block<2, 1>(0, 0),
358 Eigen::Vector2d(unsafe_goal->catapult()->shot_position(),
359 unsafe_goal->catapult()->shot_velocity()));
360
361 const bool solved = catapult_mpc_.Solve();
362
363 if (solved || catapult_mpc_.started()) {
364 std::optional<double> solution = catapult_mpc_.Next();
365
366 if (!solution.has_value()) {
367 CHECK_NOTNULL(catapult_voltage);
368 *catapult_voltage = 0.0;
369 if (catapult_mpc_.started()) {
370 // Finished the catapult, time to fire.
371 catapult_state_ = CatapultState::RESETTING;
372 }
373 } else {
374 // TODO(austin): Voltage error?
375 CHECK_NOTNULL(catapult_voltage);
376 *catapult_voltage =
377 std::max(0.0, std::min(12.0, *solution - 0.0 * next_X(2, 0)));
378 use_profile_ = false;
379 }
380 } else {
381 if (unsafe_goal && unsafe_goal->has_catapult() &&
382 !unsafe_goal->catapult()->fire()) {
383 // Eh, didn't manage to solve before it was time to fire. Give up.
384 catapult_state_ = CatapultState::PROFILE;
385 }
386 }
387
388 if (!use_profile_ || catapult_state_ == CatapultState::RESETTING) {
389 catapult_.ForceGoal(catapult_.estimated_position(),
390 catapult_.estimated_velocity());
391 }
392 } break;
393
394 case CatapultState::RESETTING:
395 if (catapult_.controller().R(1, 0) > 0.0) {
396 catapult_.AdjustProfile(7.0, 500.0);
397 } else {
398 catapult_state_ = CatapultState::PROFILE;
399 }
400 [[fallthrough]];
401
402 case CatapultState::PROFILE:
403 break;
404 }
405
406 if (use_profile_) {
407 if (catapult_state_ != CatapultState::FIRING) {
408 catapult_mpc_.Reset();
409 }
410 // Select the controller designed for when we have no ball.
411 catapult_.set_controller_index(1);
412
413 const double output_voltage = catapult_.UpdateController(catapult_disabled);
414 if (catapult_voltage != nullptr) {
415 *catapult_voltage = output_voltage;
416 }
417 }
418
419 catapult_.UpdateObserver(catapult_voltage != nullptr ? *catapult_voltage : 0.0);
420
421 return catapult_.MakeStatus(fbb);
422}
423
Austin Schuh1d731362022-02-22 13:57:55 -0800424} // namespace catapult
425} // namespace superstructure
426} // namespace control_loops
427} // namespace y2022