blob: bd4447b3635858bb536415ba3d8f0b0ba2eb2a3c [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,
Austin Schuh63d095d2019-02-23 11:57:12 -080024 dt=0.00505):
Austin Schuhc1c957a2020-02-20 17:47:58 -080025 """Constructs an AngularSystemParams object.
26
27 Args:
28 motor: Motor object with the motor constants.
29 G: float, Gear ratio. Less than 1 means output moves slower than the
30 input.
31 """
Austin Schuh2e554032019-01-21 15:07:27 -080032 self.name = name
33 self.motor = motor
34 self.G = G
35 self.J = J
36 self.q_pos = q_pos
37 self.q_vel = q_vel
38 self.kalman_q_pos = kalman_q_pos
39 self.kalman_q_vel = kalman_q_vel
40 self.kalman_q_voltage = kalman_q_voltage
41 self.kalman_r_position = kalman_r_position
42 self.dt = dt
43
44
45class AngularSystem(control_loop.ControlLoop):
Tyler Chatow6738c362019-02-16 14:12:30 -080046
Austin Schuh2e554032019-01-21 15:07:27 -080047 def __init__(self, params, name="AngularSystem"):
48 super(AngularSystem, self).__init__(name)
49 self.params = params
50
51 self.motor = params.motor
52
53 # Gear ratio
54 self.G = params.G
55
56 # Moment of inertia in kg m^2
Tyler Chatow6738c362019-02-16 14:12:30 -080057 self.J = params.J + self.motor.motor_inertia / (self.G**2.0)
Austin Schuh2e554032019-01-21 15:07:27 -080058
59 # Control loop time step
60 self.dt = params.dt
61
62 # State is [position, velocity]
63 # Input is [Voltage]
Tyler Chatow6738c362019-02-16 14:12:30 -080064 C1 = self.motor.Kt / (
65 self.G * self.G * self.motor.resistance * self.J * self.motor.Kv)
Austin Schuh2e554032019-01-21 15:07:27 -080066 C2 = self.motor.Kt / (self.G * self.J * self.motor.resistance)
67
68 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
69
70 # Start with the unmodified input
71 self.B_continuous = numpy.matrix([[0], [C2]])
72 glog.debug(repr(self.A_continuous))
73 glog.debug(repr(self.B_continuous))
74
75 self.C = numpy.matrix([[1, 0]])
76 self.D = numpy.matrix([[0]])
77
78 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
79 self.B_continuous, self.dt)
80
81 controllability = controls.ctrb(self.A, self.B)
82 glog.debug('Controllability of %d',
83 numpy.linalg.matrix_rank(controllability))
84 glog.debug('J: %f', self.J)
85 glog.debug('Stall torque: %f', self.motor.stall_torque / self.G)
86 glog.debug('Stall acceleration: %f',
87 self.motor.stall_torque / self.G / self.J)
88
89 glog.debug('Free speed is %f',
90 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
91
92 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
93 [0.0, (1.0 / (self.params.q_vel**2.0))]])
94
95 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
96 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
97
98 q_pos_ff = 0.005
99 q_vel_ff = 1.0
100 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
101 [0.0, (1.0 / (q_vel_ff**2.0))]])
102
103 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
104
105 glog.debug('K %s', repr(self.K))
106 glog.debug('Poles are %s',
107 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
108
109 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
110 [0.0, (self.params.kalman_q_vel**2.0)]])
111
112 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
113
114 self.KalmanGain, self.Q_steady = controls.kalman(
115 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
116
117 glog.debug('Kal %s', repr(self.KalmanGain))
118
119 # The box formed by U_min and U_max must encompass all possible values,
120 # or else Austin's code gets angry.
121 self.U_max = numpy.matrix([[12.0]])
122 self.U_min = numpy.matrix([[-12.0]])
123
124 self.InitializeState()
125
126
127class IntegralAngularSystem(AngularSystem):
Tyler Chatow6738c362019-02-16 14:12:30 -0800128
Austin Schuh2e554032019-01-21 15:07:27 -0800129 def __init__(self, params, name="IntegralAngularSystem"):
130 super(IntegralAngularSystem, self).__init__(params, name=name)
131
132 self.A_continuous_unaugmented = self.A_continuous
133 self.B_continuous_unaugmented = self.B_continuous
134
135 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
136 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
137 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
138
139 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
140 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
141
142 self.C_unaugmented = self.C
143 self.C = numpy.matrix(numpy.zeros((1, 3)))
144 self.C[0:1, 0:2] = self.C_unaugmented
145
146 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
147 self.B_continuous, self.dt)
148
Tyler Chatow6738c362019-02-16 14:12:30 -0800149 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
150 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
151 [0.0, 0.0, (self.params.kalman_q_voltage**2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800152
153 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
154
155 self.KalmanGain, self.Q_steady = controls.kalman(
156 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
157
158 self.K_unaugmented = self.K
159 self.K = numpy.matrix(numpy.zeros((1, 3)))
160 self.K[0, 0:2] = self.K_unaugmented
161 self.K[0, 2] = 1
162
163 self.Kff = numpy.concatenate(
164 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
165
166 self.InitializeState()
167
168
169def RunTest(plant,
170 end_goal,
171 controller,
172 observer=None,
173 duration=1.0,
174 use_profile=True,
175 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500176 kick_magnitude=0.0,
177 max_velocity=10.0,
178 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800179 """Runs the plant with an initial condition and goal.
180
181 Args:
182 plant: plant object to use.
183 end_goal: end_goal state.
184 controller: AngularSystem object to get K from, or None if we should
185 use plant.
186 observer: AngularSystem object to use for the observer, or None if we
187 should use the actual state.
188 duration: float, time in seconds to run the simulation for.
189 kick_time: float, time in seconds to kick the robot.
190 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500191 max_velocity: float, The maximum velocity for the profile.
192 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800193 """
194 t_plot = []
195 x_plot = []
196 v_plot = []
197 a_plot = []
198 x_goal_plot = []
199 v_goal_plot = []
200 x_hat_plot = []
201 u_plot = []
202 offset_plot = []
203
204 if controller is None:
205 controller = plant
206
207 vbat = 12.0
208
Tyler Chatow6738c362019-02-16 14:12:30 -0800209 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
210 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800211
212 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500213 profile.set_maximum_acceleration(max_acceleration)
214 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800215 profile.SetGoal(goal[0, 0])
216
217 U_last = numpy.matrix(numpy.zeros((1, 1)))
218 iterations = int(duration / plant.dt)
219 for i in xrange(iterations):
220 t = i * plant.dt
221 observer.Y = plant.Y
222 observer.CorrectObserver(U_last)
223
224 offset_plot.append(observer.X_hat[2, 0])
225 x_hat_plot.append(observer.X_hat[0, 0])
226
227 next_goal = numpy.concatenate(
228 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
229 numpy.matrix(numpy.zeros((1, 1)))),
230 axis=0)
231
232 ff_U = controller.Kff * (next_goal - observer.A * goal)
233
234 if use_profile:
235 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
236 x_goal_plot.append(goal[0, 0])
237 v_goal_plot.append(goal[1, 0])
238 else:
239 U_uncapped = controller.K * (end_goal - observer.X_hat)
240 x_goal_plot.append(end_goal[0, 0])
241 v_goal_plot.append(end_goal[1, 0])
242
243 U = U_uncapped.copy()
244 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
245 x_plot.append(plant.X[0, 0])
246
247 if v_plot:
248 last_v = v_plot[-1]
249 else:
250 last_v = 0
251
252 v_plot.append(plant.X[1, 0])
253 a_plot.append((v_plot[-1] - last_v) / plant.dt)
254
255 u_offset = 0.0
256 if t >= kick_time:
257 u_offset = kick_magnitude
258 plant.Update(U + u_offset)
259
260 observer.PredictObserver(U)
261
262 t_plot.append(t)
263 u_plot.append(U[0, 0])
264
265 ff_U -= U_uncapped - U
266 goal = controller.A * goal + controller.B * ff_U
267
268 if U[0, 0] != U_uncapped[0, 0]:
Tyler Chatow6738c362019-02-16 14:12:30 -0800269 profile.MoveCurrentState(numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800270
271 glog.debug('Time: %f', t_plot[-1])
272 glog.debug('goal_error %s', repr(end_goal - goal))
273 glog.debug('error %s', repr(observer.X_hat - end_goal))
274
275 pylab.subplot(3, 1, 1)
276 pylab.plot(t_plot, x_plot, label='x')
277 pylab.plot(t_plot, x_hat_plot, label='x_hat')
278 pylab.plot(t_plot, x_goal_plot, label='x_goal')
279 pylab.legend()
280
281 pylab.subplot(3, 1, 2)
282 pylab.plot(t_plot, u_plot, label='u')
283 pylab.plot(t_plot, offset_plot, label='voltage_offset')
284 pylab.legend()
285
286 pylab.subplot(3, 1, 3)
287 pylab.plot(t_plot, a_plot, label='a')
288 pylab.legend()
289
290 pylab.show()
291
292
Austin Schuh9d9d3742019-02-15 23:00:13 -0800293def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800294 """Plots a step move to the goal.
295
296 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800297 params: AngularSystemParams for the controller and observer
298 plant_params: AngularSystemParams for the plant. Defaults to params if
299 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800300 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800301 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800302 controller = IntegralAngularSystem(params, params.name)
303 observer = IntegralAngularSystem(params, params.name)
304
305 # Test moving the system.
306 initial_X = numpy.matrix([[0.0], [0.0]])
307 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
308 augmented_R[0:2, :] = R
309 RunTest(
310 plant,
311 end_goal=augmented_R,
312 controller=controller,
313 observer=observer,
314 duration=2.0,
315 use_profile=False,
316 kick_time=1.0,
317 kick_magnitude=0.0)
318
319
Austin Schuh9d9d3742019-02-15 23:00:13 -0800320def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800321 """Plots a step motion with a kick at 1.0 seconds.
322
323 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800324 params: AngularSystemParams for the controller and observer
325 plant_params: AngularSystemParams for the plant. Defaults to params if
326 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800327 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800328 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800329 controller = IntegralAngularSystem(params, params.name)
330 observer = IntegralAngularSystem(params, params.name)
331
332 # Test moving the system.
333 initial_X = numpy.matrix([[0.0], [0.0]])
334 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
335 augmented_R[0:2, :] = R
336 RunTest(
337 plant,
338 end_goal=augmented_R,
339 controller=controller,
340 observer=observer,
341 duration=2.0,
342 use_profile=False,
343 kick_time=1.0,
344 kick_magnitude=2.0)
345
346
Austin Schuh9d9d3742019-02-15 23:00:13 -0800347def PlotMotion(params,
348 R,
349 max_velocity=10.0,
350 max_acceleration=70.0,
351 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800352 """Plots a trapezoidal motion.
353
354 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800355 params: AngularSystemParams for the controller and observer
356 plant_params: AngularSystemParams for the plant. Defaults to params if
357 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800358 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500359 max_velocity: float, The max velocity of the profile.
360 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800361 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800362 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800363 controller = IntegralAngularSystem(params, params.name)
364 observer = IntegralAngularSystem(params, params.name)
365
366 # Test moving the system.
367 initial_X = numpy.matrix([[0.0], [0.0]])
368 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
369 augmented_R[0:2, :] = R
370 RunTest(
371 plant,
372 end_goal=augmented_R,
373 controller=controller,
374 observer=observer,
375 duration=2.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500376 use_profile=True,
377 max_velocity=max_velocity,
378 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800379
380
381def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
382 """Writes out the constants for a angular system to a file.
383
384 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700385 params: list of AngularSystemParams or AngularSystemParams, the
386 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800387 plant_files: list of strings, the cc and h files for the plant.
388 controller_files: list of strings, the cc and h files for the integral
389 controller.
390 year_namespaces: list of strings, the namespace list to use.
391 """
392 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700393 angular_systems = []
394 integral_angular_systems = []
395
396 if type(params) is list:
397 name = params[0].name
398 for index, param in enumerate(params):
399 angular_systems.append(
400 AngularSystem(param, param.name + str(index)))
401 integral_angular_systems.append(
402 IntegralAngularSystem(param, 'Integral' + param.name + str(
403 index)))
404 else:
405 name = params.name
406 angular_systems.append(AngularSystem(params, params.name))
407 integral_angular_systems.append(
408 IntegralAngularSystem(params, 'Integral' + params.name))
409
Austin Schuh2e554032019-01-21 15:07:27 -0800410 loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700411 name, angular_systems, namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500412 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700413 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500414 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700415 control_loop.Constant('kFreeSpeed', '%f', angular_systems[0]
416 .motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800417 loop_writer.Write(plant_files[0], plant_files[1])
418
Austin Schuh2e554032019-01-21 15:07:27 -0800419 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700420 'Integral' + name,
421 integral_angular_systems,
Austin Schuh2e554032019-01-21 15:07:27 -0800422 namespaces=year_namespaces)
423 integral_loop_writer.Write(controller_files[0], controller_files[1])