Added column controller.

Change-Id: I4b0eaf36bfab6246b1822a36620c2d1325582d35
diff --git a/y2017/control_loops/python/BUILD b/y2017/control_loops/python/BUILD
index cb599a3..dc5e021 100644
--- a/y2017/control_loops/python/BUILD
+++ b/y2017/control_loops/python/BUILD
@@ -100,3 +100,42 @@
     '//frc971/control_loops/python:controls',
   ]
 )
+
+py_library(
+  name = 'turret_lib',
+  srcs = [
+    'turret.py',
+  ],
+  deps = [
+    '//aos/common/util:py_trapezoid_profile',
+    '//external:python-gflags',
+    '//external:python-glog',
+    '//frc971/control_loops/python:controls',
+  ]
+)
+
+py_library(
+  name = 'indexer_lib',
+  srcs = [
+    'indexer.py',
+  ],
+  deps = [
+    '//external:python-gflags',
+    '//external:python-glog',
+    '//frc971/control_loops/python:controls',
+  ]
+)
+
+py_binary(
+  name = 'column',
+  srcs = [
+    'column.py',
+  ],
+  deps = [
+    ':turret_lib',
+    ':indexer_lib',
+    '//external:python-gflags',
+    '//external:python-glog',
+    '//frc971/control_loops/python:controls',
+  ],
+)
diff --git a/y2017/control_loops/python/column.py b/y2017/control_loops/python/column.py
new file mode 100644
index 0000000..ebb2f60
--- /dev/null
+++ b/y2017/control_loops/python/column.py
@@ -0,0 +1,377 @@
+#!/usr/bin/python
+
+from aos.common.util.trapezoid_profile import TrapezoidProfile
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+from y2017.control_loops.python import turret
+from y2017.control_loops.python import indexer
+import numpy
+import sys
+import matplotlib
+from matplotlib import pylab
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+try:
+  gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+  pass
+
+
+# TODO(austin): Shut down with no counts on the turret.
+
+class ColumnController(control_loop.ControlLoop):
+  def __init__(self, name='Column'):
+    super(ColumnController, self).__init__(name)
+    self.turret = turret.Turret(name + 'Turret')
+    self.indexer = indexer.Indexer(name + 'Indexer')
+
+    # Control loop time step
+    self.dt = 0.005
+
+    # State is [position_indexer,
+    #           velocity_indexer,
+    #           position_shooter,
+    #           velocity_shooter]
+    # Input is [volts_indexer, volts_shooter]
+    self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+    self.B_continuous = numpy.matrix(numpy.zeros((3, 2)))
+
+    self.A_continuous[1 - 1, 1 - 1] = -(self.indexer.Kt / self.indexer.Kv / (self.indexer.J * self.indexer.resistance * self.indexer.G * self.indexer.G) +
+                                self.turret.Kt / self.turret.Kv / (self.indexer.J * self.turret.resistance * self.turret.G * self.turret.G))
+    self.A_continuous[1 - 1, 3 - 1] = self.turret.Kt / self.turret.Kv / (self.indexer.J * self.turret.resistance * self.turret.G * self.turret.G)
+    self.B_continuous[1 - 1, 0] = self.indexer.Kt / (self.indexer.J * self.indexer.resistance * self.indexer.G)
+    self.B_continuous[1 - 1, 1] = -self.turret.Kt / (self.indexer.J * self.turret.resistance * self.turret.G)
+
+    self.A_continuous[2 - 1, 3 - 1] = 1
+
+    self.A_continuous[3 - 1, 1 - 1] = self.turret.Kt / self.turret.Kv / (self.turret.J * self.turret.resistance * self.turret.G * self.turret.G)
+    self.A_continuous[3 - 1, 3 - 1] = -self.turret.Kt / self.turret.Kv / (self.turret.J * self.turret.resistance * self.turret.G * self.turret.G)
+
+    self.B_continuous[3 - 1, 1] = self.turret.Kt / (self.turret.J * self.turret.resistance * self.turret.G)
+
+    self.C = numpy.matrix([[1, 0, 0], [0, 1, 0]])
+    self.D = numpy.matrix([[0, 0], [0, 0]])
+
+    self.A, self.B = self.ContinuousToDiscrete(
+        self.A_continuous, self.B_continuous, self.dt)
+
+    q_pos = 0.015
+    q_vel = 0.3
+    self.Q = numpy.matrix([[(1.0 / (q_vel ** 2.0)), 0.0, 0.0],
+                           [0.0, (1.0 / (q_pos ** 2.0)), 0.0],
+                           [0.0, 0.0, (1.0 / (q_vel ** 2.0))]])
+
+    self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0)), 0.0],
+                           [0.0, (1.0 / (12.0 ** 2.0))]])
+    self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+    q_vel_indexer_ff = 0.000005
+    q_pos_ff = 0.0000005
+    q_vel_ff = 0.00008
+    self.Qff = numpy.matrix([[(1.0 / (q_vel_indexer_ff ** 2.0)), 0.0, 0.0],
+                             [0.0, (1.0 / (q_pos_ff ** 2.0)), 0.0],
+                             [0.0, 0.0, (1.0 / (q_vel_ff ** 2.0))]])
+
+    self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
+
+    self.U_max = numpy.matrix([[12.0], [12.0]])
+    self.U_min = numpy.matrix([[-12.0], [-12.0]])
+
+    self.InitializeState()
+
+
+class Column(ColumnController):
+  def __init__(self, name='Column'):
+    super(Column, self).__init__(name)
+    A_continuous = numpy.matrix(numpy.zeros((4, 4)))
+    B_continuous = numpy.matrix(numpy.zeros((4, 2)))
+
+    A_continuous[0, 1] = 1
+    A_continuous[1:, 1:] = self.A_continuous
+    B_continuous[1:, :] = self.B_continuous
+
+    self.A_continuous = A_continuous
+    self.B_continuous = B_continuous
+
+    self.A, self.B = self.ContinuousToDiscrete(
+        self.A_continuous, self.B_continuous, self.dt)
+
+    glog.debug('Eig is ' + repr(numpy.linalg.eig(self.A_continuous)))
+
+    self.C = numpy.matrix([[1, 0, 0, 0], [-1, 0, 1, 0]])
+    self.D = numpy.matrix([[0, 0], [0, 0]])
+
+    orig_K = self.K
+    self.K = numpy.matrix(numpy.zeros((2, 4)))
+    self.K[:, 1:] = orig_K
+
+    orig_Kff = self.Kff
+    self.Kff = numpy.matrix(numpy.zeros((2, 4)))
+    self.Kff[:, 1:] = orig_Kff
+
+    q_pos = 0.12
+    q_vel = 2.00
+    self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0],
+                           [0.0, (q_vel ** 2.0), 0.0, 0.0],
+                           [0.0, 0.0, (q_pos ** 2.0), 0.0],
+                           [0.0, 0.0, 0.0, (q_vel ** 2.0)]])
+
+    r_pos = 0.05
+    self.R = numpy.matrix([[(r_pos ** 2.0), 0.0],
+                           [0.0, (r_pos ** 2.0)]])
+
+    self.KalmanGain, self.Q_steady = controls.kalman(
+        A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+    self.L = self.A * self.KalmanGain
+
+    self.InitializeState()
+
+
+class IntegralColumn(Column):
+  def __init__(self, name='IntegralColumn', voltage_error_noise=None):
+    super(IntegralColumn, self).__init__(name)
+
+    A_continuous = numpy.matrix(numpy.zeros((6, 6)))
+    A_continuous[0:4, 0:4] = self.A_continuous
+    A_continuous[0:4:, 4:6] = self.B_continuous
+
+    B_continuous = numpy.matrix(numpy.zeros((6, 2)))
+    B_continuous[0:4, :] = self.B_continuous
+
+    self.A_continuous = A_continuous
+    self.B_continuous = B_continuous
+    glog.debug('A_continuous: ' + repr(self.A_continuous))
+    glog.debug('B_continuous: ' + repr(self.B_continuous))
+
+    self.A, self.B = self.ContinuousToDiscrete(
+        self.A_continuous, self.B_continuous, self.dt)
+
+    glog.debug('Eig is ' + repr(numpy.linalg.eig(self.A_continuous)))
+
+    C = numpy.matrix(numpy.zeros((2, 6)))
+    C[0:2, 0:4] = self.C
+    self.C = C
+    glog.debug('C is ' + repr(self.C))
+
+    self.D = numpy.matrix([[0, 0], [0, 0]])
+
+    orig_K = self.K
+    self.K = numpy.matrix(numpy.zeros((2, 6)))
+    self.K[:, 0:4] = orig_K
+    self.K[0, 4] = 1
+    self.K[1, 5] = 1
+
+    orig_Kff = self.Kff
+    self.Kff = numpy.matrix(numpy.zeros((2, 6)))
+    self.Kff[:, 0:4] = orig_Kff
+
+    q_pos = 0.12
+    q_vel = 2.00
+    q_voltage = 4.0
+    if voltage_error_noise is not None:
+      q_voltage = voltage_error_noise
+
+    self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0, 0.0, 0.0],
+                           [0.0, (q_vel ** 2.0), 0.0, 0.0, 0.0, 0.0],
+                           [0.0, 0.0, (q_pos ** 2.0), 0.0, 0.0, 0.0],
+                           [0.0, 0.0, 0.0, (q_vel ** 2.0), 0.0, 0.0],
+                           [0.0, 0.0, 0.0, 0.0, (q_voltage ** 2.0), 0.0],
+                           [0.0, 0.0, 0.0, 0.0, 0.0, (q_voltage ** 2.0)]])
+
+    r_pos = 0.05
+    self.R = numpy.matrix([[(r_pos ** 2.0), 0.0],
+                           [0.0, (r_pos ** 2.0)]])
+
+    self.KalmanGain, self.Q_steady = controls.kalman(
+        A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+    self.L = self.A * self.KalmanGain
+
+    self.InitializeState()
+
+
+class ScenarioPlotter(object):
+  def __init__(self):
+    # Various lists for graphing things.
+    self.t = []
+    self.xi = []
+    self.xt = []
+    self.vi = []
+    self.vt = []
+    self.ai = []
+    self.at = []
+    self.x_hat = []
+    self.ui = []
+    self.ut = []
+    self.ui_fb = []
+    self.ut_fb = []
+    self.offseti = []
+    self.offsett = []
+    self.turret_error = []
+
+  def run_test(self, column, end_goal,
+             controller_column,
+             observer_column=None,
+             iterations=200):
+    """Runs the column plant with an initial condition and goal.
+
+      Args:
+        column: column object to use.
+        end_goal: end_goal state.
+        controller_column: Intake object to get K from, or None if we should
+            use column.
+        observer_column: Intake object to use for the observer, or None if we should
+            use the actual state.
+        iterations: Number of timesteps to run the model for.
+    """
+
+    if controller_column is None:
+      controller_column = column
+
+    vbat = 12.0
+
+    if self.t:
+      initial_t = self.t[-1] + column.dt
+    else:
+      initial_t = 0
+
+    goal = numpy.concatenate((column.X, numpy.matrix(numpy.zeros((2, 1)))), axis=0)
+
+    profile = TrapezoidProfile(column.dt)
+    profile.set_maximum_acceleration(10.0)
+    profile.set_maximum_velocity(3.0)
+    profile.SetGoal(goal[2, 0])
+
+    U_last = numpy.matrix(numpy.zeros((2, 1)))
+    for i in xrange(iterations):
+      observer_column.Y = column.Y
+      observer_column.CorrectObserver(U_last)
+
+      self.offseti.append(observer_column.X_hat[4, 0])
+      self.offsett.append(observer_column.X_hat[5, 0])
+      self.x_hat.append(observer_column.X_hat[0, 0])
+
+      next_goal = numpy.concatenate(
+          (end_goal[0:2, :],
+           profile.Update(end_goal[2, 0], end_goal[3, 0]),
+           end_goal[4:6, :]),
+          axis=0)
+
+      ff_U = controller_column.Kff * (next_goal - observer_column.A * goal)
+      fb_U = controller_column.K * (goal - observer_column.X_hat)
+      self.turret_error.append((goal[2, 0] - column.X[2, 0]) * 100.0)
+      self.ui_fb.append(fb_U[0, 0])
+      self.ut_fb.append(fb_U[1, 0])
+
+      U_uncapped = ff_U + fb_U
+
+      U = U_uncapped.copy()
+      U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+      U[1, 0] = numpy.clip(U[1, 0], -vbat, vbat)
+      self.xi.append(column.X[0, 0])
+      self.xt.append(column.X[2, 0])
+
+      if self.vi:
+        last_vi = self.vi[-1]
+      else:
+        last_vi = 0
+      if self.vt:
+        last_vt = self.vt[-1]
+      else:
+        last_vt = 0
+
+      self.vi.append(column.X[1, 0])
+      self.vt.append(column.X[3, 0])
+      self.ai.append((self.vi[-1] - last_vi) / column.dt)
+      self.at.append((self.vt[-1] - last_vt) / column.dt)
+
+      offset = 0.0
+      if i > 100:
+        offset = 1.0
+      column.Update(U + numpy.matrix([[offset], [0.0]]))
+
+      observer_column.PredictObserver(U)
+
+      self.t.append(initial_t + i * column.dt)
+      self.ui.append(U[0, 0])
+      self.ut.append(U[1, 0])
+
+      ff_U -= U_uncapped - U
+      goal = controller_column.A * goal + controller_column.B * ff_U
+
+      if U[1, 0] != U_uncapped[1, 0]:
+        profile.MoveCurrentState(
+            numpy.matrix([[goal[2, 0]], [goal[3, 0]]]))
+
+    glog.debug('Time: %f', self.t[-1])
+    glog.debug('goal_error %s', repr(end_goal - goal))
+    glog.debug('error %s', repr(observer_column.X_hat - end_goal))
+
+  def Plot(self):
+    pylab.subplot(3, 1, 1)
+    pylab.plot(self.t, self.xi, label='xi')
+    pylab.plot(self.t, self.xt, label='xt')
+    pylab.plot(self.t, self.x_hat, label='x_hat')
+    pylab.plot(self.t, self.turret_error, label='turret_error')
+    pylab.legend()
+
+    pylab.subplot(3, 1, 2)
+    pylab.plot(self.t, self.ui, label='ui')
+    pylab.plot(self.t, self.ui_fb, label='ui_fb')
+    pylab.plot(self.t, self.ut, label='ut')
+    pylab.plot(self.t, self.ut_fb, label='ut_fb')
+    pylab.plot(self.t, self.offseti, label='voltage_offseti')
+    pylab.plot(self.t, self.offsett, label='voltage_offsett')
+    pylab.legend()
+
+    pylab.subplot(3, 1, 3)
+    pylab.plot(self.t, self.ai, label='ai')
+    pylab.plot(self.t, self.at, label='at')
+    pylab.plot(self.t, self.vi, label='vi')
+    pylab.plot(self.t, self.vt, label='vt')
+    pylab.legend()
+
+    pylab.show()
+
+
+def main(argv):
+  scenario_plotter = ScenarioPlotter()
+
+  column = Column()
+  column_controller = IntegralColumn()
+  observer_column = IntegralColumn()
+
+  initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
+  R = numpy.matrix([[0.0], [10.0], [5.0], [0.0], [0.0], [0.0]])
+  scenario_plotter.run_test(column, end_goal=R, controller_column=column_controller,
+                            observer_column=observer_column, iterations=600)
+
+  if FLAGS.plot:
+    scenario_plotter.Plot()
+
+  if len(argv) != 7:
+    glog.fatal('Expected .h file name and .cc file names')
+  else:
+    namespaces = ['y2017', 'control_loops', 'superstructure', 'column']
+    column = Column('Column')
+    loop_writer = control_loop.ControlLoopWriter('Column', [column],
+                                                 namespaces=namespaces)
+    loop_writer.Write(argv[1], argv[2])
+
+    integral_column = IntegralColumn('IntegralColumn')
+    integral_loop_writer = control_loop.ControlLoopWriter(
+        'IntegralColumn', [integral_column], namespaces=namespaces)
+    integral_loop_writer.Write(argv[3], argv[4])
+
+    stuck_integral_column = IntegralColumn('StuckIntegralColumn', voltage_error_noise=8.0)
+    stuck_integral_loop_writer = control_loop.ControlLoopWriter(
+        'StuckIntegralColumn', [stuck_integral_column], namespaces=namespaces)
+    stuck_integral_loop_writer.Write(argv[5], argv[6])
+
+
+if __name__ == '__main__':
+  argv = FLAGS(sys.argv)
+  glog.init()
+  sys.exit(main(argv))
diff --git a/y2017/control_loops/python/indexer.py b/y2017/control_loops/python/indexer.py
index 1818d62..f6a2379 100755
--- a/y2017/control_loops/python/indexer.py
+++ b/y2017/control_loops/python/indexer.py
@@ -11,7 +11,10 @@
 
 FLAGS = gflags.FLAGS
 
-gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+try:
+  gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+  pass
 
 gflags.DEFINE_bool('stall', False, 'If true, stall the indexer.')
 
@@ -40,8 +43,8 @@
     self.G_inner = (12.0 / 48.0) * (18.0 / 36.0) * (12.0 / 84.0)
     self.G_outer = (12.0 / 48.0) * (18.0 / 36.0) * (24.0 / 420.0)
 
-    # Motor inertia in kg * m^2
-    self.motor_inertia = 0.000006
+    # Motor inertia in kg m^2
+    self.motor_inertia = 0.00001187
 
     # The output coordinate system is in radians for the inner part of the
     # indexer.
@@ -51,14 +54,13 @@
         self.J_inner * self.G_inner * self.G_inner +
         self.J_outer * self.G_outer * self.G_outer) / (self.G_inner * self.G_inner) + \
         self.motor_inertia * ((1.0 / self.G_inner) ** 2.0)
