#include #include #include #include #include #include #include #include #include #include #include #include "loadtxt.h" extern "C" const int gsl_success() { return GSL_SUCCESS; } // It's zero, but just for clarity sake. // Our units are {kiloparsec, solar mass, gigayear} constexpr double G = 4.498317481097514e-06; class Interp { public: Interp(std::vector& x, std::vector& y) { acc = gsl_interp_accel_alloc(); spline = gsl_spline_alloc(gsl_interp_cspline, x.size()); gsl_spline_init(spline, x.data(), y.data(), x.size()); } Interp() {} inline double operator()(double x) const { return gsl_spline_eval(spline, x, acc); } private: gsl_interp_accel *acc; gsl_spline *spline; }; class Plummer { public: Plummer(double M, double b) : M(M), b(b) {} void calc_acceleration(const double *pos, double *acc) { double r2 = (pos[0]*pos[0] + pos[1]*pos[1] + pos[2]*pos[2] + b*b); double r = sqrt(r2); double r3_inv = 1/(r*r2); acc[0] = -G*M*pos[0]*r3_inv; acc[1] = -G*M*pos[1]*r3_inv; acc[2] = -G*M*pos[2]*r3_inv; } private: double M, b; }; class Galaxy { public: Galaxy(std::string file_name) { auto data = Loadtxt("file.dat", {1, 2, 3}).get_cols(); auto& t_data = data[0]; auto& halo_m_data = data[1]; auto& halo_b_data = data[2]; std::transform(t_data.begin(), t_data.end(), t_data.begin(), [](const double& x){ return x-2.145; }); std::transform(halo_b_data.begin(), halo_b_data.end(), halo_b_data.begin(), [](const double& x){ return x*0.7664209365408798; }); interp_halo_m = Interp(t_data, halo_m_data); interp_halo_b = Interp(t_data, halo_b_data); } int func(double t, const double y[], double f[], void *params) { double halo_m = interp_halo_m(t); double halo_b = interp_halo_b(t); Plummer plummer(halo_m, halo_b); f[0] = y[3]; // vx -> x' f[1] = y[4]; // vy -> y' f[2] = y[5]; // vz -> z' plummer.calc_acceleration(y, f+3); // a -> v' return GSL_SUCCESS; } private: Interp interp_halo_m; Interp interp_halo_b; } galaxy("file.dat"); // Not very nice to have it as a global variable but GSL will have problem otherwise. int jac(double t, const double y[], double *dfdy, double dfdt[], void *params) { return GSL_SUCCESS; } inline int func(double t, const double y[], double f[], void *params) { return galaxy.func(t, y, f, params); } extern "C" int integrate(const double y0[], const double t_max, const double step_size, double y[]) { double t = 0; constexpr double h = 1./4096.; if (step_size/h - (int)(step_size/h) != 0) throw std::runtime_error("step_size must be a multiple of h"); constexpr double epsabs = 1e-7; constexpr double epsrel = 0; const gsl_odeiv2_step_type *T = gsl_odeiv2_step_rk8pd; gsl_odeiv2_step *s = gsl_odeiv2_step_alloc(T, 6); gsl_odeiv2_evolve *e = gsl_odeiv2_evolve_alloc(6); gsl_odeiv2_control *c = gsl_odeiv2_control_y_new(epsabs, 0); gsl_odeiv2_system sys = {func, jac, 6, nullptr}; gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&sys, T, h, epsabs, epsrel); int step = 0; const int step_max = t_max / step_size; std::copy(y0, y0+6, y); for (int step=0; step