Upgraded //y2012 to use the common drive code.

This is a fixup from changing the call signature of DoCoerceGoal

Change-Id: I6a99f666bebd9a728f42083a9c0280e8f2dab295
diff --git a/y2012/BUILD b/y2012/BUILD
index 395206b..bbdab0a 100644
--- a/y2012/BUILD
+++ b/y2012/BUILD
@@ -12,7 +12,7 @@
     '//aos/common:time',
     '//aos/common/util:log_interval',
     '//aos/common/actions:action_lib',
-    '//y2012/control_loops/drivetrain:drivetrain_queue',
+    '//frc971/control_loops/drivetrain:drivetrain_queue',
     '//y2012/control_loops/accessories:accessories_queue',
     '//frc971/queues:gyro',
     '//frc971/autonomous:auto_queue',
diff --git a/y2012/control_loops/drivetrain/BUILD b/y2012/control_loops/drivetrain/BUILD
index d23c06f..e285742 100644
--- a/y2012/control_loops/drivetrain/BUILD
+++ b/y2012/control_loops/drivetrain/BUILD
@@ -2,29 +2,6 @@
 
 load('/aos/build/queues', 'queue_library')
 
-cc_binary(
-  name = 'replay_drivetrain',
-  srcs = [
-    'replay_drivetrain.cc',
-  ],
-  deps = [
-    ':drivetrain_queue',
-    '//aos/common/controls:replay_control_loop',
-    '//aos/linux_code:init',
-    '//frc971/queues:gyro',
-  ],
-)
-
-queue_library(
-  name = 'drivetrain_queue',
-  srcs = [
-    'drivetrain.q',
-  ],
-  deps = [
-    '//aos/common/controls:control_loop_queues',
-  ],
-)
-
 genrule(
   name = 'genrule_drivetrain',
   visibility = ['//visibility:private'],
@@ -73,67 +50,18 @@
 )
 
 cc_library(
-  name = 'ssdrivetrain',
+  name = 'drivetrain_base',
   srcs = [
-    'ssdrivetrain.cc',
+    'drivetrain_base.cc',
   ],
   hdrs = [
-    'ssdrivetrain.h',
+    'drivetrain_base.h',
   ],
   deps = [
     ':polydrivetrain_plants',
-    ':drivetrain_queue',
-    '//aos/common/controls:polytope',
-    '//aos/common:math',
-    '//aos/common/messages:robot_state',
-    '//frc971/control_loops:state_feedback_loop',
-    '//frc971/control_loops:coerce_goal',
-    '//aos/common/util:log_interval',
-    '//aos/common/logging:queue_logging',
-    '//aos/common/logging:matrix_logging',
-  ],
-)
-
-cc_library(
-  name = 'polydrivetrain',
-  srcs = [
-    'polydrivetrain.cc',
-  ],
-  hdrs = [
-    'polydrivetrain.h',
-  ],
-  deps = [
-    ':polydrivetrain_plants',
-    ':drivetrain_queue',
-    '//aos/common/controls:polytope',
-    '//aos/common:math',
-    '//aos/common/messages:robot_state',
-    '//frc971/control_loops:state_feedback_loop',
-    '//frc971/control_loops:coerce_goal',
-    '//aos/common/util:log_interval',
-    '//aos/common/logging:queue_logging',
-    '//aos/common/logging:matrix_logging',
-  ],
-)
-
-cc_library(
-  name = 'drivetrain_lib',
-  srcs = [
-    'drivetrain.cc',
-  ],
-  hdrs = [
-    'drivetrain.h',
-  ],
-  deps = [
-    ':drivetrain_queue',
-    ':polydrivetrain',
-    ':polydrivetrain_plants',
-    ':ssdrivetrain',
-    '//aos/common/controls:control_loop',
-    '//frc971/queues:gyro',
-    '//aos/common/util:log_interval',
-    '//aos/common/logging:queue_logging',
-    '//aos/common/logging:matrix_logging',
+    '//frc971/control_loops/drivetrain:drivetrain_config',
+    '//frc971:shifter_hall_effect',
+    '//y2016:constants',
   ],
 )
 
@@ -143,8 +71,8 @@
     'drivetrain_main.cc',
   ],
   deps = [
+    ':drivetrain_base',
     '//aos/linux_code:init',
-    ':drivetrain_lib',
-    ':drivetrain_queue',
+    '//frc971/control_loops/drivetrain:drivetrain_lib',
   ],
 )
