tatami
C++ API for different matrix representations
Loading...
Searching...
No Matches
convert_to_compressed_sparse.hpp
Go to the documentation of this file.
1#ifndef TATAMI_CONVERT_TO_COMPRESSED_SPARSE_H
2#define TATAMI_CONVERT_TO_COMPRESSED_SPARSE_H
3
4#include <memory>
5#include <vector>
6#include <cstddef>
7#include <optional>
8
11#include "convert_to_sparse_utils.hpp"
12
17#include "../utils/copy.hpp"
18
25namespace tatami {
26
30template<typename Value_, typename Index_, typename Count_>
31void count_compressed_sparse_non_zeros_consistent(
33 const Index_ primary,
34 const Index_ secondary,
35 const bool row,
36 Count_* const output,
37 const int threads
38) {
39 sanisizer::cast<Count_>(secondary); // confirm that the counts don't overflow the Count_.
40
41 if (matrix.is_sparse()) {
42 Options opt;
43 opt.sparse_extract_value = false;
44 opt.sparse_extract_index = false;
45 opt.sparse_ordered_index = false;
46
47 parallelize([&](const int, const Index_ start, const Index_ length) -> void {
48 auto wrk = make_Extractor<true, true>(matrix, row, make_ConsecutiveOracle(start, length), opt);
49 for (Index_ x = 0; x < length; ++x) {
50 const auto range = wrk->fetch(NULL, NULL);
51 output[start + x] = range.number;
52 }
53 }, primary, threads);
54
55 } else {
56 parallelize([&](const int, const Index_ start, const Index_ length) -> void {
57 auto buffer_v = create_container_of_Index_size<std::vector<Value_> >(secondary);
58 auto wrk = make_Extractor<false, true>(matrix, row, make_ConsecutiveOracle(start, length), Options());
59 for (Index_ p = start, pe = start + length; p < pe; ++p) {
60 const auto ptr = wrk->fetch(buffer_v.data());
61 Count_ count = 0;
62 for (Index_ s = 0; s < secondary; ++s) {
63 count += (ptr[s] != 0);
64 }
65 output[p] = count;
66 }
67 }, primary, threads);
68 }
69}
70
71// For back-compatiblity only, this functionality should probably not have been exported.
72// It's not even entirely correct as we only count structural non-zeros in the sparse case,
73// so it's hard to think of a case where someone would want to use this.
74struct CountCompressedSparseNonZerosOptions {
75 int num_threads = 1;
76};
77
78// For back-compatiblity only, see above.
79template<typename Value_, typename Index_, typename Count_>
80void count_compressed_sparse_non_zeros(
82 const bool row,
83 Count_* const output,
84 const CountCompressedSparseNonZerosOptions& options
85) {
86 const Index_ NR = matrix.nrow();
87 const Index_ NC = matrix.ncol();
88 const Index_ primary = (row ? NR : NC);
89 const Index_ secondary = (row ? NC : NR);
90
91 if (row == matrix.prefer_rows()) {
92 count_compressed_sparse_non_zeros_consistent(matrix, primary, secondary, row, output, options.num_threads);
93 } else {
94 std::fill_n(output, primary, 0);
95 count_sparse_non_zeros_inconsistent(matrix, primary, secondary, row, output, options.num_threads);
96 }
97}
98
99template<typename InputValue_, typename InputIndex_, typename Pointer_, typename StoredValue_, typename StoredIndex_>
100void fill_compressed_sparse_matrix_consistent(
102 const InputIndex_ primary,
103 const InputIndex_ secondary,
104 const bool row,
105 const Pointer_* const pointers,
106 StoredValue_* const output_value,
107 StoredIndex_* const output_index,
108 const int threads
109) {
110 if (matrix.is_sparse()) {
111 Options opt;
112 opt.sparse_ordered_index = false;
113
114 parallelize([&](const int, const InputIndex_ start, const InputIndex_ length) -> void {
115 auto wrk = make_Extractor<true, true>(matrix, row, make_ConsecutiveOracle(start, length), opt);
118
119 for (InputIndex_ p = start, pe = start + length; p < pe; ++p) {
120 // Resist the urge to `fetch()` straight into 'output_v'
121 // and 'output_i', as implementations may assume that they
122 // have the entire 'length' length to play with, and the
123 // output vectors only have whatever is allocated from the
124 // first pass (which might be nothing for an all-zero matrix).
125 const auto range = wrk->fetch(buffer_v.data(), buffer_i.data());
126 const auto offset = pointers[p];
127 std::copy_n(range.value, range.number, output_value + offset);
128 std::copy_n(range.index, range.number, output_index + offset);
129 }
130 }, primary, threads);
131
132 } else {
133 parallelize([&](const int, const InputIndex_ start, const InputIndex_ length) -> void {
135 auto wrk = make_Extractor<false, true>(matrix, row, make_ConsecutiveOracle(start, length), Options());
136
137 for (InputIndex_ p = start, pe = start + length; p < pe; ++p) {
138 const auto ptr = wrk->fetch(buffer_v.data());
139 auto offset = pointers[p];
140 for (InputIndex_ s = 0; s < secondary; ++s) {
141 const auto val = ptr[s];
142 if (val != 0) {
143 output_value[offset] = val;
144 output_index[offset] = s;
145 ++offset;
146 }
147 }
148 }
149 }, primary, threads);
150 }
151}
152
153template<typename InputValue_, typename InputIndex_, typename Pointer_, typename StoredValue_, typename StoredIndex_>
154void fill_compressed_sparse_matrix_inconsistent(
156 const InputIndex_ primary,
157 const InputIndex_ secondary,
158 const bool row,
159 const Pointer_* const output_ptrs,
160 StoredValue_* const output_value,
161 StoredIndex_* const output_index,
162 std::optional<CountNonZerosPerThread<InputIndex_, Pointer_> >& per_thread // see count_sparse_non_zeros_inconsistent() in convert_to_sparse_utils.hpp.
163) {
164 const bool is_sparse = matrix.is_sparse();
165 if (per_thread.has_value()) {
166 // Transforming the per-thread counts into per-thread starting offsets.
167 auto& offsets = per_thread->counts;
168 Pointer_ accumulant = 0;
169 static_assert(std::is_same<I<decltype(per_thread->counts[0][0])>, Pointer_>::value); // confirm that the accumulant assignment won't overflow.
170 for (InputIndex_ i = 0; i < primary; ++i) {
171 for (auto& pt : offsets) {
172 const auto count = pt[i];
173 pt[i] = accumulant;
174 accumulant += count;
175 }
176 }
177
178 parallelize([&](const int, const int th_start, const int th_length) -> void {
179 for (int t = 0; t < th_length; ++t) {
180 auto& offsets = (per_thread->counts)[t + th_start];
181 const auto actual_start = (per_thread->starts)[t + th_start];
182 const auto actual_length = (per_thread->lengths)[t + th_start];
183
184 // We're going to completely ignore the potential for false sharing here.
185 // False sharing would only be a risk for very fat/thin matrices (depending on row= and num_threads=),
186 // and if the input matrix is sparse, this further lowers the chance of contention between threads.
187 // The alternative would be to allocate a per-thread buffer to store all of the values,
188 // but in that case, we might as well use a one-pass algorithm.
189 if (is_sparse) {
190 Options opt;
191 opt.sparse_ordered_index = false;
192 auto wrk = make_Extractor<true, true>(matrix, !row, make_ConsecutiveOracle(actual_start, actual_length), opt);
195
196 for (InputIndex_ x = 0; x < actual_length; ++x) {
197 const auto range = wrk->fetch(buffer_v.data(), buffer_i.data());
198 for (InputIndex_ i = 0; i < range.number; ++i) {
199 auto& pos = offsets[range.index[i]];
200 output_value[pos] = range.value[i];
201 output_index[pos] = x + actual_start;
202 ++pos;
203 }
204 }
205
206 } else {
207 auto wrk = make_Extractor<false, true>(matrix, !row, make_ConsecutiveOracle(actual_start, actual_length), Options());
209 for (InputIndex_ x = 0; x < actual_length; ++x) {
210 const auto ptr = wrk->fetch(buffer_v.data());
211 for (InputIndex_ p = 0; p < primary; ++p) {
212 const auto val = ptr[p];
213 if (val != 0) {
214 auto& pos = offsets[p];
215 output_value[pos] = val;
216 output_index[pos] = x + actual_start;
217 ++pos;
218 }
219 }
220 }
221 }
222 }
223 }, per_thread->counts.size(), per_thread->counts.size());
224
225 } else {
226 std::vector<Pointer_> offsets(output_ptrs, output_ptrs + primary);
227
228 if (is_sparse){
229 Options opt;
230 opt.sparse_ordered_index = false;
231 auto wrk = make_Extractor<true, true>(matrix, !row, make_ConsecutiveOracle<InputIndex_>(0, secondary), opt);
234 for (InputIndex_ s = 0; s < secondary; ++s) {
235 const auto range = wrk->fetch(buffer_v.data(), buffer_i.data());
236 for (InputIndex_ i = 0; i < range.number; ++i) {
237 auto& pos = offsets[range.index[i]];
238 output_value[pos] = range.value[i];
239 output_index[pos] = s;
240 ++pos;
241 }
242 }
243
244 } else {
245 auto wrk = make_Extractor<false, true>(matrix, !row, make_ConsecutiveOracle<InputIndex_>(0, secondary), Options());
247 for (InputIndex_ s = 0; s < secondary; ++s) {
248 const auto ptr = wrk->fetch(buffer_v.data());
249 for (InputIndex_ p = 0; p < primary; ++p) {
250 const auto val = ptr[p];
251 if (val != 0) {
252 auto& pos = offsets[p];
253 output_value[pos] = val;
254 output_index[pos] = s;
255 ++pos;
256 }
257 }
258 }
259 }
260 }
261}
262
263// For back-compatiblity only, this functionality should probably not have been exported.
264// This is only useful in the context of retrieve_compressed_sparse_contents, so why would someone use this when they could just use retrieve?
265struct FillCompressedSparseContentsOptions {
266 int num_threads = 1;
267};
268
269// For back-compatiblity only, see above.
270template<typename InputValue_, typename InputIndex_, typename Pointer_, typename StoredValue_, typename StoredIndex_>
271void fill_compressed_sparse_contents(
273 const bool row,
274 const Pointer_* const pointers,
275 StoredValue_* const output_value,
276 StoredIndex_* const output_index,
277 const FillCompressedSparseContentsOptions& options
278) {
279 const InputIndex_ NR = matrix.nrow();
280 const InputIndex_ NC = matrix.ncol();
281 const InputIndex_ primary = (row ? NR : NC);
282 const InputIndex_ secondary = (row ? NC : NR);
283
284 if (row == matrix.prefer_rows()) {
285 fill_compressed_sparse_matrix_consistent(matrix, primary, secondary, row, pointers, output_value, output_index, options.num_threads);
286 } else {
287 std::optional<CountNonZerosPerThread<InputIndex_, Pointer_> > empty; // Force it to be single-threaded as we don't have the per-worker pointers to parallelize effectively.
288 fill_compressed_sparse_matrix_inconsistent(
289 matrix,
290 primary,
291 secondary,
292 row,
293 pointers,
294 output_value,
295 output_index,
296 empty
297 );
298 }
299}
314template<typename Value_, typename Index_, typename Pointer_>
319 std::vector<Value_> value;
320
324 std::vector<Index_> index;
325
329 std::vector<Pointer_> pointers;
330};
331
348
366template<typename StoredValue_, typename StoredIndex_, typename StoredPointer_ = std::size_t, typename InputValue_, typename InputIndex_>
369 const bool row,
371) {
372 // We use size_t as the default pointer type here, as our output consists of vectors
373 // with the default allocator, for which the size_type is unlikely to be bigger than size_t.
374
376 auto& output_v = output.value;
377 auto& output_i = output.index;
378 auto& output_p = output.pointers;
379
380 const InputIndex_ NR = matrix.nrow();
381 const InputIndex_ NC = matrix.ncol();
382 const InputIndex_ primary = (row ? NR : NC);
383 const InputIndex_ secondary = (row ? NC : NR);
384
385 output_p.resize(sanisizer::sum<I<decltype(output_p.size())> >(attest_for_Index(primary), 1));
386
387 if (!options.two_pass) {
388 // In the one-pass strategy, we load matrix contents along the preferred dimension first, then we transform it in serial.
389 std::vector<std::vector<InputValue_> > store_v;
390 std::vector<std::vector<InputIndex_> > store_i;
391 auto original_ranges = extract_sparse_matrix(matrix, store_v, store_i, options.num_threads);
392
393 const bool use_rows = matrix.prefer_rows();
394 if (use_rows == row) {
395 // Now concatenating everything together, if we're fortunate enough that the dimensions are consistent.
396 for (InputIndex_ p = 0; p < primary; ++p) {
397 output_p[p + 1] = sanisizer::sum<StoredPointer_>(output_p[p], original_ranges[p].number);
398 }
399
400 output_v.reserve(output_p.back());
401 output_i.reserve(output_p.back());
402 for (InputIndex_ p = 0; p < primary; ++p) {
403 output_v.insert(output_v.end(), original_ranges[p].value, original_ranges[p].value + original_ranges[p].number);
404 output_i.insert(output_i.end(), original_ranges[p].index, original_ranges[p].index + original_ranges[p].number);
405 }
406
407 } else {
408 // Otherwise we need to compute the non-zeros on the inconsistent dimension before populating the output vectors.
409 for (InputIndex_ s = 0; s < secondary; ++s) {
410 const auto& range = original_ranges[s];
411 for (InputIndex_ x = 0; x < range.number; ++x) {
412 output_p[range.index[x] + 1] += 1; // increments are safe at this point: p < primary and the total count must be less than 'secondary'.
413 }
414 }
415 for (InputIndex_ p = 0; p < primary; ++p) {
416 output_p[p + 1] = sanisizer::sum<StoredPointer_>(output_p[p + 1], output_p[p]);
417 }
418
419 sanisizer::resize(output_v, output_p.back());
420 sanisizer::resize(output_i, output_p.back());
421 std::vector<StoredPointer_> offsets(output_p.begin(), output_p.begin() + primary);
422 for (InputIndex_ s = 0; s < secondary; ++s) {
423 const auto& range = original_ranges[s];
424 for (InputIndex_ i = 0; i < range.number; ++i) {
425 auto& pos = offsets[range.index[i]];
426 output_v[pos] = range.value[i];
427 output_i[pos] = s;
428 ++pos;
429 }
430 }
431 }
432
433 } else if (row == matrix.prefer_rows()) {
434 // First pass to figure out how many non-zeros there are.
435 count_compressed_sparse_non_zeros_consistent(matrix, primary, secondary, row, output_p.data() + 1, options.num_threads);
436 for (InputIndex_ i = 1; i <= primary; ++i) {
437 output_p[i] = sanisizer::sum<StoredPointer_>(output_p[i], output_p[i - 1]);
438 }
439
440 // Second pass to actually fill our vectors.
441 sanisizer::resize(output_v, output_p.back());
442 sanisizer::resize(output_i, output_p.back());
443 fill_compressed_sparse_matrix_consistent(
444 matrix,
445 primary,
446 secondary,
447 row,
448 output_p.data(),
449 output_v.data(),
450 output_i.data(),
451 options.num_threads
452 );
453
454 } else {
455 // First pass to figure out how many non-zeros there are.
456 auto per_thread = count_sparse_non_zeros_inconsistent(matrix, primary, secondary, row, output_p.data() + 1, options.num_threads);
457 for (InputIndex_ i = 1; i <= primary; ++i) {
458 output_p[i] = sanisizer::sum<StoredPointer_>(output_p[i], output_p[i - 1]);
459 }
460
461 // Second pass to actually fill our vectors.
462 sanisizer::resize(output_v, output_p.back());
463 sanisizer::resize(output_i, output_p.back());
464 fill_compressed_sparse_matrix_inconsistent(
465 matrix,
466 primary,
467 secondary,
468 row,
469 output_p.data(),
470 output_v.data(),
471 output_i.data(),
472 per_thread
473 );
474 }
475
476 return output;
477}
478
488 bool two_pass = false;
489
493 int num_threads = 1;
494};
495
513template<
514 typename Value_,
515 typename Index_,
516 typename StoredValue_ = Value_,
517 typename StoredIndex_ = Index_,
518 typename StoredPointer_ = std::size_t,
519 typename InputValue_,
520 typename InputIndex_
521>
522std::shared_ptr<Matrix<Value_, Index_> > convert_to_compressed_sparse(
524 const bool row,
526) {
528 matrix,
529 row,
530 [&]{
532 ropt.two_pass = options.two_pass;
533 ropt.num_threads = options.num_threads;
534 return ropt;
535 }()
536 );
537 return std::shared_ptr<Matrix<Value_, Index_> >(
539 Value_,
540 Index_,
541 std::vector<StoredValue_>,
542 std::vector<StoredIndex_>,
543 std::vector<StoredPointer_>
544 >(
545 matrix.nrow(),
546 matrix.ncol(),
547 std::move(comp.value),
548 std::move(comp.index),
549 std::move(comp.pointers),
550 row,
551 []{
552 CompressedSparseMatrixOptions copt;
553 copt.check = false; // no need for checks, as we guarantee correctness.
554 return copt;
555 }()
556 )
557 );
558}
559
563// Backwards compatbility.
564template<typename Value_, typename Index_, typename Count_>
565void count_compressed_sparse_non_zeros(const tatami::Matrix<Value_, Index_>* matrix, bool row, Count_* output, int threads) {
566 return count_compressed_sparse_non_zeros(
567 *matrix,
568 row,
569 output,
570 [&]{
571 CountCompressedSparseNonZerosOptions copt;
572 copt.num_threads = threads;
573 return copt;
574 }()
575 );
576}
577
578template<typename InputValue_, typename InputIndex_, typename Pointer_, typename StoredValue_, typename StoredIndex_>
579void fill_compressed_sparse_contents(const tatami::Matrix<InputValue_, InputIndex_>* matrix,
580 bool row,
581 const Pointer_* pointers,
582 StoredValue_* output_value,
583 StoredIndex_* output_index,
584 int threads)
585{
586 fill_compressed_sparse_contents(
587 *matrix,
588 row,
589 pointers,
590 output_value,
591 output_index,
592 [&]{
593 FillCompressedSparseContentsOptions fopt;
594 fopt.num_threads = threads;
595 return fopt;
596 }()
597 );
598}
599
600template<typename StoredValue_, typename StoredIndex_, typename StoredPointer_ = std::size_t, typename InputValue_, typename InputIndex_>
601CompressedSparseContents<StoredValue_, StoredIndex_, StoredPointer_> retrieve_compressed_sparse_contents(const Matrix<InputValue_, InputIndex_>* matrix, bool row, bool two_pass, int threads = 1) {
603 *matrix,
604 row,
605 [&]{
606 RetrieveCompressedSparseContentsOptions opt;
607 opt.two_pass = two_pass;
608 opt.num_threads = threads;
609 return opt;
610 }()
611 );
612}
613
614template<typename Value_ = double, typename Index_ = int, typename StoredValue_ = Value_, typename StoredIndex_ = Index_, typename InputValue_, typename InputIndex_>
615std::shared_ptr<Matrix<Value_, Index_> > convert_to_compressed_sparse(const Matrix<InputValue_, InputIndex_>* matrix, bool row, bool two_pass = false, int threads = 1) {
617 *matrix,
618 row,
619 [&]{
620 ConvertToCompressedSparseOptions opt;
621 opt.two_pass = two_pass;
622 opt.num_threads = threads;
623 return opt;
624 }()
625 );
626}
627
628template <bool row_, typename Value_, typename Index_, typename InputValue_, typename InputIndex_>
629CompressedSparseContents<Value_, Index_, std::size_t> retrieve_compressed_sparse_contents(const Matrix<InputValue_, InputIndex_>* matrix, bool two_pass, int threads = 1) {
630 return retrieve_compressed_sparse_contents<Value_, Index_>(matrix, row_, two_pass, threads);
631}
632
633template <bool row_, typename Value_, typename Index_, typename StoredValue_ = Value_, typename StoredIndex_ = Index_, typename InputValue_, typename InputIndex_>
634std::shared_ptr<Matrix<Value_, Index_> > convert_to_compressed_sparse(const Matrix<InputValue_, InputIndex_>* matrix, bool two_pass = false, int threads = 1) {
636}
641}
642
643#endif
Compressed sparse matrix representation.
Iterate across consecutive elements of the target dimension.
Convert index type to container size.
Compressed sparse matrix representation.
Definition CompressedSparseMatrix.hpp:645
Virtual class for a matrix.
Definition Matrix.hpp:59
virtual Index_ ncol() const =0
virtual Index_ nrow() const =0
virtual bool prefer_rows() const =0
virtual bool is_sparse() const =0
Convert a matrix into a fragmented sparse format.
Copy data from one buffer to another.
Templated construction of a new extractor.
Flexible representations for matrix data.
Definition Extractor.hpp:15
std::shared_ptr< ConsecutiveOracle< Index_ > > make_ConsecutiveOracle(Index_ start, Index_ length)
Definition ConsecutiveOracle.hpp:56
CompressedSparseContents< StoredValue_, StoredIndex_, StoredPointer_ > retrieve_compressed_sparse_contents(const Matrix< InputValue_, InputIndex_ > &matrix, const bool row, const RetrieveCompressedSparseContentsOptions &options)
Definition convert_to_compressed_sparse.hpp:367
int parallelize(Function_ fun, const Index_ tasks, const int workers)
Definition parallelize.hpp:58
std::unique_ptr< Extractor< sparse_, oracle_, Value_, Index_ > > make_Extractor(const Matrix< Value_, Index_ > &matrix, const bool row, MaybeOracle< oracle_, Index_ > oracle, const tatami::Options &opt)
Definition make_Extractor.hpp:69
Container_ create_container_of_Index_size(const Index_ x, Args_ &&... args)
Definition Index_to_container.hpp:68
std::shared_ptr< Matrix< Value_, Index_ > > convert_to_compressed_sparse(const Matrix< InputValue_, InputIndex_ > &matrix, const bool row, const ConvertToCompressedSparseOptions &options)
Definition convert_to_compressed_sparse.hpp:522
Parallelized iteration over a tatami::Matrix.
Compressed sparse contents.
Definition convert_to_compressed_sparse.hpp:315
std::vector< Index_ > index
Definition convert_to_compressed_sparse.hpp:324
std::vector< Value_ > value
Definition convert_to_compressed_sparse.hpp:319
std::vector< Pointer_ > pointers
Definition convert_to_compressed_sparse.hpp:329
Options for convert_to_compressed_sparse().
Definition convert_to_compressed_sparse.hpp:482
bool two_pass
Definition convert_to_compressed_sparse.hpp:488
int num_threads
Definition convert_to_compressed_sparse.hpp:493
Options for retrieve_compressed_sparse_contents().
Definition convert_to_compressed_sparse.hpp:335
int num_threads
Definition convert_to_compressed_sparse.hpp:346
bool two_pass
Definition convert_to_compressed_sparse.hpp:341