blob: 615f82cfbb8a1265c3913a0c3f74061bcca49ac6 [file] [log] [blame]
Austin Schuhacd335a2017-01-01 16:20:54 -08001#include "frc971/control_loops/runge_kutta.h"
2
3#include "gtest/gtest.h"
4
5namespace frc971 {
6namespace control_loops {
7namespace testing {
8
9// Tests that integrating dx/dt = e^x works.
10TEST(RungeKuttaTest, Exponential) {
11 ::Eigen::Matrix<double, 1, 1> y0;
12 y0(0, 0) = 0.0;
13
14 ::Eigen::Matrix<double, 1, 1> y1 = RungeKutta(
15 [](::Eigen::Matrix<double, 1, 1> x) {
16 ::Eigen::Matrix<double, 1, 1> y;
17 y(0, 0) = ::std::exp(x(0, 0));
18 return y;
19 },
20 y0, 0.1);
21 EXPECT_NEAR(y1(0, 0), ::std::exp(0.1) - ::std::exp(0), 1e-3);
22}
23
Austin Schuh268a94f2018-02-17 17:10:19 -080024// Tests that integrating dx/dt = e^x works when we provide a U.
25TEST(RungeKuttaTest, ExponentialWithU) {
26 ::Eigen::Matrix<double, 1, 1> y0;
27 y0(0, 0) = 0.0;
28
Austin Schuh9edb5df2018-12-23 09:03:15 +110029 ::Eigen::Matrix<double, 1, 1> y1 = RungeKuttaU(
Austin Schuh268a94f2018-02-17 17:10:19 -080030 [](::Eigen::Matrix<double, 1, 1> x, ::Eigen::Matrix<double, 1, 1> u) {
31 ::Eigen::Matrix<double, 1, 1> y;
32 y(0, 0) = ::std::exp(u(0, 0) * x(0, 0));
33 return y;
34 },
35 y0, (::Eigen::Matrix<double, 1, 1>() << 1.0).finished(), 0.1);
36 EXPECT_NEAR(y1(0, 0), ::std::exp(0.1) - ::std::exp(0), 1e-3);
37}
38
Austin Schuhca52a242018-12-23 09:19:29 +110039::Eigen::Matrix<double, 1, 1> RungeKuttaTimeVaryingSolution(double t) {
40 return (::Eigen::Matrix<double, 1, 1>()
41 << 12.0 * ::std::exp(t) / (::std::pow(::std::exp(t) + 1.0, 2.0)))
42 .finished();
43}
44
45// Tests RungeKutta with a time varying solution.
46// Now, lets test RK4 with a time varying solution. From
47// http://www2.hawaii.edu/~jmcfatri/math407/RungeKuttaTest.html:
48// x' = x (2 / (e^t + 1) - 1)
49//
50// The true (analytical) solution is:
51//
52// x(t) = 12 * e^t / ((e^t + 1)^2)
53TEST(RungeKuttaTest, RungeKuttaTimeVarying) {
54 ::Eigen::Matrix<double, 1, 1> y0 = RungeKuttaTimeVaryingSolution(5.0);
55
56 ::Eigen::Matrix<double, 1, 1> y1 = RungeKutta(
57 [](double t, ::Eigen::Matrix<double, 1, 1> x) {
58 return (::Eigen::Matrix<double, 1, 1>()
59 << x(0, 0) * (2.0 / (::std::exp(t) + 1.0) - 1.0))
60 .finished();
61 },
62 y0, 5.0, 1.0);
63 EXPECT_NEAR(y1(0, 0), RungeKuttaTimeVaryingSolution(6.0)(0, 0), 1e-3);
64}
65
Austin Schuhacd335a2017-01-01 16:20:54 -080066} // namespace testing
67} // namespace control_loops
68} // namespace frc971