v0.16.3
Loading...
Searching...
No Matches
Classes | Namespaces | Macros | Functions
ProblemsManager.cpp File Reference

Managing complexities for problem. More...

Go to the source code of this file.

Classes

struct  MoFEM::IdxDataType
 
struct  MoFEM::IdxDataTypePtr
 

Namespaces

namespace  MoFEM
 implementation of Data Operators for Forces and Sources
 

Macros

#define ProblemManagerFunctionBegin
 

Functions

static void MoFEM::publish_numbered_dofs (NumeredDofEntity_multiIndex &dofs, const boost::shared_ptr< std::vector< NumeredDofEntity > > &sequence_ptr, const bool serial_uid_numbering=false)
 Publish stable records using hints shared by all five ordered indices.
 

Detailed Description

Managing complexities for problem.

Definition in file ProblemsManager.cpp.

Macro Definition Documentation

◆ ProblemManagerFunctionBegin

#define ProblemManagerFunctionBegin
Value:
MOFEM_LOG_CHANNEL("WORLD"); \
MOFEM_LOG_CHANNEL("SYNC"); \
MOFEM_LOG_FUNCTION(); \
MOFEM_LOG_TAG("SYNC", "ProblemsManager"); \
MOFEM_LOG_TAG("WORLD", "ProblemsManager")
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...

Definition at line 8 of file ProblemsManager.cpp.

