1#ifndef STAN_MATH_REV_FUNCTOR_KINSOL_SOLVE_HPP
2#define STAN_MATH_REV_FUNCTOR_KINSOL_SOLVE_HPP
9#include <sundials/sundials_context.h>
10#include <kinsol/kinsol.h>
11#include <sunmatrix/sunmatrix_dense.h>
12#include <sunlinsol/sunlinsol_dense.h>
13#include <nvector/nvector_serial.h>
60template <
typename F1,
typename... Args>
62 const F1& f,
const Eigen::VectorXd& x,
63 const double scaling_step_tol,
64 const double function_tolerance,
65 const int64_t max_num_steps,
66 const bool custom_jacobian,
67 const int steps_eval_jacobian,
68 const int global_line_search,
69 std::ostream*
const msgs,
const Args&... args) {
72 system_data kinsol_data(f, x, msgs, args...);
75 &system_data::kinsol_f_system, kinsol_data.nv_x_));
77 N_Vector scaling = N_VNew_Serial(N, kinsol_data.sundials_context_);
78 N_Vector nv_x = N_VNew_Serial(N, kinsol_data.sundials_context_);
79 Eigen::VectorXd x_solution(N);
82 N_VConst_Serial(1.0, scaling);
85 KINSetNumMaxIters(kinsol_data.kinsol_memory_, max_num_steps));
87 KINSetFuncNormTol(kinsol_data.kinsol_memory_, function_tolerance));
89 KINSetScaledStepTol(kinsol_data.kinsol_memory_, scaling_step_tol));
91 KINSetMaxSetupCalls(kinsol_data.kinsol_memory_, steps_eval_jacobian));
98 double max_newton_step = (x.norm() == 0) ? x.size() : 0;
100 KINSetMaxNewtonStep(kinsol_data.kinsol_memory_, max_newton_step));
102 static_cast<void*
>(&kinsol_data)));
106 kinsol_data.LS_, kinsol_data.J_));
110 &system_data::kinsol_jacobian));
112 for (
int i = 0; i < N; i++)
113 NV_Ith_S(nv_x, i) = x(i);
115 kinsol_check(KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search,
117 "KINSol", max_num_steps);
119 for (
int i = 0; i < N; i++)
120 x_solution(i) = NV_Ith_S(nv_x, i);
121 }
catch (
const std::exception&
e) {
#define CHECK_KINSOL_CALL(call)
KINSOL algebraic system data holder.
static constexpr double e()
Return the base of the natural logarithm.
void kinsol_check(int flag, const char *func_name)
Throws an exception message when the functions in KINSOL fails.
Eigen::VectorXd kinsol_solve(const F1 &f, const Eigen::VectorXd &x, const double scaling_step_tol, const double function_tolerance, const int64_t max_num_steps, const bool custom_jacobian, const int steps_eval_jacobian, const int global_line_search, std::ostream *const msgs, const Args &... args)
Return the solution to the specified algebraic system, given an initial guess.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...