blob: 88caa73fe7eaa5e2c80f2af591d07c39df574324 [file] [log] [blame]
Comran Morshed0d6cf9b2015-06-17 19:29:57 +00001#!/usr/bin/python
2
3import numpy
4import sys
5import polytope
6import drivetrain
7import control_loop
8import controls
Philipp Schrader9ffe2982016-12-07 20:51:08 -08009from frc971.control_loops.python.cim import CIM
Comran Morshed0d6cf9b2015-06-17 19:29:57 +000010from matplotlib import pylab
11
12__author__ = 'Austin Schuh (austin.linux@gmail.com)'
13
14
15def CoerceGoal(region, K, w, R):
16 """Intersects a line with a region, and finds the closest point to R.
17
18 Finds a point that is closest to R inside the region, and on the line
19 defined by K X = w. If it is not possible to find a point on the line,
20 finds a point that is inside the region and closest to the line. This
21 function assumes that
22
23 Args:
24 region: HPolytope, the valid goal region.
25 K: numpy.matrix (2 x 1), the matrix for the equation [K1, K2] [x1; x2] = w
26 w: float, the offset in the equation above.
27 R: numpy.matrix (2 x 1), the point to be closest to.
28
29 Returns:
30 numpy.matrix (2 x 1), the point.
31 """
32 return DoCoerceGoal(region, K, w, R)[0]
33
34def DoCoerceGoal(region, K, w, R):
35 if region.IsInside(R):
36 return (R, True)
37
38 perpendicular_vector = K.T / numpy.linalg.norm(K)
39 parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
40 [-perpendicular_vector[0, 0]]])
41
42 # We want to impose the constraint K * X = w on the polytope H * X <= k.
43 # We do this by breaking X up into parallel and perpendicular components to
44 # the half plane. This gives us the following equation.
45 #
46 # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
47 #
48 # Then, substitute this into the polytope.
49 #
50 # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
51 #
52 # Substitute K * X = w
53 #
54 # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
55 #
56 # Move all the knowns to the right side.
57 #
58 # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
59 #
60 # Let t = parallel.T \dot X, the component parallel to the surface.
61 #
62 # H * parallel * t <= k - H * perpendicular * w
63 #
64 # This is a polytope which we can solve, and use to figure out the range of X
65 # that we care about!
66
67 t_poly = polytope.HPolytope(
68 region.H * parallel_vector,
69 region.k - region.H * perpendicular_vector * w)
70
71 vertices = t_poly.Vertices()
72
73 if vertices.shape[0]:
74 # The region exists!
75 # Find the closest vertex
76 min_distance = numpy.infty
77 closest_point = None
78 for vertex in vertices:
79 point = parallel_vector * vertex + perpendicular_vector * w
80 length = numpy.linalg.norm(R - point)
81 if length < min_distance:
82 min_distance = length
83 closest_point = point
84
85 return (closest_point, True)
86 else:
87 # Find the vertex of the space that is closest to the line.
88 region_vertices = region.Vertices()
89 min_distance = numpy.infty
90 closest_point = None
91 for vertex in region_vertices:
92 point = vertex.T
93 length = numpy.abs((perpendicular_vector.T * point)[0, 0])
94 if length < min_distance:
95 min_distance = length
96 closest_point = point
97
98 return (closest_point, False)
99
100
101class VelocityDrivetrainModel(control_loop.ControlLoop):
102 def __init__(self, left_low=True, right_low=True, name="VelocityDrivetrainModel"):
103 super(VelocityDrivetrainModel, self).__init__(name)
104 self._drivetrain = drivetrain.Drivetrain(left_low=left_low,
105 right_low=right_low)
106 self.dt = 0.01
107 self.A_continuous = numpy.matrix(
108 [[self._drivetrain.A_continuous[1, 1], self._drivetrain.A_continuous[1, 3]],
109 [self._drivetrain.A_continuous[3, 1], self._drivetrain.A_continuous[3, 3]]])
110
111 self.B_continuous = numpy.matrix(
112 [[self._drivetrain.B_continuous[1, 0], self._drivetrain.B_continuous[1, 1]],
113 [self._drivetrain.B_continuous[3, 0], self._drivetrain.B_continuous[3, 1]]])
Brian Silverman4e55e582015-11-10 14:16:37 -0500114 self.C = numpy.matrix(numpy.eye(2))
115 self.D = numpy.matrix(numpy.zeros((2, 2)))
Comran Morshed0d6cf9b2015-06-17 19:29:57 +0000116
117 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
118 self.B_continuous, self.dt)
119
120 # FF * X = U (steady state)
121 self.FF = self.B.I * (numpy.eye(2) - self.A)
122
123 self.PlaceControllerPoles([0.6, 0.6])
124 self.PlaceObserverPoles([0.02, 0.02])
125
126 self.G_high = self._drivetrain.G_high
127 self.G_low = self._drivetrain.G_low
128 self.R = self._drivetrain.R
129 self.r = self._drivetrain.r
130 self.Kv = self._drivetrain.Kv
131 self.Kt = self._drivetrain.Kt
132
133 self.U_max = self._drivetrain.U_max
134 self.U_min = self._drivetrain.U_min
135
136
137class VelocityDrivetrain(object):
138 HIGH = 'high'
139 LOW = 'low'
140 SHIFTING_UP = 'up'
141 SHIFTING_DOWN = 'down'
142
143 def __init__(self):
144 self.drivetrain_low_low = VelocityDrivetrainModel(
145 left_low=True, right_low=True, name='VelocityDrivetrainLowLow')
146 self.drivetrain_low_high = VelocityDrivetrainModel(left_low=True, right_low=False, name='VelocityDrivetrainLowHigh')
147 self.drivetrain_high_low = VelocityDrivetrainModel(left_low=False, right_low=True, name = 'VelocityDrivetrainHighLow')
148 self.drivetrain_high_high = VelocityDrivetrainModel(left_low=False, right_low=False, name = 'VelocityDrivetrainHighHigh')
149
150 # X is [lvel, rvel]
151 self.X = numpy.matrix(
152 [[0.0],
153 [0.0]])
154
155 self.U_poly = polytope.HPolytope(
156 numpy.matrix([[1, 0],
157 [-1, 0],
158 [0, 1],
159 [0, -1]]),
160 numpy.matrix([[12],
161 [12],
162 [12],
163 [12]]))
164
165 self.U_max = numpy.matrix(
166 [[12.0],
167 [12.0]])
168 self.U_min = numpy.matrix(
169 [[-12.0000000000],
170 [-12.0000000000]])
171
172 self.dt = 0.01
173
174 self.R = numpy.matrix(
175 [[0.0],
176 [0.0]])
177
178 # ttrust is the comprimise between having full throttle negative inertia,
179 # and having no throttle negative inertia. A value of 0 is full throttle
180 # inertia. A value of 1 is no throttle negative inertia.
181 self.ttrust = 1.1
182
183 self.left_gear = VelocityDrivetrain.LOW
184 self.right_gear = VelocityDrivetrain.LOW
185 self.left_shifter_position = 0.0
186 self.right_shifter_position = 0.0
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800187 self.left_cim = CIM()
188 self.right_cim = CIM()
Comran Morshed0d6cf9b2015-06-17 19:29:57 +0000189
190 def IsInGear(self, gear):
191 return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
192
193 def MotorRPM(self, shifter_position, velocity):
194 if shifter_position > 0.5:
195 return (velocity / self.CurrentDrivetrain().G_high /
196 self.CurrentDrivetrain().r)
197 else:
198 return (velocity / self.CurrentDrivetrain().G_low /
199 self.CurrentDrivetrain().r)
200
201 def CurrentDrivetrain(self):
202 if self.left_shifter_position > 0.5:
203 if self.right_shifter_position > 0.5:
204 return self.drivetrain_high_high
205 else:
206 return self.drivetrain_high_low
207 else:
208 if self.right_shifter_position > 0.5:
209 return self.drivetrain_low_high
210 else:
211 return self.drivetrain_low_low
212
213 def SimShifter(self, gear, shifter_position):
214 if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
215 shifter_position = min(shifter_position + 0.5, 1.0)
216 else:
217 shifter_position = max(shifter_position - 0.5, 0.0)
218
219 if shifter_position == 1.0:
220 gear = VelocityDrivetrain.HIGH
221 elif shifter_position == 0.0:
222 gear = VelocityDrivetrain.LOW
223
224 return gear, shifter_position
225
226 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
227 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
228 self.CurrentDrivetrain().r)
229 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
230 self.CurrentDrivetrain().r)
231 #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
232 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
233 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
234 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
235 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
236 high_power = high_torque * high_omega
237 low_power = low_torque * low_omega
238 #if should_print:
239 # print gear_name, "High omega", high_omega, "Low omega", low_omega
240 # print gear_name, "High torque", high_torque, "Low torque", low_torque
241 # print gear_name, "High power", high_power, "Low power", low_power
242
243 # Shift algorithm improvements.
244 # TODO(aschuh):
245 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
246 # because you will end up slower than without shifting. Figure out how
247 # to include that info.
248 # If the driver is still in high gear, but isn't asking for the extra power
249 # from low gear, don't shift until he asks for it.
250 goal_gear_is_high = high_power > low_power
251 #goal_gear_is_high = True
252
253 if not self.IsInGear(current_gear):
254 print gear_name, 'Not in gear.'
255 return current_gear
256 else:
257 is_high = current_gear is VelocityDrivetrain.HIGH
258 if is_high != goal_gear_is_high:
259 if goal_gear_is_high:
260 print gear_name, 'Shifting up.'
261 return VelocityDrivetrain.SHIFTING_UP
262 else:
263 print gear_name, 'Shifting down.'
264 return VelocityDrivetrain.SHIFTING_DOWN
265 else:
266 return current_gear
267
268 def FilterVelocity(self, throttle):
269 # Invert the plant to figure out how the velocity filter would have to work
270 # out in order to filter out the forwards negative inertia.
271 # This math assumes that the left and right power and velocity are equal.
272
273 # The throttle filter should filter such that the motor in the highest gear
274 # should be controlling the time constant.
275 # Do this by finding the index of FF that has the lowest value, and computing
276 # the sums using that index.
277 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
278 min_FF_sum_index = numpy.argmin(FF_sum)
279 min_FF_sum = FF_sum[min_FF_sum_index, 0]
280 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
281 # Compute the FF sum for high gear.
282 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
283
284 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
285 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
286 # - self.K[0, :].sum() * x_avg
287
288 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
289 # (self.K[0, :].sum() + self.FF[0, :].sum())
290
291 # U = (K + FF) * R - K * X
292 # (K + FF) ^-1 * (U + K * X) = R
293
294 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
295 # have the same velocity goal as high gear, and so that the robot will hold
296 # the same speed for the same throttle for all gears.
297 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
298 return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
299 / (self.ttrust * min_K_sum + min_FF_sum))
300
301 def Update(self, throttle, steering):
302 # Shift into the gear which sends the most power to the floor.
303 # This is the same as sending the most torque down to the floor at the
304 # wheel.
305
306 self.left_gear = self.right_gear = True
307 if False:
308 self.left_gear = self.ComputeGear(self.X[0, 0], should_print=True,
309 current_gear=self.left_gear,
310 gear_name="left")
311 self.right_gear = self.ComputeGear(self.X[1, 0], should_print=True,
312 current_gear=self.right_gear,
313 gear_name="right")
314 if self.IsInGear(self.left_gear):
315 self.left_cim.X[0, 0] = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
316
317 if self.IsInGear(self.right_gear):
318 self.right_cim.X[0, 0] = self.MotorRPM(self.right_shifter_position, self.X[0, 0])
319
320 steering *= 2.3
321 if True or self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
322 # Filter the throttle to provide a nicer response.
323 fvel = self.FilterVelocity(throttle)
324
325 # Constant radius means that angualar_velocity / linear_velocity = constant.
326 # Compute the left and right velocities.
327 steering_velocity = numpy.abs(fvel) * steering
328 left_velocity = fvel - steering_velocity
329 right_velocity = fvel + steering_velocity
330
331 # Write this constraint in the form of K * R = w
332 # angular velocity / linear velocity = constant
333 # (left - right) / (left + right) = constant
334 # left - right = constant * left + constant * right
335
336 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
337 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
338 # constant
339 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
340 # (-steering * sign(fvel)) = constant
341 # (-steering * sign(fvel)) * (left + right) = left - right
342 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
343
344 equality_k = numpy.matrix(
345 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
346 equality_w = 0.0
347
348 self.R[0, 0] = left_velocity
349 self.R[1, 0] = right_velocity
350
351 # Construct a constraint on R by manipulating the constraint on U
352 # Start out with H * U <= k
353 # U = FF * R + K * (R - X)
354 # H * (FF * R + K * R - K * X) <= k
355 # H * (FF + K) * R <= k + H * K * X
356 R_poly = polytope.HPolytope(
357 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
358 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
359
360 # Limit R back inside the box.
361 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
362
363 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
364 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
365 else:
366 print 'Not all in gear'
367 if not self.IsInGear(self.left_gear) and not self.IsInGear(self.right_gear):
368 # TODO(austin): Use battery volts here.
369 R_left = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
370 self.U_ideal[0, 0] = numpy.clip(
371 self.left_cim.K * (R_left - self.left_cim.X) + R_left / self.left_cim.Kv,
372 self.left_cim.U_min, self.left_cim.U_max)
373 self.left_cim.Update(self.U_ideal[0, 0])
374
375 R_right = self.MotorRPM(self.right_shifter_position, self.X[1, 0])
376 self.U_ideal[1, 0] = numpy.clip(
377 self.right_cim.K * (R_right - self.right_cim.X) + R_right / self.right_cim.Kv,
378 self.right_cim.U_min, self.right_cim.U_max)
379 self.right_cim.Update(self.U_ideal[1, 0])
380 else:
381 assert False
382
383 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
384
385 # TODO(austin): Model the robot as not accelerating when you shift...
386 # This hack only works when you shift at the same time.
387 if True or self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
388 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
389
390 self.left_gear, self.left_shifter_position = self.SimShifter(
391 self.left_gear, self.left_shifter_position)
392 self.right_gear, self.right_shifter_position = self.SimShifter(
393 self.right_gear, self.right_shifter_position)
394
395 print "U is", self.U[0, 0], self.U[1, 0]
396 print "Left shifter", self.left_gear, self.left_shifter_position, "Right shifter", self.right_gear, self.right_shifter_position
397
398
399def main(argv):
400 vdrivetrain = VelocityDrivetrain()
401
402 if len(argv) != 7:
403 print "Expected .h file name and .cc file name"
404 else:
405 dog_loop_writer = control_loop.ControlLoopWriter(
406 "VelocityDrivetrain", [vdrivetrain.drivetrain_low_low,
407 vdrivetrain.drivetrain_low_high,
408 vdrivetrain.drivetrain_high_low,
Jasmine Zhoudde7a772015-09-11 23:08:52 -0700409 vdrivetrain.drivetrain_high_high],
Austin Schuh6d1ee0c2015-11-21 14:36:04 -0800410 namespaces=['y2015_bot3', 'control_loops'])
Comran Morshed0d6cf9b2015-06-17 19:29:57 +0000411
412 if argv[1][-3:] == '.cc':
413 dog_loop_writer.Write(argv[2], argv[1])
414 else:
415 dog_loop_writer.Write(argv[1], argv[2])
416
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800417 cim_writer = control_loop.ControlLoopWriter("CIM", [CIM()],
Austin Schuh6d1ee0c2015-11-21 14:36:04 -0800418 namespaces=['y2015_bot3', 'control_loops'])
Comran Morshed0d6cf9b2015-06-17 19:29:57 +0000419
420 if argv[5][-3:] == '.cc':
421 cim_writer.Write(argv[6], argv[5])
422 else:
423 cim_writer.Write(argv[5], argv[6])
424 return
425
426 vl_plot = []
427 vr_plot = []
428 ul_plot = []
429 ur_plot = []
430 radius_plot = []
431 t_plot = []
432 left_gear_plot = []
433 right_gear_plot = []
434 vdrivetrain.left_shifter_position = 0.0
435 vdrivetrain.right_shifter_position = 0.0
436 vdrivetrain.left_gear = VelocityDrivetrain.LOW
437 vdrivetrain.right_gear = VelocityDrivetrain.LOW
438
439 print "K is", vdrivetrain.CurrentDrivetrain().K
440
441 if vdrivetrain.left_gear is VelocityDrivetrain.HIGH:
442 print "Left is high"
443 else:
444 print "Left is low"
445 if vdrivetrain.right_gear is VelocityDrivetrain.HIGH:
446 print "Right is high"
447 else:
448 print "Right is low"
449
450 for t in numpy.arange(0, 1.7, vdrivetrain.dt):
451 if t < 0.5:
452 vdrivetrain.Update(throttle=0.00, steering=1.0)
453 elif t < 1.2:
454 vdrivetrain.Update(throttle=0.5, steering=1.0)
455 else:
456 vdrivetrain.Update(throttle=0.00, steering=1.0)
457 t_plot.append(t)
458 vl_plot.append(vdrivetrain.X[0, 0])
459 vr_plot.append(vdrivetrain.X[1, 0])
460 ul_plot.append(vdrivetrain.U[0, 0])
461 ur_plot.append(vdrivetrain.U[1, 0])
462 left_gear_plot.append((vdrivetrain.left_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
463 right_gear_plot.append((vdrivetrain.right_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
464
465 fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
466 turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
467 if abs(fwd_velocity) < 0.0000001:
468 radius_plot.append(turn_velocity)
469 else:
470 radius_plot.append(turn_velocity / fwd_velocity)
471
472 cim_velocity_plot = []
473 cim_voltage_plot = []
474 cim_time = []
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800475 cim = CIM()
Comran Morshed0d6cf9b2015-06-17 19:29:57 +0000476 R = numpy.matrix([[300]])
477 for t in numpy.arange(0, 0.5, cim.dt):
478 U = numpy.clip(cim.K * (R - cim.X) + R / cim.Kv, cim.U_min, cim.U_max)
479 cim.Update(U)
480 cim_velocity_plot.append(cim.X[0, 0])
481 cim_voltage_plot.append(U[0, 0] * 10)
482 cim_time.append(t)
483 pylab.plot(cim_time, cim_velocity_plot, label='cim spinup')
484 pylab.plot(cim_time, cim_voltage_plot, label='cim voltage')
485 pylab.legend()
486 pylab.show()
487
488 # TODO(austin):
489 # Shifting compensation.
490
491 # Tighten the turn.
492 # Closed loop drive.
493
494 pylab.plot(t_plot, vl_plot, label='left velocity')
495 pylab.plot(t_plot, vr_plot, label='right velocity')
496 pylab.plot(t_plot, ul_plot, label='left voltage')
497 pylab.plot(t_plot, ur_plot, label='right voltage')
498 pylab.plot(t_plot, radius_plot, label='radius')
499 pylab.plot(t_plot, left_gear_plot, label='left gear high')
500 pylab.plot(t_plot, right_gear_plot, label='right gear high')
501 pylab.legend()
502 pylab.show()
503 return 0
504
505if __name__ == '__main__':
506 sys.exit(main(sys.argv))