diff --git a/cpp/benchmarks/graph_simulation.cpp b/cpp/benchmarks/graph_simulation.cpp index 29498d34f9..1af1346a69 100644 --- a/cpp/benchmarks/graph_simulation.cpp +++ b/cpp/benchmarks/graph_simulation.cpp @@ -20,7 +20,7 @@ #include "benchmark/benchmark.h" #include "benchmarks/graph_simulation.h" #include "memilio/compartments/simulation.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/mobility/metapopulation_mobility_instant.h" #include "memilio/io/directories.h" #include "ode_secirvvs/model.h" diff --git a/cpp/benchmarks/integrator_step.cpp b/cpp/benchmarks/integrator_step.cpp index 4f4734765f..e0f807c9c4 100644 --- a/cpp/benchmarks/integrator_step.cpp +++ b/cpp/benchmarks/integrator_step.cpp @@ -20,7 +20,7 @@ #include "benchmarks/integrator_step.h" #include "benchmarks/secir_ageres_setups.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/math/stepper_wrapper.h" #include "memilio/io/directories.h" diff --git a/cpp/benchmarks/simulation.cpp b/cpp/benchmarks/simulation.cpp index 3a98cfab97..eae0425247 100644 --- a/cpp/benchmarks/simulation.cpp +++ b/cpp/benchmarks/simulation.cpp @@ -20,7 +20,7 @@ #include "benchmarks/simulation.h" #include "benchmarks/secir_ageres_setups.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/math/stepper_wrapper.h" #include "memilio/io/directories.h" diff --git a/cpp/examples/adapt_rk_test.cpp b/cpp/examples/adapt_rk_test.cpp index 9a19fd3d10..2a3c8aac90 100644 --- a/cpp/examples/adapt_rk_test.cpp +++ b/cpp/examples/adapt_rk_test.cpp @@ -17,7 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include #include diff --git a/cpp/memilio/CMakeLists.txt b/cpp/memilio/CMakeLists.txt index 85be088d64..6b5ed05459 100644 --- a/cpp/memilio/CMakeLists.txt +++ b/cpp/memilio/CMakeLists.txt @@ -60,8 +60,8 @@ add_library(memilio math/euler.cpp math/euler.h math/smoother.h - math/adapt_rk.h - math/adapt_rk.cpp + math/runge_kutta.h + math/runge_kutta.cpp math/stepper_wrapper.h math/stepper_wrapper.cpp math/integrator.h diff --git a/cpp/memilio/math/README.md b/cpp/memilio/math/README.md index 628df56dfd..cca070ae7d 100644 --- a/cpp/memilio/math/README.md +++ b/cpp/memilio/math/README.md @@ -9,7 +9,7 @@ The model consists of the following classes: 2. The following integrators implement OdeIntegratorCore and can be used with OdeIntegrator or [mio::Simulation](../compartments/README.md). - ControlledStepperWrapper: The ControlledStepperWrapper class allows using integrators from boosts::numeric::odeint in memilio. The integrator is passed as template argument. It must be of the concept "Error Stepper" (for more details, see [boost's own documentation](https://www.boost.org/doc/libs/1_84_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/odeint_in_detail/steppers.html#boost_numeric_odeint.odeint_in_detail.steppers.stepper_overview) ). Currently, the default for mio::Simulation is runge_kutta_cash_karp54. Alternatively, runge_kutta_fehlberg78 can be used. - Euler: The Euler class contains and explicit Euler method, adapted to the Integrator function. It also contains a (semi-)implicit Euler method which is WIP and taylored for the particular SECIR model from ../ode_secir/model.h - - Adapt_RK: The Adapt_RK module contains the RKIntegratorCore class, which implements adaptive Runge-Kutta integrators, where different pairs of methods (in form of combined Butcher tableaus) can be added. Absolute and relative tolerances can be set and the Tableau in use is that of an adaptive Runge-Kutta-Fehlberg (45) method; see, e.g., https://www.johndcook.com/blog/2020/02/19/fehlberg/. Steps where the mixed criterion on absolute and relative values (m_abs_tol + max_val * m_rel_tol) are not satisfied are directly discarded and never used. If the minimal step size (set) is reached and the criterion cannot be satisfied, it is returned that the adaptive step sizing failed. + - Runge-Kutta: The Runge-Kutta module (runge_kutta.h) contains the RKIntegratorCore class, which implements adaptive Runge-Kutta integrators, where different pairs of methods (in form of combined Butcher tableaus) can be added. Absolute and relative tolerances can be set and the Tableau in use is that of an adaptive Runge-Kutta-Fehlberg (45) method; see, e.g., https://www.johndcook.com/blog/2020/02/19/fehlberg/. Steps where the mixed criterion on absolute and relative values (m_abs_tol + max_val * m_rel_tol) are not satisfied are directly discarded and never used. If the minimal step size is reached and the criterion cannot be satisfied, a step with that minimal size is made, and warning is logged that adaptive step sizing failed. Via Tableau, further explicit methods can be specified, including methods with fixed step sizes (explicit Euler method, midpoint method, third-order Runge-Kutta methods and the classical fourth-order Runge-Kutta method), which are used when the Tableau does not contain the weights of an embedded solution for error estimation. Optionally, the stage values of all accepted steps are recorded which enables the application of identical Runge-Kutta steps to subpopulations (see https://doi.org/10.1016/j.matcom.2026.08.029). 3. The following integrators implement SdeIntegratorCore and can be used with SdeIntegrator or [mio::StochasticSimulation](../compartments/README.md). - EulerMaruyamaIntegratorCore: This class implements a Euler-Mayurama scheme for solving SDEs. The solver enforces non-negative values in the solution, by first removing negative values and then rescaling the solution vector to preserve the total sum. This does not work on flows. 4. Smoother: The smoother classes smoothes discrete jumps of function values y0 and y1 on the interval [x0,x1] by a continuously differentiable function diff --git a/cpp/memilio/math/adapt_rk.h b/cpp/memilio/math/adapt_rk.h deleted file mode 100644 index 159545b433..0000000000 --- a/cpp/memilio/math/adapt_rk.h +++ /dev/null @@ -1,314 +0,0 @@ -/* -* Copyright (C) 2020-2026 MEmilio -* -* Authors: Martin J. Kuehn, Daniel Abele -* -* Contact: Martin J. Kuehn -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -#ifndef ADAPT_RK_H_ -#define ADAPT_RK_H_ - -#include "memilio/math/integrator.h" - -#include -#include - -namespace mio -{ - -/** - * Two scheme Runge-Kutta numerical integrator with adaptive step width - * for ODE y'(t) = f(t,y) which is given by - * y_{n+1} = y_n + h*\sum_{i=1}^lb_ik_{ni} - * with - * k_{ni} = f(t_n + c_i*h, y_n + h*\sum_{j=1}^{i-1}a_{ij}k_{nj}) - * where the general Butcher tableau is - * 0 | - * c_2 | a_{21} - * c_3 | a_{31} a_{32} - * ... | ............ - * c_s | a{s,1} a_{s,2} ... a_{s,s-1} - * ---------------------------------------------- - * | b_1 b_2 ... b_{s-1} b_s - * - * - * Actually, only the RK-Fehlberg 4 (5) method is implemented. - * - * The RKF4's Butcher tableau is - * 0 | - * 1/4 | 1/4 - * 3/8 | 3/32 9/32 - * 12/13 | 1932/2197 −7200/2197 7296/2197 - * 1 | 439/216 -8 3680/513 -845/4104 - * 1/2 | -8/27 2 -3544/2565 1859/4104 -11/40 - * ---------------------------------------------------------------------------- - * | 25/216 0 1408/2565 2197/4104 -1/5 0 - * The higher order (5th) approximation only differs by the last line which is - * | 16/135 0 6656/12825 28561/56430 -9/50 2/55 - * - */ -template -class Tableau -{ -public: - std::vector> entries; - - /** - * @brief default is Runge-Kutta-Fehlberg4(5) tableau - */ - Tableau() - { - entries.resize(5); - for (size_t i = 0; i < entries.size(); i++) { - entries[i].resize(i + 2); - } - - entries[0][0] = 0.25; - entries[0][1] = 0.25; - entries[1][0] = 3 / 8.0; - entries[1][1] = 3 / 32.0; - entries[1][2] = 9 / 32.0; - entries[2][0] = 12 / 13.0; - entries[2][1] = 1932 / 2197.0; - entries[2][2] = -7200 / 2197.0; - entries[2][3] = 7296 / 2197.0; - entries[3][0] = 1.0; - entries[3][1] = 439 / 216.0; - entries[3][2] = -8.0; - entries[3][3] = 3680 / 513.0; - entries[3][4] = -845 / 4104.0; - entries[4][0] = 0.5; - entries[4][1] = -8 / 27.0; - entries[4][2] = 2.0; - entries[4][3] = -3544 / 2565.0; - entries[4][4] = 1859 / 4104.0; - entries[4][5] = -11 / 40.0; - } -}; - -/* - * Final row(s) of the Butcher tableau - * - * Repitition from above: Runge-Kutta-4 is: - * | 25/216 0 1408/2565 2197/1404 -1/5 0 - * The higher order (5th) approximation only differs by the last line which is - * | 16/135 0 6656/12825 28561/56430 -9/50 2/55 - * - */ -template -class TableauFinal -{ -public: - Eigen::VectorX entries_low; - Eigen::VectorX entries_high; - - /** - * @brief default is Runge-Kutta-Fehlberg4(5) tableau - */ - TableauFinal() - { - entries_low.resize(6); - entries_high.resize(6); - - entries_low[0] = 25 / 216.0; - entries_low[1] = 0.0; - entries_low[2] = 1408 / 2565.0; - entries_low[3] = 2197 / 4104.0; - entries_low[4] = -0.2; - entries_low[5] = 0.0; - entries_high[0] = 16 / 135.0; - entries_high[1] = 0.0; - entries_high[2] = 6656 / 12825.0; - entries_high[3] = 28561 / 56430.0; - entries_high[4] = -9 / 50.0; - entries_high[5] = 2 / 55.0; - } -}; - -/** - * @brief Two scheme Runge-Kutta numerical integrator with adaptive step width - * - * This class integrates a system of ODEs via the step method - */ -template -class RKIntegratorCore : public OdeIntegratorCore -{ -public: - /** - * @brief Setting up the integrator - */ - RKIntegratorCore() - : OdeIntegratorCore(std::numeric_limits::min(), std::numeric_limits::max()) - , m_abs_tol(1e-10) - , m_rel_tol(1e-5) - { - } - - /** - * @brief Set up the integrator - * @param abs_tol absolute tolerance - * @param rel_tol relative tolerance - * @param dt_min lower bound for time step dt - * @param dt_max upper bound for time step dt - */ - RKIntegratorCore(const FP abs_tol, const FP rel_tol, const FP dt_min, const FP dt_max) - : OdeIntegratorCore(dt_min, dt_max) - , m_abs_tol(abs_tol) - , m_rel_tol(rel_tol) - { - } - - std::unique_ptr> clone() const override - { - return std::make_unique(*this); - } - - /// @param tol the required absolute tolerance for the comparison with the Fehlberg approximation - void set_abs_tolerance(FP tol) - { - m_abs_tol = tol; - } - - /// @param tol the required relative tolerance for the comparison with the Fehlberg approximation - void set_rel_tolerance(FP tol) - { - m_rel_tol = tol; - } - - /// @param dt_min sets the minimum step size - void set_dt_min(FP dt_min) - { - this->get_dt_min() = dt_min; - } - - /// @param dt_max sets the maximum step size - void set_dt_max(FP dt_max) - { - this->get_dt_max() = dt_max; - } - - // Allow setting different RK tableau schemes - void set_tableaus(const Tableau& tab, const TableauFinal& final_tab) - { - m_tab = tab; - m_tab_final = final_tab; - m_kt_values.resize(Eigen::NoChange, m_tab_final.entries_low.size()); - } - - /** - * @brief Make a single integration step of a system of ODEs and adapt the step size - * @param[in] yt value of y at t, y(t) - * @param[in,out] t current time - * @param[in,out] dt current time step size h=dt - * @param[out] ytp1 approximated value y(t+1) - */ - bool step(const DerivFunction& f, Eigen::Ref> yt, FP& t, FP& dt, - Eigen::Ref> ytp1) const override - { - using std::max; - using std::min; - using std::pow; - - assert(0 <= this->get_dt_min()); - assert(this->get_dt_min() <= this->get_dt_max()); - - if (dt < this->get_dt_min() || dt > this->get_dt_max()) { - mio::log_warning("IntegratorCore: Restricting given step size dt = {} to [{}, {}].", dt, this->get_dt_min(), - this->get_dt_max()); - } - dt = min(dt, this->get_dt_max()); - - FP t_eval; // shifted time for evaluating yt - FP dt_new; // updated dt - - bool converged = false; // carry for convergence criterion - bool dt_is_invalid = false; - - if (m_yt_eval.size() != yt.size()) { - m_yt_eval.resize(yt.size()); - m_kt_values.resize(yt.size(), m_tab_final.entries_low.size()); - } - - m_yt_eval = yt; - - while (!converged && !dt_is_invalid) { - if (dt < this->get_dt_min()) { - dt_is_invalid = true; - dt = this->get_dt_min(); - } - // compute first column of kt, i.e. kt_0 for each y in yt_eval - f(m_yt_eval, t, m_kt_values.col(0)); - - for (Eigen::Index i = 1; i < m_kt_values.cols(); i++) { - // we first compute k_n1 for each y_j, then k_n2 for each y_j, etc. - t_eval = t; - t_eval += m_tab.entries[i - 1][0] * - dt; // t_eval = t + c_i * h // note: line zero of Butcher tableau not stored in array - // use ytp1 as temporary storage for evaluating m_kt_values[i] - ytp1 = m_yt_eval; - for (Eigen::Index k = 1; k < m_tab.entries[i - 1].size(); k++) { - ytp1 += (dt * m_tab.entries[i - 1][k]) * m_kt_values.col(k - 1); - } - // get the derivatives, i.e., compute kt_i for all y in ytp1: kt_i = f(t_eval, ytp1_low) - f(ytp1, t_eval, m_kt_values.col(i)); - } - // calculate low order estimate - ytp1 = m_yt_eval; - ytp1 += (dt * (m_kt_values * m_tab_final.entries_low)); - // truncation error estimate: yt_low - yt_high = O(h^(p+1)) where p = order of convergence - m_error_estimate = dt * (m_kt_values * (m_tab_final.entries_high - m_tab_final.entries_low)).array().abs(); - // calculate mixed tolerance - m_eps = m_abs_tol + ytp1.array().abs() * m_rel_tol; - - converged = (m_error_estimate <= m_eps).all(); // convergence criterion - - if (converged || dt_is_invalid) { - // if sufficiently exact, return ytp1, which currently contains the lower order approximation - // (higher order is not always higher accuracy) - t += dt; // this is the t where ytp1 belongs to - } - // else: repeat the calculation above (with updated dt) - - // compute new value for dt - // converged implies eps/error_estimate >= 1, so dt will be increased for the next step - // hence !converged implies 0 < eps/error_estimate < 1, strictly decreasing dt - dt_new = dt * pow((m_eps / m_error_estimate).minCoeff(), (1. / (m_tab_final.entries_low.size() - 1))); - // safety factor for more conservative step increases, - // and to avoid dt_new -> dt for step decreases when |error_estimate - eps| -> 0 - dt_new *= 0.9; - // check if updated dt stays within desired bounds and update dt for next step - dt = min(dt_new, this->get_dt_max()); - } - dt = max(dt, this->get_dt_min()); - // return 'converged' in favor of '!dt_is_invalid', as these values only differ if step sizing failed, - // but the step with size dt_min was accepted. - return converged; - } - -protected: - Tableau m_tab; - TableauFinal m_tab_final; - FP m_abs_tol, m_rel_tol; - mutable Eigen::Matrix m_kt_values; - mutable Eigen::VectorX m_yt_eval; - -private: - mutable Eigen::Array m_eps, - m_error_estimate; // tolerance and estimate used for time step adaption -}; - -} // namespace mio - -#endif // ADAPT_RK_H_ diff --git a/cpp/memilio/math/adapt_rk.cpp b/cpp/memilio/math/runge_kutta.cpp similarity index 94% rename from cpp/memilio/math/adapt_rk.cpp rename to cpp/memilio/math/runge_kutta.cpp index 6b7a2f87ec..e6afce0868 100644 --- a/cpp/memilio/math/adapt_rk.cpp +++ b/cpp/memilio/math/runge_kutta.cpp @@ -17,4 +17,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" diff --git a/cpp/memilio/math/runge_kutta.h b/cpp/memilio/math/runge_kutta.h new file mode 100644 index 0000000000..838608f467 --- /dev/null +++ b/cpp/memilio/math/runge_kutta.h @@ -0,0 +1,591 @@ +/* +* Copyright (C) 2020-2026 MEmilio +* +* Authors: Martin J. Kuehn, Daniel Abele +* +* Contact: Martin J. Kuehn +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef MIO_MATH_RUNGE_KUTTA_H +#define MIO_MATH_RUNGE_KUTTA_H + +#include "memilio/math/integrator.h" + +#include +#include +#include +#include + +namespace mio +{ + +/** + * @brief Butcher tableau of an explicit Runge-Kutta method with S stages. + * + * A step of size h from (t_n, y_n) computes the stage values Y_i and stage derivatives k_i, + * Y_i = y_n + h * sum_{j < i} a_{ij} k_j, k_i = f(t_n + c_i * h, Y_i), i = 1, ..., S, + * and the next value + * y_{n+1} = y_n + h * sum_{i=1}^S b_i k_i. + * The coefficients are arranged in the Butcher tableau + * c_1 | a_{11} ... a_{1S} + * ... | ... ... + * c_S | a_{S1} ... a_{SS} + * ----+------------------- + * | b_1 ... b_S + * | b^_1 ... b^_S + * with a strictly lower triangular matrix a, nodes c, and weights b. The embedded weights b^ of an embedded solution + * are optional. If they are given, the difference between both solutions is used to estimate the local error for + * adaptive step sizing. Otherwise, RKIntegratorCore makes steps of fixed size. The returned solution always corresponds + * to the non-embedded weights. + * + * The default is the adaptive Runge-Kutta-Fehlberg 4(5) method, where the propagated solution is of fourth order + * and the embedded solution of fifth order: + * 0 | + * 1/4 | 1/4 + * 3/8 | 3/32 9/32 + * 12/13 | 1932/2197 -7200/2197 7296/2197 + * 1 | 439/216 -8 3680/513 -845/4104 + * 1/2 | -8/27 2 -3544/2565 1859/4104 -11/40 + * ------+----------------------------------------------------------------------- + * | 25/216 0 1408/2565 2197/4104 -1/5 0 + * | 16/135 0 6656/12825 28561/56430 -9/50 2/55 + * + * @tparam FP A floating point type, e.g., double. + */ +template +class Tableau +{ +public: + Eigen::MatrixX matrix; ///< Runge-Kutta matrix a (S x S, strictly lower triangular). + Eigen::VectorX nodes; ///< Nodes c, i.e., the relative times of the stages within a step. + Eigen::VectorX weights; ///< Weights b of the solution that is propagated. + Eigen::VectorX embedded_weights; ///< Weights b^ of the embedded solution, empty for fixed-step methods. + + /** + * @brief Create a Butcher tableau from its coefficients, @see Tableau. + * @param[in] matrix_ Runge-Kutta matrix a. + * @param[in] nodes_ Nodes c. + * @param[in] weights_ Weights b of the propagated solution. + * @param[in] embedded_weights_ Weights b^ of the embedded solution, or empty for fixed steps. + */ + Tableau(Eigen::MatrixX matrix_, Eigen::VectorX nodes_, Eigen::VectorX weights_, + Eigen::VectorX embedded_weights_ = Eigen::VectorX()) + : matrix(std::move(matrix_)) + , nodes(std::move(nodes_)) + , weights(std::move(weights_)) + , embedded_weights(std::move(embedded_weights_)) + { + assert(matrix.cols() > 0); + assert(matrix.cols() == matrix.rows()); + assert(nodes.size() == matrix.rows()); + assert(weights.size() == matrix.rows()); + assert(embedded_weights.size() == matrix.rows() || embedded_weights.size() == 0); + } + + /** + * @brief Default is the adaptive Runge-Kutta-Fehlberg 4(5) method. + */ + Tableau() + : matrix(Eigen::MatrixX::Zero(6, 6)) + , nodes(6) + , weights(6) + , embedded_weights(6) + { + nodes[0] = 0.0; + nodes[1] = 0.25; + nodes[2] = 3 / 8.0; + nodes[3] = 12 / 13.0; + nodes[4] = 1.0; + nodes[5] = 0.5; + + matrix(1, 0) = 0.25; + matrix(2, 0) = 3 / 32.0; + matrix(2, 1) = 9 / 32.0; + matrix(3, 0) = 1932 / 2197.0; + matrix(3, 1) = -7200 / 2197.0; + matrix(3, 2) = 7296 / 2197.0; + matrix(4, 0) = 439 / 216.0; + matrix(4, 1) = -8.0; + matrix(4, 2) = 3680 / 513.0; + matrix(4, 3) = -845 / 4104.0; + matrix(5, 0) = -8 / 27.0; + matrix(5, 1) = 2.0; + matrix(5, 2) = -3544 / 2565.0; + matrix(5, 3) = 1859 / 4104.0; + matrix(5, 4) = -11 / 40.0; + + weights[0] = 25 / 216.0; + weights[1] = 0.0; + weights[2] = 1408 / 2565.0; + weights[3] = 2197 / 4104.0; + weights[4] = -0.2; + weights[5] = 0.0; + + embedded_weights[0] = 16 / 135.0; + embedded_weights[1] = 0.0; + embedded_weights[2] = 6656 / 12825.0; + embedded_weights[3] = 28561 / 56430.0; + embedded_weights[4] = -9 / 50.0; + embedded_weights[5] = 2 / 55.0; + } + + /// @brief Number of stages S of the method. + Eigen::Index get_num_stages() const + { + return weights.size(); + } + + /// @brief Whether the method contains an embedded solution for adaptive step sizing. + bool is_adaptive() const + { + return embedded_weights.size() > 0; + } + + /// @brief Explicit Euler method (order 1) with fixed steps. + static Tableau explicit_euler() + { + return Tableau(Eigen::MatrixX{{0.0}}, Eigen::VectorX{{0.0}}, Eigen::VectorX{{1.0}}); + } + + /// @brief Explicit midpoint method (order 2) with fixed steps. + static Tableau midpoint() + { + return Tableau(Eigen::MatrixX{{0.0, 0.0}, {0.5, 0.0}}, Eigen::VectorX{{0.0, 0.5}}, + Eigen::VectorX{{0.0, 1.0}}); + } + + /// @brief Kutta's third order method with fixed steps. + static Tableau kutta3() + { + return Tableau(Eigen::MatrixX{{0.0, 0.0, 0.0}, {0.5, 0.0, 0.0}, {-1.0, 2.0, 0.0}}, + Eigen::VectorX{{0.0, 0.5, 1.0}}, Eigen::VectorX{{1 / 6.0, 4 / 6.0, 1 / 6.0}}); + } + + /// @brief Classical Runge-Kutta method of fourth order with fixed steps. + static Tableau classical_rk4() + { + return Tableau( + Eigen::MatrixX{{0.0, 0.0, 0.0, 0.0}, {0.5, 0.0, 0.0, 0.0}, {0.0, 0.5, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}}, + Eigen::VectorX{{0.0, 0.5, 0.5, 1.0}}, Eigen::VectorX{{1 / 6.0, 1 / 3.0, 1 / 3.0, 1 / 6.0}}); + } +}; + +/** + * @brief Stage values of the accepted steps of an explicit Runge-Kutta method. + * + * For each step from t_n to t_{n+1} = t_n + h_n, the start time t_n, the step size h_n and the stage values Y_i, + * i = 1, ..., S, are stored, see Tableau. Used, e.g., by the stage-aligned Runge-Kutta scheme, see + * https://doi.org/10.1016/j.matcom.2026.08.029. + * + * The memory allocated for the steps is reused after `clear()` is called. + * + * @tparam FP A floating point type, e.g., double. + */ +template +class RungeKuttaStageHistory +{ +public: + /** + * @brief Remove all steps and set the method that is used for the following steps. + * @param[in] tab Butcher tableau of the method. + */ + void set_tableau(const Tableau& tab) + { + m_tableau = tab; + m_num_steps = 0; + } + + /// @brief Remove all steps. + void clear() + { + m_num_steps = 0; + } + + /** + * @brief Prepare the storage for the stage values of the next step, see get_next_stage_value. + * The step is only added to the history by add_step, so the storage may be overwritten before, e.g., by a + * rejected step of an adaptive method. + * @param[in] num_values Number of values per stage. + */ + void prepare_next_step(Eigen::Index num_values) + { + if (m_num_steps == m_stage_values.size()) { + m_times.emplace_back(); + m_step_sizes.emplace_back(); + m_stage_values.emplace_back(); + } + m_stage_values[m_num_steps].resize(num_values, m_tableau.get_num_stages()); + } + + /** + * @brief Storage for the value of a stage of the next step, see prepare_next_step. + * @param[in] stage Index of the stage. + */ + Eigen::Ref> get_next_stage_value(Eigen::Index stage) + { + assert(m_num_steps < m_stage_values.size()); + return m_stage_values[m_num_steps].col(stage); + } + + /** + * @brief Add the step whose stage values were written into get_next_stage_value. + * @param[in] t Start time of the step. + * @param[in] h Step size. + */ + void add_step(FP t, FP h) + { + assert(m_num_steps < m_stage_values.size()); + m_times[m_num_steps] = t; + m_step_sizes[m_num_steps] = h; + ++m_num_steps; + } + + /// @brief Number of recorded steps. + size_t get_num_steps() const + { + return m_num_steps; + } + + /// @brief Whether no step is recorded. + bool empty() const + { + return m_num_steps == 0; + } + + /// @brief Start time of a step. + FP get_time(size_t step) const + { + assert(step < m_num_steps); + return m_times[step]; + } + + /// @brief Step size of a step. + FP get_step_size(size_t step) const + { + assert(step < m_num_steps); + return m_step_sizes[step]; + } + + /// @brief Time t_n + c_i * h_n at which the stage i of a step is evaluated. + FP get_stage_time(size_t step, Eigen::Index stage) const + { + return get_time(step) + m_tableau.nodes[stage] * get_step_size(step); + } + + /// @brief Stage values of a step, one column per stage. + const Eigen::MatrixX& get_stage_values(size_t step) const + { + assert(step < m_num_steps); + return m_stage_values[step]; + } + + /// @brief The Butcher tableau of the method that computed the steps. + const Tableau& get_tableau() const + { + return m_tableau; + } + +private: + Tableau m_tableau; + std::vector m_times; + std::vector m_step_sizes; + std::vector> m_stage_values; + size_t m_num_steps = 0; +}; + +/** + * @brief Explicit Runge-Kutta integrator with adaptive or fixed step size. + * + * This class integrates a system of ODEs via the step method. By default, the adaptive Runge-Kutta-Fehlberg 4(5) + * method is used. Other explicit methods can be set with set_tableau, see Tableau. Methods without an embedded + * solution make steps of fixed size. + * + * Optionally, the stage values of all accepted steps are recorded, e.g., to apply the + * identical Runge-Kutta steps to subpopulations, see RungeKuttaStageHistory. + */ +template +class RKIntegratorCore : public OdeIntegratorCore +{ +public: + /** + * @brief Setting up the integrator + */ + RKIntegratorCore() + : OdeIntegratorCore(std::numeric_limits::min(), std::numeric_limits::max()) + , m_abs_tol(1e-10) + , m_rel_tol(1e-5) + { + } + + /** + * @brief Set up the integrator + * @param abs_tol absolute tolerance + * @param rel_tol relative tolerance + * @param dt_min lower bound for time step dt + * @param dt_max upper bound for time step dt + */ + RKIntegratorCore(const FP abs_tol, const FP rel_tol, const FP dt_min, const FP dt_max) + : OdeIntegratorCore(dt_min, dt_max) + , m_abs_tol(abs_tol) + , m_rel_tol(rel_tol) + { + } + + /** + * @brief Set up the integrator with the given method (see set_tableau). + * Uses the default tolerances and step size bounds, which only affect adaptive methods. + * @param tab Butcher tableau of the method. + */ + RKIntegratorCore(const Tableau& tab) + : RKIntegratorCore() + { + set_tableau(tab); + } + + std::unique_ptr> clone() const override + { + return std::make_unique(*this); + } + + /// @param tol the required absolute tolerance for the comparison with the Fehlberg approximation + void set_abs_tolerance(FP tol) + { + m_abs_tol = tol; + } + + /// @param tol the required relative tolerance for the comparison with the Fehlberg approximation + void set_rel_tolerance(FP tol) + { + m_rel_tol = tol; + } + + /// @param dt_min sets the minimum step size + void set_dt_min(FP dt_min) + { + this->get_dt_min() = dt_min; + } + + /// @param dt_max sets the maximum step size + void set_dt_max(FP dt_max) + { + this->get_dt_max() = dt_max; + } + + /** + * @brief Set the method used for integration. Clears the stage history. + * @param tab Butcher tableau of the method. + */ + void set_tableau(const Tableau& tab) + { + assert(tab.matrix.rows() == tab.get_num_stages() && tab.matrix.cols() == tab.get_num_stages()); + assert(tab.nodes.size() == tab.get_num_stages()); + assert(!tab.is_adaptive() || tab.embedded_weights.size() == tab.get_num_stages()); + m_tab = tab; + m_kt_values.resize(Eigen::NoChange, m_tab.get_num_stages()); + m_stage_history.set_tableau(m_tab); + } + + /// @brief The Butcher tableau of the method used for integration. + const Tableau& get_tableau() const + { + return m_tab; + } + + /** + * @brief Enable or disable recording the stage values of all accepted steps in the stage history. + * By default, recording is disabled. + * This always clears the stage history. + * The history grows with every step until it is cleared. + * @param record Whether stage values are recorded. + */ + void set_stage_recording(bool record) + { + m_record_stages = record; + reset_stage_history(); + } + + /// @brief Whether stage values of accepted steps are recorded. + bool is_recording_stages() const + { + return m_record_stages; + } + + /// @brief Remove all steps from the stage history. + void reset_stage_history() + { + m_stage_history.clear(); + } + + /** + * @brief Access the stage values of the recorded steps. + * @{ + */ + const RungeKuttaStageHistory& get_stage_history() const + { + return m_stage_history; + } + RungeKuttaStageHistory& get_stage_history() + { + return m_stage_history; + } + /** @} */ + + /** + * @brief Make a single integration step of a system of ODEs and adapt the step size. + * If the method is not adaptive (see Tableau::is_adaptive), a step of size dt is made and dt is not changed. + * @param[in] yt value of y at t, y(t) + * @param[in,out] t current time + * @param[in,out] dt current time step size h=dt + * @param[out] ytp1 approximated value y(t+dt) + * @return true if adaptive step sizing was successful, false otherwise. + */ + bool step(const DerivFunction& f, Eigen::Ref> yt, FP& t, FP& dt, + Eigen::Ref> ytp1) const override + { + using std::max; + using std::min; + using std::pow; + + assert(0 <= this->get_dt_min()); + assert(this->get_dt_min() <= this->get_dt_max()); + + if (m_yt_eval.size() != yt.size()) { + m_yt_eval.resize(yt.size()); + m_kt_values.resize(yt.size(), m_tab.get_num_stages()); + } + + m_yt_eval = yt; + + // step calculation for fixed-step methods, which do not use the step size bounds + if (!m_tab.is_adaptive()) { + compute_kt_values(f, t, dt, ytp1); + ytp1 = m_yt_eval; + ytp1 += (dt * (m_kt_values * m_tab.weights)); + record_step(t, dt); + t += dt; + return true; + } + + if (dt < this->get_dt_min() || dt > this->get_dt_max()) { + mio::log_warning("IntegratorCore: Restricting given step size dt = {} to [{}, {}].", dt, this->get_dt_min(), + this->get_dt_max()); + } + dt = min(dt, this->get_dt_max()); + + FP dt_new; // updated dt + + bool converged = false; // carry for convergence criterion + bool dt_is_invalid = false; + + while (!converged && !dt_is_invalid) { + if (dt < this->get_dt_min()) { + dt_is_invalid = true; + dt = this->get_dt_min(); + } + compute_kt_values(f, t, dt, ytp1); + // calculate low order estimate + ytp1 = m_yt_eval; + ytp1 += (dt * (m_kt_values * m_tab.weights)); + // truncation error estimate: yt_low - yt_high = O(h^(p+1)) where p = order of convergence + m_error_estimate = dt * (m_kt_values * (m_tab.embedded_weights - m_tab.weights)).array().abs(); + // calculate mixed tolerance + m_eps = m_abs_tol + ytp1.array().abs() * m_rel_tol; + + converged = (m_error_estimate <= m_eps).all(); // convergence criterion + + if (converged || dt_is_invalid) { + // if sufficiently exact, return ytp1, which currently contains the lower order approximation + // (higher order is not always higher accuracy) + record_step(t, dt); + t += dt; // this is the t where ytp1 belongs to + } + // else: repeat the calculation above (with updated dt) + + // compute new value for dt + // converged implies eps/error_estimate >= 1, so dt will be increased for the next step + // hence !converged implies 0 < eps/error_estimate < 1, strictly decreasing dt + // TODO: use the order of the error estimate instead of the number of stages, see Issue #1617 + dt_new = dt * pow((m_eps / m_error_estimate).minCoeff(), (1. / (m_tab.get_num_stages() - 1))); + // safety factor for more conservative step increases, + // and to avoid dt_new -> dt for step decreases when |error_estimate - eps| -> 0 + dt_new *= 0.9; + // check if updated dt stays within desired bounds and update dt for next step + dt = min(dt_new, this->get_dt_max()); + } + dt = max(dt, this->get_dt_min()); + // return 'converged' in favor of '!dt_is_invalid', as these values only differ if step sizing failed, + // but the step with size dt_min was accepted. + return converged; + } + +protected: + Tableau m_tab; + FP m_abs_tol, m_rel_tol; + mutable Eigen::Matrix m_kt_values; + mutable Eigen::VectorX m_yt_eval; + +private: + /** + * @brief Compute the stage derivatives k_i of a step of size dt from m_yt_eval at t and store them in m_kt_values. + * If stages are recorded, the stage values are written directly into the stage history. + * @param[in] f Right-hand side of the ODE. + * @param[in] t Start time of the step. + * @param[in] dt Step size. + * @param[out] ytp1 Used as temporary storage for the stage values, if they are not recorded. + */ + void compute_kt_values(const DerivFunction& f, FP t, FP dt, Eigen::Ref> ytp1) const + { + if (m_record_stages) { + m_stage_history.prepare_next_step(m_yt_eval.size()); + } + FP t_eval; // shifted time for evaluating yt + // compute first column of kt, i.e. kt_0 for each y in yt_eval + f(m_yt_eval, t, m_kt_values.col(0)); + if (m_record_stages) { + m_stage_history.get_next_stage_value(0) = m_yt_eval; + } + + for (Eigen::Index i = 1; i < m_kt_values.cols(); i++) { + // we first compute k_n1 for each y_j, then k_n2 for each y_j, etc. + t_eval = t; + t_eval += m_tab.nodes[i] * dt; // t_eval = t + c_i * h + // compute the stage value directly in the stage history, if stages are recorded + Eigen::Ref> y_stage = m_record_stages ? m_stage_history.get_next_stage_value(i) : ytp1; + // stage value Y_i = y_n + h * sum_{j < i} a_ij k_j + y_stage = m_yt_eval; + for (Eigen::Index j = 0; j < i; j++) { + y_stage += (dt * m_tab.matrix(i, j)) * m_kt_values.col(j); + } + // get the derivatives, i.e., compute kt_i for all y in y_stage: kt_i = f(t_eval, y_stage) + f(y_stage, t_eval, m_kt_values.col(i)); + } + } + + /// @brief Add the last computed step to the stage history, if recording is enabled. + void record_step(FP t, FP dt) const + { + if (m_record_stages) { + m_stage_history.add_step(t, dt); + } + } + + mutable Eigen::Array m_eps, + m_error_estimate; // tolerance and estimate used for time step adaption + bool m_record_stages = false; ///< Whether stage values of accepted steps are recorded. + mutable RungeKuttaStageHistory m_stage_history; ///< Stage values of the recorded steps. +}; + +} // namespace mio + +#endif // MIO_MATH_RUNGE_KUTTA_H diff --git a/cpp/models/ode_secirts/parameters.h b/cpp/models/ode_secirts/parameters.h index df26815127..8e9221c620 100644 --- a/cpp/models/ode_secirts/parameters.h +++ b/cpp/models/ode_secirts/parameters.h @@ -22,7 +22,7 @@ #include "memilio/math/eigen.h" #include "memilio/utils/uncertain_value.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/epidemiology/age_group.h" #include "memilio/epidemiology/simulation_day.h" #include "memilio/epidemiology/uncertain_matrix.h" diff --git a/cpp/tests/test_numericalIntegration.cpp b/cpp/tests/test_numericalIntegration.cpp index 0eb245692b..6a3a8101e8 100755 --- a/cpp/tests/test_numericalIntegration.cpp +++ b/cpp/tests/test_numericalIntegration.cpp @@ -20,7 +20,7 @@ #include "abm_helpers.h" #include "actions.h" #include "memilio/math/euler.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/math/euler_maruyama.h" #include "memilio/math/integrator.h" #include "memilio/math/stepper_wrapper.h" @@ -246,6 +246,75 @@ TYPED_TEST(TestVerifyNumericalIntegrator, adaptiveStepSizing) EXPECT_EQ(this->sol[0][0], t_eval); // check that the integration step matches the time step } +TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) +{ + // case: integrate known function with two fixed step sizes; expect decreasing error, scaling with method order + // y' = -y + cos(t), y(0) = 0, has the solution y(t) = (sin(t) + cos(t) - exp(-t)) / 2 + auto f = [](auto&& y, auto&& t, auto&& dydt) { + dydt[0] = -y[0] + std::cos(t); + }; + const double tmax = 2.0; + const double sol = (std::sin(tmax) + std::cos(tmax) - std::exp(-tmax)) / 2; + + auto check_order = [&](const mio::Tableau& tab, int order) { + EXPECT_FALSE(tab.is_adaptive()); + std::vector errors; + for (int num_steps : {20, 40}) { + mio::OdeIntegrator integrator(std::make_unique>(tab)); + mio::TimeSeries result(0.0, Eigen::VectorXd::Zero(1)); + double dt = tmax / num_steps; + integrator.advance(f, tmax, dt, result); + EXPECT_EQ(result.get_num_time_points(), num_steps + 1); // fixed steps + errors.push_back(std::abs(result.get_last_value()[0] - sol)); + } + EXPECT_NEAR(std::log2(errors[0] / errors[1]), order, 0.25); + }; + check_order(mio::Tableau::explicit_euler(), 1); + check_order(mio::Tableau::midpoint(), 2); + check_order(mio::Tableau::kutta3(), 3); + check_order(mio::Tableau::classical_rk4(), 4); +} + +TEST(TestRKIntegratorCore, recordsStagesOfAcceptedSteps) +{ + // case: integrate with and without stage history; expect no changes on integration result, and stages reproduce solution + auto f = [](auto&& y, auto&& t, auto&& dydt) { + dydt[0] = std::cos(10 * t) - y[0]; + }; + // adaptive RKF45, so that step sizes vary and some steps are rejected + auto core = std::make_unique>(1e-12, 1e-10, 1e-8, 1.0); + auto core_no_recording = std::make_unique>(1e-12, 1e-10, 1e-8, 1.0); + EXPECT_FALSE(core_no_recording->is_recording_stages()); + core->set_stage_recording(true); + // the cores are moved into the integrators, so their histories stay accessible + const auto& history = core->get_stage_history(); + const auto& history_no_recording = core_no_recording->get_stage_history(); + mio::OdeIntegrator integrator(std::move(core)); + mio::OdeIntegrator integrator_no_recording(std::move(core_no_recording)); + + mio::TimeSeries result(0.0, Eigen::VectorXd::Zero(1)), result_no_recording = result; + double dt = 0.5, dt_no_recording = 0.5; + integrator.advance(f, 3.0, dt, result); + integrator_no_recording.advance(f, 3.0, dt_no_recording, result_no_recording); + + // recording does not change the result + EXPECT_EQ(result.get_num_time_points(), result_no_recording.get_num_time_points()); + EXPECT_EQ(result.get_last_value()[0], result_no_recording.get_last_value()[0]); + EXPECT_TRUE(history_no_recording.empty()); + + // each step is recorded once, and its stages reproduce the next result + ASSERT_EQ(history.get_num_steps() + 1, size_t(result.get_num_time_points())); + for (size_t i = 0; i < history.get_num_steps(); ++i) { + EXPECT_EQ(history.get_time(i), result.get_time(i)); + Eigen::VectorXd y_next = result.get_value(i), k(1); + for (Eigen::Index s = 0; s < history.get_tableau().get_num_stages(); ++s) { + f(history.get_stage_values(i).col(s), history.get_stage_time(i, s), k); + y_next += history.get_step_size(i) * history.get_tableau().weights[s] * k; + } + EXPECT_NEAR(y_next[0], result.get_value(i + 1)[0], 1e-14); + } +} + auto DoStep() { return testing::DoAll(testing::WithArgs<2, 3>(AddAssign()), testing::WithArgs<4, 1>(AssignUnsafe()), diff --git a/cpp/tests/test_odesecir.cpp b/cpp/tests/test_odesecir.cpp index e1524e5b70..0786eb6c08 100755 --- a/cpp/tests/test_odesecir.cpp +++ b/cpp/tests/test_odesecir.cpp @@ -28,7 +28,7 @@ #include "ode_secir/parameters_io.h" #include "memilio/io/parameters_io.h" #include "memilio/data/analyze_result.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/geography/regions.h" #include "utils.h" diff --git a/cpp/tests/test_odesecir_ageres.cpp b/cpp/tests/test_odesecir_ageres.cpp index 1e1fbf0728..4ed815e31b 100755 --- a/cpp/tests/test_odesecir_ageres.cpp +++ b/cpp/tests/test_odesecir_ageres.cpp @@ -20,7 +20,7 @@ #include "load_test_data.h" #include "ode_secir/model.h" #include "memilio/compartments/simulation.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/math/stepper_wrapper.h" #include diff --git a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h index ce291675db..97f5ec1743 100644 --- a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h +++ b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h @@ -22,7 +22,7 @@ #include "memilio/math/integrator.h" #include "memilio/math/euler.h" -#include "memilio/math/adapt_rk.h" +#include "memilio/math/runge_kutta.h" #include "memilio/math/stepper_wrapper.h" #include #include "pybind_util.h" @@ -74,12 +74,22 @@ void bind_Integrator_Core(pybind11::module_& m) .def("set_abs_tolerance", &RungeKuttaCashKarp54Integrator::set_abs_tolerance, pybind11::arg("tol")) .def("set_rel_tolerance", &RungeKuttaCashKarp54Integrator::set_rel_tolerance, pybind11::arg("tol")); + pymio::bind_class, pymio::EnablePickling::Never>(m, "Tableau") + .def(pybind11::init<>()) + .def("is_adaptive", &mio::Tableau::is_adaptive) + .def_static("explicit_euler", &mio::Tableau::explicit_euler) + .def_static("midpoint", &mio::Tableau::midpoint) + .def_static("kutta3", &mio::Tableau::kutta3) + .def_static("classical_rk4", &mio::Tableau::classical_rk4); + pymio::bind_class, pymio::EnablePickling::Never, mio::OdeIntegratorCore, pybind11::smart_holder>(m, "RKIntegratorCore") .def(pybind11::init<>()) .def(pybind11::init(), pybind11::arg("abs_tol") = 1e-10, pybind11::arg("rel_tol") = 1e-5, pybind11::arg("dt_min") = std::numeric_limits::min(), pybind11::arg("dt_max") = std::numeric_limits::max()) + .def(pybind11::init&>(), pybind11::arg("tab")) + .def("set_tableau", &mio::RKIntegratorCore::set_tableau, pybind11::arg("tab")) .def("set_abs_tolerance", &mio::RKIntegratorCore::set_abs_tolerance, pybind11::arg("tol")) .def("set_rel_tolerance", &mio::RKIntegratorCore::set_rel_tolerance, pybind11::arg("tol")); } diff --git a/pycode/memilio-simulation/tests/test_integrators.py b/pycode/memilio-simulation/tests/test_integrators.py index 35faec3c00..bf2cd63faa 100644 --- a/pycode/memilio-simulation/tests/test_integrators.py +++ b/pycode/memilio-simulation/tests/test_integrators.py @@ -82,6 +82,29 @@ def test_model_integration(self): self.assertFalse((result1.get_last_value() == result2.get_last_value()).all()) + def test_fixed_step_runge_kutta(self): + """ """ + + self.assertTrue(mio.Tableau().is_adaptive()) + self.assertFalse(mio.Tableau.classical_rk4().is_adaptive()) + + model = Model(1) + A0 = mio.AgeGroup(0) + model.parameters.TimeInfected[A0] = 6. + model.parameters.TransmissionProbabilityOnContact[A0] = 1. + model.populations[A0, InfectionState.Infected] = 50 + model.populations.set_difference_from_total( + (A0, InfectionState.Susceptible), 8000) + + integrator = mio.RKIntegratorCore(mio.Tableau.classical_rk4()) + result = simulate(0, 5, 0.5, model, integrator) + reference = simulate(0, 5, 0.5, model, mio.RKIntegratorCore()) + + # fixed steps of size 0.5, close to the adaptive solution + self.assertTrue(np.allclose(np.diff(result.as_ndarray()[0, :]), 0.5)) + self.assertTrue(np.allclose(result.get_last_value(), + reference.get_last_value(), rtol=1e-4)) + if __name__ == '__main__': unittest.main()