blob: 0391d93b1a3f8fa0366bc272825a21b80e31cc16 [file] [log] [blame]
Austin Schuh085eab92020-11-26 13:54:51 -08001#!/usr/bin/python3
Austin Schuhb5d302f2019-01-20 20:51:19 -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
Austin Schuhb5d302f2019-01-20 20:51:19 -08007from matplotlib import pylab
8import glog
9
10
11class LinearSystemParams(object):
12 def __init__(self,
13 name,
14 motor,
15 G,
16 radius,
17 mass,
18 q_pos,
19 q_vel,
20 kalman_q_pos,
21 kalman_q_vel,
22 kalman_q_voltage,
23 kalman_r_position,
Austin Schuh63d095d2019-02-23 11:57:12 -080024 dt=0.00505):
Austin Schuhb5d302f2019-01-20 20:51:19 -080025 self.name = name
26 self.motor = motor
27 self.G = G
28 self.radius = radius
29 self.mass = mass
30 self.q_pos = q_pos
31 self.q_vel = q_vel
32 self.kalman_q_pos = kalman_q_pos
33 self.kalman_q_vel = kalman_q_vel
34 self.kalman_q_voltage = kalman_q_voltage
35 self.kalman_r_position = kalman_r_position
36 self.dt = dt
37
38
39class LinearSystem(control_loop.ControlLoop):
40 def __init__(self, params, name='LinearSystem'):
41 super(LinearSystem, self).__init__(name)
42 self.params = params
43
44 self.motor = params.motor
45
46 # Gear ratio
47 self.G = params.G
48 self.radius = params.radius
49
Austin Schuh2e554032019-01-21 15:07:27 -080050 # Mass in kg
Austin Schuhb5d302f2019-01-20 20:51:19 -080051 self.mass = params.mass + self.motor.motor_inertia / (
52 (self.G * self.radius)**2.0)
53
54 # Control loop time step
55 self.dt = params.dt
56
57 # State is [position, velocity]
58 # Input is [Voltage]
Ravago Jones26f7ad02021-02-05 15:45:59 -080059 C1 = self.motor.Kt / (
60 self.G * self.G * self.radius * self.radius * self.motor.resistance
61 * self.mass * self.motor.Kv)
Tyler Chatow6738c362019-02-16 14:12:30 -080062 C2 = self.motor.Kt / (
63 self.G * self.radius * self.motor.resistance * self.mass)
Austin Schuhb5d302f2019-01-20 20:51:19 -080064
65 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
66
67 # Start with the unmodified input
68 self.B_continuous = numpy.matrix([[0], [C2]])
69 glog.debug(repr(self.A_continuous))
70 glog.debug(repr(self.B_continuous))
71
72 self.C = numpy.matrix([[1, 0]])
73 self.D = numpy.matrix([[0]])
74
75 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
76 self.B_continuous, self.dt)
77
78 controllability = controls.ctrb(self.A, self.B)
79 glog.debug('Controllability of %d',
80 numpy.linalg.matrix_rank(controllability))
81 glog.debug('Mass: %f', self.mass)
Tyler Chatow6738c362019-02-16 14:12:30 -080082 glog.debug('Stall force: %f',
83 self.motor.stall_torque / self.G / self.radius)
84 glog.debug('Stall acceleration: %f',
85 self.motor.stall_torque / self.G / self.radius / self.mass)
Austin Schuhb5d302f2019-01-20 20:51:19 -080086
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 IntegralLinearSystem(LinearSystem):
126 def __init__(self, params, name='IntegralLinearSystem'):
127 super(IntegralLinearSystem, self).__init__(params, name=name)
128
Austin Schuhb5d302f2019-01-20 20:51:19 -0800129 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 Schuhb5d302f2019-01-20 20:51:19 -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,
174 kick_magnitude=0.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500175 max_velocity=0.3,
176 max_acceleration=10.0):
Austin Schuhb5d302f2019-01-20 20:51:19 -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.
Austin Schuh2e554032019-01-21 15:07:27 -0800182 controller: LinearSystem object to get K from, or None if we should
Austin Schuhb5d302f2019-01-20 20:51:19 -0800183 use plant.
Austin Schuh2e554032019-01-21 15:07:27 -0800184 observer: LinearSystem object to use for the observer, or None if we
185 should use the actual state.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800186 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.
189 max_velocity: float, the max speed in m/s to profile.
Lee Mracek28795ef2019-01-27 05:29:37 -0500190 max_acceleration: float, the max acceleration in m/s/s to profile.
Austin Schuhb5d302f2019-01-20 20:51:19 -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 Schuhb5d302f2019-01-20 20:51:19 -0800209
210 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500211 profile.set_maximum_acceleration(max_acceleration)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800212 profile.set_maximum_velocity(max_velocity)
213 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 Schuhb5d302f2019-01-20 20:51:19 -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 Schuhb5d302f2019-01-20 20:51:19 -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 Schuhb5d302f2019-01-20 20:51:19 -0800293 """Plots a step move to the goal.
294
295 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800296 params: LinearSystemParams for the controller and observer
297 plant_params: LinearSystemParams for the plant. Defaults to params if
298 plant_params is None.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800299 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800300 plant = LinearSystem(plant_params or params, params.name)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800301 controller = IntegralLinearSystem(params, params.name)
302 observer = IntegralLinearSystem(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 Schuhb5d302f2019-01-20 20:51:19 -0800320 """Plots a step motion with a kick at 1.0 seconds.
321
322 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800323 params: LinearSystemParams for the controller and observer
324 plant_params: LinearSystemParams for the plant. Defaults to params if
325 plant_params is None.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800326 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800327 plant = LinearSystem(plant_params or params, params.name)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800328 controller = IntegralLinearSystem(params, params.name)
329 observer = IntegralLinearSystem(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=0.3,
349 max_acceleration=10.0,
350 plant_params=None):
Austin Schuhb5d302f2019-01-20 20:51:19 -0800351 """Plots a trapezoidal motion.
352
353 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800354 params: LinearSystemParams for the controller and observer
355 plant_params: LinearSystemParams for the plant. Defaults to params if
356 plant_params is None.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800357 R: numpy.matrix(2, 1), the goal,
358 max_velocity: float, The max velocity of the profile.
Lee Mracek28795ef2019-01-27 05:29:37 -0500359 max_acceleration: float, The max acceleration of the profile.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800360 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800361 plant = LinearSystem(plant_params or params, params.name)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800362 controller = IntegralLinearSystem(params, params.name)
363 observer = IntegralLinearSystem(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,
375 use_profile=True,
Lee Mracek28795ef2019-01-27 05:29:37 -0500376 max_velocity=max_velocity,
377 max_acceleration=max_acceleration)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800378
379
380def WriteLinearSystem(params, plant_files, controller_files, year_namespaces):
381 """Writes out the constants for a linear system to a file.
382
383 Args:
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700384 params: list of LinearSystemParams or LinearSystemParams, the
385 parameters defining the system.
Austin Schuhb5d302f2019-01-20 20:51:19 -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 linear_systems = []
393 integral_linear_systems = []
394
395 if type(params) is list:
396 name = params[0].name
397 for index, param in enumerate(params):
Ravago Jones26f7ad02021-02-05 15:45:59 -0800398 linear_systems.append(LinearSystem(param, param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700399 integral_linear_systems.append(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800400 IntegralLinearSystem(param,
401 'Integral' + param.name + str(index)))
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700402 else:
403 name = params.name
404 linear_systems.append(LinearSystem(params, params.name))
405 integral_linear_systems.append(
406 IntegralLinearSystem(params, 'Integral' + params.name))
407
Austin Schuhb5d302f2019-01-20 20:51:19 -0800408 loop_writer = control_loop.ControlLoopWriter(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700409 name, linear_systems, namespaces=year_namespaces)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800410 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800411 control_loop.Constant('kFreeSpeed', '%f',
412 linear_systems[0].motor.free_speed))
Austin Schuhb5d302f2019-01-20 20:51:19 -0800413 loop_writer.AddConstant(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800414 control_loop.Constant('kOutputRatio', '%f',
415 linear_systems[0].G * linear_systems[0].radius))
Alex Perry5fb5ff22019-02-09 21:53:17 -0800416 loop_writer.AddConstant(
Tyler Chatowd3afdef2019-04-06 22:15:26 -0700417 control_loop.Constant('kRadius', '%f', linear_systems[0].radius))
Austin Schuhb5d302f2019-01-20 20:51:19 -0800418 loop_writer.Write(plant_files[0], plant_files[1])
419
Austin Schuhb5d302f2019-01-20 20:51:19 -0800420 integral_loop_writer = control_loop.ControlLoopWriter(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800421 'Integral' + name, integral_linear_systems, namespaces=year_namespaces)
Austin Schuhb5d302f2019-01-20 20:51:19 -0800422 integral_loop_writer.Write(controller_files[0], controller_files[1])