blob: a9f14f692b144880f6032f3d0fbe9dad9b659bc3 [file] [log] [blame]
Austin Schuhec7f06d2019-01-04 07:47:15 +11001#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_
2#define FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_
3
4#include <chrono>
5
6#include "Eigen/Dense"
Philipp Schrader790cb542023-07-05 21:06:52 -07007
James Kuszmauldc534432023-02-05 14:51:11 -08008#include "aos/flatbuffers.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +11009#include "frc971/control_loops/drivetrain/distance_spline.h"
10#include "frc971/control_loops/drivetrain/drivetrain_config.h"
James Kuszmaul75a18c52021-03-10 22:02:07 -080011#include "frc971/control_loops/drivetrain/spline_goal_generated.h"
James Kuszmauldc534432023-02-05 14:51:11 -080012#include "frc971/control_loops/drivetrain/trajectory_generated.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +110013#include "frc971/control_loops/hybrid_state_feedback_loop.h"
14#include "frc971/control_loops/runge_kutta.h"
15#include "frc971/control_loops/state_feedback_loop.h"
16
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080017namespace frc971::control_loops::drivetrain {
Austin Schuhec7f06d2019-01-04 07:47:15 +110018
19template <typename F>
20double IntegrateAccelForDistance(const F &fn, double v, double x, double dx) {
21 // Use a trick from
22 // https://www.johndcook.com/blog/2012/02/21/care-and-treatment-of-singularities/
23 const double a0 = fn(x, v);
24
25 return (RungeKutta(
26 [&fn, &a0](double t, double y) {
27 // Since we know that a0 == a(0) and that they are asymtotically
28 // the same at 0, we know that the limit is 0 at 0. This is
29 // true because when starting from a stop, under sane
30 // accelerations, we can assume that we will start with a
31 // constant acceleration. So, hard-code it.
James Kuszmaul75a18c52021-03-10 22:02:07 -080032 if (std::abs(y) < 1e-6) {
Austin Schuhec7f06d2019-01-04 07:47:15 +110033 return 0.0;
34 }
35 return (fn(t, y) - a0) / y;
36 },
37 v, x, dx) -
38 v) +
James Kuszmaul75a18c52021-03-10 22:02:07 -080039 std::sqrt(2.0 * a0 * dx + v * v);
Austin Schuhec7f06d2019-01-04 07:47:15 +110040}
41
James Kuszmaul75a18c52021-03-10 22:02:07 -080042class BaseTrajectory {
Austin Schuhec7f06d2019-01-04 07:47:15 +110043 public:
James Kuszmaul75a18c52021-03-10 22:02:07 -080044 BaseTrajectory(
45 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
Austin Schuhf7c65202022-11-04 21:28:20 -070046 const DrivetrainConfig<double> &config)
47 : BaseTrajectory(constraints, config,
48 std::make_shared<StateFeedbackLoop<
49 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
50 HybridKalman<2, 2, 2>>>(
51 config.make_hybrid_drivetrain_velocity_loop())) {}
52
53 BaseTrajectory(
54 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
55 const DrivetrainConfig<double> &config,
56 std::shared_ptr<
57 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
58 HybridKalman<2, 2, 2>>>
59 velocity_drivetrain);
James Kuszmaul75a18c52021-03-10 22:02:07 -080060
61 virtual ~BaseTrajectory() = default;
Austin Schuhec7f06d2019-01-04 07:47:15 +110062
James Kuszmaulea314d92019-02-18 19:45:06 -080063 // Returns the friction-constrained velocity limit at a given distance along
64 // the path. At the returned velocity, one or both wheels will be on the edge
65 // of slipping.
66 // There are some very disorganized thoughts on the math here and in some of
67 // the other functions in spline_math.tex.
68 double LateralVelocityCurvature(double distance) const;
69
70 // Returns the range of allowable longitudinal accelerations for the center of
71 // the robot at a particular distance (x) along the path and velocity (v).
72 // min_accel and max_accel correspodn to the min/max accelerations that can be
73 // achieved without breaking friction limits on one or both wheels.
74 // If max_accel < min_accel, that implies that v is too high for there to be
75 // any valid acceleration. FrictionLngAccelLimits(x,
76 // LateralVelocityCurvature(x), &min_accel, &max_accel) should result in
77 // min_accel == max_accel.
78 void FrictionLngAccelLimits(double x, double v, double *min_accel,
79 double *max_accel) const;
80
James Kuszmaul75a18c52021-03-10 22:02:07 -080081 // Returns the forwards/backwards acceleration for a distance along the spline
82 // taking into account the lateral acceleration, longitudinal acceleration,
83 // and voltage limits.
84 double BestAcceleration(double x, double v, bool backwards) const;
85 double BackwardAcceleration(double x, double v) const {
86 return BestAcceleration(x, v, true);
87 }
88 double ForwardAcceleration(double x, double v) const {
89 return BestAcceleration(x, v, false);
90 }
91
92 const StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
Austin Schuh50e3dca2023-07-23 14:34:27 -070093 HybridKalman<2, 2, 2>> &
94 velocity_drivetrain() const {
James Kuszmaul75a18c52021-03-10 22:02:07 -080095 return *velocity_drivetrain_;
96 }
97
98 // Returns K1 and K2.
99 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
100 const Eigen::Matrix<double, 2, 1> K1(double current_ddtheta) const;
101 const Eigen::Matrix<double, 2, 1> K2(double current_dtheta) const;
102
103 // Computes K3, K4, and K5 for the provided distance.
104 // K5 a + K3 v^2 + K4 v = U
105 void K345(const double x, Eigen::Matrix<double, 2, 1> *K3,
106 Eigen::Matrix<double, 2, 1> *K4,
107 Eigen::Matrix<double, 2, 1> *K5) const;
108
Austin Schuhf7c65202022-11-04 21:28:20 -0700109 virtual const DistanceSplineBase &spline() const = 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800110
111 // Returns the length of the path in meters.
112 double length() const { return spline().length(); }
113
114 // Returns whether a state represents a state at the end of the spline.
115 bool is_at_end(Eigen::Matrix<double, 2, 1> state) const {
116 return state(0) > length() - 1e-4;
117 }
118
119 // Returns true if the state is invalid or unreasonable in some way.
120 bool state_is_faulted(Eigen::Matrix<double, 2, 1> state) const {
121 // Consider things faulted if the current velocity implies we are going
122 // backwards or if any infinities/NaNs have crept in.
123 return state(1) < 0 || !state.allFinite();
124 }
125
126 virtual float plan_velocity(size_t index) const = 0;
127 virtual size_t distance_plan_size() const = 0;
128
129 // Sets the plan longitudinal acceleration limit
130 void set_longitudinal_acceleration(double longitudinal_acceleration) {
131 longitudinal_acceleration_ = longitudinal_acceleration;
132 }
133 // Sets the plan lateral acceleration limit
134 void set_lateral_acceleration(double lateral_acceleration) {
135 lateral_acceleration_ = lateral_acceleration;
136 }
137 // Sets the voltage limit
138 void set_voltage_limit(double voltage_limit) {
139 voltage_limit_ = voltage_limit;
140 }
141
142 float max_lateral_accel() const { return lateral_acceleration_; }
143
144 float max_longitudinal_accel() const { return longitudinal_acceleration_; }
145
146 float max_voltage() const { return voltage_limit_; }
147
148 // Return the next position, velocity, acceleration based on the current
149 // state. Updates the passed in state for the next iteration.
150 Eigen::Matrix<double, 3, 1> GetNextXVA(
151 std::chrono::nanoseconds dt, Eigen::Matrix<double, 2, 1> *state) const;
152
153 // Returns the distance for an index in the plan.
154 double Distance(int index) const {
155 return static_cast<double>(index) * length() /
156 static_cast<double>(distance_plan_size() - 1);
157 }
158
159 virtual fb::SegmentConstraint plan_constraint(size_t index) const = 0;
160
161 // Returns the feed forwards position, velocity, acceleration for an explicit
162 // distance.
163 Eigen::Matrix<double, 3, 1> FFAcceleration(double distance) const;
164
165 // Returns the feed forwards voltage for an explicit distance.
166 Eigen::Matrix<double, 2, 1> FFVoltage(double distance) const;
167
168 // Computes alpha for a distance.
169 size_t DistanceToSegment(double distance) const {
170 return std::max(
171 static_cast<size_t>(0),
172 std::min(distance_plan_size() - 1,
173 static_cast<size_t>(std::floor(distance / length() *
174 (distance_plan_size() - 1)))));
175 }
176
177 // Returns the goal state as a function of path distance, velocity.
178 const ::Eigen::Matrix<double, 5, 1> GoalState(double distance,
179 double velocity) const;
180
181 protected:
182 double robot_radius_l() const { return robot_radius_l_; }
183 double robot_radius_r() const { return robot_radius_r_; }
184
185 private:
186 static float ConstraintValue(
187 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
188 ConstraintType type);
189
Austin Schuhf7c65202022-11-04 21:28:20 -0700190 std::shared_ptr<
James Kuszmaul75a18c52021-03-10 22:02:07 -0800191 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
192 HybridKalman<2, 2, 2>>>
193 velocity_drivetrain_;
194
James Kuszmauldc534432023-02-05 14:51:11 -0800195 DrivetrainConfig<double> config_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800196
197 // Robot radiuses.
James Kuszmauldc534432023-02-05 14:51:11 -0800198 double robot_radius_l_;
199 double robot_radius_r_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800200 float lateral_acceleration_ = 3.0;
201 float longitudinal_acceleration_ = 2.0;
202 float voltage_limit_ = 12.0;
203};
204
205// A wrapper around the Trajectory flatbuffer to allow for controlling to a
206// spline using a pre-generated trajectory.
James Kuszmauldc534432023-02-05 14:51:11 -0800207class FinishedTrajectory : public BaseTrajectory {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800208 public:
209 // Note: The lifetime of the supplied buffer is assumed to be greater than
210 // that of this object.
Austin Schuhf7c65202022-11-04 21:28:20 -0700211 explicit FinishedTrajectory(
212 const DrivetrainConfig<double> &config, const fb::Trajectory *buffer,
213 std::shared_ptr<
214 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
215 HybridKalman<2, 2, 2>>>
216 velocity_drivetrain);
217
James Kuszmaul75a18c52021-03-10 22:02:07 -0800218 explicit FinishedTrajectory(const DrivetrainConfig<double> &config,
Austin Schuhf7c65202022-11-04 21:28:20 -0700219 const fb::Trajectory *buffer)
220 : FinishedTrajectory(
221 config, buffer,
222 std::make_shared<StateFeedbackLoop<
223 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
224 HybridKalman<2, 2, 2>>>(
225 config.make_hybrid_drivetrain_velocity_loop())) {}
James Kuszmaul75a18c52021-03-10 22:02:07 -0800226
James Kuszmauldc534432023-02-05 14:51:11 -0800227 FinishedTrajectory(const FinishedTrajectory &) = delete;
228 FinishedTrajectory &operator=(const FinishedTrajectory &) = delete;
229 FinishedTrajectory(FinishedTrajectory &&) = default;
230 FinishedTrajectory &operator=(FinishedTrajectory &&) = default;
231
James Kuszmaul75a18c52021-03-10 22:02:07 -0800232 virtual ~FinishedTrajectory() = default;
233
234 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
235 // converts it to a path-relative state, using distance as a linearization
236 // point (i.e., distance should be roughly equal to the actual distance along
237 // the path).
238 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700239 double distance, const Eigen::Matrix<double, 5, 1> &state,
240 bool drive_backwards) const;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800241
242 // Retrieves the gain matrix K for a given distance along the path.
243 Eigen::Matrix<double, 2, 5> GainForDistance(double distance) const;
244
245 size_t distance_plan_size() const override;
246 float plan_velocity(size_t index) const override;
247 fb::SegmentConstraint plan_constraint(size_t index) const override;
248
249 bool drive_spline_backwards() const {
250 return trajectory().drive_spline_backwards();
251 }
252
253 int spline_handle() const { return trajectory().handle(); }
254 const fb::Trajectory &trajectory() const { return *buffer_; }
255
256 private:
Austin Schuhf7c65202022-11-04 21:28:20 -0700257 const DistanceSplineBase &spline() const override { return spline_; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800258 const fb::Trajectory *buffer_;
James Kuszmauldc534432023-02-05 14:51:11 -0800259 FinishedDistanceSpline spline_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800260};
261
262// Class to handle plannign a trajectory and producing a flatbuffer containing
263// all the information required to create a FinishedTrajectory;
264class Trajectory : public BaseTrajectory {
265 public:
266 Trajectory(const SplineGoal &spline_goal,
267 const DrivetrainConfig<double> &config);
268 Trajectory(
269 DistanceSpline &&spline, const DrivetrainConfig<double> &config,
270 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
271 int spline_idx = 0, double vmax = 10.0, int num_distance = 0);
272
273 virtual ~Trajectory() = default;
274
James Kuszmauldc534432023-02-05 14:51:11 -0800275 std::vector<Eigen::Matrix<double, 3, 1>> PlanXVA(std::chrono::nanoseconds dt);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800276
James Kuszmaulea314d92019-02-18 19:45:06 -0800277 enum class VoltageLimit {
278 kConservative,
279 kAggressive,
280 };
281
282 // Calculates the maximum voltage at which we *can* track the path. In some
283 // cases there will be two ranges of feasible velocities for traversing the
284 // path--in such a situation, from zero to velocity A we will be able to track
285 // the path, from velocity A to B we can't, from B to C we can and above C we
286 // can't. If limit_type = kConservative, we return A; if limit_type =
287 // kAggressive, we return C. We currently just use the kConservative limit
288 // because that way we can guarantee that all velocities between zero and A
289 // are allowable and don't have to handle a more complicated planning problem.
290 // constraint_voltages will be populated by the only wheel voltages that are
291 // valid at the returned limit.
292 double VoltageVelocityLimit(
293 double distance, VoltageLimit limit_type,
294 Eigen::Matrix<double, 2, 1> *constraint_voltages = nullptr) const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100295
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800296 // Limits the velocity in the specified segment to the max velocity.
297 void LimitVelocity(double starting_distance, double ending_distance,
298 double max_velocity);
299
Austin Schuhec7f06d2019-01-04 07:47:15 +1100300 // Runs the lateral acceleration (curvature) pass on the plan.
301 void LateralAccelPass();
James Kuszmaulea314d92019-02-18 19:45:06 -0800302 void VoltageFeasibilityPass(VoltageLimit limit_type);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100303
304 // Runs the forwards pass, setting the starting velocity to 0 m/s
305 void ForwardPass();
306
Austin Schuhec7f06d2019-01-04 07:47:15 +1100307 // Runs the forwards pass, setting the ending velocity to 0 m/s
308 void BackwardPass();
309
310 // Runs all the planning passes.
311 void Plan() {
James Kuszmaulea314d92019-02-18 19:45:06 -0800312 VoltageFeasibilityPass(VoltageLimit::kConservative);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100313 LateralAccelPass();
314 ForwardPass();
315 BackwardPass();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700316 CalculatePathGains();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100317 }
318
Austin Schuhec7f06d2019-01-04 07:47:15 +1100319 // Returns a list of the distances. Mostly useful for plotting.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800320 const std::vector<double> Distances() const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100321 // Returns the distance for an index in the plan.
322 double Distance(int index) const {
323 return static_cast<double>(index) * length() /
324 static_cast<double>(plan_.size() - 1);
325 }
326
James Kuszmaul75a18c52021-03-10 22:02:07 -0800327 const std::vector<fb::SegmentConstraint> &plan_segment_type() const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800328 return plan_segment_type_;
329 }
330
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700331 // The controller represented by these functions uses a discrete-time,
332 // finite-horizon LQR with states that are relative to the predicted path
333 // of the robot to produce a gain to be used on the error.
334 // The controller does not currently account for saturation, but is defined
335 // in a way that would make accounting for saturation feasible.
336 // This controller uses a state of:
337 // distance along path
338 // distance lateral to path (positive when robot is to the left of the path).
339 // heading relative to path (positive if robot pointed to left).
340 // v_left (speed of left side of robot)
341 // v_right (speed of right side of robot).
342
343 // Retrieve the continuous-time A/B matrices for the path-relative system
344 // at the given distance along the path. Performs all linearizations about
345 // the nominal velocity that the robot should be following at that point
346 // along the path.
347 void PathRelativeContinuousSystem(double distance,
348 Eigen::Matrix<double, 5, 5> *A,
349 Eigen::Matrix<double, 5, 2> *B);
350 // Retrieve the continuous-time A/B matrices for the path-relative system
351 // given the current path-relative state, as defined above.
352 void PathRelativeContinuousSystem(const Eigen::Matrix<double, 5, 1> &X,
353 Eigen::Matrix<double, 5, 5> *A,
354 Eigen::Matrix<double, 5, 2> *B);
355
356 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
357 // converts it to a path-relative state, using distance as a linearization
358 // point (i.e., distance should be roughly equal to the actual distance along
359 // the path).
360 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
361 double distance, const Eigen::Matrix<double, 5, 1> &state);
362
363 // Estimates the current distance along the path, given the current expected
364 // distance and the [x, y, theta, v_left, v_right] state.
365 double EstimateDistanceAlongPath(double nominal_distance,
366 const Eigen::Matrix<double, 5, 1> &state);
367
368 // Calculates all the gains for each point along the planned trajectory.
369 // Only called directly in tests; this is normally a part of the planning
370 // phase, and is a relatively expensive operation.
371 void CalculatePathGains();
372
James Kuszmaul75a18c52021-03-10 22:02:07 -0800373 flatbuffers::Offset<fb::Trajectory> Serialize(
374 flatbuffers::FlatBufferBuilder *fbb) const;
375
376 const std::vector<double> plan() const { return plan_; }
377
378 const DistanceSpline &spline() const override { return spline_; }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700379
Austin Schuhec7f06d2019-01-04 07:47:15 +1100380 private:
James Kuszmauldc534432023-02-05 14:51:11 -0800381 float plan_velocity(size_t index) const override { return plan_[index]; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800382 size_t distance_plan_size() const override { return plan_.size(); }
383
384 fb::SegmentConstraint plan_constraint(size_t index) const override {
385 return plan_segment_type_[index];
Austin Schuhe73a9052019-01-07 12:16:17 -0800386 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100387
James Kuszmaul75a18c52021-03-10 22:02:07 -0800388 const int spline_idx_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100389
390 // The spline we are planning for.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800391 const DistanceSpline spline_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100392
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700393 const DrivetrainConfig<double> config_;
394
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700395 // Velocities in the plan (distance for each index is defined by Distance())
396 std::vector<double> plan_;
397 // Gain matrices to use for the path-relative state error at each stage in the
398 // plan Individual elements of the plan_gains_ vector are separated by
399 // config_.dt in time.
400 // The first value in the pair is the distance along the path corresponding to
401 // the gain matrix; the second value is the gain itself.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800402 std::vector<std::pair<double, Eigen::Matrix<float, 2, 5>>> plan_gains_;
403 std::vector<fb::SegmentConstraint> plan_segment_type_;
404
405 bool drive_spline_backwards_ = false;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100406};
407
408// Returns the continuous time dynamics given the [x, y, theta, vl, vr] state
409// and the [vl, vr] input voltage.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800410inline Eigen::Matrix<double, 5, 1> ContinuousDynamics(
Austin Schuhec7f06d2019-01-04 07:47:15 +1100411 const StateFeedbackHybridPlant<2, 2, 2> &velocity_drivetrain,
James Kuszmaul75a18c52021-03-10 22:02:07 -0800412 const Eigen::Matrix<double, 2, 2> &Tlr_to_la,
James Kuszmauldc534432023-02-05 14:51:11 -0800413 const Eigen::Matrix<double, 5, 1> X, const Eigen::Matrix<double, 2, 1> U) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100414 const auto &velocity = X.block<2, 1>(3, 0);
415 const double theta = X(2);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800416 Eigen::Matrix<double, 2, 1> la = Tlr_to_la * velocity;
417 return (Eigen::Matrix<double, 5, 1>() << std::cos(theta) * la(0),
418 std::sin(theta) * la(0), la(1),
Austin Schuhec7f06d2019-01-04 07:47:15 +1100419 (velocity_drivetrain.coefficients().A_continuous * velocity +
420 velocity_drivetrain.coefficients().B_continuous * U))
421 .finished();
422}
423
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -0800424} // namespace frc971::control_loops::drivetrain
Austin Schuhec7f06d2019-01-04 07:47:15 +1100425
426#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_