blob: 7312e57472739848db6cef5e0735ea0d7dc58f92 [file] [log] [blame]
Austin Schuh085eab92020-11-26 13:54:51 -08001#!/usr/bin/python3
Austin Schuh48d60c12017-02-04 21:58:58 -08002
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.
Austin Schuh546a0382017-04-16 19:10:18 -070043 self.G_inner = (12.0 / 48.0) * (20.0 / 34.0) * (18.0 / 36.0) * (12.0 / 84.0)
44 self.G_outer = (12.0 / 48.0) * (20.0 / 34.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 Schuhfbceb1c2017-03-11 22:10:57 -080057 glog.debug('Indexer J is %f', self.J)
Austin Schuh48d60c12017-02-04 21:58:58 -080058 self.G = self.G_inner
59
60 # Resistance of the motor, divided by 2 to account for the 2 motors
Austin Schuh82a66dc2017-03-04 15:06:44 -080061 self.resistance = 12.0 / self.stall_current
Austin Schuh48d60c12017-02-04 21:58:58 -080062 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080063 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh82a66dc2017-03-04 15:06:44 -080064 (12.0 - self.resistance * self.free_current))
Austin Schuh48d60c12017-02-04 21:58:58 -080065 # Torque constant
66 self.Kt = self.stall_torque / self.stall_current
67 # Control loop time step
68 self.dt = 0.005
69
70 # State feedback matrices
71 # [angular velocity]
72 self.A_continuous = numpy.matrix(
Austin Schuh82a66dc2017-03-04 15:06:44 -080073 [[-self.Kt / self.Kv / (self.J * self.G * self.G * self.resistance)]])
Austin Schuh48d60c12017-02-04 21:58:58 -080074 self.B_continuous = numpy.matrix(
Austin Schuh82a66dc2017-03-04 15:06:44 -080075 [[self.Kt / (self.J * self.G * self.resistance)]])
Austin Schuh48d60c12017-02-04 21:58:58 -080076 self.C = numpy.matrix([[1]])
77 self.D = numpy.matrix([[0]])
78
79 self.A, self.B = self.ContinuousToDiscrete(
80 self.A_continuous, self.B_continuous, self.dt)
81
Austin Schuha4dd26d2017-02-24 19:14:39 -080082 self.PlaceControllerPoles([.75])
Austin Schuh48d60c12017-02-04 21:58:58 -080083
84 self.PlaceObserverPoles([0.3])
85
86 self.U_max = numpy.matrix([[12.0]])
87 self.U_min = numpy.matrix([[-12.0]])
88
89 qff_vel = 8.0
90 self.Qff = numpy.matrix([[1.0 / (qff_vel ** 2.0)]])
91
92 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
93 self.InitializeState()
94
95
96class Indexer(VelocityIndexer):
97 def __init__(self, name='Indexer'):
98 super(Indexer, self).__init__(name)
99
100 self.A_continuous_unaugmented = self.A_continuous
101 self.B_continuous_unaugmented = self.B_continuous
102
103 self.A_continuous = numpy.matrix(numpy.zeros((2, 2)))
104 self.A_continuous[1:2, 1:2] = self.A_continuous_unaugmented
105 self.A_continuous[0, 1] = 1
106
107 self.B_continuous = numpy.matrix(numpy.zeros((2, 1)))
108 self.B_continuous[1:2, 0] = self.B_continuous_unaugmented
109
110 # State feedback matrices
111 # [position, angular velocity]
112 self.C = numpy.matrix([[1, 0]])
113 self.D = numpy.matrix([[0]])
114
115 self.A, self.B = self.ContinuousToDiscrete(
116 self.A_continuous, self.B_continuous, self.dt)
117
118 self.rpl = .45
119 self.ipl = 0.07
120 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
121 self.rpl - 1j * self.ipl])
122
123 self.K_unaugmented = self.K
124 self.K = numpy.matrix(numpy.zeros((1, 2)))
125 self.K[0, 1:2] = self.K_unaugmented
126 self.Kff_unaugmented = self.Kff
127 self.Kff = numpy.matrix(numpy.zeros((1, 2)))
128 self.Kff[0, 1:2] = self.Kff_unaugmented
129
130 self.InitializeState()
131
132
133class IntegralIndexer(Indexer):
Austin Schuhcd3237a2017-02-18 14:19:26 -0800134 def __init__(self, name="IntegralIndexer", voltage_error_noise=None):
Austin Schuh48d60c12017-02-04 21:58:58 -0800135 super(IntegralIndexer, self).__init__(name=name)
136
137 self.A_continuous_unaugmented = self.A_continuous
138 self.B_continuous_unaugmented = self.B_continuous
139
140 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
141 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
142 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
143
144 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
145 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
146
147 self.C_unaugmented = self.C
148 self.C = numpy.matrix(numpy.zeros((1, 3)))
149 self.C[0:1, 0:2] = self.C_unaugmented
150
151 self.A, self.B = self.ContinuousToDiscrete(
152 self.A_continuous, self.B_continuous, self.dt)
153
Austin Schuhcd3237a2017-02-18 14:19:26 -0800154 q_pos = 0.01
155 q_vel = 2.0
Austin Schuha4dd26d2017-02-24 19:14:39 -0800156 q_voltage = 0.6
Austin Schuhcd3237a2017-02-18 14:19:26 -0800157 if voltage_error_noise is not None:
158 q_voltage = voltage_error_noise
159
Austin Schuh48d60c12017-02-04 21:58:58 -0800160 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
161 [0.0, (q_vel ** 2.0), 0.0],
162 [0.0, 0.0, (q_voltage ** 2.0)]])
163
164 r_pos = 0.001
165 self.R = numpy.matrix([[(r_pos ** 2.0)]])
166
167 self.KalmanGain, self.Q_steady = controls.kalman(
168 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
169 self.L = self.A * self.KalmanGain
170
171 self.K_unaugmented = self.K
172 self.K = numpy.matrix(numpy.zeros((1, 3)))
173 self.K[0, 0:2] = self.K_unaugmented
174 self.K[0, 2] = 1
175 self.Kff_unaugmented = self.Kff
176 self.Kff = numpy.matrix(numpy.zeros((1, 3)))
177 self.Kff[0, 0:2] = self.Kff_unaugmented
178
179 self.InitializeState()
180
181
182class ScenarioPlotter(object):
183 def __init__(self):
184 # Various lists for graphing things.
185 self.t = []
186 self.x = []
187 self.v = []
188 self.a = []
Austin Schuhcd3237a2017-02-18 14:19:26 -0800189 self.stall_ratio = []
Austin Schuh48d60c12017-02-04 21:58:58 -0800190 self.x_hat = []
191 self.u = []
192 self.offset = []
193
194 def run_test(self, indexer, goal, iterations=200, controller_indexer=None,
195 observer_indexer=None):
196 """Runs the indexer plant with an initial condition and goal.
197
198 Args:
199 indexer: Indexer object to use.
200 goal: goal state.
201 iterations: Number of timesteps to run the model for.
202 controller_indexer: Indexer object to get K from, or None if we should
203 use indexer.
204 observer_indexer: Indexer object to use for the observer, or None if we
205 should use the actual state.
206 """
207
208 if controller_indexer is None:
209 controller_indexer = indexer
210
211 vbat = 12.0
212
213 if self.t:
214 initial_t = self.t[-1] + indexer.dt
215 else:
216 initial_t = 0
217
Austin Schuh5ea48472021-02-02 20:46:41 -0800218 for i in range(iterations):
Austin Schuh48d60c12017-02-04 21:58:58 -0800219 X_hat = indexer.X
220
221 if observer_indexer is not None:
222 X_hat = observer_indexer.X_hat
Austin Schuhcd3237a2017-02-18 14:19:26 -0800223 observer_indexer.Y = indexer.Y
224 observer_indexer.CorrectObserver(numpy.matrix([[0.0]]))
Austin Schuh48d60c12017-02-04 21:58:58 -0800225 self.x_hat.append(observer_indexer.X_hat[1, 0])
Austin Schuhcd3237a2017-02-18 14:19:26 -0800226 self.offset.append(observer_indexer.X_hat[2, 0])
Austin Schuh48d60c12017-02-04 21:58:58 -0800227
228 ff_U = controller_indexer.Kff * (goal - observer_indexer.A * goal)
229
230 U = controller_indexer.K * (goal - X_hat) + ff_U
231 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
232 self.x.append(indexer.X[0, 0])
233
Austin Schuh48d60c12017-02-04 21:58:58 -0800234 if self.v:
235 last_v = self.v[-1]
236 else:
237 last_v = 0
238
239 self.v.append(indexer.X[1, 0])
240 self.a.append((self.v[-1] - last_v) / indexer.dt)
241
Austin Schuh48d60c12017-02-04 21:58:58 -0800242 applied_U = U.copy()
Austin Schuhcd3237a2017-02-18 14:19:26 -0800243 if i >= 40:
244 applied_U -= 2
245
246 if FLAGS.stall and i >= 40:
247 indexer.X[1, 0] = 0.0
248 else:
249 indexer.Update(applied_U)
Austin Schuh48d60c12017-02-04 21:58:58 -0800250
251 if observer_indexer is not None:
Austin Schuhcd3237a2017-02-18 14:19:26 -0800252 clipped_u = U[0, 0]
253 clip_u_value = 3.0
254 if clipped_u < 0:
255 clipped_u = min(clipped_u, -clip_u_value)
256 else:
257 clipped_u = max(clipped_u, clip_u_value)
258
259 self.stall_ratio.append(10 * (-self.offset[-1] / clipped_u))
260
Austin Schuh48d60c12017-02-04 21:58:58 -0800261 observer_indexer.PredictObserver(U)
262
263 self.t.append(initial_t + i * indexer.dt)
264 self.u.append(U[0, 0])
265
266 def Plot(self):
267 pylab.subplot(3, 1, 1)
268 pylab.plot(self.t, self.v, label='x')
269 pylab.plot(self.t, self.x_hat, label='x_hat')
270 pylab.legend()
271
272 pylab.subplot(3, 1, 2)
273 pylab.plot(self.t, self.u, label='u')
274 pylab.plot(self.t, self.offset, label='voltage_offset')
Austin Schuhcd3237a2017-02-18 14:19:26 -0800275 pylab.plot(self.t, self.stall_ratio, label='stall_ratio')
276 pylab.plot(self.t,
277 [10.0 if x > 6.0 else 0.0 for x in self.stall_ratio],
278 label='is_stalled')
Austin Schuh48d60c12017-02-04 21:58:58 -0800279 pylab.legend()
280
281 pylab.subplot(3, 1, 3)
282 pylab.plot(self.t, self.a, label='a')
283 pylab.legend()
284
285 pylab.show()
286
287
288def main(argv):
289 scenario_plotter = ScenarioPlotter()
290
291 indexer = Indexer()
292 indexer_controller = IntegralIndexer()
293 observer_indexer = IntegralIndexer()
294
295 initial_X = numpy.matrix([[0.0], [0.0]])
296 R = numpy.matrix([[0.0], [20.0], [0.0]])
297 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
298 observer_indexer=observer_indexer, iterations=200)
299
300 if FLAGS.plot:
301 scenario_plotter.Plot()
302
Austin Schuhcd3237a2017-02-18 14:19:26 -0800303 scenario_plotter = ScenarioPlotter()
304
305 indexer = Indexer()
306 indexer_controller = IntegralIndexer(voltage_error_noise=1.5)
307 observer_indexer = IntegralIndexer(voltage_error_noise=1.5)
308
309 initial_X = numpy.matrix([[0.0], [0.0]])
310 R = numpy.matrix([[0.0], [20.0], [0.0]])
311 scenario_plotter.run_test(indexer, goal=R, controller_indexer=indexer_controller,
312 observer_indexer=observer_indexer, iterations=200)
313
314 if FLAGS.plot:
315 scenario_plotter.Plot()
316
317 if len(argv) != 7:
318 glog.fatal('Expected .h file name and .cc file names')
Austin Schuh48d60c12017-02-04 21:58:58 -0800319 else:
320 namespaces = ['y2017', 'control_loops', 'superstructure', 'indexer']
321 indexer = Indexer('Indexer')
322 loop_writer = control_loop.ControlLoopWriter('Indexer', [indexer],
323 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800324 loop_writer.AddConstant(control_loop.Constant(
325 'kFreeSpeed', '%f', indexer.free_speed))
326 loop_writer.AddConstant(control_loop.Constant(
327 'kOutputRatio', '%f', indexer.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800328 loop_writer.Write(argv[1], argv[2])
329
330 integral_indexer = IntegralIndexer('IntegralIndexer')
331 integral_loop_writer = control_loop.ControlLoopWriter(
332 'IntegralIndexer', [integral_indexer], namespaces=namespaces)
333 integral_loop_writer.Write(argv[3], argv[4])
334
Austin Schuh546a0382017-04-16 19:10:18 -0700335 stuck_integral_indexer = IntegralIndexer('StuckIntegralIndexer',
336 voltage_error_noise=1.5)
Austin Schuhcd3237a2017-02-18 14:19:26 -0800337 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))