v0.16.3
Loading...
Searching...
No Matches
crack_extension_check.cpp
Go to the documentation of this file.
1/** \file crack_extension_check.cpp
2 * \brief Fixture and checks for the tangent crack growth tool.
3 *
4 * -fixture_stage prepare writes crack_input.h5m: a 6 x 4 x 4 block of unit
5 * prisms split into tetrahedra, with a planar crack at z = 0 for x < 3 in
6 * BLOCKSET 1 and all tetrahedra in BLOCKSET 2.
7 * -fixture_stage check verifies the step files written by crack_extension.
8 * -fixture_stage compare compares the crack and mesh of two step files.
9 * -fixture_stage bridge extends one edge in a kinked direction through
10 * CGALInterface::CrackExtension::extendCrack and checks levels, parents and
11 * retirement.
12 * -fixture_stage validate checks any step file independently.
13 */
14#include <MoFEM.hpp>
15#include <CgalCrackGrowth.hpp>
16#include <filesystem>
17#include <iomanip>
18
19using namespace MoFEM;
20
21namespace {
22
23using Face = std::array<int, 3>;
24using Cell = std::array<int, 4>;
25
26constexpr int nx = 6, ny = 4;
27const std::vector<double> levels{-2, -1, 0, 1, 2};
28constexpr int crackLevel = 2, crackX = 3;
29
30MoFEMErrorCode require(bool valid, const std::string &message) {
32 if (!valid)
33 SETERRQ(PETSC_COMM_SELF, MOFEM_ATOM_TEST_INVALID, "%s", message.c_str());
35}
36
37double det(const std::vector<std::array<double, 3>> &p, const Cell &c) {
38 const auto d = [&](int a, int b) {
39 return std::array<double, 3>{p[c[b]][0] - p[c[a]][0],
40 p[c[b]][1] - p[c[a]][1],
41 p[c[b]][2] - p[c[a]][2]};
42 };
43 const auto u = d(0, 1), v = d(0, 2), w = d(0, 3);
44 return u[0] * (v[1] * w[2] - v[2] * w[1]) -
45 u[1] * (v[0] * w[2] - v[2] * w[0]) +
46 u[2] * (v[0] * w[1] - v[1] * w[0]);
47}
48
49MoFEMErrorCode prepare(MoFEM::Interface &m_field) {
51 auto &mb = m_field.get_moab();
52 const int planar = (nx + 1) * (ny + 1);
53 const auto id = [](int i, int j) { return j * (nx + 1) + i; };
54 std::vector<std::array<double, 3>> points;
55 for (double z : levels)
56 for (int j = 0; j <= ny; ++j)
57 for (int i = 0; i <= nx; ++i)
58 points.push_back({double(i), double(j), z});
59 std::vector<std::array<int, 3>> triangles;
60 std::vector<char> cracked;
61 for (int j = 0; j != ny; ++j)
62 for (int i = 0; i != nx; ++i) {
63 triangles.push_back({id(i, j), id(i + 1, j), id(i + 1, j + 1)});
64 triangles.push_back({id(i, j), id(i + 1, j + 1), id(i, j + 1)});
65 cracked.push_back(i < crackX);
66 cracked.push_back(i < crackX);
67 }
68 std::vector<Cell> cells;
69 for (int l = 0; l + 1 < static_cast<int>(levels.size()); ++l)
70 for (auto t : triangles) {
71 std::sort(t.begin(), t.end());
72 const int b0 = l * planar + t[0], b1 = l * planar + t[1],
73 b2 = l * planar + t[2];
74 const int t0 = b0 + planar, t1 = b1 + planar, t2 = b2 + planar;
75 for (Cell c :
76 {Cell{b0, b1, b2, t2}, Cell{b0, b1, t1, t2}, Cell{b0, t0, t1, t2}}) {
77 if (det(points, c) < 0)
78 std::swap(c[2], c[3]);
79 cells.push_back(c);
80 }
81 }
82 std::vector<EntityHandle> vertices;
83 for (size_t v = 0; v != points.size(); ++v) {
84 EntityHandle vertex;
85 CHKERR mb.create_vertex(points[v].data(), vertex);
86 const int gid = v + 1;
87 CHKERR mb.tag_set_data(mb.globalId_tag(), &vertex, 1, &gid);
88 vertices.push_back(vertex);
89 }
90 Range tets;
91 for (const auto &c : cells) {
92 const EntityHandle conn[] = {vertices[c[0]], vertices[c[1]], vertices[c[2]],
93 vertices[c[3]]};
94 EntityHandle tet;
95 CHKERR mb.create_element(MBTET, conn, 4, tet);
96 tets.insert(tet);
97 }
99 for (size_t t = 0; t != triangles.size(); ++t)
100 if (cracked[t]) {
101 const EntityHandle conn[] = {
102 vertices[crackLevel * planar + triangles[t][0]],
103 vertices[crackLevel * planar + triangles[t][1]],
104 vertices[crackLevel * planar + triangles[t][2]]};
105 Range face;
106 CHKERR mb.get_adjacencies(conn, 3, 2, true, face);
107 crack.merge(face);
108 }
109 auto sets = m_field.getInterface<MeshsetsManager>();
110 CHKERR sets->addMeshset(BLOCKSET, 1, "CRACK");
111 CHKERR sets->addEntitiesToMeshset(BLOCKSET, 1, crack);
112 CHKERR sets->addMeshset(BLOCKSET, 2, "MATERIAL");
113 CHKERR sets->addEntitiesToMeshset(BLOCKSET, 2, tets);
114 CHKERR mb.write_file("crack_input.h5m", "MOAB");
115 MOFEM_LOG("WORLD", Sev::inform)
116 << "Wrote crack_input.h5m: " << tets.size() << " tetrahedra, "
117 << crack.size() << " crack faces";
118 // The same mesh with straight mid-edge nodes on every element, as a
119 // higher-order input for the tool.
120 Range elements = tets;
121 elements.merge(crack);
122 EntityHandle quadratic;
123 CHKERR mb.create_meshset(MESHSET_SET, quadratic);
124 CHKERR mb.add_entities(quadratic, elements);
125 CHKERR mb.convert_entities(quadratic, true, false, false);
126 CHKERR mb.delete_entities(&quadratic, 1);
127 CHKERR mb.write_file("crack_input_quadratic.h5m", "MOAB");
129}
130
131/** Indexed content of a mesh file, keyed by vertex GLOBAL_ID. */
132struct Snapshot {
133 std::map<int, std::array<double, 3>> points;
134 std::set<Cell> cells;
135 std::set<Face> crack;
136 std::vector<Cell> orderedCells;
137 std::vector<std::array<double, 3>> coordinates;
138 std::map<int, int> index;
139 int skinFaces = 0;
140 double skinArea = 0, volume = 0;
141 int inverted = 0, overfull = 0, wrongLevel = 0, danglingParents = 0;
142 int wrongCrackTag = -1; ///< Faces whose CRACK_ID disagrees; -1 if no tag.
143 int highOrder = 0, orphanNodes = 0;
144};
145
146MoFEMErrorCode load(const std::string &file, int expected_bit,
147 Snapshot &snapshot) {
149 moab::Core mb;
150 MoFEM::CoreTmp<-1> core(mb, PETSC_COMM_SELF);
151 MoFEM::Interface &m_field = core;
152 CHKERR mb.load_file(file.c_str());
154 auto sets = m_field.getInterface<MeshsetsManager>();
156 Range tets;
157 CHKERR mb.get_entities_by_type(0, MBTET, tets);
159 CHKERR mb.get_connectivity(tets, vertices, true);
160 for (auto v : vertices) {
161 int id;
162 std::array<double, 3> x;
163 CHKERR mb.tag_get_data(mb.globalId_tag(), &v, 1, &id);
164 CHKERR mb.get_coords(&v, 1, x.data());
165 snapshot.index[id] = snapshot.coordinates.size();
166 snapshot.coordinates.push_back(x);
167 snapshot.points[id] = x;
168 }
169 const auto key = [&](EntityHandle entity, auto &result) {
171 const EntityHandle *conn;
172 int count;
173 CHKERR mb.get_connectivity(entity, conn, count, true);
174 CHKERR mb.tag_get_data(mb.globalId_tag(), conn, count, result.data());
176 };
177 {
178 Range all, used, nodes;
179 CHKERR mb.get_entities_by_handle(0, all);
180 const auto elements = subtract(subtract(all, all.subset_by_type(MBVERTEX)),
181 all.subset_by_type(MBENTITYSET));
182 for (auto e : elements) {
183 const EntityHandle *conn;
184 int count;
185 CHKERR mb.get_connectivity(e, conn, count, false);
186 snapshot.highOrder +=
187 count != moab::CN::VerticesPerEntity(mb.type_from_handle(e));
188 }
189 CHKERR mb.get_connectivity(elements, used, false);
190 CHKERR mb.get_entities_by_type(0, MBVERTEX, nodes);
191 snapshot.orphanNodes = subtract(nodes, used).size();
192 }
193 std::map<Face, int> face_count;
194 for (auto tet : tets) {
195 Cell c;
196 CHKERR key(tet, c);
197 Cell local;
198 for (int n = 0; n != 4; ++n)
199 local[n] = snapshot.index.at(c[n]);
200 const double d = det(snapshot.coordinates, local);
201 snapshot.inverted += !(d > 0);
202 snapshot.volume += d / 6;
203 auto sorted = c;
204 std::sort(sorted.begin(), sorted.end());
205 snapshot.cells.insert(sorted);
206 snapshot.orderedCells.push_back(local);
207 for (int f = 0; f != 4; ++f) {
208 Face face;
209 for (int n = 0, k = 0; n != 4; ++n)
210 if (n != f)
211 face[k++] = sorted[n];
212 ++face_count[face];
213 }
214 }
215 for (const auto &[face, count] : face_count) {
216 snapshot.overfull += count > 2;
217 if (count == 1) {
218 ++snapshot.skinFaces;
219 const auto &a = snapshot.points.at(face[0]);
220 const auto &b = snapshot.points.at(face[1]);
221 const auto &c = snapshot.points.at(face[2]);
222 const std::array<double, 3> u{b[0] - a[0], b[1] - a[1], b[2] - a[2]},
223 v{c[0] - a[0], c[1] - a[1], c[2] - a[2]};
224 const std::array<double, 3> n{u[1] * v[2] - u[2] * v[1],
225 u[2] * v[0] - u[0] * v[2],
226 u[0] * v[1] - u[1] * v[0]};
227 snapshot.skinArea +=
228 std::sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) / 2;
229 }
230 }
231 Range crack;
232 CHKERR mb.get_entities_by_type(
233 sets->getCubitMeshsetPtr(1, BLOCKSET)->getMeshset(), MBTRI, crack, true);
234 for (auto f : crack) {
235 Face face;
236 CHKERR key(f, face);
237 std::sort(face.begin(), face.end());
238 snapshot.crack.insert(face);
239 }
240 Tag crack_tag;
241 if (mb.tag_get_handle("CRACK_ID", 1, MB_TYPE_INTEGER, crack_tag) ==
242 MB_SUCCESS) {
243 Range faces;
244 CHKERR mb.get_entities_by_type(0, MBTRI, faces);
245 std::vector<int> ids(faces.size());
246 CHKERR mb.tag_get_data(crack_tag, faces, ids.data());
247 snapshot.wrongCrackTag = 0;
248 for (size_t i = 0; i != faces.size(); ++i) {
249 const bool on_crack = crack.find(faces[i]) != crack.end();
250 snapshot.wrongCrackTag += ids[i] != (on_crack ? 1 : 0);
251 }
252 }
253 if (expected_bit >= 0) {
254 auto bits = m_field.getInterface<BitRefManager>();
255 Range all, on_level;
256 CHKERR mb.get_entities_by_handle(0, all);
257 all = subtract(all, all.subset_by_type(MBENTITYSET));
258 CHKERR bits->getEntitiesByRefLevel(BitRefLevel().set(expected_bit),
259 BitRefLevel().set(expected_bit),
260 on_level);
261 // Field/FE/problem meshsets can have their own selector bits. The
262 // retirement invariant applies to geometry, not algebra metadata sets.
263 on_level = subtract(on_level, on_level.subset_by_type(MBENTITYSET));
264 snapshot.wrongLevel =
265 subtract(tets, on_level).size() + subtract(on_level, all).size();
266 Range other;
267 CHKERR bits->getEntitiesByRefLevel(~BitRefLevel().set(expected_bit),
268 BitRefLevel().set(), other);
269 other = subtract(other, other.subset_by_type(MBENTITYSET));
270 snapshot.wrongLevel += other.size();
271 const auto parent_tag = bits->get_th_RefParentHandle();
272 for (auto entity : all) {
273 EntityHandle parent = 0;
274 if (mb.tag_get_data(parent_tag, &entity, 1, &parent) == MB_SUCCESS &&
275 parent && all.find(parent) == all.end())
276 ++snapshot.danglingParents;
277 }
278 }
280}
281
282std::string stepFile(const std::string &output, int step) {
283 std::filesystem::path path(output);
284 std::ostringstream name;
285 name << path.stem().string() << '_' << std::setw(4) << std::setfill('0')
286 << step
287 << (path.has_extension() ? path.extension().string()
288 : std::string(".h5m"));
289 return (path.parent_path() / name.str()).string();
290}
291
292MoFEMErrorCode check(MoFEM::Interface &m_field) {
294 char output[PETSC_MAX_PATH_LEN] = "crack.h5m";
295 PetscInt steps = 1, input_bit = 0, output_bit = 1;
296 CHKERR PetscOptionsGetString(nullptr, nullptr, "-output_file", output,
297 sizeof(output), nullptr);
298 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-max_steps", &steps, nullptr);
299 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-input_bit", &input_bit,
300 nullptr);
301 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-output_bit", &output_bit,
302 nullptr);
303 auto testing = m_field.getInterface<TestingInterface>();
304 Snapshot reference;
305 CHKERR load("crack_input.h5m", -1, reference);
306 size_t previous = reference.crack.size();
307 int not_growing = 0, off_plane = 0, non_manifold = 0, crack_on_skin = 0;
308 int inverted = 0, overfull = 0, wrong_level = 0, dangling = 0;
309 int wrong_tag = 0, high_order = 0, orphans = 0;
310 int skin_count = 0;
311 double volume_error = 0, skin_error = 0;
312 for (int step = 1; step <= steps; ++step) {
313 const auto file = stepFile(output, step);
314 CHKERR require(std::filesystem::exists(file), "Missing step file " + file);
315 Snapshot s;
316 CHKERR load(file, step % 2 ? output_bit : input_bit, s);
317 not_growing += s.crack.size() < previous + 1;
318 previous = s.crack.size();
319 std::map<std::array<int, 2>, int> edges;
320 for (const auto &face : s.crack) {
321 for (int v : face)
322 off_plane += s.points.at(v)[2] != 0;
323 ++edges[{face[0], face[1]}];
324 ++edges[{face[1], face[2]}];
325 ++edges[{face[0], face[2]}];
326 }
327 for (const auto &[edge, count] : edges)
328 non_manifold += count > 2;
329 // Crack faces are interior: each lies between two tetrahedra.
330 std::map<Face, int> face_count;
331 for (const auto &cell : s.cells)
332 for (int f = 0; f != 4; ++f) {
333 Face face;
334 for (int n = 0, k = 0; n != 4; ++n)
335 if (n != f)
336 face[k++] = cell[n];
337 ++face_count[face];
338 }
339 for (const auto &face : s.crack)
340 crack_on_skin += face_count[face] != 2;
341 inverted += s.inverted;
342 overfull += s.overfull;
343 wrong_level += s.wrongLevel;
344 dangling += s.danglingParents;
345 wrong_tag += s.wrongCrackTag < 0 ? 1 : s.wrongCrackTag;
346 high_order += s.highOrder;
347 orphans += s.orphanNodes;
348 skin_count += s.skinFaces != reference.skinFaces;
349 volume_error =
350 std::max(volume_error, std::abs(s.volume - reference.volume));
351 skin_error =
352 std::max(skin_error, std::abs(s.skinArea - reference.skinArea));
353 }
354 CHKERR testing->checkValue<TestType::SCALAR>("Crack grows every step",
355 not_growing, 0, {0, 0});
356 CHKERR testing->checkValue<TestType::SCALAR>("Crack stays in its plane",
357 off_plane, 0, {0, 0});
358 CHKERR testing->checkValue<TestType::SCALAR>("Crack is a manifold",
359 non_manifold, 0, {0, 0});
360 CHKERR testing->checkValue<TestType::SCALAR>("Crack faces are interior",
361 crack_on_skin, 0, {0, 0});
362 CHKERR testing->checkValue<TestType::SCALAR>("Inverted tetrahedra", inverted,
363 0, {0, 0});
364 CHKERR testing->checkValue<TestType::SCALAR>("Faces with three cells",
365 overfull, 0, {0, 0});
366 CHKERR testing->checkValue<TestType::SCALAR>("Entities off the active level",
367 wrong_level, 0, {0, 0});
368 CHKERR testing->checkValue<TestType::SCALAR>("Dangling parent references",
369 dangling, 0, {0, 0});
370 CHKERR testing->checkValue<TestType::SCALAR>(
371 "Faces with a wrong CRACK_ID tag", wrong_tag, 0, {0, 0});
372 CHKERR testing->checkValue<TestType::SCALAR>("Higher-order elements",
373 high_order, 0, {0, 0});
374 CHKERR testing->checkValue<TestType::SCALAR>("Unused nodes", orphans, 0,
375 {0, 0});
376 CHKERR testing->checkValue<TestType::SCALAR>("Skin face count changed",
377 skin_count, 0, {0, 0});
378 CHKERR testing->checkError<TestType::SCALAR>("Volume", volume_error,
379 reference.volume, {0, 1e-12});
380 CHKERR testing->checkError<TestType::SCALAR>("Skin area", skin_error,
381 reference.skinArea, {0, 1e-12});
382 MOFEM_LOG("WORLD", Sev::inform)
383 << "Verified " << steps << " crack extension steps; crack "
384 << reference.crack.size() << " -> " << previous << " faces";
386}
387
388MoFEMErrorCode compare(MoFEM::Interface &m_field) {
390 char first[PETSC_MAX_PATH_LEN] = "", second[PETSC_MAX_PATH_LEN] = "";
391 PetscBool expect_equal = PETSC_TRUE;
392 CHKERR PetscOptionsGetString(nullptr, nullptr, "-first", first, sizeof(first),
393 nullptr);
394 CHKERR PetscOptionsGetString(nullptr, nullptr, "-second", second,
395 sizeof(second), nullptr);
396 CHKERR PetscOptionsGetBool(nullptr, nullptr, "-expect_equal", &expect_equal,
397 nullptr);
398 Snapshot a, b;
399 CHKERR load(first, -1, a);
400 CHKERR load(second, -1, b);
401 const bool equal =
402 a.points == b.points && a.cells == b.cells && a.crack == b.crack;
404 std::string("Step files ") + (expect_equal ? "equal" : "differ"), equal,
405 expect_equal ? 1 : 0, {0, 0});
407}
408
409/** Single-rank part of the ancestry test: one kinked extension through the
410 * bridge moves a node; check levels, parents and retirement. */
411MoFEMErrorCode bridgeStage(MoFEM::Interface &m_field) {
413 auto &mb = m_field.get_moab();
414 auto bits = m_field.getInterface<BitRefManager>();
415 auto testing = m_field.getInterface<TestingInterface>();
416 CHKERR mb.load_file("crack_input.h5m");
418 auto sets = m_field.getInterface<MeshsetsManager>();
420 const auto source = BitRefLevel().set(0), output = BitRefLevel().set(1);
421 Range tets, closure, vertices;
422 CHKERR mb.get_entities_by_type(0, MBTET, tets);
423 CHKERR mb.get_connectivity(tets, vertices, true);
424 closure = unite(tets, vertices);
425 for (int dim : {1, 2}) {
426 Range adjacent;
427 CHKERR mb.get_adjacencies(tets, dim, true, adjacent,
428 moab::Interface::UNION);
429 closure.merge(adjacent);
430 }
431 CHKERR bits->setBitRefLevel(closure, source, false);
432 Range crack;
433 CHKERR mb.get_entities_by_type(
434 sets->getCubitMeshsetPtr(1, BLOCKSET)->getMeshset(), MBTRI, crack, true);
435
436 std::map<EntityHandle, std::array<double, 3>> before;
437 std::set<int> input_ids;
438 std::array<EntityHandle, 2> ends{0, 0};
439 for (auto v : vertices) {
440 std::array<double, 3> x;
441 int id;
442 CHKERR mb.get_coords(&v, 1, x.data());
443 CHKERR mb.tag_get_data(mb.globalId_tag(), &v, 1, &id);
444 before[v] = x;
445 input_ids.insert(id);
446 if (x == std::array<double, 3>{3, 1, 0})
447 ends[0] = v;
448 if (x == std::array<double, 3>{3, 2, 0})
449 ends[1] = v;
450 }
451 Range edge;
452 CHKERR mb.get_adjacencies(ends.data(), 2, 1, false, edge,
453 moab::Interface::INTERSECT);
454 CHKERR require(edge.size() == 1, "Front edge (3,1,0)-(3,2,0) not found");
455 const double angle = 30 * M_PI / 180;
457 edge.front(), {std::cos(angle), 0, std::sin(angle)}};
458 auto volume_of = [&](const Range &cells, double &volume, int &inverted) {
460 volume = 0;
461 inverted = 0;
462 for (auto tet : cells) {
463 const EntityHandle *conn;
464 int count;
465 CHKERR mb.get_connectivity(tet, conn, count, true);
466 std::vector<std::array<double, 3>> p(4);
467 for (int n = 0; n != 4; ++n)
468 CHKERR mb.get_coords(&conn[n], 1, p[n].data());
469 const double d = det(p, {0, 1, 2, 3});
470 inverted += !(d > 0);
471 volume += d / 6;
472 }
474 };
475 double reference_volume;
476 int inverted;
477 CHKERR volume_of(tets, reference_volume, inverted);
478
479 auto bridge = m_field.getInterface<CGALInterface>();
480 Range entities;
481 EntityHandle face = 0;
483 CHKERR bridge->getCrackExtension().extendCrack(
484 source, output, crack, Range(), {request},
485 CGALTools::CrackExtensionSettings(), entities, face, &candidate);
486 CHKERR require(face != 0, "Kinked extension found no candidate");
487 CHKERR testing->checkValue<TestType::SCALAR>(
488 "Bridge kinked extension moves a node", candidate.candidateClass >= 2, 1,
489 {0, 0});
490
491 // The free node is a new vertex whose parent is the unchanged source vertex.
492 const auto parent_tag = bits->get_th_RefParentHandle();
493 const auto parent_of = [&](EntityHandle e) {
494 EntityHandle parent = 0;
495 CHK_MOAB_THROW(mb.tag_get_data(parent_tag, &e, 1, &parent), "parent");
496 return parent;
497 };
498 const auto level_of = [&](EntityHandle e) {
499 BitRefLevel level;
500 CHK_MOAB_THROW(mb.tag_get_data(bits->get_th_RefBitLevel(), &e, 1, &level),
501 "level");
502 return level;
503 };
504 const EntityHandle *face_conn;
505 int count;
506 CHKERR mb.get_connectivity(face, face_conn, count, true);
507 EntityHandle moved = 0;
508 for (int n = 0; n != 3; ++n)
509 if (face_conn[n] != ends[0] && face_conn[n] != ends[1])
510 moved = face_conn[n];
511 int moved_id;
512 CHKERR mb.tag_get_data(mb.globalId_tag(), &moved, 1, &moved_id);
513 const auto old_vertex = parent_of(moved);
514 CHKERR testing->checkValue<TestType::SCALAR>(
515 "Bridge moved vertex has a fresh ID", !input_ids.count(moved_id), 1,
516 {0, 0});
517 CHKERR testing->checkValue<TestType::SCALAR>(
518 "Bridge moved vertex parent is the source vertex",
519 before.count(old_vertex) && level_of(old_vertex) == source, 1, {0, 0});
520 std::array<double, 3> x;
521 CHKERR mb.get_coords(&old_vertex, 1, x.data());
522 CHKERR testing->checkValue<TestType::SCALAR>(
523 "Bridge source vertex keeps its coordinates", x == before[old_vertex], 1,
524 {0, 0});
525
526 // Created entities have a parent on the source level; source is intact.
527 Range on_output, on_source;
528 CHKERR bits->getEntitiesByRefLevel(output, BitRefLevel().set(), on_output);
529 CHKERR bits->getEntitiesByRefLevel(source, BitRefLevel().set(), on_source);
530 on_output = subtract(on_output, on_output.subset_by_type(MBENTITYSET));
531 int orphans = 0, created = 0;
532 for (auto e : subtract(on_output, on_source)) {
533 ++created;
534 const auto parent = parent_of(e);
535 orphans += !parent || (level_of(parent) & source).none();
536 }
537 CHKERR testing->checkValue<TestType::SCALAR>("Bridge created entities",
538 created > 0, 1, {0, 0});
539 CHKERR testing->checkValue<TestType::SCALAR>(
540 "Bridge created entities without a source parent", orphans, 0, {0, 0});
541 int moved_sources = 0;
542 for (const auto &[v, coords] : before) {
543 std::array<double, 3> now;
544 CHKERR mb.get_coords(&v, 1, now.data());
545 moved_sources += now != coords;
546 }
547 CHKERR testing->checkValue<TestType::SCALAR>(
548 "Bridge source vertices unchanged", moved_sources, 0, {0, 0});
549 double volume;
550 CHKERR volume_of(on_source.subset_by_type(MBTET), volume, inverted);
551 CHKERR testing->checkValue<TestType::SCALAR>("Bridge source level cell count",
552 on_source.num_of_type(MBTET),
553 tets.size(), {0, 0});
554 CHKERR testing->checkValue<TestType::SCALAR>(
555 "Bridge source level volume", volume, reference_volume, {0, 1e-12});
556 CHKERR volume_of(on_output.subset_by_type(MBTET), volume, inverted);
557 CHKERR testing->checkValue<TestType::SCALAR>("Bridge output volume", volume,
558 reference_volume, {0, 1e-12});
559 CHKERR testing->checkValue<TestType::SCALAR>("Bridge output inverted cells",
560 inverted, 0, {0, 0});
561 CHKERR testing->checkValue<TestType::SCALAR>(
562 "Bridge output closure returned", subtract(on_output, entities).empty(),
563 1, {0, 0});
564
565 // Retirement deletes the source-only entities and frees the bit.
566 CHKERR bridge->retireLevel(source);
567 Range remaining, all;
568 CHKERR bits->getEntitiesByRefLevel(source, BitRefLevel().set(), remaining);
569 CHKERR mb.get_entities_by_handle(0, all);
570 int dangling = 0;
571 for (auto e : subtract(all, all.subset_by_type(MBENTITYSET))) {
572 const auto parent = parent_of(e);
573 dangling += parent && all.find(parent) == all.end();
574 }
575 Range cells;
576 CHKERR mb.get_entities_by_type(0, MBTET, cells);
577 CHKERR volume_of(cells, volume, inverted);
578 CHKERR testing->checkValue<TestType::SCALAR>("Retired level has no entities",
579 remaining.size(), 0, {0, 0});
580 CHKERR testing->checkValue<TestType::SCALAR>(
581 "Retirement leaves no dangling parents", dangling, 0, {0, 0});
582 CHKERR testing->checkValue<TestType::SCALAR>(
583 "Retirement keeps the output cells", cells.size(),
584 on_output.num_of_type(MBTET), {0, 0});
585 CHKERR testing->checkValue<TestType::SCALAR>(
586 "Retirement keeps volume", volume, reference_volume, {0, 1e-12});
587 CHKERR testing->checkValue<TestType::SCALAR>(
588 "Retired old vertex is deleted", all.find(old_vertex) == all.end(), 1,
589 {0, 0});
590
591 // Invalid levels are rejected before any change.
592 Range unused;
593 EntityHandle none = 0;
594 CHKERR PetscPushErrorHandler(PetscIgnoreErrorHandler, nullptr);
595 const auto error = bridge->getCrackExtension().extendCrack(
596 output, output, crack, Range(), {request},
597 CGALTools::CrackExtensionSettings(), unused, none);
598 CHKERR PetscPopErrorHandler();
599 CHKERR testing->checkValue<TestType::SCALAR>("Bridge rejects equal levels",
600 error != 0, 1, {0, 0});
602}
603
604/** Edge priority takes precedence over direction tolerance and later joins;
605 * a blocked preferred edge falls through to the next admissible edge. */
606MoFEMErrorCode orderedStage(MoFEM::Interface &m_field) {
608 auto testing = m_field.getInterface<TestingInterface>();
609 using Growth = CgalCrackGrowth;
610 for (int mode = 0; mode != 6; ++mode) {
611 moab::Core mb;
612 MoFEM::CoreTmp<-1> core(mb);
613 MoFEM::Interface &field = core;
614 CHKERR mb.load_file("crack_input.h5m");
616 Range tets, geometry;
617 CHKERR mb.get_entities_by_type(0, MBTET, tets);
618 geometry = tets;
619 for (int dim : {0, 1, 2}) {
621 CHKERR mb.get_adjacencies(tets, dim, true, closure,
622 moab::Interface::UNION);
623 geometry.merge(closure);
624 }
625 CHKERR field.getInterface<BitRefManager>()->setBitRefLevel(
626 geometry, BitRefLevel().set(0), false);
627 const int owner = 0;
628 CHKERR mb.tag_clear_data(
629 ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX)->part_tag(), geometry,
630 &owner);
631 auto sets = field.getInterface<MeshsetsManager>();
633 const auto crack_set = sets->getCubitMeshsetPtr(1, BLOCKSET)->getMeshset();
634 std::map<std::array<int, 3>, EntityHandle> nodes;
636 CHKERR mb.get_entities_by_type(0, MBVERTEX, vertices);
637 for (auto v : vertices) {
638 double x[3];
639 CHKERR mb.get_coords(&v, 1, x);
640 nodes[{static_cast<int>(x[0]), static_cast<int>(x[1]),
641 static_cast<int>(x[2])}] = v;
642 }
643 const auto node = [&](int x, int y) { return nodes.at({x, y, 0}); };
644 const bool joining_fixture = mode == 3 || mode == 4;
645 if (joining_fixture) {
646 for (const auto &conn : std::vector<std::array<EntityHandle, 3>>{
647 {node(3, 0), node(4, 0), node(4, 1)},
648 {node(3, 0), node(4, 1), node(3, 1)},
649 {node(3, 1), node(4, 2), node(3, 2)}}) {
650 Range face;
651 CHKERR mb.get_adjacencies(conn.data(), 3, 2, false, face,
652 moab::Interface::INTERSECT);
653 CHKERR require(face.size() == 1, "Ordered fixture face exists");
654 CHKERR mb.add_entities(crack_set, face);
655 }
656 }
657 Growth::Settings settings;
658 settings.join = joining_fixture;
659 settings.extension.angleToleranceDegrees = 0.5;
660 settings.extension.maxMoveRelative = mode == 5 ? 0.5 : 0;
661 settings.angleMaxDegrees = mode == 2 || mode == 5 ? 0.5 : 20;
662 Growth growth(field, crack_set, BitRefLevel().set(0), BitRefLevel().set(1),
663 {}, settings);
664 CHKERR testing->checkValue<TestType::SCALAR>(
665 "Preview respects join policy",
666 growth.settings().extension.lookAheadJoin, settings.join, {0, 0});
667 Range crack, front;
668 CHKERR growth.crackFaces(crack);
669 CHKERR growth.frontEdges(crack, front);
670 const auto find_edge = [&](EntityHandle a, EntityHandle b) {
671 for (auto edge : front) {
672 const EntityHandle *conn;
673 int count;
674 CHK_MOAB_THROW(mb.get_connectivity(edge, conn, count, true),
675 "Ordered fixture edge");
676 if ((conn[0] == a && conn[1] == b) || (conn[0] == b && conn[1] == a))
677 return edge;
678 }
679 return EntityHandle(0);
680 };
681 const auto first = !joining_fixture ? find_edge(node(3, 1), node(3, 2))
682 : find_edge(node(3, 3), node(3, 4));
683 const auto second = find_edge(node(3, 2), node(3, 3));
684 CHKERR require(first && second, "Ordered fixture front edges exist");
685 std::vector<EntityHandle> handles{first, second};
686 if (joining_fixture) {
687 handles = {first};
688 for (auto edge : front)
689 if (edge != first)
690 handles.push_back(edge);
691 Range joins;
692 EntityHandle selected = 0;
693 CHKERR field.getInterface<CGALInterface>()->getCrackExtension().crackJoin(
694 BitRefLevel().set(0), crack, {}, joins, nullptr, handles, &selected);
695 CHKERR require(selected && selected != first && joins.size() == 1,
696 "Ordered fixture has a later eligible join");
697 if (mode == 4) {
698 const auto it = std::find(handles.begin(), handles.end(), selected);
699 std::iter_swap(handles.begin(), it);
700 }
701 }
702 std::vector<Growth::Pair> pairs;
703 for (auto edge : handles)
704 pairs.push_back(growth.edgeIds(edge));
705 const auto direction = [&](EntityHandle edge, const Range &,
706 std::array<double, 3> &d) {
707 d = {1, 0,
708 !joining_fixture && edge == first ? std::tan(13 * M_PI / 180) : 0};
709 return MoFEMErrorCode(0);
710 };
711 Growth::Step step;
712 if (mode == 0)
713 CHKERR growth.extend(pairs, direction, step);
714 else
715 CHKERR growth.advanceOrdered(pairs, direction, step);
716 const int expected = mode == 3 ? step.extended
717 : mode == 0 || mode == 2 || mode == 5 ? 1
718 : 0;
719 CHKERR require(step.extended >= 0 &&
720 static_cast<std::size_t>(step.extended) < pairs.size(),
721 "Selected priority exists");
722 if (mode == 3)
723 CHKERR require(step.extended > 0,
724 "A global gap beats the earlier feasible extension");
725 const std::string tag = "Ordered case " + std::to_string(mode);
726 CHKERR testing->checkValue<TestType::SCALAR>(
727 tag + " selected priority", step.extended, expected, {0, 0});
728 CHKERR testing->checkValue<TestType::SCALAR>(
729 tag + " selected edge", step.edge == pairs[expected], 1, {0, 0});
730 CHKERR testing->checkValue<TestType::SCALAR>(
731 tag + " selected operation",
732 step.kind ==
733 (joining_fixture ? Growth::Kind::Closure : Growth::Kind::Extension),
734 1, {0, 0});
735 if (mode == 5)
736 CHKERR testing->checkValue<TestType::SCALAR>(
737 "A flip-only extension beats an earlier vertex move",
738 step.candidate.moveRelative, 0, {0, 0});
739 if (mode == 1)
740 CHKERR testing->checkValue<TestType::SCALAR>(
741 tag + " preferred edge exhausts angle tolerance",
742 step.toleranceDegrees > settings.extension.angleToleranceDegrees, 1,
743 {0, 0});
744 }
746}
747
748/** Independent geometry and topology checks of a saved crack checkpoint. */
749MoFEMErrorCode validateStage(MoFEM::Interface &m_field) {
751 auto &mb = m_field.get_moab();
752 auto testing = m_field.getInterface<TestingInterface>();
753 char file[PETSC_MAX_PATH_LEN] = "";
754 PetscInt block = 1;
755 CHKERR PetscOptionsGetString(nullptr, nullptr, "-file_name", file,
756 sizeof(file), nullptr);
757 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-crack_block", &block, nullptr);
758 CHKERR mb.load_file(file);
760 auto sets = m_field.getInterface<MeshsetsManager>();
762 Range tets, crack;
763 CHKERR mb.get_entities_by_type(0, MBTET, tets);
764 CHKERR mb.get_entities_by_type(
765 sets->getCubitMeshsetPtr(block, BLOCKSET)->getMeshset(), MBTRI, crack,
766 true);
767 using P = std::array<double, 3>;
768 const auto coords = [&](const EntityHandle *conn, int n) {
769 std::vector<P> p(n);
770 for (int i = 0; i != n; ++i)
771 CHK_MOAB_THROW(mb.get_coords(&conn[i], 1, p[i].data()), "coords");
772 return p;
773 };
774 int inverted = 0;
775 double min_quality = 1, volume = 0;
776 std::map<std::array<EntityHandle, 3>, int> face_count;
777 for (auto tet : tets) {
778 const EntityHandle *conn;
779 int n;
780 CHKERR mb.get_connectivity(tet, conn, n, true);
781 const auto p = coords(conn, 4);
782 const double d = det(p, {0, 1, 2, 3});
783 inverted += !(d > 0);
784 volume += d / 6;
785 double x[12];
786 for (int i = 0; i != 4; ++i)
787 for (int k = 0; k != 3; ++k)
788 x[3 * i + k] = p[i][k];
789 min_quality = std::min(min_quality, Tools::volumeLengthQuality(x));
790 for (int f = 0; f != 4; ++f) {
791 std::array<EntityHandle, 3> key;
792 for (int i = 0, k = 0; i != 4; ++i)
793 if (i != f)
794 key[k++] = conn[i];
795 std::sort(key.begin(), key.end());
796 ++face_count[key];
797 }
798 }
799 int overfull = 0;
800 for (const auto &[key, n] : face_count)
801 overfull += n > 2;
802 int not_interior = 0;
803 double area = 0;
804 std::map<std::array<EntityHandle, 2>, int> crack_edges;
805 std::set<EntityHandle> crack_vertices;
806 for (auto f : crack) {
807 const EntityHandle *conn;
808 int n;
809 CHKERR mb.get_connectivity(f, conn, n, true);
810 crack_vertices.insert(conn, conn + n);
811 std::array<EntityHandle, 3> key{conn[0], conn[1], conn[2]};
812 std::sort(key.begin(), key.end());
813 not_interior += face_count[key] != 2;
814 const auto p = coords(conn, 3);
815 P u, v;
816 for (int k = 0; k != 3; ++k) {
817 u[k] = p[1][k] - p[0][k];
818 v[k] = p[2][k] - p[0][k];
819 }
820 const P c{u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2],
821 u[0] * v[1] - u[1] * v[0]};
822 area += std::sqrt(c[0] * c[0] + c[1] * c[1] + c[2] * c[2]) / 2;
823 for (int k = 0; k != 3; ++k) {
824 std::array<EntityHandle, 2> e{key[k], key[(k + 1) % 3]};
825 std::sort(e.begin(), e.end());
826 ++crack_edges[e];
827 }
828 }
829 // Skin faces have one cell; a crack edge with one crack face that is not
830 // on the skin is a front edge.
831 std::set<std::array<EntityHandle, 2>> skin_edges;
832 for (const auto &[key, n] : face_count) {
833 if (n != 1)
834 continue;
835 for (int k = 0; k != 3; ++k) {
836 std::array<EntityHandle, 2> e{key[k], key[(k + 1) % 3]};
837 std::sort(e.begin(), e.end());
838 skin_edges.insert(e);
839 }
840 }
841 int non_manifold = 0, front = 0;
842 double front_length = 0;
843 std::map<EntityHandle, std::set<EntityHandle>> front_graph;
844 for (const auto &[e, n] : crack_edges) {
845 non_manifold += n > 2;
846 if (n == 1 && !skin_edges.count(e)) {
847 front_graph[e[0]].insert(e[1]);
848 front_graph[e[1]].insert(e[0]);
849 ++front;
850 const auto p = coords(e.data(), 2);
851 front_length += std::sqrt((p[1][0] - p[0][0]) * (p[1][0] - p[0][0]) +
852 (p[1][1] - p[0][1]) * (p[1][1] - p[0][1]) +
853 (p[1][2] - p[0][2]) * (p[1][2] - p[0][2]));
854 }
855 }
856 // Gaps: short cycles of front edges (up to eight), also through vertices
857 // where crack parts touch; each found by the shortest path closing a
858 // front edge.
859 std::vector<int> holes;
860 {
861 std::set<std::vector<EntityHandle>> cycles;
862 for (const auto &[a, nb] : front_graph)
863 for (auto b : nb) {
864 if (!(a < b))
865 continue;
866 std::map<EntityHandle, EntityHandle> previous{{a, a}};
867 std::vector<EntityHandle> layer{a};
868 for (int depth = 0; depth != 7 && !previous.count(b); ++depth) {
869 std::vector<EntityHandle> next;
870 for (auto v : layer)
871 for (auto u : front_graph[v])
872 if (!(v == a && u == b) && !previous.count(u)) {
873 previous[u] = v;
874 next.push_back(u);
875 }
876 layer.swap(next);
877 }
878 if (!previous.count(b))
879 continue;
880 std::vector<EntityHandle> cycle;
881 for (auto v = b; v != a; v = previous[v])
882 cycle.push_back(v);
883 cycle.push_back(a);
884 std::sort(cycle.begin(), cycle.end());
885 cycles.insert(cycle);
886 }
887 for (const auto &c : cycles)
888 holes.push_back(c.size());
889 std::sort(holes.begin(), holes.end());
890 }
891 std::ostringstream hole_sizes;
892 for (int h : holes)
893 hole_sizes << ' ' << h;
894 const auto euler = static_cast<long>(crack_vertices.size()) -
895 static_cast<long>(crack_edges.size()) +
896 static_cast<long>(crack.size());
897 MOFEM_LOG("WORLD", Sev::inform)
898 << "Validate " << file << ": gaps " << holes.size()
899 << " (front edges each:" << hole_sizes.str() << "), cells " << tets.size()
900 << ", volume " << volume << ", minimum quality " << min_quality
901 << ", crack faces " << crack.size() << ", crack area " << area
902 << ", front edges " << front << ", front length " << front_length
903 << ", non-manifold crack edges " << non_manifold
904 << ", Euler characteristic " << euler;
905 PetscInt expected_euler;
906 PetscBool has_expected_euler;
907 CHKERR PetscOptionsGetInt(nullptr, nullptr, "-expect_crack_euler",
908 &expected_euler, &has_expected_euler);
909 if (has_expected_euler)
910 CHKERR testing->checkValue<TestType::SCALAR>("Crack Euler characteristic",
911 euler, expected_euler, {0, 0});
912 CHKERR testing->checkValue<TestType::SCALAR>("Inverted tetrahedra", inverted,
913 0, {0, 0});
914 CHKERR testing->checkValue<TestType::SCALAR>("Faces with three cells",
915 overfull, 0, {0, 0});
916 CHKERR testing->checkValue<TestType::SCALAR>("Crack faces not interior",
917 not_interior, 0, {0, 0});
919}
920
921} // namespace
922
923int main(int argc, char *argv[]) {
924 MoFEM::Core::Initialize(&argc, &argv, nullptr,
925 "Crack extension tool checks\n");
926 try {
927 moab::Core mb;
928 MoFEM::Core core(mb);
929 MoFEM::Interface &m_field = core;
931 char stage[PETSC_MAX_PATH_LEN] = "";
932 CHKERR PetscOptionsGetString(nullptr, nullptr, "-fixture_stage", stage,
933 sizeof(stage), nullptr);
934 const std::string name = stage;
935 if (name == "prepare")
936 CHKERR prepare(m_field);
937 else if (name == "check")
938 CHKERR check(m_field);
939 else if (name == "compare")
940 CHKERR compare(m_field);
941 else if (name == "bridge")
942 CHKERR bridgeStage(m_field);
943 else if (name == "validate")
944 CHKERR validateStage(m_field);
945 else if (name == "ordered")
946 CHKERR orderedStage(m_field);
947 else
948 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
949 "Use -fixture_stage prepare, check, compare, bridge, validate or "
950 "ordered");
951 }
954 return 0;
955}
CGALInterfaceImpl & owner
std::map< EntityHandle, int > index
std::vector< std::array< EntityHandle, 3 > > faces
Sorted keys.
TetMeshData result
CGALTools::CrackExtensionCandidate candidate
const Triangles & triangles
Definition CGALTools.cpp:60
bool selected
Definition CGALTools.cpp:97
std::vector< int > created
int h
Corner vertex and its two front neighbours.
std::vector< int > source
const Settings & settings
const std::vector< Vec > * points
FaceSet crack
std::vector< int > size
bool angle
Radians between candidate face and target plane.
std::vector< int > vertices
int w
Free node.
Vec t
Removal: the ring edge.
std::vector< int > parent
bool closure
The face (f0, f1, w) closes a corner at f0 or f1.
std::vector< Cell > cells
Crack growth one step at a time on two bit levels, on top of CGALInterface. Not included by MoFEM....
ParentChildKey key
moab::Interface & mb
Tag tag
ProjectedField & field
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
std::vector< std::array< double, 3 > > coordinates
It it
Definition Schur.cpp:2568
int nb
number of DOFs
Definition Schur.cpp:2505
std::string name
int main()
constexpr double a
@ QUIET
#define CATCH_ERRORS
Catch errors.
#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 ...
#define CHK_MOAB_THROW(err, msg)
Check error code of MoAB function and throw MoFEM exception.
@ BLOCKSET
@ MOFEM_ATOM_TEST_INVALID
Definition definitions.h:40
@ 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.
#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
PetscBool testing
const double c
speed of light (cm/ns)
const double v
phase velocity of light in medium (cm/ns)
FTensor::Index< 'l', 3 > l
FTensor::Index< 'j', 3 > j
FTensor::Index< 'k', 3 > k
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 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)
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.
MoFEMErrorCode setMeshsetFromFile(const string file_name, const bool clean_file_options=true)
add blocksets reading config file
static double volumeLengthQuality(const double *coords)
Calculate tetrahedron volume length quality.
Definition Tools.cpp:15
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.