blob: 9fa7841b5bb80629c8f84fdb8f05064b3240a58a [file] [log] [blame]
Austin Schuh048fb602013-10-07 23:31:04 -07001#!/usr/bin/python
2
3import numpy
4import sys
5import polytope
6import drivetrain
Austin Schuh2054f5f2013-10-27 14:54:10 -07007import control_loop
Austin Schuh048fb602013-10-07 23:31:04 -07008import 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
32 if region.IsInside(R):
33 return R
34
35 perpendicular_vector = K.T / numpy.linalg.norm(K)
36 parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
37 [-perpendicular_vector[0, 0]]])
38
39 # We want to impose the constraint K * X = w on the polytope H * X <= k.
40 # We do this by breaking X up into parallel and perpendicular components to
41 # the half plane. This gives us the following equation.
42 #
43 # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
44 #
45 # Then, substitute this into the polytope.
46 #
47 # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
48 #
49 # Substitute K * X = w
50 #
51 # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
52 #
53 # Move all the knowns to the right side.
54 #
55 # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
56 #
57 # Let t = parallel.T \dot X, the component parallel to the surface.
58 #
59 # H * parallel * t <= k - H * perpendicular * w
60 #
61 # This is a polytope which we can solve, and use to figure out the range of X
62 # that we care about!
63
64 t_poly = polytope.HPolytope(
65 region.H * parallel_vector,
66 region.k - region.H * perpendicular_vector * w)
67
68 vertices = t_poly.Vertices()
69
70 if vertices.shape[0]:
71 # The region exists!
72 # Find the closest vertex
73 min_distance = numpy.infty
74 closest_point = None
75 for vertex in vertices:
76 point = parallel_vector * vertex + perpendicular_vector * w
77 length = numpy.linalg.norm(R - point)
78 if length < min_distance:
79 min_distance = length
80 closest_point = point
81
82 return closest_point
83 else:
84 # Find the vertex of the space that is closest to the line.
85 region_vertices = region.Vertices()
86 min_distance = numpy.infty
87 closest_point = None
88 for vertex in region_vertices:
89 point = vertex.T
90 length = numpy.abs((perpendicular_vector.T * point)[0, 0])
91 if length < min_distance:
92 min_distance = length
93 closest_point = point
94
95 return closest_point
96
97
Austin Schuh2054f5f2013-10-27 14:54:10 -070098class VelocityDrivetrainModel(control_loop.ControlLoop):
99 def __init__(self, left_low=True, right_low=True, name="VelocityDrivetrainModel"):
100 super(VelocityDrivetrainModel, self).__init__(name)
Austin Schuh03513cb2013-10-08 22:29:07 -0700101 self._drivetrain = drivetrain.Drivetrain(left_low=left_low,
102 right_low=right_low)
Austin Schuh2054f5f2013-10-27 14:54:10 -0700103 self.dt = 0.01
104 self.A_continuous = numpy.matrix(
105 [[self._drivetrain.A_continuous[1, 1], self._drivetrain.A_continuous[1, 3]],
106 [self._drivetrain.A_continuous[3, 1], self._drivetrain.A_continuous[3, 3]]])
Austin Schuh03513cb2013-10-08 22:29:07 -0700107
Austin Schuh2054f5f2013-10-27 14:54:10 -0700108 self.B_continuous = numpy.matrix(
109 [[self._drivetrain.B_continuous[1, 0], self._drivetrain.B_continuous[1, 1]],
110 [self._drivetrain.B_continuous[3, 0], self._drivetrain.B_continuous[3, 1]]])
111 self.C = numpy.matrix(numpy.eye(2));
112 self.D = numpy.matrix(numpy.zeros((2, 2)));
113
114 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
115 self.B_continuous, self.dt)
Austin Schuh03513cb2013-10-08 22:29:07 -0700116
117 # FF * X = U (steady state)
118 self.FF = self.B.I * (numpy.eye(2) - self.A)
119
Austin Schuh2054f5f2013-10-27 14:54:10 -0700120 self.PlaceControllerPoles([0.3, 0.3])
121 self.PlaceObserverPoles([0.02, 0.02])
Austin Schuh03513cb2013-10-08 22:29:07 -0700122
Austin Schuhe05d2c12013-10-12 00:08:31 -0700123 self.G_high = self._drivetrain.G_high
124 self.G_low = self._drivetrain.G_low
125 self.R = self._drivetrain.R
126 self.r = self._drivetrain.r
127 self.Kv = self._drivetrain.Kv
128 self.Kt = self._drivetrain.Kt
129
Austin Schuh2054f5f2013-10-27 14:54:10 -0700130 self.U_max = self._drivetrain.U_max
131 self.U_min = self._drivetrain.U_min
132
Austin Schuh03513cb2013-10-08 22:29:07 -0700133
Austin Schuh048fb602013-10-07 23:31:04 -0700134class VelocityDrivetrain(object):
135 def __init__(self):
Austin Schuh2054f5f2013-10-27 14:54:10 -0700136 self.drivetrain_low_low = VelocityDrivetrainModel(left_low=True, right_low=True, name='VelocityDrivetrainLowLow')
137 self.drivetrain_low_high = VelocityDrivetrainModel(left_low=True, right_low=False, name='VelocityDrivetrainLowHigh')
138 self.drivetrain_high_low = VelocityDrivetrainModel(left_low=False, right_low=True, name = 'VelocityDrivetrainHighLow')
139 self.drivetrain_high_high = VelocityDrivetrainModel(left_low=False, right_low=False, name = 'VelocityDrivetrainHighHigh')
Austin Schuh048fb602013-10-07 23:31:04 -0700140
141 # X is [lvel, rvel]
142 self.X = numpy.matrix(
143 [[0.0],
144 [0.0]])
145
Austin Schuh048fb602013-10-07 23:31:04 -0700146 self.U_poly = polytope.HPolytope(
147 numpy.matrix([[1, 0],
148 [-1, 0],
149 [0, 1],
150 [0, -1]]),
151 numpy.matrix([[12],
152 [12],
153 [12],
154 [12]]))
155
156 self.U_max = numpy.matrix(
157 [[12.0],
158 [12.0]])
159 self.U_min = numpy.matrix(
160 [[-12.0000000000],
161 [-12.0000000000]])
162
Austin Schuh048fb602013-10-07 23:31:04 -0700163 self.dt = 0.01
164
165 self.R = numpy.matrix(
166 [[0.0],
167 [0.0]])
168
Austin Schuhe05d2c12013-10-12 00:08:31 -0700169 # ttrust is the comprimise between having full throttle negative inertia,
170 # and having no throttle negative inertia. A value of 0 is full throttle
171 # inertia. A value of 1 is no throttle negative inertia.
Austin Schuh03513cb2013-10-08 22:29:07 -0700172 self.ttrust = 1.0
173
174 self.left_high = False
175 self.right_high = False
176
177 def CurrentDrivetrain(self):
178 if self.left_high:
179 if self.right_high:
180 return self.drivetrain_high_high
181 else:
182 return self.drivetrain_high_low
183 else:
184 if self.right_high:
185 return self.drivetrain_low_high
186 else:
187 return self.drivetrain_low_low
Austin Schuh048fb602013-10-07 23:31:04 -0700188
Austin Schuhe05d2c12013-10-12 00:08:31 -0700189 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
190 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
191 self.CurrentDrivetrain().r)
192 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
193 self.CurrentDrivetrain().r)
Austin Schuh8afe35a2013-10-27 10:59:15 -0700194 print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
Austin Schuhe05d2c12013-10-12 00:08:31 -0700195 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
196 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
197 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
198 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
199 high_power = high_torque * high_omega
200 low_power = low_torque * low_omega
201 if should_print:
202 print gear_name, "High omega", high_omega, "Low omega", low_omega
203 print gear_name, "High torque", high_torque, "Low torque", low_torque
204 print gear_name, "High power", high_power, "Low power", low_power
205 if (high_power > low_power) != current_gear:
206 if high_power > low_power:
207 print gear_name, "Shifting to high"
208 else:
209 print gear_name, "Shifting to low"
210
Austin Schuh8afe35a2013-10-27 10:59:15 -0700211 # Shift algorithm improvements.
212 # TODO(aschuh):
213 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
214 # because you will end up slower than without shifting. Figure out how
215 # to include that info.
216 # If the driver is still in high gear, but isn't asking for the extra power
217 # from low gear, don't shift until he asks for it.
Austin Schuhe05d2c12013-10-12 00:08:31 -0700218 return high_power > low_power
219
Austin Schuhec00fc62013-10-12 00:31:49 -0700220 def FilterVelocity(self, throttle):
Austin Schuh048fb602013-10-07 23:31:04 -0700221 # Invert the plant to figure out how the velocity filter would have to work
222 # out in order to filter out the forwards negative inertia.
Austin Schuhe05d2c12013-10-12 00:08:31 -0700223 # This math assumes that the left and right power and velocity are equal.
Austin Schuh048fb602013-10-07 23:31:04 -0700224
Austin Schuhe05d2c12013-10-12 00:08:31 -0700225 # The throttle filter should filter such that the motor in the highest gear
226 # should be controlling the time constant.
227 # Do this by finding the index of FF that has the lowest value, and computing
228 # the sums using that index.
229 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
Austin Schuh2054f5f2013-10-27 14:54:10 -0700230 min_FF_sum_index = numpy.argmin(FF_sum)
231 min_FF_sum = FF_sum[min_FF_sum_index, 0]
232 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
Austin Schuhe05d2c12013-10-12 00:08:31 -0700233 # Compute the FF sum for high gear.
Austin Schuh2054f5f2013-10-27 14:54:10 -0700234 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
Austin Schuhe05d2c12013-10-12 00:08:31 -0700235
Austin Schuhec00fc62013-10-12 00:31:49 -0700236 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
Austin Schuhe05d2c12013-10-12 00:08:31 -0700237 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
Austin Schuhec00fc62013-10-12 00:31:49 -0700238 # - self.K[0, :].sum() * x_avg
Austin Schuhe05d2c12013-10-12 00:08:31 -0700239
Austin Schuhec00fc62013-10-12 00:31:49 -0700240 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
Austin Schuhe05d2c12013-10-12 00:08:31 -0700241 # (self.K[0, :].sum() + self.FF[0, :].sum())
242
243 # U = (K + FF) * R - K * X
244 # (K + FF) ^-1 * (U + K * X) = R
245
Austin Schuh2054f5f2013-10-27 14:54:10 -0700246 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
Austin Schuhe05d2c12013-10-12 00:08:31 -0700247 # have the same velocity goal as high gear, and so that the robot will hold
248 # the same speed for the same throttle for all gears.
Austin Schuh2054f5f2013-10-27 14:54:10 -0700249 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
250 return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
251 / (self.ttrust * min_K_sum + min_FF_sum))
Austin Schuhec00fc62013-10-12 00:31:49 -0700252
253 def Update(self, throttle, steering):
254 # Shift into the gear which sends the most power to the floor.
255 # This is the same as sending the most torque down to the floor at the
256 # wheel.
257
258 self.left_high = self.ComputeGear(self.X[0, 0], should_print=True, current_gear=self.left_high, gear_name="left")
259 self.right_high = self.ComputeGear(self.X[1, 0], should_print=True, current_gear=self.right_high, gear_name="right")
260
261 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
262
263 # Filter the throttle to provide a nicer response.
264
265 # TODO(austin): fn
266 fvel = self.FilterVelocity(throttle)
Austin Schuh048fb602013-10-07 23:31:04 -0700267
268 # Constant radius means that angualar_velocity / linear_velocity = constant.
269 # Compute the left and right velocities.
270 left_velocity = fvel - steering * numpy.abs(fvel)
271 right_velocity = fvel + steering * numpy.abs(fvel)
272
273 # Write this constraint in the form of K * R = w
274 # angular velocity / linear velocity = constant
275 # (left - right) / (left + right) = constant
276 # left - right = constant * left + constant * right
277
278 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
279 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
280 # constant
281 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
282 # (-steering * sign(fvel)) = constant
283 # (-steering * sign(fvel)) * (left + right) = left - right
284 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
285
286 equality_k = numpy.matrix(
287 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
288 equality_w = 0.0
289
290 self.R[0, 0] = left_velocity
291 self.R[1, 0] = right_velocity
292
293 # Construct a constraint on R by manipulating the constraint on U
294 # Start out with H * U <= k
295 # U = FF * R + K * (R - X)
296 # H * (FF * R + K * R - K * X) <= k
297 # H * (FF + K) * R <= k + H * K * X
298 R_poly = polytope.HPolytope(
Austin Schuh03513cb2013-10-08 22:29:07 -0700299 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
300 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
Austin Schuh048fb602013-10-07 23:31:04 -0700301
302 # Limit R back inside the box.
303 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
304
Austin Schuh03513cb2013-10-08 22:29:07 -0700305 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
306 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
Austin Schuh048fb602013-10-07 23:31:04 -0700307
308 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
Austin Schuh03513cb2013-10-08 22:29:07 -0700309 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
Austin Schuhe05d2c12013-10-12 00:08:31 -0700310 print "U is", self.U[0, 0], self.U[1, 0]
Austin Schuh048fb602013-10-07 23:31:04 -0700311
312
313def main(argv):
Austin Schuh8afe35a2013-10-27 10:59:15 -0700314 vdrivetrain = VelocityDrivetrain()
Austin Schuh048fb602013-10-07 23:31:04 -0700315
Austin Schuh2054f5f2013-10-27 14:54:10 -0700316 if len(argv) != 3:
317 print "Expected .h file name and .cc file name"
318 else:
319 loop_writer = control_loop.ControlLoopWriter(
320 "VDrivetrain", [vdrivetrain.drivetrain_low_low,
321 vdrivetrain.drivetrain_low_high,
322 vdrivetrain.drivetrain_high_low,
323 vdrivetrain.drivetrain_high_high])
324
325 if argv[1][-3:] == '.cc':
326 loop_writer.Write(argv[2], argv[1])
327 else:
328 loop_writer.Write(argv[1], argv[2])
329 return
330
331
Austin Schuh048fb602013-10-07 23:31:04 -0700332 vl_plot = []
333 vr_plot = []
334 ul_plot = []
335 ur_plot = []
336 radius_plot = []
337 t_plot = []
Austin Schuhe05d2c12013-10-12 00:08:31 -0700338 left_gear_plot = []
339 right_gear_plot = []
Austin Schuh8afe35a2013-10-27 10:59:15 -0700340 vdrivetrain.left_high = True
341 vdrivetrain.right_high = True
Austin Schuh03513cb2013-10-08 22:29:07 -0700342
Austin Schuh8afe35a2013-10-27 10:59:15 -0700343 print "K is", vdrivetrain.CurrentDrivetrain().K
344
345 if vdrivetrain.left_high:
Austin Schuhe05d2c12013-10-12 00:08:31 -0700346 print "Left is high"
347 else:
348 print "Left is low"
Austin Schuh8afe35a2013-10-27 10:59:15 -0700349 if vdrivetrain.right_high:
Austin Schuhe05d2c12013-10-12 00:08:31 -0700350 print "Right is high"
351 else:
352 print "Right is low"
353
Austin Schuh8afe35a2013-10-27 10:59:15 -0700354 for t in numpy.arange(0, 2.0, vdrivetrain.dt):
Austin Schuhe05d2c12013-10-12 00:08:31 -0700355 if t < 1.0:
Austin Schuh8afe35a2013-10-27 10:59:15 -0700356 vdrivetrain.Update(throttle=0.60, steering=0.3)
Austin Schuhe05d2c12013-10-12 00:08:31 -0700357 elif t < 1.5:
Austin Schuh8afe35a2013-10-27 10:59:15 -0700358 vdrivetrain.Update(throttle=0.60, steering=-0.3)
Austin Schuh048fb602013-10-07 23:31:04 -0700359 else:
Austin Schuh8afe35a2013-10-27 10:59:15 -0700360 vdrivetrain.Update(throttle=0.0, steering=0.3)
Austin Schuh048fb602013-10-07 23:31:04 -0700361 t_plot.append(t)
Austin Schuh8afe35a2013-10-27 10:59:15 -0700362 vl_plot.append(vdrivetrain.X[0, 0])
363 vr_plot.append(vdrivetrain.X[1, 0])
364 ul_plot.append(vdrivetrain.U[0, 0])
365 ur_plot.append(vdrivetrain.U[1, 0])
366 left_gear_plot.append(vdrivetrain.left_high * 2.0 - 10.0)
367 right_gear_plot.append(vdrivetrain.right_high * 2.0 - 10.0)
Austin Schuh048fb602013-10-07 23:31:04 -0700368
Austin Schuh8afe35a2013-10-27 10:59:15 -0700369 fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
370 turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
Austin Schuh048fb602013-10-07 23:31:04 -0700371 if fwd_velocity < 0.0000001:
372 radius_plot.append(turn_velocity)
373 else:
374 radius_plot.append(turn_velocity / fwd_velocity)
375
Austin Schuh8afe35a2013-10-27 10:59:15 -0700376 cim_velocity_plot = []
377 cim_voltage_plot = []
378 cim_time = []
379 cim = drivetrain.CIM()
380 R = numpy.matrix([[300]])
381 for t in numpy.arange(0, 0.5, cim.dt):
382 U = numpy.clip(cim.K * (R - cim.X) + R / cim.Kv, cim.U_min, cim.U_max)
383 cim.Update(U)
384 cim_velocity_plot.append(cim.X[0, 0])
385 cim_voltage_plot.append(U[0, 0] * 10)
386 cim_time.append(t)
387 pylab.plot(cim_time, cim_velocity_plot, label='cim spinup')
388 pylab.plot(cim_time, cim_voltage_plot, label='cim voltage')
389 pylab.legend()
390 pylab.show()
391
392
Austin Schuh048fb602013-10-07 23:31:04 -0700393 pylab.plot(t_plot, vl_plot, label='left velocity')
394 pylab.plot(t_plot, vr_plot, label='right velocity')
Austin Schuh8afe35a2013-10-27 10:59:15 -0700395 pylab.plot(t_plot, ul_plot, label='left voltage')
396 pylab.plot(t_plot, ur_plot, label='right voltage')
Austin Schuh048fb602013-10-07 23:31:04 -0700397 pylab.plot(t_plot, radius_plot, label='radius')
Austin Schuh8afe35a2013-10-27 10:59:15 -0700398 pylab.plot(t_plot, left_gear_plot, label='left gear high')
399 pylab.plot(t_plot, right_gear_plot, label='right gear high')
Austin Schuh048fb602013-10-07 23:31:04 -0700400 pylab.legend()
401 pylab.show()
402 return 0
403
404if __name__ == '__main__':
405 sys.exit(main(sys.argv))