blob: 5aef754075dd8f94b5195baf2dbefc074888000e [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
Austin Schuh3ad5ed82017-02-25 21:36:19 -080023class VelocityShooter(control_loop.HybridControlLoop):
Austin Schuh48d60c12017-02-04 21:58:58 -080024 def __init__(self, name='VelocityShooter'):
25 super(VelocityShooter, self).__init__(name)
26 # Number of motors
27 self.num_motors = 2.0
28 # Stall Torque in N m
29 self.stall_torque = 0.71 * self.num_motors
30 # Stall Current in Amps
31 self.stall_current = 134.0 * self.num_motors
32 # Free Speed in RPM
Brian Silverman052e69d2017-02-12 16:19:55 -080033 self.free_speed_rpm = 18730.0
34 # Free Speed in rotations/second.
35 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080036 # Free Current in Amps
37 self.free_current = 0.7 * self.num_motors
38 # Moment of inertia of the shooter wheel in kg m^2
39 # 1400.6 grams/cm^2
40 # 1.407 *1e-4 kg m^2
Austin Schuheb5c22e2017-04-09 18:30:28 -070041 self.J = 0.00100
Austin Schuh48d60c12017-02-04 21:58:58 -080042 # Resistance of the motor, divided by 2 to account for the 2 motors
43 self.R = 12.0 / self.stall_current
44 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080045 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh48d60c12017-02-04 21:58:58 -080046 (12.0 - self.R * self.free_current))
47 # Torque constant
48 self.Kt = self.stall_torque / self.stall_current
49 # Gear ratio
50 self.G = 12.0 / 36.0
51 # Control loop time step
52 self.dt = 0.005
53
54 # State feedback matrices
55 # [angular velocity]
56 self.A_continuous = numpy.matrix(
57 [[-self.Kt / (self.Kv * self.J * self.G * self.G * self.R)]])
58 self.B_continuous = numpy.matrix(
59 [[self.Kt / (self.J * self.G * self.R)]])
60 self.C = numpy.matrix([[1]])
61 self.D = numpy.matrix([[0]])
62
Austin Schuhc66b6fc2017-03-25 19:56:59 -070063 # The states are [unfiltered_velocity]
Austin Schuh48d60c12017-02-04 21:58:58 -080064 self.A, self.B = self.ContinuousToDiscrete(
65 self.A_continuous, self.B_continuous, self.dt)
66
Austin Schuh9f9adb62017-03-05 01:01:37 -080067 self.PlaceControllerPoles([.75])
Austin Schuh48d60c12017-02-04 21:58:58 -080068
Austin Schuhcd3237a2017-02-18 14:19:26 -080069 glog.debug('K %s', repr(self.K))
Austin Schuhc66b6fc2017-03-25 19:56:59 -070070 glog.debug('System poles are %s',
71 repr(numpy.linalg.eig(self.A_continuous)[0]))
Austin Schuhcd3237a2017-02-18 14:19:26 -080072 glog.debug('Poles are %s',
73 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
74
Austin Schuh48d60c12017-02-04 21:58:58 -080075 self.PlaceObserverPoles([0.3])
76
77 self.U_max = numpy.matrix([[12.0]])
78 self.U_min = numpy.matrix([[-12.0]])
79
80 qff_vel = 8.0
81 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
82
83 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
84 self.InitializeState()
85
Austin Schuhc66b6fc2017-03-25 19:56:59 -070086class SecondOrderVelocityShooter(VelocityShooter):
87 def __init__(self, name='SecondOrderVelocityShooter'):
88 super(SecondOrderVelocityShooter, self).__init__(name)
Austin Schuh48d60c12017-02-04 21:58:58 -080089
Austin Schuhc66b6fc2017-03-25 19:56:59 -070090 self.A_continuous_unaugmented = self.A_continuous
91 self.B_continuous_unaugmented = self.B_continuous
92
93 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
94 self.A_continuous[0:1, 0:1] = self.A_continuous_unaugmented
Austin Schuheb5c22e2017-04-09 18:30:28 -070095 self.A_continuous[1, 0] = 225.0
96 self.A_continuous[1, 1] = -self.A_continuous[1, 0]
Austin Schuhc66b6fc2017-03-25 19:56:59 -070097
98 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
99 self.B_continuous[0:1, 0] = self.B_continuous_unaugmented
100
101 self.C = numpy.matrix([[0, 1]])
102 self.D = numpy.matrix([[0]])
103
Austin Schuheb5c22e2017-04-09 18:30:28 -0700104 # The states are [unfiltered_velocity, velocity]
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700105 self.A, self.B = self.ContinuousToDiscrete(
106 self.A_continuous, self.B_continuous, self.dt)
107
Austin Schuheb5c22e2017-04-09 18:30:28 -0700108 self.PlaceControllerPoles([.70, 0.60])
109
110 q_vel = 40.0
111 q_filteredvel = 30.0
112 self.Q = numpy.matrix([[(1.0 / (q_vel ** 2.0)), 0.0],
113 [0.0, (1.0 / (q_filteredvel ** 2.0))]])
114
115 self.R = numpy.matrix([[(1.0 / (3.0 ** 2.0))]])
116 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700117
118 glog.debug('K %s', repr(self.K))
119 glog.debug('System poles are %s',
120 repr(numpy.linalg.eig(self.A_continuous)[0]))
121 glog.debug('Poles are %s',
122 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
123
124 self.PlaceObserverPoles([0.3, 0.3])
125
126 self.U_max = numpy.matrix([[12.0]])
127 self.U_min = numpy.matrix([[-12.0]])
128
129 qff_vel = 8.0
130 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0), 0.0],
131 [0.0, 1.0 / (qff_vel ** 2.0)]])
132
133 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
134 self.InitializeState()
135
136
137class Shooter(SecondOrderVelocityShooter):
Austin Schuh48d60c12017-02-04 21:58:58 -0800138 def __init__(self, name='Shooter'):
139 super(Shooter, self).__init__(name)
140
141 self.A_continuous_unaugmented = self.A_continuous
142 self.B_continuous_unaugmented = self.B_continuous
143
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700144 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
145 self.A_continuous[1:3, 1:3] = self.A_continuous_unaugmented
146 self.A_continuous[0, 2] = 1
Austin Schuh48d60c12017-02-04 21:58:58 -0800147
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700148 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
149 self.B_continuous[1:3, 0] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800150
151 # State feedback matrices
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700152 # [position, unfiltered_velocity, angular velocity]
153 self.C = numpy.matrix([[1, 0, 0]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800154 self.D = numpy.matrix([[0]])
155
156 self.A, self.B = self.ContinuousToDiscrete(
157 self.A_continuous, self.B_continuous, self.dt)
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700158 glog.debug(repr(self.A_continuous))
159 glog.debug(repr(self.B_continuous))
Austin Schuh48d60c12017-02-04 21:58:58 -0800160
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700161 observeability = controls.ctrb(self.A.T, self.C.T)
162 glog.debug('Rank of augmented observability matrix. %d', numpy.linalg.matrix_rank(
163 observeability))
164
165
166 self.PlaceObserverPoles([0.9, 0.8, 0.7])
Austin Schuh48d60c12017-02-04 21:58:58 -0800167
168 self.K_unaugmented = self.K
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700169 self.K = numpy.matrix(numpy.zeros((1, 3)))
170 self.K[0, 1:3] = self.K_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800171 self.Kff_unaugmented = self.Kff
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700172 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
173 self.Kff[0, 1:3] = self.Kff_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800174
175 self.InitializeState()
176
177
178class IntegralShooter(Shooter):
179 def __init__(self, name='IntegralShooter'):
180 super(IntegralShooter, self).__init__(name=name)
181
182 self.A_continuous_unaugmented = self.A_continuous
183 self.B_continuous_unaugmented = self.B_continuous
184
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700185 self.A_continuous = numpy.matrix(numpy.zeros((4, 4)))
186 self.A_continuous[0:3, 0:3] = self.A_continuous_unaugmented
187 self.A_continuous[0:3, 3] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800188
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700189 self.B_continuous = numpy.matrix(numpy.zeros((4, 1)))
190 self.B_continuous[0:3, 0] = self.B_continuous_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800191
192 self.C_unaugmented = self.C
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700193 self.C = numpy.matrix(numpy.zeros((1, 4)))
194 self.C[0:1, 0:3] = self.C_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800195
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700196 # The states are [position, unfiltered_velocity, velocity, torque_error]
Austin Schuh48d60c12017-02-04 21:58:58 -0800197 self.A, self.B = self.ContinuousToDiscrete(
198 self.A_continuous, self.B_continuous, self.dt)
199
Austin Schuh6c20f202017-02-18 22:31:44 -0800200 glog.debug('A: \n%s', repr(self.A_continuous))
201 glog.debug('eig(A): \n%s', repr(scipy.linalg.eig(self.A_continuous)))
202 glog.debug('schur(A): \n%s', repr(scipy.linalg.schur(self.A_continuous)))
203 glog.debug('A_dt(A): \n%s', repr(self.A))
204
Austin Schuhcd3237a2017-02-18 14:19:26 -0800205 q_pos = 0.01
Austin Schuheb5c22e2017-04-09 18:30:28 -0700206 q_vel = 4.0
207 q_velfilt = 1.5
208 q_voltage = 2.0
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700209 self.Q_continuous = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0],
210 [0.0, (q_vel ** 2.0), 0.0, 0.0],
Austin Schuheb5c22e2017-04-09 18:30:28 -0700211 [0.0, 0.0, (q_velfilt ** 2.0), 0.0],
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700212 [0.0, 0.0, 0.0, (q_voltage ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800213
Austin Schuh9f9adb62017-03-05 01:01:37 -0800214 r_pos = 0.0003
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800215 self.R_continuous = numpy.matrix([[(r_pos ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800216
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800217 _, _, self.Q, self.R = controls.kalmd(
218 A_continuous=self.A_continuous, B_continuous=self.B_continuous,
219 Q_continuous=self.Q_continuous, R_continuous=self.R_continuous,
220 dt=self.dt)
221
222 self.KalmanGain, self.P_steady_state = controls.kalman(
Austin Schuh48d60c12017-02-04 21:58:58 -0800223 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
224 self.L = self.A * self.KalmanGain
225
226 self.K_unaugmented = self.K
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700227 self.K = numpy.matrix(numpy.zeros((1, 4)))
228 self.K[0, 0:3] = self.K_unaugmented
229 self.K[0, 3] = 1
Austin Schuh48d60c12017-02-04 21:58:58 -0800230 self.Kff_unaugmented = self.Kff
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700231 self.Kff = numpy.matrix(numpy.zeros((1, 4)))
232 self.Kff[0, 0:3] = self.Kff_unaugmented
Austin Schuh48d60c12017-02-04 21:58:58 -0800233
234 self.InitializeState()
235
236
237class ScenarioPlotter(object):
238 def __init__(self):
239 # Various lists for graphing things.
240 self.t = []
241 self.x = []
242 self.v = []
243 self.a = []
244 self.x_hat = []
245 self.u = []
246 self.offset = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800247 self.diff = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800248
249 def run_test(self, shooter, goal, iterations=200, controller_shooter=None,
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800250 observer_shooter=None, hybrid_obs = False):
Austin Schuh48d60c12017-02-04 21:58:58 -0800251 """Runs the shooter plant with an initial condition and goal.
252
253 Args:
254 shooter: Shooter object to use.
255 goal: goal state.
256 iterations: Number of timesteps to run the model for.
257 controller_shooter: Shooter object to get K from, or None if we should
258 use shooter.
259 observer_shooter: Shooter object to use for the observer, or None if we
260 should use the actual state.
261 """
262
263 if controller_shooter is None:
264 controller_shooter = shooter
265
266 vbat = 12.0
267
268 if self.t:
269 initial_t = self.t[-1] + shooter.dt
270 else:
271 initial_t = 0
272
Austin Schuheb5c22e2017-04-09 18:30:28 -0700273 last_U = numpy.matrix([[0.0]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800274 for i in xrange(iterations):
275 X_hat = shooter.X
276
277 if observer_shooter is not None:
278 X_hat = observer_shooter.X_hat
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700279 self.x_hat.append(observer_shooter.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800280
281 ff_U = controller_shooter.Kff * (goal - observer_shooter.A * goal)
282
283 U = controller_shooter.K * (goal - X_hat) + ff_U
284 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
285 self.x.append(shooter.X[0, 0])
286
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700287 self.diff.append(shooter.X[2, 0] - observer_shooter.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800288
289 if self.v:
290 last_v = self.v[-1]
291 else:
292 last_v = 0
293
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700294 self.v.append(shooter.X[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800295 self.a.append((self.v[-1] - last_v) / shooter.dt)
296
297 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800298 if i != 0:
299 observer_shooter.Y = shooter.Y
300 observer_shooter.CorrectObserver(U)
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700301 self.offset.append(observer_shooter.X_hat[3, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800302
Austin Schuheb5c22e2017-04-09 18:30:28 -0700303 applied_U = last_U.copy()
304 if i > 60:
Austin Schuh48d60c12017-02-04 21:58:58 -0800305 applied_U += 2
306 shooter.Update(applied_U)
307
308 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800309 if hybrid_obs:
Austin Schuheb5c22e2017-04-09 18:30:28 -0700310 observer_shooter.PredictHybridObserver(last_U, shooter.dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800311 else:
Austin Schuheb5c22e2017-04-09 18:30:28 -0700312 observer_shooter.PredictObserver(last_U)
313 last_U = U.copy()
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800314
Austin Schuh48d60c12017-02-04 21:58:58 -0800315
316 self.t.append(initial_t + i * shooter.dt)
317 self.u.append(U[0, 0])
318
Austin Schuh48d60c12017-02-04 21:58:58 -0800319 def Plot(self):
Austin Schuh9f9adb62017-03-05 01:01:37 -0800320 pylab.figure()
Austin Schuh48d60c12017-02-04 21:58:58 -0800321 pylab.subplot(3, 1, 1)
322 pylab.plot(self.t, self.v, label='x')
323 pylab.plot(self.t, self.x_hat, label='x_hat')
324 pylab.legend()
325
326 pylab.subplot(3, 1, 2)
327 pylab.plot(self.t, self.u, label='u')
328 pylab.plot(self.t, self.offset, label='voltage_offset')
329 pylab.legend()
330
331 pylab.subplot(3, 1, 3)
332 pylab.plot(self.t, self.a, label='a')
333 pylab.legend()
334
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800335 pylab.draw()
Austin Schuh48d60c12017-02-04 21:58:58 -0800336
337
338def main(argv):
339 scenario_plotter = ScenarioPlotter()
340
Austin Schuh48d60c12017-02-04 21:58:58 -0800341 if FLAGS.plot:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800342 iterations = 200
343
Austin Schuhc66b6fc2017-03-25 19:56:59 -0700344 initial_X = numpy.matrix([[0.0], [0.0], [0.0]])
345 R = numpy.matrix([[0.0], [100.0], [100.0], [0.0]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800346
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800347 scenario_plotter_int = ScenarioPlotter()
348
349 shooter = Shooter()
350 shooter_controller = IntegralShooter()
351 observer_shooter_hybrid = IntegralShooter()
352
353 scenario_plotter_int.run_test(shooter, goal=R, controller_shooter=shooter_controller,
354 observer_shooter=observer_shooter_hybrid, iterations=iterations,
355 hybrid_obs = True)
356
357 scenario_plotter_int.Plot()
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800358
359 pylab.show()
360
Austin Schuh48d60c12017-02-04 21:58:58 -0800361 if len(argv) != 5:
362 glog.fatal('Expected .h file name and .cc file name')
363 else:
364 namespaces = ['y2017', 'control_loops', 'superstructure', 'shooter']
365 shooter = Shooter('Shooter')
366 loop_writer = control_loop.ControlLoopWriter('Shooter', [shooter],
367 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800368 loop_writer.AddConstant(control_loop.Constant(
369 'kFreeSpeed', '%f', shooter.free_speed))
370 loop_writer.AddConstant(control_loop.Constant(
371 'kOutputRatio', '%f', shooter.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800372 loop_writer.Write(argv[1], argv[2])
373
374 integral_shooter = IntegralShooter('IntegralShooter')
375 integral_loop_writer = control_loop.ControlLoopWriter(
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800376 'IntegralShooter', [integral_shooter], namespaces=namespaces,
377 plant_type='StateFeedbackHybridPlant',
378 observer_type='HybridKalman')
Austin Schuh48d60c12017-02-04 21:58:58 -0800379 integral_loop_writer.Write(argv[3], argv[4])
380
381
382if __name__ == '__main__':
383 argv = FLAGS(sys.argv)
384 glog.init()
385 sys.exit(main(argv))