blob: e6242eca882552bcd12fce6db1ec93401e79d2cd [file] [log] [blame]
Brian Silverman17f503e2015-08-02 18:17:18 -07001#!/usr/bin/python
2
Austin Schuhedc317c2015-11-08 14:07:42 -08003from frc971.control_loops.python import control_loop
4from frc971.control_loops.python import controls
5from frc971.control_loops.python import polytope
6from y2014.control_loops.python import polydrivetrain
Brian Silverman17f503e2015-08-02 18:17:18 -07007import numpy
8import sys
9from matplotlib import pylab
10
11class Claw(control_loop.ControlLoop):
12 def __init__(self, name="RawClaw"):
13 super(Claw, self).__init__(name)
14 # Stall Torque in N m
15 self.stall_torque = 2.42
16 # Stall Current in Amps
17 self.stall_current = 133
18 # Free Speed in RPM
19 self.free_speed = 5500.0
20 # Free Current in Amps
21 self.free_current = 2.7
22 # Moment of inertia of the claw in kg m^2
23 self.J_top = 2.8
24 self.J_bottom = 3.0
25
26 # Resistance of the motor
27 self.R = 12.0 / self.stall_current
28 # Motor velocity constant
29 self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
30 (13.5 - self.R * self.free_current))
31 # Torque constant
32 self.Kt = self.stall_torque / self.stall_current
33 # Gear ratio
34 self.G = 14.0 / 48.0 * 18.0 / 32.0 * 18.0 / 66.0 * 12.0 / 60.0
35 # Control loop time step
Austin Schuhadf2cde2015-11-08 20:35:16 -080036 self.dt = 0.005
Brian Silverman17f503e2015-08-02 18:17:18 -070037
38 # State is [bottom position, bottom velocity, top - bottom position,
39 # top - bottom velocity]
40 # Input is [bottom power, top power - bottom power * J_top / J_bottom]
41 # Motor time constants. difference_bottom refers to the constant for how the
42 # bottom velocity affects the difference of the top and bottom velocities.
43 self.common_motor_constant = -self.Kt / self.Kv / (self.G * self.G * self.R)
44 self.bottom_bottom = self.common_motor_constant / self.J_bottom
45 self.difference_bottom = -self.common_motor_constant * (1 / self.J_bottom
46 - 1 / self.J_top)
47 self.difference_difference = self.common_motor_constant / self.J_top
48 # State feedback matrices
49
50 self.A_continuous = numpy.matrix(
51 [[0, 0, 1, 0],
52 [0, 0, 0, 1],
53 [0, 0, self.bottom_bottom, 0],
54 [0, 0, self.difference_bottom, self.difference_difference]])
55
56 self.A_bottom_cont = numpy.matrix(
57 [[0, 1],
58 [0, self.bottom_bottom]])
59
60 self.A_diff_cont = numpy.matrix(
61 [[0, 1],
62 [0, self.difference_difference]])
63
64 self.motor_feedforward = self.Kt / (self.G * self.R)
65 self.motor_feedforward_bottom = self.motor_feedforward / self.J_bottom
66 self.motor_feedforward_difference = self.motor_feedforward / self.J_top
67 self.motor_feedforward_difference_bottom = (
68 self.motor_feedforward * (1 / self.J_bottom - 1 / self.J_top))
69 self.B_continuous = numpy.matrix(
70 [[0, 0],
71 [0, 0],
72 [self.motor_feedforward_bottom, 0],
73 [-self.motor_feedforward_bottom, self.motor_feedforward_difference]])
74
75 print "Cont X_ss", self.motor_feedforward / -self.common_motor_constant
76
77 self.B_bottom_cont = numpy.matrix(
78 [[0],
79 [self.motor_feedforward_bottom]])
80
81 self.B_diff_cont = numpy.matrix(
82 [[0],
83 [self.motor_feedforward_difference]])
84
85 self.C = numpy.matrix([[1, 0, 0, 0],
86 [1, 1, 0, 0]])
87 self.D = numpy.matrix([[0, 0],
88 [0, 0]])
89
90 self.A, self.B = self.ContinuousToDiscrete(
91 self.A_continuous, self.B_continuous, self.dt)
92
93 self.A_bottom, self.B_bottom = controls.c2d(
94 self.A_bottom_cont, self.B_bottom_cont, self.dt)
95 self.A_diff, self.B_diff = controls.c2d(
96 self.A_diff_cont, self.B_diff_cont, self.dt)
97
Austin Schuhadf2cde2015-11-08 20:35:16 -080098 self.K_bottom = controls.dplace(self.A_bottom, self.B_bottom,
99 [0.87 + 0.05j, 0.87 - 0.05j])
100 self.K_diff = controls.dplace(self.A_diff, self.B_diff,
101 [0.85 + 0.05j, 0.85 - 0.05j])
Brian Silverman17f503e2015-08-02 18:17:18 -0700102
103 print "K_diff", self.K_diff
104 print "K_bottom", self.K_bottom
105
106 print "A"
107 print self.A
108 print "B"
109 print self.B
110
111
112 self.Q = numpy.matrix([[(1.0 / (0.10 ** 2.0)), 0.0, 0.0, 0.0],
113 [0.0, (1.0 / (0.06 ** 2.0)), 0.0, 0.0],
114 [0.0, 0.0, 0.10, 0.0],
115 [0.0, 0.0, 0.0, 0.1]])
116
117 self.R = numpy.matrix([[(1.0 / (40.0 ** 2.0)), 0.0],
118 [0.0, (1.0 / (5.0 ** 2.0))]])
119 #self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
120
121 self.K = numpy.matrix([[self.K_bottom[0, 0], 0.0, self.K_bottom[0, 1], 0.0],
122 [0.0, self.K_diff[0, 0], 0.0, self.K_diff[0, 1]]])
123
124 # Compute the feed forwards aceleration term.
125 self.K[1, 0] = -self.B[1, 0] * self.K[0, 0] / self.B[1, 1]
126
127 lstsq_A = numpy.identity(2)
128 lstsq_A[0, :] = self.B[1, :]
129 lstsq_A[1, :] = self.B[3, :]
130 print "System of Equations coefficients:"
131 print lstsq_A
132 print "det", numpy.linalg.det(lstsq_A)
133
134 out_x = numpy.linalg.lstsq(
135 lstsq_A,
136 numpy.matrix([[self.A[1, 2]], [self.A[3, 2]]]))[0]
137 self.K[1, 2] = -lstsq_A[0, 0] * (self.K[0, 2] - out_x[0]) / lstsq_A[0, 1] + out_x[1]
138
139 print "K unaugmented"
140 print self.K
141 print "B * K unaugmented"
142 print self.B * self.K
143 F = self.A - self.B * self.K
144 print "A - B * K unaugmented"
145 print F
146 print "eigenvalues"
147 print numpy.linalg.eig(F)[0]
148
Austin Schuhadf2cde2015-11-08 20:35:16 -0800149 self.rpl = .09
150 self.ipl = 0.030
Brian Silverman17f503e2015-08-02 18:17:18 -0700151 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
152 self.rpl + 1j * self.ipl,
153 self.rpl - 1j * self.ipl,
154 self.rpl - 1j * self.ipl])
155
156 # The box formed by U_min and U_max must encompass all possible values,
157 # or else Austin's code gets angry.
158 self.U_max = numpy.matrix([[12.0], [12.0]])
159 self.U_min = numpy.matrix([[-12.0], [-12.0]])
160
161 # For the tests that check the limits, these are (upper, lower) for both
162 # claws.
163 self.hard_pos_limits = None
164 self.pos_limits = None
165
166 # Compute the steady state velocities for a given applied voltage.
167 # The top and bottom of the claw should spin at the same rate if the
168 # physics is right.
169 X_ss = numpy.matrix([[0], [0], [0.0], [0]])
170
171 U = numpy.matrix([[1.0],[1.0]])
172 A = self.A
173 B = self.B
174 #X_ss[2, 0] = X_ss[2, 0] * A[2, 2] + B[2, 0] * U[0, 0]
175 X_ss[2, 0] = 1 / (1 - A[2, 2]) * B[2, 0] * U[0, 0]
176 #X_ss[3, 0] = X_ss[3, 0] * A[3, 3] + X_ss[2, 0] * A[3, 2] + B[3, 0] * U[0, 0] + B[3, 1] * U[1, 0]
177 #X_ss[3, 0] * (1 - A[3, 3]) = X_ss[2, 0] * A[3, 2] + B[3, 0] * U[0, 0] + B[3, 1] * U[1, 0]
178 X_ss[3, 0] = 1 / (1 - A[3, 3]) * (X_ss[2, 0] * A[3, 2] + B[3, 1] * U[1, 0] + B[3, 0] * U[0, 0])
179 #X_ss[3, 0] = 1 / (1 - A[3, 3]) / (1 - A[2, 2]) * B[2, 0] * U[0, 0] * A[3, 2] + B[3, 0] * U[0, 0] + B[3, 1] * U[1, 0]
180 X_ss[0, 0] = A[0, 2] * X_ss[2, 0] + B[0, 0] * U[0, 0]
181 X_ss[1, 0] = A[1, 2] * X_ss[2, 0] + A[1, 3] * X_ss[3, 0] + B[1, 0] * U[0, 0] + B[1, 1] * U[1, 0]
182
183 print "X_ss", X_ss
184
185 self.InitializeState()
186
187
188class ClawDeltaU(Claw):
189 def __init__(self, name="Claw"):
190 super(ClawDeltaU, self).__init__(name)
191 A_unaugmented = self.A
192 B_unaugmented = self.B
193 C_unaugmented = self.C
194
195 self.A = numpy.matrix([[0.0, 0.0, 0.0, 0.0, 0.0],
196 [0.0, 0.0, 0.0, 0.0, 0.0],
197 [0.0, 0.0, 0.0, 0.0, 0.0],
198 [0.0, 0.0, 0.0, 0.0, 0.0],
199 [0.0, 0.0, 0.0, 0.0, 1.0]])
200 self.A[0:4, 0:4] = A_unaugmented
201 self.A[0:4, 4] = B_unaugmented[0:4, 0]
202
203 self.B = numpy.matrix([[0.0, 0.0],
204 [0.0, 0.0],
205 [0.0, 0.0],
206 [0.0, 0.0],
207 [1.0, 0.0]])
208 self.B[0:4, 1] = B_unaugmented[0:4, 1]
209
210 self.C = numpy.concatenate((C_unaugmented, numpy.matrix([[0.0], [0.0]])),
211 axis=1)
212 self.D = numpy.matrix([[0.0, 0.0],
213 [0.0, 0.0]])
214
215 #self.PlaceControllerPoles([0.55, 0.35, 0.55, 0.35, 0.80])
216 self.Q = numpy.matrix([[(1.0 / (0.04 ** 2.0)), 0.0, 0.0, 0.0, 0.0],
217 [0.0, (1.0 / (0.01 ** 2)), 0.0, 0.0, 0.0],
218 [0.0, 0.0, 0.01, 0.0, 0.0],
219 [0.0, 0.0, 0.0, 0.08, 0.0],
220 [0.0, 0.0, 0.0, 0.0, (1.0 / (10.0 ** 2))]])
221
222 self.R = numpy.matrix([[0.000001, 0.0],
223 [0.0, 1.0 / (10.0 ** 2.0)]])
224 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
225
226 self.K = numpy.matrix([[50.0, 0.0, 10.0, 0.0, 1.0],
227 [50.0, 0.0, 10.0, 0.0, 1.0]])
228 #self.K = numpy.matrix([[50.0, -100.0, 0, -10, 0],
229 # [50.0, 100.0, 0, 10, 0]])
230
Brian Silverman4e55e582015-11-10 14:16:37 -0500231 controlability = controls.ctrb(self.A, self.B)
Brian Silverman17f503e2015-08-02 18:17:18 -0700232 print "Rank of augmented controlability matrix.", numpy.linalg.matrix_rank(controlability)
233
234 print "K"
235 print self.K
236 print "Placed controller poles are"
237 print numpy.linalg.eig(self.A - self.B * self.K)[0]
238 print [numpy.abs(x) for x in numpy.linalg.eig(self.A - self.B * self.K)[0]]
239
240 self.rpl = .05
241 self.ipl = 0.008
242 self.PlaceObserverPoles([self.rpl + 1j * self.ipl, 0.10, 0.09,
243 self.rpl - 1j * self.ipl, 0.90])
244 #print "A is"
245 #print self.A
246 #print "L is"
247 #print self.L
248 #print "C is"
249 #print self.C
250 #print "A - LC is"
251 #print self.A - self.L * self.C
252
253 #print "Placed observer poles are"
254 #print numpy.linalg.eig(self.A - self.L * self.C)[0]
255
256 self.U_max = numpy.matrix([[12.0], [12.0]])
257 self.U_min = numpy.matrix([[-12.0], [-12.0]])
258
259 self.InitializeState()
260
261def ScaleU(claw, U, K, error):
262 """Clips U as necessary.
263
264 Args:
265 claw: claw object containing moments of inertia and U limits.
266 U: Input matrix to clip as necessary.
267 """
268
269 bottom_u = U[0, 0]
270 top_u = U[1, 0]
271 position_error = error[0:2, 0]
272 velocity_error = error[2:, 0]
273
274 U_poly = polytope.HPolytope(
275 numpy.matrix([[1, 0],
276 [-1, 0],
277 [0, 1],
278 [0, -1]]),
279 numpy.matrix([[12],
280 [12],
281 [12],
282 [12]]))
283
284 if (bottom_u > claw.U_max[0, 0] or bottom_u < claw.U_min[0, 0] or
285 top_u > claw.U_max[0, 0] or top_u < claw.U_min[0, 0]):
286
287 position_K = K[:, 0:2]
288 velocity_K = K[:, 2:]
289
290 # H * U <= k
291 # U = UPos + UVel
292 # H * (UPos + UVel) <= k
293 # H * UPos <= k - H * UVel
294 #
295 # Now, we can do a coordinate transformation and say the following.
296 #
297 # UPos = position_K * position_error
298 # (H * position_K) * position_error <= k - H * UVel
299 #
300 # Add in the constraint that 0 <= t <= 1
301 # Now, there are 2 ways this can go. Either we have a region, or we don't
302 # have a region. If we have a region, then pick the largest t and go for it.
303 # If we don't have a region, we need to pick a good comprimise.
304
305 pos_poly = polytope.HPolytope(
306 U_poly.H * position_K,
307 U_poly.k - U_poly.H * velocity_K * velocity_error)
308
309 # The actual angle for the line we call 45.
310 angle_45 = numpy.matrix([[numpy.sqrt(3), 1]])
311 if claw.pos_limits and claw.hard_pos_limits and claw.X[0, 0] + claw.X[1, 0] > claw.pos_limits[1]:
312 angle_45 = numpy.matrix([[1, 1]])
313
314 P = position_error
315 L45 = numpy.multiply(numpy.matrix([[numpy.sign(P[1, 0]), -numpy.sign(P[0, 0])]]), angle_45)
316 if L45[0, 1] == 0:
317 L45[0, 1] = 1
318 if L45[0, 0] == 0:
319 L45[0, 0] = 1
320 w45 = numpy.matrix([[0]])
321
322 if numpy.abs(P[0, 0]) > numpy.abs(P[1, 0]):
323 LH = numpy.matrix([[0, 1]])
324 else:
325 LH = numpy.matrix([[1, 0]])
326 wh = LH * P
327 standard = numpy.concatenate((L45, LH))
328 W = numpy.concatenate((w45, wh))
329 intersection = numpy.linalg.inv(standard) * W
330 adjusted_pos_error_h, is_inside_h = polydrivetrain.DoCoerceGoal(pos_poly,
331 LH, wh, position_error)
332 adjusted_pos_error_45, is_inside_45 = polydrivetrain.DoCoerceGoal(pos_poly,
333 L45, w45, intersection)
334 if pos_poly.IsInside(intersection):
335 adjusted_pos_error = adjusted_pos_error_h
336 else:
337 if is_inside_h:
338 if numpy.linalg.norm(adjusted_pos_error_h) > numpy.linalg.norm(adjusted_pos_error_45):
339 adjusted_pos_error = adjusted_pos_error_h
340 else:
341 adjusted_pos_error = adjusted_pos_error_45
342 else:
343 adjusted_pos_error = adjusted_pos_error_45
344 #print adjusted_pos_error
345
346 #print "Actual power is ", velocity_K * velocity_error + position_K * adjusted_pos_error
347 return velocity_K * velocity_error + position_K * adjusted_pos_error
348
349 #U = Kpos * poserror + Kvel * velerror
350
351 #scalar = claw.U_max[0, 0] / max(numpy.abs(top_u), numpy.abs(bottom_u))
352
353 #top_u *= scalar
354 #bottom_u *= scalar
355
356 return numpy.matrix([[bottom_u], [top_u]])
357
358def run_test(claw, initial_X, goal, max_separation_error=0.01, show_graph=False, iterations=200):
359 """Runs the claw plant on a given claw (claw) with an initial condition (initial_X) and goal (goal).
360
361 The tests themselves are not terribly sophisticated; I just test for
362 whether the goal has been reached and whether the separation goes
363 outside of the initial and goal values by more than max_separation_error.
364 Prints out something for a failure of either condition and returns
365 False if tests fail.
366 Args:
367 claw: claw object to use.
368 initial_X: starting state.
369 goal: goal state.
370 show_graph: Whether or not to display a graph showing the changing
371 states and voltages.
372 iterations: Number of timesteps to run the model for."""
373
374 claw.X = initial_X
375
376 # Various lists for graphing things.
377 t = []
378 x_bottom = []
379 x_top = []
380 u_bottom = []
381 u_top = []
382 x_separation = []
383
384 tests_passed = True
385
386 # Bounds which separation should not exceed.
387 lower_bound = (initial_X[1, 0] if initial_X[1, 0] < goal[1, 0]
388 else goal[1, 0]) - max_separation_error
389 upper_bound = (initial_X[1, 0] if initial_X[1, 0] > goal[1, 0]
390 else goal[1, 0]) + max_separation_error
391
392 for i in xrange(iterations):
393 U = claw.K * (goal - claw.X)
394 U = ScaleU(claw, U, claw.K, goal - claw.X)
395 claw.Update(U)
396
397 if claw.X[1, 0] > upper_bound or claw.X[1, 0] < lower_bound:
398 tests_passed = False
399 print "Claw separation was", claw.X[1, 0]
400 print "Should have been between", lower_bound, "and", upper_bound
401
402 if claw.hard_pos_limits and \
403 (claw.X[0, 0] > claw.hard_pos_limits[1] or
404 claw.X[0, 0] < claw.hard_pos_limits[0] or
405 claw.X[0, 0] + claw.X[1, 0] > claw.hard_pos_limits[1] or
406 claw.X[0, 0] + claw.X[1, 0] < claw.hard_pos_limits[0]):
407 tests_passed = False
408 print "Claws at %f and %f" % (claw.X[0, 0], claw.X[0, 0] + claw.X[1, 0])
409 print "Both should be in %s, definitely %s" % \
410 (claw.pos_limits, claw.hard_pos_limits)
411
412 t.append(i * claw.dt)
413 x_bottom.append(claw.X[0, 0] * 10.0)
414 x_top.append((claw.X[1, 0] + claw.X[0, 0]) * 10.0)
415 u_bottom.append(U[0, 0])
416 u_top.append(U[1, 0])
417 x_separation.append(claw.X[1, 0] * 10.0)
418
419 if show_graph:
420 pylab.plot(t, x_bottom, label='x bottom * 10')
421 pylab.plot(t, x_top, label='x top * 10')
422 pylab.plot(t, u_bottom, label='u bottom')
423 pylab.plot(t, u_top, label='u top')
424 pylab.plot(t, x_separation, label='separation * 10')
425 pylab.legend()
426 pylab.show()
427
428 # Test to make sure that we are near the goal.
429 if numpy.max(abs(claw.X - goal)) > 1e-4:
430 tests_passed = False
431 print "X was", claw.X, "Expected", goal
432
433 return tests_passed
434
435def main(argv):
436 claw = Claw()
437
438 # Test moving the claw with constant separation.
439 initial_X = numpy.matrix([[-1.0], [0.0], [0.0], [0.0]])
440 R = numpy.matrix([[1.0], [0.0], [0.0], [0.0]])
441 run_test(claw, initial_X, R)
442
443 # Test just changing separation.
444 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
445 R = numpy.matrix([[0.0], [1.0], [0.0], [0.0]])
446 run_test(claw, initial_X, R)
447
448 # Test changing both separation and position at once.
449 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
450 R = numpy.matrix([[1.0], [1.0], [0.0], [0.0]])
451 run_test(claw, initial_X, R)
452
453 # Test a small separation error and a large position one.
454 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
455 R = numpy.matrix([[2.0], [0.05], [0.0], [0.0]])
456 run_test(claw, initial_X, R)
457
458 # Test a small separation error and a large position one.
459 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
460 R = numpy.matrix([[-0.5], [1.0], [0.0], [0.0]])
461 run_test(claw, initial_X, R)
462
463 # Test opening with the top claw at the limit.
464 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
465 R = numpy.matrix([[-1.5], [1.5], [0.0], [0.0]])
466 claw.hard_pos_limits = (-1.6, 0.1)
467 claw.pos_limits = (-1.5, 0.0)
468 run_test(claw, initial_X, R)
469 claw.pos_limits = None
470
471 # Test opening with the bottom claw at the limit.
472 initial_X = numpy.matrix([[0.0], [0.0], [0.0], [0.0]])
473 R = numpy.matrix([[0], [1.5], [0.0], [0.0]])
474 claw.hard_pos_limits = (-0.1, 1.6)
475 claw.pos_limits = (0.0, 1.6)
476 run_test(claw, initial_X, R)
477 claw.pos_limits = None
478
479 # Write the generated constants out to a file.
480 if len(argv) != 3:
481 print "Expected .h file name and .cc file name for the claw."
482 else:
Austin Schuhedc317c2015-11-08 14:07:42 -0800483 namespaces = ['y2014', 'control_loops', 'claw']
Brian Silverman17f503e2015-08-02 18:17:18 -0700484 claw = Claw("Claw")
Austin Schuhedc317c2015-11-08 14:07:42 -0800485 loop_writer = control_loop.ControlLoopWriter("Claw", [claw],
486 namespaces=namespaces)
Brian Silverman17f503e2015-08-02 18:17:18 -0700487 loop_writer.AddConstant(control_loop.Constant("kClawMomentOfInertiaRatio",
488 "%f", claw.J_top / claw.J_bottom))
Austin Schuh0e997732015-11-08 15:14:53 -0800489 loop_writer.AddConstant(control_loop.Constant("kDt", "%f",
490 claw.dt))
Brian Silverman17f503e2015-08-02 18:17:18 -0700491 if argv[1][-3:] == '.cc':
492 loop_writer.Write(argv[2], argv[1])
493 else:
494 loop_writer.Write(argv[1], argv[2])
495
496if __name__ == '__main__':
497 sys.exit(main(sys.argv))