alpaqa 1.0.0a8
Nonconvex constrained optimization
Loading...
Searching...
No Matches
sparse-ops.hpp
Go to the documentation of this file.
1#pragma once
2
8
9#include <chrono>
10#include <iostream>
11#include <ranges>
12#include <span>
13
14#include <Eigen/Sparse>
15
16namespace alpaqa::util {
17
18namespace detail {
19
20/// Returns a range over the row indices in the given column of @p sp_mat that
21/// are also in @p mask.
22/// The range consists of the full Eigen InnerIterators (row, column, value).
23template <class SpMat, class MaskVec>
24auto select_rows_in_col(const SpMat &sp_mat, MaskVec &mask, auto column) {
25 // Make a range that iterates over all matrix elements in the given column:
26 using row_iter_t = typename SpMat::InnerIterator;
27 util::iter_range_adapter<row_iter_t> col_range{{sp_mat, column}};
28 // Projector that extracts the row index from an element of that range:
29 static constexpr auto proj_row = [](const row_iter_t &it) {
30 return static_cast<typename MaskVec::value_type>(it.row());
31 };
32 // Compute the intersection between the matrix elements and the mask:
33 auto intersection = util::iter_set_intersection(std::move(col_range),
34 std::ranges::ref_view{mask},
35 std::less{}, proj_row);
36 // Extract just the iterator to the matrix element (dropping the mask):
37 auto extract_eigen_iter = []<class T>(T &&tup) -> decltype(auto) {
38 return std::get<0>(std::forward<T>(tup));
39 };
40 return std::views::transform(std::move(intersection), extract_eigen_iter);
41}
42
43/// Like @ref select_rows_in_col, but returns a range of tuples containing the
44/// Eigen InnerIterator and a linear index into the mask.
45template <class SpMat, class MaskVec>
46auto select_rows_in_col_iota(const SpMat &sp_mat, MaskVec &mask, auto column) {
47 // Make a range that iterates over all matrix elements in the given column:
48 using row_iter_t = typename SpMat::InnerIterator;
49 util::iter_range_adapter<row_iter_t> col_range{{sp_mat, column}};
50 // Projector that extracts the row index from an element of that range:
51 static constexpr auto proj_row = [](const row_iter_t &it) {
52 return static_cast<typename MaskVec::value_type>(it.row());
53 };
54 // Make a range of tuples of the index into the mask and the mask value:
55 auto iota_mask = util::enumerate(std::ranges::ref_view{mask});
56 // Projector that extracts the mask value from such a tuple:
57 static constexpr auto proj_mask = [](const auto &tup) -> decltype(auto) {
58 return std::get<1>(tup);
59 };
60 // Compute the intersection between the matrix elements and the mask:
61 auto intersection =
62 util::iter_set_intersection(std::move(col_range), std::move(iota_mask),
63 std::less{}, proj_row, proj_mask);
64 // Extract the iterator to the matrix element and the index into the mask:
65 auto extract_eigen_iter_and_index = []<class T>(T && tup)
66 requires(std::is_rvalue_reference_v<T &&>)
67 {
68 auto &[eigen_iter, enum_tup] = tup;
69 auto &mask_index = std::get<0>(enum_tup);
70 return std::tuple{std::move(eigen_iter), std::move(mask_index)};
71 };
72 return std::views::transform(std::move(intersection),
73 extract_eigen_iter_and_index);
74}
75
76} // namespace detail
77
78/// R += R_full(mask,mask)
79template <class SpMat, class Mat, class MaskVec>
80void sparse_add_masked(const SpMat &R_full, Mat &&R, const MaskVec &mask) {
81 // Iterate over all columns in the mask
82 for (auto [ci, c] : util::enumerate(mask))
83 // Iterate over rows in intersection of mask and sparse column
84 for (auto [r, ri] : detail::select_rows_in_col_iota(R_full, mask, c))
85 R(ri, ci) += r.value();
86}
87
88/// S += S_full(mask,:)
89template <class SpMat, class Mat, class MaskVec>
90void sparse_add_masked_rows(const SpMat &S_full, Mat &&S, const MaskVec &mask) {
91 using index_t = typename SpMat::Index;
92 // Iterate over all columns
93 for (index_t c = 0; c < S_full.cols(); ++c)
94 // Iterate over rows in intersection of mask and sparse column
95 for (auto [r, ri] : detail::select_rows_in_col_iota(S_full, mask, c))
96 S(ri, c) += r.value();
97}
98
99/// out += R(mask_J,mask_K) * v(mask_K);
100template <class SpMat, class CVec, class Vec, class MaskVec>
101void sparse_matvec_add_masked_rows_cols(const SpMat &R, const CVec &v,
102 Vec &&out, const MaskVec &mask_J,
103 const MaskVec &mask_K) {
105 // Iterate over all columns in the mask K
106 for (auto c : mask_K)
107 // Iterate over rows in intersection of mask J and sparse column
108 for (auto &&[r, ri] : select_rows_in_col_iota(R, mask_J, c))
109 out(ri) += r.value() * v(c);
110}
111
112/// out += S(mask,:)ᵀ * v(mask);
113template <class SpMat, class CVec, class Vec, class MaskVec>
114void sparse_matvec_add_transpose_masked_rows(const SpMat &S, const CVec &v,
115 Vec &&out, const MaskVec &mask) {
116 using index_t = typename SpMat::Index;
117 // Iterate over all rows of Sᵀ
118 for (index_t c = 0; c < S.cols(); ++c)
119 // Iterate over columns in intersection of mask K and sparse row
120 for (auto r : detail::select_rows_in_col(S, mask, c))
121 out(c) += r.value() * v(r.row());
122}
123
124#if __cpp_lib_ranges_zip >= 202110L && __cpp_lib_ranges_enumerate >= 202302L
125
126template <Config Conf>
127void convert_triplets_to_ccs(const auto &rows, const auto &cols,
128 rindexvec<Conf> inner_idx,
129 rindexvec<Conf> outer_ptr,
130 index_t<Conf> idx_0 = 0) {
132 // Inner indices: simply the row indices
133 assert(std::size(rows) == std::size(inner_idx));
134 auto cvt_indices = [&](auto i) { return static_cast<index_t>(i) - idx_0; };
135 std::ranges::ref_view rows_vw = rows;
136 std::ranges::transform(rows_vw, std::begin(inner_idx), cvt_indices);
137 // Outer indices: need to count the number of nonzeros per column
138 auto cols_iter = std::begin(cols);
139 for (auto &&[i, outer] : std::views::enumerate(outer_ptr)) {
140 cols_iter = std::lower_bound(cols_iter, std::end(cols), i + idx_0);
141 outer = static_cast<index_t>(cols_iter - std::begin(cols));
142 }
143}
144
145/// Sort the (row, column, value) triplets, column first, then row.
146template <class... Ts>
147void sort_triplets(Ts &&...triplets) {
148 // Sort the indices (column first, then row)
149 auto cmp = [](const auto &a, const auto &b) {
150 return std::tie(std::get<1>(a), std::get<0>(a)) <
151 std::tie(std::get<1>(b), std::get<0>(b));
152 };
153 auto indices = std::views::zip(std::ranges::ref_view{triplets}...);
154 auto t0 = std::chrono::steady_clock::now();
155 std::ranges::sort(indices, cmp);
156 auto t1 = std::chrono::steady_clock::now();
157 std::cout << "Sorting took: "
158 << std::chrono::duration<double>{t1 - t0}.count() * 1e6
159 << " µs\n";
160}
161
162#endif
163
164} // namespace alpaqa::util
#define USING_ALPAQA_CONFIG(Conf)
Definition: config.hpp:42
auto select_rows_in_col(const SpMat &sp_mat, MaskVec &mask, auto column)
Returns a range over the row indices in the given column of sp_mat that are also in mask.
Definition: sparse-ops.hpp:24
auto select_rows_in_col_iota(const SpMat &sp_mat, MaskVec &mask, auto column)
Like select_rows_in_col, but returns a range of tuples containing the Eigen InnerIterator and a linea...
Definition: sparse-ops.hpp:46
void sparse_matvec_add_masked_rows_cols(const SpMat &R, const CVec &v, Vec &&out, const MaskVec &mask_J, const MaskVec &mask_K)
out += R(mask_J,mask_K) * v(mask_K);
Definition: sparse-ops.hpp:101
void sparse_add_masked_rows(const SpMat &S_full, Mat &&S, const MaskVec &mask)
S += S_full(mask,:)
Definition: sparse-ops.hpp:90
auto enumerate(Rng &&rng)
Definition: enumerate.hpp:66
void sparse_add_masked(const SpMat &R_full, Mat &&R, const MaskVec &mask)
R += R_full(mask,mask)
Definition: sparse-ops.hpp:80
void sparse_matvec_add_transpose_masked_rows(const SpMat &S, const CVec &v, Vec &&out, const MaskVec &mask)
out += S(mask,:)ᵀ * v(mask);
Definition: sparse-ops.hpp:114
set_intersection_iterable< std::ranges::views::all_t< R1 >, std::ranges::views::all_t< R2 >, Comp, Proj1, Proj2 > iter_set_intersection(R1 &&r1, R2 &&r2, Comp comp={}, Proj1 proj1={}, Proj2 proj2={})
typename Conf::rindexvec rindexvec
Definition: config.hpp:65
typename Conf::index_t index_t
Definition: config.hpp:63