v0.16.3
Loading...
Searching...
No Matches
Schur.cpp
Go to the documentation of this file.
1/**
2 * @file Schur.cpp
3 * @brief Implementation of Schur Complement
4 * @date 2023-02-03
5 *
6 * @copyright Copyright (c) 2023
7 *
8 */
9
10namespace MoFEM {
11
12constexpr bool debug_schur = false;
13
16
17protected:
19
20 /**
21 * @brief Assemble Schur complement
22 *
23 */
25
26 Mat S,
27
28 const UId &uid_row, VectorInt &row_ind,
29
30 const UId &uid_col, VectorInt &col_ind,
31
32 MatrixDouble &m, InsertMode iora
33
34 );
35};
36
37// Assemble specialisations
39
40 Mat S,
41
42 const UId &uid_row, VectorInt &row_ind,
43
44 const UId &uid_col, VectorInt &col_ind,
45
46 MatrixDouble &m, InsertMode iora
47
48) {
49 return ::MatSetValues(
50
51 S, row_ind.size(), &*row_ind.begin(), col_ind.size(), &*col_ind.begin(),
52 &*m.data().begin(), iora
53
54 );
55}
56
57/**
58 * @brief Clear Schur complement internal data
59 *
60 */
62
64
65 MoFEMErrorCode doWork(int side, EntityType type,
67};
68
70
72 boost::shared_ptr<std::vector<unsigned char>> marker_ptr,
73 double diag_val);
74
75 MoFEMErrorCode doWork(int side, EntityType type,
77
78private:
79 boost::shared_ptr<std::vector<unsigned char>> markerPtr;
80 double diagVal;
81};
82
83/**
84 * @brief Assemble Schur complement (Implementation)
85 *
86 */
87template <typename OP_SCHUR_ASSEMBLE_BASE>
89
91
92 /**
93 * @brief Construct a new Op Schur Assemble End object
94 *
95 * @param fields_name list of fields
96 * @param field_ents list of entities on which schur complement is applied
97 * (can be empty)
98 * @param schur_ao map indices to schur matrix indices
99 * @param schur_mat schur matrix
100 * @param sym_schur true if schur is symmetric
101 * @param symm_op true if block diagonal is symmetric
102 */
104
105 std::vector<std::string> fields_name,
106 std::vector<boost::shared_ptr<Range>> field_ents,
107
108 SmartPetscObj<AO> schur_ao, SmartPetscObj<Mat> schur_mat,
109
110 bool sym_schur, bool symm_op);
111
112protected:
113 template <typename I>
115
116 int side, EntityType type, EntitiesFieldData::EntData &data
117
118 );
119
120 std::vector<std::string> fieldsName;
121 std::vector<boost::shared_ptr<Range>> fieldEnts;
125
129};
130
131struct SchurDSYSV; ///< SY symmetric
132struct SchurDGESV; ///< GE general (i.e., nonsymmetric, in some cases
133 ///< rectangular)
134
135/**
136 * @brief Assemble Schur complement
137 *
138 */
139template <typename I> struct OpSchurAssembleEnd;
140
141template <>
143 : public OpSchurAssembleEndImpl<OpSchurAssembleBaseImpl> {
144 using OpSchurAssembleEndImpl<OpSchurAssembleBaseImpl>::OpSchurAssembleEndImpl;
145 MoFEMErrorCode doWork(int side, EntityType type,
147};
148
149template <>
151 : public OpSchurAssembleEndImpl<OpSchurAssembleBaseImpl> {
152 using OpSchurAssembleEndImpl<OpSchurAssembleBaseImpl>::OpSchurAssembleEndImpl;
153 MoFEMErrorCode doWork(int side, EntityType type,
155};
156
157/**
158 * @brief Schur complement data storage
159 *
160 */
161struct SchurElemMats : public boost::enable_shared_from_this<SchurElemMats> {
162
163 SchurElemMats(const size_t idx, const UId uid_row, const UId uid_col);
164 virtual ~SchurElemMats() = default;
165
166 const size_t iDX;
169
170 inline auto &getMat() const { return locMats[iDX]; }
171 inline auto &getRowInd() const { return rowIndices[iDX]; }
172 inline auto &getColInd() const { return colIndices[iDX]; }
173
174 static MoFEMErrorCode MatSetValues(Mat M,
175 const EntitiesFieldData::EntData &row_data,
176 const EntitiesFieldData::EntData &col_data,
177 const MatrixDouble &mat, InsertMode iora);
178
179protected:
180 static MoFEMErrorCode
182 const EntitiesFieldData::EntData &col_data,
183 const MatrixDouble &mat, InsertMode iora);
184
185 friend struct OpSchurAssembleBegin;
187 template <typename OP_SCHUR_ASSEMBLE_BASE>
189
190 struct uid_mi_tag {};
191 struct col_mi_tag {};
192
193 using SchurElemStorage = multi_index_container<
194 const SchurElemMats *,
195 indexed_by<
196
197 ordered_unique<
198 tag<uid_mi_tag>,
199 composite_key<
201
202 member<SchurElemMats, const UId, &SchurElemMats::uidRow>,
203 member<SchurElemMats, const UId, &SchurElemMats::uidCol>
204
205 >>,
206
207 ordered_non_unique<tag<col_mi_tag>, member<SchurElemMats, const UId,
209
210 >>;
211
212 static boost::ptr_vector<MatrixDouble> locMats;
213 static boost::ptr_vector<VectorInt> rowIndices;
214 static boost::ptr_vector<VectorInt> colIndices;
215 static boost::ptr_vector<SchurElemMats> schurElemMats;
216 static size_t maxIndexCounter;
217
219};
220
221/**
222 * @brief Storage of block matrix, shared by block matrix and its nested
223 * (Schur) sub-matrices
224 *
225 * Block is dense sub-matrix coupling DOFs on one row entity with DOFs on one
226 * column entity, stored row-major at mat_shift with leading dimension ld.
227 *
228 * Blocks which are not part of A00 are stored in data. When nested Schur
229 * structure is created (see createSchurNestedMatrixStruture), blocks of A00
230 * which belong to one finite element are stored in a buffer of that element.
231 * Elements with the same block pattern (entities, numbers of DOFs and listed
232 * pairs) share a Pattern, which defines the layout of element buffers.
233 *
234 * Element buffers start in listed layout (listed blocks only). At the first
235 * factorisation each pattern is analysed on a probe element: nodes (entities)
236 * whose diagonal block is a safe pivot are eliminated one by one (block LU in
237 * place, fill only where the pattern creates it), the remaining nodes form a
238 * dense core factorised with partial pivoting. Element buffers are then relaid
239 * element by element, and factors are kept until MatZeroEntries. Elements
240 * failing the pivot test at a later factorisation are factorised dense in a
241 * buffer of their own. See doc/development/schur.md.
242 *
243 * Factorisation works on M = A^T, which is how LAPACK reads row-major element
244 * blocks. Slot (r, c), i.e. block of A coupling row node r with column node c,
245 * read column-major is block (c, r) of M.
246 *
247 * If preconditioner blocks are requested, they are allocated for A00 element
248 * buffers only, with the same layout. Then factors of (A00 + preconditioner)
249 * are stored in place of preconditioner blocks, and A00 blocks are intact.
250*/
252
253 /**
254 * @brief block data indexes
255 *
256 */
257 struct Indexes {
258
264
265 inline UId getRowUId() const { return uid_row; }
266 inline UId getColUId() const { return uid_col; }
267 inline UId getFEUId() const { return uid_fe; }
268 inline int getRow() const { return row; }
269 inline int getCol() const { return col; }
270 inline int getNbRows() const { return nb_rows; }
271 inline int getNbCols() const { return nb_cols; }
272 inline int getLocRow() const { return loc_row; }
273 inline int getLocCol() const { return loc_col; }
274 inline size_t getMatShift() const { return mat_shift; }
275 inline int getLd() const { return ld; }
276 inline int getElem() const { return elem; }
277
278 inline void setStorage(size_t shift, int leading_dim, int element) {
279 mat_shift = shift;
280 ld = leading_dim;
281 elem = element;
282 }
283
284 /// row entity numbering: global and local index of first DOF, DOFs
285 inline void setRow(int glob, int nb, int loc) {
286 row = glob;
287 nb_rows = nb;
288 loc_row = loc;
289 }
290
291 /// column entity numbering: global and local index of first DOF, DOFs
292 inline void setCol(int glob, int nb, int loc) {
293 col = glob;
294 nb_cols = nb;
295 loc_col = loc;
296 }
297
298 private:
302 int row;
303 int col;
308 size_t mat_shift; ///< shift in data, or in element buffer if elem >= 0
309 int ld; ///< leading dimension of block in storage
310 int elem; ///< index of A00 element, -1 if none
311 };
312
313 /// DOFs on one entity (node) of A00 element
314 struct ElemEntity {
316 int nb; ///< number of DOFs
317 int offset; ///< offset in element vector (layout of pattern)
318 int locParent; ///< local index in block matrix numbering
319 int globParent; ///< global index in block matrix numbering
320 int locBlock; ///< local index in A00 sub-problem numbering
321 int globBlock; ///< global index in A00 sub-problem numbering
322 };
323
324 /**
325 * @brief Block pattern of A00 element and layout of element buffer
326 *
327 * Node is an entity of the element. Slot (r, c) couples row node r with
328 * column node c. It is stored row-major at slotShift with leading dimension
329 * slotLd, which read column-major is block (c, r) of M = A^T.
330 */
331 struct Pattern {
332
333 enum State {
334 LISTED, ///< listed blocks only, not analysed
335 BLOCK, ///< block elimination of order nodes, then dense core
336 DENSE ///< dense element matrix (core contains all nodes)
337 };
338
339 int nbNodes = 0;
340 int size = 0; ///< DOFs per element
341 int nbElems = 0;
342 int nbListed = 0;
343 std::vector<int> nodeSize;
344 std::vector<std::string> nodeName;
345 std::vector<char> listed; ///< nbNodes x nbNodes, slot (r, c) is listed
346 std::vector<long> key; ///< nodes (field, type, DOFs) and listed slots
347
349 std::vector<long> slotShift; ///< nbNodes x nbNodes, -1 if not stored
350 std::vector<int> slotLd;
351 std::vector<int> nodeOffset; ///< offset of node DOFs in element vector
352 std::vector<int> order; ///< nodes eliminated block by block
353 std::vector<int> core; ///< nodes of dense core
354 size_t coreShift = 0; ///< shift of dense core in element buffer
355 int coreSize = 0; ///< DOFs in dense core
356 int coreOffset = 0; ///< offset of core DOFs in element vector
357 size_t elemSize = 0; ///< doubles in element buffer
358
359 int nbFallback = 0; ///< elements factorised dense in last factorisation
360 double beRef = 0; ///< backward error of dense solve on probe
361 double beMax = 0; ///< largest backward error in last factorisation
362 bool warned = false;
363
364 inline long sShift(int r, int c) const {
365 return slotShift[r * nbNodes + c];
366 }
367 inline int sLd(int r, int c) const { return slotLd[r * nbNodes + c]; }
368 inline bool isListed(int r, int c) const { return listed[r * nbNodes + c]; }
369 /// shift of block (a, b) of M = A^T, column-major
370 inline long mShift(int a, int b) const { return sShift(b, a); }
371 /// leading dimension of block (a, b) of M = A^T
372 inline int mLd(int a, int b) const { return sLd(b, a); }
373 };
374
375 /// A00 element
376 struct Elem {
377 int pattern; ///< index of pattern
378 int size; ///< DOFs of element
379 int entBegin; ///< first entity in elemEntities
380 int entEnd; ///< one past last entity in elemEntities
381 int pivShift; ///< shift in pivots
382 bool local = false; ///< all entities have local index on this process
383 bool owned = false; ///< all entities are owned by this process
384 bool factorised = false; ///< factors are stored for this element
385 bool dense = false; ///< factors are in elemDense (pivot test failed)
386 UId feUId = 0; ///< uid of the finite element
387 };
388
389 std::vector<Indexes> blockIndex; ///< blocks sorted by (row uid, col uid)
390 std::vector<int> feOrder; ///< blocks sorted by (fe uid, row uid, col uid)
391 std::vector<int> colOrder; ///< blocks sorted by (col uid, row uid)
392
393 std::vector<Pattern> patterns;
394 std::vector<Elem> elems;
395 std::vector<ElemEntity> elemEntities;
396 std::vector<std::vector<double>> elemData; ///< A00 element buffers
397 std::vector<std::vector<double>> elemPrec; ///< preconditioner buffers
398 std::vector<std::vector<double>> elemDense; ///< dense factors (fallback)
399 int maxElemSize = 0; ///< maximal DOFs of element
400 size_t maxElemBuffer = 0; ///< maximal size of element buffer
401
402 size_t dataSize = 0; ///< required size of data
403 std::vector<double> data; ///< blocks not in A00, allocated on first use
404 std::vector<__CLPK_integer> pivots;
405
406 SchurFEOpsFEandFields feOps; ///< elements and field pairs of the blocks
407 /// (element uid, index in feOps) of elements of the last build, sorted
408 std::vector<std::pair<UId, int>> feList;
410 std::pair<UId, int> key;
411 std::vector<std::pair<UId, int>> row, col;
412 bool sameFields = false;
413 };
414 /// Surviving elements can acquire different field entities after local flips.
415 std::vector<FeConnectivity> feConnectivity;
416 /// patterns of the nested layout before rebuildBlockMatStructure, reused by
417 /// rebuildSchurNestedMatrixStruture
418 std::vector<Pattern> patternCache;
419 /// element buffers of the nested layout before rebuildBlockMatStructure,
420 /// by element uid, given back to the same elements when nested again
421 std::vector<std::pair<UId, std::vector<double>>> elemDataCache;
422 std::vector<std::pair<UId, std::vector<double>>> elemPrecCache;
423 /// allocation of data kept by rebuildBlockMatStructure, reused by
424 /// ensureAllocated
425 std::vector<double> dataCache;
426
427 /// data is allocated on first use, such that storage is not allocated twice
428 /// when layout is changed by createSchurNestedMatrixStruture
429 inline void ensureAllocated() {
430 if (data.size() != dataSize) {
431 // an allocation kept by rebuildBlockMatStructure is reused, and grown
432 // only if it is too small
433 if (data.empty() && dataCache.capacity() > data.capacity())
434 data.swap(dataCache);
435 std::vector<double>().swap(dataCache);
436 data.assign(dataSize, 0.);
437 }
438 }
439
444 FACTOR_FAILED ///< factorisation failed, data is corrupted
445 };
447 bool nested = false; ///< nested Schur structure has been created
448 bool hasPreconditioner = false; ///< preconditioner blocks are enabled
449
450 // options, see createSchurNestedMatrixStruture
451 bool optDense = false; ///< -schur_a00_dense
452 double optPivotThreshold = 0; ///< -schur_a00_pivot_threshold
453 double optRcondMin = 1e-12; ///< -schur_a00_rcond_min
454 double optBackwardError = 1e-12; ///< -schur_a00_backward_error
455
456 inline bool isFactorised() const { return factorStorage != FACTOR_NONE; }
457
458 /// Fails if factorisation failed, storage has to be zeroed
462 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
463 "A00 factorisation failed and block matrix data is corrupted, "
464 "call MatZeroEntries and assemble again");
466 }
467
468 /// Call before modification of data, fails if factors are stored in place
469 inline MoFEMErrorCode modified() const {
472 if (isFactorised())
473 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
474 "A00 element matrices are factorised in place, call "
475 "MatZeroEntries before assembling or modifying block matrix");
477 }
478
479 inline void resetFactors() {
481 for (auto &e : elems) {
482 e.factorised = false;
483 e.dense = false;
484 }
485 for (auto &d : elemDense)
486 std::vector<double>().swap(d);
487 }
488
489 /// values of block, preconditioner buffer if prec is true
490 inline double *blockPtr(const Indexes &b, bool prec = false) {
491 if (b.getElem() >= 0)
492 return (prec ? elemPrec : elemData)[b.getElem()].data() + b.getMatShift();
493 return data.data() + b.getMatShift();
494 }
495
496 static inline bool lessRowCol(const Indexes &a, const Indexes &b) {
497 if (a.getRowUId() != b.getRowUId())
498 return a.getRowUId() < b.getRowUId();
499 return a.getColUId() < b.getColUId();
500 }
501
502 /// find block by row and column entity uid, return nullptr if not found
503 inline const Indexes *find(const UId &row, const UId &col) const {
504 auto it = std::lower_bound(
505 blockIndex.begin(), blockIndex.end(), std::make_pair(row, col),
506 [](const Indexes &a, const std::pair<UId, UId> &p) {
507 if (a.getRowUId() != p.first)
508 return a.getRowUId() < p.first;
509 return a.getColUId() < p.second;
510 });
511 if (it != blockIndex.end() && it->getRowUId() == row &&
512 it->getColUId() == col)
513 return &*it;
514 return nullptr;
515 }
516
517 inline Indexes *findMutable(const UId &row, const UId &col) {
518 return const_cast<Indexes *>(find(row, col));
519 }
520
521 struct RowUIdLess {
522 bool operator()(const Indexes &a, const UId &b) const {
523 return a.getRowUId() < b;
524 }
525 bool operator()(const UId &a, const Indexes &b) const {
526 return a < b.getRowUId();
527 }
528 };
529
530 /// range of blocks with given row entity uid
531 inline auto rowRange(const UId &row) const {
532 return std::equal_range(blockIndex.begin(), blockIndex.end(), row,
533 RowUIdLess());
534 }
535
536 /// range (in colOrder) of blocks with given column entity uid
537 inline auto colRange(const UId &col) const {
538 auto lo = std::lower_bound(
539 colOrder.begin(), colOrder.end(), col,
540 [this](int i, const UId &c) { return blockIndex[i].getColUId() < c; });
541 auto hi = std::upper_bound(
542 colOrder.begin(), colOrder.end(), col,
543 [this](const UId &c, int i) { return c < blockIndex[i].getColUId(); });
544 return std::make_pair(lo, hi);
545 }
546};
547
548/**
549 * @brief Context of block matrix shell
550 *
551 * Block matrix, and each of nested (Schur) sub-matrices, keeps list of blocks
552 * in its own local numbering. Storage of block values is shared between
553 * matrices created from the same block structure.
554 */
556
557 /// numbering of A00 element matrix entities used by this matrix
559
560 /// block in numbering of this matrix (blocks not stored in element buffers)
561 struct Block {
562 size_t shift;
563 int ld;
564 int row;
565 int col;
570 };
571
572 boost::shared_ptr<BlockStorage> storage;
573 std::vector<Block> blocks;
574 bool hasElems = false; ///< A00 elements are part of this matrix
576
579
581
582 inline int locIdx(const BlockStorage::ElemEntity &e) const {
583 return numbering == BLOCK ? e.locBlock : e.locParent;
584 }
585 inline int globIdx(const BlockStorage::ElemEntity &e) const {
586 return numbering == BLOCK ? e.globBlock : e.globParent;
587 }
588};
589
597
599 PetscLogEventRegister("schurMatSetVal", 0, &MOFEM_EVENT_schurMatSetValues);
600 PetscLogEventRegister("opSchurAsmEnd", 0, &MOFEM_EVENT_opSchurAssembleEnd);
601 PetscLogEventRegister("blockSetVal", 0, &MOFEM_EVENT_BlockStructureSetValues);
602 PetscLogEventRegister("blockMult", 0, &MOFEM_EVENT_BlockStructureMult);
603 PetscLogEventRegister("blockSolve", 0, &MOFEM_EVENT_BlockStructureSolve);
604 PetscLogEventRegister("schurZeroRandC", 0, &MOFEM_EVENT_zeroRowsAndCols);
605 PetscLogEventRegister("assembleSchurMat", 0, &MOFEM_EVENT_AssembleSchurMat);
606}
607
609boost::ptr_vector<MatrixDouble> SchurElemMats::locMats;
610boost::ptr_vector<VectorInt> SchurElemMats::rowIndices;
611boost::ptr_vector<VectorInt> SchurElemMats::colIndices;
612boost::ptr_vector<SchurElemMats> SchurElemMats::schurElemMats;
614
615SchurElemMats::SchurElemMats(const size_t idx, const UId uid_row,
616 const UId uid_col)
617 : iDX(idx), uidRow(uid_row), uidCol(uid_col) {}
618
621 const EntitiesFieldData::EntData &col_data,
622 const MatrixDouble &mat, InsertMode iora) {
624
625#ifndef NDEBUG
626 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_schurMatSetValues, 0, 0, 0, 0);
627#endif // NDEBUG
628
629 // get row indices, in case of store, get indices from storage
630 // storage keeps marked indices to manage boundary conditions
631 auto get_row_indices = [&]() -> const VectorInt & {
632 if (auto e_ptr = row_data.getFieldEntities()[0]) {
633 if (auto stored_data_ptr =
634 e_ptr->getSharedStoragePtr<EssentialBcStorage>()) {
635 return stored_data_ptr->entityIndices;
636 }
637 }
638 return row_data.getIndices();
639 };
640
641 const auto &row_ind = get_row_indices();
642 const auto &col_ind = col_data.getIndices();
643
644 const auto nb_rows = row_ind.size();
645 const auto nb_cols = col_ind.size();
646
647#ifndef NDEBUG
648 if (mat.size1() != nb_rows) {
649 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
650 "Wrong mat size %zu != %zu", mat.size1(), nb_rows);
651 }
652 if (mat.size2() != nb_cols) {
653 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
654 "Wrong mat size %zu != %zu", mat.size2(), nb_cols);
655 }
656#endif // NDEBUG
657
658 // get entity uid
659 auto get_uid = [](auto &data) {
660 if (data.getFieldEntities().size() == 1) {
661
662 return data.getFieldEntities()[0]->getLocalUniqueId();
663
664 } else {
665
666 // Is assumed that sum of entities ids gives unique id, that is not true,
667 // but corner case is improbable.
668
669 // @todo: debug version should have test
670
671 auto &uid0 = data.getFieldEntities()[0]->getLocalUniqueId();
672 auto field_id0 = FieldEntity::getFieldBitNumberFromUniqueId(uid0);
673 auto ent0 = FieldEntity::getHandleFromUniqueId(uid0);
674 auto type0 = type_from_handle(ent0);
675 auto id = id_from_handle(ent0);
676
677 for (auto i = 1; i < data.getFieldEntities().size(); ++i) {
678
679 // get entity id from ent
680 id += id_from_handle(
681
682 // get entity handle from unique uid
684 data.getFieldEntities()[i]->getLocalUniqueId())
685
686 );
687 }
688
690 field_id0,
691
692 ent_form_type_and_id(type0, id)
693
694 );
695 }
696 };
697
698 auto uid_row = get_uid(row_data);
699 auto uid_col = get_uid(col_data);
700
701 auto it =
702 SchurElemMats::schurL2Storage.template get<SchurElemMats::uid_mi_tag>()
703 .find(boost::make_tuple(uid_row, uid_col));
704
705 if (it ==
706 SchurElemMats::schurL2Storage.template get<SchurElemMats::uid_mi_tag>()
707 .end()) {
708
709 // get size of arrays of matrices
710 const auto size = SchurElemMats::locMats.size();
711
712 // expand memory allocation
714 SchurElemMats::locMats.push_back(new MatrixDouble());
715 SchurElemMats::rowIndices.push_back(new VectorInt());
716 SchurElemMats::colIndices.push_back(new VectorInt());
718 new SchurElemMats(SchurElemMats::maxIndexCounter, uid_row, uid_col));
719 } else {
721 uid_row;
723 uid_col;
724 }
725
726 // add matrix to storage
727 auto p = SchurElemMats::schurL2Storage.emplace(
729#ifndef NDEBUG
730 if (!p.second) {
731 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Failed to insert");
732 }
733#endif // NDEBUG
734
735 auto asmb = [&](auto &sm) {
736 sm.resize(nb_rows, nb_cols, false);
737 noalias(sm) = mat;
738 };
739
740 asmb((*p.first)->getMat());
741
742 auto add_indices = [](auto &storage, auto &ind) {
743 storage.resize(ind.size(), false);
744 noalias(storage) = ind;
745 };
746
747 add_indices((*p.first)->getRowInd(), row_ind);
748 add_indices((*p.first)->getColInd(), col_ind);
749
750 } else {
751 // entry (submatrix) already exists
752
753 auto asmb = [&](auto &sm) {
755
756#ifndef NDEBUG
757 if (sm.size1() != nb_rows) {
758 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
759 "Wrong mat or storage size %zu != %zu", sm.size1(), nb_rows);
760 }
761 if (sm.size2() != nb_cols) {
762 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
763 "Wrong mat or storage size %zu != %zu", sm.size2(), nb_cols);
764 }
765#endif // NDEBUG
766
767 switch (iora) {
768 case ADD_VALUES:
769 sm += mat;
770 break;
771 case INSERT_VALUES:
772 noalias(sm) = mat;
773 break;
774 default:
775 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
776 "Assembly type not implemented");
777 }
779 };
780
781 CHKERR asmb((*it)->getMat());
782
783 // no need to set indices
784 }
785
786#ifndef NDEBUG
787 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_schurMatSetValues, 0, 0, 0, 0);
788#endif // NDEBUG
789
791}
792
795
799#ifndef NDEBUG
800 if constexpr (debug_schur)
801 MOFEM_LOG("SELF", Sev::noisy) << "Schur assemble begin";
802#endif
805
807}
808
810 boost::shared_ptr<std::vector<unsigned char>> marker_ptr, double diag_val)
811 : OpSchurAssembleBaseImpl(NOSPACE, OPSPACE), markerPtr(marker_ptr),
812 diagVal(diag_val) {}
813
818
819 auto fe_ptr = getFEMethod();
820 auto prb_ptr = fe_ptr->problemPtr;
821 auto &dof = prb_ptr->getNumeredRowDofsPtr()->get<PetscGlobalIdx_mi_tag>();
822
823 auto find_loc_dof_index = [&](auto glob) {
824 auto it = dof.find(glob);
825 if (it != dof.end()) {
826 return (*it)->getPetscLocalDofIdx();
827 }
828 MOFEM_LOG("SELF", Sev::error) << "Global dof " << glob;
831 "Global dof index not found in local numered dofs storage");
832 return -1;
833 };
834
835 for (auto &s : SchurElemMats::schurL2Storage) {
836
837 auto zero_ind = [&](auto &ind) {
838 for (auto i = 0; i < ind.size(); ++i) {
839 if (ind[i] >= 0) {
840 if ((*markerPtr)[find_loc_dof_index(ind[i])]) {
841 ind[i] = -1;
842 }
843 }
844 }
845 };
846
847 zero_ind(s->getRowInd());
848 zero_ind(s->getColInd());
849 }
850
852};
853
854template <typename OP_SCHUR_ASSEMBLE_BASE>
856 std::vector<std::string> fields_name,
857 std::vector<boost::shared_ptr<Range>> field_ents,
858 SmartPetscObj<AO> schur_ao, SmartPetscObj<Mat> schur_mat, bool sym_schur,
859 bool symm_op)
860 : OP(NOSPACE, OP::OPSPACE, symm_op), fieldsName(fields_name),
861 fieldEnts(field_ents), schurAO(schur_ao), schurMat(schur_mat),
862 symSchur(sym_schur) {}
863
864template <typename OP_SCHUR_ASSEMBLE_BASE>
865template <typename I>
867 int side, EntityType type, EntitiesFieldData::EntData &data) {
868
870
871#ifndef NDEBUG
872 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_opSchurAssembleEnd, 0, 0, 0, 0);
873#endif
874
875#ifndef NDEBUG
876 if constexpr (debug_schur)
877 MOFEM_LOG("SELF", Sev::noisy) << "Schur assemble begin -> end";
878#endif
879
880 auto get_a00_uids = [&]() {
881 auto get_field_bit = [&](auto &name) {
882 return OP::getPtrFE()->mField.get_field_bit_number(name);
883 };
884
885 std::vector<std::pair<UId, UId>> a00_uids;
886 a00_uids.reserve(fieldsName.size());
887 for (auto ss = 0; ss != fieldsName.size(); ++ss) {
888 auto field_bit = get_field_bit(fieldsName[ss]);
889 auto row_ents = fieldEnts[ss];
890 if (row_ents) {
891 for (auto p = row_ents->pair_begin(); p != row_ents->pair_end(); ++p) {
892 auto lo_uid =
893 FieldEntity::getLoLocalEntityBitNumber(field_bit, p->first);
894 auto hi_uid =
895 FieldEntity::getHiLocalEntityBitNumber(field_bit, p->second);
896 a00_uids.push_back(std::make_pair(lo_uid, hi_uid));
897 }
898 } else {
900 field_bit, get_id_for_min_type<MBVERTEX>());
902 field_bit, get_id_for_max_type<MBENTITYSET>());
903 a00_uids.push_back(std::make_pair(lo_uid, hi_uid));
904 }
905 }
906 return a00_uids;
907 };
908
909#ifndef NDEBUG
910 auto get_field_name = [&](auto uid) {
911 return OP::getPtrFE()->mField.get_field_name(field_bit_from_bit_number(
913 };
914 auto list_storage = [&](auto &storage) {
916 int i = 0;
917 for (auto &p : storage) {
918 MOFEM_LOG("SELF", Sev::noisy)
919 << "List schur storage: " << i << " " << p->iDX << ": "
920 << get_field_name(p->uidRow) << " " << get_field_name(p->uidCol)
921 << " : " << p->getMat().size1() << " " << p->getMat().size2();
922 ++i;
923 }
925 };
926#endif // NDEBUG
927
928 auto assemble_dense_blocks = [&]() {
929 using matrix_range = ublas::matrix_range<MatrixDouble>;
930 using range = ublas::range;
932 auto &storage = SchurElemMats::schurL2Storage;
933
934 auto assemble_schur = [this](auto &m, auto &uid_row, auto &uid_col,
935 auto *row_ind_ptr, auto *col_ind_ptr) {
937
938 if (schurMat) {
939
940 if (auto ierr = this->assembleSchurMat(
941
942 schurMat, uid_row, *row_ind_ptr, uid_col, *col_ind_ptr, m,
943 ADD_VALUES
944
945 )) {
946#ifndef NDEBUG
947 auto field_ents = OP::getPtrFE()->mField.get_field_ents();
948 auto row_ent_it = field_ents->find(uid_row);
949 auto col_ent_it = field_ents->find(uid_col);
950 MOFEM_LOG_CHANNEL("SELF");
951 if (row_ent_it != field_ents->end())
952 MOFEM_LOG("SELF", Sev::error)
953 << "Assemble row entity: " << (*row_ent_it)->getName() << " "
954 << (*col_ent_it)->getEntTypeName() << " side "
955 << (*row_ent_it)->getSideNumber();
956 if (col_ent_it != field_ents->end())
957 MOFEM_LOG("SELF", Sev::error)
958 << "Assemble col entity: " << (*col_ent_it)->getName() << " "
959 << (*col_ent_it)->getEntTypeName() << " side "
960 << (*col_ent_it)->getSideNumber();
961#endif // NDEBUG
962 CHK_THROW_MESSAGE(ierr, "MatSetValues");
963 }
964 }
965
967 };
968
969 auto a00_uids = get_a00_uids();
970
971 auto get_block_indexing = [&](auto &a00_uids) {
972 // iterate over a00 uids and find blocks
973 std::vector<const SchurElemMats *> block_list;
974 block_list.reserve(storage.size());
975 for (auto &rp_uid : a00_uids) {
976 auto [rlo_uid, rhi_uid] = rp_uid;
977 for (auto &cp_uid : a00_uids) {
978 auto [clo_uid, chi_uid] = cp_uid;
979
980 auto it =
981 storage.template get<SchurElemMats::uid_mi_tag>().lower_bound(
982 boost::make_tuple(rlo_uid, clo_uid));
983 auto hi_it =
984 storage.template get<SchurElemMats::uid_mi_tag>().upper_bound(
985 boost::make_tuple(rhi_uid, chi_uid));
986
987 for (; it != hi_it; ++it) {
988 if ((*it)->uidRow >= rlo_uid && (*it)->uidRow < rhi_uid &&
989 (*it)->uidCol >= clo_uid && (*it)->uidCol < chi_uid) {
990 block_list.push_back(*it);
991 }
992 }
993 }
994 }
995
996 // create block indexes map for blockMat
997 std::map<UId, std::pair<size_t, const VectorInt *>>
998 block_indexing; // uid block map
999 for (auto d : block_list) {
1000 if (block_indexing.find(d->uidRow) == block_indexing.end()) {
1001 block_indexing[d->uidRow] =
1002 std::make_pair(d->getRowInd().size(), &(d->getRowInd()));
1003 }
1004 }
1005
1006 // set indexes to block
1007 int mat_block_size = 0; // size of block matrix
1008 for (auto &p_uid : a00_uids) {
1009 auto [lo_uid, hi_uid] = p_uid;
1010 auto lo = block_indexing.lower_bound(lo_uid);
1011 auto up = block_indexing.upper_bound(hi_uid);
1012 for (; lo != up; ++lo) {
1013 lo->second.first = mat_block_size;
1014 mat_block_size += lo->second.second->size();
1015 }
1016 }
1017
1018 return std::make_tuple(block_list, block_indexing, mat_block_size);
1019 };
1020
1021 auto get_schur_block_list = [&](auto &block_indexing) {
1022 std::vector<const SchurElemMats *> block_list;
1023 block_list.reserve(storage.size());
1024 for (auto &s : storage) {
1025 if (block_indexing.find(s->uidRow) == block_indexing.end() &&
1026 block_indexing.find(s->uidCol) == block_indexing.end()) {
1027 block_list.push_back(s);
1028 }
1029 }
1030 return block_list;
1031 };
1032
1033 auto bi = get_block_indexing(a00_uids);
1034 auto &[block_list, block_indexing, block_mat_size] = bi;
1035
1036 if (block_mat_size == 0) {
1037
1038 if (schurAO) {
1039 for (auto &s : storage) {
1040 CHKERR AOApplicationToPetsc(schurAO, s->getRowInd().size(),
1041 &*s->getRowInd().begin());
1042 CHKERR AOApplicationToPetsc(schurAO, s->getColInd().size(),
1043 &*s->getColInd().begin());
1044 }
1045 }
1046
1047 for (auto &s : storage) {
1048 auto &m = s->getMat();
1049 CHKERR assemble_schur(m, s->uidRow, s->uidCol, &(s->getRowInd()),
1050 &(s->getColInd()));
1051 }
1053 }
1054
1055 blockMat.resize(block_mat_size, block_mat_size, false);
1056 blockMat.clear();
1057
1058 auto get_range = [](auto &bi) {
1059 return range(bi.first, bi.first + bi.second->size());
1060 };
1061
1062 for (auto &s : block_list) {
1063 auto &m = s->getMat();
1064#ifndef NDEBUG
1065 if (block_indexing.find(s->uidRow) == block_indexing.end())
1066 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Wrong rlo_uid");
1067 if (block_indexing.find(s->uidCol) == block_indexing.end())
1068 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Wrong clo_uid");
1069#endif // NDEBUG
1070
1071 auto &rbi = block_indexing.at(s->uidRow);
1072 auto &cbi = block_indexing.at(s->uidCol);
1073
1074 auto sub_mat = matrix_range(blockMat, get_range(rbi), get_range(cbi));
1075 sub_mat = m;
1076 }
1077
1078 auto get_zeroed_indices = [&](auto extractor_uid, auto extractor_ind) {
1079 auto &[block_list, block_indexing, block_mat_size] = bi;
1080 std::vector<int> zeroed_indices;
1081 zeroed_indices.reserve(block_mat_size);
1082 for (auto &s : block_list) {
1083 auto &bi = block_indexing.at(extractor_uid(s));
1084 auto &ind = extractor_ind(s);
1085 for (auto it = ind.begin(); it != ind.end(); ++it) {
1086 if (*it < 0) {
1087 auto idx = bi.first + std::distance(ind.begin(), it);
1088 zeroed_indices.push_back(idx);
1089 }
1090 }
1091 }
1092 std::sort(zeroed_indices.begin(), zeroed_indices.end());
1093 auto it = std::unique(zeroed_indices.begin(), zeroed_indices.end());
1094 zeroed_indices.resize(std::distance(zeroed_indices.begin(), it));
1095 return zeroed_indices;
1096 };
1097 auto zero_rows = get_zeroed_indices(
1098 [](auto &s) { return s->uidRow; },
1099 [](auto &s) -> VectorInt & { return s->getRowInd(); });
1100 auto zero_cols = get_zeroed_indices(
1101 [](auto &s) { return s->uidCol; },
1102 [](auto &s) -> VectorInt & { return s->getColInd(); });
1103
1104 for (auto i : zero_rows) {
1105 for (auto j = 0; j != blockMat.size2(); ++j) {
1106 blockMat(i, j) = 0;
1107 }
1108 }
1109 for (auto j : zero_cols) {
1110 for (auto i = 0; i != blockMat.size1(); ++i) {
1111 blockMat(i, j) = 0;
1112 }
1113 }
1114 for (auto i : zero_rows) {
1115 blockMat(i, i) = 1;
1116 }
1117
1118 CHKERR I::invertMat(blockMat, invMat);
1119
1120 // clear storage and block list from a00 blocks, no more needed
1121 for (auto &s : block_list) {
1122 auto it = storage.template get<SchurElemMats::uid_mi_tag>().find(
1123 boost::make_tuple(s->uidRow, s->uidCol));
1124 storage.template get<SchurElemMats::uid_mi_tag>().erase(it);
1125 }
1126 block_list.clear();
1127
1128 if (schurAO) {
1129 for (auto &s : storage) {
1130 if (block_indexing.find(s->uidRow) == block_indexing.end()) {
1131 CHKERR AOApplicationToPetsc(schurAO, s->getRowInd().size(),
1132 &*s->getRowInd().begin());
1133 }
1134 if (block_indexing.find(s->uidCol) == block_indexing.end()) {
1135 CHKERR AOApplicationToPetsc(schurAO, s->getColInd().size(),
1136 &*s->getColInd().begin());
1137 }
1138 }
1139 }
1140
1141 auto schur_block_list = get_schur_block_list(block_indexing);
1142 for (auto &s : schur_block_list) {
1143 auto &m = s->getMat();
1144 CHKERR assemble_schur(m, s->uidRow, s->uidCol, &(s->getRowInd()),
1145 &(s->getColInd()));
1146 }
1147 for (auto &s : schur_block_list) {
1148 auto it = storage.template get<SchurElemMats::uid_mi_tag>().find(
1149 boost::make_tuple(s->uidRow, s->uidCol));
1150 storage.template get<SchurElemMats::uid_mi_tag>().erase(it);
1151 }
1152 schur_block_list.clear();
1153
1154 for (
1155
1156 auto rp_uid_it = a00_uids.begin(); rp_uid_it != a00_uids.end();
1157 ++rp_uid_it
1158
1159 ) {
1160 auto [rlo_uid, rhi_uid] = *rp_uid_it;
1161 for (auto rm = block_indexing.lower_bound(rlo_uid);
1162 rm != block_indexing.upper_bound(rhi_uid); ++rm) {
1163 auto &rbi = rm->second;
1164
1165 auto a_lo_tmp =
1166 storage.template get<SchurElemMats::col_mi_tag>().lower_bound(
1167 rm->first);
1168 auto a_hi =
1169 storage.template get<SchurElemMats::col_mi_tag>().upper_bound(
1170 rm->first);
1171
1172 for (
1173
1174 auto cp_uid_it = (symSchur) ? rp_uid_it : a00_uids.begin();
1175 cp_uid_it != a00_uids.end(); ++cp_uid_it
1176
1177 ) {
1178 auto [clo_uid, chi_uid] = *cp_uid_it;
1179 for (auto cm = block_indexing.lower_bound(clo_uid);
1180 cm != block_indexing.upper_bound(chi_uid); ++cm) {
1181 auto &cbi = cm->second;
1182
1183 auto c_lo_tmp =
1184 storage.template get<SchurElemMats::uid_mi_tag>().lower_bound(
1185 boost::make_tuple(cm->first, 0));
1186 auto c_hi =
1187 storage.template get<SchurElemMats::uid_mi_tag>().upper_bound(
1188 boost::make_tuple(cm->first, FieldEntity::getHiBitNumberUId(
1189 BITFIELDID_SIZE - 1)));
1190
1191 auto sub_inv_mat =
1192 matrix_range(invMat, get_range(rbi), get_range(cbi));
1193 bM.resize(sub_inv_mat.size1(), sub_inv_mat.size2());
1194 noalias(bM) = sub_inv_mat;
1195
1196 for (auto a_lo = a_lo_tmp; a_lo != a_hi; ++a_lo) {
1197#ifndef NDEBUG
1198 if (block_indexing.find((*a_lo)->uidRow) != block_indexing.end())
1199 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1200 "Wrong a_lo->uidRow");
1201#endif
1202
1203 auto &a = (*a_lo)->getMat();
1204 abM.resize(a.size1(), bM.size2(), false);
1205 abM.clear();
1206 cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
1207
1208 a.size1(), bM.size2(), a.size2(), 1.,
1209
1210 &*a.data().begin(), a.size2(),
1211
1212 &*bM.data().begin(), bM.size2(), 0.,
1213
1214 &*abM.data().begin(), abM.size2());
1215
1216 for (auto c_lo = c_lo_tmp; c_lo != c_hi; ++c_lo) {
1217#ifndef NDEBUG
1218 if (block_indexing.find((*c_lo)->uidCol) !=
1219 block_indexing.end())
1220 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1221 "Wrong a_lo->uidRow");
1222#endif
1223
1224 auto &c = (*c_lo)->getMat();
1225
1226 abcM.resize(abM.size1(), c.size2(), false);
1227 abcM.clear();
1228
1229 cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
1230 abM.size1(), c.size2(), abM.size2(), -1.,
1231
1232 &*abM.data().begin(), abM.size2(),
1233
1234 &*c.data().begin(), c.size2(), 0.,
1235
1236 &*abcM.data().begin(), abcM.size2());
1237
1238 CHKERR assemble_schur(abcM, (*a_lo)->uidRow, (*c_lo)->uidCol,
1239 &((*a_lo)->getRowInd()),
1240 &((*c_lo)->getColInd()));
1241
1242 if (symSchur && rp_uid_it != cp_uid_it) {
1243 abcM = trans(abcM);
1244 CHKERR assemble_schur(abcM, (*c_lo)->uidCol, (*a_lo)->uidRow,
1245 &((*c_lo)->getColInd()),
1246 &((*a_lo)->getRowInd()));
1247 }
1248 }
1249 }
1250 }
1251 }
1252 }
1253 }
1254
1256 };
1257
1258 // Assemble Schur complements
1259 CHKERR assemble_dense_blocks();
1260
1261#ifndef NDEBUG
1262 if constexpr (debug_schur)
1263 MOFEM_LOG("SELF", Sev::noisy) << "Schur assemble done";
1264#endif
1265
1266#ifndef NDEBUG
1267 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_opSchurAssembleEnd, 0, 0, 0, 0);
1268#endif
1269
1271}
1272
1274
1275 static auto invertMat(MatrixDouble &m, MatrixDouble &inv) {
1277
1278 const auto nb = m.size1();
1279#ifndef NDEBUG
1280 if (nb != m.size2()) {
1281 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1282 "It should be square matrix %zu != %zu", nb, m.size2());
1283 }
1284#endif
1285
1286 inv.resize(nb, nb, false);
1287 inv.swap(m);
1288 m.resize(2 * nb, 2 * nb, false);
1289
1290 VectorInt ipiv(nb);
1291 int info;
1292
1293 // FIXME: add lapack_dsytrf and lapack_dsytri
1294
1295 info = lapack_dgetrf(nb, nb, &*inv.data().begin(), nb, &*ipiv.begin());
1296 if (info)
1297 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1298 "lapack error info = %d", info);
1299 info = lapack_dgetri(nb, &*inv.data().begin(), nb, &*ipiv.begin(),
1300 &*m.data().begin(), m.data().size());
1301 if (info)
1302 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1303 "lapack error info = %d", info);
1304
1306 }
1307};
1308
1310
1311 static auto invertMat(MatrixDouble &m, MatrixDouble &inv) {
1313
1314 const auto nb = m.size1();
1315#ifndef NDEBUG
1316 if (nb != m.size2()) {
1317 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1318 "It should be square matrix %zu != %zu", nb, m.size2());
1319 }
1320#endif
1321
1322 inv.resize(nb, nb, false);
1323 inv.swap(m);
1324
1325 VectorInt ipiv(nb);
1326 int info;
1327
1328 info = lapack_dgetrf(nb, nb, &*inv.data().begin(), nb, &*ipiv.begin());
1329 if (info)
1330 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1331 "lapack error info = %d", info);
1332 info = lapack_dgetri(nb, &*inv.data().begin(), nb, &*ipiv.begin(),
1333 &*m.data().begin(), m.data().size());
1334 if (info)
1335 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1336 "lapack error info = %d", info);
1337
1339 }
1340};
1341
1345 return doWorkImpl<SchurDSYSV>(side, type, data);
1346}
1347
1351 return doWorkImpl<SchurDGESV>(side, type, data);
1352}
1353
1354/**
1355 * @brief Apply in place LU factors of element matrix
1356 *
1357 * Element matrix A is stored row-major, i.e. read column-major by LAPACK it is
1358 * M = A^T = P L U. For trans == false y = A x = U^T L^T P^T x, for trans ==
1359 * true y = A^T x = P L U x. Vector t is overwritten by result.
1360 */
1361static inline void apply_lu_factors(int n, const double *lu,
1362 const __CLPK_integer *ipiv, double *t,
1363 bool trans) {
1364 if (!n)
1365 return;
1366 if (!trans) {
1367 for (int k = 0; k != n; ++k) {
1368 const int p = ipiv[k] - 1;
1369 if (p != k)
1370 std::swap(t[k], t[p]);
1371 }
1372 cblas_dtrmv(CblasColMajor, CblasLower, CblasTrans, CblasUnit, n, lu, n, t,
1373 1);
1374 cblas_dtrmv(CblasColMajor, CblasUpper, CblasTrans, CblasNonUnit, n, lu, n,
1375 t, 1);
1376 } else {
1377 cblas_dtrmv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, n, lu, n,
1378 t, 1);
1379 cblas_dtrmv(CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, n, lu, n, t,
1380 1);
1381 for (int k = n - 1; k >= 0; --k) {
1382 const int p = ipiv[k] - 1;
1383 if (p != k)
1384 std::swap(t[k], t[p]);
1385 }
1386 }
1387}
1388
1389/// copy row-major block into row-major matrix at (ridx, cidx)
1390static inline void copy_block(double *dst, int ld_dst, int ridx, int cidx,
1391 const double *src, int ld_src, int nb_rows,
1392 int nb_cols) {
1393 for (int i = 0; i != nb_rows; ++i)
1394 cblas_dcopy(nb_cols, src + static_cast<size_t>(i) * ld_src, 1,
1395 dst + static_cast<size_t>(ridx + i) * ld_dst + cidx, 1);
1396}
1397
1398static inline bool is_zero_matrix(const double *ptr, size_t size) {
1399 return std::all_of(ptr, ptr + size, [](double v) { return v == 0.; });
1400}
1401
1402extern "C" {
1404 __CLPK_integer *lda, __CLPK_doublereal *anorm,
1406 __CLPK_integer *iwork, __CLPK_integer *info);
1407}
1408
1409/// 1-norm of column-major m x n block, infinity if block is not finite
1410static inline double norm1_block(int m, int n, const double *a, int ld) {
1411 double r = 0;
1412 for (int j = 0; j != n; ++j) {
1413 // note that std::max ignores NaN as second argument
1414 const double s = cblas_dasum(m, a + static_cast<size_t>(j) * ld, 1);
1415 if (!std::isfinite(s))
1416 return std::numeric_limits<double>::infinity();
1417 r = std::max(r, s);
1418 }
1419 return r;
1420}
1421
1422/// y += op(A) x, op(A) is m x kk, A is column-major
1423static inline void add_gemv(bool trans_a, int m, int kk, const double *a,
1424 int lda, const double *x, double *y) {
1425 if (!m || !kk)
1426 return;
1427 cblas_dgemv(CblasColMajor, trans_a ? CblasTrans : CblasNoTrans,
1428 trans_a ? kk : m, trans_a ? m : kk, 1., a, lda, x, 1, 1., y, 1);
1429}
1430
1431/// C -= op(A) B, op(A) is m x kk, A, B and C are column-major
1432static inline void sub_gemm(bool trans_a, int m, int kk, int nrhs,
1433 const double *a, int lda, const double *b, int ldb,
1434 double *c, int ldc) {
1435 if (!m || !kk || !nrhs)
1436 return;
1437 if (nrhs == 1)
1438 cblas_dgemv(CblasColMajor, trans_a ? CblasTrans : CblasNoTrans,
1439 trans_a ? kk : m, trans_a ? m : kk, -1., a, lda, b, 1, 1., c,
1440 1);
1441 else
1442 cblas_dgemm(CblasColMajor, trans_a ? CblasTrans : CblasNoTrans,
1443 CblasNoTrans, m, nrhs, kk, -1., a, lda, b, ldb, 1., c, ldc);
1444}
1445
1446/**
1447 * @brief Factorise diagonal block in place and test it as block pivot
1448 *
1449 * Block is admissible pivot if it is not singular and its reciprocal condition
1450 * number (1-norm estimate) is not below rcond_min. If u > 0, its smallest
1451 * singular value (estimated as rcond * norm) has also to be not below u times
1452 * the largest norm of its couplings with nodes not yet eliminated (block
1453 * threshold pivoting). That test is off by default, since it rejects mass
1454 * blocks of hierarchical bases, which are ill-conditioned but safe pivots.
1455 * Stability is verified by backward error, see elem_backward_error.
1456 */
1457static bool factorise_pivot_block(int n, double *d, int ld, __CLPK_integer *piv,
1458 double coupling, double u, double rcond_min,
1459 std::vector<double> &work,
1460 std::vector<__CLPK_integer> &iwork,
1461 double *rcond_out = nullptr,
1462 double *anorm_out = nullptr) {
1463 const double anorm = norm1_block(n, n, d, ld);
1464 double rcond = 0;
1465 if (rcond_out)
1466 *rcond_out = rcond;
1467 if (anorm_out)
1468 *anorm_out = anorm;
1469 if (anorm == 0 || !std::isfinite(anorm))
1470 return false;
1471 if (lapack_dgetrf(n, n, d, ld, piv) != 0)
1472 return false;
1473 work.resize(4 * n);
1474 iwork.resize(n);
1475 char norm = '1';
1476 __CLPK_integer nn = n, lda = ld, info = 0;
1477 double an = anorm;
1478 dgecon_(&norm, &nn, d, &lda, &an, &rcond, work.data(), iwork.data(), &info);
1479 if (rcond_out)
1480 *rcond_out = rcond;
1481 if (info != 0 || !std::isfinite(rcond))
1482 return false;
1483 if (rcond < rcond_min)
1484 return false;
1485 if (u > 0 && rcond * anorm < u * coupling)
1486 return false;
1487 return true;
1488}
1489
1491
1492/// offsets of nodes in element vector in order of nodes
1493static std::vector<int> natural_offsets(const BlockPattern &p) {
1494 std::vector<int> off(p.nbNodes);
1495 int o = 0;
1496 for (int r = 0; r != p.nbNodes; ++r) {
1497 off[r] = o;
1498 o += p.nodeSize[r];
1499 }
1500 return off;
1501}
1502
1503/// doubles in listed blocks of one element
1504static size_t listed_size(const BlockPattern &p) {
1505 size_t s = 0;
1506 for (int r = 0; r != p.nbNodes; ++r)
1507 for (int c = 0; c != p.nbNodes; ++c)
1508 if (p.isListed(r, c))
1509 s += static_cast<size_t>(p.nodeSize[r]) * p.nodeSize[c];
1510 return s;
1511}
1512
1513/// layout with listed blocks only
1515 const int k = p.nbNodes;
1517 p.order.clear();
1518 p.core.clear();
1520 p.slotShift.assign(k * k, -1);
1521 p.slotLd.assign(k * k, 0);
1522 size_t shift = 0;
1523 for (int r = 0; r != k; ++r)
1524 for (int c = 0; c != k; ++c)
1525 if (p.isListed(r, c)) {
1526 p.slotShift[r * k + c] = shift;
1527 p.slotLd[r * k + c] = p.nodeSize[c];
1528 shift += static_cast<size_t>(p.nodeSize[r]) * p.nodeSize[c];
1529 }
1530 p.coreShift = shift;
1531 p.coreSize = 0;
1532 p.coreOffset = p.size;
1533 p.elemSize = shift;
1534}
1535
1536/**
1537 * @brief Blocks of M = A^T present after eliminating nodes in given order
1538 *
1539 * @return nbNodes x nbNodes flags, (a, b) is block a, b of M
1540 */
1541static std::vector<char> symbolic_elimination(const BlockPattern &p,
1542 const std::vector<int> &order) {
1543 const int k = p.nbNodes;
1544 std::vector<char> pm(k * k, 0);
1545 for (int r = 0; r != k; ++r)
1546 for (int c = 0; c != k; ++c)
1547 pm[c * k + r] = p.isListed(r, c);
1548 std::vector<char> done(k, 0);
1549 for (auto e : order) {
1550 done[e] = 1;
1551 for (int i = 0; i != k; ++i)
1552 if (!done[i] && pm[i * k + e])
1553 for (int j = 0; j != k; ++j)
1554 if (!done[j] && pm[e * k + j])
1555 pm[i * k + j] = 1;
1556 }
1557 return pm;
1558}
1559
1560/**
1561 * @brief Layout for block elimination of nodes in order, followed by dense
1562 * core of remaining nodes
1563 *
1564 * Element vector is ordered as eliminated nodes in order, then core nodes.
1565 * Slots with at least one eliminated node, listed or fill, are contiguous with
1566 * leading dimension equal to number of columns. Slots with both nodes in core
1567 * are parts of dense core, which is (core size)^2 matrix. With empty order
1568 * the element matrix is dense.
1569 */
1570static void make_block_layout(BlockPattern &p, const std::vector<int> &order) {
1571 const int k = p.nbNodes;
1572 auto pm = symbolic_elimination(p, order);
1573 std::vector<char> in_core(k, 1);
1574 for (auto e : order)
1575 in_core[e] = 0;
1576 p.order = order;
1577 p.core.clear();
1578 for (int i = 0; i != k; ++i)
1579 if (in_core[i])
1580 p.core.push_back(i);
1581
1582 p.nodeOffset.assign(k, 0);
1583 std::vector<int> pos(k);
1584 int off = 0, t = 0;
1585 for (auto e : p.order) {
1586 p.nodeOffset[e] = off;
1587 off += p.nodeSize[e];
1588 pos[e] = t++;
1589 }
1590 p.coreOffset = off;
1591 for (auto c : p.core) {
1592 p.nodeOffset[c] = off;
1593 off += p.nodeSize[c];
1594 pos[c] = t++;
1595 }
1596 p.coreSize = off - p.coreOffset;
1597
1598 // slots with eliminated node, ordered by elimination
1599 std::vector<std::array<int, 4>> slots;
1600 for (int r = 0; r != k; ++r)
1601 for (int c = 0; c != k; ++c)
1602 if (!(in_core[r] && in_core[c]) && pm[c * k + r])
1603 slots.push_back({std::min(pos[r], pos[c]), pos[r], pos[c], r * k + c});
1604 std::sort(slots.begin(), slots.end());
1605
1606 p.slotShift.assign(k * k, -1);
1607 p.slotLd.assign(k * k, 0);
1608 size_t shift = 0;
1609 for (auto &s : slots) {
1610 const int r = s[3] / k, c = s[3] % k;
1611 p.slotShift[s[3]] = shift;
1612 p.slotLd[s[3]] = p.nodeSize[c];
1613 shift += static_cast<size_t>(p.nodeSize[r]) * p.nodeSize[c];
1614 }
1615 p.coreShift = shift;
1616 for (auto r : p.core)
1617 for (auto c : p.core) {
1618 p.slotShift[r * k + c] =
1619 p.coreShift +
1620 static_cast<size_t>(p.nodeOffset[r] - p.coreOffset) * p.coreSize +
1621 (p.nodeOffset[c] - p.coreOffset);
1622 p.slotLd[r * k + c] = p.coreSize;
1623 }
1624 p.elemSize = p.coreShift + static_cast<size_t>(p.coreSize) * p.coreSize;
1625 p.state = order.empty() ? BlockPattern::DENSE : BlockPattern::BLOCK;
1626}
1627
1628/// elimination order by structure only (minimal fill, diagonal present)
1629static std::vector<int> structural_order(const BlockPattern &p) {
1630 const int k = p.nbNodes;
1631 auto pm = symbolic_elimination(p, {});
1632 std::vector<char> rem(k, 1);
1633 std::vector<int> order;
1634 while (true) {
1635 int best = -1;
1636 double best_fill = 0;
1637 for (int e = 0; e != k; ++e) {
1638 if (!rem[e] || !pm[e * k + e])
1639 continue;
1640 double fill = 0;
1641 for (int i = 0; i != k; ++i)
1642 if (rem[i] && i != e && pm[i * k + e])
1643 for (int j = 0; j != k; ++j)
1644 if (rem[j] && j != e && pm[e * k + j] && !pm[i * k + j])
1645 fill += static_cast<double>(p.nodeSize[i]) * p.nodeSize[j];
1646 if (best < 0 || fill < best_fill) {
1647 best = e;
1648 best_fill = fill;
1649 }
1650 }
1651 if (best < 0)
1652 break;
1653 for (int i = 0; i != k; ++i)
1654 if (rem[i] && i != best && pm[i * k + best])
1655 for (int j = 0; j != k; ++j)
1656 if (rem[j] && j != best && pm[best * k + j])
1657 pm[i * k + j] = 1;
1658 rem[best] = 0;
1659 order.push_back(best);
1660 }
1661 return order;
1662}
1663
1664/**
1665 * @brief Decide elimination order on probe element
1666 *
1667 * Greedy block elimination: among nodes whose updated diagonal block passes
1668 * the pivot test (see factorise_pivot_block), the node creating the least
1669 * fill (weighted by block sizes) is eliminated next. Nodes never admissible
1670 * form the dense core.
1671 *
1672 * @param w dense element matrix, row-major A (column-major M), in natural
1673 * node offsets, overwritten
1674 */
1675static std::vector<int> analyse_pattern(const BlockPattern &p, double *w,
1676 double u, double rcond_min) {
1677 const int k = p.nbNodes, n = p.size;
1678 auto off = natural_offsets(p);
1679 auto &ns = p.nodeSize;
1680 // block (a, b) of M in w, leading dimension n
1681 auto mb = [&](int a, int b) {
1682 return w + static_cast<size_t>(off[b]) * n + off[a];
1683 };
1684 auto pm = symbolic_elimination(p, {});
1685 std::vector<char> rem(k, 1);
1686 std::vector<int> order;
1687 std::vector<double> tmp, work;
1688 std::vector<__CLPK_integer> piv, iwork;
1689
1690 while (true) {
1691 int best = -1;
1692 double best_fill = 0;
1693 for (int e = 0; e != k; ++e) {
1694 if (!rem[e] || !pm[e * k + e])
1695 continue;
1696 const int ne = ns[e];
1697 double coupling = 0;
1698 for (int j = 0; j != k; ++j) {
1699 if (!rem[j] || j == e)
1700 continue;
1701 if (pm[e * k + j])
1702 coupling = std::max(coupling, norm1_block(ne, ns[j], mb(e, j), n));
1703 if (pm[j * k + e])
1704 coupling = std::max(coupling, norm1_block(ns[j], ne, mb(j, e), n));
1705 }
1706 tmp.resize(static_cast<size_t>(ne) * ne);
1707 for (int c = 0; c != ne; ++c)
1708 cblas_dcopy(ne, mb(e, e) + static_cast<size_t>(c) * n, 1,
1709 tmp.data() + static_cast<size_t>(c) * ne, 1);
1710 piv.resize(ne);
1711 double rcond, anorm;
1712 const bool admissible =
1713 factorise_pivot_block(ne, tmp.data(), ne, piv.data(), coupling, u,
1714 rcond_min, work, iwork, &rcond, &anorm);
1715 MOFEM_TAG_AND_LOG("SELF", Sev::noisy, "BlockMat")
1716 << "A00 analysis step " << order.size() << " node " << p.nodeName[e]
1717 << "(" << ne << ") rcond " << rcond << " smin " << rcond * anorm
1718 << " norm " << anorm << " coupling " << coupling
1719 << (admissible ? " admissible" : " rejected");
1720 if (!admissible)
1721 continue;
1722 double fill = 0;
1723 for (int i = 0; i != k; ++i)
1724 if (rem[i] && i != e && pm[i * k + e])
1725 for (int j = 0; j != k; ++j)
1726 if (rem[j] && j != e && pm[e * k + j] && !pm[i * k + j])
1727 fill += static_cast<double>(ns[i]) * ns[j];
1728 if (best < 0 || fill < best_fill) {
1729 best = e;
1730 best_fill = fill;
1731 }
1732 }
1733 if (best < 0)
1734 break;
1735
1736 const int e = best, ne = ns[e];
1737 piv.resize(ne);
1738 lapack_dgetrf(ne, ne, mb(e, e), n, piv.data());
1739 for (int j = 0; j != k; ++j)
1740 if (rem[j] && j != e && pm[e * k + j])
1741 lapack_dgetrs('N', ne, ns[j], mb(e, e), n, piv.data(), mb(e, j), n);
1742 for (int i = 0; i != k; ++i)
1743 if (rem[i] && i != e && pm[i * k + e])
1744 for (int j = 0; j != k; ++j)
1745 if (rem[j] && j != e && pm[e * k + j]) {
1746 cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, ns[i], ns[j],
1747 ne, -1., mb(i, e), n, mb(e, j), n, 1., mb(i, j), n);
1748 pm[i * k + j] = 1;
1749 }
1750 rem[e] = 0;
1751 order.push_back(e);
1752 }
1753 return order;
1754}
1755
1756/// copy listed blocks of element buffer from one layout to another
1757static void copy_listed(const BlockPattern &from, const double *src,
1758 const BlockPattern &to, double *dst) {
1759 for (int r = 0; r != from.nbNodes; ++r)
1760 for (int c = 0; c != from.nbNodes; ++c)
1761 if (from.isListed(r, c))
1762 copy_block(dst + to.sShift(r, c), to.sLd(r, c), 0, 0,
1763 src + from.sShift(r, c), from.sLd(r, c), from.nodeSize[r],
1764 from.nodeSize[c]);
1765}
1766
1767/// dense element matrix (row-major A, size x size) from listed blocks
1768static void elem_gather_dense(const BlockPattern &p, const double *buf,
1769 double *dense) {
1770 const int n = p.size;
1771 for (int r = 0; r != p.nbNodes; ++r)
1772 for (int c = 0; c != p.nbNodes; ++c)
1773 if (p.isListed(r, c))
1774 copy_block(dense, n, p.nodeOffset[r], p.nodeOffset[c],
1775 buf + p.sShift(r, c), p.sLd(r, c), p.nodeSize[r],
1776 p.nodeSize[c]);
1777}
1778
1779/// y += A x (trans false) or y += A^T x (trans true) from listed blocks
1780static void elem_mult_listed(const BlockPattern &p, const double *buf,
1781 const double *x, double *y, bool trans) {
1782 for (int r = 0; r != p.nbNodes; ++r)
1783 for (int c = 0; c != p.nbNodes; ++c)
1784 if (p.isListed(r, c)) {
1785 const int nr = p.nodeSize[r], nc = p.nodeSize[c];
1786 const double *a = buf + p.sShift(r, c);
1787 if (!trans)
1788 cblas_dgemv(CblasRowMajor, CblasNoTrans, nr, nc, 1., a, p.sLd(r, c),
1789 x + p.nodeOffset[c], 1, 1., y + p.nodeOffset[r], 1);
1790 else
1791 cblas_dgemv(CblasRowMajor, CblasTrans, nr, nc, 1., a, p.sLd(r, c),
1792 x + p.nodeOffset[r], 1, 1., y + p.nodeOffset[c], 1);
1793 }
1794}
1795
1796/**
1797 * @brief Factorise element buffer in place
1798 *
1799 * Block LU of M = A^T: for each node e in order, D_e = M_ee is factorised and
1800 * tested as pivot, rows M_ej are overwritten by D_e^{-1} M_ej, and M_ij -=
1801 * M_ie D_e^{-1} M_ej for remaining nodes i, j. Columns M_ie are kept. Then
1802 * dense core is factorised with partial pivoting. M = L U, L block lower with
1803 * diagonal D, U block upper with unit diagonal.
1804 *
1805 * @return 0 on success, 1 if pivot test failed, 2 if core is singular
1806 */
1807static int elem_factorise(const BlockPattern &p, double *buf,
1808 __CLPK_integer *piv, double u, double rcond_min,
1809 std::vector<double> &work,
1810 std::vector<__CLPK_integer> &iwork) {
1811 const int m = p.order.size();
1812 std::vector<int> seq(p.order);
1813 seq.insert(seq.end(), p.core.begin(), p.core.end());
1814 auto &ns = p.nodeSize;
1815
1816 for (int t = 0; t != m; ++t) {
1817 const int e = seq[t], ne = ns[e];
1818 double *d = buf + p.mShift(e, e);
1819 const int ldd = p.mLd(e, e);
1820
1821 double coupling = 0;
1822 for (int q = t + 1; u > 0 && q < static_cast<int>(seq.size()); ++q) {
1823 const int j = seq[q];
1824 if (p.mShift(e, j) >= 0)
1825 coupling =
1826 std::max(coupling,
1827 norm1_block(ne, ns[j], buf + p.mShift(e, j), p.mLd(e, j)));
1828 if (p.mShift(j, e) >= 0)
1829 coupling =
1830 std::max(coupling,
1831 norm1_block(ns[j], ne, buf + p.mShift(j, e), p.mLd(j, e)));
1832 }
1833 if (!factorise_pivot_block(ne, d, ldd, piv + p.nodeOffset[e], coupling, u,
1834 rcond_min, work, iwork))
1835 return 1;
1836
1837 for (int q = t + 1; q < static_cast<int>(seq.size()); ++q) {
1838 const int j = seq[q];
1839 if (p.mShift(e, j) >= 0)
1840 lapack_dgetrs('N', ne, ns[j], d, ldd, piv + p.nodeOffset[e],
1841 buf + p.mShift(e, j), p.mLd(e, j));
1842 }
1843 for (int qi = t + 1; qi < static_cast<int>(seq.size()); ++qi) {
1844 const int i = seq[qi];
1845 if (p.mShift(i, e) < 0)
1846 continue;
1847 for (int qj = t + 1; qj < static_cast<int>(seq.size()); ++qj) {
1848 const int j = seq[qj];
1849 if (p.mShift(e, j) < 0)
1850 continue;
1851 cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, ns[i], ns[j], ne,
1852 -1., buf + p.mShift(i, e), p.mLd(i, e),
1853 buf + p.mShift(e, j), p.mLd(e, j), 1., buf + p.mShift(i, j),
1854 p.mLd(i, j));
1855 }
1856 }
1857 }
1858
1859 if (p.coreSize) {
1860 if (lapack_dgetrf(p.coreSize, p.coreSize, buf + p.coreShift, p.coreSize,
1861 piv + p.coreOffset) != 0)
1862 return 2;
1863 }
1864 return 0;
1865}
1866
1867/**
1868 * @brief Solve with factorised element buffer
1869 *
1870 * trans false solves A X = R, i.e. M^T X = R = U^T L^T X, trans true solves
1871 * A^T X = R, i.e. M X = R = L U X. R is column-major (size x nrhs), with rows
1872 * in element vector layout, overwritten by X.
1873 *
1874 * @param nz_in optional flags of nodes with non-zero rows of R, nodes with
1875 * zero rows are skipped where possible
1876 */
1877static MoFEMErrorCode elem_solve(const BlockPattern &p, const double *buf,
1878 const __CLPK_integer *piv, double *r, int ldr,
1879 int nrhs, bool trans,
1880 const std::vector<char> *nz_in) {
1882 const int k = p.nbNodes, m = p.order.size();
1883 std::vector<int> seq(p.order);
1884 seq.insert(seq.end(), p.core.begin(), p.core.end());
1885 auto &ns = p.nodeSize;
1886 auto &off = p.nodeOffset;
1887 std::vector<char> nz = nz_in ? *nz_in : std::vector<char>(k, 1);
1888 auto blk = [&](int a, int b) { return buf + p.mShift(a, b); };
1889 auto rr = [&](int a) { return r + off[a]; };
1890 auto lu = [&](int e) { return const_cast<double *>(blk(e, e)); };
1891 auto pv = [&](int e) { return const_cast<__CLPK_integer *>(piv + off[e]); };
1892 auto core_solve = [&](char t) {
1894 if (!p.coreSize)
1896 bool any = false;
1897 for (auto c : p.core)
1898 any = any || nz[c];
1899 if (!any)
1901 auto info = lapack_dgetrs(
1902 t, p.coreSize, nrhs, const_cast<double *>(buf + p.coreShift),
1903 p.coreSize, const_cast<__CLPK_integer *>(piv + p.coreOffset),
1904 r + p.coreOffset, ldr);
1905 if (info)
1906 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1907 "error lapack dgetrs info = %d", static_cast<int>(info));
1908 for (auto c : p.core)
1909 nz[c] = 1;
1911 };
1912 auto diag_solve = [&](int e, char t) {
1914 if (!nz[e])
1916 auto info =
1917 lapack_dgetrs(t, ns[e], nrhs, lu(e), p.mLd(e, e), pv(e), rr(e), ldr);
1918 if (info)
1919 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1920 "error lapack dgetrs info = %d", static_cast<int>(info));
1922 };
1923
1924 if (!trans) {
1925 // forward with U^T (unit diagonal)
1926 for (int t = 0; t != static_cast<int>(seq.size()); ++t) {
1927 const int e = seq[t];
1928 for (int q = 0; q != std::min(t, m); ++q) {
1929 const int j = seq[q];
1930 if (nz[j] && p.mShift(j, e) >= 0) {
1931 sub_gemm(true, ns[e], ns[j], nrhs, blk(j, e), p.mLd(j, e), rr(j), ldr,
1932 rr(e), ldr);
1933 nz[e] = 1;
1934 }
1935 }
1936 }
1937 // backward with L^T
1938 CHKERR core_solve('T');
1939 for (int t = m - 1; t >= 0; --t) {
1940 const int e = seq[t];
1941 for (int q = t + 1; q != static_cast<int>(seq.size()); ++q) {
1942 const int i = seq[q];
1943 if (nz[i] && p.mShift(i, e) >= 0) {
1944 sub_gemm(true, ns[e], ns[i], nrhs, blk(i, e), p.mLd(i, e), rr(i), ldr,
1945 rr(e), ldr);
1946 nz[e] = 1;
1947 }
1948 }
1949 CHKERR diag_solve(e, 'T');
1950 }
1951 } else {
1952 // forward with L
1953 for (int t = 0; t != static_cast<int>(seq.size()); ++t) {
1954 const int e = seq[t];
1955 for (int q = 0; q != std::min(t, m); ++q) {
1956 const int i = seq[q];
1957 if (nz[i] && p.mShift(e, i) >= 0) {
1958 sub_gemm(false, ns[e], ns[i], nrhs, blk(e, i), p.mLd(e, i), rr(i),
1959 ldr, rr(e), ldr);
1960 nz[e] = 1;
1961 }
1962 }
1963 if (t < m)
1964 CHKERR diag_solve(e, 'N');
1965 }
1966 CHKERR core_solve('N');
1967 // backward with U (unit diagonal)
1968 for (int t = m - 1; t >= 0; --t) {
1969 const int e = seq[t];
1970 for (int q = t + 1; q != static_cast<int>(seq.size()); ++q) {
1971 const int j = seq[q];
1972 if (nz[j] && p.mShift(e, j) >= 0) {
1973 sub_gemm(false, ns[e], ns[j], nrhs, blk(e, j), p.mLd(e, j), rr(j),
1974 ldr, rr(e), ldr);
1975 nz[e] = 1;
1976 }
1977 }
1978 }
1979 }
1981}
1982
1983/**
1984 * @brief Product with factorised element buffer, in place
1985 *
1986 * trans false computes A v = M^T v = U^T (L^T v), trans true computes A^T v =
1987 * M v = L (U v). Every stored block is used once.
1988 */
1989static void elem_mult_factors(const BlockPattern &p, const double *buf,
1990 const __CLPK_integer *piv, double *v,
1991 bool trans) {
1992 const int m = p.order.size();
1993 std::vector<int> seq(p.order);
1994 seq.insert(seq.end(), p.core.begin(), p.core.end());
1995 const int nseq = seq.size();
1996 auto &ns = p.nodeSize;
1997 auto &off = p.nodeOffset;
1998 auto blk = [&](int a, int b) { return buf + p.mShift(a, b); };
1999 auto vv = [&](int a) { return v + off[a]; };
2000
2001 if (!trans) {
2002 // t = L^T v
2003 for (int t = 0; t != m; ++t) {
2004 const int e = seq[t];
2005 apply_lu_factors(ns[e], blk(e, e), piv + off[e], vv(e), false);
2006 for (int q = t + 1; q != nseq; ++q) {
2007 const int i = seq[q];
2008 if (p.mShift(i, e) >= 0)
2009 add_gemv(true, ns[e], ns[i], blk(i, e), p.mLd(i, e), vv(i), vv(e));
2010 }
2011 }
2012 apply_lu_factors(p.coreSize, buf + p.coreShift, piv + p.coreOffset,
2013 v + p.coreOffset, false);
2014 // y = U^T t
2015 for (int t = nseq - 1; t >= 0; --t) {
2016 const int e = seq[t];
2017 for (int q = 0; q != std::min(t, m); ++q) {
2018 const int j = seq[q];
2019 if (p.mShift(j, e) >= 0)
2020 add_gemv(true, ns[e], ns[j], blk(j, e), p.mLd(j, e), vv(j), vv(e));
2021 }
2022 }
2023 } else {
2024 // t = U v
2025 for (int t = 0; t != m; ++t) {
2026 const int e = seq[t];
2027 for (int q = t + 1; q != nseq; ++q) {
2028 const int j = seq[q];
2029 if (p.mShift(e, j) >= 0)
2030 add_gemv(false, ns[e], ns[j], blk(e, j), p.mLd(e, j), vv(j), vv(e));
2031 }
2032 }
2033 // y = L t
2034 apply_lu_factors(p.coreSize, buf + p.coreShift, piv + p.coreOffset,
2035 v + p.coreOffset, true);
2036 for (int t = nseq - 1; t >= 0; --t) {
2037 const int e = seq[t];
2038 if (t < m)
2039 apply_lu_factors(ns[e], blk(e, e), piv + off[e], vv(e), true);
2040 for (int q = 0; q != std::min(t, m); ++q) {
2041 const int i = seq[q];
2042 if (p.mShift(e, i) >= 0)
2043 add_gemv(false, ns[e], ns[i], blk(e, i), p.mLd(e, i), vv(i), vv(e));
2044 }
2045 }
2046 }
2047}
2048
2049/// factor of dense backward error accepted for block factors
2050constexpr double backward_error_factor = 100;
2051
2052/// right-hand side used to measure backward error
2053static inline double backward_error_rhs(int i) {
2054 return 1. + 0.5 * std::sin(1. + i);
2055}
2056
2057/**
2058 * @brief Normwise backward error of solve with factors of element
2059 *
2060 * ||A x - b||_inf / (||A||_inf ||x||_inf + ||b||_inf), where x is obtained
2061 * with factors lu, and A x is computed from listed blocks of orig (matrix
2062 * before factorisation, in the same layout). Cost is a few passes over element
2063 * buffer.
2064 */
2065static double elem_backward_error(const BlockPattern &p, const double *orig,
2066 const double *lu, const __CLPK_integer *piv,
2067 std::vector<double> &x,
2068 std::vector<double> &r,
2069 std::vector<double> &rs) {
2070 const int n = p.size;
2071 x.resize(n);
2072 r.resize(n);
2073 rs.assign(n, 0.);
2074 double b_norm = 0;
2075 for (int i = 0; i != n; ++i) {
2076 x[i] = backward_error_rhs(i);
2077 r[i] = -x[i];
2078 b_norm = std::max(b_norm, std::abs(x[i]));
2079 }
2080 constexpr double inf = std::numeric_limits<double>::infinity();
2081 if (elem_solve(p, lu, piv, x.data(), n, 1, false, nullptr))
2082 return inf;
2083 // note that std::max ignores NaN as second argument, thus non-finite values
2084 // are rejected explicitly
2085 for (int i = 0; i != n; ++i)
2086 if (!std::isfinite(x[i]))
2087 return inf;
2088 elem_mult_listed(p, orig, x.data(), r.data(), false);
2089 // row sums of |A|
2090 for (int a = 0; a != p.nbNodes; ++a)
2091 for (int c = 0; c != p.nbNodes; ++c)
2092 if (p.isListed(a, c)) {
2093 const double *blk = orig + p.sShift(a, c);
2094 for (int i = 0; i != p.nodeSize[a]; ++i)
2095 rs[p.nodeOffset[a] + i] += cblas_dasum(
2096 p.nodeSize[c], blk + static_cast<size_t>(i) * p.sLd(a, c), 1);
2097 }
2098 double r_norm = 0, x_norm = 0, a_norm = 0;
2099 for (int i = 0; i != n; ++i) {
2100 if (!std::isfinite(r[i]) || !std::isfinite(rs[i]))
2101 return inf;
2102 r_norm = std::max(r_norm, std::abs(r[i]));
2103 x_norm = std::max(x_norm, std::abs(x[i]));
2104 a_norm = std::max(a_norm, rs[i]);
2105 }
2106 const double den = a_norm * x_norm + b_norm;
2107 if (!std::isfinite(den) || !(den > 0))
2108 return inf;
2109 const double be = r_norm / den;
2110 return std::isfinite(be) ? be : inf;
2111}
2112
2113/// backward error accepted for block factors, given dense backward error
2114static inline double accepted_backward_error(double be_dense, double be_tol) {
2115 return std::isfinite(be_dense)
2116 ? std::max(backward_error_factor * be_dense, be_tol)
2117 : be_tol;
2118}
2119
2120/// true if backward error is finite and not larger than accepted
2121static inline bool backward_error_accepted(double be, double be_dense,
2122 double be_tol) {
2123 return std::isfinite(be) && be <= accepted_backward_error(be_dense, be_tol);
2124}
2125
2126/**
2127 * @brief Verify block layout on probe element
2128 *
2129 * Normwise backward errors of a solve with block factors and with dense
2130 * factors are compared. Block layout is accepted if its backward error is
2131 * finite and not larger than backward_error_factor times dense backward error
2132 * (if that is finite), or than be_tol.
2133 *
2134 * @param mat matrix of probe in layout nl (not factorised)
2135 */
2136static bool verify_probe(const BlockPattern &nl, const std::vector<double> &mat,
2137 double u, double rcond_min, double be_tol,
2138 double &be_block, double &be_dense) {
2139 const int n = nl.size;
2140 std::vector<double> x, r, rs, f, work;
2141 std::vector<__CLPK_integer> piv(n), iwork;
2142
2143 // dense factors of probe, as element with dense layout
2144 BlockPattern dl = nl;
2145 make_block_layout(dl, {});
2146 std::vector<double> dense(dl.elemSize, 0.);
2147 copy_listed(nl, mat.data(), dl, dense.data());
2148 f = dense;
2149 be_dense = std::numeric_limits<double>::infinity();
2150 if (elem_factorise(dl, f.data(), piv.data(), u, rcond_min, work, iwork) == 0)
2151 be_dense =
2152 elem_backward_error(dl, dense.data(), f.data(), piv.data(), x, r, rs);
2153
2154 be_block = std::numeric_limits<double>::infinity();
2155 f = mat;
2156 if (elem_factorise(nl, f.data(), piv.data(), u, rcond_min, work, iwork))
2157 return false;
2158 be_block =
2159 elem_backward_error(nl, mat.data(), f.data(), piv.data(), x, r, rs);
2160 return backward_error_accepted(be_block, be_dense, be_tol);
2161}
2162
2163static std::string describe_nodes(const BlockPattern &p,
2164 const std::vector<int> &nodes) {
2165 std::string s;
2166 for (auto r : nodes) {
2167 if (!s.empty())
2168 s += " ";
2169 s += p.nodeName[r] + "(" + std::to_string(p.nodeSize[r]) + ")";
2170 }
2171 return s.empty() ? std::string("none") : s;
2172}
2173
2174/**
2175 * @brief Relayout element buffers of pattern pi, element by element, in place
2176 *
2177 * Element buffers have capacity of dense element matrix (reserved, pages not
2178 * used are not touched), which is upper bound of any layout. Buffers are
2179 * relaid within their capacity through a copy of one element, so nothing is
2180 * reallocated or freed. Freed buffers would be kept resident by allocators.
2181 */
2182static void relayout_pattern(BlockStorage &s, int pi, BlockPattern nl) {
2183 auto &p = s.patterns[pi];
2184 const int k = p.nbNodes;
2185 std::vector<double> scratch;
2186 for (int ei = 0; ei != static_cast<int>(s.elems.size()); ++ei) {
2187 auto &e = s.elems[ei];
2188 if (e.pattern != pi)
2189 continue;
2190 auto relayout_buf = [&](std::vector<double> &buf) {
2191 scratch.assign(buf.begin(), buf.end());
2192 if (nl.elemSize > buf.capacity())
2193 buf.reserve(static_cast<size_t>(nl.size) * nl.size);
2194 buf.resize(nl.elemSize);
2195 std::fill(buf.begin(), buf.end(), 0.);
2196 copy_listed(p, scratch.data(), nl, buf.data());
2197 };
2198 relayout_buf(s.elemData[ei]);
2199 if (s.hasPreconditioner)
2200 relayout_buf(s.elemPrec[ei]);
2201 for (int r = 0; r != k; ++r)
2202 for (int c = 0; c != k; ++c)
2203 if (p.isListed(r, c)) {
2204 auto idx = s.findMutable(s.elemEntities[e.entBegin + r].uid,
2205 s.elemEntities[e.entBegin + c].uid);
2206 idx->setStorage(nl.sShift(r, c), nl.sLd(r, c), ei);
2207 }
2208 for (int r = 0; r != k; ++r)
2209 s.elemEntities[e.entBegin + r].offset = nl.nodeOffset[r];
2210 }
2211 p = nl;
2212 s.maxElemBuffer = 0;
2213 for (auto &q : s.patterns)
2214 s.maxElemBuffer = std::max(s.maxElemBuffer, q.elemSize);
2215}
2216
2217/**
2218 * @brief Factorise A00 elements in place
2219 *
2220 * Factors are stored in element buffers (operator A00), or in preconditioner
2221 * buffers (operator A00 + preconditioner). In the second case A00 blocks are
2222 * intact. Patterns in listed layout are analysed first, see analyse_pattern.
2223 */
2227 CHKERR storage.checkNotFailed();
2228 if (storage.isFactorised()) {
2229 if (storage.factorStorage == where)
2231 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2232 "A00 element matrices are already factorised in other storage");
2233 }
2234 const bool in_prec = where == BlockStorage::FACTOR_IN_PRECONDITIONER;
2235 if (in_prec && !storage.hasPreconditioner)
2236 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2237 "No preconditioner blocks");
2238
2239 const double u = storage.optPivotThreshold;
2240 const double rcond_min = storage.optRcondMin;
2241
2242 // matrix which is factorised
2243 auto get_matrix = [&](int ei, std::vector<double> &out) {
2244 out = storage.elemData[ei];
2245 if (in_prec)
2246 cblas_daxpy(out.size(), 1., storage.elemPrec[ei].data(), 1, out.data(),
2247 1);
2248 };
2249
2250 std::vector<double> mat, w;
2251 for (int pi = 0; pi != static_cast<int>(storage.patterns.size()); ++pi) {
2252 auto &p = storage.patterns[pi];
2253 if (p.state != BlockPattern::LISTED)
2254 continue;
2255
2256 // probe is first element with non-zero matrix, owned if possible
2257 int probe = -1;
2258 for (int pass = 0; pass != 2 && probe < 0; ++pass)
2259 for (int ei = 0; ei != static_cast<int>(storage.elems.size()); ++ei) {
2260 auto &e = storage.elems[ei];
2261 if (e.pattern != pi || !e.local || (pass == 0 && !e.owned))
2262 continue;
2263 get_matrix(ei, mat);
2264 if (!is_zero_matrix(mat.data(), mat.size())) {
2265 probe = ei;
2266 break;
2267 }
2268 }
2269 if (probe < 0)
2270 continue;
2271
2272 const int n = p.size;
2273 w.assign(static_cast<size_t>(n) * n, 0.);
2274 elem_gather_dense(p, mat.data(), w.data());
2275
2276 BlockPattern nl = p;
2277 make_block_layout(nl, analyse_pattern(p, w.data(), u, rcond_min));
2278 double be_block = 0, be_dense = 0;
2279 bool verified = true;
2280 if (nl.state == BlockPattern::BLOCK) {
2281 std::vector<double> probe_mat(nl.elemSize, 0.);
2282 copy_listed(p, mat.data(), nl, probe_mat.data());
2283 verified = verify_probe(nl, probe_mat, u, rcond_min,
2284 storage.optBackwardError, be_block, be_dense);
2285 nl.beRef = be_dense;
2286 if (!verified) {
2287 MOFEM_TAG_AND_LOG("SELF", Sev::warning, "BlockMat")
2288 << "A00 pattern " << pi << ": block elimination rejected on probe "
2289 << "(backward error " << be_block << ", dense " << be_dense
2290 << "), element matrices are dense";
2291 make_block_layout(nl, {});
2292 }
2293 }
2294
2295 MOFEM_TAG_AND_LOG("WORLD", Sev::verbose, "BlockMat")
2296 << "A00 pattern " << pi << " (" << p.nbElems
2297 << " elements): eliminated " << describe_nodes(nl, nl.order)
2298 << "; core " << describe_nodes(nl, nl.core)
2299 << "; doubles per element: listed " << listed_size(p) << ", layout "
2300 << nl.elemSize << ", dense " << static_cast<size_t>(n) * n
2301 << "; probe backward error " << be_block << " (dense " << be_dense
2302 << ")";
2303
2304 relayout_pattern(storage, pi, nl);
2305 }
2306
2307 // from here data is modified, on failure storage is marked as corrupted
2308 storage.factorStorage = BlockStorage::FACTOR_FAILED;
2309 for (auto &p : storage.patterns)
2310 p.nbFallback = 0;
2311 for (auto &p : storage.patterns)
2312 p.beMax = 0;
2313 std::vector<double> scratch, work, be_x, be_r, be_rs;
2314 std::vector<__CLPK_integer> iwork;
2315 for (int ei = 0; ei != static_cast<int>(storage.elems.size()); ++ei) {
2316 auto &e = storage.elems[ei];
2317 e.factorised = false;
2318 e.dense = false;
2319 std::vector<double>().swap(storage.elemDense[ei]);
2320 if (!e.size || !e.local)
2321 continue;
2322 auto &p = storage.patterns[e.pattern];
2323 auto &buf = in_prec ? storage.elemPrec[ei] : storage.elemData[ei];
2324 if (in_prec)
2325 cblas_daxpy(buf.size(), 1., storage.elemData[ei].data(), 1, buf.data(),
2326 1);
2327 // matrices of elements which are not assembled on this process (copies
2328 // of elements owned by other processes) are zero and are skipped
2329 if (is_zero_matrix(buf.data(), buf.size())) {
2330 if (e.owned)
2331 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
2332 "A00 element matrix is zero (not assembled or singular)");
2333 continue;
2334 }
2335 if (p.state == BlockPattern::LISTED)
2336 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2337 "A00 pattern not analysed");
2338
2339 auto piv = storage.pivots.data() + e.pivShift;
2340 if (p.state == BlockPattern::BLOCK)
2341 scratch.assign(buf.begin(), buf.end());
2342 auto ret = elem_factorise(p, buf.data(), piv, u, rcond_min, work, iwork);
2343 if (!ret && p.state == BlockPattern::BLOCK) {
2344 // block factors are accepted if solve with them is backward stable
2345 const double be = elem_backward_error(p, scratch.data(), buf.data(), piv,
2346 be_x, be_r, be_rs);
2347 p.beMax = std::max(p.beMax, be);
2348 if (!backward_error_accepted(be, p.beRef, storage.optBackwardError))
2349 ret = 3;
2350 }
2351 if (ret) {
2352 if (p.state != BlockPattern::BLOCK)
2353 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
2354 "error lapack dgetrf, A00 element matrix is singular");
2355 // element factorised dense, block buffer is not used
2356 auto &dense = storage.elemDense[ei];
2357 dense.assign(static_cast<size_t>(e.size) * e.size, 0.);
2358 elem_gather_dense(p, scratch.data(), dense.data());
2359 if (lapack_dgetrf(e.size, e.size, dense.data(), e.size, piv) != 0)
2360 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
2361 "error lapack dgetrf, A00 element matrix is singular");
2362 e.dense = true;
2363 ++p.nbFallback;
2364 }
2365 e.factorised = true;
2366 }
2367 for (int pi = 0; pi != static_cast<int>(storage.patterns.size()); ++pi) {
2368 auto &p = storage.patterns[pi];
2369 if (!p.nbFallback)
2370 continue;
2371 MOFEM_TAG_AND_LOG("SELF", p.warned ? Sev::verbose : Sev::warning,
2372 "BlockMat")
2373 << "A00 pattern " << pi << ": " << p.nbFallback << " of " << p.nbElems
2374 << " elements failed block pivot or backward error test and are "
2375 "factorised dense";
2376 p.warned = true;
2377 }
2378 for (int pi = 0; pi != static_cast<int>(storage.patterns.size()); ++pi) {
2379 auto &p = storage.patterns[pi];
2380 if (p.state == BlockPattern::BLOCK) {
2381 MOFEM_TAG_AND_LOG("SELF", Sev::noisy, "BlockMat")
2382 << "A00 pattern " << pi << ": largest backward error " << p.beMax
2383 << " (dense on probe " << p.beRef << "), dense fallback "
2384 << p.nbFallback;
2385 }
2386 }
2387 storage.factorStorage = where;
2389}
2390
2391/// set orders of blocks by finite element and by column entity
2392static void set_block_orders(BlockStorage &storage) {
2393 auto &index = storage.blockIndex;
2394 auto &fe_order = storage.feOrder;
2395 fe_order.resize(index.size());
2396 std::iota(fe_order.begin(), fe_order.end(), 0);
2397 std::sort(fe_order.begin(), fe_order.end(), [&index](int a, int b) {
2398 if (index[a].getFEUId() != index[b].getFEUId())
2399 return index[a].getFEUId() < index[b].getFEUId();
2400 return a < b;
2401 });
2402 auto &col_order = storage.colOrder;
2403 col_order.resize(index.size());
2404 std::iota(col_order.begin(), col_order.end(), 0);
2405 std::sort(col_order.begin(), col_order.end(), [&index](int a, int b) {
2406 if (index[a].getColUId() != index[b].getColUId())
2407 return index[a].getColUId() < index[b].getColUId();
2408 return a < b;
2409 });
2410}
2411
2412/// set blocks of block matrix (parent numbering)
2414 s.blocks.clear();
2415 for (auto &d : s.storage->blockIndex) {
2416 if (d.getElem() == -1)
2417 s.blocks.push_back({d.getMatShift(), d.getLd(), d.getRow(), d.getCol(),
2418 d.getNbRows(), d.getNbCols(), d.getLocRow(),
2419 d.getLocCol()});
2420 }
2421 s.blocks.shrink_to_fit();
2422 s.hasElems = !s.storage->elems.empty();
2423 s.numbering = BlockStructure::PARENT;
2424}
2425
2426/**
2427 * @brief Iterate all blocks of matrix, including listed blocks of A00
2428 * elements
2429 *
2430 * fun(ptr, ld, row, col, nb_rows, nb_cols, loc_row, loc_col)
2431 */
2432template <typename FUN>
2433static inline void for_each_block(const BlockStructure &ctx, FUN &&fun) {
2434 auto &storage = *ctx.storage;
2435 double *data = storage.data.data();
2436 for (auto &b : ctx.blocks)
2437 fun(data + b.shift, b.ld, b.row, b.col, b.nbRows, b.nbCols, b.locRow,
2438 b.locCol);
2439 if (ctx.hasElems) {
2440 for (int ei = 0; ei != static_cast<int>(storage.elems.size()); ++ei) {
2441 auto &e = storage.elems[ei];
2442 auto &p = storage.patterns[e.pattern];
2443 double *buf = storage.elemData[ei].data();
2444 for (int r = 0; r != p.nbNodes; ++r) {
2445 auto &re = storage.elemEntities[e.entBegin + r];
2446 for (int c = 0; c != p.nbNodes; ++c) {
2447 if (!p.isListed(r, c))
2448 continue;
2449 auto &ce = storage.elemEntities[e.entBegin + c];
2450 fun(buf + p.sShift(r, c), p.sLd(r, c), ctx.globIdx(re),
2451 ctx.globIdx(ce), re.nb, ce.nb, ctx.locIdx(re), ctx.locIdx(ce));
2452 }
2453 }
2454 }
2455 }
2456}
2457
2458namespace {
2459
2460/// Field entities of one field in a uid-sorted vector of weak pointers
2461std::pair<FieldEntity_vector_view::const_iterator,
2462 FieldEntity_vector_view::const_iterator>
2463field_ents_range(const FieldEntity_vector_view &field_ents,
2464 const FieldBitNumber bit_number) {
2465 auto cmp_uid_lo = [](const boost::weak_ptr<FieldEntity> &a, const UId &b) {
2466 if (auto a_ptr = a.lock())
2467 return a_ptr->getLocalUniqueId() < b;
2468 return false;
2469 };
2470 auto cmp_uid_hi = [](const UId &b, const boost::weak_ptr<FieldEntity> &a) {
2471 if (auto a_ptr = a.lock())
2472 return b < a_ptr->getLocalUniqueId();
2473 return true;
2474 };
2475 const auto lo_uid = FieldEntity::getLocalUniqueIdCalculate(
2476 bit_number, get_id_for_min_type<MBVERTEX>());
2477 const auto hi_uid = FieldEntity::getLocalUniqueIdCalculate(
2478 bit_number, get_id_for_max_type<MBENTITYSET>());
2479 return std::make_pair(
2480 std::lower_bound(field_ents.begin(), field_ents.end(), lo_uid,
2481 cmp_uid_lo),
2482 std::upper_bound(field_ents.begin(), field_ents.end(), hi_uid,
2483 cmp_uid_hi));
2484}
2485
2486/// Field bit numbers of the (row, column) field pairs of each element
2487struct OpBits {
2488 std::vector<FieldBitNumber> row, col;
2489};
2490
2491std::vector<OpBits> get_op_bits(MoFEM::Interface &m_field,
2492 const SchurFEOpsFEandFields &ops) {
2493 std::vector<OpBits> bits(ops.size());
2494 for (size_t op = 0; op != ops.size(); ++op)
2495 for (auto &p : ops[op].second) {
2496 bits[op].row.push_back(m_field.get_field_bit_number(p.first));
2497 bits[op].col.push_back(m_field.get_field_bit_number(p.second));
2498 }
2499 return bits;
2500}
2501
2502/// DOFs of a field entity in a problem
2503struct EntDofs {
2504 int glob = -1; ///< global index of first DOF
2505 int nb = 0; ///< number of DOFs
2506 int loc = -1; ///< local index of first DOF
2507};
2508
2509/// DOFs of the entity with the given uid, as createBlockMatStructure reads
2510/// them from the entity caches: DOFs with a global index only
2511EntDofs ent_dofs(const NumeredDofEntity_multiIndex &dofs, const UId &uid) {
2512 EntDofs r;
2513 auto lo = dofs.lower_bound(uid);
2514 const auto hi =
2515 dofs.upper_bound(uid | static_cast<UId>(MAX_DOFS_ON_ENTITY - 1));
2516 for (; lo != hi; ++lo) {
2517 const auto glob = (*lo)->getPetscGlobalDofIdx();
2518 if (glob == -1)
2519 continue;
2520 if (!r.nb) {
2521 r.glob = glob;
2522 r.loc = (*lo)->getPetscLocalDofIdx();
2523 }
2524 ++r.nb;
2525 }
2526 return r;
2527}
2528
2529/// DOFs of entity uid in [lo, hi)
2530template <typename IT> EntDofs ent_dofs(IT lo, const IT hi) {
2531 EntDofs r;
2532 for (; lo != hi; ++lo) {
2533 const auto glob = (*lo)->getPetscGlobalDofIdx();
2534 if (glob == -1)
2535 continue;
2536 if (!r.nb) {
2537 r.glob = glob;
2538 r.loc = (*lo)->getPetscLocalDofIdx();
2539 }
2540 ++r.nb;
2541 }
2542 return r;
2543}
2544
2545/**
2546 * @brief DOF ranges of entities asked for in ascending uid order
2547 *
2548 * One pass over the container in uid order instead of a tree search per
2549 * entity, for queries which cover most of the entities.
2550 */
2551class DofRangeWalk {
2552public:
2553 using It = NumeredDofEntity_multiIndex::const_iterator;
2554 explicit DofRangeWalk(const NumeredDofEntity_multiIndex &dofs)
2555 : it(dofs.begin()), end(dofs.end()) {}
2556 /// DOFs of entity uid; uids are asked for in ascending order
2557 std::pair<It, It> operator()(const UId &uid) {
2558 const auto hi_uid = uid | static_cast<UId>(MAX_DOFS_ON_ENTITY - 1);
2559 while (it != end && (*it)->getLocalUniqueId() < uid)
2560 ++it;
2561 const auto lo = it;
2562 while (it != end && (*it)->getLocalUniqueId() <= hi_uid)
2563 ++it;
2564 return std::make_pair(lo, it);
2565 }
2566
2567private:
2568 It it, end;
2569};
2570
2571bool same_fe_connectivity(const FieldEntity_vector_view &entities,
2572 const std::vector<std::pair<UId, int>> &record) {
2573 size_t i = 0;
2574 for (const auto &entity : entities)
2575 if (auto entity_ptr = entity.lock()) {
2576 if (i == record.size() ||
2577 record[i] != std::make_pair(entity_ptr->getLocalUniqueId(),
2578 entity_ptr->getNbDofsOnEnt()))
2579 return false;
2580 ++i;
2581 }
2582 return i == record.size();
2583}
2584
2585BlockStorage::FeConnectivity
2586record_fe_connectivity(std::pair<UId, int> key,
2587 const FieldEntity_vector_view &rows,
2588 const FieldEntity_vector_view &cols,
2589 BlockStorage::FeConnectivity record = {}) {
2590 record.key = key;
2591 record.row.clear();
2592 record.col.clear();
2593 auto collect = [](const auto &entities, auto &result) {
2594 result.reserve(entities.size());
2595 for (const auto &entity : entities)
2596 if (auto entity_ptr = entity.lock())
2597 result.emplace_back(entity_ptr->getLocalUniqueId(),
2598 entity_ptr->getNbDofsOnEnt());
2599 };
2600 collect(rows, record.row);
2601 record.sameFields = same_fe_connectivity(cols, record.row);
2602 if (!record.sameFields)
2603 collect(cols, record.col);
2604 return record;
2605}
2606
2607/// Blocks of all elements: one per listed pair of (row entity, column
2608/// entity), kept from the first element in loop order which lists it. The
2609/// visited elements are recorded for rebuildBlockMatStructure.
2610MoFEMErrorCode build_block_index(DM dm, const SchurFEOpsFEandFields &ops,
2611 BlockStorage &storage) {
2613
2614 // extract DOFs for rows/columns. DOFs are associated with fields entities
2615 // for given problem.
2616 auto row_extractor = [](auto &e) { return e->entityCacheRowDofs; };
2617 auto col_extractor = [](auto &e) { return e->entityCacheColDofs; };
2618
2619 auto extract_data = [](auto &&its, auto extractor) {
2620 std::vector<std::tuple<UId, int, int, int>> data;
2621 data.reserve(std::distance(its.first, its.second));
2622 // iterate field dofs
2623 for (; its.first != its.second; ++its.first) {
2624 if (auto e = its.first->lock()) {
2625 if (auto cache = extractor(e).lock()) {
2626 int nb_dofs = 0;
2627 for (auto dof = cache->loHi[0]; dof != cache->loHi[1]; ++dof) {
2628 if ((*dof)->getPetscGlobalDofIdx() != -1)
2629 ++nb_dofs;
2630 }
2631 auto uid = e->getLocalUniqueId();
2632 if (nb_dofs) {
2633
2634 auto glob = (*cache->loHi[0])->getPetscGlobalDofIdx();
2635 auto loc = (*cache->loHi[0])->getPetscLocalDofIdx();
2636 while (glob == -1 && cache->loHi[0] != cache->loHi[1]) {
2637 ++cache->loHi[0];
2638 glob = (*cache->loHi[0])->getPetscGlobalDofIdx();
2639 loc = (*cache->loHi[0])->getPetscLocalDofIdx();
2640 }
2641 data.emplace_back(uid, glob, nb_dofs, loc);
2642
2643#ifndef NDEBUG
2644
2645 for (auto lo = cache->loHi[0]; lo != cache->loHi[1]; ++lo) {
2646 auto glob = (*lo)->getPetscGlobalDofIdx();
2647 if (glob == -1) {
2649 "Wrong global index");
2650 }
2651 }
2652
2653#endif
2654 } else {
2655 data.emplace_back(uid, -1, 0, -1);
2656 }
2657 }
2658 }
2659 }
2660 return data;
2661 };
2662
2663 auto &index = storage.blockIndex;
2664 index.clear();
2665 storage.feList.clear();
2666 storage.feConnectivity.clear();
2667 storage.feOps = ops;
2668 auto m_field_ptr = getInterfacePtr(dm);
2669 const auto bits = get_op_bits(*m_field_ptr, ops);
2670
2671 // Both passes and all element types use the same, unchanged problem.
2672 const Problem *problem_ptr;
2673 CHKERR DMMoFEMGetProblemPtr(dm, &problem_ptr);
2674 auto cache_ptr = boost::make_shared<CacheTuple>();
2675 CHKERR m_field_ptr->cache_problem_entities(problem_ptr->getName(), cache_ptr);
2676
2677 // create element to extract data
2678 auto fe_method = boost::shared_ptr<MoFEM::FEMethod>(new MoFEM::FEMethod());
2679
2680 // first pass counts blocks, such that index is allocated once, second pass
2681 // fills index
2682 size_t nb_pairs = 0;
2683 for (auto count_only : {true, false}) {
2684
2685 if (!count_only)
2686 index.reserve(nb_pairs);
2687
2688 for (int op = 0; op != static_cast<int>(ops.size()); ++op) {
2689
2690 const auto &row_bit_numbers = bits[op].row;
2691 const auto &col_bit_numbers = bits[op].col;
2692
2693 fe_method->preProcessHook = []() { return 0; };
2694 fe_method->postProcessHook = []() { return 0; };
2695 fe_method->operatorHook = [&]() {
2697
2698 auto fe_uid = fe_method->numeredEntFiniteElementPtr->getLocalUniqueId();
2699 if (!count_only) {
2700 storage.feList.emplace_back(fe_uid, op);
2701 storage.feConnectivity.push_back(
2702 record_fe_connectivity({fe_uid, op}, fe_method->getRowFieldEnts(),
2703 fe_method->getColFieldEnts()));
2704 }
2705
2706 for (size_t f = 0; f != row_bit_numbers.size(); ++f) {
2707
2708 auto row_data =
2709 extract_data(field_ents_range(fe_method->getRowFieldEnts(),
2710 row_bit_numbers[f]),
2711 row_extractor);
2712 auto col_data = extract_data(
2713 field_ents_range(fe_method->getColFieldEnts(),
2714 col_bit_numbers[f]),
2715 col_extractor);
2716
2717 for (auto &r : row_data) {
2718 auto [r_uid, r_glob, r_nb_dofs, r_loc] = r;
2719 if (!r_nb_dofs)
2720 continue;
2721 for (auto &c : col_data) {
2722 auto [c_uid, c_glob, c_nb_dofs, c_loc] = c;
2723 if (!c_nb_dofs)
2724 continue;
2725 if (count_only)
2726 ++nb_pairs;
2727 else
2728 index.emplace_back(r_uid, c_uid, fe_uid, r_glob, c_glob,
2729 r_nb_dofs, c_nb_dofs, r_loc, c_loc);
2730 }
2731 }
2732 }
2733
2735 };
2736
2738 dm, ops[op].first, fe_method, 0, m_field_ptr->get_comm_size(),
2739 cache_ptr);
2740 };
2741 }
2742
2743 // unique blocks, block from first element which lists it is kept
2744 std::stable_sort(index.begin(), index.end(), BlockStorage::lessRowCol);
2745 index.erase(std::unique(index.begin(), index.end(),
2746 [](auto &a, auto &b) {
2747 return a.getRowUId() == b.getRowUId() &&
2748 a.getColUId() == b.getColUId();
2749 }),
2750 index.end());
2751 index.shrink_to_fit();
2752
2753 std::sort(storage.feList.begin(), storage.feList.end());
2754 storage.feList.erase(
2755 std::unique(storage.feList.begin(), storage.feList.end()),
2756 storage.feList.end());
2757 std::sort(storage.feConnectivity.begin(), storage.feConnectivity.end(),
2758 [](const auto &a, const auto &b) { return a.key < b.key; });
2759
2761}
2762
2763/// Storage layout, block orders, blocks of the block matrix and its vectors
2764MoFEMErrorCode finalise_block_structure(DM dm, BlockStructure &s) {
2766 auto &storage = *s.storage;
2767 auto &index = storage.blockIndex;
2768
2769 // blocks are stored in order of row entities
2770 size_t mem_size = 0;
2771 for (auto &v : index) {
2772 v.setStorage(mem_size, v.getNbCols(), -1);
2773 mem_size += static_cast<size_t>(v.getNbRows()) * v.getNbCols();
2774 }
2775
2776 if (mem_size > storage.data.max_size())
2777 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL, "Vector too big");
2778 storage.dataSize = mem_size;
2779 // Values are not kept. Allocated storage is zeroed in the new layout; it
2780 // is reallocated only if it has to grow. Unallocated storage is allocated
2781 // on first use.
2782 if (!storage.data.empty())
2783 storage.data.assign(mem_size, 0.);
2784
2785 set_block_orders(storage);
2787
2788 auto ghost_x = createDMVector(dm);
2789 auto ghost_y = createDMVector(dm);
2790 CHKERR VecSetDM(ghost_x, PETSC_NULLPTR);
2791 CHKERR VecSetDM(ghost_y, PETSC_NULLPTR);
2792
2793 s.ghostX = ghost_x;
2794 s.ghostY = ghost_y;
2795
2796 MPI_Comm comm;
2797 CHKERR PetscObjectGetComm((PetscObject)dm, &comm);
2798 std::array<size_t, 2> loc_stats = {index.size(), mem_size * sizeof(double)};
2799 std::array<size_t, 2> sum_stats, max_stats;
2800 MPI_Allreduce(loc_stats.data(), sum_stats.data(), 2, MPIU_SIZE_T, MPI_SUM,
2801 comm);
2802 MPI_Allreduce(loc_stats.data(), max_stats.data(), 2, MPIU_SIZE_T, MPI_MAX,
2803 comm);
2804 constexpr double mb = 1024. * 1024.;
2805 MOFEM_TAG_AND_LOG("WORLD", Sev::verbose, "BlockMat")
2806 << "Blocks " << sum_stats[0] << " (max per process " << max_stats[0]
2807 << "), data " << sum_stats[1] / mb << " MB (max per process "
2808 << max_stats[1] / mb << " MB), index "
2809 << (sum_stats[0] * (sizeof(BlockStorage::Indexes) + 2 * sizeof(int) +
2810 sizeof(BlockStructure::Block))) /
2811 mb
2812 << " MB";
2813
2815}
2816
2817} // namespace
2818
2819boost::shared_ptr<BlockStructure> createBlockMatStructure(
2820
2821 DM dm, //< dm
2822 SchurFEOpsFEandFields schur_fe_op_vec //< block elements
2823
2824) {
2825 auto data_ptr = boost::make_shared<BlockStructure>();
2826 data_ptr->storage = boost::make_shared<BlockStorage>();
2827 CHKERR build_block_index(dm, schur_fe_op_vec, *data_ptr->storage);
2828 CHKERR finalise_block_structure(dm, *data_ptr);
2829 return data_ptr;
2830}
2831
2832MoFEMErrorCode
2834 boost::shared_ptr<BlockStructure> data_ptr) {
2836 if (!data_ptr || !data_ptr->storage)
2837 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Block data not set");
2838 auto &storage = *data_ptr->storage;
2839 if (schur_fe_op_vec != storage.feOps)
2840 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
2841 "A block structure is rebuilt with the elements and field pairs "
2842 "it was created with; create a new one for other pairs");
2843
2844 // A nested layout goes back to plain storage. Element patterns are kept,
2845 // so that rebuildSchurNestedMatrixStruture reuses their layout and
2846 // analysis for elements with the same pattern.
2847 if (storage.nested) {
2848 storage.patternCache = std::move(storage.patterns);
2849 storage.patterns.clear();
2850 // allocations are kept: element buffers by element uid (elements are
2851 // ordered by uid), and data for its next allocation
2852 storage.elemDataCache.clear();
2853 storage.elemPrecCache.clear();
2854 for (size_t ei = 0; ei != storage.elems.size(); ++ei) {
2855 const auto uid = storage.elems[ei].feUId;
2856 storage.elemDataCache.emplace_back(uid, std::move(storage.elemData[ei]));
2857 if (storage.hasPreconditioner)
2858 storage.elemPrecCache.emplace_back(uid,
2859 std::move(storage.elemPrec[ei]));
2860 }
2861 storage.elems.clear();
2862 storage.elemEntities.clear();
2863 storage.elemData.clear();
2864 storage.elemPrec.clear();
2865 storage.elemDense.clear();
2866 storage.pivots.clear();
2867 storage.maxElemSize = 0;
2868 storage.maxElemBuffer = 0;
2869 storage.dataCache.swap(storage.data);
2870 std::vector<double>().swap(storage.data);
2871 storage.nested = false;
2872 }
2873 storage.resetFactors();
2874
2875 auto m_field_ptr = getInterfacePtr(dm);
2876 const Problem *problem_ptr;
2877 CHKERR DMMoFEMGetProblemPtr(dm, &problem_ptr);
2878
2879 // Elements of the problem in the order createBlockMatStructure visits
2880 // them: by element name in the order of schur_fe_op_vec, then by part,
2881 // then in container order.
2882 struct FeRecord {
2883 UId uid;
2884 int op;
2885 int seq;
2886 const NumeredEntFiniteElement *fe;
2887 bool changed = false;
2888 };
2889 std::vector<FeRecord> current;
2890 {
2891 auto &fes = problem_ptr->numeredFiniteElementsPtr
2893 const int comm_size = m_field_ptr->get_comm_size();
2894 int seq = 0;
2895 for (int op = 0; op != static_cast<int>(schur_fe_op_vec.size()); ++op) {
2896 const auto &name = schur_fe_op_vec[op].first;
2897 auto lo = fes.lower_bound(boost::make_tuple(name, 0));
2898 auto hi = fes.upper_bound(boost::make_tuple(name, comm_size));
2899 for (; lo != hi; ++lo)
2900 current.push_back({(*lo)->getLocalUniqueId(), op, seq++, lo->get()});
2901 }
2902 std::sort(current.begin(), current.end(), [](auto &a, auto &b) {
2903 if (a.uid != b.uid)
2904 return a.uid < b.uid;
2905 return a.op < b.op;
2906 });
2907 }
2908 std::vector<std::pair<UId, int>> current_keys;
2909 current_keys.reserve(current.size());
2910 for (auto &c : current)
2911 current_keys.emplace_back(c.uid, c.op);
2912 std::vector<std::pair<UId, int>> removed, added;
2913 std::set_difference(storage.feList.begin(), storage.feList.end(),
2914 current_keys.begin(), current_keys.end(),
2915 std::back_inserter(removed));
2916 std::set_difference(current_keys.begin(), current_keys.end(),
2917 storage.feList.begin(), storage.feList.end(),
2918 std::back_inserter(added));
2919 // A face FE can survive a flip while its adjacent broken-cell entities
2920 // change. Treat it as removed+added so both old and new pairs enter the
2921 // patch. Comparing UIDs alone would silently keep an incomplete index.
2922 auto previous = storage.feConnectivity.begin();
2923 for (auto &record : current) {
2924 const auto key = std::make_pair(record.uid, record.op);
2925 while (previous != storage.feConnectivity.end() && previous->key < key)
2926 ++previous;
2927 if (previous != storage.feConnectivity.end() && previous->key == key &&
2928 (!same_fe_connectivity(record.fe->getRowFieldEnts(), previous->row) ||
2929 !same_fe_connectivity(record.fe->getColFieldEnts(),
2930 previous->sameFields ? previous->row
2931 : previous->col))) {
2932 record.changed = true;
2933 removed.push_back(key);
2934 added.push_back(key);
2935 }
2936 }
2937 std::sort(removed.begin(), removed.end());
2938 std::sort(added.begin(), added.end());
2939
2940 // A local change updates the blocks of the entities it touches; a large
2941 // one rebuilds the index with the element loop of createBlockMatStructure.
2942 PetscReal patch_fraction = 0.25;
2943 CHKERR ::PetscOptionsGetReal(PETSC_NULLPTR, "",
2944 "-schur_rebuild_patch_fraction", &patch_fraction,
2945 PETSC_NULLPTR);
2946 const bool patch = removed.size() + added.size() <=
2947 patch_fraction * std::max<size_t>(current.size(), 1);
2948
2949 size_t nb_patch_ents = 0, nb_visited = 0;
2950 if (!patch) {
2951
2952 CHKERR build_block_index(dm, schur_fe_op_vec, storage);
2953
2954 } else {
2955
2956 auto &index = storage.blockIndex;
2957 const auto bits = get_op_bits(*m_field_ptr, schur_fe_op_vec);
2958 auto find_current = [&](const UId &uid) {
2959 return std::lower_bound(
2960 current.begin(), current.end(), uid,
2961 [](const FeRecord &a, const UId &u) { return a.uid < u; });
2962 };
2963
2964 // Entities whose pairs can change: those of blocks listed first by a
2965 // removed element, and those of added elements. A pair listed by a
2966 // removed element and first by another, surviving one is still listed.
2967 std::vector<UId> ents;
2968 {
2969 auto &fe_order = storage.feOrder;
2970 for (auto &r : removed) {
2971 auto lo = std::lower_bound(
2972 fe_order.begin(), fe_order.end(), r.first,
2973 [&index](int i, const UId &u) { return index[i].getFEUId() < u; });
2974 for (; lo != fe_order.end() && index[*lo].getFEUId() == r.first;
2975 ++lo) {
2976 ents.push_back(index[*lo].getRowUId());
2977 ents.push_back(index[*lo].getColUId());
2978 }
2979 }
2980 for (auto &a : added) {
2981 auto it = find_current(a.first);
2982 while (it->op != a.second)
2983 ++it;
2984 auto &fe = *it->fe;
2985 auto &op_bits = bits[a.second];
2986 for (size_t f = 0; f != op_bits.row.size(); ++f) {
2987 auto rr = field_ents_range(fe.getRowFieldEnts(), op_bits.row[f]);
2988 for (; rr.first != rr.second; ++rr.first)
2989 if (auto e = rr.first->lock())
2990 ents.push_back(e->getLocalUniqueId());
2991 auto cr = field_ents_range(fe.getColFieldEnts(), op_bits.col[f]);
2992 for (; cr.first != cr.second; ++cr.first)
2993 if (auto e = cr.first->lock())
2994 ents.push_back(e->getLocalUniqueId());
2995 }
2996 }
2997 std::sort(ents.begin(), ents.end());
2998 ents.erase(std::unique(ents.begin(), ents.end()), ents.end());
2999 }
3000 nb_patch_ents = ents.size();
3001 auto ent_pos = [&ents](const UId &u) {
3002 auto it = std::lower_bound(ents.begin(), ents.end(), u);
3003 return (it != ents.end() && *it == u)
3004 ? static_cast<int>(it - ents.begin())
3005 : -1;
3006 };
3007
3008 // Elements of the problem with an entity of the patch: every element
3009 // which lists a pair of patch entities is one of them.
3010 std::vector<int> visit;
3011 {
3012 auto &adj =
3013 m_field_ptr->get_ents_elements_adjacency()->get<Unique_mi_tag>();
3014 for (auto &u : ents) {
3015 auto r = adj.equal_range(u);
3016 for (; r.first != r.second; ++r.first) {
3017 const auto fe_uid = r.first->getFeUniqueId();
3018 for (auto it = find_current(fe_uid);
3019 it != current.end() && it->uid == fe_uid; ++it)
3020 visit.push_back(static_cast<int>(it - current.begin()));
3021 }
3022 }
3023 std::sort(visit.begin(), visit.end(), [&current](int a, int b) {
3024 return current[a].seq < current[b].seq;
3025 });
3026 visit.erase(std::unique(visit.begin(), visit.end()), visit.end());
3027 }
3028 nb_visited = visit.size();
3029
3030 const auto &row_dofs = *problem_ptr->getNumeredRowDofsPtr();
3031 const auto &col_dofs = *problem_ptr->getNumeredColDofsPtr();
3032 std::vector<EntDofs> row_info(ents.size()), col_info(ents.size());
3033 for (size_t i = 0; i != ents.size(); ++i) {
3034 row_info[i] = ent_dofs(row_dofs, ents[i]);
3035 col_info[i] = ent_dofs(col_dofs, ents[i]);
3036 }
3037
3038 // Pairs of patch entities, listed by the visited elements in loop
3039 // order; the first lister is kept, as in createBlockMatStructure.
3040 std::vector<BlockStorage::Indexes> fresh;
3041 std::vector<std::pair<UId, const EntDofs *>> rows, cols;
3042 for (auto ci : visit) {
3043 auto &rec = current[ci];
3044 auto &op_bits = bits[rec.op];
3045 for (size_t f = 0; f != op_bits.row.size(); ++f) {
3046 rows.clear();
3047 cols.clear();
3048 auto rr = field_ents_range(rec.fe->getRowFieldEnts(), op_bits.row[f]);
3049 for (; rr.first != rr.second; ++rr.first)
3050 if (auto e = rr.first->lock()) {
3051 const auto u = e->getLocalUniqueId();
3052 const int p = ent_pos(u);
3053 if (p >= 0 && row_info[p].nb)
3054 rows.emplace_back(u, &row_info[p]);
3055 }
3056 auto cr = field_ents_range(rec.fe->getColFieldEnts(), op_bits.col[f]);
3057 for (; cr.first != cr.second; ++cr.first)
3058 if (auto e = cr.first->lock()) {
3059 const auto u = e->getLocalUniqueId();
3060 const int p = ent_pos(u);
3061 if (p >= 0 && col_info[p].nb)
3062 cols.emplace_back(u, &col_info[p]);
3063 }
3064 for (auto &r : rows)
3065 for (auto &c : cols)
3066 fresh.emplace_back(r.first, c.first, rec.uid, r.second->glob,
3067 c.second->glob, r.second->nb, c.second->nb,
3068 r.second->loc, c.second->loc);
3069 }
3070 }
3071 std::stable_sort(fresh.begin(), fresh.end(), BlockStorage::lessRowCol);
3072 fresh.erase(std::unique(fresh.begin(), fresh.end(),
3073 [](auto &a, auto &b) {
3074 return a.getRowUId() == b.getRowUId() &&
3075 a.getColUId() == b.getColUId();
3076 }),
3077 fresh.end());
3078
3079 // Old blocks of patch pairs are replaced by the fresh ones; the others
3080 // are renumbered with one lookup per entity, and dropped if an entity
3081 // has no DOFs left.
3082 std::vector<char> keep(index.size(), 1);
3083 for (auto &u : ents) {
3084 auto range = storage.rowRange(u);
3085 for (auto it = range.first; it != range.second; ++it)
3086 if (std::binary_search(ents.begin(), ents.end(), it->getColUId()))
3087 keep[it - index.begin()] = 0;
3088 }
3089 DofRangeWalk row_walk(row_dofs), col_walk(col_dofs);
3090 for (size_t i = 0; i != index.size();) {
3091 const auto uid = index[i].getRowUId();
3092 size_t e = i;
3093 while (e != index.size() && index[e].getRowUId() == uid)
3094 ++e;
3095 if (std::any_of(keep.begin() + i, keep.begin() + e,
3096 [](char k) { return k; })) {
3097 const auto range = row_walk(uid);
3098 const auto d = ent_dofs(range.first, range.second);
3099 for (; i != e; ++i)
3100 if (keep[i]) {
3101 if (d.nb)
3102 index[i].setRow(d.glob, d.nb, d.loc);
3103 else
3104 keep[i] = 0;
3105 }
3106 }
3107 i = e;
3108 }
3109 auto &col_order = storage.colOrder;
3110 for (size_t p = 0; p != col_order.size();) {
3111 const auto uid = index[col_order[p]].getColUId();
3112 size_t e = p;
3113 while (e != col_order.size() && index[col_order[e]].getColUId() == uid)
3114 ++e;
3115 if (std::any_of(col_order.begin() + p, col_order.begin() + e,
3116 [&keep](int i) { return keep[i]; })) {
3117 const auto range = col_walk(uid);
3118 const auto d = ent_dofs(range.first, range.second);
3119 for (; p != e; ++p) {
3120 const int i = col_order[p];
3121 if (keep[i]) {
3122 if (d.nb)
3123 index[i].setCol(d.glob, d.nb, d.loc);
3124 else
3125 keep[i] = 0;
3126 }
3127 }
3128 }
3129 p = e;
3130 }
3131
3132 // merge kept and fresh blocks, both ordered by (row uid, col uid)
3133 std::vector<BlockStorage::Indexes> merged;
3134 merged.reserve(std::count(keep.begin(), keep.end(), 1) + fresh.size());
3135 auto f = fresh.begin();
3136 for (size_t i = 0; i != index.size(); ++i) {
3137 if (!keep[i])
3138 continue;
3139 while (f != fresh.end() && BlockStorage::lessRowCol(*f, index[i]))
3140 merged.push_back(*f++);
3141 merged.push_back(index[i]);
3142 }
3143 merged.insert(merged.end(), f, fresh.end());
3144 index.swap(merged);
3145 storage.feList.swap(current_keys);
3146 // Retain allocations for unchanged elements. Square elements store their
3147 // identical row/column lists only once; changed lists reuse old capacity.
3148 std::vector<BlockStorage::FeConnectivity> current_connectivity;
3149 current_connectivity.reserve(current.size());
3150 previous = storage.feConnectivity.begin();
3151 for (const auto &record : current) {
3152 const auto key = std::make_pair(record.uid, record.op);
3153 while (previous != storage.feConnectivity.end() && previous->key < key)
3154 ++previous;
3155 BlockStorage::FeConnectivity next;
3156 const bool found =
3157 previous != storage.feConnectivity.end() && previous->key == key;
3158 if (found)
3159 next = std::move(*previous);
3160 if (!found || record.changed)
3161 next = record_fe_connectivity(key, record.fe->getRowFieldEnts(),
3162 record.fe->getColFieldEnts(),
3163 std::move(next));
3164 current_connectivity.push_back(std::move(next));
3165 }
3166 storage.feConnectivity.swap(current_connectivity);
3167 }
3168
3169 CHKERR finalise_block_structure(dm, *data_ptr);
3170
3171 MOFEM_TAG_AND_LOG("SYNC", Sev::verbose, "BlockMat")
3172 << "Rebuilt block structure (" << (patch ? "patch" : "full")
3173 << "): removed elements " << removed.size() << ", added elements "
3174 << added.size() << ", patch entities " << nb_patch_ents
3175 << ", elements visited " << nb_visited << ", blocks "
3176 << storage.blockIndex.size();
3177 MPI_Comm comm;
3178 CHKERR PetscObjectGetComm((PetscObject)dm, &comm);
3179 MOFEM_LOG_SEVERITY_SYNC(comm, Sev::verbose);
3180
3182}
3183
3184/**
3185 * @brief Matrix-vector product of block matrix
3186 *
3187 * Blocks with owned columns are multiplied while ghost values of x are
3188 * communicated, then blocks with ghost columns. A00 elements are applied as
3189 * whole, from listed blocks, or from factors if elements are factorised.
3190 */
3191static MoFEMErrorCode mult_block_structure(Mat mat, Vec x, Vec y,
3192 InsertMode iora, bool trans) {
3194 BlockStructure *ctx;
3195 CHKERR MatShellGetContext(mat, (void **)&ctx);
3196 auto &storage = *ctx->storage;
3197 storage.ensureAllocated();
3198
3199 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_BlockStructureMult, 0, 0, 0, 0);
3200
3201 int x_loc_size;
3202 CHKERR VecGetLocalSize(x, &x_loc_size);
3203
3204 Vec ghost_x = ctx->ghostX;
3205 Vec ghost_y = ctx->ghostY;
3206 if (trans)
3207 std::swap(ghost_x, ghost_y);
3208
3209 CHKERR storage.checkNotFailed();
3210 const bool with_p = ctx->hasElems && ctx->multiplyByPreconditioner;
3211 if (with_p && !storage.hasPreconditioner)
3212 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3213 "No preconditioner blocks");
3214 const bool use_lu =
3215 ctx->hasElems && storage.isFactorised() &&
3216 (storage.factorStorage == BlockStorage::FACTOR_IN_DATA || with_p);
3217 auto &lu_bufs =
3218 storage.factorStorage == BlockStorage::FACTOR_IN_PRECONDITIONER
3219 ? storage.elemPrec
3220 : storage.elemData;
3221
3222 CHKERR VecCopy(x, ghost_x);
3223 {
3224 Vec loc_ghost_y;
3225 CHKERR VecGhostGetLocalForm(ghost_y, &loc_ghost_y);
3226 CHKERR VecSet(loc_ghost_y, 0.);
3227 CHKERR VecGhostRestoreLocalForm(ghost_y, &loc_ghost_y);
3228 }
3229
3230 std::vector<double> xe, ye;
3231 if (ctx->hasElems) {
3232 xe.resize(storage.maxElemSize);
3233 ye.resize(storage.maxElemSize);
3234 }
3235
3236 auto mult_pass = [&](bool ghost_pass) {
3238
3239 const double *x_array;
3240 Vec loc_ghost_x;
3241 CHKERR VecGhostGetLocalForm(ghost_x, &loc_ghost_x);
3242 CHKERR VecGetArrayRead(loc_ghost_x, &x_array);
3243
3244 double *y_array;
3245 Vec loc_ghost_y;
3246 CHKERR VecGhostGetLocalForm(ghost_y, &loc_ghost_y);
3247 CHKERR VecGetArray(loc_ghost_y, &y_array);
3248
3249 const double *data = storage.data.data();
3250 const auto cblas_trans = trans ? CblasTrans : CblasNoTrans;
3251
3252 for (auto &b : ctx->blocks) {
3253 const int x_loc = trans ? b.locRow : b.locCol;
3254 const int y_loc = trans ? b.locCol : b.locRow;
3255 // blocks with entities not available on this process are skipped
3256 if (x_loc < 0 || y_loc < 0)
3257 continue;
3258 if ((x_loc >= x_loc_size) != ghost_pass)
3259 continue;
3260 cblas_dgemv(CblasRowMajor, cblas_trans, b.nbRows, b.nbCols, 1.0,
3261 data + b.shift, b.ld, x_array + x_loc, 1, 1.0,
3262 y_array + y_loc, 1);
3263 }
3264
3265 if (ctx->hasElems) {
3266 for (int ei = 0; ei != static_cast<int>(storage.elems.size()); ++ei) {
3267 auto &e = storage.elems[ei];
3268 const int n = e.size;
3269 if (!n || !e.local)
3270 continue;
3271 // factorised storage holds factors only for assembled elements,
3272 // other element matrices are zero
3273 if (use_lu && !e.factorised)
3274 continue;
3275 auto ent_begin = storage.elemEntities.data() + e.entBegin;
3276 auto ent_end = storage.elemEntities.data() + e.entEnd;
3277
3278 // element with any ghost column is multiplied after ghost update,
3279 // element with entity not available on this process is skipped
3280 bool any_ghost = false;
3281 bool available = true;
3282 for (auto ent = ent_begin; ent != ent_end; ++ent) {
3283 if (!ent->nb)
3284 continue;
3285 const int loc = ctx->locIdx(*ent);
3286 if (loc < 0)
3287 available = false;
3288 else if (loc >= x_loc_size)
3289 any_ghost = true;
3290 }
3291 if (!available || any_ghost != ghost_pass)
3292 continue;
3293
3294 for (auto ent = ent_begin; ent != ent_end; ++ent)
3295 if (ent->nb)
3296 cblas_dcopy(ent->nb, x_array + ctx->locIdx(*ent), 1,
3297 xe.data() + ent->offset, 1);
3298
3299 auto &p = storage.patterns[e.pattern];
3300 auto piv = storage.pivots.data() + e.pivShift;
3301 double *y_e;
3302 if (use_lu) {
3303 if (e.dense)
3304 apply_lu_factors(n, storage.elemDense[ei].data(), piv, xe.data(),
3305 trans);
3306 else
3307 elem_mult_factors(p, lu_bufs[ei].data(), piv, xe.data(), trans);
3308 y_e = xe.data();
3309 } else {
3310 std::fill(ye.begin(), ye.begin() + n, 0.);
3311 elem_mult_listed(p, storage.elemData[ei].data(), xe.data(), ye.data(),
3312 trans);
3313 if (with_p)
3314 elem_mult_listed(p, storage.elemPrec[ei].data(), xe.data(),
3315 ye.data(), trans);
3316 y_e = ye.data();
3317 }
3318
3319 for (auto ent = ent_begin; ent != ent_end; ++ent)
3320 if (ent->nb)
3321 cblas_daxpy(ent->nb, 1.0, y_e + ent->offset, 1,
3322 y_array + ctx->locIdx(*ent), 1);
3323 }
3324 }
3325
3326 CHKERR VecRestoreArrayRead(loc_ghost_x, &x_array);
3327 CHKERR VecRestoreArray(loc_ghost_y, &y_array);
3328 CHKERR VecGhostRestoreLocalForm(ghost_x, &loc_ghost_x);
3329 CHKERR VecGhostRestoreLocalForm(ghost_y, &loc_ghost_y);
3331 };
3332
3333 CHKERR VecGhostUpdateBegin(ghost_x, INSERT_VALUES, SCATTER_FORWARD);
3334 CHKERR mult_pass(false);
3335 CHKERR VecGhostUpdateEnd(ghost_x, INSERT_VALUES, SCATTER_FORWARD);
3336 CHKERR mult_pass(true);
3337
3338 CHKERR VecGhostUpdateBegin(ghost_y, ADD_VALUES, SCATTER_REVERSE);
3339 CHKERR VecGhostUpdateEnd(ghost_y, ADD_VALUES, SCATTER_REVERSE);
3340
3341 switch (iora) {
3342 case INSERT_VALUES:
3343 CHKERR VecCopy(ghost_y, y);
3344 break;
3345 case ADD_VALUES:
3346 CHKERR VecAXPY(y, 1., ghost_y);
3347 break;
3348 default:
3349 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED, "Wrong InsertMode");
3350 }
3351
3352 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_BlockStructureMult, 0, 0, 0, 0);
3353
3355}
3356
3357/**
3358 * @brief Solve with A00, i.e. x = A00^{-1} f, element by element
3359 *
3360 * Elements are factorised in place on first call, and factors are reused
3361 * until matrix is zeroed.
3362 */
3363static MoFEMErrorCode solve_block_structure(Mat mat, Vec f, Vec x,
3364 InsertMode iora, bool trans) {
3366 BlockStructure *ctx;
3367 CHKERR MatShellGetContext(mat, (void **)&ctx);
3368 auto &storage = *ctx->storage;
3369 storage.ensureAllocated();
3370
3371 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_BlockStructureSolve, 0, 0, 0, 0);
3372
3373 if (ctx->numbering != BlockStructure::BLOCK)
3374 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
3375 "Solve is implemented only for A00 block of nested Schur matrix, "
3376 "see createSchurNestedMatrixStruture");
3377
3378 CHKERR storage.checkNotFailed();
3379 const bool with_p = ctx->multiplyByPreconditioner;
3380 if (with_p && !storage.hasPreconditioner)
3381 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3382 "No preconditioner blocks");
3383
3384 bool use_lu = true;
3385 if (with_p) {
3386 CHKERR factorise_elems(storage, BlockStorage::FACTOR_IN_PRECONDITIONER);
3387 } else if (!storage.hasPreconditioner) {
3388 CHKERR factorise_elems(storage, BlockStorage::FACTOR_IN_DATA);
3389 } else {
3390 // operator without preconditioner while preconditioner blocks exist,
3391 // element matrices are factorised on the fly
3392 use_lu = false;
3393 }
3394 auto &lu_bufs = with_p ? storage.elemPrec : storage.elemData;
3395
3396 int nb_local;
3397 CHKERR VecGetLocalSize(x, &nb_local);
3398
3399 if (iora == INSERT_VALUES)
3400 CHKERR VecZeroEntries(x);
3401
3402 double *x_array;
3403 CHKERR VecGetArray(x, &x_array);
3404 const double *f_array;
3405 CHKERR VecGetArrayRead(f, &f_array);
3406
3407 std::vector<double> t(storage.maxElemSize);
3408 std::vector<double> scratch;
3409 std::vector<__CLPK_integer> scratch_piv;
3410 if (!use_lu) {
3411 scratch.resize(static_cast<size_t>(storage.maxElemSize) *
3412 storage.maxElemSize);
3413 scratch_piv.resize(storage.maxElemSize);
3414 }
3415
3416 const char lapack_trans = trans ? 'N' : 'T';
3417
3418 for (int ei = 0; ei != static_cast<int>(storage.elems.size()); ++ei) {
3419 auto &e = storage.elems[ei];
3420 const int n = e.size;
3421 if (!n || !e.local)
3422 continue;
3423 if (use_lu && !e.factorised)
3424 continue;
3425 auto ent_begin = storage.elemEntities.data() + e.entBegin;
3426 auto ent_end = storage.elemEntities.data() + e.entEnd;
3427
3428 // only elements with owned DOFs are solved
3429 bool owned = true;
3430 for (auto ent = ent_begin; ent != ent_end; ++ent) {
3431 if (ent->nb && (ent->locBlock < 0 || ent->locBlock >= nb_local)) {
3432 owned = false;
3433 break;
3434 }
3435 }
3436 if (!owned)
3437 continue;
3438
3439 for (auto ent = ent_begin; ent != ent_end; ++ent)
3440 if (ent->nb)
3441 cblas_dcopy(ent->nb, f_array + ent->locBlock, 1, t.data() + ent->offset,
3442 1);
3443
3444 auto &p = storage.patterns[e.pattern];
3445 auto piv = storage.pivots.data() + e.pivShift;
3446 __CLPK_integer info = 0;
3447 if (use_lu) {
3448 if (e.dense)
3449 info = lapack_dgetrs(lapack_trans, n, 1, storage.elemDense[ei].data(),
3450 n, piv, t.data(), n);
3451 else
3452 CHKERR elem_solve(p, lu_bufs[ei].data(), piv, t.data(), n, 1, trans,
3453 nullptr);
3454 } else {
3455 std::fill(scratch.begin(), scratch.begin() + static_cast<size_t>(n) * n,
3456 0.);
3457 elem_gather_dense(p, storage.elemData[ei].data(), scratch.data());
3458 info = lapack_dgetrf(n, n, scratch.data(), n, scratch_piv.data());
3459 if (info == 0)
3460 info = lapack_dgetrs(lapack_trans, n, 1, scratch.data(), n,
3461 scratch_piv.data(), t.data(), n);
3462 }
3463 if (info != 0)
3464 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3465 "error lapack solve info = %d", static_cast<int>(info));
3466
3467 for (auto ent = ent_begin; ent != ent_end; ++ent)
3468 if (ent->nb)
3469 cblas_daxpy(ent->nb, 1.0, t.data() + ent->offset, 1,
3470 x_array + ent->locBlock, 1);
3471 }
3472
3473 CHKERR VecRestoreArray(x, &x_array);
3474 CHKERR VecRestoreArrayRead(f, &f_array);
3475
3476 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_BlockStructureSolve, 0, 0, 0, 0);
3477
3479}
3480
3481static PetscErrorCode mult(Mat mat, Vec x, Vec y) {
3482 return mult_block_structure(mat, x, y, INSERT_VALUES, false);
3483}
3484static PetscErrorCode mult_add(Mat mat, Vec x, Vec y) {
3485 return mult_block_structure(mat, x, y, ADD_VALUES, false);
3486}
3487static PetscErrorCode mult_transpose(Mat mat, Vec x, Vec y) {
3488 return mult_block_structure(mat, x, y, INSERT_VALUES, true);
3489}
3490static PetscErrorCode mult_transpose_add(Mat mat, Vec x, Vec y) {
3491 return mult_block_structure(mat, x, y, ADD_VALUES, true);
3492}
3493
3494static PetscErrorCode solve(Mat mat, Vec x, Vec y) {
3495 return solve_block_structure(mat, x, y, INSERT_VALUES, false);
3496}
3497static PetscErrorCode solve_add(Mat mat, Vec x, Vec y) {
3498 return solve_block_structure(mat, x, y, ADD_VALUES, false);
3499}
3500static PetscErrorCode solve_transpose(Mat mat, Vec x, Vec y) {
3501 return solve_block_structure(mat, x, y, INSERT_VALUES, true);
3502}
3503static PetscErrorCode solve_transpose_add(Mat mat, Vec x, Vec y) {
3504 return solve_block_structure(mat, x, y, ADD_VALUES, true);
3505}
3506
3507static PetscErrorCode zero_rows_columns(Mat A, PetscInt N,
3508 const PetscInt rows[], PetscScalar diag,
3509 Vec x, Vec b) {
3510
3512 BlockStructure *ctx;
3513 CHKERR MatShellGetContext(A, (void **)&ctx);
3514 auto &storage = *ctx->storage;
3515 CHKERR storage.modified();
3516 storage.ensureAllocated();
3517
3518 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_zeroRowsAndCols, 0, 0, 0, 0);
3519
3520 // rows are gathered from all processes, since blocks with ghost rows or
3521 // columns are stored on this process
3522 std::vector<int> zero_idx;
3523 {
3524 MPI_Comm comm;
3525 CHKERR PetscObjectGetComm((PetscObject)A, &comm);
3526 int size;
3527 MPI_Comm_size(comm, &size);
3528 if (size > 1) {
3529 auto is = createISGeneral(comm, N, rows, PETSC_USE_POINTER);
3530 auto is_local = isAllGather(is);
3531 int is_nb_rows;
3532 CHKERR ISGetSize(is_local, &is_nb_rows);
3533 const int *ptr;
3534 CHKERR ISGetIndices(is_local, &ptr);
3535 zero_idx.assign(ptr, ptr + is_nb_rows);
3536 CHKERR ISRestoreIndices(is_local, &ptr);
3537 } else {
3538 zero_idx.assign(rows, rows + N);
3539 }
3540 }
3541 std::sort(zero_idx.begin(), zero_idx.end());
3542 zero_idx.erase(std::unique(zero_idx.begin(), zero_idx.end()), zero_idx.end());
3543
3544 int loc_m, loc_n;
3545 CHKERR MatGetLocalSize(A, &loc_m, &loc_n);
3546
3547 for_each_block(*ctx, [&](double *ptr, int ld, int row, int col, int nb_rows,
3548 int nb_cols, int loc_row, int loc_col) {
3549 if (!nb_rows || !nb_cols)
3550 return;
3551
3552 auto lo = std::lower_bound(zero_idx.begin(), zero_idx.end(), row);
3553 for (; lo != zero_idx.end() && *lo < row + nb_rows; ++lo) {
3554 auto *row_ptr = ptr + static_cast<size_t>(*lo - row) * ld;
3555 std::fill(row_ptr, row_ptr + nb_cols, 0.);
3556 }
3557
3558 const bool diag_block = row == col && loc_row >= 0 && loc_row < loc_m &&
3559 loc_col >= 0 && loc_col < loc_n;
3560 lo = std::lower_bound(zero_idx.begin(), zero_idx.end(), col);
3561 for (; lo != zero_idx.end() && *lo < col + nb_cols; ++lo) {
3562 const int c = *lo - col;
3563 for (int i = 0; i != nb_rows; ++i)
3564 ptr[static_cast<size_t>(i) * ld + c] = 0.;
3565 if (diag_block && c < nb_rows)
3566 ptr[static_cast<size_t>(c) * ld + c] = diag;
3567 }
3568 });
3569
3570 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_zeroRowsAndCols, 0, 0, 0, 0);
3571
3573}
3574
3575static PetscErrorCode mat_zero(Mat m) {
3577 BlockStructure *ctx;
3578 CHKERR MatShellGetContext(m, (void **)&ctx);
3579 auto &storage = *ctx->storage;
3580 storage.ensureAllocated();
3581 std::fill(storage.data.begin(), storage.data.end(), 0.);
3582 for (auto &buf : storage.elemData)
3583 std::fill(buf.begin(), buf.end(), 0.);
3584 for (auto &buf : storage.elemPrec)
3585 std::fill(buf.begin(), buf.end(), 0.);
3586 storage.resetFactors();
3588}
3589
3592 CHKERR MatShellSetManageScalingShifts(mat_raw);
3593 CHKERR MatShellSetOperation(mat_raw, MATOP_MULT, (void (*)(void))mult);
3594 CHKERR MatShellSetOperation(mat_raw, MATOP_MULT_ADD,
3595 (void (*)(void))mult_add);
3596 CHKERR MatShellSetOperation(mat_raw, MATOP_MULT_TRANSPOSE,
3597 (void (*)(void))mult_transpose);
3598 CHKERR MatShellSetOperation(mat_raw, MATOP_MULT_TRANSPOSE_ADD,
3599 (void (*)(void))mult_transpose_add);
3600 CHKERR MatShellSetOperation(mat_raw, MATOP_SOLVE, (void (*)(void))solve);
3601 CHKERR MatShellSetOperation(mat_raw, MATOP_SOLVE_ADD,
3602 (void (*)(void))solve_add);
3603 CHKERR MatShellSetOperation(mat_raw, MATOP_SOLVE_TRANSPOSE,
3604 (void (*)(void))solve_transpose);
3605 CHKERR MatShellSetOperation(mat_raw, MATOP_SOLVE_TRANSPOSE_ADD,
3606 (void (*)(void))solve_transpose_add);
3607 CHKERR MatShellSetOperation(mat_raw, MATOP_ZERO_ENTRIES,
3608 (void (*)(void))mat_zero);
3609 CHKERR MatShellSetOperation(mat_raw, MATOP_ZERO_ROWS_COLUMNS,
3610 (void (*)(void))zero_rows_columns);
3611
3613};
3614
3616 boost::shared_ptr<BlockStructure> data) {
3617
3618 auto problem_ptr = getProblemPtr(dm);
3619 auto nb_local = problem_ptr->nbLocDofsRow;
3620 auto nb_global = problem_ptr->nbDofsRow;
3621
3622 // check in nb, rows is equal to nb. columns.
3623 if (nb_local != problem_ptr->nbLocDofsCol) {
3624 MOFEM_LOG("SELF", Sev::error)
3625 << "Wrong size " << nb_local << " != " << problem_ptr->nbLocDofsCol;
3627 "nb. cols is inconsistent with nb. rows");
3628 }
3629 if (nb_global != problem_ptr->nbDofsCol) {
3630 MOFEM_LOG("SELF", Sev::error)
3631 << "Wrong size " << nb_global << " != " << problem_ptr->nbDofsCol;
3633 "nb. cols is inconsistent with nb. rows");
3634 }
3635
3636 // get comm from DM
3637 MPI_Comm comm;
3638 CHKERR PetscObjectGetComm((PetscObject)dm, &comm);
3639
3640 Mat mat_raw;
3641 CHKERR MatCreateShell(comm, nb_local, nb_local, nb_global, nb_global,
3642 (void *)data.get(), &mat_raw);
3643 CHKERR setSchurBlockMatOps(mat_raw);
3644 // CHKERR PetscObjectSetName((PetscObject)mat_raw, MoFEM_BLOCK_MAT);
3645
3646 return std::make_pair(SmartPetscObj<Mat>(mat_raw), data);
3647}
3648
3649MoFEMErrorCode
3651 std::vector<std::string> fields_name,
3652 std::vector<boost::shared_ptr<Range>> field_ents,
3653 SmartPetscObj<AO> ao) {
3655 BlockStructure *ctx;
3656 CHKERR MatShellGetContext(B, (void **)&ctx);
3657 auto &storage = *ctx->storage;
3658 auto &index = storage.blockIndex;
3659 storage.ensureAllocated();
3660
3661 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_AssembleSchurMat, 0, 0, 0, 0);
3662
3663 if (ao.use_count() == 0) {
3664 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "No AO set");
3665 }
3666 CHKERR storage.checkNotFailed();
3667
3668 const bool with_p = ctx->multiplyByPreconditioner;
3669 if (with_p && !storage.hasPreconditioner)
3670 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3671 "No preconditioner blocks");
3672
3673 if (fields_name.size() != field_ents.size()) {
3674 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3675 "fields_name.size() != field_ents.size()");
3676 }
3677
3678 std::vector<std::pair<UId, UId>> a00_fields_uids;
3679 a00_fields_uids.reserve(fields_name.size());
3680 auto it_field_ents = field_ents.begin();
3681 for (auto &f : fields_name) {
3682 int bn = m_field.get_field_bit_number(f);
3683 if (*it_field_ents) {
3684 for (auto p = (*it_field_ents)->pair_begin();
3685 p != (*it_field_ents)->pair_end(); ++p) {
3686 a00_fields_uids.emplace_back(
3687 DofEntity::getLoFieldEntityUId(bn, p->first),
3688 DofEntity::getHiFieldEntityUId(bn, p->second));
3689 }
3690 } else {
3691 a00_fields_uids.emplace_back(FieldEntity::getLoBitNumberUId(bn),
3692 FieldEntity::getHiBitNumberUId(bn));
3693 }
3694 ++it_field_ents;
3695 }
3696
3697 auto is_a00 = [&](const UId &uid) {
3698 for (auto &uid_pair : a00_fields_uids) {
3699 if (uid >= uid_pair.first && uid < uid_pair.second)
3700 return true;
3701 }
3702 return false;
3703 };
3704
3705 using Idx = BlockStorage::Indexes;
3706 std::vector<const Idx *> a00_blocks, a01_blocks, a10_blocks, a11_blocks;
3707 struct LocIdx {
3708 int index; ///< index in local matrix
3709 int size; ///< number of DOFs
3710 int glob; ///< global index in block matrix numbering
3711 };
3712 std::map<UId, LocIdx> a00_indexing, a11_indexing;
3713 std::vector<UId> col_uids;
3714 std::vector<double> a00_mat, a01t_mat, a10_mat, s_mat, tmp_block;
3715 std::vector<__CLPK_integer> ipiv;
3716 std::vector<int> glob_idx, row_glob_idx, col_glob_idx;
3717 std::vector<char> nz;
3718
3719 // assemble block directly to Schur matrix
3720 auto set_values_block = [&](const Idx *b) {
3722 const int nb_rows = b->getNbRows();
3723 const int nb_cols = b->getNbCols();
3724 row_glob_idx.resize(nb_rows);
3725 col_glob_idx.resize(nb_cols);
3726 std::iota(row_glob_idx.begin(), row_glob_idx.end(), b->getRow());
3727 std::iota(col_glob_idx.begin(), col_glob_idx.end(), b->getCol());
3728 CHKERR AOApplicationToPetsc(ao, nb_rows, row_glob_idx.data());
3729 CHKERR AOApplicationToPetsc(ao, nb_cols, col_glob_idx.data());
3730 const double *ptr = storage.blockPtr(*b);
3731 if (b->getLd() != nb_cols) {
3732 tmp_block.resize(static_cast<size_t>(nb_rows) * nb_cols);
3733 copy_block(tmp_block.data(), nb_cols, 0, 0, ptr, b->getLd(), nb_rows,
3734 nb_cols);
3735 ptr = tmp_block.data();
3736 }
3737 CHKERR MatSetValues(S, nb_rows, row_glob_idx.data(), nb_cols,
3738 col_glob_idx.data(), ptr, ADD_VALUES);
3740 };
3741
3742 // local indices of entities, ordered by uid
3743 auto set_local_indices = [](auto &indexing, auto &row_blocks,
3744 auto &col_blocks) {
3745 indexing.clear();
3746 for (auto b : row_blocks)
3747 indexing.emplace(b->getRowUId(), LocIdx{0, b->getNbRows(), b->getRow()});
3748 for (auto b : col_blocks)
3749 indexing.emplace(b->getColUId(), LocIdx{0, b->getNbCols(), b->getCol()});
3750 int size = 0;
3751 for (auto &p : indexing) {
3752 p.second.index = size;
3753 size += p.second.size;
3754 }
3755 return size;
3756 };
3757
3758 const auto &fe_order = storage.feOrder;
3759
3760 // classify blocks of finite element starting at position p in fe_order,
3761 // advance p to next element
3762 auto classify_fe = [&](size_t &p) {
3763 a00_blocks.clear();
3764 a01_blocks.clear();
3765 a10_blocks.clear();
3766 a11_blocks.clear();
3767 const auto fe_uid = index[fe_order[p]].getFEUId();
3768 for (; p != fe_order.size() && index[fe_order[p]].getFEUId() == fe_uid;
3769 ++p) {
3770 auto b = &index[fe_order[p]];
3771 const bool r00 = is_a00(b->getRowUId());
3772 const bool c00 = is_a00(b->getColUId());
3773 if (r00 && c00)
3774 a00_blocks.push_back(b);
3775 else if (r00)
3776 a01_blocks.push_back(b);
3777 else if (c00)
3778 a10_blocks.push_back(b);
3779 else
3780 a11_blocks.push_back(b);
3781 }
3782 return fe_uid;
3783 };
3784
3785 // return index of A00 element if eliminated blocks of finite element are
3786 // exactly listed blocks of that element, otherwise -1
3787 auto element_of = [&]() {
3788 const int elem = a00_blocks.front()->getElem();
3789 if (elem < 0)
3790 return -1;
3791 auto &p = storage.patterns[storage.elems[elem].pattern];
3792 if (static_cast<int>(a00_blocks.size()) != p.nbListed)
3793 return -1;
3794 for (auto b : a00_blocks)
3795 if (b->getElem() != elem)
3796 return -1;
3797 return elem;
3798 };
3799
3800 // Factors stored in place can be used only if for every element the
3801 // eliminated blocks coincide with A00 element. That is checked before any
3802 // destructive factorisation.
3803 // process without A00 elements (nested structure exists) is consistent
3804 bool all_consistent = storage.nested;
3805 for (size_t p = 0; all_consistent && p != fe_order.size();) {
3806 classify_fe(p);
3807 // retained block which is part of A00 element means that eliminated set
3808 // is smaller than nested A00
3809 for (auto blocks : {&a01_blocks, &a10_blocks, &a11_blocks})
3810 for (auto b : *blocks)
3811 if (b->getElem() >= 0)
3812 all_consistent = false;
3813 if (!a00_blocks.empty() && element_of() < 0)
3814 all_consistent = false;
3815 }
3816
3817 enum Mode { SCRATCH, DATA_FACTORS, PRECONDITIONER_FACTORS } mode = SCRATCH;
3818 if (with_p) {
3819 if (!all_consistent)
3820 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
3821 "Schur complement with preconditioner blocks requires eliminated "
3822 "fields equal to A00 of nested matrix");
3823 CHKERR factorise_elems(storage, BlockStorage::FACTOR_IN_PRECONDITIONER);
3824 mode = PRECONDITIONER_FACTORS;
3825 } else if (storage.nested && !storage.hasPreconditioner) {
3826 if (all_consistent) {
3827 CHKERR factorise_elems(storage, BlockStorage::FACTOR_IN_DATA);
3828 mode = DATA_FACTORS;
3829 } else if (storage.isFactorised()) {
3830 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3831 "A00 is factorised in place, eliminated fields have to be equal "
3832 "to A00 of nested matrix");
3833 }
3834 }
3835
3836 for (size_t p = 0; p != fe_order.size();) {
3837
3838 const auto fe_uid = classify_fe(p);
3839
3840 for (auto b : a11_blocks)
3841 CHKERR set_values_block(b);
3842
3843 if (a00_blocks.empty())
3844 continue;
3845
3846 // couplings of A00 entities assembled by other elements, e.g. skeleton
3847 // elements of hybridised problem. Blocks of A00 are sorted by row uid.
3848 for (size_t i = 0; i != a00_blocks.size(); ++i) {
3849 const auto r_uid = a00_blocks[i]->getRowUId();
3850 if (i && a00_blocks[i - 1]->getRowUId() == r_uid)
3851 continue;
3852 auto range = storage.rowRange(r_uid);
3853 for (auto it = range.first; it != range.second; ++it) {
3854 if (it->getFEUId() != fe_uid && !is_a00(it->getColUId()))
3855 a01_blocks.push_back(&*it);
3856 }
3857 }
3858 col_uids.clear();
3859 for (auto b : a00_blocks)
3860 col_uids.push_back(b->getColUId());
3861 std::sort(col_uids.begin(), col_uids.end());
3862 col_uids.erase(std::unique(col_uids.begin(), col_uids.end()),
3863 col_uids.end());
3864 for (auto &c_uid : col_uids) {
3865 auto range = storage.colRange(c_uid);
3866 for (auto it = range.first; it != range.second; ++it) {
3867 auto &b = index[*it];
3868 if (b.getFEUId() != fe_uid && !is_a00(b.getRowUId()))
3869 a10_blocks.push_back(&b);
3870 }
3871 }
3872
3873 const int a11_size =
3874 set_local_indices(a11_indexing, a10_blocks, a01_blocks);
3875 if (!a11_size)
3876 continue;
3877
3878 // A01 is gathered transposed (i.e. column-major), then X = A00^{-1} A01 is
3879 // obtained directly by solve with factors of M = A00^T
3880 auto gather_a01t = [&](int a00_size) {
3881 a01t_mat.assign(static_cast<size_t>(a11_size) * a00_size, 0.);
3882 for (auto b : a01_blocks) {
3883 const auto &ri = a00_indexing.at(b->getRowUId());
3884 const auto &ci = a11_indexing.at(b->getColUId());
3885 const double *ptr = storage.blockPtr(*b);
3886 const int ld = b->getLd();
3887 for (int i = 0; i != b->getNbRows(); ++i)
3888 for (int j = 0; j != b->getNbCols(); ++j)
3889 a01t_mat[static_cast<size_t>(ci.index + j) * a00_size + ri.index +
3890 i] = ptr[static_cast<size_t>(i) * ld + j];
3891 }
3892 };
3893
3894 int a00_size;
3895 if (mode != SCRATCH) {
3896 const int elem = element_of();
3897 if (elem < 0)
3898 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3899 "Inconsistent A00 element");
3900 auto &e = storage.elems[elem];
3901 // element matrix not assembled on this process
3902 if (!e.factorised)
3903 continue;
3904 auto &pat = storage.patterns[e.pattern];
3905 // A00 rows and columns in layout of element vector
3906 a00_indexing.clear();
3907 for (int r = e.entBegin; r != e.entEnd; ++r) {
3908 auto &ent = storage.elemEntities[r];
3909 a00_indexing.emplace(ent.uid,
3910 LocIdx{ent.offset, ent.nb, ent.globParent});
3911 }
3912 a00_size = e.size;
3913 gather_a01t(a00_size);
3914 auto piv = storage.pivots.data() + e.pivShift;
3915 if (e.dense) {
3916 auto info = lapack_dgetrs('T', a00_size, a11_size,
3917 storage.elemDense[elem].data(), a00_size, piv,
3918 a01t_mat.data(), a00_size);
3919 if (info != 0)
3920 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3921 "error lapack dgetrs info = %d", static_cast<int>(info));
3922 } else {
3923 // nodes coupled to retained entities, other rows of A01 are zero
3924 nz.assign(pat.nbNodes, 0);
3925 for (auto b : a01_blocks)
3926 for (int r = 0; r != pat.nbNodes; ++r)
3927 if (storage.elemEntities[e.entBegin + r].uid == b->getRowUId())
3928 nz[r] = 1;
3929 auto &buf = mode == DATA_FACTORS ? storage.elemData[elem]
3930 : storage.elemPrec[elem];
3931 CHKERR elem_solve(pat, buf.data(), piv, a01t_mat.data(), a00_size,
3932 a11_size, false, &nz);
3933 }
3934 } else {
3935 a00_size = set_local_indices(a00_indexing, a00_blocks, a00_blocks);
3936 const int elem = a00_blocks.front()->getElem();
3937 if (elem >= 0 && !storage.elems[elem].local)
3938 continue;
3939 a00_mat.assign(static_cast<size_t>(a00_size) * a00_size, 0.);
3940 for (auto b : a00_blocks) {
3941 const auto &ri = a00_indexing.at(b->getRowUId());
3942 const auto &ci = a00_indexing.at(b->getColUId());
3943 copy_block(a00_mat.data(), a00_size, ri.index, ci.index,
3944 storage.blockPtr(*b), b->getLd(), b->getNbRows(),
3945 b->getNbCols());
3946 }
3947 // copy of element owned by other process
3948 if (elem >= 0 && !storage.elems[elem].owned &&
3949 is_zero_matrix(a00_mat.data(), a00_mat.size()))
3950 continue;
3951 ipiv.resize(a00_size);
3952 auto info = lapack_dgetrf(a00_size, a00_size, a00_mat.data(), a00_size,
3953 ipiv.data());
3954 if (info != 0)
3955 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3956 "error lapack dgetrf info = %d", static_cast<int>(info));
3957 gather_a01t(a00_size);
3958 info = lapack_dgetrs('T', a00_size, a11_size, a00_mat.data(), a00_size,
3959 ipiv.data(), a01t_mat.data(), a00_size);
3960 if (info != 0)
3961 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3962 "error lapack dgetrs info = %d", static_cast<int>(info));
3963 }
3964
3965 a10_mat.assign(static_cast<size_t>(a11_size) * a00_size, 0.);
3966 for (auto b : a10_blocks) {
3967 const auto &ri = a11_indexing.at(b->getRowUId());
3968 const auto &ci = a00_indexing.at(b->getColUId());
3969 copy_block(a10_mat.data(), a00_size, ri.index, ci.index,
3970 storage.blockPtr(*b), b->getLd(), b->getNbRows(),
3971 b->getNbCols());
3972 }
3973
3974 // S = -A10 A00^{-1} A01
3975 s_mat.resize(static_cast<size_t>(a11_size) * a11_size);
3976 cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, a11_size, a11_size,
3977 a00_size, -1., a10_mat.data(), a00_size, a01t_mat.data(),
3978 a00_size, 0., s_mat.data(), a11_size);
3979
3980 glob_idx.resize(a11_size);
3981 for (auto &pi : a11_indexing) {
3982 auto &[idx, size, glob] = pi.second;
3983 std::iota(glob_idx.begin() + idx, glob_idx.begin() + idx + size, glob);
3984 }
3985 CHKERR AOApplicationToPetsc(ao, a11_size, glob_idx.data());
3986 CHKERR MatSetValues(S, a11_size, glob_idx.data(), a11_size, glob_idx.data(),
3987 s_mat.data(), ADD_VALUES);
3988 }
3989
3990 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_AssembleSchurMat, 0, 0, 0, 0);
3991
3993}
3994
3995boost::shared_ptr<std::vector<double>> getBlockMatStorageMat(Mat B) {
3996 BlockStructure *ctx;
3997 CHKERR MatShellGetContext(B, (void **)&ctx);
3998 ctx->storage->ensureAllocated();
3999 return boost::shared_ptr<std::vector<double>>(ctx->storage,
4000 &ctx->storage->data);
4001}
4002
4003boost::shared_ptr<std::vector<double>>
4005 // preconditioner blocks are stored in buffers of A00 elements
4006 return boost::make_shared<std::vector<double>>();
4007}
4008
4010 BlockStructure *ctx, const EntitiesFieldData::EntData &row_data,
4011 const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat,
4012 InsertMode iora, bool is_preconditioner) {
4013
4015
4016 if (row_data.getIndices().empty())
4018 if (col_data.getIndices().empty())
4020
4021#ifndef NDEBUG
4022
4023 PetscLogEventBegin(SchurEvents::MOFEM_EVENT_BlockStructureSetValues, 0, 0, 0,
4024 0);
4025
4026#endif // NDEBUG
4027
4028 switch (iora) {
4029 case ADD_VALUES:
4030 case INSERT_VALUES:
4031 break;
4032 default:
4033 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED, "Wrong InsertMode");
4034 }
4035
4036 auto &storage = *ctx->storage;
4037 CHKERR storage.modified();
4038 storage.ensureAllocated();
4039
4040 auto get_row_data = [&]() -> std::pair<bool, VectorInt> {
4041 if (auto e_ptr = row_data.getFieldEntities()[0]) {
4042 if (auto stored_data_ptr =
4043 e_ptr->getSharedStoragePtr<EssentialBcStorage>()) {
4044 MOFEM_LOG("SELF", Sev::warning) << "Can lead to unhandled behaviour";
4045 return std::make_pair(true, stored_data_ptr->entityIndices);
4046 }
4047 }
4048 return std::make_pair(false, row_data.getIndices());
4049 };
4050
4051 auto row_indices = get_row_data();
4052 const auto &row_ind = row_indices.second;
4053 const auto &col_ind = col_data.getIndices();
4054
4055 std::vector<int> ent_row_indices;
4056 std::vector<int> ent_col_indices;
4057
4058 auto get_ent_indices = [](auto &cache, auto &ind) {
4059 ind.clear();
4060 ind.reserve(std::distance(cache->loHi[0], cache->loHi[1]));
4061 for (auto e = cache->loHi[0]; e != cache->loHi[1]; ++e) {
4062 auto glob = (*e)->getPetscGlobalDofIdx();
4063 if (glob != -1)
4064 ind.push_back(glob);
4065 }
4066 };
4067
4068 for (auto &rent : row_data.getFieldEntities()) {
4069 auto r_cache = rent->entityCacheRowDofs.lock();
4070 if (!r_cache)
4071 continue;
4072 get_ent_indices(r_cache, ent_row_indices);
4073 if (ent_row_indices.empty())
4074 continue;
4075 const auto &row_uid = rent->getLocalUniqueId();
4076
4077 for (auto &cent : col_data.getFieldEntities()) {
4078 auto c_cache = cent->entityCacheColDofs.lock();
4079 if (!c_cache)
4080 continue;
4081 get_ent_indices(c_cache, ent_col_indices);
4082 if (ent_col_indices.empty())
4083 continue;
4084 const auto &col_uid = cent->getLocalUniqueId();
4085
4086 auto idx = storage.find(row_uid, col_uid);
4087 if (!idx) {
4088 MOFEM_LOG_CHANNEL("SELF");
4089 MOFEM_TAG_AND_LOG("SELF", Sev::error, "BlockMat")
4090 << "missing block: row " << row_data.getFieldDofs()[0]->getName()
4091 << " col " << col_data.getFieldDofs()[0]->getName();
4092 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
4093 "Block not allocated");
4094 }
4095 if (is_preconditioner && idx->getElem() == -1)
4096 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
4097 "Preconditioner blocks are allocated only for A00 element "
4098 "matrices");
4099
4100 const int nb_rows = idx->getNbRows();
4101 const int nb_cols = idx->getNbCols();
4102 const int ld = idx->getLd();
4103 double *s_mat = storage.blockPtr(*idx, is_preconditioner);
4104
4105 if (mat.size1() == ent_row_indices.size() &&
4106 mat.size2() == ent_col_indices.size()) {
4107
4108 const double *m = mat.data().data();
4109 if (ld == nb_cols) {
4110 if (iora == ADD_VALUES)
4111 cblas_daxpy(nb_rows * nb_cols, 1.0, m, 1, s_mat, 1);
4112 else
4113 cblas_dcopy(nb_rows * nb_cols, m, 1, s_mat, 1);
4114 } else {
4115 for (int i = 0; i != nb_rows; ++i) {
4116 if (iora == ADD_VALUES)
4117 cblas_daxpy(nb_cols, 1.0, m + static_cast<size_t>(i) * nb_cols, 1,
4118 s_mat + static_cast<size_t>(i) * ld, 1);
4119 else
4120 cblas_dcopy(nb_cols, m + static_cast<size_t>(i) * nb_cols, 1,
4121 s_mat + static_cast<size_t>(i) * ld, 1);
4122 }
4123 }
4124
4125 } else {
4126
4127 auto ri = row_ind.begin();
4128 auto rie = row_ind.end();
4129
4130 int row = 0;
4131 for (auto re : ent_row_indices) {
4132 ri = std::find(ri, rie, re);
4133 if (ri != rie) {
4134
4135 auto ci = col_ind.begin();
4136 auto cie = col_ind.end();
4137
4138 int col = 0;
4139 for (auto ce : ent_col_indices) {
4140 ci = std::find(ci, cie, ce);
4141 if (ci != cie) {
4142 auto &m = s_mat[static_cast<size_t>(row) * ld + col];
4143 if (iora == ADD_VALUES) {
4144 m += mat(std::distance(row_ind.begin(), ri),
4145 std::distance(col_ind.begin(), ci));
4146 } else {
4147 m = mat(std::distance(row_ind.begin(), ri),
4148 std::distance(col_ind.begin(), ci));
4149 }
4150 }
4151 ++col;
4152 } // cols
4153 }
4154 ++row;
4155 } // rows
4156 }
4157
4158 } // iterate entities
4159 }
4160
4161#ifndef NDEBUG
4162 PetscLogEventEnd(SchurEvents::MOFEM_EVENT_BlockStructureSetValues, 0, 0, 0,
4163 0);
4164#endif // NDEBUG
4165
4167}
4168
4169MoFEMErrorCode
4171 const EntitiesFieldData::EntData &col_data,
4172 const MatrixDouble &mat, InsertMode iora) {
4174 PetscBool is_mat_shell = PETSC_FALSE;
4175 PetscObjectTypeCompare((PetscObject)M, MATSHELL, &is_mat_shell);
4176 if (is_mat_shell) {
4177 BlockStructure *ctx;
4178 CHKERR MatShellGetContext(M, (void **)&ctx);
4179 CHKERR shell_block_mat_asmb_wrap_impl(ctx, row_data, col_data, mat, iora,
4180 false);
4181 } else {
4182 CHKERR MatSetValues<AssemblyTypeSelector<PETSC>>(M, row_data, col_data, mat,
4183 iora);
4184 }
4186}
4187
4189 Mat M, const EntitiesFieldData::EntData &row_data,
4190 const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat,
4191 InsertMode iora) {
4193 PetscBool is_mat_shell = PETSC_FALSE;
4194 PetscObjectTypeCompare((PetscObject)M, MATSHELL, &is_mat_shell);
4195 if (is_mat_shell) {
4196 BlockStructure *ctx;
4197 CHKERR MatShellGetContext(M, (void **)&ctx);
4198 if (!ctx->storage->hasPreconditioner)
4199 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
4200 "No preconditioner blocks");
4201 CHKERR shell_block_mat_asmb_wrap_impl(ctx, row_data, col_data, mat, iora,
4202 true);
4203 } else {
4204 CHKERR MatSetValues<AssemblyTypeSelector<PETSC>>(M, row_data, col_data, mat,
4205 iora);
4206 }
4208}
4209
4210/**
4211 * @brief Lay A00 blocks out in element buffers and make the nested matrices
4212 *
4213 * Shared by createSchurNestedMatrixStruture and
4214 * rebuildSchurNestedMatrixStruture. Given data_ptrs are reused; patterns
4215 * cached by rebuildBlockMatStructure are reused for elements with the same
4216 * pattern key, with their layout and analysis.
4217 */
4218static boost::shared_ptr<NestSchurData> nest_block_structure(
4219
4220 std::pair<SmartPetscObj<DM>, SmartPetscObj<DM>> dms,
4221 boost::shared_ptr<BlockStructure> block_mat_data_ptr,
4222 bool add_preconditioner_block,
4223 std::array<boost::shared_ptr<BlockStructure>, 4> data_ptrs) {
4224
4225 auto &storage = *block_mat_data_ptr->storage;
4226 auto &index = storage.blockIndex;
4227 const int nb_blocks = index.size();
4228
4229 if (storage.isFactorised())
4231 "Block matrix is factorised in place");
4232 // layout of storage is changed, that would invalidate nested matrices
4233 // created before
4234 if (storage.nested)
4236 "Nested Schur structure already created for this block "
4237 "matrix, create new one with createBlockMatStructure");
4238
4239 int nb_local_parent;
4240 CHKERR VecGetLocalSize(block_mat_data_ptr->ghostX, &nb_local_parent);
4241
4242 auto [schur_dm, block_dm] = dms;
4243 auto schur_prb = getProblemPtr(schur_dm);
4244 auto block_prb = getProblemPtr(block_dm);
4245 auto m_field_ptr = getInterfacePtr(block_dm);
4246
4247 auto schur_vec_x = createDMVector(schur_dm);
4248 auto block_vec_x = createDMVector(block_dm);
4249 auto schur_vec_y = vectorDuplicate(schur_vec_x);
4250 auto block_vec_y = vectorDuplicate(block_vec_x);
4251 CHKERR VecSetDM(schur_vec_x, PETSC_NULLPTR);
4252 CHKERR VecSetDM(block_vec_x, PETSC_NULLPTR);
4253 CHKERR VecSetDM(schur_vec_y, PETSC_NULLPTR);
4254 CHKERR VecSetDM(block_vec_y, PETSC_NULLPTR);
4255
4256 auto find_field_ent = [&](auto uid, auto prb, auto rc) {
4257 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs;
4258
4259 switch (rc) {
4260 case ROW:
4261 dofs = prb->getNumeredRowDofsPtr();
4262 break;
4263 case COL:
4264 dofs = prb->getNumeredColDofsPtr();
4265 break;
4266 default:
4268 break;
4269 }
4270
4271 auto lo = dofs->get<Unique_mi_tag>().lower_bound(uid);
4272 if (lo == dofs->get<Unique_mi_tag>().end())
4273 return boost::shared_ptr<NumeredDofEntity>();
4274 auto hi = dofs->get<Unique_mi_tag>().upper_bound(
4275 DofEntity::getUniqueIdCalculate(MAX_DOFS_ON_ENTITY - 1, uid));
4276 if (lo != hi)
4277 return *lo;
4278
4279 return boost::shared_ptr<NumeredDofEntity>();
4280 };
4281
4282 // indices of block entities in sub-problems, -1 if entity is not in
4283 // sub-problem
4284 struct SubIdx {
4285 int glob = -1;
4286 int loc = -1;
4287 };
4288 struct SubIdxs {
4289 SubIdx schurRow, schurCol, blockRow, blockCol;
4290 };
4291 std::vector<SubIdxs> sub(nb_blocks);
4292 auto get_sub = [&](auto uid, auto prb, auto rc) {
4293 SubIdx s;
4294 if (auto dof = find_field_ent(uid, prb, rc)) {
4295 s.glob = dof->getPetscGlobalDofIdx();
4296 s.loc = dof->getPetscLocalDofIdx();
4297 }
4298 return s;
4299 };
4300 // One ordered walk per DOF container: blocks are ordered by row uid, and
4301 // colOrder orders them by column uid. The first DOF of the entity gives
4302 // its indices, as get_sub does.
4303 auto walk_sub = [](DofRangeWalk &walk, const UId &uid) {
4304 SubIdx s;
4305 const auto range = walk(uid);
4306 if (range.first != range.second) {
4307 s.glob = (*range.first)->getPetscGlobalDofIdx();
4308 s.loc = (*range.first)->getPetscLocalDofIdx();
4309 }
4310 return s;
4311 };
4312 (void)get_sub;
4313 DofRangeWalk schur_row_walk(*schur_prb->getNumeredRowDofsPtr());
4314 DofRangeWalk block_row_walk(*block_prb->getNumeredRowDofsPtr());
4315 DofRangeWalk schur_col_walk(*schur_prb->getNumeredColDofsPtr());
4316 DofRangeWalk block_col_walk(*block_prb->getNumeredColDofsPtr());
4317 for (int i = 0; i != nb_blocks;) {
4318 const auto uid = index[i].getRowUId();
4319 const auto schur_row = walk_sub(schur_row_walk, uid);
4320 const auto block_row = walk_sub(block_row_walk, uid);
4321 for (; i != nb_blocks && index[i].getRowUId() == uid; ++i) {
4322 sub[i].schurRow = schur_row;
4323 sub[i].blockRow = block_row;
4324 }
4325 }
4326 {
4327 auto &col_order = storage.colOrder;
4328 for (size_t p = 0; p != col_order.size();) {
4329 const auto uid = index[col_order[p]].getColUId();
4330 const auto schur_col = walk_sub(schur_col_walk, uid);
4331 const auto block_col = walk_sub(block_col_walk, uid);
4332 for (; p != col_order.size() && index[col_order[p]].getColUId() == uid;
4333 ++p) {
4334 sub[col_order[p]].schurCol = schur_col;
4335 sub[col_order[p]].blockCol = block_col;
4336 }
4337 }
4338 }
4339
4340 // A00 elements: blocks with both entities in block sub-problem, grouped by
4341 // finite element, stored in element buffers
4342 std::vector<std::pair<size_t, int>> old_layout(nb_blocks);
4343 for (int i = 0; i != nb_blocks; ++i) {
4344 old_layout[i] = std::make_pair(index[i].getMatShift(), index[i].getLd());
4345 index[i].setStorage(0, index[i].getNbCols(), -1);
4346 }
4347
4348 std::vector<int> a00;
4349 for (int i = 0; i != nb_blocks; ++i) {
4350 if (sub[i].blockRow.glob != -1 && sub[i].blockCol.glob != -1)
4351 a00.push_back(i);
4352 }
4353 std::sort(a00.begin(), a00.end(), [&index](int a, int b) {
4354 if (index[a].getFEUId() != index[b].getFEUId())
4355 return index[a].getFEUId() < index[b].getFEUId();
4356 return a < b;
4357 });
4358
4359 storage.patterns.clear();
4360 storage.elems.clear();
4361 storage.elemEntities.clear();
4362 storage.maxElemSize = 0;
4363 int nb_pivots = 0;
4364 std::map<std::vector<long>, int> pattern_map;
4365 std::map<std::vector<long>, int> cache_map;
4366 for (int ci = 0; ci != static_cast<int>(storage.patternCache.size()); ++ci)
4367 cache_map.emplace(storage.patternCache[ci].key, ci);
4368 std::vector<BlockStorage::ElemEntity> ents;
4369 std::vector<long> key;
4370
4371 for (size_t p = 0; p != a00.size();) {
4372 const auto fe_uid = index[a00[p]].getFEUId();
4373 const size_t p_begin = p;
4374 ents.clear();
4375 for (; p != a00.size() && index[a00[p]].getFEUId() == fe_uid; ++p) {
4376 const auto i = a00[p];
4377 auto &d = index[i];
4378 ents.push_back({d.getRowUId(), d.getNbRows(), 0, d.getLocRow(),
4379 d.getRow(), sub[i].blockRow.loc, sub[i].blockRow.glob});
4380 ents.push_back({d.getColUId(), d.getNbCols(), 0, d.getLocCol(),
4381 d.getCol(), sub[i].blockCol.loc, sub[i].blockCol.glob});
4382 }
4383 std::sort(ents.begin(), ents.end(),
4384 [](auto &a, auto &b) { return a.uid < b.uid; });
4385 ents.erase(std::unique(ents.begin(), ents.end(),
4386 [](auto &a, auto &b) { return a.uid == b.uid; }),
4387 ents.end());
4388 const int k = ents.size();
4389 auto node_of = [&](const UId &uid) {
4390 return static_cast<int>(
4391 std::lower_bound(ents.begin(), ents.end(), uid,
4392 [](auto &e, auto &u) { return e.uid < u; }) -
4393 ents.begin());
4394 };
4395
4396 // pattern: fields, entity types and sizes of nodes, listed pairs
4397 std::vector<char> listed(k * k, 0);
4398 for (size_t q = p_begin; q != p; ++q) {
4399 auto &d = index[a00[q]];
4400 listed[node_of(d.getRowUId()) * k + node_of(d.getColUId())] = 1;
4401 }
4402 key.clear();
4403 key.push_back(k);
4404 int n = 0;
4405 for (auto &e : ents) {
4406 key.push_back(FieldEntity::getFieldBitNumberFromUniqueId(e.uid));
4407 key.push_back(
4408 type_from_handle(FieldEntity::getHandleFromUniqueId(e.uid)));
4409 key.push_back(e.nb);
4410 n += e.nb;
4411 }
4412 key.insert(key.end(), listed.begin(), listed.end());
4413 auto pit = pattern_map.find(key);
4414 if (pit == pattern_map.end()) {
4416 auto cit = cache_map.find(key);
4417 if (cit != cache_map.end()) {
4418 // pattern of the layout before rebuild: its layout and analysis are
4419 // reused, statistics start again
4420 pat = storage.patternCache[cit->second];
4421 pat.nbElems = 0;
4422 pat.nbFallback = 0;
4423 pat.beMax = 0;
4424 pat.warned = false;
4425 } else {
4426 pat.nbNodes = k;
4427 pat.size = n;
4428 pat.listed = listed;
4429 pat.key = key;
4430 pat.nbListed = std::count(listed.begin(), listed.end(), 1);
4431 for (auto &e : ents) {
4432 pat.nodeSize.push_back(e.nb);
4433 pat.nodeName.push_back(
4434 m_field_ptr->get_field_name(field_bit_from_bit_number(
4435 FieldEntity::getFieldBitNumberFromUniqueId(e.uid))));
4436 }
4437 if (storage.optDense)
4438 make_block_layout(pat, {});
4439 else
4440 make_listed_layout(pat);
4441 }
4442 pit = pattern_map.emplace(key, storage.patterns.size()).first;
4443 storage.patterns.push_back(pat);
4444 }
4445 const int pi = pit->second;
4446 auto &pat = storage.patterns[pi];
4447 ++pat.nbElems;
4448
4449 const int elem_idx = storage.elems.size();
4450 const int ent_begin = storage.elemEntities.size();
4451 for (int r = 0; r != k; ++r)
4452 ents[r].offset = pat.nodeOffset[r];
4453 storage.elems.push_back({pi, n, ent_begin, ent_begin + k, nb_pivots});
4454 storage.elems.back().feUId = fe_uid;
4455 storage.elemEntities.insert(storage.elemEntities.end(), ents.begin(),
4456 ents.end());
4457 for (size_t q = p_begin; q != p; ++q) {
4458 auto &d = index[a00[q]];
4459 const int r = node_of(d.getRowUId()), c = node_of(d.getColUId());
4460 d.setStorage(pat.sShift(r, c), pat.sLd(r, c), elem_idx);
4461 }
4462
4463 nb_pivots += n;
4464 storage.maxElemSize = std::max(storage.maxElemSize, n);
4465
4466 auto &elem = storage.elems.back();
4467 elem.local = true;
4468 elem.owned = true;
4469 for (auto &e : ents) {
4470 if (!e.nb)
4471 continue;
4472 if (e.locParent < 0)
4473 elem.local = false;
4474 if (e.locParent < 0 || e.locParent >= nb_local_parent)
4475 elem.owned = false;
4476 }
4477 }
4478
4479 // eliminated entities have to be element local, i.e. each A00 entity
4480 // belongs to exactly one element
4481 {
4482 std::vector<UId> uids;
4483 uids.reserve(storage.elemEntities.size());
4484 for (auto &e : storage.elemEntities)
4485 uids.push_back(e.uid);
4486 std::sort(uids.begin(), uids.end());
4487 if (std::adjacent_find(uids.begin(), uids.end()) != uids.end())
4489 "Entity of A00 field is shared by more than one "
4490 "element, eliminated fields have to be element local "
4491 "(L2, broken spaces, or interior DOFs)");
4492 }
4493
4494 // blocks not in A00 elements are stored in data
4495 size_t mem_size = 0;
4496 for (auto &d : index) {
4497 if (d.getElem() == -1) {
4498 d.setStorage(mem_size, d.getNbCols(), -1);
4499 mem_size += static_cast<size_t>(d.getNbRows()) * d.getNbCols();
4500 }
4501 }
4502
4503 const int nb_elems = storage.elems.size();
4504 storage.hasPreconditioner = add_preconditioner_block;
4505 storage.elemData.assign(nb_elems, std::vector<double>());
4506 storage.elemPrec.assign(add_preconditioner_block ? nb_elems : 0,
4507 std::vector<double>());
4508 storage.elemDense.assign(nb_elems, std::vector<double>());
4509 storage.maxElemBuffer = 0;
4510 // buffers kept by rebuildBlockMatStructure go back to the same elements;
4511 // both are ordered by element uid
4512 auto take_cached = [](auto &cache, size_t &pos, const UId &uid,
4513 std::vector<double> &buf) {
4514 while (pos != cache.size() && cache[pos].first < uid)
4515 ++pos;
4516 if (pos != cache.size() && cache[pos].first == uid)
4517 buf.swap(cache[pos].second);
4518 };
4519 size_t data_pos = 0, prec_pos = 0;
4520 for (int ei = 0; ei != nb_elems; ++ei) {
4521 const auto sz = storage.patterns[storage.elems[ei].pattern].elemSize;
4522 // capacity of dense matrix, which is upper bound of any layout, is
4523 // reserved, such that buffers are relaid in place, see relayout_pattern
4524 const auto n = storage.elems[ei].size;
4525 const auto uid = storage.elems[ei].feUId;
4526 take_cached(storage.elemDataCache, data_pos, uid, storage.elemData[ei]);
4527 storage.elemData[ei].reserve(static_cast<size_t>(n) * n);
4528 storage.elemData[ei].assign(sz, 0.);
4529 if (add_preconditioner_block) {
4530 take_cached(storage.elemPrecCache, prec_pos, uid, storage.elemPrec[ei]);
4531 storage.elemPrec[ei].reserve(static_cast<size_t>(n) * n);
4532 storage.elemPrec[ei].assign(sz, 0.);
4533 }
4534 storage.maxElemBuffer = std::max(storage.maxElemBuffer, sz);
4535 }
4536 decltype(storage.elemDataCache)().swap(storage.elemDataCache);
4537 decltype(storage.elemPrecCache)().swap(storage.elemPrecCache);
4538
4539 // move data to new layout, data is allocated on first use, thus usually
4540 // nothing is moved
4541 auto &data = storage.data;
4542 const bool has_values =
4543 std::any_of(data.begin(), data.end(), [](double v) { return v != 0.; });
4544 if (has_values) {
4545 std::vector<double> new_data(mem_size, 0.);
4546 for (int i = 0; i != nb_blocks; ++i) {
4547 auto &d = index[i];
4548 auto [old_shift, old_ld] = old_layout[i];
4549 double *dst = d.getElem() >= 0
4550 ? storage.elemData[d.getElem()].data() + d.getMatShift()
4551 : new_data.data() + d.getMatShift();
4552 copy_block(dst, d.getLd(), 0, 0, data.data() + old_shift, old_ld,
4553 d.getNbRows(), d.getNbCols());
4554 }
4555 data.swap(new_data);
4556 } else {
4557 std::vector<double>().swap(data);
4558 }
4559 storage.dataSize = mem_size;
4560 storage.ensureAllocated();
4561 storage.pivots.assign(nb_pivots, 0);
4562 storage.factorStorage = BlockStorage::FACTOR_NONE;
4563
4564 set_parent_blocks(*block_mat_data_ptr);
4565
4566 // nested matrices share storage, each keeps blocks in its own numbering;
4567 // structures of a rebuilt nest are reused
4568 for (auto r = 0; r != 4; ++r) {
4569 if (!data_ptrs[r])
4570 data_ptrs[r] = boost::make_shared<BlockStructure>();
4571 auto &d = *data_ptrs[r];
4572 d.storage = block_mat_data_ptr->storage;
4573 d.blocks.clear();
4574 d.hasElems = false;
4575 d.numbering = BlockStructure::PARENT;
4576 d.multiplyByPreconditioner = false;
4577 d.ghostX.reset();
4578 d.ghostY.reset();
4579 }
4580 data_ptrs[3]->hasElems = !storage.elems.empty();
4581 data_ptrs[3]->numbering = BlockStructure::BLOCK;
4582
4583 for (int i = 0; i != nb_blocks; ++i) {
4584 auto &d = index[i];
4585 auto &s = sub[i];
4586 auto add = [&](auto &m, const SubIdx &r, const SubIdx &c) {
4587 m->blocks.push_back({d.getMatShift(), d.getLd(), r.glob, c.glob,
4588 d.getNbRows(), d.getNbCols(), r.loc, c.loc});
4589 };
4590 if (s.schurRow.glob != -1 && s.schurCol.glob != -1)
4591 add(data_ptrs[0], s.schurRow, s.schurCol);
4592 if (s.schurRow.glob != -1 && s.blockCol.glob != -1)
4593 add(data_ptrs[1], s.schurRow, s.blockCol);
4594 if (s.blockRow.glob != -1 && s.schurCol.glob != -1)
4595 add(data_ptrs[2], s.blockRow, s.schurCol);
4596 // blocks with both entities in block sub-problem are element blocks
4597 if (s.blockRow.glob != -1 && s.blockCol.glob != -1 && d.getElem() == -1)
4598 CHK_THROW_MESSAGE(MOFEM_DATA_INCONSISTENCY, "Block not in element");
4599 }
4600 for (auto r = 0; r != 3; ++r)
4601 data_ptrs[r]->blocks.shrink_to_fit();
4602
4603 data_ptrs[0]->ghostX = schur_vec_x;
4604 data_ptrs[0]->ghostY = schur_vec_y;
4605 data_ptrs[1]->ghostX = block_vec_x;
4606 data_ptrs[1]->ghostY = schur_vec_y;
4607 data_ptrs[2]->ghostX = schur_vec_x;
4608 data_ptrs[2]->ghostY = block_vec_y;
4609 data_ptrs[3]->ghostX = block_vec_x;
4610 data_ptrs[3]->ghostY = block_vec_y;
4611
4612 if (add_preconditioner_block) {
4613 data_ptrs[3]->multiplyByPreconditioner = true;
4614 block_mat_data_ptr->multiplyByPreconditioner = false;
4615 }
4616
4617 MPI_Comm comm;
4618 CHKERR PetscObjectGetComm((PetscObject)schur_dm, &comm);
4619
4620 auto create_shell_mat = [&](auto nb_r_loc, auto nb_c_loc, auto nb_r_glob,
4621 auto nb_c_glob, auto data_ptr) {
4622 Mat mat_raw;
4623 CHKERR MatCreateShell(comm, nb_r_loc, nb_c_loc, nb_r_glob, nb_c_glob,
4624 (void *)data_ptr.get(), &mat_raw);
4625 CHKERR setSchurBlockMatOps(mat_raw);
4626 return SmartPetscObj<Mat>(mat_raw);
4627 };
4628
4629 auto schur_nb_global = schur_prb->getNbDofsRow();
4630 auto block_nb_global = block_prb->getNbDofsRow();
4631 auto schur_nb_local = schur_prb->getNbLocalDofsRow();
4632 auto block_nb_local = block_prb->getNbLocalDofsRow();
4633
4634 std::array<SmartPetscObj<Mat>, 4> mats_array;
4635 mats_array[0] =
4636 create_shell_mat(schur_nb_local, schur_nb_local, schur_nb_global,
4637 schur_nb_global, data_ptrs[0]);
4638 mats_array[1] =
4639 create_shell_mat(schur_nb_local, block_nb_local, schur_nb_global,
4640 block_nb_global, data_ptrs[1]);
4641 mats_array[2] =
4642 create_shell_mat(block_nb_local, schur_nb_local, block_nb_global,
4643 schur_nb_global, data_ptrs[2]);
4644 mats_array[3] =
4645 create_shell_mat(block_nb_local, block_nb_local, block_nb_global,
4646 block_nb_global, data_ptrs[3]);
4647
4648 MOFEM_TAG_AND_LOG("SYNC", Sev::verbose, "NestedSchur")
4649 << "(0, 0) " << schur_nb_local << " " << schur_nb_global << " "
4650 << data_ptrs[0]->blocks.size();
4651 MOFEM_TAG_AND_LOG("SYNC", Sev::verbose, "NestedSchur")
4652 << "(0, 1) " << schur_nb_local << " " << block_nb_local << " "
4653 << schur_nb_global << " " << block_nb_global << " "
4654 << data_ptrs[1]->blocks.size();
4655 MOFEM_TAG_AND_LOG("SYNC", Sev::verbose, "NestedSchur")
4656 << "(1, 0) " << block_nb_local << " " << schur_nb_local << " "
4657 << block_nb_global << " " << schur_nb_global << " "
4658 << data_ptrs[2]->blocks.size();
4659 MOFEM_TAG_AND_LOG("SYNC", Sev::verbose, "NestedSchur")
4660 << "(1, 1) " << block_nb_local << " " << block_nb_global << " "
4661 << storage.elems.size() << " elements (" << a00.size() << " blocks, "
4662 << storage.patterns.size() << " patterns) max size "
4663 << storage.maxElemSize;
4664
4665 MOFEM_LOG_SEVERITY_SYNC(comm, Sev::verbose);
4666
4667 {
4668 // element storage: listed blocks, dense element matrices, and block
4669 // elimination estimated from pattern structure only
4670 size_t listed_d = 0, dense_d = 0, struct_d = 0, buffers_d = 0;
4671 for (auto &pat : storage.patterns) {
4672 auto est = pat;
4674 listed_d += pat.nbElems * listed_size(pat);
4675 dense_d += pat.nbElems * static_cast<size_t>(pat.size) * pat.size;
4676 struct_d += pat.nbElems * est.elemSize;
4677 buffers_d += pat.nbElems * pat.elemSize;
4678 MOFEM_TAG_AND_LOG("WORLD", Sev::verbose, "NestedSchur")
4679 << "A00 pattern (" << pat.nbElems << " elements): "
4680 << describe_nodes(pat,
4681 [&]() {
4682 std::vector<int> all(pat.nbNodes);
4683 std::iota(all.begin(), all.end(), 0);
4684 return all;
4685 }())
4686 << "; listed pairs " << pat.nbListed << " of "
4687 << pat.nbNodes * pat.nbNodes << "; doubles per element: listed "
4688 << listed_size(pat) << ", dense "
4689 << static_cast<size_t>(pat.size) * pat.size
4690 << ", structural estimate " << est.elemSize << " (eliminated "
4691 << describe_nodes(est, est.order) << ")";
4692 }
4693 // data of elements and blocks with all rows and columns not owned by this
4694 // process (such blocks are not assembled by this process)
4695 size_t ghost_elems = 0, ghost_elems_data = 0, ghost_blocks_data = 0;
4696 for (int ei = 0; ei != nb_elems; ++ei) {
4697 auto &e = storage.elems[ei];
4698 bool all_ghost = true;
4699 for (int k = e.entBegin; k != e.entEnd; ++k)
4700 if (storage.elemEntities[k].locParent < nb_local_parent)
4701 all_ghost = false;
4702 if (all_ghost) {
4703 ++ghost_elems;
4704 ghost_elems_data += storage.elemData[ei].size();
4705 }
4706 }
4707 for (auto &d : index)
4708 if (d.getElem() == -1 && d.getLocRow() >= nb_local_parent &&
4709 d.getLocCol() >= nb_local_parent)
4710 ghost_blocks_data += static_cast<size_t>(d.getNbRows()) * d.getNbCols();
4711
4712 constexpr size_t dsz = sizeof(double);
4713 std::array<size_t, 10> loc_stats = {
4714 storage.elems.size(),
4715 buffers_d * dsz,
4716 listed_d * dsz,
4717 dense_d * dsz,
4718 struct_d * dsz,
4719 mem_size * dsz,
4720 (add_preconditioner_block ? buffers_d : 0) * dsz,
4721 ghost_elems,
4722 ghost_elems_data * dsz,
4723 ghost_blocks_data * dsz};
4724 std::array<size_t, 10> sum_stats, max_stats;
4725 MPI_Allreduce(loc_stats.data(), sum_stats.data(), 10, MPIU_SIZE_T, MPI_SUM,
4726 comm);
4727 MPI_Allreduce(loc_stats.data(), max_stats.data(), 10, MPIU_SIZE_T, MPI_MAX,
4728 comm);
4729 constexpr double mb = 1024. * 1024.;
4730 MOFEM_TAG_AND_LOG("WORLD", Sev::verbose, "NestedSchur")
4731 << "A00 elements " << sum_stats[0] << " (max per process "
4732 << max_stats[0] << "), element buffers " << sum_stats[1] / mb
4733 << " MB (max per process " << max_stats[1] / mb
4734 << " MB); listed blocks " << sum_stats[2] / mb
4735 << " MB, dense element matrices would be " << sum_stats[3] / mb
4736 << " MB, structural estimate of block elimination " << sum_stats[4] / mb
4737 << " MB; other blocks data " << sum_stats[5] / mb
4738 << " MB (max per process " << max_stats[5] / mb
4739 << " MB); preconditioner blocks " << sum_stats[6] / mb << " MB";
4740 MOFEM_TAG_AND_LOG("WORLD", Sev::verbose, "NestedSchur")
4741 << "Not owned (ghost) elements " << sum_stats[7] << " data "
4742 << sum_stats[8] / mb << " MB, not owned other blocks data "
4743 << sum_stats[9] / mb << " MB";
4744 }
4745
4746 auto schur_is = schur_prb->getSubData()->getSmartRowIs();
4747 auto block_is = block_prb->getSubData()->getSmartRowIs();
4748
4749 storage.nested = true;
4750 std::vector<BlockStorage::Pattern>().swap(storage.patternCache);
4751
4752 return boost::make_shared<NestSchurData>(
4753
4754 mats_array, data_ptrs, block_mat_data_ptr,
4755 std::make_pair(schur_is, block_is)
4756
4757 );
4758}
4759
4760boost::shared_ptr<NestSchurData> createSchurNestedMatrixStruture(
4761
4762 std::pair<SmartPetscObj<DM>, SmartPetscObj<DM>> dms,
4763 boost::shared_ptr<BlockStructure> block_mat_data_ptr,
4764
4765 std::vector<std::string> fields_names, //< a00 fields
4766 std::vector<boost::shared_ptr<Range>>
4767 field_ents, //< a00 ranges (can be null),
4768 bool add_preconditioner_block) {
4769
4770 if (!block_mat_data_ptr) {
4771 CHK_THROW_MESSAGE(MOFEM_DATA_INCONSISTENCY, "Block data not set");
4772 }
4773
4774 if (fields_names.size() != field_ents.size())
4776 "fields_names.size() != field_ents.size()");
4777
4778 auto &storage = *block_mat_data_ptr->storage;
4779 {
4780 PetscBool dense = PETSC_FALSE;
4781 CHKERR PetscOptionsGetBool(PETSC_NULLPTR, "", "-schur_a00_dense", &dense,
4782 PETSC_NULLPTR);
4783 storage.optDense = dense == PETSC_TRUE;
4784 CHKERR ::PetscOptionsGetReal(PETSC_NULLPTR, "",
4785 "-schur_a00_pivot_threshold",
4786 &storage.optPivotThreshold, PETSC_NULLPTR);
4787 CHKERR ::PetscOptionsGetReal(PETSC_NULLPTR, "", "-schur_a00_rcond_min",
4788 &storage.optRcondMin, PETSC_NULLPTR);
4789 CHKERR ::PetscOptionsGetReal(PETSC_NULLPTR, "", "-schur_a00_backward_error",
4790 &storage.optBackwardError, PETSC_NULLPTR);
4791 }
4792 if (!storage.nested)
4793 std::vector<BlockStorage::Pattern>().swap(storage.patternCache);
4794
4795 return nest_block_structure(dms, block_mat_data_ptr,
4796 add_preconditioner_block, {});
4797}
4798
4800 std::pair<SmartPetscObj<DM>, SmartPetscObj<DM>> dms,
4801 boost::shared_ptr<NestSchurData> nest_data_ptr) {
4803 if (!nest_data_ptr)
4804 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Nested data not set");
4805 auto block_mat_data_ptr = std::get<2>(*nest_data_ptr);
4806 if (!block_mat_data_ptr || !block_mat_data_ptr->storage)
4807 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Block data not set");
4808 auto &storage = *block_mat_data_ptr->storage;
4809 if (storage.nested)
4810 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
4811 "Block structure has not been rebuilt: call "
4812 "rebuildBlockMatStructure before rebuildSchurNestedMatrixStruture");
4813 auto rebuilt =
4814 nest_block_structure(dms, block_mat_data_ptr, storage.hasPreconditioner,
4815 std::get<1>(*nest_data_ptr));
4816 *nest_data_ptr = *rebuilt;
4818}
4819
4820SchurBlockStructureDigest
4821schurBlockStructureDigest(boost::shared_ptr<BlockStructure> data_ptr) {
4823 if (!data_ptr || !data_ptr->storage)
4824 return d;
4825 auto &s = *data_ptr->storage;
4826 auto add_uid = [](std::size_t &h, const UId &u) {
4827 boost::hash_combine(h, static_cast<unsigned long long>(u));
4828 boost::hash_combine(h, static_cast<unsigned long long>(u >> 64));
4829 };
4830 d.nbBlocks = s.blockIndex.size();
4831 d.nbElems = s.elems.size();
4832 d.nbPatterns = s.patterns.size();
4833 for (auto &b : s.blockIndex) {
4834 add_uid(d.indexHash, b.getRowUId());
4835 add_uid(d.indexHash, b.getColUId());
4836 add_uid(d.indexHash, b.getFEUId());
4837 for (int v : {b.getRow(), b.getCol(), b.getNbRows(), b.getNbCols(),
4838 b.getLocRow(), b.getLocCol(), b.getElem() >= 0 ? 1 : 0})
4839 boost::hash_combine(d.indexHash, v);
4840 }
4841 for (auto &b : data_ptr->blocks)
4842 for (int v : {b.row, b.col, b.nbRows, b.nbCols, b.locRow, b.locCol})
4843 boost::hash_combine(d.blocksHash, v);
4844 for (auto &e : s.elems) {
4845 for (auto v : s.patterns[e.pattern].key)
4846 boost::hash_combine(d.elemsHash, v);
4847 for (int k = e.entBegin; k != e.entEnd; ++k) {
4848 auto &ent = s.elemEntities[k];
4849 add_uid(d.elemsHash, ent.uid);
4850 for (int v : {ent.nb, ent.locParent, ent.globParent, ent.locBlock,
4851 ent.globBlock})
4852 boost::hash_combine(d.elemsHash, v);
4853 }
4854 }
4855 return d;
4856}
4857
4858std::pair<SmartPetscObj<Mat>, boost::shared_ptr<NestSchurData>>
4859createSchurNestedMatrix(boost::shared_ptr<NestSchurData> schur_net_data_ptr) {
4860
4861 if (!schur_net_data_ptr)
4863
4864 auto [mat_arrays, data_ptrs, block_mat_data_ptr, iss] = *schur_net_data_ptr;
4865 auto [schur_is, block_is] = iss;
4866
4867 std::array<IS, 2> is_a = {schur_is, block_is};
4868 std::array<Mat, 4> mats_a = {
4869
4870 mat_arrays[0], mat_arrays[1], mat_arrays[2], mat_arrays[3]
4871
4872 };
4873
4874 MPI_Comm comm;
4875 CHKERR PetscObjectGetComm((PetscObject)mat_arrays[0], &comm);
4876
4877 Mat mat_raw;
4878 CHKERR MatCreateNest(
4879
4880 comm, 2, is_a.data(), 2, is_a.data(), mats_a.data(), &mat_raw
4881
4882 );
4883
4884 return std::make_pair(SmartPetscObj<Mat>(mat_raw), schur_net_data_ptr);
4885}
4886
4890
4891OpSchurAssembleBase *
4892createOpSchurAssembleEnd(std::vector<std::string> fields_name,
4893 std::vector<boost::shared_ptr<Range>> field_ents,
4895 bool sym_schur, bool symm_op) {
4896 if (symm_op)
4897 return new OpSchurAssembleEnd<SchurDSYSV>(fields_name, field_ents, ao,
4898 schur, sym_schur, symm_op);
4899 else
4900 return new OpSchurAssembleEnd<SchurDGESV>(fields_name, field_ents, ao,
4901 schur, sym_schur, symm_op);
4902}
4903
4905 boost::shared_ptr<std::vector<unsigned char>> marker_ptr, double diag_val) {
4906 return new OpSchurZeroRowsAndCols(marker_ptr, diag_val);
4907}
4908
4909OpSchurAssembleBase *
4910createOpSchurAssembleEnd(std::vector<std::string> fields_name,
4911 std::vector<boost::shared_ptr<Range>> field_ents,
4912 std::vector<SmartPetscObj<AO>> sequence_of_aos,
4913 std::vector<SmartPetscObj<Mat>> sequence_of_mats,
4914 std::vector<bool> sym_schur, bool symm_op,
4915 boost::shared_ptr<BlockStructure> diag_blocks) {
4917 fields_name, field_ents, sequence_of_aos.back(), sequence_of_mats.back(),
4918 sym_schur.back(), symm_op);
4919}
4920
4921OpSchurAssembleBase *
4922createOpSchurAssembleEnd(std::vector<std::string> fields_name,
4923 std::vector<boost::shared_ptr<Range>> field_ents,
4924 std::vector<SmartPetscObj<AO>> sequence_of_aos,
4925 std::vector<SmartPetscObj<Mat>> sequence_of_mats,
4926 std::vector<bool> sym_schur,
4927 std::vector<double> diag_eps, bool symm_op,
4928 boost::shared_ptr<BlockStructure> diag_blocks) {
4930 fields_name, field_ents, sequence_of_aos.back(), sequence_of_mats.back(),
4931 sym_schur.back(), symm_op);
4932}
4933
4936
4937 auto apply = [](PC pc, Vec f, Vec x) {
4939 Mat A, P;
4940 CHKERR PCGetOperators(pc, &A, &P);
4941 CHKERR MatSolve(P, f, x);
4943 };
4944
4945 auto apply_transpose = [](PC pc, Vec f, Vec x) {
4947 Mat A, P;
4948 CHKERR PCGetOperators(pc, &A, &P);
4949 CHKERR MatSolveTranspose(P, f, x);
4951 };
4952
4953 CHKERR PCSetType(pc, PCSHELL);
4954 CHKERR PCShellSetApply(pc, apply);
4955 CHKERR PCShellSetApplyTranspose(pc, apply_transpose);
4956 CHKERR PCShellSetName(pc, "MoFEMSchurBlockPC");
4957
4959}
4960
4961// This is used to assemble local element matrices for Schur complement
4962// and matrix for KSP
4963template <>
4965MatSetValues<SchurElemMats>(Mat M, const EntitiesFieldData::EntData &row_data,
4966 const EntitiesFieldData::EntData &col_data,
4967 const MatrixDouble &mat, InsertMode iora) {
4968 return SchurElemMats::MatSetValues(M, row_data, col_data, mat, iora);
4969}
4970
4971MoFEMErrorCode
4973 const EntitiesFieldData::EntData &col_data,
4974 const MatrixDouble &mat, InsertMode iora) {
4975 return MatSetValues<AssemblyTypeSelector<PETSC>>(M, row_data, col_data, mat,
4976 iora);
4977}
4978
4979// Is assumed that standard PETSc assembly works for matrices used by KSP
4980SchurBackendMatSetValuesPtr::MatSetValuesPtr
4981 SchurBackendMatSetValuesPtr::matSetValuesPtr = schur_mat_set_values_wrap;
4982
4983// We assemble matrix for KSP and store local matrices for Schur complement.
4984// Schur complement is calculated and assembled in OpSchurAssembleEnd.
4985MoFEMErrorCode
4986SchurElemMats::MatSetValues(Mat M, const EntitiesFieldData::EntData &row_data,
4987 const EntitiesFieldData::EntData &col_data,
4988 const MatrixDouble &mat, InsertMode iora) {
4990 CHKERR assembleStorage(row_data, col_data, mat, iora);
4991 CHKERR SchurBackendMatSetValuesPtr::matSetValuesPtr(M, row_data, col_data,
4992 mat, iora);
4994}
4995
4996// All is now wrapped in specialisation of
4997// MatSetValues<AssemblyTypeSelector<SCHUR>>
4998template <>
4999MoFEMErrorCode MatSetValues<AssemblyTypeSelector<SCHUR>>(
5000 Mat M, const EntitiesFieldData::EntData &row_data,
5001 const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat,
5002 InsertMode iora) {
5003 return MatSetValues<SchurElemMats>(M, row_data, col_data, mat, iora);
5004}
5005
5006// Standard (PETSc) assembly block matrices do noe work
5007template <>
5009MatSetValues<BlockStructure>(Mat M, const EntitiesFieldData::EntData &row_data,
5010 const EntitiesFieldData::EntData &col_data,
5011 const MatrixDouble &mat, InsertMode iora) {
5012 return shell_block_mat_asmb_wrap(M, row_data, col_data, mat, iora);
5013}
5014
5016
5017 static MoFEMErrorCode MatSetValues(Mat M,
5018 const EntitiesFieldData::EntData &row_data,
5019 const EntitiesFieldData::EntData &col_data,
5020 const MatrixDouble &mat, InsertMode iora);
5021};
5022
5024 SchurBackendMatSetValuesPtr::matSetValuesBlockPtr =
5026
5028SchurElemMatsBlock::MatSetValues(Mat M,
5029 const EntitiesFieldData::EntData &row_data,
5030 const EntitiesFieldData::EntData &col_data,
5031 const MatrixDouble &mat, InsertMode iora) {
5033 CHKERR assembleStorage(row_data, col_data, mat, iora);
5034 CHKERR SchurBackendMatSetValuesPtr::matSetValuesBlockPtr(M, row_data,
5035 col_data, mat, iora);
5037}
5038
5039template <>
5041MatSetValues<SchurElemMatsBlock>(Mat M,
5042 const EntitiesFieldData::EntData &row_data,
5043 const EntitiesFieldData::EntData &col_data,
5044 const MatrixDouble &mat, InsertMode iora) {
5045 return SchurElemMatsBlock::MatSetValues(M, row_data, col_data, mat, iora);
5046}
5047
5049
5050 static MoFEMErrorCode MatSetValues(Mat M,
5051 const EntitiesFieldData::EntData &row_data,
5052 const EntitiesFieldData::EntData &col_data,
5053 const MatrixDouble &mat, InsertMode iora);
5054};
5055
5057 SchurBackendMatSetValuesPtr::matSetValuesPreconditionedBlockPtr =
5059
5060MoFEMErrorCode SchurElemMatsPreconditionedBlock::MatSetValues(
5061 Mat M, const EntitiesFieldData::EntData &row_data,
5062 const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat,
5063 InsertMode iora) {
5065 CHKERR assembleStorage(row_data, col_data, mat, iora);
5066 CHKERR SchurBackendMatSetValuesPtr::matSetValuesPreconditionedBlockPtr(
5067 M, row_data, col_data, mat, iora);
5069}
5070
5071template <>
5072MoFEMErrorCode MatSetValues<SchurElemMatsPreconditionedBlock>(
5073 Mat M, const EntitiesFieldData::EntData &row_data,
5074 const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat,
5075 InsertMode iora) {
5076 return SchurElemMatsPreconditionedBlock::MatSetValues(M, row_data, col_data,
5077 mat, iora);
5078}
5079
5080MoFEMErrorCode
5081schurSwitchPreconditioner(boost::shared_ptr<BlockStructure> block_mat_data) {
5083 if (block_mat_data->multiplyByPreconditioner) {
5084 block_mat_data->multiplyByPreconditioner = false;
5085 } else {
5086 if (!block_mat_data->storage->hasPreconditioner) {
5087 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
5088 "preconditioner blocks not set");
5089 }
5090 block_mat_data->multiplyByPreconditioner = true;
5091 }
5093}
5094
5095MoFEMErrorCode
5096schurSaveBlockMesh(boost::shared_ptr<BlockStructure> block_mat_data,
5097 std::string filename) {
5099
5100 moab::Core core;
5101 moab::Interface &moab = core;
5102
5103 ReadUtilIface *iface;
5104 CHKERR moab.query_interface(iface);
5105
5106 size_t size = 0;
5107 for_each_block(*block_mat_data,
5108 [&](double *, int, int, int, int, int, int, int) { ++size; });
5109
5110 EntityHandle starting_vertex;
5111 vector<double *> arrays_coord;
5112 CHKERR iface->get_node_coords(3, 4 * size, 0, starting_vertex, arrays_coord);
5113 EntityHandle starting_handle;
5114 EntityHandle *array;
5115 CHKERR iface->get_element_connect(size, 4, MBQUAD, 0, starting_handle, array);
5116
5117 double def_val_nrm2 = 0;
5118 Tag th_nrm2;
5119 CHKERR moab.tag_get_handle("nrm2", 1, MB_TYPE_DOUBLE, th_nrm2,
5120 MB_TAG_CREAT | MB_TAG_DENSE, &def_val_nrm2);
5121
5122 int def_val_mat_shift = 0;
5123 Tag th_mat_shift;
5124 CHKERR moab.tag_get_handle("mat_shift", 1, MB_TYPE_INTEGER, th_mat_shift,
5125 MB_TAG_CREAT | MB_TAG_DENSE, &def_val_mat_shift);
5126
5127 block_mat_data->storage->ensureAllocated();
5128
5129 int i = 0;
5130 for_each_block(*block_mat_data, [&](double *ptr, int ld, int row, int col,
5131 int nb_rows, int nb_cols, int, int) {
5132 // q0
5133 arrays_coord[0][4 * i + 0] = row;
5134 arrays_coord[1][4 * i + 0] = col;
5135 arrays_coord[2][4 * i + 0] = 0;
5136
5137 // q1
5138 arrays_coord[0][4 * i + 1] = row + nb_rows;
5139 arrays_coord[1][4 * i + 1] = col;
5140 arrays_coord[2][4 * i + 1] = 0;
5141
5142 // q2
5143 arrays_coord[0][4 * i + 2] = row + nb_rows;
5144 arrays_coord[1][4 * i + 2] = col + nb_cols;
5145 arrays_coord[2][4 * i + 2] = 0;
5146
5147 // q3
5148 arrays_coord[0][4 * i + 3] = row;
5149 arrays_coord[1][4 * i + 3] = col + nb_cols;
5150 arrays_coord[2][4 * i + 3] = 0;
5151
5152 // ele conn
5153 array[4 * i + 0] = starting_vertex + 4 * i + 0;
5154 array[4 * i + 1] = starting_vertex + 4 * i + 1;
5155 array[4 * i + 2] = starting_vertex + 4 * i + 2;
5156 array[4 * i + 3] = starting_vertex + 4 * i + 3;
5157
5158 double nrm2 = 0;
5159 for (int r = 0; r != nb_rows; ++r) {
5160 auto row_nrm2 =
5161 cblas_dnrm2(nb_cols, ptr + static_cast<size_t>(r) * ld, 1);
5162 nrm2 += row_nrm2 * row_nrm2;
5163 }
5164 nrm2 = std::sqrt(nrm2);
5165 int mat_shift = i;
5166 EntityHandle ele = starting_handle + i;
5167 CHKERR moab.tag_set_data(th_nrm2, &ele, 1, &nrm2);
5168 CHKERR moab.tag_set_data(th_mat_shift, &ele, 1, &mat_shift);
5169
5170 ++i;
5171 });
5172
5173 CHKERR iface->update_adjacencies(starting_handle, size, 4, array);
5174 CHKERR moab.write_file(filename.c_str(), "VTK", "");
5175
5177}
5178
5179} // namespace MoFEM
std::map< EntityHandle, int > index
TetMeshData result
size_t best
Definition CGALTools.cpp:63
int h
Corner vertex and its two front neighbours.
std::vector< int > removed
std::vector< int > size
int w
Free node.
Vec t
Removal: the ring edge.
ParentChildKey key
MPI_Comm comm
moab::Interface & mb
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
std::string type
#define MOFEM_LOG_SEVERITY_SYNC(comm, severity)
Synchronise "SYNC" on curtain severity level.
#define MOFEM_TAG_AND_LOG(channel, severity, tag)
Tag and log in channel.
std::vector< FieldBitNumber > row
Definition Schur.cpp:2488
int glob
global index of first DOF
Definition Schur.cpp:2504
int loc
local index of first DOF
Definition Schur.cpp:2506
It it
Definition Schur.cpp:2568
int nb
number of DOFs
Definition Schur.cpp:2505
It end
Definition Schur.cpp:2568
std::vector< FieldBitNumber > col
Definition Schur.cpp:2488
SmartPetscObj< Vec > work
SmartPetscObj< IS > rows
std::string name
constexpr double a
@ COL
@ ROW
#define MAX_DOFS_ON_ENTITY
Maximal number of DOFs on entity.
#define CHK_THROW_MESSAGE(err, msg)
Check and throw MoFEM exception.
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
@ NOSPACE
Definition definitions.h:83
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
#define BITFIELDID_SIZE
max number of fields
@ MOFEM_OPERATION_UNSUCCESSFUL
Definition definitions.h:34
@ MOFEM_DATA_INCONSISTENCY
Definition definitions.h:31
@ MOFEM_INVALID_DATA
Definition definitions.h:36
@ MOFEM_NOT_IMPLEMENTED
Definition definitions.h:32
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
#define MoFEMFunctionBeginHot
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
auto fun
constexpr int order
PetscErrorCode DMMoFEMGetProblemPtr(DM dm, const MoFEM::Problem **problem_ptr)
Get pointer to problem data structure.
Definition DMMoFEM.cpp:451
auto createDMVector(DM dm, RowColData rc=RowColData::COL)
Get smart vector from DM.
Definition DMMoFEM.hpp:1279
PetscErrorCode DMoFEMLoopFiniteElementsUpAndLowRank(DM dm, const char fe_name[], MoFEM::FEMethod *method, int low_rank, int up_rank, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
Executes FEMethod for finite elements in DM.
Definition DMMoFEM.cpp:643
multi_index_container< boost::shared_ptr< NumeredDofEntity >, indexed_by< ordered_unique< tag< Unique_mi_tag >, const_mem_fun< NumeredDofEntity::interface_type_DofEntity, UId, &NumeredDofEntity::getLocalUniqueId > >, ordered_non_unique< tag< Part_mi_tag >, member< NumeredDofEntity, unsigned int, &NumeredDofEntity::pArt > >, ordered_non_unique< tag< PetscGlobalIdx_mi_tag >, member< NumeredDofEntity, DofIdx, &NumeredDofEntity::petscGloablDofIdx > >, ordered_non_unique< tag< PetscLocalIdx_mi_tag >, member< NumeredDofEntity, DofIdx, &NumeredDofEntity::petscLocalDofIdx > >, ordered_non_unique< tag< Ent_mi_tag >, const_mem_fun< NumeredDofEntity::interface_type_DofEntity, EntityHandle, &NumeredDofEntity::getEnt > > > > NumeredDofEntity_multiIndex
MultiIndex container keeps NumeredDofEntity.
#define MOFEM_LOG(channel, severity)
Log.
#define MOFEM_LOG_CHANNEL(channel)
Set and reset channel.
FTensor::Index< 'i', SPACE_DIM > i
const double c
speed of light (cm/ns)
const double v
phase velocity of light in medium (cm/ns)
long int __CLPK_integer
Definition lapack_wrap.h:23
static __CLPK_integer lapack_dgetrf(__CLPK_integer m, __CLPK_integer n, __CLPK_doublereal *a, __CLPK_integer lda, __CLPK_integer *ipiv)
static __CLPK_integer lapack_dgetri(__CLPK_integer n, __CLPK_doublereal *a, __CLPK_integer lda, __CLPK_integer *ipiv, __CLPK_doublereal *work, __CLPK_integer lwork)
static __CLPK_integer lapack_dgetrs(char trans, __CLPK_integer n, __CLPK_integer nrhs, __CLPK_doublereal *a, __CLPK_integer lda, __CLPK_integer *ipiv, __CLPK_doublereal *b, __CLPK_integer ldb)
FTensor::Index< 'j', 3 > j
FTensor::Index< 'k', 3 > k
static MoFEMErrorCodeGeneric< PetscErrorCode > ierr
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
uint128_t UId
Unique Id.
Definition Types.hpp:31
UBlasMatrix< double > MatrixDouble
Definition Types.hpp:77
UBlasVector< int > VectorInt
Definition Types.hpp:67
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
SchurBlockStructureDigest schurBlockStructureDigest(boost::shared_ptr< BlockStructure > data_ptr)
Definition Schur.cpp:4821
auto type_from_handle(const EntityHandle h)
get type from entity handle
MoFEMErrorCode schur_mat_set_values_wrap(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)
Definition Schur.cpp:4972
static void add_gemv(bool trans_a, int m, int kk, const double *a, int lda, const double *x, double *y)
y += op(A) x, op(A) is m x kk, A is column-major
Definition Schur.cpp:1423
MoFEMErrorCode shell_block_mat_asmb_wrap_impl(BlockStructure *ctx, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora, bool is_preconditioner)
Definition Schur.cpp:4009
static void elem_mult_listed(const BlockPattern &p, const double *buf, const double *x, double *y, bool trans)
y += A x (trans false) or y += A^T x (trans true) from listed blocks
Definition Schur.cpp:1780
static PetscErrorCode solve_add(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3497
OpSchurAssembleBase * createOpSchurAssembleEnd(std::vector< std::string > fields_name, std::vector< boost::shared_ptr< Range > > field_ents, SmartPetscObj< AO > ao, SmartPetscObj< Mat > schur, bool sym_schur, bool symm_op)
Construct a new Op Schur Assemble End object.
Definition Schur.cpp:4892
static MoFEMErrorCode mult_block_structure(Mat mat, Vec x, Vec y, InsertMode iora, bool trans)
Matrix-vector product of block matrix.
Definition Schur.cpp:3191
static bool verify_probe(const BlockPattern &nl, const std::vector< double > &mat, double u, double rcond_min, double be_tol, double &be_block, double &be_dense)
Verify block layout on probe element.
Definition Schur.cpp:2136
auto isAllGather(IS is)
IS All gather.
static void apply_lu_factors(int n, const double *lu, const __CLPK_integer *ipiv, double *t, bool trans)
Apply in place LU factors of element matrix.
Definition Schur.cpp:1361
MoFEMErrorCode schurSwitchPreconditioner(boost::shared_ptr< BlockStructure > block_mat_data)
Switch preconditioner.
Definition Schur.cpp:5081
static void for_each_block(const BlockStructure &ctx, FUN &&fun)
Iterate all blocks of matrix, including listed blocks of A00 elements.
Definition Schur.cpp:2433
MoFEMErrorCode setSchurA00MatSolvePC(SmartPetscObj< PC > pc)
Set PC for A00 block.
Definition Schur.cpp:4934
constexpr bool debug_schur
Definition Schur.cpp:12
static PetscErrorCode solve_transpose_add(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3503
static int elem_factorise(const BlockPattern &p, double *buf, __CLPK_integer *piv, double u, double rcond_min, std::vector< double > &work, std::vector< __CLPK_integer > &iwork)
Factorise element buffer in place.
Definition Schur.cpp:1807
auto id_from_handle(const EntityHandle h)
static void elem_gather_dense(const BlockPattern &p, const double *buf, double *dense)
dense element matrix (row-major A, size x size) from listed blocks
Definition Schur.cpp:1768
static size_t listed_size(const BlockPattern &p)
doubles in listed blocks of one element
Definition Schur.cpp:1504
std::pair< SmartPetscObj< Mat >, boost::shared_ptr< BlockStructure > > SchurShellMatData
Definition Schur.hpp:140
static std::vector< int > analyse_pattern(const BlockPattern &p, double *w, double u, double rcond_min)
Decide elimination order on probe element.
Definition Schur.cpp:1675
std::pair< SmartPetscObj< Mat >, boost::shared_ptr< NestSchurData > > createSchurNestedMatrix(boost::shared_ptr< NestSchurData > schur_net_data_ptr)
Create a Mat Diag Blocks object.
Definition Schur.cpp:4859
static PetscErrorCode mult_transpose_add(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3490
PetscErrorCode PetscOptionsGetBool(PetscOptions *, const char pre[], const char name[], PetscBool *bval, PetscBool *set)
MoFEMErrorCode shell_block_mat_asmb_wrap(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)
Definition Schur.cpp:4170
static double accepted_backward_error(double be_dense, double be_tol)
backward error accepted for block factors, given dense backward error
Definition Schur.cpp:2114
static void sub_gemm(bool trans_a, int m, int kk, int nrhs, const double *a, int lda, const double *b, int ldb, double *c, int ldc)
C -= op(A) B, op(A) is m x kk, A, B and C are column-major.
Definition Schur.cpp:1432
static MoFEMErrorCode factorise_elems(BlockStorage &storage, BlockStorage::FactorStorage where)
Factorise A00 elements in place.
Definition Schur.cpp:2224
static bool is_zero_matrix(const double *ptr, size_t size)
Definition Schur.cpp:1398
auto createISGeneral(MPI_Comm comm, PetscInt n, const PetscInt idx[], PetscCopyMode mode)
Creates a data structure for an index set containing a list of integers.
SmartPetscObj< Vec > vectorDuplicate(Vec vec)
Create duplicate vector of smart vector.
static std::vector< char > symbolic_elimination(const BlockPattern &p, const std::vector< int > &order)
Blocks of M = A^T present after eliminating nodes in given order.
Definition Schur.cpp:1541
static void copy_block(double *dst, int ld_dst, int ridx, int cidx, const double *src, int ld_src, int nb_rows, int nb_cols)
copy row-major block into row-major matrix at (ridx, cidx)
Definition Schur.cpp:1390
static bool factorise_pivot_block(int n, double *d, int ld, __CLPK_integer *piv, double coupling, double u, double rcond_min, std::vector< double > &work, std::vector< __CLPK_integer > &iwork, double *rcond_out=nullptr, double *anorm_out=nullptr)
Factorise diagonal block in place and test it as block pivot.
Definition Schur.cpp:1457
void dgecon_(char *norm, __CLPK_integer *n, __CLPK_doublereal *a, __CLPK_integer *lda, __CLPK_doublereal *anorm, __CLPK_doublereal *rcond, __CLPK_doublereal *work, __CLPK_integer *iwork, __CLPK_integer *info)
static PetscErrorCode solve(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3494
static MoFEMErrorCode elem_solve(const BlockPattern &p, const double *buf, const __CLPK_integer *piv, double *r, int ldr, int nrhs, bool trans, const std::vector< char > *nz_in)
Solve with factorised element buffer.
Definition Schur.cpp:1877
boost::shared_ptr< std::vector< double > > getBlockMatPrconditionerStorageMat(Mat B)
Get preconditioner blocks storage.
Definition Schur.cpp:4004
static MoFEMErrorCode solve_block_structure(Mat mat, Vec f, Vec x, InsertMode iora, bool trans)
Solve with A00, i.e. x = A00^{-1} f, element by element.
Definition Schur.cpp:3363
static double elem_backward_error(const BlockPattern &p, const double *orig, const double *lu, const __CLPK_integer *piv, std::vector< double > &x, std::vector< double > &r, std::vector< double > &rs)
Normwise backward error of solve with factors of element.
Definition Schur.cpp:2065
static bool backward_error_accepted(double be, double be_dense, double be_tol)
true if backward error is finite and not larger than accepted
Definition Schur.cpp:2121
static std::string describe_nodes(const BlockPattern &p, const std::vector< int > &nodes)
Definition Schur.cpp:2163
static void make_block_layout(BlockPattern &p, const std::vector< int > &order)
Layout for block elimination of nodes in order, followed by dense core of remaining nodes.
Definition Schur.cpp:1570
static PetscErrorCode zero_rows_columns(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
Definition Schur.cpp:3507
static std::vector< int > natural_offsets(const BlockPattern &p)
offsets of nodes in element vector in order of nodes
Definition Schur.cpp:1493
boost::shared_ptr< BlockStructure > createBlockMatStructure(DM dm, SchurFEOpsFEandFields schur_fe_op_vec)
Create block matrix structure.
Definition Schur.cpp:2819
boost::shared_ptr< NestSchurData > createSchurNestedMatrixStruture(std::pair< SmartPetscObj< DM >, SmartPetscObj< DM > > dms, boost::shared_ptr< BlockStructure > block_mat_data_ptr, std::vector< std::string > fields_names, std::vector< boost::shared_ptr< Range > > field_ents, bool add_preconditioner_block)
Create structure of nested matrix [A11 A10; A01 A00].
Definition Schur.cpp:4760
static PetscErrorCode mult_add(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3484
MoFEMErrorCode MatSetValues(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const double *ptr, InsertMode iora)
Assemble PETSc matrix.
static void set_block_orders(BlockStorage &storage)
set orders of blocks by finite element and by column entity
Definition Schur.cpp:2392
static PetscErrorCode mult_transpose(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3487
auto field_bit_from_bit_number(const int bit_number)
get field bit id from bit number
OpSchurAssembleBase * createOpSchurZeroRowsAndCols(boost::shared_ptr< std::vector< unsigned char > > marker_ptr, double diag_val)
Create a Op Schur Zero Rows And Cols object.
Definition Schur.cpp:4904
static PetscErrorCode mat_zero(Mat m)
Definition Schur.cpp:3575
MoFEMErrorCode schurSaveBlockMesh(boost::shared_ptr< BlockStructure > block_mat_data, std::string filename)
Save block matrix as a mesh.
Definition Schur.cpp:5096
auto getInterfacePtr(DM dm)
Get the Interface Ptr object.
Definition DMMoFEM.hpp:1213
MoFEMErrorCode rebuildSchurNestedMatrixStruture(std::pair< SmartPetscObj< DM >, SmartPetscObj< DM > > dms, boost::shared_ptr< NestSchurData > nest_data_ptr)
Rebuild a nested Schur structure after rebuildBlockMatStructure.
Definition Schur.cpp:4799
static PetscErrorCode mult(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3481
static PetscErrorCode solve_transpose(Mat mat, Vec x, Vec y)
Definition Schur.cpp:3500
static double norm1_block(int m, int n, const double *a, int ld)
1-norm of column-major m x n block, infinity if block is not finite
Definition Schur.cpp:1410
static double backward_error_rhs(int i)
right-hand side used to measure backward error
Definition Schur.cpp:2053
static void copy_listed(const BlockPattern &from, const double *src, const BlockPattern &to, double *dst)
copy listed blocks of element buffer from one layout to another
Definition Schur.cpp:1757
static void elem_mult_factors(const BlockPattern &p, const double *buf, const __CLPK_integer *piv, double *v, bool trans)
Product with factorised element buffer, in place.
Definition Schur.cpp:1989
MoFEMErrorCode rebuildBlockMatStructure(DM dm, SchurFEOpsFEandFields schur_fe_op_vec, boost::shared_ptr< BlockStructure > data_ptr)
Rebuild a block matrix structure after its problem changed.
Definition Schur.cpp:2833
static boost::shared_ptr< NestSchurData > nest_block_structure(std::pair< SmartPetscObj< DM >, SmartPetscObj< DM > > dms, boost::shared_ptr< BlockStructure > block_mat_data_ptr, bool add_preconditioner_block, std::array< boost::shared_ptr< BlockStructure >, 4 > data_ptrs)
Lay A00 blocks out in element buffers and make the nested matrices.
Definition Schur.cpp:4218
static void set_parent_blocks(BlockStructure &s)
set blocks of block matrix (parent numbering)
Definition Schur.cpp:2413
static void make_listed_layout(BlockPattern &p)
layout with listed blocks only
Definition Schur.cpp:1514
constexpr double backward_error_factor
factor of dense backward error accepted for block factors
Definition Schur.cpp:2050
std::vector< std::pair< std::string, std::vector< SchurFieldPair > > > SchurFEOpsFEandFields
Definition Schur.hpp:83
static MoFEMErrorCode setSchurBlockMatOps(Mat mat_raw)
Definition Schur.cpp:3590
MoFEMErrorCode shell_block_preconditioner_mat_asmb_wrap(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)
Definition Schur.cpp:4188
auto getProblemPtr(DM dm)
get problem pointer from DM
Definition DMMoFEM.hpp:1224
static void relayout_pattern(BlockStorage &s, int pi, BlockPattern nl)
Relayout element buffers of pattern pi, element by element, in place.
Definition Schur.cpp:2182
static std::vector< int > structural_order(const BlockPattern &p)
elimination order by structure only (minimal fill, diagonal present)
Definition Schur.cpp:1629
SchurShellMatData createBlockMat(DM dm, boost::shared_ptr< BlockStructure > data)
Create a Schur Mat object.
Definition Schur.cpp:3615
MoFEMErrorCode assembleBlockMatSchur(MoFEM::Interface &m_field, Mat B, Mat S, std::vector< std::string > fields_name, std::vector< boost::shared_ptr< Range > > field_ents, SmartPetscObj< AO > ao)
Assemble Schur complement S = A11 - A10 A00^{-1} A01 from block matrix.
Definition Schur.cpp:3650
OpSchurAssembleBase * createOpSchurAssembleBegin()
Definition Schur.cpp:4887
auto ent_form_type_and_id(const EntityType type, const EntityID id)
get entity handle from type and id
boost::shared_ptr< std::vector< double > > getBlockMatStorageMat(Mat B)
Get block values storage.
Definition Schur.cpp:3995
int r
Definition sdf.py:205
constexpr AssemblyType A
double q
FTensor::Index< 'm', 3 > m
const int N
Definition speed_test.cpp:3
DOFs on one entity (node) of A00 element.
Definition Schur.cpp:314
int globParent
global index in block matrix numbering
Definition Schur.cpp:319
int offset
offset in element vector (layout of pattern)
Definition Schur.cpp:317
int locParent
local index in block matrix numbering
Definition Schur.cpp:318
int locBlock
local index in A00 sub-problem numbering
Definition Schur.cpp:320
int globBlock
global index in A00 sub-problem numbering
Definition Schur.cpp:321
int size
DOFs of element.
Definition Schur.cpp:378
bool local
all entities have local index on this process
Definition Schur.cpp:382
int entBegin
first entity in elemEntities
Definition Schur.cpp:379
bool owned
all entities are owned by this process
Definition Schur.cpp:383
int pivShift
shift in pivots
Definition Schur.cpp:381
UId feUId
uid of the finite element
Definition Schur.cpp:386
int entEnd
one past last entity in elemEntities
Definition Schur.cpp:380
int pattern
index of pattern
Definition Schur.cpp:377
bool factorised
factors are stored for this element
Definition Schur.cpp:384
bool dense
factors are in elemDense (pivot test failed)
Definition Schur.cpp:385
std::vector< std::pair< UId, int > > col
Definition Schur.cpp:411
std::vector< std::pair< UId, int > > row
Definition Schur.cpp:411
std::pair< UId, int > key
Definition Schur.cpp:410
block data indexes
Definition Schur.cpp:257
void setRow(int glob, int nb, int loc)
row entity numbering: global and local index of first DOF, DOFs
Definition Schur.cpp:285
Indexes(UId uid_row, UId uid_col, UId uid_fe, int row, int col, int nb_rows, int nb_cols, int loc_row, int loc_col)
Definition Schur.cpp:259
size_t mat_shift
shift in data, or in element buffer if elem >= 0
Definition Schur.cpp:308
void setStorage(size_t shift, int leading_dim, int element)
Definition Schur.cpp:278
size_t getMatShift() const
Definition Schur.cpp:274
int ld
leading dimension of block in storage
Definition Schur.cpp:309
void setCol(int glob, int nb, int loc)
column entity numbering: global and local index of first DOF, DOFs
Definition Schur.cpp:292
int elem
index of A00 element, -1 if none
Definition Schur.cpp:310
Block pattern of A00 element and layout of element buffer.
Definition Schur.cpp:331
long mShift(int a, int b) const
shift of block (a, b) of M = A^T, column-major
Definition Schur.cpp:370
int coreOffset
offset of core DOFs in element vector
Definition Schur.cpp:356
long sShift(int r, int c) const
Definition Schur.cpp:364
int size
DOFs per element.
Definition Schur.cpp:340
std::vector< int > nodeSize
Definition Schur.cpp:343
double beRef
backward error of dense solve on probe
Definition Schur.cpp:360
std::vector< std::string > nodeName
Definition Schur.cpp:344
int coreSize
DOFs in dense core.
Definition Schur.cpp:355
std::vector< char > listed
nbNodes x nbNodes, slot (r, c) is listed
Definition Schur.cpp:345
int nbFallback
elements factorised dense in last factorisation
Definition Schur.cpp:359
int mLd(int a, int b) const
leading dimension of block (a, b) of M = A^T
Definition Schur.cpp:372
@ LISTED
listed blocks only, not analysed
Definition Schur.cpp:334
@ DENSE
dense element matrix (core contains all nodes)
Definition Schur.cpp:336
@ BLOCK
block elimination of order nodes, then dense core
Definition Schur.cpp:335
size_t coreShift
shift of dense core in element buffer
Definition Schur.cpp:354
size_t elemSize
doubles in element buffer
Definition Schur.cpp:357
int sLd(int r, int c) const
Definition Schur.cpp:367
std::vector< int > order
nodes eliminated block by block
Definition Schur.cpp:352
bool isListed(int r, int c) const
Definition Schur.cpp:368
std::vector< long > key
nodes (field, type, DOFs) and listed slots
Definition Schur.cpp:346
std::vector< long > slotShift
nbNodes x nbNodes, -1 if not stored
Definition Schur.cpp:349
double beMax
largest backward error in last factorisation
Definition Schur.cpp:361
std::vector< int > core
nodes of dense core
Definition Schur.cpp:353
std::vector< int > nodeOffset
offset of node DOFs in element vector
Definition Schur.cpp:351
std::vector< int > slotLd
Definition Schur.cpp:350
bool operator()(const UId &a, const Indexes &b) const
Definition Schur.cpp:525
bool operator()(const Indexes &a, const UId &b) const
Definition Schur.cpp:522
Storage of block matrix, shared by block matrix and its nested (Schur) sub-matrices.
Definition Schur.cpp:251
bool hasPreconditioner
preconditioner blocks are enabled
Definition Schur.cpp:448
MoFEMErrorCode modified() const
Call before modification of data, fails if factors are stored in place.
Definition Schur.cpp:469
size_t maxElemBuffer
maximal size of element buffer
Definition Schur.cpp:400
double optRcondMin
-schur_a00_rcond_min
Definition Schur.cpp:453
auto rowRange(const UId &row) const
range of blocks with given row entity uid
Definition Schur.cpp:531
std::vector< std::pair< UId, std::vector< double > > > elemDataCache
Definition Schur.cpp:421
SchurFEOpsFEandFields feOps
Definition Schur.cpp:406
bool isFactorised() const
Definition Schur.cpp:456
std::vector< FeConnectivity > feConnectivity
Surviving elements can acquire different field entities after local flips.
Definition Schur.cpp:415
double * blockPtr(const Indexes &b, bool prec=false)
values of block, preconditioner buffer if prec is true
Definition Schur.cpp:490
std::vector< ElemEntity > elemEntities
Definition Schur.cpp:395
std::vector< int > feOrder
blocks sorted by (fe uid, row uid, col uid)
Definition Schur.cpp:390
std::vector< int > colOrder
blocks sorted by (col uid, row uid)
Definition Schur.cpp:391
std::vector< Elem > elems
Definition Schur.cpp:394
std::vector< std::pair< UId, int > > feList
(element uid, index in feOps) of elements of the last build, sorted
Definition Schur.cpp:408
bool optDense
-schur_a00_dense
Definition Schur.cpp:451
FactorStorage factorStorage
Definition Schur.cpp:446
std::vector< double > data
blocks not in A00, allocated on first use
Definition Schur.cpp:403
std::vector< std::vector< double > > elemPrec
preconditioner buffers
Definition Schur.cpp:397
std::vector< std::vector< double > > elemDense
dense factors (fallback)
Definition Schur.cpp:398
double optBackwardError
-schur_a00_backward_error
Definition Schur.cpp:454
std::vector< std::vector< double > > elemData
A00 element buffers.
Definition Schur.cpp:396
MoFEMErrorCode checkNotFailed() const
Fails if factorisation failed, storage has to be zeroed.
Definition Schur.cpp:459
std::vector< Indexes > blockIndex
blocks sorted by (row uid, col uid)
Definition Schur.cpp:389
double optPivotThreshold
-schur_a00_pivot_threshold
Definition Schur.cpp:452
size_t dataSize
required size of data
Definition Schur.cpp:402
@ FACTOR_FAILED
factorisation failed, data is corrupted
Definition Schur.cpp:444
std::vector< double > dataCache
Definition Schur.cpp:425
int maxElemSize
maximal DOFs of element
Definition Schur.cpp:399
static bool lessRowCol(const Indexes &a, const Indexes &b)
Definition Schur.cpp:496
const Indexes * find(const UId &row, const UId &col) const
find block by row and column entity uid, return nullptr if not found
Definition Schur.cpp:503
Indexes * findMutable(const UId &row, const UId &col)
Definition Schur.cpp:517
std::vector< Pattern > patternCache
Definition Schur.cpp:418
std::vector< Pattern > patterns
Definition Schur.cpp:393
std::vector< __CLPK_integer > pivots
Definition Schur.cpp:404
bool nested
nested Schur structure has been created
Definition Schur.cpp:447
std::vector< std::pair< UId, std::vector< double > > > elemPrecCache
Definition Schur.cpp:422
void ensureAllocated()
Definition Schur.cpp:429
auto colRange(const UId &col) const
range (in colOrder) of blocks with given column entity uid
Definition Schur.cpp:537
block in numbering of this matrix (blocks not stored in element buffers)
Definition Schur.cpp:561
Context of block matrix shell.
Definition Schur.cpp:555
std::vector< Block > blocks
Definition Schur.cpp:573
Numbering
numbering of A00 element matrix entities used by this matrix
Definition Schur.cpp:558
bool multiplyByPreconditioner
Definition Schur.cpp:580
boost::shared_ptr< BlockStorage > storage
Definition Schur.cpp:572
int locIdx(const BlockStorage::ElemEntity &e) const
Definition Schur.cpp:582
SmartPetscObj< Vec > ghostX
Definition Schur.cpp:577
SmartPetscObj< Vec > ghostY
Definition Schur.cpp:578
int globIdx(const BlockStorage::ElemEntity &e) const
Definition Schur.cpp:585
Numbering numbering
Definition Schur.cpp:575
bool hasElems
A00 elements are part of this matrix.
Definition Schur.cpp:574
virtual FieldBitNumber get_field_bit_number(const std::string name) const =0
get field bit number
Deprecated interface functions.
Data on single entity (This is passed as argument to DataOperator::doWork)
const VectorFieldEntities & getFieldEntities() const
Get field entities (const version)
const VectorDofs & getFieldDofs() const
Get DOF data structures (const version)
const VectorInt & getIndices() const
Get global indices of degrees of freedom on entity.
[Storage and set boundary conditions]
Structure for user loop methods on finite elements.
static UId getHiBitNumberUId(const FieldBitNumber bit_number)
static auto getHandleFromUniqueId(const UId uid)
Get the Handle From Unique Id.
static auto getFieldBitNumberFromUniqueId(const UId uid)
Get the Field Bit Number From Unique Id.
UId getLocalUniqueIdCalculate()
Get the Local Unique Id Calculate object.
static UId getLoLocalEntityBitNumber(const char bit_number, const EntityHandle ent)
static UId getHiLocalEntityBitNumber(const char bit_number, const EntityHandle ent)
const FEMethod * getFEMethod() const
Return raw pointer to Finite Element Method object.
Partitioned (Indexed) Finite Element in Problem.
MoFEMErrorCode assembleSchurMat(Mat S, const UId &uid_row, VectorInt &row_ind, const UId &uid_col, VectorInt &col_ind, MatrixDouble &m, InsertMode iora)
Assemble Schur complement.
Definition Schur.cpp:38
Clear Schur complement internal data.
Definition Schur.cpp:61
MoFEMErrorCode doWork(int side, EntityType type, EntitiesFieldData::EntData &data)
Operator for linear form, usually to calculate values on right hand side.
Definition Schur.cpp:796
Assemble Schur complement (Implementation)
Definition Schur.cpp:88
SmartPetscObj< AO > schurAO
Definition Schur.cpp:122
MoFEMErrorCode doWorkImpl(int side, EntityType type, EntitiesFieldData::EntData &data)
Definition Schur.cpp:866
SmartPetscObj< Mat > schurMat
Definition Schur.cpp:123
std::vector< boost::shared_ptr< Range > > fieldEnts
Definition Schur.cpp:121
OpSchurAssembleEndImpl(std::vector< std::string > fields_name, std::vector< boost::shared_ptr< Range > > field_ents, SmartPetscObj< AO > schur_ao, SmartPetscObj< Mat > schur_mat, bool sym_schur, bool symm_op)
Construct a new Op Schur Assemble End object.
Definition Schur.cpp:855
std::vector< std::string > fieldsName
Definition Schur.cpp:120
Assemble Schur complement.
Definition Schur.cpp:139
OpSchurZeroRowsAndCols(boost::shared_ptr< std::vector< unsigned char > > marker_ptr, double diag_val)
Definition Schur.cpp:809
boost::shared_ptr< std::vector< unsigned char > > markerPtr
Definition Schur.cpp:79
MoFEMErrorCode doWork(int side, EntityType type, EntitiesFieldData::EntData &data)
Operator for linear form, usually to calculate values on right hand side.
Definition Schur.cpp:815
Index tags of the numbered DOF containers that also read the index.
keeps basic data about problem
boost::shared_ptr< NumeredEntFiniteElement_multiIndex > numeredFiniteElementsPtr
store finite elements
boost::function< MoFEMErrorCode(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)> MatSetValuesPtr
Definition Schur.hpp:371
Digest of a block structure, for tests.
Definition Schur.hpp:253
static auto invertMat(MatrixDouble &m, MatrixDouble &inv)
Definition Schur.cpp:1311
static auto invertMat(MatrixDouble &m, MatrixDouble &inv)
Definition Schur.cpp:1275
Schur complement data storage.
Definition Schur.cpp:161
static MoFEMErrorCode assembleStorage(const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)
Definition Schur.cpp:620
static boost::ptr_vector< VectorInt > colIndices
Definition Schur.cpp:214
static boost::ptr_vector< MatrixDouble > locMats
Definition Schur.cpp:212
SchurElemMats(const size_t idx, const UId uid_row, const UId uid_col)
Definition Schur.cpp:615
virtual ~SchurElemMats()=default
static size_t maxIndexCounter
Definition Schur.cpp:216
static boost::ptr_vector< VectorInt > rowIndices
Definition Schur.cpp:213
auto & getMat() const
Definition Schur.cpp:170
static MoFEMErrorCode MatSetValues(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const MatrixDouble &mat, InsertMode iora)
Definition Schur.cpp:4986
auto & getColInd() const
Definition Schur.cpp:172
static boost::ptr_vector< SchurElemMats > schurElemMats
Definition Schur.cpp:215
auto & getRowInd() const
Definition Schur.cpp:171
static SchurElemStorage schurL2Storage
Definition Schur.cpp:218
const size_t iDX
Definition Schur.cpp:166
multi_index_container< const SchurElemMats *, indexed_by< ordered_unique< tag< uid_mi_tag >, composite_key< SchurElemMats, member< SchurElemMats, const UId, &SchurElemMats::uidRow >, member< SchurElemMats, const UId, &SchurElemMats::uidCol > > >, ordered_non_unique< tag< col_mi_tag >, member< SchurElemMats, const UId, &SchurElemMats::uidCol > > > > SchurElemStorage
Definition Schur.cpp:210
static PetscLogEvent MOFEM_EVENT_BlockStructureSetValues
Definition Schur.hpp:29
static PetscLogEvent MOFEM_EVENT_BlockStructureMult
Definition Schur.hpp:30
static PetscLogEvent MOFEM_EVENT_zeroRowsAndCols
Definition Schur.hpp:33
static PetscLogEvent MOFEM_EVENT_opSchurAssembleEnd
Definition Schur.hpp:28
static PetscLogEvent MOFEM_EVENT_BlockStructureSolve
Definition Schur.hpp:31
static PetscLogEvent MOFEM_EVENT_schurMatSetValues
Definition Schur.hpp:27
static PetscLogEvent MOFEM_EVENT_AssembleSchurMat
Definition Schur.hpp:32
intrusive_ptr for managing petsc objects
constexpr IntegrationType IT