blob: f6a2379383f15aad2652f55de2287ca483a82f31 [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
Austin Schuh82a66dc2017-03-04 15:06:44 -080014try:
15 gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
16except gflags.DuplicateFlagError:
17 pass
Austin Schuh48d60c12017-02-04 21:58:58 -080018
Austin Schuhcd3237a2017-02-18 14:19:26 -080019gflags.DEFINE_bool('stall', False, 'If true, stall the indexer.')
20
Austin Schuh48d60c12017-02-04 21:58:58 -080021class VelocityIndexer(control_loop.ControlLoop):
22 def __init__(self, name='VelocityIndexer'):
23 super(VelocityIndexer, self).__init__(name)
24 # Stall Torque in N m
25 self.stall_torque = 0.71
26 # Stall Current in Amps
27 self.stall_current = 134
Brian Silverman052e69d2017-02-12 16:19:55 -080028 self.free_speed_rpm = 18730.0
29 # Free Speed in rotations/second.
30 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080031 # Free Current in Amps
32 self.free_current = 0.7
33 # Moment of inertia of the indexer halves in kg m^2
34 # This is measured as Iyy in CAD (the moment of inertia around the Y axis).
35 # Inner part of indexer -> Iyy = 59500 lb * mm * mm
36 # Inner spins with 12 / 48 * 18 / 48 * 24 / 36 * 16 / 72
37 # Outer part of indexer -> Iyy = 210000 lb * mm * mm
38 # 1 775 pro -> 12 / 48 * 18 / 48 * 30 / 422
39
40 self.J_inner = 0.0269
41 self.J_outer = 0.0952
42 # Gear ratios for the inner and outer parts.
Ed Jordan8683f432017-02-12 00:13:26 +000043 self.G_inner = (12.0 / 48.0) * (18.0 / 36.0) * (12.0 / 84.0)
44 self.G_outer = (12.0 / 48.0) * (18.0 / 36.0) * (24.0 / 420.0)
Austin Schuh48d60c12017-02-04 21:58:58 -080045
Austin Schuh82a66dc2017-03-04 15:06:44 -080046 # Motor inertia in kg m^2
47 self.motor_inertia = 0.00001187
Austin Schuh48d60c12017-02-04 21:58:58 -080048
49 # The output coordinate system is in radians for the inner part of the
50 # indexer.
51 # Compute the effective moment of inertia assuming all the mass is in that
52 # coordinate system.
53 self.J = (
54 self.J_inner * self.G_inner * self.G_inner +
55 self.J_outer * self.G_outer * self.G_outer) / (self.G_inner * self.G_inner) + \
56 self.motor_inertia * ((1.0 / self.G_inner) ** 2.0)
Austin Schuh48d60c12017-02-04 21:58:58 -080057 self.G = self.G_inner
58
59 # Resistance of the motor, divided by 2 to account for the 2 motors
Austin Schuh82a66dc2017-03-04 15:06:44 -080060 self.resistance = 12.0 / self.stall_current
Austin Schuh48d60c12017-02-04 21:58:58 -080061 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080062 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh82a66dc2017-03-04 15:06:44 -080063 (12.0 - self.resistance * self.free_current))
Austin Schuh48d60c12017-02-04 21:58:58 -080064 # Torque constant
65 self.Kt = self.stall_torque / self.stall_current
66 # Control loop time step
67 self.dt = 0.005
68
69 # State feedback matrices
70 # [angular velocity]
71 self.A_continuous = numpy.matrix(
Austin Schuh82a66dc2017-03-04 15:06:44 -080072 [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.resistance)]])
Austin Schuh48d60c12017-02-04 21:58:58 -080073 self.B_continuous = numpy.matrix(
Austin Schuh82a66dc2017-03-04 15:06:44 -080074 [[self.Kt / (self.J * self.G * self.resistance)]])
Austin Schuh48d60c12017-02-04 21:58:58 -080075 self.C = numpy.matrix([[1]])
76 self.D = numpy.matrix([[0]])
77
78 self.A, self.B = self.ContinuousToDiscrete(
79 self.A_continuous, self.B_continuous, self.dt)
80
Austin Schuha4dd26d2017-02-24 19:14:39 -080081 self.PlaceControllerPoles([.75])
Austin Schuh48d60c12017-02-04 21:58:58 -080082
83 self.PlaceObserverPoles([0.3])
84
85 self.U_max = numpy.matrix([[12.0]])
86 self.U_min = numpy.matrix([[-12.0]])
87
88 qff_vel = 8.0
89 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
90
91 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
92 self.InitializeState()
93
94
95class Indexer(VelocityIndexer):
96 def __init__(self, name='Indexer'):
97 super(Indexer, self).__init__(name)
98
99 self.A_continuous_unaugmented = self.A_continuous
100 self.B_continuous_unaugmented = self.B_continuous
101
102 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
103 self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
104 self.A_continuous[0, 1] = 1
105
106 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
107 self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
108
109 # State feedback matrices
110 # [position, angular velocity]
111 self.C = numpy.matrix([[1, 0]])
112 self.D = numpy.matrix([[0]])
113
114 self.A, self.B = self.ContinuousToDiscrete(
115 self.A_continuous, self.B_continuous, self.dt)
116
117 self.rpl = .45
118 self.ipl = 0.07
119 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
120 self.rpl - 1j * self.ipl])
121
122 self.K_unaugmented = self.K
123 self.K = numpy.matrix(numpy.zeros((1, 2)))
124 self.K[0, 1:2] = self.K_unaugmented
125 self.Kff_unaugmented = self.Kff
126 self.Kff = numpy.matrix(numpy.zeros((1, 2)))
127 self.Kff[0, 1:2] = self.Kff_unaugmented
128
129 self.InitializeState()
130
131
132class IntegralIndexer(Indexer):
Austin Schuhcd3237a2017-02-18 14:19:26 -0800133 def __init__(self, name="IntegralIndexer", voltage_error_noise=None):
Austin Schuh48d60c12017-02-04 21:58:58 -0800134 super(IntegralIndexer, self).__init__(name=name)
135
136 self.A_continuous_unaugmented = self.A_continuous
137 self.B_continuous_unaugmented = self.B_continuous
138
139 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
140 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
141 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
142
143 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
144 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
145
146 self.C_unaugmented = self.C
147 self.C = numpy.matrix(numpy.zeros((1, 3)))
148 self.C[0:1, 0:2] = self.C_unaugmented
149
150 self.A, self.B = self.ContinuousToDiscrete(
151 self.A_continuous, self.B_continuous, self.dt)
152
Austin Schuhcd3237a2017-02-18 14:19:26 -0800153 q_pos = 0.01
154 q_vel = 2.0
Austin Schuha4dd26d2017-02-24 19:14:39 -0800155 q_voltage = 0.6
Austin Schuhcd3237a2017-02-18 14:19:26 -0800156 if voltage_error_noise is not None:
157 q_voltage = voltage_error_noise
158
Austin Schuh48d60c12017-02-04 21:58:58 -0800159 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
160 [0.0, (q_vel ** 2.0), 0.0],
161 [0.0, 0.0, (q_voltage ** 2.0)]])
162
163 r_pos = 0.001
164 self.R = numpy.matrix([[(r_pos ** 2.0)]])
165
166 self.KalmanGain, self.Q_steady = controls.kalman(
167 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
168 self.L = self.A * self.KalmanGain
169
170 self.K_unaugmented = self.K
171 self.K = numpy.matrix(numpy.zeros((1, 3)))
172 self.K[0, 0:2] = self.K_unaugmented
173 self.K[0, 2] = 1
174 self.Kff_unaugmented = self.Kff
175 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
176 self.Kff[0, 0:2] = self.Kff_unaugmented
177
178 self.InitializeState()
179
180
181class ScenarioPlotter(object):
182 def __init__(self):
183 # Various lists for graphing things.
184 self.t = []
185 self.x = []
186 self.v = []
187 self.a = []
Austin Schuhcd3237a2017-02-18 14:19:26 -0800188 self.stall_ratio = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800189 self.x_hat = []
190 self.u = []
191 self.offset = []
192
193 def run_test(self, indexer, goal, iterations=200, controller_indexer=None,
194 observer_indexer=None):
195 """Runs the indexer plant with an initial condition and goal.
196
197 Args:
198 indexer: Indexer object to use.
199 goal: goal state.
200 iterations: Number of timesteps to run the model for.
201 controller_indexer: Indexer object to get K from, or None if we should
202 use indexer.
203 observer_indexer: Indexer object to use for the observer, or None if we
204 should use the actual state.
205 """
206
207 if controller_indexer is None:
208 controller_indexer = indexer
209
210 vbat = 12.0
211
212 if self.t:
213 initial_t = self.t[-1] + indexer.dt
214 else:
215 initial_t = 0
216
217 for i in xrange(iterations):
218 X_hat = indexer.X
219
220 if observer_indexer is not None:
221 X_hat = observer_indexer.X_hat
Austin Schuhcd3237a2017-02-18 14:19:26 -0800222 observer_indexer.Y = indexer.Y
223 observer_indexer.CorrectObserver(numpy.matrix([[0.0]]))
Austin Schuh48d60c12017-02-04 21:58:58 -0800224 self.x_hat.append(observer_indexer.X_hat[1, 0])
Austin Schuhcd3237a2017-02-18 14:19:26 -0800225 self.offset.append(observer_indexer.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800226
227 ff_U = controller_indexer.Kff * (goal - observer_indexer.A * goal)
228
229 U = controller_indexer.K * (goal - X_hat) + ff_U
230 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
231 self.x.append(indexer.X[0, 0])
232
Austin Schuh48d60c12017-02-04 21:58:58 -0800233 if self.v:
234 last_v = self.v[-1]
235 else:
236 last_v = 0
237
238 self.v.append(indexer.X[1, 0])
239 self.a.append((self.v[-1] - last_v) / indexer.dt)
240
Austin Schuh48d60c12017-02-04 21:58:58 -0800241 applied_U = U.copy()
Austin Schuhcd3237a2017-02-18 14:19:26 -0800242 if i >= 40:
243 applied_U -= 2
244
245 if FLAGS.stall and i >= 40:
246 indexer.X[1, 0] = 0.0
247 else:
248 indexer.Update(applied_U)
Austin Schuh48d60c12017-02-04 21:58:58 -0800249
250 if observer_indexer is not None:
Austin Schuhcd3237a2017-02-18 14:19:26 -0800251 clipped_u = U[0, 0]
252 clip_u_value = 3.0
253 if clipped_u < 0:
254 clipped_u = min(clipped_u, -clip_u_value)
255 else:
256 clipped_u = max(clipped_u, clip_u_value)
257
258 self.stall_ratio.append(10 * (-self.offset[-1] / clipped_u))
259
Austin Schuh48d60c12017-02-04 21:58:58 -0800260 observer_indexer.PredictObserver(U)
261
262 self.t.append(initial_t + i * indexer.dt)
263 self.u.append(U[0, 0])
264
265 def Plot(self):
266 pylab.subplot(3, 1, 1)
267 pylab.plot(self.t, self.v, label='x')
268 pylab.plot(self.t, self.x_hat, label='x_hat')
269 pylab.legend()
270
271 pylab.subplot(3, 1, 2)
272 pylab.plot(self.t, self.u, label='u')
273 pylab.plot(self.t, self.offset, label='voltage_offset')
Austin Schuhcd3237a2017-02-18 14:19:26 -0800274 pylab.plot(self.t, self.stall_ratio, label='stall_ratio')
275 pylab.plot(self.t,
276 [10.0 if x > 6.0 else 0.0 for x in self.stall_ratio],
277 label='is_stalled')
Austin Schuh48d60c12017-02-04 21:58:58 -0800278 pylab.legend()
279
280 pylab.subplot(3, 1, 3)
281 pylab.plot(self.t, self.a, label='a')
282 pylab.legend()
283
284 pylab.show()
285
286
287def main(argv):
288 scenario_plotter = ScenarioPlotter()
289
290 indexer = Indexer()
291 indexer_controller = IntegralIndexer()
292 observer_indexer = IntegralIndexer()
293
294 initial_X = numpy.matrix([[0.0], [0.0]])
295 R = numpy.matrix([[0.0], [20.0], [0.0]])
296 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
297 observer_indexer=observer_indexer, iterations=200)
298
299 if FLAGS.plot:
300 scenario_plotter.Plot()
301
Austin Schuhcd3237a2017-02-18 14:19:26 -0800302 scenario_plotter = ScenarioPlotter()
303
304 indexer = Indexer()
305 indexer_controller = IntegralIndexer(voltage_error_noise=1.5)
306 observer_indexer = IntegralIndexer(voltage_error_noise=1.5)
307
308 initial_X = numpy.matrix([[0.0], [0.0]])
309 R = numpy.matrix([[0.0], [20.0], [0.0]])
310 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
311 observer_indexer=observer_indexer, iterations=200)
312
313 if FLAGS.plot:
314 scenario_plotter.Plot()
315
316 if len(argv) != 7:
317 glog.fatal('Expected .h file name and .cc file names')
Austin Schuh48d60c12017-02-04 21:58:58 -0800318 else:
319 namespaces = ['y2017', 'control_loops', 'superstructure', 'indexer']
320 indexer = Indexer('Indexer')
321 loop_writer = control_loop.ControlLoopWriter('Indexer', [indexer],
322 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800323 loop_writer.AddConstant(control_loop.Constant(
324 'kFreeSpeed', '%f', indexer.free_speed))
325 loop_writer.AddConstant(control_loop.Constant(
326 'kOutputRatio', '%f', indexer.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800327 loop_writer.Write(argv[1], argv[2])
328
329 integral_indexer = IntegralIndexer('IntegralIndexer')
330 integral_loop_writer = control_loop.ControlLoopWriter(
331 'IntegralIndexer', [integral_indexer], namespaces=namespaces)
332 integral_loop_writer.Write(argv[3], argv[4])
333
Austin Schuhcd3237a2017-02-18 14:19:26 -0800334 stuck_integral_indexer = IntegralIndexer('StuckIntegralIndexer', voltage_error_noise=1.5)
335 stuck_integral_loop_writer = control_loop.ControlLoopWriter(
336 'StuckIntegralIndexer', [stuck_integral_indexer], namespaces=namespaces)
337 stuck_integral_loop_writer.Write(argv[5], argv[6])
338
Austin Schuh48d60c12017-02-04 21:58:58 -0800339
340if __name__ == '__main__':
341 argv = FLAGS(sys.argv)
342 glog.init()
343 sys.exit(main(argv))