diff --git a/y2012/control_loops/drivetrain/drivetrain.cc b/y2012/control_loops/drivetrain/drivetrain.cc
deleted file mode 100644
index 0a2eef0..0000000
--- a/y2012/control_loops/drivetrain/drivetrain.cc
+++ /dev/null
@@ -1,152 +0,0 @@
-#include "y2012/control_loops/drivetrain/drivetrain.h"
-
-#include <stdio.h>
-#include <sched.h>
-#include <cmath>
-#include <memory>
-#include "Eigen/Dense"
-
-#include "aos/common/logging/logging.h"
-#include "aos/common/logging/queue_logging.h"
-#include "aos/common/logging/matrix_logging.h"
-
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "y2012/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-#include "y2012/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
-#include "y2012/control_loops/drivetrain/polydrivetrain.h"
-#include "y2012/control_loops/drivetrain/ssdrivetrain.h"
-#include "frc971/queues/gyro.q.h"
-
-// A consistent way to mark code that goes away without shifters. It's still
-// here because we will have shifters again in the future.
-#define HAVE_SHIFTERS 1
-
-using frc971::sensors::gyro_reading;
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-DrivetrainLoop::DrivetrainLoop(
-    ::y2012::control_loops::DrivetrainQueue *my_drivetrain)
-    : aos::controls::ControlLoop<::y2012::control_loops::DrivetrainQueue>(
-          my_drivetrain),
-      kf_(::y2012::control_loops::drivetrain::MakeKFDrivetrainLoop()) {
-  ::aos::controls::HPolytope<0>::Init();
-}
-
-void DrivetrainLoop::RunIteration(
-    const ::y2012::control_loops::DrivetrainQueue::Goal *goal,
-    const ::y2012::control_loops::DrivetrainQueue::Position *position,
-    ::y2012::control_loops::DrivetrainQueue::Output *output,
-    ::y2012::control_loops::DrivetrainQueue::Status *status) {
-  bool bad_pos = false;
-  if (position == nullptr) {
-    LOG_INTERVAL(no_position_);
-    bad_pos = true;
-  }
-  no_position_.Print();
-
-  bool control_loop_driving = false;
-  if (goal) {
-    double wheel = goal->steering;
-    double throttle = goal->throttle;
-    bool quickturn = goal->quickturn;
-#if HAVE_SHIFTERS
-    bool highgear = goal->highgear;
-#endif
-
-    control_loop_driving = goal->control_loop_driving;
-    double left_goal = goal->left_goal;
-    double right_goal = goal->right_goal;
-
-    dt_closedloop_.SetGoal(left_goal, goal->left_velocity_goal, right_goal,
-                           goal->right_velocity_goal);
-#if HAVE_SHIFTERS
-    dt_openloop_.SetGoal(wheel, throttle, quickturn, highgear);
-#else
-    dt_openloop_.SetGoal(wheel, throttle, quickturn, false);
-#endif
-  }
-
-  if (!bad_pos) {
-    const double left_encoder = position->left_encoder;
-    const double right_encoder = position->right_encoder;
-    if (gyro_reading.FetchLatest()) {
-      LOG_STRUCT(DEBUG, "using", *gyro_reading.get());
-      dt_closedloop_.SetPosition(left_encoder, right_encoder,
-                                 gyro_reading->angle);
-      last_gyro_heading_ = gyro_reading->angle;
-      last_gyro_rate_ = gyro_reading->velocity;
-    } else {
-      dt_closedloop_.SetRawPosition(left_encoder, right_encoder);
-    }
-  }
-  dt_openloop_.SetPosition(position);
-  dt_openloop_.Update();
-
-  if (control_loop_driving) {
-    dt_closedloop_.Update(output == NULL, true);
-    dt_closedloop_.SendMotors(output);
-  } else {
-    dt_openloop_.SendMotors(output);
-    if (output) {
-      dt_closedloop_.SetExternalMotors(output->left_voltage,
-                                       output->right_voltage);
-    }
-    dt_closedloop_.Update(output == NULL, false);
-  }
-
-  // set the output status of the control loop state
-  if (status) {
-    status->robot_speed = dt_closedloop_.GetEstimatedRobotSpeed();
-    status->estimated_left_position = dt_closedloop_.GetEstimatedLeftEncoder();
-    status->estimated_right_position = dt_closedloop_.GetEstimatedRightEncoder();
-
-    status->estimated_left_velocity = dt_closedloop_.loop().X_hat(1, 0);
-    status->estimated_right_velocity = dt_closedloop_.loop().X_hat(3, 0);
-    status->output_was_capped = dt_closedloop_.OutputWasCapped();
-    status->uncapped_left_voltage = dt_closedloop_.loop().U_uncapped(0, 0);
-    status->uncapped_right_voltage = dt_closedloop_.loop().U_uncapped(1, 0);
-  }
-
-
-  double left_voltage = 0.0;
-  double right_voltage = 0.0;
-  if (output) {
-    left_voltage = output->left_voltage;
-    right_voltage = output->right_voltage;
-  }
-
-  const double scalar = ::aos::robot_state->voltage_battery / 12.0;
-
-  left_voltage *= scalar;
-  right_voltage *= scalar;
-
-  kf_.set_controller_index(dt_openloop_.controller_index());
-
-  Eigen::Matrix<double, 3, 1> Y;
-  Y << position->left_encoder, position->right_encoder, last_gyro_rate_;
-  kf_.Correct(Y);
-  integrated_kf_heading_ +=
-      kDt * (kf_.X_hat(3, 0) - kf_.X_hat(1, 0)) / (kRobotRadius * 2.0);
-
-  // To validate, look at the following:
-
-  // Observed - dx/dt velocity for left, right.
-
-  // Angular velocity error compared to the gyro
-  // Gyro heading vs left-right
-  // Voltage error.
-
-  Eigen::Matrix<double, 2, 1> U;
-  U << last_left_voltage_, last_right_voltage_;
-  last_left_voltage_ = left_voltage;
-  last_right_voltage_ = right_voltage;
-
-  kf_.UpdateObserver(U);
-}
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
diff --git a/y2012/control_loops/drivetrain/drivetrain.h b/y2012/control_loops/drivetrain/drivetrain.h
deleted file mode 100644
index 6fcbca7..0000000
--- a/y2012/control_loops/drivetrain/drivetrain.h
+++ /dev/null
@@ -1,55 +0,0 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
-
-#include "Eigen/Dense"
-
-#include "aos/common/controls/polytope.h"
-#include "aos/common/controls/control_loop.h"
-#include "aos/common/controls/polytope.h"
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "y2012/control_loops/drivetrain/polydrivetrain.h"
-#include "y2012/control_loops/drivetrain/ssdrivetrain.h"
-#include "aos/common/util/log_interval.h"
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-class DrivetrainLoop : public aos::controls::ControlLoop<
-                           ::y2012::control_loops::DrivetrainQueue> {
- public:
-  // Constructs a control loop which can take a Drivetrain or defaults to the
-  // drivetrain at y2012::control_loops::drivetrain
-  explicit DrivetrainLoop(
-      ::y2012::control_loops::DrivetrainQueue *my_drivetrain =
-          &::y2012::control_loops::drivetrain_queue);
-
- protected:
-  // Executes one cycle of the control loop.
-  virtual void RunIteration(
-      const ::y2012::control_loops::DrivetrainQueue::Goal *goal,
-      const ::y2012::control_loops::DrivetrainQueue::Position *position,
-      ::y2012::control_loops::DrivetrainQueue::Output *output,
-      ::y2012::control_loops::DrivetrainQueue::Status *status);
-
-  typedef ::aos::util::SimpleLogInterval SimpleLogInterval;
-  SimpleLogInterval no_position_ = SimpleLogInterval(
-      ::aos::time::Time::InSeconds(0.25), WARNING, "no position");
-  double last_gyro_heading_ = 0.0;
-  double last_gyro_rate_ = 0.0;
-
-  PolyDrivetrain dt_openloop_;
-  DrivetrainMotorsSS dt_closedloop_;
-  StateFeedbackLoop<7, 2, 3> kf_;
-
-  double last_left_voltage_ = 0;
-  double last_right_voltage_ = 0;
-
-  double integrated_kf_heading_ = 0;
-};
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
-
-#endif  // Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
diff --git a/y2012/control_loops/drivetrain/drivetrain.q b/y2012/control_loops/drivetrain/drivetrain.q
deleted file mode 100644
index 44080da..0000000
--- a/y2012/control_loops/drivetrain/drivetrain.q
+++ /dev/null
@@ -1,126 +0,0 @@
-package y2012.control_loops;
-
-import "aos/common/controls/control_loops.q";
-
-// For logging information about what the code is doing with the shifters.
-struct GearLogging {
-  // Which controller is being used.
-  int8_t controller_index;
-  // Whether the left loop is the high-gear one.
-  bool left_loop_high;
-  // Whether the right loop is the high-gear one.
-  bool right_loop_high;
-  // The state of the left shifter.
-  int8_t left_state;
-  // The state of the right shifter.
-  int8_t right_state;
-};
-
-// For logging information about the state of the shifters.
-struct CIMLogging {
-  // Whether the code thinks the left side is currently in gear.
-  bool left_in_gear;
-  // Whether the code thinks the right side is currently in gear.
-  bool right_in_gear;
-  // The velocity in rad/s (positive forward) the code thinks the left motor
-  // is currently spinning at.
-  double left_motor_speed;
-  // The velocity in rad/s (positive forward) the code thinks the right motor
-  // is currently spinning at.
-  double right_motor_speed;
-  // The velocity estimate for the left side of the robot in m/s (positive
-  // forward) used for shifting.
-  double left_velocity;
-  // The velocity estimate for the right side of the robot in m/s (positive
-  // forward) used for shifting.
-  double right_velocity;
-};
-
-queue_group DrivetrainQueue {
-  implements aos.control_loops.ControlLoop;
-
-  message Goal {
-    // Position of the steering wheel (positive = turning left when going
-    // forwards).
-    double steering;
-    // Position of the throttle (positive forwards).
-    double throttle;
-    // True to shift into high, false to shift into low.
-    bool highgear;
-    // True to activate quickturn.
-    bool quickturn;
-    // True to have the closed-loop controller take over.
-    bool control_loop_driving;
-    // Position goal for the left side in meters when the closed-loop controller
-    // is active.
-    double left_goal;
-    // Velocity goal for the left side in m/s when the closed-loop controller
-    // is active.
-    double left_velocity_goal;
-    // Position goal for the right side in meters when the closed-loop
-    // controller is active.
-    double right_goal;
-    // Velocity goal for the right side in m/s when the closed-loop controller
-    // is active.
-    double right_velocity_goal;
-  };
-
-  message Position {
-    // Relative position of the left side in meters.
-    double left_encoder;
-    // Relative position of the right side in meters.
-    double right_encoder;
-    // The speed in m/s of the left side from the most recent encoder pulse,
-    // or 0 if there was no edge within the last 5ms.
-    double left_speed;
-    // The speed in m/s of the right side from the most recent encoder pulse,
-    // or 0 if there was no edge within the last 5ms.
-    double right_speed;
-    // Position of the left shifter (smaller = towards low gear).
-    double left_shifter_position;
-    // Position of the right shifter (smaller = towards low gear).
-    double right_shifter_position;
-    double low_left_hall;
-    double high_left_hall;
-    double low_right_hall;
-    double high_right_hall;
-  };
-
-  message Output {
-    // Voltage to send to the left motor(s).
-    double left_voltage;
-    // Voltage to send to the right motor(s).
-    double right_voltage;
-    // True to set the left shifter piston for high gear.
-    bool left_high;
-    // True to set the right shifter piston for high gear.
-    bool right_high;
-  };
-
-  message Status {
-    // Estimated speed of the center of the robot in m/s (positive forwards).
-    double robot_speed;
-    // Estimated relative position of the left side in meters.
-    double estimated_left_position;
-    // Estimated relative position of the right side in meters.
-    double estimated_right_position;
-    // Estimated velocity of the left side in m/s.
-    double estimated_left_velocity;
-    // Estimated velocity of the left side in m/s.
-    double estimated_right_velocity;
-
-    // The voltage we wanted to send to the left side last cycle.
-    double uncapped_left_voltage;
-    // The voltage we wanted to send to the right side last cycle.
-    double uncapped_right_voltage;
-    // True if the output voltage was capped last cycle.
-    bool output_was_capped;
-  };
-
-  queue Goal goal;
-  queue Position position;
-  queue Output output;
-  queue Status status;
-};
-
-queue_group DrivetrainQueue drivetrain_queue;
diff --git a/y2012/control_loops/drivetrain/drivetrain_base.cc b/y2012/control_loops/drivetrain/drivetrain_base.cc
new file mode 100644
index 0000000..321962e
--- /dev/null
+++ b/y2012/control_loops/drivetrain/drivetrain_base.cc
@@ -0,0 +1,48 @@
+#include "y2012/control_loops/drivetrain/drivetrain_base.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+#include "frc971/control_loops/state_feedback_loop.h"
+#include "y2012/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+#include "y2012/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
+#include "y2012/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainConfig;
+
+namespace y2012 {
+namespace control_loops {
+namespace drivetrain {
+
+using ::frc971::constants::ShifterHallEffect;
+
+const ShifterHallEffect kThreeStateDriveShifter{0.0, 0.0, 0.0, 0.0, 0.25, 0.75};
+
+const DrivetrainConfig &GetDrivetrainConfig() {
+  static DrivetrainConfig kDrivetrainConfig{
+      ::frc971::control_loops::drivetrain::ShifterType::NO_SHIFTER,
+      ::frc971::control_loops::drivetrain::LoopType::CLOSED_LOOP,
+
+      ::y2012::control_loops::drivetrain::MakeDrivetrainLoop,
+      ::y2012::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+      ::y2012::control_loops::drivetrain::MakeKFDrivetrainLoop,
+
+      drivetrain::kDt,
+      drivetrain::kRobotRadius,
+      drivetrain::kWheelRadius,
+      drivetrain::kV,
+
+      drivetrain::kHighGearRatio,
+      drivetrain::kLowGearRatio,
+      kThreeStateDriveShifter,
+      kThreeStateDriveShifter,
+      true,
+      0.0,
+      0.4,
+      1.0};
+
+  return kDrivetrainConfig;
+};
+
+}  // namespace drivetrain
+}  // namespace control_loops
+}  // namespace y2012
diff --git a/y2012/control_loops/drivetrain/drivetrain_base.h b/y2012/control_loops/drivetrain/drivetrain_base.h
new file mode 100644
index 0000000..3d85af1
--- /dev/null
+++ b/y2012/control_loops/drivetrain/drivetrain_base.h
@@ -0,0 +1,17 @@
+#ifndef Y2012_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+#define Y2012_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+namespace y2012 {
+namespace control_loops {
+namespace drivetrain {
+
+const ::frc971::control_loops::drivetrain::DrivetrainConfig &
+GetDrivetrainConfig();
+
+}  // namespace drivetrain
+}  // namespace control_loops
+}  // namespace y2012
+
+#endif  // Y2012_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
diff --git a/y2012/control_loops/drivetrain/drivetrain_main.cc b/y2012/control_loops/drivetrain/drivetrain_main.cc
index ddff516..cb453f5 100644
--- a/y2012/control_loops/drivetrain/drivetrain_main.cc
+++ b/y2012/control_loops/drivetrain/drivetrain_main.cc
@@ -1,10 +1,14 @@
-#include "y2012/control_loops/drivetrain/drivetrain.h"
-
 #include "aos/linux_code/init.h"
 
