blob: 6be898af2801ceac9a12367c6a11c3f675b5218c [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();
127 }
128
129 // Returns the feed forwards position, velocity, acceleration for an explicit
130 // distance.
131 ::Eigen::Matrix<double, 3, 1> FFAcceleration(double distance);
132
133 // Returns the feed forwards voltage for an explicit distance.
134 ::Eigen::Matrix<double, 2, 1> FFVoltage(double distance);
135
Alex Perry4ae2fd72019-02-03 15:55:57 -0800136 // Returns whether a state represents a state at the end of the spline.
137 bool is_at_end(::Eigen::Matrix<double, 2, 1> state) const {
138 return state(0) > length() - 1e-4;
139 }
140
James Kuszmaul4d3c2642020-03-05 07:32:39 -0800141 // Returns true if the state is invalid or unreasonable in some way.
142 bool state_is_faulted(::Eigen::Matrix<double, 2, 1> state) const {
143 // Consider things faulted if the current velocity implies we are going
144 // backwards or if any infinities/NaNs have crept in.
145 return state(1) < 0 || !state.allFinite();
146 }
147
Austin Schuhec7f06d2019-01-04 07:47:15 +1100148 // Returns the length of the path in meters.
149 double length() const { return spline_->length(); }
150
151 // Returns a list of the distances. Mostly useful for plotting.
152 const ::std::vector<double> Distances() const;
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>(plan_.size() - 1);
157 }
158
159 // Returns the plan. This is the pathwise velocity as a function of distance.
160 // To get the distance for an index, use the Distance(index) function provided
161 // with the index.
162 const ::std::vector<double> plan() const { return plan_; }
163
164 // Returns the left, right to linear, angular transformation matrix.
165 const ::Eigen::Matrix<double, 2, 2> &Tlr_to_la() const { return Tlr_to_la_; }
166 // Returns the linear, angular to left, right transformation matrix.
167 const ::Eigen::Matrix<double, 2, 2> &Tla_to_lr() const { return Tla_to_lr_; }
168
169 // Returns the goal state as a function of path distance, velocity.
170 const ::Eigen::Matrix<double, 5, 1> GoalState(double distance,
171 double velocity);
172
173 // Returns the velocity drivetrain in use.
174 const StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
175 HybridKalman<2, 2, 2>>
176 &velocity_drivetrain() const {
177 return *velocity_drivetrain_;
178 }
179
180 // Returns the continuous statespace A and B matricies for [x, y, theta, vl,
181 // vr] for the linearized system (around the provided state).
182 ::Eigen::Matrix<double, 5, 5> ALinearizedContinuous(
183 const ::Eigen::Matrix<double, 5, 1> &state) const;
184 ::Eigen::Matrix<double, 5, 2> BLinearizedContinuous() const;
185
186 // Returns the discrete time A and B matricies for the provided state,
187 // assuming the provided timestep.
188 void AB(const ::Eigen::Matrix<double, 5, 1> &state,
189 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 5, 5> *A,
190 ::Eigen::Matrix<double, 5, 2> *B) const;
191
192 // Returns the lqr controller for the current state, timestep, and Q and R
193 // gains.
194 // TODO(austin): This feels like it should live somewhere else, but I'm not
195 // sure where. So, throw it here...
196 ::Eigen::Matrix<double, 2, 5> KForState(
197 const ::Eigen::Matrix<double, 5, 1> &state, ::std::chrono::nanoseconds dt,
198 const ::Eigen::DiagonalMatrix<double, 5> &Q,
199 const ::Eigen::DiagonalMatrix<double, 2> &R) const;
200
Alex Perry4ae2fd72019-02-03 15:55:57 -0800201 // Return the next position, velocity, acceleration based on the current
202 // state. Updates the passed in state for the next iteration.
203 ::Eigen::Matrix<double, 3, 1> GetNextXVA(
204 ::std::chrono::nanoseconds dt, ::Eigen::Matrix<double, 2, 1> *state);
Austin Schuhec7f06d2019-01-04 07:47:15 +1100205 ::std::vector<::Eigen::Matrix<double, 3, 1>> PlanXVA(
206 ::std::chrono::nanoseconds dt);
207
Austin Schuhe73a9052019-01-07 12:16:17 -0800208 enum SegmentType : uint8_t {
209 VELOCITY_LIMITED,
210 CURVATURE_LIMITED,
211 ACCELERATION_LIMITED,
James Kuszmaulea314d92019-02-18 19:45:06 -0800212 DECELERATION_LIMITED,
213 VOLTAGE_LIMITED,
Austin Schuhe73a9052019-01-07 12:16:17 -0800214 };
215
216 const ::std::vector<SegmentType> &plan_segment_type() const {
217 return plan_segment_type_;
218 }
219
James Kuszmaulea314d92019-02-18 19:45:06 -0800220 // Returns K1 and K2.
221 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
222 const ::Eigen::Matrix<double, 2, 1> K1(double current_ddtheta) const {
223 return (::Eigen::Matrix<double, 2, 1>()
224 << -robot_radius_l_ * current_ddtheta,
225 robot_radius_r_ * current_ddtheta).finished();
226 }
227
228 const ::Eigen::Matrix<double, 2, 1> K2(double current_dtheta) const {
229 return (::Eigen::Matrix<double, 2, 1>()
230 << 1.0 - robot_radius_l_ * current_dtheta,
231 1.0 + robot_radius_r_ * current_dtheta)
232 .finished();
233 }
234
Austin Schuhec7f06d2019-01-04 07:47:15 +1100235 private:
236 // Computes alpha for a distance.
Austin Schuhe73a9052019-01-07 12:16:17 -0800237 size_t DistanceToSegment(double distance) const {
238 return ::std::max(
239 static_cast<size_t>(0),
240 ::std::min(plan_segment_type_.size() - 1,
241 static_cast<size_t>(::std::floor(distance / length() *
242 (plan_.size() - 1)))));
243 }
Austin Schuhec7f06d2019-01-04 07:47:15 +1100244
Austin Schuhec7f06d2019-01-04 07:47:15 +1100245 // Computes K3, K4, and K5 for the provided distance.
246 // K5 a + K3 v^2 + K4 v = U
247 void K345(const double x, ::Eigen::Matrix<double, 2, 1> *K3,
248 ::Eigen::Matrix<double, 2, 1> *K4,
249 ::Eigen::Matrix<double, 2, 1> *K5) {
250 const double current_ddtheta = spline_->DDTheta(x);
251 const double current_dtheta = spline_->DTheta(x);
252 // We've now got the equation:
253 // K2 * d^x/dt^2 + K1 (dx/dt)^2 = A * K2 * dx/dt + B * U
254 const ::Eigen::Matrix<double, 2, 1> my_K2 = K2(current_dtheta);
255
256 const ::Eigen::Matrix<double, 2, 2> B_inverse =
257 velocity_drivetrain_->plant().coefficients().B_continuous.inverse();
258
259 // Now, rephrase it as K5 a + K3 v^2 + K4 v = U
260 *K3 = B_inverse * K1(current_ddtheta);
261 *K4 = -B_inverse *
262 velocity_drivetrain_->plant().coefficients().A_continuous * my_K2;
263 *K5 = B_inverse * my_K2;
264 }
265
266 // The spline we are planning for.
267 const DistanceSpline *spline_;
268 // The drivetrain we are controlling.
269 ::std::unique_ptr<
270 StateFeedbackLoop<2, 2, 2, double, StateFeedbackHybridPlant<2, 2, 2>,
271 HybridKalman<2, 2, 2>>>
272 velocity_drivetrain_;
273
James Kuszmaulea314d92019-02-18 19:45:06 -0800274 // Robot radiuses.
Austin Schuhec7f06d2019-01-04 07:47:15 +1100275 const double robot_radius_l_;
276 const double robot_radius_r_;
277 // Acceleration limits.
James Kuszmaulea314d92019-02-18 19:45:06 -0800278 double longitudinal_acceleration_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100279 double lateral_acceleration_;
280 // Transformation matrix from left, right to linear, angular
281 const ::Eigen::Matrix<double, 2, 2> Tlr_to_la_;
282 // Transformation matrix from linear, angular to left, right
283 const ::Eigen::Matrix<double, 2, 2> Tla_to_lr_;
284 // Velocities in the plan (distance for each index is defined by distance())
285 ::std::vector<double> plan_;
Austin Schuhe73a9052019-01-07 12:16:17 -0800286 ::std::vector<SegmentType> plan_segment_type_;
Austin Schuhec7f06d2019-01-04 07:47:15 +1100287 // Plan voltage limit.
288 double voltage_limit_ = 12.0;
289};
290
291// Returns the continuous time dynamics given the [x, y, theta, vl, vr] state
292// and the [vl, vr] input voltage.
293inline ::Eigen::Matrix<double, 5, 1> ContinuousDynamics(
294 const StateFeedbackHybridPlant<2, 2, 2> &velocity_drivetrain,
295 const ::Eigen::Matrix<double, 2, 2> &Tlr_to_la,
296 const ::Eigen::Matrix<double, 5, 1> X,
297 const ::Eigen::Matrix<double, 2, 1> U) {
298 const auto &velocity = X.block<2, 1>(3, 0);
299 const double theta = X(2);
300 ::Eigen::Matrix<double, 2, 1> la = Tlr_to_la * velocity;
301 return (::Eigen::Matrix<double, 5, 1>() << ::std::cos(theta) * la(0),
302 ::std::sin(theta) * la(0), la(1),
303 (velocity_drivetrain.coefficients().A_continuous * velocity +
304 velocity_drivetrain.coefficients().B_continuous * U))
305 .finished();
306}
307
308} // namespace drivetrain
309} // namespace control_loops
310} // namespace frc971
311
312#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_TRAJECTORY_H_