Austin Schuh | acd335a | 2017-01-01 16:20:54 -0800 | [diff] [blame] | 1 | #include "frc971/control_loops/runge_kutta.h" |
| 2 | |
| 3 | #include "gtest/gtest.h" |
| 4 | |
| 5 | namespace frc971 { |
| 6 | namespace control_loops { |
| 7 | namespace testing { |
| 8 | |
| 9 | // Tests that integrating dx/dt = e^x works. |
| 10 | TEST(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 Schuh | 268a94f | 2018-02-17 17:10:19 -0800 | [diff] [blame] | 24 | // Tests that integrating dx/dt = e^x works when we provide a U. |
| 25 | TEST(RungeKuttaTest, ExponentialWithU) { |
| 26 | ::Eigen::Matrix<double, 1, 1> y0; |
| 27 | y0(0, 0) = 0.0; |
| 28 | |
Austin Schuh | 9edb5df | 2018-12-23 09:03:15 +1100 | [diff] [blame] | 29 | ::Eigen::Matrix<double, 1, 1> y1 = RungeKuttaU( |
Austin Schuh | 268a94f | 2018-02-17 17:10:19 -0800 | [diff] [blame] | 30 | [](::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 Schuh | ca52a24 | 2018-12-23 09:19:29 +1100 | [diff] [blame^] | 39 | ::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) |
| 53 | TEST(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 Schuh | acd335a | 2017-01-01 16:20:54 -0800 | [diff] [blame] | 66 | } // namespace testing |
| 67 | } // namespace control_loops |
| 68 | } // namespace frc971 |