blob: ef02db596db22b20b5996922504eb57d039cde5b [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"
7#include "frc971/control_loops/drivetrain/distance_spline.h"
8#include "frc971/control_loops/drivetrain/drivetrain_config.h"
9#include "frc971/control_loops/hybrid_state_feedback_loop.h"
10#include "frc971/control_loops/runge_kutta.h"
11#include "frc971/control_loops/state_feedback_loop.h"
12
13namespace frc971 {
14namespace control_loops {
15namespace drivetrain {
16
17template <typename F>
18double IntegrateAccelForDistance(const F &fn, double v, double x, double dx) {
19 // Use a trick from
20 // https://www.johndcook.com/blog/2012/02/21/care-and-treatment-of-singularities/
21 const double a0 = fn(x, v);
22
23 return (RungeKutta(
24 [&fn, &a0](double t, double y) {
25 // Since we know that a0 == a(0) and that they are asymtotically
26 // the same at 0, we know that the limit is 0 at 0. This is
27 // true because when starting from a stop, under sane
28 // accelerations, we can assume that we will start with a
29 // constant acceleration. So, hard-code it.
30 if (::std::abs(y) < 1e-6) {
31 return 0.0;
32 }
33 return (fn(t, y) - a0) / y;
34 },
35 v, x, dx) -
36 v) +
37 ::std::sqrt(2.0 * a0 * dx + v * v);
38}
39
40// Class to plan and hold the velocity plan for a spline.
41class Trajectory {
42 public:
43 Trajectory(const DistanceSpline *spline,
Austin Schuh45cfd8b2019-01-07 16:14:31 -080044 const DrivetrainConfig<double> &config, double vmax = 10.0,
45 int num_distance = 0);
James Kuszmaulea314d92019-02-18 19:45:06 -080046 // Sets the plan longitudinal acceleration limit
47 void set_longitudinal_acceleration(double longitudinal_acceleration) {
48 longitudinal_acceleration_ = longitudinal_acceleration;
Austin Schuhec7f06d2019-01-04 07:47:15 +110049 }
50 // Sets the plan lateral acceleration limit
51 void set_lateral_acceleration(double lateral_acceleration) {
52 lateral_acceleration_ = lateral_acceleration;
53 }
54 // Sets the voltage limit
55 void set_voltage_limit(double voltage_limit) {
56 voltage_limit_ = voltage_limit;
57 }
58
James Kuszmaulea314d92019-02-18 19:45:06 -080059 // Returns the friction-constrained velocity limit at a given distance along
60 // the path. At the returned velocity, one or both wheels will be on the edge
61 // of slipping.
62 // There are some very disorganized thoughts on the math here and in some of
63 // the other functions in spline_math.tex.
64 double LateralVelocityCurvature(double distance) const;
65
66 // Returns the range of allowable longitudinal accelerations for the center of
67 // the robot at a particular distance (x) along the path and velocity (v).
68 // min_accel and max_accel correspodn to the min/max accelerations that can be
69 // achieved without breaking friction limits on one or both wheels.
70 // If max_accel < min_accel, that implies that v is too high for there to be
71 // any valid acceleration. FrictionLngAccelLimits(x,
72 // LateralVelocityCurvature(x), &min_accel, &max_accel) should result in
73 // min_accel == max_accel.
74 void FrictionLngAccelLimits(double x, double v, double *min_accel,
75 double *max_accel) const;
76
77 enum class VoltageLimit {
78 kConservative,
79 kAggressive,
80 };
81
82 // Calculates the maximum voltage at which we *can* track the path. In some
83 // cases there will be two ranges of feasible velocities for traversing the
84 // path--in such a situation, from zero to velocity A we will be able to track
85 // the path, from velocity A to B we can't, from B to C we can and above C we
86 // can't. If limit_type = kConservative, we return A; if limit_type =
87 // kAggressive, we return C. We currently just use the kConservative limit
88 // because that way we can guarantee that all velocities between zero and A
89 // are allowable and don't have to handle a more complicated planning problem.
90 // constraint_voltages will be populated by the only wheel voltages that are
91 // valid at the returned limit.
92 double VoltageVelocityLimit(
93 double distance, VoltageLimit limit_type,
94 Eigen::Matrix<double, 2, 1> *constraint_voltages = nullptr) const;
Austin Schuhec7f06d2019-01-04 07:47:15 +110095
Austin Schuh5b9e9c22019-01-07 15:44:06 -080096 // Limits the velocity in the specified segment to the max velocity.
97 void LimitVelocity(double starting_distance, double ending_distance,
98 double max_velocity);
99
Austin Schuhec7f06d2019-01-04 07:47:15 +1100100 // Runs the lateral acceleration (curvature) pass on the plan.
101 void LateralAccelPass();
James Kuszmaulea314d92019-02-18 19:45:06 -0800102 void VoltageFeasibilityPass(VoltageLimit limit_type);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100103
104 // Runs the forwards pass, setting the starting velocity to 0 m/s
105 void ForwardPass();
106
James Kuszmaulea314d92019-02-18 19:45:06 -0800107 // Returns the forwards/backwards acceleration for a distance along the spline
108 // taking into account the lateral acceleration, longitudinal acceleration,
109 // and voltage limits.
110 double BestAcceleration(double x, double v, bool backwards);
111 double BackwardAcceleration(double x, double v) {
112 return BestAcceleration(x, v, true);
113 }
114 double ForwardAcceleration(double x, double v) {
115 return BestAcceleration(x, v, false);
116 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100117
118 // Runs the forwards pass, setting the ending velocity to 0 m/s
119 void BackwardPass();
120
121 // Runs all the planning passes.
122 void Plan() {
James Kuszmaulea314d92019-02-18 19:45:06 -0800123 VoltageFeasibilityPass(VoltageLimit::kConservative);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100124 LateralAccelPass();
125 ForwardPass();
126 BackwardPass();
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700127 CalculatePathGains();
Austin Schuhec7f06d2019-01-04 07:47:15 +1100128 }
129
130 // Returns the feed forwards position, velocity, acceleration for an explicit
131 // distance.
132 ::Eigen::Matrix<double, 3, 1> FFAcceleration(double distance);
133
134 // Returns the feed forwards voltage for an explicit distance.
135 ::Eigen::Matrix<double, 2, 1> FFVoltage(double distance);
136
Alex Perry4ae2fd72019-02-03 15:55:57 -0800137 // Returns whether a state represents a state at the end of the spline.
138 bool is_at_end(::Eigen::Matrix<double, 2, 1> state) const {
139 return state(0) > length() - 1e-4;
140 }
141
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800142 // Returns true if the state is invalid or unreasonable in some way.
143 bool state_is_faulted(::Eigen::Matrix<double, 2, 1> state) const {
144 // Consider things faulted if the current velocity implies we are going
145 // backwards or if any infinities/NaNs have crept in.
146 return state(1) < 0 || !state.allFinite();
147 }
148
Austin Schuhec7f06d2019-01-04 07:47:15 +1100149 // Returns the length of the path in meters.
150 double length() const { return spline_->length(); }
151
152 // Returns a list of the distances. Mostly useful for plotting.
153 const ::std::vector<double> Distances() const;
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>(plan_.size() - 1);
158 }
159
160 // Returns the plan. This is the pathwise velocity as a function of distance.
161 // To get the distance for an index, use the Distance(index) function provided
162 // with the index.
163 const ::std::vector<double> plan() const { return plan_; }
164
165 // Returns the left, right to linear, angular transformation matrix.
166 const ::Eigen::Matrix<double, 2, 2> &Tlr_to_la() const { return Tlr_to_la_; }
167 // Returns the linear, angular to left, right transformation matrix.
168 const ::Eigen::Matrix<double, 2, 2> &Tla_to_lr() const { return Tla_to_lr_; }
169
170 // Returns the goal state as a function of path distance, velocity.
171 const ::Eigen::Matrix<double, 5, 1> GoalState(double distance,
172 double velocity);
173
174 // Returns the velocity drivetrain in use.
175 const StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
176 HybridKalman<2, 2, 2>>
177 &velocity_drivetrain() const {
178 return *velocity_drivetrain_;
179 }
180
181 // Returns the continuous statespace A and B matricies for [x, y, theta, vl,
182 // vr] for the linearized system (around the provided state).
183 ::Eigen::Matrix<double, 5, 5> ALinearizedContinuous(
184 const ::Eigen::Matrix<double, 5, 1> &state) const;
185 ::Eigen::Matrix<double, 5, 2> BLinearizedContinuous() const;
186
187 // Returns the discrete time A and B matricies for the provided state,
188 // assuming the provided timestep.
189 void AB(const ::Eigen::Matrix<double, 5, 1> &state,
190 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 5, 5> *A,
191 ::Eigen::Matrix<double, 5, 2> *B) const;
192
193 // Returns the lqr controller for the current state, timestep, and Q and R
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700194 // gains. This controller is currently not used--we instead are experimenting
195 // with the path-relative LQR (and potentially MPC, in the future) controller,
196 // which uses the methods defined below.
Austin Schuhec7f06d2019-01-04 07:47:15 +1100197 // TODO(austin): This feels like it should live somewhere else, but I'm not
198 // sure where. So, throw it here...
199 ::Eigen::Matrix<double, 2, 5> KForState(
200 const ::Eigen::Matrix<double, 5, 1> &state, ::std::chrono::nanoseconds dt,
201 const ::Eigen::DiagonalMatrix<double, 5> &Q,
202 const ::Eigen::DiagonalMatrix<double, 2> &R) const;
203
Alex Perry4ae2fd72019-02-03 15:55:57 -0800204 // Return the next position, velocity, acceleration based on the current
205 // state. Updates the passed in state for the next iteration.
206 ::Eigen::Matrix<double, 3, 1> GetNextXVA(
207 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 2, 1> *state);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100208 ::std::vector<::Eigen::Matrix<double, 3, 1>> PlanXVA(
209 ::std::chrono::nanoseconds dt);
210
Austin Schuhe73a9052019-01-07 12:16:17 -0800211 enum SegmentType : uint8_t {
212 VELOCITY_LIMITED,
213 CURVATURE_LIMITED,
214 ACCELERATION_LIMITED,
James Kuszmaulea314d92019-02-18 19:45:06 -0800215 DECELERATION_LIMITED,
216 VOLTAGE_LIMITED,
Austin Schuhe73a9052019-01-07 12:16:17 -0800217 };
218
219 const ::std::vector<SegmentType> &plan_segment_type() const {
220 return plan_segment_type_;
221 }
222
James Kuszmaulea314d92019-02-18 19:45:06 -0800223 // Returns K1 and K2.
224 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
225 const ::Eigen::Matrix<double, 2, 1> K1(double current_ddtheta) const {
226 return (::Eigen::Matrix<double, 2, 1>()
227 << -robot_radius_l_ * current_ddtheta,
Austin Schuhd749d932020-12-30 21:38:40 -0800228 robot_radius_r_ * current_ddtheta)
229 .finished();
James Kuszmaulea314d92019-02-18 19:45:06 -0800230 }
231
232 const ::Eigen::Matrix<double, 2, 1> K2(double current_dtheta) const {
233 return (::Eigen::Matrix<double, 2, 1>()
234 << 1.0 - robot_radius_l_ * current_dtheta,
235 1.0 + robot_radius_r_ * current_dtheta)
236 .finished();
237 }
238
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700239 // The controller represented by these functions uses a discrete-time,
240 // finite-horizon LQR with states that are relative to the predicted path
241 // of the robot to produce a gain to be used on the error.
242 // The controller does not currently account for saturation, but is defined
243 // in a way that would make accounting for saturation feasible.
244 // This controller uses a state of:
245 // distance along path
246 // distance lateral to path (positive when robot is to the left of the path).
247 // heading relative to path (positive if robot pointed to left).
248 // v_left (speed of left side of robot)
249 // v_right (speed of right side of robot).
250
251 // Retrieve the continuous-time A/B matrices for the path-relative system
252 // at the given distance along the path. Performs all linearizations about
253 // the nominal velocity that the robot should be following at that point
254 // along the path.
255 void PathRelativeContinuousSystem(double distance,
256 Eigen::Matrix<double, 5, 5> *A,
257 Eigen::Matrix<double, 5, 2> *B);
258 // Retrieve the continuous-time A/B matrices for the path-relative system
259 // given the current path-relative state, as defined above.
260 void PathRelativeContinuousSystem(const Eigen::Matrix<double, 5, 1> &X,
261 Eigen::Matrix<double, 5, 5> *A,
262 Eigen::Matrix<double, 5, 2> *B);
263
264 // Takes the 5-element state that is [x, y, theta, v_left, v_right] and
265 // converts it to a path-relative state, using distance as a linearization
266 // point (i.e., distance should be roughly equal to the actual distance along
267 // the path).
268 Eigen::Matrix<double, 5, 1> StateToPathRelativeState(
269 double distance, const Eigen::Matrix<double, 5, 1> &state);
270
271 // Estimates the current distance along the path, given the current expected
272 // distance and the [x, y, theta, v_left, v_right] state.
273 double EstimateDistanceAlongPath(double nominal_distance,
274 const Eigen::Matrix<double, 5, 1> &state);
275
276 // Calculates all the gains for each point along the planned trajectory.
277 // Only called directly in tests; this is normally a part of the planning
278 // phase, and is a relatively expensive operation.
279 void CalculatePathGains();
280
281 // Retrieves the gain matrix K for a given distance along the path.
282 Eigen::Matrix<double, 2, 5> GainForDistance(double distance);
283
Austin Schuhec7f06d2019-01-04 07:47:15 +1100284 private:
285 // Computes alpha for a distance.
Austin Schuhe73a9052019-01-07 12:16:17 -0800286 size_t DistanceToSegment(double distance) const {
287 return ::std::max(
288 static_cast<size_t>(0),
289 ::std::min(plan_segment_type_.size() - 1,
290 static_cast<size_t>(::std::floor(distance / length() *
291 (plan_.size() - 1)))));
292 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100293
Austin Schuhec7f06d2019-01-04 07:47:15 +1100294 // Computes K3, K4, and K5 for the provided distance.
295 // K5 a + K3 v^2 + K4 v = U
296 void K345(const double x, ::Eigen::Matrix<double, 2, 1> *K3,
297 ::Eigen::Matrix<double, 2, 1> *K4,
298 ::Eigen::Matrix<double, 2, 1> *K5) {
299 const double current_ddtheta = spline_->DDTheta(x);
300 const double current_dtheta = spline_->DTheta(x);
301 // We've now got the equation:
302 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
303 const ::Eigen::Matrix<double, 2, 1> my_K2 = K2(current_dtheta);
304
305 const ::Eigen::Matrix<double, 2, 2> B_inverse =
306 velocity_drivetrain_->plant().coefficients().B_continuous.inverse();
307
308 // Now, rephrase it as K5 a + K3 v^2 + K4 v = U
309 *K3 = B_inverse * K1(current_ddtheta);
310 *K4 = -B_inverse *
311 velocity_drivetrain_->plant().coefficients().A_continuous * my_K2;
312 *K5 = B_inverse * my_K2;
313 }
314
315 // The spline we are planning for.
316 const DistanceSpline *spline_;
317 // The drivetrain we are controlling.
318 ::std::unique_ptr<
319 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
320 HybridKalman<2, 2, 2>>>
321 velocity_drivetrain_;
322
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700323 const DrivetrainConfig<double> config_;
324
James Kuszmaulea314d92019-02-18 19:45:06 -0800325 // Robot radiuses.
Austin Schuhec7f06d2019-01-04 07:47:15 +1100326 const double robot_radius_l_;
327 const double robot_radius_r_;
328 // Acceleration limits.
James Kuszmaulea314d92019-02-18 19:45:06 -0800329 double longitudinal_acceleration_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100330 double lateral_acceleration_;
331 // Transformation matrix from left, right to linear, angular
332 const ::Eigen::Matrix<double, 2, 2> Tlr_to_la_;
333 // Transformation matrix from linear, angular to left, right
334 const ::Eigen::Matrix<double, 2, 2> Tla_to_lr_;
James Kuszmaulaa2499d2020-06-02 21:31:19 -0700335 // Velocities in the plan (distance for each index is defined by Distance())
336 std::vector<double> plan_;
337 // Gain matrices to use for the path-relative state error at each stage in the
338 // plan Individual elements of the plan_gains_ vector are separated by
339 // config_.dt in time.
340 // The first value in the pair is the distance along the path corresponding to
341 // the gain matrix; the second value is the gain itself.
342 std::vector<std::pair<double, Eigen::Matrix<double, 2, 5>>> plan_gains_;
343 std::vector<SegmentType> plan_segment_type_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100344 // Plan voltage limit.
345 double voltage_limit_ = 12.0;
346};
347
348// Returns the continuous time dynamics given the [x, y, theta, vl, vr] state
349// and the [vl, vr] input voltage.
350inline ::Eigen::Matrix<double, 5, 1> ContinuousDynamics(
351 const StateFeedbackHybridPlant<2, 2, 2> &velocity_drivetrain,
352 const ::Eigen::Matrix<double, 2, 2> &Tlr_to_la,
353 const ::Eigen::Matrix<double, 5, 1> X,
354 const ::Eigen::Matrix<double, 2, 1> U) {
355 const auto &velocity = X.block<2, 1>(3, 0);
356 const double theta = X(2);
357 ::Eigen::Matrix<double, 2, 1> la = Tlr_to_la * velocity;
358 return (::Eigen::Matrix<double, 5, 1>() << ::std::cos(theta) * la(0),
359 ::std::sin(theta) * la(0), la(1),
360 (velocity_drivetrain.coefficients().A_continuous * velocity +
361 velocity_drivetrain.coefficients().B_continuous * U))
362 .finished();
363}
364
365} // namespace drivetrain
366} // namespace control_loops
367} // namespace frc971
368
369#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_