blob: 6bccc74961f95d9850fc5d7514c54cafdd2c8118 [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
James Kuszmaul75a18c52021-03-10 22:02:07 -08006#include "aos/flatbuffers.h"
Austin Schuhec7f06d2019-01-04 07:47:15 +11007#include "Eigen/Dense"
8#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/trajectory_generated.h"
11#include "frc971/control_loops/drivetrain/spline_goal_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
196 const DrivetrainConfig<double> config_;
197
198 // Robot radiuses.
199 const double robot_radius_l_;
200 const double robot_radius_r_;
201 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.
208class FinishedTrajectory : public BaseTrajectory {
209 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
228 virtual ~FinishedTrajectory() = default;
229
230 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
231 // converts it to a path-relative state, using distance as a linearization
232 // point (i.e., distance should be roughly equal to the actual distance along
233 // the path).
234 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
James Kuszmaul5e8ce312021-03-27 14:59:17 -0700235 double distance, const Eigen::Matrix<double, 5, 1> &state,
236 bool drive_backwards) const;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800237
238 // Retrieves the gain matrix K for a given distance along the path.
239 Eigen::Matrix<double, 2, 5> GainForDistance(double distance) const;
240
241 size_t distance_plan_size() const override;
242 float plan_velocity(size_t index) const override;
243 fb::SegmentConstraint plan_constraint(size_t index) const override;
244
245 bool drive_spline_backwards() const {
246 return trajectory().drive_spline_backwards();
247 }
248
249 int spline_handle() const { return trajectory().handle(); }
250 const fb::Trajectory &trajectory() const { return *buffer_; }
251
252 private:
Austin Schuhf7c65202022-11-04 21:28:20 -0700253 const DistanceSplineBase &spline() const override { return spline_; }
James Kuszmaul75a18c52021-03-10 22:02:07 -0800254 const fb::Trajectory *buffer_;
Austin Schuhf7c65202022-11-04 21:28:20 -0700255 const FinishedDistanceSpline spline_;
James Kuszmaul75a18c52021-03-10 22:02:07 -0800256};
257
258// Class to handle plannign a trajectory and producing a flatbuffer containing
259// all the information required to create a FinishedTrajectory;
260class Trajectory : public BaseTrajectory {
261 public:
262 Trajectory(const SplineGoal &spline_goal,
263 const DrivetrainConfig<double> &config);
264 Trajectory(
265 DistanceSpline &&spline, const DrivetrainConfig<double> &config,
266 const flatbuffers::Vector<flatbuffers::Offset<Constraint>> *constraints,
267 int spline_idx = 0, double vmax = 10.0, int num_distance = 0);
268
269 virtual ~Trajectory() = default;
270
271 std::vector<Eigen::Matrix<double, 3, 1>> PlanXVA(
272 std::chrono::nanoseconds dt);
273
James Kuszmaulea314d92019-02-18 19:45:06 -0800274 enum class VoltageLimit {
275 kConservative,
276 kAggressive,
277 };
278
279 // Calculates the maximum voltage at which we *can* track the path. In some
280 // cases there will be two ranges of feasible velocities for traversing the
281 // path--in such a situation, from zero to velocity A we will be able to track
282 // the path, from velocity A to B we can't, from B to C we can and above C we
283 // can't. If limit_type = kConservative, we return A; if limit_type =
284 // kAggressive, we return C. We currently just use the kConservative limit
285 // because that way we can guarantee that all velocities between zero and A
286 // are allowable and don't have to handle a more complicated planning problem.
287 // constraint_voltages will be populated by the only wheel voltages that are
288 // valid at the returned limit.
289 double VoltageVelocityLimit(
290 double distance, VoltageLimit limit_type,
291 Eigen::Matrix<double, 2, 1> *constraint_voltages = nullptr) const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100292
Austin Schuh5b9e9c22019-01-07 15:44:06 -0800293 // Limits the velocity in the specified segment to the max velocity.
294 void LimitVelocity(double starting_distance, double ending_distance,
295 double max_velocity);
296
Austin Schuhec7f06d2019-01-04 07:47:15 +1100297 // Runs the lateral acceleration (curvature) pass on the plan.
298 void LateralAccelPass();
James Kuszmaulea314d92019-02-18 19:45:06 -0800299 void VoltageFeasibilityPass(VoltageLimit limit_type);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100300
301 // Runs the forwards pass, setting the starting velocity to 0 m/s
302 void ForwardPass();
303
Austin Schuhec7f06d2019-01-04 07:47:15 +1100304 // Runs the forwards pass, setting the ending velocity to 0 m/s
305 void BackwardPass();
306
307 // Runs all the planning passes.
308 void Plan() {
James Kuszmaulea314d92019-02-18 19:45:06 -0800309 VoltageFeasibilityPass(VoltageLimit::kConservative);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100310 LateralAccelPass();
311 ForwardPass();
312 BackwardPass();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700313 CalculatePathGains();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100314 }
315
Austin Schuhec7f06d2019-01-04 07:47:15 +1100316 // Returns a list of the distances. Mostly useful for plotting.
James Kuszmaul75a18c52021-03-10 22:02:07 -0800317 const std::vector<double> Distances() const;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100318 // Returns the distance for an index in the plan.
319 double Distance(int index) const {
320 return static_cast<double>(index) * length() /
321 static_cast<double>(plan_.size() - 1);
322 }
323
James Kuszmaul75a18c52021-03-10 22:02:07 -0800324 const std::vector<fb::SegmentConstraint> &plan_segment_type() const {
Austin Schuhe73a9052019-01-07 12:16:17 -0800325 return plan_segment_type_;
326 }
327
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700328 // The controller represented by these functions uses a discrete-time,
329 // finite-horizon LQR with states that are relative to the predicted path
330 // of the robot to produce a gain to be used on the error.
331 // The controller does not currently account for saturation, but is defined
332 // in a way that would make accounting for saturation feasible.
333 // This controller uses a state of:
334 // distance along path
335 // distance lateral to path (positive when robot is to the left of the path).
336 // heading relative to path (positive if robot pointed to left).
337 // v_left (speed of left side of robot)
338 // v_right (speed of right side of robot).
339
340 // Retrieve the continuous-time A/B matrices for the path-relative system
341 // at the given distance along the path. Performs all linearizations about
342 // the nominal velocity that the robot should be following at that point
343 // along the path.
344 void PathRelativeContinuousSystem(double distance,
345 Eigen::Matrix<double, 5, 5> *A,
346 Eigen::Matrix<double, 5, 2> *B);
347 // Retrieve the continuous-time A/B matrices for the path-relative system
348 // given the current path-relative state, as defined above.
349 void PathRelativeContinuousSystem(const Eigen::Matrix<double, 5, 1> &X,
350 Eigen::Matrix<double, 5, 5> *A,
351 Eigen::Matrix<double, 5, 2> *B);
352
353 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
354 // converts it to a path-relative state, using distance as a linearization
355 // point (i.e., distance should be roughly equal to the actual distance along
356 // the path).
357 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
358 double distance, const Eigen::Matrix<double, 5, 1> &state);
359
360 // Estimates the current distance along the path, given the current expected
361 // distance and the [x, y, theta, v_left, v_right] state.
362 double EstimateDistanceAlongPath(double nominal_distance,
363 const Eigen::Matrix<double, 5, 1> &state);
364
365 // Calculates all the gains for each point along the planned trajectory.
366 // Only called directly in tests; this is normally a part of the planning
367 // phase, and is a relatively expensive operation.
368 void CalculatePathGains();
369
James Kuszmaul75a18c52021-03-10 22:02:07 -0800370 flatbuffers::Offset<fb::Trajectory> Serialize(
371 flatbuffers::FlatBufferBuilder *fbb) const;
372
373 const std::vector<double> plan() const { return plan_; }
374
375 const DistanceSpline &spline() const override { return spline_; }
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700376
Austin Schuhec7f06d2019-01-04 07:47:15 +1100377 private:
James Kuszmaul75a18c52021-03-10 22:02:07 -0800378
379 float plan_velocity(size_t index) const override {
380 return plan_[index];
381 }
382 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,
413 const Eigen::Matrix<double, 5, 1> X,
414 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_