blob: 97662d4c5f1f40d127fb49dd67c8fc83eabf6d15 [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
94 if (max_friction_accel < min_friction_accel - 0.1 ||
95 best_accel < min_voltage_accel || best_accel > max_voltage_accel) {
96 AOS_LOG(WARNING,
97 "Viable friction limits and viable voltage limits do not overlap (x: "
98 "%f, v: %f, backwards: %d) best_accel = %f, min voltage %f, max "
99 "voltage %f min friction %f max friction %f.\n",
100 x, v, backwards, best_accel, min_voltage_accel, max_voltage_accel,
101 min_friction_accel, max_friction_accel);
102 // Don't actually do anything--this will just result in attempting to drive
103 // higher voltages thatn we have available. In practice, that'll probably
104 // work out fine.
105 }
106
107 return best_accel;
108}
109
110double Trajectory::LateralVelocityCurvature(double distance) const {
111 // To calculate these constraints, we first note that:
112 // wheel accels = K2 * v_robot' + K1 * v_robot^2
113 // All that this logic does is solve for v_robot, leaving v_robot' free,
114 // assuming that the wheels are at their limits.
115 // To do this, we:
116 //
117 // 1) Determine what the wheel accels will be at the limit--since we have
118 // two free variables (v_robot, v_robot'), both wheels will be at their
119 // limits--if in a sufficiently tight turn (such that the signs of the
120 // coefficients of K2 are different), then the wheels will be accelerating
121 // in opposite directions; otherwise, they accelerate in the same direction.
122 // The magnitude of these per-wheel accelerations is a function of velocity,
123 // so it must also be solved for.
124 //
125 // 2) Eliminate that v_robot' term (since we don't care
126 // about it) by multiplying be a "K2prime" term (where K2prime * K2 = 0) on
127 // both sides of the equation.
128 //
129 // 3) Solving the relatively tractable remaining equation, which is
130 // basically just grouping all the terms together in one spot and taking the
131 // 4th root of everything.
132 const double dtheta = spline_->DTheta(distance);
133 const ::Eigen::Matrix<double, 1, 2> K2prime =
134 K2(dtheta).transpose() *
135 (::Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
136 // Calculate whether the wheels are spinning in opposite directions.
137 const bool opposites = K2prime(0) * K2prime(1) < 0;
138 const ::Eigen::Matrix<double, 2, 1> K1calc = K1(spline_->DDTheta(distance));
139 const double lat_accel_squared =
140 ::std::pow(dtheta / lateral_acceleration_, 2);
141 const double curvature_change_term =
142 (K2prime * K1calc).value() /
143 (K2prime *
144 (::Eigen::Matrix<double, 2, 1>() << 1.0, (opposites ? -1.0 : 1.0))
145 .finished() *
146 longitudinal_acceleration_)
147 .value();
148 const double vel_inv = ::std::sqrt(
149 ::std::sqrt(::std::pow(curvature_change_term, 2) + lat_accel_squared));
150 if (vel_inv == 0.0) {
151 return ::std::numeric_limits<double>::infinity();
152 }
153 return 1.0 / vel_inv;
154}
155
156void Trajectory::FrictionLngAccelLimits(double x, double v, double *min_accel,
157 double *max_accel) const {
158 // First, calculate the max longitudinal acceleration that can be achieved
159 // by either wheel given the friction elliipse that we have.
160 const double lateral_acceleration = v * v * spline_->DDXY(x).norm();
161 const double max_wheel_lng_accel_squared =
162 1.0 - ::std::pow(lateral_acceleration / lateral_acceleration_, 2.0);
163 if (max_wheel_lng_accel_squared < 0.0) {
164 AOS_LOG(DEBUG,
165 "Something (probably Runge-Kutta) queried invalid velocity %f at "
166 "distance %f\n",
167 v, x);
168 // If we encounter this, it means that the Runge-Kutta has attempted to
169 // sample points a bit past the edge of the friction boundary. If so, we
170 // gradually ramp the min/max accels to be more and more incorrect (note
171 // how min_accel > max_accel if we reach this case) to avoid causing any
172 // numerical issues.
173 *min_accel =
174 ::std::sqrt(-max_wheel_lng_accel_squared) * longitudinal_acceleration_;
175 *max_accel = -*min_accel;
176 return;
177 }
178 *min_accel = -::std::numeric_limits<double>::infinity();
179 *max_accel = ::std::numeric_limits<double>::infinity();
180
181 // Calculate max/min accelerations by calculating what the robots overall
182 // longitudinal acceleration would be if each wheel were running at the max
183 // forwards/backwards longitudinal acceleration.
184 const double max_wheel_lng_accel =
185 longitudinal_acceleration_ * ::std::sqrt(max_wheel_lng_accel_squared);
186 const ::Eigen::Matrix<double, 2, 1> K1v2 = K1(spline_->DDTheta(x)) * v * v;
187 const ::Eigen::Matrix<double, 2, 1> K2inv =
188 K2(spline_->DTheta(x)).cwiseInverse();
189 // Store the accelerations of the robot corresponding to each wheel being at
190 // the max/min acceleration. The first coefficient in each vector
191 // corresponds to the left wheel, the second to the right wheel.
192 const ::Eigen::Matrix<double, 2, 1> accels1 =
193 K2inv.array() * (-K1v2.array() + max_wheel_lng_accel);
194 const ::Eigen::Matrix<double, 2, 1> accels2 =
195 K2inv.array() * (-K1v2.array() - max_wheel_lng_accel);
196
197 // If either term is non-finite, that suggests that a term of K2 is zero
198 // (which is physically possible when turning such that one wheel is
199 // stationary), so just ignore that side of the drivetrain.
200 if (::std::isfinite(accels1(0))) {
201 // The inner max/min in this case determines which of the two cases (+ or
202 // - acceleration on the left wheel) we care about--in a sufficiently
203 // tight turning radius, the left hweel may be accelerating backwards when
204 // the robot as a whole accelerates forwards. We then use that
205 // acceleration to bound the min/max accel.
206 *min_accel = ::std::max(*min_accel, ::std::min(accels1(0), accels2(0)));
207 *max_accel = ::std::min(*max_accel, ::std::max(accels1(0), accels2(0)));
208 }
209 // Same logic as previous if-statement, but for the right wheel.
210 if (::std::isfinite(accels1(1))) {
211 *min_accel = ::std::max(*min_accel, ::std::min(accels1(1), accels2(1)));
212 *max_accel = ::std::min(*max_accel, ::std::max(accels1(1), accels2(1)));
213 }
214}
215
216double Trajectory::VoltageVelocityLimit(
217 double distance, VoltageLimit limit_type,
218 Eigen::Matrix<double, 2, 1> *constraint_voltages) const {
219 // To sketch an outline of the math going on here, we start with the basic
220 // dynamics of the robot along the spline:
221 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot + B * U
222 // We need to determine the maximum v_robot given constrained U and free
223 // v_robot'.
224 // Similarly to the friction constraints, we accomplish this by first
225 // multiplying by a K2prime term to eliminate the v_robot' term.
226 // As with the friction constraints, we also know that the limits will occur
227 // when both sides of the drivetrain are driven at their max magnitude
228 // voltages, although they may be driven at different signs.
229 // Once we determine whether the voltages match signs, we still have to
230 // consider both possible pairings (technically we could probably
231 // predetermine which pairing, e.g. +/- or -/+, we acre about, but we don't
232 // need to).
233 //
234 // For each pairing, we then get to solve a quadratic formula for the robot
235 // velocity at those voltages. This gives us up to 4 solutions, of which
236 // up to 3 will give us positive velocities; each solution velocity
237 // corresponds to a transition from feasibility to infeasibility, where a
238 // velocity of zero is always feasible, and there will always be 0, 1, or 3
239 // positive solutions. Among the positive solutions, we take both the min
240 // and the max--the min will be the highest velocity such that all
241 // velocities between zero and that velocity are valid; the max will be
242 // the highest feasible velocity. Which we return depends on what the
243 // limit_type is.
244 //
245 // Sketching the actual math:
246 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot +/- B * U_max
247 // K2prime * K1 * v_robot^2 = K2prime * (A * K2 * v_robot +/- B * U_max)
248 // a v_robot^2 + b v_robot +/- c = 0
249 const ::Eigen::Matrix<double, 2, 2> B =
250 velocity_drivetrain_->plant().coefficients().B_continuous;
251 const double dtheta = spline_->DTheta(distance);
252 const ::Eigen::Matrix<double, 2, 1> BinvK2 = B.inverse() * K2(dtheta);
253 // Because voltages can actually impact *both* wheels, in order to determine
254 // whether the voltages will have opposite signs, we need to use B^-1 * K2.
255 const bool opposite_voltages = BinvK2(0) * BinvK2(1) > 0.0;
256 const ::Eigen::Matrix<double, 1, 2> K2prime =
257 K2(dtheta).transpose() *
258 (::Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
259 const double a = K2prime * K1(spline_->DDTheta(distance));
260 const double b = -K2prime *
261 velocity_drivetrain_->plant().coefficients().A_continuous *
262 K2(dtheta);
263 const ::Eigen::Matrix<double, 1, 2> c_coeff = -K2prime * B;
264 // Calculate the "positive" version of the voltage limits we will use.
265 const ::Eigen::Matrix<double, 2, 1> abs_volts =
266 voltage_limit_ *
267 (::Eigen::Matrix<double, 2, 1>() << 1.0, (opposite_voltages ? -1.0 : 1.0))
268 .finished();
269
270 double min_valid_vel = ::std::numeric_limits<double>::infinity();
271 if (limit_type == VoltageLimit::kAggressive) {
272 min_valid_vel = 0.0;
273 }
274 // Iterate over both possibilites for +/- voltage, and solve the quadratic
275 // formula. For every positive solution, adjust the velocity limit
276 // appropriately.
277 for (const double sign : {1.0, -1.0}) {
278 const ::Eigen::Matrix<double, 2, 1> U = sign * abs_volts;
279 const double prev_vel = min_valid_vel;
280 const double c = c_coeff * U;
281 const double determinant = b * b - 4 * a * c;
282 if (a == 0) {
283 // If a == 0, that implies we are on a constant curvature path, in which
284 // case we just have b * v + c = 0.
285 // Note that if -b * c > 0.0, then vel will be greater than zero and b
286 // will be non-zero.
287 if (-b * c > 0.0) {
288 const double vel = -c / b;
289 if (limit_type == VoltageLimit::kConservative) {
290 min_valid_vel = ::std::min(min_valid_vel, vel);
291 } else {
292 min_valid_vel = ::std::max(min_valid_vel, vel);
293 }
294 } else if (b == 0) {
295 // If a and b are zero, then we are travelling in a straight line and
296 // have no voltage-based velocity constraints.
297 min_valid_vel = ::std::numeric_limits<double>::infinity();
298 }
299 } else if (determinant > 0) {
300 const double sqrt_determinant = ::std::sqrt(determinant);
301 const double high_vel = (-b + sqrt_determinant) / (2.0 * a);
302 const double low_vel = (-b - sqrt_determinant) / (2.0 * a);
303 if (low_vel > 0) {
304 if (limit_type == VoltageLimit::kConservative) {
305 min_valid_vel = ::std::min(min_valid_vel, low_vel);
306 } else {
307 min_valid_vel = ::std::max(min_valid_vel, low_vel);
308 }
309 }
310 if (high_vel > 0) {
311 if (limit_type == VoltageLimit::kConservative) {
312 min_valid_vel = ::std::min(min_valid_vel, high_vel);
313 } else {
314 min_valid_vel = ::std::max(min_valid_vel, high_vel);
315 }
316 }
317 } else if (determinant == 0 && -b * a > 0) {
318 const double vel = -b / (2.0 * a);
319 if (vel > 0.0) {
320 if (limit_type == VoltageLimit::kConservative) {
321 min_valid_vel = ::std::min(min_valid_vel, vel);
322 } else {
323 min_valid_vel = ::std::max(min_valid_vel, vel);
324 }
325 }
326 }
327 if (constraint_voltages != nullptr && prev_vel != min_valid_vel) {
328 *constraint_voltages = U;
329 }
330 }
331 return min_valid_vel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100332}
333
334void Trajectory::ForwardPass() {
335 plan_[0] = 0.0;
336 const double delta_distance = Distance(1) - Distance(0);
337 for (size_t i = 0; i < plan_.size() - 1; ++i) {
338 const double distance = Distance(i);
339
340 // Integrate our acceleration forward one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800341 const double new_plan_velocity = IntegrateAccelForDistance(
342 [this](double x, double v) { return ForwardAcceleration(x, v); },
343 plan_[i], distance, delta_distance);
344
James Kuszmaulea314d92019-02-18 19:45:06 -0800345 if (new_plan_velocity <= plan_[i + 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800346 plan_[i + 1] = new_plan_velocity;
347 plan_segment_type_[i] = SegmentType::ACCELERATION_LIMITED;
348 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100349 }
350}
351
Austin Schuhec7f06d2019-01-04 07:47:15 +1100352void Trajectory::BackwardPass() {
353 const double delta_distance = Distance(0) - Distance(1);
354 plan_.back() = 0.0;
355 for (size_t i = plan_.size() - 1; i > 0; --i) {
356 const double distance = Distance(i);
357
358 // Integrate our deceleration back one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800359 const double new_plan_velocity = IntegrateAccelForDistance(
360 [this](double x, double v) { return BackwardAcceleration(x, v); },
361 plan_[i], distance, delta_distance);
362
James Kuszmaulea314d92019-02-18 19:45:06 -0800363 if (new_plan_velocity <= plan_[i - 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800364 plan_[i - 1] = new_plan_velocity;
365 plan_segment_type_[i - 1] = SegmentType::DECELERATION_LIMITED;
366 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100367 }
368}
369
370::Eigen::Matrix<double, 3, 1> Trajectory::FFAcceleration(double distance) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800371 if (distance < 0.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100372 // Make sure we don't end up off the beginning of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800373 distance = 0.0;
374 } else if (distance > length()) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100375 // Make sure we don't end up off the end of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800376 distance = length();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100377 }
Austin Schuhe73a9052019-01-07 12:16:17 -0800378 const size_t before_index = DistanceToSegment(distance);
379 const size_t after_index = before_index + 1;
380
Austin Schuhec7f06d2019-01-04 07:47:15 +1100381 const double before_distance = Distance(before_index);
382 const double after_distance = Distance(after_index);
383
Austin Schuhec7f06d2019-01-04 07:47:15 +1100384 // And then also make sure we aren't curvature limited.
385 const double vcurvature = LateralVelocityCurvature(distance);
386
387 double acceleration;
388 double velocity;
James Kuszmaulea314d92019-02-18 19:45:06 -0800389 // TODO(james): While technically correct for sufficiently small segment
390 // steps, this method of switching between limits has a tendency to produce
391 // sudden jumps in acceelrations, which is undesirable.
Austin Schuhe73a9052019-01-07 12:16:17 -0800392 switch (plan_segment_type_[DistanceToSegment(distance)]) {
393 case SegmentType::VELOCITY_LIMITED:
394 acceleration = 0.0;
395 velocity = (plan_[before_index] + plan_[after_index]) / 2.0;
396 // TODO(austin): Accelerate or decelerate until we hit the limit in the
397 // time slice. Otherwise our acceleration will be lying for this slice.
398 // Do note, we've got small slices so the effect will be small.
399 break;
400 case SegmentType::CURVATURE_LIMITED:
401 velocity = vcurvature;
James Kuszmaulea314d92019-02-18 19:45:06 -0800402 FrictionLngAccelLimits(distance, velocity, &acceleration, &acceleration);
403 break;
404 case SegmentType::VOLTAGE_LIMITED:
405 // Normally, we expect that voltage limited plans will all get dominated
406 // by the acceleration/deceleration limits. This may not always be true;
407 // if we ever encounter this error, we just need to back out what the
408 // accelerations would be in this case.
409 LOG(FATAL) << "Unexpectedly got VOLTAGE_LIMITED plan.";
Austin Schuhe73a9052019-01-07 12:16:17 -0800410 break;
411 case SegmentType::ACCELERATION_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800412 // TODO(james): The integration done here and in the DECELERATION_LIMITED
413 // can technically cause us to violate friction constraints. We currently
414 // don't do anything about it to avoid causing sudden jumps in voltage,
415 // but we probably *should* at some point.
Austin Schuhe73a9052019-01-07 12:16:17 -0800416 velocity = IntegrateAccelForDistance(
417 [this](double x, double v) { return ForwardAcceleration(x, v); },
418 plan_[before_index], before_distance, distance - before_distance);
419 acceleration = ForwardAcceleration(distance, velocity);
420 break;
421 case SegmentType::DECELERATION_LIMITED:
422 velocity = IntegrateAccelForDistance(
423 [this](double x, double v) { return BackwardAcceleration(x, v); },
424 plan_[after_index], after_distance, distance - after_distance);
425 acceleration = BackwardAcceleration(distance, velocity);
426 break;
427 default:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700428 AOS_LOG(
429 FATAL, "Unknown segment type %d\n",
Austin Schuhe73a9052019-01-07 12:16:17 -0800430 static_cast<int>(plan_segment_type_[DistanceToSegment(distance)]));
431 break;
432 }
433
Austin Schuhec7f06d2019-01-04 07:47:15 +1100434 return (::Eigen::Matrix<double, 3, 1>() << distance, velocity, acceleration)
435 .finished();
436}
437
438::Eigen::Matrix<double, 2, 1> Trajectory::FFVoltage(double distance) {
439 const Eigen::Matrix<double, 3, 1> xva = FFAcceleration(distance);
440 const double velocity = xva(1);
441 const double acceleration = xva(2);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100442
Austin Schuhe73a9052019-01-07 12:16:17 -0800443 ::Eigen::Matrix<double, 2, 1> K3;
444 ::Eigen::Matrix<double, 2, 1> K4;
445 ::Eigen::Matrix<double, 2, 1> K5;
446 K345(distance, &K3, &K4, &K5);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100447
448 return K5 * acceleration + K3 * velocity * velocity + K4 * velocity;
449}
450
451const ::std::vector<double> Trajectory::Distances() const {
452 ::std::vector<double> d;
453 d.reserve(plan_.size());
454 for (size_t i = 0; i < plan_.size(); ++i) {
455 d.push_back(Distance(i));
456 }
457 return d;
458}
459
460::Eigen::Matrix<double, 5, 5> Trajectory::ALinearizedContinuous(
461 const ::Eigen::Matrix<double, 5, 1> &state) const {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100462 const double sintheta = ::std::sin(state(2));
463 const double costheta = ::std::cos(state(2));
464 const ::Eigen::Matrix<double, 2, 1> linear_angular =
465 Tlr_to_la_ * state.block<2, 1>(3, 0);
466
467 // When stopped, just roll with a min velocity.
468 double linear_velocity = 0.0;
469 constexpr double kMinVelocity = 0.1;
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700470 if (::std::abs(linear_angular(0)) < kMinVelocity / 100.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100471 linear_velocity = 0.1;
472 } else if (::std::abs(linear_angular(0)) > kMinVelocity) {
473 linear_velocity = linear_angular(0);
474 } else if (linear_angular(0) > 0) {
475 linear_velocity = kMinVelocity;
476 } else if (linear_angular(0) < 0) {
477 linear_velocity = -kMinVelocity;
478 }
479
480 ::Eigen::Matrix<double, 5, 5> result = ::Eigen::Matrix<double, 5, 5>::Zero();
481 result(0, 2) = -sintheta * linear_velocity;
482 result(0, 3) = 0.5 * costheta;
483 result(0, 4) = 0.5 * costheta;
484
485 result(1, 2) = costheta * linear_velocity;
486 result(1, 3) = 0.5 * sintheta;
487 result(1, 4) = 0.5 * sintheta;
488
489 result(2, 3) = Tlr_to_la_(1, 0);
490 result(2, 4) = Tlr_to_la_(1, 1);
491
492 result.block<2, 2>(3, 3) =
493 velocity_drivetrain_->plant().coefficients().A_continuous;
494 return result;
495}
496
497::Eigen::Matrix<double, 5, 2> Trajectory::BLinearizedContinuous() const {
498 ::Eigen::Matrix<double, 5, 2> result = ::Eigen::Matrix<double, 5, 2>::Zero();
499 result.block<2, 2>(3, 0) =
500 velocity_drivetrain_->plant().coefficients().B_continuous;
501 return result;
502}
503
504void Trajectory::AB(const ::Eigen::Matrix<double, 5, 1> &state,
505 ::std::chrono::nanoseconds dt,
506 ::Eigen::Matrix<double, 5, 5> *A,
507 ::Eigen::Matrix<double, 5, 2> *B) const {
508 ::Eigen::Matrix<double, 5, 5> A_linearized_continuous =
509 ALinearizedContinuous(state);
510 ::Eigen::Matrix<double, 5, 2> B_linearized_continuous =
511 BLinearizedContinuous();
512
513 // Now, convert it to discrete.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700514 controls::C2D(A_linearized_continuous, B_linearized_continuous, dt, A, B);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100515}
516
517::Eigen::Matrix<double, 2, 5> Trajectory::KForState(
518 const ::Eigen::Matrix<double, 5, 1> &state, ::std::chrono::nanoseconds dt,
519 const ::Eigen::DiagonalMatrix<double, 5> &Q,
520 const ::Eigen::DiagonalMatrix<double, 2> &R) const {
521 ::Eigen::Matrix<double, 5, 5> A;
522 ::Eigen::Matrix<double, 5, 2> B;
523 AB(state, dt, &A, &B);
524
525 ::Eigen::Matrix<double, 5, 5> S = ::Eigen::Matrix<double, 5, 5>::Zero();
526 ::Eigen::Matrix<double, 2, 5> K = ::Eigen::Matrix<double, 2, 5>::Zero();
527
528 int info = ::frc971::controls::dlqr<5, 2>(A, B, Q, R, &K, &S);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529 if (info != 0) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700530 AOS_LOG(ERROR, "Failed to solve %d, controllability: %d\n", info,
531 controls::Controllability(A, B));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100532 // TODO(austin): Can we be more clever here? Use the last one? We should
533 // collect more info about when this breaks down from logs.
534 K = ::Eigen::Matrix<double, 2, 5>::Zero();
535 }
536 ::Eigen::EigenSolver<::Eigen::Matrix<double, 5, 5>> eigensolver(A - B * K);
537 const auto eigenvalues = eigensolver.eigenvalues();
Austin Schuhf257f3c2019-10-27 21:00:43 -0700538 AOS_LOG(DEBUG,
539 "Eigenvalues: (%f + %fj), (%f + %fj), (%f + %fj), (%f + %fj), (%f + "
540 "%fj)\n",
541 eigenvalues(0).real(), eigenvalues(0).imag(), eigenvalues(1).real(),
542 eigenvalues(1).imag(), eigenvalues(2).real(), eigenvalues(2).imag(),
543 eigenvalues(3).real(), eigenvalues(3).imag(), eigenvalues(4).real(),
544 eigenvalues(4).imag());
Austin Schuhec7f06d2019-01-04 07:47:15 +1100545 return K;
546}
547
548const ::Eigen::Matrix<double, 5, 1> Trajectory::GoalState(double distance,
549 double velocity) {
550 ::Eigen::Matrix<double, 5, 1> result;
551 result.block<2, 1>(0, 0) = spline_->XY(distance);
552 result(2, 0) = spline_->Theta(distance);
553
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700554 result.block<2, 1>(3, 0) =
555 Tla_to_lr_ * (::Eigen::Matrix<double, 2, 1>() << velocity,
556 spline_->DThetaDt(distance, velocity))
557 .finished();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100558 return result;
559}
560
Alex Perry4ae2fd72019-02-03 15:55:57 -0800561::Eigen::Matrix<double, 3, 1> Trajectory::GetNextXVA(
562 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 2, 1> *state) {
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700563 double dt_float = ::aos::time::DurationInSeconds(dt);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100564
Alex Perry4ae2fd72019-02-03 15:55:57 -0800565 // TODO(austin): This feels like something that should be pulled out into
566 // a library for re-use.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700567 *state = RungeKutta(
568 [this](const ::Eigen::Matrix<double, 2, 1> x) {
569 ::Eigen::Matrix<double, 3, 1> xva = FFAcceleration(x(0));
570 return (::Eigen::Matrix<double, 2, 1>() << x(1), xva(2)).finished();
571 },
572 *state, dt_float);
Alex Perry4ae2fd72019-02-03 15:55:57 -0800573
574 ::Eigen::Matrix<double, 3, 1> result = FFAcceleration((*state)(0));
575 (*state)(1) = result(1);
576 return result;
577}
578
579::std::vector<::Eigen::Matrix<double, 3, 1>> Trajectory::PlanXVA(
580 ::std::chrono::nanoseconds dt) {
581 ::Eigen::Matrix<double, 2, 1> state = ::Eigen::Matrix<double, 2, 1>::Zero();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100582 ::std::vector<::Eigen::Matrix<double, 3, 1>> result;
583 result.emplace_back(FFAcceleration(0));
584 result.back()(1) = 0.0;
585
Alex Perry4ae2fd72019-02-03 15:55:57 -0800586 while (!is_at_end(state)) {
587 result.emplace_back(GetNextXVA(dt, &state));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100588 }
589 return result;
590}
591
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800592void Trajectory::LimitVelocity(double starting_distance, double ending_distance,
593 const double max_velocity) {
594 const double segment_length = ending_distance - starting_distance;
595
596 const double min_length = length() / static_cast<double>(plan_.size() - 1);
597 if (starting_distance > ending_distance) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700598 AOS_LOG(FATAL, "End before start: %f > %f\n", starting_distance,
599 ending_distance);
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800600 }
601 starting_distance = ::std::min(length(), ::std::max(0.0, starting_distance));
602 ending_distance = ::std::min(length(), ::std::max(0.0, ending_distance));
603 if (segment_length < min_length) {
604 const size_t plan_index = static_cast<size_t>(
605 ::std::round((starting_distance + ending_distance) / 2.0 / min_length));
606 if (max_velocity < plan_[plan_index]) {
607 plan_[plan_index] = max_velocity;
608 }
609 } else {
610 for (size_t i = DistanceToSegment(starting_distance) + 1;
611 i < DistanceToSegment(ending_distance) + 1; ++i) {
612 if (max_velocity < plan_[i]) {
613 plan_[i] = max_velocity;
614 if (i < DistanceToSegment(ending_distance)) {
615 plan_segment_type_[i] = SegmentType::VELOCITY_LIMITED;
616 }
617 }
618 }
619 }
620}
621
Austin Schuhec7f06d2019-01-04 07:47:15 +1100622} // namespace drivetrain
623} // namespace control_loops
624} // namespace frc971