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