-    glog.debug('J is %f', self.J)
     self.G = self.G_inner
 
     # Resistance of the motor, divided by 2 to account for the 2 motors
-    self.R = 12.0 / self.stall_current
+    self.resistance = 12.0 / self.stall_current
     # Motor velocity constant
     self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
-              (12.0 - self.R * self.free_current))
+              (12.0 - self.resistance * self.free_current))
     # Torque constant
     self.Kt = self.stall_torque / self.stall_current
     # Control loop time step
@@ -67,9 +69,9 @@
     # State feedback matrices
     # [angular velocity]
     self.A_continuous = numpy.matrix(
-        [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.R)]])
+        [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.resistance)]])
     self.B_continuous = numpy.matrix(
-        [[self.Kt / (self.J * self.G * self.R)]])
+        [[self.Kt / (self.J * self.G * self.resistance)]])
     self.C = numpy.matrix([[1]])
     self.D = numpy.matrix([[0]])
 
@@ -77,10 +79,6 @@
         self.A_continuous, self.B_continuous, self.dt)
 
     self.PlaceControllerPoles([.75])
-    glog.debug('K: %s', repr(self.K))
-
-    glog.debug('Poles are %s',
-               repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
 
     self.PlaceObserverPoles([0.3])
 
diff --git a/y2017/control_loops/python/intake.py b/y2017/control_loops/python/intake.py
index 712dfa4..ae209c3 100755
--- a/y2017/control_loops/python/intake.py
+++ b/y2017/control_loops/python/intake.py
@@ -99,13 +99,6 @@
     glog.debug('Poles are %s',
               repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
 
-    self.rpl = 0.30
-    self.ipl = 0.10
-    self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
-                             self.rpl - 1j * self.ipl])
-
-    glog.debug('L is %s', repr(self.L))
-
     q_pos = 0.10
     q_vel = 1.65
     self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
