v0.16.3
Loading...
Searching...
No Matches
CGALInterface.cpp
Go to the documentation of this file.
1#include <MoFEM.hpp>
3#include <map>
4#include <memory>
5#include <optional>
6#include <set>
7#include <limits>
8#include <numeric>
9
10namespace MoFEM {
11namespace {
12
13struct CGALInterfaceImpl;
14
15/** The array sorted: a key independent of the order of its vertices. */
16template <class T, std::size_t N> std::array<T, N> sorted(std::array<T, N> a) {
17 std::sort(a.begin(), a.end());
18 return a;
19}
20
21/** Coordinates and GLOBAL_IDs of vertices, in the order of the range. */
22MoFEMErrorCode readVertices(moab::Interface &mb, const Range &vertices,
23 std::vector<std::array<double, 3>> &points,
24 std::vector<int> &ids) {
26 std::vector<double> coords(3 * vertices.size());
27 ids.resize(vertices.size());
28 CHKERR mb.get_coords(vertices, coords.data());
29 CHKERR mb.tag_get_data(mb.globalId_tag(), vertices, ids.data());
30 points.resize(vertices.size());
31 for (std::size_t i = 0; i != points.size(); ++i)
32 points[i] = {coords[3 * i], coords[3 * i + 1], coords[3 * i + 2]};
34}
35
36/** CGALInterface::CrackExtension on the levels managed by a
37 * CGALInterfaceImpl, which owns it. */
38struct CrackExtensionImpl final : CGALInterface::CrackExtension {
39 explicit CrackExtensionImpl(CGALInterfaceImpl &owner);
40
41 MoFEMErrorCode extendCrack(BitRefLevel source_bit, BitRefLevel output_bit,
42 const Range &crack_faces,
43 const Range &constraints,
44 const std::vector<CrackFrontRequest> &requests,
45 const CGALTools::CrackExtensionSettings &settings,
46 Range &entities, EntityHandle &new_face,
47 CGALTools::CrackExtensionCandidate *applied,
48 CGALTools::CrackExtensionReport *report,
49 Range *closure_faces) override;
50 MoFEMErrorCode closeCrackGap(
51 BitRefLevel source_bit, BitRefLevel output_bit, const Range &crack_faces,
52 const Range &constraints, const std::vector<CrackFrontRequest> &requests,
53 const CGALTools::CrackExtensionSettings &settings, Range &entities,
54 EntityHandle &new_face, CGALTools::CrackExtensionCandidate *applied,
55 CGALTools::CrackExtensionReport *report, Range *closure_faces) override;
56 MoFEMErrorCode joinCrack(BitRefLevel source_bit, BitRefLevel output_bit,
57 const Range &crack_faces, const Range &constraints,
58 const std::vector<CrackFrontRequest> &requests,
59 const CGALTools::CrackExtensionSettings &settings,
60 Range &entities, EntityHandle &new_face,
61 CGALTools::CrackExtensionCandidate *applied,
62 CGALTools::CrackExtensionReport *report,
63 Range *closure_faces) override;
64 MoFEMErrorCode crackFill(BitRefLevel bit, const Range &crack_faces,
65 const Range &constraints,
66 Range &fill_faces) override;
67 MoFEMErrorCode crackJoin(BitRefLevel bit, const Range &crack_faces,
68 const Range &constraints, Range &join_faces,
69 std::vector<int> *categories,
70 const std::vector<EntityHandle> &front_order,
71 EntityHandle *selected_front,
72 bool gaps_only) override;
73 /** Drop the reused search data. Every function of this interface that
74 * changes the mesh calls it first; see SearchCacheScope. */
75 void forgetSearchCache() { searchCache.reset(); }
76
77private:
78 void openSearchCache() override { ++searchCacheDepth; }
79 void closeSearchCache() override {
80 if (--searchCacheDepth == 0)
81 forgetSearchCache();
82 }
83 CGALInterfaceImpl &owner;
85 CGALTools &tools;
86
87 enum class Change { EXTEND, CLOSE, JOIN };
88 /** Shared publication of extension, gap closure and flip-assisted joining. */
89 MoFEMErrorCode changeCrack(Change operation, BitRefLevel source_bit,
90 BitRefLevel output_bit, const Range &crack_faces,
91 const Range &constraints,
92 const std::vector<CrackFrontRequest> &requests,
93 const CGALTools::CrackExtensionSettings &settings,
94 Range &entities, EntityHandle &new_face,
95 CGALTools::CrackExtensionCandidate *applied,
96 CGALTools::CrackExtensionReport *report,
97 Range *closure_faces);
98 /** Protected entities and volume labels for crack extension. Protected
99 * faces and curve edges are kept as sorted keys of their corner vertices,
100 * so a patch looks them up without MOAB queries. */
101 struct CrackClassification {
103 std::map<EntityHandle, int> labels;
104 std::vector<std::array<EntityHandle, 3>> faces; ///< Sorted keys.
105 std::vector<std::array<EntityHandle, 2>> curves; ///< Sorted keys.
106 bool isFace(const std::array<EntityHandle, 3> &key) const {
107 return std::binary_search(faces.begin(), faces.end(), key);
108 }
109 bool isCurve(const std::array<EntityHandle, 2> &key) const {
110 return std::binary_search(curves.begin(), curves.end(), key);
111 }
112 };
113 /** Indexed patch with its MOAB handles. */
114 struct CrackPatch {
115 TetMeshData mesh;
116 std::vector<int> crack;
117 std::vector<EntityHandle> vertices, cells;
118 std::map<EntityHandle, int> index;
119 /// Sorted vertex handles of a face or an edge given by patch indices.
120 template <std::size_t N>
121 std::array<EntityHandle, N> key(const std::array<int, N> &indices) const {
122 std::array<EntityHandle, N> handles;
123 for (std::size_t n = 0; n != N; ++n)
124 handles[n] = vertices[indices[n]];
125 return sorted(handles);
126 }
127 };
128 /** What the searches on one level read, and the patches made from it.
129 * Built for a call, or reused within a SearchCacheScope. */
130 struct SearchState {
131 /// The arguments the state was built from.
134 Range cells; ///< Tetrahedra on bit.
135 CrackClassification classification;
136 /// Patches by front edge and number of vertex rings.
137 std::map<std::pair<EntityHandle, int>, CrackPatch> edgePatches;
138 /// Patch of every cell at a crack node, for joins and the fill.
139 std::optional<CrackPatch> crackNeighbourhood;
140
141 bool builtFrom(BitRefLevel level, const Range &crack,
142 const Range &constrained) const {
143 return level == bit && crack == crackFaces && constrained == constraints;
144 }
145 };
146 int searchCacheDepth = 0; ///< Open SearchCacheScope objects.
147 std::shared_ptr<SearchState> searchCache;
148 /** The state of bit for crack_faces and constraints: the cached one when
149 * built from the same arguments, otherwise a new one, cached in a scope. */
150 MoFEMErrorCode searchState(BitRefLevel bit, const Range &crack_faces,
151 const Range &constraints,
152 std::shared_ptr<SearchState> &state);
153 /** The patch of the cells within rings vertex rings of edge. */
154 MoFEMErrorCode edgePatch(SearchState &state, EntityHandle edge, int rings,
155 const CrackPatch *&patch) const;
156 /** The patch of every cell at a crack node of bit, for joins and the
157 * fill; its cells are empty when the crack has none on bit. */
159 const Range &constraints,
160 std::shared_ptr<SearchState> &state,
161 const CrackPatch *&patch);
162 MoFEMErrorCode classifyCrackConstraints(const Range &cells,
163 const Range &crack_faces,
164 const Range &constraints,
165 CrackClassification &result) const;
166 MoFEMErrorCode crackPatch(const Range &source_cells, const Range &patch_cells,
167 const Range &crack_faces,
168 const CrackClassification &classification,
169 CrackPatch &patch) const;
170 /** A candidate prepared for publication: the result on the indexed patch,
171 * the source cells it replaces and the cells it creates, including the
172 * recreated star of a moved node. */
173 struct CrackChange {
174 CGALTools::CrackExtensionCandidate candidate;
175 TetMeshData result;
177 std::vector<std::array<int, 4>> created; ///< Patch point indices.
178 EntityHandle oldVertex = 0; ///< The free node's vertex.
179 bool moved = false;
180 };
181 /** Cells of source_cells within rings vertex rings of an edge. */
182 MoFEMErrorCode cellsAround(const EntityHandle *edge, int rings,
183 const Range &source_cells, Range &cells) const;
184 MoFEMErrorCode prepareCrackChange(const CrackPatch &patch,
185 const Range &source_cells,
186 CrackChange &change) const;
187 /** Put the change on output_bit: unchanged entities gain it, created ones
188 * are imported with parents, removed ones stay on source_bit. */
190 publishCrackChange(const CrackPatch &patch, const CrackChange &change,
191 const Range &source_cells, BitRefLevel source_bit,
192 BitRefLevel output_bit, const Range &import_sets,
193 Range &entities, EntityHandle &new_face,
194 Range *closure_faces);
195 /** Handles of the candidate's new face and closure faces; moved_vertex
196 * replaces the free node, within restricts the match. */
198 resolveCrackFaces(const CrackPatch &patch,
199 const CGALTools::CrackExtensionCandidate &candidate,
200 EntityHandle moved_vertex, bool create, const Range *within,
201 EntityHandle &new_face, Range *closure_faces) const;
202 /** The patch faces with the given indices, created if missing and put on
203 * bit: the common part of crackJoin and crackFill. They are neither crack
204 * nor protected faces, so creating them changes no search state. */
205 MoFEMErrorCode addPatchFaces(BitRefLevel bit, const CrackPatch &patch,
206 const std::vector<std::array<int, 3>> &indexed,
207 const std::string &what, Range &faces);
208};
209
210struct CGALInterfaceImpl final : CGALInterface {
211 explicit CGALInterfaceImpl(const Core &core)
212 : mField(const_cast<Core &>(core)) {
213 if (!LogManager::checkIfChannelExist("CGALInterface")) {
214 logging::core::get()->add_sink(
216 LogManager::setLog("CGALInterface");
217 MOFEM_LOG_TAG("CGALInterface", "CGALInterface");
218 }
219 }
220
221 MoFEMErrorCode query_interface(boost::typeindex::type_index,
222 UnknownInterface **iface) const override {
223 *iface = const_cast<CGALInterfaceImpl *>(this);
224 return 0;
225 }
226
227 CGALTools &getTools() override { return tools; }
228 MoFEMErrorCode importMesh(const TetMeshData &data, BitRefLevel bit,
229 Range &entities, EntityHandle &volume,
230 EntityHandle &surface) override;
231 MoFEMErrorCode exportMesh(const Range &cells, TetMeshData &data) override;
232 MoFEMErrorCode remesh(const Range &source_entities,
233 const Range &selected_cells, BitRefLevel output_bit,
234 Range &entities,
235 const CGALTools::RemeshSettings &settings,
236 CGALTools::RemeshReport &report) override;
238 reconstructDelaunay(const Range &source_entities, BitRefLevel output_bit,
239 Range &entities,
240 CGALTools::ReconstructionMethod method) override;
241 MoFEMErrorCode moabToCgal(BitRefLevel bit, BitRefLevel mask,
242 int verb) override;
243 MoFEMErrorCode cgalToMoab(BitRefLevel source_bit, BitRefLevel output_bit,
244 int verb) override;
245 MoFEMErrorCode getMesh(BitRefLevel bit, CGALMesh *&mesh) override;
246 MoFEMErrorCode getLinkedVertices(BitRefLevel bit,
247 Range &vertices) const override;
248 MoFEMErrorCode clear(BitRefLevel bit) override;
249 CrackExtension &getCrackExtension() override { return crackExtension; }
250 MoFEMErrorCode retireLevel(BitRefLevel bit) override;
251
252private:
253 friend struct CrackExtensionImpl;
254
255 /** Orient the exterior of the complete output level, excluding old parents. */
256 MoFEMErrorCode orientSkin(BitRefLevel bit) const {
258 auto &mb = mField.get_moab();
260 CHKERR mField.getInterface<BitRefManager>()->getEntitiesByTypeAndRefLevel(
261 bit, BitRefLevel().set(), MBTET, cells);
262 CHKERR mb.get_adjacencies(cells, 2, false, faces,
263 moab::Interface::UNION);
264 for (auto face : faces) {
265 Range adjacent;
266 CHKERR mb.get_adjacencies(&face, 1, 3, false, adjacent);
267 adjacent = intersect(adjacent, cells);
268 if (adjacent.size() != 1)
269 continue;
270 int side, sense, offset;
271 CHKERR mb.side_number(adjacent.front(), face, side, sense, offset);
272 if (sense != -1)
273 continue;
274 const EntityHandle *nodes;
275 int count;
276 CHKERR mb.get_connectivity(face, nodes, count, false);
277 std::vector<EntityHandle> conn(nodes, nodes + count);
278 std::swap(conn[1], conn[2]);
279 // Reversing triangle corners also reverses the mid-edge node ordering.
280 const auto first = moab::CN::HONodeIndex(MBTRI, count, 1, 0);
281 const auto last = moab::CN::HONodeIndex(MBTRI, count, 1, 2);
282 if (first >= 0 && last >= 0)
283 std::swap(conn[first], conn[last]);
284 CHKERR mb.set_connectivity(face, conn.data(), count);
285 }
287 }
288
289 /** Cells with their corner vertices, edges and faces (created if missing). */
290 MoFEMErrorCode cellClosure(const Range &cells, Range &closure) const {
292 auto &mb = mField.get_moab();
294 CHKERR mb.get_connectivity(cells, vertices, true);
295 closure = cells;
296 closure.merge(vertices);
297 for (int dim : {1, 2}) {
298 Range adjacent;
299 CHKERR mb.get_adjacencies(cells, dim, true, adjacent,
300 moab::Interface::UNION);
301 closure.merge(adjacent);
302 }
304 }
305 MoFEMErrorCode requireOneRank(const char *operation) const {
307 if (mField.get_comm_size() != 1)
309 "%s runs on one rank; the distributed workflow is not "
310 "implemented",
311 operation);
313 }
314
315 struct ManagedMesh {
316 CGALMesh mesh;
319 };
321 CGALTools tools;
322 std::map<unsigned long long, std::unique_ptr<ManagedMesh>> meshes;
323 CrackExtensionImpl crackExtension{*this};
324
325 // This bridge is local. Distributed callers establish shared identity and
326 // allocate persistent IDs through their communication workflow before import.
327 MoFEMErrorCode allocateVertexIds(size_t count, std::vector<int> &ids) const {
329 auto &mb = mField.get_moab();
331 CHKERR mb.get_entities_by_type(0, MBVERTEX, vertices);
332 int maximum = 0;
333 for (auto vertex : vertices) {
334 int id;
335 CHKERR mb.tag_get_data(mb.globalId_tag(), &vertex, 1, &id);
336 maximum = std::max(maximum, id);
337 }
338 if (count > static_cast<size_t>(INT_MAX - maximum))
339 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Vertex IDs exhausted");
340 ids.resize(count);
341 std::iota(ids.begin(), ids.end(), static_cast<long long>(maximum) + 1);
343 }
344
345 MoFEMErrorCode rollback(const Range &before, BitRefLevel bit) {
347 crackExtension.forgetSearchCache();
348 auto &mb = mField.get_moab();
349 CHKERR mField.getInterface<BitRefManager>()->lambdaBitRefLevel(
350 [&](EntityHandle, BitRefLevel &level) { level &= ~bit; });
351 Range after;
352 CHKERR mb.get_entities_by_handle(0, after);
353 const auto created = subtract(after, before);
354 const auto geometry =
355 subtract(created, created.subset_by_type(MBENTITYSET));
357 CHKERR mField.remove_ents(geometry, QUIET);
358 CHKERR mb.delete_entities(created.subset_by_type(MBENTITYSET));
359 for (int dim = 3; dim >= 0; --dim)
360 CHKERR mb.delete_entities(geometry.subset_by_dimension(dim));
362 }
363
364 // High-level operations transfer labels to registered meshsets, so their
365 // temporary import containers have no remaining ownership role.
366 MoFEMErrorCode discardImportContainers(const Range &before) {
368 Range sets;
369 CHKERR mField.get_moab().get_entities_by_type(0, MBENTITYSET, sets);
370 CHKERR mField.get_moab().delete_entities(
371 subtract(sets, before.subset_by_type(MBENTITYSET)));
373 }
374
375 MoFEMErrorCode checkLevel(BitRefLevel bit) const {
377 if (bit.none())
379 "CGAL mesh level must be nonzero");
381 }
382};
383
384MoFEMErrorCode CGALInterfaceImpl::exportMesh(const Range &cells,
385 TetMeshData &data) {
387 auto &mb = mField.get_moab();
388 TetMeshData next;
389 Range vertices, all_nodes;
390 CHKERR mb.get_connectivity(cells, vertices, true);
391 CHKERR mb.get_connectivity(cells, all_nodes, false);
392 if (all_nodes != vertices)
393 MOFEM_LOG("CGALInterface", Sev::warning)
394 << "Higher-order nodes are ignored by CGAL; using corner connectivity";
395 CHKERR readVertices(mb, vertices, next.points, next.vertexIds);
396 std::map<EntityHandle, int> indices;
397 for (auto v : vertices)
398 indices.emplace(v, static_cast<int>(indices.size()));
399 auto pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
400 for (auto c : cells) {
401 const EntityHandle *conn;
402 int n, part = 0;
403 CHKERR mb.get_connectivity(c, conn, n, true);
404 if (mb.type_from_handle(c) != MBTET || n != 4)
405 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Expected tetrahedra");
406 if (pc)
407 CHKERR mb.tag_get_data(pc->part_tag(), &c, 1, &part);
408 next.cells.push_back({indices.at(conn[0]), indices.at(conn[1]),
409 indices.at(conn[2]), indices.at(conn[3])});
410 next.partitions.push_back(part);
411 }
412 data = std::move(next);
414}
415
417CGALInterfaceImpl::remesh(const Range &source_entities,
418 const Range &selected_cells, BitRefLevel output_bit,
419 Range &entities,
420 const CGALTools::RemeshSettings &settings,
421 CGALTools::RemeshReport &report) {
423 CHKERR checkLevel(output_bit);
424 auto &mb = mField.get_moab();
425 auto bits = mField.getInterface<BitRefManager>();
426 Range occupied;
427 CHKERR bits->getEntitiesByRefLevel(output_bit, BitRefLevel().set(), occupied);
428 if (!occupied.empty())
429 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
430 "Output bit level is occupied");
431 const auto cells = source_entities.subset_by_type(MBTET);
432 if (cells.empty() || !subtract(selected_cells, cells).empty())
433 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
434 "Remeshing requires source tetrahedra and a selection within them");
436 CHKERR mb.get_connectivity(cells, vertices, true);
437 closure.merge(vertices);
438 for (int d : {1, 2}) {
439 Range adjacent;
440 CHKERR mb.get_adjacencies(cells, d, false, adjacent,
441 moab::Interface::UNION);
442 closure.merge(adjacent);
443 }
444 Range all_nodes;
445 CHKERR mb.get_connectivity(cells, all_nodes, false);
446 if (!subtract(source_entities, unite(closure, all_nodes)).empty())
447 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
448 "Remeshing constraints must belong to the source cell closure");
449 for (auto entity : closure.subset_by_dimension(3)) {
450 const EntityHandle *conn;
451 int count;
452 CHKERR mb.get_connectivity(entity, conn, count, true);
453 if (count != 4)
454 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
455 "Remeshing requires tetrahedra");
456 }
457 TetMeshData source, candidate;
458 CHKERR exportMesh(cells, source);
459 std::map<EntityHandle, int> indices;
460 int index = 0;
461 for (auto v : vertices)
462 indices.emplace(v, index++);
463 // Preserve each direct membership, including nested sideset sense groups.
464 // CGAL sees only integer labels encoding the full membership signature.
465 std::map<EntityHandle, Range> groups;
466 std::map<EntityHandle, int> group_dimensions;
467 std::vector<EntityHandle> pending;
468 auto manager = mField.getInterface<MeshsetsManager>();
469 for (auto it = manager->getBegin(); it != manager->getEnd(); ++it)
470 pending.push_back(it->getMeshset());
471 for (size_t i = 0; i != pending.size(); ++i) {
472 const auto group = pending[i];
473 if (groups.count(group))
474 continue;
475 Range members, nested;
476 CHKERR mb.get_entities_by_handle(group, members, false);
477 CHKERR mb.get_entities_by_type(group, MBENTITYSET, nested, false);
478 pending.insert(pending.end(), nested.begin(), nested.end());
479 int dim = 3;
480 while (dim >= 0 && members.subset_by_dimension(dim).empty())
481 --dim;
482 group_dimensions[group] = dim;
483 groups.emplace(group, intersect(members, closure));
484 }
485 // A set's highest-dimensional members define its classification. Lower
486 // members are closure, rather than independent curve/node constraints.
487 auto signature = [&](EntityHandle entity) {
488 std::vector<EntityHandle> value;
489 const int dim = mb.dimension_from_handle(entity);
490 for (const auto &[group, members] : groups)
491 if (group_dimensions.at(group) == dim &&
492 members.find(entity) != members.end())
493 value.push_back(group);
494 return value;
495 };
496 std::map<std::vector<EntityHandle>, int> cell_classes, face_classes,
497 edge_classes;
498 auto label = [](auto &classes, auto value) {
499 return classes.emplace(std::move(value), classes.size() + 1).first->second;
500 };
501 for (auto cell : cells)
502 source.cellLabels.push_back(label(cell_classes, signature(cell)));
503 auto connectivity = [&](EntityHandle entity, auto &conn) {
505 const EntityHandle *v;
506 int count;
507 CHKERR mb.get_connectivity(entity, v, count, true);
508 if (count != static_cast<int>(conn.size()))
509 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
510 "Remeshing constraints must be simplices");
511 for (int d = 0; d != count; ++d)
512 conn[d] = indices.at(v[d]);
514 };
515 for (auto face : closure.subset_by_type(MBTRI)) {
516 auto membership = signature(face);
517 if (membership.empty() &&
518 source_entities.find(face) == source_entities.end())
519 continue;
520 std::array<int, 3> conn;
521 CHKERR connectivity(face, conn);
522 source.boundary.push_back(conn);
523 source.surfaceLabels.push_back(label(face_classes, membership));
524 }
525 for (auto edge : closure.subset_by_type(MBEDGE)) {
526 auto membership = signature(edge);
527 if (membership.empty() &&
528 source_entities.find(edge) == source_entities.end())
529 continue;
530 std::array<int, 2> conn;
531 CHKERR connectivity(edge, conn);
532 source.featureEdges.push_back(conn);
533 source.edgeLabels.push_back(label(edge_classes, membership));
534 }
535 for (auto vertex : vertices)
536 if (source_entities.find(vertex) != source_entities.end() ||
537 !signature(vertex).empty())
538 source.fixedVertices.push_back(indices.at(vertex));
539 std::vector<int> selected;
540 for (auto cell : selected_cells)
541 selected.push_back(cells.index(cell));
542 CGALTools::RemeshReport next_report;
543 try {
544 tools.remesh(candidate, source, selected, settings, next_report);
545 } catch (const std::exception &e) {
546 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
547 "Tetrahedral remeshing rejected the candidate: %s", e.what());
548 }
549 std::set<int> source_ids(source.vertexIds.begin(), source.vertexIds.end());
550 const auto fresh_count =
551 std::count_if(candidate.vertexIds.begin(), candidate.vertexIds.end(),
552 [&](int id) { return !source_ids.count(id); });
553 std::vector<int> fresh_ids;
554 CHKERR allocateVertexIds(fresh_count, fresh_ids);
555 auto next_id = fresh_ids.begin();
556 for (auto &id : candidate.vertexIds)
557 if (!source_ids.count(id))
558 id = *next_id++;
559 Range before;
560 CHKERR mb.get_entities_by_handle(0, before);
561 Range output;
562 std::map<EntityHandle, Range> additions;
563 bool memberships_ready = false;
564 const auto publish = [&]() {
566 EntityHandle volume, surface;
567 CHKERR importMesh(candidate, output_bit, output, volume, surface);
568 std::map<int, EntityHandle> by_id;
569 for (auto vertex : output.subset_by_type(MBVERTEX)) {
570 int id;
571 CHKERR mb.tag_get_data(mb.globalId_tag(), &vertex, 1, &id);
572 by_id.emplace(id, vertex);
573 }
574 auto find = [&](const auto &conn, int dim, EntityHandle &entity) {
576 std::vector<EntityHandle> handles;
577 for (int i : conn)
578 handles.push_back(by_id.at(candidate.vertexIds[i]));
579 Range matches;
580 CHKERR mb.get_adjacencies(handles.data(), handles.size(), dim, false,
581 matches, moab::Interface::INTERSECT);
582 matches = intersect(matches, output);
583 if (matches.size() != 1)
584 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
585 "Missing remeshed simplex during classification transfer");
586 entity = matches.front();
588 };
589 auto members = [&](const auto &classes, int id, EntityHandle entity) {
590 for (const auto &[signature, label] : classes)
591 if (id == label)
592 for (auto group : signature)
593 additions[group].insert(entity);
594 };
595 for (size_t i = 0; i != candidate.cells.size(); ++i) {
596 EntityHandle entity;
597 CHKERR find(candidate.cells[i], 3, entity);
598 members(cell_classes, candidate.cellLabels[i], entity);
599 }
600 for (size_t i = 0; i != candidate.boundary.size(); ++i) {
601 EntityHandle entity;
602 CHKERR find(candidate.boundary[i], 2, entity);
603 members(face_classes, candidate.surfaceLabels[i], entity);
604 }
605 for (size_t i = 0; i != candidate.featureEdges.size(); ++i) {
606 EntityHandle entity;
607 CHKERR find(candidate.featureEdges[i], 1, entity);
608 members(edge_classes, candidate.edgeLabels[i], entity);
609 }
610 for (const auto &[group, original] : groups) {
611 for (auto vertex : original.subset_by_type(MBVERTEX)) {
612 int id;
613 CHKERR mb.tag_get_data(mb.globalId_tag(), &vertex, 1, &id);
614 if (by_id.count(id))
615 additions[group].insert(by_id.at(id));
616 }
617 }
618 for (auto &[group, added] : additions) {
619 const auto &original = groups.at(group);
620 const int dim = group_dimensions.at(group);
621 const auto top = added.subset_by_dimension(dim);
622 // Preserve the source convention for explicitly stored closure as well.
623 for (int d = 0; d < dim; ++d) {
624 if (original.subset_by_dimension(d).empty() || top.empty())
625 continue;
627 if (d == 0)
628 CHKERR mb.get_connectivity(top, closure, true);
629 else
630 CHKERR mb.get_adjacencies(top, d, false, closure,
631 moab::Interface::UNION);
632 added.merge(closure);
633 }
634 Range present;
635 CHKERR mb.get_entities_by_handle(group, present, false);
636 added = subtract(added, present);
637 }
638 memberships_ready = true;
639 for (const auto &[group, added] : additions) {
640 CHKERR mb.add_entities(group, added);
641 }
642 CHKERR discardImportContainers(before);
644 };
645 const auto error = publish();
646 if (error) {
647 if (memberships_ready)
648 for (const auto &[group, added] : additions)
649 CHKERR mb.remove_entities(group, added);
650 CHKERR rollback(before, output_bit);
651 CHKERR error;
652 }
653 entities = std::move(output);
654 report = std::move(next_report);
656}
657
659CGALInterfaceImpl::reconstructDelaunay(const Range &source_entities,
660 BitRefLevel output_bit, Range &entities,
663 CHKERR checkLevel(output_bit);
664 auto &mb = mField.get_moab();
665 auto bits = mField.getInterface<BitRefManager>();
666 Range occupied;
667 CHKERR bits->getEntitiesByRefLevel(output_bit, BitRefLevel().set(), occupied);
668 if (!occupied.empty())
669 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
670 "Output bit level is occupied");
671 Range before, output;
672 CHKERR mb.get_entities_by_handle(0, before);
673 const auto publish = [&]() {
675 const auto cells = source_entities.subset_by_type(MBTET);
676 if (cells.empty())
677 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "No source tetrahedra");
679 CHKERR mb.get_connectivity(cells, vertices, true);
680 closure.merge(vertices);
681 for (int dim : {1, 2}) {
682 Range adjacent;
683 CHKERR mb.get_adjacencies(cells, dim, true, adjacent,
684 moab::Interface::UNION);
685 closure.merge(adjacent);
686 }
687 Range all_nodes;
688 CHKERR mb.get_connectivity(cells, all_nodes, false);
689 if (!subtract(source_entities, unite(closure, all_nodes)).empty())
690 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
691 "Preserved output must belong to the selected cell closure");
692 for (auto entity : closure) {
693 const auto type = mb.type_from_handle(entity);
694 if (type == MBVERTEX)
695 continue;
696 const EntityHandle *conn;
697 int count;
698 CHKERR mb.get_connectivity(entity, conn, count, true);
699 if ((type != MBEDGE && type != MBTRI && type != MBTET) ||
700 count != moab::CN::Dimension(type) + 1)
701 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
702 "Reconstruction requires simplices");
703 }
704 TetMeshData source, reconstructed;
705 CHKERR exportMesh(cells, source);
706 std::map<EntityHandle, int> indices;
707 int index = 0;
708 for (auto vertex : vertices)
709 indices.emplace(vertex, index++);
710 Range protected_faces = source_entities.subset_by_type(MBTRI);
711 for (auto face : closure.subset_by_type(MBTRI)) {
712 Range incident;
713 CHKERR mb.get_adjacencies(&face, 1, 3, false, incident);
714 if (intersect(incident, cells).size() == 1)
715 protected_faces.insert(face);
716 }
717 std::vector<Range> memberships;
718 auto manager = mField.getInterface<MeshsetsManager>();
719 std::vector<EntityHandle> groups;
720 for (auto it = manager->getBegin(); it != manager->getEnd(); ++it)
721 groups.push_back(it->getMeshset());
722 std::set<EntityHandle> visited;
723 for (size_t i = 0; i != groups.size(); ++i) {
724 const auto group = groups[i];
725 if (!visited.insert(group).second)
726 continue;
727 Range nested, members;
728 CHKERR mb.get_entities_by_type(group, MBENTITYSET, nested, false);
729 groups.insert(groups.end(), nested.begin(), nested.end());
730 CHKERR mb.get_entities_by_handle(group, members, true);
731 members = intersect(members, closure);
732 const auto volume = members.subset_by_type(MBTET);
733 if (!volume.empty() && volume != cells)
734 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
735 "A volume meshset has an interface; constrained classification "
736 "is required");
737 memberships.push_back(std::move(members));
738 }
739 std::vector<EntityHandle> carriers(protected_faces.begin(),
740 protected_faces.end());
741 std::map<std::vector<int>, int> classes;
742 for (auto face : carriers) {
743 const EntityHandle *conn;
744 int count;
745 CHKERR mb.get_connectivity(face, conn, count, true);
746 source.boundary.push_back(
747 {indices.at(conn[0]), indices.at(conn[1]), indices.at(conn[2])});
748 std::vector<int> signature;
749 for (size_t i = 0; i != memberships.size(); ++i)
750 if (memberships[i].find(face) != memberships[i].end())
751 signature.push_back(i);
752 const int label =
753 classes.emplace(signature, classes.size() + 1).first->second;
754 source.surfaceLabels.push_back(label);
755 }
756 std::vector<std::array<int, 2>> protected_edges;
757 for (auto edge : source_entities.subset_by_type(MBEDGE)) {
758 const EntityHandle *conn;
759 int count;
760 CHKERR mb.get_connectivity(edge, conn, count, true);
761 protected_edges.push_back({indices.at(conn[0]), indices.at(conn[1])});
762 }
763 std::vector<int> parents;
764 try {
765 source.featureEdges = protected_edges;
766 parents = tools.reconstructDelaunay(reconstructed, source, method);
768 parents = tools.validateReconstruction(source, reconstructed,
769 protected_edges);
770 } catch (const std::exception &e) {
771 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
772 "Delaunay reconstruction cannot preserve this input: %s",
773 e.what());
774 }
775 Range import_sets;
776 CHKERR mb.get_entities_by_type(0, MBENTITYSET, import_sets);
777 EntityHandle volume, surface;
778 CHKERR importMesh(reconstructed, output_bit, output, volume, surface);
779 CHKERR mField.getInterface<MeshRefinement>()->setTopologicalParents(
780 closure, output, output_bit);
781 // Keep surface ancestry in its full classification, with deterministic
782 // source-face representatives for new diagonals shared by several faces.
783 std::map<EntityHandle, int> surface_parents;
784 auto identity = [&](int parent) {
785 auto face = source.boundary[parent];
786 for (auto &v : face)
787 v = source.vertexIds[v];
788 std::sort(face.begin(), face.end());
789 return face;
790 };
791 auto remember = [&](EntityHandle child, int parent) {
792 if (closure.find(child) != closure.end())
793 return;
794 auto [it, added] = surface_parents.emplace(child, parent);
795 if (!added && identity(parent) < identity(it->second))
796 it->second = parent;
797 };
798 for (size_t i = 0; i != reconstructed.boundary.size(); ++i) {
799 std::array<EntityHandle, 3> conn;
800 for (int n = 0; n != 3; ++n)
801 conn[n] = vertices[reconstructed.boundary[i][n]];
802 Range face;
803 CHKERR mb.get_adjacencies(conn.data(), 3, 2, false, face,
804 moab::Interface::INTERSECT);
805 face = intersect(face, output);
806 if (face.size() != 1)
807 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
808 "Missing reconstructed surface face");
809 remember(face.front(), parents[i]);
810 Range edges;
811 CHKERR mb.get_adjacencies(face, 1, false, edges, moab::Interface::UNION);
812 for (auto edge : edges)
813 remember(edge, parents[i]);
814 }
815 auto *refs = const_cast<RefEntity_multiIndex *>(mField.get_ref_ents());
816 for (const auto &[child, parent] : surface_parents) {
817 const auto entry = refs->find(child);
818 if (entry == refs->end() ||
819 !refs->modify(entry, RefEntity_change_parent(carriers.at(parent))))
820 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
821 "Could not register surface ancestry");
822 }
823 CHKERR discardImportContainers(import_sets);
825 };
826 const auto error = publish();
827 if (error) {
828 CHKERR rollback(before, output_bit);
829 CHKERR error;
830 }
831 entities = std::move(output);
833}
834
835MoFEMErrorCode CGALInterfaceImpl::importMesh(const TetMeshData &data,
836 BitRefLevel bit, Range &entities,
837 EntityHandle &volume,
838 EntityHandle &surface) {
840 crackExtension.forgetSearchCache();
841 CHKERR checkLevel(bit);
842 auto &mb = mField.get_moab();
843 const auto count = data.points.size();
844 std::vector<int> vertex_ids = data.vertexIds;
845 if (vertex_ids.empty())
846 CHKERR allocateVertexIds(count, vertex_ids);
847 if (count != vertex_ids.size() || count > INT_MAX ||
848 data.cells.size() > INT_MAX || data.boundary.size() > INT_MAX ||
849 (!data.partitions.empty() &&
850 data.partitions.size() != data.cells.size()) ||
851 (!data.cellLabels.empty() &&
852 data.cellLabels.size() != data.cells.size()) ||
853 (!data.surfaceLabels.empty() &&
854 data.surfaceLabels.size() != data.boundary.size()))
855 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
856 "Invalid indexed mesh dimensions");
857 std::set<int> ids;
858 for (size_t i = 0; i != count; ++i) {
859 if (vertex_ids[i] <= 0 || !ids.insert(vertex_ids[i]).second ||
860 !std::all_of(data.points[i].begin(), data.points[i].end(),
861 [](double x) { return std::isfinite(x); }))
862 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Invalid mesh vertex or ID");
863 }
864 auto validate = [&](const auto &simplices) {
866 std::set<std::vector<int>> keys;
867 for (const auto &s : simplices) {
868 std::set<int> unique;
869 for (int v : s)
870 if (v < 0 || static_cast<size_t>(v) >= count ||
871 !unique.insert(v).second)
872 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
873 "Invalid mesh connectivity");
874 std::vector<int> key(s.begin(), s.end());
875 std::sort(key.begin(), key.end());
876 if (!keys.insert(key).second)
877 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Duplicate mesh simplex");
878 }
880 };
881 CHKERR validate(data.cells);
882 CHKERR validate(data.boundary);
883 using K = CGALMesh::Kernel;
884 auto point = [&](int i) {
885 const auto &x = data.points[i];
886 return K::Point_3(x[0], x[1], x[2]);
887 };
888 std::vector<std::array<int, 4>> cells = data.cells;
889 for (auto &c : cells) {
890 const auto orientation =
891 CGAL::orientation(point(c[0]), point(c[1]), point(c[2]), point(c[3]));
892 if (orientation == CGAL::COPLANAR)
893 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
894 "Degenerate mesh tetrahedron");
895 if (orientation == CGAL::NEGATIVE)
896 std::swap(c[0], c[1]);
897 }
898 std::map<int, EntityHandle> existing;
899 Range all_vertices;
900 CHKERR mb.get_entities_by_type(0, MBVERTEX, all_vertices);
901 for (auto v : all_vertices) {
902 int id;
903 CHKERR mb.tag_get_data(mb.globalId_tag(), &v, 1, &id);
904 if (ids.count(id) && !existing.emplace(id, v).second)
905 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
906 "Duplicate local vertex ID");
907 }
908 std::vector<EntityHandle> vertices(count);
909 std::vector<int> missing;
910 for (size_t i = 0; i != count; ++i) {
911 if (auto it = existing.find(vertex_ids[i]); it != existing.end()) {
912 std::array<double, 3> x;
913 CHKERR mb.get_coords(&it->second, 1, x.data());
914 if (x != data.points[i])
915 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
916 "Coordinates disagree for vertex ID %d", vertex_ids[i]);
917 vertices[i] = it->second;
918 } else
919 missing.push_back(i);
920 }
921 ReadUtilIface *reader;
922 CHKERR mb.query_interface(reader);
923 if (!missing.empty()) {
924 EntityHandle start;
925 std::vector<double *> arrays;
926 CHKERR reader->get_node_coords(3, missing.size(), 0, start, arrays);
927 for (size_t n = 0; n != missing.size(); ++n) {
928 const auto i = missing[n];
929 vertices[i] = start + n;
930 for (int d = 0; d != 3; ++d)
931 arrays[d][n] = data.points[i][d];
932 CHKERR mb.tag_set_data(mb.globalId_tag(), &vertices[i], 1,
933 &vertex_ids[i]);
934 }
935 }
936 auto import = [&](const auto &simplices, EntityType type, Range &result) {
937 MoFEMFunctionBegin;
938 const int width = moab::CN::VerticesPerEntity(type);
939 std::vector<EntityHandle> new_conn;
940 for (const auto &s : simplices) {
941 std::vector<EntityHandle> conn;
942 for (int i : s)
943 conn.push_back(vertices[i]);
944 Range matches;
945 CHKERR mb.get_adjacencies(conn.data(), width, moab::CN::Dimension(type),
946 false, matches, moab::Interface::INTERSECT);
947 matches = matches.subset_by_type(type);
948 if (matches.size() > 1)
949 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY, "Duplicate simplex");
950 if (!matches.empty())
951 result.merge(matches);
952 else
953 new_conn.insert(new_conn.end(), conn.begin(), conn.end());
954 }
955 if (!new_conn.empty()) {
956 EntityHandle start, *conn;
957 const int n = new_conn.size() / width;
958 CHKERR reader->get_element_connect(n, width, type, 0, start, conn);
959 std::copy(new_conn.begin(), new_conn.end(), conn);
960 CHKERR reader->update_adjacencies(start, n, width, conn);
961 result.insert(start, start + n - 1);
962 }
964 };
965 Range tets, faces;
966 CHKERR import(cells, MBTET, tets);
967 CHKERR import(data.boundary, MBTRI, faces);
968 std::map<std::array<int, 4>, size_t> cell_indices;
969 for (size_t n = 0; n != cells.size(); ++n) {
970 std::array<int, 4> key;
971 for (int d = 0; d != 4; ++d)
972 key[d] = vertex_ids[cells[n][d]];
973 std::sort(key.begin(), key.end());
974 cell_indices.emplace(key, n);
975 }
976 auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
977 for (auto tet : tets) {
978 const EntityHandle *conn;
979 int count;
980 std::array<int, 4> key;
981 CHKERR mb.get_connectivity(tet, conn, count, true);
982 CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 4, key.data());
983 std::sort(key.begin(), key.end());
984 if (!data.partitions.empty())
985 CHKERR mb.tag_set_data(pc->part_tag(), &tet, 1,
986 &data.partitions[cell_indices.at(key)]);
987 }
988 // Source lower entities seed preferred ownership from incident source cells.
989 // Output sharing will be reconstructed separately from active cell closure.
990 entities = tets;
991 entities.merge(faces);
992 entities.insert_list(vertices.begin(), vertices.end());
993 for (int dim : {1, 2}) {
994 Range adj;
995 CHKERR mb.get_adjacencies(tets, dim, true, adj, moab::Interface::UNION);
996 entities.merge(adj);
997 }
998 CHKERR mField.getInterface<BitRefManager>()->setBitRefLevel(entities, bit,
999 false);
1000 CHKERR orientSkin(bit);
1001 if (!data.partitions.empty())
1002 for (auto entity : subtract(entities, tets)) {
1003 Range incident;
1004 CHKERR mb.get_adjacencies(&entity, 1, 3, false, incident);
1005 incident = intersect(incident, tets);
1006 int owner = INT_MAX;
1007 for (auto cell : incident) {
1008 int part;
1009 CHKERR mb.tag_get_data(pc->part_tag(), &cell, 1, &part);
1010 owner = std::min(owner, part);
1011 }
1012 if (owner != INT_MAX)
1013 CHKERR mb.tag_set_data(pc->part_tag(), &entity, 1, &owner);
1014 }
1015 volume = surface = 0;
1016 if (!tets.empty()) {
1017 CHKERR mb.create_meshset(MESHSET_SET, volume);
1018 CHKERR mb.add_entities(volume, tets);
1019 }
1020 if (!faces.empty()) {
1021 CHKERR mb.create_meshset(MESHSET_SET, surface);
1022 CHKERR mb.add_entities(surface, faces);
1023 }
1024 // Retain CGAL labels on explicit sets without assigning physical BC meaning.
1025 Tag label;
1026 CHKERR mb.tag_get_handle("CGAL_LABEL", 1, MB_TYPE_INTEGER, label,
1027 MB_TAG_SPARSE | MB_TAG_CREAT);
1028 std::map<int, Range> labelled_cells;
1029 for (auto tet : tets) {
1030 const EntityHandle *conn;
1031 int count;
1032 std::array<int, 4> key;
1033 CHKERR mb.get_connectivity(tet, conn, count, true);
1034 CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 4, key.data());
1035 std::sort(key.begin(), key.end());
1036 const int id =
1037 data.cellLabels.empty() ? 1 : data.cellLabels[cell_indices.at(key)];
1038 labelled_cells[id].insert(tet);
1039 }
1040 for (const auto &[id, range] : labelled_cells) {
1041 EntityHandle set = volume;
1042 if (labelled_cells.size() > 1) {
1043 CHKERR mb.create_meshset(MESHSET_SET, set);
1044 CHKERR mb.add_entities(set, range);
1045 }
1046 CHKERR mb.tag_set_data(label, &set, 1, &id);
1047 }
1048 std::map<std::array<int, 3>, int> face_labels;
1049 for (size_t n = 0; n != data.boundary.size(); ++n) {
1050 std::array<int, 3> key;
1051 for (int d = 0; d != 3; ++d)
1052 key[d] = vertex_ids[data.boundary[n][d]];
1053 std::sort(key.begin(), key.end());
1054 face_labels[key] = data.surfaceLabels.empty() ? 1 : data.surfaceLabels[n];
1055 }
1056 std::map<int, Range> labelled_faces;
1057 for (auto face : faces) {
1058 const EntityHandle *conn;
1059 int count;
1060 std::array<int, 3> key;
1061 CHKERR mb.get_connectivity(face, conn, count, true);
1062 CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 3, key.data());
1063 std::sort(key.begin(), key.end());
1064 labelled_faces[face_labels.at(key)].insert(face);
1065 }
1066 for (const auto &[id, range] : labelled_faces) {
1067 EntityHandle set = surface;
1068 if (labelled_faces.size() > 1) {
1069 CHKERR mb.create_meshset(MESHSET_SET, set);
1070 CHKERR mb.add_entities(set, range);
1071 }
1072 CHKERR mb.tag_set_data(label, &set, 1, &id);
1073 }
1075}
1076
1077MoFEMErrorCode CGALInterfaceImpl::moabToCgal(BitRefLevel bit, BitRefLevel mask,
1078 int verb) {
1080 CHKERR checkLevel(bit);
1081 auto next = std::make_unique<ManagedMesh>();
1082 CHKERR mField.getInterface<BitRefManager>()->getEntitiesByRefLevel(
1083 bit, mask, next->sourceEntities, verb);
1084 next->sourceEntities = subtract(
1085 next->sourceEntities, next->sourceEntities.subset_by_type(MBENTITYSET));
1086 next->knownVertices = next->sourceEntities.subset_by_type(MBVERTEX);
1087 std::vector<std::array<double, 3>> points(next->knownVertices.size());
1088 std::vector<std::uint64_t> identifiers;
1089 identifiers.reserve(points.size());
1090 size_t n = 0;
1091 for (auto vertex : next->knownVertices) {
1092 CHKERR mField.get_moab().get_coords(&vertex, 1, points[n++].data());
1093 identifiers.push_back(vertex);
1094 }
1095 try {
1096 tools.createDelaunay(next->mesh, points, identifiers);
1097 } catch (const std::exception &e) {
1099 "MOAB to CGAL transfer failed: %s", e.what());
1100 }
1101 meshes[bit.to_ullong()] = std::move(next);
1103}
1104
1105MoFEMErrorCode CGALInterfaceImpl::getMesh(BitRefLevel bit, CGALMesh *&mesh) {
1107 CHKERR checkLevel(bit);
1108 mesh = nullptr;
1109 const auto it = meshes.find(bit.to_ullong());
1110 if (it == meshes.end())
1112 "No CGAL mesh for the requested level; call moabToCgal first");
1113 mesh = &it->second->mesh;
1115}
1116
1117MoFEMErrorCode CGALInterfaceImpl::getLinkedVertices(BitRefLevel bit,
1118 Range &vertices) const {
1120 CHKERR checkLevel(bit);
1121 vertices.clear();
1122 const auto it = meshes.find(bit.to_ullong());
1123 if (it == meshes.end())
1125 "No CGAL mesh for the requested level");
1126 for (auto v = it->second->mesh.tr.finite_vertices_begin();
1127 v != it->second->mesh.tr.finite_vertices_end(); ++v)
1128 if (v->moabHandle)
1129 vertices.insert(v->moabHandle);
1131}
1132
1133MoFEMErrorCode CGALInterfaceImpl::clear(BitRefLevel bit) {
1135 CHKERR checkLevel(bit);
1136 meshes.erase(bit.to_ullong());
1138}
1139
1140MoFEMErrorCode CGALInterfaceImpl::cgalToMoab(BitRefLevel source_bit,
1141 BitRefLevel output_bit, int verb) {
1143 crackExtension.forgetSearchCache();
1144 CHKERR checkLevel(output_bit);
1145 CGALMesh *mesh;
1146 CHKERR getMesh(source_bit, mesh);
1147 auto &managed = *meshes.at(source_bit.to_ullong());
1148 auto &mb = mField.get_moab();
1149
1150 // Check provenance and coordinates before creating any MOAB entities.
1151 std::set<std::uint64_t> seen;
1152 for (auto v = mesh->tr.finite_vertices_begin();
1153 v != mesh->tr.finite_vertices_end(); ++v) {
1154 const auto &p = v->point();
1155 if (!std::isfinite(CGAL::to_double(p.x())) ||
1156 !std::isfinite(CGAL::to_double(p.y())) ||
1157 !std::isfinite(CGAL::to_double(p.z())))
1159 "Cannot export non-finite CGAL coordinates");
1160 if (v->moabHandle && (managed.knownVertices.find(v->moabHandle) ==
1161 managed.knownVertices.end() ||
1162 !seen.insert(v->moabHandle).second))
1164 "CGAL vertex has an unknown or duplicate MOAB identifier");
1165 }
1166
1167 const auto source_vertices = managed.sourceEntities.subset_by_type(MBVERTEX);
1168 std::vector<CGALTools::Simplex> sources;
1169 for (auto entity : subtract(managed.sourceEntities, source_vertices)) {
1170 const auto type = mb.type_from_handle(entity);
1171 if (type != MBEDGE && type != MBTRI && type != MBTET)
1173 "CGAL ancestry requires a linear simplicial source mesh");
1174 const EntityHandle *conn;
1175 int count;
1176 CHKERR mb.get_connectivity(entity, conn, count, false);
1177 if (count != moab::CN::Dimension(type) + 1)
1179 "CGAL ancestry requires linear source connectivity");
1180 CGALTools::Simplex source{entity, {}};
1181 source.vertices.resize(count);
1182 for (int n = 0; n != count; ++n) {
1183 if (source_vertices.find(conn[n]) == source_vertices.end())
1185 "Selected source mesh is missing a bounding vertex");
1186 CHKERR mb.get_coords(conn + n, 1, source.vertices[n].data());
1187 }
1188 sources.push_back(std::move(source));
1189 }
1190
1191 using Vertex = CGALMesh::Delaunay::Vertex_handle;
1192 std::vector<Vertex> new_vertices, classified_vertices;
1193 std::vector<std::array<double, 3>> new_coords, classified_coords;
1195 for (auto v = mesh->tr.finite_vertices_begin();
1196 v != mesh->tr.finite_vertices_end(); ++v) {
1197 const std::array<double, 3> coords{CGAL::to_double(v->point().x()),
1198 CGAL::to_double(v->point().y()),
1199 CGAL::to_double(v->point().z())};
1200 EntityHandle handle = v->moabHandle;
1201 bool create = !handle;
1202 if (handle) {
1203 std::array<double, 3> old_coords;
1204 CHKERR mb.get_coords(&handle, 1, old_coords.data());
1205 create = old_coords != coords;
1206 }
1207 if (create) {
1208 new_vertices.push_back(v);
1209 new_coords.push_back(coords);
1210 } else {
1211 vertices.insert(handle);
1212 }
1213 if (!sources.empty() &&
1214 (create || source_vertices.find(handle) == source_vertices.end())) {
1215 classified_vertices.push_back(v);
1216 classified_coords.push_back(coords);
1217 }
1218 }
1219
1220 std::vector<std::uint64_t> parent_ids;
1221 if (!sources.empty()) {
1222 try {
1223 parent_ids = tools.findVertexParents(classified_coords, sources);
1224 } catch (const std::exception &e) {
1226 "CGAL vertex ancestry failed: %s", e.what());
1227 }
1228 }
1229 if (new_vertices.size() >
1230 static_cast<size_t>(std::numeric_limits<int>::max()) ||
1231 mesh->tr.number_of_finite_cells() >
1232 static_cast<size_t>(std::numeric_limits<int>::max()))
1234 "CGAL export exceeds MOAB bulk allocation count limits");
1235
1236 std::vector<int> fresh_ids;
1237 CHKERR allocateVertexIds(new_vertices.size(), fresh_ids);
1238 ReadUtilIface *read_util;
1239 CHKERR mb.query_interface(read_util);
1240 if (!new_vertices.empty()) {
1241 EntityHandle start;
1242 std::vector<double *> arrays;
1243 CHKERR read_util->get_node_coords(3, static_cast<int>(new_vertices.size()),
1244 0, start, arrays);
1245 for (size_t n = 0; n != new_vertices.size(); ++n) {
1246 for (int d = 0; d != 3; ++d)
1247 arrays[d][n] = new_coords[n][d];
1248 const EntityHandle vertex = start + n;
1249 CHKERR mb.tag_set_data(mb.globalId_tag(), &vertex, 1, &fresh_ids[n]);
1250 new_vertices[n]->moabHandle = start + n;
1251 managed.knownVertices.insert(start + n);
1252 vertices.insert(start + n);
1253 }
1254 }
1255 std::map<EntityHandle, EntityHandle> vertex_parents;
1256 for (size_t n = 0; n != classified_vertices.size(); ++n)
1257 vertex_parents.emplace(classified_vertices[n]->moabHandle, parent_ids[n]);
1258
1259 Range tetrahedra;
1260 std::vector<EntityHandle> new_connectivity;
1261 if (mesh->tr.dimension() == 3) {
1262 for (auto c = mesh->tr.finite_cells_begin();
1263 c != mesh->tr.finite_cells_end(); ++c) {
1264 std::array<EntityHandle, 4> conn;
1265 for (int n = 0; n != 4; ++n)
1266 conn[n] = c->vertex(n)->moabHandle;
1267 Range candidates;
1268 CHKERR mb.get_adjacencies(conn.data(), 4, 3, false, candidates,
1269 moab::Interface::INTERSECT);
1270 EntityHandle tet = 0;
1271 for (auto candidate : candidates.subset_by_type(MBTET)) {
1272 const EntityHandle *old_conn;
1273 int count;
1274 CHKERR mb.get_connectivity(candidate, old_conn, count, true);
1275 if (count == 4) {
1276 tet = candidate;
1277 break;
1278 }
1279 }
1280 if (tet)
1281 tetrahedra.insert(tet);
1282 else
1283 new_connectivity.insert(new_connectivity.end(), conn.begin(),
1284 conn.end());
1285 }
1286 }
1287 if (!new_connectivity.empty()) {
1288 EntityHandle start, *connectivity;
1289 const int count = static_cast<int>(new_connectivity.size() / 4);
1290 CHKERR read_util->get_element_connect(count, 4, MBTET, 0, start,
1291 connectivity);
1292 std::copy(new_connectivity.begin(), new_connectivity.end(), connectivity);
1293 CHKERR read_util->update_adjacencies(start, count, 4, connectivity);
1294 tetrahedra.insert(start, start + count - 1);
1295 }
1296
1297 Range children = vertices;
1298 children.merge(tetrahedra);
1299 for (int dim : {1, 2}) {
1300 Range adjacent;
1301 CHKERR mb.get_adjacencies(tetrahedra, dim, true, adjacent,
1302 moab::Interface::UNION);
1303 children.merge(adjacent);
1304 }
1305 if (sources.empty()) {
1306 CHKERR mField.getInterface<BitRefManager>()->setBitRefLevel(
1307 children, output_bit, false, verb);
1308 } else {
1309 CHKERR mField.getInterface<MeshRefinement>()->setParents(
1310 managed.sourceEntities, children, vertex_parents, output_bit, verb);
1311 }
1312 CHKERR orientSkin(output_bit);
1314}
1315
1316CrackExtensionImpl::CrackExtensionImpl(CGALInterfaceImpl &owner)
1318
1319MoFEMErrorCode CrackExtensionImpl::classifyCrackConstraints(
1320 const Range &cells, const Range &crack_faces, const Range &constraints,
1321 CrackClassification &result) const {
1323 auto &mb = mField.get_moab();
1324 result = CrackClassification();
1325 // A meshset's highest-dimensional members define its classification;
1326 // lower-dimensional members stored with them are closure.
1327 std::map<EntityHandle, std::vector<int>> signatures;
1329 auto manager = mField.getInterface<MeshsetsManager>();
1330 std::vector<EntityHandle> groups;
1331 for (auto it = manager->getBegin(); it != manager->getEnd(); ++it)
1332 groups.push_back(it->getMeshset());
1333 std::set<EntityHandle> visited;
1334 for (size_t i = 0; i != groups.size(); ++i) {
1335 const auto group = groups[i];
1336 if (!visited.insert(group).second)
1337 continue;
1338 Range nested, members;
1339 CHKERR mb.get_entities_by_type(group, MBENTITYSET, nested, false);
1340 groups.insert(groups.end(), nested.begin(), nested.end());
1341 CHKERR mb.get_entities_by_handle(group, members, true);
1342 members = subtract(members, members.subset_by_type(MBENTITYSET));
1343 for (int dim = 3; dim >= 0; --dim) {
1344 const auto top = members.subset_by_dimension(dim);
1345 if (top.empty())
1346 continue;
1347 if (dim == 3)
1348 for (auto cell : intersect(top, cells))
1349 signatures[cell].push_back(i);
1350 else if (dim == 2)
1351 faces.merge(top.subset_by_type(MBTRI));
1352 else if (dim == 1)
1353 curves.merge(top.subset_by_type(MBEDGE));
1354 else
1355 result.vertices.merge(top);
1356 break;
1357 }
1358 }
1359 faces.merge(constraints.subset_by_type(MBTRI));
1360 curves.merge(constraints.subset_by_type(MBEDGE));
1361 result.vertices.merge(constraints.subset_by_type(MBVERTEX));
1362 faces = subtract(faces, crack_faces); // The crack is not protected.
1363 std::map<std::vector<int>, int> classes;
1364 for (const auto &[cell, signature] : signatures)
1365 result.labels[cell] =
1366 classes.emplace(signature, classes.size() + 1).first->second;
1367 const auto keys_of = [&](const Range &entities, auto &keys) {
1369 for (auto entity : entities) {
1370 const EntityHandle *conn;
1371 int count;
1372 CHKERR mb.get_connectivity(entity, conn, count, true);
1373 auto &key = keys.emplace_back();
1374 std::copy(conn, conn + key.size(), key.begin());
1375 key = sorted(key);
1376 }
1377 std::sort(keys.begin(), keys.end());
1379 };
1380 CHKERR keys_of(faces, result.faces);
1381 CHKERR keys_of(curves, result.curves);
1383}
1384
1385MoFEMErrorCode CrackExtensionImpl::crackPatch(
1386 const Range &source_cells, const Range &patch_cells,
1387 const Range &crack_faces, const CrackClassification &classification,
1388 CrackPatch &patch) const {
1390 auto &mb = mField.get_moab();
1391 patch = CrackPatch();
1393 CHKERR mb.get_connectivity(patch_cells, vertices, true);
1394 // Joining needs global crack connectivity even when its volume cavity is
1395 // local: a remote connection must not look like a separate component.
1396 Range crack_vertices;
1397 CHKERR mb.get_connectivity(crack_faces, crack_vertices, true);
1398 vertices.merge(crack_vertices);
1399 CHKERR readVertices(mb, vertices, patch.mesh.points, patch.mesh.vertexIds);
1400 for (auto v : vertices) {
1401 const int i = patch.vertices.size();
1402 if (patch.mesh.vertexIds[i] <= 0)
1403 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1404 "Crack extension needs positive vertex GLOBAL_IDs");
1405 patch.index.emplace(v, i);
1406 patch.vertices.push_back(v);
1407 if (classification.vertices.find(v) != classification.vertices.end())
1408 patch.mesh.fixedVertices.push_back(i);
1409 }
1410 // Cells, their edges, and their faces with the number of patch cells at
1411 // each face.
1412 std::map<std::array<int, 3>, int> faces;
1413 std::set<std::array<int, 2>> edges;
1414 for (auto cell : patch_cells) {
1415 const EntityHandle *conn;
1416 int count;
1417 CHKERR mb.get_connectivity(cell, conn, count, true);
1418 if (mb.type_from_handle(cell) != MBTET || count != 4)
1419 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1420 "Crack extension needs tetrahedra");
1421 std::array<int, 4> c;
1422 for (int n = 0; n != 4; ++n)
1423 c[n] = patch.index.at(conn[n]);
1424 patch.mesh.cells.push_back(c);
1425 patch.cells.push_back(cell);
1426 const auto label = classification.labels.find(cell);
1427 patch.mesh.cellLabels.push_back(
1428 label == classification.labels.end() ? 0 : label->second);
1429 for (int a = 0; a != 4; ++a)
1430 for (int b = a + 1; b != 4; ++b) {
1431 edges.insert(sorted(std::array<int, 2>{c[a], c[b]}));
1432 for (int d = b + 1; d != 4; ++d)
1433 ++faces[sorted(std::array<int, 3>{c[a], c[b], c[d]})];
1434 }
1435 }
1436
1437 // Boundary: the crack, protected and skin faces among the cell faces, in
1438 // face order, then the crack faces away from the cells, in crack order.
1439 std::vector<std::array<int, 3>> crack_keys;
1440 for (auto handle : crack_faces) {
1441 const EntityHandle *conn;
1442 int count;
1443 CHKERR mb.get_connectivity(handle, conn, count, true);
1444 crack_keys.push_back(
1445 sorted(std::array<int, 3>{patch.index.at(conn[0]),
1446 patch.index.at(conn[1]),
1447 patch.index.at(conn[2])}));
1448 }
1449 const std::set<std::array<int, 3>> crack(crack_keys.begin(),
1450 crack_keys.end());
1451 for (const auto &[f, patch_count] : faces) {
1452 if (crack.count(f)) {
1453 patch.crack.push_back(patch.mesh.boundary.size());
1454 patch.mesh.boundary.push_back(f);
1455 continue;
1456 }
1457 const auto key = patch.key(f);
1458 bool boundary = classification.isFace(key);
1459 // A face of two patch cells has two source cells. A face of one may be
1460 // on the skin; that depends on the cells outside the patch.
1461 if (!boundary && patch_count == 1) {
1462 Range incident;
1463 CHKERR mb.get_adjacencies(key.data(), 3, 3, false, incident,
1464 moab::Interface::INTERSECT);
1465 boundary = intersect(incident, source_cells).size() == 1;
1466 }
1467 if (boundary)
1468 patch.mesh.boundary.push_back(f);
1469 }
1470 for (const auto &face : crack_keys)
1471 if (!faces.count(face)) {
1472 patch.crack.push_back(patch.mesh.boundary.size());
1473 patch.mesh.boundary.push_back(face);
1474 }
1475 for (const auto &e : edges)
1476 if (classification.isCurve(patch.key(e)))
1477 patch.mesh.featureEdges.push_back(e);
1479}
1480
1481MoFEMErrorCode CrackExtensionImpl::extendCrack(
1482 BitRefLevel source_bit, BitRefLevel output_bit, const Range &crack_faces,
1483 const Range &constraints, const std::vector<CrackFrontRequest> &requests,
1484 const CGALTools::CrackExtensionSettings &settings, Range &entities,
1485 EntityHandle &new_face, CGALTools::CrackExtensionCandidate *applied,
1486 CGALTools::CrackExtensionReport *report, Range *closure_faces) {
1487 return changeCrack(Change::EXTEND, source_bit, output_bit, crack_faces,
1488 constraints, requests, settings, entities, new_face,
1489 applied, report, closure_faces);
1490}
1491
1492MoFEMErrorCode CrackExtensionImpl::closeCrackGap(
1493 BitRefLevel source_bit, BitRefLevel output_bit, const Range &crack_faces,
1494 const Range &constraints, const std::vector<CrackFrontRequest> &requests,
1495 const CGALTools::CrackExtensionSettings &settings, Range &entities,
1496 EntityHandle &new_face, CGALTools::CrackExtensionCandidate *applied,
1497 CGALTools::CrackExtensionReport *report, Range *closure_faces) {
1498 return changeCrack(Change::CLOSE, source_bit, output_bit, crack_faces,
1499 constraints, requests, settings, entities, new_face,
1500 applied, report, closure_faces);
1501}
1502
1503MoFEMErrorCode CrackExtensionImpl::joinCrack(
1504 BitRefLevel source_bit, BitRefLevel output_bit, const Range &crack_faces,
1505 const Range &constraints, const std::vector<CrackFrontRequest> &requests,
1506 const CGALTools::CrackExtensionSettings &settings, Range &entities,
1507 EntityHandle &new_face, CGALTools::CrackExtensionCandidate *applied,
1508 CGALTools::CrackExtensionReport *report, Range *closure_faces) {
1509 return changeCrack(Change::JOIN, source_bit, output_bit, crack_faces,
1510 constraints, requests, settings, entities, new_face,
1511 applied, report, closure_faces);
1512}
1513
1514MoFEMErrorCode CrackExtensionImpl::changeCrack(
1515 Change operation, BitRefLevel source_bit, BitRefLevel output_bit,
1516 const Range &crack_faces, const Range &constraints,
1517 const std::vector<CrackFrontRequest> &requests,
1518 const CGALTools::CrackExtensionSettings &settings, Range &entities,
1519 EntityHandle &new_face, CGALTools::CrackExtensionCandidate *applied,
1520 CGALTools::CrackExtensionReport *report, Range *closure_faces) {
1522 CHKERR owner.requireOneRank("crack change");
1523 CHKERR owner.checkLevel(source_bit);
1524 CHKERR owner.checkLevel(output_bit);
1525 if ((source_bit & output_bit).any())
1526 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1527 "Crack extension needs distinct source and output levels");
1528 auto &mb = mField.get_moab();
1529 auto bits = mField.getInterface<BitRefManager>();
1530 Range occupied;
1531 CHKERR bits->getEntitiesByRefLevel(output_bit, BitRefLevel().set(), occupied);
1532 if (!occupied.empty())
1533 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1534 "Output bit level is occupied");
1535 new_face = 0;
1536 entities.clear();
1537 if (closure_faces)
1538 closure_faces->clear();
1539 std::shared_ptr<SearchState> state;
1540 CHKERR searchState(source_bit, crack_faces, constraints, state);
1541 const Range &source_cells = state->cells;
1542 if (source_cells.empty())
1543 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1544 "Source level has no tetrahedra");
1545
1546 for (const auto &request : requests) {
1547 if (mb.type_from_handle(request.edge) != MBEDGE)
1548 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1549 "Crack extension request is not an edge");
1550 const EntityHandle *edge_conn;
1551 int count;
1552 CHKERR mb.get_connectivity(request.edge, edge_conn, count, true);
1553 const CrackPatch *patch_ptr;
1554 CHKERR edgePatch(*state, request.edge, settings.ringLimit, patch_ptr);
1555 const CrackPatch &patch = *patch_ptr;
1556 const std::array<int, 2> front_edge{patch.index.at(edge_conn[0]),
1557 patch.index.at(edge_conn[1])};
1558 const auto candidates =
1559 operation == Change::CLOSE
1560 ? tools.crackClosureCandidates(patch.mesh, patch.crack, front_edge,
1561 request.direction, settings, report)
1562 : operation == Change::JOIN
1563 ? tools.crackJoiningCandidates(patch.mesh, patch.crack, front_edge,
1564 request.direction, settings, report)
1565 : tools.crackExtensionCandidates(patch.mesh, patch.crack,
1566 front_edge, request.direction,
1567 settings, report);
1568 if (candidates.empty())
1569 continue;
1570 // Validate the result on the indexed patch before touching MOAB.
1571 CrackChange change;
1572 change.candidate = candidates.front();
1573 change.result = patch.mesh;
1574 auto result_crack = patch.crack;
1575 tools.applyCrackExtension(change.result, result_crack, change.candidate);
1576 CHKERR prepareCrackChange(patch, source_cells, change);
1577
1578 Range before, import_sets;
1579 CHKERR mb.get_entities_by_handle(0, before);
1580 CHKERR mb.get_entities_by_type(0, MBENTITYSET, import_sets);
1581 const auto error =
1582 publishCrackChange(patch, change, source_cells, source_bit, output_bit,
1583 import_sets, entities, new_face, closure_faces);
1584 if (error) {
1585 new_face = 0;
1586 entities.clear();
1587 if (closure_faces)
1588 closure_faces->clear();
1589 CHKERR owner.rollback(before, output_bit);
1590 CHKERR error;
1591 }
1592 if (applied)
1593 *applied = change.candidate;
1594 MOFEM_LOG("CGALInterface", Sev::verbose)
1595 << "Crack extension class " << change.candidate.candidateClass << ", "
1596 << change.candidate.removedCells.size() << " removed and "
1597 << change.candidate.createdCells.size() << " created cells"
1598 << (change.moved ? ", free node moved" : "");
1599 break;
1600 }
1602}
1603
1604MoFEMErrorCode CrackExtensionImpl::cellsAround(const EntityHandle *edge,
1605 int rings,
1606 const Range &source_cells,
1607 Range &cells) const {
1609 auto &mb = mField.get_moab();
1610 cells.clear();
1611 Range ring(edge[0], edge[0]);
1612 ring.insert(edge[1]);
1613 for (int r = 0; r != rings; ++r) {
1614 Range adjacent;
1615 CHKERR mb.get_adjacencies(ring, 3, false, adjacent, moab::Interface::UNION);
1616 cells.merge(intersect(adjacent, source_cells));
1617 ring.clear();
1618 CHKERR mb.get_connectivity(cells, ring, true);
1619 }
1621}
1622
1624CrackExtensionImpl::searchState(BitRefLevel bit, const Range &crack_faces,
1625 const Range &constraints,
1626 std::shared_ptr<SearchState> &state) {
1628 if (searchCache && searchCache->builtFrom(bit, crack_faces, constraints)) {
1631 }
1632 state = std::make_shared<SearchState>();
1633 state->bit = bit;
1634 state->crackFaces = crack_faces;
1635 state->constraints = constraints;
1636 CHKERR mField.getInterface<BitRefManager>()->getEntitiesByTypeAndRefLevel(
1637 bit, BitRefLevel().set(), MBTET, state->cells);
1638 CHKERR classifyCrackConstraints(state->cells, crack_faces, constraints,
1639 state->classification);
1640 if (searchCacheDepth)
1643}
1644
1645MoFEMErrorCode CrackExtensionImpl::edgePatch(SearchState &state,
1646 EntityHandle edge, int rings,
1647 const CrackPatch *&patch) const {
1649 const auto key = std::make_pair(edge, rings);
1650 auto it = state.edgePatches.find(key);
1651 if (it == state.edgePatches.end()) {
1652 const EntityHandle *conn;
1653 int count;
1654 CHKERR mField.get_moab().get_connectivity(edge, conn, count, true);
1655 Range patch_cells;
1656 CHKERR cellsAround(conn, rings, state.cells, patch_cells);
1657 if (patch_cells.empty())
1658 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
1659 "Crack extension edge is not on the source level");
1660 CrackPatch built;
1661 CHKERR crackPatch(state.cells, patch_cells, state.crackFaces,
1662 state.classification, built);
1663 it = state.edgePatches.emplace(key, std::move(built)).first;
1664 }
1665 patch = &it->second;
1667}
1668
1669MoFEMErrorCode CrackExtensionImpl::crackNeighbourhood(
1670 BitRefLevel bit, const Range &crack_faces, const Range &constraints,
1671 std::shared_ptr<SearchState> &state, const CrackPatch *&patch) {
1673 CHKERR searchState(bit, crack_faces, constraints, state);
1674 if (!state->crackNeighbourhood) {
1675 // Every cell at a crack node, so crack faces per edge are exact; its
1676 // cost grows with the crack.
1677 auto &mb = mField.get_moab();
1678 Range crack_vertices, patch_cells;
1679 CHKERR mb.get_connectivity(crack_faces, crack_vertices, true);
1680 CHKERR mb.get_adjacencies(crack_vertices, 3, false, patch_cells,
1681 moab::Interface::UNION);
1682 patch_cells = intersect(patch_cells, state->cells);
1683 auto &neighbourhood = state->crackNeighbourhood.emplace();
1684 if (!patch_cells.empty())
1685 CHKERR crackPatch(state->cells, patch_cells, crack_faces,
1686 state->classification, neighbourhood);
1687 }
1688 patch = &*state->crackNeighbourhood;
1690}
1691
1693CrackExtensionImpl::prepareCrackChange(const CrackPatch &patch,
1694 const Range &source_cells,
1695 CrackChange &change) const {
1697 auto &mb = mField.get_moab();
1698 const auto &candidate = change.candidate;
1699 const int w = candidate.freeNode;
1700 change.oldVertex = patch.vertices[w];
1701 change.moved = candidate.displacement != std::array<double, 3>{};
1702 for (int c : candidate.removedCells)
1703 change.removed.insert(patch.cells[c]);
1704 if (change.moved) {
1705 Range star;
1706 CHKERR mb.get_adjacencies(&change.oldVertex, 1, 3, false, star);
1707 change.removed.merge(intersect(star, source_cells));
1708 }
1709 std::set<std::array<int, 4>> keys;
1710 const auto add_created = [&](const std::array<int, 4> &cell) {
1711 auto key = cell;
1712 std::sort(key.begin(), key.end());
1713 if (keys.insert(key).second)
1714 change.created.push_back(cell);
1715 };
1716 for (const auto &cell : candidate.createdCells)
1717 add_created(cell);
1718 if (change.moved)
1719 for (const auto &cell : change.result.cells)
1720 if (std::count(cell.begin(), cell.end(), w))
1721 add_created(cell);
1723}
1724
1725MoFEMErrorCode CrackExtensionImpl::resolveCrackFaces(
1726 const CrackPatch &patch,
1727 const CGALTools::CrackExtensionCandidate &candidate,
1728 EntityHandle moved_vertex, bool create, const Range *within,
1729 EntityHandle &new_face, Range *closure_faces) const {
1731 auto &mb = mField.get_moab();
1732 const auto resolve = [&](const std::array<int, 3> &face_vertices,
1733 EntityHandle &handle) {
1735 std::array<EntityHandle, 3> conn;
1736 for (int n = 0; n != 3; ++n) {
1737 const int v = face_vertices[n];
1738 conn[n] = moved_vertex && v == candidate.freeNode ? moved_vertex
1739 : patch.vertices[v];
1740 }
1741 Range face;
1742 CHKERR mb.get_adjacencies(conn.data(), 3, 2, create, face,
1743 moab::Interface::INTERSECT);
1744 face = face.subset_by_type(MBTRI);
1745 if (within)
1746 face = intersect(face, *within);
1747 if (face.size() != 1)
1748 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1749 "Crack extension face is missing on the output level");
1750 handle = face.front();
1752 };
1753 CHKERR resolve(candidate.newFace, new_face);
1755 for (const auto &face_vertices : candidate.closureFaces) {
1756 EntityHandle handle;
1757 CHKERR resolve(face_vertices, handle);
1758 closures.insert(handle);
1759 }
1760 if (closure_faces)
1761 *closure_faces = closures;
1763}
1764
1765MoFEMErrorCode CrackExtensionImpl::publishCrackChange(
1766 const CrackPatch &patch, const CrackChange &change,
1767 const Range &source_cells, BitRefLevel source_bit, BitRefLevel output_bit,
1768 const Range &import_sets, Range &entities, EntityHandle &new_face,
1769 Range *closure_faces) {
1771 forgetSearchCache();
1772 auto &mb = mField.get_moab();
1773 auto bits = mField.getInterface<BitRefManager>();
1774 const auto &candidate = change.candidate;
1775 const int w = candidate.freeNode;
1776
1777 // Unchanged entities join the output level.
1778 Range closure;
1779 CHKERR owner.cellClosure(subtract(source_cells, change.removed), closure);
1780 CHKERR bits->setBitRefLevel(closure, output_bit, false);
1781 if (change.created.empty()) {
1782 // The faces already exist and nothing moves: no new entities.
1783 CHKERR resolveCrackFaces(patch, candidate, 0, true, nullptr, new_face,
1784 closure_faces);
1785 Range added(new_face, new_face);
1786 if (closure_faces)
1787 added.merge(*closure_faces);
1788 CHKERR bits->setBitRefLevel(added, output_bit, false);
1789 entities = unite(closure, added);
1791 }
1792
1793 // Created cells and the faces joining the crack, the new face first, as
1794 // indexed data; a moved node gets a fresh ID.
1795 std::vector<int> new_ids;
1796 if (change.moved)
1797 CHKERR owner.allocateVertexIds(1, new_ids);
1798 TetMeshData data;
1799 std::map<int, int> local;
1800 const auto point = [&](int v) {
1801 auto it = local.find(v);
1802 if (it != local.end())
1803 return it->second;
1804 const int i = data.points.size();
1805 local.emplace(v, i);
1806 data.points.push_back(change.result.points[v]);
1807 data.vertexIds.push_back(change.moved && v == w ? new_ids[0]
1808 : patch.mesh.vertexIds[v]);
1809 return i;
1810 };
1811 for (const auto &cell : change.created)
1812 data.cells.push_back(
1813 {point(cell[0]), point(cell[1]), point(cell[2]), point(cell[3])});
1814 std::vector<std::array<int, 3>> crack_added{candidate.newFace};
1815 crack_added.insert(crack_added.end(), candidate.closureFaces.begin(),
1816 candidate.closureFaces.end());
1817 for (const auto &f : crack_added)
1818 data.boundary.push_back({point(f[0]), point(f[1]), point(f[2])});
1819 Range existing, imported;
1820 CHKERR mb.get_entities_by_handle(0, existing);
1821 EntityHandle volume, surface;
1822 CHKERR owner.importMesh(data, output_bit, imported, volume, surface);
1823 // Only entities created by the import need parents; reused ones, such as
1824 // an existing closure face, already belong to the output level.
1825 const auto children = subtract(imported, existing);
1826
1827 // Removed entities stay on the source level as parents; a moved node's
1828 // new vertex has the source vertex as parent.
1829 Range source;
1830 CHKERR owner.cellClosure(change.removed, source);
1831 CHKERR bits->setBitRefLevel(source, source_bit, false);
1832 std::map<EntityHandle, EntityHandle> moved_vertices;
1833 EntityHandle moved_vertex = 0;
1834 if (change.moved) {
1835 for (auto v : imported.subset_by_type(MBVERTEX)) {
1836 int id;
1837 CHKERR mb.tag_get_data(mb.globalId_tag(), &v, 1, &id);
1838 if (id == new_ids[0])
1839 moved_vertex = v;
1840 }
1841 if (!moved_vertex)
1842 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1843 "Moved vertex was not imported");
1844 moved_vertices.emplace(moved_vertex, change.oldVertex);
1845 }
1846 CHKERR mField.getInterface<MeshRefinement>()->setTopologicalParents(
1847 source, children, output_bit, QUIET, moved_vertices);
1848
1849 CHKERR resolveCrackFaces(patch, candidate, moved_vertex, false, &imported,
1850 new_face, closure_faces);
1851 entities = unite(closure, imported);
1852 CHKERR owner.discardImportContainers(import_sets);
1854}
1855
1857CrackExtensionImpl::crackJoin(BitRefLevel bit, const Range &crack_faces,
1858 const Range &constraints, Range &join_faces,
1859 std::vector<int> *categories,
1860 const std::vector<EntityHandle> &front_order,
1861 EntityHandle *selected_front, bool gaps_only) {
1863 CHKERR owner.requireOneRank("crackJoin");
1864 CHKERR owner.checkLevel(bit);
1865 join_faces.clear();
1866 if (categories)
1867 categories->clear();
1868 if (selected_front)
1869 *selected_front = 0;
1870 std::shared_ptr<SearchState> state;
1871 const CrackPatch *patch_ptr;
1872 CHKERR crackNeighbourhood(bit, crack_faces, constraints, state, patch_ptr);
1873 const CrackPatch &patch = *patch_ptr;
1874 if (patch.cells.empty())
1876
1877 // The listed front edges as patch index pairs.
1878 auto &mb = mField.get_moab();
1879 std::vector<std::array<int, 2>> indexed_order;
1880 std::map<std::array<int, 2>, EntityHandle> handles;
1881 for (auto edge : front_order) {
1882 const EntityHandle *conn;
1883 int count;
1884 CHKERR mb.get_connectivity(edge, conn, count, true);
1885 if (count != 2 || !patch.index.count(conn[0]) ||
1886 !patch.index.count(conn[1]))
1887 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1888 "Ordered crack join edge is not in the crack patch");
1889 const auto key = sorted(
1890 std::array<int, 2>{patch.index.at(conn[0]), patch.index.at(conn[1])});
1891 indexed_order.push_back(key);
1892 handles.emplace(key, edge);
1893 }
1894
1895 // With gaps_only, a face must share at least two edges with the crack.
1896 const auto face_edges = [](const std::array<int, 3> &f) {
1897 return std::array<std::array<int, 2>, 3>{
1898 sorted(std::array<int, 2>{f[0], f[1]}),
1899 sorted(std::array<int, 2>{f[1], f[2]}),
1900 sorted(std::array<int, 2>{f[0], f[2]})};
1901 };
1902 std::set<std::array<int, 2>> crack_edges;
1903 if (gaps_only)
1904 for (int i : patch.crack)
1905 for (const auto &edge : face_edges(patch.mesh.boundary[i]))
1906 crack_edges.insert(edge);
1907 const auto accept = [&](const std::array<int, 3> &face) {
1908 if (!gaps_only)
1909 return true;
1910 int shared = 0;
1911 for (const auto &edge : face_edges(face))
1912 shared += crack_edges.count(edge);
1913 return shared >= 2;
1914 };
1915
1916 std::vector<std::array<int, 3>> faces;
1917 for (const auto &join :
1918 tools.crackJoinFaces(patch.mesh, patch.crack, indexed_order, accept)) {
1919 faces.push_back(join.face);
1920 if (categories)
1921 categories->push_back(join.category);
1922 if (selected_front && !front_order.empty())
1923 *selected_front =
1924 handles.at(sorted(std::array<int, 2>{join.face[0], join.face[1]}));
1925 }
1926 CHKERR addPatchFaces(bit, patch, faces, "join", join_faces);
1928}
1929
1930MoFEMErrorCode CrackExtensionImpl::crackFill(BitRefLevel bit,
1931 const Range &crack_faces,
1932 const Range &constraints,
1933 Range &fill_faces) {
1935 CHKERR owner.requireOneRank("crackFill");
1936 CHKERR owner.checkLevel(bit);
1937 fill_faces.clear();
1938 std::shared_ptr<SearchState> state;
1939 const CrackPatch *patch;
1940 CHKERR crackNeighbourhood(bit, crack_faces, constraints, state, patch);
1941 if (patch->cells.empty())
1943 CHKERR addPatchFaces(bit, *patch,
1944 tools.crackFillFaces(patch->mesh, patch->crack), "fill",
1945 fill_faces);
1947}
1948
1949MoFEMErrorCode CrackExtensionImpl::addPatchFaces(
1950 BitRefLevel bit, const CrackPatch &patch,
1951 const std::vector<std::array<int, 3>> &indexed, const std::string &what,
1952 Range &faces) {
1954 auto &mb = mField.get_moab();
1955 for (const auto &f : indexed) {
1956 const EntityHandle conn[] = {patch.vertices[f[0]], patch.vertices[f[1]],
1957 patch.vertices[f[2]]};
1958 Range face;
1959 CHKERR mb.get_adjacencies(conn, 3, 2, true, face,
1960 moab::Interface::INTERSECT);
1961 face = face.subset_by_type(MBTRI);
1962 if (face.size() != 1)
1963 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1964 "Crack %s face is ambiguous", what.c_str());
1965 faces.merge(face);
1966 }
1967 CHKERR mField.getInterface<BitRefManager>()->setBitRefLevel(faces, bit,
1968 false);
1970}
1971
1972MoFEMErrorCode CGALInterfaceImpl::retireLevel(BitRefLevel bit) {
1974 CHKERR requireOneRank("retireLevel");
1975 CHKERR checkLevel(bit);
1976 crackExtension.forgetSearchCache();
1977 auto &mb = mField.get_moab();
1978 auto bits = mField.getInterface<BitRefManager>();
1979 Range retired, active;
1980 CHKERR bits->getEntitiesByRefLevel(bit, bit, retired);
1981 retired = subtract(retired, retired.subset_by_type(MBENTITYSET));
1982 CHKERR bits->getEntitiesByRefLevel(~bit, BitRefLevel().set(), active);
1983 active = subtract(active, active.subset_by_type(MBENTITYSET));
1984 // Entities on another level must not depend on retired ones.
1985 const auto elements = subtract(active, active.subset_by_type(MBVERTEX));
1986 Range used;
1987 CHKERR mb.get_connectivity(elements, used, false);
1988 for (int dim : {1, 2}) {
1989 Range adjacent;
1990 CHKERR mb.get_adjacencies(elements.subset_by_dimension(3), dim, false,
1991 adjacent, moab::Interface::UNION);
1992 used.merge(adjacent);
1993 }
1994 if (!intersect(used, retired).empty())
1995 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1996 "A retired entity is still used by an entity on another level");
1998 CHKERR bits->lambdaBitRefLevel(
1999 [&](EntityHandle, BitRefLevel &level) { level &= ~bit; });
2001}
2002
2003} // namespace
2004
2005template <> CGALInterface *createInterface<CGALInterface>(const Core &core) {
2006 return new CGALInterfaceImpl(core);
2007}
2008
2009} // namespace MoFEM
Opt-in CGAL types; not included by MoFEM.hpp.
std::map< EntityHandle, int > labels
CGALInterfaceImpl & owner
TetMeshData mesh
std::map< EntityHandle, int > index
Range vertices
int searchCacheDepth
Open SearchCacheScope objects.
Range removed
Range crackFaces
CGALTools & tools
std::optional< CrackPatch > crackNeighbourhood
Patch of every cell at a crack node, for joins and the fill.
BitRefLevel bit
The arguments the state was built from.
std::vector< std::array< EntityHandle, 3 > > faces
Sorted keys.
TetMeshData result
std::vector< std::array< int, 4 > > created
Patch point indices.
CGALTools::CrackExtensionCandidate candidate
CrackExtensionImpl crackExtension
std::vector< std::array< EntityHandle, 2 > > curves
Sorted keys.
std::vector< EntityHandle > cells
Tetrahedra on bit.
CrackClassification classification
std::shared_ptr< SearchState > searchCache
Range knownVertices
Range constraints
std::map< std::pair< EntityHandle, int >, CrackPatch > edgePatches
Patches by front edge and number of vertex rings.
Range sourceEntities
EntityHandle oldVertex
The free node's vertex.
std::map< unsigned long long, std::unique_ptr< ManagedMesh > > meshes
MoFEM::Interface & mField
std::vector< int > crack
bool selected
Definition CGALTools.cpp:97
std::function< bool(size_t)> accept
Definition CGALTools.cpp:61
Report & report
std::vector< int > created
std::vector< int > source
const Settings & settings
int boundary
const std::vector< Vec > * points
FaceSet crack
std::vector< Face > closures
Faces closing non-convex front corners.
std::vector< int > removed
std::vector< int > size
std::vector< int > label
WorkMesh mesh
std::vector< int > vertices
int w
Free node.
std::vector< int > parent
bool closure
The face (f0, f1, w) closes a corner at f0 or f1.
std::unordered_map< int, NodeConstraint > constraints
std::vector< Cell > cells
std::array< int, 4 > connectivity
EntityHandle handle
ParentChildKey key
bool active
moab::Interface & mb
std::vector< double > empty
One value per component.
std::string type
PyGILState_STATE state
Definition SDFPython.cpp:13
It it
Definition Schur.cpp:2568
It end
Definition Schur.cpp:2568
constexpr double a
@ QUIET
#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.
virtual const RefEntity_multiIndex * get_ref_ents() const =0
Get the ref ents object.
static LoggerType & setLog(const std::string channel)
Set ans resset chanel logger.
#define MOFEM_LOG(channel, severity)
Log.
#define MOFEM_LOG_TAG(channel, tag)
Tag channel.
auto bit
set bit
FTensor::Index< 'i', SPACE_DIM > i
const double c
speed of light (cm/ns)
const double v
phase velocity of light in medium (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
multi_index_container< boost::shared_ptr< RefEntity >, indexed_by< ordered_unique< tag< Ent_mi_tag >, const_mem_fun< RefEntity, EntityHandle, &RefEntity::getEnt > >, ordered_non_unique< tag< Ent_Ent_mi_tag >, const_mem_fun< RefEntity, EntityHandle, &RefEntity::getParentEnt > >, ordered_non_unique< tag< Composite_EntType_and_ParentEntType_mi_tag >, composite_key< RefEntity, const_mem_fun< RefEntity, EntityType, &RefEntity::getEntType >, const_mem_fun< RefEntity, EntityType, &RefEntity::getParentEntType > > >, ordered_non_unique< tag< Composite_ParentEnt_And_EntType_mi_tag >, composite_key< RefEntity, const_mem_fun< RefEntity, EntityType, &RefEntity::getEntType >, const_mem_fun< RefEntity, EntityHandle, &RefEntity::getParentEnt > > > > > RefEntity_multiIndex
CoreTmp< 0 > Core
Definition Core.hpp:1161
float offset
Definition sdf_python.py:3
int r
Definition sdf.py:205
const int N
Definition speed_test.cpp:3
CGAL::Exact_predicates_inexact_constructions_kernel Kernel
void remesh(TetMeshData &result, const TetMeshData &source, const std::vector< int > &selected_cells, const RemeshSettings &settings, RemeshReport &report) const
std::vector< int > validateReconstruction(const TetMeshData &source, TetMeshData &result, const std::vector< std::array< int, 2 > > &protected_edges={}, const std::function< void(const std::string &)> &warning={}) const
std::vector< int > reconstructDelaunay(TetMeshData &result, const TetMeshData &vertices, ReconstructionMethod method=ReconstructionMethod::PointDelaunay) const
std::vector< std::uint64_t > findVertexParents(const std::vector< std::array< double, 3 > > &points, const std::vector< Simplex > &sources) const
void createDelaunay(CGALMesh &mesh, const std::vector< std::array< double, 3 > > &points, const std::vector< std::uint64_t > &identifiers={}) const
virtual int get_comm_size() const =0
virtual moab::Interface & get_moab()=0
virtual MoFEMErrorCode delete_ents_by_bit_ref(const BitRefLevel bit, const BitRefLevel mask, const bool remove_parent=false, int verb=DEFAULT_VERBOSITY, MoFEMTypes mf=MF_ZERO)=0
Delete entities from MoFEM and MOAB database.
virtual MPI_Comm & get_comm() const =0
virtual MoFEMErrorCode remove_ents(const Range ents, int verb=DEFAULT_VERBOSITY)=0
Remove entities from MoFEM database.
virtual MoFEMErrorCode remove_parents_by_ents(const Range &ents, int verb=DEFAULT_VERBOSITY)=0
Remove parents from entities.
Core (interface) class.
Definition Core.hpp:83
Deprecated interface functions.
static boost::shared_ptr< SinkType > createSink(boost::shared_ptr< std::ostream > stream_ptr, std::string comm_filter)
Create a sink object.
static bool checkIfChannelExist(const std::string channel)
Check if channel exist.
static boost::shared_ptr< std::ostream > getStrmSelf()
Get the strm self object.
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.