v0.16.3
Loading...
Searching...
No Matches
remesh_tetrahedra.cpp
Go to the documentation of this file.
1/** \file remesh_tetrahedra.cpp
2 * \brief Independent native-file checks for the remeshing command-line tool.
3 */
4#include <MoFEM.hpp>
5#include <filesystem>
6#include <fstream>
7#include <map>
8#include <set>
9using namespace MoFEM;
10
11namespace {
12MoFEMErrorCode require(bool value, const char *message) {
14 if (!value)
15 SETERRQ(PETSC_COMM_SELF, MOFEM_ATOM_TEST_INVALID, "%s", message);
17}
18std::string contents(const std::string &file) {
19 std::ifstream input(file, std::ios::binary);
20 return {std::istreambuf_iterator<char>(input),
21 std::istreambuf_iterator<char>()};
22}
23const std::array<const char *, 3> rejected{"size", "duplicate", "block"};
24double determinant(const std::array<double, 3> &a,
25 const std::array<double, 3> &b,
26 const std::array<double, 3> &c) {
27 return a[0] * (b[1] * c[2] - b[2] * c[1]) -
28 a[1] * (b[0] * c[2] - b[2] * c[0]) +
29 a[2] * (b[0] * c[1] - b[1] * c[0]);
30}
31
32MoFEMErrorCode cubeFixture(MoFEM::Interface &m_field) {
35 mesh.points = {{-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}, {1, 1, -1},
36 {-1, -1, 1}, {1, -1, 1}, {-1, 1, 1}, {1, 1, 1}};
37 mesh.vertexIds = {1, 2, 3, 4, 5, 6, 7, 8};
38 mesh.cells = {{0, 1, 3, 7}, {0, 1, 5, 7}, {0, 2, 3, 7},
39 {0, 2, 6, 7}, {0, 4, 5, 7}, {0, 4, 6, 7}};
41 EntityHandle volume, surface;
42 CHKERR m_field.getInterface<CGALInterface>()->importMesh(
43 mesh, BitRefLevel().set(0), source, volume, surface);
44 auto &mb = m_field.get_moab();
45 auto sets = m_field.getInterface<MeshsetsManager>();
46 auto add = [&](int id, CubitBCType type, const std::string &name,
47 const Range &members) {
49 CHKERR sets->addMeshset(type, id, name);
50 CHKERR sets->addEntitiesToMeshset(type, id, members);
51 Tag metadata;
52 const auto set = sets->getCubitMeshsetPtr(id, type)->getMeshset();
53 const int value = id + 100;
54 CHKERR mb.tag_get_handle("RECONSTRUCTION_METADATA", 1, MB_TYPE_INTEGER,
55 metadata, MB_TAG_SPARSE | MB_TAG_CREAT);
56 CHKERR mb.tag_set_data(metadata, &set, 1, &value);
58 };
59 const auto cells = source.subset_by_type(MBTET),
60 vertices = source.subset_by_type(MBVERTEX);
61 CHKERR add(11, BLOCKSET, "MATERIAL", cells);
62 CHKERR add(12, BLOCKSET, "OVERLAP", cells);
63 CHKERR sets->setAttributes(BLOCKSET, 11, {3.25, 7.});
64 auto entity = [&](std::vector<int> indices, int dim, Range &result) {
66 std::vector<EntityHandle> conn;
67 for (int i : indices)
68 conn.push_back(vertices[i]);
69 CHKERR mb.get_adjacencies(conn.data(), conn.size(), dim, false, result,
70 moab::Interface::INTERSECT);
71 CHKERR require(result.size() == 1, "Missing cube fixture simplex");
73 };
74 Range boundary, side, curve;
75 CHKERR entity({0, 1, 3}, 2, boundary);
76 CHKERR entity({4, 5, 7}, 2, side);
77 CHKERR entity({0, 1}, 1, curve);
78 CHKERR add(20, BLOCKSET, "BOUNDARY", boundary);
79 CHKERR add(21, BLOCKSET, "CURVE", curve);
80 CHKERR add(30, SIDESET, "LOAD", side);
81 CHKERR add(40, NODESET, "FIXED", Range(vertices.front(), vertices.front()));
82 ReadUtilIface *reader;
83 CHKERR mb.query_interface(reader);
84 EntityHandle unused;
85 std::vector<double *> coords;
86 CHKERR reader->get_node_coords(3, 1, 0, unused, coords);
87 for (auto x : coords)
88 x[0] = 4;
89 const int id = 100;
90 CHKERR mb.tag_set_data(mb.globalId_tag(), &unused, 1, &id);
91 CHKERR m_field.getInterface<BitRefManager>()->setEntitiesBitRefLevel(
92 Range(unused, unused), BitRefLevel().set(7));
93 CHKERR mb.write_file("remesh_cube.h5m", "MOAB");
94 EntityHandle quadratic;
95 CHKERR mb.create_meshset(MESHSET_SET, quadratic);
96 CHKERR mb.add_entities(quadratic, subtract(source, vertices));
97 CHKERR mb.convert_entities(quadratic, true, false, false);
98 CHKERR mb.delete_entities(&quadratic, 1);
99 // Curve the higher-order geometry: the tool must use the original corners.
100 Range mid_nodes;
101 CHKERR mb.get_connectivity(cells, mid_nodes, false);
102 mid_nodes = subtract(mid_nodes, vertices);
103 for (auto node : mid_nodes) {
104 double xyz[3];
105 CHKERR mb.get_coords(&node, 1, xyz);
106 xyz[0] += 0.05;
107 CHKERR mb.set_coords(&node, 1, xyz);
108 }
109 CHKERR mb.write_file("remesh_quadratic_input.h5m", "MOAB");
110 std::filesystem::copy_file("remesh_quadratic_input.h5m",
111 "remesh_quadratic_before.h5m",
112 std::filesystem::copy_options::overwrite_existing);
114}
115
119 char stage[32] = "check", path[PETSC_MAX_PATH_LEN] = "remeshed.h5m",
120 input_path[PETSC_MAX_PATH_LEN] = "valid.h5m";
121 PetscInt output_bit = 0;
122 PetscBool crack = PETSC_FALSE, reverse = PETSC_FALSE, recovery = PETSC_FALSE,
123 steiner = PETSC_FALSE;
124 CHKERR PetscOptionsGetString(nullptr, nullptr, "-remesh_check_stage", stage,
125 sizeof(stage), nullptr);
126 CHKERR PetscOptionsGetString(nullptr, nullptr, "-output_file", path,
127 sizeof(path), nullptr);
128 CHKERR PetscOptionsGetString(nullptr, nullptr, "-file_name", input_path,
129 sizeof(input_path), nullptr);
130 // Level of the saved mesh; the tools squash it to 0 unless -shift false.
131 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-saved_bit", &output_bit,
132 nullptr);
133 CHKERR PetscOptionsGetBool(nullptr, nullptr, "-remesh_check_crack", &crack,
134 nullptr);
135 CHKERR PetscOptionsGetBool(nullptr, nullptr, "-remesh_check_reverse",
136 &reverse, nullptr);
137 CHKERR PetscOptionsGetBool(nullptr, nullptr, "-remesh_check_recovery",
138 &recovery, nullptr);
139 CHKERR PetscOptionsGetBool(nullptr, nullptr, "-remesh_check_steiner",
140 &steiner, nullptr);
141 if (std::string(stage) == "prepare") {
142 for (const auto *name : rejected)
143 std::ofstream("remesh_rejected_" + std::string(name) + ".h5m")
144 << "preserve existing output\n";
145 std::filesystem::copy_file(
146 "valid.h5m", "remesh_valid_before.h5m",
147 std::filesystem::copy_options::overwrite_existing);
148 CHKERR cubeFixture(m_field);
150 }
151 if (std::string(stage) == "failures") {
152 for (const auto *name : rejected) {
153 const auto file = "remesh_rejected_" + std::string(name) + ".h5m";
154 CHKERR require(contents(file) == "preserve existing output\n" &&
155 !std::filesystem::exists(file + ".tmp.h5m"),
156 "Rejected remesh replaced an existing output");
157 }
158 CHKERR require(contents("valid.h5m") == contents("remesh_valid_before.h5m"),
159 "Remeshing changed the input file");
160 CHKERR require(contents("remesh_quadratic_input.h5m") ==
161 contents("remesh_quadratic_before.h5m"),
162 "Remeshing changed the higher-order input file");
164 }
165 auto &mb = m_field.get_moab();
166 CHKERR mb.load_file(path);
168 auto bits = m_field.getInterface<BitRefManager>();
169 auto sets = m_field.getInterface<MeshsetsManager>();
170 CHKERR sets->setMeshsetFromFile();
171 Range entities;
172 CHKERR mb.get_entities_by_handle(0, entities);
173 entities = subtract(entities, entities.subset_by_type(MBENTITYSET));
174 const auto cells = entities.subset_by_type(MBTET);
175 CHKERR require(!cells.empty() && !entities.subset_by_type(MBVERTEX).empty(),
176 "Empty remeshed checkpoint");
177 Range skin;
178 CHKERR mb.get_adjacencies(cells, 2, false, skin, moab::Interface::UNION);
179 for (auto face : skin) {
180 Range adjacent;
181 CHKERR mb.get_adjacencies(&face, 1, 3, false, adjacent);
182 if (adjacent.size() != 1)
183 continue;
184 int side, sense, offset;
185 CHKERR mb.side_number(adjacent.front(), face, side, sense, offset);
186 CHKERR require(sense == 1, "Saved skin triangle is not outward oriented");
187 }
188 moab::Core original;
189 CHKERR original.load_file(input_path);
190 Range input_cells;
191 CHKERR original.get_entities_by_type(0, MBTET, input_cells);
192 using CellGeometry = std::array<std::array<double, 3>, 4>;
193 std::vector<CellGeometry> source_geometry;
194 double source_volume = 0, output_volume = 0;
195 auto geometry = [&](moab::Interface &database, EntityHandle cell,
196 CellGeometry &x, double &volume) {
198 const EntityHandle *conn;
199 int count;
200 CHKERR database.get_connectivity(cell, conn, count, true);
201 CHKERR database.get_coords(conn, 4, x[0].data());
202 for (int i = 1; i != 4; ++i)
203 for (int d = 0; d != 3; ++d)
204 x[i][d] -= x[0][d];
205 volume = determinant(x[1], x[2], x[3]) / 6;
206 CHKERR require(volume > 0,
207 "Saved/source fixture has a nonpositive tetrahedron");
209 };
210 for (auto cell : input_cells) {
211 CellGeometry x;
212 double volume;
213 CHKERR geometry(original, cell, x, volume);
214 source_geometry.push_back(x);
215 source_volume += volume;
216 }
217 for (auto cell : cells) {
218 CellGeometry x;
219 double volume;
220 CHKERR geometry(mb, cell, x, volume);
221 output_volume += volume;
222 std::array<double, 3> centre = x[0];
223 for (int d = 0; d != 3; ++d)
224 centre[d] += (x[1][d] + x[2][d] + x[3][d]) / 4;
225 const bool inside = std::any_of(
226 source_geometry.begin(), source_geometry.end(),
227 [&](const auto &source) {
228 std::array<double, 3> p;
229 for (int d = 0; d != 3; ++d)
230 p[d] = centre[d] - source[0][d];
231 const auto den = determinant(source[1], source[2], source[3]);
232 const double a = determinant(p, source[2], source[3]) / den,
233 b = determinant(source[1], p, source[3]) / den,
234 c = determinant(source[1], source[2], p) / den;
235 return a >= -1e-10 && b >= -1e-10 && c >= -1e-10 &&
236 a + b + c <= 1 + 1e-10;
237 });
238 CHKERR require(inside,
239 "Saved remeshing filled a region outside the source mesh");
240 }
242 "Saved remeshing volume", output_volume, source_volume, {1e-8, 1e-10});
243 Range attached;
244 CHKERR mb.get_connectivity(
245 subtract(entities, entities.subset_by_type(MBVERTEX)), attached, false);
246 CHKERR require(subtract(attached, entities).empty(),
247 "Output omitted a referenced node");
248 Range topological_nodes;
249 CHKERR mb.get_connectivity(cells, topological_nodes, true);
250 CHKERR require(entities.subset_by_type(MBVERTEX) == topological_nodes,
251 "Output contains orphan higher-order or unrelated nodes");
252 std::set<int> ids;
253 for (auto entity : entities) {
254 BitRefLevel level;
255 EntityHandle parent;
256 CHKERR mb.tag_get_data(bits->get_th_RefBitLevel(), &entity, 1, &level);
257 CHKERR mb.tag_get_data(bits->get_th_RefParentHandle(), &entity, 1, &parent);
258 CHKERR require(level == BitRefLevel().set(output_bit) && parent == 0,
259 "Output contains another level or a dangling parent");
260 const auto type = mb.type_from_handle(entity);
261 if (type == MBTET || type == MBTRI || type == MBEDGE) {
262 const EntityHandle *conn;
263 int count;
264 CHKERR mb.get_connectivity(entity, conn, count, false);
265 CHKERR require(count == (type == MBTET ? 4
266 : type == MBTRI ? 3
267 : 2),
268 "Saved output contains higher-order connectivity");
269 }
270 if (type == MBVERTEX &&
271 topological_nodes.find(entity) != topological_nodes.end()) {
272 int id;
273 CHKERR mb.tag_get_data(mb.globalId_tag(), &entity, 1, &id);
274 CHKERR require(id > 0 && id != 100 && ids.insert(id).second,
275 "Invalid IDs or an unrelated source vertex in output");
276 }
277 }
278 if (recovery) {
279 std::map<int, std::array<double, 3>> output_points;
280 for (auto vertex : topological_nodes) {
281 int id;
282 std::array<double, 3> x;
283 CHKERR mb.tag_get_data(mb.globalId_tag(), &vertex, 1, &id);
284 CHKERR mb.get_coords(&vertex, 1, x.data());
285 output_points.emplace(id, x);
286 }
287 Range original_vertices, source_corners;
288 CHKERR original.get_entities_by_type(0, MBVERTEX, original_vertices);
289 CHKERR original.get_connectivity(input_cells, source_corners, true);
290 int largest = 0;
291 for (auto vertex : original_vertices) {
292 int id;
293 CHKERR original.tag_get_data(original.globalId_tag(), &vertex, 1, &id);
294 largest = std::max(largest, id);
295 }
296 for (auto vertex : source_corners) {
297 int id;
298 std::array<double, 3> x;
299 CHKERR original.tag_get_data(original.globalId_tag(), &vertex, 1, &id);
300 CHKERR original.get_coords(&vertex, 1, x.data());
301 const auto found = output_points.find(id);
302 CHKERR require(found != output_points.end() && found->second == x,
303 "Recovery changed a source corner coordinate or ID");
304 output_points.erase(found);
305 }
306 for (const auto &[id, x] : output_points)
307 CHKERR require(id > largest,
308 "Steiner ID collides with the source database namespace");
309 if (steiner)
310 CHKERR require(!output_points.empty(),
311 "Recovery did not exercise Steiner insertion");
312 }
313 for (int id : {11, 12}) {
314 Range members;
315 const auto set = sets->getCubitMeshsetPtr(id, BLOCKSET)->getMeshset();
316 CHKERR mb.get_entities_by_type(set, MBTET, members, true);
317 CHKERR require(members == cells,
318 "Lost material or overlapping volume membership");
319 }
320 std::vector<double> attributes;
321 CHKERR sets->getCubitMeshsetPtr(11, BLOCKSET)->getAttributes(attributes);
322 CHKERR require(attributes == std::vector<double>({3.25, 7.}),
323 "Lost material attributes");
324 for (const auto &[id, type, dim] :
325 std::vector<std::tuple<int, CubitBCType, int>>{{20, BLOCKSET, 2},
326 {21, BLOCKSET, 1},
327 {30, SIDESET, 2},
328 {40, NODESET, 0}}) {
329 const auto set = sets->getCubitMeshsetPtr(id, type)->getMeshset();
330 Range members;
331 CHKERR mb.get_entities_by_dimension(set, dim, members, true);
332 CHKERR require(!members.empty(), "Lost a boundary, curve or node meshset");
333 Tag metadata;
334 int value;
335 CHKERR mb.tag_get_handle("RECONSTRUCTION_METADATA", metadata);
336 CHKERR mb.tag_get_data(metadata, &set, 1, &value);
337 CHKERR require(value == id + 100, "Lost meshset metadata");
338 if (id == 40) {
339 int vertex_id;
340 const auto vertex = members.front();
341 CHKERR mb.tag_get_data(mb.globalId_tag(), &vertex, 1, &vertex_id);
342 CHKERR require(members.size() == 1 && vertex_id == 1,
343 "Lost the fixed node identity");
344 }
345 }
346 if (reverse) {
347 const auto side = sets->getCubitMeshsetPtr(30, SIDESET)->getMeshset();
348 Range nested, direct;
349 CHKERR mb.get_entities_by_type(side, MBENTITYSET, nested, false);
350 CHKERR mb.get_entities_by_type(side, MBTRI, direct, false);
351 CHKERR require(nested.size() == 1 && direct.empty(),
352 "Flattened a reverse sideset");
353 Tag sense;
354 int value;
355 const auto child = nested.front();
356 CHKERR mb.tag_get_handle("NEUSET_SENSE", sense);
357 CHKERR mb.tag_get_data(sense, &child, 1, &value);
358 CHKERR require(value == -1, "Lost reverse sideset sense");
359 }
360 if (crack) {
362 CHKERR mb.get_entities_by_type(
363 sets->getCubitMeshsetPtr(50, BLOCKSET)->getMeshset(), MBTRI, faces,
364 true);
365 CHKERR mb.get_connectivity(faces, vertices, true);
366 std::map<std::array<EntityHandle, 2>, int> edges;
367 for (auto face : faces) {
368 Range adjacent;
369 CHKERR mb.get_adjacencies(&face, 1, 3, false, adjacent);
370 CHKERR require(adjacent.size() == 2,
371 "Crack is no longer an internal sheet");
372 const EntityHandle *conn;
373 int count;
374 CHKERR mb.get_connectivity(face, conn, count, true);
375 for (int i = 0; i != 3; ++i) {
376 std::array<EntityHandle, 2> edge{conn[i], conn[(i + 1) % 3]};
377 std::sort(edge.begin(), edge.end());
378 CHKERR require(++edges[edge] <= 2,
379 "Non-manifold crack edge in saved mesh");
380 }
381 }
382 CHKERR require(!faces.empty() && static_cast<long>(vertices.size()) -
383 static_cast<long>(edges.size()) +
384 static_cast<long>(faces.size()) ==
385 1,
386 "Saved crack lost its disk topology");
387 }
388 MOFEM_LOG("WORLD", Sev::inform) << "Verified remeshed checkpoint";
390}
391} // namespace
392
393int main(int argc, char *argv[]) {
394 MoFEM::Core::Initialize(&argc, &argv, nullptr,
395 "Remeshing tool checkpoint checks\n");
396 try {
397 moab::Core mb;
398 MoFEM::Core core(mb);
399 CHKERR run(core);
400 }
403 return 0;
404}
std::vector< std::array< EntityHandle, 3 > > faces
Sorted keys.
TetMeshData result
FaceSet skin
std::vector< int > source
int boundary
FaceSet crack
WorkMesh mesh
std::vector< int > vertices
std::vector< int > parent
std::vector< Cell > cells
moab::Interface & mb
std::vector< double > empty
One value per component.
std::string type
std::string name
int main()
constexpr double a
@ QUIET
#define CATCH_ERRORS
Catch errors.
#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 ...
@ NODESET
@ SIDESET
@ BLOCKSET
@ MOFEM_ATOM_TEST_INVALID
Definition definitions.h:40
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
#define MOFEM_LOG(channel, severity)
Log.
MoFEMErrorCode addMeshset(const CubitBCType cubit_bc_type, const int ms_id, const std::string name="")
Add CUBIT meshset to manager.
FTensor::Index< 'i', SPACE_DIM > i
const double c
speed of light (cm/ns)
PetscBool output_volume
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
std::bitset< 32 > CubitBCType
Definition Types.hpp:52
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 PetscOptionsGetBool(PetscOptions *, const char pre[], const char name[], PetscBool *bval, PetscBool *set)
MoFEMErrorCode TestingInterface::checkValue< TestType::SCALAR >(const std::string &check_name, PetscReal actual, PetscReal expected, Tolerance tolerance, Sev error_severity, Sev success_severity) const
PetscErrorCode PetscOptionsGetString(PetscOptions *, const char pre[], const char name[], char str[], size_t size, PetscBool *set)
float offset
Definition sdf_python.py:3
MoFEMErrorCode run(MoFEM::Interface &m_field)
Definition sdf_python.cpp:7
Managing BitRefLevels.
virtual moab::Interface & get_moab()=0
virtual MoFEMErrorCode rebuild_database(int verb=DEFAULT_VERBOSITY)=0
Clear database and initialize it once again.
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.
Interface for managing meshsets containing materials and boundary conditions.
std::vector< std::array< double, 3 > > points
Definition CGALTools.hpp:17
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.