Refactor year-agnostic catapult code to frc971

This breaks up the y2022 catapult code into multiple files and moves
them into the frc971 folder. Year-specific parameters are now
provided via the constructors, and the goal message is moved into
frc971 as well.

Signed-off-by: Niko Sohmers <nikolai@sohmers.com>
Change-Id: I4ea720ae62a7c6c229d6c24a1f08edd7bc5b9728
diff --git a/frc971/control_loops/catapult/BUILD b/frc971/control_loops/catapult/BUILD
new file mode 100644
index 0000000..1235044
--- /dev/null
+++ b/frc971/control_loops/catapult/BUILD
@@ -0,0 +1,86 @@
+load("//aos/flatbuffers:generate.bzl", "static_flatbuffer")
+
+package(default_visibility = ["//visibility:public"])
+
+static_flatbuffer(
+    name = "catapult_goal_fbs",
+    srcs = [
+        "catapult_goal.fbs",
+    ],
+    deps = [
+        "//frc971/control_loops:profiled_subsystem_fbs",
+    ],
+)
+
+cc_library(
+    name = "catapult_controller",
+    srcs =
+        [
+            "catapult_controller.cc",
+        ],
+    hdrs =
+        [
+            "catapult_controller.h",
+        ],
+    visibility = ["//visibility:public"],
+    deps =
+        [
+            ":mpc_problem_generator",
+        ],
+)
+
+cc_library(
+    name = "mpc_problem",
+    srcs =
+        [
+            "mpc_problem.cc",
+        ],
+    hdrs =
+        [
+            "mpc_problem.h",
+        ],
+    visibility = ["//visibility:public"],
+    deps =
+        [
+            "//aos:realtime",
+            "//aos/time",
+            "//third_party/osqp-cpp",
+            "@org_tuxfamily_eigen//:eigen",
+        ],
+)
+
+cc_library(
+    name = "mpc_problem_generator",
+    srcs =
+        [
+            "mpc_problem_generator.cc",
+        ],
+    hdrs =
+        [
+            "mpc_problem_generator.h",
+        ],
+    visibility = ["//visibility:public"],
+    deps =
+        [
+            ":mpc_problem",
+            "//frc971/control_loops:state_feedback_loop",
+        ],
+)
+
+cc_library(
+    name = "catapult",
+    srcs = [
+        "catapult.cc",
+    ],
+    hdrs =
+        [
+            "catapult.h",
+        ],
+    visibility = ["//visibility:public"],
+    deps = [
+        ":catapult_controller",
+        "//frc971/control_loops:static_zeroing_single_dof_profiled_subsystem",
+        "//frc971/control_loops/catapult:catapult_goal_fbs",
+        "//frc971/zeroing:pot_and_absolute_encoder",
+    ],
+)
diff --git a/frc971/control_loops/catapult/catapult.cc b/frc971/control_loops/catapult/catapult.cc
new file mode 100644
index 0000000..2e1867c
--- /dev/null
+++ b/frc971/control_loops/catapult/catapult.cc
@@ -0,0 +1,138 @@
+#include "frc971/control_loops/catapult/catapult.h"
+
+namespace frc971::control_loops::catapult {
+
+const flatbuffers::Offset<
+    frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
+Catapult::Iterate(const CatapultGoal *catapult_goal,
+                  const PotAndAbsolutePosition *position,
+                  double battery_voltage, double *catapult_voltage, bool fire,
+                  flatbuffers::FlatBufferBuilder *fbb) {
+  const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
+      *return_goal =
+          catapult_goal != nullptr && catapult_goal->has_return_position()
+              ? catapult_goal->return_position()
+              : nullptr;
+
+  const bool catapult_disabled =
+      catapult_.Correct(return_goal, position, catapult_voltage == nullptr);
+
+  if (catapult_disabled) {
+    catapult_state_ = CatapultState::PROFILE;
+  } else if (catapult_.running() && catapult_goal != nullptr && fire &&
+             !last_firing_) {
+    catapult_state_ = CatapultState::FIRING;
+    latched_shot_position = catapult_goal->shot_position();
+    latched_shot_velocity = catapult_goal->shot_velocity();
+  }
+
+  // Don't update last_firing_ if the catapult is disabled, so that we actually
+  // end up firing once it's enabled
+  if (catapult_.running() && !catapult_disabled) {
+    last_firing_ = fire;
+  }
+
+  use_profile_ = true;
+
+  switch (catapult_state_) {
+    case CatapultState::FIRING: {
+      // Select the ball controller.  We should only be firing if we have a
+      // ball, or at least should only care about the shot accuracy.
+      catapult_.set_controller_index(0);
+      // Ok, so we've now corrected.  Next step is to run the MPC.
+      //
+      // Since there is a unit delay between when we ask for a U and the
+      // hardware applies it, we need to run the optimizer for the position at
+      // the *next* control loop cycle.
+
+      Eigen::Vector3d next_X = catapult_.estimated_state();
+      for (int i = catapult_.controller().plant().coefficients().delayed_u;
+           i > 1; --i) {
+        next_X = catapult_.controller().plant().A() * next_X +
+                 catapult_.controller().plant().B() *
+                     catapult_.controller().observer().last_U(i - 1);
+      }
+
+      catapult_mpc_.SetState(
+          next_X.block<2, 1>(0, 0),
+          Eigen::Vector2d(latched_shot_position, latched_shot_velocity));
+
+      const bool solved = catapult_mpc_.Solve();
+      current_horizon_ = catapult_mpc_.current_horizon();
+      const bool started = catapult_mpc_.started();
+      if (solved || started) {
+        std::optional<double> solution = catapult_mpc_.Next();
+
+        if (!solution.has_value()) {
+          CHECK_NOTNULL(catapult_voltage);
+          *catapult_voltage = 0.0;
+          if (catapult_mpc_.started()) {
+            ++shot_count_;
+            // Finished the catapult, time to fire.
+            catapult_state_ = CatapultState::RESETTING;
+          }
+        } else {
+          // TODO(austin): Voltage error?
+          CHECK_NOTNULL(catapult_voltage);
+          if (current_horizon_ == 1) {
+            battery_voltage = 12.0;
+          }
+          *catapult_voltage = std::max(
+              0.0, std::min(12.0, (*solution - 0.0 * next_X(2, 0)) * 12.0 /
+                                      std::max(battery_voltage, 8.0)));
+          use_profile_ = false;
+        }
+      } else {
+        if (!fire) {
+          // Eh, didn't manage to solve before it was time to fire.  Give up.
+          catapult_state_ = CatapultState::PROFILE;
+        }
+      }
+
+      if (!use_profile_) {
+        catapult_.ForceGoal(catapult_.estimated_position(),
+                            catapult_.estimated_velocity());
+      }
+    }
+      if (catapult_state_ != CatapultState::RESETTING) {
+        break;
+      } else {
+        [[fallthrough]];
+      }
+
+    case CatapultState::RESETTING:
+      if (catapult_.controller().R(1, 0) > 7.0) {
+        catapult_.AdjustProfile(7.0, 2000.0);
+      } else if (catapult_.controller().R(1, 0) > 0.0) {
+        catapult_.AdjustProfile(7.0, 1000.0);
+      } else {
+        catapult_state_ = CatapultState::PROFILE;
+      }
+      [[fallthrough]];
+
+    case CatapultState::PROFILE:
+      break;
+  }
+
+  if (use_profile_) {
+    if (catapult_state_ != CatapultState::FIRING) {
+      catapult_mpc_.Reset();
+    }
+    // Select the controller designed for when we have no ball.
+    catapult_.set_controller_index(1);
+
+    current_horizon_ = 0u;
+    const double output_voltage = catapult_.UpdateController(catapult_disabled);
+    if (catapult_voltage != nullptr) {
+      *catapult_voltage = output_voltage;
+    }
+  }
+
+  catapult_.UpdateObserver(catapult_voltage != nullptr
+                               ? (*catapult_voltage * battery_voltage / 12.0)
+                               : 0.0);
+
+  return catapult_.MakeStatus(fbb);
+}
+
+}  // namespace frc971::control_loops::catapult
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/catapult.h b/frc971/control_loops/catapult/catapult.h
new file mode 100644
index 0000000..e84ea88
--- /dev/null
+++ b/frc971/control_loops/catapult/catapult.h
@@ -0,0 +1,79 @@
+#ifndef FRC971_CONTROL_LOOPS_CATAPULT_CATAPULT_H_
+#define FRC971_CONTROL_LOOPS_CATAPULT_CATAPULT_H_
+
+#include "frc971/control_loops/catapult/catapult_controller.h"
+#include "frc971/control_loops/catapult/catapult_goal_generated.h"
+#include "frc971/control_loops/static_zeroing_single_dof_profiled_subsystem.h"
+#include "frc971/zeroing/pot_and_absolute_encoder.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace catapult {
+
+// Class to handle transitioning between both the profiled subsystem and the MPC
+// for shooting.
+class Catapult {
+ public:
+  Catapult(frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemParams<
+               zeroing::PotAndAbsoluteEncoderZeroingEstimator>
+               catapult_params,
+           StateFeedbackPlant<2, 1, 1> plant)
+      : catapult_(catapult_params), catapult_mpc_(std::move(plant), 30) {}
+
+  using PotAndAbsoluteEncoderSubsystem =
+      ::frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystem<
+          ::frc971::zeroing::PotAndAbsoluteEncoderZeroingEstimator,
+          ::frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>;
+
+  // Resets all state for when WPILib restarts.
+  void Reset() { catapult_.Reset(); }
+
+  void Estop() { catapult_.Estop(); }
+
+  bool zeroed() const { return catapult_.zeroed(); }
+  bool estopped() const { return catapult_.estopped(); }
+  double solve_time() const { return catapult_mpc_.solve_time(); }
+
+  uint8_t mpc_horizon() const { return current_horizon_; }
+
+  bool mpc_active() const { return !use_profile_; }
+
+  // Returns the number of shots taken.
+  int shot_count() const { return shot_count_; }
+
+  // Returns the estimated position
+  double estimated_position() const { return catapult_.estimated_position(); }
+
+  // Runs either the MPC or the profiled subsystem depending on if we are
+  // shooting or not.  Returns the status.
+  const flatbuffers::Offset<
+      frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus>
+  Iterate(const CatapultGoal *catapult_goal,
+          const PotAndAbsolutePosition *position, double battery_voltage,
+          double *catapult_voltage, bool fire,
+          flatbuffers::FlatBufferBuilder *fbb);
+
+ private:
+  PotAndAbsoluteEncoderSubsystem catapult_;
+
+  frc971::control_loops::catapult::CatapultController catapult_mpc_;
+
+  enum CatapultState { PROFILE, FIRING, RESETTING };
+
+  CatapultState catapult_state_ = CatapultState::PROFILE;
+
+  double latched_shot_position = 0.0;
+  double latched_shot_velocity = 0.0;
+
+  bool last_firing_ = false;
+  bool use_profile_ = true;
+
+  int shot_count_ = 0;
+  uint8_t current_horizon_ = 0u;
+};
+
+}  // namespace catapult
+}  // namespace control_loops
+}  // namespace frc971
+
+#endif  // Y2022_CONTROL_LOOPS_SUPERSTRUCTURE_CATAPULT_CATAPULT_H_
diff --git a/frc971/control_loops/catapult/catapult_controller.cc b/frc971/control_loops/catapult/catapult_controller.cc
new file mode 100644
index 0000000..a4187f7
--- /dev/null
+++ b/frc971/control_loops/catapult/catapult_controller.cc
@@ -0,0 +1,62 @@
+#include "frc971/control_loops/catapult/catapult_controller.h"
+
+namespace frc971::control_loops::catapult {
+
+CatapultController::CatapultController(StateFeedbackPlant<2, 1, 1> plant,
+                                       size_t horizon)
+    : generator_(std::move(plant), horizon) {
+  problems_.reserve(generator_.horizon());
+  for (size_t i = generator_.horizon(); i > 0; --i) {
+    problems_.emplace_back(generator_.MakeProblem(i));
+  }
+
+  Reset();
+}
+
+void CatapultController::Reset() {
+  current_controller_ = 0;
+  solve_time_ = 0.0;
+}
+
+void CatapultController::SetState(Eigen::Matrix<double, 2, 1> X_initial,
+                                  Eigen::Matrix<double, 2, 1> X_final) {
+  if (current_controller_ >= problems_.size()) {
+    return;
+  }
+  problems_[current_controller_]->SetState(X_initial, X_final);
+}
+
+bool CatapultController::Solve() {
+  if (current_controller_ >= problems_.size()) {
+    return true;
+  }
+  const bool result = problems_[current_controller_]->Solve();
+  solve_time_ = problems_[current_controller_]->solve_time();
+  return result;
+}
+
+std::optional<double> CatapultController::Next() {
+  if (current_controller_ >= problems_.size()) {
+    return std::nullopt;
+  }
+
+  double u;
+  size_t solution_number = 0;
+  if (current_controller_ == 0u) {
+    while (solution_number < problems_[current_controller_]->horizon() &&
+           problems_[current_controller_]->U(solution_number) < 0.01) {
+      u = problems_[current_controller_]->U(solution_number);
+      ++solution_number;
+    }
+  }
+  u = problems_[current_controller_]->U(solution_number);
+
+  if (current_controller_ + 1u + solution_number < problems_.size()) {
+    problems_[current_controller_ + solution_number + 1]->WarmStart(
+        *problems_[current_controller_]);
+  }
+  current_controller_ += 1u + solution_number;
+  return u;
+}
+
+}  // namespace frc971::control_loops::catapult
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/catapult_controller.h b/frc971/control_loops/catapult/catapult_controller.h
new file mode 100644
index 0000000..3a666f9
--- /dev/null
+++ b/frc971/control_loops/catapult/catapult_controller.h
@@ -0,0 +1,65 @@
+#include "frc971/control_loops/catapult/mpc_problem_generator.h"
+// A class to hold all the state needed to manage the catapult MPC solvers for
+// repeated shots.
+//
+// The solver may take a couple of cycles to get everything converged and ready.
+// The flow is as follows:
+//  1) Reset() the state for the new problem.
+//  2) Update to the current state with SetState()
+//  3) Call Solve().  This will return true if it is ready to be executed, false
+//     if it needs more iterations to fully converge.
+//  4) Next() returns the current optimal control output and advances the
+//     pointers to the next problem.
+//  5) Go back to 2 for the next cycle.
+
+namespace frc971 {
+namespace control_loops {
+namespace catapult {
+
+class CatapultController {
+ public:
+  CatapultController(StateFeedbackPlant<2, 1, 1> plant, size_t horizon);
+
+  // Starts back over at the first controller.
+  void Reset();
+
+  // Updates our current and final states for the current controller.
+  void SetState(Eigen::Matrix<double, 2, 1> X_initial,
+                Eigen::Matrix<double, 2, 1> X_final);
+
+  // Solves!  Returns true if the solution converged and osqp was happy.
+  bool Solve();
+
+  // Returns the time in seconds it last took Solve to run.
+  double solve_time() const { return solve_time_; }
+
+  // Returns the horizon of the current controller.
+  size_t current_horizon() const {
+    if (current_controller_ >= problems_.size()) {
+      return 0u;
+    } else {
+      return problems_[current_controller_]->horizon();
+    }
+  }
+
+  // Returns the controller value if there is a controller to run, or nullopt if
+  // we finished the last controller.  Advances the controller pointer to the
+  // next controller and warms up the next controller.
+  std::optional<double> Next();
+
+  // Returns true if Next has been called and a controller has been used.  Reset
+  // starts over.
+  bool started() const { return current_controller_ != 0u; }
+
+ private:
+  CatapultProblemGenerator generator_;
+
+  std::vector<std::unique_ptr<MPCProblem>> problems_;
+
+  size_t current_controller_ = 0;
+  double solve_time_ = 0.0;
+};
+
+}  // namespace catapult
+}  // namespace control_loops
+}  // namespace frc971
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/catapult_goal.fbs b/frc971/control_loops/catapult/catapult_goal.fbs
new file mode 100644
index 0000000..3e59455
--- /dev/null
+++ b/frc971/control_loops/catapult/catapult_goal.fbs
@@ -0,0 +1,17 @@
+include "frc971/control_loops/profiled_subsystem.fbs";
+
+namespace frc971.control_loops.catapult;
+
+table CatapultGoal {
+  // Old fire flag, only kept for backwards-compatability with logs.
+  // Use the fire flag in the root Goal instead
+  fire:bool (id: 0, deprecated);
+
+  // The target shot position and velocity.  If these are provided before fire
+  // is called, the optimizer can pre-compute the trajectory.
+  shot_position:double (id: 1);
+  shot_velocity:double (id: 2);
+
+  // The target position to return the catapult to when not shooting.
+  return_position:frc971.control_loops.StaticZeroingSingleDOFProfiledSubsystemGoal (id: 3);
+}
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/mpc.tex b/frc971/control_loops/catapult/mpc.tex
new file mode 100644
index 0000000..b7110fe
--- /dev/null
+++ b/frc971/control_loops/catapult/mpc.tex
@@ -0,0 +1,202 @@
+\documentclass[a4paper,12pt]{article}
+\usepackage{amsmath}
+\usepackage{graphicx}
+\begin{document}
+
+TODO(austin): Now that the python matches the original problem and solves, confirm the paper matches what got implemented.
+
+osqp!
+
+\section{Catapult MPC}
+We want to phrase our problem as trying to solve for the set of control inputs
+which get us closest to the destination, but minimizes acceleration.
+Specifically, we want to minimize acceleration close to the end.
+We also have a voltage limit.
+
+Our model is
+
+\begin{equation}
+\label{cost}
+  \begin{bmatrix} x_1 \\ v_1 \end{bmatrix} =
+    \begin{bmatrix} a_{00} & a_{01} \\ 0 & a_{11} \end{bmatrix}
+      \begin{bmatrix} x_0 \\ v_0 \end{bmatrix} + 
+    \begin{bmatrix} b_{0} \\ b_{1} \end{bmatrix} \begin{bmatrix} u_0 \end{bmatrix}
+\end{equation}
+
+Our acceleration can be measured as:
+
+\begin{equation}
+\label{accel}
+  \frac{ \left( \boldsymbol{X_1(1)} - \boldsymbol{X_1(0)} \right)}{\Delta t}
+\end{equation}
+
+This simplifies to:
+
+\begin{equation}
+  \frac{a_{11} v_0 + b_1 u_0 - v_0}{\Delta t}
+\end{equation}
+
+and finally
+
+\begin{equation}
+  \frac{(a_{11} - 1) v_0 + b_1 u_0}{\Delta t}
+\end{equation}
+
+
+We can also compute our state matrix as a function of inital state and the control inputs.
+
+\begin{equation}
+\label{all_x}
+  \begin{bmatrix} X_1 \\ X_2 \\ X_3 \\ \vdots \end{bmatrix} = 
+  \begin{bmatrix} A  \\
+                  A^2  \\
+                  A^3  \\
+                  \vdots \end{bmatrix} 
+   X_0 + 
+  \begin{bmatrix} B & 0 & 0 & 0 \\
+                  A B & B & 0 & 0 \\
+                  A^2 B & A B & B & 0 \\
+                  \vdots  & \ddots & & \hdots \end{bmatrix} 
+  \begin{bmatrix} U_0 \\ U_1 \\ U_2 \\ \vdots \end{bmatrix}
+\end{equation}
+
+\section{MPC problem formulation}
+
+We want to penalize both final state and intermediate acceleration.  
+
+\begin{equation}
+C = \sum_{n=0}^{39} \frac{\left(v(n + 1) - v(n)\right)^2}{\Delta t} \pi_n + (X_{40} - X_{final})^T Q_{final} (X_{40} - X_{final})
+\end{equation}
+
+where $\pi_n$ is a constant only dependent on $n$, and designed such that it depends on the distance to the end of the sequence, not the distance from the start.
+
+In order to use OSQP, which has a code generator, we need to get this into the form of
+
+\begin{tabular}{ l l }
+minimize &      $ \frac{1}{2} X^T P X + q^T X $ \\
+subject to &    $ l <= A X <= u $ \\
+\end{tabular}
+
+This is the simplest form of a constrained quadratic program that we can solve efficiently.
+Luckily for us, the problem statement above fits that definition.
+
+\section{Manipulating the formulation}
+
+We need to separate constant factors from things dependent on U (or X in OSQP parlance) so we can create these matrices easier.
+
+\subsection{Terminal cost}
+
+Next step is to compute $X_{40}$ using equation \ref{all_x}.
+We can do this by only computing the final row of the matrix.
+
+\begin{equation}
+\label{x40}
+  X_{40} = \begin{bmatrix} A^{39} B & A^{38} B & \hdots & B \end{bmatrix}
+           \begin{bmatrix} U_0 \\
+                           \vdots \\
+                           U_{39}
+           \end{bmatrix} + A^{40} X_0 = B_f \boldsymbol{U} + A^{40} X_0
+\end{equation}
+
+We can substitute equation \ref{x40} into equation \ref{cost}.
+
+\begin{equation}
+\label{final_cost}
+\begin{aligned}[t]
+  C_f = & \boldsymbol{U}^T B_f^T Q_{final} B_f \boldsymbol{U} \\
+        & + 2 (A^{40} X_0 - X_{final})^T Q_{final} B_f \boldsymbol{U} \\
+        & + (A^{40} X_0 - X_{final})^T Q_{final} (A^{40} X_0 - X_{final})
+\end{aligned}
+\end{equation}
+
+\subsection{Acceleration costs}
+
+We can compute a velocity matrix for all the times by stripping out the positions from equation \ref{all_x} by using every other row.
+We can use this to then compute the accelerations for each time slice and then penalize them.
+
+\begin{equation}
+  \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_{40} \end{bmatrix} =
+     M \boldsymbol{U} + \begin{bmatrix} a_{11} \\ a^2_{11} \\ \vdots \\ a^{40}_{11} \end{bmatrix} v_0 =
+     M \boldsymbol{U} + m v_0
+\end{equation}
+
+We can then use equation \ref{accel} in matrix form to convert a velocity matrix to an acceleration matrix.
+
+\begin{equation}
+  \begin{bmatrix} \alpha_1 \\ \alpha_2 \\ \alpha_3 \\ \vdots \\ \alpha_{40} \end{bmatrix} =
+    \frac{1}{\Delta t} \left(
+    \begin{bmatrix} 1 & 0 & 0 & \hdots & 0 \\
+                    -1 & 1 & 0 & \hdots & 0 \\
+                    0 & -1 & 1 & \hdots & 0 \\
+                    \vdots & & & \ddots  & \vdots \\
+                    0 & 0 & \hdots & -1 & 1 \\
+  \end{bmatrix}
+  \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_{40} \end{bmatrix} - \begin{bmatrix} v_0 \\ 0 \\ \vdots \\ 0 \end{bmatrix}
+\right)
+\end{equation}
+
+We can pull some of these terms out to make it easier to work with.
+
+\begin{equation}
+\boldsymbol{\alpha} = W V + w v_0
+\end{equation}
+
+Our acceleration cost function is then:
+
+\begin{equation}
+C_a = \boldsymbol{\alpha}^T
+        \begin{bmatrix} \pi_1 &  & 0 \\
+                        & \pi_2 &   \\
+                        0 & & \ddots \end{bmatrix} \boldsymbol{\alpha} = 
+ \boldsymbol{\alpha}^T \Pi \boldsymbol{\alpha}
+\end{equation}
+
+We can substitute everything in to get something as a function of $U$.
+
+\begin{equation}
+C_a = \left(W \left(M \boldsymbol{U} + m v_0 \right) + w v_0 \right)^T \Pi \left(W \left(M \boldsymbol{U} + m v_0 \right) + w v_0 \right)
+\end{equation}
+
+And then simplify this down into the expected form.
+
+\begin{equation}
+  C_a = \left(W M \boldsymbol{U} + (W m + w) v_0 \right)^T \Pi \left(W M \boldsymbol{U} + (W m + w) v_0  \right)
+\end{equation}
+
+\begin{equation}
+\label{accel_cost}
+\begin{aligned}[t]
+C_a = & \boldsymbol{U}^T M^T W^T \Pi W M \boldsymbol{U} \\
+  & + 2 v_0 (W m + w)^T \Pi W M \boldsymbol{U} \\
+& +  v_0 (W m + w)^T  \Pi \left(W m + w \right) v_0
+\end{aligned}
+\end{equation}
+
+\subsection{Overall cost}
+
+We can combine equations \ref{final_cost} and \ref{accel_cost} to get our overall cost in the correct form.
+
+\begin{equation}
+\begin{aligned}[t]
+C &= \boldsymbol{U}^T \left( M^T W^T \Pi W M + B_f^T Q_{final} B_f \right) \boldsymbol{U}  \\
+ &+ \left(2 v_0 (W m + w)^T \Pi W M
+   - 2 X_{final}^T Q_{final} B_f
+\right) \boldsymbol{U} \\
+& + X_{final}^T Q_{final} X_{final}
+  +  v_0 (W m + w)^T  \Pi \left(W m + w \right) v_0
+\end{aligned}
+\end{equation}
+
+
+\section{Response}
+
+For a reasonable request (11 m/s after 90 degrees), we get the following response
+
+\begin{figure}
+    \centering
+    \includegraphics[width=\linewidth]{response.png}
+\end{figure}
+
+This is well within 1\% error, and avoid saturation and keeps the acceleration down at the end.
+
+\end{document}
diff --git a/frc971/control_loops/catapult/mpc_problem.cc b/frc971/control_loops/catapult/mpc_problem.cc
new file mode 100644
index 0000000..23859cd
--- /dev/null
+++ b/frc971/control_loops/catapult/mpc_problem.cc
@@ -0,0 +1,95 @@
+#include "frc971/control_loops/catapult/mpc_problem.h"
+
+namespace frc971::control_loops::catapult {
+namespace chrono = std::chrono;
+
+namespace {
+osqp::OsqpInstance MakeInstance(
+    size_t horizon, Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P) {
+  osqp::OsqpInstance instance;
+  instance.objective_matrix = P.sparseView();
+
+  instance.constraint_matrix =
+      Eigen::SparseMatrix<double, Eigen::ColMajor, osqp::c_int>(horizon,
+                                                                horizon);
+  instance.constraint_matrix.setIdentity();
+
+  instance.lower_bounds =
+      Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon, 1);
+  instance.upper_bounds =
+      Eigen::Matrix<double, Eigen::Dynamic, 1>::Ones(horizon, 1) * 12.0;
+  return instance;
+}
+
+}  // namespace
+MPCProblem::MPCProblem(size_t horizon,
+                       Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P,
+                       Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q,
+                       Eigen::Matrix<double, 2, 2> Af,
+                       Eigen::Matrix<double, Eigen::Dynamic, 2> final_q)
+    : horizon_(horizon),
+      accel_q_(std::move(accel_q)),
+      Af_(std::move(Af)),
+      final_q_(std::move(final_q)),
+      instance_(MakeInstance(horizon, std::move(P))) {
+  // Start with a representative problem.
+  Eigen::Matrix<double, 2, 1> X_initial(0.0, 0.0);
+  Eigen::Matrix<double, 2, 1> X_final(2.0, 25.0);
+
+  objective_vector_ =
+      X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
+  instance_.objective_vector = objective_vector_;
+  settings_.max_iter = 25;
+  settings_.check_termination = 5;
+  settings_.warm_start = 1;
+  // TODO(austin): Do we need this scaling thing?  It makes it not solve
+  // sometimes... I'm pretty certain by giving it a decently formed problem to
+  // initialize with, it will not try doing crazy things with the scaling
+  // internally.
+  settings_.scaling = 0;
+  auto status = solver_.Init(instance_, settings_);
+  CHECK(status.ok()) << status;
+}
+
+void MPCProblem::SetState(Eigen::Matrix<double, 2, 1> X_initial,
+                          Eigen::Matrix<double, 2, 1> X_final) {
+  X_initial_ = X_initial;
+  X_final_ = X_final;
+  // If we mark this noalias(), it won't re-allocate the vector each time.
+  objective_vector_.noalias() =
+      X_initial(1, 0) * accel_q_ + final_q_ * (Af_ * X_initial - X_final);
+
+  auto status = solver_.SetObjectiveVector(objective_vector_);
+  CHECK(status.ok()) << status;
+}
+
+bool MPCProblem::Solve() {
+  const aos::monotonic_clock::time_point start_time =
+      aos::monotonic_clock::now();
+  osqp::OsqpExitCode exit_code = solver_.Solve();
+  const aos::monotonic_clock::time_point end_time = aos::monotonic_clock::now();
+  VLOG(1) << "OSQP solved in "
+          << std::chrono::duration<double>(end_time - start_time).count();
+  solve_time_ = std::chrono::duration<double>(end_time - start_time).count();
+  // TODO(austin): Dump the exit codes out as an enum for logging.
+  //
+  // TODO(austin): The dual problem doesn't appear to be converging on all
+  // problems.  Are we phrasing something wrong?
+
+  // TODO(austin): Set a time limit so we can't run forever, and signal back
+  // when we hit our limit.
+  return exit_code == osqp::OsqpExitCode::kOptimal;
+}
+
+void MPCProblem::WarmStart(const MPCProblem &p) {
+  CHECK_GE(p.horizon(), horizon())
+      << ": Can only copy a bigger problem's solution into a smaller problem.";
+  auto status = solver_.SetPrimalWarmStart(p.solver_.primal_solution().block(
+      p.horizon() - horizon(), 0, horizon(), 1));
+  CHECK(status.ok()) << status;
+  status = solver_.SetDualWarmStart(p.solver_.dual_solution().block(
+      p.horizon() - horizon(), 0, horizon(), 1));
+  CHECK(status.ok()) << status;
+}
+
+}  // namespace frc971::control_loops::catapult
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/mpc_problem.h b/frc971/control_loops/catapult/mpc_problem.h
new file mode 100644
index 0000000..04e3936
--- /dev/null
+++ b/frc971/control_loops/catapult/mpc_problem.h
@@ -0,0 +1,72 @@
+#include "Eigen/Dense"
+#include "Eigen/Sparse"
+#include "glog/logging.h"
+
+#include "aos/realtime.h"
+#include "aos/time/time.h"
+#include "osqp++.h"
+#include "osqp.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace catapult {
+
+// MPC problem for a specified horizon.  This contains all the state for the
+// solver, setters to modify the current and target state, and a way to fetch
+// the solution.
+class MPCProblem {
+ public:
+  MPCProblem(size_t horizon,
+             Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P,
+             Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q,
+             Eigen::Matrix<double, 2, 2> Af,
+             Eigen::Matrix<double, Eigen::Dynamic, 2> final_q);
+
+  MPCProblem(MPCProblem const &) = delete;
+  void operator=(MPCProblem const &x) = delete;
+
+  // Sets the current and final state.  This keeps the problem in tact and
+  // doesn't recreate it, so it will be fast.
+  void SetState(Eigen::Matrix<double, 2, 1> X_initial,
+                Eigen::Matrix<double, 2, 1> X_final);
+
+  // Solves our problem.
+  bool Solve();
+
+  double solve_time() const { return solve_time_; }
+
+  // Returns the solution that the solver found when Solve was last called.
+  double U(size_t i) const { return solver_.primal_solution()(i); }
+
+  // Returns the number of U's to be solved.
+  size_t horizon() const { return horizon_; }
+
+  // Warm starts the optimizer with the provided solution to make it solve
+  // faster.
+  void WarmStart(const MPCProblem &p);
+
+ private:
+  // The number of u's to solve for.
+  const size_t horizon_;
+
+  // The problem statement variables needed by SetState to update q.
+  const Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q_;
+  const Eigen::Matrix<double, 2, 2> Af_;
+  const Eigen::Matrix<double, Eigen::Dynamic, 2> final_q_;
+
+  Eigen::Matrix<double, 2, 1> X_initial_;
+  Eigen::Matrix<double, 2, 1> X_final_;
+
+  Eigen::Matrix<double, Eigen::Dynamic, 1> objective_vector_;
+
+  // Solver state.
+  osqp::OsqpInstance instance_;
+  osqp::OsqpSolver solver_;
+  osqp::OsqpSettings settings_;
+
+  double solve_time_ = 0;
+};
+
+}  // namespace catapult
+}  // namespace control_loops
+}  // namespace frc971
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/mpc_problem_generator.cc b/frc971/control_loops/catapult/mpc_problem_generator.cc
new file mode 100644
index 0000000..3b36318
--- /dev/null
+++ b/frc971/control_loops/catapult/mpc_problem_generator.cc
@@ -0,0 +1,168 @@
+#include "frc971/control_loops/catapult/mpc_problem_generator.h"
+
+namespace frc971::control_loops::catapult {
+namespace chrono = std::chrono;
+
+CatapultProblemGenerator::CatapultProblemGenerator(
+    StateFeedbackPlant<2, 1, 1> plant, size_t horizon)
+    : plant_(std::move(plant)),
+      horizon_(horizon),
+      Q_final_(
+          (Eigen::DiagonalMatrix<double, 2>().diagonal() << 10000.0, 10000.0)
+              .finished()),
+      As_(MakeAs()),
+      Bs_(MakeBs()),
+      m_(Makem()),
+      M_(MakeM()),
+      W_(MakeW()),
+      w_(Makew()),
+      Pi_(MakePi()),
+      WM_(W_ * M_),
+      Wmpw_(W_ * m_ + w_) {}
+
+std::unique_ptr<MPCProblem> CatapultProblemGenerator::MakeProblem(
+    size_t horizon) {
+  return std::make_unique<MPCProblem>(
+      horizon, P(horizon), accel_q(horizon), Af(horizon),
+      (2.0 * Q_final_ * Bf(horizon)).transpose());
+}
+
+const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::P(size_t horizon) {
+  CHECK_GT(horizon, 0u);
+  CHECK_LE(horizon, horizon_);
+  return 2.0 * (WM_.block(0, 0, horizon, horizon).transpose() * Pi(horizon) *
+                    WM_.block(0, 0, horizon, horizon) +
+                Bf(horizon).transpose() * Q_final_ * Bf(horizon));
+}
+
+const Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::q(
+    size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
+    Eigen::Matrix<double, 2, 1> X_final) {
+  CHECK_GT(horizon, 0u);
+  CHECK_LE(horizon, horizon_);
+  return 2.0 * X_initial(1, 0) * accel_q(horizon) +
+         2.0 * ((Af(horizon) * X_initial - X_final).transpose() * Q_final_ *
+                Bf(horizon))
+                   .transpose();
+}
+
+const Eigen::Matrix<double, Eigen::Dynamic, 1>
+CatapultProblemGenerator::accel_q(size_t horizon) {
+  return 2.0 * ((Wmpw_.block(0, 0, horizon, 1)).transpose() * Pi(horizon) *
+                WM_.block(0, 0, horizon, horizon))
+                   .transpose();
+}
+
+const Eigen::Matrix<double, 2, 2> CatapultProblemGenerator::Af(size_t horizon) {
+  CHECK_GT(horizon, 0u);
+  CHECK_LE(horizon, horizon_);
+  return As_.block<2, 2>(2 * (horizon - 1), 0);
+}
+
+const Eigen::Matrix<double, 2, Eigen::Dynamic> CatapultProblemGenerator::Bf(
+    size_t horizon) {
+  CHECK_GT(horizon, 0u);
+  CHECK_LE(horizon, horizon_);
+  return Bs_.block(2 * (horizon - 1), 0, 2, horizon);
+}
+
+const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::Pi(size_t horizon) {
+  CHECK_GT(horizon, 0u);
+  CHECK_LE(horizon, horizon_);
+  return Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(Pi_).block(
+      horizon_ - horizon, horizon_ - horizon, horizon, horizon);
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, 2> CatapultProblemGenerator::MakeAs() {
+  Eigen::Matrix<double, Eigen::Dynamic, 2> As =
+      Eigen::Matrix<double, Eigen::Dynamic, 2>::Zero(horizon_ * 2, 2);
+  for (size_t i = 0; i < horizon_; ++i) {
+    if (i == 0) {
+      As.block<2, 2>(0, 0) = plant_.A();
+    } else {
+      As.block<2, 2>(i * 2, 0) = plant_.A() * As.block<2, 2>((i - 1) * 2, 0);
+    }
+  }
+  return As;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::MakeBs() {
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs =
+      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_ * 2,
+                                                                  horizon_);
+  for (size_t i = 0; i < horizon_; ++i) {
+    for (size_t j = 0; j < i + 1; ++j) {
+      if (i == j) {
+        Bs.block<2, 1>(i * 2, j) = plant_.B();
+      } else {
+        Bs.block<2, 1>(i * 2, j) =
+            As_.block<2, 2>((i - j - 1) * 2, 0) * plant_.B();
+      }
+    }
+  }
+  return Bs;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makem() {
+  Eigen::Matrix<double, Eigen::Dynamic, 1> m =
+      Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
+  for (size_t i = 0; i < horizon_; ++i) {
+    m(i, 0) = As_(1 + 2 * i, 1);
+  }
+  return m;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::MakeM() {
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M =
+      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Zero(horizon_,
+                                                                  horizon_);
+  for (size_t i = 0; i < horizon_; ++i) {
+    for (size_t j = 0; j < horizon_; ++j) {
+      M(i, j) = Bs_(2 * i + 1, j);
+    }
+  }
+  return M;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::MakeW() {
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W =
+      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(horizon_,
+                                                                      horizon_);
+  for (size_t i = 0; i < horizon_ - 1; ++i) {
+    W(i + 1, i) = -1.0;
+  }
+  W /= std::chrono::duration<double>(plant_.dt()).count();
+  return W;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, 1> CatapultProblemGenerator::Makew() {
+  Eigen::Matrix<double, Eigen::Dynamic, 1> w =
+      Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(horizon_, 1);
+  w(0, 0) = -1.0 / std::chrono::duration<double>(plant_.dt()).count();
+  return w;
+}
+
+Eigen::DiagonalMatrix<double, Eigen::Dynamic>
+CatapultProblemGenerator::MakePi() {
+  Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi(horizon_);
+  for (size_t i = 0; i < horizon_; ++i) {
+    Pi.diagonal()(i) =
+        std::pow(0.01, 2.0) +
+        std::pow(0.02 * std::max(0.0, (20 - ((int)horizon_ - (int)i)) / 20.),
+                 2.0);
+  }
+  return Pi;
+}
+
+Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
+CatapultProblemGenerator::MakeP() {
+  return 2.0 * (M_.transpose() * W_.transpose() * Pi_ * W_ * M_ +
+                Bf(horizon_).transpose() * Q_final_ * Bf(horizon_));
+}
+
+}  // namespace frc971::control_loops::catapult
\ No newline at end of file
diff --git a/frc971/control_loops/catapult/mpc_problem_generator.h b/frc971/control_loops/catapult/mpc_problem_generator.h
new file mode 100644
index 0000000..2fbaf66
--- /dev/null
+++ b/frc971/control_loops/catapult/mpc_problem_generator.h
@@ -0,0 +1,69 @@
+#include "frc971/control_loops/catapult/mpc_problem.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace catapult {
+
+// Decently efficient problem generator for multiple horizons given a max
+// horizon to solve for.
+//
+// The math is documented in mpc.tex
+class CatapultProblemGenerator {
+ public:
+  // Builds a problem generator for the specified max horizon and caches a lot
+  // of the state.
+  CatapultProblemGenerator(StateFeedbackPlant<2, 1, 1> plant, size_t horizon);
+
+  // Returns the maximum horizon.
+  size_t horizon() const { return horizon_; }
+
+  // Makes a problem for the specificed horizon.
+  std::unique_ptr<MPCProblem> MakeProblem(size_t horizon);
+
+  // Returns the P and Q matrices for the problem statement.
+  //   cost = 0.5 X.T P X + q.T X
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> P(size_t horizon);
+  const Eigen::Matrix<double, Eigen::Dynamic, 1> q(
+      size_t horizon, Eigen::Matrix<double, 2, 1> X_initial,
+      Eigen::Matrix<double, 2, 1> X_final);
+
+ private:
+  const Eigen::Matrix<double, Eigen::Dynamic, 1> accel_q(size_t horizon);
+
+  const Eigen::Matrix<double, 2, 2> Af(size_t horizon);
+  const Eigen::Matrix<double, 2, Eigen::Dynamic> Bf(size_t horizon);
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Pi(
+      size_t horizon);
+
+  // These functions are used in the constructor to build up the matrices below.
+  Eigen::Matrix<double, Eigen::Dynamic, 2> MakeAs();
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MakeBs();
+  Eigen::Matrix<double, Eigen::Dynamic, 1> Makem();
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MakeM();
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MakeW();
+  Eigen::Matrix<double, Eigen::Dynamic, 1> Makew();
+  Eigen::DiagonalMatrix<double, Eigen::Dynamic> MakePi();
+  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MakeP();
+
+  const StateFeedbackPlant<2, 1, 1> plant_;
+  const size_t horizon_;
+
+  const Eigen::DiagonalMatrix<double, 2> Q_final_;
+
+  const Eigen::Matrix<double, Eigen::Dynamic, 2> As_;
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Bs_;
+  const Eigen::Matrix<double, Eigen::Dynamic, 1> m_;
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> M_;
+
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> W_;
+  const Eigen::Matrix<double, Eigen::Dynamic, 1> w_;
+  const Eigen::DiagonalMatrix<double, Eigen::Dynamic> Pi_;
+
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> WM_;
+  const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Wmpw_;
+};
+
+}  // namespace catapult
+}  // namespace control_loops
+}  // namespace frc971
\ No newline at end of file
diff --git a/frc971/control_loops/state_feedback_loop.h b/frc971/control_loops/state_feedback_loop.h
index 3c90434..988aaa9 100644
--- a/frc971/control_loops/state_feedback_loop.h
+++ b/frc971/control_loops/state_feedback_loop.h
@@ -256,8 +256,12 @@
   static const int kNumInputs = number_of_inputs;
 
  private:
-  Eigen::Matrix<Scalar, number_of_states, 1> X_;
-  Eigen::Matrix<Scalar, number_of_outputs, 1> Y_;
+  // X_ and Y_ must be explicitly initialized to avoid having gcc complain about
+  // uninitialized values when using the move constructor.
+  Eigen::Matrix<Scalar, number_of_states, 1> X_ =
+      Eigen::Matrix<Scalar, number_of_states, 1>::Zero();
+  Eigen::Matrix<Scalar, number_of_outputs, 1> Y_ =
+      Eigen::Matrix<Scalar, number_of_outputs, 1>::Zero();
   Eigen::Matrix<Scalar, number_of_inputs, Eigen::Dynamic> last_U_;
 
   ::std::vector<::std::unique_ptr<StateFeedbackPlantCoefficients<