15 {
16 IdxDataType(const UId uid, const int dof) {
17 bcopy(&uid, dAta, 4 * sizeof(int));
18 dAta[4] = dof;
19 }
20
21private:
22 int dAta[5];
23};
24
25struct IdxDataTypePtr {
26 IdxDataTypePtr(const int *ptr) : pTr(ptr) {}
27 inline int getGlobalIdx() const {
28 int global_dof = pTr[4];
29 return global_dof;
30 }
31 inline UId getUId() const {
32 unsigned int b0, b1, b2, b3;
33 bcopy(&pTr[0], &b0, sizeof(int));
34 bcopy(&pTr[1], &b1, sizeof(int));
35 bcopy(&pTr[2], &b2, sizeof(int));
36 bcopy(&pTr[3], &b3, sizeof(int));
37 UId uid = static_cast<UId>(b0) | static_cast<UId>(b1) << 8 * sizeof(int) |
38 static_cast<UId>(b2) << 16 * sizeof(int) |
39 static_cast<UId>(b3) << 24 * sizeof(int);
40 return uid;
41 }
42
43private:
44 const int *pTr;
45};
46
47/// Publish stable records using hints shared by all five ordered indices.
48static void publish_numbered_dofs(
50 const boost::shared_ptr<std::vector<NumeredDofEntity>> &sequence_ptr,
51 const bool serial_uid_numbering = false) {
52 if (sequence_ptr->empty())
53 return;
54 const auto end_hint = dofs.end();
55 // The serial main builders assign numbering in UID order. Within one
56 // field, entity handles have that order too, so no group checks are needed.
57 if (serial_uid_numbering && dofs.empty() &&
58 sequence_ptr->front().getFieldEntityPtr()->getBitNumber() ==
59 sequence_ptr->back().getFieldEntityPtr()->getBitNumber()) {
60 for (auto &dof : *sequence_ptr)
61 dofs.emplace_hint(end_hint, sequence_ptr, &dof);
62 return;
63 }
64 auto first = sequence_ptr->begin();
65 while (first != sequence_ptr->end()) {
66 const auto &head = *first;
67 const bool append =
68 dofs.empty() ||
69 ((*dofs.rbegin())->getLocalUniqueId() < head.getLocalUniqueId() &&
70 (*dofs.get<Part_mi_tag>().rbegin())->getPart() <= head.getPart() &&
71 (*dofs.get<PetscGlobalIdx_mi_tag>().rbegin())
72 ->getPetscGlobalDofIdx() <= head.getPetscGlobalDofIdx() &&
73 (*dofs.get<PetscLocalIdx_mi_tag>().rbegin())->getPetscLocalDofIdx() <=
74 head.getPetscLocalDofIdx() &&
75 (*dofs.get<Ent_mi_tag>().rbegin())->getEnt() <= head.getEnt());
76
77 auto last = std::next(first);
78 auto previous = first;
79 // Split at field/entity boundaries and at incompatible numbering runs.
80 // Equal owner/entity keys are kept in their original publication order.
81 while (last != sequence_ptr->end() &&
82 last->getEntLocalUniqueId() == head.getEntLocalUniqueId() &&
83 last->getPart() == head.getPart() &&
84 previous->getLocalUniqueId() < last->getLocalUniqueId() &&
85 previous->getPetscGlobalDofIdx() <= last->getPetscGlobalDofIdx() &&
86 previous->getPetscLocalDofIdx() <= last->getPetscLocalDofIdx()) {
87 previous = last;
88 ++last;
89 }
90
91 if (append) {
92 for (auto it = first; it != last; ++it)
93 dofs.emplace_hint(end_hint, sequence_ptr, &*it);
94 } else {
95 // Insert the largest key first, then insert before its successor.
96 // Interleaved keys from earlier groups may still need tree searches.
97 auto hint = end_hint;
98 auto it = last;
99 while (it != first) {
100 --it;
101 hint = dofs.emplace_hint(hint, sequence_ptr, &*it);
102 }
103 }
104 first = last;
105 }
106}
107
109ProblemsManager::query_interface(boost::typeindex::type_index type_index,
110 UnknownInterface **iface) const {
111 *iface = const_cast<ProblemsManager *>(this);
112 return 0;
113}
114
115ProblemsManager::ProblemsManager(const MoFEM::Core &core)
116 : cOre(const_cast<MoFEM::Core &>(core)),
117 buildProblemFromFields(PETSC_FALSE),
118 synchroniseProblemEntities(PETSC_FALSE) {
119 PetscLogEventRegister("ProblemsManager", 0, &MOFEM_EVENT_ProblemsManager);
120}
121
122MoFEMErrorCode ProblemsManager::getOptions() {
123 MoFEM::Interface &m_field = cOre;
125 PetscOptionsBegin(m_field.get_comm(), "", "Problem manager", "none");
126 {
127 CHKERR PetscOptionsBool(
128 "-problem_build_from_fields",
129 "Add DOFs to problem directly from fields not through DOFs on elements",
130 "", buildProblemFromFields, &buildProblemFromFields, NULL);
131 }
132 PetscOptionsEnd();
134}
135
136MoFEMErrorCode ProblemsManager::partitionMesh(
137 const Range &ents, const int dim, const int adj_dim, const int n_parts,
138 Tag *th_vertex_weights, Tag *th_edge_weights, Tag *th_part_weights,
139 int verb, const bool debug) {
140 return static_cast<MoFEM::Interface &>(cOre)
141 .getInterface<CommInterface>()
142 ->partitionMesh(ents, dim, adj_dim, n_parts, th_vertex_weights,
143 th_edge_weights, th_part_weights, verb, debug);
144}
145
146MoFEMErrorCode ProblemsManager::buildProblem(const std::string name,
147 const bool square_matrix,
148 int verb) {
149
150 MoFEM::Interface &m_field = cOre;
152 if (!(cOre.getBuildMoFEM() & (1 << 0)))
153 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "fields not build");
154 if (!(cOre.getBuildMoFEM() & (1 << 1)))
155 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "FEs not build");
156 if (!(cOre.getBuildMoFEM() & (1 << 2)))
157 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "adjacencies not build");
158 const Problem *problem_ptr;
159 CHKERR m_field.get_problem(name, &problem_ptr);
160 CHKERR buildProblem(const_cast<Problem *>(problem_ptr), square_matrix, verb);
161 cOre.getBuildMoFEM() |= 1 << 3; // It is assumed that user who uses this
162 // function knows what he is doing
164}
165
166MoFEMErrorCode ProblemsManager::buildProblem(Problem *problem_ptr,
167 const bool square_matrix,
168 int verb) {
169 MoFEM::Interface &m_field = cOre;
170 auto dofs_field_ptr = m_field.get_dofs();
171 auto ents_field_ptr = m_field.get_field_ents();
172 auto adjacencies_ptr = m_field.get_ents_elements_adjacency();
174 PetscLogEventBegin(MOFEM_EVENT_ProblemsManager, 0, 0, 0, 0);
175
176 // Note: Only allowed changes on problem_ptr structure which not influence
177 // multi-index.
178
179 if (problem_ptr->getBitRefLevel().none()) {
180 SETERRQ(PETSC_COMM_SELF, 1, "problem <%s> refinement level not set",
181 problem_ptr->getName().c_str());
182 }
183 CHKERR m_field.clear_problem(problem_ptr->getName());
184
185 // zero finite elements
186 problem_ptr->numeredFiniteElementsPtr->clear();
187
188 // Field entities are visited in UID order and each contributes its DOF
189 // range at most once per view, so plain vectors arrive sorted and unique;
190 // an indexed view would pay two tree insertions per DOF for nothing.
191 using DofPtrVector = std::vector<boost::shared_ptr<DofEntity>>;
192 DofPtrVector dofs_rows, dofs_cols;
193 auto make_rows_and_cols_view = [&](auto &dofs_rows, auto &dofs_cols) {
195 for (auto it = ents_field_ptr->begin(); it != ents_field_ptr->end(); ++it) {
196
197 const auto uid = (*it)->getLocalUniqueId();
198
199 auto r = adjacencies_ptr->get<Unique_mi_tag>().equal_range(uid);
200 for (auto lo = r.first; lo != r.second; ++lo) {
201
202 if ((lo->getBitFEId() & problem_ptr->getBitFEId()).any()) {
203 std::array<bool, 2> row_col = {false, false};
204
205 const BitRefLevel &prb_bit = problem_ptr->getBitRefLevel();
206 const BitRefLevel &prb_mask = problem_ptr->getBitRefLevelMask();
207 const BitRefLevel &fe_bit = lo->entFePtr->getBitRefLevel();
208
209 // if entity is not problem refinement level
210 if ((fe_bit & prb_mask) != fe_bit)
211 continue;
212 if ((fe_bit & prb_bit).none())
213 continue;
214
215 auto add_to_view = [&](auto &nb_dofs, auto &view, auto rc) {
216 auto dit = nb_dofs->lower_bound(uid);
217 decltype(dit) hi_dit;
218 if (dit != nb_dofs->end()) {
219 hi_dit = nb_dofs->upper_bound(
220 uid | static_cast<UId>(MAX_DOFS_ON_ENTITY - 1));
221 view.insert(view.end(), dit, hi_dit);
222 row_col[rc] = true;
223 }
224 };
225
226 if ((lo->entFePtr->getBitFieldIdRow() & (*it)->getId()).any())
227 add_to_view(dofs_field_ptr, dofs_rows, ROW);
228
229 if (!square_matrix)
230 if ((lo->entFePtr->getBitFieldIdCol() & (*it)->getId()).any())
231 add_to_view(dofs_field_ptr, dofs_cols, COL);
232
233 if (square_matrix && row_col[ROW])
234 break;
235 else if (row_col[ROW] && row_col[COL])
236 break;
237 }
238 }
239 }
240 auto by_uid = [](const auto &a, const auto &b) {
241 return a->getLocalUniqueId() < b->getLocalUniqueId();
242 };
243 for (auto *view : {&dofs_rows, &dofs_cols}) {
244 if (!std::is_sorted(view->begin(), view->end(), by_uid))
245 std::sort(view->begin(), view->end(), by_uid);
246 }
248 };
249
250 CHKERR make_rows_and_cols_view(dofs_rows, dofs_cols);
251
252 // Add row dofs to problem
253 {
254 // zero rows
255 problem_ptr->nbDofsRow = 0;
256 problem_ptr->nbLocDofsRow = 0;
257 problem_ptr->nbGhostDofsRow = 0;
258
259 // add dofs for rows
260 int count_dofs = 0;
261 for (auto &dof : dofs_rows)
262 if (dof->getActive())
263 ++count_dofs;
264 boost::shared_ptr<std::vector<NumeredDofEntity>> dofs_array =
265 boost::shared_ptr<std::vector<NumeredDofEntity>>(
266 new std::vector<NumeredDofEntity>());
267 problem_ptr->getRowDofsSequence()->push_back(dofs_array);
268 dofs_array->reserve(count_dofs);
269 // The global index is the insertion order, which is the UID order and
270 // the same on every rank. On one rank it is final, with part 0 and the
271 // same local index, so partitionProblem finds nothing to modify. On more
272 // ranks it is provisional: part and local index stay -1 and
273 // partitionProblem renumbers through the adjacency of this ordering.
274 const bool serial = m_field.get_comm_size() == 1;
275 for (auto miit = dofs_rows.begin(); miit != dofs_rows.end(); miit++) {
276 if ((*miit)->getActive()) {
277 dofs_array->emplace_back(*miit);
278 auto &dof = dofs_array->back();
279 dof.petscGloablDofIdx = (problem_ptr->nbDofsRow)++;
280 if (serial) {
281 dof.pArt = 0;
282 dof.petscLocalDofIdx = dof.petscGloablDofIdx;
283 }
284 }
285 }
286 publish_numbered_dofs(*problem_ptr->numeredRowDofsPtr, dofs_array, serial);
287 }
288
289 // Add col dofs to problem
290 if (!square_matrix) {
291 // zero cols
292 problem_ptr->nbDofsCol = 0;
293 problem_ptr->nbLocDofsCol = 0;
294 problem_ptr->nbGhostDofsCol = 0;
295
296 // add dofs for cols
297 int count_dofs = 0;
298 for (auto &dof : dofs_cols)
299 if (dof->getActive())
300 ++count_dofs;
301
302 boost::shared_ptr<std::vector<NumeredDofEntity>> dofs_array =
303 boost::shared_ptr<std::vector<NumeredDofEntity>>(
304 new std::vector<NumeredDofEntity>());
305 problem_ptr->getColDofsSequence()->push_back(dofs_array);
306 dofs_array->reserve(count_dofs);
307 for (auto miit = dofs_cols.begin(); miit != dofs_cols.end(); miit++) {
308 if (!(*miit)->getActive()) {
309 continue;
310 }
311 dofs_array->emplace_back(*miit);
312 auto &dof = dofs_array->back();
313 dof.petscGloablDofIdx = problem_ptr->nbDofsCol++;
314 if (m_field.get_comm_size() == 1) {
315 dof.pArt = 0;
316 dof.petscLocalDofIdx = dof.petscGloablDofIdx;
317 }
318 }
319 publish_numbered_dofs(*problem_ptr->numeredColDofsPtr, dofs_array,
320 m_field.get_comm_size() == 1);
321 } else {
322 problem_ptr->numeredColDofsPtr = problem_ptr->numeredRowDofsPtr;
323 problem_ptr->nbLocDofsCol = problem_ptr->nbLocDofsRow;
324 problem_ptr->nbDofsCol = problem_ptr->nbDofsRow;
325 }
326
327 // job done, some debugging and postprocessing
328 if (verb >= VERBOSE) {
329 MOFEM_LOG("SYNC", Sev::verbose)
330 << problem_ptr->getName() << " Nb. local dofs "
331 << problem_ptr->numeredRowDofsPtr->size() << " by "
332 << problem_ptr->numeredColDofsPtr->size();
333 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
334 }
335
336 if (verb >= NOISY) {
337 MOFEM_LOG("SYNC", Sev::noisy)
338 << "FEs row dofs " << *problem_ptr << " Nb. row dof "
339 << problem_ptr->getNbDofsRow();
340 for (auto &miit : *problem_ptr->numeredRowDofsPtr)
341 MOFEM_LOG("SYNC", Sev::noisy) << *miit;
342
343 MOFEM_LOG("SYNC", Sev::noisy)
344 << "FEs col dofs " << *problem_ptr << " Nb. col dof "
345 << problem_ptr->getNbDofsCol();
346 for (auto &miit : *problem_ptr->numeredColDofsPtr)
347 MOFEM_LOG("SYNC", Sev::noisy) << *miit;
348 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::noisy);
349 }
350
351 cOre.getBuildMoFEM() |= Core::BUILD_PROBLEM; // It is assumed that user who
352 // uses this function knows
353 // what he is doing
354
355 PetscLogEventEnd(MOFEM_EVENT_ProblemsManager, 0, 0, 0, 0);
356
358}
359
360MoFEMErrorCode ProblemsManager::buildProblemOnDistributedMesh(
361 const std::string name, const bool square_matrix, int verb) {
362 MoFEM::Interface &m_field = cOre;
364
365 if (!((cOre.getBuildMoFEM()) & Core::BUILD_FIELD))
366 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "fields not build");
367 if (!((cOre.getBuildMoFEM()) & Core::BUILD_FE))
368 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "FEs not build");
369 if (!((cOre.getBuildMoFEM()) & Core::BUILD_ADJ))
370 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "adjacencies not build");
371
372 const Problem *problem_ptr;
373 CHKERR m_field.get_problem(name, &problem_ptr);
374 CHKERR buildProblemOnDistributedMesh(const_cast<Problem *>(problem_ptr),
375 square_matrix, verb);
376
377 cOre.getBuildMoFEM() |= Core::BUILD_PROBLEM;
378 cOre.getBuildMoFEM() |= Core::PARTITION_PROBLEM;
379
381}
382
383MoFEMErrorCode ProblemsManager::rebuildProblemOnDistributedMesh(
384 const std::string &name, const BitRefLevel target_bit,
385 const BitRefLevel target_mask, const bool square_matrix, int verb,
386 SmartPetscObj<IS> *old_row_indices, SmartPetscObj<IS> *new_row_indices) {
387 MoFEM::Interface &m_field = cOre;
389
390 if (target_bit.none())
391 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
392 "rebuild of <%s>: target bit ref level is not set", name.c_str());
393
394 using ProblemsByName = Problem_multiIndex::index<Problem_mi_tag>::type;
395 auto &problems_by_name = const_cast<ProblemsByName &>(
396 m_field.get_problems()->get<Problem_mi_tag>());
397 auto live_it = problems_by_name.find(name);
398 if (live_it == problems_by_name.end())
399 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_FOUND,
400 "problem <%s> is not found (top tip: check spelling)",
401 name.c_str());
402 if (live_it->getSubData() || live_it->getComposedProblemsData())
403 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
404 "rebuild of <%s>: only a parent problem is rebuilt in place",
405 name.c_str());
406
407 auto modify = [&](auto it, auto &&change) {
409 if (!problems_by_name.modify(it, change))
410 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
411 "modification unsuccessful");
413 };
414
415 // Stage: a hidden problem with the live problem's elements and the target
416 // selector, built by the distributed builder. The live problem is not
417 // touched until the staged containers are published below, so a failure
418 // of the build leaves it as it was.
419 const std::string staged_name = name + "__REBUILD_STAGE";
420 if (m_field.check_problem(staged_name))
421 CHKERR m_field.delete_problem(staged_name);
422 CHKERR m_field.add_problem(staged_name, MF_EXCL, verb);
423 auto staged_it = problems_by_name.find(staged_name);
424 CHKERR modify(staged_it,
425 ProblemFiniteElementChangeBitAdd(live_it->getBitFEId()));
426 CHKERR modify(staged_it, ProblemChangeRefLevelBitSet(target_bit));
427 CHKERR modify(staged_it, ProblemChangeRefLevelBitDofMaskSet(target_mask));
428 staged_it->getEmptyFieldBlocks() = live_it->getEmptyFieldBlocks();
429 CHKERR buildProblemOnDistributedMesh(staged_name, square_matrix, verb);
430
431 // Survivors: DOFs owned by this rank in the new numbering that exist in
432 // the old one, with their old and new global row indices in one order.
433 if (old_row_indices || new_row_indices) {
434 std::vector<PetscInt> old_idx, new_idx;
435 const auto &old_by_uid =
436 live_it->getNumeredRowDofsPtr()->get<Unique_mi_tag>();
437 const auto &new_by_local =
438 staged_it->getNumeredRowDofsPtr()->get<PetscLocalIdx_mi_tag>();
439 const auto hi = new_by_local.lower_bound(staged_it->getNbLocalDofsRow());
440 for (auto it = new_by_local.lower_bound(0); it != hi; ++it) {
441 auto old_it = old_by_uid.find((*it)->getLocalUniqueId());
442 if (old_it != old_by_uid.end() &&
443 (*old_it)->getPetscGlobalDofIdx() >= 0) {
444 old_idx.push_back((*old_it)->getPetscGlobalDofIdx());
445 new_idx.push_back((*it)->getPetscGlobalDofIdx());
446 }
447 }
448 auto make_is = [&](std::vector<PetscInt> &idx) {
449 return createISGeneral(m_field.get_comm(), idx.size(),
450 idx.empty() ? nullptr : idx.data(),
451 PETSC_COPY_VALUES);
452 };
453 if (old_row_indices)
454 *old_row_indices = make_is(old_idx);
455 if (new_row_indices)
456 *new_row_indices = make_is(new_idx);
457 }
458
459 // Publish: the live problem takes the staged containers, sequences, counts
460 // and the target selector; the staged problem takes the old numbering and
461 // is deleted with it. The numbered finite elements are cleared, to be
462 // rebuilt by partitionFiniteElements.
463 const Problem &live = *live_it;
464 const Problem &staged = *staged_it;
465 std::swap(live.numeredRowDofsPtr, staged.numeredRowDofsPtr);
466 std::swap(live.numeredColDofsPtr, staged.numeredColDofsPtr);
467 std::swap(live.getRowDofsSequence(), staged.getRowDofsSequence());
468 std::swap(live.getColDofsSequence(), staged.getColDofsSequence());
469 std::swap(live.nbDofsRow, staged.nbDofsRow);
470 std::swap(live.nbDofsCol, staged.nbDofsCol);
471 std::swap(live.nbLocDofsRow, staged.nbLocDofsRow);
472 std::swap(live.nbLocDofsCol, staged.nbLocDofsCol);
473 std::swap(live.nbGhostDofsRow, staged.nbGhostDofsRow);
474 std::swap(live.nbGhostDofsCol, staged.nbGhostDofsCol);
475 CHKERR modify(live_it, ProblemClearNumeredFiniteElementsChange());
476 CHKERR modify(live_it, ProblemChangeRefLevelBitSet(target_bit));
477 CHKERR modify(live_it, ProblemChangeRefLevelBitDofMaskSet(target_mask));
478 CHKERR m_field.delete_problem(staged_name);
479
480 MOFEM_LOG("WORLD", Sev::verbose)
481 << "Rebuilt problem " << name << " in place: " << live.getNbDofsRow()
482 << " dofs (" << live.getNbLocalDofsRow() << " local)";
483
485}
486
487MoFEMErrorCode ProblemsManager::buildProblemOnDistributedMesh(
488 Problem *problem_ptr, const bool square_matrix, int verb) {
489 MoFEM::Interface &m_field = cOre;
490 auto fields_ptr = m_field.get_fields();
491 auto fe_ptr = m_field.get_finite_elements();
492 auto dofs_field_ptr = m_field.get_dofs();
494 PetscLogEventBegin(MOFEM_EVENT_ProblemsManager, 0, 0, 0, 0);
495
496 // Fetched once: every owner/status query below would otherwise look the
497 // ParallelComm up through two tag operations.
498 auto *pcomm = ParallelComm::get_pcomm(
499 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
500
501 // clear data structures
502 CHKERR m_field.clear_problem(problem_ptr->getName());
503
504 CHKERR getOptions();
505
506 if (problem_ptr->getBitRefLevel().none())
507 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_FOUND,
508 "problem <%s> refinement level not set",
509 problem_ptr->getName().c_str());
510
511 int loop_size = 2;
512 if (square_matrix) {
513 loop_size = 1;
514 problem_ptr->numeredColDofsPtr = problem_ptr->numeredRowDofsPtr;
515 } else if (problem_ptr->numeredColDofsPtr == problem_ptr->numeredRowDofsPtr) {
516 problem_ptr->numeredColDofsPtr =
517 boost::shared_ptr<NumeredDofEntity_multiIndex>(
519 }
520
521 const BitRefLevel &prb_bit = problem_ptr->getBitRefLevel();
522 const BitRefLevel &prb_mask = problem_ptr->getBitRefLevelMask();
523
524 // Rows and columns DOF views as plain vectors of DOF pointers; they are
525 // sorted by UID and made unique once all selection and synchronisation
526 // has added to them (finalise_views below). An indexed view would pay two
527 // tree insertions per DOF for the same result.
528 using DofPtrVector = std::vector<boost::shared_ptr<DofEntity>>;
529 DofPtrVector dofs_rows, dofs_cols;
530
531 // Add DOFs to problem by visiting all elements and adding DOFs from
532 // elements to the problem
533 if (buildProblemFromFields == PETSC_FALSE) {
534
535 auto make_rows_and_cols_view = [&](auto &dofs_rows, auto &dofs_cols) {
536 auto ents_field_ptr = m_field.get_field_ents();
537 auto adjacencies_ptr = m_field.get_ents_elements_adjacency();
539 for (auto it = ents_field_ptr->begin(); it != ents_field_ptr->end();
540 ++it) {
541
542 const auto uid = (*it)->getLocalUniqueId();
543
544 auto r = adjacencies_ptr->get<Unique_mi_tag>().equal_range(uid);
545 for (auto lo = r.first; lo != r.second; ++lo) {
546
547 if ((lo->getBitFEId() & problem_ptr->getBitFEId()).any()) {
548 std::array<bool, 2> row_col = {false, false};
549
550 const BitRefLevel &fe_bit = lo->entFePtr->getBitRefLevel();
551
552 // if entity is not problem refinement level
553 if ((fe_bit & prb_bit).any() && (fe_bit & prb_mask) == fe_bit) {
554
555 auto add_to_view = [&](auto dofs, auto &view, auto rc) {
556 auto dit = dofs->lower_bound(uid);
557 decltype(dit) hi_dit;
558 if (dit != dofs->end()) {
559 hi_dit = dofs->upper_bound(
560 uid | static_cast<UId>(MAX_DOFS_ON_ENTITY - 1));
561 view.insert(view.end(), dit, hi_dit);
562 row_col[rc] = true;
563 }
564 };
565
566 if ((lo->entFePtr->getBitFieldIdRow() & (*it)->getId()).any())
567 add_to_view(dofs_field_ptr, dofs_rows, ROW);
568
569 if (!square_matrix)
570 if ((lo->entFePtr->getBitFieldIdCol() & (*it)->getId()).any())
571 add_to_view(dofs_field_ptr, dofs_cols, COL);
572
573 if (square_matrix && row_col[ROW])
574 break;
575 else if (row_col[ROW] && row_col[COL])
576 break;
577 }
578 }
579 }
580 }
582 };
583
584 CHKERR make_rows_and_cols_view(dofs_rows, dofs_cols);
585 }
586
587 // Add DOFS to the problem by searching all the filedes, and adding to
588 // problem owned or shared DOFs
589 if (buildProblemFromFields == PETSC_TRUE) {
590 // Get fields IDs on elements
591 BitFieldId fields_ids_row, fields_ids_col;
592 for (auto fit = fe_ptr->begin(); fit != fe_ptr->end(); fit++) {
593 if ((fit->get()->getId() & problem_ptr->getBitFEId()).any()) {
594 fields_ids_row |= fit->get()->getBitFieldIdRow();
595 fields_ids_col |= fit->get()->getBitFieldIdCol();
596 }
597 }
598 // Get fields DOFs
599 for (auto fit = fields_ptr->begin(); fit != fields_ptr->end(); fit++) {
600 if ((fit->get()->getId() & (fields_ids_row | fields_ids_col)).any()) {
601
602 auto dit = dofs_field_ptr->get<Unique_mi_tag>().lower_bound(
603 FieldEntity::getLoBitNumberUId((*fit)->getBitNumber()));
604 auto hi_dit = dofs_field_ptr->get<Unique_mi_tag>().upper_bound(
605 FieldEntity::getHiBitNumberUId((*fit)->getBitNumber()));
606
607 for (; dit != hi_dit; dit++) {
608
609 const int owner_proc = dit->get()->getOwnerProc(pcomm);
610 if (owner_proc != m_field.get_comm_rank()) {
611 const unsigned char pstatus = dit->get()->getPStatus(pcomm);
612 if (pstatus == 0) {
613 continue;
614 }
615 }
616
617 const auto &dof_bit = (*dit)->getBitRefLevel();
618 // if entity is not problem refinement level
619 if ((dof_bit & prb_bit).any() && (dof_bit & prb_mask) == dof_bit) {
620
621 if ((fit->get()->getId() & fields_ids_row).any()) {
622 dofs_rows.push_back(*dit);
623 }
624 if (!square_matrix) {
625 if ((fit->get()->getId() & fields_ids_col).any()) {
626 dofs_cols.push_back(*dit);
627 }
628 }
629 }
630 }
631 }
632 }
633 }
634
635 if (synchroniseProblemEntities) {
636 // Get fields IDs on elements
637 BitFieldId fields_ids_row, fields_ids_col;
638 BitFieldId *fields_ids[2] = {&fields_ids_row, &fields_ids_col};
639 for (FiniteElement_multiIndex::iterator fit = fe_ptr->begin();
640 fit != fe_ptr->end(); fit++) {
641 if ((fit->get()->getId() & problem_ptr->getBitFEId()).any()) {
642 fields_ids_row |= fit->get()->getBitFieldIdRow();
643 fields_ids_col |= fit->get()->getBitFieldIdCol();
644 }
645 }
646
647 DofPtrVector *dofs_ptr[] = {&dofs_rows, &dofs_cols};
648 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ++ss) {
649 Range ents_to_synchronise;
650 for (auto &dof : *dofs_ptr[ss]) {
651 if (!dof->getActive() || dof->getEntDofIdx() != 0)
652 continue;
653 ents_to_synchronise.insert(dof->getEnt());
654 }
655 Range tmp_ents = ents_to_synchronise;
656 CHKERR m_field.getInterface<CommInterface>()->synchroniseEntities(
657 ents_to_synchronise, nullptr, verb);
658 ents_to_synchronise = subtract(ents_to_synchronise, tmp_ents);
659 for (auto fit = fields_ptr->begin(); fit != fields_ptr->end(); fit++) {
660 if ((fit->get()->getId() & *fields_ids[ss]).any()) {
661 const auto bit_number = (*fit)->getBitNumber();
662 for (Range::pair_iterator pit = ents_to_synchronise.pair_begin();
663 pit != ents_to_synchronise.pair_end(); ++pit) {
664 const auto f = pit->first;
665 const auto s = pit->second;
666 const auto lo_uid =
667 FieldEntity::getLocalUniqueIdCalculate(bit_number, f);
668 const auto hi_uid =
669 FieldEntity::getLocalUniqueIdCalculate(bit_number, s);
670
671 auto dit = dofs_field_ptr->get<Unique_mi_tag>().lower_bound(lo_uid);
672 auto hi_dit =
673 dofs_field_ptr->get<Unique_mi_tag>().upper_bound(hi_uid);
674
675 dofs_ptr[ss]->insert(dofs_ptr[ss]->end(), dit, hi_dit);
676 }
677 }
678 }
679 }
680 }
681
682 // Element-based selection appends each entity's DOF range once in UID
683 // order; field-based selection and synchronisation may append out of
684 // order or twice, so sort when needed and drop duplicates.
685 auto finalise_view = [](DofPtrVector &view) {
686 auto by_uid = [](const auto &a, const auto &b) {
687 return a->getLocalUniqueId() < b->getLocalUniqueId();
688 };
689 if (!std::is_sorted(view.begin(), view.end(), by_uid))
690 std::sort(view.begin(), view.end(), by_uid);
691 view.erase(std::unique(view.begin(), view.end(),
692 [](const auto &a, const auto &b) {
693 return a->getLocalUniqueId() ==
694 b->getLocalUniqueId();
695 }),
696 view.end());
697 };
698 finalise_view(dofs_rows);
699 finalise_view(dofs_cols);
700
701 // add dofs for rows and cols and set ownership
702 DofPtrVector *dofs_ptr[] = {&dofs_rows, &dofs_cols};
703 boost::shared_ptr<NumeredDofEntity_multiIndex> numered_dofs_ptr[] = {
704 problem_ptr->numeredRowDofsPtr, problem_ptr->numeredColDofsPtr};
705 int *nbdof_ptr[] = {&problem_ptr->nbDofsRow, &problem_ptr->nbDofsCol};
706 int *local_nbdof_ptr[] = {&problem_ptr->nbLocDofsRow,
707 &problem_ptr->nbLocDofsCol};
708 int *ghost_nbdof_ptr[] = {&problem_ptr->nbGhostDofsRow,
709 &problem_ptr->nbGhostDofsCol};
710 for (int ss = 0; ss < 2; ss++) {
711 *(nbdof_ptr[ss]) = 0;
712 *(local_nbdof_ptr[ss]) = 0;
713 *(ghost_nbdof_ptr[ss]) = 0;
714 }
715
716 // Loop over dofs on rows and columns and add to multi-indices in dofs
717 // problem structure, set partition for each dof
718 int nb_local_dofs[] = {0, 0};
719 for (int ss = 0; ss < loop_size; ss++) {
720 for (auto &dof : *dofs_ptr[ss]) {
721 if (!dof->getActive())
722 continue;
723 if (dof->getOwnerProc(pcomm) == m_field.get_comm_rank())
724 nb_local_dofs[ss]++;
725 }
726 }
727
728 // get layout
729 int start_ranges[2], end_ranges[2];
730 for (int ss = 0; ss != loop_size; ss++) {
731 PetscLayout layout;
732 CHKERR PetscLayoutCreate(m_field.get_comm(), &layout);
733 CHKERR PetscLayoutSetBlockSize(layout, 1);
734 CHKERR PetscLayoutSetLocalSize(layout, nb_local_dofs[ss]);
735 CHKERR PetscLayoutSetUp(layout);
736 CHKERR PetscLayoutGetSize(layout, &*nbdof_ptr[ss]);
737 CHKERR PetscLayoutGetRange(layout, &start_ranges[ss], &end_ranges[ss]);
738 CHKERR PetscLayoutDestroy(&layout);
739 }
740 if (square_matrix) {
741 nbdof_ptr[1] = nbdof_ptr[0];
742 nb_local_dofs[1] = nb_local_dofs[0];
743 start_ranges[1] = start_ranges[0];
744 end_ranges[1] = end_ranges[0];
745 }
746
747 // set local and global indices on own dofs
748 const size_t idx_data_type_size = sizeof(IdxDataType);
749 const size_t data_block_size = idx_data_type_size / sizeof(int);
750
751 if (sizeof(IdxDataType) % sizeof(int)) {
752 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "data inconsistency");
753 }
754 std::vector<std::vector<IdxDataType>> ids_data_packed_rows(
755 m_field.get_comm_size()),
756 ids_data_packed_cols(m_field.get_comm_size());
757
758 // Loop over dofs on this processor and prepare those dofs to send on
759 // another proc
760 for (int ss = 0; ss != loop_size; ++ss) {
761
762 boost::shared_ptr<std::vector<NumeredDofEntity>> dofs_array =
763 boost::shared_ptr<std::vector<NumeredDofEntity>>(
764 new std::vector<NumeredDofEntity>());
765 int nb_dofs_to_add = 0;
766 for (auto &dof : *dofs_ptr[ss])
767 if (dof->getActive())
768 ++nb_dofs_to_add;
769 dofs_array->reserve(nb_dofs_to_add);
770 if (ss == 0) {
771 problem_ptr->getRowDofsSequence()->push_back(dofs_array);
772 } else {
773 problem_ptr->getColDofsSequence()->push_back(dofs_array);
774 }
775
776 int &local_idx = *local_nbdof_ptr[ss];
777 for (auto miit = dofs_ptr[ss]->begin(); miit != dofs_ptr[ss]->end();
778 ++miit) {
779
780 // Only set global idx for dofs on this processor part
781 if (!(miit->get()->getActive()))
782 continue;
783
784 dofs_array->emplace_back(*miit);
785
786 int owner_proc = dofs_array->back().getOwnerProc(pcomm);
787 if (owner_proc < 0) {
788 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
789 "data inconsistency");
790 }
791
792 if (owner_proc != m_field.get_comm_rank()) {
793 dofs_array->back().pArt = owner_proc;
794 dofs_array->back().petscGloablDofIdx = -1;
795 dofs_array->back().petscLocalDofIdx = -1;
796 } else {
797
798 // Set part and indexes
799 int glob_idx = start_ranges[ss] + local_idx;
800 dofs_array->back().pArt = owner_proc;
801 dofs_array->back().petscGloablDofIdx = glob_idx;
802 dofs_array->back().petscLocalDofIdx = local_idx;
803 local_idx++;
804
805 unsigned char pstatus = dofs_array->back().getPStatus(pcomm);
806 // check id dof is shared, if that is a case global idx added to data
807 // structure and is sended to other processors
808 if (pstatus > 0) {
809 const UId global_uid = dofs_array->back().getGlobalUniqueId();
810
811 for (int proc = 0;
812 proc < MAX_SHARING_PROCS &&
813 -1 != dofs_array->back().getSharingProcsPtr(pcomm)[proc];
814 proc++) {
815 // make it different for rows and columns when needed
816 if (ss == 0) {
817 ids_data_packed_rows[dofs_array->back()
818 .getSharingProcsPtr(pcomm)[proc]]
819 .emplace_back(global_uid, glob_idx);
820 } else {
821 ids_data_packed_cols[dofs_array->back()
822 .getSharingProcsPtr(pcomm)[proc]]
823 .emplace_back(global_uid, glob_idx);
824 }
825 if (!(pstatus & PSTATUS_MULTISHARED)) {
826 break;
827 }
828 }
829 }
830 }
831 }
832
833 publish_numbered_dofs(*numered_dofs_ptr[ss], dofs_array,
834 m_field.get_comm_size() == 1);
835 }
836 if (square_matrix) {
837 local_nbdof_ptr[1] = local_nbdof_ptr[0];
838 }
839
840 int nsends_rows = 0, nsends_cols = 0;
841 // Non zero lengths[i] represent a message to i of length lengths[i].
842 // Value-initialised to zero; the size must stay comm_size for the indexed
843 // writes below and for PetscGatherNumberOfMessages.
844 std::vector<int> lengths_rows(m_field.get_comm_size(), 0),
845 lengths_cols(m_field.get_comm_size(), 0);
846 for (int proc = 0; proc < m_field.get_comm_size(); proc++) {
847 lengths_rows[proc] = ids_data_packed_rows[proc].size() * data_block_size;
848 lengths_cols[proc] = ids_data_packed_cols[proc].size() * data_block_size;
849 if (!ids_data_packed_rows[proc].empty())
850 nsends_rows++;
851 if (!ids_data_packed_cols[proc].empty())
852 nsends_cols++;
853 }
854
855 MPI_Status *status;
856 CHKERR PetscMalloc1(m_field.get_comm_size(), &status);
857
858 // Do rows
859 int nrecvs_rows; // number of messages received
860 int *onodes_rows; // list of node-ids from which messages are expected
861 int *olengths_rows; // corresponding message lengths
862 int **rbuf_row; // must bee freed by user
863
864 // make sure it is a PETSc comm
865 MPI_Comm comm;
866 CHKERR PetscCommDuplicate(m_field.get_comm(), &comm, NULL);
867
868 {
869
870 // rows
871
872 // Computes the number of messages a node expects to receive
873 CHKERR PetscGatherNumberOfMessages(comm, NULL, &lengths_rows[0],
874 &nrecvs_rows);
875 // std::cerr << nrecvs_rows << std::endl;
876
877 // Computes info about messages that a MPI-node will receive, including
878 // (from-id,length) pairs for each message.
879 CHKERR PetscGatherMessageLengths(comm, nsends_rows, nrecvs_rows,
880 &lengths_rows[0], &onodes_rows,
881 &olengths_rows);
882
883 // Gets a unique new tag from a PETSc communicator. All processors that
884 // share the communicator MUST call this routine EXACTLY the same number
885 // of times. This tag should only be used with the current objects
886 // communicator; do NOT use it with any other MPI communicator.
887 int tag_row;
888 CHKERR PetscCommGetNewTag(comm, &tag_row);
889
890 // Allocate a buffer sufficient to hold messages of size specified in
891 // olengths. And post Irecvs on these buffers using node info from onodes
892 MPI_Request *r_waits_row; // must bee freed by user
893 // rbuf has a pointers to messeges. It has size of of nrecvs (number of
894 // messages) +1. In the first index a block is allocated,
895 // such that rbuf[i] = rbuf[i-1]+olengths[i-1].
896
897 CHKERR PetscPostIrecvInt(comm, tag_row, nrecvs_rows, onodes_rows,
898 olengths_rows, &rbuf_row, &r_waits_row);
899 CHKERR PetscFree(onodes_rows);
900
901 MPI_Request *s_waits_row; // status of sens messages
902 CHKERR PetscMalloc1(nsends_rows, &s_waits_row);
903
904 // Send messeges
905 for (int proc = 0, kk = 0; proc < m_field.get_comm_size(); proc++) {
906 if (!lengths_rows[proc])
907 continue; // no message to send to this proc
908 CHKERR MPI_Isend(&(ids_data_packed_rows[proc])[0], // buffer to send
909 lengths_rows[proc], // message length
910 MPIU_INT, proc, // to proc
911 tag_row, comm, s_waits_row + kk);
912 kk++;
913 }
914
915 if (nrecvs_rows) {
916 CHKERR MPI_Waitall(nrecvs_rows, r_waits_row, status);
917 }
918 if (nsends_rows) {
919 CHKERR MPI_Waitall(nsends_rows, s_waits_row, status);
920 }
921
922 CHKERR PetscFree(r_waits_row);
923 CHKERR PetscFree(s_waits_row);
924 }
925
926 // cols
927 int nrecvs_cols = nrecvs_rows;
928 int *olengths_cols = olengths_rows;
929 PetscInt **rbuf_col = rbuf_row;
930 if (!square_matrix) {
931
932 // Computes the number of messages a node expects to receive
933 CHKERR PetscGatherNumberOfMessages(comm, NULL, &lengths_cols[0],
934 &nrecvs_cols);
935
936 // Computes info about messages that a MPI-node will receive, including
937 // (from-id,length) pairs for each message.
938 int *onodes_cols;
939 CHKERR PetscGatherMessageLengths(comm, nsends_cols, nrecvs_cols,
940 &lengths_cols[0], &onodes_cols,
941 &olengths_cols);
942
943 // Gets a unique new tag from a PETSc communicator.
944 int tag_col;
945 CHKERR PetscCommGetNewTag(comm, &tag_col);
946
947 // Allocate a buffer sufficient to hold messages of size specified in
948 // olengths. And post Irecvs on these buffers using node info from onodes
949 MPI_Request *r_waits_col; // must bee freed by user
950 CHKERR PetscPostIrecvInt(comm, tag_col, nrecvs_cols, onodes_cols,
951 olengths_cols, &rbuf_col, &r_waits_col);
952 CHKERR PetscFree(onodes_cols);
953
954 MPI_Request *s_waits_col; // status of sens messages
955 CHKERR PetscMalloc1(nsends_cols, &s_waits_col);
956
957 // Send messages
958 for (int proc = 0, kk = 0; proc < m_field.get_comm_size(); proc++) {
959 if (!lengths_cols[proc])
960 continue; // no message to send to this proc
961 CHKERR MPI_Isend(&(ids_data_packed_cols[proc])[0], // buffer to send
962 lengths_cols[proc], // message length
963 MPIU_INT, proc, // to proc
964 tag_col, comm, s_waits_col + kk);
965 kk++;
966 }
967
968 if (nrecvs_cols) {
969 CHKERR MPI_Waitall(nrecvs_cols, r_waits_col, status);
970 }
971 if (nsends_cols) {
972 CHKERR MPI_Waitall(nsends_cols, s_waits_col, status);
973 }
974
975 CHKERR PetscFree(r_waits_col);
976 CHKERR PetscFree(s_waits_col);
977 }
978
979 CHKERR PetscCommDestroy(&comm);
980 CHKERR PetscFree(status);
981
982 // Cache global keys only for this receive phase: comparison must not query
983 // ownership tags, and keys must be refreshed after sharing/ownership changes.
984 using GlobalDof = std::pair<UId, boost::shared_ptr<DofEntity>>;
985 std::vector<GlobalDof> dofs_glob_uid_view;
986 if (nrecvs_rows > 0 || nrecvs_cols > 0) {
987 dofs_glob_uid_view.reserve(m_field.get_dofs()->size());
988 const FieldEntity *last_field_ptr = nullptr;
989 UId field_uid;
990 for (const auto &dof : *m_field.get_dofs()) {
991 const auto &field_ptr = dof->getFieldEntityPtr();
992 if (field_ptr.get() != last_field_ptr) {
993 field_uid = field_ptr->getGlobalUniqueId();
994 last_field_ptr = field_ptr.get();
995 }
996 dofs_glob_uid_view.emplace_back(
997 DofEntity::getUniqueIdCalculate(dof->getEntDofIdx(), field_uid), dof);
998 }
999 // A duplicate global UID keeps the first DOF in the original UID traversal,
1000 // as the former ordered_unique view did. std::sort needs no merge buffer.
1001 std::sort(dofs_glob_uid_view.begin(), dofs_glob_uid_view.end(),
1002 [](const GlobalDof &a, const GlobalDof &b) {
1003 return a.first == b.first
1004 ? a.second->getLocalUniqueId() <
1005 b.second->getLocalUniqueId()
1006 : a.first < b.first;
1007 });
1008 }
1009
1010 // set values received from other processors
1011 for (int ss = 0; ss != loop_size; ++ss) {
1012
1013 int nrecvs;
1014 int *olengths;
1015 int **data_procs;
1016 if (ss == 0) {
1017 nrecvs = nrecvs_rows;
1018 olengths = olengths_rows;
1019 data_procs = rbuf_row;
1020 } else {
1021 nrecvs = nrecvs_cols;
1022 olengths = olengths_cols;
1023 data_procs = rbuf_col;
1024 }
1025
1026 UId uid;
1027 for (int kk = 0; kk != nrecvs; ++kk) {
1028 int len = olengths[kk];
1029 int *data_from_proc = data_procs[kk];
1030 for (int dd = 0; dd < len; dd += data_block_size) {
1031 uid = IdxDataTypePtr(&data_from_proc[dd]).getUId();
1032 auto ddit = std::lower_bound(
1033 dofs_glob_uid_view.begin(), dofs_glob_uid_view.end(), uid,
1034 [](const GlobalDof &record, const UId &key) {
1035 return record.first < key;
1036 });
1037 if (ddit != dofs_glob_uid_view.end() && ddit->first != uid)
1038 ddit = dofs_glob_uid_view.end();
1039 const auto owner_proc = FieldEntity::getOwnerFromUniqueId(uid);
1040
1041 if (owner_proc == m_field.get_comm_rank() &&
1042 PetscUnlikely(ddit == dofs_glob_uid_view.end())) {
1043
1044#ifndef NDEBUG
1045 auto ents_field_ptr = m_field.get_field_ents();
1046 MOFEM_LOG("SELF", Sev::error)
1047 << "DOF is shared or multishared between processors. For example "
1048 "if order of field on given entity is set in inconsistently, "
1049 "has different value on two processor, error such as this is "
1050 "triggered";
1051
1052 MOFEM_LOG("SELF", Sev::error) << "UId " << uid << " is not found";
1053 MOFEM_LOG("SELF", Sev::error)
1054 << "Problematic UId owner proc is " << owner_proc;
1055 const auto uid_handle = FieldEntity::getHandleFromUniqueId(uid);
1056 MOFEM_LOG("SELF", Sev::error)
1057 << "Problematic UId entity owning processor handle is "
1058 << uid_handle << " entity type "
1059 << moab::CN::EntityTypeName(type_from_handle(uid_handle));
1060 const auto uid_bit_number =
1061 FieldEntity::getFieldBitNumberFromUniqueId(uid);
1062 MOFEM_LOG("SELF", Sev::error)
1063 << "Problematic UId field is "
1064 << m_field.get_field_name(
1065 field_bit_from_bit_number(uid_bit_number));
1066
1068 field_view.insert(ents_field_ptr->begin(), ents_field_ptr->end());
1069 auto fe_it = field_view.find(FieldEntity::getGlobalUniqueIdCalculate(
1070 owner_proc, uid_bit_number, uid_handle));
1071 if (fe_it == field_view.end()) {
1072 MOFEM_LOG("SELF", Sev::error)
1073 << "Also, no field entity in database for given global UId";
1074 } else {
1075 MOFEM_LOG("SELF", Sev::error) << "Field entity in databse exist "
1076 "(but have no DOF wih give UId";
1077 MOFEM_LOG("SELF", Sev::error) << **fe_it;
1078
1079 // Save file with missing entity
1080 auto error_file_name =
1081 "error_with_missing_entity_" +
1082 boost::lexical_cast<std::string>(m_field.get_comm_rank()) +
1083 ".vtk";
1084 MOFEM_LOG("SELF", Sev::error)
1085 << "Look to file < " << error_file_name
1086 << " > it contains entity with missing DOF.";
1087
1088 auto tmp_msh = get_temp_meshset_ptr(m_field.get_moab());
1089 const auto local_fe_ent = (*fe_it)->getEnt();
1090 CHKERR m_field.get_moab().add_entities(*tmp_msh, &local_fe_ent, 1);
1091 CHKERR m_field.get_moab().write_file(error_file_name.c_str(), "VTK",
1092 "", tmp_msh->get_ptr(), 1);
1093 }
1094#endif
1095
1096 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1097 "DOF with global UId not found (Compile code in Debug to "
1098 "learn more about problem");
1099 }
1100
1101 if (PetscUnlikely(ddit == dofs_glob_uid_view.end())) {
1102 continue;
1103 }
1104
1105 auto dit = numered_dofs_ptr[ss]->find(ddit->second->getLocalUniqueId());
1106
1107 if (dit != numered_dofs_ptr[ss]->end()) {
1108
1109 int global_idx = IdxDataTypePtr(&data_from_proc[dd]).getGlobalIdx();
1110#ifndef NDEBUG
1111 if (PetscUnlikely(global_idx < 0))
1112 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1113 "received negative dof");
1114#endif
1115 // One modify sets the global index; the part and the local index
1116 // (-1, not owned) are kept.
1117 const bool success = numered_dofs_ptr[ss]->modify(
1118 dit, NumeredDofEntity_part_and_indices_change(
1119 (*dit)->getPart(), global_idx,
1120 (*dit)->getPetscLocalDofIdx()));
1121 if (PetscUnlikely(!success))
1122 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1123 "modification unsuccessful");
1124 };
1125
1126#ifndef NDEBUG
1127 if (PetscUnlikely(ddit->second->getPStatus() == 0)) {
1128
1129 // Dof is shared on this processor, however there is no element
1130 // which have this dof. If DOF is not shared and received from other
1131 // processor, but not marked as a shared on other that means that is
1132 // data inconstancy and error should be thrown.
1133
1134 std::ostringstream zz;
1135 zz << *ddit->second << std::endl;
1136 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1137 "data inconsistency, dofs is not shared, but received "
1138 "from other proc\n"
1139 "%s",
1140 zz.str().c_str());
1141 }
1142#endif
1143 }
1144 }
1145 }
1146
1147 if (square_matrix) {
1148 (problem_ptr->nbDofsCol) = (problem_ptr->nbDofsRow);
1149 (problem_ptr->nbLocDofsCol) = (problem_ptr->nbLocDofsRow);
1150 }
1151
1152 CHKERR PetscFree(olengths_rows);
1153 CHKERR PetscFree(rbuf_row[0]);
1154 CHKERR PetscFree(rbuf_row);
1155 if (!square_matrix) {
1156 CHKERR PetscFree(olengths_cols);
1157 CHKERR PetscFree(rbuf_col[0]);
1158 CHKERR PetscFree(rbuf_col);
1159 }
1160
1161 if (square_matrix) {
1162 if (numered_dofs_ptr[0]->size() != numered_dofs_ptr[1]->size()) {
1163 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1164 "data inconsistency for square_matrix %ld!=%ld",
1165 numered_dofs_ptr[0]->size(), numered_dofs_ptr[1]->size());
1166 }
1167 if (problem_ptr->numeredRowDofsPtr != problem_ptr->numeredColDofsPtr) {
1168 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1169 "data inconsistency for square_matrix");
1170 }
1171 }
1172
1173 CHKERR printPartitionedProblem(problem_ptr, verb);
1174 CHKERR debugPartitionedProblem(problem_ptr, verb);
1175
1176 PetscLogEventEnd(MOFEM_EVENT_ProblemsManager, 0, 0, 0, 0);
1177
1179}
1180
1181MoFEMErrorCode ProblemsManager::buildSubProblem(
1182 const std::string out_name,
1183
1184 const std::vector<std::string> &fields_row,
1185 const std::vector<std::string> &fields_col,
1186
1187 const std::string main_problem, const bool square_matrix,
1188
1189 const map<std::string, boost::shared_ptr<Range>> *entityMapRow,
1190 const map<std::string, boost::shared_ptr<Range>> *entityMapCol,
1191
1192 int verb) {
1193 MoFEM::Interface &m_field = cOre;
1194 auto problems_ptr = m_field.get_problems();
1196
1197 CHKERR m_field.clear_problem(out_name);
1198
1199 // get reference to all problems
1200 using ProblemByName = decltype(problems_ptr->get<Problem_mi_tag>());
1201 auto &problems_by_name =
1202 const_cast<ProblemByName &>(problems_ptr->get<Problem_mi_tag>());
1203
1204 // get iterators to out problem, i.e. build problem
1205 auto out_problem_it = problems_by_name.find(out_name);
1206 if (out_problem_it == problems_by_name.end()) {
1207 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1208 "subproblem with name < %s > not defined (top tip check spelling)",
1209 out_name.c_str());
1210 }
1211 // get iterator to main problem, i.e. out problem is subproblem of main
1212 // problem
1213 auto main_problem_it = problems_by_name.find(main_problem);
1214 if (main_problem_it == problems_by_name.end()) {
1215 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1216 "problem of subproblem with name < %s > not defined (top tip "
1217 "check spelling)",
1218 main_problem.c_str());
1219 }
1220
1221 // get dofs for row & columns for out problem,
1222 boost::shared_ptr<NumeredDofEntity_multiIndex> out_problem_dofs[] = {
1223 out_problem_it->numeredRowDofsPtr, out_problem_it->numeredColDofsPtr};
1224 // get dofs for row & columns for main problem
1225 boost::shared_ptr<NumeredDofEntity_multiIndex> main_problem_dofs[] = {
1226 main_problem_it->numeredRowDofsPtr, main_problem_it->numeredColDofsPtr};
1227 // get local indices counter
1228 int *nb_local_dofs[] = {&out_problem_it->nbLocDofsRow,
1229 &out_problem_it->nbLocDofsCol};
1230 // get global indices counter
1231 int *nb_dofs[] = {&out_problem_it->nbDofsRow, &out_problem_it->nbDofsCol};
1232
1233 // set number of ghost nodes to zero
1234 {
1235 out_problem_it->nbGhostDofsRow = 0;
1236 out_problem_it->nbGhostDofsCol = 0;
1237 }
1238
1239 // put rows & columns field names in array
1240 std::vector<std::string> fields[] = {fields_row, fields_col};
1241 const map<std::string, boost::shared_ptr<Range>> *entityMap[] = {
1242 entityMapRow, entityMapCol};
1243
1244 // make data structure fos sub-problem data
1245 out_problem_it->subProblemData =
1246 boost::make_shared<Problem::SubProblemData>();
1247
1248 // Loop over rows and columns
1249 for (int ss = 0; ss != (square_matrix ? 1 : 2); ++ss) {
1250
1251 // reset dofs and columns counters
1252 (*nb_local_dofs[ss]) = 0;
1253 (*nb_dofs[ss]) = 0;
1254 // clear arrays
1255 out_problem_dofs[ss]->clear();
1256
1257 // If DOFs are cleared clear finite elements too.
1258 out_problem_it->numeredFiniteElementsPtr->clear();
1259
1260 // Number records in stable sequences before publishing them once.
1261 struct Record {
1262 NumeredDofEntity *dof;
1263 };
1264 std::vector<Record> records;
1265 std::vector<boost::shared_ptr<std::vector<NumeredDofEntity>>> sequences;
1266 auto fields_by_bit = fields[ss];
1267 std::sort(fields_by_bit.begin(), fields_by_bit.end(),
1268 [&](const std::string &a, const std::string &b) {
1269 return m_field.get_field_bit_number(a) <
1270 m_field.get_field_bit_number(b);
1271 });
1272
1273 // get dofs by field name and copy them into the out problem sequences
1274 for (auto field : fields_by_bit) {
1275
1276 // Following reserve memory in sequences, only two allocations are here,
1277 // once for array of objects, next for array of shared pointers
1278
1279 // aliased sequence of pointer is killed with element
1280 boost::shared_ptr<std::vector<NumeredDofEntity>> dofs_array =
1281 boost::make_shared<std::vector<NumeredDofEntity>>();
1282 sequences.push_back(dofs_array);
1283 // reserve memory for field dofs
1284 if (!ss)
1285 out_problem_it->getRowDofsSequence()->emplace_back(dofs_array);
1286 else
1287 out_problem_it->getColDofsSequence()->emplace_back(dofs_array);
1288
1289 // create elements objects
1290 auto bit_number = m_field.get_field_bit_number(field);
1291
1292 auto add_dit_to_dofs_array = [&](auto &dit) {
1293 if (dit->get()->getPetscGlobalDofIdx() >= 0)
1294 dofs_array->emplace_back(
1295 dit->get()->getDofEntityPtr(), dit->get()->getPetscGlobalDofIdx(),
1296 dit->get()->getPetscLocalDofIdx(), dit->get()->getPart());
1297 };
1298
1299 auto get_dafult_dof_range = [&]() {
1300 auto dit = main_problem_dofs[ss]->get<Unique_mi_tag>().lower_bound(
1301 FieldEntity::getLoBitNumberUId(bit_number));
1302 auto hi_dit = main_problem_dofs[ss]->get<Unique_mi_tag>().upper_bound(
1303 FieldEntity::getHiBitNumberUId(bit_number));
1304 return std::make_pair(dit, hi_dit);
1305 };
1306
1307 auto check = [&](auto &field) -> boost::shared_ptr<Range> {
1308 if (entityMap[ss]) {
1309 auto mit = entityMap[ss]->find(field);
1310 if (mit != entityMap[ss]->end()) {
1311 return mit->second;
1312 } else {
1313 return nullptr;
1314 }
1315 } else {
1316 return nullptr;
1317 }
1318 };
1319
1320 if (auto r_ptr = check(field)) {
1321 for (auto p = r_ptr->pair_begin(); p != r_ptr->pair_end(); ++p) {
1322 const auto lo_ent = p->first;
1323 const auto hi_ent = p->second;
1324 auto dit = main_problem_dofs[ss]->get<Unique_mi_tag>().lower_bound(
1325 DofEntity::getLoFieldEntityUId(bit_number, lo_ent));
1326 auto hi_dit = main_problem_dofs[ss]->get<Unique_mi_tag>().upper_bound(
1327 DofEntity::getHiFieldEntityUId(bit_number, hi_ent));
1328 dofs_array->reserve(std::distance(dit, hi_dit));
1329 for (; dit != hi_dit; dit++) {
1330 add_dit_to_dofs_array(dit);
1331 }
1332 }
1333 } else {
1334 auto [dit, hi_dit] = get_dafult_dof_range();
1335 dofs_array->reserve(std::distance(dit, hi_dit));
1336 for (; dit != hi_dit; dit++)
1337 add_dit_to_dofs_array(dit);
1338 }
1339
1340 // The sequence is complete, so pointers into it are stable.
1341 records.reserve(records.size() + dofs_array->size());
1342 for (auto &v : *dofs_array)
1343 records.push_back({&v});
1344 }
1345
1346 // Number the records before insertion, as the main problem would be
1347 // visited by its global index (the records still carry it): local index
1348 // in that order for DOFs of this part, -1 otherwise.
1349 std::vector<Record *> by_main_index;
1350 by_main_index.reserve(records.size());
1351 for (auto &r : records)
1352 by_main_index.push_back(&r);
1353 std::sort(by_main_index.begin(), by_main_index.end(),
1354 [](const Record *a, const Record *b) {
1355 return a->dof->getPetscGlobalDofIdx() <
1356 b->dof->getPetscGlobalDofIdx();
1357 });
1358 const unsigned int rank = m_field.get_comm_rank();
1359 for (auto *r : by_main_index)
1360 r->dof->petscLocalDofIdx =
1361 (r->dof->getPart() == rank) ? (*nb_local_dofs[ss])++ : -1;
1362
1363 // Map the main problem's global indices of this part's DOFs to the
1364 // compressed global indices of the out problem.
1365 {
1366 std::vector<int> main_indices;
1367 main_indices.reserve(*nb_local_dofs[ss]);
1368 for (auto *r : by_main_index)
1369 if (r->dof->petscLocalDofIdx >= 0)
1370 main_indices.push_back(r->dof->getPetscGlobalDofIdx());
1371 const int nb = main_indices.size();
1372 IS is;
1373 CHKERR ISCreateGeneral(m_field.get_comm(), nb, main_indices.data(),
1374 PETSC_USE_POINTER, &is);
1375 AO ao;
1376 CHKERR AOCreateMappingIS(is, PETSC_NULLPTR, &ao);
1377 if (ss == 0) {
1378 IS is_dup;
1379 CHKERR ISDuplicate(is, &is_dup);
1380 out_problem_it->getSubData()->rowIs = SmartPetscObj<IS>(is_dup, false);
1381 out_problem_it->getSubData()->rowMap = SmartPetscObj<AO>(ao, true);
1382 } else {
1383 IS is_dup;
1384 CHKERR ISDuplicate(is, &is_dup);
1385 out_problem_it->getSubData()->colIs = SmartPetscObj<IS>(is_dup, false);
1386 out_problem_it->getSubData()->colMap = SmartPetscObj<AO>(ao, true);
1387 }
1388 // The IS uses main_indices in place; after the mapping they are the
1389 // out problem's global indices.
1390 CHKERR AOApplicationToPetscIS(ao, is);
1391 CHKERR ISGetSize(is, nb_dofs[ss]);
1392 CHKERR ISDestroy(&is);
1393 {
1394 auto it = main_indices.begin();
1395 for (auto *r : by_main_index)
1396 if (r->dof->petscLocalDofIdx >= 0) {
1397 r->dof->petscGloablDofIdx = *it;
1398 ++it;
1399 }
1400 }
1401 // DOFs of other parts get the mapped global index. The IS and the
1402 // mapping are collective, so every rank makes them, with no entries if
1403 // it has no such DOFs.
1404 std::vector<int> main_indices_non_local;
1405 main_indices_non_local.reserve(records.size() - nb);
1406 for (auto *r : by_main_index)
1407 if (r->dof->petscLocalDofIdx < 0)
1408 main_indices_non_local.push_back(r->dof->getPetscGlobalDofIdx());
1409 {
1410 IS is_non_local;
1411 CHKERR ISCreateGeneral(m_field.get_comm(), main_indices_non_local.size(),
1412 main_indices_non_local.data(), PETSC_USE_POINTER,
1413 &is_non_local);
1414 CHKERR AOApplicationToPetscIS(ao, is_non_local);
1415 CHKERR ISDestroy(&is_non_local);
1416 auto it = main_indices_non_local.begin();
1417 for (auto *r : by_main_index)
1418 if (r->dof->petscLocalDofIdx < 0)
1419 r->dof->petscGloablDofIdx = *it++;
1420 }
1421 CHKERR AODestroy(&ao);
1422 }
1423
1424 for (auto &sequence_ptr : sequences)
1425 publish_numbered_dofs(*out_problem_dofs[ss], sequence_ptr);
1426 }
1427
1428 if (square_matrix) {
1429 out_problem_it->numeredColDofsPtr = out_problem_it->numeredRowDofsPtr;
1430 out_problem_it->nbLocDofsCol = out_problem_it->nbLocDofsRow;
1431 out_problem_it->nbDofsCol = out_problem_it->nbDofsRow;
1432 out_problem_it->getSubData()->colIs = out_problem_it->getSubData()->rowIs;
1433 out_problem_it->getSubData()->colMap = out_problem_it->getSubData()->rowMap;
1434 }
1435
1436 CHKERR printPartitionedProblem(&*out_problem_it, verb);
1437 CHKERR debugPartitionedProblem(&*out_problem_it, verb);
1438
1440}
1441
1442MoFEMErrorCode ProblemsManager::buildComposedProblem(
1443 const std::string out_name, const std::vector<std::string> add_row_problems,
1444 const std::vector<std::string> add_col_problems, const bool square_matrix,
1445 int verb) {
1446 if (!(cOre.getBuildMoFEM() & Core::BUILD_FIELD))
1447 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "fields not build");
1448 if (!(cOre.getBuildMoFEM() & Core::BUILD_FE))
1449 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "FEs not build");
1450 if (!(cOre.getBuildMoFEM() & Core::BUILD_ADJ))
1451 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "adjacencies not build");
1452 MoFEM::Interface &m_field = cOre;
1453 auto problems_ptr = m_field.get_problems();
1455
1456 CHKERR m_field.clear_problem(out_name);
1457 // get reference to all problems
1458 typedef Problem_multiIndex::index<Problem_mi_tag>::type ProblemByName;
1459 ProblemByName &problems_by_name =
1460 const_cast<ProblemByName &>(problems_ptr->get<Problem_mi_tag>());
1461
1462 // Get iterators to out problem, i.e. build problem
1463 ProblemByName::iterator out_problem_it = problems_by_name.find(out_name);
1464 if (out_problem_it == problems_by_name.end()) {
1465 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1466 "problem with name < %s > not defined (top tip check spelling)",
1467 out_name.c_str());
1468 }
1469 // Make data structure for composed-problem data
1470 out_problem_it->composedProblemsData =
1471 boost::make_shared<ComposedProblemsData>();
1472 boost::shared_ptr<ComposedProblemsData> cmp_prb_data =
1473 out_problem_it->getComposedProblemsData();
1474
1475 const std::vector<std::string> *add_prb[] = {&add_row_problems,
1476 &add_col_problems};
1477 std::vector<const Problem *> *add_prb_ptr[] = {&cmp_prb_data->rowProblemsAdd,
1478 &cmp_prb_data->colProblemsAdd};
1479 std::vector<SmartPetscObj<IS>> *add_prb_is[] = {&cmp_prb_data->rowIs,
1480 &cmp_prb_data->colIs};
1481
1482 // Get local indices counter
1483 int *nb_local_dofs[] = {&out_problem_it->nbLocDofsRow,
1484 &out_problem_it->nbLocDofsCol};
1485 // Get global indices counter
1486 int *nb_dofs[] = {&out_problem_it->nbDofsRow, &out_problem_it->nbDofsCol};
1487
1488 // Set number of ghost nodes to zero
1489 {
1490 out_problem_it->nbDofsRow = 0;
1491 out_problem_it->nbDofsCol = 0;
1492 out_problem_it->nbLocDofsRow = 0;
1493 out_problem_it->nbLocDofsCol = 0;
1494 out_problem_it->nbGhostDofsRow = 0;
1495 out_problem_it->nbGhostDofsCol = 0;
1496 }
1497 int nb_dofs_reserve[] = {0, 0};
1498
1499 // Loop over rows and columns in the main problem and sub-problems
1500 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ss++) {
1501 add_prb_ptr[ss]->reserve(add_prb[ss]->size());
1502 add_prb_is[ss]->reserve(add_prb[ss]->size());
1503 for (std::vector<std::string>::const_iterator vit = add_prb[ss]->begin();
1504 vit != add_prb[ss]->end(); vit++) {
1505 ProblemByName::iterator prb_it = problems_by_name.find(*vit);
1506 if (prb_it == problems_by_name.end()) {
1507 SETERRQ(
1508 PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1509 "problem with name < %s > not defined (top tip check spelling)",
1510 vit->c_str());
1511 }
1512 add_prb_ptr[ss]->push_back(&*prb_it);
1513 // set number of dofs on rows and columns
1514 if (ss == 0) {
1515 // row
1516 *nb_dofs[ss] += add_prb_ptr[ss]->back()->getNbDofsRow();
1517 *nb_local_dofs[ss] += add_prb_ptr[ss]->back()->getNbLocalDofsRow();
1518 nb_dofs_reserve[ss] +=
1519 add_prb_ptr[ss]->back()->numeredRowDofsPtr->size();
1520 } else {
1521 // column
1522 *nb_dofs[ss] += add_prb_ptr[ss]->back()->getNbDofsCol();
1523 *nb_local_dofs[ss] += add_prb_ptr[ss]->back()->getNbLocalDofsCol();
1524 nb_dofs_reserve[ss] +=
1525 add_prb_ptr[ss]->back()->numeredColDofsPtr->size();
1526 }
1527 }
1528 }
1529 // if squre problem, rows and columns are the same
1530 if (square_matrix) {
1531 add_prb_ptr[1]->reserve(add_prb_ptr[0]->size());
1532 add_prb_is[1]->reserve(add_prb_ptr[0]->size());
1533 out_problem_it->numeredColDofsPtr = out_problem_it->numeredRowDofsPtr;
1534 *nb_dofs[1] = *nb_dofs[0];
1535 *nb_local_dofs[1] = *nb_local_dofs[0];
1536 }
1537
1538 // reserve memory for dofs
1539 boost::shared_ptr<std::vector<NumeredDofEntity>> dofs_array[2];
1540 // Reserve memory
1541 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ss++) {
1542 dofs_array[ss] = boost::make_shared<std::vector<NumeredDofEntity>>();
1543 dofs_array[ss]->reserve(nb_dofs_reserve[ss]);
1544 if (!ss)
1545 out_problem_it->getRowDofsSequence()->emplace_back(dofs_array[ss]);
1546 else
1547 out_problem_it->getColDofsSequence()->emplace_back(dofs_array[ss]);
1548 }
1549
1550 // Push back DOFs
1551 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ss++) {
1552 NumeredDofEntity_multiIndex::index<PetscGlobalIdx_mi_tag>::type::iterator
1553 dit,
1554 hi_dit;
1555 int shift_glob = 0;
1556 int shift_loc = 0;
1557 for (unsigned int pp = 0; pp != add_prb_ptr[ss]->size(); pp++) {
1558 PetscInt *dofs_out_idx_ptr;
1559 int nb_local_dofs = (*add_prb_ptr[ss])[pp]->getNbLocalDofsRow();
1560 CHKERR PetscMalloc(nb_local_dofs * sizeof(int), &dofs_out_idx_ptr);
1561 if (ss == 0) {
1562 dit = (*add_prb_ptr[ss])[pp]
1563 ->numeredRowDofsPtr->get<PetscGlobalIdx_mi_tag>()
1564 .begin();
1565 hi_dit = (*add_prb_ptr[ss])[pp]
1566 ->numeredRowDofsPtr->get<PetscGlobalIdx_mi_tag>()
1567 .end();
1568 } else {
1569 dit = (*add_prb_ptr[ss])[pp]
1570 ->numeredColDofsPtr->get<PetscGlobalIdx_mi_tag>()
1571 .begin();
1572 hi_dit = (*add_prb_ptr[ss])[pp]
1573 ->numeredColDofsPtr->get<PetscGlobalIdx_mi_tag>()
1574 .end();
1575 }
1576 int is_nb = 0;
1577 for (; dit != hi_dit; dit++) {
1578 const BitRefLevel &prb_bit = out_problem_it->getBitRefLevel();
1579 const BitRefLevel &prb_mask = out_problem_it->getBitRefLevelMask();
1580 const BitRefLevel &dof_bit = dit->get()->getBitRefLevel();
1581 if ((dof_bit & prb_bit).none() || ((dof_bit & prb_mask) != dof_bit))
1582 continue;
1583 const int rank = m_field.get_comm_rank();
1584 const int part = dit->get()->getPart();
1585 const int glob_idx = shift_glob + dit->get()->getPetscGlobalDofIdx();
1586 const int loc_idx =
1587 (part == rank) ? (shift_loc + dit->get()->getPetscLocalDofIdx())
1588 : -1;
1589 dofs_array[ss]->emplace_back(dit->get()->getDofEntityPtr(), glob_idx,
1590 loc_idx, part);
1591 if (part == rank) {
1592 dofs_out_idx_ptr[is_nb++] = glob_idx;
1593 }
1594 }
1595 if (is_nb > nb_local_dofs) {
1596 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
1597 "Data inconsistency");
1598 }
1599 IS is;
1600 CHKERR ISCreateGeneral(m_field.get_comm(), is_nb, dofs_out_idx_ptr,
1601 PETSC_OWN_POINTER, &is);
1602 auto smart_is = SmartPetscObj<IS>(is);
1603 (*add_prb_is[ss]).push_back(smart_is);
1604 if (ss == 0) {
1605 shift_glob += (*add_prb_ptr[ss])[pp]->getNbDofsRow();
1606 shift_loc += (*add_prb_ptr[ss])[pp]->getNbLocalDofsRow();
1607 } else {
1608 shift_glob += (*add_prb_ptr[ss])[pp]->getNbDofsCol();
1609 shift_loc += (*add_prb_ptr[ss])[pp]->getNbLocalDofsCol();
1610 }
1611 if (square_matrix) {
1612 (*add_prb_ptr[1]).push_back((*add_prb_ptr[0])[pp]);
1613 (*add_prb_is[1]).push_back(smart_is);
1614 }
1615 }
1616 }
1617
1618 if ((*add_prb_is[1]).size() != (*add_prb_is[0]).size()) {
1619 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY, "Data inconsistency");
1620 }
1621
1622 // Insert DOFs to problem multi-index
1623 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ss++) {
1624 auto &dofs = ss == 0 ? *out_problem_it->numeredRowDofsPtr
1625 : *out_problem_it->numeredColDofsPtr;
1626 publish_numbered_dofs(dofs, dofs_array[ss]);
1627 }
1628
1629 // Compress DOFs
1630 *nb_dofs[0] = 0;
1631 *nb_dofs[1] = 0;
1632 *nb_local_dofs[0] = 0;
1633 *nb_local_dofs[1] = 0;
1634 for (int ss = 0; ss != ((square_matrix) ? 1 : 2); ss++) {
1635
1636 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs_ptr;
1637 if (ss == 0) {
1638 dofs_ptr = out_problem_it->numeredRowDofsPtr;
1639 } else {
1640 dofs_ptr = out_problem_it->numeredColDofsPtr;
1641 }
1642 NumeredDofEntityByUId::iterator dit, hi_dit;
1643 dit = dofs_ptr->get<Unique_mi_tag>().begin();
1644 hi_dit = dofs_ptr->get<Unique_mi_tag>().end();
1645 std::vector<int> idx;
1646 idx.reserve(std::distance(dit, hi_dit));
1647 // set dofs in order entity and dof number on entity
1648 for (; dit != hi_dit; dit++) {
1649 if (dit->get()->getPart() == (unsigned int)m_field.get_comm_rank()) {
1650 bool success = dofs_ptr->get<Unique_mi_tag>().modify(
1651 dit, NumeredDofEntity_local_idx_change((*nb_local_dofs[ss])++));
1652 if (!success) {
1653 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
1654 "modification unsuccessful");
1655 }
1656 idx.push_back(dit->get()->getPetscGlobalDofIdx());
1657 } else {
1658 if (dit->get()->getPetscLocalDofIdx() != -1) {
1659 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
1660 "local index should be negative");
1661 }
1662 }
1663 }
1664 if (square_matrix) {
1665 *nb_local_dofs[1] = *nb_local_dofs[0];
1666 }
1667
1668 // set new dofs mapping
1669 IS is;
1670 CHKERR ISCreateGeneral(m_field.get_comm(), idx.size(), &*idx.begin(),
1671 PETSC_USE_POINTER, &is);
1672 CHKERR ISGetSize(is, nb_dofs[ss]);
1673 if (square_matrix) {
1674 *nb_dofs[1] = *nb_dofs[0];
1675 }
1676
1677 AO ao;
1678 CHKERR AOCreateMappingIS(is, PETSC_NULLPTR, &ao);
1679 for (unsigned int pp = 0; pp != (*add_prb_is[ss]).size(); pp++)
1680 CHKERR AOApplicationToPetscIS(ao, (*add_prb_is[ss])[pp]);
1681
1682 // Set DOFs numeration
1683 {
1684 std::vector<int> idx_new;
1685 idx_new.reserve(dofs_ptr->size());
1686 for (NumeredDofEntityByUId::iterator dit =
1687 dofs_ptr->get<Unique_mi_tag>().begin();
1688 dit != dofs_ptr->get<Unique_mi_tag>().end(); dit++) {
1689 idx_new.push_back(dit->get()->getPetscGlobalDofIdx());
1690 }
1691 // set new global dofs numeration
1692 IS is_new;
1693 CHKERR ISCreateGeneral(m_field.get_comm(), idx_new.size(),
1694 &*idx_new.begin(), PETSC_USE_POINTER, &is_new);
1695 CHKERR AOApplicationToPetscIS(ao, is_new);
1696 // set global indices to multi-index
1697 std::vector<int>::iterator vit = idx_new.begin();
1698 for (NumeredDofEntityByUId::iterator dit =
1699 dofs_ptr->get<Unique_mi_tag>().begin();
1700 dit != dofs_ptr->get<Unique_mi_tag>().end(); dit++) {
1701 bool success =
1702 dofs_ptr->modify(dit, NumeredDofEntity_part_and_glob_idx_change(
1703 dit->get()->getPart(), *(vit++)));
1704 if (!success) {
1705 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
1706 "modification unsuccessful");
1707 }
1708 }
1709 CHKERR ISDestroy(&is_new);
1710 }
1711 CHKERR ISDestroy(&is);
1712 CHKERR AODestroy(&ao);
1713 }
1714
1715 CHKERR printPartitionedProblem(&*out_problem_it, verb);
1716 CHKERR debugPartitionedProblem(&*out_problem_it, verb);
1717
1718 // Inidcate that porble has been build
1719 cOre.getBuildMoFEM() |= Core::BUILD_PROBLEM;
1720 cOre.getBuildMoFEM() |= Core::PARTITION_PROBLEM;
1721
1723}
1724
1725MoFEMErrorCode ProblemsManager::partitionSimpleProblem(const std::string name,
1726 int verb) {
1727
1728 MoFEM::Interface &m_field = cOre;
1729 auto problems_ptr = m_field.get_problems();
1731
1732 if (!(cOre.getBuildMoFEM() & Core::BUILD_FIELD))
1733 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "fields not build");
1734 if (!(cOre.getBuildMoFEM() & Core::BUILD_FE))
1735 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "FEs not build");
1736 if (!(cOre.getBuildMoFEM() & Core::BUILD_ADJ))
1737 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "adjacencies not build");
1738 if (!(cOre.getBuildMoFEM() & Core::BUILD_PROBLEM))
1739 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "adjacencies not build");
1740 MOFEM_LOG("WORLD", Sev::verbose) << "Simple partition problem " << name;
1741
1742 // find p_miit
1743 typedef Problem_multiIndex::index<Problem_mi_tag>::type ProblemByName;
1744 ProblemByName &problems_set =
1745 const_cast<ProblemByName &>(problems_ptr->get<Problem_mi_tag>());
1746 ProblemByName::iterator p_miit = problems_set.find(name);
1747 if (p_miit == problems_set.end()) {
1748 SETERRQ(PETSC_COMM_SELF, 1,
1749 "problem < %s > is not found (top tip: check spelling)",
1750 name.c_str());
1751 }
1752 // Parts are contiguous ranges of the provisional global index set by
1753 // buildProblem; the index is kept and only the part and the local index
1754 // change, so modifying through the iterated index leaves elements in place.
1755 typedef boost::multi_index::index<NumeredDofEntity_multiIndex,
1756 PetscGlobalIdx_mi_tag>::type
1757 NumeredDofEntitysByIdx;
1758 NumeredDofEntitysByIdx &dofs_row_by_idx =
1759 p_miit->numeredRowDofsPtr->get<PetscGlobalIdx_mi_tag>();
1760 NumeredDofEntitysByIdx &dofs_col_by_idx =
1761 p_miit->numeredColDofsPtr->get<PetscGlobalIdx_mi_tag>();
1762 NumeredDofEntitysByIdx::iterator miit_row, hi_miit_row;
1763 NumeredDofEntitysByIdx::iterator miit_col, hi_miit_col;
1764 DofIdx &nb_row_local_dofs = p_miit->nbLocDofsRow;
1765 DofIdx &nb_row_ghost_dofs = p_miit->nbGhostDofsRow;
1766 nb_row_local_dofs = 0;
1767 nb_row_ghost_dofs = 0;
1768 DofIdx &nb_col_local_dofs = p_miit->nbLocDofsCol;
1769 DofIdx &nb_col_ghost_dofs = p_miit->nbGhostDofsCol;
1770 nb_col_local_dofs = 0;
1771 nb_col_ghost_dofs = 0;
1772
1773 bool square_matrix = false;
1774 if (p_miit->numeredRowDofsPtr == p_miit->numeredColDofsPtr) {
1775 square_matrix = true;
1776 }
1777
1778 // get row range of local indices
1779 PetscLayout layout_row;
1780 const int *ranges_row;
1781
1782 DofIdx nb_dofs_row = dofs_row_by_idx.size();
1783 CHKERR PetscLayoutCreate(m_field.get_comm(), &layout_row);
1784 CHKERR PetscLayoutSetBlockSize(layout_row, 1);
1785 CHKERR PetscLayoutSetSize(layout_row, nb_dofs_row);
1786 CHKERR PetscLayoutSetUp(layout_row);
1787 CHKERR PetscLayoutGetRanges(layout_row, &ranges_row);
1788 // get col range of local indices
1789 PetscLayout layout_col;
1790 const int *ranges_col;
1791 if (!square_matrix) {
1792 DofIdx nb_dofs_col = dofs_col_by_idx.size();
1793 CHKERR PetscLayoutCreate(m_field.get_comm(), &layout_col);
1794 CHKERR PetscLayoutSetBlockSize(layout_col, 1);
1795 CHKERR PetscLayoutSetSize(layout_col, nb_dofs_col);
1796 CHKERR PetscLayoutSetUp(layout_col);
1797 CHKERR PetscLayoutGetRanges(layout_col, &ranges_col);
1798 }
1799 for (unsigned int part = 0; part < (unsigned int)m_field.get_comm_size();
1800 part++) {
1801 miit_row = dofs_row_by_idx.lower_bound(ranges_row[part]);
1802 hi_miit_row = dofs_row_by_idx.lower_bound(ranges_row[part + 1]);
1803 if (std::distance(miit_row, hi_miit_row) !=
1804 ranges_row[part + 1] - ranges_row[part]) {
1805 SETERRQ(
1806 PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ,
1807 "data inconsistency, std::distance(miit_row,hi_miit_row) != rend - "
1808 "rstart (%ld != %d - %d = %d) ",
1809 std::distance(miit_row, hi_miit_row), ranges_row[part + 1],
1810 ranges_row[part], ranges_row[part + 1] - ranges_row[part]);
1811 }
1812 // loop rows
1813 for (; miit_row != hi_miit_row; miit_row++) {
1814 bool success = dofs_row_by_idx.modify(
1815 miit_row, NumeredDofEntity_part_and_glob_idx_change(
1816 part, (*miit_row)->getPetscGlobalDofIdx()));
1817 if (!success)
1818 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1819 "modification unsuccessful");
1820 if (part == (unsigned int)m_field.get_comm_rank()) {
1821 success = dofs_row_by_idx.modify(
1822 miit_row, NumeredDofEntity_local_idx_change(nb_row_local_dofs++));
1823 if (!success)
1824 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1825 "modification unsuccessful");
1826 }
1827 }
1828 if (!square_matrix) {
1829 miit_col = dofs_col_by_idx.lower_bound(ranges_col[part]);
1830 hi_miit_col = dofs_col_by_idx.lower_bound(ranges_col[part + 1]);
1831 if (std::distance(miit_col, hi_miit_col) !=
1832 ranges_col[part + 1] - ranges_col[part]) {
1833 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ,
1834 "data inconsistency, std::distance(miit_col,hi_miit_col) != "
1835 "rend - "
1836 "rstart (%ld != %d - %d = %d) ",
1837 std::distance(miit_col, hi_miit_col), ranges_col[part + 1],
1838 ranges_col[part], ranges_col[part + 1] - ranges_col[part]);
1839 }
1840 // loop cols
1841 for (; miit_col != hi_miit_col; miit_col++) {
1842 bool success = dofs_col_by_idx.modify(
1843 miit_col, NumeredDofEntity_part_and_glob_idx_change(
1844 part, (*miit_col)->getPetscGlobalDofIdx()));
1845 if (!success)
1846 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1847 "modification unsuccessful");
1848 if (part == (unsigned int)m_field.get_comm_rank()) {
1849 success = dofs_col_by_idx.modify(
1850 miit_col, NumeredDofEntity_local_idx_change(nb_col_local_dofs++));
1851 if (!success)
1852 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1853 "modification unsuccessful");
1854 }
1855 }
1856 }
1857 }
1858 CHKERR PetscLayoutDestroy(&layout_row);
1859 if (!square_matrix) {
1860 CHKERR PetscLayoutDestroy(&layout_col);
1861 }
1862 if (square_matrix) {
1863 nb_col_local_dofs = nb_row_local_dofs;
1864 nb_col_ghost_dofs = nb_row_ghost_dofs;
1865 }
1866 CHKERR printPartitionedProblem(&*p_miit, verb);
1867 cOre.getBuildMoFEM() |= Core::PARTITION_PROBLEM;
1869}
1870
1871MoFEMErrorCode ProblemsManager::partitionProblem(const std::string name,
1872 int verb) {
1873 MoFEM::Interface &m_field = cOre;
1874 auto problems_ptr = m_field.get_problems();
1876
1877 MOFEM_LOG("WORLD", Sev::noisy) << "Partition problem " << name;
1878
1879 // DOFs are visited in UID order, which is the order of the provisional
1880 // global index set by buildProblem, through the UID index: the global
1881 // index is modified and must not be the iterated key.
1882 using NumeredDofEntitysByIdx =
1883 NumeredDofEntity_multiIndex::index<Unique_mi_tag>::type;
1884 using ProblemsByName = Problem_multiIndex::index<Problem_mi_tag>::type;
1885
1886 // Find problem pointer by name
1887 auto &problems_set =
1888 const_cast<ProblemsByName &>(problems_ptr->get<Problem_mi_tag>());
1889 auto p_miit = problems_set.find(name);
1890 if (p_miit == problems_set.end()) {
1891 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1892 "problem with name %s not defined (top tip check spelling)",
1893 name.c_str());
1894 }
1895 int nb_dofs_row = p_miit->getNbDofsRow();
1896
1897 if (m_field.get_comm_size() != 1) {
1898
1899 if (!(cOre.getBuildMoFEM() & (1 << 0)))
1900 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "fields not build");
1901 if (!(cOre.getBuildMoFEM() & (1 << 1)))
1902 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "FEs not build");
1903 if (!(cOre.getBuildMoFEM() & (1 << 2)))
1904 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1905 "entFEAdjacencies not build");
1906 if (!(cOre.getBuildMoFEM() & (1 << 3)))
1907 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Problems not build");
1908
1909 Mat Adj;
1910 CHKERR m_field.getInterface<MatrixManager>()
1911 ->createMPIAdjWithArrays<PetscGlobalIdx_mi_tag>(name, &Adj, verb);
1912
1913 int m, n;
1914 CHKERR MatGetSize(Adj, &m, &n);
1915 if (verb > VERY_VERBOSE)
1916 MatView(Adj, PETSC_VIEWER_STDOUT_WORLD);
1917
1918 // partitioning
1919 MatPartitioning part;
1920 IS is;
1921 CHKERR MatPartitioningCreate(m_field.get_comm(), &part);
1922 CHKERR MatPartitioningSetAdjacency(part, Adj);
1923 CHKERR MatPartitioningSetFromOptions(part);
1924 CHKERR MatPartitioningSetNParts(part, m_field.get_comm_size());
1925 CHKERR MatPartitioningApply(part, &is);
1926 if (verb > VERY_VERBOSE)
1927 ISView(is, PETSC_VIEWER_STDOUT_WORLD);
1928
1929 // gather
1930 IS is_gather, is_num, is_gather_num;
1931 CHKERR ISAllGather(is, &is_gather);
1932 CHKERR ISPartitioningToNumbering(is, &is_num);
1933 CHKERR ISAllGather(is_num, &is_gather_num);
1934 const int *part_number, *petsc_idx;
1935 CHKERR ISGetIndices(is_gather, &part_number);
1936 CHKERR ISGetIndices(is_gather_num, &petsc_idx);
1937 int size_is_num, size_is_gather;
1938 CHKERR ISGetSize(is_gather, &size_is_gather);
1939 if (size_is_gather != (int)nb_dofs_row)
1940 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ,
1941 "data inconsistency %d != %d", size_is_gather, nb_dofs_row);
1942
1943 CHKERR ISGetSize(is_num, &size_is_num);
1944 if (size_is_num != (int)nb_dofs_row)
1945 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ,
1946 "data inconsistency %d != %d", size_is_num, nb_dofs_row);
1947
1948 bool square_matrix = false;
1949 if (p_miit->numeredRowDofsPtr == p_miit->numeredColDofsPtr)
1950 square_matrix = true;
1951
1952 // if (!square_matrix) {
1953 // // FIXME: This is for back compatibility, if deprecate interface
1954 // function
1955 // // build interfaces is removed, this part of the code will be obsolete
1956 // auto mit_row = p_miit->numeredRowDofsPtr->get<Unique_mi_tag>().begin();
1957 // auto hi_mit_row = p_miit->numeredRowDofsPtr->get<Unique_mi_tag>().end();
1958 // auto mit_col = p_miit->numeredColDofsPtr->get<Unique_mi_tag>().begin();
1959 // auto hi_mit_col = p_miit->numeredColDofsPtr->get<Unique_mi_tag>().end();
1960 // for (; mit_row != hi_mit_row; mit_row++, mit_col++) {
1961 // if (mit_col == hi_mit_col) {
1962 // SETERRQ(
1963 // PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1964 // "check finite element definition, nb. of rows is not equal to "
1965 // "number for columns");
1966 // }
1967 // if (mit_row->get()->getLocalUniqueId() !=
1968 // mit_col->get()->getLocalUniqueId()) {
1969 // SETERRQ(
1970 // PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1971 // "check finite element definition, nb. of rows is not equal to "
1972 // "number for columns");
1973 // }
1974 // }
1975 // }
1976
1977 auto number_dofs = [&](auto &dofs_idx, auto &counter) {
1979 for (auto miit_dofs_row = dofs_idx.begin();
1980 miit_dofs_row != dofs_idx.end(); miit_dofs_row++) {
1981 const int idx = (*miit_dofs_row)->getPetscGlobalDofIdx();
1982 const int part = part_number[idx];
1983 if (part == (unsigned int)m_field.get_comm_rank()) {
1984 const bool success = dofs_idx.modify(
1985 miit_dofs_row, NumeredDofEntity_part_and_indices_change(
1986 part, petsc_idx[idx], counter++));
1987 if (!success) {
1988 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1989 "modification unsuccessful");
1990 }
1991 } else {
1992 const bool success = dofs_idx.modify(
1993 miit_dofs_row, NumeredDofEntity_part_and_glob_idx_change(
1994 part, petsc_idx[idx]));
1995 if (!success) {
1996 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
1997 "modification unsuccessful");
1998 }
1999 }
2000 }
2002 };
2003
2004 // Set petsc global indices
2005 auto &dofs_row_by_idx_no_const = const_cast<NumeredDofEntitysByIdx &>(
2006 p_miit->numeredRowDofsPtr->get<Unique_mi_tag>());
2007 int &nb_row_local_dofs = p_miit->nbLocDofsRow;
2008 int &nb_row_ghost_dofs = p_miit->nbGhostDofsRow;
2009 nb_row_local_dofs = 0;
2010 nb_row_ghost_dofs = 0;
2011
2012 CHKERR number_dofs(dofs_row_by_idx_no_const, nb_row_local_dofs);
2013
2014 int &nb_col_local_dofs = p_miit->nbLocDofsCol;
2015 int &nb_col_ghost_dofs = p_miit->nbGhostDofsCol;
2016 if (square_matrix) {
2017 nb_col_local_dofs = nb_row_local_dofs;
2018 nb_col_ghost_dofs = nb_row_ghost_dofs;
2019 } else {
2020 NumeredDofEntitysByIdx &dofs_col_by_idx_no_const =
2021 const_cast<NumeredDofEntitysByIdx &>(
2022 p_miit->numeredColDofsPtr->get<Unique_mi_tag>());
2023 nb_col_local_dofs = 0;
2024 nb_col_ghost_dofs = 0;
2025 CHKERR number_dofs(dofs_col_by_idx_no_const, nb_col_local_dofs);
2026 }
2027
2028 CHKERR ISRestoreIndices(is_gather, &part_number);
2029 CHKERR ISRestoreIndices(is_gather_num, &petsc_idx);
2030 CHKERR ISDestroy(&is_num);
2031 CHKERR ISDestroy(&is_gather_num);
2032 CHKERR ISDestroy(&is_gather);
2033 CHKERR ISDestroy(&is);
2034 CHKERR MatPartitioningDestroy(&part);
2035 CHKERR MatDestroy(&Adj);
2036 CHKERR printPartitionedProblem(&*p_miit, verb);
2037 } else {
2038
2039 auto number_dofs = [&](auto &dof_idx, auto &counter) {
2041 for (auto miit_dofs_row = dof_idx.begin(); miit_dofs_row != dof_idx.end();
2042 miit_dofs_row++) {
2043 // buildProblem numbers serial problems at insertion; a modify through
2044 // the five indices is needed only when the record does not match.
2045 const auto &dof = **miit_dofs_row;
2046 if (dof.getPart() != 0 || dof.getPetscGlobalDofIdx() != counter ||
2047 dof.getPetscLocalDofIdx() != counter) {
2048 const bool success = dof_idx.modify(
2049 miit_dofs_row,
2050 NumeredDofEntity_part_and_indices_change(0, counter, counter));
2051 if (!success) {
2052 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
2053 "modification unsuccessful");
2054 }
2055 }
2056 ++counter;
2057 }
2059 };
2060
2061 auto &dofs_row_by_idx_no_const = const_cast<NumeredDofEntitysByIdx &>(
2062 p_miit->numeredRowDofsPtr->get<Unique_mi_tag>());
2063 int &nb_row_local_dofs = p_miit->nbLocDofsRow;
2064 int &nb_row_ghost_dofs = p_miit->nbGhostDofsRow;
2065 nb_row_local_dofs = 0;
2066 nb_row_ghost_dofs = 0;
2067
2068 CHKERR number_dofs(dofs_row_by_idx_no_const, nb_row_local_dofs);
2069
2070 bool square_matrix = false;
2071 if (p_miit->numeredRowDofsPtr == p_miit->numeredColDofsPtr)
2072 square_matrix = true;
2073
2074 int &nb_col_local_dofs = p_miit->nbLocDofsCol;
2075 int &nb_col_ghost_dofs = p_miit->nbGhostDofsCol;
2076 if (square_matrix) {
2077 nb_col_local_dofs = nb_row_local_dofs;
2078 nb_col_ghost_dofs = nb_row_ghost_dofs;
2079 } else {
2080 NumeredDofEntitysByIdx &dofs_col_by_idx_no_const =
2081 const_cast<NumeredDofEntitysByIdx &>(
2082 p_miit->numeredColDofsPtr->get<Unique_mi_tag>());
2083 nb_col_local_dofs = 0;
2084 nb_col_ghost_dofs = 0;
2085 CHKERR number_dofs(dofs_col_by_idx_no_const, nb_col_local_dofs);
2086 }
2087 }
2088
2089 cOre.getBuildMoFEM() |= 1 << 4;
2091}
2092
2093MoFEMErrorCode ProblemsManager::inheritPartition(
2094 const std::string name, const std::string problem_for_rows, bool copy_rows,
2095 const std::string problem_for_cols, bool copy_cols, int verb) {
2096 MoFEM::Interface &m_field = cOre;
2097 auto problems_ptr = m_field.get_problems();
2099
2100 if (!(cOre.getBuildMoFEM() & Core::BUILD_PROBLEM))
2101 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY, "pRoblems not build");
2102
2103 typedef Problem_multiIndex::index<Problem_mi_tag>::type ProblemByName;
2104
2105 // find p_miit
2106 ProblemByName &problems_by_name =
2107 const_cast<ProblemByName &>(problems_ptr->get<Problem_mi_tag>());
2108 ProblemByName::iterator p_miit = problems_by_name.find(name);
2109 if (p_miit == problems_by_name.end()) {
2110 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
2111 "problem with name < %s > not defined (top tip check spelling)",
2112 name.c_str());
2113 }
2114 if (verb > QUIET)
2115 MOFEM_LOG("WORLD", Sev::inform)
2116 << p_miit->getName() << " from rows of " << problem_for_rows
2117 << " and columns of " << problem_for_cols;
2118
2119 // find p_miit_row
2120 ProblemByName::iterator p_miit_row = problems_by_name.find(problem_for_rows);
2121 if (p_miit_row == problems_by_name.end()) {
2122 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2123 "problem with name < %s > not defined (top tip check spelling)",
2124 problem_for_rows.c_str());
2125 }
2126 const boost::shared_ptr<NumeredDofEntity_multiIndex> dofs_row =
2127 p_miit_row->numeredRowDofsPtr;
2128
2129 // find p_mit_col
2130 ProblemByName::iterator p_miit_col = problems_by_name.find(problem_for_cols);
2131 if (p_miit_col == problems_by_name.end()) {
2132 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2133 "problem with name < %s > not defined (top tip check spelling)",
2134 problem_for_cols.c_str());
2135 }
2136 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs_col =
2137 p_miit_col->numeredColDofsPtr;
2138
2139 bool copy[] = {copy_rows, copy_cols};
2140 boost::shared_ptr<NumeredDofEntity_multiIndex> composed_dofs[] = {
2141 p_miit->numeredRowDofsPtr, p_miit->numeredColDofsPtr};
2142
2143 int *nb_local_dofs[] = {&p_miit->nbLocDofsRow, &p_miit->nbLocDofsCol};
2144 int *nb_dofs[] = {&p_miit->nbDofsRow, &p_miit->nbDofsCol};
2145 boost::shared_ptr<NumeredDofEntity_multiIndex> copied_dofs[] = {dofs_row,
2146 dofs_col};
2147
2148 for (int ss = 0; ss < 2; ss++) {
2149
2150 // build indices
2151 *nb_local_dofs[ss] = 0;
2152 if (!copy[ss]) {
2153
2154 // only copy indices which are belong to some elements if this problem
2155 std::vector<int> is_local, is_new;
2156
2157 NumeredDofEntityByUId &dofs_by_uid =
2158 copied_dofs[ss]->get<Unique_mi_tag>();
2159 for (NumeredDofEntity_multiIndex::iterator dit =
2160 composed_dofs[ss]->begin();
2161 dit != composed_dofs[ss]->end(); dit++) {
2162 NumeredDofEntityByUId::iterator diit =
2163 dofs_by_uid.find((*dit)->getLocalUniqueId());
2164 if (diit == dofs_by_uid.end()) {
2165 SETERRQ(
2167 "data inconsistency, could not find dof in composite problem");
2168 }
2169 int part_number = (*diit)->getPart(); // get part number
2170 int petsc_global_dof = (*diit)->getPetscGlobalDofIdx();
2171 bool success;
2172 success = composed_dofs[ss]->modify(
2173 dit, NumeredDofEntity_part_and_glob_idx_change(part_number,
2174 petsc_global_dof));
2175 if (!success) {
2176 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2177 "modification unsuccessful");
2178 }
2179 if ((*dit)->getPart() == (unsigned int)m_field.get_comm_rank()) {
2180 success = composed_dofs[ss]->modify(
2181 dit, NumeredDofEntity_local_idx_change((*nb_local_dofs[ss])++));
2182 if (!success) {
2183 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2184 "modification unsuccessful");
2185 }
2186 is_local.push_back(petsc_global_dof);
2187 }
2188 }
2189
2190 AO ao;
2191 CHKERR AOCreateMapping(m_field.get_comm(), is_local.size(), &is_local[0],
2192 NULL, &ao);
2193
2194 // apply local to global mapping
2195 is_local.resize(0);
2196 for (NumeredDofEntity_multiIndex::iterator dit =
2197 composed_dofs[ss]->begin();
2198 dit != composed_dofs[ss]->end(); dit++) {
2199 is_local.push_back((*dit)->getPetscGlobalDofIdx());
2200 }
2201 CHKERR AOPetscToApplication(ao, is_local.size(), &is_local[0]);
2202 int idx2 = 0;
2203 for (NumeredDofEntity_multiIndex::iterator dit =
2204 composed_dofs[ss]->begin();
2205 dit != composed_dofs[ss]->end(); dit++) {
2206 int part_number = (*dit)->getPart(); // get part number
2207 int petsc_global_dof = is_local[idx2++];
2208 bool success;
2209 success = composed_dofs[ss]->modify(
2210 dit, NumeredDofEntity_part_and_glob_idx_change(part_number,
2211 petsc_global_dof));
2212 if (!success) {
2213 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2214 "modification unsuccessful");
2215 }
2216 }
2217
2218 CHKERR AODestroy(&ao);
2219
2220 } else {
2221
2222 for (NumeredDofEntity_multiIndex::iterator dit = copied_dofs[ss]->begin();
2223 dit != copied_dofs[ss]->end(); dit++) {
2224 std::pair<NumeredDofEntity_multiIndex::iterator, bool> p;
2225 p = composed_dofs[ss]->insert(boost::shared_ptr<NumeredDofEntity>(
2226 new NumeredDofEntity((*dit)->getDofEntityPtr())));
2227 if (p.second) {
2228 (*nb_dofs[ss])++;
2229 }
2230 int part_number = (*dit)->getPart(); // get part number
2231 int petsc_global_dof = (*dit)->getPetscGlobalDofIdx();
2232 if (part_number == (unsigned int)m_field.get_comm_rank()) {
2233 const bool success = composed_dofs[ss]->modify(
2234 p.first, NumeredDofEntity_part_and_indices_change(
2235 part_number, petsc_global_dof,
2236 (*nb_local_dofs[ss])++));
2237 if (!success) {
2238 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2239 "modification unsuccessful");
2240 }
2241 } else {
2242 const bool success = composed_dofs[ss]->modify(
2243 p.first, NumeredDofEntity_part_and_glob_idx_change(
2244 part_number, petsc_global_dof));
2245 if (!success) {
2246 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2247 "modification unsuccessful");
2248 }
2249 }
2250 }
2251 }
2252 }
2253
2254 CHKERR printPartitionedProblem(&*p_miit, verb);
2255 CHKERR debugPartitionedProblem(&*p_miit, verb);
2256
2258}
2259
2261ProblemsManager::printPartitionedProblem(const Problem *problem_ptr, int verb) {
2262 MoFEM::Interface &m_field = cOre;
2264
2265 if (verb > QUIET) {
2266
2267 MOFEM_LOG("SYNC", Sev::inform)
2268 << problem_ptr->getName() << " Nb. local dof "
2269 << problem_ptr->getNbLocalDofsRow() << " by "
2270 << problem_ptr->getNbLocalDofsCol() << " nb global dofs "
2271 << problem_ptr->getNbDofsRow() << " by " << problem_ptr->getNbDofsCol();
2272
2274 }
2275
2277}
2278
2280ProblemsManager::debugPartitionedProblem(const Problem *problem_ptr, int verb) {
2281 MoFEM::Interface &m_field = cOre;
2283
2284 auto save_ent = [](moab::Interface &moab, const std::string name,
2285 const EntityHandle ent) {
2287 EntityHandle out_meshset;
2288 CHKERR moab.create_meshset(MESHSET_SET, out_meshset);
2289 CHKERR moab.add_entities(out_meshset, &ent, 1);
2290 CHKERR moab.write_file(name.c_str(), "VTK", "", &out_meshset, 1);
2291 CHKERR moab.delete_entities(&out_meshset, 1);
2293 };
2294
2295 if (debug > 0) {
2296
2297 typedef NumeredDofEntity_multiIndex::index<Unique_mi_tag>::type
2298 NumeredDofEntitysByIdx;
2299 NumeredDofEntitysByIdx::iterator dit, hi_dit;
2300 const NumeredDofEntitysByIdx *numered_dofs_ptr[] = {
2301 &(problem_ptr->numeredRowDofsPtr->get<Unique_mi_tag>()),
2302 &(problem_ptr->numeredColDofsPtr->get<Unique_mi_tag>())};
2303
2304 int *nbdof_ptr[] = {&problem_ptr->nbDofsRow, &problem_ptr->nbDofsCol};
2305 int *local_nbdof_ptr[] = {&problem_ptr->nbLocDofsRow,
2306 &problem_ptr->nbLocDofsCol};
2307
2308 for (int ss = 0; ss < 2; ss++) {
2309
2310 dit = numered_dofs_ptr[ss]->begin();
2311 hi_dit = numered_dofs_ptr[ss]->end();
2312 for (; dit != hi_dit; dit++) {
2313 if ((*dit)->getPart() == (unsigned int)m_field.get_comm_rank()) {
2314 if ((*dit)->getPetscLocalDofIdx() < 0) {
2315 std::ostringstream zz;
2316 zz << "rank " << m_field.get_comm_rank() << " " << **dit;
2317 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
2318 "local dof index for %d (0-row, 1-col) not set, i.e. has "
2319 "negative value\n %s",
2320 ss, zz.str().c_str());
2321 }
2322 if ((*dit)->getPetscLocalDofIdx() >= *local_nbdof_ptr[ss]) {
2323 std::ostringstream zz;
2324 zz << "rank " << m_field.get_comm_rank() << " " << **dit;
2325 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
2326 "local dofs for %d (0-row, 1-col) out of range\n %s", ss,
2327 zz.str().c_str());
2328 }
2329 } else {
2330 if ((*dit)->getPetscGlobalDofIdx() < 0) {
2331
2332 const EntityHandle ent = (*dit)->getEnt();
2333 CHKERR save_ent(
2334 m_field.get_moab(),
2335 "debug_part" +
2336 boost::lexical_cast<std::string>(m_field.get_comm_rank()) +
2337 "_negative_global_index.vtk",
2338 ent);
2339
2340 std::ostringstream zz;
2341 zz << "rank " << m_field.get_comm_rank() << " "
2342 << dit->get()->getBitRefLevel() << " " << **dit;
2343 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
2344 "global dof index for %d (0-row, 1-col) row not set, i.e. "
2345 "has negative value\n %s",
2346 ss, zz.str().c_str());
2347 }
2348 if ((*dit)->getPetscGlobalDofIdx() >= *nbdof_ptr[ss]) {
2349 std::ostringstream zz;
2350 zz << "rank " << m_field.get_comm_rank() << " nb_dofs "
2351 << *nbdof_ptr[ss] << " " << **dit;
2352 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
2353 "global dofs for %d (0-row, 1-col) out of range\n %s", ss,
2354 zz.str().c_str());
2355 }
2356 }
2357 }
2358 }
2359 }
2361}
2362
2363MoFEMErrorCode ProblemsManager::partitionFiniteElements(const std::string name,
2364 bool part_from_moab,
2365 int low_proc,
2366 int hi_proc, int verb) {
2367 MoFEM::Interface &m_field = cOre;
2368 auto problems_ptr = m_field.get_problems();
2369 auto fe_ent_ptr = m_field.get_ents_finite_elements();
2371
2372 if (!(cOre.getBuildMoFEM() & Core::BUILD_FIELD))
2373 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY, "fields not build");
2374
2375 if (!(cOre.getBuildMoFEM() & Core::BUILD_FE))
2376 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY, "FEs not build");
2377
2378 if (!(cOre.getBuildMoFEM() & Core::BUILD_ADJ))
2379 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2380 "adjacencies not build");
2381
2382 if (!(cOre.getBuildMoFEM() & Core::BUILD_PROBLEM))
2383 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY, "problem not build");
2384
2385 if (!(cOre.getBuildMoFEM() & Core::PARTITION_PROBLEM))
2386 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2387 "problem not partitioned");
2388
2389 if (low_proc == -1)
2390 low_proc = m_field.get_comm_rank();
2391 if (hi_proc == -1)
2392 hi_proc = m_field.get_comm_rank();
2393
2394 // Find pointer to problem of given name
2395 typedef Problem_multiIndex::index<Problem_mi_tag>::type ProblemByName;
2396 auto &problems =
2397 const_cast<ProblemByName &>(problems_ptr->get<Problem_mi_tag>());
2398 ProblemByName::iterator p_miit = problems.find(name);
2399 if (p_miit == problems.end()) {
2400 SETERRQ(m_field.get_comm(), MOFEM_NOT_FOUND,
2401 "problem < %s > not found (top tip: check spelling)",
2402 name.c_str());
2403 }
2404
2405 // Get reference on finite elements multi-index on the problem
2406 NumeredEntFiniteElement_multiIndex &problem_finite_elements =
2407 *p_miit->numeredFiniteElementsPtr;
2408
2409 // Clear all elements and data, build it again
2410 problem_finite_elements.clear();
2411
2412 // Check if dofs and columns are the same, i.e. structurally symmetric
2413 // problem
2414 bool do_cols_prob = true;
2415 if (p_miit->numeredRowDofsPtr == p_miit->numeredColDofsPtr) {
2416 do_cols_prob = false;
2417 }
2418
2419 auto get_good_elems = [&]() {
2420 auto good_elems = std::vector<decltype(fe_ent_ptr->begin())>();
2421 good_elems.reserve(fe_ent_ptr->size());
2422
2423 const auto prb_bit = p_miit->getBitRefLevel();
2424 const auto prb_mask = p_miit->getBitRefLevelMask();
2425
2426 // Loop over all elements in database and if right element is there add it
2427 // to problem finite element multi-index
2428 for (auto efit = fe_ent_ptr->begin(); efit != fe_ent_ptr->end(); ++efit) {
2429
2430 // if element is not part of problem
2431 if (((*efit)->getId() & p_miit->getBitFEId()).any()) {
2432
2433 const auto &fe_bit = (*efit)->getBitRefLevel();
2434
2435 // if entity is not problem refinement level
2436 if ((fe_bit & prb_mask) == fe_bit && (fe_bit & prb_bit).any())
2437 good_elems.emplace_back(efit);
2438 }
2439 }
2440
2441 return good_elems;
2442 };
2443
2444 auto good_elems = get_good_elems();
2445
2446 auto numbered_good_elems_ptr =
2447 boost::make_shared<std::vector<NumeredEntFiniteElement>>();
2448 numbered_good_elems_ptr->reserve(good_elems.size());
2449 for (auto &efit : good_elems)
2450 numbered_good_elems_ptr->emplace_back(NumeredEntFiniteElement(*efit));
2451
2452 if (!do_cols_prob) {
2453 for (auto &fe : *numbered_good_elems_ptr) {
2454 if (fe.sPtr->getRowFieldEntsPtr() == fe.sPtr->getColFieldEntsPtr()) {
2455 fe.getColFieldEntsPtr() = fe.getRowFieldEntsPtr();
2456 }
2457 }
2458 }
2459
2460 if (part_from_moab) {
2461 for (auto &fe : *numbered_good_elems_ptr) {
2462 // All imported elements belong to rank zero in a serial communicator.
2463 if (m_field.get_comm_size() == 1 || fe.getEntType() == MBENTITYSET) {
2464 fe.part = m_field.get_comm_rank();
2465 } else {
2466 // if partition is taken from moab partition
2467 int proc = fe.getPartProc();
2468 if (proc == -1 && fe.getEntType() == MBVERTEX)
2469 proc = fe.getOwnerProc();
2470 fe.part = proc;
2471 }
2472 }
2473 }
2474
2475 // The element's row DOF view is needed only to vote on its part when the
2476 // partition is not taken from MOAB and there is more than one rank.
2477 if (!part_from_moab) {
2478 for (auto &fe : *numbered_good_elems_ptr) {
2479 if (fe.getEntType() == MBENTITYSET || m_field.get_comm_size() == 1) {
2480 fe.part = m_field.get_comm_rank();
2481 } else {
2483 CHKERR fe.sPtr->getRowDofView(*(p_miit->numeredRowDofsPtr), rows_view);
2484 std::vector<int> parts(m_field.get_comm_size(), 0);
2485 for (auto &dof_ptr : rows_view)
2486 parts[dof_ptr->pArt]++;
2487 std::vector<int>::iterator pos =
2488 max_element(parts.begin(), parts.end());
2489 const auto max_part = std::distance(parts.begin(), pos);
2490 fe.part = max_part;
2491 }
2492 }
2493 }
2494
2495 for (auto &fe : *numbered_good_elems_ptr) {
2496
2497 auto check_fields_and_dofs = [&]() {
2498 if (!part_from_moab) {
2499 if (fe.getBitFieldIdRow().none() && m_field.get_comm_size() == 0) {
2500 MOFEM_LOG("WORLD", Sev::warning)
2501 << "At least one field has to be added to element row to "
2502 "determine partition of finite element. Check element " +
2503 boost::lexical_cast<std::string>(fe.getName());
2504 }
2505 }
2506
2507 return true;
2508 };
2509
2510 if (check_fields_and_dofs()) {
2511 // Add element to the problem
2512 auto p = problem_finite_elements.insert(
2513 boost::shared_ptr<NumeredEntFiniteElement>(numbered_good_elems_ptr,
2514 &fe));
2515 if (!p.second)
2516 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_FOUND, "element is there");
2517 }
2518 }
2519
2520 if (verb >= VERBOSE) {
2521 auto elements_on_rank =
2522 problem_finite_elements.get<Part_mi_tag>().equal_range(
2523 m_field.get_comm_rank());
2524 MOFEM_LOG("SYNC", Sev::verbose)
2525 << p_miit->getName() << " nb. elems "
2526 << std::distance(elements_on_rank.first, elements_on_rank.second);
2527 auto fe_ptr = m_field.get_finite_elements();
2528 for (auto &fe : *fe_ptr) {
2529 auto e_range =
2530 problem_finite_elements.get<Composite_Name_And_Part_mi_tag>()
2531 .equal_range(
2532 boost::make_tuple(fe->getName(), m_field.get_comm_rank()));
2533 MOFEM_LOG("SYNC", Sev::noisy)
2534 << "Element " << fe->getName() << " nb. elems "
2535 << std::distance(e_range.first, e_range.second);
2536 }
2537
2539 }
2540
2541 cOre.getBuildMoFEM() |= Core::PARTITION_FE;
2543}
2544
2545MoFEMErrorCode ProblemsManager::partitionGhostDofs(const std::string name,
2546 int verb) {
2547 MoFEM::Interface &m_field = cOre;
2548 auto problems_ptr = m_field.get_problems();
2550
2551 if (!(cOre.getBuildMoFEM() & Core::PARTITION_PROBLEM))
2552 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2553 "partition of problem not build");
2554 if (!(cOre.getBuildMoFEM() & Core::PARTITION_FE))
2555 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2556 "partitions finite elements not build");
2557
2558 // get problem pointer
2559 auto p_miit = problems_ptr->get<Problem_mi_tag>().find(name);
2560 if (p_miit == problems_ptr->get<Problem_mi_tag>().end())
2561 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Problem %s not fond",
2562 name.c_str());
2563
2564 // get reference to number of ghost dofs
2565 int &nb_row_ghost_dofs = p_miit->nbGhostDofsRow;
2566 int &nb_col_ghost_dofs = p_miit->nbGhostDofsCol;
2567 nb_row_ghost_dofs = 0;
2568 nb_col_ghost_dofs = 0;
2569
2570 // do work if more than one processor
2571 if (m_field.get_comm_size() > 1) {
2572
2574 ghost_idx_col_view;
2575
2576 // get elements on this partition
2577 auto fe_range =
2578 p_miit->numeredFiniteElementsPtr->get<Part_mi_tag>().equal_range(
2579 m_field.get_comm_rank());
2580
2581 // get dofs on elements which are not part of this partition
2582
2583 struct Inserter {
2584 using Vec = std::vector<boost::shared_ptr<NumeredDofEntity>>;
2585 using It = Vec::iterator;
2586 It operator()(Vec &dofs_view, It &hint,
2587 boost::shared_ptr<NumeredDofEntity> &&dof) {
2588 dofs_view.emplace_back(dof);
2589 return dofs_view.end();
2590 }
2591 };
2592
2593 // rows
2594 std::vector<boost::shared_ptr<NumeredDofEntity>> fe_vec_view;
2595 auto hint_r = ghost_idx_row_view.begin();
2596 for (auto fe_ptr = fe_range.first; fe_ptr != fe_range.second; ++fe_ptr) {
2597
2598 fe_vec_view.clear();
2599 CHKERR EntFiniteElement::getDofView((*fe_ptr)->getRowFieldEnts(),
2600 *(p_miit->getNumeredRowDofsPtr()),
2601 fe_vec_view, Inserter());
2602
2603 for (auto &dof_ptr : fe_vec_view) {
2604 if (dof_ptr->getPart() != (unsigned int)m_field.get_comm_rank()) {
2605 hint_r = ghost_idx_row_view.emplace_hint(hint_r, dof_ptr);
2606 ++hint_r;
2607 }
2608 }
2609 }
2610
2611 // columns
2612 if (p_miit->numeredColDofsPtr == p_miit->numeredRowDofsPtr) {
2613
2614 auto hint_c = ghost_idx_col_view.begin();
2615 for (auto fe_ptr = fe_range.first; fe_ptr != fe_range.second; ++fe_ptr) {
2616
2617 fe_vec_view.clear();
2618 CHKERR EntFiniteElement::getDofView((*fe_ptr)->getColFieldEnts(),
2619 *(p_miit->getNumeredColDofsPtr()),
2620 fe_vec_view, Inserter());
2621
2622 for (auto &dof_ptr : fe_vec_view) {
2623 if (dof_ptr->getPart() != (unsigned int)m_field.get_comm_rank()) {
2624 hint_c = ghost_idx_col_view.emplace_hint(hint_c, dof_ptr);
2625 ++hint_c;
2626 }
2627 }
2628 }
2629 }
2630
2631 int *nb_ghost_dofs[2] = {&nb_row_ghost_dofs, &nb_col_ghost_dofs};
2632 int nb_local_dofs[2] = {p_miit->nbLocDofsRow, p_miit->nbLocDofsCol};
2633
2635 &ghost_idx_row_view, &ghost_idx_col_view};
2636 NumeredDofEntityByUId *dof_by_uid_no_const[2] = {
2637 &p_miit->numeredRowDofsPtr->get<Unique_mi_tag>(),
2638 &p_miit->numeredColDofsPtr->get<Unique_mi_tag>()};
2639
2640 int loop_size = 2;
2641 if (p_miit->numeredColDofsPtr == p_miit->numeredRowDofsPtr) {
2642 loop_size = 1;
2643 }
2644
2645 // set local ghost dofs indices
2646 for (int ss = 0; ss != loop_size; ++ss) {
2647 for (auto &gid : *ghost_idx_view[ss]) {
2648 NumeredDofEntityByUId::iterator dof =
2649 dof_by_uid_no_const[ss]->find(gid->getLocalUniqueId());
2650 if (PetscUnlikely((*dof)->petscLocalDofIdx != (DofIdx)-1))
2651 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2652 "inconsistent data, ghost dof already set");
2653 bool success = dof_by_uid_no_const[ss]->modify(
2654 dof, NumeredDofEntity_local_idx_change(nb_local_dofs[ss]++));
2655 if (PetscUnlikely(!success))
2656 SETERRQ(m_field.get_comm(), MOFEM_OPERATION_UNSUCCESSFUL,
2657 "modification unsuccessful");
2658 (*nb_ghost_dofs[ss])++;
2659 }
2660 }
2661 if (loop_size == 1) {
2662 (*nb_ghost_dofs[1]) = (*nb_ghost_dofs[0]);
2663 }
2664 }
2665
2666 if (verb > QUIET) {
2667 MOFEM_LOG("SYNC", Sev::inform)
2668 << " FEs ghost dofs on problem " << p_miit->getName()
2669 << " Nb. ghost dof " << p_miit->getNbGhostDofsRow() << " by "
2670 << p_miit->getNbGhostDofsCol() << " Nb. local dof "
2671 << p_miit->getNbLocalDofsRow() << " by " << p_miit->getNbLocalDofsCol();
2672
2674 }
2675
2676 cOre.getBuildMoFEM() |= Core::PARTITION_GHOST_DOFS;
2678}
2679
2681ProblemsManager::partitionGhostDofsOnDistributedMesh(const std::string name,
2682 int verb) {
2683 MoFEM::Interface &m_field = cOre;
2684 auto problems_ptr = m_field.get_problems();
2686
2687 if (!(cOre.getBuildMoFEM() & Core::PARTITION_PROBLEM))
2688 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2689 "partition of problem not build");
2690 if (!(cOre.getBuildMoFEM() & Core::PARTITION_FE))
2691 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2692 "partitions finite elements not build");
2693
2694 // get problem pointer
2695 typedef Problem_multiIndex::index<Problem_mi_tag>::type ProblemsByName;
2696 // find p_miit
2697 ProblemsByName &problems_set =
2698 const_cast<ProblemsByName &>(problems_ptr->get<Problem_mi_tag>());
2699 ProblemsByName::iterator p_miit = problems_set.find(name);
2700
2701 // get reference to number of ghost dofs
2702 // get number of local dofs
2703 DofIdx *nb_ghost_dofs[2] = {&(p_miit->nbGhostDofsRow),
2704 &(p_miit->nbGhostDofsCol)};
2705 DofIdx nb_local_dofs[2] = {p_miit->nbLocDofsRow, p_miit->nbLocDofsCol};
2706 for (int ss = 0; ss != 2; ++ss) {
2707 (*nb_ghost_dofs[ss]) = 0;
2708 }
2709
2710 // do work if more than one processor
2711 if (m_field.get_comm_size() > 1) {
2712 // determine if rows on columns are different from dofs on rows
2713 int loop_size = 2;
2714 if (p_miit->numeredColDofsPtr == p_miit->numeredRowDofsPtr) {
2715 loop_size = 1;
2716 }
2717
2718 typedef decltype(p_miit->numeredRowDofsPtr) NumbDofTypeSharedPtr;
2719 NumbDofTypeSharedPtr numered_dofs[] = {p_miit->numeredRowDofsPtr,
2720 p_miit->numeredColDofsPtr};
2721
2722 // iterate over dofs on rows and dofs on columns
2723 for (int ss = 0; ss != loop_size; ++ss) {
2724
2725 // create dofs view by uid
2726 auto r = numered_dofs[ss]->get<PetscLocalIdx_mi_tag>().equal_range(-1);
2727
2728 std::vector<NumeredDofEntity_multiIndex::iterator> ghost_idx_view;
2729 ghost_idx_view.reserve(std::distance(r.first, r.second));
2730 for (; r.first != r.second; ++r.first)
2731 ghost_idx_view.emplace_back(numered_dofs[ss]->project<0>(r.first));
2732
2733 auto cmp = [](auto a, auto b) {
2734 return (*a)->getLocalUniqueId() < (*b)->getLocalUniqueId();
2735 };
2736 sort(ghost_idx_view.begin(), ghost_idx_view.end(), cmp);
2737
2738 // iterate over dofs which have negative local index
2739 for (auto gid_it : ghost_idx_view) {
2740 bool success = numered_dofs[ss]->modify(
2741 gid_it, NumeredDofEntity_local_idx_change((nb_local_dofs[ss])++));
2742 if (!success)
2743 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
2744 "modification unsuccessful");
2745 ++(*nb_ghost_dofs[ss]);
2746 }
2747 }
2748 if (loop_size == 1) {
2749 (*nb_ghost_dofs[1]) = (*nb_ghost_dofs[0]);
2750 }
2751 }
2752
2753 if (verb > QUIET) {
2754 MOFEM_LOG("SYNC", Sev::inform)
2755 << " FEs ghost dofs on problem " << p_miit->getName()
2756 << " Nb. ghost dof " << p_miit->getNbGhostDofsRow() << " by "
2757 << p_miit->getNbGhostDofsCol() << " Nb. local dof "
2758 << p_miit->getNbLocalDofsRow() << " by " << p_miit->getNbLocalDofsCol();
2759
2761 }
2762
2763 cOre.getBuildMoFEM() |= Core::PARTITION_GHOST_DOFS;
2765}
2766
2767MoFEMErrorCode ProblemsManager::getFEMeshset(const std::string prb_name,
2768 const std::string &fe_name,
2769 EntityHandle *meshset) const {
2770 MoFEM::Interface &m_field = cOre;
2771 const Problem *problem_ptr;
2772 const FiniteElement_multiIndex *fes_ptr;
2774
2775 CHKERR m_field.get_moab().create_meshset(MESHSET_SET, *meshset);
2776 CHKERR m_field.get_problem(prb_name, &problem_ptr);
2777 CHKERR m_field.get_finite_elements(&fes_ptr);
2778
2779 auto fe_miit = fes_ptr->get<FiniteElement_name_mi_tag>().find(fe_name);
2780 if (fe_miit != fes_ptr->get<FiniteElement_name_mi_tag>().end()) {
2781 auto fit =
2782 problem_ptr->numeredFiniteElementsPtr->get<Unique_mi_tag>().lower_bound(
2783 EntFiniteElement::getLocalUniqueIdCalculate(
2784 0, (*fe_miit)->getFEUId()));
2785 auto hi_fe_it =
2786 problem_ptr->numeredFiniteElementsPtr->get<Unique_mi_tag>().upper_bound(
2787 EntFiniteElement::getLocalUniqueIdCalculate(
2788 get_id_for_max_type<MBENTITYSET>(), (*fe_miit)->getFEUId()));
2789 std::vector<EntityHandle> fe_vec;
2790 fe_vec.reserve(std::distance(fit, hi_fe_it));
2791 for (; fit != hi_fe_it; fit++)
2792 fe_vec.push_back(fit->get()->getEnt());
2793 CHKERR m_field.get_moab().add_entities(*meshset, &*fe_vec.begin(),
2794 fe_vec.size());
2795 }
2796
2798}
2799
2801ProblemsManager::getProblemElementsLayout(const std::string name,
2802 const std::string &fe_name,
2803 PetscLayout *layout) const {
2804 MoFEM::Interface &m_field = cOre;
2805 const Problem *problem_ptr;
2807 CHKERR m_field.get_problem(name, &problem_ptr);
2808 CHKERR problem_ptr->getNumberOfElementsByNameAndPart(PETSC_COMM_WORLD,
2809 fe_name, layout);
2811}
2812
2813MoFEMErrorCode ProblemsManager::getSideDofsOnBrokenSpaceEntities(
2814
2815 std::vector<boost::weak_ptr<NumeredDofEntity>> &vec_dof_view,
2816
2817 const std::string problem_name, RowColData rc, const std::string field_name,
2818 const Range ents, int bridge_dim, const int lo_coeff, const int hi_coeff,
2819 const int lo_order, const int hi_order, int verb, const bool debug
2820
2821) const {
2822 MoFEM::Interface &m_field = cOre;
2824
2825 switch (rc) {
2826 case ROW:
2827 case COL:
2828 break;
2829 default:
2830 SETERRQ(m_field.get_comm(), MOFEM_INVALID_DATA, "invalid RowColData");
2831 break;
2832 }
2833
2834 const Problem *prb_ptr;
2835 CHKERR m_field.get_problem(problem_name, &prb_ptr);
2836
2837 decltype(prb_ptr->numeredRowDofsPtr) numered_dofs[2] = {
2838 prb_ptr->numeredRowDofsPtr, nullptr};
2839 if (prb_ptr->numeredRowDofsPtr != prb_ptr->numeredColDofsPtr)
2840 numered_dofs[1] = prb_ptr->numeredColDofsPtr;
2841
2842 Range bridge_ents;
2843 CHKERR m_field.get_moab().get_adjacencies(
2844 ents, bridge_dim, false, bridge_ents, moab::Interface::UNION);
2845
2846 auto &moab = m_field.get_moab();
2847 const auto bit_number = m_field.get_field_bit_number(field_name);
2848 const auto nb_coeffs =
2850 const auto &side_dof_map = m_field.get_field_structure(field_name)
2851 ->getDofSideMap();
2852
2853 using NumeredDofEntity_it_view_multiIndex = multi_index_container<
2854
2855 NumeredDofEntity_multiIndex::iterator, indexed_by<sequenced<>>
2856
2857 >;
2858 NumeredDofEntity_it_view_multiIndex dofs_it_view;
2859
2860 for (auto pit = bridge_ents.const_pair_begin();
2861 pit != bridge_ents.const_pair_end(); ++pit) {
2862 auto lo = numered_dofs[rc]->get<Unique_mi_tag>().lower_bound(
2863 DofEntity::getLoFieldEntityUId(bit_number, pit->first));
2864 auto hi = numered_dofs[rc]->get<Unique_mi_tag>().upper_bound(
2865 DofEntity::getHiFieldEntityUId(bit_number, pit->second));
2866
2867 auto bride_type = moab.type_from_handle(pit->first);
2868
2869 for (; lo != hi; ++lo) {
2870 if ((*lo)->getDofCoeffIdx() >= lo_coeff &&
2871 (*lo)->getDofCoeffIdx() <= hi_coeff &&
2872 (*lo)->getDofOrder() >= lo_order &&
2873 (*lo)->getDofOrder() <= hi_order) {
2874 auto ent_dof_index = (*lo)->getEntDofIdx();
2875 auto side_it = side_dof_map.at(bride_type)
2876 .get<EntDofIdx_mi_tag>()
2877 .find(std::floor(static_cast<double>(ent_dof_index) /
2878 nb_coeffs));
2879 if (side_it !=
2880 side_dof_map.at(bride_type).get<EntDofIdx_mi_tag>().end()) {
2881 auto bridge_ent = (*lo)->getEnt();
2882 auto type = side_it->type;
2883 auto side = side_it->side;
2884 auto dim = CN::Dimension(type);
2885 EntityHandle side_ent = 0;
2886 CHKERR moab.side_element(bridge_ent, dim, side, side_ent);
2887 if (ents.find(side_ent) != ents.end()) {
2888 dofs_it_view.emplace_back(numered_dofs[rc]->project<0>(lo));
2889 }
2890 } else {
2891#ifndef NDEBUG
2892 MOFEM_LOG("SELF", Sev::error)
2893 << *m_field.get_field_structure(field_name);
2894 MOFEM_LOG("SELF", Sev::error)
2895 << "side not found for entity " << CN::EntityTypeName(bride_type);
2896 MOFEM_LOG("SELF", Sev::error)
2897 << "ent_dof_index / nb_coeffs "
2898 << std::floor(static_cast<double>(ent_dof_index) / nb_coeffs);
2899 MOFEM_LOG("SELF", Sev::error)
2900 << "side_dof_map.size() " << side_dof_map.size();
2901#endif // NDEBUG
2902 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
2903 "side not found - you will get more information in debug");
2904 }
2905 }
2906 }
2907 }
2908
2909 if (verb > QUIET) {
2910 for (auto &dof : dofs_it_view)
2911 MOFEM_LOG("SYNC", Sev::noisy) << **dof;
2912 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::noisy);
2913 }
2914
2915 vec_dof_view.reserve(vec_dof_view.size() + dofs_it_view.size());
2916 for (auto dit : dofs_it_view)
2917 vec_dof_view.push_back(*dit);
2918
2920}
2921
2922MoFEMErrorCode ProblemsManager::removeDofs(
2923 const std::string problem_name, RowColData rc,
2924 std::vector<boost::weak_ptr<NumeredDofEntity>> &vec_dof_view, int verb,
2925 const bool debug) {
2926
2927 MoFEM::Interface &m_field = cOre;
2929
2930 switch (rc) {
2931 case ROW:
2932 case COL:
2933 break;
2934 default:
2935 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE, "Should be row or column");
2936 }
2937
2938 const Problem *prb_ptr;
2939 CHKERR m_field.get_problem(problem_name, &prb_ptr);
2940
2941 decltype(prb_ptr->numeredRowDofsPtr) numered_dofs[2] = {
2942 prb_ptr->numeredRowDofsPtr, nullptr};
2943 if (prb_ptr->numeredRowDofsPtr != prb_ptr->numeredColDofsPtr)
2944 numered_dofs[1] = prb_ptr->numeredColDofsPtr;
2945
2946 int *nbdof_ptr[] = {&prb_ptr->nbDofsRow, &prb_ptr->nbDofsCol};
2947 int *local_nbdof_ptr[] = {&prb_ptr->nbLocDofsRow, &prb_ptr->nbLocDofsCol};
2948 int *ghost_nbdof_ptr[] = {&prb_ptr->nbGhostDofsRow, &prb_ptr->nbGhostDofsCol};
2949
2950 const int nb_init_row_dofs = prb_ptr->getNbDofsRow();
2951 const int nb_init_col_dofs = prb_ptr->getNbDofsCol();
2952 const int nb_init_loc_row_dofs = prb_ptr->getNbLocalDofsRow();
2953 const int nb_init_ghost_row_dofs = prb_ptr->getNbGhostDofsRow();
2954 const int nb_init_ghost_col_dofs = prb_ptr->getNbGhostDofsCol();
2955
2956 if (numered_dofs[rc]) {
2957
2958 if (verb >= NOISY)
2959 MOFEM_LOG_C("SYNC", Sev::noisy,
2960 "Number of DOFs in multi-index %zu and to delete %zu\n",
2961 numered_dofs[rc]->size(), vec_dof_view.size());
2962
2963 // erase dofs from problem
2964 for (auto weak_dit : vec_dof_view)
2965 if (auto dit = weak_dit.lock()) {
2966 numered_dofs[rc]->erase(dit->getLocalUniqueId());
2967 }
2968
2969 if (verb >= NOISY)
2970 MOFEM_LOG_C("SYNC", Sev::noisy,
2971 "Number of DOFs in multi-index after delete %zu\n",
2972 numered_dofs[rc]->size());
2973
2974 // get current number of ghost dofs
2975 int nb_local_dofs = 0;
2976 int nb_ghost_dofs = 0;
2977 for (auto dit = numered_dofs[rc]->get<PetscLocalIdx_mi_tag>().begin();
2978 dit != numered_dofs[rc]->get<PetscLocalIdx_mi_tag>().end(); ++dit) {
2979 if ((*dit)->getPetscLocalDofIdx() >= 0 &&
2980 (*dit)->getPetscLocalDofIdx() < *(local_nbdof_ptr[rc]))
2981 ++nb_local_dofs;
2982 else if ((*dit)->getPetscLocalDofIdx() >= *(local_nbdof_ptr[rc]))
2983 ++nb_ghost_dofs;
2984 else
2985 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2986 "Impossible case. You could run problem on no distributed "
2987 "mesh. That is not implemented. Dof local index is %d",
2988 (*dit)->getPetscLocalDofIdx());
2989 }
2990
2991 // get indices
2992 auto get_indices_by_tag = [&](auto tag, auto &indices, bool only_local) {
2993 const int nb_dofs = numered_dofs[rc]->size();
2994 indices.clear();
2995 indices.reserve(nb_dofs);
2996 for (auto dit = numered_dofs[rc]->get<decltype(tag)>().begin();
2997 dit != numered_dofs[rc]->get<decltype(tag)>().end(); ++dit) {
2998 bool add = true;
2999 if (only_local) {
3000 if ((*dit)->getPetscLocalDofIdx() < 0 ||
3001 (*dit)->getPetscLocalDofIdx() >= *(local_nbdof_ptr[rc])) {
3002 add = false;
3003 }
3004 }
3005 if (add)
3006 indices.push_back(decltype(tag)::get_index(dit));
3007 }
3008 };
3009
3010 auto get_indices_by_uid = [&](auto tag, auto &indices) {
3011 const int nb_dofs = numered_dofs[rc]->size();
3012 indices.clear();
3013 indices.reserve(nb_dofs);
3014 for (auto dit = numered_dofs[rc]->begin(); dit != numered_dofs[rc]->end();
3015 ++dit)
3016 indices.push_back(decltype(tag)::get_index(dit));
3017 };
3018
3019 auto get_sub_ao = [&](auto sub_data) {
3020 if (rc == 0) {
3021 return sub_data->getSmartRowMap();
3022 } else {
3023 return sub_data->getSmartColMap();
3024 }
3025 };
3026
3027 auto set_sub_is_and_ao = [&rc, &prb_ptr](auto sub_data, auto is, auto ao) {
3028 if (rc == ROW) {
3029 sub_data->rowIs = is;
3030 sub_data->rowMap = ao;
3031 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3032 sub_data->colIs = is;
3033 sub_data->colMap = ao;
3034 }
3035 } else {
3036 sub_data->colIs = is;
3037 sub_data->colMap = ao;
3038 }
3039 };
3040
3041 auto apply_symmetry = [&rc, &prb_ptr](auto sub_data) {
3042 if (rc == ROW) {
3043 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3044 sub_data->colIs = sub_data->getSmartRowIs();
3045 sub_data->colMap = sub_data->getSmartRowMap();
3046 }
3047 }
3048 };
3049
3050 auto concatenate_dofs = [&](auto tag, auto &indices,
3051 const auto local_only) {
3053 get_indices_by_tag(tag, indices, local_only);
3054
3055 auto indices_ptr = [](auto &indices) {
3056 return indices.empty() ? nullptr : indices.data();
3057 };
3058
3059 SmartPetscObj<AO> ao;
3060 // Create AO from app indices (i.e. old), to pestc indices (new after
3061 // remove)
3062 if (local_only)
3063 ao = createAOMapping(m_field.get_comm(), indices.size(),
3064 indices_ptr(indices), PETSC_NULLPTR);
3065 else
3066 ao = createAOMapping(PETSC_COMM_SELF, indices.size(),
3067 indices_ptr(indices), PETSC_NULLPTR);
3068
3069 // Set mapping to sub dm data
3070 if (local_only) {
3071 if (auto sub_data = prb_ptr->getSubData()) {
3072 // create is and then map it to main problem of sub-problem
3073 auto sub_is = createISGeneral(m_field.get_comm(), indices.size(),
3074 indices_ptr(indices), PETSC_COPY_VALUES);
3075 // get old app, i.e. oroginal befor sub indices, and ao, from app,
3076 // to petsc sub indices.
3077 auto sub_ao = get_sub_ao(sub_data);
3078 if (sub_ao.get()) {
3079 CHKERR AOPetscToApplicationIS(sub_ao, sub_is);
3080 sub_ao = createAOMappingIS(sub_is, PETSC_NULLPTR);
3081 } else {
3082 sub_ao = ao;
3083 }
3084 // set new sub ao
3085 set_sub_is_and_ao(sub_data, sub_is, sub_ao);
3086 apply_symmetry(sub_data);
3087 } else {
3088 // create sub data
3089 prb_ptr->getSubData() = boost::make_shared<Problem::SubProblemData>();
3090 auto sub_is = createISGeneral(m_field.get_comm(), indices.size(),
3091 indices_ptr(indices), PETSC_COPY_VALUES);
3092 // set sub is ao
3093 set_sub_is_and_ao(prb_ptr->getSubData(), sub_is, ao);
3094 apply_symmetry(prb_ptr->getSubData());
3095 }
3096 }
3097
3098 get_indices_by_uid(tag, indices);
3099 CHKERR AOApplicationToPetsc(ao, indices.size(), indices_ptr(indices));
3100
3102 };
3103
3104 // set indices index
3105 auto set_concatenated_indices = [&]() {
3106 std::vector<int> global_indices;
3107 std::vector<int> local_indices;
3109 CHKERR concatenate_dofs(PetscGlobalIdx_mi_tag(), global_indices, true);
3110 CHKERR concatenate_dofs(PetscLocalIdx_mi_tag(), local_indices, false);
3111 auto gi = global_indices.begin();
3112 auto li = local_indices.begin();
3113 for (auto dit = numered_dofs[rc]->begin(); dit != numered_dofs[rc]->end();
3114 ++dit) {
3115 auto mod = NumeredDofEntity_part_and_indices_change(
3116 (*dit)->getPart(), *gi, *li);
3117 bool success = numered_dofs[rc]->modify(dit, mod);
3118 if (!success)
3119 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3120 "can not set negative indices");
3121 ++gi;
3122 ++li;
3123 }
3125 };
3126 CHKERR set_concatenated_indices();
3127
3128 MPI_Allreduce(&nb_local_dofs, nbdof_ptr[rc], 1, MPI_INT, MPI_SUM,
3129 m_field.get_comm());
3130 *(local_nbdof_ptr[rc]) = nb_local_dofs;
3131 *(ghost_nbdof_ptr[rc]) = nb_ghost_dofs;
3132
3133 if (debug)
3134 for (auto dof : (*numered_dofs[rc])) {
3135 if (dof->getPetscGlobalDofIdx() < 0) {
3136 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
3137 "Negative global idx");
3138 }
3139 if (dof->getPetscLocalDofIdx() < 0) {
3140 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
3141 "Negative local idx");
3142 }
3143 }
3144
3145 } else {
3146
3147 *(nbdof_ptr[1]) = *(nbdof_ptr[0]);
3148 *(local_nbdof_ptr[1]) = *(local_nbdof_ptr[0]);
3149 *(ghost_nbdof_ptr[1]) = *(ghost_nbdof_ptr[0]);
3150 }
3151
3152 if (verb > QUIET) {
3154 "WORLD", Sev::inform,
3155 "Removed DOFs from problem %s dofs [%d / %d (before %d / %d) global]",
3156 prb_ptr->getName().c_str(), prb_ptr->getNbDofsRow(),
3157 prb_ptr->getNbDofsCol(), nb_init_row_dofs, nb_init_col_dofs);
3158 MOFEM_LOG_C("SYNC", Sev::verbose,
3159 "Removed DOFs from problem %s dofs [ %d / %d "
3160 "(before %d / %d) local, %d / %d (before %d / %d)]",
3161 prb_ptr->getName().c_str(), prb_ptr->getNbLocalDofsRow(),
3162 prb_ptr->getNbLocalDofsCol(), nb_init_loc_row_dofs,
3163 nb_init_loc_row_dofs, prb_ptr->getNbGhostDofsRow(),
3164 prb_ptr->getNbGhostDofsCol(), nb_init_ghost_row_dofs,
3165 nb_init_ghost_col_dofs);
3166 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
3167 }
3168
3170}
3171
3172MoFEMErrorCode ProblemsManager::removeDofsOnEntities(
3173 const std::string problem_name, const std::string field_name,
3174 const Range ents, const int lo_coeff, const int hi_coeff,
3175 const int lo_order, const int hi_order, int verb, const bool debug) {
3176
3177 MoFEM::Interface &m_field = cOre;
3179
3180 const Problem *prb_ptr;
3181 CHKERR m_field.get_problem(problem_name, &prb_ptr);
3182
3183 decltype(prb_ptr->numeredRowDofsPtr) numered_dofs[2] = {
3184 prb_ptr->numeredRowDofsPtr, nullptr};
3185 if (prb_ptr->numeredRowDofsPtr != prb_ptr->numeredColDofsPtr)
3186 numered_dofs[1] = prb_ptr->numeredColDofsPtr;
3187
3188 int *nbdof_ptr[] = {&prb_ptr->nbDofsRow, &prb_ptr->nbDofsCol};
3189 int *local_nbdof_ptr[] = {&prb_ptr->nbLocDofsRow, &prb_ptr->nbLocDofsCol};
3190 int *ghost_nbdof_ptr[] = {&prb_ptr->nbGhostDofsRow, &prb_ptr->nbGhostDofsCol};
3191
3192 const int nb_init_row_dofs = prb_ptr->getNbDofsRow();
3193 const int nb_init_col_dofs = prb_ptr->getNbDofsCol();
3194 const int nb_init_loc_row_dofs = prb_ptr->getNbLocalDofsRow();
3195 const int nb_init_loc_col_dofs = prb_ptr->getNbLocalDofsCol();
3196 const int nb_init_ghost_row_dofs = prb_ptr->getNbGhostDofsRow();
3197 const int nb_init_ghost_col_dofs = prb_ptr->getNbGhostDofsCol();
3198
3199 for (int s = 0; s != 2; ++s)
3200 if (numered_dofs[s]) {
3201
3202 using NumeredDofEntity_it_view_multiIndex = multi_index_container<
3203
3204 NumeredDofEntity_multiIndex::iterator, indexed_by<sequenced<>>
3205
3206 >;
3207
3208 const auto bit_number = m_field.get_field_bit_number(field_name);
3209 NumeredDofEntity_it_view_multiIndex dofs_it_view;
3210
3211 // Set -1 to global and local dofs indices
3212 for (auto pit = ents.const_pair_begin(); pit != ents.const_pair_end();
3213 ++pit) {
3214 auto lo = numered_dofs[s]->get<Unique_mi_tag>().lower_bound(
3215 DofEntity::getLoFieldEntityUId(bit_number, pit->first));
3216 auto hi = numered_dofs[s]->get<Unique_mi_tag>().upper_bound(
3217 DofEntity::getHiFieldEntityUId(bit_number, pit->second));
3218
3219 for (; lo != hi; ++lo)
3220 if ((*lo)->getDofCoeffIdx() >= lo_coeff &&
3221 (*lo)->getDofCoeffIdx() <= hi_coeff &&
3222 (*lo)->getDofOrder() >= lo_order &&
3223 (*lo)->getDofOrder() <= hi_order)
3224 dofs_it_view.emplace_back(numered_dofs[s]->project<0>(lo));
3225 }
3226
3227 if (verb > QUIET) {
3228 for (auto &dof : dofs_it_view)
3229 MOFEM_LOG("SYNC", Sev::noisy) << **dof;
3230 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::noisy);
3231 }
3232
3233 // create weak view
3234 std::vector<boost::weak_ptr<NumeredDofEntity>> dofs_weak_view;
3235 dofs_weak_view.reserve(dofs_it_view.size());
3236 for (auto dit : dofs_it_view)
3237 dofs_weak_view.push_back(*dit);
3238
3239 if (verb >= NOISY)
3240 MOFEM_LOG_C("SYNC", Sev::noisy,
3241 "Number of DOFs in multi-index %zu and to delete %zu\n",
3242 numered_dofs[s]->size(), dofs_it_view.size());
3243
3244 // erase dofs from problem
3245 for (auto weak_dit : dofs_weak_view)
3246 if (auto dit = weak_dit.lock()) {
3247 numered_dofs[s]->erase(dit->getLocalUniqueId());
3248 }
3249
3250 if (verb >= NOISY)
3251 MOFEM_LOG_C("SYNC", Sev::noisy,
3252 "Number of DOFs in multi-index after delete %zu\n",
3253 numered_dofs[s]->size());
3254
3255 // get current number of ghost dofs
3256 int nb_local_dofs = 0;
3257 int nb_ghost_dofs = 0;
3258 for (auto dit = numered_dofs[s]->get<PetscLocalIdx_mi_tag>().begin();
3259 dit != numered_dofs[s]->get<PetscLocalIdx_mi_tag>().end(); ++dit) {
3260 if ((*dit)->getPetscLocalDofIdx() >= 0 &&
3261 (*dit)->getPetscLocalDofIdx() < *(local_nbdof_ptr[s]))
3262 ++nb_local_dofs;
3263 else if ((*dit)->getPetscLocalDofIdx() >= *(local_nbdof_ptr[s]))
3264 ++nb_ghost_dofs;
3265 else
3266 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3267 "Impossible case. You could run problem on no distributed "
3268 "mesh. That is not implemented. Dof local index is %d",
3269 (*dit)->getPetscLocalDofIdx());
3270 }
3271
3272 // get indices
3273 auto get_indices_by_tag = [&](auto tag, auto &indices, bool only_local) {
3274 const int nb_dofs = numered_dofs[s]->size();
3275 indices.clear();
3276 indices.reserve(nb_dofs);
3277 for (auto dit = numered_dofs[s]->get<decltype(tag)>().begin();
3278 dit != numered_dofs[s]->get<decltype(tag)>().end(); ++dit) {
3279 bool add = true;
3280 if (only_local) {
3281 if ((*dit)->getPetscLocalDofIdx() < 0 ||
3282 (*dit)->getPetscLocalDofIdx() >= *(local_nbdof_ptr[s])) {
3283 add = false;
3284 }
3285 }
3286 if (add)
3287 indices.push_back(decltype(tag)::get_index(dit));
3288 }
3289 };
3290
3291 auto get_indices_by_uid = [&](auto tag, auto &indices) {
3292 const int nb_dofs = numered_dofs[s]->size();
3293 indices.clear();
3294 indices.reserve(nb_dofs);
3295 for (auto dit = numered_dofs[s]->begin(); dit != numered_dofs[s]->end();
3296 ++dit)
3297 indices.push_back(decltype(tag)::get_index(dit));
3298 };
3299
3300 auto get_sub_ao = [&](auto sub_data) {
3301 if (s == 0) {
3302 return sub_data->getSmartRowMap();
3303 } else {
3304 return sub_data->getSmartColMap();
3305 }
3306 };
3307
3308 auto set_sub_is_and_ao = [&s, &prb_ptr](auto sub_data, auto is, auto ao) {
3309 if (s == 0) {
3310 sub_data->rowIs = is;
3311 sub_data->rowMap = ao;
3312 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3313 sub_data->colIs = is;
3314 sub_data->colMap = ao;
3315 }
3316 } else {
3317 sub_data->colIs = is;
3318 sub_data->colMap = ao;
3319 }
3320 };
3321
3322 auto apply_symmetry = [&s, &prb_ptr](auto sub_data) {
3323 if (s == 0) {
3324 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3325 sub_data->colIs = sub_data->getSmartRowIs();
3326 sub_data->colMap = sub_data->getSmartRowMap();
3327 }
3328 }
3329 };
3330
3331 auto concatenate_dofs = [&](auto tag, auto &indices,
3332 const auto local_only) {
3334 get_indices_by_tag(tag, indices, local_only);
3335
3336 auto indices_ptr = [](auto &indices) {
3337 return indices.empty() ? nullptr : indices.data();
3338 };
3339
3340 SmartPetscObj<AO> ao;
3341 // Create AO from app indices (i.e. old), to pestc indices (new after
3342 // remove)
3343 if (local_only)
3344 ao = createAOMapping(m_field.get_comm(), indices.size(),
3345 indices_ptr(indices), PETSC_NULLPTR);
3346 else
3347 ao = createAOMapping(PETSC_COMM_SELF, indices.size(),
3348 indices_ptr(indices), PETSC_NULLPTR);
3349
3350 // Set mapping to sub dm data
3351 if (local_only) {
3352 if (auto sub_data = prb_ptr->getSubData()) {
3353 // create is and then map it to main problem of sub-problem
3354 auto sub_is =
3355 createISGeneral(m_field.get_comm(), indices.size(),
3356 indices_ptr(indices), PETSC_COPY_VALUES);
3357 // get old app, i.e. oroginal befor sub indices, and ao, from app,
3358 // to petsc sub indices.
3359 auto sub_ao = get_sub_ao(sub_data);
3360 if (sub_ao.get()) {
3361 CHKERR AOPetscToApplicationIS(sub_ao, sub_is);
3362 sub_ao = createAOMappingIS(sub_is, PETSC_NULLPTR);
3363 } else {
3364 sub_ao = ao;
3365 }
3366 // set new sub ao
3367 set_sub_is_and_ao(sub_data, sub_is, sub_ao);
3368 apply_symmetry(sub_data);
3369 } else {
3370 // create sub data
3371 prb_ptr->getSubData() =
3372 boost::make_shared<Problem::SubProblemData>();
3373 auto sub_is =
3374 createISGeneral(m_field.get_comm(), indices.size(),
3375 indices_ptr(indices), PETSC_COPY_VALUES);
3376 // set sub is ao
3377 set_sub_is_and_ao(prb_ptr->getSubData(), sub_is, ao);
3378 apply_symmetry(prb_ptr->getSubData());
3379 }
3380 }
3381
3382 get_indices_by_uid(tag, indices);
3383 CHKERR AOApplicationToPetsc(ao, indices.size(), indices_ptr(indices));
3384
3386 };
3387
3388 // set indices index
3389 auto set_concatenated_indices = [&]() {
3390 std::vector<int> global_indices;
3391 std::vector<int> local_indices;
3393 CHKERR concatenate_dofs(PetscGlobalIdx_mi_tag(), global_indices, true);
3394 CHKERR concatenate_dofs(PetscLocalIdx_mi_tag(), local_indices, false);
3395 auto gi = global_indices.begin();
3396 auto li = local_indices.begin();
3397 for (auto dit = numered_dofs[s]->begin(); dit != numered_dofs[s]->end();
3398 ++dit) {
3399 auto mod = NumeredDofEntity_part_and_indices_change(
3400 (*dit)->getPart(), *gi, *li);
3401 bool success = numered_dofs[s]->modify(dit, mod);
3402 if (!success)
3403 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3404 "can not set negative indices");
3405 ++gi;
3406 ++li;
3407 }
3409 };
3410 CHKERR set_concatenated_indices();
3411
3412 MPI_Allreduce(&nb_local_dofs, nbdof_ptr[s], 1, MPI_INT, MPI_SUM,
3413 m_field.get_comm());
3414 *(local_nbdof_ptr[s]) = nb_local_dofs;
3415 *(ghost_nbdof_ptr[s]) = nb_ghost_dofs;
3416
3417 if (debug)
3418 for (auto dof : (*numered_dofs[s])) {
3419 if (dof->getPetscGlobalDofIdx() < 0) {
3420 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
3421 "Negative global idx");
3422 }
3423 if (dof->getPetscLocalDofIdx() < 0) {
3424 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
3425 "Negative local idx");
3426 }
3427 }
3428
3429 } else {
3430
3431 *(nbdof_ptr[1]) = *(nbdof_ptr[0]);
3432 *(local_nbdof_ptr[1]) = *(local_nbdof_ptr[0]);
3433 *(ghost_nbdof_ptr[1]) = *(ghost_nbdof_ptr[0]);
3434 }
3435
3436 if (verb > QUIET) {
3438 "WORLD", Sev::inform,
3439 "Removed DOFs from problem %s dofs [%d / %d (before %d / %d) global]",
3440 prb_ptr->getName().c_str(), prb_ptr->getNbDofsRow(),
3441 prb_ptr->getNbDofsCol(), nb_init_row_dofs, nb_init_col_dofs);
3442 MOFEM_LOG_C("SYNC", Sev::verbose,
3443 "Removed DOFs from problem %s dofs [ %d / %d "
3444 "(before %d / %d) local, %d / %d (before %d / %d)]",
3445 prb_ptr->getName().c_str(), prb_ptr->getNbLocalDofsRow(),
3446 prb_ptr->getNbLocalDofsCol(), nb_init_loc_row_dofs,
3447 nb_init_loc_col_dofs, prb_ptr->getNbGhostDofsRow(),
3448 prb_ptr->getNbGhostDofsCol(), nb_init_ghost_row_dofs,
3449 nb_init_ghost_col_dofs);
3450 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
3451 }
3452
3454}
3455
3456MoFEMErrorCode ProblemsManager::removeDofsOnEntitiesNotDistributed(
3457 const std::string problem_name, const std::string field_name,
3458 const Range ents, const int lo_coeff, const int hi_coeff,
3459 const int lo_order, const int hi_order, int verb, const bool debug) {
3460
3461 MoFEM::Interface &m_field = cOre;
3463
3464 const Problem *prb_ptr;
3465 CHKERR m_field.get_problem(problem_name, &prb_ptr);
3466
3467 decltype(prb_ptr->numeredRowDofsPtr) numered_dofs[2] = {
3468 prb_ptr->numeredRowDofsPtr, nullptr};
3469 if (prb_ptr->numeredRowDofsPtr != prb_ptr->numeredColDofsPtr)
3470 numered_dofs[1] = prb_ptr->numeredColDofsPtr;
3471
3472 int *nbdof_ptr[] = {&prb_ptr->nbDofsRow, &prb_ptr->nbDofsCol};
3473 int *local_nbdof_ptr[] = {&prb_ptr->nbLocDofsRow, &prb_ptr->nbLocDofsCol};
3474 int *ghost_nbdof_ptr[] = {&prb_ptr->nbGhostDofsRow, &prb_ptr->nbGhostDofsCol};
3475
3476 const int nb_init_row_dofs = prb_ptr->getNbDofsRow();
3477 const int nb_init_col_dofs = prb_ptr->getNbDofsCol();
3478 const int nb_init_loc_row_dofs = prb_ptr->getNbLocalDofsRow();
3479 // const int nb_init_loc_col_dofs = prb_ptr->getNbLocalDofsCol();
3480 const int nb_init_ghost_row_dofs = prb_ptr->getNbGhostDofsRow();
3481 const int nb_init_ghost_col_dofs = prb_ptr->getNbGhostDofsCol();
3482
3483 const std::array<int, 2> nb_init_dofs = {nb_init_row_dofs, nb_init_col_dofs};
3484
3485 for (int s = 0; s != 2; ++s)
3486 if (numered_dofs[s]) {
3487
3488 typedef multi_index_container<
3489
3490 NumeredDofEntity_multiIndex::iterator, indexed_by<sequenced<>>
3491
3492 >
3493 NumeredDofEntity_it_view_multiIndex;
3494
3495 const auto bit_number = m_field.get_field_bit_number(field_name);
3496 NumeredDofEntity_it_view_multiIndex dofs_it_view;
3497
3498 // Set -1 to global and local dofs indices
3499 for (auto pit = ents.const_pair_begin(); pit != ents.const_pair_end();
3500 ++pit) {
3501 auto lo = numered_dofs[s]->get<Unique_mi_tag>().lower_bound(
3502 DofEntity::getLoFieldEntityUId(bit_number, pit->first));
3503 auto hi = numered_dofs[s]->get<Unique_mi_tag>().upper_bound(
3504 DofEntity::getHiFieldEntityUId(bit_number, pit->second));
3505
3506 for (; lo != hi; ++lo)
3507 if ((*lo)->getDofCoeffIdx() >= lo_coeff &&
3508 (*lo)->getDofCoeffIdx() <= hi_coeff &&
3509 (*lo)->getDofOrder() >= lo_order &&
3510 (*lo)->getDofOrder() <= hi_order)
3511 dofs_it_view.emplace_back(numered_dofs[s]->project<0>(lo));
3512 }
3513
3514 if (verb > QUIET) {
3515 for (auto &dof : dofs_it_view)
3516 MOFEM_LOG("SYNC", Sev::noisy) << **dof;
3517 }
3518
3519 // set negative index
3520 auto mod = NumeredDofEntity_part_and_indices_change(-1, -1, -1);
3521 for (auto dit : dofs_it_view) {
3522 bool success = numered_dofs[s]->modify(dit, mod);
3523 if (!success)
3524 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3525 "can not set negative indices");
3526 }
3527
3528 // create weak view
3529 std::vector<boost::weak_ptr<NumeredDofEntity>> dosf_weak_view;
3530 dosf_weak_view.reserve(dofs_it_view.size());
3531 for (auto dit : dofs_it_view)
3532 dosf_weak_view.push_back(*dit);
3533
3534 if (verb >= NOISY)
3535 MOFEM_LOG_C("SYNC", Sev::noisy,
3536 "Number of DOFs in multi-index %zu and to delete %zu\n",
3537 numered_dofs[s]->size(), dofs_it_view.size());
3538
3539 // erase dofs from problem
3540 for (auto weak_dit : dosf_weak_view)
3541 if (auto dit = weak_dit.lock()) {
3542 numered_dofs[s]->erase(dit->getLocalUniqueId());
3543 }
3544
3545 if (verb >= NOISY)
3546 MOFEM_LOG_C("SYNC", Sev::noisy,
3547 "Number of DOFs in multi-index after delete %zu\n",
3548 numered_dofs[s]->size());
3549
3550 // get current number of ghost dofs
3551 int nb_global_dof = 0;
3552 int nb_local_dofs = 0;
3553 int nb_ghost_dofs = 0;
3554
3555 for (auto dit = numered_dofs[s]->begin(); dit != numered_dofs[s]->end();
3556 ++dit) {
3557
3558 if ((*dit)->getPetscGlobalDofIdx() >= 0) {
3559
3560 if ((*dit)->getPetscLocalDofIdx() >= 0 &&
3561 (*dit)->getPetscLocalDofIdx() < *(local_nbdof_ptr[s]))
3562 ++nb_local_dofs;
3563 else if ((*dit)->getPetscLocalDofIdx() >= *(local_nbdof_ptr[s]))
3564 ++nb_ghost_dofs;
3565
3566 ++nb_global_dof;
3567 }
3568 }
3569
3570 if (debug) {
3571 MPI_Allreduce(&nb_local_dofs, nbdof_ptr[s], 1, MPI_INT, MPI_SUM,
3572 m_field.get_comm());
3573 if (*(nbdof_ptr[s]) != nb_global_dof)
3574 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3575 "Number of local DOFs do not add up %d != %d",
3576 *(nbdof_ptr[s]), nb_global_dof);
3577 }
3578
3579 *(nbdof_ptr[s]) = nb_global_dof;
3580 *(local_nbdof_ptr[s]) = nb_local_dofs;
3581 *(ghost_nbdof_ptr[s]) = nb_ghost_dofs;
3582
3583 // Indices in slots of the global index before renumbering. The slots
3584 // are sized by the global count: on a replicated mesh DOFs of other
3585 // parts have a global index but no local index.
3586 auto get_indices_by_tag = [&](auto tag) {
3587 std::vector<int> indices;
3588 indices.resize(nb_init_dofs[s], -1);
3589 for (auto dit =
3590 numered_dofs[s]->get<PetscGlobalIdx_mi_tag>().lower_bound(0);
3591 dit != numered_dofs[s]->get<PetscGlobalIdx_mi_tag>().end();
3592 ++dit) {
3593 indices[(*dit)->getPetscGlobalDofIdx()] =
3594 decltype(tag)::get_index(dit);
3595 }
3596 return indices;
3597 };
3598
3599 auto renumber = [&](auto tag, auto &indices) {
3601 int idx = 0;
3602 for (auto dit = numered_dofs[s]->get<decltype(tag)>().lower_bound(0);
3603 dit != numered_dofs[s]->get<decltype(tag)>().end(); ++dit) {
3604 indices[(*dit)->getPetscGlobalDofIdx()] = idx++;
3605 }
3607 };
3608
3609 auto get_sub_ao = [&](auto sub_data) {
3610 if (s == 0) {
3611 return sub_data->getSmartRowMap();
3612 } else {
3613 return sub_data->getSmartColMap();
3614 }
3615 };
3616
3617 auto set_sub_is_and_ao = [&s, &prb_ptr](auto sub_data, auto is, auto ao) {
3618 if (s == 0) {
3619 sub_data->rowIs = is;
3620 sub_data->rowMap = ao;
3621 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3622 sub_data->colIs = is;
3623 sub_data->colMap = ao;
3624 }
3625 } else {
3626 sub_data->colIs = is;
3627 sub_data->colMap = ao;
3628 }
3629 };
3630
3631 auto apply_symmetry = [&s, &prb_ptr](auto sub_data) {
3632 if (s == 0) {
3633 if (prb_ptr->numeredRowDofsPtr == prb_ptr->numeredColDofsPtr) {
3634 sub_data->colIs = sub_data->getSmartRowIs();
3635 sub_data->colMap = sub_data->getSmartRowMap();
3636 }
3637 }
3638 };
3639
3640 auto set_sub_data = [&](auto &indices) {
3642 auto indices_ptr = [](auto &indices) {
3643 return indices.empty() ? nullptr : indices.data();
3644 };
3645 if (auto sub_data = prb_ptr->getSubData()) {
3646 // create is and then map it to main problem of sub-problem
3647 auto sub_is = createISGeneral(m_field.get_comm(), indices.size(),
3648 indices_ptr(indices), PETSC_COPY_VALUES);
3649 // get old app, i.e. oroginal befor sub indices, and ao, from
3650 // app, to petsc sub indices.
3651 auto sub_ao = get_sub_ao(sub_data);
3652 if (sub_ao.get())
3653 CHKERR AOPetscToApplicationIS(sub_ao, sub_is);
3654 sub_ao = createAOMappingIS(sub_is, PETSC_NULLPTR);
3655 // set new sub ao
3656 set_sub_is_and_ao(sub_data, sub_is, sub_ao);
3657 apply_symmetry(sub_data);
3658 } else {
3659 prb_ptr->getSubData() = boost::make_shared<Problem::SubProblemData>();
3660 auto sub_is = createISGeneral(m_field.get_comm(), indices.size(),
3661 indices_ptr(indices), PETSC_COPY_VALUES);
3662 auto sub_ao = createAOMappingIS(sub_is, PETSC_NULLPTR);
3663 // set sub is ao
3664 set_sub_is_and_ao(prb_ptr->getSubData(), sub_is, sub_ao);
3665 apply_symmetry(prb_ptr->getSubData());
3666 }
3668 };
3669
3670 auto global_indices = get_indices_by_tag(PetscGlobalIdx_mi_tag());
3671 auto local_indices = get_indices_by_tag(PetscLocalIdx_mi_tag());
3672 CHKERR set_sub_data(global_indices);
3673 CHKERR renumber(PetscGlobalIdx_mi_tag(), global_indices);
3674 CHKERR renumber(PetscLocalIdx_mi_tag(), local_indices);
3675
3676 for (auto dit = numered_dofs[s]->begin(); dit != numered_dofs[s]->end();
3677 ++dit) {
3678 const auto idx = (*dit)->getPetscGlobalDofIdx();
3679 if (idx >= 0) {
3680 auto mod = NumeredDofEntity_part_and_indices_change(
3681 (*dit)->getPart(), global_indices[idx], local_indices[idx]);
3682 bool success = numered_dofs[s]->modify(dit, mod);
3683 if (!success)
3684 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3685 "can not set negative indices");
3686 } else {
3687 auto mod = NumeredDofEntity_part_and_indices_change(
3688 (*dit)->getPart(), -1, -1);
3689 bool success = numered_dofs[s]->modify(dit, mod);
3690 if (!success)
3691 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
3692 "can not set negative indices");
3693 }
3694 };
3695
3696 if (debug) {
3697 for (auto dof : (*numered_dofs[s])) {
3698 if (dof->getPetscGlobalDofIdx() >= *(nbdof_ptr[s])) {
3699 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
3700 "Global idx out of range");
3701 }
3702 }
3703 }
3704
3705 } else {
3706
3707 *(nbdof_ptr[1]) = *(nbdof_ptr[0]);
3708 *(local_nbdof_ptr[1]) = *(local_nbdof_ptr[0]);
3709 *(ghost_nbdof_ptr[1]) = *(ghost_nbdof_ptr[0]);
3710 }
3711
3712 if (verb >= NOISY)
3714
3715 if (verb > QUIET) {
3717 "WORLD", Sev::inform,
3718 "Removed DOFs from problem %s dofs [%d / %d (before %d / %d) global]",
3719 prb_ptr->getName().c_str(), prb_ptr->getNbDofsRow(),
3720 prb_ptr->getNbDofsCol(), nb_init_row_dofs, nb_init_col_dofs);
3721 MOFEM_LOG_C("SYNC", Sev::verbose,
3722 "Removed DOFs from problem %s dofs [ %d / %d "
3723 "(before %d / %d) local, %d / %d (before %d / %d)]",
3724 prb_ptr->getName().c_str(), prb_ptr->getNbLocalDofsRow(),
3725 prb_ptr->getNbLocalDofsCol(), nb_init_loc_row_dofs,
3726 nb_init_loc_row_dofs, prb_ptr->getNbGhostDofsRow(),
3727 prb_ptr->getNbGhostDofsCol(), nb_init_ghost_row_dofs,
3728 nb_init_ghost_col_dofs);
3730 }
3732}
3733
3734MoFEMErrorCode ProblemsManager::removeDofsOnEntities(
3735 const std::string problem_name, const std::string field_name,
3736 const BitRefLevel bit_ref_level, const BitRefLevel bit_ref_mask,
3737 Range *ents_ptr, const int lo_coeff, const int hi_coeff, const int lo_order,
3738 const int hi_order, int verb, const bool debug) {
3739 MoFEM::Interface &m_field = cOre;
3741
3742 auto bit_manager = m_field.getInterface<BitRefManager>();
3743
3744 Range ents;
3745 if (ents_ptr) {
3746 ents = *ents_ptr;
3747 CHKERR bit_manager->filterEntitiesByRefLevel(bit_ref_level, bit_ref_mask,
3748 ents, verb);
3749 } else {
3750 CHKERR bit_manager->getEntitiesByRefLevel(bit_ref_level, bit_ref_mask, ents,
3751 verb);
3752 }
3753
3754 CHKERR removeDofsOnEntities(problem_name, field_name, ents, lo_coeff,
3755 hi_coeff, lo_order, hi_order, verb, debug);
3756
3758}
3759
3760MoFEMErrorCode ProblemsManager::removeDofsOnEntitiesNotDistributed(
3761 const std::string problem_name, const std::string field_name,
3762 const BitRefLevel bit_ref_level, const BitRefLevel bit_ref_mask,
3763 Range *ents_ptr, const int lo_coeff, const int hi_coeff, const int lo_order,
3764 const int hi_order, int verb, const bool debug) {
3765 MoFEM::Interface &m_field = cOre;
3767
3768 auto bit_manager = m_field.getInterface<BitRefManager>();
3769
3770 Range ents;
3771 if (ents_ptr) {
3772 ents = *ents_ptr;
3773 CHKERR bit_manager->filterEntitiesByRefLevel(bit_ref_level, bit_ref_mask,
3774 ents, verb);
3775 } else {
3776 CHKERR bit_manager->getEntitiesByRefLevel(bit_ref_level, bit_ref_mask, ents,
3777 verb);
3778 }
3779
3780 CHKERR removeDofsOnEntitiesNotDistributed(problem_name, field_name, ents,
3781 lo_coeff, hi_coeff, lo_order,
3782 hi_order, verb, debug);
3783
3785}
3786
3788ProblemsManager::markDofs(const std::string problem_name, RowColData rc,
3789 const enum MarkOP op, const Range ents,
3790 std::vector<unsigned char> &marker) const {
3791
3792 Interface &m_field = cOre;
3793 const Problem *problem_ptr;
3795 CHKERR m_field.get_problem(problem_name, &problem_ptr);
3796 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs;
3797 switch (rc) {
3798 case ROW:
3799 dofs = problem_ptr->getNumeredRowDofsPtr();
3800 break;
3801 case COL:
3802 dofs = problem_ptr->getNumeredColDofsPtr();
3803 default:
3804 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE, "Should be row or column");
3805 }
3806 marker.resize(dofs->size(), 0);
3807 std::vector<unsigned char> marker_tmp;
3808
3809 switch (op) {
3810 case MarkOP::OR:
3811 for (auto p = ents.pair_begin(); p != ents.pair_end(); ++p) {
3812 auto lo = dofs->get<Ent_mi_tag>().lower_bound(p->first);
3813 auto hi = dofs->get<Ent_mi_tag>().upper_bound(p->second);
3814 for (; lo != hi; ++lo) {
3815 if ((*lo)->getPetscLocalDofIdx() < 0)
3816 continue;
3817 marker[(*lo)->getPetscLocalDofIdx()] |= 1;
3818 }
3819 }
3820 break;
3821 case MarkOP::AND:
3822 marker_tmp.resize(dofs->size(), 0);
3823 for (auto p = ents.pair_begin(); p != ents.pair_end(); ++p) {
3824 auto lo = dofs->get<Ent_mi_tag>().lower_bound(p->first);
3825 auto hi = dofs->get<Ent_mi_tag>().upper_bound(p->second);
3826 for (; lo != hi; ++lo) {
3827 if ((*lo)->getPetscLocalDofIdx() < 0)
3828 continue;
3829 marker_tmp[(*lo)->getPetscLocalDofIdx()] = 1;
3830 }
3831 }
3832 for (int i = 0; i != marker.size(); ++i) {
3833 marker[i] &= marker_tmp[i];
3834 }
3835 break;
3836 }
3837
3839}
3840
3841MoFEMErrorCode ProblemsManager::modifyMarkDofs(
3842 const std::string problem_name, RowColData rc, const std::string field_name,
3843 const int lo, const int hi, const enum ProblemsManager::MarkOP op,
3844 const unsigned char c, std::vector<unsigned char> &marker) const {
3845
3846 Interface &m_field = cOre;
3847 const Problem *problem_ptr;
3849 CHKERR m_field.get_problem(problem_name, &problem_ptr);
3850 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs;
3851 switch (rc) {
3852 case ROW:
3853 dofs = problem_ptr->getNumeredRowDofsPtr();
3854 break;
3855 case COL:
3856 dofs = problem_ptr->getNumeredColDofsPtr();
3857 default:
3858 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE, "Should be row or column");
3859 }
3860 marker.resize(dofs->size(), 0);
3861
3862 auto dof_lo = dofs->get<Unique_mi_tag>().lower_bound(
3863 FieldEntity::getLoBitNumberUId(m_field.get_field_bit_number(field_name)));
3864 auto dof_hi = dofs->get<Unique_mi_tag>().upper_bound(
3865 FieldEntity::getHiBitNumberUId(m_field.get_field_bit_number(field_name)));
3866
3867 switch (op) {
3868 case MarkOP::OR:
3869 for (; dof_lo != dof_hi; ++dof_lo) {
3870 if ((*dof_lo)->getPetscLocalDofIdx() < 0)
3871 continue;
3872 if ((*dof_lo)->getDofCoeffIdx() >= lo &&
3873 (*dof_lo)->getDofCoeffIdx() <= hi)
3874 marker[(*dof_lo)->getPetscLocalDofIdx()] |= c;
3875 }
3876 break;
3877 case MarkOP::AND:
3878 for (; dof_lo != dof_hi; ++dof_lo) {
3879 if ((*dof_lo)->getPetscLocalDofIdx() < 0)
3880 continue;
3881 if ((*dof_lo)->getDofCoeffIdx() >= lo &&
3882 (*dof_lo)->getDofCoeffIdx() <= hi)
3883 marker[(*dof_lo)->getPetscLocalDofIdx()] &= c;
3884 }
3885 break;
3886 }
3887
3889}
3890
3891MoFEMErrorCode ProblemsManager::markDofs(
3892
3893 const std::string problem_name, RowColData rc,
3894 std::vector<boost::weak_ptr<NumeredDofEntity>> &vec_dof_view,
3895 const enum MarkOP op, std::vector<unsigned char> &marker
3896
3897) const {
3898 Interface &m_field = cOre;
3900
3901 const Problem *problem_ptr;
3902 CHKERR m_field.get_problem(problem_name, &problem_ptr);
3903 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs;
3904 switch (rc) {
3905 case ROW:
3906 dofs = problem_ptr->getNumeredRowDofsPtr();
3907 break;
3908 case COL:
3909 dofs = problem_ptr->getNumeredColDofsPtr();
3910 break;
3911 default:
3912 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE, "Should be row or column");
3913 }
3914 marker.resize(dofs->size(), 0);
3915
3916 for (auto &dof : vec_dof_view) {
3917 if (auto dof_ptr = dof.lock()) {
3918 if (dof_ptr->getPetscLocalDofIdx() < 0)
3919 continue;
3920 if (op == MarkOP::OR)
3921 marker[dof_ptr->getPetscLocalDofIdx()] |= 1;
3922 else
3923 marker[dof_ptr->getPetscLocalDofIdx()] &= 1;
3924 }
3925 }
3926
3928}
3929
3931ProblemsManager::addFieldToEmptyFieldBlocks(const std::string problem_name,
3932 const std::string row_field,
3933 const std::string col_field) const {
3934
3935 Interface &m_field = cOre;
3937
3938 const auto problem_ptr = m_field.get_problem(problem_name);
3939 auto get_field_id = [&](const std::string field_name) {
3940 return m_field.get_field_structure(field_name)->getId();
3941 };
3942 const auto row_id = get_field_id(row_field);
3943 const auto col_id = get_field_id(col_field);
3944
3945 problem_ptr->addFieldToEmptyFieldBlocks(BlockFieldPair(row_id, col_id));
3946
3948}
3949
3950} // namespace MoFEM
std::vector< int > size
unsigned char status
ParentChildKey key
MPI_Comm comm
Core & cOre
Tag tag
ProjectedField & field
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
std::vector< double > empty
One value per component.
std::map< EntityHandle, std::vector< double > > staged
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 ProblemManagerFunctionBegin
It it
Definition Schur.cpp:2568
int nb
number of DOFs
Definition Schur.cpp:2505
It end
Definition Schur.cpp:2568
std::string name
constexpr double a
@ VERY_VERBOSE
@ QUIET
@ NOISY
@ VERBOSE
RowColData
RowColData.
@ COL
@ ROW
@ MF_EXCL
#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()
@ MOFEM_NOT_FOUND
Definition definitions.h:33
@ MOFEM_IMPOSSIBLE_CASE
Definition definitions.h:35
@ 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 ...
static const bool debug
multi_index_container< boost::shared_ptr< FieldEntity >, indexed_by< ordered_unique< tag< Unique_mi_tag >, const_mem_fun< FieldEntity, UId, &FieldEntity::getGlobalUniqueId > > > > FieldEntity_multiIndex_global_uid_view
multi-index view on DofEntity by uid
NumeredDofEntity_multiIndex::index< Unique_mi_tag >::type NumeredDofEntityByUId
Numbered DoF multi-index by UId.
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.
multi_index_container< boost::shared_ptr< NumeredEntFiniteElement >, indexed_by< ordered_unique< tag< Unique_mi_tag >, const_mem_fun< NumeredEntFiniteElement::interface_type_EntFiniteElement, UId, &NumeredEntFiniteElement::getLocalUniqueId > >, ordered_non_unique< tag< Part_mi_tag >, member< NumeredEntFiniteElement, unsigned int, &NumeredEntFiniteElement::part > >, ordered_non_unique< tag< Ent_mi_tag >, const_mem_fun< NumeredEntFiniteElement::interface_type_RefEntity, EntityHandle, &NumeredEntFiniteElement::getEnt > >, ordered_non_unique< tag< Composite_Name_And_Part_mi_tag >, composite_key< NumeredEntFiniteElement, const_mem_fun< NumeredEntFiniteElement::interface_type_FiniteElement, boost::string_ref, &NumeredEntFiniteElement::getNameRef >, member< NumeredEntFiniteElement, unsigned int, &NumeredEntFiniteElement::part > > > > > NumeredEntFiniteElement_multiIndex
MultiIndex for entities for NumeredEntFiniteElement.
multi_index_container< boost::shared_ptr< FiniteElement >, indexed_by< hashed_unique< tag< FiniteElement_Meshset_mi_tag >, member< FiniteElement, EntityHandle, &FiniteElement::meshset > >, hashed_unique< tag< BitFEId_mi_tag >, const_mem_fun< FiniteElement, BitFEId, &FiniteElement::getId >, HashBit< BitFEId >, EqBit< BitFEId > >, ordered_unique< tag< FiniteElement_name_mi_tag >, const_mem_fun< FiniteElement, boost::string_ref, &FiniteElement::getNameRef > > > > FiniteElement_multiIndex
MultiIndex for entities for FiniteElement.
virtual const Problem * get_problem(const std::string problem_name) const =0
Get the problem object.
virtual const FieldEntity_multiIndex * get_field_ents() const =0
Get the field ents object.
virtual MoFEMErrorCode get_ents_elements_adjacency(const FieldEntityEntFiniteElementAdjacencyMap_multiIndex **dofs_elements_adjacency) const =0
Get the dofs elements adjacency object.
virtual const FiniteElement_multiIndex * get_finite_elements() const =0
Get the finite elements object.
virtual const DofEntity_multiIndex * get_dofs() const =0
Get the dofs object.
virtual const Problem_multiIndex * get_problems() const =0
Get the problems object.
virtual const EntFiniteElement_multiIndex * get_ents_finite_elements() const =0
Get the ents finite elements object.
virtual const Field_multiIndex * get_fields() const =0
Get the fields object.
virtual const Field * get_field_structure(const std::string &name, enum MoFEMTypes bh=MF_EXIST) const =0
get field structure
#define MOFEM_LOG(channel, severity)
Log.
virtual MoFEMErrorCode add_problem(const std::string &name, enum MoFEMTypes bh=MF_EXCL, int verb=DEFAULT_VERBOSITY)=0
Add problem.
virtual MoFEMErrorCode delete_problem(const std::string name)=0
Delete problem.
virtual MoFEMErrorCode clear_problem(const std::string name, int verb=DEFAULT_VERBOSITY)=0
clear problem
virtual bool check_problem(const std::string name)=0
check if problem exist
auto marker
set bit to marker
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)
const FTensor::Tensor2< T, Dim, Dim > Vec
const Tensor2_symmetric_Expr< const ddTensor0< T, Dim, i, j >, typename promote< T, double >::V, Dim, i, j > dd(const Tensor0< T * > &a, const Index< i, Dim > index1, const Index< j, Dim > index2, const Tensor1< int, Dim > &d_ijk, const Tensor1< double, Dim > &d_xyz)
Definition ddTensor0.hpp:33
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
auto type_from_handle(const EntityHandle h)
get type from entity handle
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.
auto createAOMapping(MPI_Comm comm, PetscInt napp, const PetscInt myapp[], const PetscInt mypetsc[])
Creates an application mapping using two integer arrays.
CoreTmp< 0 > Core
Definition Core.hpp:1161
auto createAOMappingIS(IS isapp, IS ispetsc)
Creates an application mapping using two index sets.
auto field_bit_from_bit_number(const int bit_number)
get field bit id from bit number
MoFEM::LogManager::SeverityLevel Sev
Problem::BlockFieldPair BlockFieldPair
auto get_temp_meshset_ptr(moab::Interface &moab)
Create smart pointer to temporary meshset.
multi_index_container< boost::shared_ptr< NumeredDofEntity >, indexed_by< ordered_unique< const_mem_fun< NumeredDofEntity::interface_type_DofEntity, UId, &NumeredDofEntity::getLocalUniqueId > > > > NumeredDofEntity_multiIndex_uid_view_ordered
DeprecatedCoreInterface Interface
static void publish_numbered_dofs(NumeredDofEntity_multiIndex &dofs, const boost::shared_ptr< std::vector< NumeredDofEntity > > &sequence_ptr, const bool serial_uid_numbering=false)
Publish stable records using hints shared by all five ordered indices.
int r
Definition sdf.py:205
constexpr auto field_name
FTensor::Index< 'm', 3 > m
virtual int get_comm_size() const =0
virtual FieldBitNumber get_field_bit_number(const std::string name) const =0
get field bit number
virtual moab::Interface & get_moab()=0
virtual MPI_Comm & get_comm() const =0
virtual std::string get_field_name(const BitFieldId id) const =0
get field name from id
virtual int get_comm_rank() const =0
virtual boost::shared_ptr< BasicEntityData > & get_basic_entity_data_ptr()=0
Get pointer to basic entity data.
Core (interface) class.
Definition Core.hpp:83
Deprecated interface functions.
FieldCoefficientsNumber getNbOfCoeffs() const
Get number of field coefficients per DOF.
std::map< int, BaseFunction::DofsSideMap > & getDofSideMap() const
Get DOF side mapping for broken spaces.
MoFEMErrorCode getNumberOfElementsByNameAndPart(MPI_Comm comm, const std::string name, PetscLayout *layout) const
Get number of finite elements by name on processors.
boost::shared_ptr< NumeredDofEntity_multiIndex > numeredRowDofsPtr
store DOFs on rows for this problem
BitProblemId getId() const
auto & getNumeredRowDofsPtr() const
get access to numeredRowDofsPtr storing DOFs on rows
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.