KASKADE 7 development version
Loading...
Searching...
No Matches
threadedMatrix.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2012-2025 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13#ifndef THREADED_MATRIX
14#define THREADED_MATRIX
15
16#include <cmath>
17#include <iostream>
18#include <boost/timer/timer.hpp>
19
20#include "dune/common/config.h"
21#include <dune/istl/bcrsmatrix.hh>
22#include <dune/istl/operators.hh>
23
24#include "fem/firstless.hh"
25#include "fem/fixdune.hh"
28#include "triplet.hh"
32
33
34
35namespace Kaskade
36{
37
39 {
40
41 //-------------------------------------------------------------------------
42
47 template <class Entry, class Index>
49 {
50 public:
51 using ColIterator = typename std::vector<Index,NumaAllocator<Index>>::const_iterator;
52 typedef typename std::vector<Entry,NumaAllocator<Entry>>::const_iterator ValueIterator;
54
55 // typedefs required by std::iterator_traits
56 using value_type = Entry;
57 using difference_type = std::ptrdiff_t;
58 using pointer = Entry const*;
59 using reference = Entry const&;
60 using iterator_category = std::random_access_iterator_tag;
61
66
73
75 : col(col_), val(val_)
76 {}
77
81
82 Index index() const
83 {
84 return *col;
85 }
86
91 Entry const& operator*() const { return *val; }
92 Entry const* operator->() const { return &*val; }
96
101 void operator++() { ++col; ++val; }
102 void operator--() { --col; --val; }
103 void operator+=(Index i) { col += i; val += i; }
104 void operator-=(Index i) { col -= i; val -= i; }
108
109 bool operator==(Self const& it) const { return val==it.val; }
110 bool operator!=(Self const& it) const { return ! (*this==it); }
111 difference_type operator-(Self const& it) const { return val-it.val; }
112
113 protected:
116 };
117
118 template <class Entry, class Index>
120 {
121 public:
122 typedef typename std::vector<Index,NumaAllocator<Index>>::const_iterator ColIterator;
123 typedef typename std::vector<Entry,NumaAllocator<Entry>>::iterator ValueIterator;
124
126
130
135 Entry& operator*() const { return const_cast<Entry&>(*this->val); }
136 Entry* operator->() const { return &(**this); }
140 };
141
142
143
144 template <class Arguments, class Operation>
152
153
154 //---------------------------------------------------------------------------------------------
155
156 template <class Entry, class Index>
158 {
159 public:
160 typedef Index size_type;
161 typedef Entry block_type;
162
165
169 size_type size() const { return std::distance(vBegin,vEnd); }
170
174 Index const* getindexptr() const { return &*cBegin; }
175
179 block_type const* getptr() const { return &*vBegin; }
180 block_type* getptr() { return &*vBegin; }
181
187
190
196 ConstIterator find(Index c) const
197 {
198 auto ci = std::lower_bound(cBegin,cEnd,c);
199 if (ci==cEnd || *ci!=c)
200 return end();
201 return ConstIterator(ci,vBegin+(ci-cBegin));
202 }
203
209 Iterator find(Index c)
210 {
211 auto ci = std::lower_bound(cBegin,cEnd,c);
212 if (ci==cEnd || *ci!=c)
213 return end();
214 return Iterator(ci,vBegin+(ci-cBegin));
215 }
216
227 Entry const& operator[](Index c) const
228 {
229 static Entry const zero(0);
230
231 auto ci = std::lower_bound(cBegin,cEnd,c);
232 if (ci==cEnd || *ci!=c)
233 return zero;
234
235 return vBegin[ci-cBegin];
236 }
237
238
245 Entry& operator[](Index c)
246 {
247 auto ci = std::lower_bound(cBegin,cEnd,c);
248 if (ci==cEnd || *ci!=c)
249 throw LookupException("write access to nonexistent matrix entry",__FILE__,__LINE__);
250
251 return vBegin[ci-cBegin];
252 }
253
254
255 protected:
256 typedef typename std::vector<Index,NumaAllocator<Index>>::const_iterator ColIterator;
257 typedef typename std::vector<Entry,NumaAllocator<Entry>>::iterator ValueIterator;
258
259 ColIterator cBegin, cEnd; // iterators giving the range of column indices
260 ValueIterator vBegin, vEnd; // iterators giving the range of values
261
262 // Extracts the row begin and end iterators at the current position (if it is a valid position)
263 void update(NumaBCRSMatrix<Entry,Index>& matrix, Index row, int chunk)
264 {
265 if (0<=row && row<matrix.N()) // we have a valid row in a valid chunk in front of us
266 {
267 auto& c = matrix.chunk(chunk);
268 auto const& p = c.pattern();
269 assert(p.first()<=row && row<p.last()); // check that the row is contained in the chunk
270 Index first = p.first();
271 cBegin = p.colStartIterator(row-first);
272 cEnd = p.colStartIterator(row-first+1);
273 vBegin = c.valStartIterator(row-first);
274 vEnd = c.valStartIterator(row-first+1);
275 }
276 }
277 };
278
279 // -----------------------------------------------------------------------------------
280
281 template <class Entry, class Index>
282 class NumaBCRSMatrixConstIterator: public NumaBCRSRow<Entry,Index> // TODO: derive from const row type!
283 {
285 typedef NumaBCRSRow<Entry,Index> Row;
286 using value_type = Row;
287
288 public:
290 : matrix(const_cast<NumaBCRSMatrix<Entry,Index>*>(&matrix_)), row(row_), chunk(getChunk(row_))
291 {
292 assert(row>=0 && row<=matrix->N());
293 this->update(*matrix,row,chunk);
294 }
295
298 {
299 ++row; // next row
300 if (row==matrix->N()) // we've reached the end
301 return; // -> skip anything else
302 while (matrix->getPattern()->rowStart()[chunk+1]==row) // oops, we tripped into the next chunk...
303 ++chunk; // which may be empty (zero rows), then go on
304 this->update(*matrix,row,chunk);
305 }
306
308 {
309 --row;
310 while (matrix->getPattern()->rowStart()[chunk] > row) // oops, we stepped before our chunk
311 --chunk; // previous one may be empty, then go on
312 this->update(*matrix,row,chunk);
313 }
314
315 void operator+=(Index inc)
316 {
317 row += inc;
318 if (row > matrix->N())
319 {
320 row = matrix->N(); // we're behind the end - move to end
321 return; // such that we compare equal to end.
322 }
323 chunk = getChunk(row);
324 this->update(*matrix,row,chunk);
325 }
326
327 bool operator==(Self const& it) const { return matrix==it.matrix && row==it.row; }
328 bool operator!=(Self const& it) const { return !(*this==it); }
330
331 Index index() const { return row; }
332
334
341 Row const& operator*() const { return *this; }
342 Row const* operator->() const { return this; }
344
345 private:
347 Index row;
348 int chunk;
349
350 int getChunk(Index r) const { return matrix->getPattern()->chunk(r); }
351 };
352
353
354
355 template <class Entry, class Index>
357 {
359 typedef NumaBCRSRow<Entry,Index> Row;
360
361 public:
363 : NumaBCRSMatrixConstIterator<Entry,Index>(matrix_,row_) {}
364
365
366 Row& operator*() { return *this; }
367 Row* operator->() { return this; }
368 };
369
370
371
372
373 } // end of namespace ThreadedMatrixDetail
374
377
378 //---------------------------------------------------------------------------
379 //---------------------------------------------------------------------------
380
391 template <class Index=size_t>
393 {
395
396 public:
428 NumaCRSPatternCreator(Index rows_, Index cols, bool symmetric=false, int nnzPerRow=0)
429 : rows(rows_), columns(cols)
430 , sym(symmetric && rows==columns)
431 {
432 int nodes = static_cast<Index>(NumaThreadPool::instance().nodes());
433 creators.reserve(nodes);
434
435 for (int i=0; i<nodes; ++i)
436 if (sym)
437 creators.push_back(ChunkCreator(i*rows/nodes,(i+1)*rows/nodes,cols,sym,i)); // TODO: more balanced
438 else
439 creators.push_back(ChunkCreator(i*rows/nodes,(i+1)*rows/nodes,cols,sym,i));
440
441 if (nnzPerRow > 0)
442 parallelForNodes([this,nnzPerRow](int i, int n)
443 {
444 this->creators[i].reserve(nnzPerRow);
445 },nodes);
446 }
447
448 // The default destructor does not parallelize the release of memory on the NUMA chunks.Thus we
449 // define our own destructor.
451 {
453 parallelForNodes([this](int i, int n)
454 {
455 this->creators[i].clear();
456 },nodes);
457 }
458
464 void addElement(Index row, Index col)
465 {
466 addElements(&row,&row+1,&col,&col+1,true);
467 }
468
477 void addDenseBlock(Index fromRow, Index toRow, Index fromCol, Index toCol)
478 {
479 assert(fromRow>=0 && toRow<=rows && fromRow<=toRow);
480 assert(fromCol>=0 && toCol<=columns && fromCol<=toCol);
481
482 for (int r=fromRow; r<toRow; ++r) // TODO: this is probably inefficient and not
483 for (int c=fromCol; c<toCol; ++c) // NUMA-parallelized. Consider a more
484 addElement(r,c); // efficient implementation
485 }
486
501 template <class IterRow, class IterCol>
502 void addElements(IterRow const fromRow, IterRow const toRow, IterCol const fromCol, IterCol const toCol, bool colIsSorted=false)
503 {
504 assert(fromCol==toCol || *std::max_element(fromCol,toCol) < columns);
505 assert(fromRow==toRow || *std::max_element(fromRow,toRow) < rows);
506 for (auto& c: creators)
507 c.addElements(fromRow,toRow,fromCol,toCol,colIsSorted);
508 }
509
524 template <class RowRangeSequence, class ColRangeSequence>
525 void addElements(RowRangeSequence const& rrs, ColRangeSequence const& crs, bool colsAreSorted=false)
526 {
527 assert(rrs.size() == crs.size());
528
529 for (auto c=std::begin(crs); c!=std::end(crs); ++c)
530 assert((*c).empty() || (*std::max_element(std::begin(*c),std::end(*c)) < columns)); // check that all column indices are ok
531
532 parallelForNodes([&rrs,&crs,colsAreSorted,this](int i, int nodes) {
533 auto c = std::begin(crs);
534 for (auto r=std::begin(rrs); r!=std::end(rrs); ++r, ++c)
535 this->creators[i].addElements(std::begin(*r),std::end(*r),std::begin(*c),std::end(*c),colsAreSorted);
536 },nodes());
537 }
538
547 {
548 parallelForNodes([this](int i, int nodes) {
549 this->creators[i].addAllElements(this->columns);
550 }, nodes());
551 }
552
557 {
558 for (Index i=0; i<std::min(rows,columns); ++i)
559 addElement(i,i);
560 }
561
567 size_t nonzeroes() const
568 {
569 size_t nnz = 0;
570 for (auto const& c: creators)
571 nnz += c.nonzeroes();
572 return nnz;
573 }
574
578 Index cols() const { return columns; }
579
587 void balance();
588
594 int nodes() const { return creators.size(); }
595
600 ChunkCreator const& creator(int node) const { return creators[node]; }
601
607 bool isSymmetric() const { return sym; }
608
609 private:
610 Index rows, columns;
611 std::vector<ChunkCreator> creators;
612 bool sym;
613 };
614
615 //---------------------------------------------------------------------------
616
622 template <class Index=size_t>
624 {
626
627 public:
628
635
640
644 template <class IndexA>
646 : patterns(p.nodes())
647 , sym(p.isSymmetric())
648 , rowSt(p.rowStart().begin(),p.rowStart().end())
649 , cols(p.M())
650 {
651 for (int i=0; i<p.nodes(); ++i)
652 patterns[i] = std::make_shared<ChunkPattern>(*p.pattern(i));
653 }
654
659 : patterns(creator.nodes()), sym(creator.isSymmetric()), rowSt(creator.nodes()+1), cols(creator.cols())
660 {
661 parallelForNodes([this,&creator](int i, int n)
662 {
663 this->patterns[i] = std::make_shared<ChunkPattern>(creator.creator(i));
664 this->rowSt[i] = this->patterns[i]->first();
665 },creator.nodes());
666 rowSt[patterns.size()] = patterns.back()->last();
667 }
668
682 template <class Expanded, class Condensed, class Matrix>
683 NumaCRSPattern(Expanded const& eIndices, Condensed const& cIndices, Matrix const& mat)
684 : patterns(NumaThreadPool::instance().nodes()), sym(false)
685 , rowSt(eIndices.size(),0), cols(eIndices.size())
686 {
687 assert(mat.M()==mat.N()); // works only for quadratic matrices
688 assert(eIndices.size() <= cIndices.size());
689
690 for (Index r=0; r<eIndices.size(); ++r) // extract the number of entries in each
691 { // row of the condensed matrix
692 auto row = mat[eIndices[r]];
693 for (auto ci=row.begin(); ci!=row.end(); ++ci)
694 if (cIndices[ci.index()] < eIndices.size()) // only count those entries that fall in our col range
695 ++rowSt[r];
696 }
697
698 equalWeightRanges(rowSt,patterns.size()); // balance the number of entries in each chunk
699
700 for (int i=0; i<patterns.size(); ++i) // create patterns
701 patterns[i] = std::make_shared<ChunkPattern>(rowSt[i],rowSt[i+1],eIndices,cIndices,mat,i);
702 }
703
718 template <class Matrix>
719 NumaCRSPattern(Matrix const& matrix, bool isSymmetric, bool isTransposed, bool symmetric)
720 : sym(symmetric), cols(isTransposed? matrix.N(): matrix.M())
721 {
722 assert(isSymmetric || !symmetric);
723
724 // Compute an equilibrated distribution of rows to chunks (attempt as many chunks as NUMA nodes).
725 Index rows = isTransposed? matrix.M(): matrix.N();
726 std::vector<size_t> rowCount(rows,0);
727 ThreadedMatrixDetail::getRowCount(matrix,isTransposed,rowCount);
729
730 // Create chunk patterns
731 patterns.reserve(rowCount.size()-1);
732 for (int i=0; i<rowCount.size()-1; ++i)
733 patterns.push_back(std::make_shared<ChunkPattern>(matrix,isSymmetric,isTransposed,
734 rowCount[i],rowCount[i+1],symmetric,i));
735
736 rowSt.resize(patterns.size()+1);
737 for (int i=0; i<patterns.size(); ++i)
738 rowSt[i] = patterns[i]->first();
739 rowSt[patterns.size()] = patterns.back()->last();
740 }
741
745
749 Index N() const { return rowSt.back(); }
750
754 Index M() const { return cols; }
755
761 size_t storage() const
762 {
763 size_t nnz = 0;
764 for (auto const& p: patterns)
765 nnz += p->storage();
766 return nnz;
767 }
768
772 size_t nonzeroes() const
773 {
774 size_t nnz = 0;
775 for (auto const& p: patterns)
776 nnz += p->nonzeroes();
777 return nnz;
778 }
779
783 int nodes() const { return patterns.size(); }
784
788 std::shared_ptr<ChunkPattern> pattern(int i) const
789 {
790 return patterns[i];
791 }
792
798 bool isSymmetric() const { return sym; }
799
806 int chunk(Index row) const
807 {
808 assert(0<=row && row<=N());
809 auto it = std::upper_bound(rowSt.begin(),rowSt.end(),row); // use upper bound here, with lower_bound rows 0 and 1 would end up
810 int c = it - rowSt.begin() - 1; // in different chunks...
811 assert(0<=c && c<=patterns.size());
812 assert(c==patterns.size() || (patterns[c]->first() <= row && row < patterns[c]->last()));
813 return c;
814 }
815
822 std::vector<Index> const& rowStart() const { return rowSt; }
823
827 bool exists(Index r, Index c) const
828 {
829 return patterns[chunk(r)]->exists(r,c);
830 }
831
832 private:
833 std::vector<std::shared_ptr<ChunkPattern>> patterns;
834 bool sym;
835 std::vector<Index> rowSt; // row start indices
836 Index cols; // how many columns the pattern has
837 };
838
839 //------------------------------------------------------------------------------------------------
840
841 template <class Index, class Index2>
843 {
844 assert(pa.N()==pb.N() && pa.M()==pb.M());
845 Index nnzPerRow = (pa.nonzeroes()+pb.nonzeroes())/pa.N();
846 NumaCRSPatternCreator<Index> creator(pa.N(),pa.M(),pa.isSymmetric()&&pb.isSymmetric(),nnzPerRow);
847
848 for (int i=0; i<pa.nodes(); ++i)
849 {
850 bool symmetrize = pa.isSymmetric() && !pb.isSymmetric();
851 auto const& chunkPattern = *pa.pattern(i);
852 Index first = chunkPattern.first();
853 for (Index row=first; row<chunkPattern.last(); ++row)
854 for (auto it=chunkPattern.colStartIterator(row-first); it!=chunkPattern.colStartIterator(row+1-first); ++it)
855 {
856 creator.addElement(row,*it);
857 if (symmetrize)
858 creator.addElement(*it,row);
859 }
860 }
861
862 for (int i=0; i<pb.nodes(); ++i)
863 {
864 bool symmetrize = pb.isSymmetric() && !pa.isSymmetric();
865 auto const& chunkPattern = *pb.pattern(i);
866 Index2 first = chunkPattern.first();
867 for (Index2 row=first; row<chunkPattern.last(); ++row)
868 for (auto it=chunkPattern.colStartIterator(row-first); it!=chunkPattern.colStartIterator(row+1-first); ++it)
869 {
870 creator.addElement(static_cast<Index>(row),*it);
871 if (symmetrize)
872 creator.addElement(*it,static_cast<Index>(row));
873 }
874 }
875
876 return NumaCRSPattern<Index>(creator);
877 }
878
879 //------------------------------------------------------------------------------------------------
880 //------------------------------------------------------------------------------------------------
881
919 template <class Entry, class Index=size_t>
921 {
923 typedef NumaBCRSMatrix<Entry,Index> Self;
924
925 public:
927 using field_type = Scalar; // for compatibility with Dune
928 using block_type = Entry;
929 using value_type = Entry; // or should this be row_type?
930 using size_type = Index; // compatibility with Dune::BCRSMatrix
931
939
941
944
947
948
953
958 : NumaBCRSMatrix(std::make_shared<NumaCRSPattern<Index>>())
959 {}
960
964 NumaBCRSMatrix(Self const& A) = default; // TODO: do this in parallel
965
969 NumaBCRSMatrix(Self&& A) = default; // move should be efficient without parallelization
970
979 NumaBCRSMatrix(NumaCRSPatternCreator<Index> const& creator, Entry const& init=Entry(0))
980 : NumaBCRSMatrix(std::make_shared<NumaCRSPattern<Index>>(creator),init)
981 {}
982
989 NumaBCRSMatrix(std::shared_ptr<NumaCRSPattern<Index>> const& pattern_, Entry const& init=Entry(0))
990 : pattern(pattern_)
991 {
992 for (int i=0; i<pattern->nodes(); ++i)
993 chunks.push_back(Chunk(i));
994
995 parallelForNodes([this,&init] (int i, int n)
996 {
997 this->chunks[i] = std::move(Chunk(this->pattern->pattern(i),init));
998 },chunks.size());
999
1000 dps.resize(chunks.size());
1001 }
1002
1008 template <class Expanded, class Condensed, class Matrix>
1009 NumaBCRSMatrix(Expanded const& eIndices, Condensed const& cIndices, Matrix const& mat)
1010 : pattern(std::make_shared<NumaCRSPattern<Index>>(eIndices,cIndices,mat)) // TODO: move this to private, and have a convenience constructor creating cIndices under the hood
1011 {
1012 chunks.reserve(pattern->nodes());
1013 for (int i=0; i<pattern->nodes(); ++i)
1014 chunks.push_back(Chunk(pattern->pattern(i),eIndices,cIndices,mat)); // TODO: do this in parallel
1015 dps.resize(chunks.size());
1016 }
1017
1018 private:
1019
1020 // Creates a vector cIndices that for each index in the source matrix tells
1021 // the index in the extracted submatrix (or a too large sentinel value if the
1022 // index is not contained in the submatrix). I.e. result[eIndices[i]]==i
1023 // for 0 <= i < eIndices.size(), and result[j]>=eIndices.size() otherwise.
1024 template <class Expanded>
1025 static std::vector<Index> createCondensed(Expanded const& eIndices, Index n)
1026 {
1027 std::vector<Index> cIndices(n,eIndices.size());
1028 for (Index i=0; i<eIndices.size(); ++i)
1029 cIndices[eIndices[i]] = i;
1030 return cIndices;
1031 }
1032
1033 public:
1034
1047 template <class Expanded, class Matrix>
1048 NumaBCRSMatrix(Expanded const& eIndices, Matrix const& mat)
1049 : NumaBCRSMatrix(eIndices,createCondensed(eIndices,mat.N()),mat)
1050 { }
1051
1052
1064 template <class Matrix>
1065 NumaBCRSMatrix(std::shared_ptr<NumaCRSPattern<Index>> const& pattern_, Matrix const& matrix,
1066 bool isSymmetric, bool isTransposed)
1067 : pattern(pattern_)
1068 {
1069 chunks.reserve(pattern->nodes());
1070 for (int i=0; i<pattern->nodes(); ++i)
1071 chunks.push_back(Chunk(pattern->pattern(i),matrix,isSymmetric,isTransposed)); // TODO: do this in parallel
1072 dps.resize(chunks.size());
1073 }
1074
1087 template <class OtherEntry>
1089 : NumaBCRSMatrix(matrix.getPattern(),matrix,matrix.getPattern()->isSymmetric(),false)
1090 { }
1091
1109 template <class Matrix>
1110 NumaBCRSMatrix(Matrix const& matrix,
1111 bool isSymmetric, bool isTransposed=false, bool symmetric=false)
1112 : NumaBCRSMatrix(std::make_shared<NumaCRSPattern<Index>>(matrix,isSymmetric,isTransposed,symmetric),
1113 matrix,isSymmetric,isTransposed)
1114 {
1115 assert(matrix.N()==matrix.M() || !(symmetric||isSymmetric)); // only go into symmetric mode if the matrix is square
1116 assert(Entry::rows==Entry::cols || !(symmetric||isSymmetric)); // symmetry only if the entries are square
1117
1118 // Make sure symmetry is handled correctly (even if not in debug mode). TODO: shall we take this as a feature instead of complaining via assert?
1119 symmetric &= Entry::rows==Entry::cols && matrix.N()==matrix.M();
1120 isSymmetric &= Entry::rows==Entry::cols && matrix.N()==matrix.M();
1121 }
1122
1142 bool isSymmetric, bool isTransposed=false, bool symmetric=false)
1143 : NumaBCRSMatrix(isTransposed==false && isSymmetric==symmetric? matrix.pattern // just copy
1144 : std::make_shared<NumaCRSPattern<Index>>(matrix,isSymmetric,isTransposed,symmetric),
1145 matrix,isSymmetric,isTransposed)
1146 {
1147 assert(matrix.N()==matrix.M() || !(symmetric||isSymmetric)); // only go into symmetric mode if the matrix is square
1148 assert(Entry::rows==Entry::cols || !(symmetric||isSymmetric)); // symmetry only if the entries are square
1149 assert(isTransposed? (matrix.N()==M() && matrix.M()==N()): (matrix.N()==N() && matrix.M()==M()));
1150 assert(!isTransposed || Entry::rows==Entry::cols);
1151 }
1152
1166 template <class TripletIndex, class TripletScalar>
1167 NumaBCRSMatrix(std::vector<TripletIndex> const& ridx, std::vector<TripletIndex> const& cidx,
1168 TripletIndex nRows, TripletIndex nCols,
1169 std::vector<TripletScalar> const& entries)
1170 : NumaBCRSMatrix()
1171 {
1172 int const nr = EntryTraits<Entry>::rows;
1173 int const nc = EntryTraits<Entry>::cols;
1174
1175 assert(ridx.size()==cidx.size() && cidx.size()==entries.size());
1176
1177 // Create the sparsity pattern
1178 NumaCRSPatternCreator<Index> creator(nRows,nCols);
1179 for (size_t i=0; i<entries.size(); ++i)
1180 creator.addElement(ridx[i]/nr,cidx[i]/nc);
1181
1182 // Copy entries into the matrix
1183 NumaBCRSMatrix<Entry,Index> A(creator);
1184 for (size_t i=0; i<entries.size(); ++i)
1185 if constexpr (nr==1 && nc==1) // we have scalar entries and can assign directly
1186 A[ridx[i]][cidx[i]] += entries[i];
1187 else // we have matrix-valued entries and assign sub-elements
1188 A[ridx[i]/nr][cidx[i]/nc][ridx[i]%nr][cidx[i]%nc] += entries[i];
1189
1190 *this = std::move(A);
1191 }
1192
1193
1195
1200
1207 Self& operator=(Self const& mat) = default;
1208
1214 Self& operator=(Self&& mat) = default;
1215
1222 template <class EntryA, class IndexA,
1223 typename = std::enable_if_t<std::is_convertible_v<EntryA,Entry>>>
1225 {
1226 // If the index types agree, we can simply use the exact same pattern and share it.
1227 // Otherwise, we need to copy the given pattern into our own.
1228 if constexpr (std::is_same_v<Index,IndexA>)
1229 pattern = A.getPattern();
1230 else
1231 pattern.reset(new NumaCRSPattern<Index>(*A.getPattern()));
1232
1233 chunks.clear();
1234 chunks.reserve(pattern->nodes());
1235 for (int i=0; i<pattern->nodes(); ++i)
1236 chunks.push_back(Chunk(pattern->pattern(i),A.chunk(i)));
1237 dps.resize(chunks.size());
1238
1239 return *this;
1240 }
1241
1245 Self& operator=(Entry const& a)
1246 {
1247 if (chunks.size()>0)
1248 parallelForNodes([this,&a] (int i, int n)
1249 {
1250 this->chunks[i] = a;
1251 },chunks.size());
1252
1253 return *this;
1254 }
1255
1259 Self& operator=(typename Entry::field_type const& a)
1260 {
1261 return *this = Entry(a);
1262 }
1263
1267 template <class Arguments, class Operation>
1269 {
1270 if (chunks.size()>0)
1271 parallelForNodes([this,&e] (int i, int n)
1272 {
1273 this->chunks[i] = e[i];
1274 },chunks.size());
1275
1276 return *this;
1277 }
1278
1284 template <class EntryB, class IndexB>
1286 {
1287 entrywiseOp([](Entry const& a, Entry const& b) { return a+b; }, B);
1288 return *this;
1289 }
1290
1296 template <class EntryB, class IndexB>
1298 {
1299 entrywiseOp([](Entry const& a, Entry const& b) { return a-b; }, B);
1300 return *this;
1301 }
1302
1308 template <class Factor>
1309 Self& operator*=(Factor a)
1310 {
1311 entrywiseOp([=](Entry const& e, Entry const&) { return a*e; }, *this);
1312 return *this;
1313 }
1314
1316
1335
1342 iterator begin() { return iterator(*this,0); }
1343 const_iterator begin() const { return const_iterator(*this,0); }
1344
1348 iterator end() { return iterator(*this,N()); }
1349 const_iterator end() const { return const_iterator(*this,N()); }
1350
1356 row_type operator[](Index r) { return iterator(*this,r); }
1357 const_row_type operator[](Index r) const { return const_iterator(*this,r); }
1358
1360
1365 template <class RowIndices, class ColIndices>
1366 Self operator()(RowIndices const& ri, ColIndices const& ci) const
1367 {
1368 return submatrix<Self>(*this,ri,ci);
1369 };
1370
1374
1379
1383 Index N() const { return pattern->N(); }
1384
1388 Index M() const { return pattern->M(); }
1389
1396 size_t nonzeroes() const
1397 {
1398 return pattern->nonzeroes();
1399 }
1400
1404 std::shared_ptr<NumaCRSPattern<Index>> getPattern() const
1405 {
1406 return pattern;
1407 }
1408
1412 Chunk& chunk(int i)
1413 {
1414 return chunks[i];
1415 }
1416
1417 Chunk const& chunk(int i) const
1418 {
1419 return chunks[i];
1420 }
1421
1425 bool exists(Index r, Index c) const
1426 {
1427 return pattern->exists(r,c);
1428 }
1429
1435 {
1436 return sqrt(frobenius_norm2());
1437 }
1438
1444 {
1445 field_type sum = 0;
1446 for (auto ri=begin(); ri!=end(); ++ri)
1447 for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
1448 sum += ci->frobenius_norm2();
1449 return sqrt(sum);
1450 }
1451
1453
1458
1464 template <class X, class Y>
1465 field_type mv(X const& x, Y& y) const { return doMv(1.0,x,y,true); }
1466
1475 template <class X, class Y>
1476 void mtv(X const& x, Y& y) const { doMtv(1.0,x,y,true); }
1477
1481 template <class X, class Y>
1482 void mmv(X const& x, Y& y) const { doMv(-1.0,x,y,true); }
1483
1487 template <class X, class Y>
1488 field_type smv(field_type const& a, X const& x, Y& y) const { return doMv(a,x,y,true); }
1489
1496 template <class X, class Y>
1497 void smtv(field_type const& a, X const& x, Y& y) const { doMtv(a,x,y,true); }
1498
1502 template <class X, class Y>
1503 field_type umv(X const& x, Y& y) const { return doMv(1.0,x,y,false); }
1504
1511 template <class X, class Y>
1512 void umtv(X const& x, Y& y) const { doMtv(1.0,x,y,false); }
1513
1517 template <class X, class Y>
1518 field_type usmv(field_type const& a, X const& x, Y& y) const { return doMv(a,x,y,false); }
1519
1526 template <class X, class Y>
1527 void usmtv(field_type const& a, X const& x, Y& y) const { doMtv(a,x,y,false); }
1528
1530
1535
1560 template <class LMIterator>
1561 void scatter(LMIterator first, LMIterator last)
1562 {
1563 for (auto& c: chunks) // TODO: run this in parallel on NUMA nodes
1564 c.scatter(first,last);
1565 }
1566
1591 template <class RowIndices, class ColIndices, class BinaryOp=std::plus<Entry>>
1592 void scatter(DynamicMatrix<Entry> const& B, RowIndices const& rows, ColIndices const& cols,
1593 BinaryOp const& op = BinaryOp())
1594 {
1595 // TODO: implement this in the chunks for performance
1596 for (int r=0; r<rows.size(); ++r)
1597 for (int c=0; c<cols.size(); ++c)
1598 {
1599 auto ci = (*this)[rows[r]].find(cols[c]);
1600 assert(ci!=(*this)[rows[r]].end());
1601 *ci = op(*ci,B[r][c]);
1602 }
1603 }
1604
1606
1607
1608 private:
1609 std::shared_ptr<NumaCRSPattern<Index>> pattern;
1610 std::vector<Chunk> chunks;
1611 mutable std::vector<field_type> dps; // could be local to doMv, but we don't like frequent reallocations
1612
1613
1614 // Perform matrix-vector multiplication y = (initToZero? 0: y) + a A x and return a x^T Ax
1615 template <class X, class Y>
1616 Scalar doMv(Scalar const& a, X const& x, Y& y, bool initToZero) const
1617 {
1618 assert(y.size()==N());
1619 assert(x.size()==M());
1620
1621 if (chunks.size()>1)
1622 {
1623 parallelForNodes([this,a,&x,&y,initToZero] (int i, int n)
1624 {
1625 if (pattern->isSymmetric()) // if it's symmetric, we have to add the transpose of the other blocks
1626 for (int k=i; k<n; ++k)
1627 this->chunks[i].gatherMirrored(a,x,y,this->chunks[k],true,initToZero&&k==i);
1628 this->dps[i] = this->chunks[i].apply(a,x,y,initToZero&&!pattern->isSymmetric());
1629 },chunks.size());
1630
1631 return std::accumulate(dps.begin(),dps.end(),0.0);
1632 }
1633 else
1634 {
1635 if (pattern->isSymmetric())
1636 chunks[0].gatherMirrored(a,x,y,chunks[0],true,initToZero);
1637 return chunks[0].apply(a,x,y,initToZero&&!pattern->isSymmetric());
1638 }
1639 }
1640
1641 // Perform transpose matrix-vector multiplication y = a A^T x and return y^T x
1642 template <class X, class Y>
1643 void doMtv(Scalar const& a, X const& x, Y& y, bool initToZero) const
1644 {
1645 assert(y.size()==M());
1646 assert(x.size()==N());
1647
1648 if (pattern->isSymmetric()) // matrix is symmetric, hence we can multiply with A instead of A^T
1649 doMv(a,x,y,initToZero);
1650 else
1651 {
1652 if (initToZero)
1653 y = 0;
1654 for (auto const& chunk: chunks) // WARNING: applyTransposed is not thread-safe due to global unstructured scattering
1655 chunk.applyTransposed(a,x,y); // into y. It is possible to parallelize this, in a window-shingled fashion, but is
1656 } // it worth the implementation effort?
1657 }
1658
1659 // performs elementwise operations on two matrices (most useful for axpy-like operations):
1660 // a_ij = f(a_ij,b_ij)
1661 // This affects exactly the entries present in *both* matrices. Others are unchanged. Matrices have to have the same shape.
1662 template <class F, class EntryB, class IndexB>
1663 void entrywiseOp(F const& f, NumaBCRSMatrix<EntryB,IndexB> const& B)
1664 {
1665 assert(N()==B.N() && M()==B.M());
1666 parallelForNodes([this,&f,&B](int i, int n)
1667 {
1668 this->chunks[i].entrywiseOp(f,B);
1669 },chunks.size());
1670 }
1671 };
1672
1673 // ------------------------------------------------------------------------------------------
1674
1682 template <class Entry, class Index>
1683 std::ostream& operator <<(std::ostream& out, NumaBCRSMatrix<Entry,Index> const& A)
1684 {
1685 constexpr int const nr = EntryTraits<Entry>::rows;
1686 constexpr int const nc = EntryTraits<Entry>::cols;
1687
1688 for (auto ri=A.begin(); ri!=A.end(); ++ri)
1689 for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
1690 if constexpr (nr>1 || nc>1)
1691 {
1692 for (int k=0; k<nr; ++k)
1693 for (int l=0; l<nc; ++l)
1694 out << nr*ri.index()+k << ' ' << nc*ci.index()+l << ' ' << (*ci)[k][l] << '\n';
1695 }
1696 else
1697 out << ri.index() << ' ' << ci.index() << ' ' << *ci << '\n';
1698
1699 return out;
1700 }
1701
1702 // ----------------------------------------------------------------------------------------------
1703
1712 template <class SparseMatrix>
1714 {
1716 for (auto ri=A.begin(); ri!=A.end(); ++ri)
1717 for (auto ci=ri->begin(); ci!=ri->end(); ++ci)
1718 B[ri.index()][ci.index()] = *ci;
1719 return B;
1720 }
1721
1739 template <class SparseMatrix, class RowRange, class ColRange>
1740 DynamicMatrix<typename SparseMatrix::block_type> full(SparseMatrix const& A, RowRange const& rows, ColRange const& cols)
1741 {
1742 using std::begin;
1743 using std::end;
1744 using Index = typename ColRange::value_type;
1745
1746 // First we prepare a lookup structure for efficient determination where
1747 // a sparse matrix entry should end up.
1748 std::vector<std::pair<Index,Index>> cidx;
1749 cidx.reserve(cols.size());
1750
1751 Index i=0;
1752 for (auto c: cols)
1753 {
1754 cidx.push_back(std::make_pair(c,i));
1755 ++i;
1756 }
1757 std::sort(begin(cidx),end(cidx),FirstLess());
1758
1759 // Now create the matrix and extract the entries.
1760 DynamicMatrix<typename SparseMatrix::block_type> B(rows.size(),cols.size());
1761
1762 for (size_t r=0; r<rows.size(); ++r)
1763 for (auto ci=A[rows[r]].begin(); ci!=A[rows[r]].end(); ++ci)
1764 {
1765 auto it = std::lower_bound(begin(cidx),end(cidx),
1766 std::make_pair(ci.index(),ci.index()),FirstLess());
1767 if (it!=end(cidx) && it->first==ci.index()) // this is an entry from our column range
1768 B[r][it->second] = *ci;
1769 }
1770
1771 return B;
1772 }
1773
1774 // ----------------------------------------------------------------------------------------------
1775
1783 template <class Entry, class Index, class Index2>
1785 {
1786 auto pat = std::make_shared<NumaCRSPattern<Index>>(*A.getPattern()+*B.getPattern());
1788 assert(!A.getPattern()->isSymmetric() && !B.getPattern()->isSymmetric());
1789
1790 // TODO: parallelize
1791 for (Index row=0; row<AB.N(); ++row)
1792 {
1793 auto ABrow = AB[row];
1794 for (auto ci=A[row].begin(); ci!=A[row].end(); ++ci)
1795 ABrow[ci.index()] += *ci;
1796 for (auto ci=B[row].begin(); ci!=B[row].end(); ++ci)
1797 ABrow[static_cast<Index>(ci.index())] += *ci;
1798 }
1799 return AB;
1800 }
1801
1802 // ----------------------------------------------------------------------------------------------
1803
1804
1816 template <class Scalar, int n, class Index=size_t>
1818 {
1819 NumaCRSPatternCreator<Index> creator(N,N,false,1);
1820 for (Index i=0; i<N; ++i)
1821 creator.addElement(i,i);
1823 }
1824
1825
1826 // ----------------------------------------------------------------------------------------------
1827
1828
1840 template <class Scalar, int n, int m, class Index=size_t>
1842 {
1843 NumaCRSPatternCreator<Index> creator(N,M,false,1);
1844 return NumaBCRSMatrix<Dune::FieldMatrix<Scalar,n,m>,Index>(creator);
1845 }
1846
1847 // ----------------------------------------------------------------------------------------------
1848
1854 template <class Entry, class Index>
1856 {
1858 return At;
1859 }
1860
1861 // ----------------------------------------------------------------------------------------------
1862
1863
1877 template <class Target, class Source, class RowIndices, class ColIndices>
1878 Target eraseRowsNCols(Source const& A, RowIndices const& ri, ColIndices const& ci)
1879 {
1880 // rows and columns to keep
1881 std::vector<size_t> rows(A.N()), cols(A.M());
1882 std::iota(rows.begin(),rows.end(),0); // vector of rows to keep
1883 std::iota(cols.begin(),cols.end(),0); // vector of columns to keep
1884
1885 if(!ri.empty())
1886 for(int i=0; i<ri.size();++i)
1887 rows.erase(rows.begin() + ri[i]); // erase the corresponding row indices
1888
1889 if(!ci.empty())
1890 for(int i=0; i<ci.size();++i)
1891 cols.erase(cols.begin() + ci[i]); // erase the corresponding columns indices
1892
1893 return submatrix(A,rows,cols);
1894 }
1895
1908 template <class Target, class Source, class RowIndices>
1909 Target eraseRows(Source const& A, RowIndices const& ri)
1910 {
1911 // empty column vector (no columns to delete)
1912 std::vector<size_t> cols;
1913 return eraseRowsNCols(A,ri,cols);
1914 }
1915
1928 template <class Target, class Source, class ColIndices>
1929 Target eraseCols(Source const& A, ColIndices const& ci)
1930 {
1931 // empty row vector (no rows to delete)
1932 std::vector<size_t> rows;
1933 return eraseRowsNCols(A,rows,ci);
1934 }
1935
1936
1947 template <class Source>
1948 std::vector<size_t> nonZeroColumns(Source const& A)
1949 {
1950 // flag vector:
1951 // 1 = non zero column
1952 // 0 = zero column
1953 std::vector<size_t> nzFlags(A.M(),0);
1954 for(auto r=A.begin(); r!=A.end(); ++r)
1955 for(auto c=r->begin(); c!= r->end(); ++c)
1956 nzFlags.at(c.index()) = 1;
1957
1958 // build column index vector
1959 std::vector<size_t> nzCols;
1960 for(int i=0; i<nzFlags.size(); ++i)
1961 if(nzFlags.at(i) == 1) nzCols.push_back(i);
1962
1963 return nzCols;
1964 }
1965
1966
1984 template<int row2, int col2, int row1, int col1, class Scalar, class Index>
1987 {
1988 // If there is nothing to convert, we can simply return A itself (actually a copy)
1989 // and be done.
1990 if constexpr (row2==row1 && col2==col1)
1991 return A;
1992
1993 static_assert(row1 % row2 == 0);
1994 static_assert(col1 % col2 == 0);
1995 int const qN = row1/row2;
1996 int const qM = col1/col2;
1997
1998 Index N = A.N()*qN;
1999 Index M = A.M()*qM;
2000 NumaCRSPatternCreator<Index> creator(N, M, A.getPattern()->isSymmetric());
2001
2002 for(auto row=A.begin(); row!=A.end(); ++row)
2003 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in A
2004 for(int i=0; i<qN; ++i)
2005 for(int j=0; j<qM; ++j)
2006 creator.addElement(row.index()*qN + i, col.index()*qM + j); // create qN*qM non-zero entries in B
2007
2008
2009 NumaBCRSMatrix<Dune::FieldMatrix<Scalar,row2,col2>, Index> B(creator); // empty matrix with sparsity pattern
2010
2011 for(auto row=A.begin(); row!=A.end(); ++row)
2012 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in A
2013 {
2014 Dune::FieldMatrix<Scalar,row1,col1> mat = *col; // get block entry of A
2015 for(int k=0; k<row1; ++k)
2016 for(int l=0; l<col1; ++l) // add data at corresponding entries of B
2017 B[row.index()*qN + k/row2][col.index()*qM + l/col2][k%row2][l%col2] = mat[k][l];
2018 }
2019
2020 return B;
2021 }
2022
2023
2024
2037 template<int blockrows, int blockcols, class Scalar, class Index>
2041 {
2042 assert(A.N() == B.N());
2043 Index cols = (A.M() + B.M());
2044 Index rows = A.N();
2045
2046 NumaCRSPatternCreator<Index> creator(rows, cols, false);
2047
2048 //loop over non-zero elements in A
2049 for(auto row=A.begin(); row!=A.end(); ++row)
2050 for(auto col=row->begin(); col!=row->end(); ++col)
2051 creator.addElement(row.index(), col.index());
2052 //loop over non-zero elements in B
2053 for(auto row=B.begin(); row!=B.end(); ++row)
2054 for(auto col=row->begin(); col!=row->end(); ++col)
2055 creator.addElement(row.index(), col.index()+A.M()); // append columns on the right
2056
2057
2058 NumaBCRSMatrix<Dune::FieldMatrix<Scalar,blockrows,blockcols>,Index> result(creator); //empty matrix with sparsity pattern
2059
2060 for(auto row=A.begin(); row!=A.end(); ++row)
2061 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in A
2062 result[row.index()][col.index()] = *col;
2063
2064 for(auto row=B.begin(); row!=B.end(); ++row)
2065 for(auto col=row->begin(); col!=row->end(); ++col)
2066 result[row.index()][col.index()+A.M()] = *col;
2067
2068
2069 return result;
2070 }
2071
2084 template<int blockrows, int blockcols, class Scalar, class Index>
2088 {
2089 assert(A.M() == B.M());
2090 Index cols = A.M();
2091 Index rows = (A.N()+B.N());
2092 NumaCRSPatternCreator<Index> creator(rows, cols, false);
2093
2094 //loop over non-zero elements in A
2095 for(auto row=A.begin(); row!=A.end(); ++row)
2096 for(auto col=row->begin(); col!=row->end(); ++col)
2097 creator.addElement(row.index(), col.index());
2098 //loop over non-zero elements in B
2099 for(auto row=B.begin(); row!=B.end(); ++row)
2100 for(auto col=row->begin(); col!=row->end(); ++col)
2101 creator.addElement(row.index()+A.N(), col.index()); // append columns on the right
2102
2103
2104 NumaBCRSMatrix<Dune::FieldMatrix<Scalar,blockrows,blockcols>, Index> result(creator); //empty matrix with sparsity pattern
2105
2106 for(auto row=A.begin(); row!=A.end(); ++row)
2107 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in A
2108 result[row.index()][col.index()] = *col;
2109
2110 for(auto row=B.begin(); row!=B.end(); ++row)
2111 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in B
2112 result[row.index()+A.N()][col.index()] = *col;
2113
2114 return result;
2115 }
2116
2117
2131 template<int blockrows, int blockcols, class Index=size_t>
2134 {
2135 Index cols = (A.M()+B.M());
2136 Index rows = (A.N()+B.N());
2137 NumaCRSPatternCreator<Index> creator(rows, cols, false);
2138
2139 //loop over non-zero elements in A
2140 for(auto row=A.begin(); row!=A.end(); ++row)
2141 for(auto col=row->begin(); col!=row->end(); ++col)
2142 creator.addElement(row.index(), col.index());
2143 //loop over non-zero elements in B
2144 for(auto row=B.begin(); row!=B.end(); ++row)
2145 for(auto col=row->begin(); col!=row->end(); ++col)
2146 creator.addElement(row.index()+A.N(), col.index()+A.M()); // append columns on the right
2147
2148
2149 NumaBCRSMatrix<Dune::FieldMatrix<double,blockrows,blockcols>, Index> result(creator); //empty matrix with sparsity pattern
2150
2151 for(auto row=A.begin(); row!=A.end(); ++row)
2152 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in A
2153 {
2154 auto mat = *col;
2155 for(int k=0; k < blockrows; ++k)
2156 for(int l= 0; l < blockcols; ++l)
2157 result[row.index()][col.index()][k][l] =mat[k][l];
2158 }
2159
2160 for(auto row=B.begin(); row!=B.end(); ++row)
2161 for(auto col=row->begin(); col!=row->end(); ++col) // loop over non-zero elements in B
2162 {
2163 auto mat = *col;
2164 for(int k=0; k < blockrows; ++k)
2165 for(int l= 0; l < blockcols; ++l)
2166 result[row.index()+A.N()][col.index()+A.M()][k][l] = mat[k][l];
2167 }
2168
2169
2170 return result;
2171 }
2172
2173} // end namespace Kaskade
2174
2175#endif
A LAPACK-compatible dense matrix class with shape specified at runtime.
An exception that can be thrown whenever a key lookup fails.
A NUMA-aware compressed row storage matrix adhering mostly to the Dune ISTL interface (to complete....
iterator end()
returns an iterator to the first row
Self & operator-=(NumaBCRSMatrix< EntryB, IndexB > const &B)
Subtracts a sparse matrix from this one.
NumaBCRSMatrix(Expanded const &eIndices, Condensed const &cIndices, Matrix const &mat)
Deprecated. Use simpler version without cIndices instead.
void mmv(X const &x, Y &y) const
Matrix-vector multiplication .
NumaBCRSMatrix(NumaBCRSMatrix< OtherEntry, Index > const &matrix)
Constructor copying a given matrix.
NumaBCRSMatrix(Matrix const &matrix, bool isSymmetric, bool isTransposed=false, bool symmetric=false)
Constructor.
Self & operator=(Self &&mat)=default
Move assignment.
Chunk & chunk(int i)
Obtains a reference to the given chunk.
Self & operator=(ThreadedMatrixDetail::NumaBCRSMatrixExpression< Arguments, Operation > const &e)
NOT YET IMPLEMENTED Assigns the given Numa matrix expression.
Self & operator+=(NumaBCRSMatrix< EntryB, IndexB > const &B)
Adds a sparse matrix to this one.
size_t nonzeroes() const
Returns the number of structurally nonzero elements.
Chunk const & chunk(int i) const
NumaBCRSMatrix(Self &&A)=default
Move constructor.
Self & operator*=(Factor a)
Multiplication with a "scalar".
NumaBCRSMatrix(std::shared_ptr< NumaCRSPattern< Index > > const &pattern_, Entry const &init=Entry(0))
Constructor creating a matrix from a given sparsity pattern.
std::shared_ptr< NumaCRSPattern< Index > > getPattern() const
Returns a pointer to the sparsity pattern.
Self & operator=(typename Entry::field_type const &a)
Assigns the given scalar value to each entry.
NumaBCRSMatrix(NumaCRSPatternCreator< Index > const &creator, Entry const &init=Entry(0))
Constructor creating a matrix from a given sparsity pattern creator.
bool exists(Index r, Index c) const
returns true if (r,c) is structurally nonzero
void scatter(DynamicMatrix< Entry > const &B, RowIndices const &rows, ColIndices const &cols, BinaryOp const &op=BinaryOp())
Scatters given submarix into the matrix.
NumaBCRSMatrix(std::vector< TripletIndex > const &ridx, std::vector< TripletIndex > const &cidx, TripletIndex nRows, TripletIndex nCols, std::vector< TripletScalar > const &entries)
Constructor.
field_type smv(field_type const &a, X const &x, Y &y) const
Matrix-vector multiplication .
void scatter(LMIterator first, LMIterator last)
Scatters given sub-matrices into the matrix by adding up their entries.
const_iterator end() const
NumaBCRSMatrix()
Constructs an empty 0x0 matrix.
NumaBCRSMatrix(Self const &A)=default
Copy constructor.
Self & operator=(NumaBCRSMatrix< EntryA, IndexA > const &A)
Copy assignment from another NumaBCRSMatrix, with compatible entry and index types.
NumaBCRSMatrix(std::shared_ptr< NumaCRSPattern< Index > > const &pattern_, Matrix const &matrix, bool isSymmetric, bool isTransposed)
Constructor copying a given matrix.
ThreadedMatrixDetail::NumaBCRSMatrixIterator< Dune::FieldMatrix< Scalar, 1, 1 >, Index > iterator
Self & operator=(Entry const &a)
Assigns the given value to each entry.
NumaBCRSMatrix(Expanded const &eIndices, Matrix const &mat)
Indexed submatrix constructor.
iterator begin()
returns an iterator to the first row
field_type usmv(field_type const &a, X const &x, Y &y) const
Matrix-vector multiplication and subsequent computation of if A is square.
row_type operator[](Index r)
Subscript operator allowing random access to rows.
const_row_type operator[](Index r) const
void umtv(X const &x, Y &y) const
Matrix-vector multiplication .
const_iterator begin() const
field_type frobenius_norm() const
Computes the Frobenius norm .
ThreadedMatrixDetail::NumaBCRSMatrixConstIterator< Dune::FieldMatrix< Scalar, 1, 1 >, Index > const_iterator
NumaBCRSMatrix(NumaBCRSMatrix< Entry, Index > const &matrix, bool isSymmetric, bool isTransposed=false, bool symmetric=false)
Constructor.
Self & operator=(Self const &mat)=default
Copy assignment.
void smtv(field_type const &a, X const &x, Y &y) const
Matrix-vector multiplication .
void usmtv(field_type const &a, X const &x, Y &y) const
Matrix-vector multiplication .
field_type umv(X const &x, Y &y) const
Matrix-vector multiplication and subsequent computation of if A is square.
Self operator()(RowIndices const &ri, ColIndices const &ci) const
Index M() const
The number of columns.
void mtv(X const &x, Y &y) const
Matrix-vector multiplication .
field_type frobenius_norm2() const
Computes the square of the Frobenius norm .
Index N() const
The number of rows.
ScalarType< Dune::FieldMatrix< Scalar, 1, 1 > > Scalar
field_type mv(X const &x, Y &y) const
Matrix-vector multiplication with computation of if A is square.
A NUMA-aware creator for matrix sparsity patterns.
Index cols() const
The number of columns.
void addElements(IterRow const fromRow, IterRow const toRow, IterCol const fromCol, IterCol const toCol, bool colIsSorted=false)
Enters entries into the sparsity pattern.
ChunkCreator const & creator(int node) const
Returns the chunk creator.
void balance()
Redistributes the rows to the NUMA chunks in order to have the same number of entries in each chunk.
void addElement(Index row, Index col)
Enters a single entry into the sparsity pattern.
int nodes() const
Returns the number of NUMA nodes/chunks used.
void addElements(RowRangeSequence const &rrs, ColRangeSequence const &crs, bool colsAreSorted=false)
Enters elements into the sparsity pattern.
size_t nonzeroes() const
The number of structurally nonzero elements.
void addAllElements()
Enters all possible elements (defining a dense matrix).
bool isSymmetric() const
Returns the symmetry status of the pattern.
NumaCRSPatternCreator(Index rows_, Index cols, bool symmetric=false, int nnzPerRow=0)
Constructs a rows times cols matrix sparsity structure creator.
void addDiagonal()
Enters the diagonal elements.
void addDenseBlock(Index fromRow, Index toRow, Index fromCol, Index toCol)
Enters a contiguous dense block into the sparsity pattern.
A NUMA-aware compressed row storage sparsity pattern.
std::shared_ptr< ChunkPattern > pattern(int i) const
Returns the individual pattern of chunk i.
int nodes() const
Returns the number of NUMA nodes/chunks used.
int chunk(Index row) const
Returns the number of the chunk containing the given row.
Index N() const
The number of rows.
NumaCRSPattern()
Constructs an empty 0x0 pattern.
NumaCRSPattern(NumaCRSPatternCreator< Index > const &creator)
Constructor creating a sparsity pattern from the given creator.
NumaCRSPattern(Expanded const &eIndices, Condensed const &cIndices, Matrix const &mat)
Constructor.
NumaCRSPattern(NumaCRSPattern< IndexA > const &p)
Copy constructor.
bool isSymmetric() const
Returns the symmetry status of the pattern.
Index M() const
The number of columns.
std::vector< Index > const & rowStart() const
Returns the limiting row indices between the chunks.
size_t nonzeroes() const
Returns the number of structurally nonzero entries.
size_t storage() const
Returns the number of stored entries.
bool exists(Index r, Index c) const
queries whether an entry is present in the sparsity pattern
NumaCRSPattern(Matrix const &matrix, bool isSymmetric, bool isTransposed, bool symmetric)
Constructor extracting the sparsity pattern of a given matrix (usually a Dune::BCRSMatrix).
Implementation of thread pools suitable for parallelization of (more or less) memory-bound algorithms...
Definition threading.hh:299
static NumaThreadPool & instance(int maxThreads=std::numeric_limits< int >::max())
Returns a globally unique thread pool instance.
int nodes() const
Reports the number of NUMA nodes (i.e., memory interfaces/CPU sockets)
Definition threading.hh:327
This class stores a couple of compressed row storage rows in memory allocated locally on a NUMA node.
CRSChunkPattern< Index > const & pattern() const
Returns the sparsity pattern of this chunk.
A class supporting two-stage construction of sparsity patterns of NUMA matrix chunks.
This class maintains the sparsity structure of a couple of matrix rows (a NUMA matrix chunk).
NumaBCRSMatrixConstIterator(NumaBCRSMatrix< Entry, Index > const &matrix_, Index row_)
Row const & operator*() const
Dereferentiation yields the row.
An iterator stepping through all entries in a row.
NumaBCRSMatrixConstRowIterator(ColIterator col_, ValueIterator val_)
NumaBCRSMatrixConstRowIterator< Entry, Index > Self
std::vector< Entry, NumaAllocator< Entry > >::const_iterator ValueIterator
typename std::vector< Index, NumaAllocator< Index > >::const_iterator ColIterator
ThreadedMatrixDetail::NumaBCRSMatrixExpressionChunk< Arguments, Operation > const & operator[](int i) const
NumaBCRSMatrixIterator(NumaBCRSMatrix< Entry, Index > &matrix_, Index row_)
std::vector< Entry, NumaAllocator< Entry > >::iterator ValueIterator
NumaBCRSMatrixRowIterator(ColIterator col_, ValueIterator val_)
std::vector< Index, NumaAllocator< Index > >::const_iterator ColIterator
Entry const & operator[](Index c) const
Random read access to row entries by global column index.
NumaBCRSMatrixRowIterator< Entry, Index > Iterator
void update(NumaBCRSMatrix< Entry, Index > &matrix, Index row, int chunk)
Entry & operator[](Index c)
Random write access to row entries by global column index.
Iterator find(Index c)
Looks up a particular entry specified by column index.
ConstIterator begin() const
Start of row entries.
size_type size() const
Returns the number of entries in the current row.
Index const * getindexptr() const
Low-level access to array of (sorted) column indices in this row.
block_type const * getptr() const
Low-level access to array of values in this row.
std::vector< Index, NumaAllocator< Index > >::const_iterator ColIterator
NumaBCRSMatrixConstRowIterator< Entry, Index > ConstIterator
std::vector< Entry, NumaAllocator< Entry > >::iterator ValueIterator
ConstIterator find(Index c) const
Looks up a particular entry specified by column index.
This file contains various utility functions that augment the basic functionality of Dune.
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, row2, col2 >, Index > reshapeBlocks(NumaBCRSMatrix< Dune::FieldMatrix< Scalar, row1, col1 >, Index > const &A)
reshapes NumaBRCSMAtrix entry block structure
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, n, n >, Index > sparseUnitMatrix(Index N)
creates a unit matrix in NUMA block compressed row storage format
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > vertcat(NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > const &A, NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > const &B)
concatenate two matrices vertically
auto transpose(NumaBCRSMatrix< Entry, Index > const &A)
Creates the transposed sparse matrix .
DynamicMatrix< typename SparseMatrix::block_type > full(SparseMatrix const &A)
Converts a sparse NumaBCRSMatrix to a dense matrix.
Target submatrix(Source const &A, RowIndices const &ri, ColIndices const &ci)
extracts a sparse or dense submatrix of
Definition matrixOps.hh:183
Dune::FieldMatrix< T, n, n > unitMatrix()
Returns the identity matrix of size n .
Definition fixdune.hh:506
Target eraseCols(Source const &A, ColIndices const &ci)
"deletes" columns by extracting a copy of the matrix keeping only the non-deleted columns.
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, n, m >, Index > sparseZeroMatrix(Index N, Index M)
creates a zero matrix in NUMA block compressed row storage format
DynamicMatrix< typename SparseMatrix::block_type > full(SparseMatrix const &A, RowRange const &rows, ColRange const &cols)
Converts a subrange of a sparse matrix to a dense matrix.
Target eraseRows(Source const &A, RowIndices const &ri)
"deletes" rows by extracting a copy of the matrix keeping only the non-deleted rows.
DynamicMatrix< MEntry > submatrix(DynamicMatrix< MEntry > const &A, int rowstart, int rowend, int colstart, int colend)
extracts contiguous submatrices, copying the data
NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > horzcat(NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > const &A, NumaBCRSMatrix< Dune::FieldMatrix< Scalar, blockrows, blockcols >, Index > const &B)
concatenate two matrices horizontally
Target eraseRowsNCols(Source const &A, RowIndices const &ri, ColIndices const &ci)
"deletes" rows/columns by extracting a copy of the matrix keeping the non-deleted rows/columns.
std::vector< size_t > nonZeroColumns(Source const &A)
returns all indices of nonzero columns.
NumaBCRSMatrix< Dune::FieldMatrix< double, blockrows, blockcols >, Index > diagcat(NumaBCRSMatrix< Dune::FieldMatrix< double, blockrows, blockcols >, Index > const &A, NumaBCRSMatrix< Dune::FieldMatrix< double, blockrows, blockcols >, Index > const &B)
concatenate two matrices diagonally, resulting matrix is zero on the off block-diagonal
NumaBCRSMatrix< Entry, Index > operator+(NumaBCRSMatrix< Entry, Index > const &A, NumaBCRSMatrix< Entry, Index2 > const &B)
Matrix addition . The sparsity patterns of both matrices can be different. The size of the matrices h...
void parallelForNodes(Func const &f, int maxTasks=std::numeric_limits< int >::max())
A parallel for loop that executes the given functor in parallel on different NUMA nodes.
Definition threading.hh:617
void equalWeightRanges(std::vector< Index > &x, int n)
Computes partitioning points such that the sum of weights in each partition is roughly the same.
void getRowCount(Dune::BCRSMatrix< Entry, Allocator > const &matrix, bool isTransposed, std::vector< Index > &rowCount)
typename GetScalar< Type >::type ScalarType
Extracts the scalar field type from linear algebra data types.
NumaCRSPattern< Index > operator+(NumaCRSPattern< Index > const &pa, NumaCRSPattern< Index2 > const &pb)
std::ostream & operator<<(std::ostream &stream, VTKReader::FunctionInfo const &info)
static int const rows
Definition scalar.hh:77
static int const cols
Definition scalar.hh:78
A comparator functor that supports sorting std::pair by their first component.
Definition firstless.hh:22