blob: e5dd19905f32d73d92722e6dd4ce8705cb730711 [file] [log] [blame]
Austin Schuh2e554032019-01-21 15:07:27 -08001#!/usr/bin/python
2
3from aos.util.trapezoid_profile import TrapezoidProfile
4from frc971.control_loops.python import control_loop
5from frc971.control_loops.python import controls
6import numpy
7from matplotlib import pylab
8import glog
9
10
11class AngularSystemParams(object):
12 def __init__(self,
13 name,
14 motor,
15 G,
16 J,
17 q_pos,
18 q_vel,
19 kalman_q_pos,
20 kalman_q_vel,
21 kalman_q_voltage,
22 kalman_r_position,
23 dt=0.005):
24 self.name = name
25 self.motor = motor
26 self.G = G
27 self.J = J
28 self.q_pos = q_pos
29 self.q_vel = q_vel
30 self.kalman_q_pos = kalman_q_pos
31 self.kalman_q_vel = kalman_q_vel
32 self.kalman_q_voltage = kalman_q_voltage
33 self.kalman_r_position = kalman_r_position
34 self.dt = dt
35
36
37class AngularSystem(control_loop.ControlLoop):
38 def __init__(self, params, name="AngularSystem"):
39 super(AngularSystem, self).__init__(name)
40 self.params = params
41
42 self.motor = params.motor
43
44 # Gear ratio
45 self.G = params.G
46
47 # Moment of inertia in kg m^2
48 self.J = params.J + self.motor.motor_inertia / (self.G ** 2.0)
49
50 # Control loop time step
51 self.dt = params.dt
52
53 # State is [position, velocity]
54 # Input is [Voltage]
55 C1 = self.motor.Kt / (self.G * self.G * self.motor.resistance *
56 self.J * self.motor.Kv)
57 C2 = self.motor.Kt / (self.G * self.J * self.motor.resistance)
58
59 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
60
61 # Start with the unmodified input
62 self.B_continuous = numpy.matrix([[0], [C2]])
63 glog.debug(repr(self.A_continuous))
64 glog.debug(repr(self.B_continuous))
65
66 self.C = numpy.matrix([[1, 0]])
67 self.D = numpy.matrix([[0]])
68
69 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
70 self.B_continuous, self.dt)
71
72 controllability = controls.ctrb(self.A, self.B)
73 glog.debug('Controllability of %d',
74 numpy.linalg.matrix_rank(controllability))
75 glog.debug('J: %f', self.J)
76 glog.debug('Stall torque: %f', self.motor.stall_torque / self.G)
77 glog.debug('Stall acceleration: %f',
78 self.motor.stall_torque / self.G / self.J)
79
80 glog.debug('Free speed is %f',
81 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
82
83 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
84 [0.0, (1.0 / (self.params.q_vel**2.0))]])
85
86 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
87 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
88
89 q_pos_ff = 0.005
90 q_vel_ff = 1.0
91 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
92 [0.0, (1.0 / (q_vel_ff**2.0))]])
93
94 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
95
96 glog.debug('K %s', repr(self.K))
97 glog.debug('Poles are %s',
98 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
99
100 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
101 [0.0, (self.params.kalman_q_vel**2.0)]])
102
103 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
104
105 self.KalmanGain, self.Q_steady = controls.kalman(
106 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
107
108 glog.debug('Kal %s', repr(self.KalmanGain))
109
110 # The box formed by U_min and U_max must encompass all possible values,
111 # or else Austin's code gets angry.
112 self.U_max = numpy.matrix([[12.0]])
113 self.U_min = numpy.matrix([[-12.0]])
114
115 self.InitializeState()
116
117
118class IntegralAngularSystem(AngularSystem):
119 def __init__(self, params, name="IntegralAngularSystem"):
120 super(IntegralAngularSystem, self).__init__(params, name=name)
121
122 self.A_continuous_unaugmented = self.A_continuous
123 self.B_continuous_unaugmented = self.B_continuous
124
125 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
126 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
127 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
128
129 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
130 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
131
132 self.C_unaugmented = self.C
133 self.C = numpy.matrix(numpy.zeros((1, 3)))
134 self.C[0:1, 0:2] = self.C_unaugmented
135
136 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
137 self.B_continuous, self.dt)
138
139 self.Q = numpy.matrix(
140 [[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
141 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
142 [0.0, 0.0, (self.params.kalman_q_voltage**2.0)]])
143
144 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
145
146 self.KalmanGain, self.Q_steady = controls.kalman(
147 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
148
149 self.K_unaugmented = self.K
150 self.K = numpy.matrix(numpy.zeros((1, 3)))
151 self.K[0, 0:2] = self.K_unaugmented
152 self.K[0, 2] = 1
153
154 self.Kff = numpy.concatenate(
155 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
156
157 self.InitializeState()
158
159
160def RunTest(plant,
161 end_goal,
162 controller,
163 observer=None,
164 duration=1.0,
165 use_profile=True,
166 kick_time=0.5,
167 kick_magnitude=0.0):
168 """Runs the plant with an initial condition and goal.
169
170 Args:
171 plant: plant object to use.
172 end_goal: end_goal state.
173 controller: AngularSystem object to get K from, or None if we should
174 use plant.
175 observer: AngularSystem object to use for the observer, or None if we
176 should use the actual state.
177 duration: float, time in seconds to run the simulation for.
178 kick_time: float, time in seconds to kick the robot.
179 kick_magnitude: float, disturbance in volts to apply.
180 """
181 t_plot = []
182 x_plot = []
183 v_plot = []
184 a_plot = []
185 x_goal_plot = []
186 v_goal_plot = []
187 x_hat_plot = []
188 u_plot = []
189 offset_plot = []
190
191 if controller is None:
192 controller = plant
193
194 vbat = 12.0
195
196 goal = numpy.concatenate(
197 (plant.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
198
199 profile = TrapezoidProfile(plant.dt)
200 profile.set_maximum_acceleration(70.0)
201 profile.set_maximum_velocity(10.0)
202 profile.SetGoal(goal[0, 0])
203
204 U_last = numpy.matrix(numpy.zeros((1, 1)))
205 iterations = int(duration / plant.dt)
206 for i in xrange(iterations):
207 t = i * plant.dt
208 observer.Y = plant.Y
209 observer.CorrectObserver(U_last)
210
211 offset_plot.append(observer.X_hat[2, 0])
212 x_hat_plot.append(observer.X_hat[0, 0])
213
214 next_goal = numpy.concatenate(
215 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
216 numpy.matrix(numpy.zeros((1, 1)))),
217 axis=0)
218
219 ff_U = controller.Kff * (next_goal - observer.A * goal)
220
221 if use_profile:
222 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
223 x_goal_plot.append(goal[0, 0])
224 v_goal_plot.append(goal[1, 0])
225 else:
226 U_uncapped = controller.K * (end_goal - observer.X_hat)
227 x_goal_plot.append(end_goal[0, 0])
228 v_goal_plot.append(end_goal[1, 0])
229
230 U = U_uncapped.copy()
231 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
232 x_plot.append(plant.X[0, 0])
233
234 if v_plot:
235 last_v = v_plot[-1]
236 else:
237 last_v = 0
238
239 v_plot.append(plant.X[1, 0])
240 a_plot.append((v_plot[-1] - last_v) / plant.dt)
241
242 u_offset = 0.0
243 if t >= kick_time:
244 u_offset = kick_magnitude
245 plant.Update(U + u_offset)
246
247 observer.PredictObserver(U)
248
249 t_plot.append(t)
250 u_plot.append(U[0, 0])
251
252 ff_U -= U_uncapped - U
253 goal = controller.A * goal + controller.B * ff_U
254
255 if U[0, 0] != U_uncapped[0, 0]:
256 profile.MoveCurrentState(
257 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
258
259 glog.debug('Time: %f', t_plot[-1])
260 glog.debug('goal_error %s', repr(end_goal - goal))
261 glog.debug('error %s', repr(observer.X_hat - end_goal))
262
263 pylab.subplot(3, 1, 1)
264 pylab.plot(t_plot, x_plot, label='x')
265 pylab.plot(t_plot, x_hat_plot, label='x_hat')
266 pylab.plot(t_plot, x_goal_plot, label='x_goal')
267 pylab.legend()
268
269 pylab.subplot(3, 1, 2)
270 pylab.plot(t_plot, u_plot, label='u')
271 pylab.plot(t_plot, offset_plot, label='voltage_offset')
272 pylab.legend()
273
274 pylab.subplot(3, 1, 3)
275 pylab.plot(t_plot, a_plot, label='a')
276 pylab.legend()
277
278 pylab.show()
279
280
281def PlotStep(params, R):
282 """Plots a step move to the goal.
283
284 Args:
285 R: numpy.matrix(2, 1), the goal"""
286 plant = AngularSystem(params, params.name)
287 controller = IntegralAngularSystem(params, params.name)
288 observer = IntegralAngularSystem(params, params.name)
289
290 # Test moving the system.
291 initial_X = numpy.matrix([[0.0], [0.0]])
292 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
293 augmented_R[0:2, :] = R
294 RunTest(
295 plant,
296 end_goal=augmented_R,
297 controller=controller,
298 observer=observer,
299 duration=2.0,
300 use_profile=False,
301 kick_time=1.0,
302 kick_magnitude=0.0)
303
304
305def PlotKick(params, R):
306 """Plots a step motion with a kick at 1.0 seconds.
307
308 Args:
309 R: numpy.matrix(2, 1), the goal"""
310 plant = AngularSystem(params, params.name)
311 controller = IntegralAngularSystem(params, params.name)
312 observer = IntegralAngularSystem(params, params.name)
313
314 # Test moving the system.
315 initial_X = numpy.matrix([[0.0], [0.0]])
316 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
317 augmented_R[0:2, :] = R
318 RunTest(
319 plant,
320 end_goal=augmented_R,
321 controller=controller,
322 observer=observer,
323 duration=2.0,
324 use_profile=False,
325 kick_time=1.0,
326 kick_magnitude=2.0)
327
328
329def PlotMotion(params, R):
330 """Plots a trapezoidal motion.
331
332 Args:
333 R: numpy.matrix(2, 1), the goal,
334 """
335 plant = AngularSystem(params, params.name)
336 controller = IntegralAngularSystem(params, params.name)
337 observer = IntegralAngularSystem(params, params.name)
338
339 # Test moving the system.
340 initial_X = numpy.matrix([[0.0], [0.0]])
341 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
342 augmented_R[0:2, :] = R
343 RunTest(
344 plant,
345 end_goal=augmented_R,
346 controller=controller,
347 observer=observer,
348 duration=2.0,
349 use_profile=True)
350
351
352def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
353 """Writes out the constants for a angular system to a file.
354
355 Args:
356 params: AngularSystemParams, the parameters defining the system.
357 plant_files: list of strings, the cc and h files for the plant.
358 controller_files: list of strings, the cc and h files for the integral
359 controller.
360 year_namespaces: list of strings, the namespace list to use.
361 """
362 # Write the generated constants out to a file.
363 angular_system = AngularSystem(params, params.name)
364 loop_writer = control_loop.ControlLoopWriter(
365 angular_system.name, [angular_system], namespaces=year_namespaces)
366 loop_writer.Write(plant_files[0], plant_files[1])
367
368 integral_angular_system = IntegralAngularSystem(params,
369 'Integral' + params.name)
370 integral_loop_writer = control_loop.ControlLoopWriter(
371 integral_angular_system.name, [integral_angular_system],
372 namespaces=year_namespaces)
373 integral_loop_writer.Write(controller_files[0], controller_files[1])