v0.16.3
Loading...
Searching...
No Matches
rebuild_problem.cpp
Go to the documentation of this file.
1/** \file rebuild_problem.cpp
2 * \example mofem/atom_tests/rebuild_problem.cpp
3 * \brief Recreate a problem on uniformly refined levels while the previous
4 * level's problem is alive, and compare it with a fresh build.
5 *
6 * Level 0 is built fresh. For every further level l the mesh of level l-1 is
7 * refined uniformly to level l, then:
8 *
9 * 1. problem P<l>_rebuild is built on bit l with mask {l-1, l} (every bit
10 * from the first local refinement on, whose unrefined elements keep
11 * their older bits) while the problem of level l-1 is alive: the
12 * recreate path of doc/development/rebuild_problems.md;
13 * 2. the level l-1 problem is checked to be unchanged and destroyed;
14 * 3. problem P<l> is built fresh on bit l with the default mask;
15 * 4. the two are compared: DOF and element counts, every DOF's global and
16 * local index and part, absence of DOFs on source-only parents, and the
17 * matrix size, non-zeros and every owned row's column indices;
18 * 5. the fresh problem is destroyed and the rebuilt one becomes the source
19 * of the next level.
20 *
21 * Every stage is a TestingInterface test (number 10*l + stage) registered
22 * with addTest and run in order by runTests; the stages share one state and
23 * each checks that the previous one has run. Phase times are PETSc log
24 * events RP_Refine, RP_FieldsFEs, RP_Rebuild, RP_Fresh and RP_Matrix; run
25 * with -log_view.
26 *
27 * Options: -file_name, -nb_levels, -order; -dm_is_partitioned uses the
28 * distributed builder (one rank, or a partitioned mesh whose partition sets
29 * are updated after refinement, which this test does not do); -incremental
30 * (default true) registers only the entities each refinement creates,
31 * through build_fields(ents), build_finite_elements(name, &ents) and
32 * build_adjacencies(ents), false uses the all-entities overloads;
33 * -local_from <l> refines only one vertex star from level l on, so the cost
34 * of a local change on a fixed mesh can be measured; -skip_matrix omits the
35 * matrix graphs; -in_place (with -dm_is_partitioned) rebuilds the alive
36 * problem under its own name and DM with DMMoFEMRebuildProblem instead of
37 * stage 1, and checks the survivor index sets it returns: every pair maps
38 * an old global index to the new one of the same DOF, every surviving owned
39 * DOF is listed, and a VecScatter through them carries values.
40 */
41
42#include <MoFEM.hpp>
43#include <map>
44#include <boost/functional/hash.hpp>
45
46using namespace MoFEM;
47
48static char help[] =
49 "Build a problem on uniformly refined levels while the previous level's "
50 "problem is alive, and compare with a fresh build.\n"
51 "-file_name <mesh> -nb_levels <n> -order <p> [-dm_is_partitioned]\n\n";
52
53namespace {
54
55constexpr const char *fieldName = "F1";
56constexpr const char *elementName = "E1";
57
58inline BitRefLevel bit(int l) { return BitRefLevel().set(l); }
59inline BitRefLevel allBits() { return BitRefLevel().set(); }
60
61struct Events {
62 PetscLogEvent refine, fieldsFes, rebuild, fresh, matrix;
63};
64
65/// Counts and a hash of the numbering of one problem, in UID order.
66struct Summary {
67 int globalDofs = 0, localDofs = 0, ghostDofs = 0, elements = 0;
68 std::size_t numbering = 0;
69};
70
71/// Differences between the rebuilt and the fresh problem of one level.
72struct Mismatch {
73 int missing = 0; ///< Rebuilt DOFs absent from the fresh problem.
74 int index = 0; ///< DOFs with a different global/local index or part.
75 int parents = 0; ///< Rebuilt DOFs on entities without the level bit.
76};
77
78/// Keep only the rebuilt matrix's local graph while the fresh matrix is made.
79struct MatrixGraph {
80 PetscInt firstRow = 0, lastRow = 0, differentRows = 0;
81 std::vector<std::size_t> offsets;
82 std::vector<PetscInt> columns;
83};
84
85/// Add the entities of level l to the field and the element, and build.
86/// Incrementally: only entities created by the refinement (on bit l but not
87/// on bit l-1) are added, ordered and built, with the range overloads
88/// build_fields(ents), build_finite_elements(name, &ents) and
89/// build_adjacencies(ents). Otherwise the all-entities overloads are used,
90/// which revisit every entity of every level.
91MoFEMErrorCode registerLevel(MoFEM::Interface &m_field, int l, int order,
92 bool incremental) {
94 auto bit_mng = m_field.getInterface<BitRefManager>();
95 Range ents;
96 CHKERR bit_mng->getEntitiesByRefLevel(bit(l), allBits(), ents);
97 if (incremental && l > 0) {
99 CHKERR bit_mng->getEntitiesByRefLevel(bit(l - 1), allBits(), previous);
100 ents = subtract(ents, previous);
101 }
102 for (auto type : {MBVERTEX, MBEDGE, MBTRI, MBTET}) {
103 Range of_type = ents.subset_by_type(type);
104 CHKERR m_field.add_ents_to_field_by_type(of_type, type, fieldName);
105 CHKERR m_field.set_field_order(of_type, fieldName,
106 type == MBVERTEX ? 1 : order);
107 }
109 elementName, MBTET);
110 if (incremental) {
111 const Range tets = ents.subset_by_type(MBTET);
112 CHKERR m_field.build_fields(ents);
113 CHKERR m_field.build_finite_elements(elementName, &tets);
114 CHKERR m_field.build_adjacencies(tets);
115 } else {
116 CHKERR m_field.build_fields();
118 CHKERR m_field.build_adjacencies(bit(l));
119 }
121}
122
123/// Entities listed more than once in the data views of all finite elements.
124MoFEMErrorCode countDuplicateViewEntries(MoFEM::Interface &m_field,
125 int &duplicates) {
127 duplicates = 0;
128 std::vector<UId> uids;
129 for (auto &fe : *m_field.get_ents_finite_elements()) {
130 auto &view = *fe->getDataFieldEntsPtr();
131 uids.clear();
132 for (auto &weak : view)
133 if (auto ent = weak.lock())
134 uids.push_back(ent->getLocalUniqueId());
135 std::sort(uids.begin(), uids.end());
136 duplicates += uids.size() - (std::unique(uids.begin(), uids.end()) -
137 uids.begin());
138 }
140}
141
142/// Refine level l-1 onto level l: every tetrahedron, or, when local, only
143/// the star of the lowest vertex of the level, with the unchanged
144/// tetrahedra and their closure also given bit l, as a crack step leaves
145/// unchanged entities on the output level. Returns the number refined.
146MoFEMErrorCode refineLevel(MoFEM::Interface &m_field, int l, bool local,
147 int &refined) {
149 auto bit_mng = m_field.getInterface<BitRefManager>();
150 auto &moab = m_field.get_moab();
151 Range level_tets;
152 CHKERR bit_mng->getEntitiesByDimAndRefLevel(bit(l - 1), allBits(), 3,
153 level_tets);
154 Range tets = level_tets;
155 if (local) {
156 Range verts;
157 CHKERR moab.get_connectivity(level_tets, verts, true);
158 const EntityHandle vertex = verts.front();
159 Range star;
160 CHKERR moab.get_adjacencies(&vertex, 1, 3, false, star);
161 tets = intersect(star, level_tets);
162 }
163 refined = tets.size();
164 Range edges;
165 CHKERR moab.get_adjacencies(tets, 1, true, edges, moab::Interface::UNION);
166 auto refine = m_field.getInterface<MeshRefinement>();
167 CHKERR refine->addVerticesInTheMiddleOfEdges(edges, bit(l));
168 CHKERR refine->refineTets(tets, bit(l));
169 if (local) {
170 const Range unchanged = subtract(level_tets, tets);
171 CHKERR bit_mng->setBitRefLevel(unchanged, bit(l), true);
172 }
174}
175
176/// Check the survivor index sets of an in-place rebuild: every pair maps
177/// the old global index of a DOF to its new one, every surviving owned DOF
178/// is listed, and a VecScatter through the two sets carries values from a
179/// vector of the old layout to one of the new.
180MoFEMErrorCode checkSurvivors(MoFEM::Interface &m_field,
182 const std::string &tag, const std::string &name,
183 const std::map<UId, int> &old_global,
184 int old_local, int old_total,
185 SmartPetscObj<IS> is_old,
186 SmartPetscObj<IS> is_new) {
188 const auto zero = TestingInterface::Tolerance{0, 0};
189 const Problem *prb;
190 CHKERR m_field.get_problem(name, &prb);
191 PetscInt n_old, n_new;
192 CHKERR ISGetLocalSize(is_old, &n_old);
193 CHKERR ISGetLocalSize(is_new, &n_new);
194 CHKERR testing.checkValue<TestType::SCALAR>(
195 tag + " survivor sets have one size", n_old, n_new, zero);
196 const PetscInt *old_idx, *new_idx;
197 CHKERR ISGetIndices(is_old, &old_idx);
198 CHKERR ISGetIndices(is_new, &new_idx);
199
200 auto &by_global = prb->getNumeredRowDofsPtr()->get<PetscGlobalIdx_mi_tag>();
201 int wrong = 0;
202 for (PetscInt i = 0; i != n_new; ++i) {
203 auto it = by_global.find(new_idx[i]);
204 if (it == by_global.end()) {
205 ++wrong;
206 continue;
207 }
208 auto o = old_global.find((*it)->getLocalUniqueId());
209 if (o == old_global.end() || o->second != old_idx[i])
210 ++wrong;
211 }
212 CHKERR testing.checkValue<TestType::SCALAR>(
213 tag + " survivor pairs map old to new index", wrong, 0, zero);
214 int expected = 0;
215 auto &by_local = prb->getNumeredRowDofsPtr()->get<PetscLocalIdx_mi_tag>();
216 for (auto it = by_local.lower_bound(0),
217 hi = by_local.lower_bound(prb->getNbLocalDofsRow());
218 it != hi; ++it)
219 if (old_global.count((*it)->getLocalUniqueId()))
220 ++expected;
221 CHKERR testing.checkValue<TestType::SCALAR>(
222 tag + " every surviving owned dof is listed", n_new, expected, zero);
223
224 // A vector of the old layout holding its own global index, scattered into
225 // a vector of the new layout through the two sets.
226 Vec old_vec, new_vec;
227 CHKERR VecCreateMPI(m_field.get_comm(), old_local, old_total, &old_vec);
228 PetscInt lo, hi;
229 CHKERR VecGetOwnershipRange(old_vec, &lo, &hi);
230 {
231 PetscScalar *a;
232 CHKERR VecGetArray(old_vec, &a);
233 for (PetscInt i = lo; i != hi; ++i)
234 a[i - lo] = i;
235 CHKERR VecRestoreArray(old_vec, &a);
236 }
237 CHKERR VecCreateMPI(m_field.get_comm(), prb->getNbLocalDofsRow(),
238 prb->getNbDofsRow(), &new_vec);
239 CHKERR VecSet(new_vec, -1);
240 VecScatter scatter;
241 CHKERR VecScatterCreate(old_vec, is_old, new_vec, is_new, &scatter);
242 CHKERR VecScatterBegin(scatter, old_vec, new_vec, INSERT_VALUES,
243 SCATTER_FORWARD);
244 CHKERR VecScatterEnd(scatter, old_vec, new_vec, INSERT_VALUES,
245 SCATTER_FORWARD);
246 CHKERR VecScatterDestroy(&scatter);
247 PetscInt new_lo, new_hi;
248 CHKERR VecGetOwnershipRange(new_vec, &new_lo, &new_hi);
249 int wrong_scatter = 0;
250 {
251 const PetscScalar *a;
252 CHKERR VecGetArrayRead(new_vec, &a);
253 for (PetscInt i = 0; i != n_new; ++i) {
254 if (new_idx[i] < new_lo || new_idx[i] >= new_hi)
255 ++wrong_scatter;
256 else if (a[new_idx[i] - new_lo] != static_cast<PetscScalar>(old_idx[i]))
257 ++wrong_scatter;
258 }
259 CHKERR VecRestoreArrayRead(new_vec, &a);
260 }
261 CHKERR testing.checkValue<TestType::SCALAR>(
262 tag + " scatter through survivors carries values", wrong_scatter, 0,
263 zero);
264 CHKERR VecDestroy(&old_vec);
265 CHKERR VecDestroy(&new_vec);
266 CHKERR ISRestoreIndices(is_old, &old_idx);
267 CHKERR ISRestoreIndices(is_new, &new_idx);
269}
270
271/// Create a DM for a new problem name on the given level and mask and set it
272/// up; the DM owns the problem.
273MoFEMErrorCode buildProblem(MoFEM::Interface &m_field, const std::string &name,
274 BitRefLevel level, BitRefLevel mask,
275 PetscBool is_partitioned, PetscLogEvent event,
276 SmartPetscObj<DM> &dm, double &seconds) {
278 if (m_field.check_problem(name))
279 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
280 "Problem %s exists: its previous owner was not destroyed",
281 name.c_str());
282 dm = createDM(m_field.get_comm(), "DMMOFEM");
283 CHKERR DMMoFEMCreateMoFEM(dm, &m_field, name.c_str(), level, mask);
284 // DMMoFEMCreateMoFEM ORs the mask onto the all-ones default of a new
285 // problem, so the mask given above is not in force; set the selector.
288 CHKERR DMMoFEMSetDestroyProblem(dm, PETSC_TRUE);
289 CHKERR DMMoFEMSetIsPartitioned(dm, is_partitioned);
290 CHKERR DMMoFEMSetSquareProblem(dm, PETSC_TRUE);
291 CHKERR DMMoFEMAddElement(dm, elementName);
292 PetscLogDouble t0, t1;
293 CHKERR PetscTime(&t0);
294 PetscLogEventBegin(event, 0, 0, 0, 0);
295 CHKERR DMSetUp(dm);
296 PetscLogEventEnd(event, 0, 0, 0, 0);
297 CHKERR PetscTime(&t1);
298 seconds = t1 - t0;
300}
301
302MoFEMErrorCode summarise(MoFEM::Interface &m_field, const std::string &name,
303 Summary &s) {
305 const Problem *prb;
306 CHKERR m_field.get_problem(name, &prb);
307 s.globalDofs = prb->getNbDofsRow();
308 s.localDofs = prb->getNbLocalDofsRow();
309 s.ghostDofs = prb->getNbGhostDofsRow();
310 s.elements = prb->getNumeredFiniteElementsPtr()->size();
311 s.numbering = 0;
312 for (auto &dof : *prb->getNumeredRowDofsPtr()) {
313 const UId uid = dof->getLocalUniqueId();
314 boost::hash_combine(s.numbering, static_cast<unsigned long long>(uid));
315 boost::hash_combine(s.numbering,
316 static_cast<unsigned long long>(uid >> 64));
317 boost::hash_combine(s.numbering, dof->getPetscGlobalDofIdx());
318 boost::hash_combine(s.numbering, dof->getPetscLocalDofIdx());
319 boost::hash_combine(s.numbering, dof->getPart());
320 }
322}
323
324MoFEMErrorCode compareProblems(MoFEM::Interface &m_field,
325 const std::string &rebuilt,
326 const std::string &fresh, BitRefLevel level,
327 Mismatch &m) {
329 const Problem *prb_rebuilt, *prb_fresh;
330 CHKERR m_field.get_problem(rebuilt, &prb_rebuilt);
331 CHKERR m_field.get_problem(fresh, &prb_fresh);
332 auto &fresh_by_uid =
333 prb_fresh->getNumeredRowDofsPtr()->get<Unique_mi_tag>();
334 for (auto &dof : *prb_rebuilt->getNumeredRowDofsPtr()) {
335 if (!(dof->getBitRefLevel() & level).any())
336 ++m.parents;
337 auto it = fresh_by_uid.find(dof->getLocalUniqueId());
338 if (it == fresh_by_uid.end()) {
339 ++m.missing;
340 continue;
341 }
342 if ((*it)->getPetscGlobalDofIdx() != dof->getPetscGlobalDofIdx() ||
343 (*it)->getPetscLocalDofIdx() != dof->getPetscLocalDofIdx() ||
344 (*it)->getPart() != dof->getPart())
345 ++m.index;
346 }
348}
349
350/// Assemble the sparsity of the problem's matrix and report its size.
351MoFEMErrorCode matrixInfo(MoFEM::Interface &m_field, const std::string &name,
352 PetscLogEvent event, double &rows, double &nonzeros,
353 double &seconds, MatrixGraph &graph,
354 bool compare = false) {
357 PetscLogDouble t0, t1;
358 CHKERR PetscTime(&t0);
359 PetscLogEventBegin(event, 0, 0, 0, 0);
361 ->createMPIAIJWithArrays<PetscGlobalIdx_mi_tag>(name, A);
362 PetscLogEventEnd(event, 0, 0, 0, 0);
363 CHKERR PetscTime(&t1);
364 seconds = t1 - t0;
365 PetscInt m, n;
366 CHKERR MatGetSize(A, &m, &n);
367 MatInfo info;
368 CHKERR MatGetInfo(A, MAT_GLOBAL_SUM, &info);
369 rows = m;
370 nonzeros = info.nz_used;
371
372 // Graph validation is outside the matrix creation timer. Keep one CSR
373 // snapshot, rather than retaining two full PETSc matrices at large orders.
374 PetscInt first_row, last_row;
375 CHKERR MatGetOwnershipRange(A, &first_row, &last_row);
376 if (compare) {
377 if (first_row != graph.firstRow || last_row != graph.lastRow)
378 SETERRQ(m_field.get_comm(), MOFEM_DATA_INCONSISTENCY,
379 "Matrix ownership ranges differ");
380 } else {
381 graph.firstRow = first_row;
382 graph.lastRow = last_row;
383 graph.differentRows = 0;
384 graph.offsets = {0};
385 graph.offsets.reserve(last_row - first_row + 1);
386 graph.columns.clear();
387 MatInfo local_info;
388 CHKERR MatGetInfo(A, MAT_LOCAL, &local_info);
389 graph.columns.reserve(static_cast<std::size_t>(local_info.nz_used));
390 }
391 std::vector<PetscInt> row_columns;
392 for (PetscInt row = first_row; row < last_row; ++row) {
393 PetscInt nb_cols;
394 const PetscInt *cols;
395 CHKERR MatGetRow(A, row, &nb_cols, &cols, nullptr);
396 row_columns.clear();
397 if (nb_cols)
398 row_columns.assign(cols, cols + nb_cols);
399 CHKERR MatRestoreRow(A, row, &nb_cols, &cols, nullptr);
400 std::sort(row_columns.begin(), row_columns.end());
401 if (compare) {
402 const auto local_row = row - first_row;
403 const auto begin = graph.offsets[local_row];
404 const auto end = graph.offsets[local_row + 1];
405 if (row_columns.size() != end - begin ||
406 !std::equal(row_columns.begin(), row_columns.end(),
407 graph.columns.begin() + begin))
408 ++graph.differentRows;
409 } else {
410 graph.columns.insert(graph.columns.end(), row_columns.begin(),
411 row_columns.end());
412 graph.offsets.push_back(graph.columns.size());
413 }
414 }
416}
417
418/// State shared by the registered stages of one run.
419struct State {
420 SmartPetscObj<DM> alive, rebuilt, fresh;
421 std::string aliveName, rebuiltName, freshName;
422 Summary aliveSummary, rebuiltSummary, freshSummary;
423 double aliveSeconds = 0, rebuiltSeconds = 0, freshSeconds = 0;
424 int level = -1; ///< Last level whose mesh and fields are registered.
425};
426
427} // namespace
428
429int main(int argc, char *argv[]) {
430
431 MoFEM::Core::Initialize(&argc, &argv, (char *)0, help);
432
433 try {
434
435 moab::Core mb_instance;
436 moab::Interface &moab = mb_instance;
437
438 char mesh_file_name[255];
439 PetscBool flg = PETSC_FALSE;
440 CHKERR PetscOptionsGetString(PETSC_NULLPTR, "", "-file_name",
441 mesh_file_name, 255, &flg);
442 if (flg != PETSC_TRUE)
443 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_FOUND,
444 "-file_name <mesh> is required");
445 PetscInt nb_levels = 2, order = 3;
446 PetscBool is_partitioned = PETSC_FALSE, skip_matrix = PETSC_FALSE;
447 CHKERR PetscOptionsGetInt(PETSC_NULLPTR, "", "-nb_levels", &nb_levels,
448 PETSC_NULLPTR);
449 CHKERR PetscOptionsGetInt(PETSC_NULLPTR, "", "-order", &order,
450 PETSC_NULLPTR);
451 CHKERR PetscOptionsGetBool(PETSC_NULLPTR, "", "-dm_is_partitioned",
452 &is_partitioned, PETSC_NULLPTR);
453 // Skip the matrix graphs: at large sizes they cost more memory than the
454 // problems themselves and are not part of the build being measured.
455 CHKERR PetscOptionsGetBool(PETSC_NULLPTR, "", "-skip_matrix", &skip_matrix,
456 PETSC_NULLPTR);
457 // Register each level's new entities only (default), or rebuild every
458 // field entity and element with the all-entities overloads.
459 PetscBool incremental = PETSC_TRUE;
460 CHKERR PetscOptionsGetBool(PETSC_NULLPTR, "", "-incremental", &incremental,
461 PETSC_NULLPTR);
462 // From this level on, refine only the star of one vertex instead of the
463 // whole mesh, so registration and build costs can be compared for a
464 // local change on a mesh of fixed size. Negative: always uniform.
465 PetscInt local_from = -1;
466 CHKERR PetscOptionsGetInt(PETSC_NULLPTR, "", "-local_from", &local_from,
467 PETSC_NULLPTR);
468 // Rebuild the alive problem in place (DMMoFEMRebuildProblem, same name
469 // and DM) instead of building the output under a second name; needs the
470 // distributed builder.
471 PetscBool in_place = PETSC_FALSE;
472 CHKERR PetscOptionsGetBool(PETSC_NULLPTR, "", "-in_place", &in_place,
473 PETSC_NULLPTR);
474 if (in_place && !is_partitioned)
475 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
476 "-in_place needs -dm_is_partitioned");
477
478 CHKERR moab.load_file(mesh_file_name, 0, "");
479
480 MoFEM::Core core(moab);
481 MoFEM::Interface &m_field = core;
483 CHKERR DMRegister_MoFEM("DMMOFEM");
484
485 Events ev;
486 CHKERR PetscLogEventRegister("RP_Refine", 0, &ev.refine);
487 CHKERR PetscLogEventRegister("RP_FieldsFEs", 0, &ev.fieldsFes);
488 CHKERR PetscLogEventRegister("RP_Rebuild", 0, &ev.rebuild);
489 CHKERR PetscLogEventRegister("RP_Fresh", 0, &ev.fresh);
490 CHKERR PetscLogEventRegister("RP_Matrix", 0, &ev.matrix);
491
492 MOFEM_LOG_CHANNEL("WORLD");
493 MOFEM_LOG_TAG("WORLD", "RebuildProblem");
494 MOFEM_LOG("WORLD", Sev::inform)
495 << "Levels " << nb_levels << ", order " << order << ", "
496 << (is_partitioned ? "distributed" : "replicated") << " builder, "
497 << (incremental ? "incremental" : "full")
498 << " field/element registration, "
499 << (in_place ? "in-place rebuild" : "recreate path");
500
501 auto count_tets = [&](int l) {
502 Range tets;
505 bit(l), allBits(), 3, tets),
506 "count tets");
507 return tets.size();
508 };
509
510 auto log_level = [&](int l, const std::string &name, const Summary &s,
511 double seconds) {
512 MOFEM_LOG_CHANNEL("WORLD");
513 MOFEM_LOG_TAG("WORLD", "RebuildProblem");
514 MOFEM_LOG("WORLD", Sev::inform)
515 << "Level " << l << " " << name << ": tets " << count_tets(l)
516 << ", elements " << s.elements << ", dofs " << s.globalDofs
517 << " (local " << s.localDofs << ", ghost " << s.ghostDofs
518 << "), build " << seconds << " s";
519 };
520
521 auto zero = TestingInterface::Tolerance{0, 0};
522 State st;
523
524 // Mask of the rebuilt problem on level l. After a uniform refinement the
525 // level's elements carry bit l only, and {l-1, l} selects them; a local
526 // refinement adds bit l to the unrefined elements, which keep their
527 // older bits, so from the first local level on every bit is admitted.
528 auto rebuilt_mask = [&](int l) {
529 return (local_from >= 0 && l >= local_from) ? allBits()
530 : (bit(l - 1) | bit(l));
531 };
532
533 // Fields and the element are declared once; entities join per level.
534 CHKERR m_field.getInterface<BitRefManager>()->setBitRefLevelByDim(
535 0, 3, bit(0));
536 CHKERR m_field.add_field(fieldName, H1, AINSWORTH_LEGENDRE_BASE, 3,
537 MB_TAG_DENSE);
538 CHKERR m_field.add_finite_element(elementName);
539 CHKERR m_field.modify_finite_element_add_field_row(elementName, fieldName);
540 CHKERR m_field.modify_finite_element_add_field_col(elementName, fieldName);
542 fieldName);
543
544 auto require = [&](bool ok, const std::string &what) {
546 if (!ok)
547 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
548 "Stage order broken: %s", what.c_str());
550 };
551
552 // Stage 1 of level 0: register the mesh and build the first problem.
553 CHKERR testing->addTest(1, "level 0 build", [&]() {
555 PetscLogEventBegin(ev.fieldsFes, 0, 0, 0, 0);
556 CHKERR registerLevel(m_field, 0, order, incremental);
557 PetscLogEventEnd(ev.fieldsFes, 0, 0, 0, 0);
558 st.level = 0;
559 st.aliveName = "P0";
560 CHKERR buildProblem(m_field, st.aliveName, bit(0), allBits(),
561 is_partitioned, ev.fresh, st.alive, st.aliveSeconds);
562 CHKERR summarise(m_field, st.aliveName, st.aliveSummary);
563 log_level(0, st.aliveName, st.aliveSummary, st.aliveSeconds);
564 CHKERR testing->checkValue<TestType::SCALAR>(
565 "level 0 has dofs", st.aliveSummary.globalDofs > 0 ? 1 : 0, 1,
566 zero);
568 });
569
570 for (int l = 1; l <= nb_levels; ++l) {
571 const auto tag = "level " + std::to_string(l);
572 const int base = 10 * l;
573
574 CHKERR testing->addTest(base + 1, tag + " refine", [&, l, tag]() {
576 CHKERR require(st.level == l - 1 && st.alive,
577 tag + " refine needs level " + std::to_string(l - 1) +
578 " registered and its problem alive");
579 const bool local = local_from >= 0 && l >= local_from;
580 const auto tets_before = count_tets(l - 1);
581 int refined;
582 PetscLogEventBegin(ev.refine, 0, 0, 0, 0);
583 CHKERR refineLevel(m_field, l, local, refined);
584 PetscLogEventEnd(ev.refine, 0, 0, 0, 0);
585 PetscLogDouble t0, t1;
586 CHKERR PetscTime(&t0);
587 PetscLogEventBegin(ev.fieldsFes, 0, 0, 0, 0);
588 CHKERR registerLevel(m_field, l, order, incremental);
589 PetscLogEventEnd(ev.fieldsFes, 0, 0, 0, 0);
590 CHKERR PetscTime(&t1);
591 st.level = l;
592 int duplicates;
593 CHKERR countDuplicateViewEntries(m_field, duplicates);
594 MOFEM_LOG_CHANNEL("WORLD");
595 MOFEM_LOG_TAG("WORLD", "RebuildProblem");
596 MOFEM_LOG("WORLD", Sev::inform)
597 << "Level " << l << (local ? " local" : " uniform")
598 << " refinement of " << refined
599 << " tets; fields and elements registered in " << t1 - t0
600 << " s, duplicate view entries " << duplicates;
601 // Each refined tetrahedron is replaced by eight.
602 CHKERR testing->checkValue<TestType::SCALAR>(
603 tag + " tets after refinement", count_tets(l),
604 tets_before + 7. * refined, zero);
605 CHKERR testing->checkValue<TestType::SCALAR>(
606 tag + " element views without duplicates", duplicates, 0, zero);
608 });
609
610 // Recreate path: the output problem is built while the source is
611 // alive, the source is checked and then destroyed. In-place path: the
612 // alive problem is rebuilt under its own name and DM, and the survivor
613 // index sets are checked.
614 CHKERR testing->addTest(base + 2, tag + " rebuild", [&, l, tag]() {
616 CHKERR require(st.level == l && st.alive && !st.rebuilt,
617 tag + " rebuild needs the refined level and the "
618 "previous problem alive");
619 if (in_place) {
620 std::map<UId, int> old_global;
621 {
622 const Problem *prb;
623 CHKERR m_field.get_problem(st.aliveName, &prb);
624 for (auto &dof : *prb->getNumeredRowDofsPtr())
625 if (dof->getPetscGlobalDofIdx() >= 0)
626 old_global[dof->getLocalUniqueId()] =
627 dof->getPetscGlobalDofIdx();
628 }
629 IS raw_old, raw_new;
630 PetscLogDouble t0, t1;
631 CHKERR PetscTime(&t0);
632 PetscLogEventBegin(ev.rebuild, 0, 0, 0, 0);
633 CHKERR DMMoFEMRebuildProblem(st.alive, bit(l), rebuilt_mask(l),
634 &raw_old, &raw_new);
635 PetscLogEventEnd(ev.rebuild, 0, 0, 0, 0);
636 CHKERR PetscTime(&t1);
637 SmartPetscObj<IS> is_old(raw_old), is_new(raw_new);
638 st.rebuilt = st.alive;
639 st.alive.reset();
640 st.rebuiltName = st.aliveName;
641 st.rebuiltSeconds = t1 - t0;
642 CHKERR summarise(m_field, st.rebuiltName, st.rebuiltSummary);
643 log_level(l, st.rebuiltName + " in place", st.rebuiltSummary,
644 st.rebuiltSeconds);
645 CHKERR testing->checkValue<TestType::SCALAR>(
646 tag + " problem keeps its name",
647 m_field.check_problem(st.rebuiltName) ? 1 : 0, 1, zero);
648 CHKERR testing->checkValue<TestType::SCALAR>(
649 tag + " staging problem removed",
650 m_field.check_problem(st.rebuiltName + "__REBUILD_STAGE") ? 1
651 : 0,
652 0, zero);
653 CHKERR checkSurvivors(m_field, *testing, tag, st.rebuiltName,
654 old_global, st.aliveSummary.localDofs,
655 st.aliveSummary.globalDofs, is_old, is_new);
657 }
658 st.rebuiltName = "P" + std::to_string(l) + "_rebuild";
659 CHKERR buildProblem(m_field, st.rebuiltName, bit(l), rebuilt_mask(l),
660 is_partitioned, ev.rebuild, st.rebuilt,
661 st.rebuiltSeconds);
662 CHKERR summarise(m_field, st.rebuiltName, st.rebuiltSummary);
663 log_level(l, st.rebuiltName, st.rebuiltSummary, st.rebuiltSeconds);
664
665 Summary source_after;
666 CHKERR summarise(m_field, st.aliveName, source_after);
667 CHKERR testing->checkValue<TestType::SCALAR>(
668 tag + " source dofs unchanged", source_after.globalDofs,
669 st.aliveSummary.globalDofs, zero);
670 CHKERR testing->checkValue<TestType::SCALAR>(
671 tag + " source numbering unchanged",
672 source_after.numbering == st.aliveSummary.numbering ? 0 : 1, 0,
673 zero);
674
675 // Commit: destroying the source DM deletes its problem.
676 st.alive.reset();
677 CHKERR testing->checkValue<TestType::SCALAR>(
678 tag + " source problem deleted",
679 m_field.check_problem(st.aliveName) ? 1 : 0, 0, zero);
681 });
682
683 // Oracle: the same level built fresh, alone.
684 CHKERR testing->addTest(base + 3, tag + " fresh build", [&, l, tag]() {
686 CHKERR require(st.level == l && st.rebuilt && !st.alive && !st.fresh,
687 tag + " fresh build needs the rebuilt problem and "
688 "the source destroyed");
689 st.freshName = "P" + std::to_string(l);
690 CHKERR buildProblem(m_field, st.freshName, bit(l), allBits(),
691 is_partitioned, ev.fresh, st.fresh,
692 st.freshSeconds);
693 CHKERR summarise(m_field, st.freshName, st.freshSummary);
694 log_level(l, st.freshName, st.freshSummary, st.freshSeconds);
696 });
697
698 CHKERR testing->addTest(base + 4, tag + " compare", [&, l, tag]() {
700 CHKERR require(st.level == l && st.rebuilt && st.fresh,
701 tag + " compare needs both problems");
702 const auto &r = st.rebuiltSummary, &f = st.freshSummary;
703 CHKERR testing->checkValue<TestType::SCALAR>(
704 tag + " global dofs", r.globalDofs, f.globalDofs, zero);
705 CHKERR testing->checkValue<TestType::SCALAR>(
706 tag + " local dofs", r.localDofs, f.localDofs, zero);
707 CHKERR testing->checkValue<TestType::SCALAR>(
708 tag + " ghost dofs", r.ghostDofs, f.ghostDofs, zero);
709 CHKERR testing->checkValue<TestType::SCALAR>(
710 tag + " elements", r.elements, f.elements, zero);
711 CHKERR testing->checkValue<TestType::SCALAR>(
712 tag + " numbering hash equal",
713 r.numbering == f.numbering ? 0 : 1, 0, zero);
714 Mismatch mismatch;
715 CHKERR compareProblems(m_field, st.rebuiltName, st.freshName, bit(l),
716 mismatch);
717 CHKERR testing->checkValue<TestType::SCALAR>(
718 tag + " dofs missing from fresh", mismatch.missing, 0, zero);
719 CHKERR testing->checkValue<TestType::SCALAR>(
720 tag + " dofs with different index", mismatch.index, 0, zero);
721 CHKERR testing->checkValue<TestType::SCALAR>(
722 tag + " dofs on source-only parents", mismatch.parents, 0, zero);
724 });
725
726 // Matrix graphs agree; then the fresh oracle goes and the rebuilt
727 // problem is the next source.
728 CHKERR testing->addTest(base + 5, tag + " matrix", [&, l, tag]() {
730 CHKERR require(st.level == l && st.rebuilt && st.fresh,
731 tag + " matrix needs both problems");
732 if (!skip_matrix) {
733 double rows_rebuilt, nnz_rebuilt, rows_fresh, nnz_fresh;
734 double seconds_rebuilt, seconds_fresh;
735 MatrixGraph graph;
736 CHKERR matrixInfo(m_field, st.rebuiltName, ev.matrix, rows_rebuilt,
737 nnz_rebuilt, seconds_rebuilt, graph);
738 CHKERR matrixInfo(m_field, st.freshName, ev.matrix, rows_fresh,
739 nnz_fresh, seconds_fresh, graph, true);
740 MOFEM_LOG_CHANNEL("WORLD");
741 MOFEM_LOG_TAG("WORLD", "RebuildProblem");
742 MOFEM_LOG("WORLD", Sev::inform)
743 << "Level " << l << " matrix rows " << rows_rebuilt
744 << ", non-zeros " << nnz_rebuilt << ", created in "
745 << seconds_rebuilt << " s and " << seconds_fresh << " s";
746 CHKERR testing->checkValue<TestType::SCALAR>(
747 tag + " matrix rows", rows_rebuilt, rows_fresh, zero);
748 CHKERR testing->checkValue<TestType::SCALAR>(
749 tag + " matrix rows equal dofs", rows_rebuilt,
750 st.rebuiltSummary.globalDofs, zero);
751 CHKERR testing->checkValue<TestType::SCALAR>(
752 tag + " matrix non-zeros", nnz_rebuilt, nnz_fresh, zero);
753 CHKERR testing->checkValue<TestType::SCALAR>(
754 tag + " matrix rows with different column indices",
755 graph.differentRows, 0, zero);
756 }
757
758 st.fresh.reset();
759 st.alive = st.rebuilt;
760 st.rebuilt.reset();
761 st.aliveName = st.rebuiltName;
762 st.aliveSummary = st.rebuiltSummary;
763 st.aliveSeconds = st.rebuiltSeconds;
765 });
766 }
767
768 // Stages run in ascending number: level 0, then refine, rebuild, fresh,
769 // compare and matrix for each level.
770 CHKERR testing->runTests();
771 }
773
775
776 return 0;
777}
std::map< EntityHandle, int > index
WorkMesh base
std::vector< char > alive
PetscLogEvent event
Tag tag
std::map< EntityHandle, size_t > offsets
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
std::string type
std::vector< FieldBitNumber > row
Definition Schur.cpp:2488
It it
Definition Schur.cpp:2568
It end
Definition Schur.cpp:2568
SmartPetscObj< IS > rows
std::string name
int main()
constexpr double a
#define CATCH_ERRORS
Catch errors.
@ AINSWORTH_LEGENDRE_BASE
Ainsworth Cole (Legendre) approx. base .
Definition definitions.h:60
#define CHK_THROW_MESSAGE(err, msg)
Check and throw MoFEM exception.
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
@ H1
continuous field
Definition definitions.h:85
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_NOT_FOUND
Definition definitions.h:33
@ MOFEM_DATA_INCONSISTENCY
Definition definitions.h:31
@ MOFEM_INVALID_DATA
Definition definitions.h:36
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
constexpr int order
PetscErrorCode DMMoFEMSetIsPartitioned(DM dm, PetscBool is_partitioned)
Definition DMMoFEM.cpp:1199
PetscErrorCode DMMoFEMAddElement(DM dm, std::string fe_name)
add element to dm
Definition DMMoFEM.cpp:574
PetscErrorCode DMMoFEMRebuildProblem(DM dm, const MoFEM::BitRefLevel target_bit, const MoFEM::BitRefLevel target_mask, IS *old_row_indices=PETSC_NULLPTR, IS *new_row_indices=PETSC_NULLPTR)
Rebuild the DM's parent problem in place on a new bit ref level.
Definition DMMoFEM.cpp:479
PetscErrorCode DMMoFEMSetSquareProblem(DM dm, PetscBool square_problem)
set squared problem
Definition DMMoFEM.cpp:536
PetscErrorCode DMMoFEMCreateMoFEM(DM dm, MoFEM::Interface *m_field_ptr, const char problem_name[], const MoFEM::BitRefLevel bit_level, const MoFEM::BitRefLevel bit_mask=MoFEM::BitRefLevel().set())
Must be called by user to set MoFEM data structures.
Definition DMMoFEM.cpp:143
PetscErrorCode DMRegister_MoFEM(const char sname[])
Register MoFEM problem.
Definition DMMoFEM.cpp:43
virtual const Problem * get_problem(const std::string problem_name) const =0
Get the problem object.
virtual const EntFiniteElement_multiIndex * get_ents_finite_elements() const =0
Get the ents finite elements object.
MoFEMErrorCode getEntitiesByDimAndRefLevel(const BitRefLevel bit, const BitRefLevel mask, const int dim, const EntityHandle meshset, int verb=0) const
add all ents from ref level given by bit to meshset
virtual MoFEMErrorCode add_finite_element(const std::string &fe_name, enum MoFEMTypes bh=MF_EXCL, int verb=DEFAULT_VERBOSITY)=0
add finite element
virtual MoFEMErrorCode build_finite_elements(int verb=DEFAULT_VERBOSITY)=0
Build finite elements.
virtual MoFEMErrorCode modify_finite_element_add_field_col(const std::string &fe_name, const std::string name_row)=0
set field col which finite element use
virtual MoFEMErrorCode modify_finite_element_add_field_row(const std::string &fe_name, const std::string name_row)=0
set field row which finite element use
virtual MoFEMErrorCode add_ents_to_finite_element_by_bit_ref(const BitRefLevel bit, const BitRefLevel mask, const std::string name, EntityType type, int verb=DEFAULT_VERBOSITY)=0
add TET entities from given refinement level to finite element database given by name
virtual MoFEMErrorCode modify_finite_element_add_field_data(const std::string &fe_name, const std::string name_field)=0
set finite element field data
virtual MoFEMErrorCode build_fields(int verb=DEFAULT_VERBOSITY)=0
virtual MoFEMErrorCode set_field_order(const EntityHandle meshset, const EntityType type, const std::string &name, const ApproximationOrder order, int verb=DEFAULT_VERBOSITY)=0
Set order approximation of the entities in the field.
virtual MoFEMErrorCode add_ents_to_field_by_type(const Range &ents, const EntityType type, const std::string &name, int verb=DEFAULT_VERBOSITY)=0
Add entities to field meshset.
#define MOFEM_LOG(channel, severity)
Log.
#define MOFEM_LOG_TAG(channel, tag)
Tag channel.
#define MOFEM_LOG_CHANNEL(channel)
Set and reset channel.
virtual MoFEMErrorCode modify_problem_mask_ref_level_set_bit(const std::string &name_problem, const BitRefLevel &bit)=0
set dof mask ref level for problem
virtual MoFEMErrorCode modify_problem_ref_level_set_bit(const std::string &name_problem, const BitRefLevel &bit)=0
set ref level for problem
virtual bool check_problem(const std::string name)=0
check if problem exist
auto bit
set bit
FTensor::Index< 'i', SPACE_DIM > i
PetscBool testing
constexpr int nb_levels
Definition level_set.cpp:58
FTensor::Index< 'l', 3 > l
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
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
PetscErrorCode DMMoFEMSetDestroyProblem(DM dm, PetscBool destroy_problem)
Definition DMMoFEM.cpp:463
PetscErrorCode PetscOptionsGetInt(PetscOptions *, const char pre[], const char name[], PetscInt *ivalue, PetscBool *set)
PetscErrorCode PetscOptionsGetBool(PetscOptions *, const char pre[], const char name[], PetscBool *bval, PetscBool *set)
PetscErrorCode PetscOptionsGetString(PetscOptions *, const char pre[], const char name[], char str[], size_t size, PetscBool *set)
auto createDM(MPI_Comm comm, const std::string dm_type_name)
Creates smart DM object.
constexpr AssemblyType A
static char help[]
FTensor::Index< 'm', 3 > m
Managing BitRefLevels.
virtual moab::Interface & get_moab()=0
virtual MoFEMErrorCode build_adjacencies(const Range &ents, int verb=DEFAULT_VERBOSITY)=0
build adjacencies
virtual MoFEMErrorCode add_field(const std::string name, const FieldSpace space, const FieldApproximationBase base, const FieldCoefficientsNumber nb_of_coefficients, const TagType tag_type=MB_TAG_SPARSE, const enum MoFEMTypes bh=MF_EXCL, int verb=DEFAULT_VERBOSITY)=0
Add field.
virtual MPI_Comm & get_comm() const =0
Core (interface) class.
Definition Core.hpp:83
static MoFEMErrorCode Initialize(int *argc, char ***args, const char file[], const char help[])
Initializes the MoFEM database PETSc, MOAB and MPI.
Definition Core.cpp:68
static MoFEMErrorCode Finalize()
Checks for options to be called at the conclusion of the program.
Definition Core.cpp:123
Deprecated interface functions.
Matrix manager is used to build and partition problems.
Mesh refinement interface.
MoFEMErrorCode addVerticesInTheMiddleOfEdges(const EntityHandle meshset, const BitRefLevel &bit, const bool recursive=false, int verb=QUIET, EntityHandle start_v=0)
make vertices in the middle of edges in meshset and add them to refinement levels defined by bit
Index tags of the numbered DOF containers that also read the index.
keeps basic data about problem
DofIdx getNbLocalDofsRow() const
DofIdx getNbDofsRow() const
const auto & getNumeredFiniteElementsPtr() const
get access to reference for multi-index storing finite elements
DofIdx getNbGhostDofsRow() const
auto & getNumeredRowDofsPtr() const
get access to numeredRowDofsPtr storing DOFs on rows
intrusive_ptr for managing petsc objects
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.