blob: e17990aee95213b69a79f9c03ea611c1df195aa8 [file] [log] [blame]
Brian Silverman17f503e2015-08-02 18:17:18 -07001#!/usr/bin/python
2
3import control_loop
4import controls
5import polytope
6import polydrivetrain
7import numpy
8import math
9import sys
10import matplotlib
11from matplotlib import pylab
12
13
14class Arm(control_loop.ControlLoop):
15 def __init__(self, name="Arm", mass=None):
16 super(Arm, self).__init__(name)
17 # Stall Torque in N m
18 self.stall_torque = 0.476
19 # Stall Current in Amps
20 self.stall_current = 80.730
21 # Free Speed in RPM
22 self.free_speed = 13906.0
23 # Free Current in Amps
24 self.free_current = 5.820
25 # Mass of the arm
26 if mass is None:
27 self.mass = 13.0
28 else:
29 self.mass = mass
30
31 # Resistance of the motor
32 self.R = 12.0 / self.stall_current
33 # Motor velocity constant
34 self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
35 (12.0 - self.R * self.free_current))
36 # Torque constant
37 self.Kt = self.stall_torque / self.stall_current
38 # Gear ratio
39 self.G = (44.0 / 12.0) * (54.0 / 14.0) * (54.0 / 14.0) * (44.0 / 20.0) * (72.0 / 16.0)
40 # Fridge arm length
41 self.r = 32 * 0.0254
42 # Control loop time step
43 self.dt = 0.005
44
45 # Arm moment of inertia
46 self.J = self.r * self.mass
47
48 # Arm left/right spring constant (N*m / radian)
49 self.spring = 100.0
50
51 # State is [average position, average velocity,
52 # position difference/2, velocity difference/2]
53 # Position difference is 1 - 2
54 # Input is [Voltage 1, Voltage 2]
55
56 self.C1 = self.spring / (self.J * 0.5)
57 self.C2 = self.Kt * self.G / (self.J * 0.5 * self.R)
58 self.C3 = self.G * self.G * self.Kt / (self.R * self.J * 0.5 * self.Kv)
59
60 self.A_continuous = numpy.matrix(
61 [[0, 1, 0, 0],
62 [0, -self.C3, 0, 0],
63 [0, 0, 0, 1],
64 [0, 0, -self.C1 * 2.0, -self.C3]])
65
66 print 'Full speed is', self.C2 / self.C3 * 12.0
67
68 print 'Stall arm difference is', 12.0 * self.C2 / self.C1
69 print 'Stall arm difference first principles is', self.stall_torque * self.G / self.spring
70
71 print '5 degrees of arm error is', self.spring / self.r * (math.pi * 5.0 / 180.0)
72
73 # Start with the unmodified input
74 self.B_continuous = numpy.matrix(
75 [[0, 0],
76 [self.C2 / 2.0, self.C2 / 2.0],
77 [0, 0],
78 [self.C2 / 2.0, -self.C2 / 2.0]])
79
80 self.C = numpy.matrix([[1, 0, 1, 0],
81 [1, 0, -1, 0]])
82 self.D = numpy.matrix([[0, 0],
83 [0, 0]])
84
85 self.A, self.B = self.ContinuousToDiscrete(
86 self.A_continuous, self.B_continuous, self.dt)
87
88 controlability = controls.ctrb(self.A, self.B);
89 print 'Rank of augmented controlability matrix.', numpy.linalg.matrix_rank(
90 controlability)
91
92 q_pos = 0.02
93 q_vel = 0.300
94 q_pos_diff = 0.005
95 q_vel_diff = 0.13
96 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
97 [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
98 [0.0, 0.0, (1.0 / (q_pos_diff ** 2.0)), 0.0],
99 [0.0, 0.0, 0.0, (1.0 / (q_vel_diff ** 2.0))]])
100
101 self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0)), 0.0],
102 [0.0, 1.0 / (12.0 ** 2.0)]])
103 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
104 print 'Controller'
105 print self.K
106
107 print 'Controller Poles'
108 print numpy.linalg.eig(self.A - self.B * self.K)[0]
109
110 self.rpl = 0.20
111 self.ipl = 0.05
112 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
113 self.rpl + 1j * self.ipl,
114 self.rpl - 1j * self.ipl,
115 self.rpl - 1j * self.ipl])
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], [12.0]])
120 self.U_min = numpy.matrix([[-12.0], [-12.0]])
121
122 print 'Observer (Converted to a KF)', numpy.linalg.inv(self.A) * self.L
123
124 self.InitializeState()
125
126
127class IntegralArm(Arm):
128 def __init__(self, name="IntegralArm", mass=None):
129 super(IntegralArm, self).__init__(name=name, mass=mass)
130
131 self.A_continuous_unaugmented = self.A_continuous
132 self.A_continuous = numpy.matrix(numpy.zeros((5, 5)))
133 self.A_continuous[0:4, 0:4] = self.A_continuous_unaugmented
134 self.A_continuous[1, 4] = self.C2
135
136 # Start with the unmodified input
137 self.B_continuous_unaugmented = self.B_continuous
138 self.B_continuous = numpy.matrix(numpy.zeros((5, 2)))
139 self.B_continuous[0:4, 0:2] = self.B_continuous_unaugmented
140
141 self.C_unaugmented = self.C
142 self.C = numpy.matrix(numpy.zeros((2, 5)))
143 self.C[0:2, 0:4] = self.C_unaugmented
144
145 self.A, self.B = self.ContinuousToDiscrete(
146 self.A_continuous, self.B_continuous, self.dt)
147 print 'A cont', self.A_continuous
148 print 'B cont', self.B_continuous
149 print 'A discrete', self.A
150
151 q_pos = 0.08
152 q_vel = 0.40
153
154 q_pos_diff = 0.08
155 q_vel_diff = 0.40
156 q_voltage = 6.0
157 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0, 0.0],
158 [0.0, (q_vel ** 2.0), 0.0, 0.0, 0.0],
159 [0.0, 0.0, (q_pos_diff ** 2.0), 0.0, 0.0],
160 [0.0, 0.0, 0.0, (q_vel_diff ** 2.0), 0.0],
161 [0.0, 0.0, 0.0, 0.0, (q_voltage ** 2.0)]])
162
163 r_volts = 0.05
164 self.R = numpy.matrix([[(r_volts ** 2.0), 0.0],
165 [0.0, (r_volts ** 2.0)]])
166
167 self.KalmanGain, self.Q_steady = controls.kalman(
168 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
169
170 self.U_max = numpy.matrix([[12.0], [12.0]])
171 self.U_min = numpy.matrix([[-12.0], [-12.0]])
172
173 self.K_unaugmented = self.K
174 self.K = numpy.matrix(numpy.zeros((2, 5)));
175 self.K[0:2, 0:4] = self.K_unaugmented
176 self.K[0, 4] = 1;
177 self.K[1, 4] = 1;
178 print 'Kal', self.KalmanGain
179 self.L = self.A * self.KalmanGain
180
181 self.InitializeState()
182
183
184def CapU(U):
185 if U[0, 0] - U[1, 0] > 24:
186 return numpy.matrix([[12], [-12]])
187 elif U[0, 0] - U[1, 0] < -24:
188 return numpy.matrix([[-12], [12]])
189 else:
190 max_u = max(U[0, 0], U[1, 0])
191 min_u = min(U[0, 0], U[1, 0])
192 if max_u > 12:
193 return U - (max_u - 12)
194 if min_u < -12:
195 return U - (min_u + 12)
196 return U
197
198
199def run_test(arm, initial_X, goal, max_separation_error=0.01,
200 show_graph=True, iterations=200, controller_arm=None,
201 observer_arm=None):
202 """Runs the arm plant with an initial condition and goal.
203
204 The tests themselves are not terribly sophisticated; I just test for
205 whether the goal has been reached and whether the separation goes
206 outside of the initial and goal values by more than max_separation_error.
207 Prints out something for a failure of either condition and returns
208 False if tests fail.
209 Args:
210 arm: arm object to use.
211 initial_X: starting state.
212 goal: goal state.
213 show_graph: Whether or not to display a graph showing the changing
214 states and voltages.
215 iterations: Number of timesteps to run the model for.
216 controller_arm: arm object to get K from, or None if we should
217 use arm.
218 observer_arm: arm object to use for the observer, or None if we should
219 use the actual state.
220 """
221
222 arm.X = initial_X
223
224 if controller_arm is None:
225 controller_arm = arm
226
227 if observer_arm is not None:
228 observer_arm.X_hat = initial_X + 0.01
229 observer_arm.X_hat = initial_X
230
231 # Various lists for graphing things.
232 t = []
233 x_avg = []
234 x_sep = []
235 x_hat_avg = []
236 x_hat_sep = []
237 v_avg = []
238 v_sep = []
239 u_left = []
240 u_right = []
241
242 sep_plot_gain = 100.0
243
244 for i in xrange(iterations):
245 X_hat = arm.X
246 if observer_arm is not None:
247 X_hat = observer_arm.X_hat
248 x_hat_avg.append(observer_arm.X_hat[0, 0])
249 x_hat_sep.append(observer_arm.X_hat[2, 0] * sep_plot_gain)
250 U = controller_arm.K * (goal - X_hat)
251 U = CapU(U)
252 x_avg.append(arm.X[0, 0])
253 v_avg.append(arm.X[1, 0])
254 x_sep.append(arm.X[2, 0] * sep_plot_gain)
255 v_sep.append(arm.X[3, 0])
256 if observer_arm is not None:
257 observer_arm.PredictObserver(U)
258 arm.Update(U)
259 if observer_arm is not None:
260 observer_arm.Y = arm.Y
261 observer_arm.CorrectObserver(U)
262
263 t.append(i * arm.dt)
264 u_left.append(U[0, 0])
265 u_right.append(U[1, 0])
266
267 print numpy.linalg.inv(arm.A)
268 print "delta time is ", arm.dt
269 print "Velocity at t=0 is ", x_avg[0], v_avg[0], x_sep[0], v_sep[0]
270 print "Velocity at t=1+dt is ", x_avg[1], v_avg[1], x_sep[1], v_sep[1]
271
272 if show_graph:
273 pylab.subplot(2, 1, 1)
274 pylab.plot(t, x_avg, label='x avg')
275 pylab.plot(t, x_sep, label='x sep')
276 if observer_arm is not None:
277 pylab.plot(t, x_hat_avg, label='x_hat avg')
278 pylab.plot(t, x_hat_sep, label='x_hat sep')
279 pylab.legend()
280
281 pylab.subplot(2, 1, 2)
282 pylab.plot(t, u_left, label='u left')
283 pylab.plot(t, u_right, label='u right')
284 pylab.legend()
285 pylab.show()
286
287
288def run_integral_test(arm, initial_X, goal, observer_arm, disturbance,
289 max_separation_error=0.01, show_graph=True,
290 iterations=400):
291 """Runs the integral control arm plant with an initial condition and goal.
292
293 The tests themselves are not terribly sophisticated; I just test for
294 whether the goal has been reached and whether the separation goes
295 outside of the initial and goal values by more than max_separation_error.
296 Prints out something for a failure of either condition and returns
297 False if tests fail.
298 Args:
299 arm: arm object to use.
300 initial_X: starting state.
301 goal: goal state.
302 observer_arm: arm object to use for the observer.
303 show_graph: Whether or not to display a graph showing the changing
304 states and voltages.
305 iterations: Number of timesteps to run the model for.
306 disturbance: Voltage missmatch between controller and model.
307 """
308
309 arm.X = initial_X
310
311 # Various lists for graphing things.
312 t = []
313 x_avg = []
314 x_sep = []
315 x_hat_avg = []
316 x_hat_sep = []
317 v_avg = []
318 v_sep = []
319 u_left = []
320 u_right = []
321 u_error = []
322
323 sep_plot_gain = 100.0
324
325 unaugmented_goal = goal
326 goal = numpy.matrix(numpy.zeros((5, 1)))
327 goal[0:4, 0] = unaugmented_goal
328
329 for i in xrange(iterations):
330 X_hat = observer_arm.X_hat[0:4]
331
332 x_hat_avg.append(observer_arm.X_hat[0, 0])
333 x_hat_sep.append(observer_arm.X_hat[2, 0] * sep_plot_gain)
334
335 U = observer_arm.K * (goal - observer_arm.X_hat)
336 u_error.append(observer_arm.X_hat[4,0])
337 U = CapU(U)
338 x_avg.append(arm.X[0, 0])
339 v_avg.append(arm.X[1, 0])
340 x_sep.append(arm.X[2, 0] * sep_plot_gain)
341 v_sep.append(arm.X[3, 0])
342
343 observer_arm.PredictObserver(U)
344
345 arm.Update(U + disturbance)
346 observer_arm.Y = arm.Y
347 observer_arm.CorrectObserver(U)
348
349 t.append(i * arm.dt)
350 u_left.append(U[0, 0])
351 u_right.append(U[1, 0])
352
353 print 'End is', observer_arm.X_hat[4, 0]
354
355 if show_graph:
356 pylab.subplot(2, 1, 1)
357 pylab.plot(t, x_avg, label='x avg')
358 pylab.plot(t, x_sep, label='x sep')
359 if observer_arm is not None:
360 pylab.plot(t, x_hat_avg, label='x_hat avg')
361 pylab.plot(t, x_hat_sep, label='x_hat sep')
362 pylab.legend()
363
364 pylab.subplot(2, 1, 2)
365 pylab.plot(t, u_left, label='u left')
366 pylab.plot(t, u_right, label='u right')
367 pylab.plot(t, u_error, label='u error')
368 pylab.legend()
369 pylab.show()
370
371
372def main(argv):
373 loaded_mass = 25
374 #loaded_mass = 0
375 arm = Arm(mass=13 + loaded_mass)
376 #arm_controller = Arm(mass=13 + 15)
377 #observer_arm = Arm(mass=13 + 15)
378 #observer_arm = None
379
380 integral_arm = IntegralArm(mass=13 + loaded_mass)
381 integral_arm.X_hat[0, 0] += 0.02
382 integral_arm.X_hat[2, 0] += 0.02
383 integral_arm.X_hat[4] = 0
384
385 # Test moving the arm with constant separation.
386 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
387 R = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
388 run_integral_test(arm, initial_X, R, integral_arm, disturbance=2)
389
390 # Write the generated constants out to a file.
391 if len(argv) != 5:
392 print "Expected .h file name and .cc file name for the arm and augmented arm."
393 else:
394 arm = Arm("Arm", mass=13)
395 loop_writer = control_loop.ControlLoopWriter("Arm", [arm])
396 if argv[1][-3:] == '.cc':
397 loop_writer.Write(argv[2], argv[1])
398 else:
399 loop_writer.Write(argv[1], argv[2])
400
401 integral_arm = IntegralArm("IntegralArm", mass=13)
402 loop_writer = control_loop.ControlLoopWriter("IntegralArm", [integral_arm])
403 if argv[3][-3:] == '.cc':
404 loop_writer.Write(argv[4], argv[3])
405 else:
406 loop_writer.Write(argv[3], argv[4])
407
408if __name__ == '__main__':
409 sys.exit(main(sys.argv))