FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
sparse_matrix_banded.hpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#pragma once
7
8// includes, FEAT
11#include <kernel/util/math.hpp>
12#include <kernel/util/memory_arbiter.hpp>
13#include <kernel/adjacency/graph.hpp>
14#include <kernel/lafem/forward.hpp>
15#include <kernel/lafem/container.hpp>
16#include <kernel/lafem/dense_vector.hpp>
17#include <kernel/lafem/sparse_layout.hpp>
18#include <kernel/lafem/arch/axpy_dense.hpp>
19#include <kernel/lafem/arch/matvecmult_banded_dense.hpp>
20#include <kernel/lafem/arch/norm2_dense.hpp>
21#include <kernel/lafem/arch/scale_dense.hpp>
22
23// includes, system
24#include <fstream>
25#include <set>
26
27namespace FEAT
28{
29 namespace LAFEM
30 {
75 template <typename DT_, typename IT_ = Index>
76 class SparseMatrixBanded : public Container<DT_, IT_>
77 {
78 public:
80 typedef DT_ DataType;
82 typedef IT_ IndexType;
90 typedef DT_ ValueType;
92 template <typename DT2_ = DT_, typename IT2_ = IT_>
94
96 template <typename DataType2_, typename IndexType2_>
98
99 protected:
100 Index & _rows()
101 {
102 return this->_scalar_index.at(0);
103 }
104
105 Index & _cols()
106 {
107 return this->_scalar_index.at(1);
108 }
109
110 Index & _bands()
111 {
112 return this->_scalar_index.at(2);
113 }
114
115 Index & _nzes()
116 {
117 return this->_scalar_index.at(3);
118 }
119
120
122 template <typename ITX_>
123 inline Index _start_offset(const Index i, const ITX_ * const offsets,
124 const Index rows_in, const Index columns_in, const Index noo) const
125 {
126 if (i == Index(-1))
127 {
128 return rows_in;
129 }
130 else if (i == noo)
131 {
132 return Index(0);
133 }
134 else
135 {
136 return Math::max(columns_in + Index(1), rows_in + columns_in - Index(offsets[i])) - columns_in - Index(1);
137 }
138 }
139
141 template <typename ITX_>
142 inline Index _end_offset(const Index i, const ITX_ * const offsets,
143 const Index rows_in, const Index columns_in, const Index noo) const
144 {
145 if (i == Index (-1))
146 {
147 return rows_in - 1;
148 }
149 else if (i == noo)
150 {
151 return Index(-1);
152 }
153 else
154 {
155 return Math::min(rows_in, columns_in + rows_in - Index(offsets[i]) - Index(1)) - Index(1);
156 }
157 }
158
159 public:
166 {
167 this->_scalar_index.push_back(0);
168 this->_scalar_index.push_back(0);
169 this->_scalar_index.push_back(0);
170 }
171
182 explicit SparseMatrixBanded(const Index rows_in, const Index columns_in, const Index bands_in, const Index nzes_in)
183 {
184 this->_scalar_index.push_back(rows_in);
185 this->_scalar_index.push_back(columns_in);
186 this->_scalar_index.push_back(bands_in);
187 this->_scalar_index.push_back(nzes_in);
188
189 this->_elements.push_back(Memory::Arbiter(sizeof(DT_) * rows_in * bands_in,
191 this->_elements_size.push_back(rows_in * bands_in);
192 this->_indices.push_back(Memory::Arbiter(sizeof(IT_) * rows_in * bands_in));
193 this->_indices_size.push_back(rows_in * bands_in);
194 }
195
204 {
205 this->_indices_size.assign(layout_in._indices_size.begin(), layout_in._indices_size.end());
206 this->_scalar_index.assign(layout_in._scalar_index.begin(), layout_in._scalar_index.end());
207
208 for(const auto& idx : layout_in.get_indices())
209 this->_indices.push_back(idx.attach());
210
211 this->_elements.push_back(Memory::Arbiter(sizeof(DT_) * _rows() * _bands(),
213 this->_elements_size.push_back(_rows() * _bands());
214 }
215
226 explicit SparseMatrixBanded(const Index rows_in, const Index columns_in,
227 DenseVector<DT_, IT_> & val_in,
228 DenseVector<IT_, IT_> & bands_in)
229 {
230 if (val_in.size() != rows_in * bands_in.size())
231 {
232 XABORTM("Size of values does not match to number of offsets and row count!");
233 }
234
235 this->_scalar_index.push_back(rows_in);
236 this->_scalar_index.push_back(columns_in);
237
238 Index tnonzeros(0);
239
240 Memory::TypedView<IT_> vbands(bands_in.elements_view_r());
241 for (Index i(0); i < bands_in.size(); ++i)
242 {
243 const Index toffset(Index(vbands(i)));
244
245 if (toffset + Index(2) > rows_in + columns_in)
246 {
247 XABORTM("Offset out of matrix!");
248 }
249
250 tnonzeros += columns_in + Math::min(rows_in, columns_in + rows_in - toffset - 1) - Math::max(columns_in + rows_in - toffset - 1, columns_in);
251 }
252 vbands.release();
253
254 this->_scalar_index.push_back(bands_in.size());
255 this->_scalar_index.push_back(tnonzeros);
256
257 this->_elements.push_back(val_in.elements_arbiter().attach());
258 this->_elements_size.push_back(val_in.size());
259 this->_indices.push_back(bands_in.elements_arbiter().attach());
260 this->_indices_size.push_back(bands_in.size());
261 }
262
270 template <typename MT_>
271 explicit SparseMatrixBanded(const MT_ & other)
272 {
273 this->convert(other);
274 }
275
283 explicit SparseMatrixBanded(const Adjacency::Graph & graph)
284 {
285 Index num_rows = graph.get_num_nodes_domain();
286 Index num_cols = graph.get_num_nodes_image();
287
288 const Index * dom_ptr(graph.get_domain_ptr());
289 const Index * img_idx(graph.get_image_idx());
290
291 std::set<IT_> moffsets;
292
293 for(Index row(0); row < num_rows; ++row)
294 {
295 for(Index j(dom_ptr[row]); j < dom_ptr[row+1]; ++j)
296 {
297 moffsets.insert(IT_(num_rows - 1 + img_idx[j] - row));
298 }
299 }
300
301 DenseVector<IT_, IT_> toffsets(Index(moffsets.size()));
302 Memory::TypedView<IT_> ptoffsets = toffsets.elements_view_w();
303
304 IT_ idx(0);
305 for (auto off : moffsets)
306 {
307 ptoffsets[idx] = off;
308 ++idx;
309 }
310
311 DenseVector<DT_, IT_> tval(Index(moffsets.size()) * num_rows, DT_(0));
312
313 this->move(SparseMatrixBanded(num_rows, num_cols, tval, toffsets));
314 }
315
324 explicit SparseMatrixBanded(FileMode mode, String filename)
325 {
326 this->read_from(mode, filename);
327 }
328
337 explicit SparseMatrixBanded(FileMode mode, std::istream& file)
338 {
339 this->read_from(mode, file);
340 }
341
349 template <typename DT2_ = DT_, typename IT2_ = IT_>
350 explicit SparseMatrixBanded(std::vector<char> input)
351 {
352 this->deserialize<DT2_, IT2_>(input);
353 }
354
363 Container<DT_, IT_>(std::forward<SparseMatrixBanded>(other))
364 {
365 }
366
375 {
376 this->move(std::forward<SparseMatrixBanded>(other));
377 return *this;
378 }
379
389 {
391 t.clone(*this, clone_mode);
392 return t;
393 }
394
403 template<typename DT2_, typename IT2_>
405 {
406 Container<DT_, IT_>::clone(other, clone_mode);
407 }
408
417 {
418 this->_elements.clear();
419 this->_indices.clear();
420 this->_elements_size.clear();
421 this->_indices_size.clear();
422 this->_scalar_index.clear();
423
424 this->_indices_size.assign(layout_in._indices_size.begin(), layout_in._indices_size.end());
425 this->_scalar_index.assign(layout_in._scalar_index.begin(), layout_in._scalar_index.end());
426
427 for(const auto& idx : layout_in.get_indices())
428 this->_indices.push_back(idx.attach());
429
430 this->_elements.push_back(Memory::Arbiter(sizeof(DT_) * _rows() * _bands(),
432 this->_elements_size.push_back(_rows() * _bands());
433
434 return *this;
435 }
436
444 template <typename DT2_, typename IT2_>
446 {
447 this->assign(other);
448 }
449
450 template <typename DT2_, typename IT2_>
451 void convert(const SparseMatrixCSR<DT2_, IT2_> & csr)
452 {
453 XASSERT(csr.num_nzes() > 0);
454
455 const Memory::TypedView<IT_> row_ptr = csr.row_ptr_view_r();
456 const Memory::TypedView<IT_> col_idx = csr.col_idx_view_r();
457 const Memory::TypedView<DT_> csr_val = csr.val_view_r();
458
459 std::set<IT_> offset_set;
460 Index nrows(csr.num_rows());
461 Index ncolumns(csr.num_cols());
462 for (Index row(0) ; row < nrows ; ++row)
463 {
464 for (Index i(row_ptr[row]) ; i < row_ptr[row+1] ; ++i)
465 {
466 //compute band offset for each non zero entry
467 IT_ off = IT_(col_idx[i] - row + nrows - 1);
468 offset_set.insert(off);
469 }
470 }
471
472 DenseVector<DT_, IT_> val_new(Index(offset_set.size()) * nrows, DT_(0));
473 Memory::TypedView<DT_ > pval = val_new.elements_view_w();
474 for (Index row(0) ; row < nrows ; ++row)
475 {
476 for (Index i(row_ptr[row]) ; i < row_ptr[row+1] ; ++i)
477 {
478 Index col = col_idx[i];
479 Index offset = (col - row + nrows - 1);
480 Index band = Index(std::distance(offset_set.begin(), offset_set.find(IT_(offset))));
481 pval[band * nrows + row] = csr_val[i];
482 }
483 }
484
485 DenseVector<IT_, IT_> offsets_new(Index(offset_set.size()));
486 Memory::TypedView<IT_> poffsets = offsets_new.elements_view_w();
487 auto it_offset = offset_set.begin();
488 for (Index i(0) ; i < offset_set.size() ; ++i, ++it_offset)
489 {
490 poffsets[i] = *it_offset;
491 }
492 offset_set.clear();
493
494 pval.release();
495 poffsets.release();
496
497 SparseMatrixBanded<DT_, IT_> temp(nrows, ncolumns, val_new, offsets_new);
498 this->move(std::move(temp));
499 }
500
507 void write_out(FileMode mode, const String& filename) const
508 {
509 std::ios_base::openmode bin = std::ofstream::out | std::ofstream::binary;
510 if(mode == FileMode::fm_mtx)
511 bin = std::ofstream::out;
512 std::ofstream file;
513 char* buff = nullptr;
514 if(mode == FileMode::fm_mtx)
515 {
516 buff = new char[LAFEM::file_out_stream_buffer_size];
517 file.rdbuf()->pubsetbuf(buff, LAFEM::file_out_stream_buffer_size);
518 }
519 file.open(filename.c_str(), bin);
520 if(! file.is_open())
521 XABORTM("Unable to open Matrix file " + filename);
522 write_out(mode, file);
523 file.close();
524 delete[] buff;
525 }
532 void write_out(FileMode mode, std::ostream& file) const
533 {
534 switch(mode)
535 {
536 case FileMode::fm_bm:
537 [[fallthrough]];
538
540 if (! std::is_same<DT_, double>::value)
541 std::cout<<"Warning: You are writing out a banded matrix that is not double precision!\n";
542 this->template _serialize<double, std::uint64_t>(FileMode::fm_bm, file);
543 break;
544
545 default:
546 XABORTM("Filemode not supported!");
547 }
548 }
549
556 {
558 }
559
566 {
567 return this->_scalar_index.empty() ? Index(0) : this->_scalar_index.at(0);
568 }
569
576 {
577 return this->_scalar_index.empty() ? Index(0) : this->_scalar_index.at(1);
578 }
579
586 {
587 return this->_scalar_index.empty() ? Index(0) : this->_scalar_index.at(2);
588 }
589
598 {
599 return this->_scalar_index.empty() ? Index(0) : this->_scalar_index.at(3);
600 }
601
604 {
605 return this->num_rows();
606 }
607
610 {
611 return this->num_cols();
612 }
613
616 {
617 return this->num_nzes();
618 }
619
628 {
629 return this->_scalar_index.empty() ? Index(0) : this->_scalar_index.at(0) * this->_scalar_index.at(2);
630 }
631
633 bool empty() const
634 {
635 return this->_scalar_index.empty() || (this->_scalar_index.at(0) == Index(0));
636 }
637
639 bool hollow() const
640 {
641 return this->_scalar_index.empty() || (this->_scalar_index.at(2) == Index(0));
642 }
643
646 {
647 return this->_indices.at(0);
648 }
649
652 {
653 return this->_indices.at(0);
654 }
655
658 {
659 return this->_elements.front();
660 }
661
664 {
665 return this->_elements.front();
666 }
667
669 {
670 if(this->_elements.empty())
671 return Memory::TypedView<DT_>();
672 return Memory::TypedView<DT_>(this->_elements.at(0).view(loc, Memory::Access::read));
673 }
674
676 {
677 if(this->_elements.empty())
678 return Memory::TypedView<DT_>();
679 return Memory::TypedView<DT_>(this->_elements.at(0).view(loc, Memory::Access::write));
680 }
681
682 Memory::TypedView<DT_> val_view_rw(Memory::Location loc = Memory::Location::main)
683 {
684 if(this->_elements.empty())
685 return Memory::TypedView<DT_>();
686 return Memory::TypedView<DT_>(this->_elements.at(0).view(loc, Memory::Access::read_write));
687 }
688
689 Memory::TypedView<DT_> val_view(Memory::Location loc, Memory::Access acc)
690 {
691 if(this->_elements.empty())
692 return Memory::TypedView<DT_>();
693 return Memory::TypedView<DT_>(this->_elements.at(0).view(loc, acc));
694 }
695
696 Memory::TypedView<IT_> offsets_view_r(Memory::Location loc = Memory::Location::main) const
697 {
698 if(this->_indices.empty())
699 return Memory::TypedView<IT_>();
700 return Memory::TypedView<IT_>(this->_indices.at(0).view(loc, Memory::Access::read));
701 }
702
703 Memory::TypedView<IT_> offsets_view_w(Memory::Location loc = Memory::Location::main)
704 {
705 if(this->_indices.empty())
706 return Memory::TypedView<IT_>();
707 return Memory::TypedView<IT_>(this->_indices.at(0).view(loc, Memory::Access::write));
708 }
709
710 Memory::TypedView<IT_> offsets_view_rw(Memory::Location loc = Memory::Location::main)
711 {
712 if(this->_indices.empty())
713 return Memory::TypedView<IT_>();
714 return Memory::TypedView<IT_>(this->_indices.at(0).view(loc, Memory::Access::read_write));
715 }
716
717 Memory::TypedView<IT_> offsets_view(Memory::Location loc, Memory::Access acc)
718 {
719 if(this->_indices.empty())
720 return Memory::TypedView<IT_>();
721 return Memory::TypedView<IT_>(this->_indices.at(0).view(loc, acc));
722 }
723
729 static String name()
730 {
731 return "SparseMatrixBanded";
732 }
733
740 void copy(const SparseMatrixBanded & x, bool full = false)
741 {
742 this->_copy_content(x, full);
743 }
744
747
754 void axpy(const SparseMatrixBanded & x, const DT_ alpha = DT_(1))
755 {
756 XASSERTM(x.num_rows() == this->num_rows(), "Matrix rows do not match!");
757 XASSERTM(x.num_cols() == this->num_cols(), "Matrix columns do not match!");
758 XASSERTM(x.num_bands() == this->num_bands(), "Matrix bands do not match!");
759 XASSERTM(x.num_nzes() == this->num_nzes(), "Matrix nonzeros do not match!");
760
761 if(this->empty())
762 return;
763
764 TimeStamp ts_start;
765
766 Arch::AxpyDense::template exec<DT_>(this->val_arbiter(), alpha, x.val_arbiter(), this->val_size());
767
768 TimeStamp ts_stop;
769
770 Statistics::add_flops(this->val_size() * 2);
771 Statistics::add_time_axpy(ts_stop.elapsed(ts_start));
772 }
773
780 void scale(const SparseMatrixBanded & x, const DT_ alpha)
781 {
782 XASSERTM(x.num_rows() == this->num_rows(), "Matrix rows do not match!");
783 XASSERTM(x.num_cols() == this->num_cols(), "Matrix columns do not match!");
784 XASSERTM(x.num_bands() == this->num_bands(), "Matrix bands do not match!");
785 XASSERTM(x.num_nzes() == this->num_nzes(), "Matrix nonzeros do not match!");
786
787 if(this->empty())
788 return;
789
790 TimeStamp ts_start;
791
792 Arch::ScaleDense::template exec<DT_>(this->val_arbiter(), x.val_arbiter(), alpha, this->val_size());
793
794 TimeStamp ts_stop;
795
797 Statistics::add_time_axpy(ts_stop.elapsed(ts_start));
798 }
799
805 DT_ norm_frobenius() const
806 {
807 XASSERT(!this->empty());
808
809 TimeStamp ts_start;
810
811 DT_ result = Arch::Norm2Dense::template exec<DT_>(this->val_arbiter(), this->val_size());
812
813 TimeStamp ts_stop;
814
815 Statistics::add_flops(this->val_size() * 2);
816 Statistics::add_time_reduction(ts_stop.elapsed(ts_start));
817
818 return result;
819 }
820
828 {
829 XASSERTM(r.size() == this->num_rows(), "Vector size of r does not match!");
830 XASSERTM(x.size() == this->num_cols(), "Vector size of x does not match!");
831
832 if(this->empty())
833 return;
834
835 if (this->num_nzes() == Index(0))
836 {
837 r.format();
838 return;
839 }
840
841 XASSERTM(r.elements_arbiter() != x.elements_arbiter(), "Vector x and r must not share the same memory!");
842
843 TimeStamp ts_start;
844
845 Arch::MatVecMultBandedDense::template exec<DT_, IT_>(
847 this->val_arbiter(), this->offsets_arbiter(), this->num_bands(), this->num_rows(), this->num_cols());
848
849 TimeStamp ts_stop;
850
851 Statistics::add_flops(2 * this->val_size());
852 Statistics::add_time_blas2(ts_stop.elapsed(ts_start));
853 }
854
862 {
863 XASSERTM(r.size() == this->num_cols(), "Vector size of r does not match!");
864 XASSERTM(x.size() == this->num_rows(), "Vector size of x does not match!");
865
866 if(this->empty())
867 return;
868
869 if (this->num_nzes() == Index(0))
870 {
871 r.format();
872 return;
873 }
874
875 XASSERTM(r.elements_arbiter() != x.elements_arbiter(), "Vector x and r must not share the same memory!");
876
877 TimeStamp ts_start;
878
879 Arch::MatVecMultBandedDense::template exec<DT_, IT_>(
881 this->val_arbiter(), this->offsets_arbiter(), this->num_bands(), this->num_rows(), this->num_cols(), true);
882
883 TimeStamp ts_stop;
884 Statistics::add_flops( 2 * this->val_size() );
885 Statistics::add_time_blas2(ts_stop.elapsed(ts_start));
886 }
887
897 const DenseVector<DT_, IT_>& x,
898 const DenseVector<DT_, IT_>& y,
899 const DT_ alpha = DT_(1)) const
900 {
901 XASSERTM(r.size() == this->num_rows(), "Vector size of r does not match!");
902 XASSERTM(x.size() == this->num_cols(), "Vector size of x does not match!");
903 XASSERTM(y.size() == this->num_rows(), "Vector size of y does not match!");
904
905 if(this->empty())
906 return;
907
908 XASSERTM(r.elements_arbiter() != x.elements_arbiter(), "Vector x and r must not share the same memory!");
909
910 // we check alpha strictly for equality to 0, because testing if |alpha| < eps may
911 // lead to false triggers if the matrix/vector contents are also < eps
912 if((this->num_nzes() == Index(0)) || (alpha == DT_(0)))
913 {
914 r.copy(y);
915 return;
916 }
917
918 TimeStamp ts_start;
919
920 Arch::MatVecMultBandedDense::template exec<DT_, IT_>(
922 this->val_arbiter(), this->offsets_arbiter(), this->num_bands(), this->num_rows(), this->num_cols());
923
924 TimeStamp ts_stop;
925
926 Statistics::add_flops( 2 * (this->val_size() + this->num_rows()) );
927 Statistics::add_time_blas2(ts_stop.elapsed(ts_start));
928 }
929
939 const DenseVector<DT_, IT_>& x,
940 const DenseVector<DT_, IT_>& y,
941 const DT_ alpha = DT_(1)) const
942 {
943 XASSERTM(r.size() == this->num_cols(), "Vector size of r does not match!");
944 XASSERTM(x.size() == this->num_rows(), "Vector size of x does not match!");
945 XASSERTM(y.size() == this->num_cols(), "Vector size of y does not match!");
946
947 if(this->empty())
948 return;
949
950 XASSERTM(r.elements_arbiter() != x.elements_arbiter(), "Vector x and r must not share the same memory!");
951
952 // we check alpha strictly for equality to 0, because testing if |alpha| < eps may
953 // lead to false triggers if the matrix/vector contents are also < eps
954 if((this->num_nzes() == Index(0)) || (alpha == DT_(0)))
955 {
956 r.copy(y);
957 return;
958 }
959
960 TimeStamp ts_start;
961 Statistics::add_flops( 2 * (this->val_size() + this->num_rows()) );
962
963 Arch::MatVecMultBandedDense::template exec<DT_, IT_>(
965 this->val_arbiter(), this->offsets_arbiter(), this->num_bands(), this->num_rows(), this->num_cols(), true);
966
967 TimeStamp ts_stop;
968 Statistics::add_time_blas2(ts_stop.elapsed(ts_start));
969 }
971
973 void extract_diag(VectorTypeL & diag) const
974 {
975 XASSERTM(diag.size() == num_rows(), "diag size does not match matrix row count!");
976 XASSERTM(num_rows() == num_cols(), "matrix is not square!");
977
978 if(this->empty())
979 return;
980
981 const Memory::TypedView<IT_> offs = this->offsets_view_r();
982 const Memory::TypedView<DT_> vals = this->val_view_r();
983
984 const Index nrows = this->num_rows();
985 for (Index i(0) ; i < num_bands() ; ++i)
986 {
987 if (offs[i]+1 == nrows)
988 {
989 diag.elements_arbiter().copy(&vals[i*nrows], Memory::Location::main);
990 break;
991 }
992 }
993 }
994
997 {
999 extract_diag(diag);
1000 return diag;
1001 }
1002
1010 template <typename DT2_ = DT_, typename IT2_ = IT_>
1011 void deserialize(std::vector<char> input)
1012 {
1013 this->template _deserialize<DT2_, IT2_>(FileMode::fm_bm, input);
1014 }
1015
1023 {
1024 XASSERTM(x.num_nzes() == this->num_nzes(), "Nonzero count does not match!");
1025 XASSERT(!this->empty());
1026
1027 TimeStamp ts_start;
1028
1029 DT_ result = Arch::MaxRelDiffDense::template exec<DT_>(this->val_arbiter(), x.val_arbiter(), this->val_size());
1030
1031 TimeStamp ts_stop;
1032 Statistics::add_time_reduction(ts_stop.elapsed(ts_start));
1033
1034 return result;
1035 }
1036
1045 bool same_layout(const SparseMatrixBanded& x) const
1046 {
1047 if (this->num_rows() != x.num_rows())
1048 return false;
1049 if (this->num_cols() != x.num_cols())
1050 return false;
1051 if (this->num_bands() != x.num_bands())
1052 return false;
1053 if (this->num_nzes() != x.num_nzes())
1054 return false;
1055
1056 if(this->num_nzes() == Index(0))
1057 return true;
1058
1059 // check if the arbiters for offsets are the same
1060 if(this->offsets_arbiter() == x.offsets_arbiter())
1061 return true;
1062
1063 // compare the offsets
1064 const Memory::TypedView<IT_> offsets_a = this->offsets_view_r();
1065 const Memory::TypedView<IT_> offsets_b = x.offsets_view_r();
1066 for (Index i(0); i < this->num_bands(); ++i)
1067 {
1068 if (offsets_a[i] != offsets_b[i])
1069 return false;
1070 }
1071
1072 return true;
1073 }
1074
1086 template <typename DT2_ = DT_, typename IT2_ = IT_>
1087 std::vector<char> serialize(const LAFEM::SerialConfig& config = SerialConfig()) const
1088 {
1089 return this->template _serialize<DT2_, IT2_>(FileMode::fm_bm, config);
1090 }
1091
1098 void read_from(FileMode mode, const String& filename)
1099 {
1100 std::ios_base::openmode bin = std::ifstream::in | std::ifstream::binary;
1101 if(mode == FileMode::fm_mtx)
1102 bin = std::ifstream::in;
1103 std::ifstream file(filename.c_str(), bin);
1104 if (! file.is_open())
1105 XABORTM("Unable to open Matrix file " + filename);
1106 read_from(mode, file);
1107 file.close();
1108 }
1109
1116 void read_from(FileMode mode, std::istream& file)
1117 {
1118 switch(mode)
1119 {
1120 case FileMode::fm_bm:
1121 [[fallthrough]];
1122
1124 this->template _deserialize<double, std::uint64_t>(FileMode::fm_bm, file);
1125 break;
1126
1127 default:
1128 XABORTM("Filemode not supported!");
1129 }
1130 }
1131
1134 {
1135 return VectorTypeL(this->num_rows());
1136 }
1137
1139 VectorTypeR create_vector_r() const
1140 {
1141 return VectorTypeR(this->num_cols());
1142 }
1143
1154 void print(std::ostream& os, bool print_dense) const
1155 {
1156 if(this->num_rows() <= Index(0))
1157 {
1158 os << "[]";
1159 return;
1160 }
1161
1162 const Memory::TypedView<IT_> off = this->offsets_view_r();
1163 const Memory::TypedView<DT_> val = this->val_view_r();
1164 const Index nrows = this->num_rows();
1165 const Index ncols = this->num_cols();
1166 const Index nbands = this->num_bands();
1167
1168 os << "[\n";
1169 for (Index i(0) ; i < nrows ; ++i)
1170 {
1171 os << "[";
1172
1173 Index k = 0;
1174 for(IT_ j(0); j < nbands; ++j)
1175 {
1176 if((off[j] + i + 2 > nrows) && (off[j] + i + 1 < 2 * nrows))
1177 {
1178 const Index col_idx = Index(off[j] + i + 1) - nrows;
1179 if(print_dense)
1180 {
1181 for(; k < col_idx; ++k)
1182 os << " " << DT_(0);
1183 }
1184 else
1185 {
1186 os << " " << col_idx << ":";
1187 }
1188 os << " " << val(j * nrows + i);
1189 ++k;
1190 }
1191 }
1192
1193 // write trailing zeros
1194 if(print_dense)
1195 {
1196 for(; k < ncols; ++k)
1197 os << " " << DT_(0);
1198 }
1199
1200 os << "]\n";
1201 }
1202 os << "]";
1203 }
1204
1211 friend std::ostream & operator<< (std::ostream & os, const SparseMatrixBanded & b)
1212 {
1213 b.print(os, true);
1214 return os;
1215 }
1216
1217 public:
1219 {
1220 public:
1223 {
1224 private:
1225 IT_ _k;
1226 const IT_ _s;
1227 const IT_ * const _offsets;
1228
1229 public:
1230 ImageIterator() : _k(IT_(0)), _s(IT_(0)), _offsets(nullptr) {}
1231
1232 ImageIterator(IT_ k, IT_ s, const IT_ * offsets) : _k(k), _s(s), _offsets(offsets) {}
1233
1235 {
1236 _k = other._k;
1237 _s = other._s;
1238 _offsets = other._offsets;
1239 return *this;
1240 }
1241
1242 bool operator!=(const ImageIterator& other) const
1243 {
1244 return this->_k != other._k;
1245 }
1246
1247 ImageIterator& operator++()
1248 {
1249 ++_k;
1250 return *this;
1251 }
1252
1253 Index operator*() const
1254 {
1255 return Index(_s + _offsets[_k]);
1256 }
1257 };
1258
1259 private:
1260 const SparseMatrixBanded& _matrix;
1261 const Memory::TypedView<IT_> _offsets;
1262
1263 public:
1264 explicit Adjactor(const SparseMatrixBanded& matrix) :
1265 _matrix(matrix),
1266 _offsets(matrix.offsets_view_r())
1267 {
1268 }
1269
1272 {
1273 return _matrix.num_rows();
1274 }
1275
1278 {
1279 return _matrix.num_cols();
1280 }
1281
1283 inline ImageIterator image_begin(Index domain_node) const
1284 {
1285 const IT_ tbands(_matrix.num_bands());
1286 const Index trows(_matrix.num_rows());
1287
1288 XASSERT(domain_node < trows);
1289
1290 for(IT_ k(0); k < tbands; ++k)
1291 {
1292 if(_offsets[k] + domain_node + 1 >= trows)
1293 return ImageIterator(k, domain_node + 1 - trows, _offsets.get_r());
1294 }
1295 }
1296
1298 inline ImageIterator image_end(Index domain_node) const
1299 {
1300 const IT_ tbands(_matrix.num_bands());
1301 const Index trows(_matrix.num_rows());
1302
1303 XASSERT(domain_node < trows);
1304
1305 for(IT_ k(0); k < tbands; ++k)
1306 {
1307 if(_offsets[k] + domain_node + 1 >= 2 * trows)
1308 {
1309 return ImageIterator(k, domain_node + 1 - trows, _offsets.get_r());
1310 }
1311 }
1312 return ImageIterator(tbands, domain_node + 1 - trows, _offsets.get_r());
1313 }
1314 }; // class Adjactor
1315
1322 {
1323 public:
1325 typedef DT_ DataType;
1326 typedef IT_ IndexType;
1327
1328 private:
1329#ifdef DEBUG
1330 static constexpr IT_ _deadcode = ~IT_(0);
1331#endif
1332 Index _num_rows;
1333 Index _num_cols;
1334 Index _num_bands;
1335 Memory::Arbiter _col_ptr_arbiter;
1336 const Memory::TypedView<IT_> _offsets;
1337 Memory::TypedView<IT_> _col_ptr;
1339
1340 public:
1341 explicit ScatterAxpy(MatrixType& matrix) :
1342 _num_rows(matrix.num_rows()),
1343 _num_cols(matrix.num_cols()),
1344 _num_bands(matrix.num_bands()),
1345 _col_ptr_arbiter(_num_cols * sizeof(IT_), Memory::Location::main, Memory::Init::format_to_one),
1346 _offsets(matrix.offsets_view_r()),
1347 _col_ptr(_col_ptr_arbiter.view(Memory::Location::main, Memory::Access::read_write)),
1349 {
1350 }
1351
1352 template<typename LocalMatrix_, typename RowMapping_, typename ColMapping_>
1353 void operator()(const LocalMatrix_& loc_mat, const RowMapping_& row_map,
1354 const ColMapping_& col_map, DT_ alpha = DT_(1))
1355 {
1356 // loop over all local row entries
1357 for(int i(0); i < row_map.get_num_local_dofs(); ++i)
1358 {
1359 // fetch row index
1360 const Index ix = row_map.get_index(i);
1361
1362 // build column pointer for this row entry contribution
1363 for(IT_ k(0); k < _num_bands; ++k)
1364 {
1365 if(_offsets[k] + ix + 1 >= _num_rows && _offsets[k] + ix + 1 < 2 * _num_rows)
1366 {
1367 _col_ptr[_offsets[k] + ix + 1 - _num_rows] = IT_(k * _num_rows + ix);
1368 }
1369 }
1370
1371 // loop over all local column entries
1372 for(int j(0); j < col_map.get_num_local_dofs(); ++j)
1373 {
1374 // fetch column index
1375 const Index jx = col_map.get_index(j);
1376
1377 // ensure that the column pointer is valid for this index
1378 ASSERTM(_col_ptr[jx] != _deadcode, "invalid column index");
1379
1380 // incorporate data into global matrix
1381 _data[_col_ptr[jx]] += alpha * loc_mat[i][j];
1382
1383 // continue with next column entry
1384 }
1385
1386#ifdef DEBUG
1387 // reformat column-pointer array
1388 for(IT_ k(0); k < _num_bands; ++k)
1389 {
1390 if(_offsets[k] + ix + 1 >= _num_rows && _offsets[k] + ix + 1 < 2 * _num_rows)
1391 {
1392 _col_ptr[_offsets[k] + ix + 1 - _num_rows] = _deadcode;
1393 }
1394 }
1395#endif
1396 // continue with next row entry
1397 }
1398 }
1399 }; // class ScatterAxpy
1400
1407 {
1408 public:
1410 typedef DT_ DataType;
1411 typedef IT_ IndexType;
1412
1413 private:
1414#ifdef DEBUG
1415 static constexpr IT_ _deadcode = ~IT_(0);
1416#endif
1417 Index _num_rows;
1418 Index _num_cols;
1419 Index _num_bands;
1420 Memory::Arbiter _col_ptr_arbiter;
1421 const Memory::TypedView<IT_> _offsets;
1422 Memory::TypedView<IT_> _col_ptr;
1423 const Memory::TypedView<DT_> _data;
1424
1425 public:
1426 explicit GatherAxpy(const MatrixType& matrix) :
1427 _num_rows(matrix.num_rows()),
1428 _num_cols(matrix.num_cols()),
1429 _num_bands(matrix.num_bands()),
1430 _col_ptr_arbiter(_num_cols * sizeof(IT_), Memory::Location::main, Memory::Init::format_to_one),
1431 _offsets(matrix.offsets_view_r()),
1432 _col_ptr(_col_ptr_arbiter.view(Memory::Location::main, Memory::Access::read_write)),
1433 _data(matrix.val_view_r())
1434 {
1435 }
1436
1437 template<typename LocalMatrix_, typename RowMapping_, typename ColMapping_>
1438 void operator()(LocalMatrix_& loc_mat, const RowMapping_& row_map,
1439 const ColMapping_& col_map, DT_ alpha = DT_(1))
1440 {
1441 // loop over all local row entries
1442 for(int i(0); i < row_map.get_num_local_dofs(); ++i)
1443 {
1444 // fetch row index
1445 const Index ix = row_map.get_index(i);
1446
1447 // build column pointer for this row entry contribution
1448 for(IT_ k(0); k < _num_bands; ++k)
1449 {
1450 if(_offsets[k] + ix + 1 >= _num_rows && _offsets[k] + ix + 1 < 2 * _num_rows)
1451 {
1452 _col_ptr[_offsets[k] + ix + 1 - _num_rows] = IT_(k * _num_rows + ix);
1453 }
1454 }
1455
1456 // loop over all local column entries
1457 for(int j(0); j < col_map.get_num_local_dofs(); ++j)
1458 {
1459 // fetch column index
1460 const Index jx = col_map.get_index(j);
1461
1462 // ensure that the column pointer is valid for this index
1463 ASSERTM(_col_ptr[jx] != _deadcode, "invalid column index");
1464
1465 // update local matrix data
1466 loc_mat[i][j] += alpha * _data[_col_ptr[jx]];
1467
1468 // continue with next column entry
1469 }
1470
1471#ifdef DEBUG
1472 // reformat column-pointer array
1473 for(IT_ k(0); k < _num_bands; ++k)
1474 {
1475 if(_offsets[k] + ix + 1 >= _num_rows && _offsets[k] + ix + 1 < 2 * _num_rows)
1476 {
1477 _col_ptr[_offsets[k] + ix + 1 - _num_rows] = _deadcode;
1478 }
1479 }
1480#endif
1481 // continue with next row entry
1482 }
1483 }
1484 }; // class GatherAxpy
1485 }; // class SparseMatrixBanded
1486 } // namespace LAFEM
1487} // namespace FEAT
#define XABORTM(msg)
Abortion macro definition with custom message.
Definition: assertion.hpp:192
#define ASSERTM(expr, msg)
Debug-Assertion macro definition with custom message.
Definition: assertion.hpp:230
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
#define XASSERTM(expr, msg)
Assertion macro definition with custom message.
Definition: assertion.hpp:263
FEAT Kernel base header.
Adjacency Graph implementation.
Definition: graph.hpp:34
Index * get_domain_ptr()
Returns the domain pointer array.
Definition: graph.hpp:359
Index * get_image_idx()
Returns the image node index array.
Definition: graph.hpp:374
Container base class.
Definition: container.hpp:224
void format()
Reset all elements of the container to a given value or zero if missing.
Definition: container.hpp:831
void move(Container &&source)
Assignment move operation.
Definition: container.hpp:1007
void clone(const Container &source, CloneMode clone_mode=CloneMode::Weak)
Clone operation.
Definition: container.hpp:904
std::vector< Index > _elements_size
List of corresponding datatype array sizes.
Definition: container.hpp:234
void assign(const Container< DT2_, IT2_ > &other)
Assignment operation.
Definition: container.hpp:285
std::vector< Memory::Arbiter > _indices
List of pointers to all IT_ dependent arrays.
Definition: container.hpp:232
std::vector< Index > _indices_size
List of corresponding IT_ array sizes.
Definition: container.hpp:236
std::vector< Memory::Arbiter > _elements
List of pointers to all datatype dependent arrays.
Definition: container.hpp:230
std::vector< Index > _scalar_index
List of scalars with datatype index.
Definition: container.hpp:238
Dense data vector class template.
Memory::Arbiter & elements_arbiter()
Returns a reference to the element array arbiter.
void copy(const VT_ &a)
Performs .
Index size() const
Returns the size of this vector, i.e. its number of entries.
Config class for serialize parameter.
Definition: container.hpp:50
Layout scheme for sparse matrix containers.
const std::vector< Memory::Arbiter > & get_indices() const
Returns a list of all Index arrays.
ImageIterator class for Adjactor interface implementation.
ImageIterator image_begin(Index domain_node) const
ImageIterator image_end(Index domain_node) const
Gather-Axpy operation for SparseMatrixBanded.
Scatter-Axpy operation for SparseMatrixBanded.
void extract_diag(VectorTypeL &diag) const
SparseMatrixBanded clone(CloneMode clone_mode=CloneMode::Weak) const
Clone operation.
bool empty() const
Checks whether the matrix is empty, i.e. whether it is a 0x0 matrix.
SparseMatrixBanded & operator=(SparseMatrixBanded &&other)
Move operator.
void read_from(FileMode mode, std::istream &file)
Read in matrix from stream.
void apply(DenseVector< DT_, IT_ > &r, const DenseVector< DT_, IT_ > &x) const
Calculate .
const Memory::Arbiter & offsets_arbiter() const
Returns a reference to the band offsets array arbiter.
void convert(const SparseMatrixBanded< DT2_, IT2_ > &other)
Conversion method.
bool same_layout(const SparseMatrixBanded &x) const
Checks if the structural layout of this matrix matches that of another matrix. This excludes comparis...
Index num_nzes() const
Retrieve non zero element count.
SparseMatrixBanded(const SparseLayout< IT_, layout_id > &layout_in)
Constructor.
Memory::Arbiter & offsets_arbiter()
Returns a reference to the band offsets array arbiter.
void copy(const SparseMatrixBanded &x, bool full=false)
Performs .
SparseLayout< IT_, layout_id > layout() const
Retrieve convenient sparse matrix layout object.
DenseVector< DataType, IT_ > VectorTypeR
Compatible R-vector type.
bool hollow() const
Checks whether the matrix has no non-zero entries, i.e. whether it is a null matrix.
void deserialize(std::vector< char > input)
Deserialization of complete container entity.
const Memory::Arbiter & val_arbiter() const
Returns a reference to the values array arbiter.
Memory::Arbiter & val_arbiter()
Returns a reference to the values array arbiter.
void write_out(FileMode mode, const String &filename) const
Write out matrix to file.
static constexpr SparseLayoutId layout_id
Our used layout type.
SparseMatrixBanded(FileMode mode, String filename)
Constructor.
friend std::ostream & operator<<(std::ostream &os, const SparseMatrixBanded &b)
SparseMatrixBanded streaming operator.
void apply_transposed(DenseVector< DT_, IT_ > &r, const DenseVector< DT_, IT_ > &x) const
Calculate .
Index val_size() const
Retrieve total element count.
Index _start_offset(const Index i, const ITX_ *const offsets, const Index rows_in, const Index columns_in, const Index noo) const
Returns first row-index of the diagonal matching to the offset i.
VectorTypeL extract_diag() const
extract main diagonal vector from matrix
SparseMatrixBanded(const Index rows_in, const Index columns_in, DenseVector< DT_, IT_ > &val_in, DenseVector< IT_, IT_ > &bands_in)
Constructor.
Index num_cols() const
Retrieve matrix column count.
DenseVector< DataType, IT_ > VectorTypeL
Compatible L-vector type.
SparseMatrixBanded(const Index rows_in, const Index columns_in, const Index bands_in, const Index nzes_in)
Constructor.
void read_from(FileMode mode, const String &filename)
Read in matrix from file.
DT_ max_rel_diff(const SparseMatrixBanded &x) const
Retrieve the maximum relative difference of this matrix and another one y.max_rel_diff(x) returns .
SparseMatrixBanded(FileMode mode, std::istream &file)
Constructor.
Index _end_offset(const Index i, const ITX_ *const offsets, const Index rows_in, const Index columns_in, const Index noo) const
Returns last row-index of the diagonal matching to the offset i.
void write_out(FileMode mode, std::ostream &file) const
Write out matrix to file.
SparseMatrixBanded(const Adjacency::Graph &graph)
Constructor.
DT_ norm_frobenius() const
Calculates the Frobenius norm of this matrix.
void clone(const SparseMatrixBanded< DT2_, IT2_ > &other, CloneMode clone_mode=CloneMode::Weak)
Clone operation.
std::vector< char > serialize(const LAFEM::SerialConfig &config=SerialConfig()) const
Serialization of complete container entity.
VectorTypeL create_vector_l() const
Returns a new compatible L-Vector.
VectorTypeR create_vector_r() const
Returns a new compatible R-Vector.
void apply(DenseVector< DT_, IT_ > &r, const DenseVector< DT_, IT_ > &x, const DenseVector< DT_, IT_ > &y, const DT_ alpha=DT_(1)) const
Calculate .
SparseMatrixBanded(std::vector< char > input)
Constructor.
Index num_rows() const
Retrieve matrix row count.
Index num_bands() const
Retrieve number of bands.
void axpy(const SparseMatrixBanded &x, const DT_ alpha=DT_(1))
Calculate .
SparseMatrixBanded(const MT_ &other)
Constructor.
Index num_cols_raw() const
Returns the scalar matrix column count.
Index num_nzes_raw() const
Returns the scalar matrix nonzero element count.
void scale(const SparseMatrixBanded &x, const DT_ alpha)
Calculate .
SparseMatrixBanded(SparseMatrixBanded &&other)
Move Constructor.
Index num_rows_raw() const
Returns the scalar matrix row count.
void apply_transposed(DenseVector< DT_, IT_ > &r, const DenseVector< DT_, IT_ > &x, const DenseVector< DT_, IT_ > &y, const DT_ alpha=DT_(1)) const
Calculate .
static String name()
Returns a descriptive string.
void print(std::ostream &os, bool print_dense) const
Prints this sparse matrix in human-readable format into an output stream.
CSR based sparse matrix.
Index num_cols() const
Retrieve matrix column count.
Index num_rows() const
Retrieve matrix row count.
Index num_nzes() const
Retrieve non zero element count.
Memory arbiter class.
void copy(const Arbiter &source, Location mem_loc=Location::none)
Copies of the contents of one memory block into another one.
Arbiter attach(std::size_t offset=0u, std::size_t size=full_size) const
Creates a new arbiter that is attached to the same memory block as this arbiter.
View view(Location mem_loc, Access access)
Maps a raw view to a memory block.
Typed memory view class.
const T_ * get_r() const
Returns a const typed pointer to the array that grants read access.
void release() const
Releases this view.
static void add_flops(Index flops)
Add an amount of flops to the global flop counter.
Definition: statistics.hpp:206
String class implementation.
Definition: string.hpp:47
Time stamp class.
Definition: time_stamp.hpp:54
double elapsed(const TimeStamp &before) const
Calculates the time elapsed between two time stamps.
Definition: time_stamp.hpp:100
constexpr std::size_t file_out_stream_buffer_size
OutStreamBufferSize.
Definition: base.hpp:105
SparseLayoutId
Definition: base.hpp:63
bool operator*(TestMatrixFlags a, TestMatrixFlags b)
checks whether a & b != 0
T_ min(T_ a, T_ b)
Returns the minimum of two values.
Definition: math.hpp:123
T_ max(T_ a, T_ b)
Returns the maximum of two values.
Definition: math.hpp:137
Access
Memory access enumeration.
@ read_write
read-write access
@ overlap
explicitly allow overlapping writes (see Overlapping Memory Views)
@ read
read-only access
@ write
write-only access (see attention note above)
Location
Memory location enumeration.
@ none
no or unknown or unspecified location
@ format_to_zero
allocate and format all bits to zero
@ format_to_one
allocate and format all bits to one
FEAT namespace.
Definition: adjactor.hpp:12
std::uint64_t Index
Index data type.