v0.16.3
Loading...
Searching...
No Matches
CommInterface.cpp
Go to the documentation of this file.
1/** \file CommInterface.cpp
2 * \brief Functions for interprocess communications
3 * \mofem_comm
4 */
5
6#include "CGALTools.hpp"
7
8namespace MoFEM {
9
11CommInterface::query_interface(boost::typeindex::type_index type_index,
12 UnknownInterface **iface) const {
14 *iface = const_cast<CommInterface *>(this);
16}
17
19 : cOre(const_cast<MoFEM::Core &>(core)), dEbug(false) {}
20
21namespace {
22
23using ParentChildKey = std::array<int, 5>;
24
25struct ParentChildCopy {
26 ParentChildKey key{}, parent{};
27 std::array<int, 4> connectivity{};
28 EntityHandle handle = 0;
29 int owner = 0;
30 unsigned char status = 0;
31};
32
33using ParentChildCopies = std::map<int, ParentChildCopy>;
34using ParentChildRecords = std::map<ParentChildKey, ParentChildCopies>;
35
36// Local validation must finish on every rank before any topology transfer.
37MoFEMErrorCode parentChildAgree(MPI_Comm comm, MoFEMErrorCode local_error) {
39 int error = local_error, global_error;
40 CHKERR MPI_Allreduce(&error, &global_error, 1, MPI_INT, MPI_MAX, comm);
41 if (global_error)
42 SETERRQ(comm, global_error,
43 "Collective mesh operation failed validation on an MPI rank");
45}
46
47MoFEMErrorCode parentChildKey(moab::Interface &mb, Tag ids, EntityHandle entity,
48 ParentChildKey &key,
49 std::array<int, 4> &connectivity) {
51 key.fill(0);
52 connectivity.fill(0);
53 const auto type = mb.type_from_handle(entity);
54 key[0] = type;
55 if (type == MBVERTEX) {
56 CHKERR mb.tag_get_data(ids, &entity, 1, &key[1]);
57 } else {
58 if (type != MBEDGE && type != MBTRI && type != MBTET)
59 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
60 "Parent-child synchronisation requires linear simplices");
61 const EntityHandle *conn;
62 int count;
63 CHKERR mb.get_connectivity(entity, conn, count, false);
64 if (count != moab::CN::Dimension(type) + 1)
65 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
66 "Parent-child synchronisation requires linear connectivity");
67 CHKERR mb.tag_get_data(ids, conn, count, connectivity.data());
68 std::copy_n(connectivity.begin(), count, key.begin() + 1);
69 std::sort(key.begin() + 1, key.begin() + 1 + count);
70 if (std::adjacent_find(key.begin() + 1, key.begin() + 1 + count) !=
71 key.begin() + 1 + count)
72 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
73 "Element has repeated global vertex IDs");
74 }
75 if (key[1] <= 0)
76 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
77 "Every selected vertex requires a positive GLOBAL_ID");
79}
80
81MoFEMErrorCode parentChildSnapshot(MoFEM::Interface &m_field,
82 ParallelComm &pcomm, const Range &parents,
83 const Range &entities, bool source,
84 std::vector<ParentChildCopy> &copies) {
86 auto &mb = m_field.get_moab();
87 const auto ids = mb.globalId_tag();
88 const auto parent_tag =
89 m_field.getInterface<BitRefManager>()->get_th_RefParentHandle();
90 std::set<ParentChildKey> keys;
91 const auto vertices = entities.subset_by_type(MBVERTEX);
92 for (auto entity : entities) {
93 ParentChildCopy copy;
94 copy.handle = entity;
95 CHKERR parentChildKey(mb, ids, entity, copy.key, copy.connectivity);
96 if (!keys.insert(copy.key).second)
97 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
98 "Duplicate global entity identity on one MPI rank");
99 if (mb.type_from_handle(entity) != MBVERTEX) {
100 Range corners;
101 CHKERR mb.get_connectivity(&entity, 1, corners);
102 if (!subtract(corners, vertices).empty())
103 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
104 "Selected level is missing bounding vertices");
105 }
106 if (source) {
107 CHKERR pcomm.get_owner(entity, copy.owner);
108 CHKERR pcomm.get_pstatus(entity, copy.status);
109 } else if (parents.find(entity) == parents.end()) {
110 EntityHandle parent;
111 CHKERR mb.tag_get_data(parent_tag, &entity, 1, &parent);
112 if (!parent || parents.find(parent) == parents.end())
113 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
114 "Child parent is absent from the selected parent level");
115 std::array<int, 4> unused;
116 CHKERR parentChildKey(mb, ids, parent, copy.parent, unused);
117 }
118 copies.push_back(copy);
119 }
121}
122
123// Exchange descriptions, not mesh payloads. MOAB transports topology and tags.
124MoFEMErrorCode parentChildGather(MPI_Comm comm,
125 const std::vector<ParentChildCopy> &local,
126 ParentChildRecords &records) {
128 int size;
129 CHKERR MPI_Comm_size(comm, &size);
130 CHKERR parentChildAgree(comm, local.size() > static_cast<size_t>(INT_MAX) /
131 sizeof(ParentChildCopy)
133 : 0);
134 const int bytes = local.size() * sizeof(ParentChildCopy);
135 std::vector<int> counts(size), offsets(size);
136 CHKERR MPI_Allgather(&bytes, 1, MPI_INT, counts.data(), 1, MPI_INT, comm);
137 size_t total = 0;
138 for (int rank = 0; rank != size; ++rank) {
139 offsets[rank] = total <= INT_MAX ? total : 0;
140 total += counts[rank];
141 }
142 CHKERR parentChildAgree(comm, total > INT_MAX ? MOFEM_DATA_INCONSISTENCY : 0);
143 std::vector<ParentChildCopy> all(total / sizeof(ParentChildCopy));
144 CHKERR MPI_Allgatherv(local.data(), bytes, MPI_BYTE, all.data(),
145 counts.data(), offsets.data(), MPI_BYTE, comm);
146 records.clear();
147 for (int rank = 0; rank != size; ++rank)
148 for (size_t i = offsets[rank] / sizeof(ParentChildCopy);
149 i != (offsets[rank] + counts[rank]) / sizeof(ParentChildCopy); ++i)
150 records[all[i].key].emplace(rank, all[i]);
152}
153
154MoFEMErrorCode parentChildValidate(const ParentChildRecords &parents,
155 const ParentChildRecords &children) {
157 auto validate_copies = [](const auto &copies, bool source) {
159 const auto &first = copies.begin()->second;
160 if (copies.size() > MAX_SHARING_PROCS)
161 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
162 "MOAB MAX_SHARING_PROCS exceeded");
163 for (const auto &[rank, copy] : copies) {
164 if (copy.parent != first.parent || (source && copy.owner != first.owner))
165 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
166 "Copies disagree on ancestry or source owner");
167 }
168 if (source && copies.find(first.owner) == copies.end())
169 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
170 "Source owner has no resident source entity");
172 };
173 for (const auto &[key, copies] : parents)
174 CHKERR validate_copies(copies, true);
175 std::map<ParentChildKey, std::map<int, std::set<ParentChildKey>>>
176 subdivisions;
177 for (const auto &[key, copies] : children) {
178 CHKERR validate_copies(copies, false);
179 const auto &carrier = copies.begin()->second.parent;
180 if (carrier != ParentChildKey{} && parents.count(key))
181 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
182 "New child identity collides with an existing source entity");
183 const auto parent =
184 parents.find(carrier == ParentChildKey{} ? key : carrier);
185 if (parent == parents.end())
186 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
187 "Child has no selected source carrier");
188 for (const auto &[rank, copy] : copies) {
189 if (parent->second.find(rank) == parent->second.end())
190 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
191 "Producer does not have the source carrier");
192 if (carrier != ParentChildKey{})
193 subdivisions[carrier][rank].insert(key);
194 }
195 if (key[0] != MBVERTEX)
196 for (int i = 1;
197 i <= moab::CN::Dimension(static_cast<EntityType>(key[0])) + 1; ++i) {
198 const auto vertex = children.find(ParentChildKey{MBVERTEX, key[i]});
199 if (vertex == children.end())
200 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
201 "Child connectivity is missing a selected vertex");
202 const auto &v_parent = vertex->second.begin()->second.parent;
203 const auto &residents =
204 parents.at(v_parent == ParentChildKey{} ? vertex->first : v_parent);
205 for (const auto &[rank, unused] : parent->second)
206 if (residents.find(rank) == residents.end())
207 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
208 "Parent layout cannot supply child bounding closure");
209 }
210 }
211 for (const auto &[parent, producers] : subdivisions)
212 for (const auto &[rank, subdivision] : producers)
213 if (subdivision != producers.begin()->second)
214 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
215 "Concurrent producers disagree on a parent's subdivision");
217}
218
219MoFEMErrorCode parentChildSharing(moab::Interface &mb, ParallelComm &pcomm,
220 const ParentChildRecords &parents,
221 const ParentChildRecords &children) {
223 const int rank = pcomm.rank();
224 for (const auto &[key, copies] : children) {
225 const auto local = copies.find(rank);
226 if (local == copies.end() || local->second.parent == ParentChildKey{} ||
227 copies.size() == 1)
228 continue;
229 const auto &source = parents.at(local->second.parent);
230 const int inherited_owner = source.begin()->second.owner;
231 const int owner =
232 copies.count(inherited_owner) ? inherited_owner : copies.begin()->first;
233 std::vector<int> procs;
234 std::vector<EntityHandle> handles;
235 for (const auto &[other, copy] : copies)
236 if (other != rank) {
237 procs.push_back(other);
238 handles.push_back(copy.handle);
239 }
240 const auto entity = local->second.handle;
241 CHKERR pcomm.update_remote_data(entity, procs, handles);
242
243 // MOAB's public registration chooses the lowest rank. Restore the source
244 // owner/role using MOAB's tag layout; keep its shared-entity registry intact.
245 unsigned char status =
246 source.at(rank).status & (PSTATUS_INTERFACE | PSTATUS_GHOST);
247 if (owner == rank)
248 status &= ~PSTATUS_GHOST;
249 status |= PSTATUS_SHARED;
250 if (owner != rank)
251 status |= PSTATUS_NOT_OWNED;
252 if (copies.size() > 2) {
253 status |= PSTATUS_MULTISHARED;
254 std::array<int, MAX_SHARING_PROCS> ps;
255 std::array<EntityHandle, MAX_SHARING_PROCS> hs{};
256 ps.fill(-1);
257 ps[0] = owner;
258 hs[0] = copies.at(owner).handle;
259 int i = 1;
260 for (const auto &[other, copy] : copies)
261 if (other != owner) {
262 ps[i] = other;
263 hs[i++] = copy.handle;
264 }
265 CHKERR mb.tag_set_data(pcomm.sharedps_tag(), &entity, 1, ps.data());
266 CHKERR mb.tag_set_data(pcomm.sharedhs_tag(), &entity, 1, hs.data());
267 }
268 CHKERR mb.tag_set_data(pcomm.pstatus_tag(), &entity, 1, &status);
269 }
271}
272
273} // namespace
274
276 MoFEM::Interface &m_field = cOre;
278 const auto comm = m_field.get_comm();
279 CHKERR parentChildAgree(comm, root < 0 || root >= m_field.get_comm_size()
281 : 0);
282 auto broadcast = [&](auto &values) {
284 using Value = typename std::decay_t<decltype(values)>::value_type;
285 unsigned long long count = values.size();
286 CHKERR MPI_Bcast(&count, 1, MPI_UNSIGNED_LONG_LONG, root, comm);
287 if (count > static_cast<unsigned long long>(INT_MAX) / sizeof(Value))
289 "Mesh transport exceeds MPI count range");
290 values.resize(count);
291 CHKERR MPI_Bcast(values.data(), count * sizeof(Value), MPI_BYTE, root,
292 comm);
294 };
295 CHKERR broadcast(data.points);
296 CHKERR broadcast(data.vertexIds);
297 CHKERR broadcast(data.cells);
298 CHKERR broadcast(data.boundary);
299 CHKERR broadcast(data.cellLabels);
300 CHKERR broadcast(data.surfaceLabels);
301 CHKERR broadcast(data.partitions);
303}
304
306 int root) {
307 MoFEM::Interface &m_field = cOre;
309 auto &mb = m_field.get_moab();
310 const auto comm = m_field.get_comm();
311 auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
312 struct Cell {
313 std::array<int, 4> ids, owners;
314 std::array<double, 12> coordinates;
315 int part, rank;
316 };
317 std::vector<Cell> local;
318 auto snapshot = [&]() {
320 if (root < 0 || root >= m_field.get_comm_size() || !pc ||
321 cells.size() > static_cast<size_t>(INT_MAX) / sizeof(Cell))
322 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Invalid mesh gather input");
323 for (auto cell : cells) {
324 const EntityHandle *conn;
325 int n;
326 CHKERR mb.get_connectivity(cell, conn, n, true);
327 if (mb.type_from_handle(cell) != MBTET || n != 4)
328 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
329 "Gather requires linear tetrahedra");
330 Cell row;
331 row.rank = m_field.get_comm_rank();
332 CHKERR mb.tag_get_data(mb.globalId_tag(), conn, 4, row.ids.data());
333 CHKERR mb.get_coords(conn, 4, row.coordinates.data());
334 for (int i = 0; i != 4; ++i)
335 CHKERR pc->get_owner(conn[i], row.owners[i]);
336 CHKERR mb.tag_get_data(pc->part_tag(), &cell, 1, &row.part);
337 for (int id : row.ids)
338 if (id <= 0)
339 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
340 "Missing vertex global ID");
341 if (row.part < 0 || row.part >= m_field.get_comm_size())
342 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
343 "Invalid source cell partition");
344 local.push_back(row);
345 }
347 };
348 CHKERR parentChildAgree(comm, snapshot());
349 const int bytes = local.size() * sizeof(Cell);
350 std::vector<int> counts(m_field.get_comm_size()), offsets(counts.size());
351 CHKERR MPI_Allgather(&bytes, 1, MPI_INT, counts.data(), 1, MPI_INT, comm);
352 size_t total = 0;
353 for (size_t n = 0; n != counts.size(); ++n) {
354 if (total + counts[n] > INT_MAX)
356 "Global mesh exceeds MPI count range");
357 offsets[n] = total;
358 total += counts[n];
359 }
360 std::vector<Cell> rows(m_field.get_comm_rank() == root ? total / sizeof(Cell)
361 : 0);
362 CHKERR MPI_Gatherv(local.data(), bytes, MPI_BYTE, rows.data(), counts.data(),
363 offsets.data(), MPI_BYTE, root, comm);
364 auto merge = [&]() {
366 if (m_field.get_comm_rank() != root)
368 struct Vertex {
369 std::array<double, 3> coordinates;
370 std::pair<bool, int> priority;
371 };
372 std::map<int, Vertex> vertices;
373 std::map<std::array<int, 4>, Cell> unique;
374 for (const auto &row : rows) {
375 auto key = row.ids;
376 std::sort(key.begin(), key.end());
377 auto [it, inserted] = unique.emplace(key, row);
378 if (!inserted && it->second.part != row.part)
379 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
380 "Conflicting source partitions");
381 for (int n = 0; n != 4; ++n) {
382 const std::array<double, 3> x{row.coordinates[3 * n],
383 row.coordinates[3 * n + 1],
384 row.coordinates[3 * n + 2]};
385 // Prefer the owner's copy; absent ownership or an absent owner falls
386 // back to the lowest contributing rank. Geometry is not an identity.
387 const Vertex vertex{x, {row.owners[n] != row.rank, row.rank}};
388 auto [v, added] = vertices.emplace(row.ids[n], vertex);
389 if (!added && vertex.priority < v->second.priority)
390 v->second = vertex;
391 }
392 }
393 TetMeshData next;
394 std::map<int, int> indices;
395 for (const auto &[id, vertex] : vertices) {
396 indices[id] = next.points.size();
397 next.vertexIds.push_back(id);
398 next.points.push_back(vertex.coordinates);
399 }
400 for (const auto &[key, row] : unique) {
401 std::array<int, 4> c;
402 for (int n = 0; n != 4; ++n)
403 c[n] = indices.at(row.ids[n]);
404 next.cells.push_back(c);
405 next.partitions.push_back(row.part);
406 }
407 data = std::move(next);
409 };
410 CHKERR parentChildAgree(comm, merge());
412}
413
415 const Range &child_entities) {
416 MoFEM::Interface &m_field = cOre;
418 auto &mb = m_field.get_moab();
419 auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
420 auto parent_tag =
421 m_field.getInterface<BitRefManager>()->get_th_RefParentHandle();
422 for (auto entity : subtract(child_entities, source_entities)) {
423 EntityHandle parent;
424 CHKERR mb.tag_get_data(parent_tag, &entity, 1, &parent);
425 if (parent) {
426 int part;
427 CHKERR mb.tag_get_data(pc->part_tag(), &parent, 1, &part);
428 CHKERR mb.tag_set_data(pc->part_tag(), &entity, 1, &part);
429 }
430 }
432}
433
435 const BitRefLevel &active_bit,
436 const Range &preserve) {
437 MoFEM::Interface &m_field = cOre;
439 auto &mb = m_field.get_moab();
440 auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
441 if (active_bit.none())
442 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Select an active mesh level");
443 Range keep;
444 for (auto cell : entities.subset_by_type(MBTET)) {
445 int part;
446 CHKERR mb.tag_get_data(pc->part_tag(), &cell, 1, &part);
447 if (part < 0 || part >= m_field.get_comm_size())
448 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Invalid cell partition");
449 if (part == m_field.get_comm_rank())
450 keep.insert(cell);
451 }
452 for (int dim : {0, 1, 2}) {
453 Range adj;
454 CHKERR mb.get_adjacencies(keep.subset_by_type(MBTET), dim, false, adj,
455 moab::Interface::UNION);
456 keep.merge(adj);
457 }
458 const auto inactive = subtract(entities, keep);
459 CHKERR m_field.getInterface<BitRefManager>()->lambdaBitRefLevel(
460 intersect(inactive, preserve),
461 [&](EntityHandle, BitRefLevel &bit) { bit &= ~active_bit; });
462 auto remove = subtract(inactive, preserve);
463 if (!remove.empty()) {
464 Range shared = remove;
465 CHKERR pc->filter_pstatus(shared, PSTATUS_SHARED, PSTATUS_OR);
466 if (!shared.empty())
467 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
468 "Prune the output before registering its sharing");
469 }
470 CHKERR m_field.remove_ents(remove, QUIET);
471 Range sets;
472 CHKERR mb.get_entities_by_type(0, MBENTITYSET, sets);
473 for (auto set : sets)
474 CHKERR mb.remove_entities(set, remove);
475 for (int dim = 3; dim >= 0; --dim) {
476 auto batch = remove.subset_by_dimension(dim);
477 if (!batch.empty())
478 // Output sharing is not registered yet. ParallelComm::delete_entities
479 // is collective and would also request deletion of remote copies.
480 CHKERR mb.delete_entities(batch);
481 }
482 entities = keep;
484}
485
488 int complete_mesh_rank) {
489 MoFEM::Interface &m_field = cOre;
491 auto &mb = m_field.get_moab();
492 auto *pc = ParallelComm::get_pcomm(&mb, MYPCOMM_INDEX);
493 const auto comm = m_field.get_comm();
494 CHKERR parentChildAgree(comm,
495 complete_mesh_rank < -1 ||
496 complete_mesh_rank >= m_field.get_comm_size()
498 : 0);
499 int first_rank, last_rank;
500 CHKERR MPI_Allreduce(&complete_mesh_rank, &first_rank, 1, MPI_INT, MPI_MIN,
501 comm);
502 CHKERR MPI_Allreduce(&complete_mesh_rank, &last_rank, 1, MPI_INT, MPI_MAX,
503 comm);
504 if (first_rank != last_rank)
505 SETERRQ(comm, MOFEM_INVALID_DATA, "Inconsistent complete-mesh rank");
506 std::vector<ParentChildCopy> local;
507 auto snapshot = [&]() {
509 std::set<ParentChildKey> keys;
510 for (auto entity : entities) {
511 ParentChildCopy row;
512 unsigned char status;
513 CHKERR pc->get_pstatus(entity, status);
514 if (status & PSTATUS_SHARED)
515 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
516 "Connectivity synchronisation requires unregistered output "
517 "sharing");
518 CHKERR parentChildKey(mb, mb.globalId_tag(), entity, row.key,
519 row.connectivity);
520 if (!keys.insert(row.key).second)
521 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
522 "Duplicate local entity identity");
523 if (mb.type_from_handle(entity) != MBVERTEX) {
525 CHKERR mb.get_connectivity(&entity, 1, vertices);
526 if (!subtract(vertices, entities).empty())
527 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA, "Missing cell closure");
528 }
529 row.parent = row.key;
530 row.handle = entity;
531 row.status = PSTATUS_INTERFACE | (status & PSTATUS_GHOST);
532 CHKERR mb.tag_get_data(pc->part_tag(), &entity, 1, &row.owner);
533 if (row.key[0] == MBTET && row.owner != m_field.get_comm_rank())
534 row.status = PSTATUS_GHOST;
535 local.push_back(row);
536 }
538 };
539 CHKERR parentChildAgree(comm, snapshot());
540 ParentChildRecords records;
541 CHKERR parentChildGather(comm, local, records);
542 for (const auto &[key, copies] : records) {
543 if (copies.size() > MAX_SHARING_PROCS ||
544 (key[0] == MBTET && complete_mesh_rank < 0 && copies.size() != 1))
546 "Invalid cell ownership or sharing count");
547 for (const auto &[rank, copy] : copies)
548 if (copy.owner != copies.begin()->second.owner)
550 "Inconsistent connectivity copies");
551 const int owner = copies.begin()->second.owner;
552 if (key[0] == MBTET && !copies.count(owner))
553 SETERRQ(comm, MOFEM_DATA_INCONSISTENCY, "Cell owner is not resident");
554 if (key[0] == MBTET && complete_mesh_rank >= 0 &&
555 !copies.count(complete_mesh_rank))
557 "The complete-mesh rank is missing an active cell");
558 }
559 CHKERR parentChildSharing(mb, *pc, records, records);
560 std::map<std::vector<int>, std::vector<EntityHandle>> interfaces;
561 for (const auto &[key, copies] : records) {
562 auto local_copy = copies.find(m_field.get_comm_rank());
563 if (local_copy == copies.end() || copies.size() == 1)
564 continue;
565 std::vector<int> ranks;
566 for (const auto &[rank, copy] : copies)
567 if (copies.size() > 2 || rank != m_field.get_comm_rank())
568 ranks.push_back(rank);
569 interfaces[ranks].push_back(local_copy->second.handle);
570 }
571 CHKERR pc->create_interface_sets(interfaces);
572 CHKERR parentChildSharing(mb, *pc, records, records);
573 Range old_sets;
574 auto part_tag = pc->part_tag();
575 CHKERR mb.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag, nullptr, 1,
576 old_sets);
577 for (auto set : old_sets) {
578 CHKERR mb.tag_delete_data(part_tag, &set, 1);
579 }
580 pc->partition_sets().clear();
581 EntityHandle part;
582 CHKERR pc->create_part(part);
583 Range part_entities = entities;
584 if (complete_mesh_rank >= 0) {
585 part_entities.clear();
586 for (auto cell : entities.subset_by_type(MBTET)) {
587 int owner;
588 CHKERR mb.tag_get_data(part_tag, &cell, 1, &owner);
589 if (owner == m_field.get_comm_rank())
590 part_entities.insert(cell);
591 }
592 for (int dim : {0, 1, 2}) {
594 CHKERR mb.get_adjacencies(part_entities.subset_by_type(MBTET), dim, false,
595 closure, moab::Interface::UNION);
596 part_entities.merge(closure);
597 }
598 }
599 CHKERR mb.add_entities(part, part_entities);
600 std::set<unsigned int> interface_procs;
601 CHKERR pc->get_interface_procs(interface_procs, true);
602 CHKERR pc->check_all_shared_handles();
604}
605
607 const BitRefLevel &parent_bit, const BitRefLevel &child_bit, int verb) {
609 MoFEM::Interface &m_field = cOre;
610 auto &mb = m_field.get_moab();
611 auto *pcomm = ParallelComm::get_pcomm(
612 &mb, m_field.get_basic_entity_data_ptr()->pcommID);
613 const auto comm = m_field.get_comm();
614 CHKERR parentChildAgree(comm, !pcomm || parent_bit.none() ||
615 child_bit.none() ||
616 (parent_bit & child_bit).any()
618 : 0);
619 const std::array<unsigned long long, 2> levels{parent_bit.to_ullong(),
620 child_bit.to_ullong()};
621 std::array<unsigned long long, 2> lo, hi;
622 CHKERR MPI_Allreduce(levels.data(), lo.data(), 2, MPI_UNSIGNED_LONG_LONG,
623 MPI_MIN, comm);
624 CHKERR MPI_Allreduce(levels.data(), hi.data(), 2, MPI_UNSIGNED_LONG_LONG,
625 MPI_MAX, comm);
626 CHKERR parentChildAgree(comm, lo != hi ? MOFEM_INVALID_DATA : 0);
627 auto *bits = m_field.getInterface<BitRefManager>();
628 Range source, children;
629 CHKERR bits->getEntitiesByRefLevel(parent_bit, BitRefLevel().set(), source);
630 CHKERR bits->getEntitiesByRefLevel(child_bit, BitRefLevel().set(), children);
631 source = subtract(source, source.subset_by_type(MBENTITYSET));
632 children = subtract(children, children.subset_by_type(MBENTITYSET));
633 std::vector<ParentChildCopy> local_source, local_children;
634 CHKERR parentChildAgree(
635 comm,
636 parentChildSnapshot(m_field, *pcomm, source, source, true, local_source));
637 CHKERR parentChildAgree(comm,
638 parentChildSnapshot(m_field, *pcomm, source, children,
639 false, local_children));
640 ParentChildRecords parent_records, child_records;
641 CHKERR parentChildGather(comm, local_source, parent_records);
642 CHKERR parentChildGather(comm, local_children, child_records);
643 CHKERR parentChildAgree(comm,
644 parentChildValidate(parent_records, child_records));
645
646 // Retained source vertices/edges already exist on their inherited ranks;
647 // publish their child membership without transmitting or reparenting them.
648 Range retained;
649 for (const auto &[key, copies] : child_records)
650 if (copies.begin()->second.parent == ParentChildKey{}) {
651 const auto local = parent_records.at(key).find(pcomm->rank());
652 if (local != parent_records.at(key).end())
653 retained.insert(local->second.handle);
654 }
655 CHKERR bits->setEntitiesBitRefLevel(retained, child_bit, verb);
656
657 // Vertices first: later MOAB batches refer to the remote vertices already
658 // registered, including those concurrently created in a different order.
659 for (int dim = 0; dim != 4; ++dim) {
660 CHKERR parentChildSharing(mb, *pcomm, parent_records, child_records);
661 std::vector<Range> outgoing(pcomm->size());
662 std::set<int> neighbors;
663 bool transfer = false;
664 for (const auto &[key, copies] : child_records) {
665 const auto &carrier = copies.begin()->second.parent;
666 if (carrier == ParentChildKey{} ||
667 moab::CN::Dimension(static_cast<EntityType>(key[0])) != dim)
668 continue;
669 const auto &destinations = parent_records.at(carrier);
670 const auto owner = destinations.begin()->second.owner;
671 const auto publisher =
672 copies.count(owner) ? owner : copies.begin()->first;
673 for (const auto &[destination, unused] : destinations)
674 if (!copies.count(destination)) {
675 transfer = true;
676 if (publisher == static_cast<int>(pcomm->rank())) {
677 outgoing[destination].insert(copies.at(publisher).handle);
678 neighbors.insert(destination);
679 } else if (destination == static_cast<int>(pcomm->rank())) {
680 neighbors.insert(publisher);
681 }
682 }
683 }
684 if (!transfer)
685 continue;
686 std::vector<unsigned int> peers(neighbors.begin(), neighbors.end());
687 std::vector<Range *> ranges;
688 for (auto peer : peers)
689 ranges.push_back(&outgoing[peer]);
690 std::vector<MPI_Request> entity_requests, handle_requests;
691 // Empty participants still enter MOAB; communicating peers are symmetric.
692 CHKERR parentChildAgree(
693 comm, pcomm->exchange_owned_mesh(peers, ranges, entity_requests,
694 handle_requests, false, true, true));
695 CHKERR bits->getEntitiesByRefLevel(child_bit, BitRefLevel().set(),
696 children);
697 children = subtract(children, children.subset_by_type(MBENTITYSET));
698 local_children.clear();
699 CHKERR parentChildAgree(comm, parentChildSnapshot(m_field, *pcomm, source,
700 children, false,
701 local_children));
702 CHKERR parentChildGather(comm, local_children, child_records);
703 }
704 CHKERR parentChildSharing(mb, *pcomm, parent_records, child_records);
705
706 const auto parent_tag = bits->get_th_RefParentHandle();
707 auto *ref_entities =
708 const_cast<RefEntity_multiIndex *>(m_field.get_ref_ents());
709 for (const auto &[key, copies] : child_records) {
710 const auto local = copies.find(pcomm->rank());
711 if (local == copies.end() || local->second.parent == ParentChildKey{})
712 continue;
713 const auto child = local->second.handle;
714 const auto parent =
715 parent_records.at(local->second.parent).at(pcomm->rank()).handle;
716 const auto indexed = ref_entities->find(child);
717 if (indexed == ref_entities->end()) {
718 CHKERR mb.tag_set_data(parent_tag, &child, 1, &parent);
719 } else if ((*indexed)->getParentEnt() != parent) {
720 if (!ref_entities->modify(indexed, RefEntity_change_parent(parent)))
722 "Could not update refinement parent index");
723 }
724 }
725 CHKERR bits->setBitRefLevel(children, child_bit, false, verb);
726 Range meshsets;
727 const auto part_tag = pcomm->part_tag();
728 CHKERR mb.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag, nullptr, 1,
729 meshsets);
730 // MOAB's owned-mesh receive may insert arrivals into the receiver's part.
731 // Restore membership from source carriers rather than receiver location.
732 const auto new_children = subtract(children, source);
733 for (auto partition : meshsets)
734 CHKERR mb.remove_entities(partition, new_children);
735 auto *meshsets_manager = m_field.getInterface<MeshsetsManager>();
736 for (auto it = meshsets_manager->getBegin(); it != meshsets_manager->getEnd();
737 ++it)
738 meshsets.insert(it->getMeshset());
739 for (auto meshset : meshsets)
740 CHKERR bits->updateMeshsetByEntitiesChildren(meshset, child_bit, meshset,
741 MBMAXTYPE, false, verb);
742 std::map<std::vector<int>, std::vector<EntityHandle>> interfaces;
743 for (auto child : children) {
744 if (source.find(child) != source.end())
745 continue;
746 std::array<int, MAX_SHARING_PROCS> procs;
747 std::array<EntityHandle, MAX_SHARING_PROCS> handles;
748 unsigned char status;
749 int count;
750 CHKERR pcomm->get_sharing_data(child, procs.data(), handles.data(), status,
751 count);
752 if (status & PSTATUS_INTERFACE) {
753 std::sort(procs.begin(), procs.begin() + count);
754 interfaces[std::vector<int>(procs.begin(), procs.begin() + count)]
755 .push_back(child);
756 }
757 }
758 // Reuse interface sets: MOAB's create_interface_sets always allocates new
759 // ones, and also normalises interface ownership to the lowest rank.
760 for (auto meshset : pcomm->interface_sets()) {
761 std::array<int, MAX_SHARING_PROCS> procs;
762 std::array<EntityHandle, MAX_SHARING_PROCS> handles;
763 unsigned char status;
764 int count;
765 CHKERR pcomm->get_sharing_data(meshset, procs.data(), handles.data(), status,
766 count);
767 std::sort(procs.begin(), procs.begin() + count);
768 const auto group = interfaces.find(
769 std::vector<int>(procs.begin(), procs.begin() + count));
770 if (group != interfaces.end()) {
771 CHKERR mb.add_entities(meshset, group->second.data(), group->second.size());
772 interfaces.erase(group);
773 }
774 }
775 CHKERR pcomm->create_interface_sets(interfaces);
776 CHKERR parentChildSharing(mb, *pcomm, parent_records, child_records);
777 std::set<unsigned int> interface_procs;
778 CHKERR pcomm->get_interface_procs(interface_procs, true);
779 CHKERR pcomm->check_all_shared_handles();
781}
782
784 Range &ents, std::map<int, Range> *received_ents, int verb) {
785 MoFEM::Interface &m_field = cOre;
786 ParallelComm *pcomm = ParallelComm::get_pcomm(
787 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
789
790 auto get_pstatus = [&](const auto ent) {
791 unsigned char pstatus;
792 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->pstatus_tag(), &ent,
793 1, &pstatus),
794 "can not get pstatus");
795 return pstatus;
796 };
797
798 auto get_sharing_procs = [&](const auto ent, const auto pstatus) {
799 std::vector<int> sharing_procs(MAX_SHARING_PROCS, -1);
800 if (pstatus & PSTATUS_MULTISHARED) {
801 // entity is multi shared
802 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(
803 pcomm->sharedps_tag(), &ent, 1, &sharing_procs[0]),
804 "can not ger sharing_procs_ptr");
805 } else if (pstatus & PSTATUS_SHARED) {
806 // shared
807 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->sharedp_tag(), &ent,
808 1, &sharing_procs[0]),
809 "can not get sharing proc");
810 }
811 return sharing_procs;
812 };
813
814 auto get_sharing_handles = [&](const auto ent, const auto pstatus) {
815 std::vector<EntityHandle> sharing_handles(MAX_SHARING_PROCS, 0);
816 if (pstatus & PSTATUS_MULTISHARED) {
817 // entity is multi shared
818 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(
819 pcomm->sharedhs_tag(), &ent, 1, &sharing_handles[0]),
820 "get shared handles");
821 } else if (pstatus & PSTATUS_SHARED) {
822 // shared
823 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->sharedh_tag(), &ent,
824 1, &sharing_handles[0]),
825 "get sharing handle");
826 }
827 return sharing_handles;
828 };
829
830 // make a buffer entities to send
831 std::vector<std::vector<EntityHandle>> sbuffer(m_field.get_comm_size());
832
833 for (auto ent : ents) {
834
835 auto pstatus = get_pstatus(ent);
836 if (pstatus) {
837 auto sharing_procs = get_sharing_procs(ent, pstatus);
838 auto sharing_handles = get_sharing_handles(ent, pstatus);
839
840 if (verb >= NOISY) {
841 MOFEM_LOG("SYNC", Sev::noisy) << "pstatus " << std::bitset<8>(pstatus);
842 }
843
844 for (int proc = 0; proc < MAX_SHARING_PROCS && -1 != sharing_procs[proc];
845 proc++) {
846 if (sharing_procs[proc] == -1)
847 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
848 "sharing processor not set");
849
850 if (sharing_procs[proc] == m_field.get_comm_rank())
851 continue;
852
853 const auto handle_on_sharing_proc = sharing_handles[proc];
854 // add entity to send, handle on the other side
855 sbuffer[sharing_procs[proc]].push_back(handle_on_sharing_proc);
856 if (verb >= NOISY) {
857 MOFEM_LOG_C("SYNC", Sev::noisy, "send %lu (%lu) to %d at %d\n", ent,
858 handle_on_sharing_proc, sharing_procs[proc],
859 m_field.get_comm_rank());
860 }
861
862 if (!(pstatus & PSTATUS_MULTISHARED))
863 break;
864 }
865 }
866 }
867 if (verb >= NOISY) {
868 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::noisy);
869 }
870
871 int nsends = 0; // number of messages to send
872 std::vector<int> sbuffer_lengths(
873 m_field.get_comm_size()); // length of the message to proc
874 const size_t block_size =
875 sizeof(EntityHandle) /
876 sizeof(int); // FIXME check if that works on given architecture!
877 for (int proc = 0; proc < m_field.get_comm_size(); proc++) {
878
879 if (!sbuffer[proc].empty()) {
880
881 sbuffer_lengths[proc] = sbuffer[proc].size() * block_size;
882 nsends++;
883
884 } else {
885
886 sbuffer_lengths[proc] = 0;
887 }
888 }
889
890 // Make sure it is a PETSc m_field.get_comm()
891 MPI_Comm comm;
892 CHKERR PetscCommDuplicate(m_field.get_comm(), &comm, NULL);
893
894 std::vector<MPI_Status> status(m_field.get_comm_size());
895
896 // Computes the number of messages a node expects to receive
897 int nrecvs; // number of messages received
898 CHKERR PetscGatherNumberOfMessages(comm, NULL, &sbuffer_lengths[0], &nrecvs);
899
900 // Computes info about messages that a MPI-node will receive, including
901 // (from-id,length) pairs for each message.
902 int *onodes; // list of node-ids from which messages are expected
903 int *olengths; // corresponding message lengths
904 CHKERR PetscGatherMessageLengths(comm, nsends, nrecvs, &sbuffer_lengths[0],
905 &onodes, &olengths);
906
907 // Gets a unique new tag from a PETSc communicator. All processors that share
908 // the communicator MUST call this routine EXACTLY the same number of times.
909 // This tag should only be used with the current objects communicator; do NOT
910 // use it with any other MPI communicator.
911 int tag;
912 CHKERR PetscCommGetNewTag(comm, &tag);
913
914 // Allocate a buffer sufficient to hold messages of size specified in
915 // olengths. And post Irecvs on these buffers using node info from onodes
916 int **rbuf; // must bee freed by user
917 MPI_Request *r_waits; // must bee freed by user
918 // rbuf has a pointers to messages. It has size of of nrecvs (number of
919 // messages) +1. In the first index a block is allocated,
920 // such that rbuf[i] = rbuf[i-1]+olengths[i-1].
921 CHKERR PetscPostIrecvInt(comm, tag, nrecvs, onodes, olengths, &rbuf,
922 &r_waits);
923
924 MPI_Request *s_waits; // status of sens messages
925 CHKERR PetscMalloc1(nsends, &s_waits);
926
927 // Send messages
928 for (int proc = 0, kk = 0; proc < m_field.get_comm_size(); proc++) {
929 if (!sbuffer_lengths[proc])
930 continue; // no message to send to this proc
931 CHKERR MPI_Isend(&(sbuffer[proc])[0], // buffer to send
932 sbuffer_lengths[proc], // message length
933 MPIU_INT, proc, // to proc
934 tag, comm, s_waits + kk);
935 kk++;
936 }
937
938 // Wait for received
939 if (nrecvs)
940 CHKERR MPI_Waitall(nrecvs, r_waits, &status[0]);
941
942 // Wait for send messages
943 if (nsends)
944 CHKERR MPI_Waitall(nsends, s_waits, &status[0]);
945
946 if (verb >= VERBOSE) {
947 MOFEM_LOG_C("SYNC", Sev::verbose, "Rank %d nb. before ents %zu\n",
948 m_field.get_comm_rank(), ents.size());
949 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
950 }
951
952 // synchronise range
953 for (int kk = 0; kk < nrecvs; kk++) {
954
955 int len = olengths[kk];
956 int *data_from_proc = rbuf[kk];
957
958 for (int ee = 0; ee < len;) {
959 EntityHandle ent;
960 bcopy(&data_from_proc[ee], &ent, sizeof(EntityHandle));
961 ents.insert(ent);
962
963 if (received_ents) {
964 (*received_ents)[onodes[kk]].insert(ent);
965 }
966
967 ee += block_size;
968
969 if (verb >= VERBOSE) {
970 MOFEM_LOG_C("SYNC", Sev::noisy, "received %lu from %d at %d\n", ent,
971 onodes[kk], m_field.get_comm_rank());
972 }
973 }
974 }
975 if (verb >= VERBOSE) {
976 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
977 }
978
979 if (verb >= VERBOSE) {
980 MOFEM_LOG_C("SYNC", Sev::verbose, "Rank %d nb. after ents %zu",
981 m_field.get_comm_rank(), ents.size());
982 MOFEM_LOG_SEVERITY_SYNC(m_field.get_comm(), Sev::verbose);
983 }
984
985 // Cleaning
986 CHKERR PetscFree(s_waits);
987 CHKERR PetscFree(rbuf[0]);
988 CHKERR PetscFree(rbuf);
989 CHKERR PetscFree(r_waits);
990 CHKERR PetscFree(onodes);
991 CHKERR PetscFree(olengths);
992 CHKERR PetscCommDestroy(&comm);
993
995}
996
998 return synchroniseEntities(ents, nullptr, verb);
999}
1000
1002 int verb) {
1003 MoFEM::Interface &m_field = cOre;
1005 EntityHandle idm = m_field.get_field_meshset(name);
1006 Range ents;
1007 CHKERR m_field.get_moab().get_entities_by_handle(idm, ents, false);
1008 CHKERR synchroniseEntities(ents, nullptr, verb);
1009 CHKERR m_field.get_moab().add_entities(idm, ents);
1011}
1012
1014 int verb) {
1015 MoFEM::Interface &m_field = cOre;
1016 ParallelComm *pcomm = ParallelComm::get_pcomm(
1017 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1018
1020
1021 Range shared = ents;
1022 CHKERR pcomm->filter_pstatus(shared, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1,
1023 nullptr);
1024 CHKERR pcomm->filter_pstatus(shared, PSTATUS_SHARED | PSTATUS_MULTISHARED,
1025 PSTATUS_OR, -1, nullptr);
1026
1027 auto th_RefParentHandle = cOre.get_th_RefParentHandle();
1028 auto th_RefBitLevel = cOre.get_th_RefBitLevel();
1029
1030 auto get_pstatus = [&](const auto ent) {
1031 unsigned char pstatus;
1032 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->pstatus_tag(), &ent,
1033 1, &pstatus),
1034 "can not get pstatus");
1035 return pstatus;
1036 };
1037
1038 auto get_sharing_procs = [&](const auto ent, const auto pstatus) {
1039 std::vector<int> sharing_procs(MAX_SHARING_PROCS, -1);
1040 if (pstatus & PSTATUS_MULTISHARED) {
1041 // entity is multi shared
1042 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(
1043 pcomm->sharedps_tag(), &ent, 1, &sharing_procs[0]),
1044 "can not ger sharing_procs_ptr");
1045 } else if (pstatus & PSTATUS_SHARED) {
1046 // shared
1047 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->sharedp_tag(), &ent,
1048 1, &sharing_procs[0]),
1049 "can not get sharing proc");
1050 }
1051 return sharing_procs;
1052 };
1053
1054 auto get_sharing_handles = [&](const auto ent, const auto pstatus) {
1055 std::vector<EntityHandle> sharing_handles(MAX_SHARING_PROCS, 0);
1056 if (pstatus & PSTATUS_MULTISHARED) {
1057 // entity is multi shared
1058 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(
1059 pcomm->sharedhs_tag(), &ent, 1, &sharing_handles[0]),
1060 "get shared handles");
1061 } else if (pstatus & PSTATUS_SHARED) {
1062 // shared
1063 CHK_MOAB_THROW(m_field.get_moab().tag_get_data(pcomm->sharedh_tag(), &ent,
1064 1, &sharing_handles[0]),
1065 "get sharing handle");
1066 }
1067 return sharing_handles;
1068 };
1069
1070 auto get_parent_and_bit = [&](const auto ent) {
1071 EntityHandle parent;
1073 m_field.get_moab().tag_get_data(th_RefParentHandle, &ent, 1, &parent),
1074 "get parent");
1077 m_field.get_moab().tag_get_data(th_RefBitLevel, &ent, 1, &bit),
1078 "get parent");
1079 return std::make_pair(parent, bit);
1080 };
1081
1082 auto set_parent = [&](const auto ent, const auto parent) {
1083 return m_field.get_moab().tag_set_data(th_RefParentHandle, &ent, 1,
1084 &parent);
1085 };
1086
1087 auto set_bit = [&](const auto ent, const auto bit) {
1088 return m_field.get_moab().tag_set_data(th_RefBitLevel, &ent, 1, &bit);
1089 };
1090
1091 // make a buffer
1092 std::vector<std::vector<unsigned long long>> sbuffer(m_field.get_comm_size());
1093
1094 for (auto ent : shared) {
1095
1096 auto pstatus = get_pstatus(ent);
1097 auto sharing_procs = get_sharing_procs(ent, pstatus);
1098 auto sharing_handles = get_sharing_handles(ent, pstatus);
1099 auto [parent, bit] = get_parent_and_bit(ent);
1100
1101 if (verb >= NOISY)
1102 MOFEM_LOG("SYNC", Sev::noisy) << "pstatus " << std::bitset<8>(pstatus);
1103
1104 if (parent) {
1105 auto pstatus_parent = get_pstatus(parent);
1106 auto sharing_procs_parent = get_sharing_procs(parent, pstatus_parent);
1107 auto sharing_handles_parent = get_sharing_handles(parent, pstatus_parent);
1108
1109 for (int proc = 0; proc < MAX_SHARING_PROCS && -1 != sharing_procs[proc];
1110 proc++) {
1111 if (sharing_procs[proc] == -1)
1112 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
1113 "sharing processor not set");
1114
1115 if (sharing_procs[proc] != m_field.get_comm_rank()) {
1116
1117 auto it = std::find(sharing_procs_parent.begin(),
1118 sharing_procs_parent.end(), sharing_procs[proc]);
1119 if (it == sharing_procs_parent.end()) {
1120 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1121 "Sharing proc for parent entity can not be found proc = %u",
1122 sharing_procs[proc]);
1123 }
1124
1125 auto handle_on_sharing_proc = sharing_handles[proc];
1126 auto parent_handle_on_sharing_proc =
1127 sharing_handles_parent[std::distance(sharing_procs_parent.begin(),
1128 it)];
1129 sbuffer[sharing_procs[proc]].push_back(handle_on_sharing_proc);
1130 sbuffer[sharing_procs[proc]].push_back(parent_handle_on_sharing_proc);
1131 try {
1132 sbuffer[sharing_procs[proc]].push_back(bit.to_ullong());
1133 } catch (std::exception &ex) {
1134 MOFEM_LOG("SELF", Sev::warning) << ex.what();
1135 MOFEM_LOG("SELF", Sev::warning)
1136 << "On " << ent << " "
1137 << moab::CN::EntityTypeName(type_from_handle(ent));
1138 MOFEM_LOG("SELF", Sev::warning) << "For bit ref " << bit;
1139 }
1140 if (verb >= NOISY)
1141 MOFEM_LOG_C("SYNC", Sev::noisy, "send %lu (%lu) to %d at %d\n", ent,
1142 handle_on_sharing_proc, sharing_procs[proc],
1143 m_field.get_comm_rank());
1144
1145 if (!(pstatus & PSTATUS_MULTISHARED))
1146 break;
1147 }
1148 }
1149 } else {
1150 for (int proc = 0; proc < MAX_SHARING_PROCS && -1 != sharing_procs[proc];
1151 proc++) {
1152 if (sharing_procs[proc] == -1)
1153 SETERRQ(PETSC_COMM_SELF, MOFEM_IMPOSSIBLE_CASE,
1154 "sharing processor not set");
1155
1156 if (sharing_procs[proc] != m_field.get_comm_rank()) {
1157 auto handle_on_sharing_proc = sharing_handles[proc];
1158 sbuffer[sharing_procs[proc]].push_back(handle_on_sharing_proc);
1159 sbuffer[sharing_procs[proc]].push_back(parent);
1160
1161 try {
1162 sbuffer[sharing_procs[proc]].push_back(bit.to_ullong());
1163 } catch (std::exception &ex) {
1164 MOFEM_LOG("SELF", Sev::warning) << ex.what();
1165 MOFEM_LOG("SELF", Sev::warning)
1166 << "On " << ent << " "
1167 << moab::CN::EntityTypeName(type_from_handle(ent));
1168 MOFEM_LOG("SELF", Sev::warning) << "For bit ref " << bit;
1169 }
1170
1171 if (verb >= NOISY)
1172 MOFEM_LOG_C("SYNC", Sev::noisy, "send %lu (%lu) to %d at %d\n", ent,
1173 handle_on_sharing_proc, sharing_procs[proc],
1174 m_field.get_comm_rank());
1175
1176 if (!(pstatus & PSTATUS_MULTISHARED))
1177 break;
1178 }
1179 }
1180 }
1181 }
1182
1183 int nsends = 0; // number of messages to send
1184 std::vector<int> sbuffer_lengths(
1185 m_field.get_comm_size()); // length of the message to proc
1186
1187 const size_t block_size = sizeof(unsigned long long) / sizeof(int);
1188 for (int proc = 0; proc < m_field.get_comm_size(); proc++) {
1189
1190 if (!sbuffer[proc].empty()) {
1191
1192 sbuffer_lengths[proc] = sbuffer[proc].size() * block_size;
1193 nsends++;
1194
1195 } else {
1196
1197 sbuffer_lengths[proc] = 0;
1198 }
1199 }
1200
1201 // Make sure it is a PETSc m_field.get_comm()
1202 MPI_Comm comm;
1203 CHKERR PetscCommDuplicate(m_field.get_comm(), &comm, NULL);
1204
1205 std::vector<MPI_Status> status(m_field.get_comm_size());
1206
1207 // Computes the number of messages a node expects to receive
1208 int nrecvs; // number of messages received
1209 CHKERR PetscGatherNumberOfMessages(comm, NULL, &sbuffer_lengths[0], &nrecvs);
1210
1211 // Computes info about messages that a MPI-node will receive, including
1212 // (from-id,length) pairs for each message.
1213 int *onodes; // list of node-ids from which messages are expected
1214 int *olengths; // corresponding message lengths
1215 CHKERR PetscGatherMessageLengths(comm, nsends, nrecvs, &sbuffer_lengths[0],
1216 &onodes, &olengths);
1217
1218 // Gets a unique new tag from a PETSc communicator. All processors that share
1219 // the communicator MUST call this routine EXACTLY the same number of times.
1220 // This tag should only be used with the current objects communicator; do NOT
1221 // use it with any other MPI communicator.
1222 int tag;
1223 CHKERR PetscCommGetNewTag(comm, &tag);
1224
1225 // Allocate a buffer sufficient to hold messages of size specified in
1226 // olengths. And post Irecvs on these buffers using node info from onodes
1227 int **rbuf; // must bee freed by user
1228 MPI_Request *r_waits; // must bee freed by user
1229 // rbuf has a pointers to messages. It has size of of nrecvs (number of
1230 // messages) +1. In the first index a block is allocated,
1231 // such that rbuf[i] = rbuf[i-1]+olengths[i-1].
1232 CHKERR PetscPostIrecvInt(comm, tag, nrecvs, onodes, olengths, &rbuf,
1233 &r_waits);
1234
1235 MPI_Request *s_waits; // status of sens messages
1236 CHKERR PetscMalloc1(nsends, &s_waits);
1237
1238 // Send messages
1239 for (int proc = 0, kk = 0; proc < m_field.get_comm_size(); proc++) {
1240 if (!sbuffer_lengths[proc])
1241 continue; // no message to send to this proc
1242 CHKERR MPI_Isend(&(sbuffer[proc])[0], // buffer to send
1243 sbuffer_lengths[proc], // message length
1244 MPIU_INT, proc, // to proc
1245 tag, comm, s_waits + kk);
1246 kk++;
1247 }
1248
1249 // Wait for received
1250 if (nrecvs)
1251 CHKERR MPI_Waitall(nrecvs, r_waits, &status[0]);
1252
1253 // Wait for send messages
1254 if (nsends)
1255 CHKERR MPI_Waitall(nsends, s_waits, &status[0]);
1256
1257 if (verb >= VERBOSE) {
1258 MOFEM_LOG_C("SYNC", Sev::verbose,
1259 "Rank %d nb. shared to synchronise parents ents %zu\n",
1260 m_field.get_comm_rank(), shared.size());
1261 }
1262
1263 // synchronise range
1264 for (int kk = 0; kk < nrecvs; kk++) {
1265
1266 int len = olengths[kk];
1267 int *data_from_proc = rbuf[kk];
1268
1269 for (int ee = 0; ee < len;) {
1270 EntityHandle ent;
1271 EntityHandle parent;
1272 unsigned long long uulong_bit;
1273 bcopy(&data_from_proc[ee], &ent, sizeof(EntityHandle));
1274 ee += block_size;
1275 bcopy(&data_from_proc[ee], &parent, sizeof(EntityHandle));
1276 ee += block_size;
1277 bcopy(&data_from_proc[ee], &uulong_bit, sizeof(unsigned long long));
1278 ee += block_size;
1279
1280 CHKERR set_parent(ent, parent);
1281 CHKERR set_bit(ent, BitRefLevel(uulong_bit));
1282
1283 if (verb >= VERBOSE) {
1284 MOFEM_LOG_C("SYNC", Sev::noisy, "received %lu (%lu) from %d at %d\n",
1285 ent, parent, onodes[kk], m_field.get_comm_rank());
1286 MOFEM_LOG("SYNC", Sev::noisy) << "Bit " << BitRefLevel(uulong_bit);
1287 }
1288 }
1289 }
1290
1291 // Cleaning
1292 CHKERR PetscFree(s_waits);
1293 CHKERR PetscFree(rbuf[0]);
1294 CHKERR PetscFree(rbuf);
1295 CHKERR PetscFree(r_waits);
1296 CHKERR PetscFree(onodes);
1297 CHKERR PetscFree(olengths);
1298 CHKERR PetscCommDestroy(&comm);
1299
1300 if (verb >= VERBOSE)
1302
1304}
1305
1307 const Problem *problem_ptr, const std::string &fe_name, int verb) {
1308 MoFEM::Interface &m_field = cOre;
1310 ParallelComm *pcomm = ParallelComm::get_pcomm(
1311 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1312 std::vector<int> shprocs(MAX_SHARING_PROCS, 0);
1313 std::vector<EntityHandle> shhandles(MAX_SHARING_PROCS, 0);
1314 Range ents;
1315 Tag th_gid = m_field.get_moab().globalId_tag();
1316 PetscLayout layout;
1317 CHKERR problem_ptr->getNumberOfElementsByNameAndPart(m_field.get_comm(),
1318 fe_name, &layout);
1319 int gid, last_gid;
1320 CHKERR PetscLayoutGetRange(layout, &gid, &last_gid);
1321 CHKERR PetscLayoutDestroy(&layout);
1322
1323 const FiniteElement_multiIndex *fes_ptr;
1324 CHKERR m_field.get_finite_elements(&fes_ptr);
1325
1326 auto fe_miit = fes_ptr->get<FiniteElement_name_mi_tag>().find(fe_name);
1327 if (fe_miit != fes_ptr->get<FiniteElement_name_mi_tag>().end()) {
1328 auto fit =
1329 problem_ptr->numeredFiniteElementsPtr->get<Unique_mi_tag>().lower_bound(
1331 0, (*fe_miit)->getFEUId()));
1332 auto hi_fe_it =
1333 problem_ptr->numeredFiniteElementsPtr->get<Unique_mi_tag>().upper_bound(
1335 get_id_for_max_type<MBENTITYSET>(), (*fe_miit)->getFEUId()));
1336 for (; fit != hi_fe_it; ++fit) {
1337
1338 auto ent = (*fit)->getEnt();
1339 auto part = (*fit)->getPart();
1340
1341 ents.insert(ent);
1342 CHKERR m_field.get_moab().tag_set_data(pcomm->part_tag(), &ent, 1, &part);
1343 if (part == pcomm->rank()) {
1344 CHKERR m_field.get_moab().tag_set_data(th_gid, &ent, 1, &gid);
1345 gid++;
1346 }
1347 shprocs.clear();
1348 shhandles.clear();
1349
1350 if (pcomm->size() > 1) {
1351
1352 unsigned char pstatus = 0;
1353 if (pcomm->rank() != part) {
1354 pstatus = PSTATUS_NOT_OWNED;
1355 pstatus |= PSTATUS_GHOST;
1356 }
1357
1358 if (pcomm->size() > 2) {
1359 pstatus |= PSTATUS_SHARED;
1360 pstatus |= PSTATUS_MULTISHARED;
1361 } else {
1362 pstatus |= PSTATUS_SHARED;
1363 }
1364
1365 size_t rrr = 0;
1366 for (size_t rr = 0; rr < pcomm->size(); ++rr) {
1367 if (rr != pcomm->rank()) {
1368 shhandles[rrr] = ent;
1369 shprocs[rrr] = rr;
1370 ++rrr;
1371 }
1372 }
1373 for (; rrr != pcomm->size(); ++rrr)
1374 shprocs[rrr] = -1;
1375
1376 if (pstatus & PSTATUS_SHARED) {
1377 CHKERR m_field.get_moab().tag_set_data(pcomm->sharedp_tag(), &ent, 1,
1378 &shprocs[0]);
1379 CHKERR m_field.get_moab().tag_set_data(pcomm->sharedh_tag(), &ent, 1,
1380 &shhandles[0]);
1381 }
1382
1383 if (pstatus & PSTATUS_MULTISHARED) {
1384 CHKERR m_field.get_moab().tag_set_data(pcomm->sharedps_tag(), &ent, 1,
1385 &shprocs[0]);
1386 CHKERR m_field.get_moab().tag_set_data(pcomm->sharedhs_tag(), &ent, 1,
1387 &shhandles[0]);
1388 }
1389 CHKERR m_field.get_moab().tag_set_data(pcomm->pstatus_tag(), &ent, 1,
1390 &pstatus);
1391 }
1392 }
1393 }
1394
1395 CHKERR pcomm->exchange_tags(th_gid, ents);
1397}
1398
1400 const std::string name, const std::string &fe_name, int verb) {
1401 MoFEM::Interface &m_field = cOre;
1403 const Problem *problem_ptr;
1404 CHKERR m_field.get_problem(name, &problem_ptr);
1405 CHKERR resolveSharedFiniteElements(problem_ptr, fe_name, verb);
1407}
1408
1410CommInterface::makeEntitiesMultishared(const EntityHandle *entities,
1411 const int num_entities,
1412 const int owner_proc, int verb) {
1413 MoFEM::Interface &m_field = cOre;
1415
1416 if (m_field.get_comm_size() > 1) {
1417
1418 ParallelComm *pcomm = ParallelComm::get_pcomm(
1419 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1420
1421 Range all_ents_range;
1422 all_ents_range.insert_list(entities, entities + num_entities);
1423
1424 auto get_tag = [&]() {
1425 const int negone = -1;
1426 Tag th;
1427 m_field.get_moab().tag_get_handle("TMP_GLOBAL_ID_TAG_NAME", 1,
1428 MB_TYPE_INTEGER, th,
1429 MB_TAG_CREAT | MB_TAG_SPARSE, &negone);
1430 return th;
1431 };
1432
1433 auto delete_tag = [&](auto &&th_gid) {
1435 CHKERR m_field.get_moab().tag_delete(th_gid);
1437 };
1438
1439 auto resolve_shared_ents = [&](auto &&th_gid, auto &all_ents_range) {
1440 auto set_gid = [&](auto &th_gid) {
1441 std::vector<int> gids(num_entities);
1442 for (size_t g = 0; g != all_ents_range.size(); ++g)
1443 gids[g] = g + 1;
1444 CHKERR m_field.get_moab().tag_set_data(th_gid, all_ents_range,
1445 &*gids.begin());
1446
1447 return &th_gid;
1448 };
1449
1450 auto get_skin_ents = [&](auto &all_ents_range) {
1451 std::array<Range, 4> proc_ents_skin;
1452 proc_ents_skin[3] = all_ents_range.subset_by_dimension(3);
1453 proc_ents_skin[2] = all_ents_range.subset_by_dimension(2);
1454 proc_ents_skin[1] = all_ents_range.subset_by_dimension(1);
1455 proc_ents_skin[0] = all_ents_range.subset_by_dimension(0);
1456 return proc_ents_skin;
1457 };
1458
1459 auto resolve_dim = [&](auto &all_ents_range) {
1460 for (int resolve_dim = 3; resolve_dim >= 0; --resolve_dim) {
1461 if (all_ents_range.num_of_dimension(resolve_dim))
1462 return resolve_dim;
1463 }
1464 return -1;
1465 };
1466
1467 auto get_proc_ent = [&](auto &all_ents_range) {
1468 Range proc_ent;
1469 if (m_field.get_comm_rank() == owner_proc)
1470 proc_ent = all_ents_range;
1471 return proc_ent;
1472 };
1473
1474 auto resolve_shared_ents = [&](auto &&proc_ents, auto &&skin_ents) {
1475 return pcomm->resolve_shared_ents(
1476 0, proc_ents, resolve_dim(all_ents_range),
1477 resolve_dim(all_ents_range), skin_ents.data(), set_gid(th_gid));
1478 };
1479
1480 CHKERR resolve_shared_ents(get_proc_ent(all_ents_range),
1481 get_skin_ents(all_ents_range));
1482
1483 return th_gid;
1484 };
1485
1486 CHKERR delete_tag(resolve_shared_ents(get_tag(), all_ents_range));
1487
1488 if (verb >= NOISY) {
1489
1490 auto print_owner = [&](const EntityHandle e) {
1492 int moab_owner_proc;
1493 EntityHandle moab_owner_handle;
1494 CHKERR pcomm->get_owner_handle(e, moab_owner_proc, moab_owner_handle);
1495
1496 unsigned char pstatus = 0;
1497
1498 CHKERR m_field.get_moab().tag_get_data(pcomm->pstatus_tag(), &e, 1,
1499 &pstatus);
1500
1501 std::vector<int> shprocs(MAX_SHARING_PROCS, 0);
1502 std::vector<EntityHandle> shhandles(MAX_SHARING_PROCS, 0);
1503
1504 CHKERR m_field.get_moab().tag_get_data(pcomm->sharedp_tag(), &e, 1,
1505 &shprocs[0]);
1506 CHKERR m_field.get_moab().tag_get_data(pcomm->sharedh_tag(), &e, 1,
1507 &shhandles[0]);
1508 if (pstatus & PSTATUS_MULTISHARED) {
1509 CHKERR m_field.get_moab().tag_get_data(pcomm->sharedps_tag(), &e, 1,
1510 &shprocs[0]);
1511 CHKERR m_field.get_moab().tag_get_data(pcomm->sharedhs_tag(), &e, 1,
1512 &shhandles[0]);
1513 }
1514
1515 std::ostringstream ss;
1516
1517 ss << "Rank " << m_field.get_comm_rank() << " ";
1518 if (!(pstatus & PSTATUS_NOT_OWNED))
1519 ss << "OWNER ";
1520 if (pstatus & PSTATUS_SHARED)
1521 ss << "PSTATUS_SHARED ";
1522 if (pstatus & PSTATUS_MULTISHARED)
1523 ss << "PSTATUS_MULTISHARED ";
1524
1525 ss << "owner " << moab_owner_proc << " (" << owner_proc << ") ";
1526
1527 ss << "shprocs: ";
1528 for (size_t r = 0; r != m_field.get_comm_size() + 1; ++r)
1529 ss << shprocs[r] << " ";
1530
1531 ss << "shhandles: ";
1532 for (size_t r = 0; r != m_field.get_comm_size() + 1; ++r)
1533 ss << shhandles[r] << " ";
1534
1535 ss << std::endl;
1536 MOFEM_LOG("SYNC", Sev::noisy) << ss.str();
1538
1540 };
1541
1542 for (auto e : all_ents_range)
1543 CHKERR print_owner(e);
1544 }
1545 }
1546
1548}
1549
1551 const int owner_proc,
1552 int verb) {
1553 MoFEM::Interface &m_field = cOre;
1555 if (m_field.get_comm_size() > 1) {
1556 const int num_ents = entities.size();
1557 std::vector<EntityHandle> vec_ents(num_ents);
1558 std::copy(entities.begin(), entities.end(), vec_ents.begin());
1559 CHKERR makeEntitiesMultishared(&*vec_ents.begin(), num_ents, owner_proc,
1560 verb);
1561 }
1563}
1564
1567 const int owner_proc, int verb) {
1568 MoFEM::Interface &m_field = cOre;
1570 if (m_field.get_comm_size() > 1) {
1571 EntityHandle field_meshset = m_field.get_field_meshset(field_name);
1572 std::vector<EntityHandle> field_ents;
1573 CHKERR m_field.get_moab().get_entities_by_handle(field_meshset, field_ents,
1574 true);
1575 CHKERR makeEntitiesMultishared(&*field_ents.begin(), field_ents.size(),
1576 owner_proc, verb);
1577 }
1579}
1580
1582 int verb) {
1583 MoFEM::Interface &m_field = cOre;
1585 if (m_field.get_comm_size() > 1) {
1586
1587 Range exchange_ents_data_verts, exchange_ents_data;
1588
1589 auto *field_ents = m_field.get_field_ents();
1590 auto field_bit_number = m_field.get_field_bit_number(field_name);
1591 auto lo = field_ents->get<Unique_mi_tag>().lower_bound(
1592 FieldEntity::getLoBitNumberUId(field_bit_number));
1593 auto hi = field_ents->get<Unique_mi_tag>().lower_bound(
1594 FieldEntity::getHiBitNumberUId(field_bit_number));
1595
1596 for (auto it = lo; it != hi; ++it)
1597 if (
1598
1599 ((*it)->getPStatus()) &&
1600
1601 (*it)->getNbDofsOnEnt()
1602
1603 ) {
1604 if ((*it)->getEntType() == MBVERTEX)
1605 exchange_ents_data_verts.insert((*it)->getEnt());
1606 else
1607 exchange_ents_data.insert((*it)->getEnt());
1608 }
1609
1610 auto field_ptr = m_field.get_field_structure(field_name);
1611 ParallelComm *pcomm = ParallelComm::get_pcomm(
1612 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1613
1614 auto exchange = [&](const Range &ents, Tag th) {
1616 if (!ents.empty()) {
1617 std::vector<Tag> tags;
1618 tags.push_back(th);
1619 CHKERR pcomm->exchange_tags(tags, tags, ents);
1620 }
1622 };
1623
1624 CHKERR exchange(exchange_ents_data_verts, field_ptr->th_FieldDataVerts);
1625 CHKERR exchange(exchange_ents_data, field_ptr->th_FieldData);
1626 }
1628}
1629
1631 const Range &ents, const int dim, const int adj_dim, const int n_parts,
1632 Tag *th_vertex_weights, Tag *th_edge_weights, Tag *th_part_weights,
1633 int verb, const bool debug, const bool preserve_vertex_ids) {
1634 MoFEM::Interface &m_field = cOre;
1636
1637 // get layout
1638 int rstart, rend, nb_elems;
1639 {
1640 PetscLayout layout;
1641 CHKERR PetscLayoutCreate(m_field.get_comm(), &layout);
1642 CHKERR PetscLayoutSetBlockSize(layout, 1);
1643 CHKERR PetscLayoutSetSize(layout, ents.size());
1644 CHKERR PetscLayoutSetUp(layout);
1645 CHKERR PetscLayoutGetSize(layout, &nb_elems);
1646 CHKERR PetscLayoutGetRange(layout, &rstart, &rend);
1647 CHKERR PetscLayoutDestroy(&layout);
1648 if (verb >= VERBOSE) {
1649 MOFEM_LOG("SYNC", Sev::inform)
1650 << "Finite elements in problem: row lower " << rstart << " row upper "
1651 << rend << " nb. elems " << nb_elems << " ( " << ents.size() << " )";
1653 }
1654 }
1655
1656 std::vector<EntityHandle> weight_ents;
1657 weight_ents.reserve(rend - rstart + 1);
1658
1659 struct AdjBridge {
1660 EntityHandle ent;
1661 std::vector<int> adj;
1662 AdjBridge(const EntityHandle ent, std::vector<int> &adj)
1663 : ent(ent), adj(adj) {}
1664 };
1665
1666 typedef multi_index_container<
1667 AdjBridge,
1668 indexed_by<
1669
1670 hashed_unique<member<AdjBridge, EntityHandle, &AdjBridge::ent>>
1671
1672 >>
1673 AdjBridgeMap;
1674
1675 auto get_it = [&](auto i) {
1676 auto it = ents.begin();
1677 for (; i > 0; --i) {
1678 if (it == ents.end())
1679 break;
1680 ++it;
1681 }
1682 return it;
1683 };
1684
1685 Range proc_ents;
1686 proc_ents.insert(get_it(rstart), get_it(rend));
1687 if (proc_ents.size() != rend - rstart)
1688 SETERRQ(PETSC_COMM_WORLD, MOFEM_DATA_INCONSISTENCY,
1689 "Wrong number of elements in range %zu != %zu", proc_ents.size(),
1690 static_cast<size_t>(rend - rstart));
1691
1692 Range all_dim_ents;
1693 CHKERR m_field.get_moab().get_adjacencies(
1694 proc_ents, adj_dim, true, all_dim_ents, moab::Interface::UNION);
1695
1696 AdjBridgeMap adj_bridge_map;
1697 auto hint = adj_bridge_map.begin();
1698 std::vector<int> adj;
1699 for (auto ent : all_dim_ents) {
1700 Range adj_ents;
1701 CHKERR m_field.get_moab().get_adjacencies(&ent, 1, dim, false, adj_ents);
1702 adj_ents = intersect(adj_ents, ents);
1703 adj.clear();
1704 adj.reserve(adj_ents.size());
1705 for (auto a : adj_ents)
1706 adj.emplace_back(ents.index(a));
1707 hint = adj_bridge_map.emplace_hint(hint, ent, adj);
1708 }
1709
1710 int *_i;
1711 int *_j;
1712 {
1713 const int nb_loc_elements = rend - rstart;
1714 std::vector<int> i(nb_loc_elements + 1, 0), j;
1715 {
1716 std::vector<int> row_adj;
1717 Range::iterator fe_it;
1718 int ii, jj;
1719 size_t max_row_size;
1720 for (fe_it = proc_ents.begin(), ii = rstart, jj = 0, max_row_size = 0;
1721 fe_it != proc_ents.end(); ++fe_it, ++ii) {
1722
1723 if (type_from_handle(*fe_it) == MBENTITYSET) {
1724 SETERRQ(PETSC_COMM_SELF, MOFEM_NOT_IMPLEMENTED,
1725 "not yet implemented, don't know what to do for meshset "
1726 "element");
1727 } else {
1728
1729 Range dim_ents;
1730 CHKERR m_field.get_moab().get_adjacencies(&*fe_it, 1, adj_dim, false,
1731 dim_ents);
1732 dim_ents = intersect(dim_ents, all_dim_ents);
1733
1734 row_adj.clear();
1735 for (auto e : dim_ents) {
1736 auto adj_it = adj_bridge_map.find(e);
1737 if (adj_it != adj_bridge_map.end()) {
1738
1739 for (const auto idx : adj_it->adj)
1740 row_adj.push_back(idx);
1741
1742 } else
1743 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
1744 "Entity not found");
1745 }
1746
1747 std::sort(row_adj.begin(), row_adj.end());
1748 auto end = std::unique(row_adj.begin(), row_adj.end());
1749
1750 size_t row_size = std::distance(row_adj.begin(), end);
1751 max_row_size = std::max(max_row_size, row_size);
1752 if (j.capacity() < (nb_loc_elements - jj) * max_row_size)
1753 j.reserve(nb_loc_elements * max_row_size);
1754
1755 i[jj] = j.size();
1756 auto diag = ents.index(*fe_it);
1757 for (auto it = row_adj.begin(); it != end; ++it)
1758 if (*it != diag)
1759 j.push_back(*it);
1760 }
1761
1762 ++jj;
1763
1764 if (th_vertex_weights != NULL)
1765 weight_ents.push_back(*fe_it);
1766 }
1767
1768 i[jj] = j.size();
1769 }
1770
1771 CHKERR PetscMalloc(i.size() * sizeof(int), &_i);
1772 CHKERR PetscMalloc(j.size() * sizeof(int), &_j);
1773 copy(i.begin(), i.end(), _i);
1774 copy(j.begin(), j.end(), _j);
1775 }
1776
1777 // get weights
1778 int *vertex_weights = NULL;
1779 if (th_vertex_weights != NULL) {
1780 CHKERR PetscMalloc(weight_ents.size() * sizeof(int), &vertex_weights);
1781 CHKERR m_field.get_moab().tag_get_data(*th_vertex_weights,
1782 &*weight_ents.begin(),
1783 weight_ents.size(), vertex_weights);
1784 }
1785
1786 {
1787 Mat Adj;
1788 // Adjacency matrix used to partition problems, f.e. METIS
1789 CHKERR MatCreateMPIAdj(m_field.get_comm(), rend - rstart, nb_elems, _i, _j,
1790 PETSC_NULLPTR, &Adj);
1791 CHKERR MatSetOption(Adj, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE);
1792
1793 if (debug) {
1794 Mat A;
1795 CHKERR MatConvert(Adj, MATMPIAIJ, MAT_INITIAL_MATRIX, &A);
1796 CHKERR MatView(A, PETSC_VIEWER_DRAW_WORLD);
1797 std::string wait;
1798 std::cin >> wait;
1799 CHKERR MatDestroy(&A);
1800 }
1801
1802 // run pets to do partitioning
1803 MOFEM_LOG("WORLD", Sev::verbose) << "Start";
1804
1805 MatPartitioning part;
1806 IS is;
1807 CHKERR MatPartitioningCreate(m_field.get_comm(), &part);
1808
1809 CHKERR MatPartitioningSetAdjacency(part, Adj);
1810 CHKERR MatPartitioningSetFromOptions(part);
1811 CHKERR MatPartitioningSetNParts(part, n_parts);
1812 if (th_vertex_weights != NULL) {
1813 CHKERR MatPartitioningSetVertexWeights(part, vertex_weights);
1814 }
1815 CHKERR MatPartitioningApply(part, &is);
1816
1817 MOFEM_LOG("WORLD", Sev::verbose) << "End";
1818
1819 // gather
1820 IS is_gather, is_num, is_gather_num;
1821 CHKERR ISAllGather(is, &is_gather);
1822 CHKERR ISPartitioningToNumbering(is, &is_num);
1823 CHKERR ISAllGather(is_num, &is_gather_num);
1824
1825 const int *part_number, *gids;
1826 CHKERR ISGetIndices(is_gather, &part_number);
1827 CHKERR ISGetIndices(is_gather_num, &gids);
1828
1829 // set partition tag and gid tag to entities
1830 ParallelComm *pcomm = ParallelComm::get_pcomm(
1831 &m_field.get_moab(), m_field.get_basic_entity_data_ptr()->pcommID);
1832 Tag part_tag = pcomm->part_tag();
1833 CHKERR m_field.get_moab().tag_set_data(part_tag, ents, part_number);
1834 Tag gid_tag = m_field.get_moab().globalId_tag();
1835
1836 std::map<int, Range> parts_ents;
1837 {
1838 // get entities on each part
1839 Range::iterator eit = ents.begin();
1840 for (int ii = 0; eit != ents.end(); eit++, ii++) {
1841 parts_ents[part_number[ii]].insert(*eit);
1842 }
1843 Range tagged_sets;
1844 CHKERR m_field.get_moab().get_entities_by_type_and_tag(
1845 0, MBENTITYSET, &part_tag, NULL, 1, tagged_sets,
1846 moab::Interface::UNION);
1847 if (!tagged_sets.empty())
1848 CHKERR m_field.get_moab().tag_delete_data(part_tag, tagged_sets);
1849
1850 if (n_parts > (int)tagged_sets.size()) {
1851 // too few partition sets - create missing ones
1852 int num_new = n_parts - tagged_sets.size();
1853 for (int i = 0; i < num_new; i++) {
1854 EntityHandle new_set;
1855 CHKERR m_field.get_moab().create_meshset(MESHSET_SET, new_set);
1856 tagged_sets.insert(new_set);
1857 }
1858 } else if (n_parts < (int)tagged_sets.size()) {
1859 // too many partition sets - delete extras
1860 int num_del = tagged_sets.size() - n_parts;
1861 for (int i = 0; i < num_del; i++) {
1862 EntityHandle old_set = tagged_sets.pop_back();
1863 CHKERR m_field.get_moab().delete_entities(&old_set, 1);
1864 }
1865 }
1866 // write a tag to those sets denoting they're partition sets, with a
1867 // value of the proc number
1868 std::vector<int> dum_ids(n_parts);
1869 for (int i = 0; i < n_parts; i++)
1870 dum_ids[i] = i;
1871 CHKERR m_field.get_moab().tag_set_data(part_tag, tagged_sets,
1872 &*dum_ids.begin());
1873 CHKERR m_field.get_moab().clear_meshset(tagged_sets);
1874
1875 // get lower dimension entities on each part
1876 for (int pp = 0; pp != n_parts; pp++) {
1877 Range dim_ents = parts_ents[pp].subset_by_dimension(dim);
1878 for (int dd = dim - 1; dd >= 0; dd--) {
1879 Range adj_ents;
1880 CHKERR m_field.get_moab().get_adjacencies(
1881 dim_ents, dd, false, adj_ents, moab::Interface::UNION);
1882 parts_ents[pp].merge(adj_ents);
1883 }
1884 }
1885 for (int pp = 1; pp != n_parts; pp++) {
1886 for (int ppp = 0; ppp != pp; ppp++) {
1887 parts_ents[pp] = subtract(parts_ents[pp], parts_ents[ppp]);
1888 }
1889 }
1890
1891 for (int pp = 0; pp != n_parts; pp++) {
1892 CHKERR m_field.get_moab().add_entities(tagged_sets[pp], parts_ents[pp]);
1893 }
1894
1895 auto set_part = [&]() {
1897 for (EntityType t = MBEDGE; t != MBENTITYSET; ++t) {
1898 for (int pp = 0; pp != n_parts; pp++) {
1899 Range type_ents = parts_ents[pp].subset_by_type(t);
1900 CHKERR m_field.get_moab().tag_clear_data(part_tag, type_ents, &pp);
1901 }
1902 }
1904 };
1905
1906 auto set_gid = [&]() {
1908 for (int d = 0; d != 4; ++d) {
1909 if (d == 0 && preserve_vertex_ids)
1910 continue;
1911
1912 void *ptr;
1913 int count;
1914
1915 int gid = 1; // moab indexing from 1
1916 for (int pp = 0; pp != n_parts; pp++) {
1917 Range type_ents = parts_ents[pp].subset_by_dimension(d);
1918
1919 auto eit = type_ents.begin();
1920 for (; eit != type_ents.end();) {
1921 CHKERR m_field.get_moab().tag_iterate(
1922 gid_tag, eit, type_ents.end(), count, ptr);
1923 auto gid_tag_ptr = static_cast<int *>(ptr);
1924 for (; count > 0; --count) {
1925 *gid_tag_ptr = gid;
1926 ++eit;
1927 ++gid;
1928 ++gid_tag_ptr;
1929 }
1930 }
1931 }
1932 }
1933
1935 };
1936
1937 CHKERR set_part();
1938 CHKERR set_gid();
1939 }
1940
1941 if (debug) {
1942 if (m_field.get_comm_rank() == 0) {
1943 for (int rr = 0; rr != n_parts; rr++) {
1944 ostringstream ss;
1945 ss << "out_part_" << rr << ".vtk";
1946 MOFEM_LOG("SELF", Sev::inform) << "Save debug part mesh " << ss.str();
1947 EntityHandle meshset;
1948 CHKERR m_field.get_moab().create_meshset(MESHSET_SET, meshset);
1949 CHKERR m_field.get_moab().add_entities(meshset, parts_ents[rr]);
1950 CHKERR m_field.get_moab().write_file(ss.str().c_str(), "VTK", "",
1951 &meshset, 1);
1952 CHKERR m_field.get_moab().delete_entities(&meshset, 1);
1953 }
1954 }
1955 }
1956
1957 CHKERR ISRestoreIndices(is_gather, &part_number);
1958 CHKERR ISRestoreIndices(is_gather_num, &gids);
1959 CHKERR ISDestroy(&is_num);
1960 CHKERR ISDestroy(&is_gather_num);
1961 CHKERR ISDestroy(&is_gather);
1962 CHKERR ISDestroy(&is);
1963 CHKERR MatPartitioningDestroy(&part);
1964 CHKERR MatDestroy(&Adj);
1965 }
1966
1968}
1969
1971 moab::Interface &moab, const char *file_name, int dim,
1972 LoadFileFun proc_skin_fun, const char *options) {
1974
1975 MOFEM_LOG_CHANNEL("WORLD");
1976 MOFEM_LOG_CHANNEL("SYNC");
1977
1978 MOFEM_LOG("SYNC", sev) << "Load file " << file_name;
1979 CHKERR moab.load_file(file_name, 0, options);
1981 MOFEM_LOG("SYNC", sev) << "Load file <- done";
1982 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, sev);
1983
1984 ParallelComm *pcomm = ParallelComm::get_pcomm(&moab, MYPCOMM_INDEX);
1985 if (pcomm == NULL)
1986 pcomm = new ParallelComm(&moab, PETSC_COMM_WORLD);
1987 if (pcomm->size() == 1)
1989
1990 Skinner skin(&moab);
1991
1992 auto print_range_on_procs = [&](const Range &range, std::string name) {
1993 MOFEM_LOG("SYNC", sev) << name << " on proc [" << pcomm->rank()
1994 << "] : " << range.size();
1995 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, sev);
1996 };
1997
1998 auto save_range_to_file = [&](const Range range, std::string name = "part") {
1999 if (!debug)
2000 return;
2001 int rr = pcomm->rank();
2002 ostringstream ss;
2003 ss << "out_" << name << "_" << rr << ".vtk";
2004 MOFEM_LOG("SYNC", sev) << "Save debug part mesh " << ss.str();
2005 EntityHandle meshset;
2006 CHKERR moab.create_meshset(MESHSET_SET, meshset);
2007 CHKERR moab.add_entities(meshset, range);
2008 if (!range.empty())
2009 CHKERR moab.write_file(ss.str().c_str(), "VTK", "", &meshset, 1);
2010 MOFEM_LOG("SYNC", sev) << "Empty range";
2011 CHKERR moab.delete_entities(&meshset, 1);
2012 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, sev);
2013 };
2014
2015 auto get_skin = [&](auto e) {
2016 Range s;
2017 CHKERR skin.find_skin(0, e.subset_by_dimension(dim), false, s);
2018 return s;
2019 };
2020
2021 auto get_adj = [&](auto ents, auto dim) {
2022 Range adj;
2023 CHKERR moab.get_adjacencies(ents, dim, false, adj, moab::Interface::UNION);
2024 return adj;
2025 };
2026
2027 Range all_ents;
2028 CHKERR moab.get_entities_by_handle(0, all_ents, false);
2029 save_range_to_file(all_ents, "all_ents");
2030
2031 Tag part_tag = pcomm->part_tag();
2032 Range tagged_sets, proc_ents, off_proc_ents;
2033
2034 CHKERR moab.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag, NULL, 1,
2035 tagged_sets, moab::Interface::UNION);
2036 print_range_on_procs(tagged_sets, "tagged_sets");
2037 for (auto &mit : tagged_sets) {
2038 int part;
2039 CHKERR moab.tag_get_data(part_tag, &mit, 1, &part);
2040 if (part == pcomm->rank()) {
2041 CHKERR moab.get_entities_by_handle(mit, proc_ents, true);
2042 } else {
2043 CHKERR moab.get_entities_by_handle(mit, off_proc_ents, true);
2044 }
2045 }
2046
2047 // set part tags to entities, they might be not set
2048 for (auto &mit : tagged_sets) {
2049 int part;
2050 CHKERR moab.tag_get_data(part_tag, &mit, 1, &part);
2051 Range ents;
2052 CHKERR moab.get_entities_by_handle(mit, ents, true);
2053 CHKERR moab.tag_clear_data(part_tag, ents, &part);
2054 }
2055
2056 print_range_on_procs(proc_ents, "proc_ents");
2057 save_range_to_file(proc_ents, "proc_ents");
2058
2059 auto get_proc_ents_skin = [&]() {
2060 std::array<Range, 4>
2061 proc_ents_skin; // stores only entities shared with other processors
2062 auto all_skin = get_skin(all_ents.subset_by_dimension(dim));
2063 auto proc_skin = get_skin(proc_ents.subset_by_dimension(dim));
2064 if (dim == 3) {
2065 proc_ents_skin[2] = subtract(proc_skin, all_skin); // faces
2066 proc_ents_skin[1] = get_adj(proc_ents_skin[dim - 1], 1); // edges
2067 }
2068 if (dim == 2) {
2069 proc_ents_skin[1] = subtract(proc_skin, all_skin); // edges
2070 }
2071 CHKERR moab.get_connectivity(proc_ents_skin[dim - 1], proc_ents_skin[0],
2072 false); // vertices
2073 return proc_ents_skin;
2074 };
2075
2076 auto add_post_proc_skin = [&](auto &&proc_ents_skin) {
2077 CubitMeshSet_multiIndex cubit_meshsets_index; ///< cubit meshsets
2078
2079 Tag nsTag, ssTag, nsTag_data, ssTag_data, bhTag, bhTag_header;
2080 CHKERR MeshsetsManager::getTags(moab, nsTag, ssTag, nsTag_data, ssTag_data,
2081 bhTag, bhTag_header, QUIET);
2082
2083 Range meshsets;
2084 CHKERR moab.get_entities_by_type(0, MBENTITYSET, meshsets, false);
2085 for (auto m : meshsets) {
2086 // check if meshset is cubit meshset
2087 CubitMeshSets block(moab, m);
2089 .any()) {
2090 auto p = cubit_meshsets_index.insert(block);
2091 if (!p.second) {
2092 // blockset/nodeset/sideset set exist, could be created on other
2093 // processor.
2094 Range ents;
2095 CHKERR moab.get_entities_by_handle(m, ents, true);
2096 CHKERR moab.add_entities(p.first->getMeshset(), ents);
2097 CHKERR moab.delete_entities(&m, 1);
2098 }
2099 }
2100 }
2101
2102 for (auto &m : cubit_meshsets_index) {
2103 MOFEM_LOG("WORLD", sev) << "LoadFile read " << m;
2104 }
2105 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, sev);
2106
2107 std::vector<const CubitMeshSets *> vec_ptr;
2108 for (auto &m : cubit_meshsets_index) {
2109 vec_ptr.push_back(&m);
2110 }
2112
2113 return proc_skin_fun(std::move(proc_ents_skin), std::move(vec_ptr));
2114 };
2115
2116 auto remove_off_proc_ents = [&](auto &all_ents, auto &off_proc_ents,
2117 auto &proc_ents_skin) {
2118 auto to_remove = off_proc_ents;
2119 for (auto d = dim - 1; d >= 0; --d) {
2120 to_remove = subtract(to_remove, proc_ents_skin[d]);
2121 }
2122
2123 Range meshsets;
2124 CHKERR moab.get_entities_by_type(0, MBENTITYSET, meshsets, true);
2125 for (auto m : meshsets) {
2126 CHKERR moab.remove_entities(m, to_remove);
2127 }
2128 for (int dd = dim; dd > 0; --dd) {
2129 CHKERR moab.delete_entities(to_remove.subset_by_dimension(dd));
2130 }
2131 };
2132
2133 auto proc_ents_skin = add_post_proc_skin(get_proc_ents_skin());
2134 for (auto d = dim - 1; d >= 0; --d) {
2135 save_range_to_file(proc_ents_skin[d], "proc_ents_skin" + std::to_string(d));
2136 }
2137
2138 if (pcomm->rank()) {
2139 remove_off_proc_ents(all_ents, off_proc_ents, proc_ents_skin);
2140 }
2141
2142 for (auto d = dim - 1; d >= 0; --d) {
2143 print_range_on_procs(proc_ents_skin[d],
2144 "proc_ents_skin by dim" + std::to_string(d));
2145 }
2146
2147 CHKERR pcomm->resolve_shared_ents(0, proc_ents, dim, -1,
2148 proc_ents_skin.data());
2149
2150 if (debug) {
2151
2152 // Create a tag
2153 auto gid_tag = moab.globalId_tag();
2154
2155 int def_val = -1;
2156 Tag tag_handle;
2157 CHKERR moab.tag_get_handle("TestGather", 1, MB_TYPE_INTEGER, tag_handle,
2158 MB_TAG_DENSE | MB_TAG_CREAT, &def_val);
2159 Range gather_ents;
2160 if (pcomm->rank() > 0) {
2161 gather_ents = proc_ents.subset_by_dimension(3);
2162 std::vector<int> vals(gather_ents.size());
2163 std::for_each(vals.begin(), vals.end(), [](auto &v) { v = std::rand(); });
2164 CHKERR moab.tag_set_data(tag_handle, gather_ents, vals.data());
2165 CHKERR pcomm->gather_data(gather_ents, tag_handle, gid_tag, 0, 0);
2166 } else {
2167 gather_ents = proc_ents.subset_by_dimension(3);
2168 CHKERR pcomm->gather_data(gather_ents, tag_handle, gid_tag, 0, 0);
2169 }
2170 }
2171
2172 Range all_ents_after;
2173 CHKERR moab.get_entities_by_handle(0, all_ents_after);
2174 save_range_to_file(all_ents_after.subset_by_dimension(3),
2175 "all_ents_part_after");
2176
2177 MOFEM_LOG("SYNC", sev) << "Resolved entities <- done";
2178 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, sev);
2179
2181}
2182
2183Range CommInterface::getPartEntities(moab::Interface &moab, int part) {
2184
2185 ParallelComm *pcomm = ParallelComm::get_pcomm(&moab, MYPCOMM_INDEX);
2186 if (pcomm == NULL)
2187 pcomm = new ParallelComm(&moab, PETSC_COMM_WORLD);
2188 if (pcomm->size() == 1) {
2189 Range ents;
2190 CHK_MOAB_THROW(moab.get_entities_by_handle(0, ents, false),
2191 "get_entities_by_handle failed");
2192 return subtract(ents, ents.subset_by_type(MBENTITYSET));
2193 }
2194
2195 Range proc_ents;
2196
2197 auto get_proc_ents = [&]() {
2199
2200 auto get_all_mesh_entities = [&]() {
2202 CHKERR moab.get_entities_by_handle(0, proc_ents, false);
2203 proc_ents = subtract(proc_ents, proc_ents.subset_by_type(MBENTITYSET));
2205 };
2206
2207 Tag part_tag = pcomm->part_tag();
2208 Range tagged_sets;
2209 auto rval =
2210 moab.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag, NULL, 1,
2211 tagged_sets, moab::Interface::UNION);
2212 if (rval == MB_TAG_NOT_FOUND || rval == MB_ENTITY_NOT_FOUND ||
2213 tagged_sets.empty()) {
2214 MOFEM_LOG("SELF", Sev::warning)
2215 << "Partition tag or partition sets not found, returning all mesh "
2216 "entities";
2217 CHKERR get_all_mesh_entities();
2219 }
2220 CHKERR rval;
2221
2222 for (auto &mit : tagged_sets) {
2223 int part_set;
2224 CHKERR moab.tag_get_data(part_tag, &mit, 1, &part_set);
2225 if (part_set == part) {
2226 rval = moab.get_entities_by_handle(mit, proc_ents, true);
2227 if (rval == MB_SUCCESS) {
2229 }
2230 if (rval == MB_ENTITY_NOT_FOUND) {
2231 MOFEM_LOG("SELF", Sev::warning)
2232 << "Partition set is stale, returning all mesh entities";
2233 proc_ents.clear();
2234 CHKERR get_all_mesh_entities();
2236 }
2237 CHKERR rval;
2238 }
2239 }
2240
2241 MOFEM_LOG("SELF", Sev::warning)
2242 << "Partition set for requested part not found, returning all mesh "
2243 "entities";
2244 CHKERR get_all_mesh_entities();
2247 };
2248
2249 CHK_THROW_MESSAGE(get_proc_ents(), "get_proc_ents failed");
2250
2251 return proc_ents;
2252}
2253
2256 const EntityHandle meshset,
2257 const int pcomm_id) {
2259 ParallelComm *pcomm = ParallelComm::get_pcomm(&moab, pcomm_id);
2260 if (!pcomm)
2262 Tag part_tag = pcomm->part_tag();
2263 Range tagged_sets;
2264 // Any part value: a set read from file may carry another part number.
2265 auto rval = moab.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag,
2266 nullptr, 1, tagged_sets,
2267 moab::Interface::UNION);
2268 if (rval == MB_TAG_NOT_FOUND || rval == MB_ENTITY_NOT_FOUND)
2270 CHKERR rval;
2271 for (auto s : tagged_sets)
2272 if (s != meshset)
2273 CHKERR moab.remove_entities(s, &meshset, 1);
2275}
2276
2278 MPI_Comm comm, moab::Interface &moab,
2279 std::function<Range(Range)> get_entities_fun, const int nb_coeffs, Sev sev,
2280 int root_rank, bool get_vertices) {
2281
2283 Range r, ghost_ents;
2284
2285 auto get_gids = [&](Range &ents) {
2286 std::vector<int> ids(ents.size());
2287 auto gid_tag = moab.globalId_tag();
2288 CHKERR moab.tag_get_data(gid_tag, ents, ids.data());
2289 return ids;
2290 };
2291
2292 auto create_ao = [&](auto &&ids) {
2293 AO ao_raw;
2295 AOCreateMapping(comm, ids.size(), ids.data(), PETSC_NULLPTR, &ao_raw),
2296 "create ao failed");
2297 return SmartPetscObj<AO>(ao_raw, false);
2298 };
2299
2300 auto apply_ao = [&](auto ao, std::vector<int> &&ids) {
2301 CHK_THROW_MESSAGE(AOApplicationToPetsc(ao, ids.size(), ids.data()),
2302 "AOApplicationToPetsc failed");
2303 return ids;
2304 };
2305
2306 auto get_tag_ids = [&](auto ao, Range &ents) {
2307 return apply_ao(ao, get_gids(ents));
2308 };
2309
2310 auto fun = [&]() {
2312 auto pcomm = ParallelComm::get_pcomm(&moab, MYPCOMM_INDEX);
2313 Tag part_tag = pcomm->part_tag();
2314 Range tagged_sets;
2315 CHKERR moab.get_entities_by_type_and_tag(0, MBENTITYSET, &part_tag, NULL, 1,
2316 tagged_sets,
2317 moab::Interface::UNION);
2318 auto get_proc_and_off_proc_ents = [&]() {
2319 Range proc_ents, off_proc_ents;
2320 // Imported partition labels do not imply remote ownership in serial.
2321 if (pcomm->size() == 1) {
2322 CHK_MOAB_THROW(moab.get_entities_by_handle(0, proc_ents, false),
2323 "get_entities_by_handle failed");
2324 proc_ents = subtract(proc_ents, proc_ents.subset_by_type(MBENTITYSET));
2325 proc_ents = subtract(proc_ents, proc_ents.subset_by_type(MBVERTEX));
2326 return std::make_pair(proc_ents, Range());
2327 }
2328 for (auto &mit : tagged_sets) {
2329 int part;
2330 CHK_MOAB_THROW(moab.tag_get_data(part_tag, &mit, 1, &part),
2331 "tag_get_data failed");
2332 if (part == pcomm->rank()) {
2333 CHK_MOAB_THROW(moab.get_entities_by_handle(mit, proc_ents, false),
2334 "get_entities_by_handle failed");
2335 } else {
2336 CHK_MOAB_THROW(moab.get_entities_by_handle(mit, off_proc_ents, false),
2337 "get_entities_by_handle failed");
2338 }
2339 proc_ents = subtract(proc_ents, off_proc_ents);
2340 }
2341 return std::make_pair(proc_ents, off_proc_ents);
2342 };
2343
2344 auto get_proc_and_off_proc_verts = [&]() {
2345 Range proc_ents, off_proc_ents;
2346 if (pcomm->size() == 1 || tagged_sets.empty()) {
2347 CHK_MOAB_THROW(moab.get_entities_by_type(0, MBVERTEX, proc_ents),
2348 "get_entities_by_type failed");
2349 return std::make_pair(proc_ents, Range());
2350 }
2351 std::map<int, Range> parts_ents;
2352 for (auto &mit : tagged_sets) {
2353 int part;
2354 CHK_MOAB_THROW(moab.tag_get_data(part_tag, &mit, 1, &part),
2355 "tag_get_data failed");
2357 moab.get_entities_by_handle(mit, parts_ents[part], false),
2358 "get_entities_by_handle failed");
2359 parts_ents[part] = subtract(
2360 parts_ents[part], parts_ents[part].subset_by_type(MBENTITYSET));
2361 }
2362 Range v;
2363 CHK_MOAB_THROW(moab.get_connectivity(parts_ents[pcomm->rank()], v),
2364 "get_connectivity failed");
2365 int p = 0;
2366 for (; p != pcomm->rank(); ++p) {
2367 Range vv;
2368 CHK_MOAB_THROW(moab.get_connectivity(parts_ents[p], vv),
2369 "get_connectivity failed");
2370 v = subtract(v, vv);
2371 off_proc_ents.merge(vv);
2372 }
2373 for (; p != pcomm->size(); ++p) {
2374 Range vv;
2375 CHK_MOAB_THROW(moab.get_connectivity(parts_ents[p], vv),
2376 "get_connectivity failed");
2377 vv = subtract(vv, v);
2378 off_proc_ents.merge(vv);
2379 }
2380 proc_ents = v;
2381 return std::make_pair(proc_ents, off_proc_ents);
2382 };
2383
2384 auto [proc_ents, off_proc_ents] = get_proc_and_off_proc_ents();
2385
2386 if (get_vertices) {
2387 auto [proc_verts, off_proc_verts] = get_proc_and_off_proc_verts();
2388 proc_ents.merge(proc_verts);
2389 off_proc_ents.merge(off_proc_verts);
2390 }
2391 r = get_entities_fun(proc_ents);
2392 auto o = get_entities_fun(off_proc_ents);
2393 auto ao = create_ao(get_gids(r));
2394
2395 auto set_ghosts = [&](auto &&ghosts_gids) {
2396 std::vector<int> ghosts_dofs(nb_coeffs * ghosts_gids.size());
2397 for (int i = 0; i < ghosts_gids.size(); ++i)
2398 for (int j = 0; j < nb_coeffs; ++j)
2399 ghosts_dofs[i * nb_coeffs + j] = nb_coeffs * ghosts_gids[i] + j;
2400 return ghosts_dofs;
2401 };
2402
2403 std::vector<int> ghosts;
2404 if (pcomm->rank() == root_rank) {
2405 ghosts = set_ghosts(get_tag_ids(ao, o));
2406 ghost_ents = o;
2407 } else {
2408 Range ents;
2409 CHKERR moab.get_entities_by_handle(0, ents, true);
2410 ents = get_entities_fun(ents);
2411 ents = subtract(ents, r);
2412 ghosts = set_ghosts(get_tag_ids(ao, ents));
2413 ghost_ents = ents;
2414 }
2415
2416 auto create_vec = [&]() {
2418 vec = createGhostVector(comm, nb_coeffs * r.size(), PETSC_DETERMINE,
2419 ghosts.size(), ghosts.data());
2421 };
2422 CHKERR create_vec();
2423
2425 };
2426
2427 CHKERR fun();
2428
2429 auto out = std::make_pair(std::make_pair(r, ghost_ents), vec);
2430
2431#ifndef NDEBUG
2432 {
2433
2434 auto check = [&](auto &ents, auto &id, auto &idx) {
2436 bool error = false;
2437 for (int i = 0; i < ents.size(); ++i) {
2438 for (int j = 0; j < nb_coeffs; ++j) {
2439 if (idx[i * nb_coeffs + j] != nb_coeffs * id[i] + j) {
2440 error = true;
2441 MOFEM_LOG("SYNC", Sev::error)
2442 << "indexes not equal: " << idx[i * nb_coeffs + j]
2443 << " != " << nb_coeffs * idx[i] + j;
2444 }
2445 }
2446 }
2447 MOFEM_LOG_SEVERITY_SYNC(PETSC_COMM_WORLD, Sev::error);
2448 if (error)
2449 CHK_THROW_MESSAGE(MOFEM_DATA_INCONSISTENCY, "indexes do not match");
2451 };
2452
2453 std::vector<double> def_val(nb_coeffs, 0.0);
2454 Tag tag;
2455 CHKERR moab.tag_get_handle("TestGather", nb_coeffs, MB_TYPE_DOUBLE, tag,
2456 MB_TAG_SPARSE | MB_TAG_CREAT, def_val.data());
2457 auto ao = create_ao(get_gids(r));
2458 auto id = get_tag_ids(ao, r);
2459 std::vector<double> idx(nb_coeffs * r.size());
2460 for (int i = 0; i < r.size(); ++i) {
2461 for (int j = 0; j < nb_coeffs; ++j) {
2462 idx[i * nb_coeffs + j] = nb_coeffs * id[i] + j;
2463 }
2464 }
2465 CHKERR moab.tag_set_data(tag, r, idx.data());
2467 idx.resize(nb_coeffs * r.size());
2468 CHKERR moab.tag_get_data(tag, r, idx.data());
2469 CHK_THROW_MESSAGE(check(r, id, idx), "indexes do not match")
2470 auto ghost_id = get_tag_ids(ao, ghost_ents);
2471 idx.resize(nb_coeffs * ghost_ents.size());
2472 CHKERR moab.tag_get_data(tag, ghost_ents, idx.data());
2473 CHK_THROW_MESSAGE(check(ghost_ents, ghost_id, idx),
2474 "ghost indexes do not match")
2475 CHKERR moab.tag_delete(tag);
2476 }
2477#endif // NDEBUG
2478
2479 return out;
2480}
2481
2484 Tag tag) {
2486
2487 int local_size;
2488 CHKERR VecGetLocalSize(vec.second, &local_size);
2489 int nb_coeffs;
2490 CHKERR moab.tag_get_length(tag, nb_coeffs);
2491 if (vec.first.first.size() * nb_coeffs != local_size) {
2492 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2493 "Local size of vector does not match number of entities");
2494 }
2495
2496 auto set_vec_from_tags = [&]() {
2498 double *v_array;
2499 // set vector
2500 CHKERR VecGetArray(vec.second, &v_array);
2501 CHKERR moab.tag_get_data(tag, vec.first.first, v_array);
2502 CHKERR moab.tag_get_data(tag, vec.first.second, &v_array[local_size]);
2503 CHKERR VecRestoreArray(vec.second, &v_array);
2505 };
2506
2507 CHKERR set_vec_from_tags();
2508
2510}
2511
2514 Tag tag) {
2516
2517 int local_size;
2518 CHKERR VecGetLocalSize(vec.second, &local_size);
2519 int nb_coeffs;
2520 CHKERR moab.tag_get_length(tag, nb_coeffs);
2521 if (vec.first.first.size() * nb_coeffs != local_size) {
2522 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
2523 "Local size of vector does not match number of entities");
2524 }
2525
2526 auto set_tags_from_vec = [&]() {
2528 double *v_array;
2529 CHKERR VecGetArray(vec.second, &v_array);
2530 CHKERR moab.tag_set_data(tag, vec.first.first, v_array);
2531 CHKERR moab.tag_set_data(tag, vec.first.second, &v_array[local_size]);
2532 CHKERR VecRestoreArray(vec.second, &v_array);
2534 };
2535
2536 CHKERR set_tags_from_vec();
2537
2539}
2540
2542CommInterface::createEntitiesPetscVector(MPI_Comm comm, moab::Interface &moab,
2543 int dim, const int nb_coeffs, Sev sev,
2544 int root_rank) {
2546 comm, moab,
2547
2548 [dim](Range r) { return r.subset_by_dimension(dim); }
2549
2550 ,
2551 nb_coeffs, sev, root_rank, (dim != 0) ? false : true);
2552}
2553
2557 UpdateGhosts update_ghosts) {
2559
2560 CHKERR setVectorFromTag(moab, vec, tag);
2561 CHKERR update_ghosts(vec.second);
2562 CHKERR setTagFromVector(moab, vec, tag);
2563
2565}
2566
2567} // namespace MoFEM
CGALInterfaceImpl & owner
CGAL algorithms independent of the MoFEM/MOAB database.
FaceSet skin
std::vector< int > source
std::vector< int > size
std::vector< int > vertices
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
std::array< int, 4 > connectivity
unsigned char status
EntityHandle handle
ParentChildKey key
MPI_Comm comm
moab::Interface & mb
Core & cOre
Tag tag
std::map< EntityHandle, size_t > offsets
std::vector< double > empty
One value per component.
std::vector< std::array< double, 3 > > coordinates
std::string type
#define MOFEM_LOG_SEVERITY_SYNC(comm, severity)
Synchronise "SYNC" on curtain severity level.
#define MOFEM_LOG_SYNCHRONISE(comm)
Synchronise "SYNC" channel.
#define MOFEM_LOG_C(channel, severity, format,...)
std::vector< FieldBitNumber > row
Definition Schur.cpp:2488
It it
Definition Schur.cpp:2568
It end
Definition Schur.cpp:2568
SmartPetscObj< Vec > values
SmartPetscObj< IS > rows
std::string name
constexpr double a
@ QUIET
@ NOISY
@ VERBOSE
#define CHK_THROW_MESSAGE(err, msg)
Check and throw MoFEM exception.
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define 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.
@ NODESET
@ SIDESET
@ BLOCKSET
@ MOFEM_IMPOSSIBLE_CASE
Definition definitions.h:35
@ 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.
#define MoFEMFunctionBeginHot
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
auto fun
static const bool debug
multi_index_container< boost::shared_ptr< FiniteElement >, indexed_by< hashed_unique< tag< FiniteElement_Meshset_mi_tag >, member< FiniteElement, EntityHandle, &FiniteElement::meshset > >, hashed_unique< tag< BitFEId_mi_tag >, const_mem_fun< FiniteElement, BitFEId, &FiniteElement::getId >, HashBit< BitFEId >, EqBit< BitFEId > >, ordered_unique< tag< FiniteElement_name_mi_tag >, const_mem_fun< FiniteElement, boost::string_ref, &FiniteElement::getNameRef > > > > FiniteElement_multiIndex
MultiIndex for entities for FiniteElement.
virtual const Problem * get_problem(const std::string problem_name) const =0
Get the problem object.
virtual const FieldEntity_multiIndex * get_field_ents() const =0
Get the field ents object.
virtual const FiniteElement_multiIndex * get_finite_elements() const =0
Get the finite elements object.
virtual const RefEntity_multiIndex * get_ref_ents() const =0
Get the ref ents object.
virtual const Field * get_field_structure(const std::string &name, enum MoFEMTypes bh=MF_EXIST) const =0
get field structure
MoFEMErrorCode synchroniseFieldEntities(const std::string name, int verb=DEFAULT_VERBOSITY)
#define MOFEM_LOG(channel, severity)
Log.
SeverityLevel
Severity levels.
#define MOFEM_LOG_CHANNEL(channel)
Set and reset channel.
MoFEMErrorCode getTags(int verb=-1)
Get tag handles used on meshsets.
MoFEMErrorCode partitionMesh(const Range &ents, const int dim, const int adj_dim, const int n_parts, Tag *th_vertex_weights=nullptr, Tag *th_edge_weights=nullptr, Tag *th_part_weights=nullptr, int verb=VERBOSE, const bool debug=false, const bool preserve_vertex_ids=false)
Set partition tag to each finite element in the problem.
MoFEMErrorCode resolveSharedFiniteElements(const Problem *problem_ptr, const std::string &fe_name, int verb=DEFAULT_VERBOSITY)
resolve shared entities for finite elements in the problem
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)
FTensor::Index< 'j', 3 > j
static MoFEMErrorCodeGeneric< moab::ErrorCode > rval
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
std::bitset< 32 > CubitBCType
Definition Types.hpp:52
std::bitset< BITREFLEVEL_SIZE > BitRefLevel
Bit structure attached to each entity identifying to what mesh entity is attached.
Definition Types.hpp:40
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
auto type_from_handle(const EntityHandle h)
get type from entity handle
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
multi_index_container< CubitMeshSets, indexed_by< hashed_unique< tag< Meshset_mi_tag >, member< CubitMeshSets, EntityHandle, &CubitMeshSets::meshset > >, ordered_non_unique< tag< CubitMeshsetType_mi_tag >, const_mem_fun< CubitMeshSets, unsigned long int, &CubitMeshSets::getBcTypeULong > >, ordered_non_unique< tag< CubitMeshsetMaskedType_mi_tag >, const_mem_fun< CubitMeshSets, unsigned long int, &CubitMeshSets::getMaskedBcTypeULong > >, ordered_non_unique< tag< CubitMeshsets_name >, const_mem_fun< CubitMeshSets, std::string, &CubitMeshSets::getName > >, hashed_unique< tag< Composite_Cubit_msId_And_MeshsetType_mi_tag >, composite_key< CubitMeshSets, const_mem_fun< CubitMeshSets, int, &CubitMeshSets::getMeshsetId >, const_mem_fun< CubitMeshSets, unsigned long int, &CubitMeshSets::getMaskedBcTypeULong > > > > > CubitMeshSet_multiIndex
Stores data about meshsets (see CubitMeshSets) storing data about boundary conditions,...
auto createGhostVector(MPI_Comm comm, PetscInt n, PetscInt N, PetscInt nghost, const PetscInt ghosts[])
Create smart ghost vector.
constexpr AssemblyType A
constexpr auto field_name
FTensor::Index< 'm', 3 > m
Managing BitRefLevels.
Managing BitRefLevels.
static MoFEMErrorCode updateEntitiesPetscVector(moab::Interface &moab, EntitiesPetscVector &vec, Tag tag, UpdateGhosts update_gosts=defaultUpdateGhosts)
Exchange data between vector and data.
MoFEMErrorCode query_interface(boost::typeindex::type_index type_index, UnknownInterface **iface) const
std::function< MoFEMErrorCode(Vec vec)> UpdateGhosts
MoFEMErrorCode inheritPartitions(const Range &source_entities, const Range &child_entities)
static Range getPartEntities(moab::Interface &moab, int part)
MoFEMErrorCode synchroniseByConnectivity(const Range &entities, int complete_mesh_rank=-1)
CommInterface(const MoFEM::Core &core)
MoFEMErrorCode retainPartition(Range &entities, const BitRefLevel &active_bit, const Range &preserve={})
MoFEMErrorCode makeEntitiesMultishared(const EntityHandle *entities, const int num_entities, const int owner_proc=0, int verb=DEFAULT_VERBOSITY)
make entities from proc 0 shared on all proc
static MoFEMErrorCode loadFileRootProcAllRestDistributed(moab::Interface &moab, const char *file_name, int dim, LoadFileFun proc_skin_fun=defaultProcSkinFun, const char *options="PARALLEL=BCAST;PARTITION=")
Root proc has whole mesh, other procs only part of it.
MoFEMErrorCode synchroniseEntities(Range &ent, std::map< int, Range > *received_ents, int verb=DEFAULT_VERBOSITY)
synchronize entity range on processors (collective)
MoFEMErrorCode synchroniseByParentChild(const BitRefLevel &parent_bit, const BitRefLevel &child_bit, int verb=DEFAULT_VERBOSITY)
std::function< std::array< Range, 4 >(std::array< Range, 4 > &&, std::vector< const CubitMeshSets * > &&)> LoadFileFun
static MoFEMErrorCode setVectorFromTag(moab::Interface &moab, EntitiesPetscVector &vec, Tag tag)
Set the Vector From Tag object.
static MoFEMErrorCode removeMeshsetFromPartition(moab::Interface &moab, const EntityHandle meshset, const int pcomm_id=MYPCOMM_INDEX)
Remove a meshset from all partition sets before it is deleted.
static MoFEMErrorCode setTagFromVector(moab::Interface &moab, EntitiesPetscVector &vec, Tag tag)
Set the Tag From Vector object.
MoFEMErrorCode makeFieldEntitiesMultishared(const std::string field_name, const int owner_proc=0, int verb=DEFAULT_VERBOSITY)
make field entities multi shared
std::pair< std::pair< Range, Range >, SmartPetscObj< Vec > > EntitiesPetscVector
MoFEMErrorCode resolveParentEntities(const Range &ent, int verb=DEFAULT_VERBOSITY)
Synchronise parent entities.
MoFEMErrorCode gatherMesh(const Range &cells, TetMeshData &data, int root=0)
MoFEMErrorCode exchangeFieldData(const std::string field_name, int verb=DEFAULT_VERBOSITY)
Exchange field data.
static EntitiesPetscVector createEntitiesPetscVector(MPI_Comm comm, moab::Interface &moab, std::function< Range(Range)> get_entities_fun, const int nb_coeffs, Sev sev=Sev::verbose, int root_rank=0, bool get_vertices=true)
Create a ghost vector for exchanging data.
MoFEMErrorCode broadcastMesh(TetMeshData &data, int root=0)
virtual int get_comm_size() const =0
virtual FieldBitNumber get_field_bit_number(const std::string name) const =0
get field bit number
virtual moab::Interface & get_moab()=0
virtual EntityHandle get_field_meshset(const std::string name) const =0
get field meshset
virtual MPI_Comm & get_comm() const =0
virtual MoFEMErrorCode remove_ents(const Range ents, int verb=DEFAULT_VERBOSITY)=0
Remove entities from MoFEM database.
virtual int get_comm_rank() const =0
virtual boost::shared_ptr< BasicEntityData > & get_basic_entity_data_ptr()=0
Get pointer to basic entity data.
Core (interface) class.
Definition Core.hpp:83
Tag get_th_RefBitLevel() const
Definition Core.hpp:203
Tag get_th_RefParentHandle() const
Definition Core.hpp:202
this struct keeps basic methods for moab meshset about material and boundary conditions
Deprecated interface functions.
UId getLocalUniqueIdCalculate() const
Generate UId for finite element entity.
static UId getHiBitNumberUId(const FieldBitNumber bit_number)
static UId getLoBitNumberUId(const FieldBitNumber bit_number)
Interface for managing meshsets containing materials and boundary conditions.
static void sortMeshsets(std::vector< const CubitMeshSets * > &vec_ptr)
keeps basic data about problem
MoFEMErrorCode getNumberOfElementsByNameAndPart(MPI_Comm comm, const std::string name, PetscLayout *layout) const
Get number of finite elements by name on processors.
boost::shared_ptr< NumeredEntFiniteElement_multiIndex > numeredFiniteElementsPtr
store finite elements
intrusive_ptr for managing petsc objects
std::vector< int > partitions
Optional cell-to-rank assignment.
Definition CGALTools.hpp:22
std::vector< std::array< int, 3 > > boundary
Definition CGALTools.hpp:20
std::vector< int > cellLabels
Definition CGALTools.hpp:21
std::vector< std::array< int, 4 > > cells
Zero-based point indices.
Definition CGALTools.hpp:19
std::vector< std::array< double, 3 > > points
Definition CGALTools.hpp:17
std::vector< int > vertexIds
Definition CGALTools.hpp:18
std::vector< int > surfaceLabels
Definition CGALTools.hpp:21
base class for all interface classes
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.