blob: 7129e324a75a9205647f007afeaad15d28bd1dda [file] [log] [blame]
Austin Schuhb5d302f2019-01-20 20:51:19 -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
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,
24 dt=0.005):
25 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]
59 C1 = self.motor.Kt / (self.G * self.G * self.radius * self.radius *
60 self.motor.resistance * self.mass *
61 self.motor.Kv)
62 C2 = self.motor.Kt / (self.G * self.radius * self.motor.resistance *
63 self.mass)
64
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)
82 glog.debug('Stall force: %f', self.motor.stall_torque / self.G / self.radius)
83 glog.debug('Stall acceleration: %f', self.motor.stall_torque / self.G /
84 self.radius / self.mass)
85
86 glog.debug('Free speed is %f',
87 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
88
89 self.Q = numpy.matrix([[(1.0 / (self.params.q_pos**2.0)), 0.0],
90 [0.0, (1.0 / (self.params.q_vel**2.0))]])
91
92 self.R = numpy.matrix([[(1.0 / (12.0**2.0))]])
93 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
94
95 q_pos_ff = 0.005
96 q_vel_ff = 1.0
97 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff**2.0)), 0.0],
98 [0.0, (1.0 / (q_vel_ff**2.0))]])
99
100 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
101
102 glog.debug('K %s', repr(self.K))
103 glog.debug('Poles are %s',
104 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
105
106 self.Q = numpy.matrix([[(self.params.kalman_q_pos**2.0), 0.0],
107 [0.0, (self.params.kalman_q_vel**2.0)]])
108
109 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
110
111 self.KalmanGain, self.Q_steady = controls.kalman(
112 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
113
114 glog.debug('Kal %s', repr(self.KalmanGain))
115
116 # The box formed by U_min and U_max must encompass all possible values,
117 # or else Austin's code gets angry.
118 self.U_max = numpy.matrix([[12.0]])
119 self.U_min = numpy.matrix([[-12.0]])
120
121 self.InitializeState()
122
123
124class IntegralLinearSystem(LinearSystem):
125 def __init__(self, params, name='IntegralLinearSystem'):
126 super(IntegralLinearSystem, self).__init__(params, name=name)
127
Austin Schuhb5d302f2019-01-20 20:51:19 -0800128 self.A_continuous_unaugmented = self.A_continuous
129 self.B_continuous_unaugmented = self.B_continuous
130
131 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
132 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
133 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
134
135 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
136 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
137
138 self.C_unaugmented = self.C
139 self.C = numpy.matrix(numpy.zeros((1, 3)))
140 self.C[0:1, 0:2] = self.C_unaugmented
141
142 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
143 self.B_continuous, self.dt)
144
145 self.Q = numpy.matrix(
146 [[(self.params.kalman_q_pos**2.0), 0.0, 0.0],
147 [0.0, (self.params.kalman_q_vel**2.0), 0.0],
148 [0.0, 0.0, (self.params.kalman_q_voltage**2.0)]])
149
150 self.R = numpy.matrix([[(self.params.kalman_r_position**2.0)]])
151
152 self.KalmanGain, self.Q_steady = controls.kalman(
153 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
154
155 self.K_unaugmented = self.K
156 self.K = numpy.matrix(numpy.zeros((1, 3)))
157 self.K[0, 0:2] = self.K_unaugmented
158 self.K[0, 2] = 1
159
160 self.Kff = numpy.concatenate(
161 (self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
162
163 self.InitializeState()
164
165
166def RunTest(plant,
167 end_goal,
168 controller,
169 observer=None,
170 duration=1.0,
171 use_profile=True,
172 kick_time=0.5,
173 kick_magnitude=0.0,
174 max_velocity=0.3):
175 """Runs the plant with an initial condition and goal.
176
177 Args:
178 plant: plant object to use.
179 end_goal: end_goal state.
Austin Schuh2e554032019-01-21 15:07:27 -0800180 controller: LinearSystem object to get K from, or None if we should
Austin Schuhb5d302f2019-01-20 20:51:19 -0800181 use plant.
Austin Schuh2e554032019-01-21 15:07:27 -0800182 observer: LinearSystem object to use for the observer, or None if we
183 should use the actual state.
Austin Schuhb5d302f2019-01-20 20:51:19 -0800184 duration: float, time in seconds to run the simulation for.
185 kick_time: float, time in seconds to kick the robot.
186 kick_magnitude: float, disturbance in volts to apply.
187 max_velocity: float, the max speed in m/s to profile.
188 """
189 t_plot = []
190 x_plot = []
191 v_plot = []
192 a_plot = []
193 x_goal_plot = []
194 v_goal_plot = []
195 x_hat_plot = []
196 u_plot = []
197 offset_plot = []
198
199 if controller is None:
200 controller = plant
201
202 vbat = 12.0
203
204 goal = numpy.concatenate(
205 (plant.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
206
207 profile = TrapezoidProfile(plant.dt)
208 profile.set_maximum_acceleration(10.0)
209 profile.set_maximum_velocity(max_velocity)
210 profile.SetGoal(goal[0, 0])
211
212 U_last = numpy.matrix(numpy.zeros((1, 1)))
213 iterations = int(duration / plant.dt)
214 for i in xrange(iterations):
215 t = i * plant.dt
216 observer.Y = plant.Y
217 observer.CorrectObserver(U_last)
218
219 offset_plot.append(observer.X_hat[2, 0])
220 x_hat_plot.append(observer.X_hat[0, 0])
221
222 next_goal = numpy.concatenate(
223 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
224 numpy.matrix(numpy.zeros((1, 1)))),
225 axis=0)
226
227 ff_U = controller.Kff * (next_goal - observer.A * goal)
228
229 if use_profile:
230 U_uncapped = controller.K * (goal - observer.X_hat) + ff_U
231 x_goal_plot.append(goal[0, 0])
232 v_goal_plot.append(goal[1, 0])
233 else:
234 U_uncapped = controller.K * (end_goal - observer.X_hat)
235 x_goal_plot.append(end_goal[0, 0])
236 v_goal_plot.append(end_goal[1, 0])
237
238 U = U_uncapped.copy()
239 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
240 x_plot.append(plant.X[0, 0])
241
242 if v_plot:
243 last_v = v_plot[-1]
244 else:
245 last_v = 0
246
247 v_plot.append(plant.X[1, 0])
248 a_plot.append((v_plot[-1] - last_v) / plant.dt)
249
250 u_offset = 0.0
251 if t >= kick_time:
252 u_offset = kick_magnitude
253 plant.Update(U + u_offset)
254
255 observer.PredictObserver(U)
256
257 t_plot.append(t)
258 u_plot.append(U[0, 0])
259
260 ff_U -= U_uncapped - U
261 goal = controller.A * goal + controller.B * ff_U
262
263 if U[0, 0] != U_uncapped[0, 0]:
264 profile.MoveCurrentState(
265 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
266
267 glog.debug('Time: %f', t_plot[-1])
268 glog.debug('goal_error %s', repr(end_goal - goal))
269 glog.debug('error %s', repr(observer.X_hat - end_goal))
270
271 pylab.subplot(3, 1, 1)
272 pylab.plot(t_plot, x_plot, label='x')
273 pylab.plot(t_plot, x_hat_plot, label='x_hat')
274 pylab.plot(t_plot, x_goal_plot, label='x_goal')
275 pylab.legend()
276
277 pylab.subplot(3, 1, 2)
278 pylab.plot(t_plot, u_plot, label='u')
279 pylab.plot(t_plot, offset_plot, label='voltage_offset')
280 pylab.legend()
281
282 pylab.subplot(3, 1, 3)
283 pylab.plot(t_plot, a_plot, label='a')
284 pylab.legend()
285
286 pylab.show()
287
288
289def PlotStep(params, R):
290 """Plots a step move to the goal.
291
292 Args:
293 R: numpy.matrix(2, 1), the goal"""
294 plant = LinearSystem(params, params.name)
295 controller = IntegralLinearSystem(params, params.name)
296 observer = IntegralLinearSystem(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
313def PlotKick(params, R):
314 """Plots a step motion with a kick at 1.0 seconds.
315
316 Args:
317 R: numpy.matrix(2, 1), the goal"""
318 plant = LinearSystem(params, params.name)
319 controller = IntegralLinearSystem(params, params.name)
320 observer = IntegralLinearSystem(params, params.name)
321
322 # Test moving the system.
323 initial_X = numpy.matrix([[0.0], [0.0]])
324 augmented_R = numpy.matrix(numpy.zeros((3, 1)))
325 augmented_R[0:2, :] = R
326 RunTest(
327 plant,
328 end_goal=augmented_R,
329 controller=controller,
330 observer=observer,
331 duration=2.0,
332 use_profile=False,
333 kick_time=1.0,
334 kick_magnitude=2.0)
335
336
337def PlotMotion(params, R, max_velocity=0.3):
338 """Plots a trapezoidal motion.
339
340 Args:
341 R: numpy.matrix(2, 1), the goal,
342 max_velocity: float, The max velocity of the profile.
343 """
344 plant = LinearSystem(params, params.name)
345 controller = IntegralLinearSystem(params, params.name)
346 observer = IntegralLinearSystem(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=True,
359 max_velocity=max_velocity)
360
361
362def WriteLinearSystem(params, plant_files, controller_files, year_namespaces):
363 """Writes out the constants for a linear system to a file.
364
365 Args:
366 params: LinearSystemParams, the parameters defining the system.
367 plant_files: list of strings, the cc and h files for the plant.
368 controller_files: list of strings, the cc and h files for the integral
369 controller.
370 year_namespaces: list of strings, the namespace list to use.
371 """
372 # Write the generated constants out to a file.
373 linear_system = LinearSystem(params, params.name)
374 loop_writer = control_loop.ControlLoopWriter(
375 linear_system.name, [linear_system], namespaces=year_namespaces)
376 loop_writer.AddConstant(
377 control_loop.Constant('kFreeSpeed', '%f', linear_system.motor.
378 free_speed / (2.0 * numpy.pi)))
379 loop_writer.AddConstant(
380 control_loop.Constant('kOutputRatio', '%f', linear_system.G *
381 linear_system.radius))
382 loop_writer.Write(plant_files[0], plant_files[1])
383
384 integral_linear_system = IntegralLinearSystem(params,
385 'Integral' + params.name)
386 integral_loop_writer = control_loop.ControlLoopWriter(
387 integral_linear_system.name, [integral_linear_system],
388 namespaces=year_namespaces)
389 integral_loop_writer.Write(controller_files[0], controller_files[1])