blob: 43b1c30f6e0fc941765f8badbe748ee0b4560394 [file] [log] [blame]
Austin Schuhec7f06d2019-01-04 07:47:15 +11001#include "frc971/control_loops/drivetrain/trajectory.h"
2
3#include <chrono>
4
5#include "Eigen/Dense"
Austin Schuhec7f06d2019-01-04 07:47:15 +11006#include "frc971/control_loops/c2d.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -07007#include "frc971/control_loops/dlqr.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +11008#include "frc971/control_loops/drivetrain/distance_spline.h"
9#include "frc971/control_loops/drivetrain/drivetrain_config.h"
10#include "frc971/control_loops/hybrid_state_feedback_loop.h"
11#include "frc971/control_loops/state_feedback_loop.h"
12
13namespace frc971 {
14namespace control_loops {
15namespace drivetrain {
16
17Trajectory::Trajectory(const DistanceSpline *spline,
18 const DrivetrainConfig<double> &config, double vmax,
19 int num_distance)
20 : spline_(spline),
James Kuszmaulea314d92019-02-18 19:45:06 -080021 velocity_drivetrain_(::std::unique_ptr<
22 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
23 HybridKalman<2, 2, 2>>>(
24 new StateFeedbackLoop<2, 2, 2, double,
25 StateFeedbackHybridPlant<2, 2, 2>,
26 HybridKalman<2, 2, 2>>(
27 config.make_hybrid_drivetrain_velocity_loop()))),
Austin Schuhec7f06d2019-01-04 07:47:15 +110028 robot_radius_l_(config.robot_radius),
29 robot_radius_r_(config.robot_radius),
James Kuszmaulea314d92019-02-18 19:45:06 -080030 longitudinal_acceleration_(3.0),
Austin Schuhec7f06d2019-01-04 07:47:15 +110031 lateral_acceleration_(2.0),
32 Tlr_to_la_((::Eigen::Matrix<double, 2, 2>() << 0.5, 0.5,
33 -1.0 / (robot_radius_l_ + robot_radius_r_),
James Kuszmaulea314d92019-02-18 19:45:06 -080034 1.0 / (robot_radius_l_ + robot_radius_r_)).finished()),
Austin Schuhec7f06d2019-01-04 07:47:15 +110035 Tla_to_lr_(Tlr_to_la_.inverse()),
Austin Schuhe73a9052019-01-07 12:16:17 -080036 plan_(num_distance == 0
37 ? ::std::max(100, static_cast<int>(spline_->length() / 0.0025))
38 : num_distance,
39 vmax),
40 plan_segment_type_(plan_.size() - 1, SegmentType::VELOCITY_LIMITED) {}
Austin Schuhec7f06d2019-01-04 07:47:15 +110041
42void Trajectory::LateralAccelPass() {
43 for (size_t i = 0; i < plan_.size(); ++i) {
44 const double distance = Distance(i);
James Kuszmaulea314d92019-02-18 19:45:06 -080045 const double velocity_limit = LateralVelocityCurvature(distance);
46 if (velocity_limit < plan_[i]) {
47 plan_[i] = velocity_limit;
48 plan_segment_type_[i] = CURVATURE_LIMITED;
49 }
Austin Schuhec7f06d2019-01-04 07:47:15 +110050 }
51}
52
James Kuszmaulea314d92019-02-18 19:45:06 -080053void Trajectory::VoltageFeasibilityPass(VoltageLimit limit_type) {
54 for (size_t i = 0; i < plan_.size(); ++i) {
55 const double distance = Distance(i);
56 const double velocity_limit = VoltageVelocityLimit(distance, limit_type);
57 if (velocity_limit < plan_[i]) {
58 plan_[i] = velocity_limit;
59 plan_segment_type_[i] = VOLTAGE_LIMITED;
60 }
61 }
62}
63
64double Trajectory::BestAcceleration(double x, double v, bool backwards) {
Austin Schuhec7f06d2019-01-04 07:47:15 +110065 ::Eigen::Matrix<double, 2, 1> K3;
66 ::Eigen::Matrix<double, 2, 1> K4;
67 ::Eigen::Matrix<double, 2, 1> K5;
68 K345(x, &K3, &K4, &K5);
69
Austin Schuhec7f06d2019-01-04 07:47:15 +110070 // Now, solve for all a's and find the best one which meets our criteria.
James Kuszmaulea314d92019-02-18 19:45:06 -080071 const ::Eigen::Matrix<double, 2, 1> C = K3 * v * v + K4 * v;
72 double min_voltage_accel = ::std::numeric_limits<double>::infinity();
73 double max_voltage_accel = -min_voltage_accel;
Austin Schuhec7f06d2019-01-04 07:47:15 +110074 for (const double a : {(voltage_limit_ - C(0, 0)) / K5(0, 0),
75 (voltage_limit_ - C(1, 0)) / K5(1, 0),
76 (-voltage_limit_ - C(0, 0)) / K5(0, 0),
77 (-voltage_limit_ - C(1, 0)) / K5(1, 0)}) {
78 const ::Eigen::Matrix<double, 2, 1> U = K5 * a + K3 * v * v + K4 * v;
79 if ((U.array().abs() < voltage_limit_ + 1e-6).all()) {
James Kuszmaulea314d92019-02-18 19:45:06 -080080 min_voltage_accel = ::std::min(a, min_voltage_accel);
81 max_voltage_accel = ::std::max(a, max_voltage_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +110082 }
83 }
James Kuszmaulea314d92019-02-18 19:45:06 -080084 double best_accel = backwards ? min_voltage_accel : max_voltage_accel;
Austin Schuhec7f06d2019-01-04 07:47:15 +110085
James Kuszmaulea314d92019-02-18 19:45:06 -080086 double min_friction_accel, max_friction_accel;
87 FrictionLngAccelLimits(x, v, &min_friction_accel, &max_friction_accel);
88 if (backwards) {
89 best_accel = ::std::max(best_accel, min_friction_accel);
90 } else {
91 best_accel = ::std::min(best_accel, max_friction_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +110092 }
James Kuszmaulea314d92019-02-18 19:45:06 -080093
James Kuszmaul66b78042020-02-23 15:30:51 -080094 // Ideally, the max would never be less than the min, but due to the way that
95 // the runge kutta solver works, it sometimes ticks over the edge.
96 if (max_friction_accel < min_friction_accel) {
97 VLOG(1) << "At x " << x << " v " << v << " min fric acc "
98 << min_friction_accel << " max fric accel " << max_friction_accel;
99 }
100 if (best_accel < min_voltage_accel || best_accel > max_voltage_accel) {
101 LOG(WARNING) << "Viable friction limits and viable voltage limits do not "
102 "overlap (x: " << x << ", v: " << v
103 << ", backwards: " << backwards
104 << ") best_accel = " << best_accel << ", min voltage "
105 << min_voltage_accel << ", max voltage " << max_voltage_accel
106 << " min friction " << min_friction_accel << " max friction "
107 << max_friction_accel << ".";
108
James Kuszmaulea314d92019-02-18 19:45:06 -0800109 // Don't actually do anything--this will just result in attempting to drive
110 // higher voltages thatn we have available. In practice, that'll probably
111 // work out fine.
112 }
113
114 return best_accel;
115}
116
117double Trajectory::LateralVelocityCurvature(double distance) const {
118 // To calculate these constraints, we first note that:
119 // wheel accels = K2 * v_robot' + K1 * v_robot^2
120 // All that this logic does is solve for v_robot, leaving v_robot' free,
121 // assuming that the wheels are at their limits.
122 // To do this, we:
123 //
124 // 1) Determine what the wheel accels will be at the limit--since we have
125 // two free variables (v_robot, v_robot'), both wheels will be at their
126 // limits--if in a sufficiently tight turn (such that the signs of the
127 // coefficients of K2 are different), then the wheels will be accelerating
128 // in opposite directions; otherwise, they accelerate in the same direction.
129 // The magnitude of these per-wheel accelerations is a function of velocity,
130 // so it must also be solved for.
131 //
132 // 2) Eliminate that v_robot' term (since we don't care
133 // about it) by multiplying be a "K2prime" term (where K2prime * K2 = 0) on
134 // both sides of the equation.
135 //
136 // 3) Solving the relatively tractable remaining equation, which is
137 // basically just grouping all the terms together in one spot and taking the
138 // 4th root of everything.
139 const double dtheta = spline_->DTheta(distance);
140 const ::Eigen::Matrix<double, 1, 2> K2prime =
141 K2(dtheta).transpose() *
142 (::Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
143 // Calculate whether the wheels are spinning in opposite directions.
144 const bool opposites = K2prime(0) * K2prime(1) < 0;
145 const ::Eigen::Matrix<double, 2, 1> K1calc = K1(spline_->DDTheta(distance));
146 const double lat_accel_squared =
147 ::std::pow(dtheta / lateral_acceleration_, 2);
148 const double curvature_change_term =
149 (K2prime * K1calc).value() /
150 (K2prime *
151 (::Eigen::Matrix<double, 2, 1>() << 1.0, (opposites ? -1.0 : 1.0))
152 .finished() *
153 longitudinal_acceleration_)
154 .value();
155 const double vel_inv = ::std::sqrt(
156 ::std::sqrt(::std::pow(curvature_change_term, 2) + lat_accel_squared));
157 if (vel_inv == 0.0) {
158 return ::std::numeric_limits<double>::infinity();
159 }
160 return 1.0 / vel_inv;
161}
162
163void Trajectory::FrictionLngAccelLimits(double x, double v, double *min_accel,
164 double *max_accel) const {
165 // First, calculate the max longitudinal acceleration that can be achieved
166 // by either wheel given the friction elliipse that we have.
167 const double lateral_acceleration = v * v * spline_->DDXY(x).norm();
168 const double max_wheel_lng_accel_squared =
169 1.0 - ::std::pow(lateral_acceleration / lateral_acceleration_, 2.0);
170 if (max_wheel_lng_accel_squared < 0.0) {
James Kuszmaul66b78042020-02-23 15:30:51 -0800171 VLOG(1) << "Something (probably Runge-Kutta) queried invalid velocity " << v
172 << " at distance " << x;
James Kuszmaulea314d92019-02-18 19:45:06 -0800173 // If we encounter this, it means that the Runge-Kutta has attempted to
174 // sample points a bit past the edge of the friction boundary. If so, we
175 // gradually ramp the min/max accels to be more and more incorrect (note
176 // how min_accel > max_accel if we reach this case) to avoid causing any
177 // numerical issues.
178 *min_accel =
179 ::std::sqrt(-max_wheel_lng_accel_squared) * longitudinal_acceleration_;
180 *max_accel = -*min_accel;
181 return;
182 }
183 *min_accel = -::std::numeric_limits<double>::infinity();
184 *max_accel = ::std::numeric_limits<double>::infinity();
185
186 // Calculate max/min accelerations by calculating what the robots overall
187 // longitudinal acceleration would be if each wheel were running at the max
188 // forwards/backwards longitudinal acceleration.
189 const double max_wheel_lng_accel =
190 longitudinal_acceleration_ * ::std::sqrt(max_wheel_lng_accel_squared);
191 const ::Eigen::Matrix<double, 2, 1> K1v2 = K1(spline_->DDTheta(x)) * v * v;
192 const ::Eigen::Matrix<double, 2, 1> K2inv =
193 K2(spline_->DTheta(x)).cwiseInverse();
194 // Store the accelerations of the robot corresponding to each wheel being at
195 // the max/min acceleration. The first coefficient in each vector
196 // corresponds to the left wheel, the second to the right wheel.
197 const ::Eigen::Matrix<double, 2, 1> accels1 =
198 K2inv.array() * (-K1v2.array() + max_wheel_lng_accel);
199 const ::Eigen::Matrix<double, 2, 1> accels2 =
200 K2inv.array() * (-K1v2.array() - max_wheel_lng_accel);
201
202 // If either term is non-finite, that suggests that a term of K2 is zero
203 // (which is physically possible when turning such that one wheel is
204 // stationary), so just ignore that side of the drivetrain.
205 if (::std::isfinite(accels1(0))) {
206 // The inner max/min in this case determines which of the two cases (+ or
207 // - acceleration on the left wheel) we care about--in a sufficiently
208 // tight turning radius, the left hweel may be accelerating backwards when
209 // the robot as a whole accelerates forwards. We then use that
210 // acceleration to bound the min/max accel.
211 *min_accel = ::std::max(*min_accel, ::std::min(accels1(0), accels2(0)));
212 *max_accel = ::std::min(*max_accel, ::std::max(accels1(0), accels2(0)));
213 }
214 // Same logic as previous if-statement, but for the right wheel.
215 if (::std::isfinite(accels1(1))) {
216 *min_accel = ::std::max(*min_accel, ::std::min(accels1(1), accels2(1)));
217 *max_accel = ::std::min(*max_accel, ::std::max(accels1(1), accels2(1)));
218 }
219}
220
221double Trajectory::VoltageVelocityLimit(
222 double distance, VoltageLimit limit_type,
223 Eigen::Matrix<double, 2, 1> *constraint_voltages) const {
224 // To sketch an outline of the math going on here, we start with the basic
225 // dynamics of the robot along the spline:
226 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot + B * U
227 // We need to determine the maximum v_robot given constrained U and free
228 // v_robot'.
229 // Similarly to the friction constraints, we accomplish this by first
230 // multiplying by a K2prime term to eliminate the v_robot' term.
231 // As with the friction constraints, we also know that the limits will occur
232 // when both sides of the drivetrain are driven at their max magnitude
233 // voltages, although they may be driven at different signs.
234 // Once we determine whether the voltages match signs, we still have to
235 // consider both possible pairings (technically we could probably
236 // predetermine which pairing, e.g. +/- or -/+, we acre about, but we don't
237 // need to).
238 //
239 // For each pairing, we then get to solve a quadratic formula for the robot
240 // velocity at those voltages. This gives us up to 4 solutions, of which
241 // up to 3 will give us positive velocities; each solution velocity
242 // corresponds to a transition from feasibility to infeasibility, where a
243 // velocity of zero is always feasible, and there will always be 0, 1, or 3
244 // positive solutions. Among the positive solutions, we take both the min
245 // and the max--the min will be the highest velocity such that all
246 // velocities between zero and that velocity are valid; the max will be
247 // the highest feasible velocity. Which we return depends on what the
248 // limit_type is.
249 //
250 // Sketching the actual math:
251 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot +/- B * U_max
252 // K2prime * K1 * v_robot^2 = K2prime * (A * K2 * v_robot +/- B * U_max)
253 // a v_robot^2 + b v_robot +/- c = 0
254 const ::Eigen::Matrix<double, 2, 2> B =
255 velocity_drivetrain_->plant().coefficients().B_continuous;
256 const double dtheta = spline_->DTheta(distance);
257 const ::Eigen::Matrix<double, 2, 1> BinvK2 = B.inverse() * K2(dtheta);
258 // Because voltages can actually impact *both* wheels, in order to determine
259 // whether the voltages will have opposite signs, we need to use B^-1 * K2.
260 const bool opposite_voltages = BinvK2(0) * BinvK2(1) > 0.0;
261 const ::Eigen::Matrix<double, 1, 2> K2prime =
262 K2(dtheta).transpose() *
263 (::Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
264 const double a = K2prime * K1(spline_->DDTheta(distance));
265 const double b = -K2prime *
266 velocity_drivetrain_->plant().coefficients().A_continuous *
267 K2(dtheta);
268 const ::Eigen::Matrix<double, 1, 2> c_coeff = -K2prime * B;
269 // Calculate the "positive" version of the voltage limits we will use.
270 const ::Eigen::Matrix<double, 2, 1> abs_volts =
271 voltage_limit_ *
272 (::Eigen::Matrix<double, 2, 1>() << 1.0, (opposite_voltages ? -1.0 : 1.0))
273 .finished();
274
275 double min_valid_vel = ::std::numeric_limits<double>::infinity();
276 if (limit_type == VoltageLimit::kAggressive) {
277 min_valid_vel = 0.0;
278 }
279 // Iterate over both possibilites for +/- voltage, and solve the quadratic
280 // formula. For every positive solution, adjust the velocity limit
281 // appropriately.
282 for (const double sign : {1.0, -1.0}) {
283 const ::Eigen::Matrix<double, 2, 1> U = sign * abs_volts;
284 const double prev_vel = min_valid_vel;
285 const double c = c_coeff * U;
286 const double determinant = b * b - 4 * a * c;
287 if (a == 0) {
288 // If a == 0, that implies we are on a constant curvature path, in which
289 // case we just have b * v + c = 0.
290 // Note that if -b * c > 0.0, then vel will be greater than zero and b
291 // will be non-zero.
292 if (-b * c > 0.0) {
293 const double vel = -c / b;
294 if (limit_type == VoltageLimit::kConservative) {
295 min_valid_vel = ::std::min(min_valid_vel, vel);
296 } else {
297 min_valid_vel = ::std::max(min_valid_vel, vel);
298 }
299 } else if (b == 0) {
300 // If a and b are zero, then we are travelling in a straight line and
301 // have no voltage-based velocity constraints.
302 min_valid_vel = ::std::numeric_limits<double>::infinity();
303 }
304 } else if (determinant > 0) {
305 const double sqrt_determinant = ::std::sqrt(determinant);
306 const double high_vel = (-b + sqrt_determinant) / (2.0 * a);
307 const double low_vel = (-b - sqrt_determinant) / (2.0 * a);
308 if (low_vel > 0) {
309 if (limit_type == VoltageLimit::kConservative) {
310 min_valid_vel = ::std::min(min_valid_vel, low_vel);
311 } else {
312 min_valid_vel = ::std::max(min_valid_vel, low_vel);
313 }
314 }
315 if (high_vel > 0) {
316 if (limit_type == VoltageLimit::kConservative) {
317 min_valid_vel = ::std::min(min_valid_vel, high_vel);
318 } else {
319 min_valid_vel = ::std::max(min_valid_vel, high_vel);
320 }
321 }
322 } else if (determinant == 0 && -b * a > 0) {
323 const double vel = -b / (2.0 * a);
324 if (vel > 0.0) {
325 if (limit_type == VoltageLimit::kConservative) {
326 min_valid_vel = ::std::min(min_valid_vel, vel);
327 } else {
328 min_valid_vel = ::std::max(min_valid_vel, vel);
329 }
330 }
331 }
332 if (constraint_voltages != nullptr && prev_vel != min_valid_vel) {
333 *constraint_voltages = U;
334 }
335 }
336 return min_valid_vel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100337}
338
339void Trajectory::ForwardPass() {
340 plan_[0] = 0.0;
341 const double delta_distance = Distance(1) - Distance(0);
342 for (size_t i = 0; i < plan_.size() - 1; ++i) {
343 const double distance = Distance(i);
344
345 // Integrate our acceleration forward one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800346 const double new_plan_velocity = IntegrateAccelForDistance(
347 [this](double x, double v) { return ForwardAcceleration(x, v); },
348 plan_[i], distance, delta_distance);
349
James Kuszmaulea314d92019-02-18 19:45:06 -0800350 if (new_plan_velocity <= plan_[i + 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800351 plan_[i + 1] = new_plan_velocity;
352 plan_segment_type_[i] = SegmentType::ACCELERATION_LIMITED;
353 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100354 }
355}
356
Austin Schuhec7f06d2019-01-04 07:47:15 +1100357void Trajectory::BackwardPass() {
358 const double delta_distance = Distance(0) - Distance(1);
359 plan_.back() = 0.0;
360 for (size_t i = plan_.size() - 1; i > 0; --i) {
361 const double distance = Distance(i);
362
363 // Integrate our deceleration back one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800364 const double new_plan_velocity = IntegrateAccelForDistance(
365 [this](double x, double v) { return BackwardAcceleration(x, v); },
366 plan_[i], distance, delta_distance);
367
James Kuszmaulea314d92019-02-18 19:45:06 -0800368 if (new_plan_velocity <= plan_[i - 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800369 plan_[i - 1] = new_plan_velocity;
370 plan_segment_type_[i - 1] = SegmentType::DECELERATION_LIMITED;
371 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100372 }
373}
374
375::Eigen::Matrix<double, 3, 1> Trajectory::FFAcceleration(double distance) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800376 if (distance < 0.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100377 // Make sure we don't end up off the beginning of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800378 distance = 0.0;
379 } else if (distance > length()) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100380 // Make sure we don't end up off the end of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800381 distance = length();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100382 }
Austin Schuhe73a9052019-01-07 12:16:17 -0800383 const size_t before_index = DistanceToSegment(distance);
384 const size_t after_index = before_index + 1;
385
Austin Schuhec7f06d2019-01-04 07:47:15 +1100386 const double before_distance = Distance(before_index);
387 const double after_distance = Distance(after_index);
388
Austin Schuhec7f06d2019-01-04 07:47:15 +1100389 // And then also make sure we aren't curvature limited.
390 const double vcurvature = LateralVelocityCurvature(distance);
391
392 double acceleration;
393 double velocity;
James Kuszmaulea314d92019-02-18 19:45:06 -0800394 // TODO(james): While technically correct for sufficiently small segment
395 // steps, this method of switching between limits has a tendency to produce
396 // sudden jumps in acceelrations, which is undesirable.
Austin Schuhe73a9052019-01-07 12:16:17 -0800397 switch (plan_segment_type_[DistanceToSegment(distance)]) {
398 case SegmentType::VELOCITY_LIMITED:
399 acceleration = 0.0;
400 velocity = (plan_[before_index] + plan_[after_index]) / 2.0;
401 // TODO(austin): Accelerate or decelerate until we hit the limit in the
402 // time slice. Otherwise our acceleration will be lying for this slice.
403 // Do note, we've got small slices so the effect will be small.
404 break;
405 case SegmentType::CURVATURE_LIMITED:
406 velocity = vcurvature;
James Kuszmaulea314d92019-02-18 19:45:06 -0800407 FrictionLngAccelLimits(distance, velocity, &acceleration, &acceleration);
408 break;
409 case SegmentType::VOLTAGE_LIMITED:
410 // Normally, we expect that voltage limited plans will all get dominated
411 // by the acceleration/deceleration limits. This may not always be true;
412 // if we ever encounter this error, we just need to back out what the
413 // accelerations would be in this case.
414 LOG(FATAL) << "Unexpectedly got VOLTAGE_LIMITED plan.";
Austin Schuhe73a9052019-01-07 12:16:17 -0800415 break;
416 case SegmentType::ACCELERATION_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800417 // TODO(james): The integration done here and in the DECELERATION_LIMITED
418 // can technically cause us to violate friction constraints. We currently
419 // don't do anything about it to avoid causing sudden jumps in voltage,
420 // but we probably *should* at some point.
Austin Schuhe73a9052019-01-07 12:16:17 -0800421 velocity = IntegrateAccelForDistance(
422 [this](double x, double v) { return ForwardAcceleration(x, v); },
423 plan_[before_index], before_distance, distance - before_distance);
424 acceleration = ForwardAcceleration(distance, velocity);
425 break;
426 case SegmentType::DECELERATION_LIMITED:
427 velocity = IntegrateAccelForDistance(
428 [this](double x, double v) { return BackwardAcceleration(x, v); },
429 plan_[after_index], after_distance, distance - after_distance);
430 acceleration = BackwardAcceleration(distance, velocity);
431 break;
432 default:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700433 AOS_LOG(
434 FATAL, "Unknown segment type %d\n",
Austin Schuhe73a9052019-01-07 12:16:17 -0800435 static_cast<int>(plan_segment_type_[DistanceToSegment(distance)]));
436 break;
437 }
438
Austin Schuhec7f06d2019-01-04 07:47:15 +1100439 return (::Eigen::Matrix<double, 3, 1>() << distance, velocity, acceleration)
440 .finished();
441}
442
443::Eigen::Matrix<double, 2, 1> Trajectory::FFVoltage(double distance) {
444 const Eigen::Matrix<double, 3, 1> xva = FFAcceleration(distance);
445 const double velocity = xva(1);
446 const double acceleration = xva(2);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100447
Austin Schuhe73a9052019-01-07 12:16:17 -0800448 ::Eigen::Matrix<double, 2, 1> K3;
449 ::Eigen::Matrix<double, 2, 1> K4;
450 ::Eigen::Matrix<double, 2, 1> K5;
451 K345(distance, &K3, &K4, &K5);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100452
453 return K5 * acceleration + K3 * velocity * velocity + K4 * velocity;
454}
455
456const ::std::vector<double> Trajectory::Distances() const {
457 ::std::vector<double> d;
458 d.reserve(plan_.size());
459 for (size_t i = 0; i < plan_.size(); ++i) {
460 d.push_back(Distance(i));
461 }
462 return d;
463}
464
465::Eigen::Matrix<double, 5, 5> Trajectory::ALinearizedContinuous(
466 const ::Eigen::Matrix<double, 5, 1> &state) const {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100467 const double sintheta = ::std::sin(state(2));
468 const double costheta = ::std::cos(state(2));
469 const ::Eigen::Matrix<double, 2, 1> linear_angular =
470 Tlr_to_la_ * state.block<2, 1>(3, 0);
471
472 // When stopped, just roll with a min velocity.
473 double linear_velocity = 0.0;
474 constexpr double kMinVelocity = 0.1;
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700475 if (::std::abs(linear_angular(0)) < kMinVelocity / 100.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100476 linear_velocity = 0.1;
477 } else if (::std::abs(linear_angular(0)) > kMinVelocity) {
478 linear_velocity = linear_angular(0);
479 } else if (linear_angular(0) > 0) {
480 linear_velocity = kMinVelocity;
481 } else if (linear_angular(0) < 0) {
482 linear_velocity = -kMinVelocity;
483 }
484
485 ::Eigen::Matrix<double, 5, 5> result = ::Eigen::Matrix<double, 5, 5>::Zero();
486 result(0, 2) = -sintheta * linear_velocity;
487 result(0, 3) = 0.5 * costheta;
488 result(0, 4) = 0.5 * costheta;
489
490 result(1, 2) = costheta * linear_velocity;
491 result(1, 3) = 0.5 * sintheta;
492 result(1, 4) = 0.5 * sintheta;
493
494 result(2, 3) = Tlr_to_la_(1, 0);
495 result(2, 4) = Tlr_to_la_(1, 1);
496
497 result.block<2, 2>(3, 3) =
498 velocity_drivetrain_->plant().coefficients().A_continuous;
499 return result;
500}
501
502::Eigen::Matrix<double, 5, 2> Trajectory::BLinearizedContinuous() const {
503 ::Eigen::Matrix<double, 5, 2> result = ::Eigen::Matrix<double, 5, 2>::Zero();
504 result.block<2, 2>(3, 0) =
505 velocity_drivetrain_->plant().coefficients().B_continuous;
506 return result;
507}
508
509void Trajectory::AB(const ::Eigen::Matrix<double, 5, 1> &state,
510 ::std::chrono::nanoseconds dt,
511 ::Eigen::Matrix<double, 5, 5> *A,
512 ::Eigen::Matrix<double, 5, 2> *B) const {
513 ::Eigen::Matrix<double, 5, 5> A_linearized_continuous =
514 ALinearizedContinuous(state);
515 ::Eigen::Matrix<double, 5, 2> B_linearized_continuous =
516 BLinearizedContinuous();
517
518 // Now, convert it to discrete.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700519 controls::C2D(A_linearized_continuous, B_linearized_continuous, dt, A, B);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100520}
521
522::Eigen::Matrix<double, 2, 5> Trajectory::KForState(
523 const ::Eigen::Matrix<double, 5, 1> &state, ::std::chrono::nanoseconds dt,
524 const ::Eigen::DiagonalMatrix<double, 5> &Q,
525 const ::Eigen::DiagonalMatrix<double, 2> &R) const {
526 ::Eigen::Matrix<double, 5, 5> A;
527 ::Eigen::Matrix<double, 5, 2> B;
528 AB(state, dt, &A, &B);
529
530 ::Eigen::Matrix<double, 5, 5> S = ::Eigen::Matrix<double, 5, 5>::Zero();
531 ::Eigen::Matrix<double, 2, 5> K = ::Eigen::Matrix<double, 2, 5>::Zero();
532
533 int info = ::frc971::controls::dlqr<5, 2>(A, B, Q, R, &K, &S);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534 if (info != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700535 AOS_LOG(ERROR, "Failed to solve %d, controllability: %d\n", info,
536 controls::Controllability(A, B));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100537 // TODO(austin): Can we be more clever here? Use the last one? We should
538 // collect more info about when this breaks down from logs.
539 K = ::Eigen::Matrix<double, 2, 5>::Zero();
540 }
541 ::Eigen::EigenSolver<::Eigen::Matrix<double, 5, 5>> eigensolver(A - B * K);
542 const auto eigenvalues = eigensolver.eigenvalues();
Austin Schuhf257f3c2019-10-27 21:00:43 -0700543 AOS_LOG(DEBUG,
544 "Eigenvalues: (%f + %fj), (%f + %fj), (%f + %fj), (%f + %fj), (%f + "
545 "%fj)\n",
546 eigenvalues(0).real(), eigenvalues(0).imag(), eigenvalues(1).real(),
547 eigenvalues(1).imag(), eigenvalues(2).real(), eigenvalues(2).imag(),
548 eigenvalues(3).real(), eigenvalues(3).imag(), eigenvalues(4).real(),
549 eigenvalues(4).imag());
Austin Schuhec7f06d2019-01-04 07:47:15 +1100550 return K;
551}
552
553const ::Eigen::Matrix<double, 5, 1> Trajectory::GoalState(double distance,
554 double velocity) {
555 ::Eigen::Matrix<double, 5, 1> result;
556 result.block<2, 1>(0, 0) = spline_->XY(distance);
557 result(2, 0) = spline_->Theta(distance);
558
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700559 result.block<2, 1>(3, 0) =
560 Tla_to_lr_ * (::Eigen::Matrix<double, 2, 1>() << velocity,
561 spline_->DThetaDt(distance, velocity))
562 .finished();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100563 return result;
564}
565
Alex Perry4ae2fd72019-02-03 15:55:57 -0800566::Eigen::Matrix<double, 3, 1> Trajectory::GetNextXVA(
567 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 2, 1> *state) {
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700568 double dt_float = ::aos::time::DurationInSeconds(dt);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100569
Alex Perry4ae2fd72019-02-03 15:55:57 -0800570 // TODO(austin): This feels like something that should be pulled out into
571 // a library for re-use.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700572 *state = RungeKutta(
573 [this](const ::Eigen::Matrix<double, 2, 1> x) {
574 ::Eigen::Matrix<double, 3, 1> xva = FFAcceleration(x(0));
575 return (::Eigen::Matrix<double, 2, 1>() << x(1), xva(2)).finished();
576 },
577 *state, dt_float);
Alex Perry4ae2fd72019-02-03 15:55:57 -0800578
579 ::Eigen::Matrix<double, 3, 1> result = FFAcceleration((*state)(0));
580 (*state)(1) = result(1);
581 return result;
582}
583
584::std::vector<::Eigen::Matrix<double, 3, 1>> Trajectory::PlanXVA(
585 ::std::chrono::nanoseconds dt) {
586 ::Eigen::Matrix<double, 2, 1> state = ::Eigen::Matrix<double, 2, 1>::Zero();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100587 ::std::vector<::Eigen::Matrix<double, 3, 1>> result;
588 result.emplace_back(FFAcceleration(0));
589 result.back()(1) = 0.0;
590
Alex Perry4ae2fd72019-02-03 15:55:57 -0800591 while (!is_at_end(state)) {
592 result.emplace_back(GetNextXVA(dt, &state));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100593 }
594 return result;
595}
596
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800597void Trajectory::LimitVelocity(double starting_distance, double ending_distance,
598 const double max_velocity) {
599 const double segment_length = ending_distance - starting_distance;
600
601 const double min_length = length() / static_cast<double>(plan_.size() - 1);
602 if (starting_distance > ending_distance) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700603 AOS_LOG(FATAL, "End before start: %f > %f\n", starting_distance,
604 ending_distance);
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800605 }
606 starting_distance = ::std::min(length(), ::std::max(0.0, starting_distance));
607 ending_distance = ::std::min(length(), ::std::max(0.0, ending_distance));
608 if (segment_length < min_length) {
609 const size_t plan_index = static_cast<size_t>(
610 ::std::round((starting_distance + ending_distance) / 2.0 / min_length));
611 if (max_velocity < plan_[plan_index]) {
612 plan_[plan_index] = max_velocity;
613 }
614 } else {
615 for (size_t i = DistanceToSegment(starting_distance) + 1;
616 i < DistanceToSegment(ending_distance) + 1; ++i) {
617 if (max_velocity < plan_[i]) {
618 plan_[i] = max_velocity;
619 if (i < DistanceToSegment(ending_distance)) {
620 plan_segment_type_[i] = SegmentType::VELOCITY_LIMITED;
621 }
622 }
623 }
624 }
625}
626
Austin Schuhec7f06d2019-01-04 07:47:15 +1100627} // namespace drivetrain
628} // namespace control_loops
629} // namespace frc971