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