+#include "frc971/control_loops/drivetrain/drivetrain.h"
+#include "y2012/control_loops/drivetrain/drivetrain_base.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainLoop;
+
 int main() {
   ::aos::Init();
-  ::y2012::control_loops::drivetrain::DrivetrainLoop drivetrain;
+  DrivetrainLoop drivetrain(
+      ::y2012::control_loops::drivetrain::GetDrivetrainConfig());
   drivetrain.Run();
   ::aos::Cleanup();
   return 0;
diff --git a/y2012/control_loops/drivetrain/polydrivetrain.cc b/y2012/control_loops/drivetrain/polydrivetrain.cc
deleted file mode 100644
index 598d635..0000000
--- a/y2012/control_loops/drivetrain/polydrivetrain.cc
+++ /dev/null
@@ -1,332 +0,0 @@
-#include "y2012/control_loops/drivetrain/polydrivetrain.h"
-
-#include "aos/common/logging/logging.h"
-#include "aos/common/controls/polytope.h"
-#include "aos/common/commonmath.h"
-#include "aos/common/logging/queue_logging.h"
-#include "aos/common/logging/matrix_logging.h"
-
-#include "aos/common/messages/robot_state.q.h"
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "frc971/control_loops/coerce_goal.h"
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "y2012/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-#include "y2012/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
-
-#define HAVE_SHIFTERS 1
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-using ::y2012::control_loops::GearLogging;
-using ::y2012::control_loops::CIMLogging;
-using ::frc971::control_loops::CoerceGoal;
-
-PolyDrivetrain::PolyDrivetrain()
-    : U_Poly_((Eigen::Matrix<double, 4, 2>() << /*[[*/ 1, 0 /*]*/,
-               /*[*/ -1, 0 /*]*/,
-               /*[*/ 0, 1 /*]*/,
-               /*[*/ 0, -1 /*]]*/).finished(),
-              (Eigen::Matrix<double, 4, 1>() << /*[[*/ 12 /*]*/,
-               /*[*/ 12 /*]*/,
-               /*[*/ 12 /*]*/,
-               /*[*/ 12 /*]]*/).finished()),
-      loop_(new StateFeedbackLoop<2, 2, 2>(
-          ::y2012::control_loops::drivetrain::MakeVelocityDrivetrainLoop())),
-      ttrust_(1.1),
-      wheel_(0.0),
-      throttle_(0.0),
-      quickturn_(false),
-      stale_count_(0),
-      position_time_delta_(kDt),
-      left_gear_(LOW),
-      right_gear_(LOW),
-      counter_(0) {
-  last_position_.Zero();
-  position_.Zero();
-}
-
-double PolyDrivetrain::MotorSpeed(bool high_gear, double velocity) {
-  if (high_gear) {
-    return velocity / kHighGearRatio / kWheelRadius;
-  } else {
-    return velocity / kLowGearRatio / kWheelRadius;
-  }
-}
-
-void PolyDrivetrain::SetGoal(double wheel, double throttle, bool quickturn,
-                             bool highgear) {
-  const double kWheelNonLinearity = 0.3;
-  // Apply a sin function that's scaled to make it feel better.
-  const double angular_range = M_PI_2 * kWheelNonLinearity;
-
-  wheel_ = sin(angular_range * wheel) / sin(angular_range);
-  wheel_ = sin(angular_range * wheel_) / sin(angular_range);
-  quickturn_ = quickturn;
-
-  static const double kThrottleDeadband = 0.05;
-  if (::std::abs(throttle) < kThrottleDeadband) {
-    throttle_ = 0;
-  } else {
-    throttle_ = copysign(
-        (::std::abs(throttle) - kThrottleDeadband) / (1.0 - kThrottleDeadband),
-        throttle);
-  }
-
-  // TODO(austin): Fix the upshift logic to include states.
-  Gear requested_gear = highgear ? HIGH : LOW;
-
-  const Gear shift_up = HIGH;
-  const Gear shift_down = LOW;
-
-  if (left_gear_ != requested_gear) {
-    if (IsInGear(left_gear_)) {
-      if (requested_gear == HIGH) {
-        left_gear_ = shift_up;
-      } else {
-        left_gear_ = shift_down;
-      }
-    } else {
-      if (requested_gear == HIGH && left_gear_ == SHIFTING_DOWN) {
-        left_gear_ = SHIFTING_UP;
-      } else if (requested_gear == LOW && left_gear_ == SHIFTING_UP) {
-        left_gear_ = SHIFTING_DOWN;
-      }
-    }
-  }
-  if (right_gear_ != requested_gear) {
-    if (IsInGear(right_gear_)) {
-      if (requested_gear == HIGH) {
-        right_gear_ = shift_up;
-      } else {
-        right_gear_ = shift_down;
-      }
-    } else {
-      if (requested_gear == HIGH && right_gear_ == SHIFTING_DOWN) {
-        right_gear_ = SHIFTING_UP;
-      } else if (requested_gear == LOW && right_gear_ == SHIFTING_UP) {
-        right_gear_ = SHIFTING_DOWN;
-      }
-    }
-  }
-}
-void PolyDrivetrain::SetPosition(
-    const ::y2012::control_loops::DrivetrainQueue::Position *position) {
-  if (position == NULL) {
-    ++stale_count_;
-  } else {
-    last_position_ = position_;
-    position_ = *position;
-    position_time_delta_ = (stale_count_ + 1) * kDt;
-    stale_count_ = 0;
-  }
-
-#if HAVE_SHIFTERS
-  if (position) {
-    if (left_gear_ == LOW) {
-      if (right_gear_ == LOW) {
-        loop_->set_controller_index(0);
-      } else {
-        loop_->set_controller_index(1);
-      }
-    } else {
-      if (right_gear_ == LOW) {
-        loop_->set_controller_index(2);
-      } else {
-        loop_->set_controller_index(3);
-      }
-    }
-  }
-#endif
-}
-
-double PolyDrivetrain::FilterVelocity(double throttle) {
-  const Eigen::Matrix<double, 2, 2> FF =
-      loop_->B().inverse() *
-      (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
-
-  constexpr int kHighGearController = 3;
-  const Eigen::Matrix<double, 2, 2> FF_high =
-      loop_->controller(kHighGearController).plant.B().inverse() *
-      (Eigen::Matrix<double, 2, 2>::Identity() -
-       loop_->controller(kHighGearController).plant.A());
-
-  ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
-  int min_FF_sum_index;
-  const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
-  const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
-  const double high_min_FF_sum = FF_high.col(0).sum();
-
-  const double adjusted_ff_voltage =
-      ::aos::Clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
-  return (adjusted_ff_voltage +
-          ttrust_ * min_K_sum * (loop_->X_hat(0, 0) + loop_->X_hat(1, 0)) /
-              2.0) /
-         (ttrust_ * min_K_sum + min_FF_sum);
-}
-
-double PolyDrivetrain::MaxVelocity() {
-  const Eigen::Matrix<double, 2, 2> FF =
-      loop_->B().inverse() *
-      (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
-
-  constexpr int kHighGearController = 3;
-  const Eigen::Matrix<double, 2, 2> FF_high =
-      loop_->controller(kHighGearController).plant.B().inverse() *
-      (Eigen::Matrix<double, 2, 2>::Identity() -
-       loop_->controller(kHighGearController).plant.A());
-
-  ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
-  int min_FF_sum_index;
-  const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
-  // const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
-  const double high_min_FF_sum = FF_high.col(0).sum();
-
-  const double adjusted_ff_voltage =
-      ::aos::Clip(12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
-  return adjusted_ff_voltage / min_FF_sum;
-}
-
-void PolyDrivetrain::Update() {
-  // TODO(austin): Observer for the current velocity instead of difference
-  // calculations.
-  ++counter_;
-#if HAVE_SHIFTERS
-  const double current_left_velocity =
-      (position_.left_encoder - last_position_.left_encoder) /
-      position_time_delta_;
-  const double current_right_velocity =
-      (position_.right_encoder - last_position_.right_encoder) /
-      position_time_delta_;
-  const double left_motor_speed =
-      MotorSpeed(left_gear_ == HIGH, current_left_velocity);
-  const double right_motor_speed =
-      MotorSpeed(right_gear_ == HIGH, current_right_velocity);
-
-  {
-    CIMLogging logging;
-
-    // Reset the CIM model to the current conditions to be ready for when we
-    // shift.
-    if (IsInGear(left_gear_)) {
-      logging.left_in_gear = true;
-    } else {
-      logging.left_in_gear = false;
-    }
-    logging.left_motor_speed = left_motor_speed;
-    logging.left_velocity = current_left_velocity;
-    if (IsInGear(right_gear_)) {
-      logging.right_in_gear = true;
-    } else {
-      logging.right_in_gear = false;
-    }
-    logging.right_motor_speed = right_motor_speed;
-    logging.right_velocity = current_right_velocity;
-
-    LOG_STRUCT(DEBUG, "currently", logging);
-  }
-#endif
-
-#if HAVE_SHIFTERS
-  if (IsInGear(left_gear_) && IsInGear(right_gear_))
-#endif
-  {
-    // FF * X = U (steady state)
-    const Eigen::Matrix<double, 2, 2> FF =
-        loop_->B().inverse() *
-        (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
-
-    // Invert the plant to figure out how the velocity filter would have to
-    // work
-    // out in order to filter out the forwards negative inertia.
-    // This math assumes that the left and right power and velocity are
-    // equals,
-    // and that the plant is the same on the left and right.
-    const double fvel = FilterVelocity(throttle_);
-
-    const double sign_svel = wheel_ * ((fvel > 0.0) ? 1.0 : -1.0);
-    double steering_velocity;
-    if (quickturn_) {
-      steering_velocity = wheel_ * MaxVelocity();
-    } else {
-      steering_velocity = ::std::abs(fvel) * wheel_;
-    }
-    const double left_velocity = fvel - steering_velocity;
-    const double right_velocity = fvel + steering_velocity;
-
-    // Integrate velocity to get the position.
-    // This position is used to get integral control.
-    loop_->mutable_R() << left_velocity, right_velocity;
-
-    if (!quickturn_) {
-      // K * R = w
-      Eigen::Matrix<double, 1, 2> equality_k;
-      equality_k << 1 + sign_svel, -(1 - sign_svel);
-      const double equality_w = 0.0;
-
-      // Construct a constraint on R by manipulating the constraint on U
-      ::aos::controls::HPolytope<2> R_poly = ::aos::controls::HPolytope<2>(
-          U_Poly_.H() * (loop_->K() + FF),
-          U_Poly_.k() + U_Poly_.H() * loop_->K() * loop_->X_hat());
-
-      // Limit R back inside the box.
-      loop_->mutable_R() =
-          CoerceGoal(R_poly, equality_k, equality_w, loop_->R());
-    }
-
-    const Eigen::Matrix<double, 2, 1> FF_volts = FF * loop_->R();
-    const Eigen::Matrix<double, 2, 1> U_ideal =
-        loop_->K() * (loop_->R() - loop_->X_hat()) + FF_volts;
-
-    for (int i = 0; i < 2; i++) {
-      loop_->mutable_U()[i] = ::aos::Clip(U_ideal[i], -12, 12);
-    }
-
-    // TODO(austin): Model this better.
-    // TODO(austin): Feed back?
-    loop_->mutable_X_hat() =
-        loop_->A() * loop_->X_hat() + loop_->B() * loop_->U();
-#if HAVE_SHIFTERS
-  } else {
-    // Any motor is not in gear.  Speed match.
-    ::Eigen::Matrix<double, 1, 1> R_left;
-    ::Eigen::Matrix<double, 1, 1> R_right;
-    R_left(0, 0) = left_motor_speed;
-    R_right(0, 0) = right_motor_speed;
-
-    const double wiggle =
-        (static_cast<double>((counter_ % 20) / 10) - 0.5) * 5.0;
-
-    loop_->mutable_U(0, 0) = ::aos::Clip(
-        (R_left / Kv)(0, 0) + (IsInGear(left_gear_) ? 0 : wiggle), -12.0, 12.0);
-    loop_->mutable_U(1, 0) =
-        ::aos::Clip((R_right / Kv)(0, 0) + (IsInGear(right_gear_) ? 0 : wiggle),
-                    -12.0, 12.0);
-    loop_->mutable_U() *= 12.0 / ::aos::robot_state->voltage_battery;
-#endif
-  }
-}
-
-void PolyDrivetrain::SendMotors(
-    ::y2012::control_loops::DrivetrainQueue::Output *output) {
-  if (output != NULL) {
-    output->left_voltage = loop_->U(0, 0);
-    output->right_voltage = loop_->U(1, 0);
-    output->left_high = left_gear_ == HIGH || left_gear_ == SHIFTING_UP;
-    output->right_high = right_gear_ == HIGH || right_gear_ == SHIFTING_UP;
-  }
-}
-
-constexpr double PolyDrivetrain::kStallTorque;
-constexpr double PolyDrivetrain::kStallCurrent;
-constexpr double PolyDrivetrain::kFreeSpeed;
-constexpr double PolyDrivetrain::kFreeCurrent;
-constexpr double PolyDrivetrain::kWheelRadius;
-constexpr double PolyDrivetrain::kR;
-constexpr double PolyDrivetrain::Kv;
-constexpr double PolyDrivetrain::Kt;
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
diff --git a/y2012/control_loops/drivetrain/polydrivetrain.h b/y2012/control_loops/drivetrain/polydrivetrain.h
deleted file mode 100644
index 73dcc8b..0000000
--- a/y2012/control_loops/drivetrain/polydrivetrain.h
+++ /dev/null
@@ -1,80 +0,0 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
-
-#include "aos/common/controls/polytope.h"
-
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "y2012/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-class PolyDrivetrain {
- public:
-  enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
-  // Stall Torque in N m
-  static constexpr double kStallTorque = drivetrain::kStallTorque;
-  // Stall Current in Amps
-  static constexpr double kStallCurrent = drivetrain::kStallCurrent;
-  // Free Speed in RPM. Used number from last year.
-  static constexpr double kFreeSpeed = drivetrain::kFreeSpeedRPM;
-  // Free Current in Amps
-  static constexpr double kFreeCurrent = drivetrain::kFreeCurrent;
-  static constexpr double kWheelRadius = drivetrain::kWheelRadius;
-  // Resistance of the motor, divided by the number of motors per side.
-  static constexpr double kR = drivetrain::kR;
-  // Motor velocity constant
-  static constexpr double Kv = drivetrain::kV;
-
-  // Torque constant
-  static constexpr double Kt = drivetrain::kT;
-
-  static constexpr double kLowGearRatio = 15.0 / 60.0 * 15.0 / 50.0;
-  static constexpr double kHighGearRatio = 30.0 / 45.0 * 15.0 / 50.0;
-
-  PolyDrivetrain();
-
-  int controller_index() const { return loop_->controller_index(); }
-
-  static bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
-
-  static double MotorSpeed(bool high_gear, double velocity);
-
-  void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
-
-  void SetPosition(
-      const ::y2012::control_loops::DrivetrainQueue::Position *position);
-
-  double FilterVelocity(double throttle);
-
-  double MaxVelocity();
-
-  void Update();
-
-  void SendMotors(::y2012::control_loops::DrivetrainQueue::Output *output);
-
- private:
-  const ::aos::controls::HPolytope<2> U_Poly_;
-
-  ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
-
-  const double ttrust_;
-  double wheel_;
-  double throttle_;
-  bool quickturn_;
-  int stale_count_;
-  double position_time_delta_;
-  Gear left_gear_;
-  Gear right_gear_;
-  ::y2012::control_loops::DrivetrainQueue::Position last_position_;
-  ::y2012::control_loops::DrivetrainQueue::Position position_;
-  int counter_;
-};
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
-
-#endif  // Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
diff --git a/y2012/control_loops/drivetrain/replay_drivetrain.cc b/y2012/control_loops/drivetrain/replay_drivetrain.cc
deleted file mode 100644
index db03741..0000000
--- a/y2012/control_loops/drivetrain/replay_drivetrain.cc
+++ /dev/null
@@ -1,36 +0,0 @@
-#include "aos/common/controls/replay_control_loop.h"
-#include "aos/linux_code/init.h"
-
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "frc971/queues/gyro.q.h"
-
-// Reads one or more log files and sends out all the queue messages (in the
-// correct order and at the correct time) to feed a "live" drivetrain process.
-
-int main(int argc, char **argv) {
-  if (argc <= 1) {
-    fprintf(stderr, "Need at least one file to replay!\n");
-    return EXIT_FAILURE;
-  }
-
-  ::aos::InitNRT();
-
-  {
-    ::aos::controls::ControlLoopReplayer<
-        ::y2012::control_loops::DrivetrainQueue>
-        replayer(&::y2012::control_loops::drivetrain_queue, "drivetrain");
-
-    replayer.AddDirectQueueSender("wpilib_interface.Gyro", "sending",
-                                  ::frc971::sensors::gyro_reading);
-    for (int i = 1; i < argc; ++i) {
-      replayer.ProcessFile(argv[i]);
-    }
-  }
-  ::frc971::sensors::gyro_reading.Clear();
-  ::y2012::control_loops::drivetrain_queue.goal.Clear();
-  ::y2012::control_loops::drivetrain_queue.status.Clear();
-  ::y2012::control_loops::drivetrain_queue.position.Clear();
-  ::y2012::control_loops::drivetrain_queue.output.Clear();
-
-  ::aos::Cleanup();
-}
diff --git a/y2012/control_loops/drivetrain/ssdrivetrain.cc b/y2012/control_loops/drivetrain/ssdrivetrain.cc
deleted file mode 100644
index 0dd3eb1..0000000
--- a/y2012/control_loops/drivetrain/ssdrivetrain.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-#include "y2012/control_loops/drivetrain/ssdrivetrain.h"
-
-#include "aos/common/controls/polytope.h"
-#include "aos/common/commonmath.h"
-#include "aos/common/logging/matrix_logging.h"
-
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "frc971/control_loops/coerce_goal.h"
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "y2012/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-using ::frc971::control_loops::DoCoerceGoal;
-
-DrivetrainMotorsSS::LimitedDrivetrainLoop::LimitedDrivetrainLoop(
-    StateFeedbackLoop<4, 2, 2> &&loop)
-    : StateFeedbackLoop<4, 2, 2>(::std::move(loop)),
-      U_Poly_((Eigen::Matrix<double, 4, 2>() << 1, 0, -1, 0, 0, 1, 0, -1)
-                  .finished(),
-              (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0, 12.0, 12.0)
-                  .finished()) {
-  ::aos::controls::HPolytope<0>::Init();
-  T << 1, -1, 1, 1;
-  T_inverse = T.inverse();
-}
-
-void DrivetrainMotorsSS::LimitedDrivetrainLoop::CapU() {
-  const Eigen::Matrix<double, 4, 1> error = R() - X_hat();
-
-  if (::std::abs(U(0, 0)) > 12.0 || ::std::abs(U(1, 0)) > 12.0) {
-    mutable_U() =
-        U() * 12.0 / ::std::max(::std::abs(U(0, 0)), ::std::abs(U(1, 0)));
-    LOG_MATRIX(DEBUG, "U is now", U());
-    // TODO(Austin): Figure out why the polytope stuff wasn't working and
-    // remove this hack.
-    output_was_capped_ = true;
-    return;
-
-    LOG_MATRIX(DEBUG, "U at start", U());
-    LOG_MATRIX(DEBUG, "R at start", R());
-    LOG_MATRIX(DEBUG, "Xhat at start", X_hat());
-
-    Eigen::Matrix<double, 2, 2> position_K;
-    position_K << K(0, 0), K(0, 2), K(1, 0), K(1, 2);
-    Eigen::Matrix<double, 2, 2> velocity_K;
-    velocity_K << K(0, 1), K(0, 3), K(1, 1), K(1, 3);
-
-    Eigen::Matrix<double, 2, 1> position_error;
-    position_error << error(0, 0), error(2, 0);
-    const auto drive_error = T_inverse * position_error;
-    Eigen::Matrix<double, 2, 1> velocity_error;
-    velocity_error << error(1, 0), error(3, 0);
-    LOG_MATRIX(DEBUG, "error", error);
-
-    const auto &poly = U_Poly_;
-    const Eigen::Matrix<double, 4, 2> pos_poly_H = poly.H() * position_K * T;
-    const Eigen::Matrix<double, 4, 1> pos_poly_k =
-        poly.k() - poly.H() * velocity_K * velocity_error;
-    const ::aos::controls::HPolytope<2> pos_poly(pos_poly_H, pos_poly_k);
-
-    Eigen::Matrix<double, 2, 1> adjusted_pos_error;
-    {
-      const auto &P = drive_error;
-
-      Eigen::Matrix<double, 1, 2> L45;
-      L45 << ::aos::sign(P(1, 0)), -::aos::sign(P(0, 0));
-      const double w45 = 0;
-
-      Eigen::Matrix<double, 1, 2> LH;
-      if (::std::abs(P(0, 0)) > ::std::abs(P(1, 0))) {
-        LH << 0, 1;
-      } else {
-        LH << 1, 0;
-      }
-      const double wh = LH.dot(P);
-
-      Eigen::Matrix<double, 2, 2> standard;
-      standard << L45, LH;
-      Eigen::Matrix<double, 2, 1> W;
-      W << w45, wh;
-      const Eigen::Matrix<double, 2, 1> intersection = standard.inverse() * W;
-
-      bool is_inside_h;
-      const auto adjusted_pos_error_h =
-          DoCoerceGoal(pos_poly, LH, wh, drive_error, &is_inside_h);
-      const auto adjusted_pos_error_45 =
-          DoCoerceGoal(pos_poly, L45, w45, intersection, nullptr);
-      if (pos_poly.IsInside(intersection)) {
-        adjusted_pos_error = adjusted_pos_error_h;
-      } else {
-        if (is_inside_h) {
-          if (adjusted_pos_error_h.norm() > adjusted_pos_error_45.norm()) {
-            adjusted_pos_error = adjusted_pos_error_h;
-          } else {
-            adjusted_pos_error = adjusted_pos_error_45;
-          }
-        } else {
-          adjusted_pos_error = adjusted_pos_error_45;
-        }
-      }
-    }
-
-    LOG_MATRIX(DEBUG, "adjusted_pos_error", adjusted_pos_error);
-    mutable_U() =
-        velocity_K * velocity_error + position_K * T * adjusted_pos_error;
-    LOG_MATRIX(DEBUG, "U is now", U());
-  } else {
-    output_was_capped_ = false;
-  }
-}
-
-DrivetrainMotorsSS::DrivetrainMotorsSS()
-    : loop_(new LimitedDrivetrainLoop(
-          ::y2012::control_loops::drivetrain::MakeDrivetrainLoop())),
-      filtered_offset_(0.0),
-      gyro_(0.0),
-      left_goal_(0.0),
-      right_goal_(0.0),
-      raw_left_(0.0),
-      raw_right_(0.0) {
-  // High gear on both.
-  loop_->set_controller_index(3);
-}
-
-void DrivetrainMotorsSS::SetGoal(double left, double left_velocity,
-                                 double right, double right_velocity) {
-  left_goal_ = left;
-  right_goal_ = right;
-  loop_->mutable_R() << left, left_velocity, right, right_velocity;
-}
-void DrivetrainMotorsSS::SetRawPosition(double left, double right) {
-  raw_right_ = right;
-  raw_left_ = left;
-  Eigen::Matrix<double, 2, 1> Y;
-  Y << left + filtered_offset_, right - filtered_offset_;
-  loop_->Correct(Y);
-}
-void DrivetrainMotorsSS::SetPosition(double left, double right, double gyro) {
-  // Decay the offset quickly because this gyro is great.
-  const double offset =
-      (right - left - gyro * 0.5) / 2.0;
-  filtered_offset_ = 0.25 * offset + 0.75 * filtered_offset_;
-  gyro_ = gyro;
-  SetRawPosition(left, right);
-}
-
-void DrivetrainMotorsSS::SetExternalMotors(double left_voltage,
-                                           double right_voltage) {
-  loop_->mutable_U() << left_voltage, right_voltage;
-}
-
-void DrivetrainMotorsSS::Update(bool stop_motors, bool enable_control_loop) {
-  if (enable_control_loop) {
-    loop_->Update(stop_motors);
-  } else {
-    if (stop_motors) {
-      loop_->mutable_U().setZero();
-      loop_->mutable_U_uncapped().setZero();
-    }
-    loop_->UpdateObserver(loop_->U());
-  }
-  ::Eigen::Matrix<double, 4, 1> E = loop_->R() - loop_->X_hat();
-  LOG_MATRIX(DEBUG, "E", E);
-}
-
-double DrivetrainMotorsSS::GetEstimatedRobotSpeed() const {
-  // lets just call the average of left and right velocities close enough
-  return (loop_->X_hat(1, 0) + loop_->X_hat(3, 0)) / 2;
-}
-
-void DrivetrainMotorsSS::SendMotors(
-    ::y2012::control_loops::DrivetrainQueue::Output *output) const {
-  if (output) {
-    output->left_voltage = loop_->U(0, 0);
-    output->right_voltage = loop_->U(1, 0);
-    output->left_high = true;
-    output->right_high = true;
-  }
-}
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
diff --git a/y2012/control_loops/drivetrain/ssdrivetrain.h b/y2012/control_loops/drivetrain/ssdrivetrain.h
deleted file mode 100644
index 76df3fd..0000000
--- a/y2012/control_loops/drivetrain/ssdrivetrain.h
+++ /dev/null
@@ -1,84 +0,0 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
-
-#include "aos/common/controls/polytope.h"
-#include "aos/common/commonmath.h"
-#include "aos/common/logging/matrix_logging.h"
-
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "frc971/control_loops/coerce_goal.h"
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-
-namespace y2012 {
-namespace control_loops {
-namespace drivetrain {
-
-class DrivetrainMotorsSS {
- public:
-  class LimitedDrivetrainLoop : public StateFeedbackLoop<4, 2, 2> {
-   public:
-    LimitedDrivetrainLoop(StateFeedbackLoop<4, 2, 2> &&loop);
-
-    bool output_was_capped() const {
-      return output_was_capped_;
-    }
-
-   private:
-    void CapU() override;
-
-    const ::aos::controls::HPolytope<2> U_Poly_;
-    Eigen::Matrix<double, 2, 2> T, T_inverse;
-    bool output_was_capped_ = false;;
-  };
-
-  DrivetrainMotorsSS();
-
-  void SetGoal(double left, double left_velocity, double right,
-               double right_velocity);
-
-  void SetRawPosition(double left, double right);
-
-  void SetPosition(double left, double right, double gyro);
-
-  void SetExternalMotors(double left_voltage, double right_voltage);
-
-  void Update(bool stop_motors, bool enable_control_loop);
-
-  double GetEstimatedRobotSpeed() const;
-
-  double GetEstimatedLeftEncoder() const {
-    return loop_->X_hat(0, 0);
-  }
-
-  double left_velocity() const { return loop_->X_hat(1, 0); }
-  double right_velocity() const { return loop_->X_hat(3, 0); }
-
-  double GetEstimatedRightEncoder() const {
-    return loop_->X_hat(2, 0);
-  }
-
-  bool OutputWasCapped() const {
-    return loop_->output_was_capped();
-  }
-
-  void SendMotors(
-      ::y2012::control_loops::DrivetrainQueue::Output *output) const;
-
-  const LimitedDrivetrainLoop &loop() const { return *loop_; }
-
- private:
-  ::std::unique_ptr<LimitedDrivetrainLoop> loop_;
-
-  double filtered_offset_;
-  double gyro_;
-  double left_goal_;
-  double right_goal_;
-  double raw_left_;
-  double raw_right_;
-};
-
-}  // namespace drivetrain
-}  // namespace control_loops
-}  // namespace y2012
-
-#endif  // Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
diff --git a/y2012/control_loops/python/drivetrain.py b/y2012/control_loops/python/drivetrain.py
index a57f211..f9004c0 100755
--- a/y2012/control_loops/python/drivetrain.py
+++ b/y2012/control_loops/python/drivetrain.py
@@ -4,7 +4,6 @@
 from frc971.control_loops.python import controls
 import numpy
 import sys
-import argparse
 from matplotlib import pylab
 
 import gflags
@@ -89,8 +88,14 @@
     self.A, self.B = self.ContinuousToDiscrete(
         self.A_continuous, self.B_continuous, self.dt)
 
-    q_pos = 0.12
-    q_vel = 1.0
+    if left_low or right_low:
+      q_pos = 0.12
+      q_vel = 1.0
+    else:
+      q_pos = 0.14
+      q_vel = 0.95
+
+    # Tune the LQR controller
     self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
                            [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
                            [0.0, 0.0, (1.0 / (q_pos ** 2.0)), 0.0],
@@ -100,9 +105,9 @@
                            [0.0, (1.0 / (12.0 ** 2.0))]])
     self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
 
-    glog.debug('DT K %s', name)
-    glog.debug(str(self.K))
+    glog.debug('DT q_pos %f q_vel %s %s', q_pos, q_vel, name)
     glog.debug(str(numpy.linalg.eig(self.A - self.B * self.K)[0]))
+    glog.debug('K %s', repr(self.K))
 
     self.hlp = 0.3
     self.llp = 0.4
@@ -110,6 +115,7 @@
 
     self.U_max = numpy.matrix([[12.0], [12.0]])
     self.U_min = numpy.matrix([[-12.0], [-12.0]])
+
     self.InitializeState()
 
 
@@ -120,12 +126,19 @@
     self.unaugmented_A_continuous = self.A_continuous
     self.unaugmented_B_continuous = self.B_continuous
 
-    # The states are
     # The practical voltage applied to the wheels is
     #   V_left = U_left + left_voltage_error
     #
+    # The states are
     # [left position, left velocity, right position, right velocity,
     #  left voltage error, right voltage error, angular_error]
+    #
+    # The left and right positions are filtered encoder positions and are not
+    # adjusted for heading error.
+    # The turn velocity as computed by the left and right velocities is
+    # adjusted by the gyro velocity.
+    # The angular_error is the angular velocity error between the wheel speed
+    # and the gyro speed.
     self.A_continuous = numpy.matrix(numpy.zeros((7, 7)))
     self.B_continuous = numpy.matrix(numpy.zeros((7, 2)))
     self.A_continuous[0:4,0:4] = self.unaugmented_A_continuous
@@ -170,15 +183,34 @@
 
     self.L = self.A * self.KalmanGain
 
-    # We need a nothing controller for the autogen code to be happy.
+    unaug_K = self.K
+
+    # Implement a nice closed loop controller for use by the closed loop
+    # controller.
     self.K = numpy.matrix(numpy.zeros((self.B.shape[1], self.A.shape[0])))
+    self.K[0:2, 0:4] = unaug_K
+    self.K[0, 4] = 1.0
+    self.K[1, 5] = 1.0
+
+    self.Qff = numpy.matrix(numpy.zeros((4, 4)))
+    qff_pos = 0.005
+    qff_vel = 1.00
+    self.Qff[0, 0] = 1.0 / qff_pos ** 2.0
+    self.Qff[1, 1] = 1.0 / qff_vel ** 2.0
+    self.Qff[2, 2] = 1.0 / qff_pos ** 2.0
+    self.Qff[3, 3] = 1.0 / qff_vel ** 2.0
+    self.Kff = numpy.matrix(numpy.zeros((2, 7)))
+    self.Kff[0:2, 0:4] = controls.TwoStateFeedForwards(self.B[0:4,:], self.Qff)
+
+    self.InitializeState()
 
 
 def main(argv):
   argv = FLAGS(argv)
+  glog.init()
 
   # Simulate the response of the system to a step input.
-  drivetrain = Drivetrain()
+  drivetrain = Drivetrain(left_low=False, right_low=False)
   simulated_left = []
   simulated_right = []
   for _ in xrange(100):
@@ -189,24 +221,33 @@
   if FLAGS.plot:
     pylab.plot(range(100), simulated_left)
     pylab.plot(range(100), simulated_right)
+    pylab.suptitle('Acceleration Test')
     pylab.show()
 
   # Simulate forwards motion.
-  drivetrain = Drivetrain()
+  drivetrain = Drivetrain(left_low=False, right_low=False)
   close_loop_left = []
   close_loop_right = []
+  left_power = []
+  right_power = []
   R = numpy.matrix([[1.0], [0.0], [1.0], [0.0]])
-  for _ in xrange(100):
+  for _ in xrange(300):
     U = numpy.clip(drivetrain.K * (R - drivetrain.X_hat),
                    drivetrain.U_min, drivetrain.U_max)
     drivetrain.UpdateObserver(U)
     drivetrain.Update(U)
     close_loop_left.append(drivetrain.X[0, 0])
     close_loop_right.append(drivetrain.X[2, 0])
+    left_power.append(U[0, 0])
+    right_power.append(U[1, 0])
 
   if FLAGS.plot:
-    pylab.plot(range(100), close_loop_left)
-    pylab.plot(range(100), close_loop_right)
+    pylab.plot(range(300), close_loop_left, label='left position')
+    pylab.plot(range(300), close_loop_right, label='right position')
+    pylab.plot(range(300), left_power, label='left power')
+    pylab.plot(range(300), right_power, label='right power')
+    pylab.suptitle('Linear Move')
+    pylab.legend()
     pylab.show()
 
   # Try turning in place
@@ -225,6 +266,7 @@
   if FLAGS.plot:
     pylab.plot(range(100), close_loop_left)
     pylab.plot(range(100), close_loop_right)
+    pylab.suptitle('Angular Move')
     pylab.show()
 
   # Try turning just one side.
@@ -243,6 +285,7 @@
   if FLAGS.plot:
     pylab.plot(range(100), close_loop_left)
     pylab.plot(range(100), close_loop_right)
+    pylab.suptitle('Pivot')
     pylab.show()
 
   # Write the generated constants out to a file.
@@ -296,6 +339,10 @@
           drivetrain_low_low.Kv))
     dog_loop_writer.AddConstant(control_loop.Constant("kT", "%f",
           drivetrain_low_low.Kt))
+    dog_loop_writer.AddConstant(control_loop.Constant("kLowGearRatio", "%f",
+          drivetrain_low_low.G_low))
+    dog_loop_writer.AddConstant(control_loop.Constant("kHighGearRatio", "%f",
+          drivetrain_high_high.G_high))
 
     dog_loop_writer.Write(argv[1], argv[2])
 
diff --git a/y2012/joystick_reader.cc b/y2012/joystick_reader.cc
index b977672..24c1b6c 100644
--- a/y2012/joystick_reader.cc
+++ b/y2012/joystick_reader.cc
@@ -10,10 +10,10 @@
 #include "aos/common/time.h"
 #include "aos/common/actions/actions.h"
 
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
 #include "y2012/control_loops/accessories/accessories.q.h"
 
-using ::y2012::control_loops::drivetrain_queue;
+using ::frc971::control_loops::drivetrain_queue;
 using ::y2012::control_loops::accessories_queue;
 
 using ::aos::input::driver_station::ButtonLocation;
diff --git a/y2012/wpilib/BUILD b/y2012/wpilib/BUILD
index afb85e4..b2e6934 100644
--- a/y2012/wpilib/BUILD
+++ b/y2012/wpilib/BUILD
@@ -6,30 +6,30 @@
     'wpilib_interface.cc',
   ],
   deps = [
-    '//aos/linux_code:init',
-    '//aos/common:stl_mutex',
-    '//aos/common/logging',
-    '//third_party:wpilib',
-    '//y2012/control_loops/drivetrain:drivetrain_queue',
-    '//y2012/control_loops/accessories:accessories_queue',
     '//aos/common/controls:control_loop',
-    '//aos/common/util:log_interval',
-    '//aos/common:time',
+    '//aos/common/logging',
     '//aos/common/logging:queue_logging',
     '//aos/common/messages:robot_state',
+    '//aos/common/util:log_interval',
     '//aos/common/util:phased_loop',
     '//aos/common/util:wrapping_counter',
-    '//frc971/wpilib:joystick_sender',
-    '//frc971/wpilib:loop_output_handler',
-    '//frc971/wpilib:buffered_pcm',
-    '//frc971/wpilib:gyro_sender',
-    '//frc971/wpilib:dma_edge_counting',
-    '//frc971/wpilib:interrupt_edge_counting',
-    '//frc971/wpilib:wpilib_robot_base',
-    '//frc971/wpilib:encoder_and_potentiometer',
+    '//aos/common:stl_mutex',
+    '//aos/common:time',
+    '//aos/linux_code:init',
+    '//frc971/control_loops/drivetrain:drivetrain_queue',
     '//frc971/control_loops:queues',
-    '//frc971/wpilib:logging_queue',
-    '//frc971/wpilib:wpilib_interface',
+    '//frc971/wpilib:buffered_pcm',
     '//frc971/wpilib:dma',
+    '//frc971/wpilib:dma_edge_counting',
+    '//frc971/wpilib:encoder_and_potentiometer',
+    '//frc971/wpilib:gyro_sender',
+    '//frc971/wpilib:interrupt_edge_counting',
+    '//frc971/wpilib:joystick_sender',
+    '//frc971/wpilib:logging_queue',
+    '//frc971/wpilib:loop_output_handler',
+    '//frc971/wpilib:wpilib_interface',
+    '//frc971/wpilib:wpilib_robot_base',
+    '//third_party:wpilib',
+    '//y2012/control_loops/accessories:accessories_queue',
   ],
 )
