blob: c19c88893c66374a2380da865259c291ecf940ef [file] [log] [blame]
Brian Silvermanc71537c2016-01-01 13:43:14 -08001#!/usr/bin/python
2
3import numpy
4import sys
5from frc971.control_loops.python import polytope
6from y2012.control_loops.python import drivetrain
7from frc971.control_loops.python import control_loop
8from frc971.control_loops.python import controls
Philipp Schrader9ffe2982016-12-07 20:51:08 -08009from frc971.control_loops.python.cim import CIM
Brian Silvermanc71537c2016-01-01 13:43:14 -080010from 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)
115 self.dt = 0.005
116 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
132 self.PlaceControllerPoles([0.8, 0.8])
133 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.R = self._drivetrain.R
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
181 self.dt = 0.005
182
183 self.R = numpy.matrix(
184 [[0.0],
185 [0.0]])
186
187 # ttrust is the comprimise between having full throttle negative inertia,
188 # and having no throttle negative inertia. A value of 0 is full throttle
189 # inertia. A value of 1 is no throttle negative inertia.
190 self.ttrust = 1.0
191
192 self.left_gear = VelocityDrivetrain.LOW
193 self.right_gear = VelocityDrivetrain.LOW
194 self.left_shifter_position = 0.0
195 self.right_shifter_position = 0.0
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800196 self.left_cim = CIM()
197 self.right_cim = CIM()
Brian Silvermanc71537c2016-01-01 13:43:14 -0800198
199 def IsInGear(self, gear):
200 return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
201
202 def MotorRPM(self, shifter_position, velocity):
203 if shifter_position > 0.5:
204 return (velocity / self.CurrentDrivetrain().G_high /
205 self.CurrentDrivetrain().r)
206 else:
207 return (velocity / self.CurrentDrivetrain().G_low /
208 self.CurrentDrivetrain().r)
209
210 def CurrentDrivetrain(self):
211 if self.left_shifter_position > 0.5:
212 if self.right_shifter_position > 0.5:
213 return self.drivetrain_high_high
214 else:
215 return self.drivetrain_high_low
216 else:
217 if self.right_shifter_position > 0.5:
218 return self.drivetrain_low_high
219 else:
220 return self.drivetrain_low_low
221
222 def SimShifter(self, gear, shifter_position):
223 if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
224 shifter_position = min(shifter_position + 0.5, 1.0)
225 else:
226 shifter_position = max(shifter_position - 0.5, 0.0)
227
228 if shifter_position == 1.0:
229 gear = VelocityDrivetrain.HIGH
230 elif shifter_position == 0.0:
231 gear = VelocityDrivetrain.LOW
232
233 return gear, shifter_position
234
235 def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
236 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
237 self.CurrentDrivetrain().r)
238 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
239 self.CurrentDrivetrain().r)
240 #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
241 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
242 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
243 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
244 self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
245 high_power = high_torque * high_omega
246 low_power = low_torque * low_omega
247 #if should_print:
248 # print gear_name, "High omega", high_omega, "Low omega", low_omega
249 # print gear_name, "High torque", high_torque, "Low torque", low_torque
250 # print gear_name, "High power", high_power, "Low power", low_power
251
252 # Shift algorithm improvements.
253 # TODO(aschuh):
254 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
255 # because you will end up slower than without shifting. Figure out how
256 # to include that info.
257 # If the driver is still in high gear, but isn't asking for the extra power
258 # from low gear, don't shift until he asks for it.
259 goal_gear_is_high = high_power > low_power
260 #goal_gear_is_high = True
261
262 if not self.IsInGear(current_gear):
263 glog.debug('%s Not in gear.', gear_name)
264 return current_gear
265 else:
266 is_high = current_gear is VelocityDrivetrain.HIGH
267 if is_high != goal_gear_is_high:
268 if goal_gear_is_high:
269 glog.debug('%s Shifting up.', gear_name)
270 return VelocityDrivetrain.SHIFTING_UP
271 else:
272 glog.debug('%s Shifting down.', gear_name)
273 return VelocityDrivetrain.SHIFTING_DOWN
274 else:
275 return current_gear
276
277 def FilterVelocity(self, throttle):
278 # Invert the plant to figure out how the velocity filter would have to work
279 # out in order to filter out the forwards negative inertia.
280 # This math assumes that the left and right power and velocity are equal.
281
282 # The throttle filter should filter such that the motor in the highest gear
283 # should be controlling the time constant.
284 # Do this by finding the index of FF that has the lowest value, and computing
285 # the sums using that index.
286 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
287 min_FF_sum_index = numpy.argmin(FF_sum)
288 min_FF_sum = FF_sum[min_FF_sum_index, 0]
289 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
290 # Compute the FF sum for high gear.
291 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
292
293 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
294 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
295 # - self.K[0, :].sum() * x_avg
296
297 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
298 # (self.K[0, :].sum() + self.FF[0, :].sum())
299
300 # U = (K + FF) * R - K * X
301 # (K + FF) ^-1 * (U + K * X) = R
302
303 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
304 # have the same velocity goal as high gear, and so that the robot will hold
305 # the same speed for the same throttle for all gears.
306 adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
307 return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
308 / (self.ttrust * min_K_sum + min_FF_sum))
309
310 def Update(self, throttle, steering):
311 # Shift into the gear which sends the most power to the floor.
312 # This is the same as sending the most torque down to the floor at the
313 # wheel.
314
315 self.left_gear = self.right_gear = True
316 if True:
317 self.left_gear = self.ComputeGear(self.X[0, 0], should_print=True,
318 current_gear=self.left_gear,
319 gear_name="left")
320 self.right_gear = self.ComputeGear(self.X[1, 0], should_print=True,
321 current_gear=self.right_gear,
322 gear_name="right")
323 if self.IsInGear(self.left_gear):
324 self.left_cim.X[0, 0] = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
325
326 if self.IsInGear(self.right_gear):
327 self.right_cim.X[0, 0] = self.MotorRPM(self.right_shifter_position, self.X[0, 0])
328
329 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
330 # Filter the throttle to provide a nicer response.
331 fvel = self.FilterVelocity(throttle)
332
333 # Constant radius means that angualar_velocity / linear_velocity = constant.
334 # Compute the left and right velocities.
335 steering_velocity = numpy.abs(fvel) * steering
336 left_velocity = fvel - steering_velocity
337 right_velocity = fvel + steering_velocity
338
339 # Write this constraint in the form of K * R = w
340 # angular velocity / linear velocity = constant
341 # (left - right) / (left + right) = constant
342 # left - right = constant * left + constant * right
343
344 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
345 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
346 # constant
347 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
348 # (-steering * sign(fvel)) = constant
349 # (-steering * sign(fvel)) * (left + right) = left - right
350 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
351
352 equality_k = numpy.matrix(
353 [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
354 equality_w = 0.0
355
356 self.R[0, 0] = left_velocity
357 self.R[1, 0] = right_velocity
358
359 # Construct a constraint on R by manipulating the constraint on U
360 # Start out with H * U <= k
361 # U = FF * R + K * (R - X)
362 # H * (FF * R + K * R - K * X) <= k
363 # H * (FF + K) * R <= k + H * K * X
364 R_poly = polytope.HPolytope(
365 self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
366 self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
367
368 # Limit R back inside the box.
369 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
370
371 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
372 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
373 else:
374 glog.debug('Not all in gear')
375 if not self.IsInGear(self.left_gear) and not self.IsInGear(self.right_gear):
376 # TODO(austin): Use battery volts here.
377 R_left = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
378 self.U_ideal[0, 0] = numpy.clip(
379 self.left_cim.K * (R_left - self.left_cim.X) + R_left / self.left_cim.Kv,
380 self.left_cim.U_min, self.left_cim.U_max)
381 self.left_cim.Update(self.U_ideal[0, 0])
382
383 R_right = self.MotorRPM(self.right_shifter_position, self.X[1, 0])
384 self.U_ideal[1, 0] = numpy.clip(
385 self.right_cim.K * (R_right - self.right_cim.X) + R_right / self.right_cim.Kv,
386 self.right_cim.U_min, self.right_cim.U_max)
387 self.right_cim.Update(self.U_ideal[1, 0])
388 else:
389 assert False
390
391 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
392
393 # TODO(austin): Model the robot as not accelerating when you shift...
394 # This hack only works when you shift at the same time.
395 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
396 self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
397
398 self.left_gear, self.left_shifter_position = self.SimShifter(
399 self.left_gear, self.left_shifter_position)
400 self.right_gear, self.right_shifter_position = self.SimShifter(
401 self.right_gear, self.right_shifter_position)
402
403 glog.debug('U is %s %s', str(self.U[0, 0]), str(self.U[1, 0]))
404 glog.debug('Left shifter %s %d Right shifter %s %d',
405 self.left_gear, self.left_shifter_position,
406 self.right_gear, self.right_shifter_position)
407
408
409def main(argv):
410 argv = FLAGS(argv)
411
412 vdrivetrain = VelocityDrivetrain()
413
414 if len(argv) != 5:
415 glog.fatal('Expected .h file name and .cc file name')
416 else:
417 namespaces = ['y2012', 'control_loops', 'drivetrain']
418 dog_loop_writer = control_loop.ControlLoopWriter(
419 "VelocityDrivetrain", [vdrivetrain.drivetrain_low_low,
420 vdrivetrain.drivetrain_low_high,
421 vdrivetrain.drivetrain_high_low,
422 vdrivetrain.drivetrain_high_high],
423 namespaces=namespaces)
424
425 dog_loop_writer.Write(argv[1], argv[2])
426
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800427 cim_writer = control_loop.ControlLoopWriter("CIM", [CIM()])
Brian Silvermanc71537c2016-01-01 13:43:14 -0800428
429 cim_writer.Write(argv[3], argv[4])
430 return
431
432 vl_plot = []
433 vr_plot = []
434 ul_plot = []
435 ur_plot = []
436 radius_plot = []
437 t_plot = []
438 left_gear_plot = []
439 right_gear_plot = []
440 vdrivetrain.left_shifter_position = 0.0
441 vdrivetrain.right_shifter_position = 0.0
442 vdrivetrain.left_gear = VelocityDrivetrain.LOW
443 vdrivetrain.right_gear = VelocityDrivetrain.LOW
444
445 glog.debug('K is %s', str(vdrivetrain.CurrentDrivetrain().K))
446
447 if vdrivetrain.left_gear is VelocityDrivetrain.HIGH:
448 glog.debug('Left is high')
449 else:
450 glog.debug('Left is low')
451 if vdrivetrain.right_gear is VelocityDrivetrain.HIGH:
452 glog.debug('Right is high')
453 else:
454 glog.debug('Right is low')
455
456 for t in numpy.arange(0, 1.7, vdrivetrain.dt):
457 if t < 0.5:
458 vdrivetrain.Update(throttle=0.00, steering=1.0)
459 elif t < 1.2:
460 vdrivetrain.Update(throttle=0.5, steering=1.0)
461 else:
462 vdrivetrain.Update(throttle=0.00, steering=1.0)
463 t_plot.append(t)
464 vl_plot.append(vdrivetrain.X[0, 0])
465 vr_plot.append(vdrivetrain.X[1, 0])
466 ul_plot.append(vdrivetrain.U[0, 0])
467 ur_plot.append(vdrivetrain.U[1, 0])
468 left_gear_plot.append((vdrivetrain.left_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
469 right_gear_plot.append((vdrivetrain.right_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
470
471 fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
472 turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
473 if abs(fwd_velocity) < 0.0000001:
474 radius_plot.append(turn_velocity)
475 else:
476 radius_plot.append(turn_velocity / fwd_velocity)
477
478 cim_velocity_plot = []
479 cim_voltage_plot = []
480 cim_time = []
Philipp Schrader9ffe2982016-12-07 20:51:08 -0800481 cim = CIM()
Brian Silvermanc71537c2016-01-01 13:43:14 -0800482 R = numpy.matrix([[300]])
483 for t in numpy.arange(0, 0.5, cim.dt):
484 U = numpy.clip(cim.K * (R - cim.X) + R / cim.Kv, cim.U_min, cim.U_max)
485 cim.Update(U)
486 cim_velocity_plot.append(cim.X[0, 0])
487 cim_voltage_plot.append(U[0, 0] * 10)
488 cim_time.append(t)
489 pylab.plot(cim_time, cim_velocity_plot, label='cim spinup')
490 pylab.plot(cim_time, cim_voltage_plot, label='cim voltage')
491 pylab.legend()
492 pylab.show()
493
494 # TODO(austin):
495 # Shifting compensation.
496
497 # Tighten the turn.
498 # Closed loop drive.
499
500 pylab.plot(t_plot, vl_plot, label='left velocity')
501 pylab.plot(t_plot, vr_plot, label='right velocity')
502 pylab.plot(t_plot, ul_plot, label='left voltage')
503 pylab.plot(t_plot, ur_plot, label='right voltage')
504 pylab.plot(t_plot, radius_plot, label='radius')
505 pylab.plot(t_plot, left_gear_plot, label='left gear high')
506 pylab.plot(t_plot, right_gear_plot, label='right gear high')
507 pylab.legend()
508 pylab.show()
509 return 0
510
511if __name__ == '__main__':
512 sys.exit(main(sys.argv))