blob: 1a4f91028ff9e04623e260d153391ffd6bea2164 [file] [log] [blame]
Austin Schuh48d60c12017-02-04 21:58:58 -08001#!/usr/bin/python
2
3from frc971.control_loops.python import control_loop
4from frc971.control_loops.python import controls
5import numpy
Austin Schuh6c20f202017-02-18 22:31:44 -08006import scipy
Austin Schuh48d60c12017-02-04 21:58:58 -08007import sys
8from matplotlib import pylab
9
10import gflags
11import glog
12
13FLAGS = gflags.FLAGS
14
15gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
16
Austin Schuh3ad5ed82017-02-25 21:36:19 -080017
18def PlotDiff(list1, list2, time):
19 pylab.subplot(1, 1, 1)
20 pylab.plot(time, numpy.subtract(list1, list2), label='diff')
21 pylab.legend()
22
23
24class VelocityShooter(control_loop.HybridControlLoop):
Austin Schuh48d60c12017-02-04 21:58:58 -080025 def __init__(self, name='VelocityShooter'):
26 super(VelocityShooter, self).__init__(name)
27 # Number of motors
28 self.num_motors = 2.0
29 # Stall Torque in N m
30 self.stall_torque = 0.71 * self.num_motors
31 # Stall Current in Amps
32 self.stall_current = 134.0 * self.num_motors
33 # Free Speed in RPM
Brian Silverman052e69d2017-02-12 16:19:55 -080034 self.free_speed_rpm = 18730.0
35 # Free Speed in rotations/second.
36 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080037 # Free Current in Amps
38 self.free_current = 0.7 * self.num_motors
39 # Moment of inertia of the shooter wheel in kg m^2
40 # 1400.6 grams/cm^2
41 # 1.407 *1e-4 kg m^2
Austin Schuh9f9adb62017-03-05 01:01:37 -080042 self.J = 0.00120
Austin Schuh48d60c12017-02-04 21:58:58 -080043 # Resistance of the motor, divided by 2 to account for the 2 motors
44 self.R = 12.0 / self.stall_current
45 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080046 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh48d60c12017-02-04 21:58:58 -080047 (12.0 - self.R * self.free_current))
48 # Torque constant
49 self.Kt = self.stall_torque / self.stall_current
50 # Gear ratio
51 self.G = 12.0 / 36.0
52 # Control loop time step
53 self.dt = 0.005
54
55 # State feedback matrices
56 # [angular velocity]
57 self.A_continuous = numpy.matrix(
58 [[-self.Kt / (self.Kv * self.J * self.G * self.G * self.R)]])
59 self.B_continuous = numpy.matrix(
60 [[self.Kt / (self.J * self.G * self.R)]])
61 self.C = numpy.matrix([[1]])
62 self.D = numpy.matrix([[0]])
63
Austin Schuhc66b6fc2017-03-25 19:56:59 -070064 # The states are [unfiltered_velocity]
Austin Schuh48d60c12017-02-04 21:58:58 -080065 self.A, self.B = self.ContinuousToDiscrete(
66 self.A_continuous, self.B_continuous, self.dt)
67
Austin Schuh9f9adb62017-03-05 01:01:37 -080068 self.PlaceControllerPoles([.75])
Austin Schuh48d60c12017-02-04 21:58:58 -080069
Austin Schuhcd3237a2017-02-18 14:19:26 -080070 glog.debug('K %s', repr(self.K))
Austin Schuhc66b6fc2017-03-25 19:56:59 -070071 glog.debug('System poles are %s',
72 repr(numpy.linalg.eig(self.A_continuous)[0]))
Austin Schuhcd3237a2017-02-18 14:19:26 -080073 glog.debug('Poles are %s',
74 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
75
Austin Schuh48d60c12017-02-04 21:58:58 -080076 self.PlaceObserverPoles([0.3])
77
78 self.U_max = numpy.matrix([[12.0]])
79 self.U_min = numpy.matrix([[-12.0]])
80
81 qff_vel = 8.0
82 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
83
84 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
85 self.InitializeState()
86
Austin Schuhc66b6fc2017-03-25 19:56:59 -070087class SecondOrderVelocityShooter(VelocityShooter):
88 def __init__(self, name='SecondOrderVelocityShooter'):
89 super(SecondOrderVelocityShooter, self).__init__(name)
Austin Schuh48d60c12017-02-04 21:58:58 -080090
Austin Schuhc66b6fc2017-03-25 19:56:59 -070091 self.A_continuous_unaugmented = self.A_continuous
92 self.B_continuous_unaugmented = self.B_continuous
93
94 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
95 self.A_continuous[0:1, 0:1] = self.A_continuous_unaugmented
96 self.A_continuous[1, 0] = 105.0
97 self.A_continuous[1, 1] = -105.0
98
99 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
100 self.B_continuous[0:1, 0] = self.B_continuous_unaugmented
101
102 self.C = numpy.matrix([[0, 1]])
103 self.D = numpy.matrix([[0]])
104
105 self.A, self.B = self.ContinuousToDiscrete(
106 self.A_continuous, self.B_continuous, self.dt)
107
108 self.PlaceControllerPoles([.75, 0.75])
109
110 glog.debug('K %s', repr(self.K))
111 glog.debug('System poles are %s',
112 repr(numpy.linalg.eig(self.A_continuous)[0]))
113 glog.debug('Poles are %s',
114 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
115
116 self.PlaceObserverPoles([0.3, 0.3])
117
118 self.U_max = numpy.matrix([[12.0]])
119 self.U_min = numpy.matrix([[-12.0]])
120
121 qff_vel = 8.0
122 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0), 0.0],
123 [0.0, 1.0 / (qff_vel ** 2.0)]])
124
125 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
126 self.InitializeState()
127
128
129class Shooter(SecondOrderVelocityShooter):
Austin Schuh48d60c12017-02-04 21:58:58 -0800130 def __init__(self, name='Shooter'):
131 super(Shooter, self).__init__(name)
132
133 self.A_continuous_unaugmented = self.A_continuous
134 self.B_continuous_unaugmented = self.B_continuous
135
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700136 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
137 self.A_continuous[1:3, 1:3] = self.A_continuous_unaugmented
138 self.A_continuous[0, 2] = 1
Austin Schuh48d60c12017-02-04 21:58:58 -0800139
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700140 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
141 self.B_continuous[1:3, 0] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800142
143 # State feedback matrices
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700144 # [position, unfiltered_velocity, angular velocity]
145 self.C = numpy.matrix([[1, 0, 0]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800146 self.D = numpy.matrix([[0]])
147
148 self.A, self.B = self.ContinuousToDiscrete(
149 self.A_continuous, self.B_continuous, self.dt)
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700150 glog.debug(repr(self.A_continuous))
151 glog.debug(repr(self.B_continuous))
Austin Schuh48d60c12017-02-04 21:58:58 -0800152
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700153 observeability = controls.ctrb(self.A.T, self.C.T)
154 glog.debug('Rank of augmented observability matrix. %d', numpy.linalg.matrix_rank(
155 observeability))
156
157
158 self.PlaceObserverPoles([0.9, 0.8, 0.7])
Austin Schuh48d60c12017-02-04 21:58:58 -0800159
160 self.K_unaugmented = self.K
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700161 self.K = numpy.matrix(numpy.zeros((1, 3)))
162 self.K[0, 1:3] = self.K_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800163 self.Kff_unaugmented = self.Kff
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700164 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
165 self.Kff[0, 1:3] = self.Kff_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800166
167 self.InitializeState()
168
169
170class IntegralShooter(Shooter):
171 def __init__(self, name='IntegralShooter'):
172 super(IntegralShooter, self).__init__(name=name)
173
174 self.A_continuous_unaugmented = self.A_continuous
175 self.B_continuous_unaugmented = self.B_continuous
176
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700177 self.A_continuous = numpy.matrix(numpy.zeros((4, 4)))
178 self.A_continuous[0:3, 0:3] = self.A_continuous_unaugmented
179 self.A_continuous[0:3, 3] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800180
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700181 self.B_continuous = numpy.matrix(numpy.zeros((4, 1)))
182 self.B_continuous[0:3, 0] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800183
184 self.C_unaugmented = self.C
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700185 self.C = numpy.matrix(numpy.zeros((1, 4)))
186 self.C[0:1, 0:3] = self.C_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800187
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700188 # The states are [position, unfiltered_velocity, velocity, torque_error]
Austin Schuh48d60c12017-02-04 21:58:58 -0800189 self.A, self.B = self.ContinuousToDiscrete(
190 self.A_continuous, self.B_continuous, self.dt)
191
Austin Schuh6c20f202017-02-18 22:31:44 -0800192 glog.debug('A: \n%s', repr(self.A_continuous))
193 glog.debug('eig(A): \n%s', repr(scipy.linalg.eig(self.A_continuous)))
194 glog.debug('schur(A): \n%s', repr(scipy.linalg.schur(self.A_continuous)))
195 glog.debug('A_dt(A): \n%s', repr(self.A))
196
Austin Schuhcd3237a2017-02-18 14:19:26 -0800197 q_pos = 0.01
198 q_vel = 2.0
Austin Schuh9f9adb62017-03-05 01:01:37 -0800199 q_voltage = 0.3
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700200 self.Q_continuous = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0],
201 [0.0, (q_vel ** 2.0), 0.0, 0.0],
202 [0.0, 0.0, (q_vel ** 2.0), 0.0],
203 [0.0, 0.0, 0.0, (q_voltage ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800204
Austin Schuh9f9adb62017-03-05 01:01:37 -0800205 r_pos = 0.0003
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800206 self.R_continuous = numpy.matrix([[(r_pos ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800207
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800208 _, _, self.Q, self.R = controls.kalmd(
209 A_continuous=self.A_continuous, B_continuous=self.B_continuous,
210 Q_continuous=self.Q_continuous, R_continuous=self.R_continuous,
211 dt=self.dt)
212
213 self.KalmanGain, self.P_steady_state = controls.kalman(
Austin Schuh48d60c12017-02-04 21:58:58 -0800214 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
215 self.L = self.A * self.KalmanGain
216
217 self.K_unaugmented = self.K
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700218 self.K = numpy.matrix(numpy.zeros((1, 4)))
219 self.K[0, 0:3] = self.K_unaugmented
220 self.K[0, 3] = 1
Austin Schuh48d60c12017-02-04 21:58:58 -0800221 self.Kff_unaugmented = self.Kff
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700222 self.Kff = numpy.matrix(numpy.zeros((1, 4)))
223 self.Kff[0, 0:3] = self.Kff_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800224
225 self.InitializeState()
226
227
228class ScenarioPlotter(object):
229 def __init__(self):
230 # Various lists for graphing things.
231 self.t = []
232 self.x = []
233 self.v = []
234 self.a = []
235 self.x_hat = []
236 self.u = []
237 self.offset = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800238 self.diff = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800239
240 def run_test(self, shooter, goal, iterations=200, controller_shooter=None,
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800241 observer_shooter=None, hybrid_obs = False):
Austin Schuh48d60c12017-02-04 21:58:58 -0800242 """Runs the shooter plant with an initial condition and goal.
243
244 Args:
245 shooter: Shooter object to use.
246 goal: goal state.
247 iterations: Number of timesteps to run the model for.
248 controller_shooter: Shooter object to get K from, or None if we should
249 use shooter.
250 observer_shooter: Shooter object to use for the observer, or None if we
251 should use the actual state.
252 """
253
254 if controller_shooter is None:
255 controller_shooter = shooter
256
257 vbat = 12.0
258
259 if self.t:
260 initial_t = self.t[-1] + shooter.dt
261 else:
262 initial_t = 0
263
264 for i in xrange(iterations):
265 X_hat = shooter.X
266
267 if observer_shooter is not None:
268 X_hat = observer_shooter.X_hat
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700269 self.x_hat.append(observer_shooter.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800270
271 ff_U = controller_shooter.Kff * (goal - observer_shooter.A * goal)
272
273 U = controller_shooter.K * (goal - X_hat) + ff_U
274 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
275 self.x.append(shooter.X[0, 0])
276
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700277 self.diff.append(shooter.X[2, 0] - observer_shooter.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800278
279 if self.v:
280 last_v = self.v[-1]
281 else:
282 last_v = 0
283
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700284 self.v.append(shooter.X[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800285 self.a.append((self.v[-1] - last_v) / shooter.dt)
286
287 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800288 if i != 0:
289 observer_shooter.Y = shooter.Y
290 observer_shooter.CorrectObserver(U)
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700291 self.offset.append(observer_shooter.X_hat[3, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800292
293 applied_U = U.copy()
294 if i > 30:
295 applied_U += 2
296 shooter.Update(applied_U)
297
298 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800299 if hybrid_obs:
300 observer_shooter.PredictHybridObserver(U, shooter.dt)
301 else:
302 observer_shooter.PredictObserver(U)
303
Austin Schuh48d60c12017-02-04 21:58:58 -0800304
305 self.t.append(initial_t + i * shooter.dt)
306 self.u.append(U[0, 0])
307
Austin Schuh48d60c12017-02-04 21:58:58 -0800308 def Plot(self):
Austin Schuh9f9adb62017-03-05 01:01:37 -0800309 pylab.figure()
Austin Schuh48d60c12017-02-04 21:58:58 -0800310 pylab.subplot(3, 1, 1)
311 pylab.plot(self.t, self.v, label='x')
312 pylab.plot(self.t, self.x_hat, label='x_hat')
313 pylab.legend()
314
315 pylab.subplot(3, 1, 2)
316 pylab.plot(self.t, self.u, label='u')
317 pylab.plot(self.t, self.offset, label='voltage_offset')
318 pylab.legend()
319
320 pylab.subplot(3, 1, 3)
321 pylab.plot(self.t, self.a, label='a')
322 pylab.legend()
323
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800324 pylab.draw()
Austin Schuh48d60c12017-02-04 21:58:58 -0800325
326
327def main(argv):
328 scenario_plotter = ScenarioPlotter()
329
Austin Schuh48d60c12017-02-04 21:58:58 -0800330 if FLAGS.plot:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800331 shooter = Shooter()
332 shooter_controller = IntegralShooter()
333 observer_shooter = IntegralShooter()
334 iterations = 200
335
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700336 initial_X = numpy.matrix([[0.0], [0.0], [0.0]])
337 R = numpy.matrix([[0.0], [100.0], [100.0], [0.0]])
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800338 scenario_plotter.run_test(shooter, goal=R, controller_shooter=shooter_controller,
339 observer_shooter=observer_shooter, iterations=iterations)
340
Austin Schuh48d60c12017-02-04 21:58:58 -0800341 scenario_plotter.Plot()
342
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800343 scenario_plotter_int = ScenarioPlotter()
344
345 shooter = Shooter()
346 shooter_controller = IntegralShooter()
347 observer_shooter_hybrid = IntegralShooter()
348
349 scenario_plotter_int.run_test(shooter, goal=R, controller_shooter=shooter_controller,
350 observer_shooter=observer_shooter_hybrid, iterations=iterations,
351 hybrid_obs = True)
352
353 scenario_plotter_int.Plot()
354 PlotDiff(scenario_plotter.x_hat, scenario_plotter_int.x_hat,
355 scenario_plotter.t)
356
357 pylab.show()
358
Austin Schuh48d60c12017-02-04 21:58:58 -0800359 if len(argv) != 5:
360 glog.fatal('Expected .h file name and .cc file name')
361 else:
362 namespaces = ['y2017', 'control_loops', 'superstructure', 'shooter']
363 shooter = Shooter('Shooter')
364 loop_writer = control_loop.ControlLoopWriter('Shooter', [shooter],
365 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800366 loop_writer.AddConstant(control_loop.Constant(
367 'kFreeSpeed', '%f', shooter.free_speed))
368 loop_writer.AddConstant(control_loop.Constant(
369 'kOutputRatio', '%f', shooter.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800370 loop_writer.Write(argv[1], argv[2])
371
372 integral_shooter = IntegralShooter('IntegralShooter')
373 integral_loop_writer = control_loop.ControlLoopWriter(
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800374 'IntegralShooter', [integral_shooter], namespaces=namespaces,
375 plant_type='StateFeedbackHybridPlant',
376 observer_type='HybridKalman')
Austin Schuh48d60c12017-02-04 21:58:58 -0800377 integral_loop_writer.Write(argv[3], argv[4])
378
379
380if __name__ == '__main__':
381 argv = FLAGS(sys.argv)
382 glog.init()
383 sys.exit(main(argv))