blob: 173014eea636bdb0c8007ff354aa187fc9ce805b [file] [log] [blame]
Austin Schuhacd335a2017-01-01 16:20:54 -08001#ifndef FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_
2#define FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_
3
Austin Schuhb0bfaf82024-06-19 19:47:23 -07004#include "glog/logging.h"
Austin Schuhacd335a2017-01-01 16:20:54 -08005#include <Eigen/Dense>
6
Austin Schuhb0bfaf82024-06-19 19:47:23 -07007#include "frc971/control_loops/runge_kutta_helpers.h"
8
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -08009namespace frc971::control_loops {
Austin Schuhacd335a2017-01-01 16:20:54 -080010
11// Implements Runge Kutta integration (4th order). fn is the function to
12// integrate. It must take 1 argument of type T. The integration starts at an
13// initial value X, and integrates for dt.
14template <typename F, typename T>
15T RungeKutta(const F &fn, T X, double dt) {
16 const double half_dt = dt * 0.5;
Austin Schuh92ebcbb2018-01-23 11:17:08 -080017 T k1 = fn(X);
18 T k2 = fn(X + half_dt * k1);
19 T k3 = fn(X + half_dt * k2);
20 T k4 = fn(X + dt * k3);
Austin Schuhacd335a2017-01-01 16:20:54 -080021 return X + dt / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4);
22}
23
milind-ue53bf552021-12-11 14:42:00 -080024// Implements Runge Kutta integration (4th order) split up into steps steps. fn
25// is the function to integrate. It must take 1 argument of type T. The
26// integration starts at an initial value X, and integrates for dt.
27template <typename F, typename T>
28T RungeKuttaSteps(const F &fn, T X, double dt, int steps) {
29 dt = dt / steps;
30 for (int i = 0; i < steps; ++i) {
31 X = RungeKutta(fn, X, dt);
32 }
33 return X;
34}
35
Austin Schuhf7466732023-02-20 22:11:41 -080036// Implements Runge Kutta integration (4th order). This integrates dy/dt =
37// fn(t, y). It must have the call signature of fn(double t, T y). The
Austin Schuhca52a242018-12-23 09:19:29 +110038// integration starts at an initial value y, and integrates for dt.
39template <typename F, typename T>
40T RungeKutta(const F &fn, T y, double t, double dt) {
41 const double half_dt = dt * 0.5;
42 T k1 = dt * fn(t, y);
43 T k2 = dt * fn(t + half_dt, y + k1 / 2.0);
44 T k3 = dt * fn(t + half_dt, y + k2 / 2.0);
45 T k4 = dt * fn(t + dt, y + k3);
46
47 return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;
48}
49
Austin Schuhf7466732023-02-20 22:11:41 -080050template <typename F, typename T>
51T RungeKuttaSteps(const F &fn, T X, double t, double dt, int steps) {
52 dt = dt / steps;
53 for (int i = 0; i < steps; ++i) {
54 X = RungeKutta(fn, X, t + dt * i, dt);
55 }
56 return X;
57}
58
Austin Schuh268a94f2018-02-17 17:10:19 -080059// Implements Runge Kutta integration (4th order). fn is the function to
60// integrate. It must take 1 argument of type T. The integration starts at an
61// initial value X, and integrates for dt.
62template <typename F, typename T, typename Tu>
Austin Schuh9edb5df2018-12-23 09:03:15 +110063T RungeKuttaU(const F &fn, T X, Tu U, double dt) {
Austin Schuh268a94f2018-02-17 17:10:19 -080064 const double half_dt = dt * 0.5;
65 T k1 = fn(X, U);
66 T k2 = fn(X + half_dt * k1, U);
67 T k3 = fn(X + half_dt * k2, U);
68 T k4 = fn(X + dt * k3, U);
69 return X + dt / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4);
70}
71
Austin Schuhb0bfaf82024-06-19 19:47:23 -070072// Integrates f(t, y) from t0 to t0 + dt using an explicit Runge Kutta 5(4) to
73// implement an adaptive step size. Translated from Scipy.
74//
75// This uses the Dormand-Prince pair of formulas. The error is controlled
76// assuming accuracy of the fourth-order method accuracy, but steps are taken
77// using the fifth-order accurate formula (local extrapolation is done). A
78// quartic interpolation polynomial is used for the dense output.
79//
80// fn(t, y) is the function to integrate. y0 is the initial y, t0 is the
81// initial time, dt is the duration to integrate, rtol is the relative
82// tolerance, and atol is the absolute tolerance.
83template <typename F, typename T>
84T AdaptiveRungeKutta(const F &fn, T y0, double t0, double dt,
85 double rtol = 1e-3, double atol = 1e-6) {
86 // Multiply steps computed from asymptotic behaviour of errors by this.
87 constexpr double SAFETY = 0.9;
88 // Minimum allowed decrease in a step size.
89 constexpr double MIN_FACTOR = 0.2;
90 // Maximum allowed increase in a step size.
91 constexpr double MAX_FACTOR = 10;
92
93 // Final time
94 const double t_bound = t0 + dt;
95
96 constexpr int order = 5;
97 constexpr int error_estimator_order = 4;
98 constexpr int n_stages = 6;
99 constexpr int states = y0.rows();
100 const double sqrt_rows = std::sqrt(static_cast<double>(states));
101 const Eigen::Matrix<double, 1, n_stages> C =
102 (Eigen::Matrix<double, 1, n_stages>() << 0, 1.0 / 5.0, 3.0 / 10.0,
103 4.0 / 5.0, 8.0 / 9.0, 1.0)
104 .finished();
105
106 const Eigen::Matrix<double, n_stages, order> A =
107 (Eigen::Matrix<double, n_stages, order>() << 0.0, 0.0, 0.0, 0.0, 0.0,
108 1.0 / 5.0, 0.0, 0.0, 0.0, 0.0, 3.0 / 40.0, 9.0 / 40.0, 0.0, 0.0, 0.0,
109 44.0 / 45.0, -56.0 / 15.0, 32.0 / 9.0, 0.0, 0.0, 19372.0 / 6561.0,
110 -25360.0 / 2187.0, 64448.0 / 6561.0, -212.0 / 729.0, 0.0,
111 9017.0 / 3168.0, -355.0 / 33.0, 46732.0 / 5247.0, 49.0 / 176.0,
112 -5103.0 / 18656.0)
113 .finished();
114
115 const Eigen::Matrix<double, 1, n_stages> B =
116 (Eigen::Matrix<double, 1, n_stages>() << 35.0 / 384.0, 0.0,
117 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0)
118 .finished();
119
120 const Eigen::Matrix<double, 1, n_stages + 1> E =
121 (Eigen::Matrix<double, 1, n_stages + 1>() << -71.0 / 57600.0, 0.0,
122 71.0 / 16695.0, -71.0 / 1920.0, 17253.0 / 339200.0, -22.0 / 525.0,
123 1.0 / 40.0)
124 .finished();
125
126 T f = fn(t0, y0);
127 double h_abs = SelectRungeKuttaInitialStep(fn, t0, y0, f,
128 error_estimator_order, rtol, atol);
129 Eigen::Matrix<double, n_stages + 1, states> K;
130
131 Eigen::Matrix<double, states, 1> y = y0;
132 const double error_exponent = -1.0 / (error_estimator_order + 1.0);
133
134 double t = t0;
135 while (true) {
136 if (t >= t_bound) {
137 return y;
138 }
139
140 // Step
141 double min_step =
142 10 * (std::nextafter(t, std::numeric_limits<double>::infinity()) - t);
143
144 // TODO(austin): max_step if we care.
145 if (h_abs < min_step) {
146 h_abs = min_step;
147 }
148
149 bool step_accepted = false;
150 bool step_rejected = false;
151
152 double t_new;
153 Eigen::Matrix<double, states, 1> y_new;
154 Eigen::Matrix<double, states, 1> f_new;
155 while (!step_accepted) {
156 // TODO(austin): Tell the user rather than just explode?
157 CHECK_GE(h_abs, min_step);
158
159 double h = h_abs;
160 t_new = t + h;
161 if (t_new >= t_bound) {
162 t_new = t_bound;
163 }
164 h = t_new - t;
165 h_abs = std::abs(h);
166
167 std::tie(y_new, f_new) =
168 RKStep<states, n_stages, order>(fn, t, y, f, h, A, B, C, K);
169
170 const Eigen::Matrix<double, states, 1> scale =
171 atol + y.array().abs().max(y_new.array().abs()) * rtol;
172
173 double error_norm =
174 (((K.transpose() * E.transpose()) * h).array() / scale.array())
175 .matrix()
176 .norm() /
177 sqrt_rows;
178
179 if (error_norm < 1) {
180 double factor;
181 if (error_norm == 0) {
182 factor = MAX_FACTOR;
183 } else {
184 factor = std::min(MAX_FACTOR,
185 SAFETY * std::pow(error_norm, error_exponent));
186 }
187
188 if (step_rejected) {
189 factor = std::min(1.0, factor);
190 }
191
192 h_abs *= factor;
193
194 step_accepted = true;
195 } else {
196 h_abs *=
197 std::max(MIN_FACTOR, SAFETY * std::pow(error_norm, error_exponent));
198 step_rejected = true;
199 }
200 }
201
202 t = t_new;
203 y = y_new;
204 f = f_new;
205 }
206
207 return y;
208}
209
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -0800210} // namespace frc971::control_loops
Austin Schuhacd335a2017-01-01 16:20:54 -0800211
212#endif // FRC971_CONTROL_LOOPS_RUNGE_KUTTA_H_