blob: df6c0f69b62c2ccffdf8e4cd4915cdbac562cb04 [file] [log] [blame]
Austin Schuh085eab92020-11-26 13:54:51 -08001#!/usr/bin/python3
Austin Schuh2e554032019-01-21 15:07:27 -08002
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,
Milo Lin5d49af02022-02-05 12:50:32 -080023 radius = None,
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
Milo Lin5d49af02022-02-05 12:50:32 -080042 self.radius = radius
Austin Schuh2e554032019-01-21 15:07:27 -080043 self.dt = dt
44
45
46class AngularSystem(control_loop.ControlLoop):
47 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)
Milo Lin5d49af02022-02-05 12:50:32 -080085 glog.debug('Stall torque: %f (N m)', self.motor.stall_torque / self.G)
86 if self.params.radius is not None:
87 glog.debug('Stall force: %f (N)',
88 self.motor.stall_torque / self.G / self.params.radius)
89 glog.debug('Stall force: %f (lbf)',
90 self.motor.stall_torque / self.G / self.params.radius * 0.224809)
91
92 glog.debug('Stall acceleration: %f (rad/s^2)',
Austin Schuh2e554032019-01-21 15:07:27 -080093 self.motor.stall_torque / self.G / self.J)
94
Milo Lin5d49af02022-02-05 12:50:32 -080095 glog.debug('Free speed is %f (rad/s)',
Austin Schuh2e554032019-01-21 15:07:27 -080096 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
97
98 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
99 [0.0, (1.0 / (self.params.q_vel**2.0))]])
100
101 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
102 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
103
104 q_pos_ff = 0.005
105 q_vel_ff = 1.0
106 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
107 [0.0, (1.0 / (q_vel_ff**2.0))]])
108
109 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
110
111 glog.debug('K %s', repr(self.K))
112 glog.debug('Poles are %s',
113 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
114
115 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
116 [0.0, (self.params.kalman_q_vel**2.0)]])
117
118 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
119
120 self.KalmanGain, self.Q_steady = controls.kalman(
121 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
122
123 glog.debug('Kal %s', repr(self.KalmanGain))
124
125 # The box formed by U_min and U_max must encompass all possible values,
126 # or else Austin's code gets angry.
127 self.U_max = numpy.matrix([[12.0]])
128 self.U_min = numpy.matrix([[-12.0]])
129
130 self.InitializeState()
131
132
133class IntegralAngularSystem(AngularSystem):
134 def __init__(self, params, name="IntegralAngularSystem"):
135 super(IntegralAngularSystem, self).__init__(params, 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(self.A_continuous,
152 self.B_continuous, self.dt)
153
Tyler Chatow6738c362019-02-16 14:12:30 -0800154 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
155 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
Ravago Jones26f7ad02021-02-05 15:45:59 -0800156 [0.0, 0.0, (self.params.kalman_q_voltage
157 **2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800158
159 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
160
161 self.KalmanGain, self.Q_steady = controls.kalman(
162 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
163
164 self.K_unaugmented = self.K
165 self.K = numpy.matrix(numpy.zeros((1, 3)))
166 self.K[0, 0:2] = self.K_unaugmented
167 self.K[0, 2] = 1
168
169 self.Kff = numpy.concatenate(
170 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
171
172 self.InitializeState()
173
174
175def RunTest(plant,
176 end_goal,
177 controller,
178 observer=None,
179 duration=1.0,
180 use_profile=True,
181 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500182 kick_magnitude=0.0,
183 max_velocity=10.0,
184 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800185 """Runs the plant with an initial condition and goal.
186
187 Args:
188 plant: plant object to use.
189 end_goal: end_goal state.
190 controller: AngularSystem object to get K from, or None if we should
191 use plant.
192 observer: AngularSystem object to use for the observer, or None if we
193 should use the actual state.
194 duration: float, time in seconds to run the simulation for.
195 kick_time: float, time in seconds to kick the robot.
196 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500197 max_velocity: float, The maximum velocity for the profile.
198 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800199 """
200 t_plot = []
201 x_plot = []
202 v_plot = []
203 a_plot = []
Austin Schuha5aa9362022-02-07 21:26:08 -0800204 motor_current_plot = []
205 battery_current_plot = []
Austin Schuh2e554032019-01-21 15:07:27 -0800206 x_goal_plot = []
207 v_goal_plot = []
208 x_hat_plot = []
209 u_plot = []
210 offset_plot = []
211
212 if controller is None:
213 controller = plant
214
215 vbat = 12.0
216
Tyler Chatow6738c362019-02-16 14:12:30 -0800217 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
218 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800219
220 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500221 profile.set_maximum_acceleration(max_acceleration)
222 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800223 profile.SetGoal(goal[0, 0])
224
225 U_last = numpy.matrix(numpy.zeros((1, 1)))
226 iterations = int(duration / plant.dt)
Austin Schuh5ea48472021-02-02 20:46:41 -0800227 for i in range(iterations):
Austin Schuh2e554032019-01-21 15:07:27 -0800228 t = i * plant.dt
229 observer.Y = plant.Y
230 observer.CorrectObserver(U_last)
231
232 offset_plot.append(observer.X_hat[2, 0])
233 x_hat_plot.append(observer.X_hat[0, 0])
234
235 next_goal = numpy.concatenate(
236 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
237 numpy.matrix(numpy.zeros((1, 1)))),
238 axis=0)
239
240 ff_U = controller.Kff * (next_goal - observer.A * goal)
241
242 if use_profile:
243 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
244 x_goal_plot.append(goal[0, 0])
245 v_goal_plot.append(goal[1, 0])
246 else:
247 U_uncapped = controller.K * (end_goal - observer.X_hat)
248 x_goal_plot.append(end_goal[0, 0])
249 v_goal_plot.append(end_goal[1, 0])
250
251 U = U_uncapped.copy()
Austin Schuha5aa9362022-02-07 21:26:08 -0800252
Austin Schuh2e554032019-01-21 15:07:27 -0800253 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
Austin Schuha5aa9362022-02-07 21:26:08 -0800254
255 motor_current = (U[0, 0] - plant.X[1, 0] / plant.G / plant.motor.Kv
256 ) / plant.motor.resistance
257 motor_current_plot.append(motor_current)
258 battery_current = U[0, 0] * motor_current / 12.0
259 battery_current_plot.append(battery_current)
Austin Schuh2e554032019-01-21 15:07:27 -0800260 x_plot.append(plant.X[0, 0])
261
262 if v_plot:
263 last_v = v_plot[-1]
264 else:
265 last_v = 0
266
267 v_plot.append(plant.X[1, 0])
268 a_plot.append((v_plot[-1] - last_v) / plant.dt)
269
270 u_offset = 0.0
271 if t >= kick_time:
272 u_offset = kick_magnitude
273 plant.Update(U + u_offset)
274
275 observer.PredictObserver(U)
276
277 t_plot.append(t)
278 u_plot.append(U[0, 0])
279
280 ff_U -= U_uncapped - U
281 goal = controller.A * goal + controller.B * ff_U
282
283 if U[0, 0] != U_uncapped[0, 0]:
Ravago Jones26f7ad02021-02-05 15:45:59 -0800284 profile.MoveCurrentState(
285 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800286
287 glog.debug('Time: %f', t_plot[-1])
288 glog.debug('goal_error %s', repr(end_goal - goal))
289 glog.debug('error %s', repr(observer.X_hat - end_goal))
290
291 pylab.subplot(3, 1, 1)
292 pylab.plot(t_plot, x_plot, label='x')
293 pylab.plot(t_plot, x_hat_plot, label='x_hat')
294 pylab.plot(t_plot, x_goal_plot, label='x_goal')
295 pylab.legend()
296
297 pylab.subplot(3, 1, 2)
298 pylab.plot(t_plot, u_plot, label='u')
299 pylab.plot(t_plot, offset_plot, label='voltage_offset')
300 pylab.legend()
301
Austin Schuha5aa9362022-02-07 21:26:08 -0800302 ax1 = pylab.subplot(3, 1, 3)
303 ax1.set_xlabel("time(s)")
304 ax1.set_ylabel("rad/s^2")
305 ax1.plot(t_plot, a_plot, label='a')
306
307 ax2 = ax1.twinx()
308 ax2.set_xlabel("time(s)")
309 ax2.set_ylabel("Amps")
310 ax2.plot(t_plot, battery_current_plot, 'g', label='battery')
311 ax2.plot(t_plot, motor_current_plot, 'r', label='motor')
Austin Schuh2e554032019-01-21 15:07:27 -0800312 pylab.legend()
313
314 pylab.show()
315
316
Austin Schuh9d9d3742019-02-15 23:00:13 -0800317def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800318 """Plots a step move to the goal.
319
320 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800321 params: AngularSystemParams for the controller and observer
322 plant_params: AngularSystemParams for the plant. Defaults to params if
323 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800324 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800325 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800326 controller = IntegralAngularSystem(params, params.name)
327 observer = IntegralAngularSystem(params, params.name)
328
329 # Test moving the system.
330 initial_X = numpy.matrix([[0.0], [0.0]])
331 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
332 augmented_R[0:2, :] = R
333 RunTest(
334 plant,
335 end_goal=augmented_R,
336 controller=controller,
337 observer=observer,
338 duration=2.0,
339 use_profile=False,
340 kick_time=1.0,
341 kick_magnitude=0.0)
342
343
Austin Schuh9d9d3742019-02-15 23:00:13 -0800344def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800345 """Plots a step motion with a kick at 1.0 seconds.
346
347 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800348 params: AngularSystemParams for the controller and observer
349 plant_params: AngularSystemParams for the plant. Defaults to params if
350 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800351 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800352 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800353 controller = IntegralAngularSystem(params, params.name)
354 observer = IntegralAngularSystem(params, params.name)
355
356 # Test moving the system.
357 initial_X = numpy.matrix([[0.0], [0.0]])
358 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
359 augmented_R[0:2, :] = R
360 RunTest(
361 plant,
362 end_goal=augmented_R,
363 controller=controller,
364 observer=observer,
365 duration=2.0,
366 use_profile=False,
367 kick_time=1.0,
368 kick_magnitude=2.0)
369
370
Austin Schuh9d9d3742019-02-15 23:00:13 -0800371def PlotMotion(params,
372 R,
373 max_velocity=10.0,
374 max_acceleration=70.0,
375 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800376 """Plots a trapezoidal motion.
377
378 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800379 params: AngularSystemParams for the controller and observer
380 plant_params: AngularSystemParams for the plant. Defaults to params if
381 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800382 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500383 max_velocity: float, The max velocity of the profile.
384 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800385 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800386 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800387 controller = IntegralAngularSystem(params, params.name)
388 observer = IntegralAngularSystem(params, params.name)
389
390 # Test moving the system.
391 initial_X = numpy.matrix([[0.0], [0.0]])
392 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
393 augmented_R[0:2, :] = R
394 RunTest(
395 plant,
396 end_goal=augmented_R,
397 controller=controller,
398 observer=observer,
399 duration=2.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500400 use_profile=True,
401 max_velocity=max_velocity,
402 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800403
404
405def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
406 """Writes out the constants for a angular system to a file.
407
408 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700409 params: list of AngularSystemParams or AngularSystemParams, the
410 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800411 plant_files: list of strings, the cc and h files for the plant.
412 controller_files: list of strings, the cc and h files for the integral
413 controller.
414 year_namespaces: list of strings, the namespace list to use.
415 """
416 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700417 angular_systems = []
418 integral_angular_systems = []
419
420 if type(params) is list:
421 name = params[0].name
422 for index, param in enumerate(params):
423 angular_systems.append(
424 AngularSystem(param, param.name + str(index)))
425 integral_angular_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800426 IntegralAngularSystem(param,
427 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700428 else:
429 name = params.name
430 angular_systems.append(AngularSystem(params, params.name))
431 integral_angular_systems.append(
432 IntegralAngularSystem(params, 'Integral' + params.name))
433
Austin Schuh2e554032019-01-21 15:07:27 -0800434 loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700435 name, angular_systems, namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500436 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700437 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500438 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800439 control_loop.Constant('kFreeSpeed', '%f',
440 angular_systems[0].motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800441 loop_writer.Write(plant_files[0], plant_files[1])
442
Austin Schuh2e554032019-01-21 15:07:27 -0800443 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700444 'Integral' + name,
445 integral_angular_systems,
Austin Schuh2e554032019-01-21 15:07:27 -0800446 namespaces=year_namespaces)
447 integral_loop_writer.Write(controller_files[0], controller_files[1])