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