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 double scaling_step_tol,
63 const double function_tolerance,
64 const int64_t max_num_steps,
65 const bool custom_jacobian,
66 const int steps_eval_jacobian,
67 const int global_line_search,
68 std::ostream*
const msgs,
const Args&... args) {
71 system_data kinsol_data(f, x, msgs, args...);
74 &system_data::kinsol_f_system, kinsol_data.nv_x_));
76 N_Vector scaling = N_VNew_Serial(N, kinsol_data.sundials_context_);
77 N_Vector nv_x = N_VNew_Serial(N, kinsol_data.sundials_context_);
78 Eigen::VectorXd x_solution(N);
81 N_VConst_Serial(1.0, scaling);
84 KINSetNumMaxIters(kinsol_data.kinsol_memory_, max_num_steps));
86 KINSetFuncNormTol(kinsol_data.kinsol_memory_, function_tolerance));
88 KINSetScaledStepTol(kinsol_data.kinsol_memory_, scaling_step_tol));
90 KINSetMaxSetupCalls(kinsol_data.kinsol_memory_, steps_eval_jacobian));
97 double max_newton_step = (x.norm() == 0) ? x.size() : 0;
99 KINSetMaxNewtonStep(kinsol_data.kinsol_memory_, max_newton_step));
101 static_cast<void*
>(&kinsol_data)));
105 kinsol_data.LS_, kinsol_data.J_));
109 &system_data::kinsol_jacobian));
111 for (
int i = 0; i < N; i++)
112 NV_Ith_S(nv_x, i) = x(i);
114 kinsol_check(KINSol(kinsol_data.kinsol_memory_, nv_x, global_line_search,
116 "KINSol", max_num_steps);
118 for (
int i = 0; i < N; i++)
119 x_solution(i) = NV_Ith_S(nv_x, i);
120 }
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 ...