1 #ifndef STAN_MATH_PRIM_FUN_CSR_EXTRACT_W_HPP
2 #define STAN_MATH_PRIM_FUN_CSR_EXTRACT_W_HPP
3 
4 #include <stan/math/prim/fun/Eigen.hpp>
5 #include <stan/math/prim/fun/to_ref.hpp>
6 
7 namespace stan {
8 namespace math {
9 
10 /** \addtogroup csr_format
11  *  @{
12  */
13 
14 /* Extract the non-zero values from a sparse matrix.
15  *
16  * @tparam T type of elements in the matrix
17  * @param[in] A sparse matrix.
18  * @return Vector of non-zero entries of A.
19  */
20 template <typename T>
csr_extract_w(const Eigen::SparseMatrix<T,Eigen::RowMajor> & A)21 const Eigen::Matrix<T, Eigen::Dynamic, 1> csr_extract_w(
22     const Eigen::SparseMatrix<T, Eigen::RowMajor>& A) {
23   Eigen::Matrix<T, Eigen::Dynamic, 1> w(A.nonZeros());
24   w.setZero();
25   for (int nze = 0; nze < A.nonZeros(); ++nze) {
26     w[nze] = *(A.valuePtr() + nze);
27   }
28   return w;
29 }
30 
31 /* Extract the non-zero values from a dense matrix by converting
32  * to sparse and calling the sparse matrix extractor.
33  *
34  * @tparam T type of elements in the matrix
35  * @tparam R number of rows, can be Eigen::Dynamic
36  * @tparam C number of columns, can be Eigen::Dynamic
37  *
38  * @param[in] A dense matrix.
39  * @return Vector of non-zero entries of A.
40  */
41 template <typename T, require_eigen_dense_base_t<T>* = nullptr>
csr_extract_w(const T & A)42 const Eigen::Matrix<scalar_type_t<T>, Eigen::Dynamic, 1> csr_extract_w(
43     const T& A) {
44   // conversion to sparse seems to touch data twice, so we need to call to_ref
45   Eigen::SparseMatrix<scalar_type_t<T>, Eigen::RowMajor> B
46       = to_ref(A).sparseView();
47   return csr_extract_w(B);
48 }
49 
50 /** @} */  // end of csr_format group
51 
52 }  // namespace math
53 }  // namespace stan
54 
55 #endif
56