blob: 551f3d0ad098176d76dfeb034dce76d63676cfb1 [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):
Ravago Jones5127ccc2022-07-31 16:32:45 -070012
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,
Ravago Jones5127ccc2022-07-31 16:32:45 -070024 radius=None,
Austin Schuh63d095d2019-02-23 11:57:12 -080025 dt=0.00505):
Austin Schuhc1c957a2020-02-20 17:47:58 -080026 """Constructs an AngularSystemParams object.
27
28 Args:
29 motor: Motor object with the motor constants.
30 G: float, Gear ratio. Less than 1 means output moves slower than the
31 input.
32 """
Austin Schuh2e554032019-01-21 15:07:27 -080033 self.name = name
34 self.motor = motor
35 self.G = G
36 self.J = J
37 self.q_pos = q_pos
38 self.q_vel = q_vel
39 self.kalman_q_pos = kalman_q_pos
40 self.kalman_q_vel = kalman_q_vel
41 self.kalman_q_voltage = kalman_q_voltage
42 self.kalman_r_position = kalman_r_position
Milo Lin5d49af02022-02-05 12:50:32 -080043 self.radius = radius
Austin Schuh2e554032019-01-21 15:07:27 -080044 self.dt = dt
45
46
47class AngularSystem(control_loop.ControlLoop):
Ravago Jones5127ccc2022-07-31 16:32:45 -070048
Austin Schuh2e554032019-01-21 15:07:27 -080049 def __init__(self, params, name="AngularSystem"):
50 super(AngularSystem, self).__init__(name)
51 self.params = params
52
53 self.motor = params.motor
54
55 # Gear ratio
56 self.G = params.G
57
58 # Moment of inertia in kg m^2
Tyler Chatow6738c362019-02-16 14:12:30 -080059 self.J = params.J + self.motor.motor_inertia / (self.G**2.0)
Austin Schuh2e554032019-01-21 15:07:27 -080060
61 # Control loop time step
62 self.dt = params.dt
63
64 # State is [position, velocity]
65 # Input is [Voltage]
Ravago Jones5127ccc2022-07-31 16:32:45 -070066 C1 = self.motor.Kt / (self.G * self.G * self.motor.resistance *
67 self.J * self.motor.Kv)
Austin Schuh2e554032019-01-21 15:07:27 -080068 C2 = self.motor.Kt / (self.G * self.J * self.motor.resistance)
69
70 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
71
72 # Start with the unmodified input
73 self.B_continuous = numpy.matrix([[0], [C2]])
74 glog.debug(repr(self.A_continuous))
75 glog.debug(repr(self.B_continuous))
76
77 self.C = numpy.matrix([[1, 0]])
78 self.D = numpy.matrix([[0]])
79
80 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
81 self.B_continuous, self.dt)
82
83 controllability = controls.ctrb(self.A, self.B)
84 glog.debug('Controllability of %d',
85 numpy.linalg.matrix_rank(controllability))
86 glog.debug('J: %f', self.J)
Milo Lin5d49af02022-02-05 12:50:32 -080087 glog.debug('Stall torque: %f (N m)', self.motor.stall_torque / self.G)
88 if self.params.radius is not None:
89 glog.debug('Stall force: %f (N)',
90 self.motor.stall_torque / self.G / self.params.radius)
Ravago Jones5127ccc2022-07-31 16:32:45 -070091 glog.debug(
92 'Stall force: %f (lbf)', self.motor.stall_torque / self.G /
93 self.params.radius * 0.224809)
Milo Lin5d49af02022-02-05 12:50:32 -080094
95 glog.debug('Stall acceleration: %f (rad/s^2)',
Austin Schuh2e554032019-01-21 15:07:27 -080096 self.motor.stall_torque / self.G / self.J)
97
Milo Lin5d49af02022-02-05 12:50:32 -080098 glog.debug('Free speed is %f (rad/s)',
Austin Schuh2e554032019-01-21 15:07:27 -080099 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
100
101 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
102 [0.0, (1.0 / (self.params.q_vel**2.0))]])
103
104 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
105 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
106
107 q_pos_ff = 0.005
108 q_vel_ff = 1.0
109 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
110 [0.0, (1.0 / (q_vel_ff**2.0))]])
111
112 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
113
114 glog.debug('K %s', repr(self.K))
115 glog.debug('Poles are %s',
116 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
117
118 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
119 [0.0, (self.params.kalman_q_vel**2.0)]])
120
121 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
122
milind-u53ad98a2023-02-20 16:26:09 -0800123 # From testing, these continuous Q and R's appear to be good approximations of Q and R.
124 self.Q_continuous = self.Q / self.dt
125 self.R_continuous = self.R * self.dt
126
127 self.KalmanGain, self.P_steady_state = controls.kalman(A=self.A,
128 B=self.B,
129 C=self.C,
130 Q=self.Q,
131 R=self.R)
Austin Schuh2e554032019-01-21 15:07:27 -0800132
133 glog.debug('Kal %s', repr(self.KalmanGain))
134
135 # The box formed by U_min and U_max must encompass all possible values,
136 # or else Austin's code gets angry.
137 self.U_max = numpy.matrix([[12.0]])
138 self.U_min = numpy.matrix([[-12.0]])
139
140 self.InitializeState()
141
142
143class IntegralAngularSystem(AngularSystem):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700144
Austin Schuh2e554032019-01-21 15:07:27 -0800145 def __init__(self, params, name="IntegralAngularSystem"):
146 super(IntegralAngularSystem, self).__init__(params, name=name)
147
148 self.A_continuous_unaugmented = self.A_continuous
149 self.B_continuous_unaugmented = self.B_continuous
150
151 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
152 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
153 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
154
155 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
156 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
157
158 self.C_unaugmented = self.C
159 self.C = numpy.matrix(numpy.zeros((1, 3)))
160 self.C[0:1, 0:2] = self.C_unaugmented
161
162 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
163 self.B_continuous, self.dt)
164
Tyler Chatow6738c362019-02-16 14:12:30 -0800165 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
166 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
Ravago Jones5127ccc2022-07-31 16:32:45 -0700167 [0.0, 0.0,
168 (self.params.kalman_q_voltage**2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800169
170 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
171
milind-u53ad98a2023-02-20 16:26:09 -0800172 # From testing, these continuous Q and R's appear to be good approximations of Q and R.
173 self.Q_continuous = self.Q / self.dt
174 self.R_continuous = self.R * self.dt
175
176 self.KalmanGain, self.P_steady_state = controls.kalman(A=self.A,
177 B=self.B,
178 C=self.C,
179 Q=self.Q,
180 R=self.R)
Austin Schuh2e554032019-01-21 15:07:27 -0800181
182 self.K_unaugmented = self.K
183 self.K = numpy.matrix(numpy.zeros((1, 3)))
184 self.K[0, 0:2] = self.K_unaugmented
185 self.K[0, 2] = 1
186
187 self.Kff = numpy.concatenate(
188 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
189
190 self.InitializeState()
191
192
193def RunTest(plant,
194 end_goal,
195 controller,
196 observer=None,
197 duration=1.0,
198 use_profile=True,
199 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500200 kick_magnitude=0.0,
201 max_velocity=10.0,
202 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800203 """Runs the plant with an initial condition and goal.
204
205 Args:
206 plant: plant object to use.
207 end_goal: end_goal state.
208 controller: AngularSystem object to get K from, or None if we should
209 use plant.
210 observer: AngularSystem object to use for the observer, or None if we
211 should use the actual state.
212 duration: float, time in seconds to run the simulation for.
213 kick_time: float, time in seconds to kick the robot.
214 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500215 max_velocity: float, The maximum velocity for the profile.
216 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800217 """
218 t_plot = []
219 x_plot = []
220 v_plot = []
221 a_plot = []
Austin Schuha5aa9362022-02-07 21:26:08 -0800222 motor_current_plot = []
223 battery_current_plot = []
Austin Schuh2e554032019-01-21 15:07:27 -0800224 x_goal_plot = []
225 v_goal_plot = []
226 x_hat_plot = []
227 u_plot = []
228 offset_plot = []
229
230 if controller is None:
231 controller = plant
232
233 vbat = 12.0
234
Tyler Chatow6738c362019-02-16 14:12:30 -0800235 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
236 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800237
238 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500239 profile.set_maximum_acceleration(max_acceleration)
240 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800241 profile.SetGoal(goal[0, 0])
242
243 U_last = numpy.matrix(numpy.zeros((1, 1)))
244 iterations = int(duration / plant.dt)
Austin Schuh5ea48472021-02-02 20:46:41 -0800245 for i in range(iterations):
Austin Schuh2e554032019-01-21 15:07:27 -0800246 t = i * plant.dt
247 observer.Y = plant.Y
248 observer.CorrectObserver(U_last)
249
250 offset_plot.append(observer.X_hat[2, 0])
251 x_hat_plot.append(observer.X_hat[0, 0])
252
Ravago Jones5127ccc2022-07-31 16:32:45 -0700253 next_goal = numpy.concatenate((profile.Update(
254 end_goal[0, 0], end_goal[1, 0]), numpy.matrix(numpy.zeros(
255 (1, 1)))),
256 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800257
258 ff_U = controller.Kff * (next_goal - observer.A * goal)
259
260 if use_profile:
261 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
262 x_goal_plot.append(goal[0, 0])
263 v_goal_plot.append(goal[1, 0])
264 else:
265 U_uncapped = controller.K * (end_goal - observer.X_hat)
266 x_goal_plot.append(end_goal[0, 0])
267 v_goal_plot.append(end_goal[1, 0])
268
269 U = U_uncapped.copy()
Austin Schuha5aa9362022-02-07 21:26:08 -0800270
Austin Schuh2e554032019-01-21 15:07:27 -0800271 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
Austin Schuha5aa9362022-02-07 21:26:08 -0800272
Ravago Jones5127ccc2022-07-31 16:32:45 -0700273 motor_current = (U[0, 0] - plant.X[1, 0] / plant.G /
274 plant.motor.Kv) / plant.motor.resistance
Austin Schuha5aa9362022-02-07 21:26:08 -0800275 motor_current_plot.append(motor_current)
276 battery_current = U[0, 0] * motor_current / 12.0
277 battery_current_plot.append(battery_current)
Austin Schuh2e554032019-01-21 15:07:27 -0800278 x_plot.append(plant.X[0, 0])
279
280 if v_plot:
281 last_v = v_plot[-1]
282 else:
283 last_v = 0
284
285 v_plot.append(plant.X[1, 0])
286 a_plot.append((v_plot[-1] - last_v) / plant.dt)
287
288 u_offset = 0.0
289 if t >= kick_time:
290 u_offset = kick_magnitude
291 plant.Update(U + u_offset)
292
293 observer.PredictObserver(U)
294
295 t_plot.append(t)
296 u_plot.append(U[0, 0])
297
298 ff_U -= U_uncapped - U
299 goal = controller.A * goal + controller.B * ff_U
300
301 if U[0, 0] != U_uncapped[0, 0]:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700302 profile.MoveCurrentState(numpy.matrix([[goal[0, 0]], [goal[1,
303 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800304
305 glog.debug('Time: %f', t_plot[-1])
306 glog.debug('goal_error %s', repr(end_goal - goal))
307 glog.debug('error %s', repr(observer.X_hat - end_goal))
308
309 pylab.subplot(3, 1, 1)
310 pylab.plot(t_plot, x_plot, label='x')
311 pylab.plot(t_plot, x_hat_plot, label='x_hat')
312 pylab.plot(t_plot, x_goal_plot, label='x_goal')
313 pylab.legend()
314
315 pylab.subplot(3, 1, 2)
316 pylab.plot(t_plot, u_plot, label='u')
317 pylab.plot(t_plot, offset_plot, label='voltage_offset')
318 pylab.legend()
319
Austin Schuha5aa9362022-02-07 21:26:08 -0800320 ax1 = pylab.subplot(3, 1, 3)
321 ax1.set_xlabel("time(s)")
322 ax1.set_ylabel("rad/s^2")
323 ax1.plot(t_plot, a_plot, label='a')
324
325 ax2 = ax1.twinx()
326 ax2.set_xlabel("time(s)")
327 ax2.set_ylabel("Amps")
328 ax2.plot(t_plot, battery_current_plot, 'g', label='battery')
329 ax2.plot(t_plot, motor_current_plot, 'r', label='motor')
Austin Schuh2e554032019-01-21 15:07:27 -0800330 pylab.legend()
331
332 pylab.show()
333
334
Austin Schuh9d9d3742019-02-15 23:00:13 -0800335def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800336 """Plots a step move to the goal.
337
338 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800339 params: AngularSystemParams for the controller and observer
340 plant_params: AngularSystemParams for the plant. Defaults to params if
341 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800342 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800343 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800344 controller = IntegralAngularSystem(params, params.name)
345 observer = IntegralAngularSystem(params, params.name)
346
347 # Test moving the system.
348 initial_X = numpy.matrix([[0.0], [0.0]])
349 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
350 augmented_R[0:2, :] = R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700351 RunTest(plant,
352 end_goal=augmented_R,
353 controller=controller,
354 observer=observer,
355 duration=2.0,
356 use_profile=False,
357 kick_time=1.0,
358 kick_magnitude=0.0)
Austin Schuh2e554032019-01-21 15:07:27 -0800359
360
Austin Schuh9d9d3742019-02-15 23:00:13 -0800361def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800362 """Plots a step motion with a kick at 1.0 seconds.
363
364 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800365 params: AngularSystemParams for the controller and observer
366 plant_params: AngularSystemParams for the plant. Defaults to params if
367 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800368 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800369 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800370 controller = IntegralAngularSystem(params, params.name)
371 observer = IntegralAngularSystem(params, params.name)
372
373 # Test moving the system.
374 initial_X = numpy.matrix([[0.0], [0.0]])
375 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
376 augmented_R[0:2, :] = R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700377 RunTest(plant,
378 end_goal=augmented_R,
379 controller=controller,
380 observer=observer,
381 duration=2.0,
382 use_profile=False,
383 kick_time=1.0,
384 kick_magnitude=2.0)
Austin Schuh2e554032019-01-21 15:07:27 -0800385
386
Austin Schuh9d9d3742019-02-15 23:00:13 -0800387def PlotMotion(params,
388 R,
389 max_velocity=10.0,
390 max_acceleration=70.0,
391 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800392 """Plots a trapezoidal motion.
393
394 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800395 params: AngularSystemParams for the controller and observer
396 plant_params: AngularSystemParams for the plant. Defaults to params if
397 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800398 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500399 max_velocity: float, The max velocity of the profile.
400 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800401 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800402 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800403 controller = IntegralAngularSystem(params, params.name)
404 observer = IntegralAngularSystem(params, params.name)
405
406 # Test moving the system.
407 initial_X = numpy.matrix([[0.0], [0.0]])
408 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
409 augmented_R[0:2, :] = R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700410 RunTest(plant,
411 end_goal=augmented_R,
412 controller=controller,
413 observer=observer,
414 duration=2.0,
415 use_profile=True,
416 max_velocity=max_velocity,
417 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800418
419
milind-u53ad98a2023-02-20 16:26:09 -0800420def WriteAngularSystem(params,
421 plant_files,
422 controller_files,
423 year_namespaces,
424 plant_type='StateFeedbackPlant',
425 observer_type='StateFeedbackObserver'):
Austin Schuh2e554032019-01-21 15:07:27 -0800426 """Writes out the constants for a angular system to a file.
427
428 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700429 params: list of AngularSystemParams or AngularSystemParams, the
430 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800431 plant_files: list of strings, the cc and h files for the plant.
432 controller_files: list of strings, the cc and h files for the integral
433 controller.
434 year_namespaces: list of strings, the namespace list to use.
435 """
436 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700437 angular_systems = []
438 integral_angular_systems = []
439
440 if type(params) is list:
441 name = params[0].name
442 for index, param in enumerate(params):
443 angular_systems.append(
444 AngularSystem(param, param.name + str(index)))
445 integral_angular_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800446 IntegralAngularSystem(param,
447 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700448 else:
449 name = params.name
450 angular_systems.append(AngularSystem(params, params.name))
451 integral_angular_systems.append(
452 IntegralAngularSystem(params, 'Integral' + params.name))
453
Ravago Jones5127ccc2022-07-31 16:32:45 -0700454 loop_writer = control_loop.ControlLoopWriter(name,
455 angular_systems,
milind-u53ad98a2023-02-20 16:26:09 -0800456 namespaces=year_namespaces,
457 plant_type=plant_type,
458 observer_type=observer_type)
Lee Mracek17cb4892019-02-07 11:24:49 -0500459 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700460 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500461 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800462 control_loop.Constant('kFreeSpeed', '%f',
463 angular_systems[0].motor.free_speed))
James Kuszmauleeb98e92024-01-14 22:15:32 -0800464 loop_writer.Write(plant_files[0], plant_files[1],
465 None if len(plant_files) < 3 else plant_files[2])
Austin Schuh2e554032019-01-21 15:07:27 -0800466
Austin Schuh2e554032019-01-21 15:07:27 -0800467 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700468 'Integral' + name,
469 integral_angular_systems,
milind-u53ad98a2023-02-20 16:26:09 -0800470 namespaces=year_namespaces,
471 plant_type=plant_type,
472 observer_type=observer_type)
James Kuszmauleeb98e92024-01-14 22:15:32 -0800473 integral_loop_writer.Write(
474 controller_files[0], controller_files[1],
475 None if len(controller_files) < 3 else controller_files[2])