diff --git a/y2017/control_loops/python/turret.py b/y2017/control_loops/python/turret.py
index a69e3e1..4bfa245 100755
--- a/y2017/control_loops/python/turret.py
+++ b/y2017/control_loops/python/turret.py
@@ -21,27 +21,27 @@
   def __init__(self, name='Turret'):
     super(Turret, self).__init__(name)
     # Stall Torque in N m
-    self.stall_torque = 0.43
+    self.stall_torque = 0.71
     # Stall Current in Amps
-    self.stall_current = 53
-    self.free_speed_rpm = 13180
+    self.stall_current = 134
+    self.free_speed_rpm = 18730.0
     # Free Speed in rotations/second.
     self.free_speed = self.free_speed_rpm / 60.0
     # Free Current in Amps
-    self.free_current = 1.8
+    self.free_current = 0.7
 
     # Resistance of the motor
-    self.R = 12.0 / self.stall_current
+    self.resistance = 12.0 / self.stall_current
     # Motor velocity constant
     self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
-               (12.0 - self.R * self.free_current))
+               (12.0 - self.resistance * self.free_current))
     # Torque constant
     self.Kt = self.stall_torque / self.stall_current
     # Gear ratio
-    self.G = (1.0 / 7.0) * (1.0 / 5.0) * (16.0 / 92.0)
+    self.G = (12.0 / 60.0) * (11.0 / 94.0)
 
     # Motor inertia in kg * m^2
