Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
0cd2196
fix(mmpde): per-cell collapse floor — mover was a silent no-op on gra…
lmoresi Jul 25, 2026
73a7cb1
feat(meshing): mesh.relax() — shape relaxation in the ideal reference…
lmoresi Jul 25, 2026
c7a3ec9
docs(relax): 3D improves QUALITY not error — correct the earlier 'was…
lmoresi Jul 25, 2026
4874f7c
feat(adapt): relax= takes a placement — True (at end, default) or per…
lmoresi Jul 26, 2026
d77106b
test+docs(relax): cover both relax hooks, document the frame trade-of…
lmoresi Jul 26, 2026
9f8eedd
docs(relax): correct the "MG is unaffected" claim — 3D can fail the c…
lmoresi Jul 26, 2026
5359890
fix(custom-mg): retry with the global-support RBF builder before drop…
lmoresi Jul 26, 2026
39ce202
docs(design): two MG transfer paths — use the nested hierarchy we alr…
lmoresi Jul 26, 2026
e24ad0e
feat(adapt): record the EXACT nested MG prolongation per refinement p…
lmoresi Jul 26, 2026
b4d3f0d
fix(custom-mg): repair orphaned coarse DOFs in place, keeping the tra…
lmoresi Jul 26, 2026
7535df2
feat(custom-mg): use the EXACT nested transfer for degree-1 fields (#…
lmoresi Jul 26, 2026
e7d08f6
docs(custom-mg): correct the "FE-exact" claim on the barycentric buil…
lmoresi Jul 26, 2026
ef79f31
refactor(adapt): remove scipy from the nested path — exact identifica…
lmoresi Jul 27, 2026
e5da5a6
refactor(nvb): drop scipy from to_dm — exact coordinate lookup, not a…
lmoresi Jul 27, 2026
fb1a93c
fix(adapt): restore round-2 composition — it was correct; the REFEREN…
lmoresi Jul 27, 2026
380afcb
chore: align the duplicated floor fix with #420 and make the dense fa…
lmoresi Jul 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions docs/developer/design/nested-vs-geometric-mg-transfers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Two MG transfer paths, each used properly

**Status**: PROPOSED (2026-07-26)

## The problem

`mesh.adapt()` maintains an exact refinement hierarchy — that is the entire
point of newest-vertex bisection with conforming closure, and it is what the
"escape"/halo cost buys. The multigrid transfer then **throws that hierarchy
away** and re-derives an approximation to it geometrically:

```python
def barycentric_prolongation(coarse_coords, fine_coords):
tri = Delaunay(coarse_coords) # re-triangulate the coarse DOF CLOUD
simp = tri.find_simplex(fine_coords) # locate each fine DOF in one simplex
```

The coarse mesh's own cells are discarded; the parent/child relation is never
consulted. We pay for exact hierarchy maintenance and then do not use it.

This is not merely inelegant — it is the direct cause of issue #424. The
barycentric builder has only **local support**: a coarse DOF is reached only if
some fine DOF happens to land in a Delaunay simplex touching it. Move the fine
coordinates — `mesh.relax()`, surface snapping, free-surface deformation — and
a coarse DOF can lose every fine image. Its column in `P` goes to zero,
`PᵀAP` acquires a zero row and column, and the coarse operator is singular.

## Why the geometric builder exists (and should stay)

It was built for genuinely **non-nested** pairs, where no topological relation
exists at all:

* a moved base mesh against an adapted child,
* two independently generated meshes,
* the planned non-hierarchical variant with newly added seed points.

That capability was asked for and is worth keeping. The error was applying it
to the *nested* case as well, where the exact answer is already known.

## The nested transfer is trivial and cannot go singular

For a bisection hierarchy every fine vertex is exactly one of two things:

* an **inherited** coarse vertex → weight 1 on itself;
* the **midpoint of a coarse edge** `(a, b)` → weights ½, ½ on `a` and `b`.

Properties that matter:

* **Exact** for the un-deformed nested mesh (it *is* the FE embedding).
* **Structurally full rank** — every coarse DOF appears with weight 1 in its
own inherited fine DOF, so a zero column is *impossible by construction*.
#424 cannot occur in this formulation.
* **Immune to node motion.** The relation is topological, so relaxation,
snapping and deformation do not disturb it.
* **Cheap** — 1 or 2 non-zeros per fine row, no Delaunay, no point location.

The engines already record exactly this. `nvb.py` keeps

```python
self.edge2mid = {} # (a, b) -> midpoint vertex id
```

for both the 2D `NVBMesh` and the 3D `TaggedBisectionMesh`, and the native
`nvb_transform.c` is a real `DMPlexTransform`, whose split-edge bookkeeping
carries the same information.

Note also that `petsc_dm_set_regular_refinement` — our own wrapper for the flag
PETSc checks to take its exact nested interpolation path — appears exactly once
in the repository: its own definition. Nothing calls it.

## The one hard part: *when* the relation can be captured

The relation must be recorded in **DM point numbering**, and the bridge from
engine-internal vertex ids to DM points is coordinate matching (this is how
`to_dm` already transfers labels). Coordinate matching is exact only while
midpoints are still exact float averages of their parents.

Both snapping and relaxation destroy that:

* **native path** — `_nvbx.refine()` produces the DM, *then*
`snap_level_boundaries()` moves boundary vertices. There is a clean window
between the two where coordinates are pristine.
* **cell-list path** — the snap is applied to `nvb.coords` *before* `to_dm()`
is called, so by the time a DM exists the window has closed.

So the capture must be designed in, not bolted on:

1. capture the parent/child map immediately after refinement, **before** any
snap or relaxation, and store it on the child;
2. or have `to_dm()` return its engine-id → DM-point map directly, removing the
dependence on coordinate matching altogether (preferable — it is exact
regardless of ordering).

Option 2 is the more robust and is the recommended route.

## Proposed shape

* Each generation stores a sparse vertex-level prolongation on the child, e.g.
`child._adapt_prolongation[k] = (parents, weights)` with `parents` of shape
`(n_fine, 2)` in DM vertex numbering (an inherited vertex is `(c, c)` with
weights `(1, 0)`).
* `custom_mg` gains a `"topological"` builder that consumes it and expands from
vertices to DOFs for the field's basis.
* Selection: **topological when the map is present** (nested adapt hierarchy),
geometric otherwise. The RBF retry added for #424 then becomes a fallback
that should essentially never fire on adapt children.

## Caveat worth measuring, not assuming

With snap-every-generation a midpoint is moved onto a curved boundary, so it is
no longer at ½(a+b) physically. The ½,½ transfer is then not the FE-exact
interpolation of the coarse space at that point — the geometric builder is.

Multigrid does not require FE-exactness, only a full-rank prolongation that
represents smooth functions well, and ½,½ on the topological hierarchy is the
classical geometric-MG choice. But on strongly curved or strongly relaxed
meshes the geometric transfer may be the more *accurate* one. The trade is
**accuracy versus robustness**, and it should be measured on the annulus and
spherical-shell cases before the default is settled — not assumed either way.

## Related

* #424 — zero-column failure and the RBF retry (the symptom this addresses).
* `custom_mg.py` — `barycentric_prolongation`, `rbf_prolongation`,
`CustomMGHierarchy`.
* `nvb.py` — `edge2mid` in `NVBMesh` and `TaggedBisectionMesh`.
* `petsc_discretisation.pyx` — `petsc_dm_set_regular_refinement` (uncalled).
1 change: 1 addition & 0 deletions docs/developer/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ CHANGELOG
:caption: Subsystems

subsystems/meshing
subsystems/mesh-shape-relaxation
subsystems/discretisation
subsystems/solvers
subsystems/boundary-stress-and-projection-postprocessing
Expand Down
184 changes: 184 additions & 0 deletions docs/developer/subsystems/mesh-shape-relaxation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# Mesh shape relaxation

Refinement chooses where new nodes go from **combinatorics**, never from
geometry: newest-vertex bisection puts the node on whichever edge the tagging
rule nominated, centroid (Alfeld) refinement puts it at the cell centre. Neither
rule knows anything about the problem being solved. A refined mesh therefore
carries needles and slivers that reflect the base mesh's arbitrary choices —
elements organised around the base grid's axes rather than around the feature
you refined towards.

**Relaxation** moves those nodes to where the geometry wants them, keeping the
resolution the refinement installed:

```python
child = mesh.adapt(metric, max_levels=3)
child.relax()
```

or, in one call:

```python
child = mesh.adapt(metric, max_levels=3, relax=True)
```

## Why the mover could not already do this

The obvious tool was the MMPDE mover (`mesh.redistribute_nodes`), and it moved
*nothing*: `redistribute_nodes(1)` on a distorted mesh is exactly a no-op.

The reason is the mover's **reference frame**, not its metric. MMPDE generates
the physical mesh as the image of a fixed *computational* mesh, and that
reference is set to the mesh's own coordinates on the first call. "Distortion"
therefore means *deviation from the mesh I was handed* — so a sliver-ridden mesh
is its own optimum, and under a uniform metric the identity map already
minimises the functional.

Relaxation swaps the reference for a **regular simplex**. Distortion now means
*deviation from equilateral in the metric*, so the distortion a mesh arrived
with is no longer self-justifying. Everything else is unchanged: same
functional, same non-folding guarantee, same parallel assembly. (This is the
target-matrix idea from the TMOP literature.)

Three frames exist on the mover's `reference=` argument:

| `reference` | reference element | what it does |
|---|---|---|
| `"mesh"` | the mesh at first call | **redistribution** — the classical MMPDE. Default. |
| `"ideal"` | regular simplex at *each cell's own* volume | **shape repair at fixed size**. `r = 1` at entry, so the size term starts at its optimum and only shape moves. |
| `"ideal-metric"` | regular simplex at one uniform volume | shape repair **plus** re-grading; the metric sets size. |

`mesh.relax()` selects `"ideal"`; `mesh.relax(metric)` selects `"ideal-metric"`.

## Relaxing is not the same as relaxing to a metric

```{warning}
Passing a metric to `relax()` changes what is being optimised. The
ideal-metric frame re-grades as well as reshapes, and it will **trade element
shape away** to chase the size field. Measured on a 4-level graded box, the
99th-percentile maximum angle went 117.9° → 113.8° with no metric, but
117.9° → **127.4°** with one.
```

Use `relax()` when you want a shape guarantee. Use `relax(metric)` when the
sizes themselves are wrong and you accept shape is no longer the objective.

## Where to put the relaxation

Two placements, and **neither dominates** — which you prefer depends on which
property you weight:

```python
adapt(metric, max_levels=N, relax=True) # once, at the end (default)
adapt(metric, max_levels=N, relax="per-generation") # inside the refinement loop
```

Measured in 2D on a gmsh base with the NVB refiner, a dipping fault segment:

| property | unrelaxed | at end | per generation |
|---|---|---|---|
| P1 interpolation error | 2.75e-2 | 2.56e-2 | **2.38e-2** |
| 99th pct max angle | 112° | 110° | **96°** |
| on-fault size spread (p90/p10) | 2.80 | **2.31** | **2.31** |
| far-field closure halo (excess cells) | 42.8 | **27.7** | 43.9 |
| cells | 1110 | 1110 | 1186 |

Relaxing **at the end** cannot change the topology, so the cell count is
identical to the unrelaxed mesh, and it cuts the far-field closure halo most.
Relaxing **per generation** gives the cleanest element shapes and the lowest
error, because each generation marks from already-relaxed coordinates — but it
changes which cells get marked, so it spends ~3% more cells.

Every column beats no relaxation. The default is at-end because it is the
cheaper and less invasive of the two.

## Multigrid: fine in 2D, can break in 3D

In **2D** relaxation is transparent to the custom-P geometric-MG tail. The
operators need only the *topological* hierarchy, and the coarse levels keep
their own coordinates. Measured with the Stokes velocity block and with
Poisson: full `pc=mg` in every configuration, no fallback, solutions agreeing
to four significant figures, and the at-end case one Krylov iteration
*cheaper*.

### Why relaxation can disturb it, and why it no longer costs you the hierarchy

The custom-P prolongation is built **geometrically, not topologically**. The
`barycentric` builder re-triangulates the coarse DOF *point cloud*
(`Delaunay(coarse_coords)`) and locates each fine DOF in one simplex of it; it
never consults the parent/child refinement relation. That is deliberate — it is
exactly what lets custom-P accept non-nested coarse/fine pairs — but it means a
preserved topology buys the transfer nothing.

So the builder has **local support**: a coarse DOF is reached only if some fine
DOF lands in a simplex touching it. Move the fine coordinates, which is what
relaxation does, and a coarse DOF can lose every fine image. Its column in `P`
goes to zero, the Galerkin coarse operator `PᵀAP` acquires a zero row and
column, and it is singular. 3D is more exposed: a Delaunay triangulation of a
graded 3D cloud is full of slivers, each simplex has only four vertices, and
proportionally more DOFs sit near the hull.

The builder now **repairs orphaned coarse DOFs directly**: each is given its
nearest fine DOF as a pure injection (weight 1), which is the same fallback
already used for fine points outside the coarse hull. Partition of unity and
sparsity (~d+1 non-zeros per row) are both preserved, and the column is no
longer empty. Measured on a relaxed 3D adapt child: `pc=mg` at 2 iterations,
where before the repair it fell back to GAMG at 23.

If a pathological pair still leaves an orphan, the build retries with the
global-support `rbf` builder before giving up. That is a **last resort, not a
scalable transfer**: the RBF prolongation is fully dense (measured
`nnz/row == n_coarse` exactly — 200 of 200, 800 of 800), so `PᵀAP` is dense
too. It rescues correctness on small problems; it is not something to rely on
at production sizes.

## What relaxation cannot do

- **It cannot rescue centroid/Alfeld refinement.** Those slivers are
*structural* — an interior point wired to a fixed parent face, producing a fan
of near-degenerate cells radiating from one vertex. Node motion cannot unpick
a topology. Measured: cells with `q < 0.3` stay at 25–28% and the worst angle
stays at 176–178° whatever the placement. Centroid refinement is a
shallow tool only — see {doc}`../design/NVB_GRADED_ADAPT`.
- **It cannot flatten the size steps along a feature.** Bisection generations
are discrete (each halves cell area), so on-feature sizes come in
powers-of-two classes. Relaxation compresses the spread (p90/p10 2.80 → 2.31)
but two size classes remain populated.
- **It does not concentrate cells on the feature.** That is refinement's job.
Relaxation holds the size distribution by construction, so the share of cells
in the band barely moves (48.9% → 51.1%).

## 3D

Relaxation improves 3D mesh **quality** but has not been shown to improve
accuracy. On an adapted 3D mesh it halves the near-degenerate population (cells
with `q < 0.1`: 3.6% → 1.8%), lifts median quality 0.32 → 0.39 and pulls the
99th-percentile dihedral angle back from 153° to 146° — but the interpolation
error of an *isotropic* feature is unchanged (+0.5%).

That is consistent rather than contradictory: relaxation holds the size
distribution, so its only route to lower error is by *aligning* cells with the
feature, and an isotropic metric gives it no reason to align anything. Whether
an anisotropic (tensor) metric recovers the 2D-style accuracy gain in 3D is
open — see the tracking issue.

Use it in 3D for element quality and conditioning, not expecting an accuracy
win.

## Diagnostics

Element quality alone is a poor guide here, and can actively mislead: on a
structured base the *unrelaxed* mesh scores best on median quality (every cell
is an identical right triangle) while resolving the feature worst. Four
properties are worth reporting together:

- **gather** — share of cells within the metric band;
- **clean** — fraction of near-degenerate cells and the 99th-percentile max
angle (not the worst single element);
- **uniform** — spread of cell size along the feature;
- **leakage** — refinement added where the metric did not ask for it.

Leakage in particular resists being reduced to one number: it is a *spatial*
property (large coherent over-refined blocks versus small scattered patches),
and per-cell maps of `log2(h / h_asked_for)` are more informative than any
scalar we have found.
Loading
Loading