blob: 6c7c2d028821c48938d483a475ad87f8ed1f9ab6 [file] [log] [blame]
Austin Schuh48d60c12017-02-04 21:58:58 -08001#!/usr/bin/python
2
3from aos.common.util.trapezoid_profile import TrapezoidProfile
4from frc971.control_loops.python import control_loop
5from frc971.control_loops.python import controls
6import 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 Hood(control_loop.ControlLoop):
21 def __init__(self, name='Hood'):
22 super(Hood, self).__init__(name)
23 # Stall Torque in N m
24 self.stall_torque = 0.43
25 # Stall Current in Amps
26 self.stall_current = 53.0
Brian Silverman052e69d2017-02-12 16:19:55 -080027 self.free_speed_rpm = 13180.0
28 # Free Speed in rotations/second.
29 self.free_speed = self.free_speed_rpm / 60
Austin Schuh48d60c12017-02-04 21:58:58 -080030 # Free Current in Amps
31 self.free_current = 1.8
32
33 # Resistance of the motor
34 self.R = 12.0 / self.stall_current
35 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080036 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh48d60c12017-02-04 21:58:58 -080037 (12.0 - self.R * self.free_current))
38 # Torque constant
39 self.Kt = self.stall_torque / self.stall_current
40 # First axle gear ratio off the motor
41 self.G1 = (12.0 / 60.0)
42 # Second axle gear ratio off the motor
43 self.G2 = self.G1 * (14.0 / 36.0)
44 # Third axle gear ratio off the motor
45 self.G3 = self.G2 * (14.0 / 36.0)
Austin Schuh0991edb2017-02-05 17:16:44 -080046 # The last gear reduction (encoder -> hood angle)
Ed Jordan8683f432017-02-12 00:13:26 +000047 self.last_G = (20.0 / 345.0)
Austin Schuh48d60c12017-02-04 21:58:58 -080048 # Gear ratio
Austin Schuh0991edb2017-02-05 17:16:44 -080049 self.G = (12.0 / 60.0) * (14.0 / 36.0) * (14.0 / 36.0) * self.last_G
Austin Schuh48d60c12017-02-04 21:58:58 -080050
51 # 36 tooth gear inertia in kg * m^2
52 self.big_gear_inertia = 0.5 * 0.039 * ((36.0 / 40.0 * 0.025) ** 2)
53
54 # Motor inertia in kg * m^2
55 self.motor_inertia = 0.000006
56 glog.debug(self.big_gear_inertia)
57
58 # Moment of inertia, measured in CAD.
59 # Extra mass to compensate for friction is added on.
Austin Schuheb5c22e2017-04-09 18:30:28 -070060 self.J = 0.08 + 2.3 + \
Austin Schuh48d60c12017-02-04 21:58:58 -080061 self.big_gear_inertia * ((self.G1 / self.G) ** 2) + \
62 self.big_gear_inertia * ((self.G2 / self.G) ** 2) + \
63 self.motor_inertia * ((1.0 / self.G) ** 2.0)
64 glog.debug('J effective %f', self.J)
65
66 # Control loop time step
67 self.dt = 0.005
68
69 # State is [position, velocity]
70 # Input is [Voltage]
71
72 C1 = self.Kt / (self.R * self.J * self.Kv * self.G * self.G)
73 C2 = self.Kt / (self.J * self.R * self.G)
74
75 self.A_continuous = numpy.matrix(
76 [[0, 1],
77 [0, -C1]])
78
79 # Start with the unmodified input
80 self.B_continuous = numpy.matrix(
81 [[0],
82 [C2]])
83
84 self.C = numpy.matrix([[1, 0]])
85 self.D = numpy.matrix([[0]])
86
87 self.A, self.B = self.ContinuousToDiscrete(
88 self.A_continuous, self.B_continuous, self.dt)
89
90 controllability = controls.ctrb(self.A, self.B)
91
92 glog.debug('Free speed is %f',
93 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
94 glog.debug(repr(self.A_continuous))
95
96 # Calculate the LQR controller gain
Austin Schuheb5c22e2017-04-09 18:30:28 -070097 q_pos = 0.015
98 q_vel = 0.40
Austin Schuh48d60c12017-02-04 21:58:58 -080099 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
100 [0.0, (1.0 / (q_vel ** 2.0))]])
101
102 self.R = numpy.matrix([[(5.0 / (12.0 ** 2.0))]])
103 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
104
105 # Calculate the feed forwards gain.
106 q_pos_ff = 0.005
107 q_vel_ff = 1.0
108 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
109 [0.0, (1.0 / (q_vel_ff ** 2.0))]])
110
111 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
112
113 glog.debug('K %s', repr(self.K))
114 glog.debug('Poles are %s',
Austin Schuhcd3237a2017-02-18 14:19:26 -0800115 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
Austin Schuh48d60c12017-02-04 21:58:58 -0800116
117 q_pos = 0.10
118 q_vel = 1.65
119 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
120 [0.0, (q_vel ** 2.0)]])
121
122 r_volts = 0.025
123 self.R = numpy.matrix([[(r_volts ** 2.0)]])
124
125 self.KalmanGain, self.Q_steady = controls.kalman(
126 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
127
128 glog.debug('Kal %s', repr(self.KalmanGain))
129 self.L = self.A * self.KalmanGain
130 glog.debug('KalL is %s', repr(self.L))
131
132 # The box formed by U_min and U_max must encompass all possible values,
133 # or else Austin's code gets angry.
134 self.U_max = numpy.matrix([[12.0]])
135 self.U_min = numpy.matrix([[-12.0]])
136
137 self.InitializeState()
138
139class IntegralHood(Hood):
140 def __init__(self, name='IntegralHood'):
141 super(IntegralHood, self).__init__(name=name)
142
143 self.A_continuous_unaugmented = self.A_continuous
144 self.B_continuous_unaugmented = self.B_continuous
145
146 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
147 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
148 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
149
150 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
151 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
152
153 self.C_unaugmented = self.C
154 self.C = numpy.matrix(numpy.zeros((1, 3)))
155 self.C[0:1, 0:2] = self.C_unaugmented
156
157 self.A, self.B = self.ContinuousToDiscrete(
158 self.A_continuous, self.B_continuous, self.dt)
159
Austin Schuh6a90cd92017-02-19 20:55:33 -0800160 q_pos = 0.01
161 q_vel = 4.0
162 q_voltage = 4.0
Austin Schuh48d60c12017-02-04 21:58:58 -0800163 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
164 [0.0, (q_vel ** 2.0), 0.0],
165 [0.0, 0.0, (q_voltage ** 2.0)]])
166
Austin Schuh6a90cd92017-02-19 20:55:33 -0800167 r_pos = 0.001
Austin Schuh48d60c12017-02-04 21:58:58 -0800168 self.R = numpy.matrix([[(r_pos ** 2.0)]])
169
170 self.KalmanGain, self.Q_steady = controls.kalman(
171 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
172 self.L = self.A * self.KalmanGain
173
174 self.K_unaugmented = self.K
175 self.K = numpy.matrix(numpy.zeros((1, 3)))
176 self.K[0, 0:2] = self.K_unaugmented
177 self.K[0, 2] = 1
178
179 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
180
181 self.InitializeState()
182
183class ScenarioPlotter(object):
184 def __init__(self):
185 # Various lists for graphing things.
186 self.t = []
187 self.x = []
188 self.v = []
Austin Schuh6a90cd92017-02-19 20:55:33 -0800189 self.v_hat = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800190 self.a = []
191 self.x_hat = []
192 self.u = []
193 self.offset = []
194
195 def run_test(self, hood, end_goal,
196 controller_hood,
197 observer_hood=None,
198 iterations=200):
199 """Runs the hood plant with an initial condition and goal.
200
201 Args:
202 hood: hood object to use.
203 end_goal: end_goal state.
204 controller_hood: Hood object to get K from, or None if we should
205 use hood.
206 observer_hood: Hood object to use for the observer, or None if we should
207 use the actual state.
208 iterations: Number of timesteps to run the model for.
209 """
210
211 if controller_hood is None:
212 controller_hood = hood
213
214 vbat = 12.0
215
216 if self.t:
217 initial_t = self.t[-1] + hood.dt
218 else:
219 initial_t = 0
220
221 goal = numpy.concatenate((hood.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
222
223 profile = TrapezoidProfile(hood.dt)
224 profile.set_maximum_acceleration(10.0)
225 profile.set_maximum_velocity(1.0)
226 profile.SetGoal(goal[0, 0])
227
228 U_last = numpy.matrix(numpy.zeros((1, 1)))
229 for i in xrange(iterations):
230 observer_hood.Y = hood.Y
231 observer_hood.CorrectObserver(U_last)
232
233 self.offset.append(observer_hood.X_hat[2, 0])
234 self.x_hat.append(observer_hood.X_hat[0, 0])
235
236 next_goal = numpy.concatenate(
237 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
238 numpy.matrix(numpy.zeros((1, 1)))),
239 axis=0)
240
241 ff_U = controller_hood.Kff * (next_goal - observer_hood.A * goal)
242
243 U_uncapped = controller_hood.K * (goal - observer_hood.X_hat) + ff_U
244 U = U_uncapped.copy()
245 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
246 self.x.append(hood.X[0, 0])
247
248 if self.v:
249 last_v = self.v[-1]
250 else:
251 last_v = 0
252
253 self.v.append(hood.X[1, 0])
254 self.a.append((self.v[-1] - last_v) / hood.dt)
Austin Schuh6a90cd92017-02-19 20:55:33 -0800255 self.v_hat.append(observer_hood.X_hat[1, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800256
257 offset = 0.0
258 if i > 100:
259 offset = 2.0
260 hood.Update(U + offset)
261
262 observer_hood.PredictObserver(U)
263
264 self.t.append(initial_t + i * hood.dt)
265 self.u.append(U[0, 0])
266
267 ff_U -= U_uncapped - U
268 goal = controller_hood.A * goal + controller_hood.B * ff_U
269
270 if U[0, 0] != U_uncapped[0, 0]:
271 profile.MoveCurrentState(
272 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
273
274 glog.debug('Time: %f', self.t[-1])
275 glog.debug('goal_error %s', repr(end_goal - goal))
276 glog.debug('error %s', repr(observer_hood.X_hat - end_goal))
277
278 def Plot(self):
279 pylab.subplot(3, 1, 1)
280 pylab.plot(self.t, self.x, label='x')
281 pylab.plot(self.t, self.x_hat, label='x_hat')
Austin Schuh6a90cd92017-02-19 20:55:33 -0800282 pylab.plot(self.t, self.v, label='v')
283 pylab.plot(self.t, self.v_hat, label='v_hat')
Austin Schuh48d60c12017-02-04 21:58:58 -0800284 pylab.legend()
285
286 pylab.subplot(3, 1, 2)
287 pylab.plot(self.t, self.u, label='u')
288 pylab.plot(self.t, self.offset, label='voltage_offset')
289 pylab.legend()
290
291 pylab.subplot(3, 1, 3)
292 pylab.plot(self.t, self.a, label='a')
293 pylab.legend()
294
295 pylab.show()
296
297
298def main(argv):
299
300 scenario_plotter = ScenarioPlotter()
301
302 hood = Hood()
303 hood_controller = IntegralHood()
304 observer_hood = IntegralHood()
305
306 # Test moving the hood with constant separation.
307 initial_X = numpy.matrix([[0.0], [0.0]])
Austin Schuh6a90cd92017-02-19 20:55:33 -0800308 R = numpy.matrix([[numpy.pi/4.0], [0.0], [0.0]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800309 scenario_plotter.run_test(hood, end_goal=R,
310 controller_hood=hood_controller,
311 observer_hood=observer_hood, iterations=200)
312
313 if FLAGS.plot:
314 scenario_plotter.Plot()
315
316 # Write the generated constants out to a file.
317 if len(argv) != 5:
318 glog.fatal('Expected .h file name and .cc file name for the hood and integral hood.')
319 else:
320 namespaces = ['y2017', 'control_loops', 'superstructure', 'hood']
321 hood = Hood('Hood')
322 loop_writer = control_loop.ControlLoopWriter('Hood', [hood],
323 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800324 loop_writer.AddConstant(control_loop.Constant(
325 'kFreeSpeed', '%f', hood.free_speed))
326 loop_writer.AddConstant(control_loop.Constant(
327 'kOutputRatio', '%f', hood.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800328 loop_writer.Write(argv[1], argv[2])
329
330 integral_hood = IntegralHood('IntegralHood')
331 integral_loop_writer = control_loop.ControlLoopWriter('IntegralHood', [integral_hood],
332 namespaces=namespaces)
Austin Schuh0991edb2017-02-05 17:16:44 -0800333 integral_loop_writer.AddConstant(control_loop.Constant('kLastReduction', '%f',
334 integral_hood.last_G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800335 integral_loop_writer.Write(argv[3], argv[4])
336
337
338if __name__ == '__main__':
339 argv = FLAGS(sys.argv)
340 glog.init()
341 sys.exit(main(argv))