blob: f9a4ecfe108dc5aab3f7dfc03698f845604feeb1 [file] [log] [blame]
Austin Schuhb0bfaf82024-06-19 19:47:23 -07001#ifndef FRC971_CONTROL_LOOPS_RUNGE_KUTTA_HELPERS_H_
2#define FRC971_CONTROL_LOOPS_RUNGE_KUTTA_HELPERS_H_
3
4#include "glog/logging.h"
5#include <Eigen/Dense>
6
7namespace frc971::control_loops {
8
9// Returns a reasonable Runge Kutta initial step size. This is translated from
10// scipy.
11template <typename F, typename T>
12double SelectRungeKuttaInitialStep(const F &fn, size_t t0, T y0, T f0,
13 int error_estimator_order, double rtol,
14 double atol) {
15 constexpr int states = y0.rows();
16 const Eigen::Matrix<double, states, 1> scale =
17 atol + (y0.cwiseAbs().matrix() * rtol).array();
18 const double sqrt_rows = std::sqrt(static_cast<double>(states));
19 const double d0 = (y0.array() / scale.array()).matrix().norm() / sqrt_rows;
20 const double d1 = (f0.array() / scale.array()).matrix().norm() / sqrt_rows;
21 double h0;
22 if (d0 < 1e-5 || d1 < 1e-5) {
23 h0 = 1e-6;
24 } else {
25 h0 = 0.01 * d0 / d1;
26 }
27
28 const Eigen::Matrix<double, states, 1> y1 = y0 + h0 * f0;
29 const Eigen::Matrix<double, states, 1> f1 = fn(t0 + h0, y1);
30 const double d2 =
31 ((f1 - f0).array() / scale.array()).matrix().norm() / sqrt_rows / h0;
32
33 double h1;
34 if (d1 <= 1e-15 && d2 <= 1e-15) {
35 h1 = std::max(1e-6, h0 * 1e-3);
36 } else {
37 h1 = std::pow((0.01 / std::max(d1, d2)),
38 (1.0 / (error_estimator_order + 1.0)));
39 }
40
41 return std::min(100 * h0, h1);
42}
43
44// Performs a single step of Runge Kutta integration for the adaptive algorithm
45// below. This is translated from scipy.
46template <size_t N, size_t NStages, size_t Order, typename F>
47std::tuple<Eigen::Matrix<double, N, 1>, Eigen::Matrix<double, N, 1>> RKStep(
48 const F &fn, const double t, const Eigen::Matrix<double, N, 1> &y0,
49 const Eigen::Matrix<double, N, 1> &f0, const double h,
50 const Eigen::Matrix<double, NStages, Order> &A,
51 const Eigen::Matrix<double, 1, NStages> &B,
52 const Eigen::Matrix<double, 1, NStages> &C,
53 Eigen::Matrix<double, NStages + 1, N> &K) {
54 K.template block<N, 1>(0, 0) = f0;
55 for (size_t s = 1; s < NStages; ++s) {
56 Eigen::Matrix<double, N, 1> dy =
57 K.block(0, 0, s, N).transpose() * A.block(s, 0, 1, s).transpose() * h;
58 K.template block<1, N>(s, 0) = fn(t + C(0, s) * h, y0 + dy).transpose();
59 }
60
61 Eigen::Matrix<double, N, 1> y_new =
62 y0 + h * (K.template block<NStages, N>(0, 0).transpose() * B.transpose());
63 Eigen::Matrix<double, N, 1> f_new = fn(t + h, y_new);
64
65 K.template block<1, N>(NStages, 0) = f_new.transpose();
66
67 return std::make_tuple(y_new, f_new);
68}
69
70} // namespace frc971::control_loops
71
72#endif // FRC971_CONTROL_LOOPS_RUNGE_KUTTA_HELPERS_H_