blob: 76a6784540f72f8ffcf55b464ba1d70eccd6099c [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"
Philipp Schrader790cb542023-07-05 21:06:52 -07006
7#include "aos/util/math.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +11008#include "frc971/control_loops/c2d.h"
James Kuszmaul651fc3f2019-05-15 21:14:25 -07009#include "frc971/control_loops/dlqr.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +110010#include "frc971/control_loops/drivetrain/distance_spline.h"
11#include "frc971/control_loops/drivetrain/drivetrain_config.h"
12#include "frc971/control_loops/hybrid_state_feedback_loop.h"
13#include "frc971/control_loops/state_feedback_loop.h"
14
15namespace frc971 {
16namespace control_loops {
17namespace drivetrain {
18
James Kuszmaul75a18c52021-03-10 22:02:07 -080019namespace {
20float DefaultConstraint(ConstraintType type) {
21 switch (type) {
22 case ConstraintType::LONGITUDINAL_ACCELERATION:
23 return 2.0;
24 case ConstraintType::LATERAL_ACCELERATION:
25 return 3.0;
26 case ConstraintType::VOLTAGE:
27 return 12.0;
28 case ConstraintType::VELOCITY:
29 case ConstraintType::CONSTRAINT_TYPE_UNDEFINED:
30 LOG(FATAL) << "No default constraint value for "
31 << EnumNameConstraintType(type);
32 }
33 LOG(FATAL) << "Invalid ConstraintType " << static_cast<int>(type);
34}
35} // namespace
36
Austin Schuhf7c65202022-11-04 21:28:20 -070037FinishedTrajectory::FinishedTrajectory(
38 const DrivetrainConfig<double> &config, const fb::Trajectory *buffer,
39 std::shared_ptr<
40 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
41 HybridKalman<2, 2, 2>>>
42 velocity_drivetrain)
James Kuszmaul75a18c52021-03-10 22:02:07 -080043 : BaseTrajectory(CHECK_NOTNULL(CHECK_NOTNULL(buffer->spline())->spline())
44 ->constraints(),
Austin Schuhf7c65202022-11-04 21:28:20 -070045 config, std::move(velocity_drivetrain)),
James Kuszmaul75a18c52021-03-10 22:02:07 -080046 buffer_(buffer),
47 spline_(*buffer_->spline()) {}
48
49const Eigen::Matrix<double, 2, 1> BaseTrajectory::K1(
50 double current_ddtheta) const {
51 return (Eigen::Matrix<double, 2, 1>() << -robot_radius_l_ * current_ddtheta,
52 robot_radius_r_ * current_ddtheta)
53 .finished();
54}
55
56const Eigen::Matrix<double, 2, 1> BaseTrajectory::K2(
57 double current_dtheta) const {
58 return (Eigen::Matrix<double, 2, 1>()
59 << 1.0 - robot_radius_l_ * current_dtheta,
60 1.0 + robot_radius_r_ * current_dtheta)
61 .finished();
62}
63
64void BaseTrajectory::K345(const double x, Eigen::Matrix<double, 2, 1> *K3,
65 Eigen::Matrix<double, 2, 1> *K4,
66 Eigen::Matrix<double, 2, 1> *K5) const {
67 const double current_ddtheta = spline().DDTheta(x);
68 const double current_dtheta = spline().DTheta(x);
69 // We've now got the equation:
70 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
71 const Eigen::Matrix<double, 2, 1> my_K2 = K2(current_dtheta);
72
73 const Eigen::Matrix<double, 2, 2> B_inverse =
74 velocity_drivetrain_->plant().coefficients().B_continuous.inverse();
75
76 // Now, rephrase it as K5 a + K3 v^2 + K4 v = U
77 *K3 = B_inverse * K1(current_ddtheta);
78 *K4 = -B_inverse * velocity_drivetrain_->plant().coefficients().A_continuous *
79 my_K2;
80 *K5 = B_inverse * my_K2;
81}
82
83BaseTrajectory::BaseTrajectory(
84 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
Austin Schuhf7c65202022-11-04 21:28:20 -070085 const DrivetrainConfig<double> &config,
86 std::shared_ptr<
87 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
88 HybridKalman<2, 2, 2>>>
89 velocity_drivetrain)
90 : velocity_drivetrain_(std::move(velocity_drivetrain)),
James Kuszmaulaa2499d2020-06-02 21:31:19 -070091 config_(config),
Austin Schuhec7f06d2019-01-04 07:47:15 +110092 robot_radius_l_(config.robot_radius),
93 robot_radius_r_(config.robot_radius),
James Kuszmaul75a18c52021-03-10 22:02:07 -080094 lateral_acceleration_(
95 ConstraintValue(constraints, ConstraintType::LATERAL_ACCELERATION)),
96 longitudinal_acceleration_(ConstraintValue(
97 constraints, ConstraintType::LONGITUDINAL_ACCELERATION)),
98 voltage_limit_(ConstraintValue(constraints, ConstraintType::VOLTAGE)) {}
99
100Trajectory::Trajectory(const SplineGoal &spline_goal,
101 const DrivetrainConfig<double> &config)
102 : Trajectory(DistanceSpline{spline_goal.spline()}, config,
103 spline_goal.spline()->constraints(),
104 spline_goal.spline_idx()) {
105 drive_spline_backwards_ = spline_goal.drive_spline_backwards();
106}
107
108Trajectory::Trajectory(
109 DistanceSpline &&input_spline, const DrivetrainConfig<double> &config,
110 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
111 int spline_idx, double vmax, int num_distance)
112 : BaseTrajectory(constraints, config),
113 spline_idx_(spline_idx),
114 spline_(std::move(input_spline)),
115 config_(config),
Austin Schuhe73a9052019-01-07 12:16:17 -0800116 plan_(num_distance == 0
Austin Schuh890196c2021-03-31 20:18:45 -0700117 ? std::max(10000, static_cast<int>(spline_.length() / 0.0025))
Austin Schuhe73a9052019-01-07 12:16:17 -0800118 : num_distance,
119 vmax),
James Kuszmaul75a18c52021-03-10 22:02:07 -0800120 plan_segment_type_(plan_.size(),
121 fb::SegmentConstraint::VELOCITY_LIMITED) {
122 if (constraints != nullptr) {
123 for (const Constraint *constraint : *constraints) {
124 if (constraint->constraint_type() == ConstraintType::VELOCITY) {
125 LimitVelocity(constraint->start_distance(), constraint->end_distance(),
126 constraint->value());
127 }
128 }
129 }
130}
Austin Schuhec7f06d2019-01-04 07:47:15 +1100131
132void Trajectory::LateralAccelPass() {
133 for (size_t i = 0; i < plan_.size(); ++i) {
134 const double distance = Distance(i);
Austin Schuhd749d932020-12-30 21:38:40 -0800135 const double velocity_limit = LateralVelocityCurvature(distance);
James Kuszmaulea314d92019-02-18 19:45:06 -0800136 if (velocity_limit < plan_[i]) {
137 plan_[i] = velocity_limit;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800138 plan_segment_type_[i] = fb::SegmentConstraint::CURVATURE_LIMITED;
James Kuszmaulea314d92019-02-18 19:45:06 -0800139 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100140 }
141}
142
James Kuszmaulea314d92019-02-18 19:45:06 -0800143void Trajectory::VoltageFeasibilityPass(VoltageLimit limit_type) {
144 for (size_t i = 0; i < plan_.size(); ++i) {
145 const double distance = Distance(i);
146 const double velocity_limit = VoltageVelocityLimit(distance, limit_type);
147 if (velocity_limit < plan_[i]) {
148 plan_[i] = velocity_limit;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800149 plan_segment_type_[i] = fb::SegmentConstraint::VOLTAGE_LIMITED;
James Kuszmaulea314d92019-02-18 19:45:06 -0800150 }
151 }
152}
153
James Kuszmaul75a18c52021-03-10 22:02:07 -0800154double BaseTrajectory::BestAcceleration(double x, double v,
155 bool backwards) const {
156 Eigen::Matrix<double, 2, 1> K3;
157 Eigen::Matrix<double, 2, 1> K4;
158 Eigen::Matrix<double, 2, 1> K5;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100159 K345(x, &K3, &K4, &K5);
160
Austin Schuhec7f06d2019-01-04 07:47:15 +1100161 // Now, solve for all a's and find the best one which meets our criteria.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800162 const Eigen::Matrix<double, 2, 1> C = K3 * v * v + K4 * v;
163 double min_voltage_accel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800164 double max_voltage_accel = -min_voltage_accel;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800165 for (const double a : {(max_voltage() - C(0, 0)) / K5(0, 0),
166 (max_voltage() - C(1, 0)) / K5(1, 0),
167 (-max_voltage() - C(0, 0)) / K5(0, 0),
168 (-max_voltage() - C(1, 0)) / K5(1, 0)}) {
169 const Eigen::Matrix<double, 2, 1> U = K5 * a + K3 * v * v + K4 * v;
170 if ((U.array().abs() < max_voltage() + 1e-6).all()) {
171 min_voltage_accel = std::min(a, min_voltage_accel);
172 max_voltage_accel = std::max(a, max_voltage_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100173 }
174 }
James Kuszmaulea314d92019-02-18 19:45:06 -0800175 double best_accel = backwards ? min_voltage_accel : max_voltage_accel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100176
James Kuszmaulea314d92019-02-18 19:45:06 -0800177 double min_friction_accel, max_friction_accel;
178 FrictionLngAccelLimits(x, v, &min_friction_accel, &max_friction_accel);
179 if (backwards) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800180 best_accel = std::max(best_accel, min_friction_accel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800181 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800182 best_accel = std::min(best_accel, max_friction_accel);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100183 }
James Kuszmaulea314d92019-02-18 19:45:06 -0800184
James Kuszmaul66b78042020-02-23 15:30:51 -0800185 // Ideally, the max would never be less than the min, but due to the way that
186 // the runge kutta solver works, it sometimes ticks over the edge.
187 if (max_friction_accel < min_friction_accel) {
188 VLOG(1) << "At x " << x << " v " << v << " min fric acc "
189 << min_friction_accel << " max fric accel " << max_friction_accel;
190 }
191 if (best_accel < min_voltage_accel || best_accel > max_voltage_accel) {
192 LOG(WARNING) << "Viable friction limits and viable voltage limits do not "
Austin Schuhd749d932020-12-30 21:38:40 -0800193 "overlap (x: "
194 << x << ", v: " << v << ", backwards: " << backwards
James Kuszmaul66b78042020-02-23 15:30:51 -0800195 << ") best_accel = " << best_accel << ", min voltage "
196 << min_voltage_accel << ", max voltage " << max_voltage_accel
197 << " min friction " << min_friction_accel << " max friction "
198 << max_friction_accel << ".";
199
James Kuszmaulea314d92019-02-18 19:45:06 -0800200 // Don't actually do anything--this will just result in attempting to drive
201 // higher voltages thatn we have available. In practice, that'll probably
202 // work out fine.
203 }
204
205 return best_accel;
206}
207
James Kuszmaul75a18c52021-03-10 22:02:07 -0800208double BaseTrajectory::LateralVelocityCurvature(double distance) const {
James Kuszmaulea314d92019-02-18 19:45:06 -0800209 // To calculate these constraints, we first note that:
210 // wheel accels = K2 * v_robot' + K1 * v_robot^2
211 // All that this logic does is solve for v_robot, leaving v_robot' free,
212 // assuming that the wheels are at their limits.
213 // To do this, we:
214 //
215 // 1) Determine what the wheel accels will be at the limit--since we have
216 // two free variables (v_robot, v_robot'), both wheels will be at their
217 // limits--if in a sufficiently tight turn (such that the signs of the
218 // coefficients of K2 are different), then the wheels will be accelerating
219 // in opposite directions; otherwise, they accelerate in the same direction.
220 // The magnitude of these per-wheel accelerations is a function of velocity,
221 // so it must also be solved for.
222 //
223 // 2) Eliminate that v_robot' term (since we don't care
224 // about it) by multiplying be a "K2prime" term (where K2prime * K2 = 0) on
225 // both sides of the equation.
226 //
227 // 3) Solving the relatively tractable remaining equation, which is
228 // basically just grouping all the terms together in one spot and taking the
229 // 4th root of everything.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800230 const double dtheta = spline().DTheta(distance);
231 const Eigen::Matrix<double, 1, 2> K2prime =
James Kuszmaulea314d92019-02-18 19:45:06 -0800232 K2(dtheta).transpose() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800233 (Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
James Kuszmaulea314d92019-02-18 19:45:06 -0800234 // Calculate whether the wheels are spinning in opposite directions.
235 const bool opposites = K2prime(0) * K2prime(1) < 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800236 const Eigen::Matrix<double, 2, 1> K1calc = K1(spline().DDTheta(distance));
237 const double lat_accel_squared = std::pow(dtheta / max_lateral_accel(), 2);
James Kuszmaulea314d92019-02-18 19:45:06 -0800238 const double curvature_change_term =
239 (K2prime * K1calc).value() /
240 (K2prime *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800241 (Eigen::Matrix<double, 2, 1>() << 1.0, (opposites ? -1.0 : 1.0))
James Kuszmaulea314d92019-02-18 19:45:06 -0800242 .finished() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800243 max_longitudinal_accel())
James Kuszmaulea314d92019-02-18 19:45:06 -0800244 .value();
James Kuszmaul75a18c52021-03-10 22:02:07 -0800245 const double vel_inv = std::sqrt(
246 std::sqrt(std::pow(curvature_change_term, 2) + lat_accel_squared));
James Kuszmaulea314d92019-02-18 19:45:06 -0800247 if (vel_inv == 0.0) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800248 return std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800249 }
250 return 1.0 / vel_inv;
251}
252
James Kuszmaul75a18c52021-03-10 22:02:07 -0800253void BaseTrajectory::FrictionLngAccelLimits(double x, double v,
254 double *min_accel,
255 double *max_accel) const {
James Kuszmaulea314d92019-02-18 19:45:06 -0800256 // First, calculate the max longitudinal acceleration that can be achieved
257 // by either wheel given the friction elliipse that we have.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800258 const double lateral_acceleration = v * v * spline().DDXY(x).norm();
James Kuszmaulea314d92019-02-18 19:45:06 -0800259 const double max_wheel_lng_accel_squared =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800260 1.0 - std::pow(lateral_acceleration / max_lateral_accel(), 2.0);
James Kuszmaulea314d92019-02-18 19:45:06 -0800261 if (max_wheel_lng_accel_squared < 0.0) {
James Kuszmaul66b78042020-02-23 15:30:51 -0800262 VLOG(1) << "Something (probably Runge-Kutta) queried invalid velocity " << v
263 << " at distance " << x;
James Kuszmaulea314d92019-02-18 19:45:06 -0800264 // If we encounter this, it means that the Runge-Kutta has attempted to
265 // sample points a bit past the edge of the friction boundary. If so, we
266 // gradually ramp the min/max accels to be more and more incorrect (note
267 // how min_accel > max_accel if we reach this case) to avoid causing any
268 // numerical issues.
269 *min_accel =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800270 std::sqrt(-max_wheel_lng_accel_squared) * max_longitudinal_accel();
James Kuszmaulea314d92019-02-18 19:45:06 -0800271 *max_accel = -*min_accel;
272 return;
273 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800274 *min_accel = -std::numeric_limits<double>::infinity();
275 *max_accel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800276
277 // Calculate max/min accelerations by calculating what the robots overall
278 // longitudinal acceleration would be if each wheel were running at the max
279 // forwards/backwards longitudinal acceleration.
280 const double max_wheel_lng_accel =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800281 max_longitudinal_accel() * std::sqrt(max_wheel_lng_accel_squared);
282 const Eigen::Matrix<double, 2, 1> K1v2 = K1(spline().DDTheta(x)) * v * v;
283 const Eigen::Matrix<double, 2, 1> K2inv =
284 K2(spline().DTheta(x)).cwiseInverse();
James Kuszmaulea314d92019-02-18 19:45:06 -0800285 // Store the accelerations of the robot corresponding to each wheel being at
286 // the max/min acceleration. The first coefficient in each vector
287 // corresponds to the left wheel, the second to the right wheel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800288 const Eigen::Matrix<double, 2, 1> accels1 =
James Kuszmaulea314d92019-02-18 19:45:06 -0800289 K2inv.array() * (-K1v2.array() + max_wheel_lng_accel);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800290 const Eigen::Matrix<double, 2, 1> accels2 =
James Kuszmaulea314d92019-02-18 19:45:06 -0800291 K2inv.array() * (-K1v2.array() - max_wheel_lng_accel);
292
293 // If either term is non-finite, that suggests that a term of K2 is zero
294 // (which is physically possible when turning such that one wheel is
295 // stationary), so just ignore that side of the drivetrain.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800296 if (std::isfinite(accels1(0))) {
James Kuszmaulea314d92019-02-18 19:45:06 -0800297 // The inner max/min in this case determines which of the two cases (+ or
298 // - acceleration on the left wheel) we care about--in a sufficiently
299 // tight turning radius, the left hweel may be accelerating backwards when
300 // the robot as a whole accelerates forwards. We then use that
301 // acceleration to bound the min/max accel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800302 *min_accel = std::max(*min_accel, std::min(accels1(0), accels2(0)));
303 *max_accel = std::min(*max_accel, std::max(accels1(0), accels2(0)));
James Kuszmaulea314d92019-02-18 19:45:06 -0800304 }
305 // Same logic as previous if-statement, but for the right wheel.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800306 if (std::isfinite(accels1(1))) {
307 *min_accel = std::max(*min_accel, std::min(accels1(1), accels2(1)));
308 *max_accel = std::min(*max_accel, std::max(accels1(1), accels2(1)));
James Kuszmaulea314d92019-02-18 19:45:06 -0800309 }
310}
311
312double Trajectory::VoltageVelocityLimit(
313 double distance, VoltageLimit limit_type,
314 Eigen::Matrix<double, 2, 1> *constraint_voltages) const {
315 // To sketch an outline of the math going on here, we start with the basic
316 // dynamics of the robot along the spline:
317 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot + B * U
318 // We need to determine the maximum v_robot given constrained U and free
319 // v_robot'.
320 // Similarly to the friction constraints, we accomplish this by first
321 // multiplying by a K2prime term to eliminate the v_robot' term.
322 // As with the friction constraints, we also know that the limits will occur
323 // when both sides of the drivetrain are driven at their max magnitude
324 // voltages, although they may be driven at different signs.
325 // Once we determine whether the voltages match signs, we still have to
326 // consider both possible pairings (technically we could probably
327 // predetermine which pairing, e.g. +/- or -/+, we acre about, but we don't
328 // need to).
329 //
330 // For each pairing, we then get to solve a quadratic formula for the robot
331 // velocity at those voltages. This gives us up to 4 solutions, of which
332 // up to 3 will give us positive velocities; each solution velocity
333 // corresponds to a transition from feasibility to infeasibility, where a
334 // velocity of zero is always feasible, and there will always be 0, 1, or 3
335 // positive solutions. Among the positive solutions, we take both the min
336 // and the max--the min will be the highest velocity such that all
337 // velocities between zero and that velocity are valid; the max will be
338 // the highest feasible velocity. Which we return depends on what the
339 // limit_type is.
340 //
341 // Sketching the actual math:
342 // K2 * v_robot' + K1 * v_robot^2 = A * K2 * v_robot +/- B * U_max
343 // K2prime * K1 * v_robot^2 = K2prime * (A * K2 * v_robot +/- B * U_max)
344 // a v_robot^2 + b v_robot +/- c = 0
James Kuszmaul75a18c52021-03-10 22:02:07 -0800345 const Eigen::Matrix<double, 2, 2> B =
346 velocity_drivetrain().plant().coefficients().B_continuous;
347 const double dtheta = spline().DTheta(distance);
348 const Eigen::Matrix<double, 2, 1> BinvK2 = B.inverse() * K2(dtheta);
James Kuszmaulea314d92019-02-18 19:45:06 -0800349 // Because voltages can actually impact *both* wheels, in order to determine
350 // whether the voltages will have opposite signs, we need to use B^-1 * K2.
351 const bool opposite_voltages = BinvK2(0) * BinvK2(1) > 0.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800352 const Eigen::Matrix<double, 1, 2> K2prime =
James Kuszmaulea314d92019-02-18 19:45:06 -0800353 K2(dtheta).transpose() *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800354 (Eigen::Matrix<double, 2, 2>() << 0, 1, -1, 0).finished();
355 const double a = K2prime * K1(spline().DDTheta(distance));
James Kuszmaulea314d92019-02-18 19:45:06 -0800356 const double b = -K2prime *
James Kuszmaul75a18c52021-03-10 22:02:07 -0800357 velocity_drivetrain().plant().coefficients().A_continuous *
James Kuszmaulea314d92019-02-18 19:45:06 -0800358 K2(dtheta);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800359 const Eigen::Matrix<double, 1, 2> c_coeff = -K2prime * B;
James Kuszmaulea314d92019-02-18 19:45:06 -0800360 // Calculate the "positive" version of the voltage limits we will use.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800361 const Eigen::Matrix<double, 2, 1> abs_volts =
362 max_voltage() *
363 (Eigen::Matrix<double, 2, 1>() << 1.0, (opposite_voltages ? -1.0 : 1.0))
James Kuszmaulea314d92019-02-18 19:45:06 -0800364 .finished();
365
James Kuszmaul75a18c52021-03-10 22:02:07 -0800366 double min_valid_vel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800367 if (limit_type == VoltageLimit::kAggressive) {
368 min_valid_vel = 0.0;
369 }
370 // Iterate over both possibilites for +/- voltage, and solve the quadratic
371 // formula. For every positive solution, adjust the velocity limit
372 // appropriately.
373 for (const double sign : {1.0, -1.0}) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800374 const Eigen::Matrix<double, 2, 1> U = sign * abs_volts;
James Kuszmaulea314d92019-02-18 19:45:06 -0800375 const double prev_vel = min_valid_vel;
376 const double c = c_coeff * U;
377 const double determinant = b * b - 4 * a * c;
378 if (a == 0) {
379 // If a == 0, that implies we are on a constant curvature path, in which
380 // case we just have b * v + c = 0.
381 // Note that if -b * c > 0.0, then vel will be greater than zero and b
382 // will be non-zero.
383 if (-b * c > 0.0) {
384 const double vel = -c / b;
385 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800386 min_valid_vel = std::min(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800387 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800388 min_valid_vel = std::max(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800389 }
390 } else if (b == 0) {
391 // If a and b are zero, then we are travelling in a straight line and
392 // have no voltage-based velocity constraints.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800393 min_valid_vel = std::numeric_limits<double>::infinity();
James Kuszmaulea314d92019-02-18 19:45:06 -0800394 }
395 } else if (determinant > 0) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800396 const double sqrt_determinant = std::sqrt(determinant);
James Kuszmaulea314d92019-02-18 19:45:06 -0800397 const double high_vel = (-b + sqrt_determinant) / (2.0 * a);
398 const double low_vel = (-b - sqrt_determinant) / (2.0 * a);
399 if (low_vel > 0) {
400 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800401 min_valid_vel = std::min(min_valid_vel, low_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800402 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800403 min_valid_vel = std::max(min_valid_vel, low_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800404 }
405 }
406 if (high_vel > 0) {
407 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800408 min_valid_vel = std::min(min_valid_vel, high_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800409 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800410 min_valid_vel = std::max(min_valid_vel, high_vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800411 }
412 }
413 } else if (determinant == 0 && -b * a > 0) {
414 const double vel = -b / (2.0 * a);
415 if (vel > 0.0) {
416 if (limit_type == VoltageLimit::kConservative) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800417 min_valid_vel = std::min(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800418 } else {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800419 min_valid_vel = std::max(min_valid_vel, vel);
James Kuszmaulea314d92019-02-18 19:45:06 -0800420 }
421 }
422 }
423 if (constraint_voltages != nullptr && prev_vel != min_valid_vel) {
424 *constraint_voltages = U;
425 }
426 }
427 return min_valid_vel;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100428}
429
430void Trajectory::ForwardPass() {
431 plan_[0] = 0.0;
432 const double delta_distance = Distance(1) - Distance(0);
433 for (size_t i = 0; i < plan_.size() - 1; ++i) {
434 const double distance = Distance(i);
435
436 // Integrate our acceleration forward one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800437 const double new_plan_velocity = IntegrateAccelForDistance(
438 [this](double x, double v) { return ForwardAcceleration(x, v); },
439 plan_[i], distance, delta_distance);
440
James Kuszmaulea314d92019-02-18 19:45:06 -0800441 if (new_plan_velocity <= plan_[i + 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800442 plan_[i + 1] = new_plan_velocity;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800443 plan_segment_type_[i] = fb::SegmentConstraint::ACCELERATION_LIMITED;
Austin Schuhe73a9052019-01-07 12:16:17 -0800444 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100445 }
446}
447
Austin Schuhec7f06d2019-01-04 07:47:15 +1100448void Trajectory::BackwardPass() {
449 const double delta_distance = Distance(0) - Distance(1);
450 plan_.back() = 0.0;
451 for (size_t i = plan_.size() - 1; i > 0; --i) {
452 const double distance = Distance(i);
453
454 // Integrate our deceleration back one step.
Austin Schuhe73a9052019-01-07 12:16:17 -0800455 const double new_plan_velocity = IntegrateAccelForDistance(
456 [this](double x, double v) { return BackwardAcceleration(x, v); },
457 plan_[i], distance, delta_distance);
458
James Kuszmaulea314d92019-02-18 19:45:06 -0800459 if (new_plan_velocity <= plan_[i - 1]) {
Austin Schuhe73a9052019-01-07 12:16:17 -0800460 plan_[i - 1] = new_plan_velocity;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800461 plan_segment_type_[i - 1] = fb::SegmentConstraint::DECELERATION_LIMITED;
Austin Schuhe73a9052019-01-07 12:16:17 -0800462 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100463 }
464}
465
James Kuszmaul75a18c52021-03-10 22:02:07 -0800466Eigen::Matrix<double, 3, 1> BaseTrajectory::FFAcceleration(
467 double distance) const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800468 if (distance < 0.0) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100469 // Make sure we don't end up off the beginning of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800470 distance = 0.0;
471 } else if (distance > length()) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100472 // Make sure we don't end up off the end of the curve.
Austin Schuhe73a9052019-01-07 12:16:17 -0800473 distance = length();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100474 }
Austin Schuhe73a9052019-01-07 12:16:17 -0800475 const size_t before_index = DistanceToSegment(distance);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800476 const size_t after_index =
477 std::min(before_index + 1, distance_plan_size() - 1);
Austin Schuhe73a9052019-01-07 12:16:17 -0800478
Austin Schuhec7f06d2019-01-04 07:47:15 +1100479 const double before_distance = Distance(before_index);
480 const double after_distance = Distance(after_index);
481
Austin Schuhec7f06d2019-01-04 07:47:15 +1100482 // And then also make sure we aren't curvature limited.
483 const double vcurvature = LateralVelocityCurvature(distance);
484
485 double acceleration;
486 double velocity;
James Kuszmaulea314d92019-02-18 19:45:06 -0800487 // TODO(james): While technically correct for sufficiently small segment
488 // steps, this method of switching between limits has a tendency to produce
489 // sudden jumps in acceelrations, which is undesirable.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800490 switch (plan_constraint(DistanceToSegment(distance))) {
491 case fb::SegmentConstraint::VELOCITY_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800492 acceleration = 0.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800493 velocity =
494 (plan_velocity(before_index) + plan_velocity(after_index)) / 2.0;
Austin Schuhe73a9052019-01-07 12:16:17 -0800495 // TODO(austin): Accelerate or decelerate until we hit the limit in the
496 // time slice. Otherwise our acceleration will be lying for this slice.
497 // Do note, we've got small slices so the effect will be small.
498 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800499 case fb::SegmentConstraint::CURVATURE_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800500 velocity = vcurvature;
James Kuszmaulea314d92019-02-18 19:45:06 -0800501 FrictionLngAccelLimits(distance, velocity, &acceleration, &acceleration);
502 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800503 case fb::SegmentConstraint::VOLTAGE_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800504 // Normally, we expect that voltage limited plans will all get dominated
505 // by the acceleration/deceleration limits. This may not always be true;
506 // if we ever encounter this error, we just need to back out what the
507 // accelerations would be in this case.
Austin Schuhd749d932020-12-30 21:38:40 -0800508 LOG(FATAL) << "Unexpectedly got VOLTAGE_LIMITED plan.";
Austin Schuhe73a9052019-01-07 12:16:17 -0800509 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800510 case fb::SegmentConstraint::ACCELERATION_LIMITED:
James Kuszmaulea314d92019-02-18 19:45:06 -0800511 // TODO(james): The integration done here and in the DECELERATION_LIMITED
512 // can technically cause us to violate friction constraints. We currently
513 // don't do anything about it to avoid causing sudden jumps in voltage,
514 // but we probably *should* at some point.
Austin Schuhe73a9052019-01-07 12:16:17 -0800515 velocity = IntegrateAccelForDistance(
516 [this](double x, double v) { return ForwardAcceleration(x, v); },
James Kuszmaul75a18c52021-03-10 22:02:07 -0800517 plan_velocity(before_index), before_distance,
518 distance - before_distance);
Austin Schuhe73a9052019-01-07 12:16:17 -0800519 acceleration = ForwardAcceleration(distance, velocity);
520 break;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800521 case fb::SegmentConstraint::DECELERATION_LIMITED:
Austin Schuhe73a9052019-01-07 12:16:17 -0800522 velocity = IntegrateAccelForDistance(
523 [this](double x, double v) { return BackwardAcceleration(x, v); },
James Kuszmaul75a18c52021-03-10 22:02:07 -0800524 plan_velocity(after_index), after_distance,
525 distance - after_distance);
Austin Schuhe73a9052019-01-07 12:16:17 -0800526 acceleration = BackwardAcceleration(distance, velocity);
527 break;
528 default:
James Kuszmaul75a18c52021-03-10 22:02:07 -0800529 AOS_LOG(FATAL, "Unknown segment type %d\n",
530 static_cast<int>(plan_constraint(DistanceToSegment(distance))));
Austin Schuhe73a9052019-01-07 12:16:17 -0800531 break;
532 }
533
James Kuszmaul75a18c52021-03-10 22:02:07 -0800534 return (Eigen::Matrix<double, 3, 1>() << distance, velocity, acceleration)
Austin Schuhec7f06d2019-01-04 07:47:15 +1100535 .finished();
536}
537
James Kuszmaul75a18c52021-03-10 22:02:07 -0800538size_t FinishedTrajectory::distance_plan_size() const {
539 return trajectory().has_distance_based_plan()
540 ? trajectory().distance_based_plan()->size()
541 : 0u;
542}
543
544fb::SegmentConstraint FinishedTrajectory::plan_constraint(size_t index) const {
545 CHECK_LT(index, distance_plan_size());
546 return trajectory().distance_based_plan()->Get(index)->segment_constraint();
547}
548
549float FinishedTrajectory::plan_velocity(size_t index) const {
550 CHECK_LT(index, distance_plan_size());
551 return trajectory().distance_based_plan()->Get(index)->velocity();
552}
553
554Eigen::Matrix<double, 2, 1> BaseTrajectory::FFVoltage(double distance) const {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100555 const Eigen::Matrix<double, 3, 1> xva = FFAcceleration(distance);
556 const double velocity = xva(1);
557 const double acceleration = xva(2);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100558
James Kuszmaul75a18c52021-03-10 22:02:07 -0800559 Eigen::Matrix<double, 2, 1> K3;
560 Eigen::Matrix<double, 2, 1> K4;
561 Eigen::Matrix<double, 2, 1> K5;
Austin Schuhe73a9052019-01-07 12:16:17 -0800562 K345(distance, &K3, &K4, &K5);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100563
564 return K5 * acceleration + K3 * velocity * velocity + K4 * velocity;
565}
566
James Kuszmaul75a18c52021-03-10 22:02:07 -0800567const std::vector<double> Trajectory::Distances() const {
568 std::vector<double> d;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100569 d.reserve(plan_.size());
570 for (size_t i = 0; i < plan_.size(); ++i) {
571 d.push_back(Distance(i));
572 }
573 return d;
574}
575
James Kuszmaul75a18c52021-03-10 22:02:07 -0800576Eigen::Matrix<double, 3, 1> BaseTrajectory::GetNextXVA(
577 std::chrono::nanoseconds dt, Eigen::Matrix<double, 2, 1> *state) const {
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700578 double dt_float = ::aos::time::DurationInSeconds(dt);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100579
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800580 const double last_distance = (*state)(0);
Alex Perry4ae2fd72019-02-03 15:55:57 -0800581 // TODO(austin): This feels like something that should be pulled out into
582 // a library for re-use.
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700583 *state = RungeKutta(
James Kuszmaul75a18c52021-03-10 22:02:07 -0800584 [this](const Eigen::Matrix<double, 2, 1> x) {
585 Eigen::Matrix<double, 3, 1> xva = FFAcceleration(x(0));
586 return (Eigen::Matrix<double, 2, 1>() << x(1), xva(2)).finished();
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700587 },
588 *state, dt_float);
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800589 // Force the distance to move forwards, to guarantee that we actually finish
590 // the planning.
591 constexpr double kMinDistanceIncrease = 1e-7;
592 if ((*state)(0) < last_distance + kMinDistanceIncrease) {
593 (*state)(0) = last_distance + kMinDistanceIncrease;
594 }
Alex Perry4ae2fd72019-02-03 15:55:57 -0800595
James Kuszmaul75a18c52021-03-10 22:02:07 -0800596 Eigen::Matrix<double, 3, 1> result = FFAcceleration((*state)(0));
Alex Perry4ae2fd72019-02-03 15:55:57 -0800597 (*state)(1) = result(1);
598 return result;
599}
600
James Kuszmaul75a18c52021-03-10 22:02:07 -0800601std::vector<Eigen::Matrix<double, 3, 1>> Trajectory::PlanXVA(
602 std::chrono::nanoseconds dt) {
603 Eigen::Matrix<double, 2, 1> state = Eigen::Matrix<double, 2, 1>::Zero();
604 std::vector<Eigen::Matrix<double, 3, 1>> result;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100605 result.emplace_back(FFAcceleration(0));
606 result.back()(1) = 0.0;
607
Alex Perry4ae2fd72019-02-03 15:55:57 -0800608 while (!is_at_end(state)) {
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800609 if (state_is_faulted(state)) {
610 LOG(WARNING)
611 << "Found invalid state in generating spline and aborting. This is "
612 "likely due to a spline with extremely high jerk/changes in "
613 "curvature with an insufficiently small step size.";
614 return {};
615 }
Alex Perry4ae2fd72019-02-03 15:55:57 -0800616 result.emplace_back(GetNextXVA(dt, &state));
Austin Schuhec7f06d2019-01-04 07:47:15 +1100617 }
618 return result;
619}
620
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800621void Trajectory::LimitVelocity(double starting_distance, double ending_distance,
622 const double max_velocity) {
623 const double segment_length = ending_distance - starting_distance;
624
625 const double min_length = length() / static_cast<double>(plan_.size() - 1);
626 if (starting_distance > ending_distance) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700627 AOS_LOG(FATAL, "End before start: %f > %f\n", starting_distance,
628 ending_distance);
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800629 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800630 starting_distance = std::min(length(), std::max(0.0, starting_distance));
631 ending_distance = std::min(length(), std::max(0.0, ending_distance));
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800632 if (segment_length < min_length) {
633 const size_t plan_index = static_cast<size_t>(
James Kuszmaul75a18c52021-03-10 22:02:07 -0800634 std::round((starting_distance + ending_distance) / 2.0 / min_length));
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800635 if (max_velocity < plan_[plan_index]) {
636 plan_[plan_index] = max_velocity;
637 }
638 } else {
639 for (size_t i = DistanceToSegment(starting_distance) + 1;
640 i < DistanceToSegment(ending_distance) + 1; ++i) {
641 if (max_velocity < plan_[i]) {
642 plan_[i] = max_velocity;
643 if (i < DistanceToSegment(ending_distance)) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800644 plan_segment_type_[i] = fb::SegmentConstraint::VELOCITY_LIMITED;
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800645 }
646 }
647 }
648 }
649}
650
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700651void Trajectory::PathRelativeContinuousSystem(double distance,
652 Eigen::Matrix<double, 5, 5> *A,
653 Eigen::Matrix<double, 5, 2> *B) {
654 const double nominal_velocity = FFAcceleration(distance)(1);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800655 const double dtheta_dt = spline().DThetaDt(distance, nominal_velocity);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700656 // Calculate the "path-relative" coordinates, which are:
657 // [[distance along the path],
658 // [lateral position along path],
659 // [theta],
660 // [left wheel velocity],
661 // [right wheel velocity]]
662 Eigen::Matrix<double, 5, 1> nominal_X;
663 nominal_X << distance, 0.0, 0.0,
James Kuszmaul75a18c52021-03-10 22:02:07 -0800664 nominal_velocity - dtheta_dt * robot_radius_l(),
665 nominal_velocity + dtheta_dt * robot_radius_r();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700666 PathRelativeContinuousSystem(nominal_X, A, B);
667}
668
669void Trajectory::PathRelativeContinuousSystem(
670 const Eigen::Matrix<double, 5, 1> &X, Eigen::Matrix<double, 5, 5> *A,
671 Eigen::Matrix<double, 5, 2> *B) {
672 A->setZero();
673 B->setZero();
674 const double theta = X(2);
675 const double ctheta = std::cos(theta);
676 const double stheta = std::sin(theta);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800677 const double curvature = spline().DTheta(X(0));
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700678 const double longitudinal_velocity = (X(3) + X(4)) / 2.0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800679 const double diameter = robot_radius_l() + robot_radius_r();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700680 // d_dpath / dt = (v_left + v_right) / 2.0 * cos(theta)
681 // (d_dpath / dt) / dv_left = cos(theta) / 2.0
682 (*A)(0, 3) = ctheta / 2.0;
683 // (d_dpath / dt) / dv_right = cos(theta) / 2.0
684 (*A)(0, 4) = ctheta / 2.0;
685 // (d_dpath / dt) / dtheta = -(v_left + v_right) / 2.0 * sin(theta)
686 (*A)(0, 2) = -longitudinal_velocity * stheta;
687 // d_dlat / dt = (v_left + v_right) / 2.0 * sin(theta)
688 // (d_dlat / dt) / dv_left = sin(theta) / 2.0
689 (*A)(1, 3) = stheta / 2.0;
690 // (d_dlat / dt) / dv_right = sin(theta) / 2.0
691 (*A)(1, 4) = stheta / 2.0;
692 // (d_dlat / dt) / dtheta = (v_left + v_right) / 2.0 * cos(theta)
693 (*A)(1, 2) = longitudinal_velocity * ctheta;
694 // dtheta / dt = (v_right - v_left) / diameter - curvature * (v_left +
695 // v_right) / 2.0
696 // (dtheta / dt) / dv_left = -1.0 / diameter - curvature / 2.0
697 (*A)(2, 3) = -1.0 / diameter - curvature / 2.0;
698 // (dtheta / dt) / dv_right = 1.0 / diameter - curvature / 2.0
699 (*A)(2, 4) = 1.0 / diameter - curvature / 2.0;
700 // v_{left,right} / dt = the normal LTI system.
701 A->block<2, 2>(3, 3) =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800702 velocity_drivetrain().plant().coefficients().A_continuous;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700703 B->block<2, 2>(3, 0) =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800704 velocity_drivetrain().plant().coefficients().B_continuous;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700705}
706
707double Trajectory::EstimateDistanceAlongPath(
708 double nominal_distance, const Eigen::Matrix<double, 5, 1> &state) {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800709 const double nominal_theta = spline().Theta(nominal_distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700710 const Eigen::Matrix<double, 2, 1> xy_err =
James Kuszmaul75a18c52021-03-10 22:02:07 -0800711 state.block<2, 1>(0, 0) - spline().XY(nominal_distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700712 return nominal_distance + xy_err.x() * std::cos(nominal_theta) +
713 xy_err.y() * std::sin(nominal_theta);
714}
715
James Kuszmaul75a18c52021-03-10 22:02:07 -0800716Eigen::Matrix<double, 5, 1> FinishedTrajectory::StateToPathRelativeState(
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700717 double distance, const Eigen::Matrix<double, 5, 1> &state,
718 bool drive_backwards) const {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800719 const double nominal_theta = spline().Theta(distance);
720 const Eigen::Matrix<double, 2, 1> nominal_xy = spline().XY(distance);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700721 const Eigen::Matrix<double, 2, 1> xy_err =
722 state.block<2, 1>(0, 0) - nominal_xy;
723 const double ctheta = std::cos(nominal_theta);
724 const double stheta = std::sin(nominal_theta);
725 Eigen::Matrix<double, 5, 1> path_state;
726 path_state(0) = distance + xy_err.x() * ctheta + xy_err.y() * stheta;
727 path_state(1) = -xy_err.x() * stheta + xy_err.y() * ctheta;
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700728 path_state(2) = aos::math::NormalizeAngle(state(2) - nominal_theta +
729 (drive_backwards ? M_PI : 0.0));
730 path_state(2) = aos::math::NormalizeAngle(state(2) - nominal_theta);
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700731 path_state(3) = state(3);
732 path_state(4) = state(4);
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700733 if (drive_backwards) {
734 std::swap(path_state(3), path_state(4));
735 path_state(3) *= -1.0;
736 path_state(4) *= -1.0;
737 }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700738 return path_state;
739}
740
741// Path-relative controller method:
742// For the path relative controller, we use a non-standard version of LQR to
743// perform the control. Essentially, we first transform the system into
744// a set of path-relative coordinates (where the reference that we use is the
745// desired path reference). This gives us a system that is linear and
746// time-varying, i.e. the system is a set of A_k, B_k matrices for each
747// timestep k.
748// In order to control this, we use a discrete-time finite-horizon LQR, using
749// the appropraite [AB]_k for the given timestep. Note that the finite-horizon
750// LQR requires choosing a terminal cost (i.e., what the cost should be
751// for if we have not precisely reached the goal at the end of the time-period).
752// For this, I approximate the infinite-horizon LQR solution by extending the
753// finite-horizon much longer (albeit with the extension just using the
754// linearization for the infal point).
755void Trajectory::CalculatePathGains() {
756 const std::vector<Eigen::Matrix<double, 3, 1>> xva_plan = PlanXVA(config_.dt);
James Kuszmaulc3eaa472021-03-03 19:43:45 -0800757 if (xva_plan.empty()) {
758 LOG(ERROR) << "Plan is empty--unable to plan trajectory.";
759 return;
760 }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700761 plan_gains_.resize(xva_plan.size());
762
763 // Set up reasonable gain matrices. Current choices of gains are arbitrary
764 // and just setup to work well enough for the simulation tests.
765 // TODO(james): Tune this on a real robot.
766 // TODO(james): Pull these out into a config.
767 Eigen::Matrix<double, 5, 5> Q;
768 Q.setIdentity();
James Kuszmaul49c93202023-03-23 20:44:03 -0700769 Q.diagonal() << 30.0, 30.0, 20.0, 15.0, 15.0;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700770 Q *= 2.0;
771 Q = (Q * Q).eval();
772
773 Eigen::Matrix<double, 2, 2> R;
774 R.setIdentity();
775 R *= 5.0;
776
777 Eigen::Matrix<double, 5, 5> P = Q;
778
779 CHECK_LT(0u, xva_plan.size());
780 const int max_index = static_cast<int>(xva_plan.size()) - 1;
781 for (int i = max_index; i >= 0; --i) {
782 const double distance = xva_plan[i](0);
783 Eigen::Matrix<double, 5, 5> A_continuous;
784 Eigen::Matrix<double, 5, 2> B_continuous;
785 PathRelativeContinuousSystem(distance, &A_continuous, &B_continuous);
786 Eigen::Matrix<double, 5, 5> A_discrete;
787 Eigen::Matrix<double, 5, 2> B_discrete;
788 controls::C2D(A_continuous, B_continuous, config_.dt, &A_discrete,
789 &B_discrete);
790
791 if (i == max_index) {
792 // At the final timestep, approximate P by iterating a bunch of times.
793 // This is terminal cost mentioned in function-level comments.
794 // This does a very loose job of solving the DARE. Ideally, we would
795 // actually use a DARE solver directly, but based on some initial testing,
796 // this method is a bit more robust (or, at least, it is a bit more robust
797 // if we don't want to spend more time handling the potential error
798 // cases the DARE solver can encounter).
799 constexpr int kExtraIters = 100;
800 for (int jj = 0; jj < kExtraIters; ++jj) {
801 const Eigen::Matrix<double, 5, 5> AP = A_discrete.transpose() * P;
802 const Eigen::Matrix<double, 5, 2> APB = AP * B_discrete;
803 const Eigen::Matrix<double, 2, 2> RBPBinv =
804 (R + B_discrete.transpose() * P * B_discrete).inverse();
805 P = AP * A_discrete - APB * RBPBinv * APB.transpose() + Q;
806 }
807 }
808
809 const Eigen::Matrix<double, 5, 5> AP = A_discrete.transpose() * P;
810 const Eigen::Matrix<double, 5, 2> APB = AP * B_discrete;
811 const Eigen::Matrix<double, 2, 2> RBPBinv =
812 (R + B_discrete.transpose() * P * B_discrete).inverse();
813 plan_gains_[i].first = distance;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800814 const Eigen::Matrix<double, 2, 5> K = RBPBinv * APB.transpose();
815 plan_gains_[i].second = K.cast<float>();
816 P = AP * A_discrete - APB * K + Q;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700817 }
818}
819
James Kuszmaul75a18c52021-03-10 22:02:07 -0800820Eigen::Matrix<double, 2, 5> FinishedTrajectory::GainForDistance(
821 double distance) const {
822 const flatbuffers::Vector<flatbuffers::Offset<fb::GainPoint>> &gains =
823 *CHECK_NOTNULL(trajectory().gains());
824 CHECK_LT(0u, gains.size());
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700825 size_t index = 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800826 for (index = 0; index < gains.size() - 1; ++index) {
827 if (gains[index + 1]->distance() > distance) {
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700828 break;
829 }
830 }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800831 // ColMajor is the default storage order, but call it out explicitly here.
832 return Eigen::Matrix<float, 2, 5, Eigen::ColMajor>{
833 gains[index]->gains()->data()}
834 .cast<double>();
835}
836
837namespace {
838flatbuffers::Offset<Constraint> MakeWholeLengthConstraint(
839 flatbuffers::FlatBufferBuilder *fbb, ConstraintType constraint_type,
840 float value) {
841 Constraint::Builder builder(*fbb);
842 builder.add_constraint_type(constraint_type);
843 builder.add_value(value);
844 return builder.Finish();
845}
846} // namespace
847
848flatbuffers::Offset<fb::Trajectory> Trajectory::Serialize(
849 flatbuffers::FlatBufferBuilder *fbb) const {
850 std::array<flatbuffers::Offset<Constraint>, 3> constraints_offsets = {
851 MakeWholeLengthConstraint(fbb, ConstraintType::LONGITUDINAL_ACCELERATION,
852 max_longitudinal_accel()),
853 MakeWholeLengthConstraint(fbb, ConstraintType::LATERAL_ACCELERATION,
854 max_lateral_accel()),
855 MakeWholeLengthConstraint(fbb, ConstraintType::VOLTAGE, max_voltage())};
856 const auto constraints = fbb->CreateVector<Constraint>(
857 constraints_offsets.data(), constraints_offsets.size());
858 const flatbuffers::Offset<fb::DistanceSpline> spline_offset =
859 spline().Serialize(fbb, constraints);
860
861 std::vector<flatbuffers::Offset<fb::PlanPoint>> plan_points;
862 for (size_t ii = 0; ii < distance_plan_size(); ++ii) {
863 plan_points.push_back(fb::CreatePlanPoint(
864 *fbb, Distance(ii), plan_velocity(ii), plan_constraint(ii)));
865 }
866
867 // TODO(james): What is an appropriate cap?
868 CHECK_LT(plan_gains_.size(), 5000u);
869 CHECK_LT(0u, plan_gains_.size());
870 std::vector<flatbuffers::Offset<fb::GainPoint>> gain_points;
871 const size_t matrix_size = plan_gains_[0].second.size();
872 for (size_t ii = 0; ii < plan_gains_.size(); ++ii) {
873 gain_points.push_back(fb::CreateGainPoint(
874 *fbb, plan_gains_[ii].first,
875 fbb->CreateVector(plan_gains_[ii].second.data(), matrix_size)));
876 }
877
878 return fb::CreateTrajectory(*fbb, spline_idx_, fbb->CreateVector(plan_points),
879 fbb->CreateVector(gain_points), spline_offset,
880 drive_spline_backwards_);
881}
882
883float BaseTrajectory::ConstraintValue(
884 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
885 ConstraintType type) {
886 if (constraints != nullptr) {
887 for (const Constraint *constraint : *constraints) {
888 if (constraint->constraint_type() == type) {
889 return constraint->value();
890 }
891 }
892 }
893 return DefaultConstraint(type);
894}
895
896const Eigen::Matrix<double, 5, 1> BaseTrajectory::GoalState(
897 double distance, double velocity) const {
898 Eigen::Matrix<double, 5, 1> result;
899 result.block<2, 1>(0, 0) = spline().XY(distance);
900 result(2, 0) = spline().Theta(distance);
901
902 result.block<2, 1>(3, 0) =
903 config_.Tla_to_lr() * (Eigen::Matrix<double, 2, 1>() << velocity,
904 spline().DThetaDt(distance, velocity))
905 .finished();
906 return result;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700907}
908
Austin Schuhec7f06d2019-01-04 07:47:15 +1100909} // namespace drivetrain
910} // namespace control_loops
911} // namespace frc971