diff --git a/y2012/wpilib/wpilib_interface.cc b/y2012/wpilib/wpilib_interface.cc
index 290f067..dd0f7ca 100644
--- a/y2012/wpilib/wpilib_interface.cc
+++ b/y2012/wpilib/wpilib_interface.cc
@@ -31,26 +31,25 @@
 #include "aos/linux_code/init.h"
 #include "aos/common/messages/robot_state.q.h"
 
-#include "y2012/control_loops/drivetrain/drivetrain.q.h"
-#include "y2012/control_loops/accessories/accessories.q.h"
-
-#include "frc971/wpilib/joystick_sender.h"
-#include "frc971/wpilib/loop_output_handler.h"
-#include "frc971/wpilib/buffered_solenoid.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
 #include "frc971/wpilib/buffered_pcm.h"
-#include "frc971/wpilib/gyro_sender.h"
-#include "frc971/wpilib/dma_edge_counting.h"
-#include "frc971/wpilib/interrupt_edge_counting.h"
-#include "frc971/wpilib/encoder_and_potentiometer.h"
-#include "frc971/wpilib/logging.q.h"
-#include "frc971/wpilib/wpilib_interface.h"
+#include "frc971/wpilib/buffered_solenoid.h"
 #include "frc971/wpilib/dma.h"
