1#ifndef STAN_MATH_MIX_FUNCTOR_LAPLACE_MARGINAL_DENSITY_ESTIMATOR_HPP
2#define STAN_MATH_MIX_FUNCTOR_LAPLACE_MARGINAL_DENSITY_ESTIMATOR_HPP
13#include <unsupported/Eigen/MatrixFunctions>
65 int max_num_steps_,
bool allow_fallthrough_,
66 int max_steps_line_search_)
75template <
bool HasInitTheta>
83 hessian_block_size = hessian_block_size_;
90 Eigen::VectorXd theta_0{0};
92 template <
typename ThetaVec>
94 int hessian_block_size_,
int solver_,
95 int max_steps_line_search_,
bool allow_fallthrough_)
97 max_num_steps_, allow_fallthrough_,
98 max_steps_line_search_),
99 theta_0(
value_of(
std::forward<ThetaVec>(theta_0_))) {}
107template <
typename Options>
109 using Ops = std::decay_t<Options>;
110 if constexpr (is_tuple_v<Ops>) {
111 if constexpr (!is_eigen_v<std::tuple_element_t<0, std::decay_t<Ops>>>) {
113 sizeof(std::decay_t<Ops>*) == 0,
114 "ERROR:(laplace_marginal_lpdf) The first laplace argument is "
115 "expected to be an Eigen vector of dynamic size representing the "
118 if constexpr (!stan::is_inner_tuple_type_v<1, Ops, double>) {
120 sizeof(std::decay_t<Ops>*) == 0,
121 "ERROR:(laplace_marginal_lpdf) The second laplace argument is "
122 "expected to be a double representing the tolerance.");
124 if constexpr (!stan::is_inner_tuple_type_v<2, Ops, int>) {
126 sizeof(std::decay_t<Ops>*) == 0,
127 "ERROR:(laplace_marginal_lpdf) The third laplace argument is "
128 "expected to be an int representing the maximum number of steps for "
129 "the laplace approximation.");
131 if constexpr (!stan::is_inner_tuple_type_v<3, Ops, int>) {
133 sizeof(std::decay_t<Ops>*) == 0,
134 "ERROR:(laplace_marginal_lpdf) The fourth laplace argument is "
135 "expected to be an int representing the solver.");
137 if constexpr (!stan::is_inner_tuple_type_v<4, Ops, int>) {
139 sizeof(std::decay_t<Ops>*) == 0,
140 "ERROR:(laplace_marginal_lpdf) The fifth laplace argument is "
141 "expected to be an int representing the max steps for the laplace "
142 "approximaton's wolfe line search.");
144 constexpr bool is_fallthrough
146 5, Ops,
int> || stan::is_inner_tuple_type_v<5, Ops, bool>;
147 if constexpr (!is_fallthrough) {
149 sizeof(std::decay_t<Ops>*) == 0,
150 "ERROR:(laplace_marginal_lpdf) The sixth laplace argument is "
151 "expected to be an int representing allow fallthrough (0/1).");
155 value_of(std::get<0>(std::forward<Options>(ops))),
158 defaults.hessian_block_size,
161 (std::get<5>(ops) > 0) ?
true :
false,
164 return std::forward<Options>(ops);
168template <
typename ThetaVec,
typename WR,
typename L_t,
typename A_vec,
169 typename ThetaGrad,
typename LU_t,
typename KRoot>
172 double lmd{std::numeric_limits<double>::infinity()};
208 A_vec&& a_, ThetaGrad&& theta_grad_, LU_t&& LU_,
209 KRoot&& K_root_,
int solver_used_)
228template <
typename WRootMat>
230 const Eigen::SparseMatrix<double>& W,
231 const Eigen::Index block_size) {
232 int n_block = W.cols() / block_size;
233 Eigen::MatrixXd local_block(block_size, block_size);
234 Eigen::MatrixXd local_block_sqrt(block_size, block_size);
235 Eigen::MatrixXd sqrt_t_mat = Eigen::MatrixXd::Zero(block_size, block_size);
238 for (
int i = 0; i < n_block; i++) {
239 sqrt_t_mat.setZero();
241 = W.block(i * block_size, i * block_size, block_size, block_size);
242 if (!local_block.array().isFinite().any()) {
243 throw std::domain_error(
244 std::string(
"Error in block_matrix_sqrt: "
245 "NaNs detected in block diagonal starting at (")
246 + std::to_string(i) +
", " + std::to_string(i) +
")");
249 Eigen::RealSchur<Eigen::MatrixXd> schurOfA(local_block);
251 const auto& t_mat = schurOfA.matrixT();
252 const auto& u_mat = schurOfA.matrixU();
254 if ((t_mat.diagonal().array() < 0).any()) {
255 throw std::domain_error(
256 std::string(
"Error in block_matrix_sqrt: "
257 "values less than 0 detected in block diagonal's schur "
258 "decomposition starting at (")
259 + std::to_string(i) +
", " + std::to_string(i) +
")");
263 Eigen::matrix_sqrt_quasi_triangular(t_mat, sqrt_t_mat);
265 local_block_sqrt = u_mat * sqrt_t_mat * u_mat.adjoint();
266 }
catch (
const std::exception&
e) {
267 throw std::domain_error(
268 "Error in block_matrix_sqrt: "
269 "The matrix is not positive definite");
271 for (
int k = 0; k < block_size; k++) {
272 for (
int j = 0; j < block_size; j++) {
273 W_root.coeffRef(i * block_size + j, i * block_size + k)
274 = local_block_sqrt(j, k);
289template <
bool InitTheta,
typename CovarMat>
292 const CovarMat& covariance) {
293 if constexpr (InitTheta) {
295 check_finite(frame_name,
"initial guess", options.theta_0);
296 if (
unlikely(options.theta_0.size() != covariance.rows())) {
297 std::stringstream msg;
298 msg << frame_name <<
": The size of the initial theta ("
299 << options.theta_0.size()
300 <<
") vector must match the rows and columns of the covariance "
302 << covariance.rows() <<
", " << covariance.cols() <<
").";
303 throw std::domain_error(msg.str());
307 check_positive(frame_name,
"max_num_steps", options.max_num_steps);
308 check_positive(frame_name,
"hessian_block_size", options.hessian_block_size);
311 const Eigen::Index theta_size = covariance.rows();
312 if (
unlikely(theta_size % options.hessian_block_size != 0
313 || theta_size < options.hessian_block_size)) {
314 throw std::domain_error(
315 "laplace_marginal_density: Hessian block size mismatch.");
318 if (
unlikely(options.solver < 1 || options.solver > 3)) {
319 throw std::domain_error(
320 "laplace_marginal_density: solver must be 1, 2, or 3. Got: "
321 + std::to_string(options.solver));
380 template <
typename ObjFun,
typename ThetaGradFun,
typename CovarianceT,
381 typename ThetaInitializer>
382 NewtonState(
int theta_size, ObjFun&& obj_fun, ThetaGradFun&& theta_grad_f,
383 CovarianceT&& covariance, ThetaInitializer&& theta_init)
385 covariance.llt().solve(theta_init),
386 std::forward<ThetaInitializer>(theta_init),
387 std::forward<ThetaGradFun>(theta_grad_f)),
390 B(theta_size, theta_size),
422 template <
typename Options>
426 = std::clamp(this->
curr().alpha(), 0.0, options.line_search.max_alpha);
439template <
typename LLT,
typename B_t>
441 double max_jitter = 1
e-5) {
443 if (llt_B.info() != Eigen::Success) {
444 double prev_jitter = 0.0;
445 double jitter_try = min_jitter;
446 for (; jitter_try < max_jitter; jitter_try *= 10) {
449 B.diagonal().array() += (jitter_try - prev_jitter);
450 prev_jitter = jitter_try;
452 if (llt_B.info() == Eigen::Success) {
456 if (llt_B.info() != Eigen::Success) {
457 throw std::domain_error(
458 "laplace_marginal_density: Cholesky failed after adding jitter up to "
459 + std::to_string(jitter_try));
487 template <
typename NewtonStateT,
typename CovarMat>
510 template <
typename NewtonStateT,
typename LLFun,
typename LLTupleArgs,
513 const LLTupleArgs& ll_args,
const CovarMat& covariance,
514 int , std::ostream* msgs) {
515 const Eigen::Index theta_size = state.b.size();
520 for (Eigen::Index j = 0; j <
W_diag.size(); j++) {
521 if (
W_diag.coeff(j) < 0 || !std::isfinite(
W_diag.coeff(j))) {
522 throw std::domain_error(
523 "laplace_marginal_density: Hessian matrix is not positive "
532 = Eigen::MatrixXd::Identity(theta_size, theta_size)
538 state.b.noalias() = (
W_diag.array() * state.prev().theta().array()).matrix()
539 + state.prev().theta_grad();
540 auto L =
llt_B.matrixL();
541 auto LT =
llt_B.matrixU();
542 state.proposal_step().a().noalias()
546 L.solve(
W_r_diag.cwiseProduct(covariance * state.b)));
554 return 2.0 *
llt_B.matrixLLT().diagonal().array().log().sum();
565 template <
typename NewtonStateT>
568 state.prev().obj() - 0.5 * log_det,
569 std::move(state).prev().
theta(),
570 Eigen::SparseMatrix<double>(
W_r_diag.asDiagonal()),
571 Eigen::MatrixXd(
llt_B.matrixL()),
572 std::move(state).prev().a(),
573 std::move(state).prev().theta_grad(),
574 Eigen::PartialPivLU<Eigen::MatrixXd>{},
575 Eigen::MatrixXd(0, 0),
595 Eigen::SparseMatrix<double>
W_r;
603 template <
typename NewtonStateT>
606 const Eigen::Index theta_size = state.b.size();
607 W_r.reserve(Eigen::VectorXi::Constant(theta_size, hessian_block_size));
608 const Eigen::Index n_block = theta_size / hessian_block_size;
609 for (Eigen::Index ii = 0; ii < n_block; ii++) {
610 for (Eigen::Index k = 0; k < hessian_block_size; k++) {
611 for (Eigen::Index j = 0; j < hessian_block_size; j++) {
612 W_r.insert(ii * hessian_block_size + j, ii * hessian_block_size + k)
617 W_r.makeCompressed();
642 template <
typename NewtonStateT,
typename LLFun,
typename LLTupleArgs,
645 const LLTupleArgs& ll_args,
const CovarMat& covariance,
646 int hessian_block_size, std::ostream* msgs) {
647 const Eigen::Index theta_size = state.b.size();
650 ll_fun, state.prev().theta(), hessian_block_size, ll_args, msgs);
652 for (Eigen::Index j = 0; j <
W_block.rows(); j++) {
653 if (
W_block.coeff(j, j) < 0 || !std::isfinite(
W_block.coeff(j, j))) {
654 throw std::domain_error(
655 "laplace_marginal_density: Hessian matrix is not positive "
664 state.B.noalias() = Eigen::MatrixXd::Identity(theta_size, theta_size)
665 +
W_r * (covariance *
W_r);
672 =
W_block * state.prev().theta() + state.prev().theta_grad();
673 auto L =
llt_B.matrixL();
674 auto LT =
llt_B.matrixU();
675 state.proposal_step().a().noalias()
676 = state.b -
W_r * LT.solve(L.solve(
W_r * (covariance * state.b)));
684 return 2.0 *
llt_B.matrixLLT().diagonal().array().log().sum();
695 template <
typename NewtonStateT>
698 std::move(state).prev().
theta(),
700 Eigen::MatrixXd(
llt_B.matrixL()),
701 std::move(state).prev().a(),
702 std::move(state).prev().theta_grad(),
703 Eigen::PartialPivLU<Eigen::MatrixXd>{},
704 Eigen::MatrixXd(0, 0),
731 template <
typename NewtonStateT,
typename CovarMat>
734 auto K_root_llt = covariance.template selfadjointView<Eigen::Lower>().llt();
735 if (K_root_llt.info() != Eigen::Success) {
736 throw std::domain_error(
737 "laplace_marginal_density: Cholesky of covariance failed at start");
739 K_root = std::move(K_root_llt.matrixL());
762 template <
typename NewtonStateT,
typename LLFun,
typename LLTupleArgs,
765 const LLTupleArgs& ll_args,
const CovarMat& covariance,
766 int hessian_block_size, std::ostream* msgs) {
767 const Eigen::Index theta_size = state.b.size();
771 ll_fun, state.prev().theta(), hessian_block_size, ll_args, msgs);
774 state.B.noalias() = Eigen::MatrixXd::Identity(theta_size, theta_size)
782 =
W_full * state.prev().theta() + state.prev().theta_grad();
783 auto L =
llt_B.matrixL();
784 auto LT =
llt_B.matrixU();
785 state.proposal_step().a().noalias()
786 =
K_root.transpose().template triangularView<Eigen::Upper>().solve(
787 LT.solve(L.solve(
K_root.transpose() * state.b)));
795 return 2.0 *
llt_B.matrixLLT().diagonal().array().log().sum();
806 template <
typename NewtonStateT>
809 std::move(state.prev().theta()),
811 Eigen::MatrixXd(
llt_B.matrixL()),
812 std::move(state.prev().a()),
813 std::move(state.prev().theta_grad()),
814 Eigen::PartialPivLU<Eigen::MatrixXd>{},
835 Eigen::PartialPivLU<Eigen::MatrixXd>
lu;
857 template <
typename NewtonStateT,
typename LLFun,
typename LLTupleArgs,
860 const LLTupleArgs& ll_args,
const CovarMat& covariance,
861 int hessian_block_size, std::ostream* msgs) {
862 const Eigen::Index theta_size = state.b.size();
866 ll_fun, state.prev().theta(), hessian_block_size, ll_args, msgs);
869 lu.compute(Eigen::MatrixXd::Identity(theta_size, theta_size)
874 =
W_full * state.prev().theta() + state.prev().theta_grad();
875 state.proposal_step().a().noalias()
876 = state.b -
W_full *
lu.solve(covariance * state.b);
889 return lu.matrixLU().diagonal().array().log().sum();
900 template <
typename NewtonStateT>
903 std::move(state).prev().
theta(),
905 Eigen::MatrixXd(0, 0),
906 std::move(state).prev().a(),
907 std::move(state).prev().theta_grad(),
909 Eigen::MatrixXd(0, 0),
936template <
typename SolverPolicy,
typename NewtonStateT,
typename OptionsT,
937 typename LLFunT,
typename LLTupleArgsT,
typename CovarMatT,
940 const OptionsT& options, Eigen::Index& step_iter,
941 const LLFunT& ll_fun,
const LLTupleArgsT& ll_args,
942 const CovarMatT& covariance, UpdateFun&& update_fun,
943 std::ostream* msgs) {
944 bool finish_update =
false;
945 for (; step_iter <= options.max_num_steps; step_iter++) {
946 solver.solve_step(state, ll_fun, ll_args, covariance,
947 options.hessian_block_size, msgs);
948 if (!state.final_loop) {
949 auto&& proposal = state.proposal_step();
950 state.wolfe_info.p_ = proposal.a() - state.prev().a();
951 state.prev_g.noalias() = -covariance * state.prev().a()
952 + covariance * state.prev().theta_grad();
953 state.wolfe_info.init_dir_ = state.prev_g.dot(state.wolfe_info.p_);
955 state.wolfe_info.flip_direction();
956 auto&& scratch = state.wolfe_info.scratch_;
957 proposal.eval_.alpha() = 1.0;
958 const bool proposal_valid
959 = update_fun(proposal, state.curr(), state.prev(), proposal.eval_,
960 state.wolfe_info.p_);
961 const bool cached_proposal_ok
962 = proposal_valid && std::isfinite(proposal.obj())
963 && std::isfinite(proposal.dir())
964 && proposal.alpha() > options.line_search.min_alpha;
965 if (!cached_proposal_ok) {
968 }
else if (options.line_search.max_iterations == 0) {
969 state.curr().update(proposal);
972 Eigen::VectorXd s = proposal.a() - state.prev().a();
974 = (-covariance * proposal.a() + covariance * proposal.theta_grad())
977 s, full_step_grad, state.prev_g, state.prev().alpha(),
978 state.wolfe_status.num_backtracks_, options.line_search.min_alpha,
979 options.line_search.max_alpha);
981 state.wolfe_info, update_fun, options.line_search, msgs);
983 bool search_failed = !state.wolfe_status.accept_;
984 const bool proposal_armijo_ok
987 proposal.obj(), state.prev().obj(), proposal.alpha(),
988 state.wolfe_info.init_dir_, options.line_search);
989 if (search_failed && proposal_armijo_ok) {
990 state.curr().update(proposal);
993 state.wolfe_status.num_backtracks_,
true};
994 search_failed =
false;
996 bool objective_converged
997 = state.wolfe_status.accept_
998 && std::abs(state.curr().obj() - state.prev().obj())
1000 finish_update = objective_converged || search_failed;
1002 if (finish_update) {
1003 if (!state.final_loop && state.wolfe_status.accept_) {
1005 state.final_loop =
true;
1006 state.update_next_step(options);
1009 return solver.build_result(state, solver.compute_log_determinant());
1011 state.update_next_step(options);
1017 "WARNING(laplace_marginal_density): max number of iterations: ")
1018 + std::to_string(options.max_num_steps) +
" exceeded.";
1020 return solver.build_result(state, solver.compute_log_determinant());
1034 std::ostream* msgs, std::string_view context,
1036 std::string_view failed_solver,
1037 std::string_view next_solver,
1038 const std::exception&
e) {
1040 std::ostringstream os;
1041 std::string msg_type = allow_fallthrough ?
"WARNING" :
"ERROR";
1042 os <<
"[" << context <<
"] " << msg_type <<
": solver fallback\n"
1043 <<
" " << std::left << std::setw(12) <<
"iteration:" << iter <<
"\n"
1044 <<
" " << std::left << std::setw(12) <<
"failed:" << failed_solver <<
"\n"
1045 <<
" " << std::left << std::setw(12) <<
"reason:" <<
e.what() <<
"\n"
1046 <<
" " << std::left << std::setw(12) <<
"action:"
1047 <<
"trying " << next_solver <<
"\n"
1048 <<
"note: this warning message will only be displayed once."
1050 if (allow_fallthrough && msgs) {
1051 (*msgs) << os.str();
1053 throw std::domain_error(std::string(
"[") + std::string(context) +
"]");
1057template <
bool InitTheta,
typename Opts>
1059 if constexpr (InitTheta) {
1061 return std::decay_t<decltype(options)>(options).theta_0;
1063 return Eigen::MatrixXd::Zero(theta_size, 1);
1085template <
typename ObjFun,
typename ThetaGradFun,
typename Covariance,
1088 Covariance&& covariance, Options&& options) {
1089 auto update_step = [&covariance, &obj_fun, &theta_grad_f](
1090 auto& proposal,
auto&& ,
auto&& prev,
1091 auto& eval_in,
auto&& p) {
1093 proposal.a() = prev.a() + eval_in.alpha() * p;
1094 proposal.theta().noalias() = covariance * proposal.a();
1095 proposal.theta_grad() = theta_grad_f(proposal.theta());
1096 eval_in.obj() = obj_fun(proposal.a(), proposal.theta());
1098 = (-covariance * proposal.a() + covariance * proposal.theta_grad())
1100 return std::isfinite(eval_in.obj()) && std::isfinite(eval_in.dir());
1101 }
catch (
const std::exception&) {
1105 auto backoff = [&options](
auto&
eval) {
1106 eval.alpha() *= options.line_search.tau;
1107 return eval.alpha() > options.line_search.min_alpha;
1110 [update_step_ = std::move(update_step), backoff_ = std::move(backoff)](
1111 auto& proposal,
auto&& curr,
auto&& prev,
auto& eval_in,
auto&& p) {
1113 eval_in, p, backoff_);
1169template <
typename LLFun,
typename LLTupleArgs,
typename CovarMat,
1173 LLFun&& ll_fun, LLTupleArgs&& ll_args, CovarMat&& covariance,
1177 const Eigen::Index theta_size = covariance.rows();
1179 auto obj_fun = [&ll_fun, &ll_args, &msgs](
const Eigen::VectorXd& a_val,
1180 auto&& theta_val) ->
double {
1181 return -0.5 * a_val.dot(theta_val)
1185 auto theta_grad_f = [&ll_fun, &ll_args, &msgs](
auto&& theta_val) {
1188 decltype(
auto) theta_init = theta_init_impl<InitTheta>(theta_size, options);
1195 =
NewtonState(theta_size, obj_fun, theta_grad_f, covariance, theta_init);
1198 std::move(obj_fun), std::move(theta_grad_f), covariance, options);
1199 Eigen::Index step_iter = 0;
1201 if (options.solver == 1) {
1202 if (options.hessian_block_size == 1) {
1205 ll_args, covariance, update_fun, msgs);
1209 ll_args, covariance, update_fun, msgs);
1212 }
catch (
const std::exception&
e) {
1213 const std::string solver_type
1214 = (options.hessian_block_size == 1) ?
"Diagonal" :
"Block";
1215 std::string failed =
"solver 1 (" + solver_type +
" Hessian-root Cholesky)";
1218 [](
auto&&... args) {
1221 options.allow_fallthrough, msgs,
"laplace_marginal_density", step_iter,
1222 std::move(failed),
"solver 2 (Covariance-root Cholesky)",
e);
1225 if (options.solver == 2 || options.allow_fallthrough) {
1227 return run_newton_loop(solver, state, options, step_iter, ll_fun, ll_args,
1228 covariance, update_fun, msgs);
1230 }
catch (
const std::exception&
e) {
1233 [](
auto&&... args) {
1236 options.allow_fallthrough, msgs,
"laplace_marginal_density", step_iter,
1237 "solver 2 (Covariance-root Cholesky)",
"solver 3 (General LU solver)",
1240 if (options.solver == 3 || options.allow_fallthrough) {
1242 return run_newton_loop(solver, state, options, step_iter, ll_fun, ll_args,
1243 covariance, update_fun, msgs);
1245 throw std::domain_error(
1246 std::string(
"You chose a solver (") + std::to_string(options.solver)
1247 +
") that is not valid. Please choose either 1, 2, or 3.");
int64_t size(const T &m)
Returns the size (number of the elements) of a matrix_cl or var_value<matrix_cl<T>>.
(Expert) Numerical traits for algorithmic differentiation variables.
WolfeStatus wolfe_line_search(Info &wolfe_info, UpdateFun &&update_fun, Options &&opt, Stream *msgs)
Strong Wolfe line search for maximization.
auto create_update_fun(ObjFun &&obj_fun, ThetaGradFun &&theta_grad_f, Covariance &&covariance, Options &&options)
Create the update function for the line search, capturing necessary references.
auto run_newton_loop(SolverPolicy &solver, NewtonStateT &state, const OptionsT &options, Eigen::Index &step_iter, const LLFunT &ll_fun, const LLTupleArgsT &ll_args, const CovarMatT &covariance, UpdateFun &&update_fun, std::ostream *msgs)
Run a Newton loop with a solver policy, updating the shared state.
double barzilai_borwein_step_size(const Eigen::VectorXd &s, const Eigen::VectorXd &g_curr, const Eigen::VectorXd &g_prev, double prev_step, int last_backtracks, double min_alpha, double max_alpha)
Curvature-aware Barzilai–Borwein (BB) step length with robust safeguards.
constexpr int laplace_default_max_num_steps
void log_solver_fallback(const bool allow_fallthrough, std::ostream *msgs, std::string_view context, Eigen::Index iter, std::string_view failed_solver, std::string_view next_solver, const std::exception &e)
Log a solver fallback event to the provided stream.
decltype(auto) theta_init_impl(Eigen::Index theta_size, Opts &&options)
auto check_armijo(double obj_next, double obj_init, double alpha_next, double dir0, Option &&opt)
constexpr double laplace_default_tolerance
constexpr int laplace_default_solver
constexpr auto tuple_to_laplace_options(Options &&ops)
constexpr int laplace_default_max_steps_line_search
constexpr int laplace_default_hessian_block_size
void validate_laplace_options(const char *frame_name, const laplace_options< InitTheta > &options, const CovarMat &covariance)
Validates the options for the Laplace approximation.
constexpr int laplace_default_allow_fallthrough
auto retry_evaluate(Update &&update, Proposal &&proposal, Curr &&curr, Prev &&prev, Eval &eval, P &&p, Backoff &&backoff)
Retry evaluation of a step until it passes a validity check.
auto laplace_marginal_density_est(LLFun &&ll_fun, LLTupleArgs &&ll_args, CovarMat &&covariance, const laplace_options< InitTheta > &options, std::ostream *msgs)
For a latent Gaussian model with hyperparameters phi and latent variables theta, and observations y,...
void llt_with_jitter(LLT &llt_B, B_t &B, double min_jitter=1e-10, double max_jitter=1e-5)
Factorize B with jittering fallback.
void block_matrix_sqrt(WRootMat &W_root, const Eigen::SparseMatrix< double > &W, const Eigen::Index block_size)
Returns the principal square root of a block diagonal matrix.
static thread_local std::once_flag fallback_warning
auto diagonal_hessian(F &&f, Theta &&theta, TupleArgs &&ll_tuple, Stream *msgs)
auto log_likelihood(F &&f, Theta &&theta, TupleArgs &&ll_tup, Stream *msgs)
A wrapper that accepts a tuple as arguments.
auto block_hessian(F &&f, Theta &&theta, const Eigen::Index hessian_block_size, TupleArgs &&ll_tuple, Stream *msgs)
auto theta_grad(F &&f, Theta &&theta, TupleArgs &&ll_tup, Stream *msgs=nullptr)
A wrapper that accepts a tuple as arguments.
void check_square(const char *function, const char *name, const T_y &y)
Check if the specified matrix is square.
void check_nonnegative(const char *function, const char *name, const T_y &y)
Check if y is non-negative.
static constexpr double e()
Return the base of the natural logarithm.
T eval(T &&arg)
Inputs which have a plain_type equal to the own time are forwarded unmodified (for Eigen expressions ...
T value_of(const fvar< T > &v)
Return the value of the specified variable.
void check_finite(const char *function, const char *name, const T_y &y)
Return true if all values in y are finite.
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
void check_positive(const char *function, const char *name, const T_y &y)
Check if y is positive.
double dot(const std::vector< double > &x, const std::vector< double > &y)
constexpr bool is_inner_tuple_type_v
Checks if the N-th element of a tuple is of the same type as CheckType.
std::enable_if_t< Check::value > require_t
If condition is true, template is enabled.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
void solve_step(NewtonStateT &state, const LLFun &ll_fun, const LLTupleArgs &ll_args, const CovarMat &covariance, int hessian_block_size, std::ostream *msgs)
Perform one Newton step using covariance Cholesky solver.
Eigen::MatrixXd K_root
Lower Cholesky factor of covariance: Sigma = K_root * K_root^T.
Eigen::LLT< Eigen::MatrixXd > llt_B
Cholesky factorization of B = I + K_root^T * W * K_root.
Eigen::SparseMatrix< double > W_full
Full (block) Hessian matrix from likelihood.
double compute_log_determinant() const
Compute log determinant of B from Cholesky factor.
auto build_result(NewtonStateT &state, double log_det)
Build the final result structure.
CholeskyKSolver(const NewtonStateT &state, const CovarMat &covariance)
Solver Policy 2: Cholesky decomposition of K (Covariance).
Eigen::LLT< Eigen::MatrixXd > llt_B
Cholesky factorization of B = I + W_r * Sigma * W_r.
Eigen::SparseMatrix< double > W_block
Sparse block-diagonal Hessian from likelihood.
Eigen::SparseMatrix< double > W_r
Sparse square root of block Hessian.
double compute_log_determinant() const
Compute log determinant of B from Cholesky factor.
void solve_step(NewtonStateT &state, const LLFun &ll_fun, const LLTupleArgs &ll_args, const CovarMat &covariance, int hessian_block_size, std::ostream *msgs)
Perform one Newton step using block-diagonal Hessian solver.
auto build_result(NewtonStateT &state, double log_det)
Build the final result structure.
CholeskyWSolverBlock(const NewtonStateT &state, int hessian_block_size)
Solver Policy 1 (Block): Cholesky decomposition using block W.
void solve_step(NewtonStateT &state, const LLFun &ll_fun, const LLTupleArgs &ll_args, const CovarMat &covariance, int, std::ostream *msgs)
Perform one Newton step using diagonal Hessian solver.
Eigen::LLT< Eigen::MatrixXd > llt_B
Cholesky factorization of B = I + W_r * Sigma * W_r.
CholeskyWSolverDiag(const NewtonStateT &state, const CovarMat &covariance)
Eigen::VectorXd W_r_diag
Square root of diagonal Hessian: W_r[j] = sqrt(W[j])
auto build_result(NewtonStateT &state, double log_det)
Build the final result structure.
Eigen::VectorXd W_diag
Diagonal Hessian values from the likelihood.
double compute_log_determinant() const
Compute log determinant of B from Cholesky factor.
Solver Policy 1 (Diagonal): Cholesky decomposition using W.
auto build_result(NewtonStateT &state, double log_det)
Build the final result structure.
void solve_step(NewtonStateT &state, const LLFun &ll_fun, const LLTupleArgs &ll_args, const CovarMat &covariance, int hessian_block_size, std::ostream *msgs)
Perform one Newton step using LU decomposition solver.
double compute_log_determinant() const
Compute log determinant from LU factorization.
Eigen::SparseMatrix< double > W_full
Full Hessian matrix from likelihood.
Eigen::PartialPivLU< Eigen::MatrixXd > lu
LU factorization of B = I + Sigma * W.
Solver Policy 3: LU Decomposition.
WolfeData proposal
Cached proposal evaluated before the Wolfe line search.
auto & prev() &
Access the previous step state (mutable).
Eigen::MatrixXd B
Workspace matrix: B = I + W_r * Sigma * W_r (or similar)
auto && proposal_step() &&
WolfeStatus wolfe_status
Status of the most recent Wolfe line search.
auto & curr() &
Access the current step state (mutable).
Eigen::VectorXd b
Workspace vector: b = W * theta + grad(log_lik)
const auto & proposal_step() const &
void update_next_step(const Options &options)
WolfeInfo wolfe_info
Wolfe line search state including current/previous steps.
const auto & curr() const &
Access the current step state (const).
NewtonState(int theta_size, ObjFun &&obj_fun, ThetaGradFun &&theta_grad_f, CovarianceT &&covariance, ThetaInitializer &&theta_init)
Constructs Newton state with a consistent (a_init, theta_init) pair.
Eigen::VectorXd prev_g
Previous gradient for Barzilai-Borwein step calculation.
bool final_loop
On the final loop if we found a better wolfe step, but we are going to exit, we want to make sure all...
const auto & prev() const &
Access the previous step state (const).
Holds the state for the Newton-Raphson optimization loop.
Data used in current evaluation of wolfe line search at a particular stepsize.
Data object used in wolfe line search.
Struct to hold the result status of the Wolfe line search.
L_t L
Solver-dependent factorization of the system matrix B.
KRoot K_root
Lower Cholesky factor of the covariance matrix.
WR W_r
Solver-dependent Hessian quantity.
A_vec a
Mode in the a parameterization, where theta = covariance * a.
ThetaGrad theta_grad
Gradient of the log-likelihood with respect to theta at the mode.
laplace_density_estimates(double lmd_, ThetaVec &&theta_, WR &&W_r_, L_t &&L_, A_vec &&a_, ThetaGrad &&theta_grad_, LU_t &&LU_, KRoot &&K_root_, int solver_used_)
Options for Wolfe line search during optimization.
laplace_options(int hessian_block_size_)
laplace_options()=default
laplace_options(ThetaVec &&theta_0_, double tolerance_, int max_num_steps_, int hessian_block_size_, int solver_, int max_steps_line_search_, bool allow_fallthrough_)
double tolerance
Iterations end when the absolute change in the optimization objective is less than this tolerance.
int solver
Which linear solver to use inside the Newton step.
laplace_options_base()=default
laplace_line_search_options line_search
laplace_options_base(int hessian_block_size_, int solver_, double tolerance_, int max_num_steps_, bool allow_fallthrough_, int max_steps_line_search_)
Options for the Laplace approximation.