blob: 5be85cd03c2038ab4fb86cef738896f970345c76 [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
27 # Free Speed in RPM
28 self.free_speed = 13180.0
29 # 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
35 self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
36 (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)
45 # Gear ratio
46 self.G = (12.0 / 60.0) * (14.0 / 36.0) * (14.0 / 36.0) * (18.0 / 345.0)
47
48 # 36 tooth gear inertia in kg * m^2
49 self.big_gear_inertia = 0.5 * 0.039 * ((36.0 / 40.0 * 0.025) ** 2)
50
51 # Motor inertia in kg * m^2
52 self.motor_inertia = 0.000006
53 glog.debug(self.big_gear_inertia)
54
55 # Moment of inertia, measured in CAD.
56 # Extra mass to compensate for friction is added on.
57 self.J = 0.08 + \
58 self.big_gear_inertia * ((self.G1 / self.G) ** 2) + \
59 self.big_gear_inertia * ((self.G2 / self.G) ** 2) + \
60 self.motor_inertia * ((1.0 / self.G) ** 2.0)
61 glog.debug('J effective %f', self.J)
62
63 # Control loop time step
64 self.dt = 0.005
65
66 # State is [position, velocity]
67 # Input is [Voltage]
68
69 C1 = self.Kt / (self.R * self.J * self.Kv * self.G * self.G)
70 C2 = self.Kt / (self.J * self.R * self.G)
71
72 self.A_continuous = numpy.matrix(
73 [[0, 1],
74 [0, -C1]])
75
76 # Start with the unmodified input
77 self.B_continuous = numpy.matrix(
78 [[0],
79 [C2]])
80
81 self.C = numpy.matrix([[1, 0]])
82 self.D = numpy.matrix([[0]])
83
84 self.A, self.B = self.ContinuousToDiscrete(
85 self.A_continuous, self.B_continuous, self.dt)
86
87 controllability = controls.ctrb(self.A, self.B)
88
89 glog.debug('Free speed is %f',
90 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
91 glog.debug(repr(self.A_continuous))
92
93 # Calculate the LQR controller gain
94 q_pos = 2.0
95 q_vel = 500.0
96 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
97 [0.0, (1.0 / (q_vel ** 2.0))]])
98
99 self.R = numpy.matrix([[(5.0 / (12.0 ** 2.0))]])
100 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
101
102 # Calculate the feed forwards gain.
103 q_pos_ff = 0.005
104 q_vel_ff = 1.0
105 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
106 [0.0, (1.0 / (q_vel_ff ** 2.0))]])
107
108 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
109
110 glog.debug('K %s', repr(self.K))
111 glog.debug('Poles are %s',
112 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
113
114 q_pos = 0.10
115 q_vel = 1.65
116 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
117 [0.0, (q_vel ** 2.0)]])
118
119 r_volts = 0.025
120 self.R = numpy.matrix([[(r_volts ** 2.0)]])
121
122 self.KalmanGain, self.Q_steady = controls.kalman(
123 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
124
125 glog.debug('Kal %s', repr(self.KalmanGain))
126 self.L = self.A * self.KalmanGain
127 glog.debug('KalL is %s', repr(self.L))
128
129 # The box formed by U_min and U_max must encompass all possible values,
130 # or else Austin's code gets angry.
131 self.U_max = numpy.matrix([[12.0]])
132 self.U_min = numpy.matrix([[-12.0]])
133
134 self.InitializeState()
135
136class IntegralHood(Hood):
137 def __init__(self, name='IntegralHood'):
138 super(IntegralHood, self).__init__(name=name)
139
140 self.A_continuous_unaugmented = self.A_continuous
141 self.B_continuous_unaugmented = self.B_continuous
142
143 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
144 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
145 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
146
147 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
148 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
149
150 self.C_unaugmented = self.C
151 self.C = numpy.matrix(numpy.zeros((1, 3)))
152 self.C[0:1, 0:2] = self.C_unaugmented
153
154 self.A, self.B = self.ContinuousToDiscrete(
155 self.A_continuous, self.B_continuous, self.dt)
156
157 q_pos = 0.12
158 q_vel = 2.00
159 q_voltage = 3.0
160 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
161 [0.0, (q_vel ** 2.0), 0.0],
162 [0.0, 0.0, (q_voltage ** 2.0)]])
163
164 r_pos = 0.05
165 self.R = numpy.matrix([[(r_pos ** 2.0)]])
166
167 self.KalmanGain, self.Q_steady = controls.kalman(
168 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
169 self.L = self.A * self.KalmanGain
170
171 self.K_unaugmented = self.K
172 self.K = numpy.matrix(numpy.zeros((1, 3)))
173 self.K[0, 0:2] = self.K_unaugmented
174 self.K[0, 2] = 1
175
176 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
177
178 self.InitializeState()
179
180class ScenarioPlotter(object):
181 def __init__(self):
182 # Various lists for graphing things.
183 self.t = []
184 self.x = []
185 self.v = []
186 self.a = []
187 self.x_hat = []
188 self.u = []
189 self.offset = []
190
191 def run_test(self, hood, end_goal,
192 controller_hood,
193 observer_hood=None,
194 iterations=200):
195 """Runs the hood plant with an initial condition and goal.
196
197 Args:
198 hood: hood object to use.
199 end_goal: end_goal state.
200 controller_hood: Hood object to get K from, or None if we should
201 use hood.
202 observer_hood: Hood object to use for the observer, or None if we should
203 use the actual state.
204 iterations: Number of timesteps to run the model for.
205 """
206
207 if controller_hood is None:
208 controller_hood = hood
209
210 vbat = 12.0
211
212 if self.t:
213 initial_t = self.t[-1] + hood.dt
214 else:
215 initial_t = 0
216
217 goal = numpy.concatenate((hood.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
218
219 profile = TrapezoidProfile(hood.dt)
220 profile.set_maximum_acceleration(10.0)
221 profile.set_maximum_velocity(1.0)
222 profile.SetGoal(goal[0, 0])
223
224 U_last = numpy.matrix(numpy.zeros((1, 1)))
225 for i in xrange(iterations):
226 observer_hood.Y = hood.Y
227 observer_hood.CorrectObserver(U_last)
228
229 self.offset.append(observer_hood.X_hat[2, 0])
230 self.x_hat.append(observer_hood.X_hat[0, 0])
231
232 next_goal = numpy.concatenate(
233 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
234 numpy.matrix(numpy.zeros((1, 1)))),
235 axis=0)
236
237 ff_U = controller_hood.Kff * (next_goal - observer_hood.A * goal)
238
239 U_uncapped = controller_hood.K * (goal - observer_hood.X_hat) + ff_U
240 U = U_uncapped.copy()
241 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
242 self.x.append(hood.X[0, 0])
243
244 if self.v:
245 last_v = self.v[-1]
246 else:
247 last_v = 0
248
249 self.v.append(hood.X[1, 0])
250 self.a.append((self.v[-1] - last_v) / hood.dt)
251
252 offset = 0.0
253 if i > 100:
254 offset = 2.0
255 hood.Update(U + offset)
256
257 observer_hood.PredictObserver(U)
258
259 self.t.append(initial_t + i * hood.dt)
260 self.u.append(U[0, 0])
261
262 ff_U -= U_uncapped - U
263 goal = controller_hood.A * goal + controller_hood.B * ff_U
264
265 if U[0, 0] != U_uncapped[0, 0]:
266 profile.MoveCurrentState(
267 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
268
269 glog.debug('Time: %f', self.t[-1])
270 glog.debug('goal_error %s', repr(end_goal - goal))
271 glog.debug('error %s', repr(observer_hood.X_hat - end_goal))
272
273 def Plot(self):
274 pylab.subplot(3, 1, 1)
275 pylab.plot(self.t, self.x, label='x')
276 pylab.plot(self.t, self.x_hat, label='x_hat')
277 pylab.legend()
278
279 pylab.subplot(3, 1, 2)
280 pylab.plot(self.t, self.u, label='u')
281 pylab.plot(self.t, self.offset, label='voltage_offset')
282 pylab.legend()
283
284 pylab.subplot(3, 1, 3)
285 pylab.plot(self.t, self.a, label='a')
286 pylab.legend()
287
288 pylab.show()
289
290
291def main(argv):
292
293 scenario_plotter = ScenarioPlotter()
294
295 hood = Hood()
296 hood_controller = IntegralHood()
297 observer_hood = IntegralHood()
298
299 # Test moving the hood with constant separation.
300 initial_X = numpy.matrix([[0.0], [0.0]])
301 R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
302 scenario_plotter.run_test(hood, end_goal=R,
303 controller_hood=hood_controller,
304 observer_hood=observer_hood, iterations=200)
305
306 if FLAGS.plot:
307 scenario_plotter.Plot()
308
309 # Write the generated constants out to a file.
310 if len(argv) != 5:
311 glog.fatal('Expected .h file name and .cc file name for the hood and integral hood.')
312 else:
313 namespaces = ['y2017', 'control_loops', 'superstructure', 'hood']
314 hood = Hood('Hood')
315 loop_writer = control_loop.ControlLoopWriter('Hood', [hood],
316 namespaces=namespaces)
317 loop_writer.Write(argv[1], argv[2])
318
319 integral_hood = IntegralHood('IntegralHood')
320 integral_loop_writer = control_loop.ControlLoopWriter('IntegralHood', [integral_hood],
321 namespaces=namespaces)
322 integral_loop_writer.Write(argv[3], argv[4])
323
324
325if __name__ == '__main__':
326 argv = FLAGS(sys.argv)
327 glog.init()
328 sys.exit(main(argv))