blob: cad322144ab80679e994d5e152e1b32d87ec6e05 [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,
Austin Schuh63d095d2019-02-23 11:57:12 -080023 dt=0.00505):
Austin Schuhc1c957a2020-02-20 17:47:58 -080024 """Constructs an AngularSystemParams object.
25
26 Args:
27 motor: Motor object with the motor constants.
28 G: float, Gear ratio. Less than 1 means output moves slower than the
29 input.
30 """
Austin Schuh2e554032019-01-21 15:07:27 -080031 self.name = name
32 self.motor = motor
33 self.G = G
34 self.J = J
35 self.q_pos = q_pos
36 self.q_vel = q_vel
37 self.kalman_q_pos = kalman_q_pos
38 self.kalman_q_vel = kalman_q_vel
39 self.kalman_q_voltage = kalman_q_voltage
40 self.kalman_r_position = kalman_r_position
41 self.dt = dt
42
43
44class AngularSystem(control_loop.ControlLoop):
45 def __init__(self, params, name="AngularSystem"):
46 super(AngularSystem, self).__init__(name)
47 self.params = params
48
49 self.motor = params.motor
50
51 # Gear ratio
52 self.G = params.G
53
54 # Moment of inertia in kg m^2
Tyler Chatow6738c362019-02-16 14:12:30 -080055 self.J = params.J + self.motor.motor_inertia / (self.G**2.0)
Austin Schuh2e554032019-01-21 15:07:27 -080056
57 # Control loop time step
58 self.dt = params.dt
59
60 # State is [position, velocity]
61 # Input is [Voltage]
Tyler Chatow6738c362019-02-16 14:12:30 -080062 C1 = self.motor.Kt / (
63 self.G * self.G * self.motor.resistance * self.J * self.motor.Kv)
Austin Schuh2e554032019-01-21 15:07:27 -080064 C2 = self.motor.Kt / (self.G * self.J * self.motor.resistance)
65
66 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
67
68 # Start with the unmodified input
69 self.B_continuous = numpy.matrix([[0], [C2]])
70 glog.debug(repr(self.A_continuous))
71 glog.debug(repr(self.B_continuous))
72
73 self.C = numpy.matrix([[1, 0]])
74 self.D = numpy.matrix([[0]])
75
76 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
77 self.B_continuous, self.dt)
78
79 controllability = controls.ctrb(self.A, self.B)
80 glog.debug('Controllability of %d',
81 numpy.linalg.matrix_rank(controllability))
82 glog.debug('J: %f', self.J)
83 glog.debug('Stall torque: %f', self.motor.stall_torque / self.G)
84 glog.debug('Stall acceleration: %f',
85 self.motor.stall_torque / self.G / self.J)
86
87 glog.debug('Free speed is %f',
88 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
89
90 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
91 [0.0, (1.0 / (self.params.q_vel**2.0))]])
92
93 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
94 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
95
96 q_pos_ff = 0.005
97 q_vel_ff = 1.0
98 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
99 [0.0, (1.0 / (q_vel_ff**2.0))]])
100
101 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
102
103 glog.debug('K %s', repr(self.K))
104 glog.debug('Poles are %s',
105 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
106
107 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
108 [0.0, (self.params.kalman_q_vel**2.0)]])
109
110 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
111
112 self.KalmanGain, self.Q_steady = controls.kalman(
113 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
114
115 glog.debug('Kal %s', repr(self.KalmanGain))
116
117 # The box formed by U_min and U_max must encompass all possible values,
118 # or else Austin's code gets angry.
119 self.U_max = numpy.matrix([[12.0]])
120 self.U_min = numpy.matrix([[-12.0]])
121
122 self.InitializeState()
123
124
125class IntegralAngularSystem(AngularSystem):
126 def __init__(self, params, name="IntegralAngularSystem"):
127 super(IntegralAngularSystem, self).__init__(params, name=name)
128
129 self.A_continuous_unaugmented = self.A_continuous
130 self.B_continuous_unaugmented = self.B_continuous
131
132 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
133 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
134 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
135
136 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
137 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
138
139 self.C_unaugmented = self.C
140 self.C = numpy.matrix(numpy.zeros((1, 3)))
141 self.C[0:1, 0:2] = self.C_unaugmented
142
143 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
144 self.B_continuous, self.dt)
145
Tyler Chatow6738c362019-02-16 14:12:30 -0800146 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
147 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
Ravago Jones26f7ad02021-02-05 15:45:59 -0800148 [0.0, 0.0, (self.params.kalman_q_voltage
149 **2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800150
151 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
152
153 self.KalmanGain, self.Q_steady = controls.kalman(
154 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
155
156 self.K_unaugmented = self.K
157 self.K = numpy.matrix(numpy.zeros((1, 3)))
158 self.K[0, 0:2] = self.K_unaugmented
159 self.K[0, 2] = 1
160
161 self.Kff = numpy.concatenate(
162 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
163
164 self.InitializeState()
165
166
167def RunTest(plant,
168 end_goal,
169 controller,
170 observer=None,
171 duration=1.0,
172 use_profile=True,
173 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500174 kick_magnitude=0.0,
175 max_velocity=10.0,
176 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800177 """Runs the plant with an initial condition and goal.
178
179 Args:
180 plant: plant object to use.
181 end_goal: end_goal state.
182 controller: AngularSystem object to get K from, or None if we should
183 use plant.
184 observer: AngularSystem object to use for the observer, or None if we
185 should use the actual state.
186 duration: float, time in seconds to run the simulation for.
187 kick_time: float, time in seconds to kick the robot.
188 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500189 max_velocity: float, The maximum velocity for the profile.
190 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800191 """
192 t_plot = []
193 x_plot = []
194 v_plot = []
195 a_plot = []
Austin Schuha5aa9362022-02-07 21:26:08 -0800196 motor_current_plot = []
197 battery_current_plot = []
Austin Schuh2e554032019-01-21 15:07:27 -0800198 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)
Austin Schuh5ea48472021-02-02 20:46:41 -0800219 for i in range(iterations):
Austin Schuh2e554032019-01-21 15:07:27 -0800220 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()
Austin Schuha5aa9362022-02-07 21:26:08 -0800244
Austin Schuh2e554032019-01-21 15:07:27 -0800245 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
Austin Schuha5aa9362022-02-07 21:26:08 -0800246
247 motor_current = (U[0, 0] - plant.X[1, 0] / plant.G / plant.motor.Kv
248 ) / plant.motor.resistance
249 motor_current_plot.append(motor_current)
250 battery_current = U[0, 0] * motor_current / 12.0
251 battery_current_plot.append(battery_current)
Austin Schuh2e554032019-01-21 15:07:27 -0800252 x_plot.append(plant.X[0, 0])
253
254 if v_plot:
255 last_v = v_plot[-1]
256 else:
257 last_v = 0
258
259 v_plot.append(plant.X[1, 0])
260 a_plot.append((v_plot[-1] - last_v) / plant.dt)
261
262 u_offset = 0.0
263 if t >= kick_time:
264 u_offset = kick_magnitude
265 plant.Update(U + u_offset)
266
267 observer.PredictObserver(U)
268
269 t_plot.append(t)
270 u_plot.append(U[0, 0])
271
272 ff_U -= U_uncapped - U
273 goal = controller.A * goal + controller.B * ff_U
274
275 if U[0, 0] != U_uncapped[0, 0]:
Ravago Jones26f7ad02021-02-05 15:45:59 -0800276 profile.MoveCurrentState(
277 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800278
279 glog.debug('Time: %f', t_plot[-1])
280 glog.debug('goal_error %s', repr(end_goal - goal))
281 glog.debug('error %s', repr(observer.X_hat - end_goal))
282
283 pylab.subplot(3, 1, 1)
284 pylab.plot(t_plot, x_plot, label='x')
285 pylab.plot(t_plot, x_hat_plot, label='x_hat')
286 pylab.plot(t_plot, x_goal_plot, label='x_goal')
287 pylab.legend()
288
289 pylab.subplot(3, 1, 2)
290 pylab.plot(t_plot, u_plot, label='u')
291 pylab.plot(t_plot, offset_plot, label='voltage_offset')
292 pylab.legend()
293
Austin Schuha5aa9362022-02-07 21:26:08 -0800294 ax1 = pylab.subplot(3, 1, 3)
295 ax1.set_xlabel("time(s)")
296 ax1.set_ylabel("rad/s^2")
297 ax1.plot(t_plot, a_plot, label='a')
298
299 ax2 = ax1.twinx()
300 ax2.set_xlabel("time(s)")
301 ax2.set_ylabel("Amps")
302 ax2.plot(t_plot, battery_current_plot, 'g', label='battery')
303 ax2.plot(t_plot, motor_current_plot, 'r', label='motor')
Austin Schuh2e554032019-01-21 15:07:27 -0800304 pylab.legend()
305
306 pylab.show()
307
308
Austin Schuh9d9d3742019-02-15 23:00:13 -0800309def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800310 """Plots a step move to the goal.
311
312 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800313 params: AngularSystemParams for the controller and observer
314 plant_params: AngularSystemParams for the plant. Defaults to params if
315 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800316 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800317 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800318 controller = IntegralAngularSystem(params, params.name)
319 observer = IntegralAngularSystem(params, params.name)
320
321 # Test moving the system.
322 initial_X = numpy.matrix([[0.0], [0.0]])
323 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
324 augmented_R[0:2, :] = R
325 RunTest(
326 plant,
327 end_goal=augmented_R,
328 controller=controller,
329 observer=observer,
330 duration=2.0,
331 use_profile=False,
332 kick_time=1.0,
333 kick_magnitude=0.0)
334
335
Austin Schuh9d9d3742019-02-15 23:00:13 -0800336def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800337 """Plots a step motion with a kick at 1.0 seconds.
338
339 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800340 params: AngularSystemParams for the controller and observer
341 plant_params: AngularSystemParams for the plant. Defaults to params if
342 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800343 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800344 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800345 controller = IntegralAngularSystem(params, params.name)
346 observer = IntegralAngularSystem(params, params.name)
347
348 # Test moving the system.
349 initial_X = numpy.matrix([[0.0], [0.0]])
350 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
351 augmented_R[0:2, :] = R
352 RunTest(
353 plant,
354 end_goal=augmented_R,
355 controller=controller,
356 observer=observer,
357 duration=2.0,
358 use_profile=False,
359 kick_time=1.0,
360 kick_magnitude=2.0)
361
362
Austin Schuh9d9d3742019-02-15 23:00:13 -0800363def PlotMotion(params,
364 R,
365 max_velocity=10.0,
366 max_acceleration=70.0,
367 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800368 """Plots a trapezoidal motion.
369
370 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800371 params: AngularSystemParams for the controller and observer
372 plant_params: AngularSystemParams for the plant. Defaults to params if
373 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800374 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500375 max_velocity: float, The max velocity of the profile.
376 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800377 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800378 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800379 controller = IntegralAngularSystem(params, params.name)
380 observer = IntegralAngularSystem(params, params.name)
381
382 # Test moving the system.
383 initial_X = numpy.matrix([[0.0], [0.0]])
384 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
385 augmented_R[0:2, :] = R
386 RunTest(
387 plant,
388 end_goal=augmented_R,
389 controller=controller,
390 observer=observer,
391 duration=2.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500392 use_profile=True,
393 max_velocity=max_velocity,
394 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800395
396
397def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
398 """Writes out the constants for a angular system to a file.
399
400 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700401 params: list of AngularSystemParams or AngularSystemParams, the
402 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800403 plant_files: list of strings, the cc and h files for the plant.
404 controller_files: list of strings, the cc and h files for the integral
405 controller.
406 year_namespaces: list of strings, the namespace list to use.
407 """
408 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700409 angular_systems = []
410 integral_angular_systems = []
411
412 if type(params) is list:
413 name = params[0].name
414 for index, param in enumerate(params):
415 angular_systems.append(
416 AngularSystem(param, param.name + str(index)))
417 integral_angular_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800418 IntegralAngularSystem(param,
419 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700420 else:
421 name = params.name
422 angular_systems.append(AngularSystem(params, params.name))
423 integral_angular_systems.append(
424 IntegralAngularSystem(params, 'Integral' + params.name))
425
Austin Schuh2e554032019-01-21 15:07:27 -0800426 loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700427 name, angular_systems, namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500428 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700429 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500430 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800431 control_loop.Constant('kFreeSpeed', '%f',
432 angular_systems[0].motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800433 loop_writer.Write(plant_files[0], plant_files[1])
434
Austin Schuh2e554032019-01-21 15:07:27 -0800435 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700436 'Integral' + name,
437 integral_angular_systems,
Austin Schuh2e554032019-01-21 15:07:27 -0800438 namespaces=year_namespaces)
439 integral_loop_writer.Write(controller_files[0], controller_files[1])