-    self.motor_inertia = 0.000006
+    self.motor_inertia = 0.00001187
 
     # Moment of inertia, measured in CAD.
     # Extra mass to compensate for friction is added on.
@@ -53,8 +53,8 @@
     # State is [position, velocity]
     # Input is [Voltage]
 
-    C1 = self.Kt / (self.R  * self.J * self.Kv * self.G * self.G)
-    C2 = self.Kt / (self.J * self.R * self.G)
+    C1 = self.Kt / (self.resistance * self.J * self.Kv * self.G * self.G)
+    C2 = self.Kt / (self.J * self.resistance * self.G)
 
     self.A_continuous = numpy.matrix(
         [[0, 1],
@@ -93,10 +93,6 @@
 
     self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
 
-    glog.debug('K %s', repr(self.K))
-    glog.debug('Poles are %s',
-              repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
-
     q_pos = 0.10
     q_vel = 1.65
     self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
@@ -107,10 +103,7 @@
 
     self.KalmanGain, self.Q_steady = controls.kalman(
         A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
-
-    glog.debug('Kal %s', repr(self.KalmanGain))
     self.L = self.A * self.KalmanGain
-    glog.debug('KalL is %s', repr(self.L))
 
     # The box formed by U_min and U_max must encompass all possible values,
     # or else Austin's code gets angry.