blob: 1818d62b77828450df1c66ab6bf537cc73a7264f [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
6import sys
7from matplotlib import pylab
8
9import gflags
10import glog
11
12FLAGS = gflags.FLAGS
13
14gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
15
Austin Schuhcd3237a2017-02-18 14:19:26 -080016gflags.DEFINE_bool('stall', False, 'If true, stall the indexer.')
17
Austin Schuh48d60c12017-02-04 21:58:58 -080018class VelocityIndexer(control_loop.ControlLoop):
19 def __init__(self, name='VelocityIndexer'):
20 super(VelocityIndexer, self).__init__(name)
21 # Stall Torque in N m
22 self.stall_torque = 0.71
23 # Stall Current in Amps
24 self.stall_current = 134
Brian Silverman052e69d2017-02-12 16:19:55 -080025 self.free_speed_rpm = 18730.0
26 # Free Speed in rotations/second.
27 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080028 # Free Current in Amps
29 self.free_current = 0.7
30 # Moment of inertia of the indexer halves in kg m^2
31 # This is measured as Iyy in CAD (the moment of inertia around the Y axis).
32 # Inner part of indexer -> Iyy = 59500 lb * mm * mm
33 # Inner spins with 12 / 48 * 18 / 48 * 24 / 36 * 16 / 72
34 # Outer part of indexer -> Iyy = 210000 lb * mm * mm
35 # 1 775 pro -> 12 / 48 * 18 / 48 * 30 / 422
36
37 self.J_inner = 0.0269
38 self.J_outer = 0.0952
39 # Gear ratios for the inner and outer parts.
Ed Jordan8683f432017-02-12 00:13:26 +000040 self.G_inner = (12.0 / 48.0) * (18.0 / 36.0) * (12.0 / 84.0)
41 self.G_outer = (12.0 / 48.0) * (18.0 / 36.0) * (24.0 / 420.0)
Austin Schuh48d60c12017-02-04 21:58:58 -080042
43 # Motor inertia in kg * m^2
44 self.motor_inertia = 0.000006
45
46 # The output coordinate system is in radians for the inner part of the
47 # indexer.
48 # Compute the effective moment of inertia assuming all the mass is in that
49 # coordinate system.
50 self.J = (
51 self.J_inner * self.G_inner * self.G_inner +
52 self.J_outer * self.G_outer * self.G_outer) / (self.G_inner * self.G_inner) + \
53 self.motor_inertia * ((1.0 / self.G_inner) ** 2.0)
54 glog.debug('J is %f', self.J)
55 self.G = self.G_inner
56
57 # Resistance of the motor, divided by 2 to account for the 2 motors
58 self.R = 12.0 / self.stall_current
59 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080060 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh48d60c12017-02-04 21:58:58 -080061 (12.0 - self.R * self.free_current))
62 # Torque constant
63 self.Kt = self.stall_torque / self.stall_current
64 # Control loop time step
65 self.dt = 0.005
66
67 # State feedback matrices
68 # [angular velocity]
69 self.A_continuous = numpy.matrix(
70 [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.R)]])
71 self.B_continuous = numpy.matrix(
72 [[self.Kt / (self.J * self.G * self.R)]])
73 self.C = numpy.matrix([[1]])
74 self.D = numpy.matrix([[0]])
75
76 self.A, self.B = self.ContinuousToDiscrete(
77 self.A_continuous, self.B_continuous, self.dt)
78
Austin Schuha4dd26d2017-02-24 19:14:39 -080079 self.PlaceControllerPoles([.75])
Austin Schuhcd3237a2017-02-18 14:19:26 -080080 glog.debug('K: %s', repr(self.K))
81
82 glog.debug('Poles are %s',
83 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
Austin Schuh48d60c12017-02-04 21:58:58 -080084
85 self.PlaceObserverPoles([0.3])
86
87 self.U_max = numpy.matrix([[12.0]])
88 self.U_min = numpy.matrix([[-12.0]])
89
90 qff_vel = 8.0
91 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
92
93 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
94 self.InitializeState()
95
96
97class Indexer(VelocityIndexer):
98 def __init__(self, name='Indexer'):
99 super(Indexer, self).__init__(name)
100
101 self.A_continuous_unaugmented = self.A_continuous
102 self.B_continuous_unaugmented = self.B_continuous
103
104 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
105 self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
106 self.A_continuous[0, 1] = 1
107
108 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
109 self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
110
111 # State feedback matrices
112 # [position, angular velocity]
113 self.C = numpy.matrix([[1, 0]])
114 self.D = numpy.matrix([[0]])
115
116 self.A, self.B = self.ContinuousToDiscrete(
117 self.A_continuous, self.B_continuous, self.dt)
118
119 self.rpl = .45
120 self.ipl = 0.07
121 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
122 self.rpl - 1j * self.ipl])
123
124 self.K_unaugmented = self.K
125 self.K = numpy.matrix(numpy.zeros((1, 2)))
126 self.K[0, 1:2] = self.K_unaugmented
127 self.Kff_unaugmented = self.Kff
128 self.Kff = numpy.matrix(numpy.zeros((1, 2)))
129 self.Kff[0, 1:2] = self.Kff_unaugmented
130
131 self.InitializeState()
132
133
134class IntegralIndexer(Indexer):
Austin Schuhcd3237a2017-02-18 14:19:26 -0800135 def __init__(self, name="IntegralIndexer", voltage_error_noise=None):
Austin Schuh48d60c12017-02-04 21:58:58 -0800136 super(IntegralIndexer, self).__init__(name=name)
137
138 self.A_continuous_unaugmented = self.A_continuous
139 self.B_continuous_unaugmented = self.B_continuous
140
141 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
142 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
143 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
144
145 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
146 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
147
148 self.C_unaugmented = self.C
149 self.C = numpy.matrix(numpy.zeros((1, 3)))
150 self.C[0:1, 0:2] = self.C_unaugmented
151
152 self.A, self.B = self.ContinuousToDiscrete(
153 self.A_continuous, self.B_continuous, self.dt)
154
Austin Schuhcd3237a2017-02-18 14:19:26 -0800155 q_pos = 0.01
156 q_vel = 2.0
Austin Schuha4dd26d2017-02-24 19:14:39 -0800157 q_voltage = 0.6
Austin Schuhcd3237a2017-02-18 14:19:26 -0800158 if voltage_error_noise is not None:
159 q_voltage = voltage_error_noise
160
Austin Schuh48d60c12017-02-04 21:58:58 -0800161 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
162 [0.0, (q_vel ** 2.0), 0.0],
163 [0.0, 0.0, (q_voltage ** 2.0)]])
164
165 r_pos = 0.001
166 self.R = numpy.matrix([[(r_pos ** 2.0)]])
167
168 self.KalmanGain, self.Q_steady = controls.kalman(
169 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
170 self.L = self.A * self.KalmanGain
171
172 self.K_unaugmented = self.K
173 self.K = numpy.matrix(numpy.zeros((1, 3)))
174 self.K[0, 0:2] = self.K_unaugmented
175 self.K[0, 2] = 1
176 self.Kff_unaugmented = self.Kff
177 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
178 self.Kff[0, 0:2] = self.Kff_unaugmented
179
180 self.InitializeState()
181
182
183class ScenarioPlotter(object):
184 def __init__(self):
185 # Various lists for graphing things.
186 self.t = []
187 self.x = []
188 self.v = []
189 self.a = []
Austin Schuhcd3237a2017-02-18 14:19:26 -0800190 self.stall_ratio = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800191 self.x_hat = []
192 self.u = []
193 self.offset = []
194
195 def run_test(self, indexer, goal, iterations=200, controller_indexer=None,
196 observer_indexer=None):
197 """Runs the indexer plant with an initial condition and goal.
198
199 Args:
200 indexer: Indexer object to use.
201 goal: goal state.
202 iterations: Number of timesteps to run the model for.
203 controller_indexer: Indexer object to get K from, or None if we should
204 use indexer.
205 observer_indexer: Indexer object to use for the observer, or None if we
206 should use the actual state.
207 """
208
209 if controller_indexer is None:
210 controller_indexer = indexer
211
212 vbat = 12.0
213
214 if self.t:
215 initial_t = self.t[-1] + indexer.dt
216 else:
217 initial_t = 0
218
219 for i in xrange(iterations):
220 X_hat = indexer.X
221
222 if observer_indexer is not None:
223 X_hat = observer_indexer.X_hat
Austin Schuhcd3237a2017-02-18 14:19:26 -0800224 observer_indexer.Y = indexer.Y
225 observer_indexer.CorrectObserver(numpy.matrix([[0.0]]))
Austin Schuh48d60c12017-02-04 21:58:58 -0800226 self.x_hat.append(observer_indexer.X_hat[1, 0])
Austin Schuhcd3237a2017-02-18 14:19:26 -0800227 self.offset.append(observer_indexer.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800228
229 ff_U = controller_indexer.Kff * (goal - observer_indexer.A * goal)
230
231 U = controller_indexer.K * (goal - X_hat) + ff_U
232 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
233 self.x.append(indexer.X[0, 0])
234
Austin Schuh48d60c12017-02-04 21:58:58 -0800235 if self.v:
236 last_v = self.v[-1]
237 else:
238 last_v = 0
239
240 self.v.append(indexer.X[1, 0])
241 self.a.append((self.v[-1] - last_v) / indexer.dt)
242
Austin Schuh48d60c12017-02-04 21:58:58 -0800243 applied_U = U.copy()
Austin Schuhcd3237a2017-02-18 14:19:26 -0800244 if i >= 40:
245 applied_U -= 2
246
247 if FLAGS.stall and i >= 40:
248 indexer.X[1, 0] = 0.0
249 else:
250 indexer.Update(applied_U)
Austin Schuh48d60c12017-02-04 21:58:58 -0800251
252 if observer_indexer is not None:
Austin Schuhcd3237a2017-02-18 14:19:26 -0800253 clipped_u = U[0, 0]
254 clip_u_value = 3.0
255 if clipped_u < 0:
256 clipped_u = min(clipped_u, -clip_u_value)
257 else:
258 clipped_u = max(clipped_u, clip_u_value)
259
260 self.stall_ratio.append(10 * (-self.offset[-1] / clipped_u))
261
Austin Schuh48d60c12017-02-04 21:58:58 -0800262 observer_indexer.PredictObserver(U)
263
264 self.t.append(initial_t + i * indexer.dt)
265 self.u.append(U[0, 0])
266
267 def Plot(self):
268 pylab.subplot(3, 1, 1)
269 pylab.plot(self.t, self.v, label='x')
270 pylab.plot(self.t, self.x_hat, label='x_hat')
271 pylab.legend()
272
273 pylab.subplot(3, 1, 2)
274 pylab.plot(self.t, self.u, label='u')
275 pylab.plot(self.t, self.offset, label='voltage_offset')
Austin Schuhcd3237a2017-02-18 14:19:26 -0800276 pylab.plot(self.t, self.stall_ratio, label='stall_ratio')
277 pylab.plot(self.t,
278 [10.0 if x > 6.0 else 0.0 for x in self.stall_ratio],
279 label='is_stalled')
Austin Schuh48d60c12017-02-04 21:58:58 -0800280 pylab.legend()
281
282 pylab.subplot(3, 1, 3)
283 pylab.plot(self.t, self.a, label='a')
284 pylab.legend()
285
286 pylab.show()
287
288
289def main(argv):
290 scenario_plotter = ScenarioPlotter()
291
292 indexer = Indexer()
293 indexer_controller = IntegralIndexer()
294 observer_indexer = IntegralIndexer()
295
296 initial_X = numpy.matrix([[0.0], [0.0]])
297 R = numpy.matrix([[0.0], [20.0], [0.0]])
298 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
299 observer_indexer=observer_indexer, iterations=200)
300
301 if FLAGS.plot:
302 scenario_plotter.Plot()
303
Austin Schuhcd3237a2017-02-18 14:19:26 -0800304 scenario_plotter = ScenarioPlotter()
305
306 indexer = Indexer()
307 indexer_controller = IntegralIndexer(voltage_error_noise=1.5)
308 observer_indexer = IntegralIndexer(voltage_error_noise=1.5)
309
310 initial_X = numpy.matrix([[0.0], [0.0]])
311 R = numpy.matrix([[0.0], [20.0], [0.0]])
312 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
313 observer_indexer=observer_indexer, iterations=200)
314
315 if FLAGS.plot:
316 scenario_plotter.Plot()
317
318 if len(argv) != 7:
319 glog.fatal('Expected .h file name and .cc file names')
Austin Schuh48d60c12017-02-04 21:58:58 -0800320 else:
321 namespaces = ['y2017', 'control_loops', 'superstructure', 'indexer']
322 indexer = Indexer('Indexer')
323 loop_writer = control_loop.ControlLoopWriter('Indexer', [indexer],
324 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800325 loop_writer.AddConstant(control_loop.Constant(
326 'kFreeSpeed', '%f', indexer.free_speed))
327 loop_writer.AddConstant(control_loop.Constant(
328 'kOutputRatio', '%f', indexer.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800329 loop_writer.Write(argv[1], argv[2])
330
331 integral_indexer = IntegralIndexer('IntegralIndexer')
332 integral_loop_writer = control_loop.ControlLoopWriter(
333 'IntegralIndexer', [integral_indexer], namespaces=namespaces)
334 integral_loop_writer.Write(argv[3], argv[4])
335
Austin Schuhcd3237a2017-02-18 14:19:26 -0800336 stuck_integral_indexer = IntegralIndexer('StuckIntegralIndexer', voltage_error_noise=1.5)
337 stuck_integral_loop_writer = control_loop.ControlLoopWriter(
338 'StuckIntegralIndexer', [stuck_integral_indexer], namespaces=namespaces)
339 stuck_integral_loop_writer.Write(argv[5], argv[6])
340
Austin Schuh48d60c12017-02-04 21:58:58 -0800341
342if __name__ == '__main__':
343 argv = FLAGS(sys.argv)
344 glog.init()
345 sys.exit(main(argv))