blob: b2cecc04877fde9cdc49627eedc6210061a078bf [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
17namespace frc971 {
18namespace control_loops {
19namespace drivetrain {
20
21template <typename F>
22double IntegrateAccelForDistance(const F &fn, double v, double x, double dx) {
23 // Use a trick from
24 // https://www.johndcook.com/blog/2012/02/21/care-and-treatment-of-singularities/
25 const double a0 = fn(x, v);
26
27 return (RungeKutta(
28 [&fn, &a0](double t, double y) {
29 // Since we know that a0 == a(0) and that they are asymtotically
30 // the same at 0, we know that the limit is 0 at 0. This is
31 // true because when starting from a stop, under sane
32 // accelerations, we can assume that we will start with a
33 // constant acceleration. So, hard-code it.
James Kuszmaul75a18c52021-03-10 22:02:07 -080034 if (std::abs(y) < 1e-6) {
Austin Schuhec7f06d2019-01-04 07:47:15 +110035 return 0.0;
36 }
37 return (fn(t, y) - a0) / y;
38 },
39 v, x, dx) -
40 v) +
James Kuszmaul75a18c52021-03-10 22:02:07 -080041 std::sqrt(2.0 * a0 * dx + v * v);
Austin Schuhec7f06d2019-01-04 07:47:15 +110042}
43
James Kuszmaul75a18c52021-03-10 22:02:07 -080044class BaseTrajectory {
Austin Schuhec7f06d2019-01-04 07:47:15 +110045 public:
James Kuszmaul75a18c52021-03-10 22:02:07 -080046 BaseTrajectory(
47 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
Austin Schuhf7c65202022-11-04 21:28:20 -070048 const DrivetrainConfig<double> &config)
49 : BaseTrajectory(constraints, config,
50 std::make_shared<StateFeedbackLoop<
51 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
52 HybridKalman<2, 2, 2>>>(
53 config.make_hybrid_drivetrain_velocity_loop())) {}
54
55 BaseTrajectory(
56 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
57 const DrivetrainConfig<double> &config,
58 std::shared_ptr<
59 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
60 HybridKalman<2, 2, 2>>>
61 velocity_drivetrain);
James Kuszmaul75a18c52021-03-10 22:02:07 -080062
63 virtual ~BaseTrajectory() = default;
Austin Schuhec7f06d2019-01-04 07:47:15 +110064
James Kuszmaulea314d92019-02-18 19:45:06 -080065 // Returns the friction-constrained velocity limit at a given distance along
66 // the path. At the returned velocity, one or both wheels will be on the edge
67 // of slipping.
68 // There are some very disorganized thoughts on the math here and in some of
69 // the other functions in spline_math.tex.
70 double LateralVelocityCurvature(double distance) const;
71
72 // Returns the range of allowable longitudinal accelerations for the center of
73 // the robot at a particular distance (x) along the path and velocity (v).
74 // min_accel and max_accel correspodn to the min/max accelerations that can be
75 // achieved without breaking friction limits on one or both wheels.
76 // If max_accel < min_accel, that implies that v is too high for there to be
77 // any valid acceleration. FrictionLngAccelLimits(x,
78 // LateralVelocityCurvature(x), &min_accel, &max_accel) should result in
79 // min_accel == max_accel.
80 void FrictionLngAccelLimits(double x, double v, double *min_accel,
81 double *max_accel) const;
82
James Kuszmaul75a18c52021-03-10 22:02:07 -080083 // Returns the forwards/backwards acceleration for a distance along the spline
84 // taking into account the lateral acceleration, longitudinal acceleration,
85 // and voltage limits.
86 double BestAcceleration(double x, double v, bool backwards) const;
87 double BackwardAcceleration(double x, double v) const {
88 return BestAcceleration(x, v, true);
89 }
90 double ForwardAcceleration(double x, double v) const {
91 return BestAcceleration(x, v, false);
92 }
93
94 const StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
Austin Schuh50e3dca2023-07-23 14:34:27 -070095 HybridKalman<2, 2, 2>> &
96 velocity_drivetrain() const {
James Kuszmaul75a18c52021-03-10 22:02:07 -080097 return *velocity_drivetrain_;
98 }
99
100 // Returns K1 and K2.
101 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
102 const Eigen::Matrix<double, 2, 1> K1(double current_ddtheta) const;
103 const Eigen::Matrix<double, 2, 1> K2(double current_dtheta) const;
104
105 // Computes K3, K4, and K5 for the provided distance.
106 // K5 a + K3 v^2 + K4 v = U
107 void K345(const double x, Eigen::Matrix<double, 2, 1> *K3,
108 Eigen::Matrix<double, 2, 1> *K4,
109 Eigen::Matrix<double, 2, 1> *K5) const;
110
Austin Schuhf7c65202022-11-04 21:28:20 -0700111 virtual const DistanceSplineBase &spline() const = 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800112
113 // Returns the length of the path in meters.
114 double length() const { return spline().length(); }
115
116 // Returns whether a state represents a state at the end of the spline.
117 bool is_at_end(Eigen::Matrix<double, 2, 1> state) const {
118 return state(0) > length() - 1e-4;
119 }
120
121 // Returns true if the state is invalid or unreasonable in some way.
122 bool state_is_faulted(Eigen::Matrix<double, 2, 1> state) const {
123 // Consider things faulted if the current velocity implies we are going
124 // backwards or if any infinities/NaNs have crept in.
125 return state(1) < 0 || !state.allFinite();
126 }
127
128 virtual float plan_velocity(size_t index) const = 0;
129 virtual size_t distance_plan_size() const = 0;
130
131 // Sets the plan longitudinal acceleration limit
132 void set_longitudinal_acceleration(double longitudinal_acceleration) {
133 longitudinal_acceleration_ = longitudinal_acceleration;
134 }
135 // Sets the plan lateral acceleration limit
136 void set_lateral_acceleration(double lateral_acceleration) {
137 lateral_acceleration_ = lateral_acceleration;
138 }
139 // Sets the voltage limit
140 void set_voltage_limit(double voltage_limit) {
141 voltage_limit_ = voltage_limit;
142 }
143
144 float max_lateral_accel() const { return lateral_acceleration_; }
145
146 float max_longitudinal_accel() const { return longitudinal_acceleration_; }
147
148 float max_voltage() const { return voltage_limit_; }
149
150 // Return the next position, velocity, acceleration based on the current
151 // state. Updates the passed in state for the next iteration.
152 Eigen::Matrix<double, 3, 1> GetNextXVA(
153 std::chrono::nanoseconds dt, Eigen::Matrix<double, 2, 1> *state) const;
154
155 // Returns the distance for an index in the plan.
156 double Distance(int index) const {
157 return static_cast<double>(index) * length() /
158 static_cast<double>(distance_plan_size() - 1);
159 }
160
161 virtual fb::SegmentConstraint plan_constraint(size_t index) const = 0;
162
163 // Returns the feed forwards position, velocity, acceleration for an explicit
164 // distance.
165 Eigen::Matrix<double, 3, 1> FFAcceleration(double distance) const;
166
167 // Returns the feed forwards voltage for an explicit distance.
168 Eigen::Matrix<double, 2, 1> FFVoltage(double distance) const;
169
170 // Computes alpha for a distance.
171 size_t DistanceToSegment(double distance) const {
172 return std::max(
173 static_cast<size_t>(0),
174 std::min(distance_plan_size() - 1,
175 static_cast<size_t>(std::floor(distance / length() *
176 (distance_plan_size() - 1)))));
177 }
178
179 // Returns the goal state as a function of path distance, velocity.
180 const ::Eigen::Matrix<double, 5, 1> GoalState(double distance,
181 double velocity) const;
182
183 protected:
184 double robot_radius_l() const { return robot_radius_l_; }
185 double robot_radius_r() const { return robot_radius_r_; }
186
187 private:
188 static float ConstraintValue(
189 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
190 ConstraintType type);
191
Austin Schuhf7c65202022-11-04 21:28:20 -0700192 std::shared_ptr<
James Kuszmaul75a18c52021-03-10 22:02:07 -0800193 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
194 HybridKalman<2, 2, 2>>>
195 velocity_drivetrain_;
196
James Kuszmauldc534432023-02-05 14:51:11 -0800197 DrivetrainConfig<double> config_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800198
199 // Robot radiuses.
James Kuszmauldc534432023-02-05 14:51:11 -0800200 double robot_radius_l_;
201 double robot_radius_r_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800202 float lateral_acceleration_ = 3.0;
203 float longitudinal_acceleration_ = 2.0;
204 float voltage_limit_ = 12.0;
205};
206
207// A wrapper around the Trajectory flatbuffer to allow for controlling to a
208// spline using a pre-generated trajectory.
James Kuszmauldc534432023-02-05 14:51:11 -0800209class FinishedTrajectory : public BaseTrajectory {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800210 public:
211 // Note: The lifetime of the supplied buffer is assumed to be greater than
212 // that of this object.
Austin Schuhf7c65202022-11-04 21:28:20 -0700213 explicit FinishedTrajectory(
214 const DrivetrainConfig<double> &config, const fb::Trajectory *buffer,
215 std::shared_ptr<
216 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
217 HybridKalman<2, 2, 2>>>
218 velocity_drivetrain);
219
James Kuszmaul75a18c52021-03-10 22:02:07 -0800220 explicit FinishedTrajectory(const DrivetrainConfig<double> &config,
Austin Schuhf7c65202022-11-04 21:28:20 -0700221 const fb::Trajectory *buffer)
222 : FinishedTrajectory(
223 config, buffer,
224 std::make_shared<StateFeedbackLoop<
225 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
226 HybridKalman<2, 2, 2>>>(
227 config.make_hybrid_drivetrain_velocity_loop())) {}
James Kuszmaul75a18c52021-03-10 22:02:07 -0800228
James Kuszmauldc534432023-02-05 14:51:11 -0800229 FinishedTrajectory(const FinishedTrajectory &) = delete;
230 FinishedTrajectory &operator=(const FinishedTrajectory &) = delete;
231 FinishedTrajectory(FinishedTrajectory &&) = default;
232 FinishedTrajectory &operator=(FinishedTrajectory &&) = default;
233
James Kuszmaul75a18c52021-03-10 22:02:07 -0800234 virtual ~FinishedTrajectory() = default;
235
236 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
237 // converts it to a path-relative state, using distance as a linearization
238 // point (i.e., distance should be roughly equal to the actual distance along
239 // the path).
240 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700241 double distance, const Eigen::Matrix<double, 5, 1> &state,
242 bool drive_backwards) const;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800243
244 // Retrieves the gain matrix K for a given distance along the path.
245 Eigen::Matrix<double, 2, 5> GainForDistance(double distance) const;
246
247 size_t distance_plan_size() const override;
248 float plan_velocity(size_t index) const override;
249 fb::SegmentConstraint plan_constraint(size_t index) const override;
250
251 bool drive_spline_backwards() const {
252 return trajectory().drive_spline_backwards();
253 }
254
255 int spline_handle() const { return trajectory().handle(); }
256 const fb::Trajectory &trajectory() const { return *buffer_; }
257
258 private:
Austin Schuhf7c65202022-11-04 21:28:20 -0700259 const DistanceSplineBase &spline() const override { return spline_; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800260 const fb::Trajectory *buffer_;
James Kuszmauldc534432023-02-05 14:51:11 -0800261 FinishedDistanceSpline spline_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800262};
263
264// Class to handle plannign a trajectory and producing a flatbuffer containing
265// all the information required to create a FinishedTrajectory;
266class Trajectory : public BaseTrajectory {
267 public:
268 Trajectory(const SplineGoal &spline_goal,
269 const DrivetrainConfig<double> &config);
270 Trajectory(
271 DistanceSpline &&spline, const DrivetrainConfig<double> &config,
272 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
273 int spline_idx = 0, double vmax = 10.0, int num_distance = 0);
274
275 virtual ~Trajectory() = default;
276
James Kuszmauldc534432023-02-05 14:51:11 -0800277 std::vector<Eigen::Matrix<double, 3, 1>> PlanXVA(std::chrono::nanoseconds dt);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800278
James Kuszmaulea314d92019-02-18 19:45:06 -0800279 enum class VoltageLimit {
280 kConservative,
281 kAggressive,
282 };
283
284 // Calculates the maximum voltage at which we *can* track the path. In some
285 // cases there will be two ranges of feasible velocities for traversing the
286 // path--in such a situation, from zero to velocity A we will be able to track
287 // the path, from velocity A to B we can't, from B to C we can and above C we
288 // can't. If limit_type = kConservative, we return A; if limit_type =
289 // kAggressive, we return C. We currently just use the kConservative limit
290 // because that way we can guarantee that all velocities between zero and A
291 // are allowable and don't have to handle a more complicated planning problem.
292 // constraint_voltages will be populated by the only wheel voltages that are
293 // valid at the returned limit.
294 double VoltageVelocityLimit(
295 double distance, VoltageLimit limit_type,
296 Eigen::Matrix<double, 2, 1> *constraint_voltages = nullptr) const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100297
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800298 // Limits the velocity in the specified segment to the max velocity.
299 void LimitVelocity(double starting_distance, double ending_distance,
300 double max_velocity);
301
Austin Schuhec7f06d2019-01-04 07:47:15 +1100302 // Runs the lateral acceleration (curvature) pass on the plan.
303 void LateralAccelPass();
James Kuszmaulea314d92019-02-18 19:45:06 -0800304 void VoltageFeasibilityPass(VoltageLimit limit_type);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100305
306 // Runs the forwards pass, setting the starting velocity to 0 m/s
307 void ForwardPass();
308
Austin Schuhec7f06d2019-01-04 07:47:15 +1100309 // Runs the forwards pass, setting the ending velocity to 0 m/s
310 void BackwardPass();
311
312 // Runs all the planning passes.
313 void Plan() {
James Kuszmaulea314d92019-02-18 19:45:06 -0800314 VoltageFeasibilityPass(VoltageLimit::kConservative);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100315 LateralAccelPass();
316 ForwardPass();
317 BackwardPass();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700318 CalculatePathGains();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100319 }
320
Austin Schuhec7f06d2019-01-04 07:47:15 +1100321 // Returns a list of the distances. Mostly useful for plotting.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800322 const std::vector<double> Distances() const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100323 // Returns the distance for an index in the plan.
324 double Distance(int index) const {
325 return static_cast<double>(index) * length() /
326 static_cast<double>(plan_.size() - 1);
327 }
328
James Kuszmaul75a18c52021-03-10 22:02:07 -0800329 const std::vector<fb::SegmentConstraint> &plan_segment_type() const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800330 return plan_segment_type_;
331 }
332
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700333 // The controller represented by these functions uses a discrete-time,
334 // finite-horizon LQR with states that are relative to the predicted path
335 // of the robot to produce a gain to be used on the error.
336 // The controller does not currently account for saturation, but is defined
337 // in a way that would make accounting for saturation feasible.
338 // This controller uses a state of:
339 // distance along path
340 // distance lateral to path (positive when robot is to the left of the path).
341 // heading relative to path (positive if robot pointed to left).
342 // v_left (speed of left side of robot)
343 // v_right (speed of right side of robot).
344
345 // Retrieve the continuous-time A/B matrices for the path-relative system
346 // at the given distance along the path. Performs all linearizations about
347 // the nominal velocity that the robot should be following at that point
348 // along the path.
349 void PathRelativeContinuousSystem(double distance,
350 Eigen::Matrix<double, 5, 5> *A,
351 Eigen::Matrix<double, 5, 2> *B);
352 // Retrieve the continuous-time A/B matrices for the path-relative system
353 // given the current path-relative state, as defined above.
354 void PathRelativeContinuousSystem(const Eigen::Matrix<double, 5, 1> &X,
355 Eigen::Matrix<double, 5, 5> *A,
356 Eigen::Matrix<double, 5, 2> *B);
357
358 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
359 // converts it to a path-relative state, using distance as a linearization
360 // point (i.e., distance should be roughly equal to the actual distance along
361 // the path).
362 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
363 double distance, const Eigen::Matrix<double, 5, 1> &state);
364
365 // Estimates the current distance along the path, given the current expected
366 // distance and the [x, y, theta, v_left, v_right] state.
367 double EstimateDistanceAlongPath(double nominal_distance,
368 const Eigen::Matrix<double, 5, 1> &state);
369
370 // Calculates all the gains for each point along the planned trajectory.
371 // Only called directly in tests; this is normally a part of the planning
372 // phase, and is a relatively expensive operation.
373 void CalculatePathGains();
374
James Kuszmaul75a18c52021-03-10 22:02:07 -0800375 flatbuffers::Offset<fb::Trajectory> Serialize(
376 flatbuffers::FlatBufferBuilder *fbb) const;
377
378 const std::vector<double> plan() const { return plan_; }
379
380 const DistanceSpline &spline() const override { return spline_; }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700381
Austin Schuhec7f06d2019-01-04 07:47:15 +1100382 private:
James Kuszmauldc534432023-02-05 14:51:11 -0800383 float plan_velocity(size_t index) const override { return plan_[index]; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800384 size_t distance_plan_size() const override { return plan_.size(); }
385
386 fb::SegmentConstraint plan_constraint(size_t index) const override {
387 return plan_segment_type_[index];
Austin Schuhe73a9052019-01-07 12:16:17 -0800388 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100389
James Kuszmaul75a18c52021-03-10 22:02:07 -0800390 const int spline_idx_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100391
392 // The spline we are planning for.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800393 const DistanceSpline spline_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100394
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700395 const DrivetrainConfig<double> config_;
396
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700397 // Velocities in the plan (distance for each index is defined by Distance())
398 std::vector<double> plan_;
399 // Gain matrices to use for the path-relative state error at each stage in the
400 // plan Individual elements of the plan_gains_ vector are separated by
401 // config_.dt in time.
402 // The first value in the pair is the distance along the path corresponding to
403 // the gain matrix; the second value is the gain itself.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800404 std::vector<std::pair<double, Eigen::Matrix<float, 2, 5>>> plan_gains_;
405 std::vector<fb::SegmentConstraint> plan_segment_type_;
406
407 bool drive_spline_backwards_ = false;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100408};
409
410// Returns the continuous time dynamics given the [x, y, theta, vl, vr] state
411// and the [vl, vr] input voltage.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800412inline Eigen::Matrix<double, 5, 1> ContinuousDynamics(
Austin Schuhec7f06d2019-01-04 07:47:15 +1100413 const StateFeedbackHybridPlant<2, 2, 2> &velocity_drivetrain,
James Kuszmaul75a18c52021-03-10 22:02:07 -0800414 const Eigen::Matrix<double, 2, 2> &Tlr_to_la,
James Kuszmauldc534432023-02-05 14:51:11 -0800415 const Eigen::Matrix<double, 5, 1> X, const Eigen::Matrix<double, 2, 1> U) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100416 const auto &velocity = X.block<2, 1>(3, 0);
417 const double theta = X(2);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800418 Eigen::Matrix<double, 2, 1> la = Tlr_to_la * velocity;
419 return (Eigen::Matrix<double, 5, 1>() << std::cos(theta) * la(0),
420 std::sin(theta) * la(0), la(1),
Austin Schuhec7f06d2019-01-04 07:47:15 +1100421 (velocity_drivetrain.coefficients().A_continuous * velocity +
422 velocity_drivetrain.coefficients().B_continuous * U))
423 .finished();
424}
425
426} // namespace drivetrain
427} // namespace control_loops
428} // namespace frc971
429
430#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_