blob: 2ffbed6013d99c70fcc3196cc1913fcef1e628fc [file] [log] [blame]
Comran Morshede9b12922015-11-04 19:46:48 +00001#!/usr/bin/python
2
3import numpy
4import sys
5import polytope
6import drivetrain
7import control_loop
8import controls
9from matplotlib import pylab
10
11__author__ = 'Austin Schuh (austin.linux@gmail.com)'
12
13
14def CoerceGoal(region, K, w, R):
15 """Intersects a line with a region, and finds the closest point to R.
16
17 Finds a point that is closest to R inside the region, and on the line
18 defined by K X = w. If it is not possible to find a point on the line,
19 finds a point that is inside the region and closest to the line. This
20 function assumes that
21
22 Args:
23 region: HPolytope, the valid goal region.
24 K: numpy.matrix (2 x 1), the matrix for the equation [K1, K2] [x1; x2] = w
25 w: float, the offset in the equation above.
26 R: numpy.matrix (2 x 1), the point to be closest to.
27
28 Returns:
29 numpy.matrix (2 x 1), the point.
30 """
31 return DoCoerceGoal(region, K, w, R)[0]
32
33def DoCoerceGoal(region, K, w, R):
34 if region.IsInside(R):
35 return (R, True)
36
37 perpendicular_vector = K.T / numpy.linalg.norm(K)
38 parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
39 [-perpendicular_vector[0, 0]]])
40
41 # We want to impose the constraint K * X = w on the polytope H * X <= k.
42 # We do this by breaking X up into parallel and perpendicular components to
43 # the half plane. This gives us the following equation.
44 #
45 # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
46 #
47 # Then, substitute this into the polytope.
48 #
49 # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
50 #
51 # Substitute K * X = w
52 #
53 # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
54 #
55 # Move all the knowns to the right side.
56 #
57 # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
58 #
59 # Let t = parallel.T \dot X, the component parallel to the surface.
60 #
61 # H * parallel * t <= k - H * perpendicular * w
62 #
63 # This is a polytope which we can solve, and use to figure out the range of X
64 # that we care about!
65
66 t_poly = polytope.HPolytope(
67 region.H * parallel_vector,
68 region.k - region.H * perpendicular_vector * w)
69
70 vertices = t_poly.Vertices()
71
72 if vertices.shape[0]:
73 # The region exists!
74 # Find the closest vertex
75 min_distance = numpy.infty
76 closest_point = None
77 for vertex in vertices:
78 point = parallel_vector * vertex + perpendicular_vector * w
79 length = numpy.linalg.norm(R - point)
80 if length < min_distance:
81 min_distance = length
82 closest_point = point
83
84 return (closest_point, True)
85 else:
86 # Find the vertex of the space that is closest to the line.
87 region_vertices = region.Vertices()
88 min_distance = numpy.infty
89 closest_point = None
90 for vertex in region_vertices:
91 point = vertex.T
92 length = numpy.abs((perpendicular_vector.T * point)[0, 0])
93 if length < min_distance:
94 min_distance = length
95 closest_point = point
96
97 return (closest_point, False)
98
99
100class VelocityDrivetrainModel(control_loop.ControlLoop):
101 def __init__(self, left_low=True, right_low=True, name="VelocityDrivetrainModel"):
102 super(VelocityDrivetrainModel, self).__init__(name)
103 self._drivetrain = drivetrain.Drivetrain(left_low=left_low,
104 right_low=right_low)
Comran Morshed41ed7c22015-11-04 21:03:37 +0000105 self.dt = 0.005
Comran Morshede9b12922015-11-04 19:46:48 +0000106 self.A_continuous = numpy.matrix(
107 [[self._drivetrain.A_continuous[1, 1], self._drivetrain.A_continuous[1, 3]],
108 [self._drivetrain.A_continuous[3, 1], self._drivetrain.A_continuous[3, 3]]])
109
110 self.B_continuous = numpy.matrix(
111 [[self._drivetrain.B_continuous[1, 0], self._drivetrain.B_continuous[1, 1]],
112 [self._drivetrain.B_continuous[3, 0], self._drivetrain.B_continuous[3, 1]]])
113 self.C = numpy.matrix(numpy.eye(2));
114 self.D = numpy.matrix(numpy.zeros((2, 2)));
115
116 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
117 self.B_continuous, self.dt)
118
119 # FF * X = U (steady state)
120 self.FF = self.B.I * (numpy.eye(2) - self.A)
121
122 self.PlaceControllerPoles([0.6, 0.6])
123 self.PlaceObserverPoles([0.02, 0.02])
124
125 self.G_high = self._drivetrain.G_high
126 self.G_low = self._drivetrain.G_low
127 self.R = self._drivetrain.R
128 self.r = self._drivetrain.r
129 self.Kv = self._drivetrain.Kv
130 self.Kt = self._drivetrain.Kt
131
132 self.U_max = self._drivetrain.U_max
133 self.U_min = self._drivetrain.U_min
134
135
136class VelocityDrivetrain(object):
137 HIGH = 'high'
138 LOW = 'low'
139 SHIFTING_UP = 'up'
140 SHIFTING_DOWN = 'down'
141
142 def __init__(self):
143 self.drivetrain_low_low = VelocityDrivetrainModel(
144 left_low=True, right_low=True, name='VelocityDrivetrainLowLow')
145 self.drivetrain_low_high = VelocityDrivetrainModel(left_low=True, right_low=False, name='VelocityDrivetrainLowHigh')
146 self.drivetrain_high_low = VelocityDrivetrainModel(left_low=False, right_low=True, name = 'VelocityDrivetrainHighLow')
147 self.drivetrain_high_high = VelocityDrivetrainModel(left_low=False, right_low=False, name = 'VelocityDrivetrainHighHigh')
148
149 # X is [lvel, rvel]
150 self.X = numpy.matrix(
151 [[0.0],
152 [0.0]])
153
154 self.U_poly = polytope.HPolytope(
155 numpy.matrix([[1, 0],
156 [-1, 0],
157 [0, 1],
158 [0, -1]]),
159 numpy.matrix([[12],
160 [12],
161 [12],
162 [12]]))
163
164 self.U_max = numpy.matrix(
165 [[12.0],
166 [12.0]])
167 self.U_min = numpy.matrix(
168 [[-12.0000000000],
169 [-12.0000000000]])
170
Comran Morshed41ed7c22015-11-04 21:03:37 +0000171 self.dt = 0.005
Comran Morshede9b12922015-11-04 19:46:48 +0000172
173 self.R = numpy.matrix(
174 [[0.0],
175 [0.0]])
176
177 # ttrust is the comprimise between having full throttle negative inertia,
178 # and having no throttle negative inertia. A value of 0 is full throttle
179 # inertia. A value of 1 is no throttle negative inertia.
Comran Morshed41ed7c22015-11-04 21:03:37 +0000180 self.ttrust = 1.1
Comran Morshede9b12922015-11-04 19:46:48 +0000181
182 self.left_gear = VelocityDrivetrain.LOW
183 self.right_gear = VelocityDrivetrain.LOW
184 self.left_shifter_position = 0.0
185 self.right_shifter_position = 0.0
186 self.left_cim = drivetrain.CIM()
187 self.right_cim = drivetrain.CIM()
188
189 def IsInGear(self, gear):
190 return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
191
192 def MotorRPM(self, shifter_position, velocity):
193 if shifter_position > 0.5:
194 return (velocity / self.CurrentDrivetrain().G_high /
195 self.CurrentDrivetrain().r)
196 else:
197 return (velocity / self.CurrentDrivetrain().G_low /
198 self.CurrentDrivetrain().r)
199
200 def CurrentDrivetrain(self):
201 if self.left_shifter_position > 0.5:
202 if self.right_shifter_position > 0.5:
203 return self.drivetrain_high_high
204 else:
205 return self.drivetrain_high_low
206 else:
207 if self.right_shifter_position > 0.5:
208 return self.drivetrain_low_high
209 else:
210 return self.drivetrain_low_low
211
212 def SimShifter(self, gear, shifter_position):
213 if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
214 shifter_position = min(shifter_position + 0.5, 1.0)
215 else:
216 shifter_position = max(shifter_position - 0.5, 0.0)
217
218 if shifter_position == 1.0:
219 gear = VelocityDrivetrain.HIGH
220 elif shifter_position == 0.0:
221 gear = VelocityDrivetrain.LOW
222
223 return gear, shifter_position
224
225 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
226 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
227 self.CurrentDrivetrain().r)
228 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
229 self.CurrentDrivetrain().r)
230 #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
231 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
232 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
233 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
234 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
235 high_power = high_torque * high_omega
236 low_power = low_torque * low_omega
237 #if should_print:
238 # print gear_name, "High omega", high_omega, "Low omega", low_omega
239 # print gear_name, "High torque", high_torque, "Low torque", low_torque
240 # print gear_name, "High power", high_power, "Low power", low_power
241
242 # Shift algorithm improvements.
243 # TODO(aschuh):
244 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
245 # because you will end up slower than without shifting. Figure out how
246 # to include that info.
247 # If the driver is still in high gear, but isn't asking for the extra power
248 # from low gear, don't shift until he asks for it.
249 goal_gear_is_high = high_power > low_power
250 #goal_gear_is_high = True
251
252 if not self.IsInGear(current_gear):
253 print gear_name, 'Not in gear.'
254 return current_gear
255 else:
256 is_high = current_gear is VelocityDrivetrain.HIGH
257 if is_high != goal_gear_is_high:
258 if goal_gear_is_high:
259 print gear_name, 'Shifting up.'
260 return VelocityDrivetrain.SHIFTING_UP
261 else:
262 print gear_name, 'Shifting down.'
263 return VelocityDrivetrain.SHIFTING_DOWN
264 else:
265 return current_gear
266
267 def FilterVelocity(self, throttle):
268 # Invert the plant to figure out how the velocity filter would have to work
269 # out in order to filter out the forwards negative inertia.
270 # This math assumes that the left and right power and velocity are equal.
271
272 # The throttle filter should filter such that the motor in the highest gear
273 # should be controlling the time constant.
274 # Do this by finding the index of FF that has the lowest value, and computing
275 # the sums using that index.
276 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
277 min_FF_sum_index = numpy.argmin(FF_sum)
278 min_FF_sum = FF_sum[min_FF_sum_index, 0]
279 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
280 # Compute the FF sum for high gear.
281 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
282
283 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
284 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
285 # - self.K[0, :].sum() * x_avg
286
287 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
288 # (self.K[0, :].sum() + self.FF[0, :].sum())
289
290 # U = (K + FF) * R - K * X
291 # (K + FF) ^-1 * (U + K * X) = R
292
293 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
294 # have the same velocity goal as high gear, and so that the robot will hold
295 # the same speed for the same throttle for all gears.
296 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
297 return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
298 / (self.ttrust * min_K_sum + min_FF_sum))
299
300 def Update(self, throttle, steering):
301 # Shift into the gear which sends the most power to the floor.
302 # This is the same as sending the most torque down to the floor at the
303 # wheel.
304
Comran Morshed41ed7c22015-11-04 21:03:37 +0000305 self.left_gear = self.right_gear = True
306 if False:
307 self.left_gear = self.ComputeGear(self.X[0, 0], should_print=True,
308 current_gear=self.left_gear,
309 gear_name="left")
310 self.right_gear = self.ComputeGear(self.X[1, 0], should_print=True,
311 current_gear=self.right_gear,
312 gear_name="right")
313 if self.IsInGear(self.left_gear):
314 self.left_cim.X[0, 0] = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
Comran Morshede9b12922015-11-04 19:46:48 +0000315
Comran Morshed41ed7c22015-11-04 21:03:37 +0000316 if self.IsInGear(self.right_gear):
317 self.right_cim.X[0, 0] = self.MotorRPM(self.right_shifter_position, self.X[0, 0])
Comran Morshede9b12922015-11-04 19:46:48 +0000318
Comran Morshed41ed7c22015-11-04 21:03:37 +0000319 steering *= 2.3
320 if True or self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
Comran Morshede9b12922015-11-04 19:46:48 +0000321 # Filter the throttle to provide a nicer response.
322 fvel = self.FilterVelocity(throttle)
323
324 # Constant radius means that angualar_velocity / linear_velocity = constant.
325 # Compute the left and right velocities.
Comran Morshed41ed7c22015-11-04 21:03:37 +0000326 steering_velocity = numpy.abs(fvel) * steering
327 left_velocity = fvel - steering_velocity
328 right_velocity = fvel + steering_velocity
Comran Morshede9b12922015-11-04 19:46:48 +0000329
330 # Write this constraint in the form of K * R = w
331 # angular velocity / linear velocity = constant
332 # (left - right) / (left + right) = constant
333 # left - right = constant * left + constant * right
334
335 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
336 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
337 # constant
338 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
339 # (-steering * sign(fvel)) = constant
340 # (-steering * sign(fvel)) * (left + right) = left - right
341 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
342
343 equality_k = numpy.matrix(
344 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
345 equality_w = 0.0
346
347 self.R[0, 0] = left_velocity
348 self.R[1, 0] = right_velocity
349
350 # Construct a constraint on R by manipulating the constraint on U
351 # Start out with H * U <= k
352 # U = FF * R + K * (R - X)
353 # H * (FF * R + K * R - K * X) <= k
354 # H * (FF + K) * R <= k + H * K * X
355 R_poly = polytope.HPolytope(
356 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
357 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
358
359 # Limit R back inside the box.
360 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
361
362 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
363 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
364 else:
365 print 'Not all in gear'
366 if not self.IsInGear(self.left_gear) and not self.IsInGear(self.right_gear):
367 # TODO(austin): Use battery volts here.
368 R_left = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
369 self.U_ideal[0, 0] = numpy.clip(
370 self.left_cim.K * (R_left - self.left_cim.X) + R_left / self.left_cim.Kv,
371 self.left_cim.U_min, self.left_cim.U_max)
372 self.left_cim.Update(self.U_ideal[0, 0])
373
374 R_right = self.MotorRPM(self.right_shifter_position, self.X[1, 0])
375 self.U_ideal[1, 0] = numpy.clip(
376 self.right_cim.K * (R_right - self.right_cim.X) + R_right / self.right_cim.Kv,
377 self.right_cim.U_min, self.right_cim.U_max)
378 self.right_cim.Update(self.U_ideal[1, 0])
379 else:
380 assert False
381
382 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
383
384 # TODO(austin): Model the robot as not accelerating when you shift...
385 # This hack only works when you shift at the same time.
Comran Morshed41ed7c22015-11-04 21:03:37 +0000386 if True or self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
Comran Morshede9b12922015-11-04 19:46:48 +0000387 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
388
389 self.left_gear, self.left_shifter_position = self.SimShifter(
390 self.left_gear, self.left_shifter_position)
391 self.right_gear, self.right_shifter_position = self.SimShifter(
392 self.right_gear, self.right_shifter_position)
393
394 print "U is", self.U[0, 0], self.U[1, 0]
395 print "Left shifter", self.left_gear, self.left_shifter_position, "Right shifter", self.right_gear, self.right_shifter_position
396
397
398def main(argv):
399 vdrivetrain = VelocityDrivetrain()
400
Comran Morshed41ed7c22015-11-04 21:03:37 +0000401 if len(argv) != 7:
Comran Morshede9b12922015-11-04 19:46:48 +0000402 print "Expected .h file name and .cc file name"
403 else:
404 dog_loop_writer = control_loop.ControlLoopWriter(
405 "VelocityDrivetrain", [vdrivetrain.drivetrain_low_low,
406 vdrivetrain.drivetrain_low_high,
407 vdrivetrain.drivetrain_high_low,
408 vdrivetrain.drivetrain_high_high],
Comran Morshed41ed7c22015-11-04 21:03:37 +0000409 namespaces=['y2014_bot3', 'control_loops'])
Comran Morshede9b12922015-11-04 19:46:48 +0000410
411 if argv[1][-3:] == '.cc':
412 dog_loop_writer.Write(argv[2], argv[1])
413 else:
414 dog_loop_writer.Write(argv[1], argv[2])
415
416 cim_writer = control_loop.ControlLoopWriter(
Comran Morshed41ed7c22015-11-04 21:03:37 +0000417 "CIM", [drivetrain.CIM()],
418 namespaces=['y2014_bot3', 'control_loops'])
Comran Morshede9b12922015-11-04 19:46:48 +0000419
Comran Morshed41ed7c22015-11-04 21:03:37 +0000420 if argv[5][-3:] == '.cc':
421 cim_writer.Write(argv[6], argv[5])
Comran Morshede9b12922015-11-04 19:46:48 +0000422 else:
Comran Morshed41ed7c22015-11-04 21:03:37 +0000423 cim_writer.Write(argv[5], argv[6])
Comran Morshede9b12922015-11-04 19:46:48 +0000424 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
Comran Morshed41ed7c22015-11-04 21:03:37 +0000450 for t in numpy.arange(0, 1.7, vdrivetrain.dt):
451 if t < 0.5:
452 vdrivetrain.Update(throttle=0.00, steering=1.0)
Comran Morshede9b12922015-11-04 19:46:48 +0000453 elif t < 1.2:
Comran Morshed41ed7c22015-11-04 21:03:37 +0000454 vdrivetrain.Update(throttle=0.5, steering=1.0)
Comran Morshede9b12922015-11-04 19:46:48 +0000455 else:
Comran Morshed41ed7c22015-11-04 21:03:37 +0000456 vdrivetrain.Update(throttle=0.00, steering=1.0)
Comran Morshede9b12922015-11-04 19:46:48 +0000457 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 = []
475 cim = drivetrain.CIM()
476 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)
Comran Morshed41ed7c22015-11-04 21:03:37 +0000483 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()
Comran Morshede9b12922015-11-04 19:46:48 +0000487
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))