blob: 6772e71ea2226fd6318c4cbd314719ff59a9ebe3 [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
Ravago Jones5127ccc2022-07-31 16:32:45 -0700123 self.KalmanGain, self.Q_steady = controls.kalman(A=self.A,
124 B=self.B,
125 C=self.C,
126 Q=self.Q,
127 R=self.R)
Austin Schuh2e554032019-01-21 15:07:27 -0800128
129 glog.debug('Kal %s', repr(self.KalmanGain))
130
131 # The box formed by U_min and U_max must encompass all possible values,
132 # or else Austin's code gets angry.
133 self.U_max = numpy.matrix([[12.0]])
134 self.U_min = numpy.matrix([[-12.0]])
135
136 self.InitializeState()
137
138
139class IntegralAngularSystem(AngularSystem):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700140
Austin Schuh2e554032019-01-21 15:07:27 -0800141 def __init__(self, params, name="IntegralAngularSystem"):
142 super(IntegralAngularSystem, self).__init__(params, name=name)
143
144 self.A_continuous_unaugmented = self.A_continuous
145 self.B_continuous_unaugmented = self.B_continuous
146
147 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
148 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
149 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
150
151 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
152 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
153
154 self.C_unaugmented = self.C
155 self.C = numpy.matrix(numpy.zeros((1, 3)))
156 self.C[0:1, 0:2] = self.C_unaugmented
157
158 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
159 self.B_continuous, self.dt)
160
Tyler Chatow6738c362019-02-16 14:12:30 -0800161 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
162 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
Ravago Jones5127ccc2022-07-31 16:32:45 -0700163 [0.0, 0.0,
164 (self.params.kalman_q_voltage**2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800165
166 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
167
Ravago Jones5127ccc2022-07-31 16:32:45 -0700168 self.KalmanGain, self.Q_steady = controls.kalman(A=self.A,
169 B=self.B,
170 C=self.C,
171 Q=self.Q,
172 R=self.R)
Austin Schuh2e554032019-01-21 15:07:27 -0800173
174 self.K_unaugmented = self.K
175 self.K = numpy.matrix(numpy.zeros((1, 3)))
176 self.K[0, 0:2] = self.K_unaugmented
177 self.K[0, 2] = 1
178
179 self.Kff = numpy.concatenate(
180 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
181
182 self.InitializeState()
183
184
185def RunTest(plant,
186 end_goal,
187 controller,
188 observer=None,
189 duration=1.0,
190 use_profile=True,
191 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500192 kick_magnitude=0.0,
193 max_velocity=10.0,
194 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800195 """Runs the plant with an initial condition and goal.
196
197 Args:
198 plant: plant object to use.
199 end_goal: end_goal state.
200 controller: AngularSystem object to get K from, or None if we should
201 use plant.
202 observer: AngularSystem object to use for the observer, or None if we
203 should use the actual state.
204 duration: float, time in seconds to run the simulation for.
205 kick_time: float, time in seconds to kick the robot.
206 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500207 max_velocity: float, The maximum velocity for the profile.
208 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800209 """
210 t_plot = []
211 x_plot = []
212 v_plot = []
213 a_plot = []
Austin Schuha5aa9362022-02-07 21:26:08 -0800214 motor_current_plot = []
215 battery_current_plot = []
Austin Schuh2e554032019-01-21 15:07:27 -0800216 x_goal_plot = []
217 v_goal_plot = []
218 x_hat_plot = []
219 u_plot = []
220 offset_plot = []
221
222 if controller is None:
223 controller = plant
224
225 vbat = 12.0
226
Tyler Chatow6738c362019-02-16 14:12:30 -0800227 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
228 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800229
230 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500231 profile.set_maximum_acceleration(max_acceleration)
232 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800233 profile.SetGoal(goal[0, 0])
234
235 U_last = numpy.matrix(numpy.zeros((1, 1)))
236 iterations = int(duration / plant.dt)
Austin Schuh5ea48472021-02-02 20:46:41 -0800237 for i in range(iterations):
Austin Schuh2e554032019-01-21 15:07:27 -0800238 t = i * plant.dt
239 observer.Y = plant.Y
240 observer.CorrectObserver(U_last)
241
242 offset_plot.append(observer.X_hat[2, 0])
243 x_hat_plot.append(observer.X_hat[0, 0])
244
Ravago Jones5127ccc2022-07-31 16:32:45 -0700245 next_goal = numpy.concatenate((profile.Update(
246 end_goal[0, 0], end_goal[1, 0]), numpy.matrix(numpy.zeros(
247 (1, 1)))),
248 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800249
250 ff_U = controller.Kff * (next_goal - observer.A * goal)
251
252 if use_profile:
253 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
254 x_goal_plot.append(goal[0, 0])
255 v_goal_plot.append(goal[1, 0])
256 else:
257 U_uncapped = controller.K * (end_goal - observer.X_hat)
258 x_goal_plot.append(end_goal[0, 0])
259 v_goal_plot.append(end_goal[1, 0])
260
261 U = U_uncapped.copy()
Austin Schuha5aa9362022-02-07 21:26:08 -0800262
Austin Schuh2e554032019-01-21 15:07:27 -0800263 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
Austin Schuha5aa9362022-02-07 21:26:08 -0800264
Ravago Jones5127ccc2022-07-31 16:32:45 -0700265 motor_current = (U[0, 0] - plant.X[1, 0] / plant.G /
266 plant.motor.Kv) / plant.motor.resistance
Austin Schuha5aa9362022-02-07 21:26:08 -0800267 motor_current_plot.append(motor_current)
268 battery_current = U[0, 0] * motor_current / 12.0
269 battery_current_plot.append(battery_current)
Austin Schuh2e554032019-01-21 15:07:27 -0800270 x_plot.append(plant.X[0, 0])
271
272 if v_plot:
273 last_v = v_plot[-1]
274 else:
275 last_v = 0
276
277 v_plot.append(plant.X[1, 0])
278 a_plot.append((v_plot[-1] - last_v) / plant.dt)
279
280 u_offset = 0.0
281 if t >= kick_time:
282 u_offset = kick_magnitude
283 plant.Update(U + u_offset)
284
285 observer.PredictObserver(U)
286
287 t_plot.append(t)
288 u_plot.append(U[0, 0])
289
290 ff_U -= U_uncapped - U
291 goal = controller.A * goal + controller.B * ff_U
292
293 if U[0, 0] != U_uncapped[0, 0]:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700294 profile.MoveCurrentState(numpy.matrix([[goal[0, 0]], [goal[1,
295 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800296
297 glog.debug('Time: %f', t_plot[-1])
298 glog.debug('goal_error %s', repr(end_goal - goal))
299 glog.debug('error %s', repr(observer.X_hat - end_goal))
300
301 pylab.subplot(3, 1, 1)
302 pylab.plot(t_plot, x_plot, label='x')
303 pylab.plot(t_plot, x_hat_plot, label='x_hat')
304 pylab.plot(t_plot, x_goal_plot, label='x_goal')
305 pylab.legend()
306
307 pylab.subplot(3, 1, 2)
308 pylab.plot(t_plot, u_plot, label='u')
309 pylab.plot(t_plot, offset_plot, label='voltage_offset')
310 pylab.legend()
311
Austin Schuha5aa9362022-02-07 21:26:08 -0800312 ax1 = pylab.subplot(3, 1, 3)
313 ax1.set_xlabel("time(s)")
314 ax1.set_ylabel("rad/s^2")
315 ax1.plot(t_plot, a_plot, label='a')
316
317 ax2 = ax1.twinx()
318 ax2.set_xlabel("time(s)")
319 ax2.set_ylabel("Amps")
320 ax2.plot(t_plot, battery_current_plot, 'g', label='battery')
321 ax2.plot(t_plot, motor_current_plot, 'r', label='motor')
Austin Schuh2e554032019-01-21 15:07:27 -0800322 pylab.legend()
323
324 pylab.show()
325
326
Austin Schuh9d9d3742019-02-15 23:00:13 -0800327def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800328 """Plots a step move to the goal.
329
330 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800331 params: AngularSystemParams for the controller and observer
332 plant_params: AngularSystemParams for the plant. Defaults to params if
333 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800334 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800335 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800336 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
Ravago Jones5127ccc2022-07-31 16:32:45 -0700343 RunTest(plant,
344 end_goal=augmented_R,
345 controller=controller,
346 observer=observer,
347 duration=2.0,
348 use_profile=False,
349 kick_time=1.0,
350 kick_magnitude=0.0)
Austin Schuh2e554032019-01-21 15:07:27 -0800351
352
Austin Schuh9d9d3742019-02-15 23:00:13 -0800353def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800354 """Plots a step motion with a kick at 1.0 seconds.
355
356 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800357 params: AngularSystemParams for the controller and observer
358 plant_params: AngularSystemParams for the plant. Defaults to params if
359 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800360 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800361 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800362 controller = IntegralAngularSystem(params, params.name)
363 observer = IntegralAngularSystem(params, params.name)
364
365 # Test moving the system.
366 initial_X = numpy.matrix([[0.0], [0.0]])
367 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
368 augmented_R[0:2, :] = R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700369 RunTest(plant,
370 end_goal=augmented_R,
371 controller=controller,
372 observer=observer,
373 duration=2.0,
374 use_profile=False,
375 kick_time=1.0,
376 kick_magnitude=2.0)
Austin Schuh2e554032019-01-21 15:07:27 -0800377
378
Austin Schuh9d9d3742019-02-15 23:00:13 -0800379def PlotMotion(params,
380 R,
381 max_velocity=10.0,
382 max_acceleration=70.0,
383 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800384 """Plots a trapezoidal motion.
385
386 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800387 params: AngularSystemParams for the controller and observer
388 plant_params: AngularSystemParams for the plant. Defaults to params if
389 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800390 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500391 max_velocity: float, The max velocity of the profile.
392 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800393 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800394 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800395 controller = IntegralAngularSystem(params, params.name)
396 observer = IntegralAngularSystem(params, params.name)
397
398 # Test moving the system.
399 initial_X = numpy.matrix([[0.0], [0.0]])
400 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
401 augmented_R[0:2, :] = R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700402 RunTest(plant,
403 end_goal=augmented_R,
404 controller=controller,
405 observer=observer,
406 duration=2.0,
407 use_profile=True,
408 max_velocity=max_velocity,
409 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800410
411
412def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
413 """Writes out the constants for a angular system to a file.
414
415 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700416 params: list of AngularSystemParams or AngularSystemParams, the
417 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800418 plant_files: list of strings, the cc and h files for the plant.
419 controller_files: list of strings, the cc and h files for the integral
420 controller.
421 year_namespaces: list of strings, the namespace list to use.
422 """
423 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700424 angular_systems = []
425 integral_angular_systems = []
426
427 if type(params) is list:
428 name = params[0].name
429 for index, param in enumerate(params):
430 angular_systems.append(
431 AngularSystem(param, param.name + str(index)))
432 integral_angular_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800433 IntegralAngularSystem(param,
434 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700435 else:
436 name = params.name
437 angular_systems.append(AngularSystem(params, params.name))
438 integral_angular_systems.append(
439 IntegralAngularSystem(params, 'Integral' + params.name))
440
Ravago Jones5127ccc2022-07-31 16:32:45 -0700441 loop_writer = control_loop.ControlLoopWriter(name,
442 angular_systems,
443 namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500444 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700445 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500446 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800447 control_loop.Constant('kFreeSpeed', '%f',
448 angular_systems[0].motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800449 loop_writer.Write(plant_files[0], plant_files[1])
450
Austin Schuh2e554032019-01-21 15:07:27 -0800451 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700452 'Integral' + name,
453 integral_angular_systems,
Austin Schuh2e554032019-01-21 15:07:27 -0800454 namespaces=year_namespaces)
455 integral_loop_writer.Write(controller_files[0], controller_files[1])