1 #ifndef STAN_MATH_PRIM_MAT_FUN_TRACE_GEN_INV_QUAD_FORM_LDLT_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_TRACE_GEN_INV_QUAD_FORM_LDLT_HPP
3
4 #include <stan/math/prim/mat/fun/Eigen.hpp>
5 #include <stan/math/prim/mat/fun/LDLT_factor.hpp>
6 #include <stan/math/prim/mat/err/check_multiplicable.hpp>
7 #include <stan/math/prim/mat/err/check_square.hpp>
8 #include <stan/math/prim/mat/fun/mdivide_left_ldlt.hpp>
9 #include <stan/math/prim/mat/fun/trace.hpp>
10 #include <stan/math/prim/mat/fun/transpose.hpp>
11 #include <stan/math/prim/mat/fun/multiply.hpp>
12 #include <stan/math/prim/scal/meta/is_var.hpp>
13
14 namespace stan {
15 namespace math {
16
17 /*
18 * Compute the trace of an inverse quadratic form. I.E., this computes
19 * trace(D B^T A^-1 B)
20 * where D is a square matrix and the LDLT_factor of A is provided.
21 */
22 template <typename T1, typename T2, typename T3, int R1, int C1, int R2, int C2,
23 int R3, int C3>
24 inline typename std::enable_if<
25 !stan::is_var<T1>::value && !stan::is_var<T2>::value
26 && !stan::is_var<T3>::value,
27 typename boost::math::tools::promote_args<T1, T2, T3>::type>::type
trace_gen_inv_quad_form_ldlt(const Eigen::Matrix<T1,R1,C1> & D,const LDLT_factor<T2,R2,C2> & A,const Eigen::Matrix<T3,R3,C3> & B)28 trace_gen_inv_quad_form_ldlt(const Eigen::Matrix<T1, R1, C1> &D,
29 const LDLT_factor<T2, R2, C2> &A,
30 const Eigen::Matrix<T3, R3, C3> &B) {
31 check_square("trace_gen_inv_quad_form_ldlt", "D", D);
32 check_multiplicable("trace_gen_inv_quad_form_ldlt", "A", A, "B", B);
33 check_multiplicable("trace_gen_inv_quad_form_ldlt", "B", B, "D", D);
34
35 return trace(multiply(multiply(D, transpose(B)), mdivide_left_ldlt(A, B)));
36 }
37
38 } // namespace math
39 } // namespace stan
40 #endif
41