blob: a45d73831218921a640a9582058d050f30367f88 [file] [log] [blame]
Austin Schuh085eab92020-11-26 13:54:51 -08001#!/usr/bin/python3
Campbell Crowley33e0e3d2017-12-27 17:55:40 -08002
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
Tyler Chatow6738c362019-02-16 14:12:30 -080013
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080014def CoerceGoal(region, K, w, R):
Tyler Chatow6738c362019-02-16 14:12:30 -080015 """Intersects a line with a region, and finds the closest point to R.
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080016
Tyler Chatow6738c362019-02-16 14:12:30 -080017 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
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080021
Tyler Chatow6738c362019-02-16 14:12:30 -080022 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.
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080027
Tyler Chatow6738c362019-02-16 14:12:30 -080028 Returns:
29 numpy.matrix (2 x 1), the point.
30 """
31 return DoCoerceGoal(region, K, w, R)[0]
32
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080033
34def DoCoerceGoal(region, K, w, R):
Tyler Chatow6738c362019-02-16 14:12:30 -080035 if region.IsInside(R):
36 return (R, True)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080037
Tyler Chatow6738c362019-02-16 14:12:30 -080038 perpendicular_vector = K.T / numpy.linalg.norm(K)
39 parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
40 [-perpendicular_vector[0, 0]]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080041
Tyler Chatow6738c362019-02-16 14:12:30 -080042 # We want to impose the constraint K * X = w on the polytope H * X <= k.
43 # We do this by breaking X up into parallel and perpendicular components to
44 # the half plane. This gives us the following equation.
45 #
46 # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
47 #
48 # Then, substitute this into the polytope.
49 #
50 # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
51 #
52 # Substitute K * X = w
53 #
54 # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
55 #
56 # Move all the knowns to the right side.
57 #
58 # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
59 #
60 # Let t = parallel.T \dot X, the component parallel to the surface.
61 #
62 # H * parallel * t <= k - H * perpendicular * w
63 #
64 # This is a polytope which we can solve, and use to figure out the range of X
65 # that we care about!
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080066
Tyler Chatow6738c362019-02-16 14:12:30 -080067 t_poly = polytope.HPolytope(region.H * parallel_vector,
68 region.k - region.H * perpendicular_vector * w)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080069
Tyler Chatow6738c362019-02-16 14:12:30 -080070 vertices = t_poly.Vertices()
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080071
Tyler Chatow6738c362019-02-16 14:12:30 -080072 if vertices.shape[0]:
73 # The region exists!
74 # Find the closest vertex
75 min_distance = numpy.infty
76 closest_point = None
77 for vertex in vertices:
78 point = parallel_vector * vertex + perpendicular_vector * w
79 length = numpy.linalg.norm(R - point)
80 if length < min_distance:
81 min_distance = length
82 closest_point = point
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080083
Tyler Chatow6738c362019-02-16 14:12:30 -080084 return (closest_point, True)
85 else:
86 # Find the vertex of the space that is closest to the line.
87 region_vertices = region.Vertices()
88 min_distance = numpy.infty
89 closest_point = None
90 for vertex in region_vertices:
91 point = vertex.T
92 length = numpy.abs((perpendicular_vector.T * point)[0, 0])
93 if length < min_distance:
94 min_distance = length
95 closest_point = point
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080096
Tyler Chatow6738c362019-02-16 14:12:30 -080097 return (closest_point, False)
98
Campbell Crowley33e0e3d2017-12-27 17:55:40 -080099
100class VelocityDrivetrainModel(control_loop.ControlLoop):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700101
Tyler Chatow6738c362019-02-16 14:12:30 -0800102 def __init__(self,
103 drivetrain_params,
104 left_low=True,
105 right_low=True,
106 name="VelocityDrivetrainModel"):
107 super(VelocityDrivetrainModel, self).__init__(name)
108 self._drivetrain = frc971.control_loops.python.drivetrain.Drivetrain(
109 left_low=left_low,
110 right_low=right_low,
111 drivetrain_params=drivetrain_params)
112 self.dt = drivetrain_params.dt
Ravago Jones5127ccc2022-07-31 16:32:45 -0700113 self.A_continuous = numpy.matrix([[
114 self._drivetrain.A_continuous[1, 1],
115 self._drivetrain.A_continuous[1, 3]
116 ],
117 [
118 self._drivetrain.A_continuous[3,
119 1],
120 self._drivetrain.A_continuous[3,
121 3]
122 ]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800123
Ravago Jones5127ccc2022-07-31 16:32:45 -0700124 self.B_continuous = numpy.matrix([[
125 self._drivetrain.B_continuous[1, 0],
126 self._drivetrain.B_continuous[1, 1]
127 ],
128 [
129 self._drivetrain.B_continuous[3,
130 0],
131 self._drivetrain.B_continuous[3,
132 1]
133 ]])
Tyler Chatow6738c362019-02-16 14:12:30 -0800134 self.C = numpy.matrix(numpy.eye(2))
135 self.D = numpy.matrix(numpy.zeros((2, 2)))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800136
Tyler Chatow6738c362019-02-16 14:12:30 -0800137 self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
138 self.B_continuous, self.dt)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800139
Tyler Chatow6738c362019-02-16 14:12:30 -0800140 # FF * X = U (steady state)
141 self.FF = self.B.I * (numpy.eye(2) - self.A)
Austin Schuh74425152018-12-21 11:37:14 +1100142
Tyler Chatow6738c362019-02-16 14:12:30 -0800143 self.PlaceControllerPoles(drivetrain_params.controller_poles)
144 # Build a kalman filter for the velocity. We don't care what the gains
145 # are, but the hybrid kalman filter that we want to write to disk to get
146 # access to A_continuous and B_continuous needs this for completeness.
Ravago Jones5127ccc2022-07-31 16:32:45 -0700147 self.Q_continuous = numpy.matrix([[(0.5**2.0), 0.0], [0.0,
148 (0.5**2.0)]])
149 self.R_continuous = numpy.matrix([[(0.1**2.0), 0.0], [0.0,
150 (0.1**2.0)]])
Tyler Chatow6738c362019-02-16 14:12:30 -0800151 self.PlaceObserverPoles(drivetrain_params.observer_poles)
Ravago Jones5127ccc2022-07-31 16:32:45 -0700152 _, _, self.Q, self.R = controls.kalmd(A_continuous=self.A_continuous,
153 B_continuous=self.B_continuous,
154 Q_continuous=self.Q_continuous,
155 R_continuous=self.R_continuous,
156 dt=self.dt)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800157
Ravago Jones5127ccc2022-07-31 16:32:45 -0700158 self.KalmanGain, self.P_steady_state = controls.kalman(A=self.A,
159 B=self.B,
160 C=self.C,
161 Q=self.Q,
162 R=self.R)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800163
Tyler Chatow6738c362019-02-16 14:12:30 -0800164 self.G_high = self._drivetrain.G_high
165 self.G_low = self._drivetrain.G_low
166 self.resistance = self._drivetrain.resistance
167 self.r = self._drivetrain.r
168 self.Kv = self._drivetrain.Kv
169 self.Kt = self._drivetrain.Kt
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800170
Tyler Chatow6738c362019-02-16 14:12:30 -0800171 self.U_max = self._drivetrain.U_max
172 self.U_min = self._drivetrain.U_min
173
174 @property
175 def robot_radius_l(self):
176 return self._drivetrain.robot_radius_l
177
178 @property
179 def robot_radius_r(self):
180 return self._drivetrain.robot_radius_r
181
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800182
183class VelocityDrivetrain(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800184 HIGH = 'high'
185 LOW = 'low'
186 SHIFTING_UP = 'up'
187 SHIFTING_DOWN = 'down'
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800188
Tyler Chatow6738c362019-02-16 14:12:30 -0800189 def __init__(self, drivetrain_params, name='VelocityDrivetrain'):
190 self.drivetrain_low_low = VelocityDrivetrainModel(
191 left_low=True,
192 right_low=True,
193 name=name + 'LowLow',
194 drivetrain_params=drivetrain_params)
195 self.drivetrain_low_high = VelocityDrivetrainModel(
196 left_low=True,
197 right_low=False,
198 name=name + 'LowHigh',
199 drivetrain_params=drivetrain_params)
200 self.drivetrain_high_low = VelocityDrivetrainModel(
201 left_low=False,
202 right_low=True,
203 name=name + 'HighLow',
204 drivetrain_params=drivetrain_params)
205 self.drivetrain_high_high = VelocityDrivetrainModel(
206 left_low=False,
207 right_low=False,
208 name=name + 'HighHigh',
209 drivetrain_params=drivetrain_params)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800210
Tyler Chatow6738c362019-02-16 14:12:30 -0800211 # X is [lvel, rvel]
212 self.X = numpy.matrix([[0.0], [0.0]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800213
Tyler Chatow6738c362019-02-16 14:12:30 -0800214 self.U_poly = polytope.HPolytope(
215 numpy.matrix([[1, 0], [-1, 0], [0, 1], [0, -1]]),
216 numpy.matrix([[12], [12], [12], [12]]))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800217
Tyler Chatow6738c362019-02-16 14:12:30 -0800218 self.U_max = numpy.matrix([[12.0], [12.0]])
219 self.U_min = numpy.matrix([[-12.0000000000], [-12.0000000000]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800220
Tyler Chatow6738c362019-02-16 14:12:30 -0800221 self.dt = 0.00505
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800222
Tyler Chatow6738c362019-02-16 14:12:30 -0800223 self.R = numpy.matrix([[0.0], [0.0]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800224
Tyler Chatow6738c362019-02-16 14:12:30 -0800225 self.U_ideal = numpy.matrix([[0.0], [0.0]])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800226
Tyler Chatow6738c362019-02-16 14:12:30 -0800227 # ttrust is the comprimise between having full throttle negative inertia,
228 # and having no throttle negative inertia. A value of 0 is full throttle
229 # inertia. A value of 1 is no throttle negative inertia.
230 self.ttrust = 1.0
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800231
Tyler Chatow6738c362019-02-16 14:12:30 -0800232 self.left_gear = VelocityDrivetrain.LOW
233 self.right_gear = VelocityDrivetrain.LOW
234 self.left_shifter_position = 0.0
235 self.right_shifter_position = 0.0
236 self.left_cim = CIM()
237 self.right_cim = CIM()
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800238
Tyler Chatow6738c362019-02-16 14:12:30 -0800239 def IsInGear(self, gear):
240 return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800241
Tyler Chatow6738c362019-02-16 14:12:30 -0800242 def MotorRPM(self, shifter_position, velocity):
243 if shifter_position > 0.5:
244 return (velocity / self.CurrentDrivetrain().G_high /
245 self.CurrentDrivetrain().r)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800246 else:
Tyler Chatow6738c362019-02-16 14:12:30 -0800247 return (velocity / self.CurrentDrivetrain().G_low /
248 self.CurrentDrivetrain().r)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800249
Tyler Chatow6738c362019-02-16 14:12:30 -0800250 def CurrentDrivetrain(self):
251 if self.left_shifter_position > 0.5:
252 if self.right_shifter_position > 0.5:
253 return self.drivetrain_high_high
254 else:
255 return self.drivetrain_high_low
256 else:
257 if self.right_shifter_position > 0.5:
258 return self.drivetrain_low_high
259 else:
260 return self.drivetrain_low_low
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800261
Tyler Chatow6738c362019-02-16 14:12:30 -0800262 def SimShifter(self, gear, shifter_position):
263 if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
264 shifter_position = min(shifter_position + 0.5, 1.0)
265 else:
266 shifter_position = max(shifter_position - 0.5, 0.0)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800267
Tyler Chatow6738c362019-02-16 14:12:30 -0800268 if shifter_position == 1.0:
269 gear = VelocityDrivetrain.HIGH
270 elif shifter_position == 0.0:
271 gear = VelocityDrivetrain.LOW
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800272
Tyler Chatow6738c362019-02-16 14:12:30 -0800273 return gear, shifter_position
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800274
Tyler Chatow6738c362019-02-16 14:12:30 -0800275 def ComputeGear(self,
276 wheel_velocity,
277 should_print=False,
278 current_gear=False,
279 gear_name=None):
280 high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
281 self.CurrentDrivetrain().r)
282 low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
283 self.CurrentDrivetrain().r)
284 #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
Ravago Jones5127ccc2022-07-31 16:32:45 -0700285 high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
286 self.CurrentDrivetrain().Kt /
287 self.CurrentDrivetrain().resistance)
288 low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
289 self.CurrentDrivetrain().Kt /
290 self.CurrentDrivetrain().resistance)
Tyler Chatow6738c362019-02-16 14:12:30 -0800291 high_power = high_torque * high_omega
292 low_power = low_torque * low_omega
293 #if should_print:
294 # print gear_name, "High omega", high_omega, "Low omega", low_omega
295 # print gear_name, "High torque", high_torque, "Low torque", low_torque
296 # print gear_name, "High power", high_power, "Low power", low_power
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800297
Tyler Chatow6738c362019-02-16 14:12:30 -0800298 # Shift algorithm improvements.
299 # TODO(aschuh):
300 # It takes time to shift. Shifting down for 1 cycle doesn't make sense
301 # because you will end up slower than without shifting. Figure out how
302 # to include that info.
303 # If the driver is still in high gear, but isn't asking for the extra power
304 # from low gear, don't shift until he asks for it.
305 goal_gear_is_high = high_power > low_power
306 #goal_gear_is_high = True
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800307
Tyler Chatow6738c362019-02-16 14:12:30 -0800308 if not self.IsInGear(current_gear):
309 glog.debug('%s Not in gear.', gear_name)
310 return current_gear
311 else:
312 is_high = current_gear is VelocityDrivetrain.HIGH
313 if is_high != goal_gear_is_high:
314 if goal_gear_is_high:
315 glog.debug('%s Shifting up.', gear_name)
316 return VelocityDrivetrain.SHIFTING_UP
317 else:
318 glog.debug('%s Shifting down.', gear_name)
319 return VelocityDrivetrain.SHIFTING_DOWN
320 else:
321 return current_gear
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800322
Tyler Chatow6738c362019-02-16 14:12:30 -0800323 def FilterVelocity(self, throttle):
324 # Invert the plant to figure out how the velocity filter would have to work
325 # out in order to filter out the forwards negative inertia.
326 # This math assumes that the left and right power and velocity are equal.
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800327
Tyler Chatow6738c362019-02-16 14:12:30 -0800328 # The throttle filter should filter such that the motor in the highest gear
329 # should be controlling the time constant.
330 # Do this by finding the index of FF that has the lowest value, and computing
331 # the sums using that index.
332 FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
333 min_FF_sum_index = numpy.argmin(FF_sum)
334 min_FF_sum = FF_sum[min_FF_sum_index, 0]
335 min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
336 # Compute the FF sum for high gear.
337 high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800338
Tyler Chatow6738c362019-02-16 14:12:30 -0800339 # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
340 # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
341 # - self.K[0, :].sum() * x_avg
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800342
Tyler Chatow6738c362019-02-16 14:12:30 -0800343 # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
344 # (self.K[0, :].sum() + self.FF[0, :].sum())
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800345
Tyler Chatow6738c362019-02-16 14:12:30 -0800346 # U = (K + FF) * R - K * X
347 # (K + FF) ^-1 * (U + K * X) = R
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800348
Tyler Chatow6738c362019-02-16 14:12:30 -0800349 # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
350 # have the same velocity goal as high gear, and so that the robot will hold
351 # the same speed for the same throttle for all gears.
352 adjusted_ff_voltage = numpy.clip(
353 throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
354 return ((adjusted_ff_voltage + self.ttrust * min_K_sum *
355 (self.X[0, 0] + self.X[1, 0]) / 2.0) /
356 (self.ttrust * min_K_sum + min_FF_sum))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800357
Tyler Chatow6738c362019-02-16 14:12:30 -0800358 def Update(self, throttle, steering):
359 # Shift into the gear which sends the most power to the floor.
360 # This is the same as sending the most torque down to the floor at the
361 # wheel.
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800362
Tyler Chatow6738c362019-02-16 14:12:30 -0800363 self.left_gear = self.right_gear = True
364 if True:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700365 self.left_gear = self.ComputeGear(self.X[0, 0],
366 should_print=True,
367 current_gear=self.left_gear,
368 gear_name="left")
369 self.right_gear = self.ComputeGear(self.X[1, 0],
370 should_print=True,
371 current_gear=self.right_gear,
372 gear_name="right")
Tyler Chatow6738c362019-02-16 14:12:30 -0800373 if self.IsInGear(self.left_gear):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700374 self.left_cim.X[0,
375 0] = self.MotorRPM(self.left_shifter_position,
376 self.X[0, 0])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800377
Tyler Chatow6738c362019-02-16 14:12:30 -0800378 if self.IsInGear(self.right_gear):
379 self.right_cim.X[0, 0] = self.MotorRPM(
380 self.right_shifter_position, self.X[0, 0])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800381
Tyler Chatow6738c362019-02-16 14:12:30 -0800382 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
383 # Filter the throttle to provide a nicer response.
384 fvel = self.FilterVelocity(throttle)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800385
Tyler Chatow6738c362019-02-16 14:12:30 -0800386 # Constant radius means that angualar_velocity / linear_velocity = constant.
387 # Compute the left and right velocities.
388 steering_velocity = numpy.abs(fvel) * steering
389 left_velocity = fvel - steering_velocity
390 right_velocity = fvel + steering_velocity
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800391
Tyler Chatow6738c362019-02-16 14:12:30 -0800392 # Write this constraint in the form of K * R = w
393 # angular velocity / linear velocity = constant
394 # (left - right) / (left + right) = constant
395 # left - right = constant * left + constant * right
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800396
Tyler Chatow6738c362019-02-16 14:12:30 -0800397 # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
398 # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
399 # constant
400 # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
401 # (-steering * sign(fvel)) = constant
402 # (-steering * sign(fvel)) * (left + right) = left - right
403 # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800404
Tyler Chatow6738c362019-02-16 14:12:30 -0800405 equality_k = numpy.matrix([[
406 1 + steering * numpy.sign(fvel),
407 -(1 - steering * numpy.sign(fvel))
408 ]])
409 equality_w = 0.0
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800410
Tyler Chatow6738c362019-02-16 14:12:30 -0800411 self.R[0, 0] = left_velocity
412 self.R[1, 0] = right_velocity
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800413
Tyler Chatow6738c362019-02-16 14:12:30 -0800414 # Construct a constraint on R by manipulating the constraint on U
415 # Start out with H * U <= k
416 # U = FF * R + K * (R - X)
417 # H * (FF * R + K * R - K * X) <= k
418 # H * (FF + K) * R <= k + H * K * X
419 R_poly = polytope.HPolytope(
420 self.U_poly.H *
421 (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
422 self.U_poly.k +
423 self.U_poly.H * self.CurrentDrivetrain().K * self.X)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800424
Tyler Chatow6738c362019-02-16 14:12:30 -0800425 # Limit R back inside the box.
426 self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
427
428 FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
Ravago Jones5127ccc2022-07-31 16:32:45 -0700429 self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R -
430 self.X) + FF_volts
Tyler Chatow6738c362019-02-16 14:12:30 -0800431 else:
432 glog.debug('Not all in gear')
433 if not self.IsInGear(self.left_gear) and not self.IsInGear(
434 self.right_gear):
435 # TODO(austin): Use battery volts here.
Ravago Jones5127ccc2022-07-31 16:32:45 -0700436 R_left = self.MotorRPM(self.left_shifter_position, self.X[0,
437 0])
Tyler Chatow6738c362019-02-16 14:12:30 -0800438 self.U_ideal[0, 0] = numpy.clip(
439 self.left_cim.K * (R_left - self.left_cim.X) +
440 R_left / self.left_cim.Kv, self.left_cim.U_min,
441 self.left_cim.U_max)
442 self.left_cim.Update(self.U_ideal[0, 0])
443
Ravago Jones5127ccc2022-07-31 16:32:45 -0700444 R_right = self.MotorRPM(self.right_shifter_position, self.X[1,
445 0])
Tyler Chatow6738c362019-02-16 14:12:30 -0800446 self.U_ideal[1, 0] = numpy.clip(
447 self.right_cim.K * (R_right - self.right_cim.X) +
448 R_right / self.right_cim.Kv, self.right_cim.U_min,
449 self.right_cim.U_max)
450 self.right_cim.Update(self.U_ideal[1, 0])
451 else:
452 assert False
453
454 self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
455
456 # TODO(austin): Model the robot as not accelerating when you shift...
457 # This hack only works when you shift at the same time.
458 if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
459 self.X = self.CurrentDrivetrain(
460 ).A * self.X + self.CurrentDrivetrain().B * self.U
461
462 self.left_gear, self.left_shifter_position = self.SimShifter(
463 self.left_gear, self.left_shifter_position)
464 self.right_gear, self.right_shifter_position = self.SimShifter(
465 self.right_gear, self.right_shifter_position)
466
467 glog.debug('U is %s %s', str(self.U[0, 0]), str(self.U[1, 0]))
468 glog.debug('Left shifter %s %d Right shifter %s %d', self.left_gear,
469 self.left_shifter_position, self.right_gear,
470 self.right_shifter_position)
471
472
473def WritePolyDrivetrain(drivetrain_files,
474 motor_files,
475 hybrid_files,
476 year_namespace,
477 drivetrain_params,
Austin Schuh74425152018-12-21 11:37:14 +1100478 scalar_type='double'):
Tyler Chatow6738c362019-02-16 14:12:30 -0800479 vdrivetrain = VelocityDrivetrain(drivetrain_params)
Ravago Jones5127ccc2022-07-31 16:32:45 -0700480 hybrid_vdrivetrain = VelocityDrivetrain(drivetrain_params,
481 name="HybridVelocityDrivetrain")
Tyler Chatow6738c362019-02-16 14:12:30 -0800482 if isinstance(year_namespace, list):
483 namespaces = year_namespace
484 else:
485 namespaces = [year_namespace, 'control_loops', 'drivetrain']
Ravago Jones5127ccc2022-07-31 16:32:45 -0700486 dog_loop_writer = control_loop.ControlLoopWriter("VelocityDrivetrain", [
487 vdrivetrain.drivetrain_low_low, vdrivetrain.drivetrain_low_high,
488 vdrivetrain.drivetrain_high_low, vdrivetrain.drivetrain_high_high
489 ],
490 namespaces=namespaces,
491 scalar_type=scalar_type)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800492
Tyler Chatow6738c362019-02-16 14:12:30 -0800493 dog_loop_writer.Write(drivetrain_files[0], drivetrain_files[1])
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800494
Tyler Chatow6738c362019-02-16 14:12:30 -0800495 hybrid_loop_writer = control_loop.ControlLoopWriter(
496 "HybridVelocityDrivetrain", [
497 hybrid_vdrivetrain.drivetrain_low_low,
498 hybrid_vdrivetrain.drivetrain_low_high,
499 hybrid_vdrivetrain.drivetrain_high_low,
500 hybrid_vdrivetrain.drivetrain_high_high
501 ],
502 namespaces=namespaces,
503 scalar_type=scalar_type,
504 plant_type='StateFeedbackHybridPlant',
505 observer_type='HybridKalman')
Austin Schuh74425152018-12-21 11:37:14 +1100506
Tyler Chatow6738c362019-02-16 14:12:30 -0800507 hybrid_loop_writer.Write(hybrid_files[0], hybrid_files[1])
Austin Schuh74425152018-12-21 11:37:14 +1100508
Ravago Jones5127ccc2022-07-31 16:32:45 -0700509 cim_writer = control_loop.ControlLoopWriter("CIM", [CIM()],
510 scalar_type=scalar_type)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800511
Tyler Chatow6738c362019-02-16 14:12:30 -0800512 cim_writer.Write(motor_files[0], motor_files[1])
513
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800514
515def PlotPolyDrivetrainMotions(drivetrain_params):
Tyler Chatow6738c362019-02-16 14:12:30 -0800516 vdrivetrain = VelocityDrivetrain(drivetrain_params)
517 vl_plot = []
518 vr_plot = []
519 ul_plot = []
520 ur_plot = []
521 radius_plot = []
522 t_plot = []
523 left_gear_plot = []
524 right_gear_plot = []
525 vdrivetrain.left_shifter_position = 0.0
526 vdrivetrain.right_shifter_position = 0.0
527 vdrivetrain.left_gear = VelocityDrivetrain.LOW
528 vdrivetrain.right_gear = VelocityDrivetrain.LOW
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800529
Tyler Chatow6738c362019-02-16 14:12:30 -0800530 glog.debug('K is %s', str(vdrivetrain.CurrentDrivetrain().K))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800531
Tyler Chatow6738c362019-02-16 14:12:30 -0800532 if vdrivetrain.left_gear is VelocityDrivetrain.HIGH:
533 glog.debug('Left is high')
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800534 else:
Tyler Chatow6738c362019-02-16 14:12:30 -0800535 glog.debug('Left is low')
536 if vdrivetrain.right_gear is VelocityDrivetrain.HIGH:
537 glog.debug('Right is high')
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800538 else:
Tyler Chatow6738c362019-02-16 14:12:30 -0800539 glog.debug('Right is low')
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800540
Tyler Chatow6738c362019-02-16 14:12:30 -0800541 for t in numpy.arange(0, 1.7, vdrivetrain.dt):
542 if t < 0.5:
543 vdrivetrain.Update(throttle=0.00, steering=1.0)
544 elif t < 1.2:
545 vdrivetrain.Update(throttle=0.5, steering=1.0)
546 else:
547 vdrivetrain.Update(throttle=0.00, steering=1.0)
548 t_plot.append(t)
549 vl_plot.append(vdrivetrain.X[0, 0])
550 vr_plot.append(vdrivetrain.X[1, 0])
551 ul_plot.append(vdrivetrain.U[0, 0])
552 ur_plot.append(vdrivetrain.U[1, 0])
553 left_gear_plot.append(
554 (vdrivetrain.left_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
555 right_gear_plot.append(
556 (vdrivetrain.right_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800557
Tyler Chatow6738c362019-02-16 14:12:30 -0800558 fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
559 turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
560 if abs(fwd_velocity) < 0.0000001:
561 radius_plot.append(turn_velocity)
562 else:
563 radius_plot.append(turn_velocity / fwd_velocity)
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800564
Tyler Chatow6738c362019-02-16 14:12:30 -0800565 # TODO(austin):
566 # Shifting compensation.
567
568 # Tighten the turn.
569 # Closed loop drive.
570
571 pylab.plot(t_plot, vl_plot, label='left velocity')
572 pylab.plot(t_plot, vr_plot, label='right velocity')
573 pylab.plot(t_plot, ul_plot, label='left voltage')
574 pylab.plot(t_plot, ur_plot, label='right voltage')
575 pylab.plot(t_plot, radius_plot, label='radius')
576 pylab.plot(t_plot, left_gear_plot, label='left gear high')
577 pylab.plot(t_plot, right_gear_plot, label='right gear high')
578 pylab.legend()
579 pylab.show()