From 38db702cf60be8febe15a60ce5ab800c33915cc7 Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:48:29 +0100 Subject: [PATCH 01/12] adjust adapt_rk integrator --- cpp/memilio/math/adapt_rk.h | 377 +++++++++++++++++++++++++++++++++--- 1 file changed, 349 insertions(+), 28 deletions(-) diff --git a/cpp/memilio/math/adapt_rk.h b/cpp/memilio/math/adapt_rk.h index 159545b433..95967d47d4 100644 --- a/cpp/memilio/math/adapt_rk.h +++ b/cpp/memilio/math/adapt_rk.h @@ -22,7 +22,9 @@ #include "memilio/math/integrator.h" +#include #include +#include #include namespace mio @@ -44,7 +46,9 @@ namespace mio * | b_1 b_2 ... b_{s-1} b_s * * - * Actually, only the RK-Fehlberg 4 (5) method is implemented. + * By default, the adaptive Runge-Kutta-Fehlberg 4(5) method is used. Other tableaus can be specified using + * RKIntegratorCore::set_tableaus, e.g. the fixed-step methods Tableau::classical_rk4 and TableauFinal::classical_rk4. + * Tableau::entries[i] contains c_{i+2}, followed by the row a_{i+2,1}, ..., a_{i+2,i+1}. * * The RKF4's Butcher tableau is * 0 | @@ -96,6 +100,39 @@ class Tableau entries[4][4] = 1859 / 4104.0; entries[4][5] = -11 / 40.0; } + + /// @brief Explicit Euler method (order 1), use with TableauFinal::explicit_euler. + static Tableau explicit_euler() + { + Tableau tab; + tab.entries.clear(); + return tab; + } + + /// @brief Explicit midpoint method (order 2), use with TableauFinal::midpoint. + static Tableau midpoint() + { + Tableau tab; + tab.entries = {Eigen::VectorX{{0.5, 0.5}}}; + return tab; + } + + /// @brief Kutta's third order method, use with TableauFinal::kutta3. + static Tableau kutta3() + { + Tableau tab; + tab.entries = {Eigen::VectorX{{0.5, 0.5}}, Eigen::VectorX{{1.0, -1.0, 2.0}}}; + return tab; + } + + /// @brief Classical Runge-Kutta method of fourth order, use with TableauFinal::classical_rk4. + static Tableau classical_rk4() + { + Tableau tab; + tab.entries = {Eigen::VectorX{{0.5, 0.5}}, Eigen::VectorX{{0.5, 0.0, 0.5}}, + Eigen::VectorX{{1.0, 0.0, 0.0, 1.0}}}; + return tab; + } }; /* @@ -135,12 +172,196 @@ class TableauFinal entries_high[4] = -9 / 50.0; entries_high[5] = 2 / 55.0; } + + /** + * @brief Specifies whether the tableau contains the entries_high weights of an embedded solution used to estimate + * the local error for adaptive step size determination. If entries_high is empty, RKIntegratorCore performs + * fixed-size steps using the entries_low weights. + */ + bool is_adaptive() const + { + return entries_high.size() > 0; + } + + /// @brief Explicit Euler method (order 1) with fixed steps, use with Tableau::explicit_euler. + static TableauFinal explicit_euler() + { + return fixed_step({1.0}); + } + + /// @brief Explicit midpoint method (order 2) with fixed steps, use with Tableau::midpoint. + static TableauFinal midpoint() + { + return fixed_step({0.0, 1.0}); + } + + /// @brief Kutta's third order method with fixed steps, use with Tableau::kutta3. + static TableauFinal kutta3() + { + return fixed_step({1 / 6.0, 4 / 6.0, 1 / 6.0}); + } + + /// @brief Classical Runge-Kutta method of fourth order with fixed steps, use with Tableau::classical_rk4. + static TableauFinal classical_rk4() + { + return fixed_step({1 / 6.0, 1 / 3.0, 1 / 3.0, 1 / 6.0}); + } + +private: + static TableauFinal fixed_step(std::initializer_list weights) + { + TableauFinal tab; + tab.entries_low = Eigen::VectorX{weights}; + tab.entries_high.resize(0); + return tab; + } +}; + +/** + * @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_s, + * s = 1, ..., S, are stored, where Y_s = y_n + h_n * sum_{r < s} a_{sr} k_r and k_s = f(Y_s, t_n + c_s h_n). + * 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, see Tableau. + * @param[in] final_tab Weights of the method. The propagated solution entries_low is used. + */ + void set_tableaus(const Tableau& tab, const TableauFinal& final_tab) + { + const Eigen::Index num_stages = final_tab.entries_low.size(); + assert(static_cast(tab.entries.size()) == num_stages - 1); + m_a = Eigen::MatrixX::Zero(num_stages, num_stages); + m_c = Eigen::VectorX::Zero(num_stages); + for (Eigen::Index s = 1; s < num_stages; ++s) { + const auto& row = tab.entries[static_cast(s - 1)]; + m_c[s] = row[0]; + for (Eigen::Index r = 1; r < row.size(); ++r) { + m_a(s, r - 1) = row[r]; + } + } + m_b = final_tab.entries_low; + m_num_steps = 0; + } + + /// @brief Remove all steps. + void clear() + { + m_num_steps = 0; + } + + /** + * @brief Add a step. + * @param[in] t Start time of the step. + * @param[in] h Step size. + * @param[in] stage_values Stage values with one column per stage. + */ + void add_step(FP t, FP h, Eigen::Ref> stage_values) + { + assert(stage_values.cols() == get_num_stages()); + if (m_num_steps == m_stage_values.size()) { + m_times.push_back(t); + m_step_sizes.push_back(h); + m_stage_values.emplace_back(stage_values); + } + else { + m_times[m_num_steps] = t; + m_step_sizes[m_num_steps] = h; + m_stage_values[m_num_steps] = stage_values; + } + ++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_s * h_n at which the stage s of a step is evaluated. + FP get_stage_time(size_t step, Eigen::Index stage) const + { + return get_time(step) + m_c[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 Number of stages S of the method. + Eigen::Index get_num_stages() const + { + return m_b.size(); + } + + /// @brief Runge-Kutta matrix a of the method (S x S). + const Eigen::MatrixX& get_a() const + { + return m_a; + } + + /// @brief Weights b of the propagated solution. + const Eigen::VectorX& get_b() const + { + return m_b; + } + + /// @brief Nodes c of the method. + const Eigen::VectorX& get_c() const + { + return m_c; + } + +private: + Eigen::MatrixX m_a; + Eigen::VectorX m_b, m_c; + std::vector m_times; + std::vector m_step_sizes; + std::vector> m_stage_values; + size_t m_num_steps = 0; }; /** * @brief Two scheme Runge-Kutta numerical integrator with adaptive step width * - * This class integrates a system of ODEs via the step method + * 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 used with set_tableaus (see Tableau and TableauFinal). + * + * 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 @@ -170,6 +391,18 @@ class RKIntegratorCore : public OdeIntegratorCore { } + /** + * @brief Set up the integrator with the given method (see set_tableaus). + * Uses the default tolerances and step size bounds, which only affect adaptive methods. + * @param tab Butcher tableau of the method. + * @param final_tab Weights of the method. + */ + RKIntegratorCore(const Tableau& tab, const TableauFinal& final_tab) + : RKIntegratorCore() + { + set_tableaus(tab, final_tab); + } + std::unique_ptr> clone() const override { return std::make_unique(*this); @@ -199,16 +432,62 @@ class RKIntegratorCore : public OdeIntegratorCore this->get_dt_max() = dt_max; } - // Allow setting different RK tableau schemes + /** + * @brief Set the method used for integration. + * @param tab Butcher tableau of the method. + * @param final_tab Weights of the method. + */ void set_tableaus(const Tableau& tab, const TableauFinal& final_tab) { + assert(static_cast(tab.entries.size()) == final_tab.entries_low.size() - 1); + assert(!final_tab.is_adaptive() || final_tab.entries_high.size() == final_tab.entries_low.size()); m_tab = tab; m_tab_final = final_tab; m_kt_values.resize(Eigen::NoChange, m_tab_final.entries_low.size()); + reset_stage_history(); } /** - * @brief Make a single integration step of a system of ODEs and adapt the step size + * @brief Enable or disable recording the stage values of all accepted steps in the stage history. + * By default, recording is disabled. Enabling it 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.set_tableaus(m_tab, m_tab_final); + } + + /** + * @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 TableauFinal::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 @@ -221,6 +500,25 @@ class RKIntegratorCore : public OdeIntegratorCore using std::min; using std::pow; + 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()); + } + if (m_record_stages && (m_stage_values.rows() != yt.size() || m_stage_values.cols() != m_kt_values.cols())) { + m_stage_values.resize(yt.size(), m_kt_values.cols()); + } + + m_yt_eval = yt; + + if (!m_tab_final.is_adaptive()) { + compute_stages(f, t, dt, ytp1); + ytp1 = m_yt_eval; + ytp1 += (dt * (m_kt_values * m_tab_final.entries_low)); + record_step(t, dt); + t += dt; + return true; + } + assert(0 <= this->get_dt_min()); assert(this->get_dt_min() <= this->get_dt_max()); @@ -230,40 +528,17 @@ class RKIntegratorCore : public OdeIntegratorCore } 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)); - } + compute_stages(f, t, dt, ytp1); // calculate low order estimate ytp1 = m_yt_eval; ytp1 += (dt * (m_kt_values * m_tab_final.entries_low)); @@ -277,6 +552,7 @@ class RKIntegratorCore : public OdeIntegratorCore 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) @@ -305,8 +581,53 @@ class RKIntegratorCore : public OdeIntegratorCore 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. + * @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. + */ + void compute_stages(const DerivFunction& f, FP t, FP dt, Eigen::Ref> ytp1) const + { + 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_values.col(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.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); + } + if (m_record_stages) { + m_stage_values.col(i) = ytp1; + } + // 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)); + } + } + + /// @brief Add the stages of 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, m_stage_values); + } + } + 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. + mutable Eigen::MatrixX m_stage_values; ///< Stage values of the current step, one column per stage. }; } // namespace mio From 20a62d5e4b74ef4af18379f25ac5aebde710232b Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:09:12 +0100 Subject: [PATCH 02/12] update readme integrator --- cpp/memilio/math/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/memilio/math/README.md b/cpp/memilio/math/README.md index 628df56dfd..f74f37e034 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. + - 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. Via Tableau and TableauFinal, 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 TableauFinal does not contain a second 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 From 36cff980e54b1beecb28c73572a939b52c31d27f Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:22:54 +0100 Subject: [PATCH 03/12] test convergence order and stage recording --- cpp/tests/test_numericalIntegration.cpp | 67 +++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/cpp/tests/test_numericalIntegration.cpp b/cpp/tests/test_numericalIntegration.cpp index 0eb245692b..80140641fe 100755 --- a/cpp/tests/test_numericalIntegration.cpp +++ b/cpp/tests/test_numericalIntegration.cpp @@ -246,6 +246,73 @@ TYPED_TEST(TestVerifyNumericalIntegrator, adaptiveStepSizing) EXPECT_EQ(this->sol[0][0], t_eval); // check that the integration step matches the time step } +TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) +{ + // 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, const mio::TableauFinal& final_tab, int order) { + EXPECT_FALSE(final_tab.is_adaptive()); + std::vector errors; + for (int num_steps : {20, 40}) { + mio::OdeIntegrator integrator(std::make_unique>(tab, final_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(), mio::TableauFinal::explicit_euler(), 1); + check_order(mio::Tableau::midpoint(), mio::TableauFinal::midpoint(), 2); + check_order(mio::Tableau::kutta3(), mio::TableauFinal::kutta3(), 3); + check_order(mio::Tableau::classical_rk4(), mio::TableauFinal::classical_rk4(), 4); +} + +TEST(TestRKIntegratorCore, recordsStagesOfAcceptedSteps) +{ + 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_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_b()[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()), From 482dbcde519196708b8dc453ef0c39770237045d Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:31:08 +0100 Subject: [PATCH 04/12] rename adapt_rk --- cpp/benchmarks/graph_simulation.cpp | 2 +- cpp/benchmarks/integrator_step.cpp | 2 +- cpp/benchmarks/simulation.cpp | 2 +- cpp/examples/adapt_rk_test.cpp | 2 +- cpp/memilio/CMakeLists.txt | 4 ++-- cpp/memilio/math/README.md | 2 +- cpp/memilio/math/{adapt_rk.cpp => runge_kutta.cpp} | 2 +- cpp/memilio/math/{adapt_rk.h => runge_kutta.h} | 6 +++--- cpp/models/ode_secirts/parameters.h | 2 +- cpp/tests/test_numericalIntegration.cpp | 2 +- cpp/tests/test_odesecir.cpp | 2 +- cpp/tests/test_odesecir_ageres.cpp | 2 +- .../memilio/simulation/bindings/math/integrator.h | 2 +- 13 files changed, 16 insertions(+), 16 deletions(-) rename cpp/memilio/math/{adapt_rk.cpp => runge_kutta.cpp} (94%) rename cpp/memilio/math/{adapt_rk.h => runge_kutta.h} (99%) 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 f74f37e034..10cbb6e2e8 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. Via Tableau and TableauFinal, 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 TableauFinal does not contain a second 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). + - 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 (set) is reached and the criterion cannot be satisfied, it is returned that the adaptive step sizing failed. Via Tableau and TableauFinal, 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 TableauFinal does not contain a second 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.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/adapt_rk.h b/cpp/memilio/math/runge_kutta.h similarity index 99% rename from cpp/memilio/math/adapt_rk.h rename to cpp/memilio/math/runge_kutta.h index 95967d47d4..03d32b625d 100644 --- a/cpp/memilio/math/adapt_rk.h +++ b/cpp/memilio/math/runge_kutta.h @@ -17,8 +17,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef ADAPT_RK_H_ -#define ADAPT_RK_H_ +#ifndef MIO_MATH_RUNGE_KUTTA_H +#define MIO_MATH_RUNGE_KUTTA_H #include "memilio/math/integrator.h" @@ -632,4 +632,4 @@ class RKIntegratorCore : public OdeIntegratorCore } // namespace mio -#endif // ADAPT_RK_H_ +#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 80140641fe..82f4e8b00b 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" 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..a9297624ad 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" From 46095808d5dc675788840107d95ecc29d798c93e Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:41:47 +0100 Subject: [PATCH 05/12] python bindings --- .../simulation/bindings/math/integrator.h | 19 +++++++++++++++ .../tests/test_integrators.py | 24 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h index a9297624ad..ae27659c2e 100644 --- a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h +++ b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h @@ -74,12 +74,31 @@ 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_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>(m, "TableauFinal") + .def(pybind11::init<>()) + .def("is_adaptive", &mio::TableauFinal::is_adaptive) + .def_static("explicit_euler", &mio::TableauFinal::explicit_euler) + .def_static("midpoint", &mio::TableauFinal::midpoint) + .def_static("kutta3", &mio::TableauFinal::kutta3) + .def_static("classical_rk4", &mio::TableauFinal::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&, const mio::TableauFinal&>(), pybind11::arg("tab"), + pybind11::arg("final_tab")) + .def("set_tableaus", &mio::RKIntegratorCore::set_tableaus, pybind11::arg("tab"), + pybind11::arg("final_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..0129fd4c53 100644 --- a/pycode/memilio-simulation/tests/test_integrators.py +++ b/pycode/memilio-simulation/tests/test_integrators.py @@ -82,6 +82,30 @@ 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.TableauFinal().is_adaptive()) + self.assertFalse(mio.TableauFinal.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(), mio.TableauFinal.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() From 935173b5711d97a5c8d5f54c5f221fe30b1f5af9 Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:43:26 +0100 Subject: [PATCH 06/12] refactor tableau (review suggestions) --- cpp/memilio/math/runge_kutta.h | 447 ++++++++++++++------------------- 1 file changed, 192 insertions(+), 255 deletions(-) diff --git a/cpp/memilio/math/runge_kutta.h b/cpp/memilio/math/runge_kutta.h index 03d32b625d..39145da0f5 100644 --- a/cpp/memilio/math/runge_kutta.h +++ b/cpp/memilio/math/runge_kutta.h @@ -24,205 +24,163 @@ #include #include -#include +#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 + * @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. The 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. * - * By default, the adaptive Runge-Kutta-Fehlberg 4(5) method is used. Other tableaus can be specified using - * RKIntegratorCore::set_tableaus, e.g. the fixed-step methods Tableau::classical_rk4 and TableauFinal::classical_rk4. - * Tableau::entries[i] contains c_{i+2}, followed by the row a_{i+2,1}, ..., a_{i+2,i+1}. - * - * 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 + * 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: - std::vector> entries; + 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 default is Runge-Kutta-Fehlberg4(5) tableau + * @brief Create a 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() - { - 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; - } - - /// @brief Explicit Euler method (order 1), use with TableauFinal::explicit_euler. - static Tableau explicit_euler() - { - Tableau tab; - tab.entries.clear(); - return tab; - } - - /// @brief Explicit midpoint method (order 2), use with TableauFinal::midpoint. - static Tableau midpoint() - { - Tableau tab; - tab.entries = {Eigen::VectorX{{0.5, 0.5}}}; - return tab; - } - - /// @brief Kutta's third order method, use with TableauFinal::kutta3. - static Tableau kutta3() + 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_)) { - Tableau tab; - tab.entries = {Eigen::VectorX{{0.5, 0.5}}, Eigen::VectorX{{1.0, -1.0, 2.0}}}; - return tab; } - /// @brief Classical Runge-Kutta method of fourth order, use with TableauFinal::classical_rk4. - static Tableau classical_rk4() - { - Tableau tab; - tab.entries = {Eigen::VectorX{{0.5, 0.5}}, Eigen::VectorX{{0.5, 0.0, 0.5}}, - Eigen::VectorX{{1.0, 0.0, 0.0, 1.0}}}; - return tab; - } -}; - -/* - * 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 + * @brief Default is the adaptive Runge-Kutta-Fehlberg 4(5) method. */ - 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; + 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 Specifies whether the tableau contains the entries_high weights of an embedded solution used to estimate - * the local error for adaptive step size determination. If entries_high is empty, RKIntegratorCore performs - * fixed-size steps using the entries_low weights. - */ - bool is_adaptive() const + /// @brief Number of stages S of the method. + Eigen::Index get_num_stages() const { - return entries_high.size() > 0; + return weights.size(); } - /// @brief Explicit Euler method (order 1) with fixed steps, use with Tableau::explicit_euler. - static TableauFinal explicit_euler() + /// @brief Whether the method contains an embedded solution for adaptive step sizing. + bool is_adaptive() const { - return fixed_step({1.0}); + return embedded_weights.size() > 0; } - /// @brief Explicit midpoint method (order 2) with fixed steps, use with Tableau::midpoint. - static TableauFinal midpoint() + /// @brief Explicit Euler method (order 1) with fixed steps. + static Tableau explicit_euler() { - return fixed_step({0.0, 1.0}); + return Tableau(Eigen::MatrixX{{0.0}}, Eigen::VectorX{{0.0}}, Eigen::VectorX{{1.0}}); } - /// @brief Kutta's third order method with fixed steps, use with Tableau::kutta3. - static TableauFinal kutta3() + /// @brief Explicit midpoint method (order 2) with fixed steps. + static Tableau midpoint() { - return fixed_step({1 / 6.0, 4 / 6.0, 1 / 6.0}); + 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 Classical Runge-Kutta method of fourth order with fixed steps, use with Tableau::classical_rk4. - static TableauFinal classical_rk4() + /// @brief Kutta's third order method with fixed steps. + static Tableau kutta3() { - return fixed_step({1 / 6.0, 1 / 3.0, 1 / 3.0, 1 / 6.0}); + 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}}); } -private: - static TableauFinal fixed_step(std::initializer_list weights) + /// @brief Classical Runge-Kutta method of fourth order with fixed steps. + static Tableau classical_rk4() { - TableauFinal tab; - tab.entries_low = Eigen::VectorX{weights}; - tab.entries_high.resize(0); - return tab; + 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_s, - * s = 1, ..., S, are stored, where Y_s = y_n + h_n * sum_{r < s} a_{sr} k_r and k_s = f(Y_s, t_n + c_s h_n). - * Used, e.g., by the stage-aligned Runge-Kutta scheme, see https://doi.org/10.1016/j.matcom.2026.08.029. + * 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. * @@ -234,23 +192,11 @@ 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, see Tableau. - * @param[in] final_tab Weights of the method. The propagated solution entries_low is used. + * @param[in] tab Butcher tableau of the method. */ - void set_tableaus(const Tableau& tab, const TableauFinal& final_tab) - { - const Eigen::Index num_stages = final_tab.entries_low.size(); - assert(static_cast(tab.entries.size()) == num_stages - 1); - m_a = Eigen::MatrixX::Zero(num_stages, num_stages); - m_c = Eigen::VectorX::Zero(num_stages); - for (Eigen::Index s = 1; s < num_stages; ++s) { - const auto& row = tab.entries[static_cast(s - 1)]; - m_c[s] = row[0]; - for (Eigen::Index r = 1; r < row.size(); ++r) { - m_a(s, r - 1) = row[r]; - } - } - m_b = final_tab.entries_low; + void set_tableau(const Tableau& tab) + { + m_tableau = tab; m_num_steps = 0; } @@ -261,24 +207,33 @@ class RungeKuttaStageHistory } /** - * @brief Add a step. - * @param[in] t Start time of the step. - * @param[in] h Step size. - * @param[in] stage_values Stage values with one column per stage. + * @brief Storage for the stage values of the next step, with one column per stage. + * 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 add_step(FP t, FP h, Eigen::Ref> stage_values) + Eigen::MatrixX& get_next_stage_values(Eigen::Index num_values) { - assert(stage_values.cols() == get_num_stages()); if (m_num_steps == m_stage_values.size()) { - m_times.push_back(t); - m_step_sizes.push_back(h); - m_stage_values.emplace_back(stage_values); - } - else { - m_times[m_num_steps] = t; - m_step_sizes[m_num_steps] = h; - m_stage_values[m_num_steps] = stage_values; + m_times.emplace_back(); + m_step_sizes.emplace_back(); + m_stage_values.emplace_back(); } + auto& stage_values = m_stage_values[m_num_steps]; + stage_values.resize(num_values, m_tableau.get_num_stages()); + return stage_values; + } + + /** + * @brief Add a step whose stage values were written into get_next_stage_values. + * @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; } @@ -308,10 +263,10 @@ class RungeKuttaStageHistory return m_step_sizes[step]; } - /// @brief Time t_n + c_s * h_n at which the stage s of a step is evaluated. + /// @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_c[stage] * get_step_size(step); + return get_time(step) + m_tableau.nodes[stage] * get_step_size(step); } /// @brief Stage values of a step, one column per stage. @@ -321,33 +276,14 @@ class RungeKuttaStageHistory return m_stage_values[step]; } - /// @brief Number of stages S of the method. - Eigen::Index get_num_stages() const - { - return m_b.size(); - } - - /// @brief Runge-Kutta matrix a of the method (S x S). - const Eigen::MatrixX& get_a() const + /// @brief The Butcher tableau of the method that computed the steps. + const Tableau& get_tableau() const { - return m_a; - } - - /// @brief Weights b of the propagated solution. - const Eigen::VectorX& get_b() const - { - return m_b; - } - - /// @brief Nodes c of the method. - const Eigen::VectorX& get_c() const - { - return m_c; + return m_tableau; } private: - Eigen::MatrixX m_a; - Eigen::VectorX m_b, m_c; + Tableau m_tableau; std::vector m_times; std::vector m_step_sizes; std::vector> m_stage_values; @@ -355,10 +291,11 @@ class RungeKuttaStageHistory }; /** - * @brief Two scheme Runge-Kutta numerical integrator with adaptive step width + * @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 used with set_tableaus (see Tableau and TableauFinal). + * 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. @@ -392,15 +329,14 @@ class RKIntegratorCore : public OdeIntegratorCore } /** - * @brief Set up the integrator with the given method (see set_tableaus). + * @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. - * @param final_tab Weights of the method. */ - RKIntegratorCore(const Tableau& tab, const TableauFinal& final_tab) + RKIntegratorCore(const Tableau& tab) : RKIntegratorCore() { - set_tableaus(tab, final_tab); + set_tableau(tab); } std::unique_ptr> clone() const override @@ -433,18 +369,23 @@ class RKIntegratorCore : public OdeIntegratorCore } /** - * @brief Set the method used for integration. + * @brief Set the method used for integration. Clears the stage history. * @param tab Butcher tableau of the method. - * @param final_tab Weights of the method. */ - void set_tableaus(const Tableau& tab, const TableauFinal& final_tab) + void set_tableau(const Tableau& tab) { - assert(static_cast(tab.entries.size()) == final_tab.entries_low.size() - 1); - assert(!final_tab.is_adaptive() || final_tab.entries_high.size() == final_tab.entries_low.size()); - m_tab = tab; - m_tab_final = final_tab; - m_kt_values.resize(Eigen::NoChange, m_tab_final.entries_low.size()); - reset_stage_history(); + 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; } /** @@ -468,7 +409,7 @@ class RKIntegratorCore : public OdeIntegratorCore /// @brief Remove all steps from the stage history. void reset_stage_history() { - m_stage_history.set_tableaus(m_tab, m_tab_final); + m_stage_history.clear(); } /** @@ -487,7 +428,7 @@ class RKIntegratorCore : public OdeIntegratorCore /** * @brief Make a single integration step of a system of ODEs and adapt the step size. - * If the method is not adaptive (see TableauFinal::is_adaptive), a step of size dt is made and dt is not changed. + * 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 @@ -500,28 +441,26 @@ class RKIntegratorCore : public OdeIntegratorCore 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_final.entries_low.size()); - } - if (m_record_stages && (m_stage_values.rows() != yt.size() || m_stage_values.cols() != m_kt_values.cols())) { - m_stage_values.resize(yt.size(), m_kt_values.cols()); + m_kt_values.resize(yt.size(), m_tab.get_num_stages()); } m_yt_eval = yt; - if (!m_tab_final.is_adaptive()) { + // step calculation for fixed-step methods, which do not use the step size bounds + if (!m_tab.is_adaptive()) { compute_stages(f, t, dt, ytp1); ytp1 = m_yt_eval; - ytp1 += (dt * (m_kt_values * m_tab_final.entries_low)); + ytp1 += (dt * (m_kt_values * m_tab.weights)); record_step(t, dt); t += dt; return true; } - 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()); @@ -541,9 +480,9 @@ class RKIntegratorCore : public OdeIntegratorCore compute_stages(f, t, dt, ytp1); // calculate low order estimate ytp1 = m_yt_eval; - ytp1 += (dt * (m_kt_values * m_tab_final.entries_low)); + 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_final.entries_high - m_tab_final.entries_low)).array().abs(); + 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; @@ -560,7 +499,7 @@ class RKIntegratorCore : public OdeIntegratorCore // 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))); + 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; @@ -575,7 +514,6 @@ class RKIntegratorCore : public OdeIntegratorCore 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; @@ -583,43 +521,43 @@ class RKIntegratorCore : public OdeIntegratorCore 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. + * @param[out] ytp1 Used as temporary storage for the stage values, if they are not recorded. */ void compute_stages(const DerivFunction& f, FP t, FP dt, Eigen::Ref> ytp1) const { + Eigen::MatrixX* stage_values = + m_record_stages ? &m_stage_history.get_next_stage_values(m_yt_eval.size()) : nullptr; 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_values.col(0) = m_yt_eval; + if (stage_values) { + stage_values->col(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.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); - } - if (m_record_stages) { - m_stage_values.col(i) = ytp1; + t_eval += m_tab.nodes[i] * dt; // t_eval = t + c_i * h + Eigen::Ref> y_stage = + stage_values ? Eigen::Ref>(stage_values->col(i)) : ytp1; + 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 ytp1: kt_i = f(t_eval, ytp1_low) - f(ytp1, t_eval, m_kt_values.col(i)); + // 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 stages of the last computed step to the stage history, if recording is enabled. + /// @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, m_stage_values); + m_stage_history.add_step(t, dt); } } @@ -627,7 +565,6 @@ class RKIntegratorCore : public OdeIntegratorCore 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. - mutable Eigen::MatrixX m_stage_values; ///< Stage values of the current step, one column per stage. }; } // namespace mio From 80a940a00146ac18e79696fa22c957636fb5979e Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:48:02 +0100 Subject: [PATCH 07/12] update tests --- cpp/tests/test_numericalIntegration.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cpp/tests/test_numericalIntegration.cpp b/cpp/tests/test_numericalIntegration.cpp index 82f4e8b00b..f4f33731f1 100755 --- a/cpp/tests/test_numericalIntegration.cpp +++ b/cpp/tests/test_numericalIntegration.cpp @@ -255,11 +255,11 @@ TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) 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, const mio::TableauFinal& final_tab, int order) { - EXPECT_FALSE(final_tab.is_adaptive()); + 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, final_tab)); + 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); @@ -268,10 +268,10 @@ TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) } EXPECT_NEAR(std::log2(errors[0] / errors[1]), order, 0.25); }; - check_order(mio::Tableau::explicit_euler(), mio::TableauFinal::explicit_euler(), 1); - check_order(mio::Tableau::midpoint(), mio::TableauFinal::midpoint(), 2); - check_order(mio::Tableau::kutta3(), mio::TableauFinal::kutta3(), 3); - check_order(mio::Tableau::classical_rk4(), mio::TableauFinal::classical_rk4(), 4); + 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) @@ -305,9 +305,9 @@ TEST(TestRKIntegratorCore, recordsStagesOfAcceptedSteps) 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_num_stages(); ++s) { + 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_b()[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); } From e6ef8d2f1806a5ba3054e21ebfda7ebbca87d1b7 Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:48:39 +0100 Subject: [PATCH 08/12] math readme --- cpp/memilio/math/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/memilio/math/README.md b/cpp/memilio/math/README.md index 10cbb6e2e8..d66376f0d9 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 - - 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 (set) is reached and the criterion cannot be satisfied, it is returned that the adaptive step sizing failed. Via Tableau and TableauFinal, 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 TableauFinal does not contain a second 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). + - 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 (set) is reached and the criterion cannot be satisfied, it is returned that the 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 From e97e46edf1807c0ab777af4bc5ec81b07c33e131 Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:52:44 +0100 Subject: [PATCH 09/12] python bindings + tests --- .../memilio/simulation/bindings/math/integrator.h | 15 +++------------ .../memilio-simulation/tests/test_integrators.py | 7 +++---- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h index ae27659c2e..97f5ec1743 100644 --- a/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h +++ b/pycode/memilio-simulation/memilio/simulation/bindings/math/integrator.h @@ -76,29 +76,20 @@ void bind_Integrator_Core(pybind11::module_& m) 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>(m, "TableauFinal") - .def(pybind11::init<>()) - .def("is_adaptive", &mio::TableauFinal::is_adaptive) - .def_static("explicit_euler", &mio::TableauFinal::explicit_euler) - .def_static("midpoint", &mio::TableauFinal::midpoint) - .def_static("kutta3", &mio::TableauFinal::kutta3) - .def_static("classical_rk4", &mio::TableauFinal::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&, const mio::TableauFinal&>(), pybind11::arg("tab"), - pybind11::arg("final_tab")) - .def("set_tableaus", &mio::RKIntegratorCore::set_tableaus, pybind11::arg("tab"), - pybind11::arg("final_tab")) + .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 0129fd4c53..bf2cd63faa 100644 --- a/pycode/memilio-simulation/tests/test_integrators.py +++ b/pycode/memilio-simulation/tests/test_integrators.py @@ -85,8 +85,8 @@ def test_model_integration(self): def test_fixed_step_runge_kutta(self): """ """ - self.assertTrue(mio.TableauFinal().is_adaptive()) - self.assertFalse(mio.TableauFinal.classical_rk4().is_adaptive()) + self.assertTrue(mio.Tableau().is_adaptive()) + self.assertFalse(mio.Tableau.classical_rk4().is_adaptive()) model = Model(1) A0 = mio.AgeGroup(0) @@ -96,8 +96,7 @@ def test_fixed_step_runge_kutta(self): model.populations.set_difference_from_total( (A0, InfectionState.Susceptible), 8000) - integrator = mio.RKIntegratorCore( - mio.Tableau.classical_rk4(), mio.TableauFinal.classical_rk4()) + integrator = mio.RKIntegratorCore(mio.Tableau.classical_rk4()) result = simulate(0, 5, 0.5, model, integrator) reference = simulate(0, 5, 0.5, model, mio.RKIntegratorCore()) From b7200489aaa31e8c6d2cbc67c7c583767eba7e7c Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:02:55 +0100 Subject: [PATCH 10/12] review suggestions --- cpp/memilio/math/runge_kutta.h | 40 +++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/cpp/memilio/math/runge_kutta.h b/cpp/memilio/math/runge_kutta.h index 39145da0f5..4fededed8d 100644 --- a/cpp/memilio/math/runge_kutta.h +++ b/cpp/memilio/math/runge_kutta.h @@ -207,25 +207,33 @@ class RungeKuttaStageHistory } /** - * @brief Storage for the stage values of the next step, with one column per stage. + * @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. */ - Eigen::MatrixX& get_next_stage_values(Eigen::Index num_values) + 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(); } - auto& stage_values = m_stage_values[m_num_steps]; - stage_values.resize(num_values, m_tableau.get_num_stages()); - return stage_values; + m_stage_values[m_num_steps].resize(num_values, m_tableau.get_num_stages()); } /** - * @brief Add a step whose stage values were written into get_next_stage_values. + * @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. */ @@ -453,7 +461,7 @@ class RKIntegratorCore : public OdeIntegratorCore // step calculation for fixed-step methods, which do not use the step size bounds if (!m_tab.is_adaptive()) { - compute_stages(f, t, dt, ytp1); + compute_kt_values(f, t, dt, ytp1); ytp1 = m_yt_eval; ytp1 += (dt * (m_kt_values * m_tab.weights)); record_step(t, dt); @@ -477,7 +485,7 @@ class RKIntegratorCore : public OdeIntegratorCore dt_is_invalid = true; dt = this->get_dt_min(); } - compute_stages(f, t, dt, ytp1); + compute_kt_values(f, t, dt, ytp1); // calculate low order estimate ytp1 = m_yt_eval; ytp1 += (dt * (m_kt_values * m_tab.weights)); @@ -527,23 +535,25 @@ class RKIntegratorCore : public OdeIntegratorCore * @param[in] dt Step size. * @param[out] ytp1 Used as temporary storage for the stage values, if they are not recorded. */ - void compute_stages(const DerivFunction& f, FP t, FP dt, Eigen::Ref> ytp1) const + void compute_kt_values(const DerivFunction& f, FP t, FP dt, Eigen::Ref> ytp1) const { - Eigen::MatrixX* stage_values = - m_record_stages ? &m_stage_history.get_next_stage_values(m_yt_eval.size()) : nullptr; + 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 (stage_values) { - stage_values->col(0) = m_yt_eval; + 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 - Eigen::Ref> y_stage = - stage_values ? Eigen::Ref>(stage_values->col(i)) : ytp1; + // 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); From 4b1a931f1166e3c098dbf1be1ca1af91a702a1e6 Mon Sep 17 00:00:00 2001 From: Henrik Zunker <69154294+HenrZu@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:32:25 +0100 Subject: [PATCH 11/12] Apply batched suggestions from code review Co-authored-by: reneSchm <49305466+reneSchm@users.noreply.github.com> --- cpp/memilio/math/README.md | 2 +- cpp/memilio/math/runge_kutta.h | 34 +++++++++++++++---------- cpp/tests/test_numericalIntegration.cpp | 10 +++++--- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/cpp/memilio/math/README.md b/cpp/memilio/math/README.md index d66376f0d9..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 - - 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 (set) is reached and the criterion cannot be satisfied, it is returned that the 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). + - 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/runge_kutta.h b/cpp/memilio/math/runge_kutta.h index 4fededed8d..761b7a6df2 100644 --- a/cpp/memilio/math/runge_kutta.h +++ b/cpp/memilio/math/runge_kutta.h @@ -44,9 +44,10 @@ namespace mio * ----+------------------- * | b_1 ... b_S * | b^_1 ... b^_S - * with a strictly lower triangular matrix a. The 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. + * 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: @@ -72,7 +73,7 @@ class Tableau Eigen::VectorX embedded_weights; ///< Weights b^ of the embedded solution, empty for fixed-step methods. /** - * @brief Create a tableau from its coefficients, see Tableau. + * @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. @@ -84,8 +85,13 @@ class Tableau , 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. @@ -398,7 +404,8 @@ class RKIntegratorCore : public OdeIntegratorCore /** * @brief Enable or disable recording the stage values of all accepted steps in the stage history. - * By default, recording is disabled. Enabling it clears 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. */ @@ -435,12 +442,13 @@ class RKIntegratorCore : public OdeIntegratorCore /** @} */ /** - * @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+1) + * @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 diff --git a/cpp/tests/test_numericalIntegration.cpp b/cpp/tests/test_numericalIntegration.cpp index f4f33731f1..6a3a8101e8 100755 --- a/cpp/tests/test_numericalIntegration.cpp +++ b/cpp/tests/test_numericalIntegration.cpp @@ -246,8 +246,9 @@ TYPED_TEST(TestVerifyNumericalIntegrator, adaptiveStepSizing) EXPECT_EQ(this->sol[0][0], t_eval); // check that the integration step matches the time step } -TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) -{ +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); @@ -274,8 +275,9 @@ TEST(TestRKIntegratorCore, fixedStepConvergenceOrder) check_order(mio::Tableau::classical_rk4(), 4); } -TEST(TestRKIntegratorCore, recordsStagesOfAcceptedSteps) -{ +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]; }; From 39668a2ef81009a4ae4a1e7e2452e2bbdad82b6f Mon Sep 17 00:00:00 2001 From: HenrZu <69154294+HenrZu@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:46:57 +0100 Subject: [PATCH 12/12] [ci skip] comment on issue --- cpp/memilio/math/runge_kutta.h | 43 +++++++++++++++++----------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/cpp/memilio/math/runge_kutta.h b/cpp/memilio/math/runge_kutta.h index 761b7a6df2..838608f467 100644 --- a/cpp/memilio/math/runge_kutta.h +++ b/cpp/memilio/math/runge_kutta.h @@ -44,10 +44,10 @@ namespace mio * ----+------------------- * | 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. + * 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: @@ -73,7 +73,7 @@ class Tableau 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. + * @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. @@ -85,13 +85,13 @@ class Tableau , 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); - } + { + 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. @@ -404,8 +404,8 @@ class RKIntegratorCore : public OdeIntegratorCore /** * @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. + * 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. */ @@ -442,13 +442,13 @@ class RKIntegratorCore : public OdeIntegratorCore /** @} */ /** - * @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. + * @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 @@ -515,6 +515,7 @@ class RKIntegratorCore : public OdeIntegratorCore // 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