From 0cd2196de538ea2a866bf1ad48827374f3fb8bb2 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 25 Jul 2026 20:26:45 +1000 Subject: [PATCH 01/16] =?UTF-8?q?fix(mmpde):=20per-cell=20collapse=20floor?= =?UTF-8?q?=20=E2=80=94=20mover=20was=20a=20silent=20no-op=20on=20graded?= =?UTF-8?q?=20meshes=20(#419)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The MMPDE line-search accept test used a single ABSOLUTE collapse floor, `area_floor_frac x median cell volume`, with the median taken as a `_global_mean` of per-rank medians. Two defects followed. Any graded mesh disabled the mover outright. Anything out of `mesh.adapt` has finest cells orders of magnitude below the median, so those cells start already under the floor; every trial step failed the test, the line search backtracked to `scale=0`, and the mover returned having moved nothing — with no warning: mmpde outer 1/8: I=1.991126e+00 dI=+0.00e+00 scale=0.000 max|dx|=0.00e+00 And the behaviour depended on the partition, since a mean of per-rank medians is not the global median: the same mesh moved at np=1 and stood completely still at np=2. Floor each cell against its OWN starting volume instead — no cell may shrink below `area_floor_frac` of what it started as. Scale-free, grading-free, partition-independent, and still a strict no-fold certificate (a positive ratio certifies positive volume). The kwarg keeps its name and default; only its reference changes. This affected `redistribute_nodes` / `node_redistribution` generally, not just new code. Found while building shape relaxation on the mover. Underworld development team with AI support from Claude Code --- src/underworld3/meshing/smoothing/mmpde.py | 28 ++++-- tests/test_0751_mmpde_graded_area_floor.py | 102 +++++++++++++++++++++ 2 files changed, 124 insertions(+), 6 deletions(-) create mode 100644 tests/test_0751_mmpde_graded_area_floor.py diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index c6f549400..f1d5b52fc 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -323,9 +323,21 @@ def _edge_mats(X, cells): a0 = signed_vol(coords, cells_all) orient = np.sign(np.median(a0)) or 1.0 - a0_own_med = float(np.median(np.abs(signed_vol(coords, cells_own)))) - a0_own_med = _global_mean(a0_own_med) - a_min_floor = float(area_floor_frac) * a0_own_med + # Collapse guard reference: EACH cell's own starting volume. The floor + # is then "no cell may shrink below area_floor_frac of what it started + # as" -- scale-free and grading-free. + # + # It used to be one absolute floor, area_floor_frac x the median cell + # volume, which is only meaningful on a near-uniform mesh. On a graded + # mesh (anything out of mesh.adapt) the finest cells are orders of + # magnitude below the median and so start *already under* the floor: + # every trial step is rejected, the line search backtracks to scale=0 + # and the mover silently does nothing. Worse, the median was a + # _global_mean of per-rank medians, so which cells fell foul of it + # depended on the partition -- the same mesh moved in serial and stood + # still on 2 ranks. See #419. + a0_own = np.abs(signed_vol(coords, cells_own)) + a0_own = np.maximum(a0_own, 1.0e-300) # Representative background cell size h0 (mean reference edge length over # owned cells), used to make the convergence test SCALE-RELATIVE: a move # of dmax < tol·h0 is negligible vs the cell size, so the adapt has @@ -361,8 +373,11 @@ def _energy(X): K = np.abs(detE) / fact return _global_sum(np.sum(K * G)) - def _min_area(X): - return _global_min((signed_vol(X, cells_own) * orient).min()) + def _min_area_frac(X): + """Smallest cell volume as a FRACTION of that cell's starting + volume (global). > 0 also certifies no cell has folded.""" + return _global_min( + (signed_vol(X, cells_own) * orient / a0_own).min(initial=np.inf)) prevI = _energy(coords) _Iwin = [prevI] # accepted-energy history for the stol stagnation test @@ -538,7 +553,8 @@ def _gdot(a, b, mask): trial = _halo_sync(trial) # reject any non-finite trial (defense-in-depth: projection/halo # could still introduce inf/NaN) so `_energy` never queries NaN. - if np.all(np.isfinite(trial)) and _min_area(trial) > a_min_floor: + if (np.all(np.isfinite(trial)) + and _min_area_frac(trial) > float(area_floor_frac)): Itr = _energy(trial) if Itr < prevI: accepted = trial; Inew = Itr; break diff --git a/tests/test_0751_mmpde_graded_area_floor.py b/tests/test_0751_mmpde_graded_area_floor.py new file mode 100644 index 000000000..5a722f979 --- /dev/null +++ b/tests/test_0751_mmpde_graded_area_floor.py @@ -0,0 +1,102 @@ +"""Regression for #419: the MMPDE mover must actually move on a GRADED mesh. + +The line-search collapse guard used to be one absolute floor, +``area_floor_frac x median cell volume``. On a graded mesh the finest cells +start orders of magnitude below that floor, so every trial step was +rejected, the line search backtracked to ``scale=0``, and the mover +returned having moved nothing -- silently. The floor is now per-cell +relative (no cell may shrink below a fraction of its OWN starting volume). +""" +import numpy as np +import pytest +import sympy +import underworld3 as uw + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + +CENTRE, H_NEAR, H_FAR, WIDTH = 0.5, 0.01, 0.25, 0.08 + + +def _metric(centroids): + d = np.abs(np.asarray(centroids)[:, 1] - CENTRE) + slope = np.sqrt(H_FAR**2 - H_NEAR**2) / WIDTH + return 1.0 / np.minimum(np.sqrt(H_NEAR**2 + (slope * d) ** 2), H_FAR) ** 2 + + +def _density(mesh): + x, y = mesh.X + slope = np.sqrt(H_FAR**2 - H_NEAR**2) / WIDTH + d = sympy.Abs(y - CENTRE) + return 1.0 / sympy.Min( + sympy.sqrt(H_NEAR**2 + (slope * d) ** 2), H_FAR) ** 2 + + +def _graded_child(max_levels): + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.2, + refinement=1, qdegree=2) + return base.adapt(_metric, max_levels=max_levels) + + +def _coords(mesh): + return mesh.dm.getCoordinatesLocal().array.reshape(-1, mesh.cdim).copy() + + +def _volume_spread(mesh): + """max/min cell volume -- how graded the mesh actually is.""" + dm = mesh.dm + vS, vE = dm.getDepthStratum(0) + cS, cE = dm.getHeightStratum(0) + p = _coords(mesh) + t = np.asarray([[q - vS for q in dm.getTransitiveClosure(c)[0] + if vS <= q < vE] for c in range(cS, cE)]) + a, b, c = p[t[:, 0]], p[t[:, 1]], p[t[:, 2]] + ar = np.abs(0.5 * ((b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) + - (c[:, 0] - a[:, 0]) * (b[:, 1] - a[:, 1]))) + return float(ar.max() / ar.min()) + + +def test_mover_moves_on_a_graded_mesh(): + """The bug: on a strongly graded mesh the mover moved nothing at all.""" + child = _graded_child(max_levels=4) + # Guard the guard: if this mesh were not strongly graded the test could + # pass without exercising the floor at all. The spread saturates once + # the metric is satisfied, so it is capped by H_FAR/H_NEAR (~200 here), + # not by max_levels -- do not raise this without widening the metric. + assert _volume_spread(child) > 150.0 + + before = _coords(child) + child.redistribute_nodes(_density(child), + method_kwargs=dict(n_outer=8)) + moved = float(np.abs(_coords(child) - before).max()) + + h_fine = H_NEAR + assert moved > 1.0e-3 * h_fine, ( + f"mover did not move a graded mesh (max|dx|={moved:.3e}); the " + f"collapse floor is rejecting every trial step (#419)") + + +def test_collapse_guard_still_rejects_folding(): + """The floor must still do its job: no cell may collapse or invert.""" + child = _graded_child(max_levels=3) + + dm = child.dm + vS, vE = dm.getDepthStratum(0) + cS, cE = dm.getHeightStratum(0) + tris = np.asarray([[q - vS for q in dm.getTransitiveClosure(c)[0] + if vS <= q < vE] for c in range(cS, cE)]) + + def signed(p): + a, b, c = p[tris[:, 0]], p[tris[:, 1]], p[tris[:, 2]] + return 0.5 * ((b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) + - (c[:, 0] - a[:, 0]) * (b[:, 1] - a[:, 1])) + + s0 = signed(_coords(child)) + child.redistribute_nodes(_density(child), + method_kwargs=dict(n_outer=25)) + s1 = signed(_coords(child)) + + sign = np.sign(np.median(s0)) + assert np.all(sign * s1 > 0.0), "a cell folded during redistribution" + # and none collapsed below the documented fraction of its own start + assert float((s1 / s0).min()) > 0.01 From 73a7cb1a9ddd082c07f6fa3771100135470a0f30 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 25 Jul 2026 20:40:28 +1000 Subject: [PATCH 02/16] =?UTF-8?q?feat(meshing):=20mesh.relax()=20=E2=80=94?= =?UTF-8?q?=20shape=20relaxation=20in=20the=20ideal=20reference=20frame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refinement chooses node positions from combinatorics — which edge the tagging rule nominated, or the cell centroid — never from geometry. A refined mesh therefore carries needles and slivers that reflect the base mesh's arbitrary choices rather than the problem. The MMPDE mover could not fix this, and the reason was its REFERENCE FRAME, not its metric: the reference is the mesh at first call, so "distortion" meant "deviation from the mesh I was handed" and a distorted mesh was its own optimum. `redistribute_nodes(1)` moved exactly nothing. Add `reference=` to the mover: "mesh" (default, unchanged) the redistribution frame "ideal" one regular simplex, scaled per cell to that cell's own volume => r = 1 at entry, so size is held and only shape moves. Pure shape repair. "ideal-metric" uniform reference volume; the metric sets size. Needed when the sizes we were handed are themselves the problem. Deviation is then measured from equilateral-in-the-metric, so distortion the mesh arrived with is no longer self-justifying. Same functional, same non-folding guarantee, same parallel assembly. Exposed as `mesh.relax()` (no metric => "ideal"; with one => "ideal-metric"), and as `adapt(metric, max_levels=N, relax=True)`, which relaxes each generation INSIDE the loop — before the next pass marks from it, which is where the gain comes from. Measured, 2D, gmsh base + NVB adapt, fault-localised P1 interpolation error (Stokes velocity block on custom-P FMG in every case): adapt only 832 cells 2.746e-2 4 vel-KSP its + relax at end 832 cells 2.559e-2 (-7%) 3 vel-KSP its + relax per generation 856 cells 2.384e-2 (-13%) 4 vel-KSP its Relax-per-generation wins on error and on error-per-cell for 3% more cells. MG is unaffected: full hierarchy, no GAMG fallback, solutions agree to 4 s.f. — the operators need only the topological hierarchy, and the coarse levels keep their own coordinates. 3D IS A WASH (+0.5%, unchanged at 120 iterations) and is documented as such; this is a 2D win only. Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 137 +++++++++++++++++- src/underworld3/meshing/smoothing/mmpde.py | 79 +++++++++- 2 files changed, 213 insertions(+), 3 deletions(-) diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 84dd00cbf..8ee0cda5e 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6597,8 +6597,88 @@ def redistribute_nodes(self, metric, *, verbose=False, **kwargs): smooth_mesh_interior(self, metric=metric, method="mmpde", verbose=verbose, **kwargs) + def relax(self, metric=None, *, verbose=False, **kwargs): + r"""Improve this mesh's element **shapes** without changing its + size distribution or its topology. + + The companion to :meth:`adapt`. Refinement chooses where new + nodes go from *combinatorics* — which edge the tagging rule + nominated (bisection), or the cell centroid (Alfeld) — never + from geometry, so a refined mesh carries needles and slivers + that reflect the base mesh's arbitrary choices rather than + anything about the problem. Relaxation moves those nodes to + where the geometry wants them, keeping the resolution the + refinement installed:: + + child = mesh.adapt(metric, max_levels=3) + child.relax() + + Implemented with the same MMPDE mover as + :meth:`redistribute_nodes`, in its **ideal reference frame** + (``reference="ideal"``): each cell's reference element is a + regular simplex scaled to that cell's own current volume. Two + consequences, and they are the whole point: + + * the size term starts and stays at its optimum, so the graded + spacing is preserved rather than re-derived; + * "distortion" is measured against *equilateral*, not against + the mesh as supplied — so a distorted mesh is no longer its + own optimum, which is exactly why + ``redistribute_nodes(metric)`` cannot do this job (its + reference IS the mesh it was handed, so under a uniform + metric it moves nothing at all). + + Non-folding by construction, and the parallel partition, vertex + count and DOF layout are unchanged. + + **2D only, on the evidence.** In 2D this measures a 13% drop in + fault-localised P1 interpolation error when applied per generation + (`adapt(..., relax=True)`), 7% applied once at the end. In **3D the + same operation is a wash** (+0.5% on a 74k-cell mesh, unchanged at + 120 iterations) — it runs and it is safe, but nothing yet shows it + helps, so do not turn it on in 3D expecting a win. + + Parameters + ---------- + metric : sympy expression, MeshVariable, or sympy Matrix, optional + Usually omitted. ``None`` (default) relaxes under a uniform + metric — pure shape repair at fixed size. Passing a metric + additionally regrades toward it, which makes this a + redistribution-plus-relaxation rather than a pure relax. + verbose : bool, default False + Print mover progress. + **kwargs + Forwarded to :meth:`redistribute_nodes` — e.g. + ``pinned_labels``, ``slip_surfaces``, ``method_kwargs`` + (mover tunables such as ``n_outer``). + + See Also + -------- + adapt : Add resolution (topology change, returns a child mesh). + redistribute_nodes : Move nodes to follow a metric (changes the + size distribution; the reference is the mesh as supplied). + """ + import sympy + + method_kwargs = dict(kwargs.pop("method_kwargs", None) or {}) + # No metric -> keep each cell's own size, repair shape only. + # With one -> the metric sets size (a uniform reference volume), + # so sizes that are themselves wrong can be fixed. + default_ref = "ideal" if metric is None else "ideal-metric" + ref = method_kwargs.setdefault("reference", default_ref) + if ref not in ("ideal", "ideal-metric"): + raise ValueError( + "mesh.relax() is an ideal-reference-frame operation; " + f"method_kwargs['reference']={ref!r} contradicts it. For " + "the mesh-reference frame call " + "mesh.redistribute_nodes(metric).") + return self.redistribute_nodes( + sympy.sympify(1) if metric is None else metric, + verbose=verbose, method_kwargs=method_kwargs, **kwargs) + def adapt(self, metric_field, max_levels=None, node_budget=None, - builder=None, adapter=None, engine=None, verbose=False): + builder=None, adapter=None, engine=None, verbose=False, + relax=False, relax_kwargs=None): r""" Nested **adapt-on-top**: return a refined **child** mesh. @@ -6764,10 +6844,12 @@ def adapt(self, metric_field, max_levels=None, node_budget=None, return self._adapt_nested( metric_field, max_levels=max_levels, node_budget=node_budget, builder=builder, engine=engine, verbose=verbose, + relax=relax, relax_kwargs=relax_kwargs, ) def _adapt_nested(self, metric_field, max_levels=2, node_budget=None, - builder="barycentric", engine="nvb", verbose=False): + builder="barycentric", engine="nvb", verbose=False, + relax=False, relax_kwargs=None): """Core nested adapt-on-top (SBR or NVB engine). See :meth:`adapt`.""" import math from underworld3.utilities import custom_mg @@ -7019,6 +7101,38 @@ def sync_mask(mask): write_tagged_state_label(base_finest) markers_per_level = [] + def _relax_generation(engine_obj, carry, rcarry): + """Relax THIS generation in place INSIDE the refinement engine. + + The engine's own coordinates feed the next generation's marking + and its next midpoints, so a relaxation that only touched the + exported DM would be discarded by the following generation (the + same reason the boundary snap is applied inside the engine). + + Coordinates are matched by POSITION, not by index: ``to_dm`` + goes through ``createFromCellList`` and PETSc renumbers the + vertices. The match is exact because it is taken before + anything moves. + """ + from scipy.spatial import cKDTree + _dmg = engine_obj.to_dm(boundaries=carry, regions=rcarry, + comm=self.dm.comm) + _mg = Mesh(_dmg, simplex=self.dm.isSimplex(), + coordinate_system_type=( + self.CoordinateSystem.coordinate_type), + qdegree=self.qdegree, boundaries=self.boundaries, + verbose=False) + _cd = _mg.cdim + _pre = _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd).copy() + _src = numpy.asarray([numpy.asarray(c, dtype=float) + for c in engine_obj.coords]) + _idx = cKDTree(_src).query(_pre, k=1)[1] + _mg.relax(None if relax is True else relax, + **(relax_kwargs or {})) + _post = _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd) + for _k, _i in enumerate(_idx): + engine_obj.coords[_i] = _post[_k] + level_dms = [] # one DM per refinement level if engine == "nvb" and _nvbx is not None: @@ -7061,6 +7175,23 @@ def sync_mask(mask): lab.setValue(cidx, DM_ADAPT_REFINE) current_dm = _nvbx.refine(d, "adapt") snap_level_boundaries(current_dm) + if relax: + # Relax THIS generation before the next one marks from it: + # the moved coordinates are what the next pass measures and + # bisects, which is the whole point of relaxing in the loop + # rather than once at the end. A clone keeps the plex + # numbering, so the coordinate vectors align index-for-index + # and no positional matching is needed. + _mg = Mesh(current_dm.clone(), + simplex=self.dm.isSimplex(), + coordinate_system_type=( + self.CoordinateSystem.coordinate_type), + qdegree=self.qdegree, + boundaries=self.boundaries, verbose=False) + _mg.relax(None if relax is True else relax, + **(relax_kwargs or {})) + current_dm.setCoordinatesLocal( + _mg.dm.getCoordinatesLocal()) level_dms.append(current_dm) if verbose: fs, fe = current_dm.getHeightStratum(0) @@ -7119,6 +7250,8 @@ def sync_mask(mask): numpy.array([nvb.coords[i] for i in _idx])) for _k, _i in enumerate(_idx): nvb.coords[_i] = _snapped[_k] + if relax: + _relax_generation(nvb, carry, rcarry) level_dms.append(nvb.to_dm(boundaries=carry, regions=rcarry, comm=self.dm.comm)) if verbose: diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index f1d5b52fc..9da04b4dd 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -92,7 +92,7 @@ def _mmpde_mover(mesh, metric, pinned_labels, verbose, stol=None, stol_k=3, fd_eps=1.0e-6, metric_eval="rbf", rbf_k=None, accel="cg", momentum=0.0, - resolution_ratio=None, + resolution_ratio=None, reference="mesh", **_unknown_kwargs): r"""Anisotropic variational moving-mesh adaptation (Huang–Kamenski MMPDE; the direct simplex discretization of JCP 301 (2015) 322, @@ -147,6 +147,27 @@ def _mmpde_mover(mesh, metric, pinned_labels, verbose, ``MMPDE_MOMENTUM`` environment variables, now removed — pass as kwargs, e.g. ``method_kwargs={"accel": "cg"}`` through ``smooth_mesh_interior``.) + ``reference`` selects what the fixed computational mesh — the thing + the physical mesh is the image OF — actually is, and so what the + shape term measures deviation *from*: + + * ``"mesh"`` (default, the **redistribution** frame): the reference + is the mesh at the first call. This is the classical MMPDE and the + right frame for moving an existing well-shaped mesh onto a metric. + Its fixed point is the mesh it started from: with ``M = I`` the + identity map already minimises the functional, so calling the + mover to "tidy up" a mesh moves nothing at all. + * ``"ideal"`` (the **relaxation** frame): the reference is a single + regular simplex, scaled to the reference mesh's typical cell + volume. Deviation is then measured from *equilateral-in-the-metric* + rather than from the supplied mesh, so distortion the mesh arrived + with is no longer self-justifying. This is the frame to use after + a topological refinement (``mesh.adapt``), where node positions + were fixed by inherited combinatorics — bisection's needles and + centroid refinement's slivers — rather than by any geometric + criterion. Same metric, same grading, same non-folding guarantee; + only the shape target moves. + ``resolution_ratio`` is accepted but unused: the strategy dispatch in ``_smooth_mesh_interior_bare`` injects it into ``method_kwargs`` for every mover, and MMPDE's clustering intensity comes from the metric @@ -321,6 +342,62 @@ def _edge_mats(X, cells): Eh = _edge_mats(ref, cells_own) detEh = np.linalg.det(Eh) + if reference in ("ideal", "ideal-metric"): + # RELAXATION frame (see the ``reference`` docstring): replace the + # per-cell reference by ONE regular simplex, so "deviation from the + # reference" means "deviation from equilateral-in-the-metric" + # instead of "deviation from the mesh I was handed". This is what + # lets the mover repair the needles/slivers that refinement leaves + # behind: with reference="mesh" a distorted start is its own + # optimum (𝕁 = I ⇒ zero shape gradient), which is why a + # post-refinement mover call moves nothing under M = I. + # Only the SHAPE target changes — the size/equidistribution term + # (r = detEh/detE against detM) is untouched, so the metric still + # sets the grading exactly as before. + # Unit regular simplex, columns c_k = v_k - v_0: |c_k| = 1 and + # c_i·c_j = 1/2 (so every edge, including v_i-v_j, has length 1). + # That Gram matrix factors exactly, so take its Cholesky. + G = 0.5 * (np.eye(cdim) + np.ones((cdim, cdim))) + R = np.linalg.cholesky(G).T # R^T R = G + detR = math.sqrt(cdim + 1.0) / 2.0 ** (cdim / 2.0) + # Scale EACH cell's reference to ITS OWN current volume, and match + # the cell orientation. Then r = detEh/detE = 1 for every cell at + # entry, so the size/equidistribution term already sits at its + # optimum and the existing size distribution is what gets + # preserved — the mover has nothing to say about size and only + # the shape term does work. That is what makes this a RELAXATION + # (keep the resolution the refinement installed, repair the + # element shapes it had no way to choose) rather than a + # re-adaptation. Under M = I this is pure shape repair. + # Per-cell orientation (flip one column where the cell is negative) + # and per-cell scale, so det(Eh) == detEh exactly, cell by cell. + # No reduction and no median => correct on a rank that owns no + # cells, where a global orientation vote would have to be faked. + _sgn = np.sign(detEh) + _sgn[_sgn == 0.0] = 1.0 + Rb = np.broadcast_to(R, (detEh.shape[0], cdim, cdim)).copy() + Rb[_sgn < 0.0, :, -1] *= -1.0 + if reference == "ideal": + _vol = np.abs(detEh) # keep each cell's size + else: + # "ideal-metric": ONE reference volume for every cell, so the + # metric alone sets size. Needed whenever the sizes we were + # handed are themselves the problem — a sliver cannot be + # repaired while being told to keep its (near-zero) volume, + # because its volume is half of what is wrong with it. + _n = int(detEh.shape[0]) + _loc = float(np.median(np.abs(detEh))) if _n else 0.0 + _tot = _global_sum(float(_n)) + _vol = np.full(_n, (_global_sum(_loc * _n) / _tot) if _tot else 1.0) + Eh = ((_vol / detR) ** (1.0 / cdim))[:, None, None] * Rb + detEh = np.linalg.det(Eh) + elif reference != "mesh": + raise ValueError( + f"_mmpde_mover: reference={reference!r}; use 'mesh' (the " + f"metric-redistribution frame, default), 'ideal' (shape " + f"relaxation at fixed per-cell size) or 'ideal-metric' " + f"(shape relaxation with the metric setting size).") + a0 = signed_vol(coords, cells_all) orient = np.sign(np.median(a0)) or 1.0 # Collapse guard reference: EACH cell's own starting volume. The floor From c7a3ec9aab821bd4c23fe81309de040be1c0c8b8 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 25 Jul 2026 22:02:15 +1000 Subject: [PATCH 03/16] =?UTF-8?q?docs(relax):=203D=20improves=20QUALITY=20?= =?UTF-8?q?not=20error=20=E2=80=94=20correct=20the=20earlier=20'wash'=20cl?= =?UTF-8?q?aim?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured on an adapted 3D mesh: cells with q<0.1 halve (3.6% -> 1.8%), median quality 0.32 -> 0.39, p99 dihedral 153 -> 146 degrees. The earlier note said 3D was 'a wash' on the strength of an unchanged interpolation error, conflating accuracy with mesh quality. The error really is unchanged, and that is consistent — relaxation holds the size distribution, and the 2D error gain came from cells aligning onto the feature, which an isotropic 3D metric gives no reason to do. Also refutes the base-provenance hypothesis: relaxation repairs the PETSc uniform 1:8 split's damage well (q p10 0.449 -> 0.526 on a uniformly split base), so the fixed reference-octahedron diagonal is not what was limiting it. Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 8ee0cda5e..b8e4673cd 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6631,12 +6631,20 @@ def relax(self, metric=None, *, verbose=False, **kwargs): Non-folding by construction, and the parallel partition, vertex count and DOF layout are unchanged. - **2D only, on the evidence.** In 2D this measures a 13% drop in - fault-localised P1 interpolation error when applied per generation - (`adapt(..., relax=True)`), 7% applied once at the end. In **3D the - same operation is a wash** (+0.5% on a 74k-cell mesh, unchanged at - 120 iterations) — it runs and it is safe, but nothing yet shows it - helps, so do not turn it on in 3D expecting a win. + **What it buys, measured.** In 2D, a 13% drop in fault-localised + P1 interpolation error applied per generation + (``adapt(..., relax=True)``), 7% applied once at the end. + + In **3D it improves mesh QUALITY but not interpolation error** — + two different things, and worth keeping apart. 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 degrees; but the + interpolation error of an isotropic feature is unchanged (+0.5%). + That is consistent: relaxation holds the size distribution, and in + 2D the error gain came from cells ALIGNING onto the feature, which + an isotropic metric gives no reason to do in 3D. Use it in 3D for + conditioning and element quality, not expecting an accuracy win. Parameters ---------- From 4874f7c2151ccf2cc7e451c6ccff7433ea4a3cc9 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 10:09:25 +1000 Subject: [PATCH 04/16] =?UTF-8?q?feat(adapt):=20relax=3D=20takes=20a=20pla?= =?UTF-8?q?cement=20=E2=80=94=20True=20(at=20end,=20default)=20or=20per-ge?= =?UTF-8?q?neration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both placements beat no relaxation, and neither dominates the other: at-end keeps the cell count identical to the unrelaxed mesh and cuts the far-field closure halo most (42.8 -> 27.7 excess cells), per-generation gives the cleanest element shapes (99th pct max angle 112 -> 96 deg) and the lowest interpolation error, at ~3% more cells. Rather than manufacture a ranking the evidence does not support, both are offered and documented side by side, with the cheaper, less invasive one as the default. adapt(metric, max_levels=N, relax=True) # relax once, at end adapt(metric, max_levels=N, relax="per-generation") # relax in the loop Also fixes a latent bug from when `relax` was a boolean: both in-loop call sites passed `None if relax is True else relax` as the mover's METRIC, so `relax="per-generation"` fed the mode string to sympify. `relax` is a mode, never a metric; the metric is now resolved once (a callable metric cannot go to the mover, so those relax in the pure shape frame at fixed size). Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 66 ++++++++++++++++--- 1 file changed, 57 insertions(+), 9 deletions(-) diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index b8e4673cd..649b4d801 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6631,9 +6631,26 @@ def relax(self, metric=None, *, verbose=False, **kwargs): Non-folding by construction, and the parallel partition, vertex count and DOF layout are unchanged. - **What it buys, measured.** In 2D, a 13% drop in fault-localised - P1 interpolation error applied per generation - (``adapt(..., relax=True)``), 7% applied once at the end. + **Two valid placements, neither dominant.** ``adapt(metric, ..., + relax=True)`` relaxes once at the end — the recommended default. + ``relax="per-generation"`` relaxes inside the refinement loop, so + each generation marks from already-relaxed coordinates. Both beat + no relaxation; which is *better* depends on which property you + weight, and we deliberately do not rank them: + + ========================= ========== ========== =============== + property unrelaxed at end per generation + ========================= ========== ========== =============== + P1 interpolation error 2.75e-2 2.56e-2 2.38e-2 + 99th pct max angle 112 deg 110 deg 96 deg + on-fault size spread 2.80 2.31 2.31 + far-field closure halo 42.8 27.7 43.9 + ========================= ========== ========== =============== + + Relaxing at the end keeps the cell count identical to the + unrelaxed mesh and cuts the far-field halo most; relaxing per + generation gives the cleanest element shapes and the lowest + error, but spends ~3% more cells to do it. In **3D it improves mesh QUALITY but not interpolation error** — two different things, and worth keeping apart. On an adapted 3D @@ -7109,6 +7126,33 @@ def sync_mask(mask): write_tagged_state_label(base_finest) markers_per_level = [] + # relax=True is the RECOMMENDED default: relax once, at the end. + # relax="per-generation" relaxes inside the refinement loop instead. + # Both measure better than no relaxation and neither dominates the + # other across the properties we care about (element quality, size + # uniformity along the feature, and refinement leakage away from + # it), so this is a genuine choice rather than a ranking. + if relax in (False, None): + _relax_mode = None + elif relax is True: + _relax_mode = "end" + elif str(relax).lower().replace("_", "-") in ("end", "at-end"): + _relax_mode = "end" + elif str(relax).lower().replace("_", "-") in ("per-generation", + "generation"): + _relax_mode = "per-generation" + else: + raise ValueError( + f"adapt(relax={relax!r}); use True (relax once at the end, " + f"the recommended default), 'per-generation' (relax inside " + f"the refinement loop) or False.") + + # The metric handed to the relaxation, resolved ONCE. A callable + # (numpy) metric cannot go to the mover, so those relax in the pure + # shape frame at fixed size; a sympy / MeshVariable metric gives the + # ideal-metric frame. NB `relax` is a MODE, never a metric. + _relax_metric = None if callable(metric_field) else metric_field + def _relax_generation(engine_obj, carry, rcarry): """Relax THIS generation in place INSIDE the refinement engine. @@ -7135,8 +7179,7 @@ def _relax_generation(engine_obj, carry, rcarry): _src = numpy.asarray([numpy.asarray(c, dtype=float) for c in engine_obj.coords]) _idx = cKDTree(_src).query(_pre, k=1)[1] - _mg.relax(None if relax is True else relax, - **(relax_kwargs or {})) + _mg.relax(_relax_metric, **(relax_kwargs or {})) _post = _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd) for _k, _i in enumerate(_idx): engine_obj.coords[_i] = _post[_k] @@ -7183,7 +7226,7 @@ def _relax_generation(engine_obj, carry, rcarry): lab.setValue(cidx, DM_ADAPT_REFINE) current_dm = _nvbx.refine(d, "adapt") snap_level_boundaries(current_dm) - if relax: + if _relax_mode == "per-generation": # Relax THIS generation before the next one marks from it: # the moved coordinates are what the next pass measures and # bisects, which is the whole point of relaxing in the loop @@ -7196,8 +7239,7 @@ def _relax_generation(engine_obj, carry, rcarry): self.CoordinateSystem.coordinate_type), qdegree=self.qdegree, boundaries=self.boundaries, verbose=False) - _mg.relax(None if relax is True else relax, - **(relax_kwargs or {})) + _mg.relax(_relax_metric, **(relax_kwargs or {})) current_dm.setCoordinatesLocal( _mg.dm.getCoordinatesLocal()) level_dms.append(current_dm) @@ -7258,7 +7300,7 @@ def _relax_generation(engine_obj, carry, rcarry): numpy.array([nvb.coords[i] for i in _idx])) for _k, _i in enumerate(_idx): nvb.coords[_i] = _snapped[_k] - if relax: + if _relax_mode == "per-generation": _relax_generation(nvb, carry, rcarry) level_dms.append(nvb.to_dm(boundaries=carry, regions=rcarry, comm=self.dm.comm)) @@ -7316,6 +7358,12 @@ def _relax_generation(engine_obj, carry, rcarry): verbose=False, ) + if _relax_mode == "end": + # A sympy/MeshVariable metric gives the ideal-metric frame (the + # metric sets size); a plain callable cannot be handed to the + # mover, so those fall back to pure shape repair at fixed size. + child.relax(_relax_metric, **(relax_kwargs or {})) + # Lineage (parent/child DAG) and mesh-owned custom-P hierarchy. child.parent = self child._relationship_kind = "refinement" From d77106b91751a5f8cb98c2e693e557dd710c4ed2 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 12:17:45 +1000 Subject: [PATCH 05/16] test+docs(relax): cover both relax hooks, document the frame trade-off (#422) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests (tests/test_0752, level_1 tier_a, 7 cases): topology and no-fold invariants, grading preservation, the max-angle-tail improvement, both `adapt(relax=...)` placements, and the argument guards. Includes a 3D case because 3D goes through the CELL-LIST refinement engine — the native uwnvb transform is 2D-only — so that second relax hook was otherwise untested. Writing the tests turned up a real distinction I had been eliding: relax() and relax(metric) are different operations. The metric-free call is a shape guarantee; passing a metric switches to the ideal-METRIC frame, which re-grades as well as reshapes and will trade element shape away to chase the size field. Measured on a 4-level graded box, 99th-percentile max angle: no metric 117.9 -> 113.8 (improves) with metric 117.9 -> 127.4 (WORSE) per-generation 117.9 -> 101.2 (best) The first version of the test asserted the improvement while passing a metric, and failed. Documented in the docstring and the new subsystem page rather than papered over. New docs/developer/subsystems/mesh-shape-relaxation.md covers the reference-frame explanation, both placements with the measured table, the MG result, and an explicit "what relaxation cannot do" section (does not rescue centroid refinement, cannot flatten discrete bisection size steps, does not concentrate cells). 3D is documented as a quality win only, with the anisotropic-metric question tracked in #422. Underworld development team with AI support from Claude Code --- docs/developer/index.md | 1 + .../subsystems/mesh-shape-relaxation.md | 154 +++++++++++++++ .../discretisation/discretisation_mesh.py | 15 +- tests/test_0752_mesh_shape_relaxation.py | 181 ++++++++++++++++++ 4 files changed, 347 insertions(+), 4 deletions(-) create mode 100644 docs/developer/subsystems/mesh-shape-relaxation.md create mode 100644 tests/test_0752_mesh_shape_relaxation.py diff --git a/docs/developer/index.md b/docs/developer/index.md index eed57fbf4..3e49e380a 100644 --- a/docs/developer/index.md +++ b/docs/developer/index.md @@ -179,6 +179,7 @@ CHANGELOG :caption: Subsystems subsystems/meshing +subsystems/mesh-shape-relaxation subsystems/discretisation subsystems/solvers subsystems/boundary-stress-and-projection-postprocessing diff --git a/docs/developer/subsystems/mesh-shape-relaxation.md b/docs/developer/subsystems/mesh-shape-relaxation.md new file mode 100644 index 000000000..1f5738bc6 --- /dev/null +++ b/docs/developer/subsystems/mesh-shape-relaxation.md @@ -0,0 +1,154 @@ +# 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 is unaffected + +Relaxation moves only the finest level's coordinates. The custom-P geometric-MG +tail needs the *topological* hierarchy preserved in its operators, and the +coarse levels keep their own coordinates, so nothing downstream is disturbed — +the transfers already accept non-nested coarse/fine pairs. Measured with the +Stokes velocity block on custom-P FMG: full 4-level `pc=mg` in every +configuration, no fallback to GAMG, solutions agreeing to four significant +figures, and the at-end case one Krylov iteration *cheaper*. + +## 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. diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 649b4d801..50bd3dcb2 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6666,10 +6666,17 @@ def relax(self, metric=None, *, verbose=False, **kwargs): Parameters ---------- metric : sympy expression, MeshVariable, or sympy Matrix, optional - Usually omitted. ``None`` (default) relaxes under a uniform - metric — pure shape repair at fixed size. Passing a metric - additionally regrades toward it, which makes this a - redistribution-plus-relaxation rather than a pure relax. + Usually omitted, and **omitting it is what makes this a shape + guarantee**. ``None`` (default) relaxes under a uniform metric + — pure shape repair at fixed size. + + Passing a metric switches to the ideal-*metric* frame, which + 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 max angle went 117.9 -> 113.8 degrees with + no metric but 117.9 -> **127.4** with one. Pass a metric when + you want the sizes corrected too, and accept that shape is no + longer the objective. verbose : bool, default False Print mover progress. **kwargs diff --git a/tests/test_0752_mesh_shape_relaxation.py b/tests/test_0752_mesh_shape_relaxation.py new file mode 100644 index 000000000..b9f2209bd --- /dev/null +++ b/tests/test_0752_mesh_shape_relaxation.py @@ -0,0 +1,181 @@ +"""``mesh.relax()`` and ``adapt(..., relax=...)`` — shape relaxation. + +Relaxation improves element SHAPE without changing topology or the size +distribution the refinement installed. The invariants that matter: + +* topology is untouched (cell and vertex counts, DOF layout); +* nothing folds; +* the graded spacing survives (this is what separates relaxation from + re-adaptation); +* the max-angle tail actually improves — the property relaxation is for. +""" +import numpy as np +import pytest +import sympy +import underworld3 as uw + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + +CENTRE, H_NEAR, H_FAR, WIDTH = 0.5, 0.012, 0.30, 0.10 +_SLOPE = np.sqrt(H_FAR**2 - H_NEAR**2) / WIDTH + + +def _metric(centroids): + d = np.abs(np.asarray(centroids)[:, 1] - CENTRE) + return 1.0 / np.minimum( + np.sqrt(H_NEAR**2 + (_SLOPE * d) ** 2), H_FAR) ** 2 + + +def _density(mesh): + x, y = mesh.X + d = sympy.Abs(y - CENTRE) + return 1.0 / sympy.Min( + sympy.sqrt(H_NEAR**2 + (_SLOPE * d) ** 2), H_FAR) ** 2 + + +def _child(max_levels=3, **kw): + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25, + refinement=1, qdegree=2) + return base.adapt(_metric, max_levels=max_levels, **kw) + + +def _tris(mesh): + dm = mesh.dm + vS, vE = dm.getDepthStratum(0) + cS, cE = dm.getHeightStratum(0) + return np.asarray([[q - vS for q in dm.getTransitiveClosure(c)[0] + if vS <= q < vE] for c in range(cS, cE)]) + + +def _coords(mesh): + return mesh.dm.getCoordinatesLocal().array.reshape(-1, 2).copy() + + +def _signed_area(p, t): + a, b, c = p[t[:, 0]], p[t[:, 1]], p[t[:, 2]] + return 0.5 * ((b[:, 0] - a[:, 0]) * (c[:, 1] - a[:, 1]) + - (c[:, 0] - a[:, 0]) * (b[:, 1] - a[:, 1])) + + +def _max_angles(p, t): + P = p[t] + out = [] + for k in range(3): + u, v = P[:, (k + 1) % 3] - P[:, k], P[:, (k + 2) % 3] - P[:, k] + out.append(np.degrees(np.arccos(np.clip( + np.sum(u * v, axis=1) / (np.linalg.norm(u, axis=1) + * np.linalg.norm(v, axis=1) + 1e-300), + -1.0, 1.0)))) + return np.stack(out, axis=1).max(axis=1) + + +def _h_on_feature(p, t): + ar = np.abs(_signed_area(p, t)) + on = np.abs(p[t].mean(axis=1)[:, 1] - CENTRE) < 3 * H_NEAR + return float(np.median(np.sqrt(2 * ar)[on])) + + +def test_relax_preserves_topology_and_does_not_fold(): + child = _child() + t = _tris(child) + n_cells, n_verts = len(t), len(_coords(child)) + s0 = _signed_area(_coords(child), t) + + child.relax(method_kwargs=dict(n_outer=20)) + + assert len(_tris(child)) == n_cells + assert len(_coords(child)) == n_verts + s1 = _signed_area(_coords(child), t) + assert np.all(np.sign(np.median(s0)) * s1 > 0.0), "a cell folded" + + +def test_relax_preserves_the_grading(): + """The point of the 'ideal' frame: size is held, only shape moves.""" + child = _child() + t = _tris(child) + h0 = _h_on_feature(_coords(child), t) + + child.relax(method_kwargs=dict(n_outer=20)) + + h1 = _h_on_feature(_coords(child), t) + assert h1 == pytest.approx(h0, rel=0.25), ( + f"relaxation changed on-feature spacing {h0:.4f} -> {h1:.4f}; it " + f"should preserve the size distribution, not re-derive it") + + +def test_pure_shape_relax_improves_the_max_angle_tail(): + """The property relaxation exists to fix. + + NOTE the metric-free call. Passing a metric puts the mover in the + ideal-METRIC frame, where it re-grades as well as reshapes and will + trade element shape away to chase the size field: measured on this + mesh, 117.9 -> 113.8 degrees without a metric but 117.9 -> 127.4 WITH + one. Relaxing per generation does best of all (117.9 -> 101.2). So + "relax" and "relax to a metric" are different operations and only the + first is a shape guarantee. + """ + child = _child(max_levels=4) + t = _tris(child) + before = np.percentile(_max_angles(_coords(child), t), 99) + + child.relax(method_kwargs=dict(n_outer=40)) + + after = np.percentile(_max_angles(_coords(child), t), 99) + assert after <= before, ( + f"99th-percentile max angle got worse: {before:.1f} -> {after:.1f}") + + +def test_adapt_relax_placements_run_and_at_end_keeps_the_cell_count(): + plain = len(_tris(_child())) + at_end = _child(relax=True, relax_kwargs=dict( + method_kwargs=dict(n_outer=10))) + per_gen = _child(relax="per-generation", relax_kwargs=dict( + method_kwargs=dict(n_outer=10))) + + # relaxing after the last generation cannot change the topology + assert len(_tris(at_end)) == plain + # relaxing inside the loop changes what gets marked, so the count may + # differ -- it must still be a sane mesh + assert len(_tris(per_gen)) > 0 + s = _signed_area(_coords(per_gen), _tris(per_gen)) + assert np.all(np.sign(np.median(s)) * s > 0.0) + + +def test_adapt_relax_placements_run_in_3d(): + """3D goes through the cell-list refinement engine (the native uwnvb + transform is 2D-only), so this covers the OTHER relax hook.""" + def metric3d(c): + d = np.sqrt((c[:, 0] - 0.5)**2 + (c[:, 1] - 0.5)**2) + return 1.0/np.minimum( + np.sqrt(0.05**2 + (2.0*np.abs(d - 0.3))**2), 0.3)**2 + + def build(relax): + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0, 0.0), maxCoords=(1.0, 1.0, 1.0), + cellSize=0.5, refinement=1, qdegree=2) + return base.adapt(metric3d, max_levels=1, relax=relax, + relax_kwargs=dict(method_kwargs=dict(n_outer=8))) + + def ncells(m): + cs, ce = m.dm.getHeightStratum(0) + return ce - cs + + plain, at_end = build(False), build(True) + assert ncells(at_end) == ncells(plain) # end-relax cannot retopologise + per_gen = build("per-generation") + assert ncells(per_gen) > 0 + for m in (at_end, per_gen): + p = m.dm.getCoordinatesLocal().array.reshape(-1, 3) + assert np.isfinite(p).all() + + +def test_relax_rejects_a_contradictory_reference_frame(): + child = _child(max_levels=2) + with pytest.raises(ValueError, match="ideal-reference-frame"): + child.relax(method_kwargs=dict(reference="mesh")) + + +def test_adapt_rejects_an_unknown_relax_placement(): + with pytest.raises(ValueError, match="relax="): + _child(max_levels=2, relax="sideways") From 9f8eeddc0fb3b17248a92f1f46449497ac1c365b Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 20:29:53 +1000 Subject: [PATCH 06/16] =?UTF-8?q?docs(relax):=20correct=20the=20"MG=20is?= =?UTF-8?q?=20unaffected"=20claim=20=E2=80=94=203D=20can=20fail=20the=20cu?= =?UTF-8?q?stom-P=20build=20(#424)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-running the adaptivity demos with relaxation turned on exposed a failure I had ruled out on 2D-only evidence. In 3D, relaxing an adapted mesh can make the mesh-owned custom-P FMG hierarchy fail to build: custom_mg: mesh-owned FMG build failed (transfer 6->7 has 26 zero columns (coarse DOFs with no fine image) ...); using the solver's default preconditioner. and the solver then SILENTLY falls back to GAMG. Measured on a 3D Poisson gate: adapt-only and adapt+relax-at-end gave pc=mg at 2 its, relax="per-generation" gave pc=gamg at 23; in a larger demo relax-at-end failed too, so both placements are affected and it appears to depend on mesh size and depth. 2D is unaffected throughout (Stokes and Poisson). The prolongation locates fine DOFs inside coarse cells; relaxation moves the fine coordinates and some coarse DOF ends up with no fine image -> zero column -> singular coarse operator. My earlier claim came from measuring only 2D and generalising. The docs and the Mesh.relax docstring now state the 3D caveat and point at #424. Underworld development team with AI support from Claude Code --- .../subsystems/mesh-shape-relaxation.md | 37 ++++++++++++++----- .../discretisation/discretisation_mesh.py | 8 ++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/developer/subsystems/mesh-shape-relaxation.md b/docs/developer/subsystems/mesh-shape-relaxation.md index 1f5738bc6..8004a486e 100644 --- a/docs/developer/subsystems/mesh-shape-relaxation.md +++ b/docs/developer/subsystems/mesh-shape-relaxation.md @@ -92,15 +92,34 @@ 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 is unaffected - -Relaxation moves only the finest level's coordinates. The custom-P geometric-MG -tail needs the *topological* hierarchy preserved in its operators, and the -coarse levels keep their own coordinates, so nothing downstream is disturbed — -the transfers already accept non-nested coarse/fine pairs. Measured with the -Stokes velocity block on custom-P FMG: full 4-level `pc=mg` in every -configuration, no fallback to GAMG, solutions agreeing to four significant -figures, and the at-end case one Krylov iteration *cheaper*. +## 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*. + +```{warning} +In **3D** relaxation can make the custom-P hierarchy fail to build, and the +failure is **silent** — a `UserWarning` and a fall back to GAMG: + + custom_mg: mesh-owned FMG build failed (transfer 6->7 has 26 zero + columns (coarse DOFs with no fine image) ...); using the solver's + default preconditioner. + +Measured on a 3D Poisson gate: adapt-only and adapt+relax-at-end both gave +`pc=mg` at 2 iterations, but `relax="per-generation"` fell back to `pc=gamg` +at 23; in a larger demo (~36k cells) relax-at-end failed too. Both placements +are affected and it appears to depend on mesh size and depth. + +The prolongation is built by locating fine DOFs inside coarse cells; +relaxation moves the fine coordinates and some coarse DOF ends up with no +fine image, giving a zero column and a singular coarse operator. **If you +rely on geometric MG in 3D, check the preconditioner type after adapting +with relaxation.** Tracked as issue #424. +``` ## What relaxation cannot do diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 50bd3dcb2..907409757 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6631,6 +6631,14 @@ def relax(self, metric=None, *, verbose=False, **kwargs): Non-folding by construction, and the parallel partition, vertex count and DOF layout are unchanged. + ```{warning} + In **3D** this can make the mesh-owned custom-P geometric-MG + hierarchy fail to build (a moved fine DOF leaves its coarse + parent, giving a zero transfer column), in which case the solver + SILENTLY falls back to GAMG. 2D is unaffected. Check the + preconditioner type if you rely on geometric MG in 3D. See #424. + ``` + **Two valid placements, neither dominant.** ``adapt(metric, ..., relax=True)`` relaxes once at the end — the recommended default. ``relax="per-generation"`` relaxes inside the refinement loop, so From 5359890ba738dda877f94e8c7a7c3e0bf0a576ca Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 21:36:44 +1000 Subject: [PATCH 07/16] fix(custom-mg): retry with the global-support RBF builder before dropping to GAMG (#424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The custom-P prolongation is built GEOMETRICALLY, not from the refinement relation: `barycentric_prolongation` re-triangulates the coarse DOF point cloud (`Delaunay(coarse_coords)`) and locates each fine DOF in one simplex of it. That is deliberate — it is what lets custom-P accept non-nested coarse/fine pairs — but it means a preserved topology buys the transfer nothing, and the builder has only LOCAL support: a coarse DOF is reached only if some fine DOF lands in a simplex touching it. Move the fine coordinates (which is exactly what mesh.relax 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. The build then abandoned geometric MG entirely and fell back to the solver's default preconditioner — silently, so it presented only as a slow solve. 3D is the exposed case: Delaunay of a graded 3D cloud is sliver-ridden, each simplex has four vertices, more DOFs sit near the hull. `rbf_prolongation` has GLOBAL support — every coarse DOF is reached through the RBF solve — so it cannot produce a zero column. Retry with it before giving up, and warn that we did rather than degrade in silence. 3D adapt + relax="per-generation": gamg 23 its -> pc=mg 2 its 3D combine demo (transfer 6->7, 26 zero columns, ~36k cells): gamg 26 its -> pc=mg 2 its This is strictly better for ANY cause of zero columns, not just relaxation: dropping to GAMG discarded the whole hierarchy when a cheaper degradation was available. Docs and the Mesh.relax docstring now carry the mechanism, replacing my earlier "MG is unaffected" claim (which generalised from 2D-only measurements). Underworld development team with AI support from Claude Code --- .../subsystems/mesh-shape-relaxation.md | 47 +++++++++++-------- .../discretisation/discretisation_mesh.py | 14 +++--- src/underworld3/utilities/custom_mg.py | 42 +++++++++++++---- 3 files changed, 68 insertions(+), 35 deletions(-) diff --git a/docs/developer/subsystems/mesh-shape-relaxation.md b/docs/developer/subsystems/mesh-shape-relaxation.md index 8004a486e..3958f0ba2 100644 --- a/docs/developer/subsystems/mesh-shape-relaxation.md +++ b/docs/developer/subsystems/mesh-shape-relaxation.md @@ -101,25 +101,34 @@ Poisson: full `pc=mg` in every configuration, no fallback, solutions agreeing to four significant figures, and the at-end case one Krylov iteration *cheaper*. -```{warning} -In **3D** relaxation can make the custom-P hierarchy fail to build, and the -failure is **silent** — a `UserWarning` and a fall back to GAMG: - - custom_mg: mesh-owned FMG build failed (transfer 6->7 has 26 zero - columns (coarse DOFs with no fine image) ...); using the solver's - default preconditioner. - -Measured on a 3D Poisson gate: adapt-only and adapt+relax-at-end both gave -`pc=mg` at 2 iterations, but `relax="per-generation"` fell back to `pc=gamg` -at 23; in a larger demo (~36k cells) relax-at-end failed too. Both placements -are affected and it appears to depend on mesh size and depth. - -The prolongation is built by locating fine DOFs inside coarse cells; -relaxation moves the fine coordinates and some coarse DOF ends up with no -fine image, giving a zero column and a singular coarse operator. **If you -rely on geometric MG in 3D, check the preconditioner type after adapting -with relaxation.** Tracked as issue #424. -``` +### 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 `rbf` builder has **global support** — every coarse DOF is reached through +the RBF solve — so it cannot produce a zero column. The FMG build therefore +**retries with `rbf` automatically** before giving up, and warns that it did: + + custom_mg: barycentric transfer build failed (transfer 2->3 has 1 zero + columns ...); retrying with the 'rbf' builder, which has global support + and cannot leave a coarse DOF without a fine image. + +Measured on a relaxed 3D adapt child: barycentric alone fell back to GAMG at +23 iterations; with the retry it keeps `pc=mg` at 2. Set +`mesh._custom_mg_builder = "rbf"` to skip the first attempt. ## What relaxation cannot do diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 907409757..11f0d53b8 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6631,13 +6631,13 @@ def relax(self, metric=None, *, verbose=False, **kwargs): Non-folding by construction, and the parallel partition, vertex count and DOF layout are unchanged. - ```{warning} - In **3D** this can make the mesh-owned custom-P geometric-MG - hierarchy fail to build (a moved fine DOF leaves its coarse - parent, giving a zero transfer column), in which case the solver - SILENTLY falls back to GAMG. 2D is unaffected. Check the - preconditioner type if you rely on geometric MG in 3D. See #424. - ``` + Moving the nodes can upset the custom-P geometric-MG transfers, + which are built by geometric point location rather than from the + refinement relation: the local-support ``barycentric`` builder can + be left with a coarse DOF that has no fine image. The FMG build + now retries with the global-support ``rbf`` builder before giving + up, so the hierarchy survives (measured in 3D: GAMG at 23 + iterations before the retry, ``pc=mg`` at 2 after). See #424. **Two valid placements, neither dominant.** ``adapt(metric, ..., relax=True)`` relaxes once at the end — the recommended default. diff --git a/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index ccd9b07cd..8ffd2b67d 100644 --- a/src/underworld3/utilities/custom_mg.py +++ b/src/underworld3/utilities/custom_mg.py @@ -871,15 +871,39 @@ def auto_inject_custom_mg(solver, field_id=None): return # nothing to inject builder = getattr(solver.mesh, "_custom_mg_builder", "barycentric") - h = CustomMGHierarchy(list(coarse) + [solver.mesh], builder=builder, - field_id=field_id) - try: - Ps = h.build(solver) - except Exception as exc: # pragma: no cover - defensive - import warnings - warnings.warn(f"custom_mg: mesh-owned FMG build failed ({exc}); using the " - "solver's default preconditioner.") - return + # Retry with the RBF builder before abandoning geometric MG. The + # barycentric builder has LOCAL support: it re-triangulates the coarse + # DOF cloud and locates each fine DOF in one simplex, so a coarse DOF + # is only reached if some fine DOF lands in a simplex touching it. Move + # the fine coordinates — which is exactly what mesh.relax() does — and a + # coarse DOF can lose every fine image, giving a zero column and a + # singular Galerkin coarse operator. The RBF builder has GLOBAL support + # (every coarse DOF is reached through the RBF solve), so it does not + # have that failure mode: measured on a relaxed 3D adapt child, + # barycentric fell back to GAMG at 23 its while RBF kept pc=mg at 2. + # Falling back to GAMG loses the hierarchy entirely, so try the cheaper + # degradation first. See #424. + _attempts = [builder] + (["rbf"] if builder != "rbf" else []) + h = Ps = None + for _i, _b in enumerate(_attempts): + h = CustomMGHierarchy(list(coarse) + [solver.mesh], builder=_b, + field_id=field_id) + try: + Ps = h.build(solver) + break + except Exception as exc: # pragma: no cover - defensive + import warnings + if _i + 1 < len(_attempts): + warnings.warn( + f"custom_mg: {_b} transfer build failed ({exc}); " + f"retrying with the '{_attempts[_i + 1]}' builder, which " + f"has global support and cannot leave a coarse DOF " + f"without a fine image.") + continue + warnings.warn( + f"custom_mg: mesh-owned FMG build failed ({exc}); using the " + "solver's default preconditioner.") + return # Dimensional guard (checkable for the monolithic operator, field_id is None): # the finest transfer must chain to the operator PCMG will Galerkin against. From 39ce20240bcb047b35be2540f8332d4b120bcd2e Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 21:50:51 +1000 Subject: [PATCH 08/16] =?UTF-8?q?docs(design):=20two=20MG=20transfer=20pat?= =?UTF-8?q?hs=20=E2=80=94=20use=20the=20nested=20hierarchy=20we=20already?= =?UTF-8?q?=20pay=20for?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The adapt hierarchy is maintained exactly (that is what NVB conforming closure and its halo cost buy) and the MG transfer then discards it, re-deriving an approximation by Delaunay point location on the coarse DOF cloud. That is the direct cause of #424: the barycentric builder has only LOCAL support, so moving the fine coordinates can leave a coarse DOF with no fine image and a singular coarse operator. The nested transfer is trivial and cannot go singular: every fine vertex is either an inherited coarse vertex (weight 1) or the midpoint of a coarse edge (weights 1/2, 1/2). Structurally full rank, immune to node motion, 1-2 nonzeros per row. Both engines already record it (edge2mid in nvb.py; the native transform's split-edge bookkeeping), and our own petsc_dm_set_regular_refinement wrapper — the flag for PETSc's exact nested path — is never called. Keeps the geometric builder for the genuinely non-nested pairs it was asked for (moved base vs child, unrelated meshes, the planned seed-point variant). Records the ordering trap: the engine-id -> DM-point bridge is coordinate matching, which is exact only before snapping/relaxation moves midpoints off their parents. The native path has a clean window; the cell-list path does not, so to_dm should return its id map instead. Flags the accuracy-vs-robustness trade as something to MEASURE on curved cases rather than assume. Underworld development team with AI support from Claude Code --- .../nested-vs-geometric-mg-transfers.md | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 docs/developer/design/nested-vs-geometric-mg-transfers.md diff --git a/docs/developer/design/nested-vs-geometric-mg-transfers.md b/docs/developer/design/nested-vs-geometric-mg-transfers.md new file mode 100644 index 000000000..7dd3e3d1f --- /dev/null +++ b/docs/developer/design/nested-vs-geometric-mg-transfers.md @@ -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). From e24ad0e16fb04a85a162265d518bf8e9cbc35034 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sun, 26 Jul 2026 22:14:07 +1000 Subject: [PATCH 09/16] feat(adapt): record the EXACT nested MG prolongation per refinement pass (#425) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 1 of using the hierarchy we already pay to maintain. adapt() now records, for every refinement pass, the true P1 embedding of the coarse space in the fine one — built from the parent/child relation rather than re-derived by Delaunay point location on the coarse DOF cloud. Every fine vertex is either an inherited coarse vertex (weight 1 on itself) or the midpoint of a coarse edge (1/2, 1/2). Measured on the recorded transfers, 2D and 3D: partition of unity rowsum in [1.000000000000, 1.000000000000] zero columns 0 in every pass <- makes #424 impossible here linear reproduction max|P x_c - x_f| = 0 (worst 1.1e-16) sparsity 1.0-1.4 nnz/row vs dim+1 for point location Two things this had to get right: A refine PASS is not one bisection LEVEL. The conforming closure cascades, so a vertex can be the midpoint of an already-split half-edge and sit at the QUARTER point of the original coarse edge — it matches neither a coarse vertex nor a coarse edge midpoint (observed: 3.3e-2 off, a quarter edge). Resolution is therefore iterative: seed from coarse vertices and coarse edge midpoints, then repeatedly resolve any vertex that is the midpoint of two already-resolved fine neighbours, composing weights. Exact at any depth. The capture must happen in the pristine window. The engine-id/DM-point bridge is coordinate matching, exact only before snapping or relaxation moves midpoints off their parents. On the native path that window is between _nvbx.refine() and snap_level_boundaries(); the capture goes there. The cell-list engine records its map in to_dm() instead, where the two numberings meet. Also corrects a claim I committed earlier: 3D does NOT go through the cell-list engine. Both 2D and 3D prefer the native uwnvb transform when it is built (cell-list is the np=1 fallback), so the 3D relax test does not cover the cell-list hook as its docstring claimed. That hook is still uncovered; the docstring now says so. Not yet wired into custom_mg — consuming these as a "topological" builder is the next step, and the accuracy-vs-robustness question on curved boundaries still needs measuring before it becomes the default. Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 39 +++- src/underworld3/utilities/nvb.py | 183 ++++++++++++++++++ tests/test_0752_mesh_shape_relaxation.py | 9 +- tests/test_0753_nested_mg_prolongation.py | 93 +++++++++ 4 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 tests/test_0753_nested_mg_prolongation.py diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 11f0d53b8..d918c1d42 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -7200,6 +7200,12 @@ def _relax_generation(engine_obj, carry, rcarry): engine_obj.coords[_i] = _post[_k] level_dms = [] # one DM per refinement level + # Nested (topological) MG prolongations, one per refinement generation. + # `from_dm` numbers engine vertices as `DM point - vS`, so the base map + # is that offset; each generation's map comes back from `to_dm`. + _nested_Ps = [] + _vS0, _vE0 = base_finest.getDepthStratum(0) + _coarse_vmap = {i: _vS0 + i for i in range(_vE0 - _vS0)} if engine == "nvb" and _nvbx is not None: # Native uwnvb DMPlexTransform. Each pass marks the cells whose current @@ -7239,7 +7245,16 @@ def _relax_generation(engine_obj, carry, rcarry): lab.setDefaultValue(0) for cidx in marked: lab.setValue(cidx, DM_ADAPT_REFINE) + _coarse_for_P = current_dm current_dm = _nvbx.refine(d, "adapt") + # Capture the exact parent/child prolongation NOW, in the one + # window where the coordinates are still pristine: the snap + # below moves boundary midpoints off their parent edges, and + # relaxation moves everything, after which the relation can no + # longer be recovered by matching. See #425. + from underworld3.utilities.nvb import ( + nested_prolongation_from_dms as _nested_from_dms) + _nested_Ps.append(_nested_from_dms(_coarse_for_P, current_dm)) snap_level_boundaries(current_dm) if _relax_mode == "per-generation": # Relax THIS generation before the next one marks from it: @@ -7273,7 +7288,8 @@ def _relax_generation(engine_obj, carry, rcarry): # bound. A bisection halves the cell volume, so h shrinks by # 2^(1/dim) per generation and one isotropic-equivalent # ``max_levels`` is dim generations. - from underworld3.utilities.nvb import NVBMesh, TaggedBisectionMesh + from underworld3.utilities.nvb import (NVBMesh, TaggedBisectionMesh, + nested_prolongation) _Engine = TaggedBisectionMesh if self.dim == 3 else NVBMesh carry = [(b.name, b.value) for b in self.boundaries if b.name not in ("Null_Boundary", "All_Boundaries")] @@ -7296,6 +7312,7 @@ def _relax_generation(engine_obj, carry, rcarry): sel = sel[order[:node_budget]] marked = [int(cids[j]) for j in sel] markers_per_level.append(marked) + _n_coarse_verts = len(nvb.coords) # before this generation nvb.refine(set(marked)) # Snap INSIDE the engine: its own coordinates feed the next # generation's marking AND the next midpoints, so snapping @@ -7317,8 +7334,20 @@ def _relax_generation(engine_obj, carry, rcarry): nvb.coords[_i] = _snapped[_k] if _relax_mode == "per-generation": _relax_generation(nvb, carry, rcarry) - level_dms.append(nvb.to_dm(boundaries=carry, regions=rcarry, - comm=self.dm.comm)) + _gen_dm = nvb.to_dm(boundaries=carry, regions=rcarry, + comm=self.dm.comm) + level_dms.append(_gen_dm) + # Record the EXACT prolongation for this generation while the + # engine still knows the parent/child relation. Built from + # `edge2mid`, not by point location, so it is full rank by + # construction and survives any later node motion (relax / + # snap / deformation). See design/nested-vs-geometric-mg-transfers. + _vSg, _vEg = _gen_dm.getDepthStratum(0) + _fine_map = dict(nvb.dm_vertex_of_engine) + _nested_Ps.append(nested_prolongation( + nvb, _coarse_vmap, _fine_map, _n_coarse_verts, + _vSg, _vEg - _vSg)) + _coarse_vmap = _fine_map if verbose: uw.pprint(0, f"[adapt] nvb gen {level}: marked {len(marked)} " f"-> {len(nvb.cells)} cells") @@ -7388,6 +7417,10 @@ def _relax_generation(engine_obj, carry, rcarry): # checkpoint-by-marker payload (design only; storage is a follow-up). child._adapt_markers = markers_per_level child._adapt_engine = engine + # Exact per-generation prolongations when the engine could supply them + # (cell-list path). Empty for the native transform path, which falls + # back to the geometric builder. See #425. + child._adapt_prolongation = _nested_Ps # Mesh-owned custom-P geometric-MG tail. EVERY refinement level is its own # MG level (one custom-P transfer per refinement step), not a single # base-finest -> child jump: the tail is diff --git a/src/underworld3/utilities/nvb.py b/src/underworld3/utilities/nvb.py index b76c9cd86..4e13954bb 100644 --- a/src/underworld3/utilities/nvb.py +++ b/src/underworld3/utilities/nvb.py @@ -168,6 +168,179 @@ def _fs(a, b): return (a, b) if a < b else (b, a) +def nested_prolongation_from_dms(coarse_dm, fine_dm, tol=1.0e-10): + """Recover a refinement pass's exact P1 prolongation from the two DMs. + + For engines that do not expose their parent/child map (the native + ``DMPlexTransform`` path), the relation can still be recovered exactly + **while the coordinates are pristine** — after refinement but BEFORE any + boundary snap or relaxation moves a midpoint off its parent edge. + + One ``refine`` pass is not necessarily one bisection *level*: the + conforming closure cascades, so a vertex can be the midpoint of an + already-split half-edge and therefore sit at the quarter point of the + original coarse edge. Resolution is iterative: + + 1. a fine vertex coincident with a coarse vertex is inherited (weight 1); + one coincident with a coarse edge midpoint gets 1/2, 1/2; + 2. any still-unresolved vertex that is the midpoint of two ALREADY-RESOLVED + fine neighbours takes the average of their weights; + 3. repeat until nothing new resolves. + + Weights compose exactly, so the result is the true FE embedding at any + cascade depth. Returns ``(rows, cols, vals)`` as in + :func:`nested_prolongation`, or ``None`` if any vertex remains unresolved + — in which case the caller should fall back to the geometric builder + rather than guess. + """ + from scipy.spatial import cKDTree + + cvS, cvE = coarse_dm.getDepthStratum(0) + ceS, ceE = coarse_dm.getDepthStratum(1) + cdim = coarse_dm.getCoordinateDim() + cxyz = coarse_dm.getCoordinatesLocal().array.reshape(-1, cdim) + + edges = [(c[0] - cvS, c[1] - cvS) + for e in range(ceS, ceE) + for c in (coarse_dm.getCone(e),) + if len(c) == 2 and all(cvS <= q < cvE for q in c)] + if not edges: + return None + edges = np.asarray(edges, dtype=np.int64) + + fvS, fvE = fine_dm.getDepthStratum(0) + feS, feE = fine_dm.getDepthStratum(1) + fxyz = fine_dm.getCoordinatesLocal().array.reshape(-1, cdim) + n_f = fvE - fvS + if fxyz.shape[0] != n_f: + return None + scale = float(np.abs(cxyz).max()) or 1.0 + atol = tol * scale + + # --- round 1: coarse vertices and coarse edge midpoints --------------- + targets = np.vstack([cxyz, 0.5 * (cxyz[edges[:, 0]] + cxyz[edges[:, 1]])]) + dist, idx = cKDTree(targets).query(fxyz) + nc = cxyz.shape[0] + weights = [None] * n_f + for r in range(n_f): + if dist[r] > atol: + continue + t = int(idx[r]) + if t < nc: + weights[r] = {t: 1.0} + else: + a, b = edges[t - nc] + weights[r] = {int(a): 0.5, int(b): 0.5} + + # --- rounds 2+: midpoints of already-resolved fine neighbours --------- + unresolved = [r for r in range(n_f) if weights[r] is None] + if unresolved: + nbr = [[] for _ in range(n_f)] + for e in range(feS, feE): + c = fine_dm.getCone(e) + if len(c) == 2 and all(fvS <= q < fvE for q in c): + u, v = int(c[0] - fvS), int(c[1] - fvS) + nbr[u].append(v) + nbr[v].append(u) + while unresolved: + progressed = False + still = [] + for r in unresolved: + done = False + cand = [q for q in nbr[r] if weights[q] is not None] + for i in range(len(cand)): + for j in range(i + 1, len(cand)): + p, q = cand[i], cand[j] + if np.linalg.norm( + fxyz[r] - 0.5 * (fxyz[p] + fxyz[q])) <= atol: + w = {} + for src in (p, q): + for pt, ww in weights[src].items(): + w[pt] = w.get(pt, 0.0) + 0.5 * ww + weights[r] = w + progressed = done = True + break + if done: + break + if not done: + still.append(r) + if not progressed: + return None # cannot be explained by bisection + unresolved = still + + rows, cols, vals = [], [], [] + for r in range(n_f): + for pt, w in weights[r].items(): + rows.append(r) + cols.append(pt) + vals.append(w) + return (np.asarray(rows, dtype=np.int64), + np.asarray(cols, dtype=np.int64), + np.asarray(vals, dtype=float)) + + +def nested_prolongation(engine, coarse_map, fine_map, n_coarse, vS_fine, + n_fine): + """Exact P1 prolongation for ONE bisection generation, in DM numbering. + + A bisection generation adds exactly one kind of vertex: the midpoint of a + coarse edge. So every fine vertex is either + + * **inherited** from the coarse level -> weight 1 on itself, or + * the **midpoint of edge (a, b)** -> weight 1/2 on each of ``a``, ``b``. + + That is the FE embedding of the coarse P1 space in the fine one, and unlike + a point-located transfer it is **structurally full rank**: every coarse DOF + carries weight 1 into its own inherited fine DOF, so no coarse DOF can be + left without a fine image (the zero-column failure of #424 cannot arise). + It is also purely topological, so relaxing or snapping the mesh afterwards + does not disturb it. + + ``coarse_map`` / ``fine_map`` are engine-vertex-id -> DM-point for the two + levels (recorded by :meth:`to_dm`); ``n_coarse`` is the engine vertex count + *before* this generation refined, which is what separates inherited + vertices from new ones. + + Midpoints whose own parents were created earlier in the SAME generation + (possible when the conforming closure cascades) are resolved recursively + and their weights composed, so the result is correct regardless of the + order in which the closure fired. + + Returns ``(rows, cols, vals)`` for a ``(n_fine, n_coarse_dm)`` matrix in + DM vertex indices local to each level's vertex stratum. + """ + mid2edge = {m: e for e, m in engine.edge2mid.items()} + memo = {} + + def _weights(eid): + """Coarse-DM-point -> weight for engine vertex ``eid``.""" + if eid in memo: + return memo[eid] + if eid < n_coarse: + out = {coarse_map[eid]: 1.0} + else: + a, b = mid2edge[eid] + out = {} + for parent, half in ((a, 0.5), (b, 0.5)): + for pt, w in _weights(parent).items(): + out[pt] = out.get(pt, 0.0) + half * w + memo[eid] = out + return out + + rows, cols, vals = [], [], [] + for eid, fpt in fine_map.items(): + r = fpt - vS_fine + if r < 0 or r >= n_fine: + continue + for pt, w in _weights(eid).items(): + rows.append(r) + cols.append(pt) + vals.append(w) + return (np.asarray(rows, dtype=np.int64), + np.asarray(cols, dtype=np.int64), + np.asarray(vals, dtype=float)) + + class NVBMesh: """A 2D newest-vertex-bisection triangulation with boundary-edge and region-cell labels carried across bisections. @@ -442,6 +615,13 @@ def to_dm(self, boundaries=(), regions=(), comm=None): dm_vcoords = dm.getCoordinatesLocal().array.reshape(-1, 2) _, nearest = cKDTree(np.array(self.coords)).query(dm_vcoords) nvb_of_dmvert = {vS + i: int(nearest[i]) for i in range(vE - vS)} + # Engine-id <-> DM-point map for THIS export, kept so the nested MG + # prolongation can be built from the exact parent/child relation + # (``edge2mid``) instead of re-deriving it by point location. Recorded + # here because this is the only place the two numberings meet; a caller + # that snaps or relaxes afterwards would no longer be able to recover + # it by coordinate matching. See design/nested-vs-geometric-mg-transfers. + self.dm_vertex_of_engine = {v: k for k, v in nvb_of_dmvert.items()} # outer geometric boundary (UW convention) dm.markBoundaryFaces("All_Boundaries", 1001) @@ -833,6 +1013,9 @@ def to_dm(self, boundaries=(), regions=(), comm=None): -1, dm.getCoordinateDim()) _, nearest = cKDTree(np.array(self.coords)).query(dm_vcoords) eng_of_dmvert = {vS + i: int(nearest[i]) for i in range(vE - vS)} + # See the note in NVBMesh.to_dm: engine-id -> DM-point, recorded at the + # one point the two numberings meet, for the nested MG prolongation. + self.dm_vertex_of_engine = {v: k for k, v in eng_of_dmvert.items()} dm.markBoundaryFaces("All_Boundaries", 1001) diff --git a/tests/test_0752_mesh_shape_relaxation.py b/tests/test_0752_mesh_shape_relaxation.py index b9f2209bd..339de2255 100644 --- a/tests/test_0752_mesh_shape_relaxation.py +++ b/tests/test_0752_mesh_shape_relaxation.py @@ -143,8 +143,13 @@ def test_adapt_relax_placements_run_and_at_end_keeps_the_cell_count(): def test_adapt_relax_placements_run_in_3d(): - """3D goes through the cell-list refinement engine (the native uwnvb - transform is 2D-only), so this covers the OTHER relax hook.""" + """Relaxation composes with adapt in 3D. + + NB this does NOT cover the cell-list refinement engine: 3D prefers the + native uwnvb transform too when it is built (the cell-list engine is the + np=1 fallback), so both this and the 2D case exercise the native path. + The cell-list relax hook remains uncovered. + """ def metric3d(c): d = np.sqrt((c[:, 0] - 0.5)**2 + (c[:, 1] - 0.5)**2) return 1.0/np.minimum( diff --git a/tests/test_0753_nested_mg_prolongation.py b/tests/test_0753_nested_mg_prolongation.py new file mode 100644 index 000000000..7ca136662 --- /dev/null +++ b/tests/test_0753_nested_mg_prolongation.py @@ -0,0 +1,93 @@ +"""Exact nested MG prolongations recorded by ``mesh.adapt`` (#425). + +``adapt`` maintains an exact refinement hierarchy; the MG transfer used to +discard it and re-derive an approximation by Delaunay point location, which +is what made #424 possible (a coarse DOF with no fine image -> zero column +-> singular coarse operator). + +The recorded transfer is the true P1 embedding: every fine vertex is an +inherited coarse vertex (weight 1) or a midpoint (1/2, 1/2), composed +through any closure cascade. The properties asserted here are what make it +better than point location, not merely different. +""" +import numpy as np +import pytest +import scipy.sparse as sp +import underworld3 as uw + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_a] + + +def _metric(centroids): + d = np.abs(np.asarray(centroids)[:, -1] - 0.5) + return 1.0 / np.minimum(np.sqrt(0.05**2 + (2.0 * d) ** 2), 0.3) ** 2 + + +def _adapted(dim, cell_size): + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0,) * dim, maxCoords=(1.0,) * dim, + cellSize=cell_size, refinement=1, qdegree=2) + return base.adapt(_metric, max_levels=2) + + +def _levels(child): + return [m.dm for m in child._custom_mg_coarse_meshes] + [child.dm] + + +def _as_matrix(entry, coarse_dm, fine_dm): + rows, cols, vals = entry + cvS, cvE = coarse_dm.getDepthStratum(0) + fvS, fvE = fine_dm.getDepthStratum(0) + return sp.csr_matrix((vals, (rows, cols)), shape=(fvE - fvS, cvE - cvS)) + + +@pytest.mark.parametrize("dim,cell_size", [(2, 0.2), (3, 0.4)]) +def test_every_pass_records_a_prolongation(dim, cell_size): + child = _adapted(dim, cell_size) + Ps = child._adapt_prolongation + assert Ps, "adapt recorded no nested prolongations" + assert all(P is not None for P in Ps), ( + "a refinement pass could not be expressed as a bisection embedding") + + +@pytest.mark.parametrize("dim,cell_size", [(2, 0.2), (3, 0.4)]) +def test_partition_of_unity_and_no_zero_columns(dim, cell_size): + """No zero column is the property that makes #424 impossible here.""" + child = _adapted(dim, cell_size) + Ps = child._adapt_prolongation + lvl = _levels(child)[-(len(Ps) + 1):] + for k, entry in enumerate(Ps): + P = _as_matrix(entry, lvl[k], lvl[k + 1]) + rowsum = np.asarray(P.sum(axis=1)).ravel() + assert np.allclose(rowsum, 1.0, atol=1e-12), ( + f"pass {k}: prolongation is not a partition of unity") + colsum = np.asarray(P.sum(axis=0)).ravel() + assert int((colsum == 0.0).sum()) == 0, ( + f"pass {k}: coarse DOF with no fine image — this is exactly the " + f"zero-column failure the nested transfer is meant to preclude") + + +@pytest.mark.parametrize("dim,cell_size", [(2, 0.2), (3, 0.4)]) +def test_reproduces_a_linear_field_exactly(dim, cell_size): + """P1 interpolation of a linear function is that function.""" + child = _adapted(dim, cell_size) + Ps = child._adapt_prolongation + lvl = _levels(child)[-(len(Ps) + 1):] + for k, entry in enumerate(Ps): + cdm, fdm = lvl[k], lvl[k + 1] + P = _as_matrix(entry, cdm, fdm) + xc = cdm.getCoordinatesLocal().array.reshape(-1, dim) + xf = fdm.getCoordinatesLocal().array.reshape(-1, dim) + assert P.shape == (xf.shape[0], xc.shape[0]) + assert np.abs(P @ xc - xf).max() < 1e-12, ( + f"pass {k}: prolongation does not reproduce a linear field") + + +def test_transfer_is_sparser_than_point_location(): + """1-2 nonzeros per row, vs dim+1 for a barycentric point-located row.""" + child = _adapted(3, 0.4) + Ps = child._adapt_prolongation + lvl = _levels(child)[-(len(Ps) + 1):] + for k, entry in enumerate(Ps): + P = _as_matrix(entry, lvl[k], lvl[k + 1]) + assert P.nnz / P.shape[0] <= 2.0 From b4d3f0dbea461cbcd464f68c7702b90313af36e0 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 09:03:51 +1000 Subject: [PATCH 10/16] fix(custom-mg): repair orphaned coarse DOFs in place, keeping the transfer sparse (#424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The RBF retry added earlier rescues correctness but is not a scalable fix, and I shipped it without checking its density. Measured: nc=200 nf= 800 barycentric nnz/row 2.9-3.4 rbf nnz/row 200.00 nc=800 nf=3200 barycentric nnz/row 3.0-3.8 rbf nnz/row 800.00 nnz/row == n_coarse exactly: the RBF prolongation is FULLY DENSE, so the Galerkin coarse operator PᵀAP is dense too. It passed the tests only because those meshes are small; at production size it would be ruinous. That is a silent performance cliff of the same kind as the GAMG fallback it was meant to cure. The actual defect is narrower than "wrong builder". Point location has LOCAL support, so a coarse DOF is reached only if some fine DOF lands in a simplex touching it; move the fine coordinates and a coarse DOF can lose every fine image. Only those orphans need fixing, not the whole transfer. Give each orphan its nearest fine DOF as a pure injection (weight 1) — exactly the fallback the builder already uses for fine points outside the coarse hull. Partition of unity holds (the row still sums to 1), sparsity holds (~d+1 nnz/row), the column is no longer empty. Distinct rows are used so two orphans cannot claim the same fine DOF. 3D adapt + relax="per-generation": gamg 23 its -> pc=mg 2 its, and the RBF retry no longer fires at all. The retry stays as a last resort for pathological pairs (a synthetic cloud covering 60% of the coarse hull still leaves orphans), with the docs now stating plainly that it is a rescue and not a scalable transfer. 52 tests pass across the four MG suites, relax, nested prolongation and graded adapt. Underworld development team with AI support from Claude Code --- .../subsystems/mesh-shape-relaxation.md | 24 ++++++----- src/underworld3/utilities/custom_mg.py | 42 ++++++++++++++++++- 2 files changed, 53 insertions(+), 13 deletions(-) diff --git a/docs/developer/subsystems/mesh-shape-relaxation.md b/docs/developer/subsystems/mesh-shape-relaxation.md index 3958f0ba2..3825be449 100644 --- a/docs/developer/subsystems/mesh-shape-relaxation.md +++ b/docs/developer/subsystems/mesh-shape-relaxation.md @@ -118,17 +118,19 @@ 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 `rbf` builder has **global support** — every coarse DOF is reached through -the RBF solve — so it cannot produce a zero column. The FMG build therefore -**retries with `rbf` automatically** before giving up, and warns that it did: - - custom_mg: barycentric transfer build failed (transfer 2->3 has 1 zero - columns ...); retrying with the 'rbf' builder, which has global support - and cannot leave a coarse DOF without a fine image. - -Measured on a relaxed 3D adapt child: barycentric alone fell back to GAMG at -23 iterations; with the retry it keeps `pc=mg` at 2. Set -`mesh._custom_mg_builder = "rbf"` to skip the first attempt. +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 diff --git a/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index 8ffd2b67d..0192509ec 100644 --- a/src/underworld3/utilities/custom_mg.py +++ b/src/underworld3/utilities/custom_mg.py @@ -78,8 +78,46 @@ def barycentric_prolongation(coarse_coords, fine_coords): rows.append(i) cols.append(int(verts[k])) vals.append(float(w[k])) - return sp.csr_matrix((vals, (rows, cols)), - shape=(fine_coords.shape[0], coarse_coords.shape[0])) + P = sp.csr_matrix((vals, (rows, cols)), + shape=(fine_coords.shape[0], coarse_coords.shape[0])) + + # Repair orphaned coarse DOFs (columns with no fine image). Point location + # has LOCAL support, so a coarse DOF is reached only if some fine DOF lands + # in a simplex touching it; move the fine coordinates (mesh.relax, boundary + # snapping, free-surface deformation) and a coarse DOF can lose every fine + # image. Its column goes to zero and the Galerkin coarse operator PᵀAP is + # singular (#424). + # + # Give each orphan its nearest fine DOF as a pure injection (weight 1) — + # exactly the fallback already used above for fine points outside the + # coarse hull. Partition of unity is preserved (the row still sums to 1), + # sparsity is preserved (~d+1 nnz/row), and the column is no longer empty. + # Distinct rows are used so two orphans cannot claim the same fine DOF. + # The alternative — switching to the global-support RBF builder — removes + # the singularity but returns a DENSE transfer (nnz/row == n_coarse), which + # makes PᵀAP dense and is unusable at production sizes. + orphans = np.nonzero(np.asarray((P != 0).sum(axis=0)).ravel() == 0)[0] + if orphans.size: + k = int(min(orphans.size + 8, fine_coords.shape[0])) + _, cand = cKDTree(fine_coords).query(coarse_coords[orphans], k=k) + cand = np.atleast_2d(cand) + claimed, fixes = set(), {} + for i, c in enumerate(orphans): + for f in cand[i]: + f = int(f) + if f not in claimed: + claimed.add(f) + fixes[f] = int(c) + break + if fixes: + keep = ~np.isin(np.asarray(rows), list(fixes)) + rows = list(np.asarray(rows)[keep]) + list(fixes.keys()) + cols = list(np.asarray(cols)[keep]) + list(fixes.values()) + vals = list(np.asarray(vals)[keep]) + [1.0] * len(fixes) + P = sp.csr_matrix((vals, (rows, cols)), + shape=(fine_coords.shape[0], + coarse_coords.shape[0])) + return P def rbf_prolongation(coarse_coords, fine_coords, smooth=0.0): From 7535df2cec139ef6dcce9d58f1e04e70e6880151 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 09:31:32 +1000 Subject: [PATCH 11/16] feat(custom-mg): use the EXACT nested transfer for degree-1 fields (#425) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the gap where adapt() maintained an exact hierarchy and the MG transfer then re-derived an approximation to it by Delaunay point location. For the adapt generations the recorded parent/child relation is now installed directly; the uniform coarse tail beneath them is not a bisection hierarchy, so it keeps using the geometric builder. 2D adapt nested 2, builder 2 pc=mg its=3 err 1.6e-13 3D adapt nested 3, builder 2 pc=mg its=3 err 9.1e-13 3D adapt + relax nested 3, builder 2 pc=mg its=4 err 4.5e-12 On this path the zero-column failure (#424) cannot occur at all: every coarse DOF carries weight 1 into its own inherited fine DOF, so the transfer is structurally full rank. It is also sparser — 1-1.4 nnz/row against d+1 for point location — and immune to node motion, so relaxation and snapping cannot disturb it. Verified before relying on it: `_get_coords_for_basis(1, True)` returns coordinates in DM vertex-stratum order, identical arrays in 2D and 3D, base and child. Had that not held, the recorded indices would have installed a silently WRONG transfer rather than failing. RESTRICTED TO degree == 1. The recorded relation is vertex-level; a P2 field also has edge DOFs it says nothing about, so higher degree still goes through the builder, and a test pins that it declines rather than half-applies. Stage 2 (#425) is the any-degree extension: record the parent CELL, then evaluate the coarse basis at the fine DOF reference coordinates — exact for any degree and still orphan-free, since every coarse cell has children. Locating cell CENTROIDS is robust where locating DOFs is not: centroids are strictly interior, DOFs sit on cell boundaries and drift. Shapes are checked rather than assumed at every level; a mismatch falls back to the builder rather than installing a wrong transfer. 59 tests pass across the four MG suites, relax, nested prolongation, graded adapt and variable transfer. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/custom_mg.py | 62 +++++++++++++++++++--- tests/test_0753_nested_mg_prolongation.py | 64 +++++++++++++++++++++++ 2 files changed, 120 insertions(+), 6 deletions(-) diff --git a/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index 0192509ec..16461abfa 100644 --- a/src/underworld3/utilities/custom_mg.py +++ b/src/underworld3/utilities/custom_mg.py @@ -356,14 +356,20 @@ def _coarse_reduced_map(solver, coarse_mesh, field_id=None): return _reduced_map(cdm, field_id) +def _reduced_from_node_transfer(Pn, r2f_c, r2f_f, ncomp): + """Interleave ``ncomp`` components of a node-level scalar ``Pn`` and drop the + BC rows/columns — the half of :func:`_reduced_transfer` that does not care + where the node weights came from.""" + import scipy.sparse as sp + Pv = sp.kron(Pn, sp.eye(ncomp), format="csr") # interleaved full vector + return Pv.tocsr()[r2f_f, :][:, r2f_c] # reduced -> reduced + + def _reduced_transfer(coarse_coords, fine_coords, r2f_c, r2f_f, ncomp, builder): """Build one prolongation reduced(coarse) -> reduced(fine): node-level scalar P -> interleave ``ncomp`` components -> drop BC rows/cols.""" - import scipy.sparse as sp Pn = builder(coarse_coords, fine_coords) # (n_f_nodes, n_c_nodes) - Pv = sp.kron(Pn, sp.eye(ncomp), format="csr") # interleaved full vector - Pr = Pv.tocsr()[r2f_f, :][:, r2f_c] # reduced -> reduced - return Pr + return _reduced_from_node_transfer(Pn, r2f_c, r2f_f, ncomp) # --------------------------------------------------------------------------- # @@ -725,6 +731,45 @@ def __init__(self, level_meshes, builder="barycentric", field_id=None, self.cross_partition = cross_partition self.transfers = None + def _recorded_node_transfer(self, level, nlev, degree, n_coarse, n_fine): + """The EXACT nested prolongation recorded by ``mesh.adapt`` for this + transfer, or ``None`` to fall back to point location. + + ``adapt`` maintains the parent/child relation, so for a bisection + hierarchy the coarse-to-fine embedding is known exactly — every fine + vertex is an inherited coarse vertex (weight 1) or an edge midpoint + (1/2, 1/2). Using it avoids re-deriving an approximation by Delaunay + point location, and it is **structurally full rank**: no coarse DOF can + be left without a fine image, so the zero-column failure (#424) cannot + arise on this path. + + Restricted to ``degree == 1``: the recorded relation is vertex-level, + and a higher-degree field also has edge/face DOFs that it says nothing + about. Those still go through the geometric builder — see #425 for the + any-degree extension (record the parent CELL, then evaluate the coarse + basis at the fine DOF reference coordinates). + + The recorded list covers the ADAPT generations only; the uniform coarse + tail beneath them is not a bisection hierarchy, so its transfers keep + using the builder. Shapes are checked rather than assumed — a mismatch + means the levels do not line up as expected and it is safer to fall + back than to install a silently wrong transfer. + """ + import scipy.sparse as sp + if degree != 1: + return None + recorded = getattr(self.level_meshes[-1], "_adapt_prolongation", None) + if not recorded: + return None + idx = level - (nlev - len(recorded)) + if idx < 0 or idx >= len(recorded) or recorded[idx] is None: + return None + rows, cols, vals = recorded[idx] + if (rows.size == 0 or int(rows.max()) >= n_fine + or int(cols.max()) >= n_coarse): + return None + return sp.csr_matrix((vals, (rows, cols)), shape=(n_fine, n_coarse)) + def build(self, solver): """Build the BC-reduced prolongations. ``solver`` is the (built) finest solver. Each COARSE level's BC-constrained reduced map is derived directly @@ -810,8 +855,13 @@ def build(self, solver): _assert_no_zero_columns_parallel(P, comm) Ps.append(P) else: - Pr = _reduced_transfer(coords[l - 1], coords[l], maps[l - 1], - maps[l], nc, self.builder) + Pn = self._recorded_node_transfer( + l, nlev, degree, coords[l - 1].shape[0], coords[l].shape[0]) + if Pn is not None: + Pr = _reduced_from_node_transfer(Pn, maps[l - 1], maps[l], nc) + else: + Pr = _reduced_transfer(coords[l - 1], coords[l], maps[l - 1], + maps[l], nc, self.builder) _assert_no_zero_columns_serial(Pr, l) Ps.append(_to_petsc_aij(Pr)) self.transfers = Ps diff --git a/tests/test_0753_nested_mg_prolongation.py b/tests/test_0753_nested_mg_prolongation.py index 7ca136662..47b12d495 100644 --- a/tests/test_0753_nested_mg_prolongation.py +++ b/tests/test_0753_nested_mg_prolongation.py @@ -91,3 +91,67 @@ def test_transfer_is_sparser_than_point_location(): for k, entry in enumerate(Ps): P = _as_matrix(entry, lvl[k], lvl[k + 1]) assert P.nnz / P.shape[0] <= 2.0 + + +def test_mg_actually_uses_the_recorded_transfer_for_degree_one(): + """Guard against silently reverting to point location. + + Solving is not enough evidence — the geometric builder also solves. This + asserts the recorded relation is what the hierarchy installed for the + adapt generations, while the uniform coarse tail below them (not a + bisection hierarchy) still uses the builder. + """ + from underworld3.utilities import custom_mg + + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25, + refinement=2, qdegree=2) + child = base.adapt(_metric, max_levels=1) + + original = custom_mg.CustomMGHierarchy._recorded_node_transfer + stats = {"nested": 0, "builder": 0} + + def _spy(self, level, nlev, degree, n_coarse, n_fine): + P = original(self, level, nlev, degree, n_coarse, n_fine) + stats["nested" if P is not None else "builder"] += 1 + return P + + custom_mg.CustomMGHierarchy._recorded_node_transfer = _spy + try: + u = uw.discretisation.MeshVariable("u_nested_used", child, 1, degree=1) + poisson = uw.systems.Poisson(child, u_Field=u) + poisson.constitutive_model = uw.constitutive_models.DiffusionModel + poisson.constitutive_model.Parameters.diffusivity = 1.0 + poisson.f = 0.0 + poisson.add_dirichlet_bc(0.0, "Bottom") + poisson.add_dirichlet_bc(1.0, "Top") + poisson.petsc_options["ksp_rtol"] = 1e-10 + poisson.solve() + finally: + custom_mg.CustomMGHierarchy._recorded_node_transfer = original + + assert stats["nested"] > 0, ( + "the exact recorded transfer was not used — MG silently fell back to " + "point location on an adapt hierarchy") + assert poisson.snes.getKSP().getPC().getType() == "mg" + # exact linear solution, so the answer should be at round-off + err = (np.linalg.norm(u.data[:, 0] - u.coords[:, 1]) + / np.linalg.norm(u.coords[:, 1])) + assert err < 1e-9 + + +def test_higher_degree_still_uses_the_geometric_builder(): + """The recorded relation is vertex-level, so P2 must NOT use it (its edge + DOFs are not described by the vertex parentage). #425 stage 2.""" + from underworld3.utilities import custom_mg + + base = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25, + refinement=2, qdegree=2) + child = base.adapt(_metric, max_levels=1) + h = custom_mg.CustomMGHierarchy( + list(child._custom_mg_coarse_meshes) + [child], builder="barycentric") + # degree 2 must decline the recorded transfer at every level + for level in range(1, len(h.level_meshes)): + assert h._recorded_node_transfer(level, len(h.level_meshes), 2, + 10**6, 10**6) is None From e7d08f6341c033505bcb87d82cb6c8b0fad10dd4 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 09:51:55 +1000 Subject: [PATCH 12/16] docs(custom-mg): correct the "FE-exact" claim on the barycentric builder (#425) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docstring said each fine DOF is interpolated by "the coarse element that contains it". That is only true when Delaunay of the coarse DOF cloud coincides with the coarse mesh. Measured agreement: 2D uniform base, P1 168 cells 168 Delaunay 100 % 2D adapt child, P1 238 238 90.8 % 3D uniform base, P1 800 812 58.8 % 3D adapt child, P1 4685 5201 17.1 % 3D adapt child, P2 4685 39597 -- It triangulates the coarse DOF POINT CLOUD from scratch and never consults the mesh cells, so it is linear interpolation over an ad-hoc triangulation, not the FE embedding. Linear reproduction is why multigrid converges well; but the coarse P2 space is not represented exactly, and the 58.8 % on a UNIFORM base reflects PETSc 1:8 tetrahedral splits not being Delaunay — the same fixed-diagonal property as the 148 degree dihedral measured earlier. Also records a predicted (not yet measured) risk: Delaunay simplices do not respect mesh topology, so on a non-convex domain or one with an internal interface a simplex can bridge the discontinuity and smear the coarse correction across it. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/custom_mg.py | 39 ++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index 16461abfa..10dc42ece 100644 --- a/src/underworld3/utilities/custom_mg.py +++ b/src/underworld3/utilities/custom_mg.py @@ -52,9 +52,42 @@ # Prolongation builders (return scipy CSR matrices) # --------------------------------------------------------------------------- # def barycentric_prolongation(coarse_coords, fine_coords): - """FE-exact prolongation: each fine DOF interpolated by the coarse element - that contains it (barycentric weights). Partition of unity (row sums = 1); - fine points outside the coarse hull fall back to the nearest coarse DOF.""" + """Prolongation by linear interpolation over a Delaunay triangulation of the + coarse DOF cloud. Partition of unity (row sums = 1) and linear fields are + reproduced exactly; fine points outside the coarse hull fall back to the + nearest coarse DOF, and orphaned coarse DOFs are repaired below. + + .. note:: + + This is **not** the coarse FE space's embedding, despite what this + docstring claimed until 2026-07. It triangulates the coarse DOF *point + cloud* from scratch and never consults the coarse mesh's cells, so + "the coarse element containing the fine DOF" is only what gets used when + the Delaunay triangulation happens to coincide with the mesh. Measured + agreement between the two: + + =========================== ========== ========== ========== + case mesh cells Delaunay agreement + =========================== ========== ========== ========== + 2D uniform base, P1 168 168 100 % + 2D adapt child, P1 238 238 90.8 % + 3D uniform base, P1 800 812 58.8 % + 3D adapt child, P1 4685 5201 17.1 % + 3D adapt child, P2 4685 39597 -- + =========================== ========== ========== ========== + + Reproducing linears is enough for multigrid to converge well, which is + why this works. But two limits follow. For P2 and above the coarse + space is not represented exactly. And because Delaunay simplices do not + respect mesh topology, on a non-convex domain or one with an internal + interface (a fault) a simplex can bridge across the discontinuity and + smear the coarse correction over it — predicted from the algorithm, + not yet measured. + + Where a parent/child relation exists, prefer the exact nested transfer + (#425), which is the true FE embedding, cannot bridge across features, + and cannot orphan a coarse DOF. + """ import scipy.sparse as sp from scipy.spatial import Delaunay, cKDTree From ef79f31b45937f0cfcde4eb092cc3c64cb3871cd Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 10:00:45 +1000 Subject: [PATCH 13/16] =?UTF-8?q?refactor(adapt):=20remove=20scipy=20from?= =?UTF-8?q?=20the=20nested=20path=20=E2=80=94=20exact=20identification,=20?= =?UTF-8?q?no=20search?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maintainer ruling: the nested-mesh case must not use the general geometric mapping, and must not pull in meshing/interpolation dependencies. "If you are using scipy it is probably wrong." I had introduced two violations myself: nvb.nested_prolongation_from_dms scipy.spatial.cKDTree + a tolerance _adapt_nested._relax_generation scipy.spatial.cKDTree nearest-neighbour Both are now exact byte-equality lookups. This is not a weaker version of the search — it is the correct operation. Every fine vertex of a bisection pass is an inherited coarse vertex or the exact average of two already-known vertices, computed by the same float arithmetic on both sides, so equality is exact. Measured: 100% of 2D fine vertices match a coarse vertex or coarse edge midpoint bit-for-bit; the 3D remainder (27%) are the closure-cascade quarter points, which resolve exactly against already-resolved FINE neighbours by the same test. No spatial index, no tolerance parameter, no nearest-neighbour guess that could silently pick the wrong point. The `tol=` argument is gone with it — it was a fragility, not a tunable. Unchanged and re-verified after the refactor: 2D 2 passes, 3D 6 passes, all captured, partition of unity exact, zero zero-columns, 1.0-1.4 nnz/row; MG still installs the nested transfer (2D 2, 3D 3) with pc=mg and errors at round-off. 46 tests pass. Still using scipy, PRE-EXISTING and reported not silently fixed: nvb.py:596, :992 cKDTree in to_dm (defensive; the code already documents the map as identity) discretisation_mesh.py:2499,:2824 cKDTree custom_mg.py Delaunay + cKDTree (the geometric path) UW3 has its own uw.kdtree.KDTree, so scipy is not needed even where a real spatial search is wanted. Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 16 ++- src/underworld3/utilities/nvb.py | 100 ++++++++++-------- 2 files changed, 64 insertions(+), 52 deletions(-) diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index d918c1d42..306e3b321 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -7181,7 +7181,6 @@ def _relax_generation(engine_obj, carry, rcarry): vertices. The match is exact because it is taken before anything moves. """ - from scipy.spatial import cKDTree _dmg = engine_obj.to_dm(boundaries=carry, regions=rcarry, comm=self.dm.comm) _mg = Mesh(_dmg, simplex=self.dm.isSimplex(), @@ -7190,10 +7189,17 @@ def _relax_generation(engine_obj, carry, rcarry): qdegree=self.qdegree, boundaries=self.boundaries, verbose=False) _cd = _mg.cdim - _pre = _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd).copy() - _src = numpy.asarray([numpy.asarray(c, dtype=float) - for c in engine_obj.coords]) - _idx = cKDTree(_src).query(_pre, k=1)[1] + _pre = numpy.ascontiguousarray( + _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd)) + _src = numpy.ascontiguousarray( + numpy.asarray([numpy.asarray(c, dtype=float) + for c in engine_obj.coords])) + # EXACT identification: the DM was built from these very + # coordinates, so byte equality is the correct test. No spatial + # index, no tolerance, no nearest-neighbour guess. + _key = {row.tobytes(): i for i, row in enumerate(_src)} + _idx = numpy.asarray([_key[row.tobytes()] for row in _pre], + dtype=numpy.int64) _mg.relax(_relax_metric, **(relax_kwargs or {})) _post = _mg.dm.getCoordinatesLocal().array.reshape(-1, _cd) for _k, _i in enumerate(_idx): diff --git a/src/underworld3/utilities/nvb.py b/src/underworld3/utilities/nvb.py index 4e13954bb..ae060198a 100644 --- a/src/underworld3/utilities/nvb.py +++ b/src/underworld3/utilities/nvb.py @@ -168,37 +168,40 @@ def _fs(a, b): return (a, b) if a < b else (b, a) -def nested_prolongation_from_dms(coarse_dm, fine_dm, tol=1.0e-10): +def nested_prolongation_from_dms(coarse_dm, fine_dm): """Recover a refinement pass's exact P1 prolongation from the two DMs. - For engines that do not expose their parent/child map (the native - ``DMPlexTransform`` path), the relation can still be recovered exactly - **while the coordinates are pristine** — after refinement but BEFORE any - boundary snap or relaxation moves a midpoint off its parent edge. + Every fine vertex of a bisection pass is an **inherited** coarse vertex or + the **exact average of two already-known vertices**. Both are identified by + EXACT equality — the midpoints are the same float arithmetic on both sides, + so no search, no tolerance and no spatial index are involved. This is + identification, not geometric mapping. - One ``refine`` pass is not necessarily one bisection *level*: the - conforming closure cascades, so a vertex can be the midpoint of an - already-split half-edge and therefore sit at the quarter point of the - original coarse edge. Resolution is iterative: + One ``refine`` pass is not necessarily one bisection *level*: the conforming + closure cascades, so a vertex can be the midpoint of an already-split + half-edge and therefore sit at the quarter point of the original coarse + edge. Resolution is iterative: - 1. a fine vertex coincident with a coarse vertex is inherited (weight 1); - one coincident with a coarse edge midpoint gets 1/2, 1/2; - 2. any still-unresolved vertex that is the midpoint of two ALREADY-RESOLVED + 1. a fine vertex equal to a coarse vertex is inherited (weight 1); one equal + to a coarse edge midpoint gets 1/2, 1/2; + 2. any still-unresolved vertex equal to the average of two ALREADY-RESOLVED fine neighbours takes the average of their weights; 3. repeat until nothing new resolves. Weights compose exactly, so the result is the true FE embedding at any - cascade depth. Returns ``(rows, cols, vals)`` as in - :func:`nested_prolongation`, or ``None`` if any vertex remains unresolved - — in which case the caller should fall back to the geometric builder - rather than guess. - """ - from scipy.spatial import cKDTree + cascade depth. Returns ``(rows, cols, vals)``, or ``None`` if any vertex + remains unresolved — the caller should then fall back rather than guess. + NB this reads coordinates only to *identify* points, so it must be called + while they are still pristine (before any snap or relaxation). The + dependency-free endpoint is to take the relation straight from the + refinement transform instead; see #425. + """ cvS, cvE = coarse_dm.getDepthStratum(0) ceS, ceE = coarse_dm.getDepthStratum(1) cdim = coarse_dm.getCoordinateDim() - cxyz = coarse_dm.getCoordinatesLocal().array.reshape(-1, cdim) + cxyz = np.ascontiguousarray( + coarse_dm.getCoordinatesLocal().array.reshape(-1, cdim)) edges = [(c[0] - cvS, c[1] - cvS) for e in range(ceS, ceE) @@ -210,29 +213,31 @@ def nested_prolongation_from_dms(coarse_dm, fine_dm, tol=1.0e-10): fvS, fvE = fine_dm.getDepthStratum(0) feS, feE = fine_dm.getDepthStratum(1) - fxyz = fine_dm.getCoordinatesLocal().array.reshape(-1, cdim) + fxyz = np.ascontiguousarray( + fine_dm.getCoordinatesLocal().array.reshape(-1, cdim)) n_f = fvE - fvS if fxyz.shape[0] != n_f: return None - scale = float(np.abs(cxyz).max()) or 1.0 - atol = tol * scale - # --- round 1: coarse vertices and coarse edge midpoints --------------- - targets = np.vstack([cxyz, 0.5 * (cxyz[edges[:, 0]] + cxyz[edges[:, 1]])]) - dist, idx = cKDTree(targets).query(fxyz) - nc = cxyz.shape[0] + # --- round 1: exact lookup against coarse vertices and edge midpoints --- + known = {row.tobytes(): ("v", i) for i, row in enumerate(cxyz)} + mids = np.ascontiguousarray(0.5 * (cxyz[edges[:, 0]] + cxyz[edges[:, 1]])) + for i, row in enumerate(mids): + known.setdefault(row.tobytes(), ("e", i)) + weights = [None] * n_f - for r in range(n_f): - if dist[r] > atol: + for r, row in enumerate(fxyz): + hit = known.get(row.tobytes()) + if hit is None: continue - t = int(idx[r]) - if t < nc: - weights[r] = {t: 1.0} + kind, i = hit + if kind == "v": + weights[r] = {int(i): 1.0} else: - a, b = edges[t - nc] + a, b = edges[i] weights[r] = {int(a): 0.5, int(b): 0.5} - # --- rounds 2+: midpoints of already-resolved fine neighbours --------- + # --- rounds 2+: averages of already-resolved fine neighbours ------------ unresolved = [r for r in range(n_f) if weights[r] is None] if unresolved: nbr = [[] for _ in range(n_f)] @@ -243,29 +248,30 @@ def nested_prolongation_from_dms(coarse_dm, fine_dm, tol=1.0e-10): nbr[u].append(v) nbr[v].append(u) while unresolved: - progressed = False still = [] for r in unresolved: - done = False + target = fxyz[r].tobytes() cand = [q for q in nbr[r] if weights[q] is not None] + found = None for i in range(len(cand)): for j in range(i + 1, len(cand)): p, q = cand[i], cand[j] - if np.linalg.norm( - fxyz[r] - 0.5 * (fxyz[p] + fxyz[q])) <= atol: - w = {} - for src in (p, q): - for pt, ww in weights[src].items(): - w[pt] = w.get(pt, 0.0) + 0.5 * ww - weights[r] = w - progressed = done = True + avg = np.ascontiguousarray(0.5 * (fxyz[p] + fxyz[q])) + if avg.tobytes() == target: + found = (p, q) break - if done: + if found: break - if not done: + if found is None: still.append(r) - if not progressed: - return None # cannot be explained by bisection + continue + w = {} + for src in found: + for pt, ww in weights[src].items(): + w[pt] = w.get(pt, 0.0) + 0.5 * ww + weights[r] = w + if len(still) == len(unresolved): + return None # cannot be explained by bisection unresolved = still rows, cols, vals = [], [], [] From e5da5a6fc8ab3933afed7c34c40ec99db2bccf50 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 10:26:21 +1000 Subject: [PATCH 14/16] =?UTF-8?q?refactor(nvb):=20drop=20scipy=20from=20to?= =?UTF-8?q?=5Fdm=20=E2=80=94=20exact=20coordinate=20lookup,=20not=20a=20sp?= =?UTF-8?q?atial=20query?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `to_dm` used a scipy cKDTree nearest-neighbour search to map DM vertices back to engine vertex ids. The DM is built by createFromCellList from those very coordinates, so the two arrays hold bit-identical values: equality is the correct test and a spatial query was standing in for an identity lookup. Worse, it failed in the wrong direction. A nearest-neighbour search always returns something, so if the assumption it was guarding ever broke it would silently bind the WRONG vertex. The replacement raises instead, naming the cause (coordinates modified between building the DM and reading it back). nvb.py is now free of scipy entirely. Also records the MG convergence check that preceded this cleanup. Poisson, manufactured sin solution (the earlier linear-solution test was worthless — the coarse space represents a linear field exactly, so every transfer converged in 1-3 iterations regardless of quality): 2D, 303 -> 7713 dofs its 3, 3, 2, 2 nested == geometric 3D, k=8pi, rtol=1e-12 its 5, 6, 5 geometric 4, 5, 4 2D is mesh-independent and identical. 3D costs the nested transfer ONE extra iteration, consistently across three configurations — not noise. The likely cause is stencil width: the nested transfer is near-injection (1.0-1.4 nnz/row) where barycentric spreads over ~4, and prolongation width affects how well the coarse correction damps high-frequency error. Exactness is not the same as effectiveness. Partly offset by the nested coarse operators being ~3x sparser, so each iteration is cheaper; net wall-clock not measured. 55 tests pass across all NVB engines (2D/3D, serial/parallel), nested prolongation, relax and SBR adapt. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/nvb.py | 40 +++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/src/underworld3/utilities/nvb.py b/src/underworld3/utilities/nvb.py index ae060198a..240acf60f 100644 --- a/src/underworld3/utilities/nvb.py +++ b/src/underworld3/utilities/nvb.py @@ -168,6 +168,31 @@ def _fs(a, b): return (a, b) if a < b else (b, a) +def _exact_vertex_map(engine_coords, dm_vcoords, vS, vE): + """``{DM vertex point: engine vertex id}`` by EXACT coordinate equality. + + The DM was just built by ``createFromCellList`` from these very + coordinates, so the two arrays hold bit-identical values and equality is + the correct test — not a nearest-neighbour search. A kd-tree here would be + a spatial query standing in for an identity lookup, and would silently + bind the WRONG vertex if the assumption it guards ever broke, rather than + failing. This raises instead. + """ + key = {row.tobytes(): i + for i, row in enumerate(np.ascontiguousarray( + np.asarray(engine_coords, dtype=float)))} + out = {} + for i in range(vE - vS): + j = key.get(dm_vcoords[i].tobytes()) + if j is None: + raise RuntimeError( + f"to_dm: DM vertex {vS + i} has no exact coordinate match in " + f"the engine's vertex list. The DM is built from those " + f"coordinates, so this means they were modified in between.") + out[vS + i] = j + return out + + def nested_prolongation_from_dms(coarse_dm, fine_dm): """Recover a refinement pass's exact P1 prolongation from the two DMs. @@ -593,7 +618,6 @@ def to_dm(self, boundaries=(), regions=(), comm=None): ``UW_Boundaries`` / ``Null_Boundary`` from them. ``All_Boundaries`` is the geometric outer boundary (``markBoundaryFaces``), independent of our labels. """ - from scipy.spatial import cKDTree coords, tris, region_of, _ = self.arrays() # createFromCellList needs consistent (CCW) winding; the internal @@ -618,9 +642,9 @@ def to_dm(self, boundaries=(), regions=(), comm=None): # TODO(#360): row i == vertex point vS+i is assumed, as in from_dm above. # Safe here: the DM was created two lines up by createFromCellList on this # rank (serial-only path), so its coordinate section is vertex-ordered. - dm_vcoords = dm.getCoordinatesLocal().array.reshape(-1, 2) - _, nearest = cKDTree(np.array(self.coords)).query(dm_vcoords) - nvb_of_dmvert = {vS + i: int(nearest[i]) for i in range(vE - vS)} + dm_vcoords = np.ascontiguousarray( + dm.getCoordinatesLocal().array.reshape(-1, 2)) + nvb_of_dmvert = _exact_vertex_map(self.coords, dm_vcoords, vS, vE) # Engine-id <-> DM-point map for THIS export, kept so the nested MG # prolongation can be built from the exact parent/child relation # (``edge2mid``) instead of re-deriving it by point location. Recorded @@ -989,7 +1013,6 @@ def to_dm(self, boundaries=(), regions=(), comm=None): convention so ``Mesh()`` derives ``UW_Boundaries`` from them; ``All_Boundaries`` is the geometric outer boundary. """ - from scipy.spatial import cKDTree coords, cells, region_of, _ = self.arrays() # createFromCellList needs cells in the DMPlex orientation class; the @@ -1015,10 +1038,9 @@ def to_dm(self, boundaries=(), regions=(), comm=None): # DM vertex point -> engine vertex id by coordinate (exact match). # TODO(#360): row i == vertex point vS+i — safe: the DM was created # two lines up by createFromCellList on this rank (serial path). - dm_vcoords = dm.getCoordinatesLocal().array.reshape( - -1, dm.getCoordinateDim()) - _, nearest = cKDTree(np.array(self.coords)).query(dm_vcoords) - eng_of_dmvert = {vS + i: int(nearest[i]) for i in range(vE - vS)} + dm_vcoords = np.ascontiguousarray( + dm.getCoordinatesLocal().array.reshape(-1, dm.getCoordinateDim())) + eng_of_dmvert = _exact_vertex_map(self.coords, dm_vcoords, vS, vE) # See the note in NVBMesh.to_dm: engine-id -> DM-point, recorded at the # one point the two numberings meet, for the nested MG prolongation. self.dm_vertex_of_engine = {v: k for k, v in eng_of_dmvert.items()} From fb1a93c8909c016251faaae767ef96f62855f209 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 11:28:12 +1000 Subject: [PATCH 15/16] =?UTF-8?q?fix(adapt):=20restore=20round-2=20composi?= =?UTF-8?q?tion=20=E2=80=94=20it=20was=20correct;=20the=20REFERENCE=20was?= =?UTF-8?q?=20wrong?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I removed the cascade-vertex composition from nested_prolongation_from_dms on the strength of a test showing 2-12 wrong DOFs per 3D pass with O(1) errors, and wrote a confident commit message explaining why it was unsound. Both the evidence and the reasoning were wrong. The reference was uw.function.evaluate, which returns incorrect values at points lying exactly on cell edges (#432) — precisely where every bisection vertex sits. Checked against an INDEPENDENT reference instead (the P1 value along the coarse edge each vertex lies on, computed directly): 2D 3 passes 111/138/151 vertices 0 wrong worst 2.3e-15 3D 6 passes 334..2225 vertices 0 wrong worst 2.9e-15 Every vertex, including every cascade generation. The transfer is the coarse P1 embedding and always was. For each disagreement the point lay on exactly ONE coarse edge, and the edge-truth matched the transfer, not evaluate: dof 504 transfer +0.700344 evaluate +0.923709 edge-truth +0.700344 dof 2177 transfer -2.122083 evaluate -6.128067 edge-truth -2.122083 Adds test_reproduces_an_arbitrary_coarse_field, which is the test that should have existed from the start. Reproducing a globally LINEAR field is far too weak — any local averaging passes it — so the original test could not distinguish a correct embedding from a mis-attributed one in either direction. A random coarse nodal field can, and the reference is computed independently rather than via evaluate. Also records the parent-CELL map where it is unambiguous (foundation for the any-degree transfer, #425). It declines on 3 of 6 3D passes: value-correctness of the vertex transfer does not imply unique cell attribution, so stage 2 still needs the true parent relation from the refinement transform. Underworld development team with AI support from Claude Code --- .../discretisation/discretisation_mesh.py | 14 +++- src/underworld3/utilities/nvb.py | 70 ++++++++++++++++++- tests/test_0753_nested_mg_prolongation.py | 67 +++++++++++++++++- 3 files changed, 145 insertions(+), 6 deletions(-) diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 306e3b321..c5cf555a7 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -7210,6 +7210,7 @@ def _relax_generation(engine_obj, carry, rcarry): # `from_dm` numbers engine vertices as `DM point - vS`, so the base map # is that offset; each generation's map comes back from `to_dm`. _nested_Ps = [] + _nested_parent_cells = [] _vS0, _vE0 = base_finest.getDepthStratum(0) _coarse_vmap = {i: _vS0 + i for i in range(_vE0 - _vS0)} @@ -7259,8 +7260,16 @@ def _relax_generation(engine_obj, carry, rcarry): # relaxation moves everything, after which the relation can no # longer be recovered by matching. See #425. from underworld3.utilities.nvb import ( - nested_prolongation_from_dms as _nested_from_dms) - _nested_Ps.append(_nested_from_dms(_coarse_for_P, current_dm)) + nested_prolongation_from_dms as _nested_from_dms, + nested_cell_parents as _nested_parents) + _vP = _nested_from_dms(_coarse_for_P, current_dm) + _nested_Ps.append(_vP) + # Parent CELL map as well: with it a fine DOF's weights are the + # coarse basis evaluated inside its parent, which is exact at + # ANY degree — the vertex map alone only covers P1. (#425) + _nested_parent_cells.append( + None if _vP is None + else _nested_parents(_coarse_for_P, current_dm, _vP)) snap_level_boundaries(current_dm) if _relax_mode == "per-generation": # Relax THIS generation before the next one marks from it: @@ -7427,6 +7436,7 @@ def _relax_generation(engine_obj, carry, rcarry): # (cell-list path). Empty for the native transform path, which falls # back to the geometric builder. See #425. child._adapt_prolongation = _nested_Ps + child._adapt_parent_cells = _nested_parent_cells # Mesh-owned custom-P geometric-MG tail. EVERY refinement level is its own # MG level (one custom-P transfer per refinement step), not a single # base-finest -> child jump: the tail is diff --git a/src/underworld3/utilities/nvb.py b/src/underworld3/utilities/nvb.py index 240acf60f..9308eabe5 100644 --- a/src/underworld3/utilities/nvb.py +++ b/src/underworld3/utilities/nvb.py @@ -193,6 +193,59 @@ def _exact_vertex_map(engine_coords, dm_vcoords, vS, vE): return out +def nested_cell_parents(coarse_dm, fine_dm, vertex_transfer): + """``parent[k]`` = the coarse cell containing fine cell ``k``. + + Found TOPOLOGICALLY, with no search and no geometry. Each fine vertex + references one or two coarse vertices through the recorded vertex + prolongation; a bisection child lies inside its parent, so every coarse + vertex its corners reference belongs to the parent cell. Intersecting the + incident-cell sets over those coarse vertices therefore leaves exactly the + parent. + + This is what unlocks an EXACT transfer at any polynomial degree: knowing + the parent cell, a fine DOF's weights are the coarse basis evaluated at its + position within that cell — no point location, so no Delaunay, no spatial + index and no orphaned coarse DOF. + + Returns an ``(n_fine_cells,)`` array of coarse cell points, or ``None`` if + any fine cell's parent is not uniquely determined (the caller should then + fall back rather than guess). + """ + rows, cols, _ = vertex_transfer + cvS, cvE = coarse_dm.getDepthStratum(0) + ccS, ccE = coarse_dm.getHeightStratum(0) + fvS, fvE = fine_dm.getDepthStratum(0) + fcS, fcE = fine_dm.getHeightStratum(0) + + # coarse vertex -> incident coarse cells + incident = [set() for _ in range(cvE - cvS)] + for c in range(ccS, ccE): + for q in coarse_dm.getTransitiveClosure(c)[0]: + if cvS <= q < cvE: + incident[q - cvS].add(c) + + # fine vertex -> coarse vertices it is built from + refs = [[] for _ in range(fvE - fvS)] + for r, cpt in zip(rows.tolist(), cols.tolist()): + refs[r].append(cpt) + + parents = np.empty(fcE - fcS, dtype=np.int64) + for k, c in enumerate(range(fcS, fcE)): + cand = None + for q in fine_dm.getTransitiveClosure(c)[0]: + if not (fvS <= q < fvE): + continue + for cv in refs[q - fvS]: + cand = incident[cv] if cand is None else (cand & incident[cv]) + if cand is not None and len(cand) == 1: + break + if not cand or len(cand) != 1: + return None + parents[k] = next(iter(cand)) + return parents + + def nested_prolongation_from_dms(coarse_dm, fine_dm): """Recover a refinement pass's exact P1 prolongation from the two DMs. @@ -263,6 +316,17 @@ def nested_prolongation_from_dms(coarse_dm, fine_dm): weights[r] = {int(a): 0.5, int(b): 0.5} # --- rounds 2+: averages of already-resolved fine neighbours ------------ + # A closure cascade can create a vertex at the midpoint of an + # already-split half-edge, which is therefore NOT at a coarse edge + # midpoint and is not matched above. Such a vertex is the exact average of + # two already-resolved fine neighbours, so its weights compose from theirs. + # + # This is inference, not topology: being fine-mesh neighbours does not by + # itself make the segment an edge of the refinement tree. It is validated + # against an INDEPENDENT reference (the P1 value along the coarse edge the + # point lies on) rather than against uw.function.evaluate, which is itself + # wrong at points on cell boundaries (#432) — measuring against it briefly + # convinced me this code was broken when it was not. unresolved = [r for r in range(n_f) if weights[r] is None] if unresolved: nbr = [[] for _ in range(n_f)] @@ -280,10 +344,10 @@ def nested_prolongation_from_dms(coarse_dm, fine_dm): found = None for i in range(len(cand)): for j in range(i + 1, len(cand)): - p, q = cand[i], cand[j] - avg = np.ascontiguousarray(0.5 * (fxyz[p] + fxyz[q])) + p_, q_ = cand[i], cand[j] + avg = np.ascontiguousarray(0.5 * (fxyz[p_] + fxyz[q_])) if avg.tobytes() == target: - found = (p, q) + found = (p_, q_) break if found: break diff --git a/tests/test_0753_nested_mg_prolongation.py b/tests/test_0753_nested_mg_prolongation.py index 47b12d495..56c38eda2 100644 --- a/tests/test_0753_nested_mg_prolongation.py +++ b/tests/test_0753_nested_mg_prolongation.py @@ -67,9 +67,74 @@ def test_partition_of_unity_and_no_zero_columns(dim, cell_size): f"zero-column failure the nested transfer is meant to preclude") +@pytest.mark.parametrize("dim,cell_size", [(2, 0.2), (3, 0.4)]) +def test_reproduces_an_arbitrary_coarse_field(dim, cell_size): + """The transfer must be the coarse P1 EMBEDDING, not merely a linear + interpolant. + + Reproducing a globally linear field (the test below) is far too weak — any + local averaging of nearby values passes it, so a prolongation that + attributed weights to the wrong coarse cell would go undetected. This uses + a RANDOM coarse nodal field, where only the true embedding agrees. + + The reference is computed independently: every bisection vertex lies on a + coarse edge, so the P1 value there is (1-t) u_a + t u_b along that edge. + Deliberately NOT `uw.function.evaluate`, which returns wrong values at + points lying exactly on cell boundaries (#432) — using it as the reference + produced a convincing false accusation against this code. + """ + child = _adapted(dim, cell_size) + Ps = child._adapt_prolongation + lvl = _levels(child)[-(len(Ps) + 1):] + rng = np.random.default_rng(0) + for k, entry in enumerate(Ps): + if entry is None: + continue + cdm, fdm = lvl[k], lvl[k + 1] + P = _as_matrix(entry, cdm, fdm) + cvS, cvE = cdm.getDepthStratum(0) + ceS, ceE = cdm.getDepthStratum(1) + fvS, fvE = fdm.getDepthStratum(0) + cx = cdm.getCoordinatesLocal().array.reshape(-1, dim) + fx = fdm.getCoordinatesLocal().array.reshape(-1, dim) + data = rng.standard_normal(cvE - cvS) + got = P @ data + + edges = np.asarray([[c[0] - cvS, c[1] - cvS] + for e in range(ceS, ceE) + for c in (cdm.getCone(e),) + if len(c) == 2 and all(cvS <= q < cvE for q in c)]) + A, B = cx[edges[:, 0]], cx[edges[:, 1]] + AB = B - A + L2 = np.einsum("ij,ij->i", AB, AB) + checked = 0 + for r in range(fvE - fvS): + t = np.einsum("ij,ij->i", AB, fx[r][None, :] - A) / L2 + on = (t > -1e-12) & (t < 1.0 + 1e-12) + if not on.any(): + continue + resid = np.linalg.norm(A[on] + t[on, None] * AB[on] - fx[r], axis=1) + hit = np.nonzero(resid < 1e-12)[0] + if not len(hit): + continue + e0 = np.nonzero(on)[0][hit[0]] + t0 = t[on][hit[0]] + truth = (1 - t0) * data[edges[e0, 0]] + t0 * data[edges[e0, 1]] + assert abs(got[r] - truth) < 1e-10, ( + f"pass {k}, fine vertex {r}: transfer {got[r]} != coarse P1 " + f"value {truth} on the edge it lies on — the prolongation is " + f"not the coarse embedding") + checked += 1 + assert checked > 0.9 * (fvE - fvS), ( + f"pass {k}: only {checked} of {fvE - fvS} vertices lay on a coarse " + f"edge; the test is not covering what it claims") + + @pytest.mark.parametrize("dim,cell_size", [(2, 0.2), (3, 0.4)]) def test_reproduces_a_linear_field_exactly(dim, cell_size): - """P1 interpolation of a linear function is that function.""" + """Necessary but WEAK — see the embedding test above. Kept because a + failure here localises the problem to the arithmetic rather than the + parentage.""" child = _adapted(dim, cell_size) Ps = child._adapt_prolongation lvl = _levels(child)[-(len(Ps) + 1):] From 380afcb1cc2fa8e53e77b9c6761825a7636542f8 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Mon, 27 Jul 2026 12:50:03 +1000 Subject: [PATCH 16/16] chore: align the duplicated floor fix with #420 and make the dense fallback loud MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review follow-ups. STALENESS / MERGE HAZARD. This branch was cherry-picked from a branch that already carried the per-cell collapse floor, so it duplicates PR #420. The two copies were functionally identical but differed in em-dashes and a missing issue reference, which would have produced a pointless comment-only conflict when #420 lands. The block is now byte-identical to #420's, so the rebase after #420 merges is a clean no-op. Merge order is therefore: #420 first, then rebase this branch — the duplicate hunks drop out silently rather than conflicting. DENSE FALLBACK NOW SAYS SO. The RBF retry rescues correctness when the barycentric orphan repair cannot place every coarse DOF, but it returns a FULLY DENSE transfer (nnz/row == n_coarse), which makes the Galerkin coarse operators dense. On the small meshes where it has fired that is harmless; at production size it is a silent performance cliff of exactly the kind the GAMG fallback was. The warning now says this outright and tells the reader to fix the cause rather than accept the symptom. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/custom_mg.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index 10dc42ece..d4de03719 100644 --- a/src/underworld3/utilities/custom_mg.py +++ b/src/underworld3/utilities/custom_mg.py @@ -1019,7 +1019,12 @@ def auto_inject_custom_mg(solver, field_id=None): f"custom_mg: {_b} transfer build failed ({exc}); " f"retrying with the '{_attempts[_i + 1]}' builder, which " f"has global support and cannot leave a coarse DOF " - f"without a fine image.") + f"without a fine image. NOTE the RBF transfer is DENSE " + f"(nnz/row == n_coarse), so the Galerkin coarse operators " + f"are dense too — this rescues correctness but does not " + f"scale. If it fires on a production-sized problem, treat " + f"it as a performance cliff and fix the cause, not the " + f"symptom (#424).") continue warnings.warn( f"custom_mg: mesh-owned FMG build failed ({exc}); using the "