blob: bea8f46b2893a99fcefb41d3ef23dffd7f4f7d7b [file] [log] [blame]
Austin Schuh048fb602013-10-07 23:31:04 -07001#!/usr/bin/python
2
3import numpy
4import sys
5import polytope
6import drivetrain
7import controls
8from matplotlib import pylab
9
10__author__ = 'Austin Schuh (austin.linux@gmail.com)'
11
12
13def CoerceGoal(region, K, w, R):
14 """Intersects a line with a region, and finds the closest point to R.
15
16 Finds a point that is closest to R inside the region, and on the line
17 defined by K X = w. If it is not possible to find a point on the line,
18 finds a point that is inside the region and closest to the line. This
19 function assumes that
20
21 Args:
22 region: HPolytope, the valid goal region.
23 K: numpy.matrix (2 x 1), the matrix for the equation [K1, K2] [x1; x2] = w
24 w: float, the offset in the equation above.
25 R: numpy.matrix (2 x 1), the point to be closest to.
26
27 Returns:
28 numpy.matrix (2 x 1), the point.
29 """
30
31 if region.IsInside(R):
32 return R
33
34 perpendicular_vector = K.T / numpy.linalg.norm(K)
35 parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
36 [-perpendicular_vector[0, 0]]])
37
38 # We want to impose the constraint K * X = w on the polytope H * X <= k.
39 # We do this by breaking X up into parallel and perpendicular components to
40 # the half plane. This gives us the following equation.
41 #
42 # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
43 #
44 # Then, substitute this into the polytope.
45 #
46 # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
47 #
48 # Substitute K * X = w
49 #
50 # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
51 #
52 # Move all the knowns to the right side.
53 #
54 # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
55 #
56 # Let t = parallel.T \dot X, the component parallel to the surface.
57 #
58 # H * parallel * t <= k - H * perpendicular * w
59 #
60 # This is a polytope which we can solve, and use to figure out the range of X
61 # that we care about!
62
63 t_poly = polytope.HPolytope(
64 region.H * parallel_vector,
65 region.k - region.H * perpendicular_vector * w)
66
67 vertices = t_poly.Vertices()
68
69 if vertices.shape[0]:
70 # The region exists!
71 # Find the closest vertex
72 min_distance = numpy.infty
73 closest_point = None
74 for vertex in vertices:
75 point = parallel_vector * vertex + perpendicular_vector * w
76 length = numpy.linalg.norm(R - point)
77 if length < min_distance:
78 min_distance = length
79 closest_point = point
80
81 return closest_point
82 else:
83 # Find the vertex of the space that is closest to the line.
84 region_vertices = region.Vertices()
85 min_distance = numpy.infty
86 closest_point = None
87 for vertex in region_vertices:
88 point = vertex.T
89 length = numpy.abs((perpendicular_vector.T * point)[0, 0])
90 if length < min_distance:
91 min_distance = length
92 closest_point = point
93
94 return closest_point
95
96
Austin Schuh03513cb2013-10-08 22:29:07 -070097class VelocityDrivetrainModel(object):
98 def __init__(self, left_low=True, right_low=True):
99 self._drivetrain = drivetrain.Drivetrain(left_low=left_low,
100 right_low=right_low)
101 self.A = numpy.matrix(
102 [[self._drivetrain.A[1, 1], self._drivetrain.A[1, 3]],
103 [self._drivetrain.A[3, 1], self._drivetrain.A[3, 3]]])
104
105 self.B = numpy.matrix(
106 [[self._drivetrain.B[1, 0], self._drivetrain.B[1, 1]],
107 [self._drivetrain.B[3, 0], self._drivetrain.B[3, 1]]])
108
109 # FF * X = U (steady state)
110 self.FF = self.B.I * (numpy.eye(2) - self.A)
111
112 self.K = controls.dplace(self.A, self.B, [0.3, 0.3])
113
Austin Schuhe05d2c12013-10-12 00:08:31 -0700114 self.G_high = self._drivetrain.G_high
115 self.G_low = self._drivetrain.G_low
116 self.R = self._drivetrain.R
117 self.r = self._drivetrain.r
118 self.Kv = self._drivetrain.Kv
119 self.Kt = self._drivetrain.Kt
120
Austin Schuh03513cb2013-10-08 22:29:07 -0700121
Austin Schuh048fb602013-10-07 23:31:04 -0700122class VelocityDrivetrain(object):
123 def __init__(self):
Austin Schuh03513cb2013-10-08 22:29:07 -0700124 self.drivetrain_low_low = VelocityDrivetrainModel(left_low=True, right_low=True)
125 self.drivetrain_low_high = VelocityDrivetrainModel(left_low=True, right_low=False)
126 self.drivetrain_high_low = VelocityDrivetrainModel(left_low=False, right_low=True)
127 self.drivetrain_high_high = VelocityDrivetrainModel(left_low=False, right_low=False)
Austin Schuh048fb602013-10-07 23:31:04 -0700128
129 # X is [lvel, rvel]
130 self.X = numpy.matrix(
131 [[0.0],
132 [0.0]])
133
Austin Schuh048fb602013-10-07 23:31:04 -0700134 self.U_poly = polytope.HPolytope(
135 numpy.matrix([[1, 0],
136 [-1, 0],
137 [0, 1],
138 [0, -1]]),
139 numpy.matrix([[12],
140 [12],
141 [12],
142 [12]]))
143
144 self.U_max = numpy.matrix(
145 [[12.0],
146 [12.0]])
147 self.U_min = numpy.matrix(
148 [[-12.0000000000],
149 [-12.0000000000]])
150
Austin Schuh048fb602013-10-07 23:31:04 -0700151 self.dt = 0.01
152
153 self.R = numpy.matrix(
154 [[0.0],
155 [0.0]])
156
Austin Schuhe05d2c12013-10-12 00:08:31 -0700157 # ttrust is the comprimise between having full throttle negative inertia,
158 # and having no throttle negative inertia. A value of 0 is full throttle
159 # inertia. A value of 1 is no throttle negative inertia.
Austin Schuh03513cb2013-10-08 22:29:07 -0700160 self.ttrust = 1.0
161
162 self.left_high = False
163 self.right_high = False
164
165 def CurrentDrivetrain(self):
166 if self.left_high:
167 if self.right_high:
168 return self.drivetrain_high_high
169 else:
170 return self.drivetrain_high_low
171 else:
172 if self.right_high:
173 return self.drivetrain_low_high
174 else:
175 return self.drivetrain_low_low
Austin Schuh048fb602013-10-07 23:31:04 -0700176
Austin Schuhe05d2c12013-10-12 00:08:31 -0700177 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
178 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
179 self.CurrentDrivetrain().r)
180 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
181 self.CurrentDrivetrain().r)
182 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
183 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
184 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
185 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
186 high_power = high_torque * high_omega
187 low_power = low_torque * low_omega
188 if should_print:
189 print gear_name, "High omega", high_omega, "Low omega", low_omega
190 print gear_name, "High torque", high_torque, "Low torque", low_torque
191 print gear_name, "High power", high_power, "Low power", low_power
192 if (high_power > low_power) != current_gear:
193 if high_power > low_power:
194 print gear_name, "Shifting to high"
195 else:
196 print gear_name, "Shifting to low"
197
198 return high_power > low_power
199
Austin Schuhec00fc62013-10-12 00:31:49 -0700200 def FilterVelocity(self, throttle):
Austin Schuh048fb602013-10-07 23:31:04 -0700201 # Invert the plant to figure out how the velocity filter would have to work
202 # out in order to filter out the forwards negative inertia.
Austin Schuhe05d2c12013-10-12 00:08:31 -0700203 # This math assumes that the left and right power and velocity are equal.
Austin Schuh048fb602013-10-07 23:31:04 -0700204
Austin Schuhe05d2c12013-10-12 00:08:31 -0700205 # The throttle filter should filter such that the motor in the highest gear
206 # should be controlling the time constant.
207 # Do this by finding the index of FF that has the lowest value, and computing
208 # the sums using that index.
209 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
210 max_FF_sum_index = numpy.argmax(FF_sum)
211 max_FF_sum = FF_sum[max_FF_sum_index, 0]
212 max_K_sum = self.CurrentDrivetrain().K[max_FF_sum_index, :].sum()
213 max_A_sum = self.CurrentDrivetrain().A[max_FF_sum_index, :].sum()
214 max_B_sum = self.CurrentDrivetrain().B[max_FF_sum_index, :].sum()
215 # Compute the FF sum for high gear.
216 high_max_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
217
Austin Schuhec00fc62013-10-12 00:31:49 -0700218 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
Austin Schuhe05d2c12013-10-12 00:08:31 -0700219 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
Austin Schuhec00fc62013-10-12 00:31:49 -0700220 # - self.K[0, :].sum() * x_avg
Austin Schuhe05d2c12013-10-12 00:08:31 -0700221
Austin Schuhec00fc62013-10-12 00:31:49 -0700222 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
Austin Schuhe05d2c12013-10-12 00:08:31 -0700223 # (self.K[0, :].sum() + self.FF[0, :].sum())
224
225 # U = (K + FF) * R - K * X
226 # (K + FF) ^-1 * (U + K * X) = R
227
Austin Schuhe05d2c12013-10-12 00:08:31 -0700228 # Scale throttle by max_FF_sum / high_max_FF_sum. This will make low gear
229 # have the same velocity goal as high gear, and so that the robot will hold
230 # the same speed for the same throttle for all gears.
231 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * max_FF_sum / high_max_FF_sum, -12.0, 12.0)
Austin Schuhec00fc62013-10-12 00:31:49 -0700232 return ((adjusted_ff_voltage + self.ttrust * max_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
Austin Schuhe05d2c12013-10-12 00:08:31 -0700233 / (self.ttrust * max_K_sum + max_FF_sum))
Austin Schuhec00fc62013-10-12 00:31:49 -0700234
235 def Update(self, throttle, steering):
236 # Shift into the gear which sends the most power to the floor.
237 # This is the same as sending the most torque down to the floor at the
238 # wheel.
239
240 self.left_high = self.ComputeGear(self.X[0, 0], should_print=True, current_gear=self.left_high, gear_name="left")
241 self.right_high = self.ComputeGear(self.X[1, 0], should_print=True, current_gear=self.right_high, gear_name="right")
242
243 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
244
245 # Filter the throttle to provide a nicer response.
246
247 # TODO(austin): fn
248 fvel = self.FilterVelocity(throttle)
Austin Schuh048fb602013-10-07 23:31:04 -0700249
250 # Constant radius means that angualar_velocity / linear_velocity = constant.
251 # Compute the left and right velocities.
252 left_velocity = fvel - steering * numpy.abs(fvel)
253 right_velocity = fvel + steering * numpy.abs(fvel)
254
255 # Write this constraint in the form of K * R = w
256 # angular velocity / linear velocity = constant
257 # (left - right) / (left + right) = constant
258 # left - right = constant * left + constant * right
259
260 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
261 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
262 # constant
263 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
264 # (-steering * sign(fvel)) = constant
265 # (-steering * sign(fvel)) * (left + right) = left - right
266 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
267
268 equality_k = numpy.matrix(
269 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
270 equality_w = 0.0
271
272 self.R[0, 0] = left_velocity
273 self.R[1, 0] = right_velocity
274
275 # Construct a constraint on R by manipulating the constraint on U
276 # Start out with H * U <= k
277 # U = FF * R + K * (R - X)
278 # H * (FF * R + K * R - K * X) <= k
279 # H * (FF + K) * R <= k + H * K * X
280 R_poly = polytope.HPolytope(
Austin Schuh03513cb2013-10-08 22:29:07 -0700281 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
282 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
Austin Schuh048fb602013-10-07 23:31:04 -0700283
284 # Limit R back inside the box.
285 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
286
Austin Schuh03513cb2013-10-08 22:29:07 -0700287 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
288 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
Austin Schuh048fb602013-10-07 23:31:04 -0700289
290 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
Austin Schuh03513cb2013-10-08 22:29:07 -0700291 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
Austin Schuhe05d2c12013-10-12 00:08:31 -0700292 print "U is", self.U[0, 0], self.U[1, 0]
Austin Schuh048fb602013-10-07 23:31:04 -0700293
294
295def main(argv):
296 drivetrain = VelocityDrivetrain()
297
298 vl_plot = []
299 vr_plot = []
300 ul_plot = []
301 ur_plot = []
302 radius_plot = []
303 t_plot = []
Austin Schuhe05d2c12013-10-12 00:08:31 -0700304 left_gear_plot = []
305 right_gear_plot = []
306 drivetrain.left_high = True
307 drivetrain.right_high = True
Austin Schuh03513cb2013-10-08 22:29:07 -0700308
Austin Schuhe05d2c12013-10-12 00:08:31 -0700309 if drivetrain.left_high:
310 print "Left is high"
311 else:
312 print "Left is low"
313 if drivetrain.right_high:
314 print "Right is high"
315 else:
316 print "Right is low"
317
318 for t in numpy.arange(0, 2.0, drivetrain.dt):
319 if t < 1.0:
320 drivetrain.Update(throttle=0.60, steering=0.3)
321 elif t < 1.5:
Austin Schuh048fb602013-10-07 23:31:04 -0700322 drivetrain.Update(throttle=0.60, steering=-0.3)
323 else:
Austin Schuhe05d2c12013-10-12 00:08:31 -0700324 drivetrain.Update(throttle=0.60, steering=0.3)
Austin Schuh048fb602013-10-07 23:31:04 -0700325 t_plot.append(t)
326 vl_plot.append(drivetrain.X[0, 0])
327 vr_plot.append(drivetrain.X[1, 0])
328 ul_plot.append(drivetrain.U[0, 0])
329 ur_plot.append(drivetrain.U[1, 0])
Austin Schuhe05d2c12013-10-12 00:08:31 -0700330 left_gear_plot.append(drivetrain.left_high * 2.0 - 10.0)
331 right_gear_plot.append(drivetrain.right_high * 2.0 - 10.0)
Austin Schuh048fb602013-10-07 23:31:04 -0700332
333 fwd_velocity = (drivetrain.X[1, 0] + drivetrain.X[0, 0]) / 2
334 turn_velocity = (drivetrain.X[1, 0] - drivetrain.X[0, 0])
335 if fwd_velocity < 0.0000001:
336 radius_plot.append(turn_velocity)
337 else:
338 radius_plot.append(turn_velocity / fwd_velocity)
339
340 pylab.plot(t_plot, vl_plot, label='left velocity')
341 pylab.plot(t_plot, vr_plot, label='right velocity')
342 pylab.plot(t_plot, ul_plot, label='left power')
343 pylab.plot(t_plot, ur_plot, label='right power')
344 pylab.plot(t_plot, radius_plot, label='radius')
Austin Schuhe05d2c12013-10-12 00:08:31 -0700345 pylab.plot(t_plot, left_gear_plot, label='left_gear')
346 pylab.plot(t_plot, right_gear_plot, label='right_gear')
Austin Schuh048fb602013-10-07 23:31:04 -0700347 pylab.legend()
348 pylab.show()
349 return 0
350
351if __name__ == '__main__':
352 sys.exit(main(sys.argv))