blob: 7ccb4afe967e79839d1bdcfabec7570b04efa23d [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 = []
196 x_goal_plot = []
197 v_goal_plot = []
198 x_hat_plot = []
199 u_plot = []
200 offset_plot = []
201
202 if controller is None:
203 controller = plant
204
205 vbat = 12.0
206
Tyler Chatow6738c362019-02-16 14:12:30 -0800207 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
208 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800209
210 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500211 profile.set_maximum_acceleration(max_acceleration)
212 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800213 profile.SetGoal(goal[0, 0])
214
215 U_last = numpy.matrix(numpy.zeros((1, 1)))
216 iterations = int(duration / plant.dt)
Austin Schuh5ea48472021-02-02 20:46:41 -0800217 for i in range(iterations):
Austin Schuh2e554032019-01-21 15:07:27 -0800218 t = i * plant.dt
219 observer.Y = plant.Y
220 observer.CorrectObserver(U_last)
221
222 offset_plot.append(observer.X_hat[2, 0])
223 x_hat_plot.append(observer.X_hat[0, 0])
224
225 next_goal = numpy.concatenate(
226 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
227 numpy.matrix(numpy.zeros((1, 1)))),
228 axis=0)
229
230 ff_U = controller.Kff * (next_goal - observer.A * goal)
231
232 if use_profile:
233 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
234 x_goal_plot.append(goal[0, 0])
235 v_goal_plot.append(goal[1, 0])
236 else:
237 U_uncapped = controller.K * (end_goal - observer.X_hat)
238 x_goal_plot.append(end_goal[0, 0])
239 v_goal_plot.append(end_goal[1, 0])
240
241 U = U_uncapped.copy()
242 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
243 x_plot.append(plant.X[0, 0])
244
245 if v_plot:
246 last_v = v_plot[-1]
247 else:
248 last_v = 0
249
250 v_plot.append(plant.X[1, 0])
251 a_plot.append((v_plot[-1] - last_v) / plant.dt)
252
253 u_offset = 0.0
254 if t >= kick_time:
255 u_offset = kick_magnitude
256 plant.Update(U + u_offset)
257
258 observer.PredictObserver(U)
259
260 t_plot.append(t)
261 u_plot.append(U[0, 0])
262
263 ff_U -= U_uncapped - U
264 goal = controller.A * goal + controller.B * ff_U
265
266 if U[0, 0] != U_uncapped[0, 0]:
Ravago Jones26f7ad02021-02-05 15:45:59 -0800267 profile.MoveCurrentState(
268 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800269
270 glog.debug('Time: %f', t_plot[-1])
271 glog.debug('goal_error %s', repr(end_goal - goal))
272 glog.debug('error %s', repr(observer.X_hat - end_goal))
273
274 pylab.subplot(3, 1, 1)
275 pylab.plot(t_plot, x_plot, label='x')
276 pylab.plot(t_plot, x_hat_plot, label='x_hat')
277 pylab.plot(t_plot, x_goal_plot, label='x_goal')
278 pylab.legend()
279
280 pylab.subplot(3, 1, 2)
281 pylab.plot(t_plot, u_plot, label='u')
282 pylab.plot(t_plot, offset_plot, label='voltage_offset')
283 pylab.legend()
284
285 pylab.subplot(3, 1, 3)
286 pylab.plot(t_plot, a_plot, label='a')
287 pylab.legend()
288
289 pylab.show()
290
291
Austin Schuh9d9d3742019-02-15 23:00:13 -0800292def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800293 """Plots a step move to the goal.
294
295 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800296 params: AngularSystemParams for the controller and observer
297 plant_params: AngularSystemParams for the plant. Defaults to params if
298 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800299 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800300 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800301 controller = IntegralAngularSystem(params, params.name)
302 observer = IntegralAngularSystem(params, params.name)
303
304 # Test moving the system.
305 initial_X = numpy.matrix([[0.0], [0.0]])
306 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
307 augmented_R[0:2, :] = R
308 RunTest(
309 plant,
310 end_goal=augmented_R,
311 controller=controller,
312 observer=observer,
313 duration=2.0,
314 use_profile=False,
315 kick_time=1.0,
316 kick_magnitude=0.0)
317
318
Austin Schuh9d9d3742019-02-15 23:00:13 -0800319def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800320 """Plots a step motion with a kick at 1.0 seconds.
321
322 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800323 params: AngularSystemParams for the controller and observer
324 plant_params: AngularSystemParams for the plant. Defaults to params if
325 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800326 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800327 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800328 controller = IntegralAngularSystem(params, params.name)
329 observer = IntegralAngularSystem(params, params.name)
330
331 # Test moving the system.
332 initial_X = numpy.matrix([[0.0], [0.0]])
333 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
334 augmented_R[0:2, :] = R
335 RunTest(
336 plant,
337 end_goal=augmented_R,
338 controller=controller,
339 observer=observer,
340 duration=2.0,
341 use_profile=False,
342 kick_time=1.0,
343 kick_magnitude=2.0)
344
345
Austin Schuh9d9d3742019-02-15 23:00:13 -0800346def PlotMotion(params,
347 R,
348 max_velocity=10.0,
349 max_acceleration=70.0,
350 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800351 """Plots a trapezoidal motion.
352
353 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800354 params: AngularSystemParams for the controller and observer
355 plant_params: AngularSystemParams for the plant. Defaults to params if
356 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800357 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500358 max_velocity: float, The max velocity of the profile.
359 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800360 """
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
369 RunTest(
370 plant,
371 end_goal=augmented_R,
372 controller=controller,
373 observer=observer,
374 duration=2.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500375 use_profile=True,
376 max_velocity=max_velocity,
377 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800378
379
380def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
381 """Writes out the constants for a angular system to a file.
382
383 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700384 params: list of AngularSystemParams or AngularSystemParams, the
385 parameters defining the system.
Austin Schuh2e554032019-01-21 15:07:27 -0800386 plant_files: list of strings, the cc and h files for the plant.
387 controller_files: list of strings, the cc and h files for the integral
388 controller.
389 year_namespaces: list of strings, the namespace list to use.
390 """
391 # Write the generated constants out to a file.
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700392 angular_systems = []
393 integral_angular_systems = []
394
395 if type(params) is list:
396 name = params[0].name
397 for index, param in enumerate(params):
398 angular_systems.append(
399 AngularSystem(param, param.name + str(index)))
400 integral_angular_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800401 IntegralAngularSystem(param,
402 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700403 else:
404 name = params.name
405 angular_systems.append(AngularSystem(params, params.name))
406 integral_angular_systems.append(
407 IntegralAngularSystem(params, 'Integral' + params.name))
408
Austin Schuh2e554032019-01-21 15:07:27 -0800409 loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700410 name, angular_systems, namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500411 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700412 control_loop.Constant('kOutputRatio', '%f', angular_systems[0].G))
Lee Mracek17cb4892019-02-07 11:24:49 -0500413 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800414 control_loop.Constant('kFreeSpeed', '%f',
415 angular_systems[0].motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800416 loop_writer.Write(plant_files[0], plant_files[1])
417
Austin Schuh2e554032019-01-21 15:07:27 -0800418 integral_loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700419 'Integral' + name,
420 integral_angular_systems,
Austin Schuh2e554032019-01-21 15:07:27 -0800421 namespaces=year_namespaces)
422 integral_loop_writer.Write(controller_files[0], controller_files[1])