Automatic Differentiation
 
Loading...
Searching...
No Matches
csr_extract.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_PRIM_FUN_CSR_EXTRACT_HPP
2#define STAN_MATH_PRIM_FUN_CSR_EXTRACT_HPP
3
6
7namespace stan {
8namespace math {
9
22template <typename T>
23const std::tuple<Eigen::Matrix<T, Eigen::Dynamic, 1>, std::vector<int>,
24 std::vector<int>>
25csr_extract(const Eigen::SparseMatrix<T, Eigen::RowMajor>& A) {
26 auto a_nonzeros = A.nonZeros();
27 Eigen::Matrix<T, Eigen::Dynamic, 1> w
28 = Eigen::Matrix<T, Eigen::Dynamic, 1>::Zero(a_nonzeros);
29 std::vector<int> v(a_nonzeros);
30 for (int nze = 0; nze < a_nonzeros; ++nze) {
31 w[nze] = *(A.valuePtr() + nze);
32 v[nze] = *(A.innerIndexPtr() + nze) + stan::error_index::value;
33 }
34 std::vector<int> u(A.outerSize() + 1); // last entry is garbage.
35 for (int nze = 0; nze <= A.outerSize(); ++nze) {
36 u[nze] = *(A.outerIndexPtr() + nze) + stan::error_index::value;
37 }
38 return std::make_tuple(std::move(w), std::move(v), std::move(u));
39}
40
41/* Extract the non-zero values from a dense matrix by converting
42 * to sparse and calling the sparse matrix extractor.
43 *
44 * @tparam T type of elements in the matrix
45 * @tparam R number of rows, can be Eigen::Dynamic
46 * @tparam C number of columns, can be Eigen::Dynamic
47 *
48 * @param[in] A dense matrix.
49 * @return a tuple W,V,U.
50 */
51template <typename T, require_eigen_dense_base_t<T>* = nullptr>
52const std::tuple<Eigen::Matrix<scalar_type_t<T>, Eigen::Dynamic, 1>,
53 std::vector<int>, std::vector<int>>
54csr_extract(const T& A) {
55 // conversion to sparse seems to touch data twice, so we need to call to_ref
56 Eigen::SparseMatrix<scalar_type_t<T>, Eigen::RowMajor> B
57 = to_ref(A).sparseView();
58 return csr_extract(B);
59}
60 // end of csr_format group
62
63} // namespace math
64} // namespace stan
65
66#endif
const std::tuple< Eigen::Matrix< T, Eigen::Dynamic, 1 >, std::vector< int >, std::vector< int > > csr_extract(const Eigen::SparseMatrix< T, Eigen::RowMajor > &A)
Extract the non-zero values, column indexes for non-zero values, and the NZE index for each entry fro...
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:17
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...