blob: 0858e450f61e56c6fc0aee5bd72cb7a5dc28eaf4 [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
42 self.J = 0.00080
43 # 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
64 self.A, self.B = self.ContinuousToDiscrete(
65 self.A_continuous, self.B_continuous, self.dt)
66
67 self.PlaceControllerPoles([.90])
68
Austin Schuhcd3237a2017-02-18 14:19:26 -080069 glog.debug('K %s', repr(self.K))
70 glog.debug('Poles are %s',
71 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
72
Austin Schuh48d60c12017-02-04 21:58:58 -080073 self.PlaceObserverPoles([0.3])
74
75 self.U_max = numpy.matrix([[12.0]])
76 self.U_min = numpy.matrix([[-12.0]])
77
78 qff_vel = 8.0
79 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
80
81 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
82 self.InitializeState()
83
84
85class Shooter(VelocityShooter):
86 def __init__(self, name='Shooter'):
87 super(Shooter, self).__init__(name)
88
89 self.A_continuous_unaugmented = self.A_continuous
90 self.B_continuous_unaugmented = self.B_continuous
91
92 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
93 self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
94 self.A_continuous[0, 1] = 1
95
96 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
97 self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
98
99 # State feedback matrices
100 # [position, angular velocity]
101 self.C = numpy.matrix([[1, 0]])
102 self.D = numpy.matrix([[0]])
103
104 self.A, self.B = self.ContinuousToDiscrete(
105 self.A_continuous, self.B_continuous, self.dt)
106
107 self.rpl = .45
108 self.ipl = 0.07
109 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
110 self.rpl - 1j * self.ipl])
111
112 self.K_unaugmented = self.K
113 self.K = numpy.matrix(numpy.zeros((1, 2)))
114 self.K[0, 1:2] = self.K_unaugmented
115 self.Kff_unaugmented = self.Kff
116 self.Kff = numpy.matrix(numpy.zeros((1, 2)))
117 self.Kff[0, 1:2] = self.Kff_unaugmented
118
119 self.InitializeState()
120
121
122class IntegralShooter(Shooter):
123 def __init__(self, name='IntegralShooter'):
124 super(IntegralShooter, self).__init__(name=name)
125
126 self.A_continuous_unaugmented = self.A_continuous
127 self.B_continuous_unaugmented = self.B_continuous
128
129 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
130 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
131 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
132
133 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
134 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
135
136 self.C_unaugmented = self.C
137 self.C = numpy.matrix(numpy.zeros((1, 3)))
138 self.C[0:1, 0:2] = self.C_unaugmented
139
140 self.A, self.B = self.ContinuousToDiscrete(
141 self.A_continuous, self.B_continuous, self.dt)
142
Austin Schuh6c20f202017-02-18 22:31:44 -0800143 glog.debug('A: \n%s', repr(self.A_continuous))
144 glog.debug('eig(A): \n%s', repr(scipy.linalg.eig(self.A_continuous)))
145 glog.debug('schur(A): \n%s', repr(scipy.linalg.schur(self.A_continuous)))
146 glog.debug('A_dt(A): \n%s', repr(self.A))
147
Austin Schuhcd3237a2017-02-18 14:19:26 -0800148 q_pos = 0.01
149 q_vel = 2.0
150 q_voltage = 0.2
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800151 self.Q_continuous = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
152 [0.0, (q_vel ** 2.0), 0.0],
153 [0.0, 0.0, (q_voltage ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800154
155 r_pos = 0.001
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800156 self.R_continuous = numpy.matrix([[(r_pos ** 2.0)]])
Austin Schuh48d60c12017-02-04 21:58:58 -0800157
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800158 _, _, self.Q, self.R = controls.kalmd(
159 A_continuous=self.A_continuous, B_continuous=self.B_continuous,
160 Q_continuous=self.Q_continuous, R_continuous=self.R_continuous,
161 dt=self.dt)
162
163 self.KalmanGain, self.P_steady_state = controls.kalman(
Austin Schuh48d60c12017-02-04 21:58:58 -0800164 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
165 self.L = self.A * self.KalmanGain
166
167 self.K_unaugmented = self.K
168 self.K = numpy.matrix(numpy.zeros((1, 3)))
169 self.K[0, 0:2] = self.K_unaugmented
170 self.K[0, 2] = 1
171 self.Kff_unaugmented = self.Kff
172 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
173 self.Kff[0, 0:2] = self.Kff_unaugmented
174
175 self.InitializeState()
176
177
178class ScenarioPlotter(object):
179 def __init__(self):
180 # Various lists for graphing things.
181 self.t = []
182 self.x = []
183 self.v = []
184 self.a = []
185 self.x_hat = []
186 self.u = []
187 self.offset = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800188 self.diff = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800189
190 def run_test(self, shooter, goal, iterations=200, controller_shooter=None,
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800191 observer_shooter=None, hybrid_obs = False):
Austin Schuh48d60c12017-02-04 21:58:58 -0800192 """Runs the shooter plant with an initial condition and goal.
193
194 Args:
195 shooter: Shooter object to use.
196 goal: goal state.
197 iterations: Number of timesteps to run the model for.
198 controller_shooter: Shooter object to get K from, or None if we should
199 use shooter.
200 observer_shooter: Shooter object to use for the observer, or None if we
201 should use the actual state.
202 """
203
204 if controller_shooter is None:
205 controller_shooter = shooter
206
207 vbat = 12.0
208
209 if self.t:
210 initial_t = self.t[-1] + shooter.dt
211 else:
212 initial_t = 0
213
214 for i in xrange(iterations):
215 X_hat = shooter.X
216
217 if observer_shooter is not None:
218 X_hat = observer_shooter.X_hat
219 self.x_hat.append(observer_shooter.X_hat[1, 0])
220
221 ff_U = controller_shooter.Kff * (goal - observer_shooter.A * goal)
222
223 U = controller_shooter.K * (goal - X_hat) + ff_U
224 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
225 self.x.append(shooter.X[0, 0])
226
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800227 self.diff.append(shooter.X[1, 0] - observer_shooter.X_hat[1, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800228
229 if self.v:
230 last_v = self.v[-1]
231 else:
232 last_v = 0
233
234 self.v.append(shooter.X[1, 0])
235 self.a.append((self.v[-1] - last_v) / shooter.dt)
236
237 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800238 if i != 0:
239 observer_shooter.Y = shooter.Y
240 observer_shooter.CorrectObserver(U)
Austin Schuh48d60c12017-02-04 21:58:58 -0800241 self.offset.append(observer_shooter.X_hat[2, 0])
242
243 applied_U = U.copy()
244 if i > 30:
245 applied_U += 2
246 shooter.Update(applied_U)
247
248 if observer_shooter is not None:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800249 if hybrid_obs:
250 observer_shooter.PredictHybridObserver(U, shooter.dt)
251 else:
252 observer_shooter.PredictObserver(U)
253
Austin Schuh48d60c12017-02-04 21:58:58 -0800254
255 self.t.append(initial_t + i * shooter.dt)
256 self.u.append(U[0, 0])
257
Austin Schuh48d60c12017-02-04 21:58:58 -0800258 def Plot(self):
259 pylab.subplot(3, 1, 1)
260 pylab.plot(self.t, self.v, label='x')
261 pylab.plot(self.t, self.x_hat, label='x_hat')
262 pylab.legend()
263
264 pylab.subplot(3, 1, 2)
265 pylab.plot(self.t, self.u, label='u')
266 pylab.plot(self.t, self.offset, label='voltage_offset')
267 pylab.legend()
268
269 pylab.subplot(3, 1, 3)
270 pylab.plot(self.t, self.a, label='a')
271 pylab.legend()
272
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800273 pylab.figure()
274 pylab.draw()
Austin Schuh48d60c12017-02-04 21:58:58 -0800275
276
277def main(argv):
278 scenario_plotter = ScenarioPlotter()
279
Austin Schuh48d60c12017-02-04 21:58:58 -0800280 if FLAGS.plot:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800281 shooter = Shooter()
282 shooter_controller = IntegralShooter()
283 observer_shooter = IntegralShooter()
284 iterations = 200
285
286 initial_X = numpy.matrix([[0.0], [0.0]])
287 R = numpy.matrix([[0.0], [100.0], [0.0]])
288 scenario_plotter.run_test(shooter, goal=R, controller_shooter=shooter_controller,
289 observer_shooter=observer_shooter, iterations=iterations)
290
Austin Schuh48d60c12017-02-04 21:58:58 -0800291 scenario_plotter.Plot()
292
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800293 scenario_plotter_int = ScenarioPlotter()
294
295 shooter = Shooter()
296 shooter_controller = IntegralShooter()
297 observer_shooter_hybrid = IntegralShooter()
298
299 scenario_plotter_int.run_test(shooter, goal=R, controller_shooter=shooter_controller,
300 observer_shooter=observer_shooter_hybrid, iterations=iterations,
301 hybrid_obs = True)
302
303 scenario_plotter_int.Plot()
304 PlotDiff(scenario_plotter.x_hat, scenario_plotter_int.x_hat,
305 scenario_plotter.t)
306
307 pylab.show()
308
Austin Schuh48d60c12017-02-04 21:58:58 -0800309 if len(argv) != 5:
310 glog.fatal('Expected .h file name and .cc file name')
311 else:
312 namespaces = ['y2017', 'control_loops', 'superstructure', 'shooter']
313 shooter = Shooter('Shooter')
314 loop_writer = control_loop.ControlLoopWriter('Shooter', [shooter],
315 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800316 loop_writer.AddConstant(control_loop.Constant(
317 'kFreeSpeed', '%f', shooter.free_speed))
318 loop_writer.AddConstant(control_loop.Constant(
319 'kOutputRatio', '%f', shooter.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800320 loop_writer.Write(argv[1], argv[2])
321
322 integral_shooter = IntegralShooter('IntegralShooter')
323 integral_loop_writer = control_loop.ControlLoopWriter(
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800324 'IntegralShooter', [integral_shooter], namespaces=namespaces,
325 plant_type='StateFeedbackHybridPlant',
326 observer_type='HybridKalman')
Austin Schuh48d60c12017-02-04 21:58:58 -0800327 integral_loop_writer.Write(argv[3], argv[4])
328
329
330if __name__ == '__main__':
331 argv = FLAGS(sys.argv)
332 glog.init()
333 sys.exit(main(argv))