v0.16.3
Loading...
Searching...
No Matches
FUN-3: Reconstruct a distributed mesh

Generate a sphere from a Python SDF, partition it, gradually stretch and twist its vertices, reconstruct Delaunay connectivity, and rebuild a hybrid problem at every checkpoint. Rank 0 retains the complete active mesh; workers retain their owned cells, a vertex-adjacent halo, cells incident to their preferred-owned faces and required parent topology. Extra cell copies are non-owned ghosts. Vertex global IDs survive every stage. Representative parents provide partition lineage; incident cells determine sharing. Field transfer is independent. Each stage writes a native MOAB H5M checkpoint.

Requires CGAL and Boost.Python/NumPy. From the installed tutorial directory:

mpirun -np 2 ./mesh_reconstruction -json_config fun3.json -stretch_steps 20 -twist_degrees 60

stretch_steps defaults to 10. scale_x/y/z give the final axis scales; axis lengths change linearly from 1 to those values. twist_degrees defaults to 60 and gives the relative rotation about the x axis between original planes x=-1 and x=+1. This position-dependent rotation is applied in sphere coordinates before stretching, so the analytic boundary remains an ellipsoid. Set -twist_degrees 0 for pure stretching. Each reconstruction uses the previous synchronised mesh. The log reports removed/added tetrahedra and skin triangles, indicating connectivity changes rather than counting individual flips.

The initial checkpoints are 01_sphere.h5m, 02_partitioned.h5m and 03_distributed.h5m. Each increment writes 04_ellipsoid_0001.h5m, 05_reconstructed_0001.h5m and 06_synchronised_0001.h5m, followed by 0002, etc. Some increments may leave connectivity unchanged. The 04 files retain the old connectivity after moving vertices; nonlinear motion can invalidate old cells before reconstruction. The reconstructed and synchronised meshes have positive tetrahedron volumes.

The example keeps one MOAB/MoFEM database and all three DMs alive through all stages. Each checkpoint updates the parent with DMMoFEMRebuildProblem(), refreshes numbering in the SCHUR (HYBRID) and BLOCK (BROKEN and U) sub-DMs, rebuilds block and nested Schur structures in place, and creates new matrix objects, following atom_tests/rebuild_problem_hybrid.cpp. Field and finite-element registration is refreshed after topology or partition changes, with field DOF construction restricted to new memberships. It is retained at coordinate-only and sharing-verification stages.

-rebuild_structures defaults to true; false creates fresh block/nested structures for comparison. -check_rebuilt_structures additionally compares rebuilt block indices, layouts and element patterns with fresh structures at every checkpoint. This check is intended for validation and adds extra work. -hybrid_order defaults to 2: BROKEN is broken H(div) of order p, U is cell L2 of order p-1 and HYBRID is interior-face L2 of order p-1. Interior faces are identified using root's complete mesh so partition boundaries remain part of the skeleton. The example checks DOF counts, vector/matrix dimensions and the hybrid matrix graph; it fills that graph with ones for validation. It does not solve a physical model or transfer a solution.

Matrices, solver contexts and cached vectors are released before topology edits. Surviving entities retain their handles and field DOFs. Older source lineage is removed, sharing registrations are reset, and source/output refinement bits are assigned again before importing and pruning the next mesh. Parent/sub-DMs and block storage are retained. Sharing is already established before the 02 and 05 checkpoint builds; 03 and 06 verify the prepared layout and rebuild the algebra again. Checkpoints contain a FUN3_HYBRID_COUNTS summary checked independently against their saved topology.

Reconstruction gathers the complete vertex/source-topology description on one producer. Indexed mesh descriptions are temporarily broadcast in full before workers prune their resident topology and release transport buffers. This small example demonstrates correctness rather than distributed Delaunay scalability. The reconstructed mesh fills the convex hull of the moved vertices. The sphere script supplies values only; derivatives are unnecessary.

