44#include <boost/functional/hash.hpp>
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";
55constexpr const char *fieldName =
"F1";
56constexpr const char *elementName =
"E1";
62 PetscLogEvent refine, fieldsFes, rebuild, fresh, matrix;
67 int globalDofs = 0, localDofs = 0, ghostDofs = 0, elements = 0;
68 std::size_t numbering = 0;
80 PetscInt firstRow = 0, lastRow = 0, differentRows = 0;
81 std::vector<std::size_t>
offsets;
82 std::vector<PetscInt> columns;
96 CHKERR bit_mng->getEntitiesByRefLevel(
bit(
l), allBits(), ents);
97 if (incremental &&
l > 0) {
102 for (
auto type : {MBVERTEX, MBEDGE, MBTRI, MBTET}) {
103 Range of_type = ents.subset_by_type(
type);
111 const Range tets = ents.subset_by_type(MBTET);
128 std::vector<UId> uids;
130 auto &view = *fe->getDataFieldEntsPtr();
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()) -
152 CHKERR bit_mng->getEntitiesByDimAndRefLevel(
bit(
l - 1), allBits(), 3,
154 Range tets = level_tets;
157 CHKERR moab.get_connectivity(level_tets, verts,
true);
158 const EntityHandle vertex = verts.front();
160 CHKERR moab.get_adjacencies(&vertex, 1, 3,
false, star);
161 tets = intersect(star, level_tets);
163 refined = tets.size();
165 CHKERR moab.get_adjacencies(tets, 1,
true, edges, moab::Interface::UNION);
170 const Range unchanged = subtract(level_tets, tets);
171 CHKERR bit_mng->setBitRefLevel(unchanged,
bit(
l),
true);
182 const std::string &
tag,
const std::string &
name,
183 const std::map<UId, int> &old_global,
184 int old_local,
int old_total,
191 PetscInt n_old, n_new;
192 CHKERR ISGetLocalSize(is_old, &n_old);
193 CHKERR ISGetLocalSize(is_new, &n_new);
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);
202 for (PetscInt
i = 0;
i != n_new; ++
i) {
203 auto it = by_global.find(new_idx[
i]);
204 if (
it == by_global.end()) {
208 auto o = old_global.find((*it)->getLocalUniqueId());
209 if (o == old_global.end() || o->second != old_idx[
i])
213 tag +
" survivor pairs map old to new index", wrong, 0, zero);
216 for (
auto it = by_local.lower_bound(0),
219 if (old_global.count((*it)->getLocalUniqueId()))
222 tag +
" every surviving owned dof is listed", n_new, expected, zero);
226 Vec old_vec, new_vec;
227 CHKERR VecCreateMPI(m_field.
get_comm(), old_local, old_total, &old_vec);
229 CHKERR VecGetOwnershipRange(old_vec, &lo, &hi);
232 CHKERR VecGetArray(old_vec, &
a);
233 for (PetscInt
i = lo;
i != hi; ++
i)
235 CHKERR VecRestoreArray(old_vec, &
a);
239 CHKERR VecSet(new_vec, -1);
241 CHKERR VecScatterCreate(old_vec, is_old, new_vec, is_new, &scatter);
242 CHKERR VecScatterBegin(scatter, old_vec, new_vec, INSERT_VALUES,
244 CHKERR VecScatterEnd(scatter, old_vec, new_vec, INSERT_VALUES,
246 CHKERR VecScatterDestroy(&scatter);
247 PetscInt new_lo, new_hi;
248 CHKERR VecGetOwnershipRange(new_vec, &new_lo, &new_hi);
249 int wrong_scatter = 0;
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)
256 else if (
a[new_idx[
i] - new_lo] !=
static_cast<PetscScalar
>(old_idx[
i]))
259 CHKERR VecRestoreArrayRead(new_vec, &
a);
262 tag +
" scatter through survivors carries values", wrong_scatter, 0,
264 CHKERR VecDestroy(&old_vec);
265 CHKERR VecDestroy(&new_vec);
266 CHKERR ISRestoreIndices(is_old, &old_idx);
267 CHKERR ISRestoreIndices(is_new, &new_idx);
275 PetscBool is_partitioned, PetscLogEvent
event,
280 "Problem %s exists: its previous owner was not destroyed",
292 PetscLogDouble t0, t1;
294 PetscLogEventBegin(
event, 0, 0, 0, 0);
296 PetscLogEventEnd(
event, 0, 0, 0, 0);
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());
325 const std::string &rebuilt,
329 const Problem *prb_rebuilt, *prb_fresh;
335 if (!(dof->getBitRefLevel() & level).any())
337 auto it = fresh_by_uid.find(dof->getLocalUniqueId());
338 if (
it == fresh_by_uid.end()) {
342 if ((*it)->getPetscGlobalDofIdx() != dof->getPetscGlobalDofIdx() ||
343 (*it)->getPetscLocalDofIdx() != dof->getPetscLocalDofIdx() ||
344 (*it)->getPart() != dof->getPart())
352 PetscLogEvent
event,
double &
rows,
double &nonzeros,
353 double &seconds, MatrixGraph &graph,
354 bool compare =
false) {
357 PetscLogDouble t0, t1;
359 PetscLogEventBegin(
event, 0, 0, 0, 0);
361 ->createMPIAIJWithArrays<PetscGlobalIdx_mi_tag>(
name,
A);
362 PetscLogEventEnd(
event, 0, 0, 0, 0);
368 CHKERR MatGetInfo(
A, MAT_GLOBAL_SUM, &info);
370 nonzeros = info.nz_used;
374 PetscInt first_row, last_row;
375 CHKERR MatGetOwnershipRange(
A, &first_row, &last_row);
377 if (first_row != graph.firstRow || last_row != graph.lastRow)
379 "Matrix ownership ranges differ");
381 graph.firstRow = first_row;
382 graph.lastRow = last_row;
383 graph.differentRows = 0;
385 graph.offsets.reserve(last_row - first_row + 1);
386 graph.columns.clear();
388 CHKERR MatGetInfo(
A, MAT_LOCAL, &local_info);
389 graph.columns.reserve(
static_cast<std::size_t
>(local_info.nz_used));
391 std::vector<PetscInt> row_columns;
392 for (PetscInt
row = first_row;
row < last_row; ++
row) {
394 const PetscInt *cols;
395 CHKERR MatGetRow(
A,
row, &nb_cols, &cols,
nullptr);
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());
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;
410 graph.columns.insert(graph.columns.end(), row_columns.begin(),
412 graph.offsets.push_back(graph.columns.size());
421 std::string aliveName, rebuiltName, freshName;
422 Summary aliveSummary, rebuiltSummary, freshSummary;
423 double aliveSeconds = 0, rebuiltSeconds = 0, freshSeconds = 0;
429int main(
int argc,
char *argv[]) {
435 moab::Core mb_instance;
436 moab::Interface &moab = mb_instance;
438 char mesh_file_name[255];
439 PetscBool flg = PETSC_FALSE;
441 mesh_file_name, 255, &flg);
442 if (flg != PETSC_TRUE)
444 "-file_name <mesh> is required");
446 PetscBool is_partitioned = PETSC_FALSE, skip_matrix = PETSC_FALSE;
452 &is_partitioned, PETSC_NULLPTR);
459 PetscBool incremental = PETSC_TRUE;
465 PetscInt local_from = -1;
471 PetscBool in_place = PETSC_FALSE;
474 if (in_place && !is_partitioned)
476 "-in_place needs -dm_is_partitioned");
478 CHKERR moab.load_file(mesh_file_name, 0,
"");
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);
496 << (is_partitioned ?
"distributed" :
"replicated") <<
" builder, "
497 << (incremental ?
"incremental" :
"full")
498 <<
" field/element registration, "
499 << (in_place ?
"in-place rebuild" :
"recreate path");
501 auto count_tets = [&](
int l) {
505 bit(
l), allBits(), 3, tets),
510 auto log_level = [&](
int l,
const std::string &
name,
const Summary &
s,
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";
528 auto rebuilt_mask = [&](
int l) {
529 return (local_from >= 0 &&
l >= local_from) ? allBits()
544 auto require = [&](
bool ok,
const std::string &what) {
548 "Stage order broken: %s", what.c_str());
555 PetscLogEventBegin(ev.fieldsFes, 0, 0, 0, 0);
556 CHKERR registerLevel(m_field, 0,
order, incremental);
557 PetscLogEventEnd(ev.fieldsFes, 0, 0, 0, 0);
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);
565 "level 0 has dofs", st.aliveSummary.globalDofs > 0 ? 1 : 0, 1,
571 const auto tag =
"level " + std::to_string(
l);
572 const int base = 10 *
l;
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);
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;
587 PetscLogEventBegin(ev.fieldsFes, 0, 0, 0, 0);
589 PetscLogEventEnd(ev.fieldsFes, 0, 0, 0, 0);
593 CHKERR countDuplicateViewEntries(m_field, duplicates);
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;
603 tag +
" tets after refinement", count_tets(
l),
604 tets_before + 7. * refined, zero);
606 tag +
" element views without duplicates", duplicates, 0, zero);
616 CHKERR require(st.level ==
l && st.alive && !st.rebuilt,
617 tag +
" rebuild needs the refined level and the "
618 "previous problem alive");
620 std::map<UId, int> old_global;
625 if (dof->getPetscGlobalDofIdx() >= 0)
626 old_global[dof->getLocalUniqueId()] =
627 dof->getPetscGlobalDofIdx();
630 PetscLogDouble t0, t1;
632 PetscLogEventBegin(ev.rebuild, 0, 0, 0, 0);
635 PetscLogEventEnd(ev.rebuild, 0, 0, 0, 0);
638 st.rebuilt = st.alive;
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,
646 tag +
" problem keeps its name",
649 tag +
" staging problem removed",
650 m_field.
check_problem(st.rebuiltName +
"__REBUILD_STAGE") ? 1
654 old_global, st.aliveSummary.localDofs,
655 st.aliveSummary.globalDofs, is_old, is_new);
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,
662 CHKERR summarise(m_field, st.rebuiltName, st.rebuiltSummary);
663 log_level(
l, st.rebuiltName, st.rebuiltSummary, st.rebuiltSeconds);
665 Summary source_after;
666 CHKERR summarise(m_field, st.aliveName, source_after);
668 tag +
" source dofs unchanged", source_after.globalDofs,
669 st.aliveSummary.globalDofs, zero);
671 tag +
" source numbering unchanged",
672 source_after.numbering == st.aliveSummary.numbering ? 0 : 1, 0,
678 tag +
" source problem deleted",
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,
693 CHKERR summarise(m_field, st.freshName, st.freshSummary);
694 log_level(
l, st.freshName, st.freshSummary, st.freshSeconds);
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;
704 tag +
" global dofs", r.globalDofs,
f.globalDofs, zero);
706 tag +
" local dofs", r.localDofs,
f.localDofs, zero);
708 tag +
" ghost dofs", r.ghostDofs,
f.ghostDofs, zero);
710 tag +
" elements", r.elements,
f.elements, zero);
712 tag +
" numbering hash equal",
713 r.numbering ==
f.numbering ? 0 : 1, 0, zero);
715 CHKERR compareProblems(m_field, st.rebuiltName, st.freshName,
bit(
l),
718 tag +
" dofs missing from fresh", mismatch.missing, 0, zero);
720 tag +
" dofs with different index", mismatch.index, 0, zero);
722 tag +
" dofs on source-only parents", mismatch.parents, 0, zero);
730 CHKERR require(st.level ==
l && st.rebuilt && st.fresh,
731 tag +
" matrix needs both problems");
733 double rows_rebuilt, nnz_rebuilt, rows_fresh, nnz_fresh;
734 double seconds_rebuilt, seconds_fresh;
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);
743 <<
"Level " <<
l <<
" matrix rows " << rows_rebuilt
744 <<
", non-zeros " << nnz_rebuilt <<
", created in "
745 << seconds_rebuilt <<
" s and " << seconds_fresh <<
" s";
747 tag +
" matrix rows", rows_rebuilt, rows_fresh, zero);
749 tag +
" matrix rows equal dofs", rows_rebuilt,
750 st.rebuiltSummary.globalDofs, zero);
752 tag +
" matrix non-zeros", nnz_rebuilt, nnz_fresh, zero);
754 tag +
" matrix rows with different column indices",
755 graph.differentRows, 0, zero);
759 st.alive = st.rebuilt;
761 st.aliveName = st.rebuiltName;
762 st.aliveSummary = st.rebuiltSummary;
763 st.aliveSeconds = st.rebuiltSeconds;
std::map< EntityHandle, int > index
std::vector< char > alive
std::map< EntityHandle, size_t > offsets
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
std::vector< FieldBitNumber > row
#define CATCH_ERRORS
Catch errors.
@ AINSWORTH_LEGENDRE_BASE
Ainsworth Cole (Legendre) approx. base .
#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()
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_DATA_INCONSISTENCY
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
PetscErrorCode DMMoFEMSetIsPartitioned(DM dm, PetscBool is_partitioned)
PetscErrorCode DMMoFEMAddElement(DM dm, std::string fe_name)
add element to dm
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.
PetscErrorCode DMMoFEMSetSquareProblem(DM dm, PetscBool square_problem)
set squared problem
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.
PetscErrorCode DMRegister_MoFEM(const char sname[])
Register MoFEM problem.
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
FTensor::Index< 'i', SPACE_DIM > i
FTensor::Index< 'l', 3 > l
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
std::bitset< BITREFLEVEL_SIZE > BitRefLevel
Bit structure attached to each entity identifying to what mesh entity is attached.
implementation of Data Operators for Forces and Sources
PetscErrorCode DMMoFEMSetDestroyProblem(DM dm, PetscBool destroy_problem)
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.
FTensor::Index< 'm', 3 > m
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
static MoFEMErrorCode Initialize(int *argc, char ***args, const char file[], const char help[])
Initializes the MoFEM database PETSc, MOAB and MPI.
static MoFEMErrorCode Finalize()
Checks for options to be called at the conclusion of the program.
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.