+#include "frc971/wpilib/dma_edge_counting.h"
+#include "frc971/wpilib/encoder_and_potentiometer.h"
+#include "frc971/wpilib/gyro_sender.h"
+#include "frc971/wpilib/interrupt_edge_counting.h"
+#include "frc971/wpilib/joystick_sender.h"
+#include "frc971/wpilib/logging.q.h"
+#include "frc971/wpilib/loop_output_handler.h"
+#include "frc971/wpilib/wpilib_interface.h"
+#include "y2012/control_loops/accessories/accessories.q.h"
 
 #ifndef M_PI
 #define M_PI 3.14159265358979323846
 #endif
 
-using ::y2012::control_loops::drivetrain_queue;
+using ::frc971::control_loops::drivetrain_queue;
 using ::y2012::control_loops::accessories_queue;
 
 namespace y2012 {
@@ -235,7 +234,7 @@
 
   ::std::unique_ptr<Compressor> compressor_;
 
-  ::aos::Queue<::y2012::control_loops::DrivetrainQueue::Output> drivetrain_;
+  ::aos::Queue<::frc971::control_loops::DrivetrainQueue::Output> drivetrain_;
   ::aos::Queue<::y2012::control_loops::AccessoriesQueue::Message> accessories_;
 
   ::std::atomic<bool> run_{true};
@@ -253,11 +252,11 @@
 
  private:
   virtual void Read() override {
-    ::y2012::control_loops::drivetrain_queue.output.FetchAnother();
+    drivetrain_queue.output.FetchAnother();
   }
 
   virtual void Write() override {
-    auto &queue = ::y2012::control_loops::drivetrain_queue.output;
+    auto &queue = drivetrain_queue.output;
     LOG_STRUCT(DEBUG, "will output", *queue);
     left_drivetrain_talon_->Set(-queue->left_voltage / 12.0);
     right_drivetrain_talon_->Set(queue->right_voltage / 12.0);
diff --git a/y2014/control_loops/python/drivetrain.py b/y2014/control_loops/python/drivetrain.py
index 7413158..dae2dd2 100755
--- a/y2014/control_loops/python/drivetrain.py
+++ b/y2014/control_loops/python/drivetrain.py
@@ -120,10 +120,10 @@
     self.unaugmented_A_continuous = self.A_continuous
     self.unaugmented_B_continuous = self.B_continuous
 
-    # The states are
     # The practical voltage applied to the wheels is
     #   V_left = U_left + left_voltage_error
     #
+    # The states are
     # [left position, left velocity, right position, right velocity,
     #  left voltage error, right voltage error, angular_error]
     self.A_continuous = numpy.matrix(numpy.zeros((7, 7)))
diff --git a/y2014_bot3/control_loops/python/drivetrain.py b/y2014_bot3/control_loops/python/drivetrain.py
index 0dc2466..029fcbb 100755
--- a/y2014_bot3/control_loops/python/drivetrain.py
+++ b/y2014_bot3/control_loops/python/drivetrain.py
@@ -96,6 +96,7 @@
       q_pos = 0.14
       q_vel = 0.95
 
+    # Tune the LQR controller
     self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
                            [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
                            [0.0, 0.0, (1.0 / (q_pos ** 2.0)), 0.0],
@@ -126,10 +127,10 @@
     self.unaugmented_A_continuous = self.A_continuous
     self.unaugmented_B_continuous = self.B_continuous
 
-    # The states are
     # The practical voltage applied to the wheels is
     #   V_left = U_left + left_voltage_error
     #
+    # The states are
     # [left position, left velocity, right position, right velocity,
     #  left voltage error, right voltage error, angular_error]
     #
diff --git a/y2016/control_loops/python/drivetrain.py b/y2016/control_loops/python/drivetrain.py
index 46f0600..9381eb2 100755
--- a/y2016/control_loops/python/drivetrain.py
+++ b/y2016/control_loops/python/drivetrain.py
@@ -95,6 +95,7 @@
       q_pos = 0.14
       q_vel = 0.95
 
+    # Tune the LQR controller
     self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
                            [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
                            [0.0, 0.0, (1.0 / (q_pos ** 2.0)), 0.0],
@@ -125,10 +126,10 @@
     self.unaugmented_A_continuous = self.A_continuous
     self.unaugmented_B_continuous = self.B_continuous
 
-    # The states are
     # The practical voltage applied to the wheels is
     #   V_left = U_left + left_voltage_error
     #
+    # The states are
     # [left position, left velocity, right position, right velocity,
     #  left voltage error, right voltage error, angular_error]
     #
diff --git a/y2016_bot3/control_loops/python/drivetrain.py b/y2016_bot3/control_loops/python/drivetrain.py
index 738031c..7f470d9 100755
--- a/y2016_bot3/control_loops/python/drivetrain.py
+++ b/y2016_bot3/control_loops/python/drivetrain.py
@@ -96,6 +96,7 @@
       q_pos = 0.14
       q_vel = 0.95
 
+    # Tune the LQR controller
     self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
                            [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
                            [0.0, 0.0, (1.0 / (q_pos ** 2.0)), 0.0],
@@ -126,10 +127,10 @@
     self.unaugmented_A_continuous = self.A_continuous
     self.unaugmented_B_continuous = self.B_continuous
 
-    # The states are
     # The practical voltage applied to the wheels is
     #   V_left = U_left + left_voltage_error
     #
+    # The states are
     # [left position, left velocity, right position, right velocity,
     #  left voltage error, right voltage error, angular_error]
     #