FML
Loading...
Searching...
No Matches
ODESolver.cpp
Go to the documentation of this file.
1#include "ODESolver.h"
2
3#include <algorithm>
4#include <cmath>
5#include <memory>
6#include <stdexcept>
7#include <string>
8
9namespace FML {
10 namespace SOLVERS {
11 namespace ODESOLVER {
12
13 void ODESolver::throw_error(std::string errormessage) const {
14#if defined(USE_MPI) && !defined(ODESOLVER_THROW_ON_ERROR)
15 std::cout << errormessage << std::flush;
16 MPI_Abort(MPI_COMM_WORLD, 1);
17 abort();
18#else
19 throw std::runtime_error(errormessage);
20#endif
21 }
22
23 //==================================================================
24 // Wrappers for conversions between std::function and the raw
25 // function pointer required by GSL
26 //==================================================================
27
28 ODEFunctionJacobian no_jacobian = []([[maybe_unused]] double t,
29 [[maybe_unused]] const double * y,
30 [[maybe_unused]] double * dfdy,
31 [[maybe_unused]] double * dfdt) { return GSL_SUCCESS; };
32
34
35 struct ODEParamWrapper {
36 private:
37 const ODEFunction & deriv;
38 const ODEFunctionJacobian & jacobian;
39
40 public:
41 ODEParamWrapper(const ODEFunction & _deriv, const ODEFunctionJacobian & _jacobian)
42 : deriv(_deriv), jacobian(_jacobian) {}
43 auto get_deriv() -> const ODEFunction & { return deriv; }
44 auto get_jacobian() -> const ODEFunctionJacobian & { return jacobian; }
45 };
46
47 int ode_wrapper(double x, const double * y, double * dydx, void * param) {
48 auto * p = static_cast<struct ODEParamWrapper *>(param);
49 return (p->get_deriv())(x, y, dydx);
50 }
51
52 int jacobian_wrapper(double t, const double * y, double * dfdy, double * dfdt, void * param) {
53 auto * p = static_cast<struct ODEParamWrapper *>(param);
54 return (p->get_jacobian())(t, y, dfdy, dfdt);
55 }
56
57 // Jacobian by forward finite differences of the ODE function: dfdy[i*n + j] = df_i/dy_j with the
58 // step h_j = 1e-8 max(|y_j|, 1e-8), and dfdt with a step 1e-8 max(|t|, 1) backwards along the
59 // direction of integration (so the function is never evaluated beyond the end point)
60 struct FiniteDifferenceJacobian {
61 const ODEFunction & deriv;
62 size_t n;
63 double direction;
64 DVector ytmp, f0, f1;
65 FiniteDifferenceJacobian(const ODEFunction & d, size_t _n, double dir)
66 : deriv(d), n(_n), direction(dir), ytmp(_n), f0(_n), f1(_n) {}
67 int operator()(double t, const double * y, double * dfdy, double * dfdt) {
68 int status = deriv(t, y, f0.data());
69 if (status != GSL_SUCCESS)
70 return status;
71 ytmp.assign(y, y + n);
72 for (size_t j = 0; j < n; j++) {
73 const double h = 1e-8 * std::max(std::fabs(y[j]), 1e-8);
74 ytmp[j] = y[j] + h;
75 status = deriv(t, ytmp.data(), f1.data());
76 if (status != GSL_SUCCESS)
77 return status;
78 for (size_t i = 0; i < n; i++)
79 dfdy[i * n + j] = (f1[i] - f0[i]) / h;
80 ytmp[j] = y[j];
81 }
82 const double ht = -direction * 1e-8 * std::max(std::fabs(t), 1.0);
83 status = deriv(t + ht, y, f1.data());
84 if (status != GSL_SUCCESS)
85 return status;
86 for (size_t i = 0; i < n; i++)
87 dfdt[i] = (f1[i] - f0[i]) / ht;
88 return GSL_SUCCESS;
89 }
90 };
91
92 //==================================================================
93 // Constructors
94 //==================================================================
95
96 ODESolver::ODESolver(double hstart, double abserr, double relerr)
97 : hstart(hstart), abserr(abserr), relerr(relerr) {}
98
99 void ODESolver::solve(const ODEFunction & ode_equation,
100 const DVector & xarr,
101 const DVector & yinitial,
102 const gsl_odeiv2_step_type * stepper,
103 const ODEFunctionJacobian & jacobian) {
104 // If no jacobian is provided pass nullptr to GSL (the dummy no_jacobian does not set dfdy, dfdt
105 // so implicit steppers would use uninitialized memory). We then throw if the stepper needs it,
106 // unless the jacobian is to be computed by finite differences
107 const bool has_jacobian = (&jacobian != no_jacobian_ptr);
108 if (!has_jacobian && finite_difference_jacobian && xarr.size() >= 2 && !yinitial.empty()) {
109 FiniteDifferenceJacobian fd(ode_equation, yinitial.size(), xarr[1] > xarr[0] ? 1.0 : -1.0);
110 const ODEFunctionJacobian fdjac = [&fd](double t, const double * y, double * dfdy, double * dfdt) {
111 return fd(t, y, dfdy, dfdt);
112 };
113 struct ODEParamWrapper equations(ode_equation, fdjac);
114 solve(ode_wrapper, &equations, xarr, yinitial, stepper, jacobian_wrapper);
115 return;
116 }
117 struct ODEParamWrapper equations(ode_equation, jacobian);
118 solve(ode_wrapper, &equations, xarr, yinitial, stepper, has_jacobian ? jacobian_wrapper : nullptr);
119 }
120
121 void ODESolver::set_finite_difference_jacobian(bool onoff) { finite_difference_jacobian = onoff; }
122
123 //==================================================================
124 // Class methods
125 //==================================================================
126
128 void * parameters,
129 const DVector & xarr,
130 const DVector & yinitial,
131 const gsl_odeiv2_step_type * stepper,
133 // Store the number of equations and size of x-array
134 nequations = int(yinitial.size());
135 num_x_points = int(xarr.size());
136 if (num_x_points < 2) {
137 std::string errormessage = "[ODESolver::solve] The xarray needs to have at least size 2\n";
138 throw_error(errormessage);
139 }
140 if (nequations < 1) {
141 std::string errormessage = "[ODESolver::solve] The yinitial is empty\n";
142 throw_error(errormessage);
143 }
144
145 // Implicit steppers need the jacobian (GSL would call a null function pointer)
146 if (jacobian == nullptr) {
147 for (auto st : {gsl_odeiv2_step_rk1imp,
148 gsl_odeiv2_step_rk2imp,
149 gsl_odeiv2_step_rk4imp,
150 gsl_odeiv2_step_bsimp,
151 gsl_odeiv2_step_msbdf}) {
152 if (stepper == st) {
153 std::string errormessage = "[ODESolver::solve] The stepper " + std::string(stepper->name) +
154 " requires the jacobian, but none was provided\n";
155 throw_error(errormessage);
156 }
157 }
158 }
159
160 // Are we integrating forward or backward?
161 double sign = xarr[1] > xarr[0] ? 1.0 : -1.0;
162
163 // Set up the ODE system
164 gsl_odeiv2_system ode_system = {ode_equation, jacobian, size_t(yinitial.size()), parameters};
165 // The driver is freed also if an exception is thrown (e.g. by the users ODE function)
166 std::unique_ptr<gsl_odeiv2_driver, decltype(&gsl_odeiv2_driver_free)> ode_driver_ptr(
167 gsl_odeiv2_driver_alloc_y_new(&ode_system, stepper, std::abs(hstart) * sign, abserr, relerr),
168 &gsl_odeiv2_driver_free);
169 gsl_odeiv2_driver * ode_driver = ode_driver_ptr.get();
170
171 // Initialize with the initial condition
172 double x = xarr[0];
173 DVector y(yinitial);
174 DVector dydx(nequations);
175 ode_equation(x, y.data(), dydx.data(), parameters);
176
177 // Allocate memory for the the results: data[i][j] = y_j(x_i)
178 data = std::vector<DVector>(xarr.size(), yinitial);
179 derivative_data = std::vector<DVector>(xarr.size(), dydx);
180
181 if (verbose) {
182 std::cout << "ODESolver step " << std::setw(5) << 0 << " / " << num_x_points - 1 << " x: ["
183 << std::setw(10) << x << "] ";
184 std::cout << "y: [";
185 for (auto & ycomp : y) {
186 std::cout << " " << std::setw(10) << ycomp << " ";
187 }
188 std::cout << "]" << std::endl;
189 }
190
191 // Solve it step by step...
192 for (int i = 1; i < num_x_points; i++) {
193 const double xnew = xarr[i];
194
195 if (verbose) {
196 std::cout << "ODESolver step " << std::setw(5) << i << " / " << num_x_points - 1 << " x: ["
197 << std::setw(10) << xnew << "] ";
198 }
199
200 // Integrate from x -> xnew
201 const int status = gsl_odeiv2_driver_apply(ode_driver, &x, xnew, y.data());
202 if (status != GSL_SUCCESS) {
203 ode_driver_ptr.reset();
204 std::string errormessage =
205 "[ODESolver::solve] GSL gsl_odeiv2_driver_apply returned non-successful at x = " +
206 std::to_string(x) + " (target " + std::to_string(xnew) + "): " + gsl_strerror(status) +
207 "\n";
208 throw_error(errormessage);
209 }
210
211 if (verbose) {
212 std::cout << "y: [";
213 for (auto & ycomp : y) {
214 std::cout << " " << std::setw(10) << ycomp << " ";
215 }
216 std::cout << "]" << std::endl;
217 }
218
219 // Store the derivative
220 ode_equation(x, y.data(), dydx.data(), parameters);
221
222 // Copy over result
223 data[i] = y;
224 derivative_data[i] = dydx;
225 }
226 }
227
228 void ODESolver::set_verbose(bool onoff) { verbose = onoff; }
229
230 DVector2D ODESolver::get_data() const { return data; }
231
233 auto data_transpose = std::vector<DVector>(nequations, DVector(num_x_points));
234 for (int ix = 0; ix < num_x_points; ix++) {
235 for (int icomponent = 0; icomponent < nequations; icomponent++) {
236 data_transpose[icomponent][ix] = data[ix][icomponent];
237 }
238 }
239 return data_transpose;
240 }
241
243 DVector res(nequations);
244 for (int icomponent = 0; icomponent < nequations; icomponent++) {
245 res[icomponent] = data[num_x_points - 1][icomponent];
246 }
247 return res;
248 }
249
250 double ODESolver::get_final_data_by_component(int icomponent) const {
251 return data[num_x_points - 1][icomponent];
252 }
253
255 DVector res(num_x_points);
256 for (int ix = 0; ix < num_x_points; ix++) {
257 res[ix] = data[ix][icomponent];
258 }
259 return res;
260 }
261
263 DVector res(nequations);
264 for (int icomponent = 0; icomponent < nequations; icomponent++) {
265 res[icomponent] = data[ix][icomponent];
266 }
267 return res;
268 }
269
270 DVector2D ODESolver::get_derivative_data() const { return derivative_data; }
271
273 DVector res(num_x_points);
274 for (int ix = 0; ix < num_x_points; ix++) {
275 res[ix] = derivative_data[ix][icomponent];
276 }
277 return res;
278 }
279
280 void ODESolver::set_accuracy(const double h, const double a, const double r) {
281 hstart = h;
282 abserr = a;
283 relerr = r;
284 }
285 } // namespace ODESOLVER
286 } // namespace SOLVERS
287} // namespace FML
FML::SOLVERS::FFTLog::DVector DVector
Definition Main.cpp:4
const double h
Definition Main.cpp:66
FML::SOLVERS::ODESOLVER::ODEFunction ODEFunction
Definition Main.cpp:83
DVector get_data_by_xindex(int ix) const
Get the data at a particular x-index y(xarr_i)
void set_finite_difference_jacobian(bool onoff)
Implicit steppers without a jacobian: compute it by forward finite differences of the ODE function (r...
DVector2D get_data() const
Get all the data z_ij = ( y_j(xarr_i) ), i.e. data[ix][icomponent].
double get_final_data_by_component(int icomponent) const
Get the solution for a given component at the end point.
DVector2D get_derivative_data() const
Get all the data for the derivatives z_ij = ( dy_j/dx(xarr_i) ), i.e.
DVector get_derivative_data_by_component(int icomponent) const
Get the data dy_i/dx(xarr) for the derivatives for a particular component.
DVector get_data_by_component(int icomponent) const
Get the data for a particular component y_i(xarr)
DVector get_final_data() const
Get the solution at the end point.
void set_verbose(bool onoff)
Show info while solving or not.
void solve(ODEFunctionPointer ode_equation, void *parameters, const DVector &xarr, const DVector &yinitial, const gsl_odeiv2_step_type *stepper=ODESOLVER_FIDUCIAL_STEPPER, ODEFunctionPointerJacobian jacobian=nullptr)
void set_accuracy(const double hstart, const double abserr, const double relerr)
Set the accuracy parameters (first guess for the step-size, the absolute and relative error)
DVector2D get_data_transpose() const
Get all the data transposed z_ij = ( y_i(xarr_j) ), i.e. data[icomponent][ix].
std::vector< double > DVector
Definition ODESolver.h:29
std::vector< DVector > DVector2D
Definition ODESolver.h:30
int ode_wrapper(double x, const double *y, double *dydx, void *param)
Definition ODESolver.cpp:47
ODEFunctionJacobian no_jacobian
Definition ODESolver.cpp:28
int(*)(double, const double[], double[], double[], void *) ODEFunctionPointerJacobian
Definition ODESolver.h:32
ODEFunctionJacobian * no_jacobian_ptr
Definition ODESolver.cpp:33
int(*)(double, const double[], double[], void *) ODEFunctionPointer
Definition ODESolver.h:31
std::function< int(double, const double *, double *, double *)> ODEFunctionJacobian
Definition ODESolver.h:34
std::function< int(double, const double *, double *)> ODEFunction
Definition ODESolver.h:33
int jacobian_wrapper(double t, const double *y, double *dfdy, double *dfdt, void *param)
Definition ODESolver.cpp:52
return y
Definition Global.h:365