blob: ab1c55f8782a6c15d84a20f6d063d75f4ce38c59 [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"
James Kuszmauldc534432023-02-05 14:51:11 -08007#include "aos/flatbuffers.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"
James Kuszmaul75a18c52021-03-10 22:02:07 -080010#include "frc971/control_loops/drivetrain/spline_goal_generated.h"
James Kuszmauldc534432023-02-05 14:51:11 -080011#include "frc971/control_loops/drivetrain/trajectory_generated.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +110012#include "frc971/control_loops/hybrid_state_feedback_loop.h"
13#include "frc971/control_loops/runge_kutta.h"
14#include "frc971/control_loops/state_feedback_loop.h"
15
16namespace frc971 {
17namespace control_loops {
18namespace drivetrain {
19
20template <typename F>
21double IntegrateAccelForDistance(const F &fn, double v, double x, double dx) {
22 // Use a trick from
23 // https://www.johndcook.com/blog/2012/02/21/care-and-treatment-of-singularities/
24 const double a0 = fn(x, v);
25
26 return (RungeKutta(
27 [&fn, &a0](double t, double y) {
28 // Since we know that a0 == a(0) and that they are asymtotically
29 // the same at 0, we know that the limit is 0 at 0. This is
30 // true because when starting from a stop, under sane
31 // accelerations, we can assume that we will start with a
32 // constant acceleration. So, hard-code it.
James Kuszmaul75a18c52021-03-10 22:02:07 -080033 if (std::abs(y) < 1e-6) {
Austin Schuhec7f06d2019-01-04 07:47:15 +110034 return 0.0;
35 }
36 return (fn(t, y) - a0) / y;
37 },
38 v, x, dx) -
39 v) +
James Kuszmaul75a18c52021-03-10 22:02:07 -080040 std::sqrt(2.0 * a0 * dx + v * v);
Austin Schuhec7f06d2019-01-04 07:47:15 +110041}
42
James Kuszmaul75a18c52021-03-10 22:02:07 -080043class BaseTrajectory {
Austin Schuhec7f06d2019-01-04 07:47:15 +110044 public:
James Kuszmaul75a18c52021-03-10 22:02:07 -080045 BaseTrajectory(
46 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
Austin Schuhf7c65202022-11-04 21:28:20 -070047 const DrivetrainConfig<double> &config)
48 : BaseTrajectory(constraints, config,
49 std::make_shared<StateFeedbackLoop<
50 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
51 HybridKalman<2, 2, 2>>>(
52 config.make_hybrid_drivetrain_velocity_loop())) {}
53
54 BaseTrajectory(
55 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
56 const DrivetrainConfig<double> &config,
57 std::shared_ptr<
58 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
59 HybridKalman<2, 2, 2>>>
60 velocity_drivetrain);
James Kuszmaul75a18c52021-03-10 22:02:07 -080061
62 virtual ~BaseTrajectory() = default;
Austin Schuhec7f06d2019-01-04 07:47:15 +110063
James Kuszmaulea314d92019-02-18 19:45:06 -080064 // Returns the friction-constrained velocity limit at a given distance along
65 // the path. At the returned velocity, one or both wheels will be on the edge
66 // of slipping.
67 // There are some very disorganized thoughts on the math here and in some of
68 // the other functions in spline_math.tex.
69 double LateralVelocityCurvature(double distance) const;
70
71 // Returns the range of allowable longitudinal accelerations for the center of
72 // the robot at a particular distance (x) along the path and velocity (v).
73 // min_accel and max_accel correspodn to the min/max accelerations that can be
74 // achieved without breaking friction limits on one or both wheels.
75 // If max_accel < min_accel, that implies that v is too high for there to be
76 // any valid acceleration. FrictionLngAccelLimits(x,
77 // LateralVelocityCurvature(x), &min_accel, &max_accel) should result in
78 // min_accel == max_accel.
79 void FrictionLngAccelLimits(double x, double v, double *min_accel,
80 double *max_accel) const;
81
James Kuszmaul75a18c52021-03-10 22:02:07 -080082 // Returns the forwards/backwards acceleration for a distance along the spline
83 // taking into account the lateral acceleration, longitudinal acceleration,
84 // and voltage limits.
85 double BestAcceleration(double x, double v, bool backwards) const;
86 double BackwardAcceleration(double x, double v) const {
87 return BestAcceleration(x, v, true);
88 }
89 double ForwardAcceleration(double x, double v) const {
90 return BestAcceleration(x, v, false);
91 }
92
93 const StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
94 HybridKalman<2, 2, 2>>
95 &velocity_drivetrain() const {
96 return *velocity_drivetrain_;
97 }
98
99 // Returns K1 and K2.
100 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
101 const Eigen::Matrix<double, 2, 1> K1(double current_ddtheta) const;
102 const Eigen::Matrix<double, 2, 1> K2(double current_dtheta) const;
103
104 // Computes K3, K4, and K5 for the provided distance.
105 // K5 a + K3 v^2 + K4 v = U
106 void K345(const double x, Eigen::Matrix<double, 2, 1> *K3,
107 Eigen::Matrix<double, 2, 1> *K4,
108 Eigen::Matrix<double, 2, 1> *K5) const;
109
Austin Schuhf7c65202022-11-04 21:28:20 -0700110 virtual const DistanceSplineBase &spline() const = 0;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800111
112 // Returns the length of the path in meters.
113 double length() const { return spline().length(); }
114
115 // Returns whether a state represents a state at the end of the spline.
116 bool is_at_end(Eigen::Matrix<double, 2, 1> state) const {
117 return state(0) > length() - 1e-4;
118 }
119
120 // Returns true if the state is invalid or unreasonable in some way.
121 bool state_is_faulted(Eigen::Matrix<double, 2, 1> state) const {
122 // Consider things faulted if the current velocity implies we are going
123 // backwards or if any infinities/NaNs have crept in.
124 return state(1) < 0 || !state.allFinite();
125 }
126
127 virtual float plan_velocity(size_t index) const = 0;
128 virtual size_t distance_plan_size() const = 0;
129
130 // Sets the plan longitudinal acceleration limit
131 void set_longitudinal_acceleration(double longitudinal_acceleration) {
132 longitudinal_acceleration_ = longitudinal_acceleration;
133 }
134 // Sets the plan lateral acceleration limit
135 void set_lateral_acceleration(double lateral_acceleration) {
136 lateral_acceleration_ = lateral_acceleration;
137 }
138 // Sets the voltage limit
139 void set_voltage_limit(double voltage_limit) {
140 voltage_limit_ = voltage_limit;
141 }
142
143 float max_lateral_accel() const { return lateral_acceleration_; }
144
145 float max_longitudinal_accel() const { return longitudinal_acceleration_; }
146
147 float max_voltage() const { return voltage_limit_; }
148
149 // Return the next position, velocity, acceleration based on the current
150 // state. Updates the passed in state for the next iteration.
151 Eigen::Matrix<double, 3, 1> GetNextXVA(
152 std::chrono::nanoseconds dt, Eigen::Matrix<double, 2, 1> *state) const;
153
154 // Returns the distance for an index in the plan.
155 double Distance(int index) const {
156 return static_cast<double>(index) * length() /
157 static_cast<double>(distance_plan_size() - 1);
158 }
159
160 virtual fb::SegmentConstraint plan_constraint(size_t index) const = 0;
161
162 // Returns the feed forwards position, velocity, acceleration for an explicit
163 // distance.
164 Eigen::Matrix<double, 3, 1> FFAcceleration(double distance) const;
165
166 // Returns the feed forwards voltage for an explicit distance.
167 Eigen::Matrix<double, 2, 1> FFVoltage(double distance) const;
168
169 // Computes alpha for a distance.
170 size_t DistanceToSegment(double distance) const {
171 return std::max(
172 static_cast<size_t>(0),
173 std::min(distance_plan_size() - 1,
174 static_cast<size_t>(std::floor(distance / length() *
175 (distance_plan_size() - 1)))));
176 }
177
178 // Returns the goal state as a function of path distance, velocity.
179 const ::Eigen::Matrix<double, 5, 1> GoalState(double distance,
180 double velocity) const;
181
182 protected:
183 double robot_radius_l() const { return robot_radius_l_; }
184 double robot_radius_r() const { return robot_radius_r_; }
185
186 private:
187 static float ConstraintValue(
188 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
189 ConstraintType type);
190
Austin Schuhf7c65202022-11-04 21:28:20 -0700191 std::shared_ptr<
James Kuszmaul75a18c52021-03-10 22:02:07 -0800192 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
193 HybridKalman<2, 2, 2>>>
194 velocity_drivetrain_;
195
James Kuszmauldc534432023-02-05 14:51:11 -0800196 DrivetrainConfig<double> config_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800197
198 // Robot radiuses.
James Kuszmauldc534432023-02-05 14:51:11 -0800199 double robot_radius_l_;
200 double robot_radius_r_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800201 float lateral_acceleration_ = 3.0;
202 float longitudinal_acceleration_ = 2.0;
203 float voltage_limit_ = 12.0;
204};
205
206// A wrapper around the Trajectory flatbuffer to allow for controlling to a
207// spline using a pre-generated trajectory.
James Kuszmauldc534432023-02-05 14:51:11 -0800208class FinishedTrajectory : public BaseTrajectory {
James Kuszmaul75a18c52021-03-10 22:02:07 -0800209 public:
210 // Note: The lifetime of the supplied buffer is assumed to be greater than
211 // that of this object.
Austin Schuhf7c65202022-11-04 21:28:20 -0700212 explicit FinishedTrajectory(
213 const DrivetrainConfig<double> &config, const fb::Trajectory *buffer,
214 std::shared_ptr<
215 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
216 HybridKalman<2, 2, 2>>>
217 velocity_drivetrain);
218
James Kuszmaul75a18c52021-03-10 22:02:07 -0800219 explicit FinishedTrajectory(const DrivetrainConfig<double> &config,
Austin Schuhf7c65202022-11-04 21:28:20 -0700220 const fb::Trajectory *buffer)
221 : FinishedTrajectory(
222 config, buffer,
223 std::make_shared<StateFeedbackLoop<
224 2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
225 HybridKalman<2, 2, 2>>>(
226 config.make_hybrid_drivetrain_velocity_loop())) {}
James Kuszmaul75a18c52021-03-10 22:02:07 -0800227
James Kuszmauldc534432023-02-05 14:51:11 -0800228 FinishedTrajectory(const FinishedTrajectory &) = delete;
229 FinishedTrajectory &operator=(const FinishedTrajectory &) = delete;
230 FinishedTrajectory(FinishedTrajectory &&) = default;
231 FinishedTrajectory &operator=(FinishedTrajectory &&) = default;
232
James Kuszmaul75a18c52021-03-10 22:02:07 -0800233 virtual ~FinishedTrajectory() = default;
234
235 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
236 // converts it to a path-relative state, using distance as a linearization
237 // point (i.e., distance should be roughly equal to the actual distance along
238 // the path).
239 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700240 double distance, const Eigen::Matrix<double, 5, 1> &state,
241 bool drive_backwards) const;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800242
243 // Retrieves the gain matrix K for a given distance along the path.
244 Eigen::Matrix<double, 2, 5> GainForDistance(double distance) const;
245
246 size_t distance_plan_size() const override;
247 float plan_velocity(size_t index) const override;
248 fb::SegmentConstraint plan_constraint(size_t index) const override;
249
250 bool drive_spline_backwards() const {
251 return trajectory().drive_spline_backwards();
252 }
253
254 int spline_handle() const { return trajectory().handle(); }
255 const fb::Trajectory &trajectory() const { return *buffer_; }
256
257 private:
Austin Schuhf7c65202022-11-04 21:28:20 -0700258 const DistanceSplineBase &spline() const override { return spline_; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800259 const fb::Trajectory *buffer_;
James Kuszmauldc534432023-02-05 14:51:11 -0800260 FinishedDistanceSpline spline_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800261};
262
263// Class to handle plannign a trajectory and producing a flatbuffer containing
264// all the information required to create a FinishedTrajectory;
265class Trajectory : public BaseTrajectory {
266 public:
267 Trajectory(const SplineGoal &spline_goal,
268 const DrivetrainConfig<double> &config);
269 Trajectory(
270 DistanceSpline &&spline, const DrivetrainConfig<double> &config,
271 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
272 int spline_idx = 0, double vmax = 10.0, int num_distance = 0);
273
274 virtual ~Trajectory() = default;
275
James Kuszmauldc534432023-02-05 14:51:11 -0800276 std::vector<Eigen::Matrix<double, 3, 1>> PlanXVA(std::chrono::nanoseconds dt);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800277
James Kuszmaulea314d92019-02-18 19:45:06 -0800278 enum class VoltageLimit {
279 kConservative,
280 kAggressive,
281 };
282
283 // Calculates the maximum voltage at which we *can* track the path. In some
284 // cases there will be two ranges of feasible velocities for traversing the
285 // path--in such a situation, from zero to velocity A we will be able to track
286 // the path, from velocity A to B we can't, from B to C we can and above C we
287 // can't. If limit_type = kConservative, we return A; if limit_type =
288 // kAggressive, we return C. We currently just use the kConservative limit
289 // because that way we can guarantee that all velocities between zero and A
290 // are allowable and don't have to handle a more complicated planning problem.
291 // constraint_voltages will be populated by the only wheel voltages that are
292 // valid at the returned limit.
293 double VoltageVelocityLimit(
294 double distance, VoltageLimit limit_type,
295 Eigen::Matrix<double, 2, 1> *constraint_voltages = nullptr) const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100296
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800297 // Limits the velocity in the specified segment to the max velocity.
298 void LimitVelocity(double starting_distance, double ending_distance,
299 double max_velocity);
300
Austin Schuhec7f06d2019-01-04 07:47:15 +1100301 // Runs the lateral acceleration (curvature) pass on the plan.
302 void LateralAccelPass();
James Kuszmaulea314d92019-02-18 19:45:06 -0800303 void VoltageFeasibilityPass(VoltageLimit limit_type);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100304
305 // Runs the forwards pass, setting the starting velocity to 0 m/s
306 void ForwardPass();
307
Austin Schuhec7f06d2019-01-04 07:47:15 +1100308 // Runs the forwards pass, setting the ending velocity to 0 m/s
309 void BackwardPass();
310
311 // Runs all the planning passes.
312 void Plan() {
James Kuszmaulea314d92019-02-18 19:45:06 -0800313 VoltageFeasibilityPass(VoltageLimit::kConservative);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100314 LateralAccelPass();
315 ForwardPass();
316 BackwardPass();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700317 CalculatePathGains();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100318 }
319
Austin Schuhec7f06d2019-01-04 07:47:15 +1100320 // Returns a list of the distances. Mostly useful for plotting.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800321 const std::vector<double> Distances() const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100322 // Returns the distance for an index in the plan.
323 double Distance(int index) const {
324 return static_cast<double>(index) * length() /
325 static_cast<double>(plan_.size() - 1);
326 }
327
James Kuszmaul75a18c52021-03-10 22:02:07 -0800328 const std::vector<fb::SegmentConstraint> &plan_segment_type() const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800329 return plan_segment_type_;
330 }
331
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700332 // The controller represented by these functions uses a discrete-time,
333 // finite-horizon LQR with states that are relative to the predicted path
334 // of the robot to produce a gain to be used on the error.
335 // The controller does not currently account for saturation, but is defined
336 // in a way that would make accounting for saturation feasible.
337 // This controller uses a state of:
338 // distance along path
339 // distance lateral to path (positive when robot is to the left of the path).
340 // heading relative to path (positive if robot pointed to left).
341 // v_left (speed of left side of robot)
342 // v_right (speed of right side of robot).
343
344 // Retrieve the continuous-time A/B matrices for the path-relative system
345 // at the given distance along the path. Performs all linearizations about
346 // the nominal velocity that the robot should be following at that point
347 // along the path.
348 void PathRelativeContinuousSystem(double distance,
349 Eigen::Matrix<double, 5, 5> *A,
350 Eigen::Matrix<double, 5, 2> *B);
351 // Retrieve the continuous-time A/B matrices for the path-relative system
352 // given the current path-relative state, as defined above.
353 void PathRelativeContinuousSystem(const Eigen::Matrix<double, 5, 1> &X,
354 Eigen::Matrix<double, 5, 5> *A,
355 Eigen::Matrix<double, 5, 2> *B);
356
357 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
358 // converts it to a path-relative state, using distance as a linearization
359 // point (i.e., distance should be roughly equal to the actual distance along
360 // the path).
361 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
362 double distance, const Eigen::Matrix<double, 5, 1> &state);
363
364 // Estimates the current distance along the path, given the current expected
365 // distance and the [x, y, theta, v_left, v_right] state.
366 double EstimateDistanceAlongPath(double nominal_distance,
367 const Eigen::Matrix<double, 5, 1> &state);
368
369 // Calculates all the gains for each point along the planned trajectory.
370 // Only called directly in tests; this is normally a part of the planning
371 // phase, and is a relatively expensive operation.
372 void CalculatePathGains();
373
James Kuszmaul75a18c52021-03-10 22:02:07 -0800374 flatbuffers::Offset<fb::Trajectory> Serialize(
375 flatbuffers::FlatBufferBuilder *fbb) const;
376
377 const std::vector<double> plan() const { return plan_; }
378
379 const DistanceSpline &spline() const override { return spline_; }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700380
Austin Schuhec7f06d2019-01-04 07:47:15 +1100381 private:
James Kuszmauldc534432023-02-05 14:51:11 -0800382 float plan_velocity(size_t index) const override { return plan_[index]; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800383 size_t distance_plan_size() const override { return plan_.size(); }
384
385 fb::SegmentConstraint plan_constraint(size_t index) const override {
386 return plan_segment_type_[index];
Austin Schuhe73a9052019-01-07 12:16:17 -0800387 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100388
James Kuszmaul75a18c52021-03-10 22:02:07 -0800389 const int spline_idx_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100390
391 // The spline we are planning for.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800392 const DistanceSpline spline_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100393
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700394 const DrivetrainConfig<double> config_;
395
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700396 // Velocities in the plan (distance for each index is defined by Distance())
397 std::vector<double> plan_;
398 // Gain matrices to use for the path-relative state error at each stage in the
399 // plan Individual elements of the plan_gains_ vector are separated by
400 // config_.dt in time.
401 // The first value in the pair is the distance along the path corresponding to
402 // the gain matrix; the second value is the gain itself.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800403 std::vector<std::pair<double, Eigen::Matrix<float, 2, 5>>> plan_gains_;
404 std::vector<fb::SegmentConstraint> plan_segment_type_;
405
406 bool drive_spline_backwards_ = false;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100407};
408
409// Returns the continuous time dynamics given the [x, y, theta, vl, vr] state
410// and the [vl, vr] input voltage.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800411inline Eigen::Matrix<double, 5, 1> ContinuousDynamics(
Austin Schuhec7f06d2019-01-04 07:47:15 +1100412 const StateFeedbackHybridPlant<2, 2, 2> &velocity_drivetrain,
James Kuszmaul75a18c52021-03-10 22:02:07 -0800413 const Eigen::Matrix<double, 2, 2> &Tlr_to_la,
James Kuszmauldc534432023-02-05 14:51:11 -0800414 const Eigen::Matrix<double, 5, 1> X, const Eigen::Matrix<double, 2, 1> U) {
Austin Schuhec7f06d2019-01-04 07:47:15 +1100415 const auto &velocity = X.block<2, 1>(3, 0);
416 const double theta = X(2);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800417 Eigen::Matrix<double, 2, 1> la = Tlr_to_la * velocity;
418 return (Eigen::Matrix<double, 5, 1>() << std::cos(theta) * la(0),
419 std::sin(theta) * la(0), la(1),
Austin Schuhec7f06d2019-01-04 07:47:15 +1100420 (velocity_drivetrain.coefficients().A_continuous * velocity +
421 velocity_drivetrain.coefficients().B_continuous * U))
422 .finished();
423}
424
425} // namespace drivetrain
426} // namespace control_loops
427} // namespace frc971
428
429#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_