Added control loops for all the subsystems.
Change-Id: Ie693940734fe0b45f010bb3da0bfb0ec3ba719f5
diff --git a/y2017/control_loops/python/BUILD b/y2017/control_loops/python/BUILD
index 56a9f3d..cb599a3 100644
--- a/y2017/control_loops/python/BUILD
+++ b/y2017/control_loops/python/BUILD
@@ -37,3 +37,66 @@
'//frc971/control_loops/python:controls',
],
)
+
+py_binary(
+ name = 'shooter',
+ srcs = [
+ 'shooter.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'indexer',
+ srcs = [
+ 'indexer.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'intake',
+ srcs = [
+ 'intake.py',
+ ],
+ deps = [
+ '//aos/common/util:py_trapezoid_profile',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'turret',
+ srcs = [
+ 'turret.py',
+ ],
+ deps = [
+ '//aos/common/util:py_trapezoid_profile',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'hood',
+ srcs = [
+ 'hood.py',
+ ],
+ deps = [
+ '//aos/common/util:py_trapezoid_profile',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
diff --git a/y2017/control_loops/python/drivetrain.py b/y2017/control_loops/python/drivetrain.py
index a9e5101..17e0079 100755
--- a/y2017/control_loops/python/drivetrain.py
+++ b/y2017/control_loops/python/drivetrain.py
@@ -28,13 +28,13 @@
# Free Current in Amps
self.free_current = 4.7 * self.num_motors
# Moment of inertia of the drivetrain in kg m^2
- self.J = 1.5
+ self.J = 2.0
# Mass of the robot, in kg.
- self.m = 50
+ self.m = 24
# Radius of the robot, in meters (requires tuning by hand)
- self.rb = 0.6 / 2.0
+ self.rb = 0.59055 / 2.0
# Radius of the wheels, in meters.
- self.r = 0.041275
+ self.r = 0.08255 / 2.0
# Resistance of the motor, divided by the number of motors.
self.resistance = 12.0 / self.stall_current
# Motor velocity constant
diff --git a/y2017/control_loops/python/hood.py b/y2017/control_loops/python/hood.py
new file mode 100755
index 0000000..5be85cd
--- /dev/null
+++ b/y2017/control_loops/python/hood.py
@@ -0,0 +1,328 @@
+#!/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
+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
+
+class Hood(control_loop.ControlLoop):
+ def __init__(self, name='Hood'):
+ super(Hood, self).__init__(name)
+ # Stall Torque in N m
+ self.stall_torque = 0.43
+ # Stall Current in Amps
+ self.stall_current = 53.0
+ # Free Speed in RPM
+ self.free_speed = 13180.0
+ # Free Current in Amps
+ self.free_current = 1.8
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # First axle gear ratio off the motor
+ self.G1 = (12.0 / 60.0)
+ # Second axle gear ratio off the motor
+ self.G2 = self.G1 * (14.0 / 36.0)
+ # Third axle gear ratio off the motor
+ self.G3 = self.G2 * (14.0 / 36.0)
+ # Gear ratio
+ self.G = (12.0 / 60.0) * (14.0 / 36.0) * (14.0 / 36.0) * (18.0 / 345.0)
+
+ # 36 tooth gear inertia in kg * m^2
+ self.big_gear_inertia = 0.5 * 0.039 * ((36.0 / 40.0 * 0.025) ** 2)
+
+ # Motor inertia in kg * m^2
+ self.motor_inertia = 0.000006
+ glog.debug(self.big_gear_inertia)
+
+ # Moment of inertia, measured in CAD.
+ # Extra mass to compensate for friction is added on.
+ self.J = 0.08 + \
+ self.big_gear_inertia * ((self.G1 / self.G) ** 2) + \
+ self.big_gear_inertia * ((self.G2 / self.G) ** 2) + \
+ self.motor_inertia * ((1.0 / self.G) ** 2.0)
+ glog.debug('J effective %f', self.J)
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # 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)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ glog.debug('Free speed is %f',
+ -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
+ glog.debug(repr(self.A_continuous))
+
+ # Calculate the LQR controller gain
+ q_pos = 2.0
+ q_vel = 500.0
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(5.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ # Calculate the feed forwards gain.
+ q_pos_ff = 0.005
+ q_vel_ff = 1.0
+ self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel_ff ** 2.0))]])
+
+ 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],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ 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.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralHood(Hood):
+ def __init__(self, name='IntegralHood'):
+ super(IntegralHood, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.12
+ q_vel = 2.00
+ q_voltage = 3.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(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.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, hood, end_goal,
+ controller_hood,
+ observer_hood=None,
+ iterations=200):
+ """Runs the hood plant with an initial condition and goal.
+
+ Args:
+ hood: hood object to use.
+ end_goal: end_goal state.
+ controller_hood: Hood object to get K from, or None if we should
+ use hood.
+ observer_hood: Hood 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_hood is None:
+ controller_hood = hood
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + hood.dt
+ else:
+ initial_t = 0
+
+ goal = numpy.concatenate((hood.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
+
+ profile = TrapezoidProfile(hood.dt)
+ profile.set_maximum_acceleration(10.0)
+ profile.set_maximum_velocity(1.0)
+ profile.SetGoal(goal[0, 0])
+
+ U_last = numpy.matrix(numpy.zeros((1, 1)))
+ for i in xrange(iterations):
+ observer_hood.Y = hood.Y
+ observer_hood.CorrectObserver(U_last)
+
+ self.offset.append(observer_hood.X_hat[2, 0])
+ self.x_hat.append(observer_hood.X_hat[0, 0])
+
+ next_goal = numpy.concatenate(
+ (profile.Update(end_goal[0, 0], end_goal[1, 0]),
+ numpy.matrix(numpy.zeros((1, 1)))),
+ axis=0)
+
+ ff_U = controller_hood.Kff * (next_goal - observer_hood.A * goal)
+
+ U_uncapped = controller_hood.K * (goal - observer_hood.X_hat) + ff_U
+ U = U_uncapped.copy()
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(hood.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(hood.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / hood.dt)
+
+ offset = 0.0
+ if i > 100:
+ offset = 2.0
+ hood.Update(U + offset)
+
+ observer_hood.PredictObserver(U)
+
+ self.t.append(initial_t + i * hood.dt)
+ self.u.append(U[0, 0])
+
+ ff_U -= U_uncapped - U
+ goal = controller_hood.A * goal + controller_hood.B * ff_U
+
+ if U[0, 0] != U_uncapped[0, 0]:
+ profile.MoveCurrentState(
+ numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
+
+ glog.debug('Time: %f', self.t[-1])
+ glog.debug('goal_error %s', repr(end_goal - goal))
+ glog.debug('error %s', repr(observer_hood.X_hat - end_goal))
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+
+ scenario_plotter = ScenarioPlotter()
+
+ hood = Hood()
+ hood_controller = IntegralHood()
+ observer_hood = IntegralHood()
+
+ # Test moving the hood with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
+ scenario_plotter.run_test(hood, end_goal=R,
+ controller_hood=hood_controller,
+ observer_hood=observer_hood, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the hood and integral hood.')
+ else:
+ namespaces = ['y2017', 'control_loops', 'superstructure', 'hood']
+ hood = Hood('Hood')
+ loop_writer = control_loop.ControlLoopWriter('Hood', [hood],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_hood = IntegralHood('IntegralHood')
+ integral_loop_writer = control_loop.ControlLoopWriter('IntegralHood', [integral_hood],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+
+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
new file mode 100755
index 0000000..a5088cb
--- /dev/null
+++ b/y2017/control_loops/python/indexer.py
@@ -0,0 +1,298 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+import numpy
+import sys
+from matplotlib import pylab
+
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+
+class VelocityIndexer(control_loop.ControlLoop):
+ def __init__(self, name='VelocityIndexer'):
+ super(VelocityIndexer, self).__init__(name)
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134
+ # Free Speed in RPM
+ self.free_speed = 18730.0
+ # Free Current in Amps
+ self.free_current = 0.7
+ # Moment of inertia of the indexer halves in kg m^2
+ # This is measured as Iyy in CAD (the moment of inertia around the Y axis).
+ # Inner part of indexer -> Iyy = 59500 lb * mm * mm
+ # Inner spins with 12 / 48 * 18 / 48 * 24 / 36 * 16 / 72
+ # Outer part of indexer -> Iyy = 210000 lb * mm * mm
+ # 1 775 pro -> 12 / 48 * 18 / 48 * 30 / 422
+
+ self.J_inner = 0.0269
+ self.J_outer = 0.0952
+ # Gear ratios for the inner and outer parts.
+ self.G_inner = (12.0 / 48.0) * (18.0 / 48.0) * (24.0 / 36.0) * (16.0 / 72.0)
+ self.G_outer = (12.0 / 48.0) * (18.0 / 48.0) * (30.0 / 422.0)
+
+ # Motor inertia in kg * m^2
+ self.motor_inertia = 0.000006
+
+ # The output coordinate system is in radians for the inner part of the
+ # indexer.
+ # Compute the effective moment of inertia assuming all the mass is in that
+ # coordinate system.
+ self.J = (
+ 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
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Control loop time step
+ self.dt = 0.005
+
+ # State feedback matrices
+ # [angular velocity]
+ self.A_continuous = numpy.matrix(
+ [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.R)]])
+ self.B_continuous = numpy.matrix(
+ [[self.Kt / (self.J * self.G * self.R)]])
+ self.C = numpy.matrix([[1]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.PlaceControllerPoles([.82])
+ glog.debug(repr(self.K))
+
+ self.PlaceObserverPoles([0.3])
+
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ qff_vel = 8.0
+ self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
+
+ self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
+ self.InitializeState()
+
+
+class Indexer(VelocityIndexer):
+ def __init__(self, name='Indexer'):
+ super(Indexer, self).__init__(name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
+ self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
+ self.A_continuous[0, 1] = 1
+
+ self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
+ self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
+
+ # State feedback matrices
+ # [position, angular velocity]
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.rpl = .45
+ self.ipl = 0.07
+ self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
+ self.rpl - 1j * self.ipl])
+
+ self.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 2)))
+ self.K[0, 1:2] = self.K_unaugmented
+ self.Kff_unaugmented = self.Kff
+ self.Kff = numpy.matrix(numpy.zeros((1, 2)))
+ self.Kff[0, 1:2] = self.Kff_unaugmented
+
+ self.InitializeState()
+
+
+class IntegralIndexer(Indexer):
+ def __init__(self, name="IntegralIndexer"):
+ super(IntegralIndexer, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 2.0
+ q_vel = 0.001
+ q_voltage = 10.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.001
+ self.R = numpy.matrix([[(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.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+ self.Kff_unaugmented = self.Kff
+ self.Kff = numpy.matrix(numpy.zeros((1, 3)))
+ self.Kff[0, 0:2] = self.Kff_unaugmented
+
+ self.InitializeState()
+
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, indexer, goal, iterations=200, controller_indexer=None,
+ observer_indexer=None):
+ """Runs the indexer plant with an initial condition and goal.
+
+ Args:
+ indexer: Indexer object to use.
+ goal: goal state.
+ iterations: Number of timesteps to run the model for.
+ controller_indexer: Indexer object to get K from, or None if we should
+ use indexer.
+ observer_indexer: Indexer object to use for the observer, or None if we
+ should use the actual state.
+ """
+
+ if controller_indexer is None:
+ controller_indexer = indexer
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + indexer.dt
+ else:
+ initial_t = 0
+
+ for i in xrange(iterations):
+ X_hat = indexer.X
+
+ if observer_indexer is not None:
+ X_hat = observer_indexer.X_hat
+ self.x_hat.append(observer_indexer.X_hat[1, 0])
+
+ ff_U = controller_indexer.Kff * (goal - observer_indexer.A * goal)
+
+ U = controller_indexer.K * (goal - X_hat) + ff_U
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(indexer.X[0, 0])
+
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(indexer.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / indexer.dt)
+
+ if observer_indexer is not None:
+ observer_indexer.Y = indexer.Y
+ observer_indexer.CorrectObserver(U)
+ self.offset.append(observer_indexer.X_hat[2, 0])
+
+ applied_U = U.copy()
+ if i > 30:
+ applied_U += 2
+ indexer.Update(applied_U)
+
+ if observer_indexer is not None:
+ observer_indexer.PredictObserver(U)
+
+ self.t.append(initial_t + i * indexer.dt)
+ self.u.append(U[0, 0])
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.v, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ scenario_plotter = ScenarioPlotter()
+
+ indexer = Indexer()
+ indexer_controller = IntegralIndexer()
+ observer_indexer = IntegralIndexer()
+
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[0.0], [20.0], [0.0]])
+ scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
+ observer_indexer=observer_indexer, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name')
+ else:
+ namespaces = ['y2017', 'control_loops', 'superstructure', 'indexer']
+ indexer = Indexer('Indexer')
+ loop_writer = control_loop.ControlLoopWriter('Indexer', [indexer],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_indexer = IntegralIndexer('IntegralIndexer')
+ integral_loop_writer = control_loop.ControlLoopWriter(
+ 'IntegralIndexer', [integral_indexer], namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+
+if __name__ == '__main__':
+ argv = FLAGS(sys.argv)
+ glog.init()
+ sys.exit(main(argv))
diff --git a/y2017/control_loops/python/intake.py b/y2017/control_loops/python/intake.py
new file mode 100755
index 0000000..41cfc0d
--- /dev/null
+++ b/y2017/control_loops/python/intake.py
@@ -0,0 +1,321 @@
+#!/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
+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
+
+class Intake(control_loop.ControlLoop):
+ def __init__(self, name='Intake'):
+ super(Intake, self).__init__(name)
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134.0
+ # Free Speed in RPM
+ self.free_speed = 18730.0
+ # Free Current in Amps
+ self.free_current = 0.7
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+
+ # (1 / 35.0) * (20.0 / 40.0) -> 16 tooth sprocket on #25 chain
+ # Gear ratio
+ self.G = (1.0 / 35.0) * (20.0 / 40.0)
+ self.r = 16.0 * 0.25 / (2.0 * numpy.pi) * 0.0254
+
+ # Motor inertia in kg m^2
+ self.motor_inertia = 0.00001187
+
+ # 5.4 kg of moving mass for the intake
+ self.mass = 5.4 + self.motor_inertia / ((self.G * self.r) ** 2.0)
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # State is [position, velocity]
+ # Input is [Voltage]
+
+ C1 = self.Kt / (self.G * self.G * self.r * self.r * self.R * self.mass * self.Kv)
+ C2 = self.Kt / (self.G * self.r * self.R * self.mass)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+ glog.debug(repr(self.A_continuous))
+ glog.debug(repr(self.B_continuous))
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ glog.debug('Free speed is %f',
+ -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
+
+ q_pos = 0.015
+ q_vel = 0.3
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ q_pos_ff = 0.005
+ q_vel_ff = 1.0
+ self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel_ff ** 2.0))]])
+
+ 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]))
+
+ 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],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ 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.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralIntake(Intake):
+ def __init__(self, name='IntegralIntake'):
+ super(IntegralIntake, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.12
+ q_vel = 2.00
+ q_voltage = 40.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(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.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, intake, end_goal,
+ controller_intake,
+ observer_intake=None,
+ iterations=200):
+ """Runs the intake plant with an initial condition and goal.
+
+ Args:
+ intake: intake object to use.
+ end_goal: end_goal state.
+ controller_intake: Intake object to get K from, or None if we should
+ use intake.
+ observer_intake: 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_intake is None:
+ controller_intake = intake
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + intake.dt
+ else:
+ initial_t = 0
+
+ goal = numpy.concatenate((intake.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
+
+ profile = TrapezoidProfile(intake.dt)
+ profile.set_maximum_acceleration(10.0)
+ profile.set_maximum_velocity(0.3)
+ profile.SetGoal(goal[0, 0])
+
+ U_last = numpy.matrix(numpy.zeros((1, 1)))
+ for i in xrange(iterations):
+ observer_intake.Y = intake.Y
+ observer_intake.CorrectObserver(U_last)
+
+ self.offset.append(observer_intake.X_hat[2, 0])
+ self.x_hat.append(observer_intake.X_hat[0, 0])
+
+ next_goal = numpy.concatenate(
+ (profile.Update(end_goal[0, 0], end_goal[1, 0]),
+ numpy.matrix(numpy.zeros((1, 1)))),
+ axis=0)
+
+ ff_U = controller_intake.Kff * (next_goal - observer_intake.A * goal)
+
+ U_uncapped = controller_intake.K * (goal - observer_intake.X_hat) + ff_U
+ U_uncapped = controller_intake.K * (end_goal - observer_intake.X_hat)
+ U = U_uncapped.copy()
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(intake.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(intake.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / intake.dt)
+
+ offset = 0.0
+ if i > 100:
+ offset = 2.0
+ intake.Update(U + offset)
+
+ observer_intake.PredictObserver(U)
+
+ self.t.append(initial_t + i * intake.dt)
+ self.u.append(U[0, 0])
+
+ ff_U -= U_uncapped - U
+ goal = controller_intake.A * goal + controller_intake.B * ff_U
+
+ if U[0, 0] != U_uncapped[0, 0]:
+ profile.MoveCurrentState(
+ numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
+
+ glog.debug('Time: %f', self.t[-1])
+ glog.debug('goal_error %s', repr(end_goal - goal))
+ glog.debug('error %s', repr(observer_intake.X_hat - end_goal))
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ scenario_plotter = ScenarioPlotter()
+
+ intake = Intake()
+ intake_controller = IntegralIntake()
+ observer_intake = IntegralIntake()
+
+ # Test moving the intake with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[0.1], [0.0], [0.0]])
+ scenario_plotter.run_test(intake, end_goal=R,
+ controller_intake=intake_controller,
+ observer_intake=observer_intake, iterations=400)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the intake and integral intake.')
+ else:
+ namespaces = ['y2017', 'control_loops', 'superstructure', 'intake']
+ intake = Intake('Intake')
+ loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_intake = IntegralIntake('IntegralIntake')
+ integral_loop_writer = control_loop.ControlLoopWriter('IntegralIntake', [integral_intake],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ argv = FLAGS(sys.argv)
+ glog.init()
+ sys.exit(main(argv))
diff --git a/y2017/control_loops/python/polydrivetrain.py b/y2017/control_loops/python/polydrivetrain.py
index 353618b..29cb209 100755
--- a/y2017/control_loops/python/polydrivetrain.py
+++ b/y2017/control_loops/python/polydrivetrain.py
@@ -129,7 +129,7 @@
# FF * X = U (steady state)
self.FF = self.B.I * (numpy.eye(2) - self.A)
- self.PlaceControllerPoles([0.67, 0.67])
+ self.PlaceControllerPoles([0.85, 0.85])
self.PlaceObserverPoles([0.02, 0.02])
self.G_high = self._drivetrain.G_high
diff --git a/y2017/control_loops/python/shooter.py b/y2017/control_loops/python/shooter.py
new file mode 100755
index 0000000..d7c505b
--- /dev/null
+++ b/y2017/control_loops/python/shooter.py
@@ -0,0 +1,280 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+import numpy
+import sys
+from matplotlib import pylab
+
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+
+class VelocityShooter(control_loop.ControlLoop):
+ def __init__(self, name='VelocityShooter'):
+ super(VelocityShooter, self).__init__(name)
+ # Number of motors
+ self.num_motors = 2.0
+ # Stall Torque in N m
+ self.stall_torque = 0.71 * self.num_motors
+ # Stall Current in Amps
+ self.stall_current = 134.0 * self.num_motors
+ # Free Speed in RPM
+ self.free_speed = 18730.0
+ # Free Current in Amps
+ self.free_current = 0.7 * self.num_motors
+ # Moment of inertia of the shooter wheel in kg m^2
+ # 1400.6 grams/cm^2
+ # 1.407 *1e-4 kg m^2
+ self.J = 0.00080
+ # Resistance of the motor, divided by 2 to account for the 2 motors
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratio
+ self.G = 12.0 / 36.0
+ # Control loop time step
+ self.dt = 0.005
+
+ # State feedback matrices
+ # [angular velocity]
+ self.A_continuous = numpy.matrix(
+ [[-self.Kt / (self.Kv * self.J * self.G * self.G * self.R)]])
+ self.B_continuous = numpy.matrix(
+ [[self.Kt / (self.J * self.G * self.R)]])
+ self.C = numpy.matrix([[1]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.PlaceControllerPoles([.90])
+
+ self.PlaceObserverPoles([0.3])
+
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ qff_vel = 8.0
+ self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
+
+ self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
+ self.InitializeState()
+
+
+class Shooter(VelocityShooter):
+ def __init__(self, name='Shooter'):
+ super(Shooter, self).__init__(name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
+ self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
+ self.A_continuous[0, 1] = 1
+
+ self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
+ self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
+
+ # State feedback matrices
+ # [position, angular velocity]
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.rpl = .45
+ self.ipl = 0.07
+ self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
+ self.rpl - 1j * self.ipl])
+
+ self.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 2)))
+ self.K[0, 1:2] = self.K_unaugmented
+ self.Kff_unaugmented = self.Kff
+ self.Kff = numpy.matrix(numpy.zeros((1, 2)))
+ self.Kff[0, 1:2] = self.Kff_unaugmented
+
+ self.InitializeState()
+
+
+class IntegralShooter(Shooter):
+ def __init__(self, name='IntegralShooter'):
+ super(IntegralShooter, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 2.0
+ q_vel = 0.001
+ q_voltage = 10.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.001
+ self.R = numpy.matrix([[(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.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+ self.Kff_unaugmented = self.Kff
+ self.Kff = numpy.matrix(numpy.zeros((1, 3)))
+ self.Kff[0, 0:2] = self.Kff_unaugmented
+
+ self.InitializeState()
+
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, shooter, goal, iterations=200, controller_shooter=None,
+ observer_shooter=None):
+ """Runs the shooter plant with an initial condition and goal.
+
+ Args:
+ shooter: Shooter object to use.
+ goal: goal state.
+ iterations: Number of timesteps to run the model for.
+ controller_shooter: Shooter object to get K from, or None if we should
+ use shooter.
+ observer_shooter: Shooter object to use for the observer, or None if we
+ should use the actual state.
+ """
+
+ if controller_shooter is None:
+ controller_shooter = shooter
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + shooter.dt
+ else:
+ initial_t = 0
+
+ for i in xrange(iterations):
+ X_hat = shooter.X
+
+ if observer_shooter is not None:
+ X_hat = observer_shooter.X_hat
+ self.x_hat.append(observer_shooter.X_hat[1, 0])
+
+ ff_U = controller_shooter.Kff * (goal - observer_shooter.A * goal)
+
+ U = controller_shooter.K * (goal - X_hat) + ff_U
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(shooter.X[0, 0])
+
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(shooter.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / shooter.dt)
+
+ if observer_shooter is not None:
+ observer_shooter.Y = shooter.Y
+ observer_shooter.CorrectObserver(U)
+ self.offset.append(observer_shooter.X_hat[2, 0])
+
+ applied_U = U.copy()
+ if i > 30:
+ applied_U += 2
+ shooter.Update(applied_U)
+
+ if observer_shooter is not None:
+ observer_shooter.PredictObserver(U)
+
+ self.t.append(initial_t + i * shooter.dt)
+ self.u.append(U[0, 0])
+
+ glog.debug('Time: %f', self.t[-1])
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.v, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ scenario_plotter = ScenarioPlotter()
+
+ shooter = Shooter()
+ shooter_controller = IntegralShooter()
+ observer_shooter = IntegralShooter()
+
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[0.0], [100.0], [0.0]])
+ scenario_plotter.run_test(shooter, goal=R, controller_shooter=shooter_controller,
+ observer_shooter=observer_shooter, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name')
+ else:
+ namespaces = ['y2017', 'control_loops', 'superstructure', 'shooter']
+ shooter = Shooter('Shooter')
+ loop_writer = control_loop.ControlLoopWriter('Shooter', [shooter],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_shooter = IntegralShooter('IntegralShooter')
+ integral_loop_writer = control_loop.ControlLoopWriter(
+ 'IntegralShooter', [integral_shooter], namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+
+if __name__ == '__main__':
+ argv = FLAGS(sys.argv)
+ glog.init()
+ sys.exit(main(argv))
diff --git a/y2017/control_loops/python/turret.py b/y2017/control_loops/python/turret.py
new file mode 100755
index 0000000..454be9e
--- /dev/null
+++ b/y2017/control_loops/python/turret.py
@@ -0,0 +1,314 @@
+#!/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
+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
+
+class Turret(control_loop.ControlLoop):
+ def __init__(self, name='Turret'):
+ super(Turret, self).__init__(name)
+ # Stall Torque in N m
+ self.stall_torque = 0.43
+ # Stall Current in Amps
+ self.stall_current = 53
+ # Free Speed in RPM
+ self.free_speed = 13180
+ # Free Current in Amps
+ self.free_current = 1.8
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * 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)
+
+ # Motor inertia in kg * m^2
+ self.motor_inertia = 0.000006
+
+ # Moment of inertia, measured in CAD.
+ # Extra mass to compensate for friction is added on.
+ self.J = 0.05 + self.motor_inertia * ((1.0 / self.G) ** 2.0)
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # 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)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ glog.debug('Free speed is %f',
+ -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
+
+ # Calculate the LQR controller gain
+ q_pos = 0.20
+ q_vel = 5.0
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ # Calculate the feed forwards gain.
+ q_pos_ff = 0.005
+ q_vel_ff = 1.0
+ self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel_ff ** 2.0))]])
+
+ 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],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ 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.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralTurret(Turret):
+ def __init__(self, name='IntegralTurret'):
+ super(IntegralTurret, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.12
+ q_vel = 2.00
+ q_voltage = 3.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(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.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, turret, end_goal,
+ controller_turret,
+ observer_turret=None,
+ iterations=200):
+ """Runs the turret plant with an initial condition and goal.
+
+ Args:
+ turret: turret object to use.
+ end_goal: end_goal state.
+ controller_turret: Turret object to get K from, or None if we should
+ use turret.
+ observer_turret: Turret 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_turret is None:
+ controller_turret = turret
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + turret.dt
+ else:
+ initial_t = 0
+
+ goal = numpy.concatenate((turret.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
+
+ profile = TrapezoidProfile(turret.dt)
+ profile.set_maximum_acceleration(100.0)
+ profile.set_maximum_velocity(7.0)
+ profile.SetGoal(goal[0, 0])
+
+ U_last = numpy.matrix(numpy.zeros((1, 1)))
+ for i in xrange(iterations):
+ observer_turret.Y = turret.Y
+ observer_turret.CorrectObserver(U_last)
+
+ self.offset.append(observer_turret.X_hat[2, 0])
+ self.x_hat.append(observer_turret.X_hat[0, 0])
+
+ next_goal = numpy.concatenate(
+ (profile.Update(end_goal[0, 0], end_goal[1, 0]),
+ numpy.matrix(numpy.zeros((1, 1)))),
+ axis=0)
+
+ ff_U = controller_turret.Kff * (next_goal - observer_turret.A * goal)
+
+ U_uncapped = controller_turret.K * (goal - observer_turret.X_hat) + ff_U
+ U_uncapped = controller_turret.K * (end_goal - observer_turret.X_hat)
+ U = U_uncapped.copy()
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(turret.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(turret.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / turret.dt)
+
+ offset = 0.0
+ if i > 100:
+ offset = 2.0
+ turret.Update(U + offset)
+
+ observer_turret.PredictObserver(U)
+
+ self.t.append(initial_t + i * turret.dt)
+ self.u.append(U[0, 0])
+
+ ff_U -= U_uncapped - U
+ goal = controller_turret.A * goal + controller_turret.B * ff_U
+
+ if U[0, 0] != U_uncapped[0, 0]:
+ profile.MoveCurrentState(
+ numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
+
+ glog.debug('Time: %f', self.t[-1])
+ glog.debug('goal_error %s', repr(end_goal - goal))
+ glog.debug('error %s', repr(observer_turret.X_hat - end_goal))
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ argv = FLAGS(argv)
+ glog.init()
+
+ scenario_plotter = ScenarioPlotter()
+
+ turret = Turret()
+ turret_controller = IntegralTurret()
+ observer_turret = IntegralTurret()
+
+ # Test moving the turret with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
+ scenario_plotter.run_test(turret, end_goal=R,
+ controller_turret=turret_controller,
+ observer_turret=observer_turret, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the turret and integral turret.')
+ else:
+ namespaces = ['y2017', 'control_loops', 'superstructure', 'turret']
+ turret = Turret('Turret')
+ loop_writer = control_loop.ControlLoopWriter('Turret', [turret],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_turret = IntegralTurret('IntegralTurret')
+ integral_loop_writer = control_loop.ControlLoopWriter(
+ 'IntegralTurret', [integral_turret],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))