blob: a0a07d670bd6c06b6fc50118adcec79378e52ef9 [file] [log] [blame]
Austin Schuh2e554032019-01-21 15:07:27 -08001#!/usr/bin/python
2
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):
Tyler Chatow6738c362019-02-16 14:12:30 -080012
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,
Austin Schuh63d095d2019-02-23 11:57:12 -080024 dt=0.00505):
Austin Schuh2e554032019-01-21 15:07:27 -080025 self.name = name
26 self.motor = motor
27 self.G = G
28 self.J = J
29 self.q_pos = q_pos
30 self.q_vel = q_vel
31 self.kalman_q_pos = kalman_q_pos
32 self.kalman_q_vel = kalman_q_vel
33 self.kalman_q_voltage = kalman_q_voltage
34 self.kalman_r_position = kalman_r_position
35 self.dt = dt
36
37
38class AngularSystem(control_loop.ControlLoop):
Tyler Chatow6738c362019-02-16 14:12:30 -080039
Austin Schuh2e554032019-01-21 15:07:27 -080040 def __init__(self, params, name="AngularSystem"):
41 super(AngularSystem, self).__init__(name)
42 self.params = params
43
44 self.motor = params.motor
45
46 # Gear ratio
47 self.G = params.G
48
49 # Moment of inertia in kg m^2
Tyler Chatow6738c362019-02-16 14:12:30 -080050 self.J = params.J + self.motor.motor_inertia / (self.G**2.0)
Austin Schuh2e554032019-01-21 15:07:27 -080051
52 # Control loop time step
53 self.dt = params.dt
54
55 # State is [position, velocity]
56 # Input is [Voltage]
Tyler Chatow6738c362019-02-16 14:12:30 -080057 C1 = self.motor.Kt / (
58 self.G * self.G * self.motor.resistance * self.J * self.motor.Kv)
Austin Schuh2e554032019-01-21 15:07:27 -080059 C2 = self.motor.Kt / (self.G * self.J * self.motor.resistance)
60
61 self.A_continuous = numpy.matrix([[0, 1], [0, -C1]])
62
63 # Start with the unmodified input
64 self.B_continuous = numpy.matrix([[0], [C2]])
65 glog.debug(repr(self.A_continuous))
66 glog.debug(repr(self.B_continuous))
67
68 self.C = numpy.matrix([[1, 0]])
69 self.D = numpy.matrix([[0]])
70
71 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
72 self.B_continuous, self.dt)
73
74 controllability = controls.ctrb(self.A, self.B)
75 glog.debug('Controllability of %d',
76 numpy.linalg.matrix_rank(controllability))
77 glog.debug('J: %f', self.J)
78 glog.debug('Stall torque: %f', self.motor.stall_torque / self.G)
79 glog.debug('Stall acceleration: %f',
80 self.motor.stall_torque / self.G / self.J)
81
82 glog.debug('Free speed is %f',
83 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
84
85 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
86 [0.0, (1.0 / (self.params.q_vel**2.0))]])
87
88 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
89 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
90
91 q_pos_ff = 0.005
92 q_vel_ff = 1.0
93 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
94 [0.0, (1.0 / (q_vel_ff**2.0))]])
95
96 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
97
98 glog.debug('K %s', repr(self.K))
99 glog.debug('Poles are %s',
100 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
101
102 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
103 [0.0, (self.params.kalman_q_vel**2.0)]])
104
105 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
106
107 self.KalmanGain, self.Q_steady = controls.kalman(
108 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
109
110 glog.debug('Kal %s', repr(self.KalmanGain))
111
112 # The box formed by U_min and U_max must encompass all possible values,
113 # or else Austin's code gets angry.
114 self.U_max = numpy.matrix([[12.0]])
115 self.U_min = numpy.matrix([[-12.0]])
116
117 self.InitializeState()
118
119
120class IntegralAngularSystem(AngularSystem):
Tyler Chatow6738c362019-02-16 14:12:30 -0800121
Austin Schuh2e554032019-01-21 15:07:27 -0800122 def __init__(self, params, name="IntegralAngularSystem"):
123 super(IntegralAngularSystem, self).__init__(params, name=name)
124
125 self.A_continuous_unaugmented = self.A_continuous
126 self.B_continuous_unaugmented = self.B_continuous
127
128 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
129 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
130 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
131
132 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
133 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
134
135 self.C_unaugmented = self.C
136 self.C = numpy.matrix(numpy.zeros((1, 3)))
137 self.C[0:1, 0:2] = self.C_unaugmented
138
139 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
140 self.B_continuous, self.dt)
141
Tyler Chatow6738c362019-02-16 14:12:30 -0800142 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
143 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
144 [0.0, 0.0, (self.params.kalman_q_voltage**2.0)]])
Austin Schuh2e554032019-01-21 15:07:27 -0800145
146 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
147
148 self.KalmanGain, self.Q_steady = controls.kalman(
149 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
150
151 self.K_unaugmented = self.K
152 self.K = numpy.matrix(numpy.zeros((1, 3)))
153 self.K[0, 0:2] = self.K_unaugmented
154 self.K[0, 2] = 1
155
156 self.Kff = numpy.concatenate(
157 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
158
159 self.InitializeState()
160
161
162def RunTest(plant,
163 end_goal,
164 controller,
165 observer=None,
166 duration=1.0,
167 use_profile=True,
168 kick_time=0.5,
Lee Mracek28795ef2019-01-27 05:29:37 -0500169 kick_magnitude=0.0,
170 max_velocity=10.0,
171 max_acceleration=70.0):
Austin Schuh2e554032019-01-21 15:07:27 -0800172 """Runs the plant with an initial condition and goal.
173
174 Args:
175 plant: plant object to use.
176 end_goal: end_goal state.
177 controller: AngularSystem object to get K from, or None if we should
178 use plant.
179 observer: AngularSystem object to use for the observer, or None if we
180 should use the actual state.
181 duration: float, time in seconds to run the simulation for.
182 kick_time: float, time in seconds to kick the robot.
183 kick_magnitude: float, disturbance in volts to apply.
Lee Mracek28795ef2019-01-27 05:29:37 -0500184 max_velocity: float, The maximum velocity for the profile.
185 max_acceleration: float, The maximum acceleration for the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800186 """
187 t_plot = []
188 x_plot = []
189 v_plot = []
190 a_plot = []
191 x_goal_plot = []
192 v_goal_plot = []
193 x_hat_plot = []
194 u_plot = []
195 offset_plot = []
196
197 if controller is None:
198 controller = plant
199
200 vbat = 12.0
201
Tyler Chatow6738c362019-02-16 14:12:30 -0800202 goal = numpy.concatenate((plant.X, numpy.matrix(numpy.zeros((1, 1)))),
203 axis=0)
Austin Schuh2e554032019-01-21 15:07:27 -0800204
205 profile = TrapezoidProfile(plant.dt)
Lee Mracek28795ef2019-01-27 05:29:37 -0500206 profile.set_maximum_acceleration(max_acceleration)
207 profile.set_maximum_velocity(max_velocity)
Austin Schuh2e554032019-01-21 15:07:27 -0800208 profile.SetGoal(goal[0, 0])
209
210 U_last = numpy.matrix(numpy.zeros((1, 1)))
211 iterations = int(duration / plant.dt)
212 for i in xrange(iterations):
213 t = i * plant.dt
214 observer.Y = plant.Y
215 observer.CorrectObserver(U_last)
216
217 offset_plot.append(observer.X_hat[2, 0])
218 x_hat_plot.append(observer.X_hat[0, 0])
219
220 next_goal = numpy.concatenate(
221 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
222 numpy.matrix(numpy.zeros((1, 1)))),
223 axis=0)
224
225 ff_U = controller.Kff * (next_goal - observer.A * goal)
226
227 if use_profile:
228 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
229 x_goal_plot.append(goal[0, 0])
230 v_goal_plot.append(goal[1, 0])
231 else:
232 U_uncapped = controller.K * (end_goal - observer.X_hat)
233 x_goal_plot.append(end_goal[0, 0])
234 v_goal_plot.append(end_goal[1, 0])
235
236 U = U_uncapped.copy()
237 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
238 x_plot.append(plant.X[0, 0])
239
240 if v_plot:
241 last_v = v_plot[-1]
242 else:
243 last_v = 0
244
245 v_plot.append(plant.X[1, 0])
246 a_plot.append((v_plot[-1] - last_v) / plant.dt)
247
248 u_offset = 0.0
249 if t >= kick_time:
250 u_offset = kick_magnitude
251 plant.Update(U + u_offset)
252
253 observer.PredictObserver(U)
254
255 t_plot.append(t)
256 u_plot.append(U[0, 0])
257
258 ff_U -= U_uncapped - U
259 goal = controller.A * goal + controller.B * ff_U
260
261 if U[0, 0] != U_uncapped[0, 0]:
Tyler Chatow6738c362019-02-16 14:12:30 -0800262 profile.MoveCurrentState(numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
Austin Schuh2e554032019-01-21 15:07:27 -0800263
264 glog.debug('Time: %f', t_plot[-1])
265 glog.debug('goal_error %s', repr(end_goal - goal))
266 glog.debug('error %s', repr(observer.X_hat - end_goal))
267
268 pylab.subplot(3, 1, 1)
269 pylab.plot(t_plot, x_plot, label='x')
270 pylab.plot(t_plot, x_hat_plot, label='x_hat')
271 pylab.plot(t_plot, x_goal_plot, label='x_goal')
272 pylab.legend()
273
274 pylab.subplot(3, 1, 2)
275 pylab.plot(t_plot, u_plot, label='u')
276 pylab.plot(t_plot, offset_plot, label='voltage_offset')
277 pylab.legend()
278
279 pylab.subplot(3, 1, 3)
280 pylab.plot(t_plot, a_plot, label='a')
281 pylab.legend()
282
283 pylab.show()
284
285
Austin Schuh9d9d3742019-02-15 23:00:13 -0800286def PlotStep(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800287 """Plots a step move to the goal.
288
289 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800290 params: AngularSystemParams for the controller and observer
291 plant_params: AngularSystemParams for the plant. Defaults to params if
292 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800293 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800294 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800295 controller = IntegralAngularSystem(params, params.name)
296 observer = IntegralAngularSystem(params, params.name)
297
298 # Test moving the system.
299 initial_X = numpy.matrix([[0.0], [0.0]])
300 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
301 augmented_R[0:2, :] = R
302 RunTest(
303 plant,
304 end_goal=augmented_R,
305 controller=controller,
306 observer=observer,
307 duration=2.0,
308 use_profile=False,
309 kick_time=1.0,
310 kick_magnitude=0.0)
311
312
Austin Schuh9d9d3742019-02-15 23:00:13 -0800313def PlotKick(params, R, plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800314 """Plots a step motion with a kick at 1.0 seconds.
315
316 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800317 params: AngularSystemParams for the controller and observer
318 plant_params: AngularSystemParams for the plant. Defaults to params if
319 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800320 R: numpy.matrix(2, 1), the goal"""
Austin Schuh9d9d3742019-02-15 23:00:13 -0800321 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800322 controller = IntegralAngularSystem(params, params.name)
323 observer = IntegralAngularSystem(params, params.name)
324
325 # Test moving the system.
326 initial_X = numpy.matrix([[0.0], [0.0]])
327 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
328 augmented_R[0:2, :] = R
329 RunTest(
330 plant,
331 end_goal=augmented_R,
332 controller=controller,
333 observer=observer,
334 duration=2.0,
335 use_profile=False,
336 kick_time=1.0,
337 kick_magnitude=2.0)
338
339
Austin Schuh9d9d3742019-02-15 23:00:13 -0800340def PlotMotion(params,
341 R,
342 max_velocity=10.0,
343 max_acceleration=70.0,
344 plant_params=None):
Austin Schuh2e554032019-01-21 15:07:27 -0800345 """Plots a trapezoidal motion.
346
347 Args:
Austin Schuh9d9d3742019-02-15 23:00:13 -0800348 params: AngularSystemParams for the controller and observer
349 plant_params: AngularSystemParams for the plant. Defaults to params if
350 plant_params is None.
Austin Schuh2e554032019-01-21 15:07:27 -0800351 R: numpy.matrix(2, 1), the goal,
Lee Mracek28795ef2019-01-27 05:29:37 -0500352 max_velocity: float, The max velocity of the profile.
353 max_acceleration: float, The max acceleration of the profile.
Austin Schuh2e554032019-01-21 15:07:27 -0800354 """
Austin Schuh9d9d3742019-02-15 23:00:13 -0800355 plant = AngularSystem(plant_params or params, params.name)
Austin Schuh2e554032019-01-21 15:07:27 -0800356 controller = IntegralAngularSystem(params, params.name)
357 observer = IntegralAngularSystem(params, params.name)
358
359 # Test moving the system.
360 initial_X = numpy.matrix([[0.0], [0.0]])
361 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
362 augmented_R[0:2, :] = R
363 RunTest(
364 plant,
365 end_goal=augmented_R,
366 controller=controller,
367 observer=observer,
368 duration=2.0,
Lee Mracek28795ef2019-01-27 05:29:37 -0500369 use_profile=True,
370 max_velocity=max_velocity,
371 max_acceleration=max_acceleration)
Austin Schuh2e554032019-01-21 15:07:27 -0800372
373
374def WriteAngularSystem(params, plant_files, controller_files, year_namespaces):
375 """Writes out the constants for a angular system to a file.
376
377 Args:
378 params: AngularSystemParams, the parameters defining the system.
379 plant_files: list of strings, the cc and h files for the plant.
380 controller_files: list of strings, the cc and h files for the integral
381 controller.
382 year_namespaces: list of strings, the namespace list to use.
383 """
384 # Write the generated constants out to a file.
385 angular_system = AngularSystem(params, params.name)
386 loop_writer = control_loop.ControlLoopWriter(
387 angular_system.name, [angular_system], namespaces=year_namespaces)
Lee Mracek17cb4892019-02-07 11:24:49 -0500388 loop_writer.AddConstant(
389 control_loop.Constant('kOutputRatio', '%f', angular_system.G))
390 loop_writer.AddConstant(
Tyler Chatow6738c362019-02-16 14:12:30 -0800391 control_loop.Constant('kFreeSpeed', '%f',
392 angular_system.motor.free_speed))
Austin Schuh2e554032019-01-21 15:07:27 -0800393 loop_writer.Write(plant_files[0], plant_files[1])
394
395 integral_angular_system = IntegralAngularSystem(params,
396 'Integral' + params.name)
397 integral_loop_writer = control_loop.ControlLoopWriter(
398 integral_angular_system.name, [integral_angular_system],
399 namespaces=year_namespaces)
400 integral_loop_writer.Write(controller_files[0], controller_files[1])