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