blob: 63cc0f427d1b24e4fcfd82d11dc9f3eab262d020 [file] [log] [blame]
Comran Morshed2ae094e2016-01-23 20:43:20 +00001#!/usr/bin/python
2
Philipp Schrader1a25ee42016-02-11 07:02:03 +00003from aos.common.util.trapezoid_profile import TrapezoidProfile
Comran Morshed2ae094e2016-01-23 20:43:20 +00004from frc971.control_loops.python import control_loop
5from frc971.control_loops.python import controls
Comran Morshed2ae094e2016-01-23 20:43:20 +00006import numpy
7import sys
8import matplotlib
9from matplotlib import pylab
10import gflags
11import glog
12
13FLAGS = gflags.FLAGS
14
15try:
16 gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
17except gflags.DuplicateFlagError:
18 pass
19
20class Intake(control_loop.ControlLoop):
Austin Schuh07cb5852016-01-31 00:58:46 -080021 def __init__(self, name="Intake"):
Comran Morshed2ae094e2016-01-23 20:43:20 +000022 super(Intake, self).__init__(name)
23 # TODO(constants): Update all of these & retune poles.
24 # Stall Torque in N m
Austin Schuh07cb5852016-01-31 00:58:46 -080025 self.stall_torque = 0.71
Comran Morshed2ae094e2016-01-23 20:43:20 +000026 # Stall Current in Amps
Austin Schuh07cb5852016-01-31 00:58:46 -080027 self.stall_current = 134
Comran Morshed2ae094e2016-01-23 20:43:20 +000028 # Free Speed in RPM
Austin Schuh07cb5852016-01-31 00:58:46 -080029 self.free_speed = 18730
Comran Morshed2ae094e2016-01-23 20:43:20 +000030 # Free Current in Amps
Austin Schuh07cb5852016-01-31 00:58:46 -080031 self.free_current = 0.7
Comran Morshed2ae094e2016-01-23 20:43:20 +000032
33 # Resistance of the motor
34 self.R = 12.0 / self.stall_current
35 # Motor velocity constant
36 self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
37 (12.0 - self.R * self.free_current))
38 # Torque constant
39 self.Kt = self.stall_torque / self.stall_current
40 # Gear ratio
Austin Schuh07cb5852016-01-31 00:58:46 -080041 self.G = (56.0 / 12.0) * (54.0 / 14.0) * (64.0 / 18.0) * (48.0 / 16.0)
Comran Morshed2ae094e2016-01-23 20:43:20 +000042
Comran Morshedb6a22362016-03-05 14:14:32 +000043 # Moment of inertia, measured in CAD.
44 # Extra mass to compensate for friction is added on.
45 self.J = 0.34 + 0.1
Comran Morshed2ae094e2016-01-23 20:43:20 +000046
47 # Control loop time step
48 self.dt = 0.005
49
50 # State is [position, velocity]
51 # Input is [Voltage]
52
53 C1 = self.G * self.G * self.Kt / (self.R * self.J * self.Kv)
54 C2 = self.Kt * self.G / (self.J * self.R)
55
56 self.A_continuous = numpy.matrix(
57 [[0, 1],
58 [0, -C1]])
59
60 # Start with the unmodified input
61 self.B_continuous = numpy.matrix(
62 [[0],
63 [C2]])
64
65 self.C = numpy.matrix([[1, 0]])
66 self.D = numpy.matrix([[0]])
67
68 self.A, self.B = self.ContinuousToDiscrete(
69 self.A_continuous, self.B_continuous, self.dt)
70
71 controllability = controls.ctrb(self.A, self.B)
72
Austin Schuha88c4072016-02-06 14:31:03 -080073 glog.debug("Free speed is %f", self.free_speed * numpy.pi * 2.0 / 60.0 / self.G)
Comran Morshed2ae094e2016-01-23 20:43:20 +000074
Austin Schuh07cb5852016-01-31 00:58:46 -080075 q_pos = 0.20
76 q_vel = 5.5
Comran Morshed2ae094e2016-01-23 20:43:20 +000077 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
78 [0.0, (1.0 / (q_vel ** 2.0))]])
79
80 self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
81 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
82
Austin Schuh2fc10fa2016-02-08 00:44:34 -080083 q_pos_ff = 0.005
84 q_vel_ff = 1.0
85 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
86 [0.0, (1.0 / (q_vel_ff ** 2.0))]])
87
88 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
89
Austin Schuha88c4072016-02-06 14:31:03 -080090 glog.debug('K %s', repr(self.K))
91 glog.debug('Poles are %s',
92 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
Comran Morshed2ae094e2016-01-23 20:43:20 +000093
94 self.rpl = 0.30
95 self.ipl = 0.10
96 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
97 self.rpl - 1j * self.ipl])
98
Austin Schuha88c4072016-02-06 14:31:03 -080099 glog.debug('L is %s', repr(self.L))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000100
Austin Schuh1aa5ee92016-02-28 21:57:45 -0800101 q_pos = 0.10
102 q_vel = 1.65
Comran Morshed2ae094e2016-01-23 20:43:20 +0000103 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
104 [0.0, (q_vel ** 2.0)]])
105
106 r_volts = 0.025
107 self.R = numpy.matrix([[(r_volts ** 2.0)]])
108
109 self.KalmanGain, self.Q_steady = controls.kalman(
110 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
111
Austin Schuha88c4072016-02-06 14:31:03 -0800112 glog.debug('Kal %s', repr(self.KalmanGain))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000113 self.L = self.A * self.KalmanGain
Austin Schuha88c4072016-02-06 14:31:03 -0800114 glog.debug('KalL is %s', repr(self.L))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000115
116 # The box formed by U_min and U_max must encompass all possible values,
117 # or else Austin's code gets angry.
118 self.U_max = numpy.matrix([[12.0]])
119 self.U_min = numpy.matrix([[-12.0]])
120
121 self.InitializeState()
122
123class IntegralIntake(Intake):
Austin Schuh07cb5852016-01-31 00:58:46 -0800124 def __init__(self, name="IntegralIntake"):
125 super(IntegralIntake, self).__init__(name=name)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000126
127 self.A_continuous_unaugmented = self.A_continuous
128 self.B_continuous_unaugmented = self.B_continuous
129
130 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
131 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
132 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
133
134 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
135 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
136
137 self.C_unaugmented = self.C
138 self.C = numpy.matrix(numpy.zeros((1, 3)))
139 self.C[0:1, 0:2] = self.C_unaugmented
140
141 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous, self.B_continuous, self.dt)
142
Austin Schuh1aa5ee92016-02-28 21:57:45 -0800143 q_pos = 0.12
144 q_vel = 2.00
Austin Schuh07cb5852016-01-31 00:58:46 -0800145 q_voltage = 3.0
Comran Morshed2ae094e2016-01-23 20:43:20 +0000146 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
147 [0.0, (q_vel ** 2.0), 0.0],
148 [0.0, 0.0, (q_voltage ** 2.0)]])
149
150 r_pos = 0.05
151 self.R = numpy.matrix([[(r_pos ** 2.0)]])
152
153 self.KalmanGain, self.Q_steady = controls.kalman(
154 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
155 self.L = self.A * self.KalmanGain
156
157 self.K_unaugmented = self.K
158 self.K = numpy.matrix(numpy.zeros((1, 3)))
159 self.K[0, 0:2] = self.K_unaugmented
160 self.K[0, 2] = 1
161
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800162 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
163
Comran Morshed2ae094e2016-01-23 20:43:20 +0000164 self.InitializeState()
Austin Schuh07cb5852016-01-31 00:58:46 -0800165
Comran Morshed2ae094e2016-01-23 20:43:20 +0000166class ScenarioPlotter(object):
167 def __init__(self):
168 # Various lists for graphing things.
169 self.t = []
170 self.x = []
171 self.v = []
172 self.a = []
173 self.x_hat = []
174 self.u = []
Austin Schuh07cb5852016-01-31 00:58:46 -0800175 self.offset = []
Comran Morshed2ae094e2016-01-23 20:43:20 +0000176
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800177 def run_test(self, intake, end_goal,
178 controller_intake,
179 observer_intake=None,
180 iterations=200):
Comran Morshed2ae094e2016-01-23 20:43:20 +0000181 """Runs the intake plant with an initial condition and goal.
182
Comran Morshed2ae094e2016-01-23 20:43:20 +0000183 Args:
184 intake: intake object to use.
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800185 end_goal: end_goal state.
Comran Morshed2ae094e2016-01-23 20:43:20 +0000186 controller_intake: Intake object to get K from, or None if we should
187 use intake.
188 observer_intake: Intake object to use for the observer, or None if we should
189 use the actual state.
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800190 iterations: Number of timesteps to run the model for.
Comran Morshed2ae094e2016-01-23 20:43:20 +0000191 """
192
193 if controller_intake is None:
194 controller_intake = intake
195
196 vbat = 12.0
197
198 if self.t:
199 initial_t = self.t[-1] + intake.dt
200 else:
201 initial_t = 0
202
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800203 goal = numpy.concatenate((intake.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
204
Philipp Schrader1a25ee42016-02-11 07:02:03 +0000205 profile = TrapezoidProfile(intake.dt)
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800206 profile.set_maximum_acceleration(70.0)
207 profile.set_maximum_velocity(10.0)
208 profile.SetGoal(goal[0, 0])
209
210 U_last = numpy.matrix(numpy.zeros((1, 1)))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000211 for i in xrange(iterations):
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800212 observer_intake.Y = intake.Y
213 observer_intake.CorrectObserver(U_last)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000214
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800215 self.offset.append(observer_intake.X_hat[2, 0])
216 self.x_hat.append(observer_intake.X_hat[0, 0])
Comran Morshed2ae094e2016-01-23 20:43:20 +0000217
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800218 next_goal = numpy.concatenate(
219 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
220 numpy.matrix(numpy.zeros((1, 1)))),
221 axis=0)
222
223 ff_U = controller_intake.Kff * (next_goal - observer_intake.A * goal)
224
225 U_uncapped = controller_intake.K * (goal - observer_intake.X_hat) + ff_U
226 U = U_uncapped.copy()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000227 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
228 self.x.append(intake.X[0, 0])
229
230 if self.v:
231 last_v = self.v[-1]
232 else:
233 last_v = 0
234
235 self.v.append(intake.X[1, 0])
236 self.a.append((self.v[-1] - last_v) / intake.dt)
237
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800238 intake.Update(U + 0.0)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000239
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800240 observer_intake.PredictObserver(U)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000241
242 self.t.append(initial_t + i * intake.dt)
243 self.u.append(U[0, 0])
244
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800245 ff_U -= U_uncapped - U
246 goal = controller_intake.A * goal + controller_intake.B * ff_U
247
248 if U[0, 0] != U_uncapped[0, 0]:
249 profile.MoveCurrentState(
250 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
251
252 glog.debug('Time: %f', self.t[-1])
253 glog.debug('goal_error %s', repr(end_goal - goal))
254 glog.debug('error %s', repr(observer_intake.X_hat - end_goal))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000255
256 def Plot(self):
257 pylab.subplot(3, 1, 1)
258 pylab.plot(self.t, self.x, label='x')
259 pylab.plot(self.t, self.x_hat, label='x_hat')
260 pylab.legend()
261
262 pylab.subplot(3, 1, 2)
263 pylab.plot(self.t, self.u, label='u')
Austin Schuh07cb5852016-01-31 00:58:46 -0800264 pylab.plot(self.t, self.offset, label='voltage_offset')
265 pylab.legend()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000266
267 pylab.subplot(3, 1, 3)
268 pylab.plot(self.t, self.a, label='a')
Comran Morshed2ae094e2016-01-23 20:43:20 +0000269 pylab.legend()
Austin Schuh07cb5852016-01-31 00:58:46 -0800270
Comran Morshed2ae094e2016-01-23 20:43:20 +0000271 pylab.show()
272
273
274def main(argv):
275 argv = FLAGS(argv)
Austin Schuha88c4072016-02-06 14:31:03 -0800276 glog.init()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000277
Comran Morshed2ae094e2016-01-23 20:43:20 +0000278 scenario_plotter = ScenarioPlotter()
279
Austin Schuh07cb5852016-01-31 00:58:46 -0800280 intake = Intake()
281 intake_controller = IntegralIntake()
282 observer_intake = IntegralIntake()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000283
284 # Test moving the intake with constant separation.
285 initial_X = numpy.matrix([[0.0], [0.0]])
Austin Schuh07cb5852016-01-31 00:58:46 -0800286 R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800287 scenario_plotter.run_test(intake, end_goal=R,
288 controller_intake=intake_controller,
Comran Morshed2ae094e2016-01-23 20:43:20 +0000289 observer_intake=observer_intake, iterations=200)
290
291 if FLAGS.plot:
292 scenario_plotter.Plot()
293
294 # Write the generated constants out to a file.
295 if len(argv) != 5:
296 glog.fatal('Expected .h file name and .cc file name for the intake and integral intake.')
297 else:
298 namespaces = ['y2016', 'control_loops', 'superstructure']
299 intake = Intake("Intake")
300 loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
301 namespaces=namespaces)
302 loop_writer.Write(argv[1], argv[2])
303
Austin Schuh07cb5852016-01-31 00:58:46 -0800304 integral_intake = IntegralIntake("IntegralIntake")
Comran Morshed2ae094e2016-01-23 20:43:20 +0000305 integral_loop_writer = control_loop.ControlLoopWriter("IntegralIntake", [integral_intake],
Austin Schuh07cb5852016-01-31 00:58:46 -0800306 namespaces=namespaces)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000307 integral_loop_writer.Write(argv[3], argv[4])
308
309if __name__ == '__main__':
310 sys.exit(main(sys.argv))