https://mooseframework.inl.gov
Loading...
Searching...
No Matches
MFEMTreeCotreeGauge.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#ifdef MOOSE_MFEM_ENABLED
11
12#include "MFEMTreeCotreeGauge.h"
14#include "MFEMConstraint.h"
15#include "MFEMConstraintUtils.h"
16#include "MooseError.h"
18
19#include <algorithm>
20#include <array>
21#include <cstdint>
22#include <numeric>
23#include <vector>
24
25namespace
26{
27
28// ---------------------------------------------------------------------
29// Minimal union-find (disjoint set) helper used to grow the spanning
30// forest. Operates on dense 0-based vertex ids.
31// ---------------------------------------------------------------------
32class UnionFind
33{
34public:
35 explicit UnionFind(int n);
36
37 int find(int x);
38
39 // Returns true if a and b were in different components, i.e. the edge
40 // between them closes no cycle and can join the spanning forest.
41 bool join(int a, int b);
42
43private:
44 std::vector<int> _parent, _rank;
45};
46
47UnionFind::UnionFind(int n) : _parent(n), _rank(n, 0)
48{
49 std::iota(_parent.begin(), _parent.end(), 0);
50}
51
52int
53UnionFind::find(int x)
54{
55 while (_parent[x] != x)
56 {
57 _parent[x] = _parent[_parent[x]];
58 x = _parent[x];
59 }
60 return x;
61}
62
63bool
64UnionFind::join(int a, int b)
65{
66 a = find(a);
67 b = find(b);
68 if (a == b)
69 return false;
70 if (_rank[a] < _rank[b])
71 std::swap(a, b);
72 _parent[b] = a;
73 if (_rank[a] == _rank[b])
74 _rank[a]++;
75 return true;
76}
77
78// A vertex location, used as a partition-independent vertex identity.
79using Coord3 = std::array<mfem::real_t, 3>;
80
81// First dof of parallel mesh edge e, sign-decoded; the edge's dofs are left in
82// ldofs. Called once per mesh edge in each pass below, so the caller supplies the
83// dof scratch space rather than having it reallocated for every edge.
84int
85edgeLDof(mfem::ParFiniteElementSpace & pfes, int e, mfem::Array<int> & ldofs)
86{
87 pfes.GetEdgeDofs(e, ldofs);
88 return mfem::FiniteElementSpace::DecodeDof(ldofs[0]);
89}
90
91Coord3
92vertexCoord(const mfem::ParMesh & pmesh, int v)
93{
94 // GetNode rather than GetVertex: on a curved (higher order geometry) mesh the
95 // authoritative coordinates live in the mesh Nodes grid function, and the
96 // vertices array is rebuilt per rank during partitioning, so its values are not
97 // bit-identical between ranks that share a vertex. Keying on it there would give
98 // one vertex several identities and a partition-dependent forest. GetNode reads
99 // the Nodes grid function when the mesh is curved and falls back to the vertices
100 // array when it is not. Indexing Nodes by vertex number relies on the vertex dofs
101 // of a continuous (H1) nodal space being numbered first; TreeCotreeGauge::trueDofs
102 // rejects discontinuous nodal spaces. Only spaceDim components are written, so the
103 // unused trailing components keep the zero they are initialised with.
104 Coord3 p{0.0, 0.0, 0.0};
105 pmesh.GetNode(v, p.data());
106 return p;
107}
108
109// ---------------------------------------------------------------------
110// The gradient of an order p H1 function that vanishes on the boundary of a
111// mesh entity (an edge, face or element "bubble") has no tangential trace on
112// that boundary, so its ND interpolant lives entirely in the ND dofs that belong
113// to the entity itself. This selects, on the reference entity, as many of those
114// dofs as there are H1 bubbles, such that the discrete gradient restricted to the
115// selected dofs and the bubbles is nonsingular: zero values on the selected dofs
116// then admit no bubble gradient but zero.
117//
118// Rows of the discrete gradient block are chosen greedily by Gram-Schmidt with
119// pivoting on the residual norm. Returns the indices of the selected dofs among
120// the entity's own ND dofs, in ascending order; empty when the entity carries no
121// H1 bubbles.
122// ---------------------------------------------------------------------
123std::vector<int>
124referenceGaugedDofs(const mfem::FiniteElementCollection & nd_fec,
125 const mfem::FiniteElementCollection & h1_fec,
126 mfem::Geometry::Type geom,
127 int order)
128{
129 const int num_bubbles = h1_fec.GetNumDof(geom, order);
130 std::vector<int> selected;
131 if (num_bubbles == 0)
132 return selected;
133
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);
140
141 // An entity's own dofs come last in MFEM's reference dof ordering, after those
142 // of its vertices, edges and faces.
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));
146 for (const auto r : make_range(num_rows))
147 for (const auto c : make_range(num_bubbles))
148 rows[r](c) = grad(row0 + r, col0 + c);
149
150 // Symmetric reference elements produce rows whose residuals are equal in exact
151 // arithmetic. Treating residuals within this relative tolerance as tied, and
152 // taking the first of them, keeps the selection from depending on roundoff; it
153 // is far above the roundoff of the few Gram-Schmidt steps involved and far below
154 // any genuine difference between residuals. (residuals = Gram-Schmidt remainders)
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)
158 {
159 mfem::real_t max_norm = 0;
160 for (const auto r : make_range(num_rows))
161 if (available[r])
162 max_norm = std::max(max_norm, rows[r].Norml2());
163
164 int pick = 0;
165 while (!available[pick] || rows[pick].Norml2() < (1 - tie_tolerance) * max_norm)
166 ++pick;
167 available[pick] = false;
168 selected.push_back(pick);
169
170 rows[pick] /= rows[pick].Norml2();
171 for (const auto r : make_range(num_rows))
172 if (available[r])
173 rows[r].Add(-(rows[r] * rows[pick]), rows[pick]);
174 }
175
176 std::sort(selected.begin(), selected.end());
177 return selected;
178}
179
180// MFEM orientation, in the sense of Mesh::GetQuadOrientation, of a frame for
181// quadrilateral face f fixed by its vertex coordinates alone: it starts at the
182// lexicographically lowest vertex and heads to the lower of that vertex's two
183// neighbours. The face's own vertex ordering, fv, comes from the local face
184// numbering and can differ between partitions; this frame cannot.
185int
186canonicalQuadOrientation(const mfem::ParMesh & pmesh, const mfem::Array<int> & fv)
187{
188 std::array<Coord3, 4> coords;
189 for (const auto i : make_range(4))
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;
194 for (const auto i : make_range(4))
195 canonical[i] = fv[(first + i * step) % 4];
196
197 // Mesh::GetQuadOrientation(base, test) is protected. It returns the entry o of
198 // the orientation table for which test[Orient[o][j]] == base[j] for every j.
199 using Square = mfem::Geometry::Constants<mfem::Geometry::SQUARE>;
200 for (const auto o : make_range(Square::NumOrient))
201 {
202 std::array<int, 4> permuted;
203 for (const auto j : make_range(4))
204 permuted[j] = canonical[Square::Orient[o][j]];
205 if (std::equal(permuted.begin(), permuted.end(), fv.begin()))
206 return o;
207 }
208 mooseError("No orientation maps the canonical frame of a quadrilateral face onto its vertices.");
209}
210
211// One of this rank's owned mesh edges, keyed on its endpoint coordinates.
212struct OwnedEdge
213{
214 Coord3 p0, p1;
216 int mesh_edge;
218 bool seed;
219};
220
221// A candidate edge once its endpoints carry canonical global vertex ids.
222struct CandidateEdge
223{
225 std::int64_t wu, wv;
228 int lu, lv;
229 int mesh_edge;
230};
231
232// Round-trip record for looking up the canonical id of a coordinate.
233struct CoordQuery
234{
235 Coord3 coord;
236 std::int64_t id;
237 int origin_rank, origin_index;
238};
239
240// Canonical numbering of the vertex coordinates handed to canonicalVertexIds.
241struct VertexNumbering
242{
244 std::vector<std::int64_t> global_id;
247 std::vector<int> local_index;
248 int num_local = 0;
249 std::int64_t num_global = 0;
250};
251
252// ---------------------------------------------------------------------
253// Assign every distinct endpoint coordinate in the mesh a dense global id
254// in the canonical (lexicographically sorted) order of the whole coordinate
255// set. That order is a property of the set alone, so the ids - and hence the
256// spanning forest built from them - are the same however the mesh is
257// partitioned, without any rank ever holding the whole set.
258//
259// The coordinates come from the mesh nodes (see vertexCoord), which are
260// bit-identical on every rank sharing a vertex and so give a
261// partition-independent vertex identity.
262// ---------------------------------------------------------------------
263VertexNumbering
264canonicalVertexIds(const std::vector<Coord3> & coords, MPI_Comm comm)
265{
266 int nprocs, rank;
267 MPI_Comm_size(comm, &nprocs);
268 MPI_Comm_rank(comm, &rank);
269
270 VertexNumbering numbering;
271
272 // Sorting (coordinate, input position) once yields both the distinct list and
273 // the mapping from every input coordinate onto it, so no coordinate ever has to
274 // be looked up by binary search afterwards.
275 std::vector<std::pair<Coord3, int>> sorted(coords.size());
276 for (const auto i : index_range(coords))
277 sorted[i] = {coords[i], static_cast<int>(i)};
278 std::sort(sorted.begin(), sorted.end());
279
280 std::vector<Coord3> distinct;
281 numbering.local_index.resize(coords.size());
282 for (const auto & [coord, position] : sorted)
283 {
284 if (distinct.empty() || distinct.back() != coord)
285 distinct.push_back(coord);
286 numbering.local_index[position] = static_cast<int>(distinct.size()) - 1;
287 }
288 sorted.clear();
289 sorted.shrink_to_fit();
290 numbering.num_local = static_cast<int>(distinct.size());
291
292 // Splitters that cut the globally sorted coordinate order into one bucket per
293 // rank. Every rank derives them from the same gathered sample, so they agree.
294 // Their exact placement only affects load balance: the ids below come from the
295 // global sorted position, which no choice of splitters can change. The number
296 // of samples per rank trades bucket balance against the size of the sample every
297 // rank gathers (oversample * nprocs coordinates); 32 keeps that gather small
298 // while giving each splitter a few dozen candidates to be chosen from.
299 constexpr std::size_t oversample = 32;
300 const std::size_t num_samples = std::min(oversample, distinct.size());
301 std::vector<Coord3> sample;
302 for (const auto i : make_range(num_samples))
303 sample.push_back(distinct[i * distinct.size() / num_samples]);
304
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);
309
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(),
316 sample_count,
317 coord_type,
318 all_samples.data(),
319 sample_counts.data(),
320 sample_displs.data(),
321 coord_type,
322 comm);
323 MPI_Type_free(&coord_type);
324 std::sort(all_samples.begin(), all_samples.end());
325
326 std::vector<Coord3> splitters;
327 for (const auto p : make_range(nprocs - 1))
328 if (!all_samples.empty())
329 splitters.push_back(all_samples[(p + 1) * all_samples.size() / nprocs]);
330 auto bucketOf = [&](const Coord3 & c)
331 {
332 return static_cast<int>(std::upper_bound(splitters.begin(), splitters.end(), c) -
333 splitters.begin());
334 };
335
336 // Send each distinct local coordinate to the rank owning its bucket.
337 std::vector<CoordQuery> outgoing(distinct.size());
338 for (const auto i : index_range(distinct))
339 outgoing[i] = {distinct[i], 0, rank, static_cast<int>(i)};
340
341 std::vector<int> counts;
342 const auto grouped = Moose::MFEM::groupByDestination(
343 outgoing, nprocs, [&](const CoordQuery & q) { return bucketOf(q.coord); }, counts);
344 auto received = Moose::MFEM::allToAll(grouped, counts, comm);
345
346 // The distinct coordinates of this bucket, in order, are a contiguous slice of
347 // the global canonical order; an exclusive scan of the slice sizes gives its
348 // starting id.
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());
355
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);
358 if (rank == 0)
359 offset = 0;
360 MPI_Allreduce(&owned_count, &numbering.num_global, 1, MPI_INT64_T, MPI_SUM, comm);
361
362 for (auto & q : received)
363 q.id = offset + (std::lower_bound(owned.begin(), owned.end(), q.coord) - owned.begin());
364
365 std::vector<int> answer_counts;
366 const auto answers = Moose::MFEM::groupByDestination(
367 received, nprocs, [](const CoordQuery & q) { return q.origin_rank; }, answer_counts);
368
369 std::vector<std::int64_t> distinct_ids(distinct.size());
370 for (const auto & q : Moose::MFEM::allToAll(answers, answer_counts, comm))
371 distinct_ids[q.origin_index] = q.id;
372
373 // Spread the distinct ids back over the caller's coordinate list.
374 numbering.global_id.resize(coords.size());
375 for (const auto i : index_range(coords))
376 numbering.global_id[i] = distinct_ids[numbering.local_index[i]];
377 return numbering;
378}
379
380// ---------------------------------------------------------------------
381// Discard edges that close a cycle among this rank's own edges. By the cycle
382// property such an edge is the heaviest on that cycle, so it cannot belong to
383// the minimum spanning forest of the whole graph either, and dropping it here
384// keeps it out of every subsequent communication round. Contracting the seed
385// components later can only shorten those cycles, never break them, so the
386// filter stays valid for the contracted graph too.
387//
388// Returns the surviving edges; @p num_local is the number of distinct vertices in
389// this rank's dense local numbering.
390// ---------------------------------------------------------------------
391std::vector<CandidateEdge>
392filterLocalCycles(std::vector<CandidateEdge> candidates, int num_local)
393{
394 // Kruskal in the canonical edge order, so the survivors are exactly those a
395 // serial pass would still have to consider.
396 std::sort(candidates.begin(),
397 candidates.end(),
398 [](const CandidateEdge & a, const CandidateEdge & b)
399 { return (a.wu != b.wu) ? a.wu < b.wu : a.wv < b.wv; });
400
401 UnionFind uf(num_local);
402 std::vector<CandidateEdge> kept;
403 for (const auto & c : candidates)
404 if (uf.join(c.lu, c.lv))
405 kept.push_back(c);
406 return kept;
407}
408
409// ---------------------------------------------------------------------
410// Build the interior tree-cotree gauge as a list of this rank's ND true
411// dofs that must be strongly set to zero, in addition to those already
412// fixed by essential boundary conditions or other essential constraints.
413//
414// The gradient null space of an order p ND space is the gradient of the order
415// p H1 space, whose dofs sit on vertices and on the interiors of edges, faces
416// and elements. The gauge removes it one entity dimension at a time. Fixing
417// every dof of each edge of a spanning forest makes the potential constant
418// along the forest, so it vanishes at every vertex. Fixing, on every free edge,
419// face and element, a selection of its own dofs on which the gradients of the
420// H1 bubbles there are linearly independent then leaves no bubble gradient
421// either (see referenceGaugedDofs). With an order 1 space only the forest edges
422// carry fixed dofs.
423//
424// The forest is grown with a distributed Boruvka pass over the mesh
425// 1-skeleton: no rank ever holds more than its own share of the edges. Edges
426// are ordered by their canonical global endpoint ids, and because that order
427// is a total order on distinct weights the minimum spanning forest is unique.
428// The dofs selected on each edge and face are chosen in a frame fixed by the
429// vertex coordinates, and element interiors keep the element's vertex ordering
430// under partitioning. The gauge - and hence the solution - therefore does not
431// depend on the number of MPI ranks or on how the mesh was partitioned.
432//
433// pfes - the ND space being solved on
434// essential_tdofs - true dofs already fixed by other essential conditions;
435// edges whose dofs are all fixed seed the forest, and no
436// entity whose dofs are all fixed is gauged
437// excluded - local dof marker of dofs the gauge must not touch;
438// their edges seed the forest like the fixed edges, and no
439// edge, face or element carrying them is gauged
440// ---------------------------------------------------------------------
441mfem::Array<int>
442buildTreeCotreeGaugeTDofs(mfem::ParFiniteElementSpace & pfes,
443 const mfem::Array<int> & essential_tdofs,
444 const mfem::Array<int> & excluded)
445{
446 mfem::ParMesh & pmesh = *pfes.GetParMesh();
447 MPI_Comm comm = pmesh.GetComm();
448 int nprocs, rank;
449 MPI_Comm_size(comm, &nprocs);
450 MPI_Comm_rank(comm, &rank);
451
452 // Dofs already fixed by other essential conditions. Only owned entities are
453 // considered below, and all dofs of an owned entity are owned by this rank, so
454 // marking this rank's true dofs is enough.
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)
459 {
460 return std::all_of(ldofs.begin(),
461 ldofs.end(),
462 [&](int d)
463 {
464 return is_essential_tdof[pfes.GetLocalTDofNumber(
465 mfem::FiniteElementSpace::DecodeDof(d))] != 0;
466 });
467 };
468
469 // The dofs on each reference entity that remove the gradients of its H1 bubbles.
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);
474
475 // 1. This rank's owned edges. Each mesh edge is owned by exactly one rank, so
476 // the union over ranks is the mesh 1-skeleton with no duplicates.
477 std::vector<OwnedEdge> owned_edges;
478 mfem::Array<int> ev, edge_ldofs;
479 for (const auto e : make_range(pmesh.GetNEdges()))
480 {
481 const int ldof = edgeLDof(pfes, e, edge_ldofs);
482 if (pfes.GetLocalTDofNumber(ldof) < 0)
483 continue; // owned by another rank; it will contribute this edge
484
485 pmesh.GetEdgeVertices(e, ev);
486 owned_edges.push_back({vertexCoord(pmesh, ev[0]),
487 vertexCoord(pmesh, ev[1]),
488 e,
489 excluded[ldof] != 0 || allFixed(edge_ldofs)});
490 }
491
492 // 2. Canonical global vertex ids for both endpoints of every owned edge.
493 std::vector<Coord3> endpoints;
494 endpoints.reserve(2 * owned_edges.size());
495 for (const auto & oe : owned_edges)
496 {
497 endpoints.push_back(oe.p0);
498 endpoints.push_back(oe.p1);
499 }
500 const auto numbering = canonicalVertexIds(endpoints, comm);
501 const std::int64_t num_vertices = numbering.num_global;
502 endpoints.clear();
503 endpoints.shrink_to_fit();
504
505 std::vector<CandidateEdge> seed_edges, free_edges;
506 // Every free edge is gauged, including those filtered out below.
507 std::vector<int> free_mesh_edges;
508 for (const auto i : index_range(owned_edges))
509 {
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];
512 // Order both representations of the endpoints the same way.
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);
518 }
519 owned_edges.clear();
520 owned_edges.shrink_to_fit();
521
522 // 3. Drop locally redundant edges before any communication.
523 seed_edges = filterLocalCycles(std::move(seed_edges), numbering.num_local);
524 free_edges = filterLocalCycles(std::move(free_edges), numbering.num_local);
525
526 // 4. Ground the seeded regions: the connected components of the essential
527 // boundary and of the excluded subdomains, which are fixed without being
528 // gauged.
529 std::vector<Moose::MFEM::DistributedEdge> seed_graph(seed_edges.size());
530 for (const auto i : index_range(seed_edges))
531 seed_graph[i] = {seed_edges[i].wu,
532 seed_edges[i].wv,
533 seed_edges[i].wu,
534 seed_edges[i].wv,
535 rank,
536 static_cast<int>(i)};
537
538 std::vector<std::int64_t> seed_labels;
539 Moose::MFEM::distributedSpanningForest(seed_graph, num_vertices, comm, nullptr, &seed_labels);
540
541 // 5. Spanning forest of the remaining edges over the contracted seed
542 // components. An edge whose endpoints already share a component closes a
543 // cycle and is left out of the forest (a cotree edge).
544 const Moose::MFEM::BlockDistribution dist(num_vertices, nprocs);
545 std::vector<std::int64_t> free_endpoints;
546 free_endpoints.reserve(2 * free_edges.size());
547 for (const auto & c : free_edges)
548 {
549 free_endpoints.push_back(c.wu);
550 free_endpoints.push_back(c.wv);
551 }
552 const auto free_labels = num_vertices
553 ? Moose::MFEM::fetchLabels(free_endpoints, seed_labels, dist, comm)
554 : std::vector<std::int64_t>();
555
556 std::vector<Moose::MFEM::DistributedEdge> free_graph;
557 free_graph.reserve(free_edges.size());
558 for (const auto i : index_range(free_edges))
559 free_graph.push_back({free_edges[i].wu,
560 free_edges[i].wv,
561 free_labels[2 * i],
562 free_labels[2 * i + 1],
563 rank,
564 static_cast<int>(i)});
565
566 std::vector<int> selected;
567 Moose::MFEM::distributedSpanningForest(free_graph, num_vertices, comm, &selected);
568
569 // Every selected edge is owned by this rank. An edge chosen by the components at
570 // both of its ends is reported twice, which marking absorbs.
571 std::vector<char> in_forest(pmesh.GetNEdges(), 0);
572 for (const auto index : selected)
573 in_forest[free_edges[index].mesh_edge] = 1;
574
575 mfem::Array<int> gauged_tdofs;
576 auto gauge = [&](int ldof)
577 { gauged_tdofs.Append(pfes.GetLocalTDofNumber(mfem::FiniteElementSpace::DecodeDof(ldof))); };
578
579 // 6. Fix every dof of a forest edge, and the bubble-removing dofs of any other
580 // free edge. MFEM orders the dofs of an edge from its lower-numbered local
581 // vertex; the selection is made from the edge's lexicographically lower
582 // endpoint instead, so it does not depend on the local numbering.
583 for (const auto e : free_mesh_edges)
584 {
585 pfes.GetEdgeDofs(e, edge_ldofs);
586 if (in_forest[e])
587 {
588 for (const auto d : edge_ldofs)
589 gauge(d);
590 continue;
591 }
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]);
597 }
598
599 // 7. Fix the bubble-removing dofs of every owned free face of a 3D mesh, chosen
600 // in the frame of canonicalQuadOrientation. Triangular faces carry no bubbles
601 // at the orders TreeCotreeGauge::trueDofs accepts.
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())
606 {
607 mfem::Array<int> face_ldofs, fv;
608 for (const auto f : make_range(pmesh.GetNFaces()))
609 {
610 if (pmesh.GetFaceGeometry(f) != mfem::Geometry::SQUARE)
611 continue;
612 pfes.GetFaceInteriorDofs(f, face_ldofs);
613 if (pfes.GetLocalTDofNumber(face_ldofs[0]) < 0 || excluded[face_ldofs[0]] ||
614 allFixed(face_ldofs))
615 continue;
616
617 pmesh.GetFaceVertices(f, fv);
618 // Maps each dof of the canonical frame onto the face's own dofs.
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])]);
623 }
624 }
625
626 // 8. Fix the bubble-removing dofs of every free element. Element interior dofs
627 // are never shared, and their frame is the element's vertex ordering, which
628 // partitioning preserves.
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);
634
635 mfem::Array<int> interior_ldofs;
636 for (const auto el : make_range(pmesh.GetNE()))
637 {
638 const auto & gauged = interior_gauged[pmesh.GetElementGeometry(el)];
639 if (gauged.empty())
640 continue;
641 pfes.GetElementInteriorDofs(el, interior_ldofs);
642 if (excluded[interior_ldofs[0]] || allFixed(interior_ldofs))
643 continue;
644 for (const auto k : gauged)
645 gauge(interior_ldofs[k]);
646 }
647
648 // Keep the ascending tdof order the caller's elimination path expects.
649 gauged_tdofs.Sort();
650
651 return gauged_tdofs;
652}
653
654} // namespace
655
656namespace Moose::MFEM
657{
658
659const mfem::Array<int> &
661 mfem::ParFiniteElementSpace & pfes,
662 const mfem::Array<int> & essential_tdofs,
663 const mfem::Array<int> & gauge_block_markers)
664{
665 mfem::ParMesh & pmesh = *pfes.GetParMesh();
666
667 // The graph is built from the mesh edges and the lowest-order dof on each, which
668 // is only meaningful for a Nedelec space: an H1 space would hand back vertex dofs
669 // and an RT space none at all.
670 if (!dynamic_cast<const mfem::ND_FECollection *>(pfes.FEColl()))
671 constraint.paramError("variable",
672 "The tree-cotree gauge requires an H(curl) (Nedelec) variable, but '",
673 constraint.getTrialVariableName(),
674 "' uses the finite element collection '",
675 pfes.FEColl()->Name(),
676 "'.");
677
678 // From THIRD order on, a triangular face carries H1 bubbles whose gradients the
679 // gauge must remove with a selection of the face's dofs. MFEM relates the dofs of
680 // a triangular face in different frames by a 2x2 transformation per point, not a
681 // permutation, so no selection is the same in every frame, and the frame of a
682 // shared face depends on the partitioning. Checked on every rank, since only some
683 // ranks may hold such faces.
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)
687 constraint.paramError(
688 "variable",
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 '",
692 constraint.getTrialVariableName(),
693 "' is order ",
694 pfes.GetMaxElementOrder(),
695 ".");
696
697 // Vertices are identified by their coordinates, read from the mesh nodes. A
698 // discontinuous nodal space, as carried by a periodic mesh, has no single node per
699 // vertex, and periodically identified vertices have no single coordinate.
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 "
703 "periodic mesh.");
704
705 // The gauge is a property of the mesh, the space and the dofs already fixed
706 // alone, so it only has to be rebuilt when one of them changes. Rebuilding it
707 // every time the linear forms are assembled would repeat a global graph
708 // computation on every time step.
709 if (_fespace_sequence == pfes.GetSequence() && _essential_tdofs == essential_tdofs)
710 return _tdofs;
711
712 // Local dof marker of the dofs of every element outside the gauged subdomains, the
713 // regions the gauge must not reach because some other term of the weak form already
714 // removes the gradient null space there. Edges carrying such dofs seed the spanning
715 // forest, and no dof of such an edge, face or element is ever gauged. The boundary
716 // of these regions is included, but dofs of a gauged region that merely touch them
717 // are not, so the gauge still reaches the vertices next to them.
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, /*include_boundary=*/true, excluded, excluded_tdofs);
724
725 _tdofs = buildTreeCotreeGaugeTDofs(pfes, essential_tdofs, excluded);
726
727 _fespace_sequence = pfes.GetSequence();
728 _essential_tdofs = essential_tdofs;
729 return _tdofs;
730}
731}
732
733#endif
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
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 &param, Args... args) const
Emits an error prefixed with the file and line number of the given param (from the input file) along ...
Definition MooseBase.h:466
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...
Definition MooseBase.h:271
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.
Definition KokkosUtils.h:40
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)