blob: 1a94756d9733d7a61c7a4259154d4b206f13e7d8 [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
James Kuszmaul75a18c52021-03-10 22:02:07 -080017namespace {
18float DefaultConstraint(ConstraintType type) {
19 switch (type) {
20 case ConstraintType::LONGITUDINAL_ACCELERATION:
21 return 2.0;
22 case ConstraintType::LATERAL_ACCELERATION:
23 return 3.0;
24 case ConstraintType::VOLTAGE:
25 return 12.0;
26 case ConstraintType::VELOCITY:
27 case ConstraintType::CONSTRAINT_TYPE_UNDEFINED:
28 LOG(FATAL) << "No default constraint value for "
29 << EnumNameConstraintType(type);
30 }
31 LOG(FATAL) << "Invalid ConstraintType " << static_cast<int>(type);
32}
33} // namespace
34
35FinishedTrajectory::FinishedTrajectory(const DrivetrainConfig<double> &config,
36 const fb::Trajectory *buffer)
37 : BaseTrajectory(CHECK_NOTNULL(CHECK_NOTNULL(buffer->spline())->spline())
38 ->constraints(),
39 config),
40 buffer_(buffer),
41 spline_(*buffer_->spline()) {}
42
43const Eigen::Matrix<double, 2, 1> BaseTrajectory::K1(
44 double current_ddtheta) const {
45 return (Eigen::Matrix<double, 2, 1>() << -robot_radius_l_ * current_ddtheta,
46 robot_radius_r_ * current_ddtheta)
47 .finished();
48}
49
50const Eigen::Matrix<double, 2, 1> BaseTrajectory::K2(
51 double current_dtheta) const {
52 return (Eigen::Matrix<double, 2, 1>()
53 << 1.0 - robot_radius_l_ * current_dtheta,
54 1.0 + robot_radius_r_ * current_dtheta)
55 .finished();
56}
57
58void BaseTrajectory::K345(const double x, Eigen::Matrix<double, 2, 1> *K3,
59 Eigen::Matrix<double, 2, 1> *K4,
60 Eigen::Matrix<double, 2, 1> *K5) const {
61 const double current_ddtheta = spline().DDTheta(x);
62 const double current_dtheta = spline().DTheta(x);
63 // We've now got the equation:
64 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
65 const Eigen::Matrix<double, 2, 1> my_K2 = K2(current_dtheta);
66
67 const Eigen::Matrix<double, 2, 2> B_inverse =
68 velocity_drivetrain_->plant().coefficients().B_continuous.inverse();
69
70 // Now, rephrase it as K5 a + K3 v^2 + K4 v = U
71 *K3 = B_inverse * K1(current_ddtheta);
72 *K4 = -B_inverse * velocity_drivetrain_->plant().coefficients().A_continuous *
73 my_K2;
74 *K5 = B_inverse * my_K2;
75}
76
77BaseTrajectory::BaseTrajectory(
78 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
79 const DrivetrainConfig<double> &config)
80 : velocity_drivetrain_(
81 std::unique_ptr<StateFeedbackLoop<2, 2, 2, double,
82 StateFeedbackHybridPlant<2, 2, 2>,
83 HybridKalman<2, 2, 2>>>(
James Kuszmaulaa2499d2020-06-02 21:31:19 -070084 new StateFeedbackLoop<2, 2, 2, double,
85 StateFeedbackHybridPlant<2, 2, 2>,
86 HybridKalman<2, 2, 2>>(
87 config.make_hybrid_drivetrain_velocity_loop()))),
88 config_(config),
Austin Schuhec7f06d2019-01-04 07:47:15 +110089 robot_radius_l_(config.robot_radius),
90 robot_radius_r_(config.robot_radius),
James Kuszmaul75a18c52021-03-10 22:02:07 -080091 lateral_acceleration_(
92 ConstraintValue(constraints, ConstraintType::LATERAL_ACCELERATION)),
93 longitudinal_acceleration_(ConstraintValue(
94 constraints, ConstraintType::LONGITUDINAL_ACCELERATION)),
95 voltage_limit_(ConstraintValue(constraints, ConstraintType::VOLTAGE)) {}
96
97Trajectory::Trajectory(const SplineGoal &spline_goal,
98 const DrivetrainConfig<double> &config)
99 : Trajectory(DistanceSpline{spline_goal.spline()}, config,
100 spline_goal.spline()->constraints(),
101 spline_goal.spline_idx()) {
102 drive_spline_backwards_ = spline_goal.drive_spline_backwards();
103}
104
105Trajectory::Trajectory(
106 DistanceSpline &&input_spline, const DrivetrainConfig<double> &config,
107 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
108 int spline_idx, double vmax, int num_distance)
109 : BaseTrajectory(constraints, config),
110 spline_idx_(spline_idx),
111 spline_(std::move(input_spline)),
112 config_(config),
Austin Schuhe73a9052019-01-07 12:16:17 -0800113 plan_(num_distance == 0
Austin Schuh890196c2021-03-31 20:18:45 -0700114 ? std::max(10000, static_cast<int>(spline_.length() / 0.0025))
Austin Schuhe73a9052019-01-07 12:16:17 -0800115 : num_distance,
116 vmax),
James Kuszmaul75a18c52021-03-10 22:02:07 -0800117 plan_segment_type_(plan_.size(),
118 fb::SegmentConstraint::VELOCITY_LIMITED) {
119 if (constraints != nullptr) {
120 for (const Constraint *constraint : *constraints) {
121 if (constraint->constraint_type() == ConstraintType::VELOCITY) {
122 LimitVelocity(constraint->start_distance(), constraint->end_distance(),
123 constraint->value());
124 }
125 }
126 }
127}
Austin Schuhec7f06d2019-01-04 07:47:15 +1100128
129void Trajectory::LateralAccelPass() {
130 for (size_t i = 0; i < plan_.size(); ++i) {
131 const double distance = Distance(i);
Austin Schuhd749d932020-12-30 21:38:40 -0800132 const double velocity_limit = LateralVelocityCurvature(distance);
James Kuszmaulea314d92019-02-18 19:45:06 -0800133 if (velocity_limit < plan_[i]) {
134 plan_[i] = velocity_limit;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800135 plan_segment_type_[i] = fb::SegmentConstraint::CURVATURE_LIMITED;
James Kuszmaulea314d92019-02-18 19:45:06 -0800136 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100137 }
138}
139
James Kuszmaulea314d92019-02-18 19:45:06 -0800140void Trajectory::VoltageFeasibilityPass(VoltageLimit limit_type) {
141 for (size_t i = 0; i < plan_.size(); ++i) {
142 const double distance = Distance(i);
143 const double velocity_limit = VoltageVelocityLimit(distance, limit_type);
144 if (velocity_limit < plan_[i]) {
145 plan_[i] = velocity_limit;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800146 plan_segment_type_[i] = fb::SegmentConstraint::VOLTAGE_LIMITED;
James Kuszmaulea314d92019-02-18 19:45:06 -0800147 }
148 }
149}
150
James Kuszmaul75a18c52021-03-10 22:02:07 -0800151double BaseTrajectory::BestAcceleration(double x, double v,
152 bool backwards) const {
153 Eigen::Matrix<double, 2, 1> K3;
154 Eigen::Matrix<double, 2, 1> K4;
155 Eigen::Matrix<double, 2, 1> K5;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100156 K345(x, &K3, &K4, &K5);
157
Austin Schuhec7f06d2019-01-04 07:47:15 +1100158 // Now, solve for all a's and find the best one which meets our criteria.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800159 const Eigen::Matrix<double, 2, 1> C = K3 * v * v + K4 * v;
160 double min_voltage_accel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800161 double max_voltage_accel = -min_voltage_accel;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800162 for (const double a : {(max_voltage() - C(0, 0)) / K5(0, 0),
163 (max_voltage() - C(1, 0)) / K5(1, 0),
164 (-max_voltage() - C(0, 0)) / K5(0, 0),
165 (-max_voltage() - C(1, 0)) / K5(1, 0)}) {
166 const Eigen::Matrix<double, 2, 1> U = K5 * a + K3 * v * v + K4 * v;
167 if ((U.array().abs() < max_voltage() + 1e-6).all()) {
168 min_voltage_accel = std::min(a, min_voltage_accel);
169 max_voltage_accel = std::max(a, max_voltage_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100170 }
171 }
James Kuszmaulea314d92019-02-18 19:45:06 -0800172 double best_accel = backwards ? min_voltage_accel : max_voltage_accel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100173
James Kuszmaulea314d92019-02-18 19:45:06 -0800174 double min_friction_accel, max_friction_accel;
175 FrictionLngAccelLimits(x, v, &min_friction_accel, &max_friction_accel);
176 if (backwards) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800177 best_accel = std::max(best_accel, min_friction_accel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800178 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800179 best_accel = std::min(best_accel, max_friction_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100180 }
James Kuszmaulea314d92019-02-18 19:45:06 -0800181
James Kuszmaul66b78042020-02-23 15:30:51 -0800182 // Ideally, the max would never be less than the min, but due to the way that
183 // the runge kutta solver works, it sometimes ticks over the edge.
184 if (max_friction_accel < min_friction_accel) {
185 VLOG(1) << "At x " << x << " v " << v << " min fric acc "
186 << min_friction_accel << " max fric accel " << max_friction_accel;
187 }
188 if (best_accel < min_voltage_accel || best_accel > max_voltage_accel) {
189 LOG(WARNING) << "Viable friction limits and viable voltage limits do not "
Austin Schuhd749d932020-12-30 21:38:40 -0800190 "overlap (x: "
191 << x << ", v: " << v << ", backwards: " << backwards
James Kuszmaul66b78042020-02-23 15:30:51 -0800192 << ") best_accel = " << best_accel << ", min voltage "
193 << min_voltage_accel << ", max voltage " << max_voltage_accel
194 << " min friction " << min_friction_accel << " max friction "
195 << max_friction_accel << ".";
196
James Kuszmaulea314d92019-02-18 19:45:06 -0800197 // Don't actually do anything--this will just result in attempting to drive
198 // higher voltages thatn we have available. In practice, that'll probably
199 // work out fine.
200 }
201
202 return best_accel;
203}
204
James Kuszmaul75a18c52021-03-10 22:02:07 -0800205double BaseTrajectory::LateralVelocityCurvature(double distance) const {
James Kuszmaulea314d92019-02-18 19:45:06 -0800206 // To calculate these constraints, we first note that:
207 // wheel accels = K2 * v_robot' + K1 * v_robot^2
208 // All that this logic does is solve for v_robot, leaving v_robot' free,
209 // assuming that the wheels are at their limits.
210 // To do this, we:
211 //
212 // 1) Determine what the wheel accels will be at the limit--since we have
213 // two free variables (v_robot, v_robot'), both wheels will be at their
214 // limits--if in a sufficiently tight turn (such that the signs of the
215 // coefficients of K2 are different), then the wheels will be accelerating
216 // in opposite directions; otherwise, they accelerate in the same direction.
217 // The magnitude of these per-wheel accelerations is a function of velocity,
218 // so it must also be solved for.
219 //
220 // 2) Eliminate that v_robot' term (since we don't care
221 // about it) by multiplying be a "K2prime" term (where K2prime * K2 = 0) on
222 // both sides of the equation.
223 //
224 // 3) Solving the relatively tractable remaining equation, which is
225 // basically just grouping all the terms together in one spot and taking the
226 // 4th root of everything.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800227 const double dtheta = spline().DTheta(distance);
228 const Eigen::Matrix<double, 1, 2> K2prime =
James Kuszmaulea314d92019-02-18 19:45:06 -0800229 K2(dtheta).transpose() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800230 (Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
James Kuszmaulea314d92019-02-18 19:45:06 -0800231 // Calculate whether the wheels are spinning in opposite directions.
232 const bool opposites = K2prime(0) * K2prime(1) < 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800233 const Eigen::Matrix<double, 2, 1> K1calc = K1(spline().DDTheta(distance));
234 const double lat_accel_squared = std::pow(dtheta / max_lateral_accel(), 2);
James Kuszmaulea314d92019-02-18 19:45:06 -0800235 const double curvature_change_term =
236 (K2prime * K1calc).value() /
237 (K2prime *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800238 (Eigen::Matrix<double, 2, 1>() << 1.0, (opposites ? -1.0 : 1.0))
James Kuszmaulea314d92019-02-18 19:45:06 -0800239 .finished() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800240 max_longitudinal_accel())
James Kuszmaulea314d92019-02-18 19:45:06 -0800241 .value();
James Kuszmaul75a18c52021-03-10 22:02:07 -0800242 const double vel_inv = std::sqrt(
243 std::sqrt(std::pow(curvature_change_term, 2) + lat_accel_squared));
James Kuszmaulea314d92019-02-18 19:45:06 -0800244 if (vel_inv == 0.0) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800245 return std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800246 }
247 return 1.0 / vel_inv;
248}
249
James Kuszmaul75a18c52021-03-10 22:02:07 -0800250void BaseTrajectory::FrictionLngAccelLimits(double x, double v,
251 double *min_accel,
252 double *max_accel) const {
James Kuszmaulea314d92019-02-18 19:45:06 -0800253 // First, calculate the max longitudinal acceleration that can be achieved
254 // by either wheel given the friction elliipse that we have.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800255 const double lateral_acceleration = v * v * spline().DDXY(x).norm();
James Kuszmaulea314d92019-02-18 19:45:06 -0800256 const double max_wheel_lng_accel_squared =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800257 1.0 - std::pow(lateral_acceleration / max_lateral_accel(), 2.0);
James Kuszmaulea314d92019-02-18 19:45:06 -0800258 if (max_wheel_lng_accel_squared < 0.0) {
James Kuszmaul66b78042020-02-23 15:30:51 -0800259 VLOG(1) << "Something (probably Runge-Kutta) queried invalid velocity " << v
260 << " at distance " << x;
James Kuszmaulea314d92019-02-18 19:45:06 -0800261 // If we encounter this, it means that the Runge-Kutta has attempted to
262 // sample points a bit past the edge of the friction boundary. If so, we
263 // gradually ramp the min/max accels to be more and more incorrect (note
264 // how min_accel > max_accel if we reach this case) to avoid causing any
265 // numerical issues.
266 *min_accel =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800267 std::sqrt(-max_wheel_lng_accel_squared) * max_longitudinal_accel();
James Kuszmaulea314d92019-02-18 19:45:06 -0800268 *max_accel = -*min_accel;
269 return;
270 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800271 *min_accel = -std::numeric_limits<double>::infinity();
272 *max_accel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800273
274 // Calculate max/min accelerations by calculating what the robots overall
275 // longitudinal acceleration would be if each wheel were running at the max
276 // forwards/backwards longitudinal acceleration.
277 const double max_wheel_lng_accel =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800278 max_longitudinal_accel() * std::sqrt(max_wheel_lng_accel_squared);
279 const Eigen::Matrix<double, 2, 1> K1v2 = K1(spline().DDTheta(x)) * v * v;
280 const Eigen::Matrix<double, 2, 1> K2inv =
281 K2(spline().DTheta(x)).cwiseInverse();
James Kuszmaulea314d92019-02-18 19:45:06 -0800282 // Store the accelerations of the robot corresponding to each wheel being at
283 // the max/min acceleration. The first coefficient in each vector
284 // corresponds to the left wheel, the second to the right wheel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800285 const Eigen::Matrix<double, 2, 1> accels1 =
James Kuszmaulea314d92019-02-18 19:45:06 -0800286 K2inv.array() * (-K1v2.array() + max_wheel_lng_accel);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800287 const Eigen::Matrix<double, 2, 1> accels2 =
James Kuszmaulea314d92019-02-18 19:45:06 -0800288 K2inv.array() * (-K1v2.array() - max_wheel_lng_accel);
289
290 // If either term is non-finite, that suggests that a term of K2 is zero
291 // (which is physically possible when turning such that one wheel is
292 // stationary), so just ignore that side of the drivetrain.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800293 if (std::isfinite(accels1(0))) {
James Kuszmaulea314d92019-02-18 19:45:06 -0800294 // The inner max/min in this case determines which of the two cases (+ or
295 // - acceleration on the left wheel) we care about--in a sufficiently
296 // tight turning radius, the left hweel may be accelerating backwards when
297 // the robot as a whole accelerates forwards. We then use that
298 // acceleration to bound the min/max accel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800299 *min_accel = std::max(*min_accel, std::min(accels1(0), accels2(0)));
300 *max_accel = std::min(*max_accel, std::max(accels1(0), accels2(0)));
James Kuszmaulea314d92019-02-18 19:45:06 -0800301 }
302 // Same logic as previous if-statement, but for the right wheel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800303 if (std::isfinite(accels1(1))) {
304 *min_accel = std::max(*min_accel, std::min(accels1(1), accels2(1)));
305 *max_accel = std::min(*max_accel, std::max(accels1(1), accels2(1)));
James Kuszmaulea314d92019-02-18 19:45:06 -0800306 }
307}
308
309double Trajectory::VoltageVelocityLimit(
310 double distance, VoltageLimit limit_type,
311 Eigen::Matrix<double, 2, 1> *constraint_voltages) const {
312 // To sketch an outline of the math going on here, we start with the basic
313 // dynamics of the robot along the spline:
314 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot + B * U
315 // We need to determine the maximum v_robot given constrained U and free
316 // v_robot'.
317 // Similarly to the friction constraints, we accomplish this by first
318 // multiplying by a K2prime term to eliminate the v_robot' term.
319 // As with the friction constraints, we also know that the limits will occur
320 // when both sides of the drivetrain are driven at their max magnitude
321 // voltages, although they may be driven at different signs.
322 // Once we determine whether the voltages match signs, we still have to
323 // consider both possible pairings (technically we could probably
324 // predetermine which pairing, e.g. +/- or -/+, we acre about, but we don't
325 // need to).
326 //
327 // For each pairing, we then get to solve a quadratic formula for the robot
328 // velocity at those voltages. This gives us up to 4 solutions, of which
329 // up to 3 will give us positive velocities; each solution velocity
330 // corresponds to a transition from feasibility to infeasibility, where a
331 // velocity of zero is always feasible, and there will always be 0, 1, or 3
332 // positive solutions. Among the positive solutions, we take both the min
333 // and the max--the min will be the highest velocity such that all
334 // velocities between zero and that velocity are valid; the max will be
335 // the highest feasible velocity. Which we return depends on what the
336 // limit_type is.
337 //
338 // Sketching the actual math:
339 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot +/- B * U_max
340 // K2prime * K1 * v_robot^2 = K2prime * (A * K2 * v_robot +/- B * U_max)
341 // a v_robot^2 + b v_robot +/- c = 0
James Kuszmaul75a18c52021-03-10 22:02:07 -0800342 const Eigen::Matrix<double, 2, 2> B =
343 velocity_drivetrain().plant().coefficients().B_continuous;
344 const double dtheta = spline().DTheta(distance);
345 const Eigen::Matrix<double, 2, 1> BinvK2 = B.inverse() * K2(dtheta);
James Kuszmaulea314d92019-02-18 19:45:06 -0800346 // Because voltages can actually impact *both* wheels, in order to determine
347 // whether the voltages will have opposite signs, we need to use B^-1 * K2.
348 const bool opposite_voltages = BinvK2(0) * BinvK2(1) > 0.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800349 const Eigen::Matrix<double, 1, 2> K2prime =
James Kuszmaulea314d92019-02-18 19:45:06 -0800350 K2(dtheta).transpose() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800351 (Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
352 const double a = K2prime * K1(spline().DDTheta(distance));
James Kuszmaulea314d92019-02-18 19:45:06 -0800353 const double b = -K2prime *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800354 velocity_drivetrain().plant().coefficients().A_continuous *
James Kuszmaulea314d92019-02-18 19:45:06 -0800355 K2(dtheta);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800356 const Eigen::Matrix<double, 1, 2> c_coeff = -K2prime * B;
James Kuszmaulea314d92019-02-18 19:45:06 -0800357 // Calculate the "positive" version of the voltage limits we will use.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800358 const Eigen::Matrix<double, 2, 1> abs_volts =
359 max_voltage() *
360 (Eigen::Matrix<double, 2, 1>() << 1.0, (opposite_voltages ? -1.0 : 1.0))
James Kuszmaulea314d92019-02-18 19:45:06 -0800361 .finished();
362
James Kuszmaul75a18c52021-03-10 22:02:07 -0800363 double min_valid_vel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800364 if (limit_type == VoltageLimit::kAggressive) {
365 min_valid_vel = 0.0;
366 }
367 // Iterate over both possibilites for +/- voltage, and solve the quadratic
368 // formula. For every positive solution, adjust the velocity limit
369 // appropriately.
370 for (const double sign : {1.0, -1.0}) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800371 const Eigen::Matrix<double, 2, 1> U = sign * abs_volts;
James Kuszmaulea314d92019-02-18 19:45:06 -0800372 const double prev_vel = min_valid_vel;
373 const double c = c_coeff * U;
374 const double determinant = b * b - 4 * a * c;
375 if (a == 0) {
376 // If a == 0, that implies we are on a constant curvature path, in which
377 // case we just have b * v + c = 0.
378 // Note that if -b * c > 0.0, then vel will be greater than zero and b
379 // will be non-zero.
380 if (-b * c > 0.0) {
381 const double vel = -c / b;
382 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800383 min_valid_vel = std::min(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800384 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800385 min_valid_vel = std::max(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800386 }
387 } else if (b == 0) {
388 // If a and b are zero, then we are travelling in a straight line and
389 // have no voltage-based velocity constraints.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800390 min_valid_vel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800391 }
392 } else if (determinant > 0) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800393 const double sqrt_determinant = std::sqrt(determinant);
James Kuszmaulea314d92019-02-18 19:45:06 -0800394 const double high_vel = (-b + sqrt_determinant) / (2.0 * a);
395 const double low_vel = (-b - sqrt_determinant) / (2.0 * a);
396 if (low_vel > 0) {
397 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800398 min_valid_vel = std::min(min_valid_vel, low_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800399 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800400 min_valid_vel = std::max(min_valid_vel, low_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800401 }
402 }
403 if (high_vel > 0) {
404 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800405 min_valid_vel = std::min(min_valid_vel, high_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800406 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800407 min_valid_vel = std::max(min_valid_vel, high_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800408 }
409 }
410 } else if (determinant == 0 && -b * a > 0) {
411 const double vel = -b / (2.0 * a);
412 if (vel > 0.0) {
413 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800414 min_valid_vel = std::min(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800415 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800416 min_valid_vel = std::max(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800417 }
418 }
419 }
420 if (constraint_voltages != nullptr && prev_vel != min_valid_vel) {
421 *constraint_voltages = U;
422 }
423 }
424 return min_valid_vel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100425}
426
427void Trajectory::ForwardPass() {
428 plan_[0] = 0.0;
429 const double delta_distance = Distance(1) - Distance(0);
430 for (size_t i = 0; i < plan_.size() - 1; ++i) {
431 const double distance = Distance(i);
432
433 // Integrate our acceleration forward one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800434 const double new_plan_velocity = IntegrateAccelForDistance(
435 [this](double x, double v) { return ForwardAcceleration(x, v); },
436 plan_[i], distance, delta_distance);
437
James Kuszmaulea314d92019-02-18 19:45:06 -0800438 if (new_plan_velocity <= plan_[i + 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800439 plan_[i + 1] = new_plan_velocity;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800440 plan_segment_type_[i] = fb::SegmentConstraint::ACCELERATION_LIMITED;
Austin Schuhe73a9052019-01-07 12:16:17 -0800441 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100442 }
443}
444
Austin Schuhec7f06d2019-01-04 07:47:15 +1100445void Trajectory::BackwardPass() {
446 const double delta_distance = Distance(0) - Distance(1);
447 plan_.back() = 0.0;
448 for (size_t i = plan_.size() - 1; i > 0; --i) {
449 const double distance = Distance(i);
450
451 // Integrate our deceleration back one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800452 const double new_plan_velocity = IntegrateAccelForDistance(
453 [this](double x, double v) { return BackwardAcceleration(x, v); },
454 plan_[i], distance, delta_distance);
455
James Kuszmaulea314d92019-02-18 19:45:06 -0800456 if (new_plan_velocity <= plan_[i - 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800457 plan_[i - 1] = new_plan_velocity;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800458 plan_segment_type_[i - 1] = fb::SegmentConstraint::DECELERATION_LIMITED;
Austin Schuhe73a9052019-01-07 12:16:17 -0800459 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100460 }
461}
462
James Kuszmaul75a18c52021-03-10 22:02:07 -0800463Eigen::Matrix<double, 3, 1> BaseTrajectory::FFAcceleration(
464 double distance) const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800465 if (distance < 0.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100466 // Make sure we don't end up off the beginning of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800467 distance = 0.0;
468 } else if (distance > length()) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100469 // Make sure we don't end up off the end of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800470 distance = length();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100471 }
Austin Schuhe73a9052019-01-07 12:16:17 -0800472 const size_t before_index = DistanceToSegment(distance);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800473 const size_t after_index =
474 std::min(before_index + 1, distance_plan_size() - 1);
Austin Schuhe73a9052019-01-07 12:16:17 -0800475
Austin Schuhec7f06d2019-01-04 07:47:15 +1100476 const double before_distance = Distance(before_index);
477 const double after_distance = Distance(after_index);
478
Austin Schuhec7f06d2019-01-04 07:47:15 +1100479 // And then also make sure we aren't curvature limited.
480 const double vcurvature = LateralVelocityCurvature(distance);
481
482 double acceleration;
483 double velocity;
James Kuszmaulea314d92019-02-18 19:45:06 -0800484 // TODO(james): While technically correct for sufficiently small segment
485 // steps, this method of switching between limits has a tendency to produce
486 // sudden jumps in acceelrations, which is undesirable.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800487 switch (plan_constraint(DistanceToSegment(distance))) {
488 case fb::SegmentConstraint::VELOCITY_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800489 acceleration = 0.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800490 velocity =
491 (plan_velocity(before_index) + plan_velocity(after_index)) / 2.0;
Austin Schuhe73a9052019-01-07 12:16:17 -0800492 // TODO(austin): Accelerate or decelerate until we hit the limit in the
493 // time slice. Otherwise our acceleration will be lying for this slice.
494 // Do note, we've got small slices so the effect will be small.
495 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800496 case fb::SegmentConstraint::CURVATURE_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800497 velocity = vcurvature;
James Kuszmaulea314d92019-02-18 19:45:06 -0800498 FrictionLngAccelLimits(distance, velocity, &acceleration, &acceleration);
499 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800500 case fb::SegmentConstraint::VOLTAGE_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800501 // Normally, we expect that voltage limited plans will all get dominated
502 // by the acceleration/deceleration limits. This may not always be true;
503 // if we ever encounter this error, we just need to back out what the
504 // accelerations would be in this case.
Austin Schuhd749d932020-12-30 21:38:40 -0800505 LOG(FATAL) << "Unexpectedly got VOLTAGE_LIMITED plan.";
Austin Schuhe73a9052019-01-07 12:16:17 -0800506 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800507 case fb::SegmentConstraint::ACCELERATION_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800508 // TODO(james): The integration done here and in the DECELERATION_LIMITED
509 // can technically cause us to violate friction constraints. We currently
510 // don't do anything about it to avoid causing sudden jumps in voltage,
511 // but we probably *should* at some point.
Austin Schuhe73a9052019-01-07 12:16:17 -0800512 velocity = IntegrateAccelForDistance(
513 [this](double x, double v) { return ForwardAcceleration(x, v); },
James Kuszmaul75a18c52021-03-10 22:02:07 -0800514 plan_velocity(before_index), before_distance,
515 distance - before_distance);
Austin Schuhe73a9052019-01-07 12:16:17 -0800516 acceleration = ForwardAcceleration(distance, velocity);
517 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800518 case fb::SegmentConstraint::DECELERATION_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800519 velocity = IntegrateAccelForDistance(
520 [this](double x, double v) { return BackwardAcceleration(x, v); },
James Kuszmaul75a18c52021-03-10 22:02:07 -0800521 plan_velocity(after_index), after_distance,
522 distance - after_distance);
Austin Schuhe73a9052019-01-07 12:16:17 -0800523 acceleration = BackwardAcceleration(distance, velocity);
524 break;
525 default:
James Kuszmaul75a18c52021-03-10 22:02:07 -0800526 AOS_LOG(FATAL, "Unknown segment type %d\n",
527 static_cast<int>(plan_constraint(DistanceToSegment(distance))));
Austin Schuhe73a9052019-01-07 12:16:17 -0800528 break;
529 }
530
James Kuszmaul75a18c52021-03-10 22:02:07 -0800531 return (Eigen::Matrix<double, 3, 1>() << distance, velocity, acceleration)
Austin Schuhec7f06d2019-01-04 07:47:15 +1100532 .finished();
533}
534
James Kuszmaul75a18c52021-03-10 22:02:07 -0800535size_t FinishedTrajectory::distance_plan_size() const {
536 return trajectory().has_distance_based_plan()
537 ? trajectory().distance_based_plan()->size()
538 : 0u;
539}
540
541fb::SegmentConstraint FinishedTrajectory::plan_constraint(size_t index) const {
542 CHECK_LT(index, distance_plan_size());
543 return trajectory().distance_based_plan()->Get(index)->segment_constraint();
544}
545
546float FinishedTrajectory::plan_velocity(size_t index) const {
547 CHECK_LT(index, distance_plan_size());
548 return trajectory().distance_based_plan()->Get(index)->velocity();
549}
550
551Eigen::Matrix<double, 2, 1> BaseTrajectory::FFVoltage(double distance) const {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100552 const Eigen::Matrix<double, 3, 1> xva = FFAcceleration(distance);
553 const double velocity = xva(1);
554 const double acceleration = xva(2);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100555
James Kuszmaul75a18c52021-03-10 22:02:07 -0800556 Eigen::Matrix<double, 2, 1> K3;
557 Eigen::Matrix<double, 2, 1> K4;
558 Eigen::Matrix<double, 2, 1> K5;
Austin Schuhe73a9052019-01-07 12:16:17 -0800559 K345(distance, &K3, &K4, &K5);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100560
561 return K5 * acceleration + K3 * velocity * velocity + K4 * velocity;
562}
563
James Kuszmaul75a18c52021-03-10 22:02:07 -0800564const std::vector<double> Trajectory::Distances() const {
565 std::vector<double> d;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100566 d.reserve(plan_.size());
567 for (size_t i = 0; i < plan_.size(); ++i) {
568 d.push_back(Distance(i));
569 }
570 return d;
571}
572
James Kuszmaul75a18c52021-03-10 22:02:07 -0800573Eigen::Matrix<double, 3, 1> BaseTrajectory::GetNextXVA(
574 std::chrono::nanoseconds dt, Eigen::Matrix<double, 2, 1> *state) const {
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700575 double dt_float = ::aos::time::DurationInSeconds(dt);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100576
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800577 const double last_distance = (*state)(0);
Alex Perry4ae2fd72019-02-03 15:55:57 -0800578 // TODO(austin): This feels like something that should be pulled out into
579 // a library for re-use.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700580 *state = RungeKutta(
James Kuszmaul75a18c52021-03-10 22:02:07 -0800581 [this](const Eigen::Matrix<double, 2, 1> x) {
582 Eigen::Matrix<double, 3, 1> xva = FFAcceleration(x(0));
583 return (Eigen::Matrix<double, 2, 1>() << x(1), xva(2)).finished();
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700584 },
585 *state, dt_float);
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800586 // Force the distance to move forwards, to guarantee that we actually finish
587 // the planning.
588 constexpr double kMinDistanceIncrease = 1e-7;
589 if ((*state)(0) < last_distance + kMinDistanceIncrease) {
590 (*state)(0) = last_distance + kMinDistanceIncrease;
591 }
Alex Perry4ae2fd72019-02-03 15:55:57 -0800592
James Kuszmaul75a18c52021-03-10 22:02:07 -0800593 Eigen::Matrix<double, 3, 1> result = FFAcceleration((*state)(0));
Alex Perry4ae2fd72019-02-03 15:55:57 -0800594 (*state)(1) = result(1);
595 return result;
596}
597
James Kuszmaul75a18c52021-03-10 22:02:07 -0800598std::vector<Eigen::Matrix<double, 3, 1>> Trajectory::PlanXVA(
599 std::chrono::nanoseconds dt) {
600 Eigen::Matrix<double, 2, 1> state = Eigen::Matrix<double, 2, 1>::Zero();
601 std::vector<Eigen::Matrix<double, 3, 1>> result;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100602 result.emplace_back(FFAcceleration(0));
603 result.back()(1) = 0.0;
604
Alex Perry4ae2fd72019-02-03 15:55:57 -0800605 while (!is_at_end(state)) {
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800606 if (state_is_faulted(state)) {
607 LOG(WARNING)
608 << "Found invalid state in generating spline and aborting. This is "
609 "likely due to a spline with extremely high jerk/changes in "
610 "curvature with an insufficiently small step size.";
611 return {};
612 }
Alex Perry4ae2fd72019-02-03 15:55:57 -0800613 result.emplace_back(GetNextXVA(dt, &state));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100614 }
615 return result;
616}
617
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800618void Trajectory::LimitVelocity(double starting_distance, double ending_distance,
619 const double max_velocity) {
620 const double segment_length = ending_distance - starting_distance;
621
622 const double min_length = length() / static_cast<double>(plan_.size() - 1);
623 if (starting_distance > ending_distance) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700624 AOS_LOG(FATAL, "End before start: %f > %f\n", starting_distance,
625 ending_distance);
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800626 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800627 starting_distance = std::min(length(), std::max(0.0, starting_distance));
628 ending_distance = std::min(length(), std::max(0.0, ending_distance));
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800629 if (segment_length < min_length) {
630 const size_t plan_index = static_cast<size_t>(
James Kuszmaul75a18c52021-03-10 22:02:07 -0800631 std::round((starting_distance + ending_distance) / 2.0 / min_length));
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800632 if (max_velocity < plan_[plan_index]) {
633 plan_[plan_index] = max_velocity;
634 }
635 } else {
636 for (size_t i = DistanceToSegment(starting_distance) + 1;
637 i < DistanceToSegment(ending_distance) + 1; ++i) {
638 if (max_velocity < plan_[i]) {
639 plan_[i] = max_velocity;
640 if (i < DistanceToSegment(ending_distance)) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800641 plan_segment_type_[i] = fb::SegmentConstraint::VELOCITY_LIMITED;
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800642 }
643 }
644 }
645 }
646}
647
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700648void Trajectory::PathRelativeContinuousSystem(double distance,
649 Eigen::Matrix<double, 5, 5> *A,
650 Eigen::Matrix<double, 5, 2> *B) {
651 const double nominal_velocity = FFAcceleration(distance)(1);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800652 const double dtheta_dt = spline().DThetaDt(distance, nominal_velocity);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700653 // Calculate the "path-relative" coordinates, which are:
654 // [[distance along the path],
655 // [lateral position along path],
656 // [theta],
657 // [left wheel velocity],
658 // [right wheel velocity]]
659 Eigen::Matrix<double, 5, 1> nominal_X;
660 nominal_X << distance, 0.0, 0.0,
James Kuszmaul75a18c52021-03-10 22:02:07 -0800661 nominal_velocity - dtheta_dt * robot_radius_l(),
662 nominal_velocity + dtheta_dt * robot_radius_r();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700663 PathRelativeContinuousSystem(nominal_X, A, B);
664}
665
666void Trajectory::PathRelativeContinuousSystem(
667 const Eigen::Matrix<double, 5, 1> &X, Eigen::Matrix<double, 5, 5> *A,
668 Eigen::Matrix<double, 5, 2> *B) {
669 A->setZero();
670 B->setZero();
671 const double theta = X(2);
672 const double ctheta = std::cos(theta);
673 const double stheta = std::sin(theta);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800674 const double curvature = spline().DTheta(X(0));
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700675 const double longitudinal_velocity = (X(3) + X(4)) / 2.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800676 const double diameter = robot_radius_l() + robot_radius_r();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700677 // d_dpath / dt = (v_left + v_right) / 2.0 * cos(theta)
678 // (d_dpath / dt) / dv_left = cos(theta) / 2.0
679 (*A)(0, 3) = ctheta / 2.0;
680 // (d_dpath / dt) / dv_right = cos(theta) / 2.0
681 (*A)(0, 4) = ctheta / 2.0;
682 // (d_dpath / dt) / dtheta = -(v_left + v_right) / 2.0 * sin(theta)
683 (*A)(0, 2) = -longitudinal_velocity * stheta;
684 // d_dlat / dt = (v_left + v_right) / 2.0 * sin(theta)
685 // (d_dlat / dt) / dv_left = sin(theta) / 2.0
686 (*A)(1, 3) = stheta / 2.0;
687 // (d_dlat / dt) / dv_right = sin(theta) / 2.0
688 (*A)(1, 4) = stheta / 2.0;
689 // (d_dlat / dt) / dtheta = (v_left + v_right) / 2.0 * cos(theta)
690 (*A)(1, 2) = longitudinal_velocity * ctheta;
691 // dtheta / dt = (v_right - v_left) / diameter - curvature * (v_left +
692 // v_right) / 2.0
693 // (dtheta / dt) / dv_left = -1.0 / diameter - curvature / 2.0
694 (*A)(2, 3) = -1.0 / diameter - curvature / 2.0;
695 // (dtheta / dt) / dv_right = 1.0 / diameter - curvature / 2.0
696 (*A)(2, 4) = 1.0 / diameter - curvature / 2.0;
697 // v_{left,right} / dt = the normal LTI system.
698 A->block<2, 2>(3, 3) =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800699 velocity_drivetrain().plant().coefficients().A_continuous;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700700 B->block<2, 2>(3, 0) =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800701 velocity_drivetrain().plant().coefficients().B_continuous;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700702}
703
704double Trajectory::EstimateDistanceAlongPath(
705 double nominal_distance, const Eigen::Matrix<double, 5, 1> &state) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800706 const double nominal_theta = spline().Theta(nominal_distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700707 const Eigen::Matrix<double, 2, 1> xy_err =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800708 state.block<2, 1>(0, 0) - spline().XY(nominal_distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700709 return nominal_distance + xy_err.x() * std::cos(nominal_theta) +
710 xy_err.y() * std::sin(nominal_theta);
711}
712
James Kuszmaul75a18c52021-03-10 22:02:07 -0800713Eigen::Matrix<double, 5, 1> FinishedTrajectory::StateToPathRelativeState(
714 double distance, const Eigen::Matrix<double, 5, 1> &state) const {
715 const double nominal_theta = spline().Theta(distance);
716 const Eigen::Matrix<double, 2, 1> nominal_xy = spline().XY(distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700717 const Eigen::Matrix<double, 2, 1> xy_err =
718 state.block<2, 1>(0, 0) - nominal_xy;
719 const double ctheta = std::cos(nominal_theta);
720 const double stheta = std::sin(nominal_theta);
721 Eigen::Matrix<double, 5, 1> path_state;
722 path_state(0) = distance + xy_err.x() * ctheta + xy_err.y() * stheta;
723 path_state(1) = -xy_err.x() * stheta + xy_err.y() * ctheta;
724 path_state(2) = state(2) - nominal_theta;
725 path_state(3) = state(3);
726 path_state(4) = state(4);
727 return path_state;
728}
729
730// Path-relative controller method:
731// For the path relative controller, we use a non-standard version of LQR to
732// perform the control. Essentially, we first transform the system into
733// a set of path-relative coordinates (where the reference that we use is the
734// desired path reference). This gives us a system that is linear and
735// time-varying, i.e. the system is a set of A_k, B_k matrices for each
736// timestep k.
737// In order to control this, we use a discrete-time finite-horizon LQR, using
738// the appropraite [AB]_k for the given timestep. Note that the finite-horizon
739// LQR requires choosing a terminal cost (i.e., what the cost should be
740// for if we have not precisely reached the goal at the end of the time-period).
741// For this, I approximate the infinite-horizon LQR solution by extending the
742// finite-horizon much longer (albeit with the extension just using the
743// linearization for the infal point).
744void Trajectory::CalculatePathGains() {
745 const std::vector<Eigen::Matrix<double, 3, 1>> xva_plan = PlanXVA(config_.dt);
James Kuszmaulc3eaa472021-03-03 19:43:45 -0800746 if (xva_plan.empty()) {
747 LOG(ERROR) << "Plan is empty--unable to plan trajectory.";
748 return;
749 }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700750 plan_gains_.resize(xva_plan.size());
751
752 // Set up reasonable gain matrices. Current choices of gains are arbitrary
753 // and just setup to work well enough for the simulation tests.
754 // TODO(james): Tune this on a real robot.
755 // TODO(james): Pull these out into a config.
756 Eigen::Matrix<double, 5, 5> Q;
757 Q.setIdentity();
758 Q.diagonal() << 20.0, 20.0, 20.0, 10.0, 10.0;
759 Q *= 2.0;
760 Q = (Q * Q).eval();
761
762 Eigen::Matrix<double, 2, 2> R;
763 R.setIdentity();
764 R *= 5.0;
765
766 Eigen::Matrix<double, 5, 5> P = Q;
767
768 CHECK_LT(0u, xva_plan.size());
769 const int max_index = static_cast<int>(xva_plan.size()) - 1;
770 for (int i = max_index; i >= 0; --i) {
771 const double distance = xva_plan[i](0);
772 Eigen::Matrix<double, 5, 5> A_continuous;
773 Eigen::Matrix<double, 5, 2> B_continuous;
774 PathRelativeContinuousSystem(distance, &A_continuous, &B_continuous);
775 Eigen::Matrix<double, 5, 5> A_discrete;
776 Eigen::Matrix<double, 5, 2> B_discrete;
777 controls::C2D(A_continuous, B_continuous, config_.dt, &A_discrete,
778 &B_discrete);
779
780 if (i == max_index) {
781 // At the final timestep, approximate P by iterating a bunch of times.
782 // This is terminal cost mentioned in function-level comments.
783 // This does a very loose job of solving the DARE. Ideally, we would
784 // actually use a DARE solver directly, but based on some initial testing,
785 // this method is a bit more robust (or, at least, it is a bit more robust
786 // if we don't want to spend more time handling the potential error
787 // cases the DARE solver can encounter).
788 constexpr int kExtraIters = 100;
789 for (int jj = 0; jj < kExtraIters; ++jj) {
790 const Eigen::Matrix<double, 5, 5> AP = A_discrete.transpose() * P;
791 const Eigen::Matrix<double, 5, 2> APB = AP * B_discrete;
792 const Eigen::Matrix<double, 2, 2> RBPBinv =
793 (R + B_discrete.transpose() * P * B_discrete).inverse();
794 P = AP * A_discrete - APB * RBPBinv * APB.transpose() + Q;
795 }
796 }
797
798 const Eigen::Matrix<double, 5, 5> AP = A_discrete.transpose() * P;
799 const Eigen::Matrix<double, 5, 2> APB = AP * B_discrete;
800 const Eigen::Matrix<double, 2, 2> RBPBinv =
801 (R + B_discrete.transpose() * P * B_discrete).inverse();
802 plan_gains_[i].first = distance;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800803 const Eigen::Matrix<double, 2, 5> K = RBPBinv * APB.transpose();
804 plan_gains_[i].second = K.cast<float>();
805 P = AP * A_discrete - APB * K + Q;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700806 }
807}
808
James Kuszmaul75a18c52021-03-10 22:02:07 -0800809Eigen::Matrix<double, 2, 5> FinishedTrajectory::GainForDistance(
810 double distance) const {
811 const flatbuffers::Vector<flatbuffers::Offset<fb::GainPoint>> &gains =
812 *CHECK_NOTNULL(trajectory().gains());
813 CHECK_LT(0u, gains.size());
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700814 size_t index = 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800815 for (index = 0; index < gains.size() - 1; ++index) {
816 if (gains[index + 1]->distance() > distance) {
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700817 break;
818 }
819 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800820 // ColMajor is the default storage order, but call it out explicitly here.
821 return Eigen::Matrix<float, 2, 5, Eigen::ColMajor>{
822 gains[index]->gains()->data()}
823 .cast<double>();
824}
825
826namespace {
827flatbuffers::Offset<Constraint> MakeWholeLengthConstraint(
828 flatbuffers::FlatBufferBuilder *fbb, ConstraintType constraint_type,
829 float value) {
830 Constraint::Builder builder(*fbb);
831 builder.add_constraint_type(constraint_type);
832 builder.add_value(value);
833 return builder.Finish();
834}
835} // namespace
836
837flatbuffers::Offset<fb::Trajectory> Trajectory::Serialize(
838 flatbuffers::FlatBufferBuilder *fbb) const {
839 std::array<flatbuffers::Offset<Constraint>, 3> constraints_offsets = {
840 MakeWholeLengthConstraint(fbb, ConstraintType::LONGITUDINAL_ACCELERATION,
841 max_longitudinal_accel()),
842 MakeWholeLengthConstraint(fbb, ConstraintType::LATERAL_ACCELERATION,
843 max_lateral_accel()),
844 MakeWholeLengthConstraint(fbb, ConstraintType::VOLTAGE, max_voltage())};
845 const auto constraints = fbb->CreateVector<Constraint>(
846 constraints_offsets.data(), constraints_offsets.size());
847 const flatbuffers::Offset<fb::DistanceSpline> spline_offset =
848 spline().Serialize(fbb, constraints);
849
850 std::vector<flatbuffers::Offset<fb::PlanPoint>> plan_points;
851 for (size_t ii = 0; ii < distance_plan_size(); ++ii) {
852 plan_points.push_back(fb::CreatePlanPoint(
853 *fbb, Distance(ii), plan_velocity(ii), plan_constraint(ii)));
854 }
855
856 // TODO(james): What is an appropriate cap?
857 CHECK_LT(plan_gains_.size(), 5000u);
858 CHECK_LT(0u, plan_gains_.size());
859 std::vector<flatbuffers::Offset<fb::GainPoint>> gain_points;
860 const size_t matrix_size = plan_gains_[0].second.size();
861 for (size_t ii = 0; ii < plan_gains_.size(); ++ii) {
862 gain_points.push_back(fb::CreateGainPoint(
863 *fbb, plan_gains_[ii].first,
864 fbb->CreateVector(plan_gains_[ii].second.data(), matrix_size)));
865 }
866
867 return fb::CreateTrajectory(*fbb, spline_idx_, fbb->CreateVector(plan_points),
868 fbb->CreateVector(gain_points), spline_offset,
869 drive_spline_backwards_);
870}
871
872float BaseTrajectory::ConstraintValue(
873 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
874 ConstraintType type) {
875 if (constraints != nullptr) {
876 for (const Constraint *constraint : *constraints) {
877 if (constraint->constraint_type() == type) {
878 return constraint->value();
879 }
880 }
881 }
882 return DefaultConstraint(type);
883}
884
885const Eigen::Matrix<double, 5, 1> BaseTrajectory::GoalState(
886 double distance, double velocity) const {
887 Eigen::Matrix<double, 5, 1> result;
888 result.block<2, 1>(0, 0) = spline().XY(distance);
889 result(2, 0) = spline().Theta(distance);
890
891 result.block<2, 1>(3, 0) =
892 config_.Tla_to_lr() * (Eigen::Matrix<double, 2, 1>() << velocity,
893 spline().DThetaDt(distance, velocity))
894 .finished();
895 return result;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700896}
897
Austin Schuhec7f06d2019-01-04 07:47:15 +1100898} // namespace drivetrain
899} // namespace control_loops
900} // namespace frc971