blob: c87c1e61b7fac8049a17caa926e9c8d7634cdbc0 [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
Austin Schuh44aa9142018-12-03 21:07:23 +1100135 @property
136 def robot_radius_l(self):
137 return self._drivetrain.robot_radius_l
138 @property
139 def robot_radius_r(self):
140 return self._drivetrain.robot_radius_r
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800141
142class VelocityDrivetrain(object):
143 HIGH = 'high'
144 LOW = 'low'
145 SHIFTING_UP = 'up'
146 SHIFTING_DOWN = 'down'
147
148 def __init__(self, drivetrain_params):
149 self.drivetrain_low_low = VelocityDrivetrainModel(
150 left_low=True, right_low=True, name='VelocityDrivetrainLowLow',
151 drivetrain_params=drivetrain_params)
152 self.drivetrain_low_high = VelocityDrivetrainModel(
153 left_low=True, right_low=False, name='VelocityDrivetrainLowHigh',
154 drivetrain_params=drivetrain_params)
155 self.drivetrain_high_low = VelocityDrivetrainModel(
156 left_low=False, right_low=True, name = 'VelocityDrivetrainHighLow',
157 drivetrain_params=drivetrain_params)
158 self.drivetrain_high_high = VelocityDrivetrainModel(
159 left_low=False, right_low=False, name = 'VelocityDrivetrainHighHigh',
160 drivetrain_params=drivetrain_params)
161
162 # X is [lvel, rvel]
163 self.X = numpy.matrix(
164 [[0.0],
165 [0.0]])
166
167 self.U_poly = polytope.HPolytope(
168 numpy.matrix([[1, 0],
169 [-1, 0],
170 [0, 1],
171 [0, -1]]),
172 numpy.matrix([[12],
173 [12],
174 [12],
175 [12]]))
176
177 self.U_max = numpy.matrix(
178 [[12.0],
179 [12.0]])
180 self.U_min = numpy.matrix(
181 [[-12.0000000000],
182 [-12.0000000000]])
183
184 self.dt = 0.00505
185
186 self.R = numpy.matrix(
187 [[0.0],
188 [0.0]])
189
190 self.U_ideal = numpy.matrix(
191 [[0.0],
192 [0.0]])
193
194 # ttrust is the comprimise between having full throttle negative inertia,
195 # and having no throttle negative inertia. A value of 0 is full throttle
196 # inertia. A value of 1 is no throttle negative inertia.
197 self.ttrust = 1.0
198
199 self.left_gear = VelocityDrivetrain.LOW
200 self.right_gear = VelocityDrivetrain.LOW
201 self.left_shifter_position = 0.0
202 self.right_shifter_position = 0.0
203 self.left_cim = CIM()
204 self.right_cim = CIM()
205
206 def IsInGear(self, gear):
207 return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
208
209 def MotorRPM(self, shifter_position, velocity):
210 if shifter_position > 0.5:
211 return (velocity / self.CurrentDrivetrain().G_high /
212 self.CurrentDrivetrain().r)
213 else:
214 return (velocity / self.CurrentDrivetrain().G_low /
215 self.CurrentDrivetrain().r)
216
217 def CurrentDrivetrain(self):
218 if self.left_shifter_position > 0.5:
219 if self.right_shifter_position > 0.5:
220 return self.drivetrain_high_high
221 else:
222 return self.drivetrain_high_low
223 else:
224 if self.right_shifter_position > 0.5:
225 return self.drivetrain_low_high
226 else:
227 return self.drivetrain_low_low
228
229 def SimShifter(self, gear, shifter_position):
230 if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
231 shifter_position = min(shifter_position + 0.5, 1.0)
232 else:
233 shifter_position = max(shifter_position - 0.5, 0.0)
234
235 if shifter_position == 1.0:
236 gear = VelocityDrivetrain.HIGH
237 elif shifter_position == 0.0:
238 gear = VelocityDrivetrain.LOW
239
240 return gear, shifter_position
241
242 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
243 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
244 self.CurrentDrivetrain().r)
245 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
246 self.CurrentDrivetrain().r)
247 #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
248 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
249 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().resistance)
250 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
251 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().resistance)
252 high_power = high_torque * high_omega
253 low_power = low_torque * low_omega
254 #if should_print:
255 # print gear_name, "High omega", high_omega, "Low omega", low_omega
256 # print gear_name, "High torque", high_torque, "Low torque", low_torque
257 # print gear_name, "High power", high_power, "Low power", low_power
258
259 # Shift algorithm improvements.
260 # TODO(aschuh):
261 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
262 # because you will end up slower than without shifting. Figure out how
263 # to include that info.
264 # If the driver is still in high gear, but isn't asking for the extra power
265 # from low gear, don't shift until he asks for it.
266 goal_gear_is_high = high_power > low_power
267 #goal_gear_is_high = True
268
269 if not self.IsInGear(current_gear):
270 glog.debug('%s Not in gear.', gear_name)
271 return current_gear
272 else:
273 is_high = current_gear is VelocityDrivetrain.HIGH
274 if is_high != goal_gear_is_high:
275 if goal_gear_is_high:
276 glog.debug('%s Shifting up.', gear_name)
277 return VelocityDrivetrain.SHIFTING_UP
278 else:
279 glog.debug('%s Shifting down.', gear_name)
280 return VelocityDrivetrain.SHIFTING_DOWN
281 else:
282 return current_gear
283
284 def FilterVelocity(self, throttle):
285 # Invert the plant to figure out how the velocity filter would have to work
286 # out in order to filter out the forwards negative inertia.
287 # This math assumes that the left and right power and velocity are equal.
288
289 # The throttle filter should filter such that the motor in the highest gear
290 # should be controlling the time constant.
291 # Do this by finding the index of FF that has the lowest value, and computing
292 # the sums using that index.
293 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
294 min_FF_sum_index = numpy.argmin(FF_sum)
295 min_FF_sum = FF_sum[min_FF_sum_index, 0]
296 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
297 # Compute the FF sum for high gear.
298 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
299
300 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
301 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
302 # - self.K[0, :].sum() * x_avg
303
304 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
305 # (self.K[0, :].sum() + self.FF[0, :].sum())
306
307 # U = (K + FF) * R - K * X
308 # (K + FF) ^-1 * (U + K * X) = R
309
310 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
311 # have the same velocity goal as high gear, and so that the robot will hold
312 # the same speed for the same throttle for all gears.
313 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
314 return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
315 / (self.ttrust * min_K_sum + min_FF_sum))
316
317 def Update(self, throttle, steering):
318 # Shift into the gear which sends the most power to the floor.
319 # This is the same as sending the most torque down to the floor at the
320 # wheel.
321
322 self.left_gear = self.right_gear = True
323 if True:
324 self.left_gear = self.ComputeGear(self.X[0, 0], should_print=True,
325 current_gear=self.left_gear,
326 gear_name="left")
327 self.right_gear = self.ComputeGear(self.X[1, 0], should_print=True,
328 current_gear=self.right_gear,
329 gear_name="right")
330 if self.IsInGear(self.left_gear):
331 self.left_cim.X[0, 0] = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
332
333 if self.IsInGear(self.right_gear):
334 self.right_cim.X[0, 0] = self.MotorRPM(self.right_shifter_position, self.X[0, 0])
335
336 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
337 # Filter the throttle to provide a nicer response.
338 fvel = self.FilterVelocity(throttle)
339
340 # Constant radius means that angualar_velocity / linear_velocity = constant.
341 # Compute the left and right velocities.
342 steering_velocity = numpy.abs(fvel) * steering
343 left_velocity = fvel - steering_velocity
344 right_velocity = fvel + steering_velocity
345
346 # Write this constraint in the form of K * R = w
347 # angular velocity / linear velocity = constant
348 # (left - right) / (left + right) = constant
349 # left - right = constant * left + constant * right
350
351 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
352 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
353 # constant
354 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
355 # (-steering * sign(fvel)) = constant
356 # (-steering * sign(fvel)) * (left + right) = left - right
357 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
358
359 equality_k = numpy.matrix(
360 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
361 equality_w = 0.0
362
363 self.R[0, 0] = left_velocity
364 self.R[1, 0] = right_velocity
365
366 # Construct a constraint on R by manipulating the constraint on U
367 # Start out with H * U <= k
368 # U = FF * R + K * (R - X)
369 # H * (FF * R + K * R - K * X) <= k
370 # H * (FF + K) * R <= k + H * K * X
371 R_poly = polytope.HPolytope(
372 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
373 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
374
375 # Limit R back inside the box.
376 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
377
378 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
379 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
380 else:
381 glog.debug('Not all in gear')
382 if not self.IsInGear(self.left_gear) and not self.IsInGear(self.right_gear):
383 # TODO(austin): Use battery volts here.
384 R_left = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
385 self.U_ideal[0, 0] = numpy.clip(
386 self.left_cim.K * (R_left - self.left_cim.X) + R_left / self.left_cim.Kv,
387 self.left_cim.U_min, self.left_cim.U_max)
388 self.left_cim.Update(self.U_ideal[0, 0])
389
390 R_right = self.MotorRPM(self.right_shifter_position, self.X[1, 0])
391 self.U_ideal[1, 0] = numpy.clip(
392 self.right_cim.K * (R_right - self.right_cim.X) + R_right / self.right_cim.Kv,
393 self.right_cim.U_min, self.right_cim.U_max)
394 self.right_cim.Update(self.U_ideal[1, 0])
395 else:
396 assert False
397
398 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
399
400 # TODO(austin): Model the robot as not accelerating when you shift...
401 # This hack only works when you shift at the same time.
402 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
403 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
404
405 self.left_gear, self.left_shifter_position = self.SimShifter(
406 self.left_gear, self.left_shifter_position)
407 self.right_gear, self.right_shifter_position = self.SimShifter(
408 self.right_gear, self.right_shifter_position)
409
410 glog.debug('U is %s %s', str(self.U[0, 0]), str(self.U[1, 0]))
411 glog.debug('Left shifter %s %d Right shifter %s %d',
412 self.left_gear, self.left_shifter_position,
413 self.right_gear, self.right_shifter_position)
414
415def WritePolyDrivetrain(drivetrain_files, motor_files, year_namespace,
Austin Schuhbcce26a2018-03-26 23:41:24 -0700416 drivetrain_params, scalar_type='double'):
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800417 vdrivetrain = VelocityDrivetrain(drivetrain_params)
Austin Schuhbcce26a2018-03-26 23:41:24 -0700418 if isinstance(year_namespace, list):
419 namespaces = year_namespace
420 else:
421 namespaces = [year_namespace, 'control_loops', 'drivetrain']
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800422 dog_loop_writer = control_loop.ControlLoopWriter(
423 "VelocityDrivetrain", [vdrivetrain.drivetrain_low_low,
424 vdrivetrain.drivetrain_low_high,
425 vdrivetrain.drivetrain_high_low,
426 vdrivetrain.drivetrain_high_high],
Austin Schuhbcce26a2018-03-26 23:41:24 -0700427 namespaces=namespaces,
428 scalar_type=scalar_type)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800429
430 dog_loop_writer.Write(drivetrain_files[0], drivetrain_files[1])
431
Austin Schuhbcce26a2018-03-26 23:41:24 -0700432 cim_writer = control_loop.ControlLoopWriter("CIM", [CIM()], scalar_type=scalar_type)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800433
434 cim_writer.Write(motor_files[0], motor_files[1])
435
436def PlotPolyDrivetrainMotions(drivetrain_params):
437 vdrivetrain = VelocityDrivetrain(drivetrain_params)
438 vl_plot = []
439 vr_plot = []
440 ul_plot = []
441 ur_plot = []
442 radius_plot = []
443 t_plot = []
444 left_gear_plot = []
445 right_gear_plot = []
446 vdrivetrain.left_shifter_position = 0.0
447 vdrivetrain.right_shifter_position = 0.0
448 vdrivetrain.left_gear = VelocityDrivetrain.LOW
449 vdrivetrain.right_gear = VelocityDrivetrain.LOW
450
451 glog.debug('K is %s', str(vdrivetrain.CurrentDrivetrain().K))
452
453 if vdrivetrain.left_gear is VelocityDrivetrain.HIGH:
454 glog.debug('Left is high')
455 else:
456 glog.debug('Left is low')
457 if vdrivetrain.right_gear is VelocityDrivetrain.HIGH:
458 glog.debug('Right is high')
459 else:
460 glog.debug('Right is low')
461
462 for t in numpy.arange(0, 1.7, vdrivetrain.dt):
463 if t < 0.5:
464 vdrivetrain.Update(throttle=0.00, steering=1.0)
465 elif t < 1.2:
466 vdrivetrain.Update(throttle=0.5, steering=1.0)
467 else:
468 vdrivetrain.Update(throttle=0.00, steering=1.0)
469 t_plot.append(t)
470 vl_plot.append(vdrivetrain.X[0, 0])
471 vr_plot.append(vdrivetrain.X[1, 0])
472 ul_plot.append(vdrivetrain.U[0, 0])
473 ur_plot.append(vdrivetrain.U[1, 0])
474 left_gear_plot.append((vdrivetrain.left_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
475 right_gear_plot.append((vdrivetrain.right_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
476
477 fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
478 turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
479 if abs(fwd_velocity) < 0.0000001:
480 radius_plot.append(turn_velocity)
481 else:
482 radius_plot.append(turn_velocity / fwd_velocity)
483
484 # TODO(austin):
485 # Shifting compensation.
486
487 # Tighten the turn.
488 # Closed loop drive.
489
490 pylab.plot(t_plot, vl_plot, label='left velocity')
491 pylab.plot(t_plot, vr_plot, label='right velocity')
492 pylab.plot(t_plot, ul_plot, label='left voltage')
493 pylab.plot(t_plot, ur_plot, label='right voltage')
494 pylab.plot(t_plot, radius_plot, label='radius')
495 pylab.plot(t_plot, left_gear_plot, label='left gear high')
496 pylab.plot(t_plot, right_gear_plot, label='right gear high')
497 pylab.legend()
498 pylab.show()