10#ifdef MOOSE_MFEM_ENABLED
35 explicit UnionFind(
int n);
41 bool join(
int a,
int b);
44 std::vector<int> _parent, _rank;
47UnionFind::UnionFind(
int n) : _parent(n), _rank(n, 0)
49 std::iota(_parent.begin(), _parent.end(), 0);
55 while (_parent[x] != x)
57 _parent[x] = _parent[_parent[x]];
64UnionFind::join(
int a,
int b)
70 if (_rank[a] < _rank[b])
73 if (_rank[a] == _rank[b])
79using Coord3 = std::array<mfem::real_t, 3>;
85edgeLDof(mfem::ParFiniteElementSpace & pfes,
int e, mfem::Array<int> & ldofs)
87 pfes.GetEdgeDofs(e, ldofs);
88 return mfem::FiniteElementSpace::DecodeDof(ldofs[0]);
92vertexCoord(
const mfem::ParMesh & pmesh,
int v)
104 Coord3 p{0.0, 0.0, 0.0};
105 pmesh.GetNode(v, p.data());
124referenceGaugedDofs(
const mfem::FiniteElementCollection & nd_fec,
125 const mfem::FiniteElementCollection & h1_fec,
126 mfem::Geometry::Type geom,
129 const int num_bubbles = h1_fec.GetNumDof(geom, order);
130 std::vector<int> selected;
131 if (num_bubbles == 0)
134 const mfem::FiniteElement & nd_fe = *nd_fec.FiniteElementForGeometry(geom);
135 const mfem::FiniteElement & h1_fe = *h1_fec.FiniteElementForGeometry(geom);
136 mfem::IsoparametricTransformation identity;
137 identity.SetIdentityTransformation(geom);
138 mfem::DenseMatrix grad;
139 nd_fe.ProjectGrad(h1_fe, identity, grad);
143 const int num_rows = nd_fec.GetNumDof(geom, order);
144 const int row0 = nd_fe.GetDof() - num_rows, col0 = h1_fe.GetDof() - num_bubbles;
145 std::vector<mfem::Vector> rows(num_rows, mfem::Vector(num_bubbles));
148 rows[r](c) = grad(row0 + r, col0 + c);
155 constexpr mfem::real_t tie_tolerance = 1e-8;
156 std::vector<bool> available(num_rows,
true);
157 while (
static_cast<int>(selected.size()) < num_bubbles)
159 mfem::real_t max_norm = 0;
162 max_norm =
std::
max(max_norm, rows[r].Norml2());
165 while (!available[pick] || rows[pick].Norml2() < (1 - tie_tolerance) * max_norm)
167 available[pick] =
false;
168 selected.push_back(pick);
170 rows[pick] /= rows[pick].Norml2();
173 rows[r].Add(-(rows[r] * rows[pick]), rows[pick]);
176 std::sort(selected.begin(), selected.end());
186canonicalQuadOrientation(
const mfem::ParMesh & pmesh,
const mfem::Array<int> & fv)
188 std::array<Coord3, 4> coords;
190 coords[i] = vertexCoord(pmesh, fv[i]);
191 const int first = std::min_element(coords.begin(), coords.end()) - coords.begin();
192 const int step = (coords[(first + 1) % 4] < coords[(first + 3) % 4]) ? 1 : 3;
193 std::array<int, 4> canonical;
195 canonical[i] = fv[(first + i * step) % 4];
199 using Square = mfem::Geometry::Constants<mfem::Geometry::SQUARE>;
200 for (
const auto o :
make_range(Square::NumOrient))
202 std::array<int, 4> permuted;
204 permuted[j] = canonical[Square::Orient[o][j]];
205 if (std::equal(permuted.begin(), permuted.end(), fv.begin()))
208 mooseError(
"No orientation maps the canonical frame of a quadrilateral face onto its vertices.");
237 int origin_rank, origin_index;
241struct VertexNumbering
244 std::vector<std::int64_t> global_id;
247 std::vector<int> local_index;
249 std::int64_t num_global = 0;
264canonicalVertexIds(
const std::vector<Coord3> & coords, MPI_Comm comm)
267 MPI_Comm_size(comm, &nprocs);
268 MPI_Comm_rank(comm, &rank);
270 VertexNumbering numbering;
275 std::vector<std::pair<Coord3, int>> sorted(coords.size());
277 sorted[i] = {coords[i],
static_cast<int>(i)};
278 std::sort(sorted.begin(), sorted.end());
280 std::vector<Coord3> distinct;
281 numbering.local_index.resize(coords.size());
282 for (
const auto & [coord, position] : sorted)
284 if (distinct.empty() || distinct.back() != coord)
285 distinct.push_back(coord);
286 numbering.local_index[position] =
static_cast<int>(distinct.size()) - 1;
289 sorted.shrink_to_fit();
290 numbering.num_local =
static_cast<int>(distinct.size());
299 constexpr std::size_t oversample = 32;
300 const std::size_t num_samples = std::min(oversample, distinct.size());
301 std::vector<Coord3> sample;
303 sample.push_back(distinct[i * distinct.size() / num_samples]);
305 int sample_count =
static_cast<int>(sample.size());
306 std::vector<int> sample_counts(nprocs), sample_displs(nprocs, 0);
307 MPI_Allgather(&sample_count, 1, MPI_INT, sample_counts.data(), 1, MPI_INT, comm);
308 std::partial_sum(sample_counts.begin(), sample_counts.end() - 1, sample_displs.begin() + 1);
310 MPI_Datatype coord_type;
311 MPI_Type_contiguous(
sizeof(Coord3), MPI_BYTE, &coord_type);
312 MPI_Type_commit(&coord_type);
313 std::vector<Coord3> all_samples(
static_cast<std::size_t
>(sample_displs.back()) +
314 sample_counts.back());
315 MPI_Allgatherv(sample.data(),
319 sample_counts.data(),
320 sample_displs.data(),
323 MPI_Type_free(&coord_type);
324 std::sort(all_samples.begin(), all_samples.end());
326 std::vector<Coord3> splitters;
328 if (!all_samples.empty())
329 splitters.push_back(all_samples[(p + 1) * all_samples.size() / nprocs]);
330 auto bucketOf = [&](
const Coord3 & c)
332 return static_cast<int>(std::upper_bound(splitters.begin(), splitters.end(), c) -
337 std::vector<CoordQuery> outgoing(distinct.size());
339 outgoing[i] = {distinct[i], 0, rank,
static_cast<int>(i)};
341 std::vector<int> counts;
343 outgoing, nprocs, [&](
const CoordQuery & q) {
return bucketOf(q.coord); }, counts);
349 std::vector<Coord3> owned;
350 owned.reserve(received.size());
351 for (
const auto & q : received)
352 owned.push_back(q.coord);
353 std::sort(owned.begin(), owned.end());
354 owned.erase(std::unique(owned.begin(), owned.end()), owned.end());
356 std::int64_t owned_count =
static_cast<std::int64_t
>(owned.size()), offset = 0;
357 MPI_Exscan(&owned_count, &offset, 1, MPI_INT64_T, MPI_SUM, comm);
360 MPI_Allreduce(&owned_count, &numbering.num_global, 1, MPI_INT64_T, MPI_SUM, comm);
362 for (
auto & q : received)
363 q.id = offset + (
std::lower_bound(owned.begin(), owned.end(), q.coord) - owned.begin());
365 std::vector<int> answer_counts;
367 received, nprocs, [](
const CoordQuery & q) {
return q.origin_rank; }, answer_counts);
369 std::vector<std::int64_t> distinct_ids(distinct.size());
371 distinct_ids[q.origin_index] = q.id;
374 numbering.global_id.resize(coords.size());
376 numbering.global_id[i] = distinct_ids[numbering.local_index[i]];
391std::vector<CandidateEdge>
392filterLocalCycles(std::vector<CandidateEdge> candidates,
int num_local)
396 std::sort(candidates.begin(),
398 [](
const CandidateEdge & a,
const CandidateEdge & b)
399 { return (a.wu != b.wu) ? a.wu < b.wu : a.wv < b.wv; });
401 UnionFind uf(num_local);
402 std::vector<CandidateEdge> kept;
403 for (
const auto & c : candidates)
404 if (uf.join(c.lu, c.lv))
442buildTreeCotreeGaugeTDofs(mfem::ParFiniteElementSpace & pfes,
443 const mfem::Array<int> & essential_tdofs,
444 const mfem::Array<int> & excluded)
446 mfem::ParMesh & pmesh = *pfes.GetParMesh();
447 MPI_Comm comm = pmesh.GetComm();
449 MPI_Comm_size(comm, &nprocs);
450 MPI_Comm_rank(comm, &rank);
455 std::vector<char> is_essential_tdof(pfes.GetTrueVSize(), 0);
456 for (
const auto tdof : essential_tdofs)
457 is_essential_tdof[tdof] = 1;
458 auto allFixed = [&](
const mfem::Array<int> & ldofs)
460 return std::all_of(ldofs.begin(),
464 return is_essential_tdof[pfes.GetLocalTDofNumber(
465 mfem::FiniteElementSpace::DecodeDof(d))] != 0;
470 const mfem::FiniteElementCollection & nd_fec = *pfes.FEColl();
471 const int order = nd_fec.GetOrder();
472 const mfem::H1_FECollection h1_fec(order, pmesh.Dimension());
473 const auto edge_gauged = referenceGaugedDofs(nd_fec, h1_fec, mfem::Geometry::SEGMENT, order);
477 std::vector<OwnedEdge> owned_edges;
478 mfem::Array<int> ev, edge_ldofs;
479 for (
const auto e :
make_range(pmesh.GetNEdges()))
481 const int ldof = edgeLDof(pfes, e, edge_ldofs);
482 if (pfes.GetLocalTDofNumber(ldof) < 0)
485 pmesh.GetEdgeVertices(e, ev);
486 owned_edges.push_back({vertexCoord(pmesh, ev[0]),
487 vertexCoord(pmesh, ev[1]),
489 excluded[ldof] != 0 || allFixed(edge_ldofs)});
493 std::vector<Coord3> endpoints;
494 endpoints.reserve(2 * owned_edges.size());
495 for (
const auto & oe : owned_edges)
497 endpoints.push_back(oe.p0);
498 endpoints.push_back(oe.p1);
500 const auto numbering = canonicalVertexIds(endpoints, comm);
501 const std::int64_t num_vertices = numbering.num_global;
503 endpoints.shrink_to_fit();
505 std::vector<CandidateEdge> seed_edges, free_edges;
507 std::vector<int> free_mesh_edges;
510 const std::int64_t a = numbering.global_id[2 * i], b = numbering.global_id[2 * i + 1];
511 const int la = numbering.local_index[2 * i], lb = numbering.local_index[2 * i + 1];
513 const CandidateEdge c = (a < b) ? CandidateEdge{a, b, la, lb, owned_edges[i].mesh_edge}
514 : CandidateEdge{b, a, lb, la, owned_edges[i].mesh_edge};
515 (owned_edges[i].seed ? seed_edges : free_edges).push_back(c);
516 if (!owned_edges[i].seed)
517 free_mesh_edges.push_back(owned_edges[i].mesh_edge);
520 owned_edges.shrink_to_fit();
523 seed_edges = filterLocalCycles(std::move(seed_edges), numbering.num_local);
524 free_edges = filterLocalCycles(std::move(free_edges), numbering.num_local);
529 std::vector<Moose::MFEM::DistributedEdge> seed_graph(seed_edges.size());
531 seed_graph[i] = {seed_edges[i].wu,
536 static_cast<int>(i)};
538 std::vector<std::int64_t> seed_labels;
545 std::vector<std::int64_t> free_endpoints;
546 free_endpoints.reserve(2 * free_edges.size());
547 for (
const auto & c : free_edges)
549 free_endpoints.push_back(c.wu);
550 free_endpoints.push_back(c.wv);
552 const auto free_labels = num_vertices
554 :
std::vector<
std::int64_t>();
556 std::vector<Moose::MFEM::DistributedEdge> free_graph;
557 free_graph.reserve(free_edges.size());
559 free_graph.push_back({free_edges[i].wu,
562 free_labels[2 * i + 1],
564 static_cast<int>(i)});
566 std::vector<int> selected;
571 std::vector<char> in_forest(pmesh.GetNEdges(), 0);
572 for (
const auto index : selected)
573 in_forest[free_edges[index].mesh_edge] = 1;
575 mfem::Array<int> gauged_tdofs;
576 auto gauge = [&](
int ldof)
577 { gauged_tdofs.Append(pfes.GetLocalTDofNumber(mfem::FiniteElementSpace::DecodeDof(ldof))); };
583 for (
const auto e : free_mesh_edges)
585 pfes.GetEdgeDofs(e, edge_ldofs);
588 for (
const auto d : edge_ldofs)
592 pmesh.GetEdgeVertices(e, ev);
593 const bool reversed =
594 vertexCoord(pmesh, std::max(ev[0], ev[1])) < vertexCoord(pmesh, std::min(ev[0], ev[1]));
595 for (
const auto k : edge_gauged)
596 gauge(edge_ldofs[reversed ? edge_ldofs.Size() - 1 - k : k]);
602 const auto face_gauged = (pmesh.Dimension() == 3)
603 ? referenceGaugedDofs(nd_fec, h1_fec, mfem::Geometry::SQUARE, order)
604 : std::vector<int>();
605 if (!face_gauged.empty())
607 mfem::Array<int> face_ldofs, fv;
608 for (
const auto f :
make_range(pmesh.GetNFaces()))
610 if (pmesh.GetFaceGeometry(f) != mfem::Geometry::SQUARE)
612 pfes.GetFaceInteriorDofs(f, face_ldofs);
613 if (pfes.GetLocalTDofNumber(face_ldofs[0]) < 0 || excluded[face_ldofs[0]] ||
614 allFixed(face_ldofs))
617 pmesh.GetFaceVertices(f, fv);
619 const int * canonical_to_face = nd_fec.DofOrderForOrientation(
620 mfem::Geometry::SQUARE, canonicalQuadOrientation(pmesh, fv));
621 for (
const auto k : face_gauged)
622 gauge(face_ldofs[
mfem::FiniteElementSpace::DecodeDof(canonical_to_face[k])]);
629 std::array<std::vector<int>, mfem::Geometry::NumGeom> interior_gauged;
630 mfem::Array<mfem::Geometry::Type> element_geoms;
631 pmesh.GetGeometries(pmesh.Dimension(), element_geoms);
632 for (
const auto geom : element_geoms)
633 interior_gauged[geom] = referenceGaugedDofs(nd_fec, h1_fec, geom, order);
635 mfem::Array<int> interior_ldofs;
636 for (
const auto el :
make_range(pmesh.GetNE()))
638 const auto & gauged = interior_gauged[pmesh.GetElementGeometry(el)];
641 pfes.GetElementInteriorDofs(el, interior_ldofs);
642 if (excluded[interior_ldofs[0]] || allFixed(interior_ldofs))
644 for (
const auto k : gauged)
645 gauge(interior_ldofs[k]);
659const mfem::Array<int> &
661 mfem::ParFiniteElementSpace & pfes,
662 const mfem::Array<int> & essential_tdofs,
663 const mfem::Array<int> & gauge_block_markers)
665 mfem::ParMesh & pmesh = *pfes.GetParMesh();
670 if (!
dynamic_cast<const mfem::ND_FECollection *
>(pfes.FEColl()))
672 "The tree-cotree gauge requires an H(curl) (Nedelec) variable, but '",
674 "' uses the finite element collection '",
675 pfes.FEColl()->Name(),
684 int has_triangles = pmesh.Dimension() == 3 && pmesh.HasGeometry(mfem::Geometry::TRIANGLE);
685 MPI_Allreduce(MPI_IN_PLACE, &has_triangles, 1, MPI_INT, MPI_LOR, pmesh.GetComm());
686 if (pfes.GetMaxElementOrder() > 2 && has_triangles)
689 "The tree-cotree gauge supports H(curl) spaces above SECOND order only on meshes "
690 "without triangular faces, since the gauge on such a face could not be chosen "
691 "independently of the mesh partitioning; the space of variable '",
694 pfes.GetMaxElementOrder(),
700 if (pmesh.GetNodes() && pmesh.GetNodalFESpace()->IsDGSpace())
701 constraint.
mooseError(
"The tree-cotree gauge identifies mesh vertices by their coordinates, "
702 "which is not possible on a mesh with discontinuous nodes, such as a "
718 mfem::Array<int> excluded_markers(gauge_block_markers.Size());
719 for (
const auto i : make_range(gauge_block_markers.Size()))
720 excluded_markers[i] = !gauge_block_markers[i];
721 mfem::Array<int> excluded, excluded_tdofs;
723 pfes, excluded_markers,
true, excluded, excluded_tdofs);
725 _tdofs = buildTreeCotreeGaugeTDofs(pfes, essential_tdofs, excluded);
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
for(PetscInt i=0;i< nvars;++i)
if(!dmm->_nl) SETERRQ(PETSC_COMM_WORLD
Base class for objects constraining the value an MFEM variable may take within one or more mesh subdo...
virtual const std::string & getTrialVariableName() const
Name of the trial variable (gridfunction) the constraint acts on.
void paramError(const std::string ¶m, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type and optionally a file path to the top-level block p...
Block distribution of a dense global index range [0, n) over the ranks of a communicator: rank r owns...
mfem::Array< int > _essential_tdofs
Already-fixed true dofs _tdofs was built for.
long _fespace_sequence
FE space sequence number _tdofs was built for.
mfem::Array< int > _tdofs
Gauged true dofs of the most recent trueDofs() call.
const mfem::Array< int > & trueDofs(const MFEMConstraint &constraint, mfem::ParFiniteElementSpace &pfes, const mfem::Array< int > &essential_tdofs, const mfem::Array< int > &gauge_block_markers)
This rank's ND true-dof indices that the tree-cotree gauge must strongly set to zero,...
auto max(const L &left, const R &right)
KOKKOS_INLINE_FUNCTION const T * find(const T &target, const T *const begin, const T *const end)
Find a value in an array.
Utilities for converting between vector(s) of libMesh Points and MFEM Vector(s).
void subdomainTDofs(mfem::ParFiniteElementSpace &pfes, const mfem::Array< int > &subdomain_markers, bool include_boundary, mfem::Array< int > &ldof_marker, mfem::Array< int > &tdofs)
Degrees of freedom of pfes belonging to elements whose mesh attribute is set in the attribute marker ...
void distributedSpanningForest(std::vector< DistributedEdge > &edges, std::int64_t num_labels, MPI_Comm comm, std::vector< int > *selected, std::vector< std::int64_t > *owned_labels=nullptr)
Distributed Boruvka over the edges held collectively by the ranks of comm.
std::vector< std::int64_t > fetchLabels(const std::vector< std::int64_t > &queries, const std::vector< std::int64_t > &owned_labels, const BlockDistribution &dist, MPI_Comm comm)
Final component representative of each id in queries, looked up from the distributed label array.
std::vector< T > groupByDestination(const std::vector< T > &items, int nprocs, DestinationFn destination, std::vector< int > &counts)
Group items by the destination rank returned by destination, so they can be handed to allToAll.
std::vector< T > allToAll(const std::vector< T > &send, const std::vector< int > &send_counts, MPI_Comm comm)
MPI_Alltoallv over a trivially copyable payload.
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
auto index_range(const T &sizable)
IntRange< T > make_range(T beg, T end)