/** \file mesh_reconstruction.cpp
* \example mesh_reconstruction.cpp
*/
#include <MoFEM.hpp>
#include <iomanip>
using namespace MoFEM;
struct Example {
currentPtr = std::make_unique<Mesh>();
CHKERR saveStage(*currentPtr, "01_sphere", false);
CHKERR saveStage(*currentPtr, "02_partitioned", false);
CHKERR saveStage(*currentPtr, "03_distributed", true);
for (PetscInt step = 1; step <= stretchSteps; ++step) {
CHKERR saveStage(*currentPtr, "04_ellipsoid", true, step);
CHKERR saveStage(*currentPtr, "05_reconstructed", false, step);
CHKERR saveStage(*currentPtr, "06_synchronised", true, step);
}
MOFEM_LOG("WORLD", Sev::inform)
<< "Completed " << stretchSteps << " stretch/reconstruction steps";
}
private:
// Keep each MOAB database alive until its MoFEM interfaces are destroyed.
// Keep entity handles stable across reconstruction for DM/storage reuse.
struct Mesh {
moab::Core database;
bool sharingReady = false;
bool registrationChanged = true;
};
std::unique_ptr<Mesh> currentPtr;
PetscInt stretchSteps = 10;
PetscInt hybridOrder = 2;
double twistDegrees = 60;
std::array<double, 3> scale{2, 1, .75};
std::string script;
// Complete rank-local work before deciding collectively whether to continue.
int error;
CHKERR MPI_Allreduce(&local_error, &error, 1, MPI_INT, MPI_MAX,
currentPtr->field.get_comm());
if (error)
SETERRQ(currentPtr->field.get_comm(), error,
"Mesh stage failed on an MPI rank");
}
currentPtr->field.getInterface<JsonConfigManager>();
char file[PETSC_MAX_PATH_LEN] = "sphere.py";
CHKERR PetscOptionsGetString(nullptr, nullptr, "-sdf_file", file,
sizeof(file), nullptr);
CHKERR PetscOptionsGetInt(nullptr, nullptr, "-hybrid_order", &hybridOrder,
nullptr);
if (hybridOrder < 1)
SETERRQ(currentPtr->field.get_comm(), MOFEM_INVALID_DATA,
"hybrid_order must be positive");
CHKERR PetscOptionsGetReal(nullptr, nullptr, "-twist_degrees",
&twistDegrees, nullptr);
if (!std::isfinite(twistDegrees))
SETERRQ(currentPtr->field.get_comm(), MOFEM_INVALID_DATA,
"twist_degrees must be finite");
CHKERR PetscOptionsGetInt(nullptr, nullptr, "-stretch_steps", &stretchSteps,
nullptr);
if (stretchSteps < 1)
SETERRQ(currentPtr->field.get_comm(), MOFEM_INVALID_DATA,
"stretch_steps must be positive");
CHKERR PetscOptionsGetReal(nullptr, nullptr, "-cell_size",
&settings.cellSize, nullptr);
CHKERR PetscOptionsGetReal(nullptr, nullptr, "-facet_size",
&settings.facetSize, nullptr);
CHKERR PetscOptionsGetReal(nullptr, nullptr, "-facet_distance",
&settings.facetDistance, nullptr);
CHKERR PetscOptionsGetReal(nullptr, nullptr, "-bounding_radius",
&settings.radius, nullptr);
for (int d = 0; d != 3; ++d) {
const std::string option = std::string("-scale_") + "xyz"[d];
CHKERR PetscOptionsGetReal(nullptr, nullptr, option.c_str(), &scale[d],
nullptr);
if (!std::isfinite(scale[d]) || scale[d] <= 0)
SETERRQ(currentPtr->field.get_comm(), MOFEM_INVALID_DATA,
"Scaling must be positive");
}
}
if (currentPtr->field.get_comm_rank())
CHKERR sdf.sdfInit(script);
auto cgal = currentPtr->field.getInterface<CGALInterface>();
sphere, [&](const auto &point) { return sdf.value(point); }, settings);
EntityHandle volume, surface;
CHKERR cgal->importMesh(sphere, BitRefLevel().set(0), currentPtr->entities,
volume, surface);
const int owner = 0;
auto *pc =
ParallelComm::get_pcomm(&currentPtr->field.get_moab(), MYPCOMM_INDEX);
CHKERR currentPtr->field.get_moab().tag_clear_data(
pc->part_tag(), currentPtr->entities, &owner);
}
CHKERR currentPtr->hybrid.prepareUpdate();
currentPtr->sharingReady = false;
currentPtr->registrationChanged = true;
auto comm = currentPtr->field.getInterface<CommInterface>();
EntityHandle volume, surface;
MoFEMErrorCode error = 0;
if (currentPtr->field.get_comm_rank())
error = currentPtr->field.getInterface<CGALInterface>()->importMesh(
sphere, BitRefLevel().set(0), currentPtr->entities, volume, surface);
CHKERR agree(error);
const int initial_owner = 0;
auto &mb = currentPtr->field.get_moab();
auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
CHKERR mb.tag_clear_data(pc->part_tag(), currentPtr->entities,
&initial_owner);
CHKERR comm->partitionMesh(currentPtr->entities.subset_by_type(MBTET), 3, 2,
currentPtr->field.get_comm_size(), nullptr,
nullptr, nullptr, QUIET, false, true);
}
}
MoFEMErrorCode deformMesh(PetscInt step) {
auto &mb = currentPtr->field.get_moab();
const double before = static_cast<double>(step - 1) / stretchSteps;
const double after = static_cast<double>(step) / stretchSteps;
std::array<double, 3> old_scale, new_scale;
for (int d = 0; d != 3; ++d) {
old_scale[d] = 1. + before * (scale[d] - 1.);
new_scale[d] = 1. + after * (scale[d] - 1.);
}
// Relative twist between the original unit sphere's x=-1 and x=+1 planes.
const double angle_increment =
.5 * twistDegrees * std::acos(-1.) / 180. / stretchSteps;
for (auto vertex : currentPtr->entities.subset_by_type(MBVERTEX)) {
std::array<double, 3> x;
CHKERR mb.get_coords(&vertex, 1, x.data());
for (int d = 0; d != 3; ++d)
x[d] /= old_scale[d];
const double angle = angle_increment * x[0];
const double c = std::cos(angle), s = std::sin(angle);
const std::array<double, 3> rotated{x[0], c * x[1] - s * x[2],
s * x[1] + c * x[2]};
for (int d = 0; d != 3; ++d)
x[d] = new_scale[d] * rotated[d];
CHKERR mb.set_coords(&vertex, 1, x.data());
}
}
static auto cellKeys(const TetMeshData &mesh) {
std::set<std::array<int, 4>> keys;
for (const auto &cell : mesh.cells) {
std::array<int, 4> ids;
for (int d = 0; d != 4; ++d)
ids[d] = mesh.vertexIds[cell[d]];
std::sort(ids.begin(), ids.end());
keys.insert(ids);
}
return keys;
}
static auto skinKeys(const TetMeshData &mesh) {
std::map<std::array<int, 3>, int> incidence;
for (const auto &cell : mesh.cells)
for (int opposite = 0; opposite != 4; ++opposite) {
std::array<int, 3> face;
int n = 0;
for (int d = 0; d != 4; ++d)
if (d != opposite)
face[n++] = mesh.vertexIds[cell[d]];
std::sort(face.begin(), face.end());
++incidence[face];
}
std::set<std::array<int, 3>> skin;
for (const auto &[face, count] : incidence)
if (count == 1)
skin.insert(face);
return skin;
}
if (!currentPtr->field.get_comm_rank()) {
currentPtr->field.getInterface<CGALInterface>()
->getTools()
auto changes = [](const auto &before, const auto &after) {
const auto retained =
std::count_if(before.begin(), before.end(),
[&](const auto &key) { return after.count(key); });
return std::make_pair(before.size() - retained,
after.size() - retained);
};
const auto cells = changes(cellKeys(sourceMesh), cellKeys(reconstructed));
const auto skin = changes(skinKeys(sourceMesh), skinKeys(reconstructed));
MOFEM_LOG("WORLD", Sev::inform)
<< "Step " << step << "/" << stretchSteps << ": tetrahedra removed "
<< cells.first << ", added " << cells.second
<< "; skin triangles removed " << skin.first << ", added "
<< skin.second;
}
}
CHKERR currentPtr->hybrid.prepareUpdate();
auto source_comm = currentPtr->field.getInterface<CommInterface>();
auto output_comm = currentPtr->field.getInterface<CommInterface>();
CHKERR source_comm->gatherMesh(currentPtr->entities.subset_by_type(MBTET),
// Keep surviving handles and the parent DM; discard only older lineage.
currentPtr->activeBit = BitRefLevel().set(1);
currentPtr->sharingReady = false;
currentPtr->registrationChanged = true;
auto cgal = currentPtr->field.getInterface<CGALInterface>();
EntityHandle volume, surface;
CHKERR agree(cgal->importMesh(sourceMesh, BitRefLevel().set(0),
sourceLineage, volume, surface));
CHKERR agree(cgal->importMesh(reconstructed, BitRefLevel().set(1),
currentPtr->entities, volume, surface));
sourceLineage, currentPtr->entities, BitRefLevel().set(1)));
output_comm->inheritPartitions(sourceLineage, currentPtr->entities));
}
// Detach obsolete registration before importing into the persistent database.
// Full indexed descriptions are still broadcast; this is not delta transport.
auto &field = currentPtr->field;
auto &mb = field.get_moab();
Range geometry;
CHKERR mb.get_entities_by_handle(0, geometry);
geometry = subtract(geometry, geometry.subset_by_type(MBENTITYSET));
// Surviving handles keep their field DOFs. Obsolete lineage is removed
// below; the hybrid update prunes field/FE membership to the active set.
// BitRefManager's setters add bits. Clear the previous active selector
// before assigning this step's source/output bits to surviving handles.
const BitRefLevel no_bits;
CHKERR mb.tag_clear_data(field.get_basic_entity_data_ptr()->th_RefBitLevel,
geometry, &no_bits);
const EntityHandle no_parent = 0;
CHKERR mb.tag_clear_data(
field.getInterface<BitRefManager>()->get_th_RefParentHandle(), geometry,
&no_parent);
auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
const unsigned char unshared = 0;
CHKERR mb.tag_clear_data(pc->pstatus_tag(), geometry, &unshared);
for (auto tag : {pc->sharedp_tag(), pc->sharedps_tag(), pc->sharedh_tag(),
pc->sharedhs_tag()}) {
const auto error = mb.tag_delete_data(tag, geometry);
if (error != MB_SUCCESS && error != MB_TAG_NOT_FOUND)
CHKERR error;
}
Range sets = pc->interface_sets();
sets.merge(pc->partition_sets());
CHKERR mb.delete_entities(sets);
// Recreating this registry clears MOAB's private shared-entity table too.
// The mesh, MoFEM core and parent DM remain alive.
delete pc;
int id = -1;
pc = new ParallelComm(&mb, field.get_comm(), &id);
if (id != MYPCOMM_INDEX)
SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
"Unexpected ParallelComm index after resetting sharing");
CHKERR deleteGeometry(subtract(geometry, currentPtr->entities));
sourceLineage.clear();
}
if (remove.empty())
auto &field = currentPtr->field;
auto &mb = field.get_moab();
CHKERR field.remove_ents(remove, QUIET);
Range sets;
CHKERR mb.get_entities_by_type(0, MBENTITYSET, sets);
for (auto set : sets)
CHKERR mb.remove_entities(set, remove);
for (int dim = 3; dim >= 0; --dim) {
const auto batch = remove.subset_by_dimension(dim);
if (!batch.empty())
CHKERR mb.delete_entities(batch);
}
}
auto trim_lineage = [&]() {
if (!currentPtr->field.get_comm_rank())
auto &field = currentPtr->field;
auto &mb = field.get_moab();
Range needed = currentPtr->entities;
const auto parent_tag =
field.getInterface<BitRefManager>()->get_th_RefParentHandle();
for (auto entity : currentPtr->entities) {
EntityHandle parent = 0;
CHKERR mb.tag_get_data(parent_tag, &entity, 1, &parent);
if (parent)
needed.insert(parent);
}
for (int dim = 2; dim >= 0; --dim) {
CHKERR mb.get_adjacencies(needed.subset_by_dimension(dim + 1), dim,
false, closure, moab::Interface::UNION);
needed.merge(closure);
}
const auto remove = subtract(sourceLineage, needed);
if (remove.empty())
sourceLineage = intersect(sourceLineage, needed);
};
CHKERR agree(trim_lineage());
}
MoFEMErrorCode prepareDistributed(Mesh &mesh, const Range &preserve = {}) {
auto &field = mesh.field;
auto &mb = field.get_moab();
auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
if (!mesh.sharingReady) {
CHKERR mesh.hybrid.prepareUpdate();
auto retain = [&]() {
if (!field.get_comm_rank())
const auto cells = mesh.entities.subset_by_type(MBTET);
Range owned, vertices, halo;
for (auto cell : cells) {
int owner;
CHKERR mb.tag_get_data(pc->part_tag(), &cell, 1, &owner);
if (owner == field.get_comm_rank())
owned.insert(cell);
}
CHKERR mb.get_connectivity(owned, vertices, true);
CHKERR mb.get_adjacencies(vertices, 3, false, halo,
moab::Interface::UNION);
// A reconstructed face inherits its representative parent's owner.
// That rank need not own either incident output cell. Keep both cells
// for every preferred-owned face as well as the owned-cell halo.
Range owned_faces, face_cells;
for (auto face : mesh.entities.subset_by_type(MBTRI)) {
int owner;
CHKERR mb.tag_get_data(pc->part_tag(), &face, 1, &owner);
if (owner == field.get_comm_rank())
owned_faces.insert(face);
}
CHKERR mb.get_adjacencies(owned_faces, 3, false, face_cells,
moab::Interface::UNION);
halo.merge(face_cells);
// Select only the active reconstruction, never inactive lineage cells.
halo = intersect(halo, cells);
for (int dim : {0, 1, 2}) {
CHKERR mb.get_adjacencies(halo.subset_by_type(MBTET), dim, false,
closure, moab::Interface::UNION);
halo.merge(closure);
}
Range protected_entities = preserve;
protected_entities.merge(halo);
CHKERR field.getInterface<CommInterface>()->retainPartition(
mesh.entities, mesh.activeBit, protected_entities);
mesh.entities = halo;
};
CHKERR agree(retain());
CHKERR field.getInterface<BitRefManager>()->setBitRefLevel(
mesh.entities, mesh.activeBit, false);
CHKERR field.getInterface<CommInterface>()->synchroniseByConnectivity(
mesh.entities, 0);
mesh.sharingReady = true;
}
int owned = 0, invalid = 0;
for (auto cell : mesh.entities.subset_by_type(MBTET)) {
int owner;
unsigned char status;
CHKERR mb.tag_get_data(pc->part_tag(), &cell, 1, &owner);
CHKERR pc->get_pstatus(cell, status);
owned += owner == field.get_comm_rank();
invalid += owner != field.get_comm_rank() && !(status & PSTATUS_GHOST);
}
int global_owned, root_cells = mesh.entities.num_of_type(MBTET);
CHKERR MPI_Allreduce(&owned, &global_owned, 1, MPI_INT, MPI_SUM,
field.get_comm());
CHKERR MPI_Bcast(&root_cells, 1, MPI_INT, 0, field.get_comm());
auto testing_ptr = field.getInterface<TestingInterface>();
const auto zero = TestingInterface::Tolerance{0, 0};
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
"root retains every owned cell", root_cells, global_owned, zero);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
"off-partition residents are ghost cells", invalid, 0, zero);
CHKERR pc->check_all_shared_handles();
}
MoFEMErrorCode rebuildHybrid(Mesh &mesh, const std::string &tag) {
auto &field = mesh.field;
auto &mb = field.get_moab();
std::vector<std::array<int, 3>> keys;
auto find_interior = [&]() {
if (field.get_comm_rank())
const auto tets = mesh.entities.subset_by_type(MBTET);
CHKERR mb.get_adjacencies(tets, 2, true, faces, moab::Interface::UNION);
Skinner skinner(&mb);
CHKERR skinner.find_skin(0, tets, false, skin);
for (auto face : subtract(faces, skin)) {
const EntityHandle *conn;
int n;
std::array<int, 3> ids;
CHKERR mb.get_connectivity(face, conn, n, true);
CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 3, ids.data());
std::sort(ids.begin(), ids.end());
keys.push_back(ids);
}
if (keys.size() > static_cast<size_t>(INT_MAX) / 3)
SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
"Skeleton exceeds MPI count range");
};
CHKERR agree(find_interior());
int count = keys.size();
CHKERR MPI_Bcast(&count, 1, MPI_INT, 0, field.get_comm());
keys.resize(count);
CHKERR MPI_Bcast(keys.data(), 3 * count, MPI_INT, 0, field.get_comm());
const std::set<std::array<int, 3>> interior(keys.begin(), keys.end());
Range skeleton;
auto select_skeleton = [&]() {
for (auto face : mesh.entities.subset_by_type(MBTRI)) {
const EntityHandle *conn;
int n;
std::array<int, 3> ids;
CHKERR mb.get_connectivity(face, conn, n, true);
CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 3, ids.data());
std::sort(ids.begin(), ids.end());
if (interior.count(ids))
skeleton.insert(face);
}
};
CHKERR agree(select_skeleton());
CHKERR mesh.hybrid.build(mesh.entities, skeleton, mesh.activeBit,
hybridOrder, mesh.registrationChanged);
CHKERR mesh.hybrid.validate(mesh.entities, skeleton, hybridOrder, tag);
mesh.registrationChanged = false;
}
MoFEMErrorCode saveStage(Mesh &mesh, const char *stage, bool distributed,
PetscInt step = 0) {
auto &m_field = mesh.field;
const auto &entities = mesh.entities;
std::ostringstream name;
name << stage;
if (step)
name << "_" << std::setw(4) << std::setfill('0') << step;
name << ".h5m";
const auto file = name.str();
auto write = [&]() {
if (!distributed && m_field.get_comm_rank())
auto &mb = m_field.get_moab();
EntityHandle selection;
CHKERR mb.create_meshset(MESHSET_SET, selection);
CHKERR mb.add_entities(selection, entities);
Tag summary_tag;
CHKERR mb.tag_get_handle("FUN3_HYBRID_COUNTS", 5, MB_TYPE_DOUBLE,
summary_tag, MB_TAG_SPARSE | MB_TAG_CREAT);
CHKERR mb.tag_set_data(summary_tag, &selection, 1,
mesh.hybrid.summary.data());
auto pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
auto tag = pc->part_tag();
Range parts;
CHKERR mb.get_entities_by_type_and_tag(0, MBENTITYSET, &tag, nullptr, 1,
parts);
CHKERR mb.add_entities(selection, parts);
CHKERR mb.write_file(file.c_str(), "MOAB",
distributed ? "PARALLEL=WRITE_PART" : "", &selection,
1);
CHKERR mb.delete_entities(&selection, 1);
};
CHKERR agree(write());
MOFEM_LOG("WORLD", Sev::inform) << "Saved " << file;
}
};
int main(int argc, char *argv[]) {
&argc, &argv, nullptr,
"Sphere, partition, stretch, twist and reconstruct a mesh\n");
try {
CHKERR SDFPython::initialise();
{
}
CHKERR SDFPython::finalise();
}
return 0;
}
CGALInterfaceImpl & owner
std::vector< std::array< EntityHandle, 3 > > faces
Sorted keys.
FaceSet skin
bool angle
Radians between candidate face and target plane.
WorkMesh mesh
std::vector< int > vertices
std::vector< int > parent
bool closure
The face (f0, f1, w) closes a corner at f0 or f1.
std::vector< Cell > cells
unsigned char status
ParentChildKey key
MPI_Comm comm
moab::Interface & mb
Tag tag
ProjectedField & field
Reusable hybrid algebra and graph validation for FUN-3.
std::string name
int main()
@ QUIET
#define CATCH_ERRORS
Catch errors.
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define MYPCOMM_INDEX
default communicator number PCOMM
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ 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.
PetscErrorCode DMRegister_MoFEM(const char sname[])
Register MoFEM problem.
Definition DMMoFEM.cpp:43
#define MOFEM_LOG(channel, severity)
Log.
const double c
speed of light (cm/ns)
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
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 PetscOptionsGetInt(PetscOptions *, const char pre[], const char name[], PetscInt *ivalue, PetscBool *set)
PetscErrorCode PetscOptionsGetReal(PetscOptions *, const char pre[], const char name[], PetscReal *dval, PetscBool *set)
PetscErrorCode PetscOptionsGetString(PetscOptions *, const char pre[], const char name[], char str[], size_t size, PetscBool *set)
Definition sdf.py:1
MoFEM::CoreTmp<-1 > core
Fun3::HybridProblem hybrid
MoFEM::Interface & field
[Example]
Definition plastic.cpp:209
std::unique_ptr< Mesh > currentPtr
TetMeshData reconstructed
MoFEMErrorCode rebuildHybrid(Mesh &mesh, const std::string &tag)
MoFEMErrorCode deleteGeometry(const Range &remove)
MoFEMErrorCode generateSphere()
CGALTools::ImplicitMeshSettings settings
PetscInt stretchSteps
TetMeshData sourceMesh
TetMeshData sphere
MoFEMErrorCode distributeSphere()
MoFEMErrorCode reconstructOnRoot(PetscInt step)
static auto skinKeys(const TetMeshData &mesh)
MoFEMErrorCode reconstructMesh(PetscInt step)
MoFEMErrorCode saveStage(Mesh &mesh, const char *stage, bool distributed, PetscInt step=0)
MoFEMErrorCode run()
static auto cellKeys(const TetMeshData &mesh)
std::string script
MoFEMErrorCode readOptions()
MoFEMErrorCode synchroniseMesh()
MoFEMErrorCode resetMeshForImport()
MoFEMErrorCode deformMesh(PetscInt step)
MoFEMErrorCode partitionSphere()
PetscInt hybridOrder
MoFEMErrorCode agree(MoFEMErrorCode local_error)
MoFEMErrorCode prepareDistributed(Mesh &mesh, const Range &preserve={})
std::array< double, 3 > scale
Retain the parent/sub-DMs, field DOFs and block storage across mesh edits.
Managing BitRefLevels.
Tag get_th_RefParentHandle() const
virtual CGALTools & getTools()=0
virtual MoFEMErrorCode importMesh(const TetMeshData &data, BitRefLevel bit, Range &entities, EntityHandle &volume, EntityHandle &surface)=0
virtual MoFEMErrorCode reconstructDelaunay(const Range &source_entities, BitRefLevel output_bit, Range &entities, CGALTools::ReconstructionMethod method=CGALTools::ReconstructionMethod::PointDelaunay)=0
void createImplicitMesh(TetMeshData &result, const std::function< double(const std::array< double, 3 > &)> &sdf, const ImplicitMeshSettings &settings) const
Managing BitRefLevels.
MoFEMErrorCode inheritPartitions(const Range &source_entities, const Range &child_entities)
MoFEMErrorCode gatherMesh(const Range &cells, TetMeshData &data, int root=0)
MoFEMErrorCode broadcastMesh(TetMeshData &data, int root=0)
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.
Mesh refinement interface.
MoFEMErrorCode setTopologicalParents(const Range &source_entities, const Range &child_entities, const BitRefLevel &output_bit, int verb=QUIET, const std::map< EntityHandle, EntityHandle > &moved_vertices={})
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.
/** \file HybridProblem.hpp
* \brief Reusable hybrid algebra and graph validation for FUN-3.
*/
#ifndef FUN3_HYBRID_PROBLEM_HPP
#define FUN3_HYBRID_PROBLEM_HPP
#include <unordered_map>
namespace Fun3 {
using namespace MoFEM;
const Range &tets, Mat matrix,
const std::string &tag,
double &nonzeros) {
const Problem *problem_ptr;
CHKERR DMMoFEMGetProblemPtr(dm, &problem_ptr);
std::unordered_map<EntityHandle, std::vector<PetscInt>> face_dofs;
for (auto &dof : *problem_ptr->getNumeredColDofsPtr())
if (dof->getPetscGlobalDofIdx() >= 0)
face_dofs[dof->getEnt()].push_back(dof->getPetscGlobalDofIdx());
// Every active cell couples all its skeleton faces, including each face
// with itself. Deduplication accounts for a face belonging to two cells.
std::unordered_map<EntityHandle, std::vector<PetscInt>> neighbors;
for (auto tet : tets) {
CHKERR m_field.get_moab().get_adjacencies(&tet, 1, 2, false, faces);
std::vector<PetscInt> columns;
for (auto face : faces) {
auto it = face_dofs.find(face);
if (it != face_dofs.end())
columns.insert(columns.end(), it->second.begin(), it->second.end());
}
for (auto face : faces)
if (face_dofs.count(face)) {
auto &adj = neighbors[face];
adj.insert(adj.end(), columns.begin(), columns.end());
}
}
PetscInt first_row, last_row;
CHKERR MatGetOwnershipRange(matrix, &first_row, &last_row);
MatInfo before;
CHKERR MatGetInfo(matrix, MAT_GLOBAL_SUM, &before);
CHKERR MatSetOption(matrix, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE);
double local_nnz = 0, root_nnz = 0;
for (auto &entry : neighbors) {
auto &columns = entry.second;
std::sort(columns.begin(), columns.end());
columns.erase(std::unique(columns.begin(), columns.end()), columns.end());
const PetscInt nb_cols = columns.size();
if (m_field.get_comm_rank() == 0)
root_nnz +=
static_cast<double>(nb_cols) * face_dofs.at(entry.first).size();
const std::vector<PetscScalar> values(nb_cols, 1.);
for (auto row : face_dofs.at(entry.first))
if (row >= first_row && row < last_row) {
local_nnz += nb_cols;
CHKERR MatSetValues(matrix, 1, &row, nb_cols, columns.data(),
values.data(), INSERT_VALUES);
}
}
double expected_nnz;
CHKERR MPI_Allreduce(&local_nnz, &expected_nnz, 1, MPI_DOUBLE, MPI_SUM,
m_field.get_comm());
CHKERR MPI_Bcast(&root_nnz, 1, MPI_DOUBLE, 0, m_field.get_comm());
const auto zero = TestingInterface::Tolerance{0, 0};
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " distributed graph equals complete root graph", expected_nnz,
root_nnz, zero);
// MPI ghost contributions can overestimate preallocation. The used graph
// below must still be exact, and filling it must require no new allocation.
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " hybrid allocation covers topology non-zeros",
before.nz_allocated >= expected_nnz ? 0 : 1, 0, zero);
if (m_field.get_comm_size() == 1)
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " serial hybrid allocation is exact", before.nz_allocated,
expected_nnz, zero);
CHKERR MatAssemblyBegin(matrix, MAT_FINAL_ASSEMBLY);
CHKERR MatAssemblyEnd(matrix, MAT_FINAL_ASSEMBLY);
MatInfo after;
CHKERR MatGetInfo(matrix, MAT_GLOBAL_SUM, &after);
nonzeros = after.nz_used;
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " hybrid filled non-zeros equal topology", nonzeros, expected_nnz,
zero);
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " hybrid fill without reallocations", after.mallocs, before.mallocs,
zero);
PetscBool missing;
PetscInt missing_row;
CHKERR MatMissingDiagonal(matrix, &missing, &missing_row);
CHKERR testing.checkValue<TestType::SCALAR>(
tag + " hybrid diagonal exists in every row", missing ? 1 : 0, 0, zero);
}
/// Retain the parent/sub-DMs, field DOFs and block storage across mesh edits.
struct HybridProblem {
bool configured = false;
bool updatePrepared = false;
bool structuresReused = false;
PetscBool rebuildStructures = PETSC_TRUE,
checkRebuiltStructures = PETSC_FALSE;
std::array<double, 5> summary{};
std::array<PetscObjectId, 3> dmIds{};
std::array<boost::shared_ptr<DofEntity>, 3> retainedDofPtrs;
boost::shared_ptr<BlockStructure> blockDataPtr;
boost::shared_ptr<NestSchurData> nestedDataPtr;
explicit HybridProblem(MoFEM::Interface &m_field)
: mField(m_field), simplePtr(m_field.getInterface<Simple>()) {}
HybridProblem(const HybridProblem &) = delete;
HybridProblem &operator=(const HybridProblem &) = delete;
~HybridProblem() { CHKERRABORT(mField.get_comm(), release()); }
/// Release numeric objects and cached vectors before topology edits.
hybridMatPtr.reset();
nestedMatPtr.reset();
blockMatPtr.reset();
for (DM dm : {simplePtr->getDM().get(), schurDMPtr.get(), blockDMPtr.get()})
if (dm) {
CHKERR DMClearGlobalVectors(dm);
CHKERR DMClearLocalVectors(dm);
CHKERR DMClearNamedGlobalVectors(dm);
CHKERR DMClearNamedLocalVectors(dm);
}
}
/// Final teardown, after all retained storage stops referencing sub-DMs.
nestedDataPtr.reset();
blockDataPtr.reset();
schurDMPtr.reset();
blockDMPtr.reset();
for (const auto &name : {"SCHUR", "BLOCK"})
auto parent_dm_ptr = simplePtr->getDM();
if (parent_dm_ptr) {
CHKERR DMMoFEMSetDestroyProblem(parent_dm_ptr, PETSC_TRUE);
parent_dm_ptr.reset();
}
}
/// Rebuild subproblem numbering while keeping its DM and field selection.
const std::vector<std::string> &fields,
const bool update = bool(dm);
if (!update) {
dm = createDM(mField.get_comm(), "DMMOFEM");
CHKERR DMMoFEMSetDestroyProblem(dm, PETSC_FALSE);
for (const auto &field : fields) {
}
}
// Creation adds selector bits to an existing named problem. Rebuilding
// must replace them, otherwise inactive source cells enter preallocation.
const Problem *parent_ptr;
name, parent_ptr->getBitRefLevel());
name, parent_ptr->getBitRefLevelMask());
// DMSetUp() skips a DM already set up by PETSc. Invoke MoFEM's subproblem
// setup directly to refresh its numbering and partitions in this object.
if (update)
else
CHKERR DMSetUp(dm);
}
/// Couplings used by both construction and the optional fresh-build oracle.
return {
{{"BROKEN", "BROKEN"}, {"U", "U"}, {"BROKEN", "U"}, {"U", "BROKEN"}}},
{{"BROKEN", "HYBRID"}, {"HYBRID", "BROKEN"}}}};
}
/// Construct the DMs and matrices without running validation or test fills.
MoFEMErrorCode build(const Range &entities, const Range &skeleton,
const BitRefLevel &active_bit, int order,
bool refresh_registration) {
updatePrepared = false;
const bool update = bool(simplePtr->getDM());
auto &mb = mField.get_moab();
if (!configured) {
CHKERR PetscOptionsGetBool(nullptr, nullptr, "-rebuild_structures",
&rebuildStructures, nullptr);
CHKERR PetscOptionsGetBool(nullptr, nullptr, "-check_rebuilt_structures",
CHKERR mb.create_meshset(MESHSET_SET, simplePtr->getMeshset());
CHKERR mb.create_meshset(MESHSET_SET, simplePtr->getSkeletonMeshSet());
1);
configured = true;
}
CHKERR mb.clear_meshset(&set, 1);
CHKERR mb.add_entities(simplePtr->getMeshset(), entities);
CHKERR mb.add_entities(simplePtr->getSkeletonMeshSet(), skeleton);
simplePtr->getBitRefLevel() = active_bit;
simplePtr->getBitAdjEnt() = active_bit;
if (!update || refresh_registration) {
Range new_field_entities;
auto comm_ptr = mField.getInterface<CommInterface>();
// A face may leave the skeleton without being deleted (e.g. when it
// joins a crack). Do not retain its old trace DOFs or skeleton element.
for (const auto &name : {"BROKEN", "U", "HYBRID"}) {
Range registered;
CHKERR mb.get_entities_by_handle(mField.get_field_meshset(name),
registered);
const auto &keep = std::string(name) == "HYBRID" ? skeleton : entities;
const auto removed = subtract(registered, keep);
if (!removed.empty())
registered = intersect(registered, keep);
const int dim = std::string(name) == "HYBRID" ? 2 : 3;
const auto added = subtract(keep.subset_by_dimension(dim), registered);
CHKERR comm_ptr->synchroniseFieldEntities(name, 0);
Range current;
CHKERR mb.get_entities_by_handle(mField.get_field_meshset(name),
current);
// A loaded checkpoint can carry field memberships and an older order.
// Initialise all current members once, then update additions only.
const auto new_entities =
update ? subtract(current, registered) : current;
if (!new_entities.empty())
new_entities, name,
std::string(name) == "BROKEN" ? order : order - 1, QUIET);
new_field_entities.merge(new_entities);
}
for (const auto &[name, keep] :
std::vector<std::pair<std::string, Range>>{
{simplePtr->getDomainFEName(), entities},
{simplePtr->getSkeletonFEName(), skeleton}}) {
continue;
Range registered;
CHKERR mb.get_entities_by_handle(
const auto removed = subtract(registered, keep);
if (!removed.empty())
}
if (!update)
// The range overload preserves existing DOF objects. Rebuilding views
// still visits surviving faces whose adjacent cells may have changed.
CHKERR mField.build_fields(new_field_entities, QUIET);
}
if (!update)
if (update) {
auto problems_ptr = mField.getInterface<ProblemsManager>();
const auto from_fields = problems_ptr->buildProblemFromFields;
problems_ptr->buildProblemFromFields = PETSC_TRUE;
const auto ierr = DMMoFEMRebuildProblem(simplePtr->getDM(), active_bit,
problems_ptr->buildProblemFromFields = from_fields;
} else
CHKERR buildSubProblem("SCHUR", {"HYBRID"}, schurDMPtr);
CHKERR buildSubProblem("BLOCK", {"BROKEN", "U"}, blockDMPtr);
const auto ops = getBlockOperations();
const bool reuse = rebuildStructures && blockDataPtr && nestedDataPtr;
if (reuse)
else {
nestedDataPtr.reset();
}
if (reuse)
else
{schurDMPtr, blockDMPtr}, blockDataPtr, {"BROKEN", "U"},
{nullptr, nullptr}, true);
}
/// Check the completed algebra; graph validation fills the hybrid matrix.
MoFEMErrorCode validate(const Range &entities, const Range &skeleton,
int order, const std::string &tag) {
"Build the hybrid problem before validating it");
auto fresh_block_ptr =
auto fresh_nested_ptr = createSchurNestedMatrixStruture(
{schurDMPtr, blockDMPtr}, fresh_block_ptr, {"BROKEN", "U"},
{nullptr, nullptr}, true);
auto compare = [&](const std::string &what, auto rebuilt_ptr,
auto fresh_ptr) {
const auto r = schurBlockStructureDigest(rebuilt_ptr);
const auto f = schurBlockStructureDigest(fresh_ptr);
if (r.nbBlocks != f.nbBlocks || r.nbElems != f.nbElems ||
r.indexHash != f.indexHash || r.blocksHash != f.blocksHash ||
r.elemsHash != f.elemsHash)
MOFEM_LOG("WORLD", Sev::error)
<< what << " digest: blocks " << r.nbBlocks << "/" << f.nbBlocks
<< ", elements " << r.nbElems << "/" << f.nbElems << ", index "
<< r.indexHash << "/" << f.indexHash << ", layout "
<< r.blocksHash << "/" << f.blocksHash << ", element layout "
<< r.elemsHash << "/" << f.elemsHash;
tag + " rebuilt " + what + " equals fresh structure",
r.nbBlocks == f.nbBlocks && r.nbElems == f.nbElems &&
r.indexHash == f.indexHash &&
r.blocksHash == f.blocksHash &&
r.elemsHash == f.elemsHash
? 0
: 1,
0, TestingInterface::Tolerance{0, 0});
};
CHKERR compare("block", blockDataPtr, fresh_block_ptr);
for (int q = 0; q != 4; ++q)
CHKERR compare("quadrant " + std::to_string(q),
std::get<1>(*nestedDataPtr)[q],
std::get<1>(*fresh_nested_ptr)[q]);
}
auto testing_ptr = mField.getInterface<TestingInterface>();
const auto zero = TestingInterface::Tolerance{0, 0};
int dm_index = 0;
for (DM dm :
{simplePtr->getDM().get(), blockDMPtr.get(), schurDMPtr.get()}) {
PetscObjectId id;
CHKERR PetscObjectGetId(reinterpret_cast<PetscObject>(dm), &id);
if (!dmIds[dm_index])
dmIds[dm_index] = id;
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
tag + " DM " + std::to_string(dm_index) + " identity retained",
id == dmIds[dm_index] ? 0 : 1, 0, zero);
++dm_index;
}
// Sample one DOF per field. Replaced entities may have new field objects;
// a surviving field entity must keep its existing DOF object as well.
const auto &dofs = mField.get_dofs()->get<Unique_mi_tag>();
int field_index = 0;
for (const auto &name : {"BROKEN", "U", "HYBRID"}) {
auto &old_ptr = retainedDofPtrs[field_index++];
int identity_error = 0;
if (old_ptr) {
auto it = dofs.find(old_ptr->getLocalUniqueId());
if (it != dofs.end() &&
(*it)->getFieldEntityPtr() == old_ptr->getFieldEntityPtr())
identity_error = *it == old_ptr ? 0 : 1;
}
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
tag + " surviving " + name + " DOF identity retained", identity_error,
0, zero);
const auto bit_number = mField.get_field_bit_number(name);
auto it = dofs.lower_bound(FieldEntity::getLoBitNumberUId(bit_number));
old_ptr = it != dofs.end() && (*it)->getBitNumber() == bit_number
? *it
: nullptr;
}
int counts[2] = {static_cast<int>(entities.num_of_type(MBTET)),
static_cast<int>(skeleton.size())};
CHKERR MPI_Bcast(counts, 2, MPI_INT, 0, mField.get_comm());
const double broken =
const double block_rows = counts[0] * (broken + NBVOLUMETET_L2(order - 1));
const double schur_rows = counts[1] * NBFACETRI_L2(order - 1);
const double parent_rows = block_rows + schur_rows;
for (const auto &[dm, expected] :
std::vector<std::pair<DM, double>>{{simplePtr->getDM(), parent_rows},
{blockDMPtr, block_rows},
{schurDMPtr, schur_rows}}) {
const Problem *problem_ptr;
CHKERR DMMoFEMGetProblemPtr(dm, &problem_ptr);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
tag + " DM DOFs match complete root topology",
problem_ptr->getNbDofsRow(), expected, zero);
auto vector = createDMVector(dm);
PetscInt n, first, last;
CHKERR VecGetSize(vector, &n);
CHKERR VecGetOwnershipRange(vector, &first, &last);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
tag + " DM vector global size", n, expected, zero);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(
tag + " DM vector local size", last - first,
problem_ptr->nbLocDofsRow, zero);
}
for (const auto &[matrix, expected] :
std::vector<std::pair<Mat, double>>{{blockMatPtr, parent_rows},
{nestedMatPtr, parent_rows},
{hybridMatPtr, schur_rows}}) {
PetscInt m, n;
CHKERR MatGetSize(matrix, &m, &n);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(tag + " matrix rows", m,
expected, zero);
CHKERR testing_ptr->checkValue<TestType::SCALAR>(tag + " matrix columns",
n, expected, zero);
}
double nnz;
entities.subset_by_type(MBTET), hybridMatPtr,
*testing_ptr, tag, nnz);
summary = {static_cast<double>(order), parent_rows, block_rows, schur_rows,
nnz};
MOFEM_LOG("WORLD", Sev::inform)
<< "Hybrid rebuilt " << tag
<< (structuresReused ? " [reused structures]" : " [fresh structures]")
<< ": parent " << parent_rows << ", BLOCK " << block_rows << ", SCHUR "
<< schur_rows << ", nonzeros " << nnz;
}
};
} // namespace Fun3
#endif
std::vector< int > removed
std::vector< FieldBitNumber > row
Definition Schur.cpp:2488
It it
Definition Schur.cpp:2568
SmartPetscObj< Vec > values
@ DEMKOWICZ_JACOBI_BASE
Definition definitions.h:66
@ L2
field with C-1 continuity
Definition definitions.h:88
@ HDIV
field with continuous normal traction
Definition definitions.h:87
constexpr int order
PetscErrorCode DMMoFEMCreateSubDM(DM subdm, DM dm, const char problem_name[])
Must be called by user to set Sub DM MoFEM data structures.
Definition DMMoFEM.cpp:244
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 DMMoFEMGetProblemPtr(DM dm, const MoFEM::Problem **problem_ptr)
Get pointer to problem data structure.
Definition DMMoFEM.cpp:451
PetscErrorCode DMMoFEMAddSubFieldRow(DM dm, const char field_name[])
Definition DMMoFEM.cpp:267
auto createDMVector(DM dm, RowColData rc=RowColData::COL)
Get smart vector from DM.
Definition DMMoFEM.hpp:1279
PetscErrorCode DMMoFEMAddSubFieldCol(DM dm, const char field_name[])
Definition DMMoFEM.cpp:309
PetscErrorCode DMSubDMSetUp_MoFEM(DM subdm)
Definition DMMoFEM.cpp:1431
virtual const DofEntity_multiIndex * get_dofs() const =0
Get the dofs object.
virtual EntityHandle get_finite_element_meshset(const std::string name) const =0
virtual MoFEMErrorCode build_fields(int verb=DEFAULT_VERBOSITY)=0
virtual MoFEMErrorCode add_ents_to_field_by_dim(const Range &ents, const int dim, const std::string &name, int verb=DEFAULT_VERBOSITY)=0
Add entities to field meshset.
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 remove_ents_from_field(const std::string name, const EntityHandle meshset, const EntityType type, int verb=DEFAULT_VERBOSITY)=0
remove entities from field
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 delete_problem(const std::string name)=0
Delete 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
#define NBFACETRI_L2(P)
Number of base functions on triangle for L2 space.
#define NBVOLUMETET_DEMKOWICZ_HDIV(P)
#define NBFACETRI_DEMKOWICZ_HDIV(P)
#define NBVOLUMETET_L2(P)
Number of base functions on tetrahedron for L2 space.
PetscBool testing
MoFEMErrorCode check_hybrid_matrix(MoFEM::Interface &m_field, DM dm, const Range &tets, Mat matrix, TestingInterface &testing, const std::string &tag, double &nonzeros)
static MoFEMErrorCodeGeneric< PetscErrorCode > ierr
SchurBlockStructureDigest schurBlockStructureDigest(boost::shared_ptr< BlockStructure > data_ptr)
Definition Schur.cpp:4821
PetscErrorCode DMMoFEMSetDestroyProblem(DM dm, PetscBool destroy_problem)
Definition DMMoFEM.cpp:463
std::pair< SmartPetscObj< Mat >, boost::shared_ptr< NestSchurData > > createSchurNestedMatrix(boost::shared_ptr< NestSchurData > schur_net_data_ptr)
Create a Mat Diag Blocks object.
Definition Schur.cpp:4859
PetscErrorCode PetscOptionsGetBool(PetscOptions *, const char pre[], const char name[], PetscBool *bval, PetscBool *set)
PetscErrorCode DMMoFEMClearDMCtx(DM dm)
Clear solver and Schur data owned by a MoFEM DM context.
Definition DMMoFEM.cpp:79
auto createDMHybridisedL2Matrix(DM dm)
Get smart hybridised L2 matrix from DM.
Definition DMMoFEM.hpp:1249
boost::shared_ptr< BlockStructure > createBlockMatStructure(DM dm, SchurFEOpsFEandFields schur_fe_op_vec)
Create block matrix structure.
Definition Schur.cpp:2819
boost::shared_ptr< NestSchurData > createSchurNestedMatrixStruture(std::pair< SmartPetscObj< DM >, SmartPetscObj< DM > > dms, boost::shared_ptr< BlockStructure > block_mat_data_ptr, std::vector< std::string > fields_names, std::vector< boost::shared_ptr< Range > > field_ents, bool add_preconditioner_block)
Create structure of nested matrix [A11 A10; A01 A00].
Definition Schur.cpp:4760
MoFEMErrorCode MatSetValues(Mat M, const EntitiesFieldData::EntData &row_data, const EntitiesFieldData::EntData &col_data, const double *ptr, InsertMode iora)
Assemble PETSc matrix.
MoFEMErrorCode rebuildSchurNestedMatrixStruture(std::pair< SmartPetscObj< DM >, SmartPetscObj< DM > > dms, boost::shared_ptr< NestSchurData > nest_data_ptr)
Rebuild a nested Schur structure after rebuildBlockMatStructure.
Definition Schur.cpp:4799
MoFEMErrorCode TestingInterface::checkValue< TestType::SCALAR >(const std::string &check_name, PetscReal actual, PetscReal expected, Tolerance tolerance, Sev error_severity, Sev success_severity) const
MoFEMErrorCode rebuildBlockMatStructure(DM dm, SchurFEOpsFEandFields schur_fe_op_vec, boost::shared_ptr< BlockStructure > data_ptr)
Rebuild a block matrix structure after its problem changed.
Definition Schur.cpp:2833
std::vector< std::pair< std::string, std::vector< SchurFieldPair > > > SchurFEOpsFEandFields
Definition Schur.hpp:83
auto createDM(MPI_Comm comm, const std::string dm_type_name)
Creates smart DM object.
SchurShellMatData createBlockMat(DM dm, boost::shared_ptr< BlockStructure > data)
Create a Schur Mat object.
Definition Schur.cpp:3615
int r
Definition sdf.py:205
double q
FTensor::Index< 'm', 3 > m
MoFEMErrorCode buildSubProblem(const char *name, const std::vector< std::string > &fields, SmartPetscObj< DM > &dm)
Rebuild subproblem numbering while keeping its DM and field selection.
MoFEM::Interface & mField
boost::shared_ptr< NestSchurData > nestedDataPtr
MoFEMErrorCode build(const Range &entities, const Range &skeleton, const BitRefLevel &active_bit, int order, bool refresh_registration)
Construct the DMs and matrices without running validation or test fills.
std::array< double, 5 > summary
std::array< PetscObjectId, 3 > dmIds
HybridProblem(MoFEM::Interface &m_field)
std::array< boost::shared_ptr< DofEntity >, 3 > retainedDofPtrs
PetscBool checkRebuiltStructures
SmartPetscObj< Mat > blockMatPtr
SmartPetscObj< DM > blockDMPtr
HybridProblem & operator=(const HybridProblem &)=delete
MoFEMErrorCode release()
Final teardown, after all retained storage stops referencing sub-DMs.
MoFEMErrorCode prepareUpdate()
Release numeric objects and cached vectors before topology edits.
SmartPetscObj< Mat > nestedMatPtr
boost::shared_ptr< BlockStructure > blockDataPtr
MoFEMErrorCode validate(const Range &entities, const Range &skeleton, int order, const std::string &tag)
Check the completed algebra; graph validation fills the hybrid matrix.
SchurFEOpsFEandFields getBlockOperations() const
Couplings used by both construction and the optional fresh-build oracle.
SmartPetscObj< DM > schurDMPtr
SmartPetscObj< Mat > hybridMatPtr
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 EntityHandle get_field_meshset(const std::string name) const =0
get field meshset
virtual bool check_finite_element(const std::string &name) const =0
Check if finite element is in database.
virtual MoFEMErrorCode build_adjacencies(const Range &ents, int verb=DEFAULT_VERBOSITY)=0
build adjacencies
virtual MPI_Comm & get_comm() const =0
virtual MoFEMErrorCode remove_ents_from_finite_element(const std::string name, const EntityHandle meshset, const EntityType type, int verb=DEFAULT_VERBOSITY)=0
remove entities from given refinement level to finite element database
virtual int get_comm_rank() const =0
static UId getLoBitNumberUId(const FieldBitNumber bit_number)
keeps basic data about problem
DofIdx getNbDofsRow() const
BitRefLevel getBitRefLevel() const
BitRefLevel getBitRefLevelMask() const
DofIdx nbLocDofsRow
Local number of DOFs in row.
Problem manager is used to build and partition problems.
Simple interface for fast problem set-up.
Definition Simple.hpp:27
MoFEMErrorCode buildProblem()
Build problem.
Definition Simple.cpp:724
MoFEMErrorCode addDomainField(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_ZERO, int verb=-1)
Add field on domain.
Definition Simple.cpp:264
bool & getAddBoundaryFE()
Get the addBoundaryFE flag.
Definition Simple.hpp:546
MoFEMErrorCode defineFiniteElements()
Define finite elements.
Definition Simple.cpp:474
EntityHandle & getMeshset()
Get the MeshSet object.
Definition Simple.hpp:394
auto & getBitAdjParent()
Get bit ref level for parent.
Definition Simple.hpp:562
MoFEMErrorCode buildFiniteElements()
Build finite elements.
Definition Simple.cpp:662
const std::string getSkeletonFEName() const
Get the Skeleton FE Name.
Definition Simple.hpp:443
EntityHandle & getSkeletonMeshSet()
Get the SkeletonMeshSet object.
Definition Simple.hpp:408
void setDim(int dim)
Set the problem dimension.
Definition Simple.hpp:380
MoFEMErrorCode getDM(DM *dm)
Get DM.
Definition Simple.cpp:802
auto & getBitAdjEnt()
Get bit ref level for entities.
Definition Simple.hpp:576
MoFEMErrorCode setFieldOrder(const std::string field_name, const int order, const Range *ents=NULL)
Set field order.
Definition Simple.cpp:578
MoFEMErrorCode defineProblem(const PetscBool is_partitioned=PETSC_TRUE)
define problem
Definition Simple.cpp:554
BitRefLevel & getBitRefLevelMask()
Get the BitRefLevelMask.
Definition Simple.hpp:422
const std::string getDomainFEName() const
Get the Domain FE Name.
Definition Simple.hpp:429
MoFEMErrorCode setSkeletonAdjacency(int dim=-1, std::string fe_name="")
Set the skeleton adjacency object.
Definition Simple.cpp:143
MoFEMErrorCode deleteDM()
Delete dm.
Definition Simple.cpp:814
BitRefLevel & getBitRefLevel()
Get the BitRefLevel.
Definition Simple.hpp:415
MoFEMErrorCode deleteFiniteElements()
Delete finite elements.
Definition Simple.cpp:825
MoFEMErrorCode addDomainBrokenField(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_ZERO, int verb=-1)
Add broken field on domain.
Definition Simple.cpp:285
MoFEMErrorCode addSkeletonField(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_ZERO, int verb=-1)
Add field on skeleton.
Definition Simple.cpp:376
intrusive_ptr for managing petsc objects