v0.16.3
Loading...
Searching...
No Matches
MatrixManager.cpp
Go to the documentation of this file.
1/**
2 * \brief Create adjacent matrices using different indices
3 *
4 */
5
6#include <limits>
7#include <unordered_map>
8
9#define MatrixManagerFunctionBegin \
10 MoFEMFunctionBegin; \
11 MOFEM_LOG_CHANNEL("WORLD"); \
12 MOFEM_LOG_CHANNEL("SYNC"); \
13 MOFEM_LOG_FUNCTION(); \
14 MOFEM_LOG_TAG("SYNC", "MatrixManager"); \
15 MOFEM_LOG_TAG("WORLD", "MatrixManager")
16
17namespace MoFEM {
18
19/** \brief Create compressed matrix
20
21 \note Only function class members are allowed in this class. NO VARIABLES.
22
23 \todo It is obsolete implementation, code should be moved to interface
24 MatrixManager.
25
26 \todo While matrix is created is assumed that all entities on element are
27 adjacent to each other, in some cases, this is created denser matrices than it
28 should be. Some kind of filtering can be added.
29
30 \todo Creation of the block matrices
31
32 \todo Some efficiency improvement are possible
33
34
35 */
36/** Column indices of the finite elements met while assembling the rows,
37 * grouped by column field, built once per element from its column view and
38 * the entity DOF cache. A row entity merges the lists of its adjacent
39 * elements with a stamp array instead of walking the views, locking weak
40 * pointers and sorting the concatenation for every row entity.
41 */
43 struct Segment {
44 BitFieldId field; ///< Column field of the indices in [begin, end).
45 int begin, end; ///< Range in indices.
46 };
47 std::vector<int> indices; ///< All elements, concatenated.
48 std::vector<Segment> segments; ///< Per element, one or more segments.
49 std::vector<std::array<int, 2>> elementSegments; ///< Segment range per slot.
50 std::unordered_map<const EntFiniteElement *, int> slot; ///< Element slot.
51};
52
54
56 MPI_Comm comm = PETSC_COMM_WORLD,
57 int verbose = 1)
58 : Core(moab, comm, verbose) {}
59
60 using ProblemsByName = Problem_multiIndex::index<Problem_mi_tag>::type;
61
62 /** \brief Create matrix adjacencies
63
64 TAG is the container index of the numbered DOFs that is iterated and
65 whose index fills the arrays. The rows of this rank are the ones with
66 its part, except for the adjacency matrix of a problem that is not
67 partitioned yet (MATMPIADJ): then they are a PetscLayout range of the
68 global index, which buildProblem assigns in UID order on every rank.
69
70 */
71 template <typename TAG>
73 createMatArrays(ProblemsByName::iterator p_miit, const MatType type,
74 std::vector<PetscInt> &i, std::vector<PetscInt> &j,
75 const bool no_diagonals = true, int verb = QUIET) const;
76
77private:
78 using AdjByEnt = FieldEntityEntFiniteElementAdjacencyMap_multiIndex::index<
80
82 NumeredDofEntity_multiIndex::index<PetscGlobalIdx_mi_tag>::type;
83
84 /** \brief Get element adjacencies
85 */
86 template <typename TAG>
88 ProblemsByName::iterator p_miit,
89 typename boost::multi_index::index<NumeredDofEntity_multiIndex,
90 TAG>::type::iterator mit_row,
91 boost::shared_ptr<FieldEntity> mofem_ent_ptr,
92 std::vector<int> &dofs_col_view, int verb) const;
93
94 /** \brief Add the column indices of one element and return its slot
95 *
96 * Requires the entity column DOF cache set by createMatArrays. Elements
97 * are added the first time a row entity is adjacent to them, so only the
98 * elements that contribute to local rows are listed.
99 */
100 template <typename TAG>
102 ElementColumns &columns, int &slot) const;
103};
104
105template <typename TAG>
107 const EntFiniteElement &fe, ElementColumns &columns, int &slot) const {
109 slot = columns.elementSegments.size();
110 columns.slot[&fe] = slot;
111 const int first_segment = columns.segments.size();
112 bool open = false;
113 for (auto &it : fe.getColFieldEnts()) {
114 if (auto e = it.lock()) {
115 auto cache = e->entityCacheColDofs.lock();
116 if (!cache)
117 SETERRQ(mofemComm, MOFEM_DATA_INCONSISTENCY, "Cache not set");
118 if (!open || columns.segments.back().field != e->getId()) {
119 if (open)
120 columns.segments.back().end = columns.indices.size();
121 columns.segments.push_back(
122 {e->getId(), static_cast<int>(columns.indices.size()), 0});
123 open = true;
124 }
125 for (auto vit = cache->loHi[0]; vit != cache->loHi[1]; ++vit) {
126 const int idx = TAG::get_index(vit);
127 if (PetscLikely(idx >= 0))
128 columns.indices.push_back(idx);
129 }
130 }
131 }
132 if (open)
133 columns.segments.back().end = columns.indices.size();
134 columns.elementSegments.push_back(
135 {first_segment, static_cast<int>(columns.segments.size())});
137}
138
139/**
140 * @deprecated do not use, instead use CreateRowCompressedADJMatrix
141 */
143
144template <typename TAG>
146 ProblemsByName::iterator p_miit,
147 typename boost::multi_index::index<NumeredDofEntity_multiIndex,
148 TAG>::type::iterator mit_row,
149 boost::shared_ptr<FieldEntity> mofem_ent_ptr,
150 std::vector<int> &dofs_col_view, int verb) const {
152
153 BitRefLevel prb_bit = p_miit->getBitRefLevel();
154 BitRefLevel prb_mask = p_miit->getBitRefLevelMask();
155
156 const EmptyFieldBlocks &empty_field_blocks = p_miit->getEmptyFieldBlocks();
157
158 dofs_col_view.clear();
159 for (auto r = entFEAdjacencies.get<Unique_mi_tag>().equal_range(
160 mofem_ent_ptr->getLocalUniqueId());
161 r.first != r.second; ++r.first) {
162
163 if (r.first->byWhat & BYROW) {
164
165 if ((r.first->entFePtr->getId() & p_miit->getBitFEId()).none()) {
166 // if element is not part of problem
167 continue;
168 }
169
170 const BitRefLevel &fe_bit = r.first->entFePtr->getBitRefLevel();
171 // if entity is not problem refinement level
172 if ((fe_bit & prb_bit).any() && (fe_bit & prb_mask) == fe_bit) {
173
174 auto check_block = [&empty_field_blocks](auto &r_if, auto &col_id) {
175 for (auto &b : empty_field_blocks) {
176 if ((b.first & r_if).any() && (b.second & col_id).any()) {
177 return false;
178 }
179 }
180 return true;
181 };
182
183 for (auto &it : r.first->entFePtr->getColFieldEnts()) {
184 if (auto e = it.lock()) {
185
186 if (check_block((*mit_row)->getId(), e->getId())) {
187
188 if (auto cache = e->entityCacheColDofs.lock()) {
189 const auto lo = cache->loHi[0];
190 const auto hi = cache->loHi[1];
191 for (auto vit = lo; vit != hi; ++vit) {
192
193 const int idx = TAG::get_index(vit);
194 if (PetscLikely(idx >= 0))
195 dofs_col_view.push_back(idx);
196
197#ifndef NDEBUG
198 const DofIdx nb_dofs_col = p_miit->getNbDofsCol();
199 if (PetscUnlikely(idx >= nb_dofs_col)) {
200 MOFEM_LOG("SELF", Sev::error)
201 << "Problem with dof: " << std::endl
202 << "Rank " << rAnk << " : " << *(*vit);
203 SETERRQ(
204 mofemComm, PETSC_ERR_ARG_SIZ,
205 "Index of dof larger than number of DOFs in column");
206 }
207#endif
208 }
209
210 } else {
211 SETERRQ(mofemComm, MOFEM_DATA_INCONSISTENCY, "Cache not set");
212 }
213 }
214 }
215 }
216 }
217 }
218 }
219
221}
222
223template <typename TAG>
225 ProblemsByName::iterator p_miit, const MatType type,
226 std::vector<PetscInt> &i, std::vector<PetscInt> &j, const bool no_diagonals,
227 int verb) const {
229
230 PetscLogEventBegin(MOFEM_EVENT_createMat, 0, 0, 0, 0);
231
232 auto cache = boost::make_shared<std::vector<EntityCacheNumeredDofs>>(
233 entsFields.size());
234
235 size_t idx = 0;
236 for (auto it = entsFields.begin(); it != entsFields.end(); ++it, ++idx) {
237
238 const auto uid = (*it)->getLocalUniqueId();
239 auto r = entFEAdjacencies.get<Unique_mi_tag>().equal_range(uid);
240 for (auto lo = r.first; lo != r.second; ++lo) {
241
242 if ((lo->getBitFEId() & p_miit->getBitFEId()).any()) {
243
244 const BitRefLevel &prb_bit = p_miit->getBitRefLevel();
245 const BitRefLevel &prb_mask = p_miit->getBitRefLevelMask();
246 const BitRefLevel &fe_bit = lo->entFePtr->getBitRefLevel();
247
248 // if entity is not problem refinement level
249 if ((fe_bit & prb_mask) != fe_bit)
250 continue;
251 if ((fe_bit & prb_bit).none())
252 continue;
253
254 auto dit = p_miit->numeredColDofsPtr->lower_bound(uid);
255
256 decltype(dit) hi_dit;
257 if (dit != p_miit->numeredColDofsPtr->end())
258 hi_dit = p_miit->numeredColDofsPtr->upper_bound(
259 uid | static_cast<UId>(MAX_DOFS_ON_ENTITY - 1));
260 else
261 hi_dit = dit;
262
263 (*it)->entityCacheColDofs =
264 boost::shared_ptr<EntityCacheNumeredDofs>(cache, &((*cache)[idx]));
265 (*cache)[idx].loHi = {dit, hi_dit};
266
267 break;
268 }
269 }
270 }
271
272 using NumeredDofEntitysByIdx =
273 typename boost::multi_index::index<NumeredDofEntity_multiIndex,
274 TAG>::type;
275
276 // Get multi-indices for rows and columns
277 const NumeredDofEntitysByIdx &dofs_row_by_idx =
278 p_miit->numeredRowDofsPtr->get<TAG>();
279 int nb_dofs_row = p_miit->getNbDofsRow();
280 if (nb_dofs_row == 0) {
281 SETERRQ(mofemComm, MOFEM_DATA_INCONSISTENCY, "problem <%s> has zero rows",
282 p_miit->getName().c_str());
283 }
284
285 // Get adjacencies form other processors
286 std::map<int, std::vector<int>> adjacent_dofs_on_other_parts;
287
288 // The adjacency matrix for partitioning is made before any part is set:
289 // its rows are a PetscLayout range of the global index. Otherwise the rows
290 // of this rank are the ones with its part, and the adjacencies of shared
291 // rows owned elsewhere are collected from the other parts. If only the
292 // algebra is partitioned there is nothing to collect: the mesh is assumed
293 // to be the same on every processor.
294 const bool rows_by_layout = strcmp(type, MATMPIADJ) == 0;
295 typename NumeredDofEntitysByIdx::iterator miit_row, hi_miit_row;
296
297 if (rows_by_layout) {
298
299 // Get range of local indices
300 PetscLayout layout;
301 CHKERR PetscLayoutCreate(mofemComm, &layout);
302 CHKERR PetscLayoutSetBlockSize(layout, 1);
303 CHKERR PetscLayoutSetSize(layout, nb_dofs_row);
304 CHKERR PetscLayoutSetUp(layout);
305 PetscInt rstart, rend;
306 CHKERR PetscLayoutGetRange(layout, &rstart, &rend);
307 CHKERR PetscLayoutDestroy(&layout);
308
309 if (verb >= VERBOSE) {
310 MOFEM_LOG("SYNC", Sev::noisy)
311 << "row lower " << rstart << " row upper " << rend;
313 }
314
315 miit_row = dofs_row_by_idx.lower_bound(rstart);
316 hi_miit_row = dofs_row_by_idx.lower_bound(rend);
317 if (std::distance(miit_row, hi_miit_row) != rend - rstart) {
318 SETERRQ(
319 mofemComm, PETSC_ERR_ARG_SIZ,
320 "data inconsistency, std::distance(miit_row,hi_miit_row) != rend - "
321 "rstart (%ld != %d - %d = %d) ",
322 std::distance(miit_row, hi_miit_row), rend, rstart, rend - rstart);
323 }
324
325 } else {
326
327 MPI_Comm comm;
328 // // Make sure it is a PETSc mofemComm
329 CHKERR PetscCommDuplicate(get_comm(), &comm, NULL);
330
331 // get adjacent nodes on other partitions
332 std::vector<std::vector<int>> dofs_vec(sIze);
333
334 boost::shared_ptr<FieldEntity> mofem_ent_ptr;
335 std::vector<int> dofs_col_view;
336
337 typename NumeredDofEntitysByIdx::iterator mit_row, hi_mit_row;
338
339 mit_row = dofs_row_by_idx.begin();
340 hi_mit_row = dofs_row_by_idx.end();
341 for (; mit_row != hi_mit_row; mit_row++) {
342
343 // Shared or multi-shared row and not owned. Those data should be send to
344 // other side.
345
346 // Get entity adjacencies, no need to repeat that operation for dofs when
347 // are on the same entity. For simplicity is assumed that those sheered
348 // the same adjacencies.
349 unsigned char pstatus = (*mit_row)->getPStatus();
350 if ((pstatus & PSTATUS_NOT_OWNED) &&
351 (pstatus & (PSTATUS_SHARED | PSTATUS_MULTISHARED))) {
352
353 bool get_adj_col = true;
354 if (mofem_ent_ptr) {
355 if (mofem_ent_ptr->getLocalUniqueId() ==
356 (*mit_row)->getFieldEntityPtr()->getLocalUniqueId()) {
357 get_adj_col = false;
358 }
359 }
360
361 if (get_adj_col) {
362 // Get entity adjacencies
363 mofem_ent_ptr = (*mit_row)->getFieldEntityPtr();
364 CHKERR getEntityAdjacencies<TAG>(p_miit, mit_row, mofem_ent_ptr,
365 dofs_col_view, verb);
366 // Sort, unique and resize dofs_col_view
367 {
368 std::sort(dofs_col_view.begin(), dofs_col_view.end());
369 std::vector<int>::iterator new_end =
370 std::unique(dofs_col_view.begin(), dofs_col_view.end());
371 int new_size = std::distance(dofs_col_view.begin(), new_end);
372 dofs_col_view.resize(new_size);
373 }
374 // Add that row. Patterns is that first index is row index, second is
375 // size of adjacencies after that follows column adjacencies.
376 int owner = (*mit_row)->getOwnerProc();
377 dofs_vec[owner].emplace_back(TAG::get_index(mit_row)); // row index
378 dofs_vec[owner].emplace_back(
379 dofs_col_view.size()); // nb. of column adjacencies
380 // add adjacent cools
381 dofs_vec[owner].insert(dofs_vec[owner].end(), dofs_col_view.begin(),
382 dofs_col_view.end());
383 }
384 }
385 }
386
387 int nsends = 0; // number of messages to send
388 std::vector<int> dofs_vec_length(sIze); // length of the message to proc
389 for (int proc = 0; proc < sIze; proc++) {
390
391 if (!dofs_vec[proc].empty()) {
392
393 dofs_vec_length[proc] = dofs_vec[proc].size();
394 nsends++;
395
396 } else {
397
398 dofs_vec_length[proc] = 0;
399 }
400 }
401
402 std::vector<MPI_Status> status(sIze);
403
404 // Computes the number of messages a node expects to receive
405 int nrecvs; // number of messages received
406 CHKERR PetscGatherNumberOfMessages(comm, NULL, &dofs_vec_length[0],
407 &nrecvs);
408
409 // Computes info about messages that a MPI-node will receive, including
410 // (from-id,length) pairs for each message.
411 int *onodes; // list of node-ids from which messages are expected
412 int *olengths; // corresponding message lengths
413 CHKERR PetscGatherMessageLengths(comm, nsends, nrecvs, &dofs_vec_length[0],
414 &onodes, &olengths);
415
416 // Gets a unique new tag from a PETSc communicator.
417 int tag;
418 CHKERR PetscCommGetNewTag(comm, &tag);
419
420 // Allocate a buffer sufficient to hold messages of size specified in
421 // olengths. And post Irecvs on these buffers using node info from onodes
422 int **rbuf; // must bee freed by user
423 MPI_Request *r_waits; // must bee freed by user
424
425 // rbuf has a pointers to messages. It has size of of nrecvs (number of
426 // messages) +1. In the first index a block is allocated,
427 // such that rbuf[i] = rbuf[i-1]+olengths[i-1].
428 CHKERR PetscPostIrecvInt(comm, tag, nrecvs, onodes, olengths, &rbuf,
429 &r_waits);
430
431 MPI_Request *s_waits; // status of sens messages
432 CHKERR PetscMalloc1(nsends, &s_waits);
433
434 // Send messages
435 for (int proc = 0, kk = 0; proc < sIze; proc++) {
436 if (!dofs_vec_length[proc])
437 continue; // no message to send to this proc
438 CHKERR MPI_Isend(&(dofs_vec[proc])[0], // buffer to send
439 dofs_vec_length[proc], // message length
440 MPIU_INT, proc, // to proc
441 tag, comm, s_waits + kk);
442 kk++;
443 }
444
445 // Wait for received
446 if (nrecvs) {
447 CHKERR MPI_Waitall(nrecvs, r_waits, &status[0]);
448 }
449 // Wait for send messages
450 if (nsends) {
451 CHKERR MPI_Waitall(nsends, s_waits, &status[0]);
452 }
453
454 for (int kk = 0; kk < nrecvs; kk++) {
455
456 int len = olengths[kk];
457 int *data_from_proc = rbuf[kk];
458
459 for (int ii = 0; ii < len;) {
460
461 int row_idx = data_from_proc[ii++]; // get row number
462 int nb_adj_dofs = data_from_proc[ii++]; // get nb. of adjacent dofs
463
464 if (debug) {
465
466 DofByGlobalPetscIndex::iterator dit;
467 dit = p_miit->numeredRowDofsPtr->get<PetscGlobalIdx_mi_tag>().find(
468 row_idx);
469 if (dit ==
470 p_miit->numeredRowDofsPtr->get<PetscGlobalIdx_mi_tag>().end()) {
472 "dof %d can not be found in problem", row_idx);
473 }
474 }
475
476 for (int jj = 0; jj < nb_adj_dofs; jj++) {
477 adjacent_dofs_on_other_parts[row_idx].push_back(data_from_proc[ii++]);
478 }
479 }
480 }
481
482 // Cleaning
483 CHKERR PetscFree(s_waits);
484 CHKERR PetscFree(rbuf[0]);
485 CHKERR PetscFree(rbuf);
486 CHKERR PetscFree(r_waits);
487 CHKERR PetscFree(onodes);
488 CHKERR PetscFree(olengths);
489
490 miit_row = dofs_row_by_idx.begin();
491 hi_miit_row = dofs_row_by_idx.end();
492
493 CHKERR PetscCommDestroy(&comm);
494 }
495
496 boost::shared_ptr<FieldEntity> mofem_ent_ptr;
497 int row_last_evaluated_idx = -1;
498
499 std::vector<int> dofs_vec;
500
501 // Column lists per element, built on first use and merged per row entity
502 // through a stamp array: an index enters the row once, without sorting
503 // the concatenation of all adjacent elements' DOFs.
504 ElementColumns columns;
505 columns.slot.reserve(p_miit->numeredFiniteElementsPtr->size());
506 std::vector<int> stamp(p_miit->getNbDofsCol(), -1);
507 int stamp_id = -1;
508 const auto &empty_field_blocks = p_miit->getEmptyFieldBlocks();
509 auto check_block = [&empty_field_blocks](const BitFieldId &row_field,
510 const BitFieldId &col_field) {
511 for (auto &b : empty_field_blocks)
512 if ((b.first & row_field).any() && (b.second & col_field).any())
513 return false;
514 return true;
515 };
516 const BitRefLevel prb_bit = p_miit->getBitRefLevel();
517 const BitRefLevel prb_mask = p_miit->getBitRefLevelMask();
518 auto push_once = [&](const int idx) {
520 if (PetscUnlikely(idx >= static_cast<int>(stamp.size())))
521 SETERRQ(mofemComm, PETSC_ERR_ARG_SIZ,
522 "Index of dof larger than number of DOFs in column");
523 if (stamp[idx] != stamp_id) {
524 stamp[idx] = stamp_id;
525 dofs_vec.push_back(idx);
526 }
528 };
529
530 // loop local rows
531 int nb_loc_row_from_iterators = 0;
532 unsigned int rows_to_fill = p_miit->getNbLocalDofsRow();
533 // Stage one sorted list per run of rows on a field entity. This is much
534 // smaller than the final CSR at high order, where many rows share a list.
535 struct RowPattern {
536 std::size_t begin, end;
537 int firstRow, lastRow;
538 };
539 std::vector<RowPattern> row_patterns;
540 row_patterns.reserve(std::min<std::size_t>(rows_to_fill, entsFields.size()));
541 std::vector<PetscInt> pattern_columns;
542 std::vector<PetscInt> row_diagonals;
543 if (no_diagonals)
544 row_diagonals.reserve(rows_to_fill);
545 std::size_t nb_nonzeros = j.size();
546 i.reserve(rows_to_fill + 1);
547 for (; miit_row != hi_miit_row; miit_row++) {
548
549 if (!rows_by_layout) {
550 if (static_cast<int>((*miit_row)->getPart()) != rAnk)
551 continue;
552 }
553 // This is only for cross-check if everything is ok
554 nb_loc_row_from_iterators++;
555
556 // add next row to compressed matrix
557 i.push_back(static_cast<PetscInt>(nb_nonzeros));
558
559 // Get entity adjacencies, no need to repeat that operation for dofs when
560 // are on the same entity. For simplicity is assumed that those share the
561 // same adjacencies.
562 if ((!mofem_ent_ptr)
563 ? 1
564 : (mofem_ent_ptr->getLocalUniqueId() !=
565 (*miit_row)->getFieldEntityPtr()->getLocalUniqueId())) {
566
567 // get entity adjacencies
568 mofem_ent_ptr = (*miit_row)->getFieldEntityPtr();
569 row_last_evaluated_idx = TAG::get_index(miit_row);
570 const BitFieldId row_field = (*miit_row)->getId();
571
572 dofs_vec.resize(0);
573 ++stamp_id;
574 for (auto r = entFEAdjacencies.get<Unique_mi_tag>().equal_range(
575 mofem_ent_ptr->getLocalUniqueId());
576 r.first != r.second; ++r.first) {
577 if (!(r.first->byWhat & BYROW))
578 continue;
579 const auto &fe_ptr = r.first->entFePtr;
580 if ((fe_ptr->getId() & p_miit->getBitFEId()).none())
581 continue;
582 const BitRefLevel &fe_bit = fe_ptr->getBitRefLevel();
583 if (!((fe_bit & prb_bit).any() && (fe_bit & prb_mask) == fe_bit))
584 continue;
585 int slot;
586 auto slot_it = columns.slot.find(fe_ptr.get());
587 if (slot_it != columns.slot.end())
588 slot = slot_it->second;
589 else
590 CHKERR addElementColumns<TAG>(*fe_ptr, columns, slot);
591 const auto segment_range = columns.elementSegments[slot];
592 for (int s = segment_range[0]; s != segment_range[1]; ++s) {
593 const auto &segment = columns.segments[s];
594 if (!check_block(row_field, segment.field))
595 continue;
596 for (int k = segment.begin; k != segment.end; ++k)
597 CHKERR push_once(columns.indices[k]);
598 }
599 }
600
601 unsigned char pstatus = (*miit_row)->getPStatus();
602 if (pstatus > 0) {
603 std::map<int, std::vector<int>>::iterator mit;
604 mit = adjacent_dofs_on_other_parts.find(row_last_evaluated_idx);
605 if (mit == adjacent_dofs_on_other_parts.end()) {
606 // NOTE: Dof can adjacent to other part but no elements are there
607 // which use that dof std::cerr << *miit_row << std::endl; SETERRQ(
608 // get_comm(),MOFEM_DATA_INCONSISTENCY,
609 // "data inconsistency row_last_evaluated_idx = %d",
610 // row_last_evaluated_idx
611 // );
612 } else {
613 for (auto idx : mit->second)
614 CHKERR push_once(idx);
615 }
616 }
617
618 // The unique list is sorted so that PETSc inserts rows in order.
619 std::sort(dofs_vec.begin(), dofs_vec.end());
620 const auto begin = pattern_columns.size();
621 pattern_columns.insert(pattern_columns.end(), dofs_vec.begin(),
622 dofs_vec.end());
623 row_patterns.push_back({begin, pattern_columns.size(),
624 nb_loc_row_from_iterators - 1,
625 nb_loc_row_from_iterators});
626 }
627
628 row_patterns.back().lastRow = nb_loc_row_from_iterators;
629 auto row_size = dofs_vec.size();
630 if (no_diagonals) {
631 const auto diagonal = TAG::get_index(miit_row);
632 row_diagonals.push_back(diagonal);
633 if (std::binary_search(dofs_vec.begin(), dofs_vec.end(), diagonal))
634 --row_size;
635 }
636 if (row_size > std::numeric_limits<PetscInt>::max() - nb_nonzeros)
637 SETERRQ(mofemComm, PETSC_ERR_ARG_SIZ,
638 "CSR column offsets exceed the PetscInt range");
639 nb_nonzeros += row_size;
640 }
641
642 i.push_back(static_cast<PetscInt>(nb_nonzeros));
643 // The exact row counts are known: reserve once and bulk-copy each list,
644 // splitting it only when the graph-partitioning path excludes a diagonal.
645 j.reserve(nb_nonzeros);
646 for (const auto &pattern : row_patterns) {
647 const auto begin = pattern_columns.begin() + pattern.begin;
648 const auto end = pattern_columns.begin() + pattern.end;
649 for (int row = pattern.firstRow; row != pattern.lastRow; ++row) {
650 if (!no_diagonals || i[row + 1] - i[row] == pattern.end - pattern.begin)
651 j.insert(j.end(), begin, end);
652 else {
653 const auto diagonal = std::lower_bound(begin, end, row_diagonals[row]);
654 j.insert(j.end(), begin, diagonal);
655 j.insert(j.end(), std::next(diagonal), end);
656 }
657 }
658 }
659
660 if (strcmp(type, MATMPIADJ) == 0) {
661
662 // Adjacency matrix used to partition problems, f.e. METIS
663 if (i.size() - 1 != (unsigned int)nb_loc_row_from_iterators) {
664 SETERRQ(
665 get_comm(), PETSC_ERR_ARG_SIZ,
666 "Number of rows from iterator is different than size of rows in "
667 "compressed row "
668 "matrix (unsigned int)nb_local_dofs_row != i.size() - 1, i.e. %u != "
669 "%zu",
670 (unsigned int)nb_loc_row_from_iterators, i.size() - 1);
671 }
672
673 } else if (strcmp(type, MATMPIAIJ) == 0) {
674
675 // Compressed MPIADJ matrix
676 if (i.size() - 1 != (unsigned int)nb_loc_row_from_iterators) {
677 SETERRQ(
678 get_comm(), PETSC_ERR_ARG_SIZ,
679 "Number of rows from iterator is different than size of rows in "
680 "compressed row "
681 "matrix (unsigned int)nb_local_dofs_row != i.size() - 1, i.e. %u != "
682 "%zu",
683 (unsigned int)nb_loc_row_from_iterators, i.size() - 1);
684 }
685 PetscInt nb_local_dofs_row = p_miit->getNbLocalDofsRow();
686 if ((unsigned int)nb_local_dofs_row != i.size() - 1) {
687 SETERRQ(
688 get_comm(), PETSC_ERR_ARG_SIZ,
689 "Number of rows is different than size of rows in compressed row "
690 "matrix (unsigned int)nb_local_dofs_row != i.size() - 1, i.e. %u != "
691 "%zu",
692 (unsigned int)nb_local_dofs_row, i.size() - 1);
693 }
694
695 } else if (strcmp(type, MATAIJ) == 0) {
696
697 // Sequential compressed ADJ matrix
698 if (i.size() - 1 != (unsigned int)nb_loc_row_from_iterators) {
699 SETERRQ(
700 get_comm(), PETSC_ERR_ARG_SIZ,
701 "Number of rows form iterator is different than size of rows in "
702 "compressed row "
703 "matrix (unsigned int)nb_local_dofs_row != i.size() - 1, i.e. %u != "
704 "%zu",
705 (unsigned int)nb_loc_row_from_iterators, i.size() - 1);
706 }
707 PetscInt nb_local_dofs_row = p_miit->getNbLocalDofsRow();
708 if ((unsigned int)nb_local_dofs_row != i.size() - 1) {
709 SETERRQ(
710 get_comm(), PETSC_ERR_ARG_SIZ,
711 "Number of rows is different than size of rows in compressed row "
712 "matrix (unsigned int)nb_local_dofs_row != i.size() - 1, i.e. %u != "
713 "%zu",
714 (unsigned int)nb_local_dofs_row, i.size() - 1);
715 }
716
717 } else if (strcmp(type, MATAIJCUSPARSE) == 0) {
718
719 if (i.size() - 1 != (unsigned int)nb_loc_row_from_iterators) {
720 SETERRQ(get_comm(), PETSC_ERR_ARG_SIZ, "data inconsistency");
721 }
722 PetscInt nb_local_dofs_row = p_miit->getNbLocalDofsRow();
723 if ((unsigned int)nb_local_dofs_row != i.size() - 1) {
724 SETERRQ(get_comm(), PETSC_ERR_ARG_SIZ, "data inconsistency");
725 }
726
727 } else {
728
729 SETERRQ(get_comm(), PETSC_ERR_ARG_NULL, "not implemented");
730 }
731
732 PetscLogEventEnd(MOFEM_EVENT_createMat, 0, 0, 0, 0);
734}
735
737MatrixManager::query_interface(boost::typeindex::type_index type_index,
738 UnknownInterface **iface) const {
739 *iface = const_cast<MatrixManager *>(this);
740 return 0;
741}
742
744 : cOre(const_cast<MoFEM::Core &>(core)) {
745 PetscLogEventRegister("MatMngCrtMPIAIJ", 0, &MOFEM_EVENT_createMPIAIJ);
746 PetscLogEventRegister("MatMngCrtMPIAIJWthArr", 0,
748 PetscLogEventRegister("MatMngCrtMPIAdjWithArr", 0,
750 PetscLogEventRegister("MatMngCrtMPIAIJCUSPARSEWthArr", 0,
752 PetscLogEventRegister("MatMngCrtSeqAIJCUSPARSEWthArrs", 0,
754 PetscLogEventRegister("MatMngCrtSeqAIJWthArrs", 0,
756 PetscLogEventRegister("MatMngCrtCheckMPIAIJWthArrFillIn", 0,
758}
759
760template <>
762 const std::string name, Mat *Aij, int verb) {
764
767 static_cast<CreateRowCompressedADJMatrix *>(&cOre);
769
770 auto problems_ptr = m_field.get_problems();
771 auto &prb = problems_ptr->get<Problem_mi_tag>();
772 auto p_miit = prb.find(name);
773 if (p_miit == prb.end()) {
774 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
775 "problem < %s > is not found (top tip: check spelling)",
776 name.c_str());
777 }
778
779 std::vector<int> i_vec, j_vec;
780 j_vec.reserve(10000);
781 CHKERR core_ptr->createMatArrays<PetscGlobalIdx_mi_tag>(
782 p_miit, MATMPIAIJ, i_vec, j_vec, false, verb);
783
784 int nb_row_dofs = p_miit->getNbDofsRow();
785 int nb_col_dofs = p_miit->getNbDofsCol();
786 int nb_local_dofs_row = p_miit->getNbLocalDofsRow();
787 int nb_local_dofs_col = p_miit->getNbLocalDofsCol();
788
789 CHKERR ::MatCreateMPIAIJWithArrays(
790 m_field.get_comm(), nb_local_dofs_row, nb_local_dofs_col, nb_row_dofs,
791 nb_col_dofs, &*i_vec.begin(), &*j_vec.begin(), PETSC_NULLPTR, Aij);
792
795}
796
797template <>
800 const std::string name, Mat *Aij, int verb) {
802
805 static_cast<CreateRowCompressedADJMatrix *>(&cOre);
807
808 auto problems_ptr = m_field.get_problems();
809 auto &prb = problems_ptr->get<Problem_mi_tag>();
810 auto p_miit = prb.find(name);
811 if (p_miit == prb.end()) {
812 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
813 "problem < %s > is not found (top tip: check spelling)",
814 name.c_str());
815 }
816
817 std::vector<int> i_vec, j_vec;
818 j_vec.reserve(10000);
819 CHKERR core_ptr->createMatArrays<PetscGlobalIdx_mi_tag>(
820 p_miit, MATAIJCUSPARSE, i_vec, j_vec, false, verb);
821
822 int nb_local_dofs_row = p_miit->getNbLocalDofsRow();
823 int nb_local_dofs_col = p_miit->getNbLocalDofsCol();
824
825 auto get_layout = [&]() {
834 return std::make_pair(start_ranges, end_ranges);
835 };
836
837 auto get_nnz = [&](auto &d_nnz, auto &o_nnz) {
839 auto layout = get_layout();
840 int j = 0;
841 for (int i = 0; i != nb_local_dofs_row; ++i) {
842 for (; j != i_vec[i + 1]; ++j) {
843 if (j_vec[j] < layout.second && j_vec[j] >= layout.first)
844 ++(d_nnz[i]);
845 else
846 ++(o_nnz[i]);
847 }
848 }
850 };
851
852 std::vector<int> d_nnz(nb_local_dofs_row, 0), o_nnz(nb_local_dofs_row, 0);
854
855#ifdef PETSC_HAVE_CUDA
856 CHKERR ::MatCreateAIJCUSPARSE(m_field.get_comm(), nb_local_dofs_row,
857 nb_local_dofs_col, nb_row_dofs, nb_col_dofs, 0,
858 &*d_nnz.begin(), 0, &*o_nnz.begin(), Aij);
859#else
861 "Error: To use this matrix type compile PETSc with CUDA.");
862#endif
863
865
867}
868
869template <>
872 const std::string name, Mat *Aij, int verb) {
874
875#ifdef PETSC_HAVE_CUDA
876 // CHKERR ::MatCreateSeqAIJCUSPARSE(MPI_Comm comm, PetscInt m, PetscInt n,
877 // PetscInt nz, const PetscInt nnz[], Mat
878 // *A);
880 "Not implemented type of matrix yet, try MPI version (aijcusparse)");
881#endif
882
884}
885
886template <>
889 Mat *Aij, int verb) {
892 static_cast<CreateRowCompressedADJMatrix *>(&cOre);
895
896 auto problems_ptr = m_field.get_problems();
897 auto &prb = problems_ptr->get<Problem_mi_tag>();
898 auto p_miit = prb.find(name);
899 if (p_miit == prb.end()) {
900 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
901 "problem < %s > is not found (top tip: check spelling)",
902 name.c_str());
903 }
904
905 std::vector<int> i_vec, j_vec;
906 j_vec.reserve(10000);
907 CHKERR core_ptr->createMatArrays<PetscGlobalIdx_mi_tag>(
908 p_miit, MATMPIAIJ, i_vec, j_vec, false, verb);
909
910 int nb_row_dofs = p_miit->getNbDofsRow();
911 int nb_col_dofs = p_miit->getNbDofsCol();
912 int nb_local_dofs_row = p_miit->getNbLocalDofsRow();
913 int nb_local_dofs_col = p_miit->getNbLocalDofsCol();
914
915 auto get_layout = [&]() {
924 return std::make_pair(start_ranges, end_ranges);
925 };
926
927 auto get_nnz = [&](auto &d_nnz, auto &o_nnz) {
929 auto layout = get_layout();
930 int j = 0;
931 for (int i = 0; i != nb_local_dofs_row; ++i) {
932 for (; j != i_vec[i + 1]; ++j) {
933 if (j_vec[j] < layout.second && j_vec[j] >= layout.first)
934 ++(d_nnz[i]);
935 else
936 ++(o_nnz[i]);
937 }
938 }
940 };
941
942 std::vector<int> d_nnz(nb_local_dofs_row, 0), o_nnz(nb_local_dofs_row, 0);
944
945 CHKERR MatCreate(m_field.get_comm(), Aij);
949 CHKERR MatMPIAIJSetPreallocation(*Aij, 0, &*d_nnz.begin(), 0,
950 &*o_nnz.begin());
951
954}
955
956template <>
959 const std::string name, Mat *Adj, int verb) {
962 static_cast<CreateRowCompressedADJMatrix *>(&cOre);
965
966 auto problems_ptr = m_field.get_problems();
967 auto &prb = problems_ptr->get<Problem_mi_tag>();
968 auto p_miit = prb.find(name);
969 if (p_miit == prb.end()) {
970 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
971 "problem < %s > is not found (top tip: check spelling)",
972 name.c_str());
973 }
974
975 std::vector<int> i_vec, j_vec;
976 j_vec.reserve(10000);
977 CHKERR core_ptr->createMatArrays<PetscGlobalIdx_mi_tag>(
978 p_miit, MATMPIADJ, i_vec, j_vec, true, verb);
979 int *_i, *_j;
980 CHKERR PetscMalloc(i_vec.size() * sizeof(int), &_i);
981 CHKERR PetscMalloc(j_vec.size() * sizeof(int), &_j);
982 copy(i_vec.begin(), i_vec.end(), _i);
983 copy(j_vec.begin(), j_vec.end(), _j);
984
985 int nb_col_dofs = p_miit->getNbDofsCol();
986 CHKERR MatCreateMPIAdj(m_field.get_comm(), i_vec.size() - 1, nb_col_dofs, _i,
989
992}
993
994template <>
996 const std::string name, Mat *Aij, int verb) {
999 static_cast<CreateRowCompressedADJMatrix *>(&cOre);
1002
1003 auto problems_ptr = m_field.get_problems();
1004 auto &prb = problems_ptr->get<Problem_mi_tag>();
1005 auto p_miit = prb.find(name);
1006 if (p_miit == prb.end()) {
1007 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
1008 "problem < %s > is not found (top tip: check spelling)",
1009 name.c_str());
1010 }
1011
1012 std::vector<int> i_vec, j_vec;
1013 j_vec.reserve(10000);
1015 j_vec, false, verb);
1016
1017 int nb_local_dofs_row = p_miit->getNbLocalDofsRow();
1018 int nb_local_dofs_col = p_miit->getNbLocalDofsCol();
1019
1020 double *_a;
1021 CHKERR PetscMalloc(j_vec.size() * sizeof(double), &_a);
1022
1023 Mat tmpMat;
1024 CHKERR ::MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, nb_local_dofs_row,
1025 nb_local_dofs_col, &*i_vec.begin(),
1026 &*j_vec.begin(), _a, &tmpMat);
1029
1031
1034}
1035
1037 int row_print, int col_print,
1038 Mat A, int verb) {
1041
1043
1044 struct TestMatrixFillIn : public FEMethod {
1045 CoreInterface *mFieldPtr;
1046
1047 Mat A;
1048
1049 int rowPrint, colPrint;
1050
1051 TestMatrixFillIn(CoreInterface *m_field_ptr, Mat a, int row_print,
1052 int col_print)
1053 : mFieldPtr(m_field_ptr), A(a), rowPrint(row_print),
1055
1056 MoFEMErrorCode preProcess() {
1059 }
1060
1061 MoFEMErrorCode operator()() {
1063
1064 if (refinedFiniteElementsPtr->find(
1065 numeredEntFiniteElementPtr->getEnt()) ==
1066 refinedFiniteElementsPtr->end()) {
1068 "data inconsistency");
1069 }
1070
1071 auto row_dofs = getRowDofsPtr();
1072 auto col_dofs = getColDofsPtr();
1073
1074 for (auto cit = col_dofs->begin(); cit != col_dofs->end(); cit++) {
1075
1076 if (refinedEntitiesPtr->find((*cit)->getEnt()) ==
1077 refinedEntitiesPtr->end()) {
1079 "data inconsistency");
1080 }
1081 if (!(*cit)->getActive()) {
1083 "data inconsistency");
1084 }
1085
1086 FieldEntityEntFiniteElementAdjacencyMap_multiIndex::index<
1087 Composite_Unique_mi_tag>::type::iterator ait;
1088 ait = adjacenciesPtr->get<Composite_Unique_mi_tag>().find(
1089 boost::make_tuple((*cit)->getFieldEntityPtr()->getLocalUniqueId(),
1090 numeredEntFiniteElementPtr->getLocalUniqueId()));
1091 if (ait == adjacenciesPtr->end()) {
1093 "adjacencies data inconsistency");
1094 } else {
1095 UId uid = ait->getEntUniqueId();
1096 if (entitiesPtr->find(uid) == entitiesPtr->end()) {
1098 "data inconsistency");
1099 }
1100 if (dofsPtr->find((*cit)->getLocalUniqueId()) == dofsPtr->end()) {
1102 "data inconsistency");
1103 }
1104 }
1105
1106 if ((*cit)->getEntType() != MBVERTEX) {
1107
1108 auto range =
1109 col_dofs->get<Ent_mi_tag>().equal_range((*cit)->getEnt());
1110 int nb_dofs_on_ent = std::distance(range.first, range.second);
1111
1112 int max_order = (*cit)->getMaxOrder();
1113 if ((*cit)->getNbOfCoeffs() * (*cit)->getOrderNbDofs(max_order) !=
1115
1116 /* It could be that you have
1117 removed DOFs from problem, and for example if this was vector field
1118 with components {Ux,Uy,Uz}, you removed on Uz element.*/
1119
1120 MOFEM_LOG("SELF", Sev::warning)
1121 << "Warning: Number of Dofs in Col different than number "
1122 "of dofs for given entity order: "
1123 << "Field name: " << (*cit)->getName() << " "
1124 << (*cit)->getNbOfCoeffs() * (*cit)->getOrderNbDofs(max_order)
1125 << " != " << nb_dofs_on_ent;
1126 }
1127 }
1128 }
1129
1130 for (auto rit = row_dofs->begin(); rit != row_dofs->end(); rit++) {
1131
1132 if (refinedEntitiesPtr->find((*rit)->getEnt()) ==
1133 refinedEntitiesPtr->end()) {
1135 "data inconsistency");
1136 }
1137 if (!(*rit)->getActive()) {
1139 "data inconsistency");
1140 }
1141
1142 FieldEntityEntFiniteElementAdjacencyMap_multiIndex::index<
1143 Composite_Unique_mi_tag>::type::iterator ait;
1144 ait = adjacenciesPtr->get<Composite_Unique_mi_tag>().find(
1145 boost::make_tuple((*rit)->getFieldEntityPtr()->getLocalUniqueId(),
1146 numeredEntFiniteElementPtr->getLocalUniqueId()));
1147 if (ait == adjacenciesPtr->end()) {
1149 MOFEM_LOG("SELF", Sev::error) << *(*rit);
1150 MOFEM_LOG("SELF", Sev::error) << *(*rit);
1151 MOFEM_LOG("SELF", Sev::error) << *numeredEntFiniteElementPtr;
1152 MOFEM_LOG("SELF", Sev::error) << "dof: " << (*rit)->getBitRefLevel();
1153 MOFEM_LOG("SELF", Sev::error)
1154 << "fe: " << numeredEntFiniteElementPtr->getBitRefLevel();
1155 MOFEM_LOG("SELF", Sev::error)
1156 << "problem: " << problemPtr->getBitRefLevel();
1157 MOFEM_LOG("SELF", Sev::error)
1158 << "problem mask: " << problemPtr->getBitRefLevelMask();
1160 "adjacencies data inconsistency");
1161 } else {
1162 UId uid = ait->getEntUniqueId();
1163 if (entitiesPtr->find(uid) == entitiesPtr->end()) {
1165 "data inconsistency");
1166 }
1167 if (dofsPtr->find((*rit)->getLocalUniqueId()) == dofsPtr->end()) {
1169 "data inconsistency");
1170 }
1171 }
1172 int row = (*rit)->getPetscGlobalDofIdx();
1173
1174 auto col_dofs = getColDofsPtr();
1175 for (auto cit = col_dofs->begin(); cit != col_dofs->end(); cit++) {
1176
1177 int col = (*cit)->getPetscGlobalDofIdx();
1178
1179 if (row == rowPrint && col == colPrint) {
1180 MOFEM_LOG("SELF", Sev::noisy) << "fe:\n"
1181 << *numeredEntFiniteElementPtr;
1182 MOFEM_LOG("SELF", Sev::noisy) << "row:\n" << *(*rit);
1183 MOFEM_LOG("SELF", Sev::noisy) << "col:\n" << *(*cit);
1184 MOFEM_LOG("SELF", Sev::noisy)
1185 << "fe:\n"
1186 << numeredEntFiniteElementPtr->getBitRefLevel();
1187 MOFEM_LOG("SELF", Sev::noisy) << "row:\n"
1188 << (*rit)->getBitRefLevel();
1189 MOFEM_LOG("SELF", Sev::noisy) << "col:\n"
1190 << (*cit)->getBitRefLevel();
1191 }
1192
1194 }
1195
1196 if ((*rit)->getEntType() != MBVERTEX) {
1197
1198 auto range =
1199 row_dofs->get<Ent_mi_tag>().equal_range((*rit)->getEnt());
1200 int nb_dofs_on_ent = std::distance(range.first, range.second);
1201
1202 int max_order = (*rit)->getMaxOrder();
1203 if ((*rit)->getNbOfCoeffs() * (*rit)->getOrderNbDofs(max_order) !=
1205
1206 /* It could be that you have removed DOFs from problem, and for
1207 * example if this was vector field with components {Ux,Uy,Uz}, you
1208 * removed on Uz element. */
1209
1210 MOFEM_LOG("SELF", Sev::warning)
1211 << "Warning: Number of Dofs in Row different than number "
1212 "of dofs for given entity order "
1213 << "Field name: " << (*rit)->getName() << " "
1214 << (*rit)->getNbOfCoeffs() * (*rit)->getOrderNbDofs(max_order)
1215 << " != " << nb_dofs_on_ent;
1216 }
1217 }
1218 }
1219
1221 }
1222
1223 MoFEMErrorCode postProcess() {
1225
1226 // cerr << mFieldPtr->get_comm_rank() << endl;
1229
1231 }
1232 };
1233
1234 // create matrix
1236
1237 if (verb >= VERY_VERBOSE) {
1239 }
1240
1241 if (verb >= NOISY) {
1243 std::string wait;
1244 std::cin >> wait;
1245 }
1246
1248
1249 // get problem
1250 auto problems_ptr = m_field.get_problems();
1251 auto &prb_set = problems_ptr->get<Problem_mi_tag>();
1252 auto p_miit = prb_set.find(problem_name);
1253 if (p_miit == prb_set.end())
1255 "problem < %s > not found (top tip: check spelling)",
1256 problem_name.c_str());
1257 MOFEM_LOG_C("WORLD", Sev::inform, "check problem < %s >",
1258 problem_name.c_str());
1259
1260 // loop all elements in problem and check if assemble is without error
1261 auto fe_ptr = m_field.get_finite_elements();
1262 for (auto &fe : *fe_ptr) {
1263 MOFEM_LOG_C("WORLD", Sev::verbose, "\tcheck element %s",
1264 fe->getName().c_str());
1265 CHKERR m_field.loop_finite_elements(problem_name, fe->getName(), method,
1266 nullptr, MF_EXIST,
1267 CacheTupleSharedPtr(), verb);
1268 }
1269
1272
1274
1276}
1277
1278template <>
1290
1291template <>
1302
1303template <>
1305 const std::string problem_name, SmartPetscObj<Mat> &aij_ptr, int verb) {
1308
1309 auto prb_ptr = m_field.get_problems();
1310 auto p_miit = prb_ptr->get<Problem_mi_tag>().find(problem_name);
1311 if (p_miit == prb_ptr->get<Problem_mi_tag>().end()) {
1312 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
1313 "problem < %s > is not found (top tip: check spelling)",
1314 problem_name.c_str());
1315 }
1316
1317 auto nb_rows = p_miit->getNbDofsRow();
1318 auto nb_cols = p_miit->getNbDofsCol();
1319 auto nb_loc_rows = p_miit->getNbLocalDofsRow();
1320 auto nb_loc_cols = p_miit->getNbLocalDofsCol();
1321
1322 auto row_ptr = p_miit->getNumeredRowDofsPtr();
1323 auto col_ptr = p_miit->getNumeredColDofsPtr();
1324
1326 for (auto &c : *col_ptr) {
1327 fields_ids |= c->getId();
1328 }
1329 auto fields = m_field.get_fields();
1330 std::vector<int> fields_bit_numbers;
1331 for (auto &f : *fields) {
1332 if ((fields_ids & f->getId()).any()) {
1333 fields_bit_numbers.push_back(f->getBitNumber());
1334 }
1335 }
1336
1337 Range adj;
1338 EntityHandle prev_ent = 0;
1339 int prev_dim = -1;
1340
1341 // Each bridge cell is reached from every one of its faces; its faces are
1342 // found in MOAB once and kept. Only cells on the problem's refinement level
1343 // are bridges: after a local refinement an unsplit face is also adjacent
1344 // to the refined parent cell, which is not in the problem.
1345 std::unordered_map<EntityHandle, Range> bridge_faces;
1346 auto ref_ents = m_field.get_ref_ents();
1347 const auto prb_bit = p_miit->getBitRefLevel();
1348 const auto prb_mask = p_miit->getBitRefLevelMask();
1349 auto on_problem_level = [&](EntityHandle cell) {
1350 auto it = ref_ents->find(cell);
1351 if (it == ref_ents->end())
1352 return false;
1353 const auto &bit = (*it)->getBitRefLevel();
1354 return (bit & prb_bit).any() && (bit & prb_mask) == bit;
1355 };
1356 auto get_adj = [&](auto ent, auto dim) -> const Range & {
1357 if (prev_ent == ent && prev_dim == dim) {
1358 return adj;
1359 } else {
1360 adj.clear();
1361 Range bridge;
1362 CHK_MOAB_THROW(m_field.get_moab().get_adjacencies(&ent, 1, dim + 1,
1363 false, bridge),
1364 "bridge adjacency");
1365 for (auto b : bridge) {
1366 auto it = bridge_faces.find(b);
1367 if (it == bridge_faces.end()) {
1368 Range faces;
1369 if (on_problem_level(b))
1370 CHK_MOAB_THROW(m_field.get_moab().get_adjacencies(&b, 1, dim,
1371 false, faces),
1372 "bridge faces");
1373 it = bridge_faces.emplace(b, std::move(faces)).first;
1374 }
1375 adj.merge(it->second);
1376 }
1377 prev_ent = ent;
1378 prev_dim = dim;
1379 return adj;
1380 }
1381 };
1382
1383 // Fetched once; every owner query below would otherwise look the
1384 // ParallelComm up through two tag operations.
1385 auto *pcomm = ParallelComm::get_pcomm(
1386 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1387
1388 int prev_bit_number = -1;
1389 EntityHandle prev_first_ent = 0;
1390 EntityHandle prev_second_ent = 0;
1391 using IT = boost::multi_index::index<NumeredDofEntity_multiIndex,
1392 Unique_mi_tag>::type::iterator;
1393 std::pair<IT, IT> pair_lo_hi;
1394 auto get_col_it = [&](auto bit_number, auto first_ent, auto second_ent) {
1397 return pair_lo_hi;
1398 } else {
1399 auto lo_it = col_ptr->get<Unique_mi_tag>().lower_bound(
1401 auto hi_it = col_ptr->get<Unique_mi_tag>().upper_bound(
1403 pair_lo_hi = std::make_pair(lo_it, hi_it);
1407 return pair_lo_hi;
1408 }
1409 };
1410
1411 auto create_ghost_vec = [&]() {
1413 CHKERR m_field.getInterface<VecManager>()->vecCreateGhost(problem_name, ROW,
1414 v);
1418 return v;
1419 };
1420
1421 auto v_o_nnz = create_ghost_vec();
1422 auto v_d_nnz = create_ghost_vec();
1423
1424
1425 double *o_nnz_real;
1427 double *d_nnz_real;
1429
1430 EntityHandle counted_ent = 0;
1431 int counted_owner = -1;
1432 PetscInt diagonal_nnz = 0, off_diagonal_nnz = 0;
1433 for (auto r = row_ptr->begin(); r != row_ptr->end(); ++r) {
1434
1435 auto row_loc_idx = (*r)->getPetscLocalDofIdx();
1436 if (row_loc_idx < 0)
1437 continue;
1438
1439 auto ent = (*r)->getEnt();
1440 const int row_owner = (*r)->getOwnerProc(pcomm);
1441 // All DOFs on this entity see the same columns. Count once for its
1442 // owner, then retain the existing ghost-row accumulation for each DOF.
1443 if (ent != counted_ent || row_owner != counted_owner) {
1445 const auto &adj = get_adj(ent, dimension_from_handle(ent));
1446 for (auto p = adj.pair_begin(); p != adj.pair_end(); ++p) {
1447 for (auto bit_number : fields_bit_numbers) {
1448 auto [lo_it, hi_it] = get_col_it(bit_number, p->first, p->second);
1449 for (; lo_it != hi_it; ++lo_it) {
1450 if ((*lo_it)->getPetscLocalDofIdx() < 0)
1451 continue;
1452 if ((*lo_it)->getOwnerProc(pcomm) == row_owner)
1453 ++diagonal_nnz;
1454 else
1456 }
1457 }
1458 }
1459 counted_ent = ent;
1461 }
1464 }
1465
1468
1469 auto update_vec = [&](auto v) {
1476 };
1477
1480
1481 int o_nz = 0;
1482 int d_nz = 0;
1483
1486
1487 std::vector<int> d_nnz(nb_loc_rows, 0);
1488 std::vector<int> o_nnz(nb_loc_rows, 0);
1489 for (auto r = row_ptr->begin(); r != row_ptr->end(); ++r) {
1490
1491 auto row_loc_idx = (*r)->getPetscLocalDofIdx();
1492
1493 if (
1494
1496
1497 ) {
1498 auto row_loc_idx = (*r)->getPetscLocalDofIdx();
1503 }
1504
1505 }
1506
1509
1510 if (verb >= QUIET) {
1511 MOFEM_LOG("SYNC", Sev::verbose)
1512 << "Hybrid L2 matrix d_nz: " << d_nz << " o_nz: " << o_nz;
1513 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
1514 }
1515
1516 if (verb >= VERBOSE) {
1517 MOFEM_LOG("SYNC", Sev::noisy) << "Hybrid L2 matrix";
1518 int idx = 0;
1519 for (auto &d : d_nnz) {
1520 MOFEM_LOG("SYNC", Sev::noisy) << idx << ": " << d;
1521 ++idx;
1522 }
1523 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::noisy);
1524 }
1525
1526 Mat a_raw;
1527 CHKERR MatCreateAIJ(m_field.get_comm(), nb_loc_rows, nb_loc_cols, nb_rows,
1528 nb_cols, 0, d_nnz.data(), 0, o_nnz.data(), &a_raw);
1531
1532 MOFEM_LOG_CHANNEL("WORLD");
1533 MOFEM_LOG_CHANNEL("SYNC");
1534
1536}
1537
1538} // namespace MoFEM
CGALInterfaceImpl & owner
std::vector< std::array< EntityHandle, 3 > > faces
Sorted keys.
unsigned char status
MPI_Comm comm
Core & cOre
Tag tag
std::vector< double > empty
One value per component.
std::string type
#define MOFEM_LOG_SEVERITY_SYNC(comm, severity)
Synchronise "SYNC" on curtain severity level.
#define MOFEM_LOG_SYNCHRONISE(comm)
Synchronise "SYNC" channel.
#define MOFEM_LOG_C(channel, severity, format,...)
#define MatrixManagerFunctionBegin
Create adjacent matrices using different indices.
std::vector< FieldBitNumber > row
Definition Schur.cpp:2488
It it
Definition Schur.cpp:2568
It end
Definition Schur.cpp:2568
std::vector< FieldBitNumber > col
Definition Schur.cpp:2488
SmartPetscObj< Vec > diagonal
std::string name
constexpr double a
@ VERY_VERBOSE
@ QUIET
@ NOISY
@ VERBOSE
@ ROW
@ MF_EXIST
#define MAX_DOFS_ON_ENTITY
Maximal number of DOFs on entity.
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
#define CHK_MOAB_THROW(err, msg)
Check error code of MoAB function and throw MoFEM exception.
@ MOFEM_NOT_FOUND
Definition definitions.h:33
@ MOFEM_DATA_INCONSISTENCY
Definition definitions.h:31
@ MOFEM_NOT_IMPLEMENTED
Definition definitions.h:32
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
@ BYROW
#define CHKERR
Inline error check.
#define MoFEMFunctionBeginHot
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
static const bool debug
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.
#define MOFEM_LOG_ATTRIBUTES(channel, bit)
Add attributes to channel.
auto bit
set bit
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)
FTensor::Index< 'j', 3 > j
FTensor::Index< 'k', 3 > k
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
int DofIdx
Index of DOF.
Definition Types.hpp:18
std::bitset< BITFIELDID_SIZE > BitFieldId
Field Id.
Definition Types.hpp:42
uint128_t UId
Unique Id.
Definition Types.hpp:31
std::bitset< BITREFLEVEL_SIZE > BitRefLevel
Bit structure attached to each entity identifying to what mesh entity is attached.
Definition Types.hpp:40
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
Problem::EmptyFieldBlocks EmptyFieldBlocks
auto dimension_from_handle(const EntityHandle h)
get entity dimension form handle
boost::shared_ptr< CacheTuple > CacheTupleSharedPtr
constexpr AssemblyType A
virtual MPI_Comm & get_comm() const =0
Core (interface) class.
Definition Core.hpp:83
MPI_Comm & get_comm() const
Definition Core.hpp:1033
PetscLogEvent MOFEM_EVENT_createMat
Definition Core.hpp:1016
FieldEntity_multiIndex entsFields
entities on fields
Definition Core.hpp:309
MoFEMErrorCode get_problems(const Problem_multiIndex **problems_ptr) const
Get pointer to problems multi-index.
Definition Core.cpp:859
int verbose
Verbosity level.
Definition Core.hpp:1051
int sIze
MoFEM communicator size.
Definition Core.hpp:1027
int rAnk
MOFEM communicator rank.
Definition Core.hpp:1028
MPI_Comm mofemComm
MoFEM communicator.
Definition Core.hpp:1024
std::reference_wrapper< moab::Interface > moab
moab database
Definition Core.hpp:326
FieldEntityEntFiniteElementAdjacencyMap_multiIndex entFEAdjacencies
adjacencies of elements to dofs
Definition Core.hpp:316
NumeredDofEntity_multiIndex::index< PetscGlobalIdx_mi_tag >::type DofByGlobalPetscIndex
MoFEMErrorCode getEntityAdjacencies(ProblemsByName::iterator p_miit, typename boost::multi_index::index< NumeredDofEntity_multiIndex, TAG >::type::iterator mit_row, boost::shared_ptr< FieldEntity > mofem_ent_ptr, std::vector< int > &dofs_col_view, int verb) const
Get element adjacencies.
CreateRowCompressedADJMatrix(moab::Interface &moab, MPI_Comm comm=PETSC_COMM_WORLD, int verbose=1)
MoFEMErrorCode createMatArrays(ProblemsByName::iterator p_miit, const MatType type, std::vector< PetscInt > &i, std::vector< PetscInt > &j, const bool no_diagonals=true, int verb=QUIET) const
Create matrix adjacencies.
FieldEntityEntFiniteElementAdjacencyMap_multiIndex::index< Unique_mi_tag >::type AdjByEnt
Problem_multiIndex::index< Problem_mi_tag >::type ProblemsByName
MoFEMErrorCode addElementColumns(const EntFiniteElement &fe, ElementColumns &columns, int &slot) const
Add the column indices of one element and return its slot.
static UId getLoFieldEntityUId(const FieldBitNumber bit, const EntityHandle ent)
static UId getHiFieldEntityUId(const FieldBitNumber bit, const EntityHandle ent)
BitFieldId field
Column field of the indices in [begin, end).
Create compressed matrix.
std::vector< Segment > segments
Per element, one or more segments.
std::vector< std::array< int, 2 > > elementSegments
Segment range per slot.
std::unordered_map< const EntFiniteElement *, int > slot
Element slot.
std::vector< int > indices
All elements, concatenated.
Finite element data for entity.
FieldEntity_vector_view & getColFieldEnts() const
Structure for user loop methods on finite elements.
Matrix manager is used to build and partition problems.
MoFEMErrorCode query_interface(boost::typeindex::type_index type_index, UnknownInterface **iface) const
PetscLogEvent MOFEM_EVENT_createSeqAIJCUSPARSEWithArrays
PetscLogEvent MOFEM_EVENT_createMPIAdjWithArrays
PetscLogEvent MOFEM_EVENT_checkMatrixFillIn
PetscLogEvent MOFEM_EVENT_createMPIAIJ
MoFEMErrorCode createMPIAIJWithArrays(const std::string name, Mat *Aij, int verb=QUIET)
Creates a MPI AIJ matrix using arrays that contain in standard CSR format the local rows.
PetscLogEvent MOFEM_EVENT_createMPIAIJWithArrays
MoFEMErrorCode checkMatrixFillIn(const std::string problem_name, int row_print, int col_print, Mat A, int verb=QUIET)
check if matrix fill in correspond to finite element indices
PetscLogEvent MOFEM_EVENT_createSeqAIJWithArrays
MatrixManager(const MoFEM::Core &core)
PetscLogEvent MOFEM_EVENT_createMPIAIJCUSPARSEWithArrays
Index tags of the numbered DOF containers that also read the index.
intrusive_ptr for managing petsc objects
base class for all interface classes
Vector manager is used to create vectors \mofem_vectors.
constexpr IntegrationType IT