From d6423fd574e60749ddc9bcd0e374c901aed487e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 15:17:00 +1100 Subject: [PATCH 1/5] The MMPDE mover reaches its minimum: no stall, and a time step that does not burn its budget On an annulus with a sharp thermal layer the default mover stopped at the fifth of 150 outer iterations, its energy 9 % above what plain descent reaches. Two causes. A failed conjugate direction was taken for convergence; it now restarts along steepest descent. The metric, interpolated from its nearest nodes, made the energy jump where those nodes change; it is now a P1 field on a copy of the starting mesh, read with evaluate (global_evaluate in parallel), so it is continuous, a function of space, and the same at any rank count. Cost: the metric is read once per step and carried to each line-search trial to first order with that step's gradient, which is what the descent direction assumes; the gradient takes forward differences. A stagnation exit is on by default (stol=3e-4): near its minimum the mover otherwise spent all 150 iterations on moves too small to matter. Rigid bounding surfaces give their normal analytically instead of re-projecting it twice per iteration. A first move on this annulus takes 33 s and a second 15 s, against 73 s and 185 s with the frozen field alone. Underworld development team with AI support from Claude Code --- src/underworld3/meshing/bounding_surface.py | 15 +++- src/underworld3/meshing/smoothing/mmpde.py | 90 +++++++++++++++---- .../test_0765_mmpde_descent_does_not_stall.py | 43 +++++++++ 3 files changed, 128 insertions(+), 20 deletions(-) create mode 100644 tests/test_0765_mmpde_descent_does_not_stall.py diff --git a/src/underworld3/meshing/bounding_surface.py b/src/underworld3/meshing/bounding_surface.py index d3ec0679f..7cf3efad8 100644 --- a/src/underworld3/meshing/bounding_surface.py +++ b/src/underworld3/meshing/bounding_surface.py @@ -147,8 +147,21 @@ def normals(self, coords): ``_gamma_p1_at_vertices`` did in git history) and re-solve only for free surfaces. See docs/developer/design/boundary-slip-strategy.md. """ + coords = np.ascontiguousarray(coords, dtype=float) + # A rigid surface knows its own normal. Up to sign, which a tangent slide + # does not see, and at the true surface rather than the faceted one. The + # projection below costs an evaluate per label per mover iteration. + if self.kind == "plane" and not self.is_free: + return (np.broadcast_to(self.normal, coords.shape).copy(), + np.ones(coords.shape[0], dtype=bool)) + if self.kind == "radial" and not self.is_free: + away = coords - self.centre + length = np.linalg.norm(away, axis=1) + valid = length > 0.0 + away[valid] /= length[valid, None] + return away, valid from underworld3.meshing.smoothing import _slip_normals - return _slip_normals(self._mesh, np.ascontiguousarray(coords, dtype=float)) + return _slip_normals(self._mesh, coords) # -- tangent slide ------------------------------------------------------- def tangent_project(self, coords, reference): diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index 9da04b4dd..d9ecdc976 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -89,8 +89,8 @@ def _mmpde_mover(mesh, metric, pinned_labels, verbose, n_outer=150, p=1.5, theta=1.0 / 3.0, tau=1.0, step_frac=0.2, area_floor_frac=0.01, boundary_slip=False, outer_tol=1.0e-7, tol=1.0e-3, - stol=None, stol_k=3, - fd_eps=1.0e-6, metric_eval="rbf", rbf_k=None, + stol=3.0e-4, stol_k=3, + fd_eps=1.0e-6, metric_eval="frozen", rbf_k=None, accel="cg", momentum=0.0, resolution_ratio=None, reference="mesh", **_unknown_kwargs): @@ -168,6 +168,15 @@ def _mmpde_mover(mesh, metric, pinned_labels, verbose, criterion. Same metric, same grading, same non-folding guarantee; only the shape target moves. + ``metric_eval`` selects how the metric is read at moved points. ``"frozen"`` + (default) holds it as a P1 field on a copy of the starting mesh and reads it there + with ``uw.function.evaluate`` (``global_evaluate`` in parallel): a function of + space, continuous, and the same at any rank count. ``"rbf"`` interpolates its + nodal values by inverse distance from the nearest nodes, which is cheaper, but the + energy jumps where the nearest nodes change and the line search stalls far from + the minimum. ``"sympy"`` evaluates the metric expression on the moving mesh, where + a metric built from a mesh variable rides the nodes. + ``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 @@ -235,16 +244,15 @@ def _eval_M_analytic(pts): # keeps the move valid for whatever M it is handed). _eval_M = _eval_M_analytic - def _dM_dx(cen): - """∂M/∂x at centroids via centred FD on the analytic metric → - (n, cdim, cdim, cdim) indexed [cell, a, b, component].""" + def _dM_dx(cen, M_at_cen): + """∂M/∂x at centroids by forward differences from ``M_at_cen``, the metric + already read there → (n, cdim, cdim, cdim) indexed [cell, a, b, component]. + One read per direction: the metric is a guide, and first order is enough.""" n = cen.shape[0] d = np.zeros((n, cdim, cdim, cdim)) for c in range(cdim): sh = np.zeros(cdim); sh[c] = fd_eps - Mp = _eval_M(cen + sh) - Mm = _eval_M(cen - sh) - d[:, :, :, c] = (Mp - Mm) / (2.0 * fd_eps) + d[:, :, :, c] = (_eval_M(cen + sh) - M_at_cen) / fd_eps return d # --- topology / parallel scaffolding --------------------------- @@ -310,6 +318,31 @@ def _eval_M(pts): w = 1.0 / np.maximum(dist, 1.0e-12) ** 2 w /= w.sum(axis=1, keepdims=True) return np.einsum('nk,nkab->nab', w, M_src[idx]) + elif metric_eval == "frozen": + # The metric is a function of space, so it lives on a copy of the mesh + # that does not move and uw.function.evaluate reads it there. Evaluated + # on the moving mesh, a metric built from a mesh variable rides the + # nodes, and the energy the line search compares changes under it. + _frozen_dm = mesh.dm.clone() + _frozen_dm.setCoordinatesLocal(mesh.dm.getCoordinatesLocal().copy()) + _frozen_mesh = uw.discretisation.Mesh( + _frozen_dm, simplex=True, qdegree=mesh.qdegree, + coordinate_system_type=mesh.CoordinateSystem.coordinate_type, + boundaries=mesh.boundaries) + _frozen_M = uw.discretisation.MeshVariable( + "M_frozen", _frozen_mesh, vtype=uw.VarType.TENSOR, degree=1) + _frozen_M.array[...] = _eval_M_analytic( + np.asarray(_frozen_M.coords_nd)).reshape(_frozen_M.array.shape) + + # A moved centroid can leave this rank's frozen patch, where the rank-local + # evaluate extrapolates: global_evaluate answers from the owning rank. Every + # rank reaches this collective: the energy and gradient are collective. + _evaluate = (uw.function.global_evaluate if parallel + else uw.function.evaluate) + + def _eval_M(pts): + return np.asarray(_evaluate( + _frozen_M.sym, pts)).reshape(-1, cdim, cdim) else: _eval_M = _eval_M_analytic @@ -434,15 +467,17 @@ def _halo_sync(X): coord_dm.globalToLocal(global_vec, local_vec) return np.asarray(local_vec.array).reshape(-1, cdim).copy() - def _energy(X): - """I_h = Σ_owned |K| G (collective).""" + def _energy(X, M=None): + """I_h = Σ_owned |K| G (collective). ``M``, the metric per owned cell, is + read at the centroids of ``X`` unless given.""" E = _edge_mats(X, cells_own) detE = np.linalg.det(E) Einv = np.linalg.inv(E) J = np.einsum('mij,mjk->mik', Eh, Einv) r = detEh / detE - cen = X[cells_own].mean(axis=1) - M = _eval_M(cen); Minv = np.linalg.inv(M); detM = np.linalg.det(M) + if M is None: + M = _eval_M(X[cells_own].mean(axis=1)) + Minv = np.linalg.inv(M); detM = np.linalg.det(M) JMi = np.einsum('mij,mjk->mik', J, Minv) S = np.einsum('mij,mij->m', JMi, J) G = (theta * np.sqrt(detM) * S ** q @@ -510,6 +545,11 @@ def _gdot(a, b, mask): G = (theta * sdetM * S ** q + (1.0 - 2.0 * theta) * dq * r ** p * detM ** ((1 - p) / 2)) K = np.abs(detE) / fact + # The line search compares energies under a metric read once per step: M at + # the current centroids, carried to each trial centroid to first order with + # this step's ∂M/∂x. That is the M the descent direction assumes, so the two + # agree, and a trial costs no metric read. + I_step = _global_sum(np.sum(K * G)) # ∂G/∂𝕁 = 2qθ√detM S^{q-1} M⁻¹ 𝕁ᵀ ; ∂G/∂r = p(1-2θ)dq detM^{(1-p)/2} r^{p-1} MinvJT = np.einsum('mij,mkj->mik', Minv, J) dGdJ = (2.0 * q * theta * sdetM * S ** (q - 1.0))[:, None, None] * MinvJT @@ -539,7 +579,7 @@ def _gdot(a, b, mask): dGdM += ((1.0 - 2.0 * theta) * dq * r ** p * ((1.0 - p) / 2.0) * detM ** ((1 - p) / 2) )[:, None, None] * Minv - dMdx = _dM_dx(cen) # (Nc,d,d,c) + dMdx = _dM_dx(cen, M) # (Nc,d,d,c) # grad contribution per centroid component c, shared 1/(d+1) per vert gmet = np.einsum('mab,mabc->mc', dGdM, dMdx) # tr(dGdM·∂_cM) gmet = (K / (cdim + 1.0))[:, None] * gmet @@ -622,7 +662,7 @@ def _gdot(a, b, mask): # energy line-search backtrack (monotone, fold-free; collective) scale = 1.0 accepted = coords - Inew = prevI + Inew = I_step for _bt in range(24): trial = coords.copy() trial[free_owned] += scale * step[free_owned] @@ -632,12 +672,23 @@ def _gdot(a, b, mask): # could still introduce inf/NaN) so `_energy` never queries NaN. if (np.all(np.isfinite(trial)) and _min_area_frac(trial) > float(area_floor_frac)): - Itr = _energy(trial) - if Itr < prevI: + shift = trial[cells_own].mean(axis=1) - cen + M_trial = _spd_sanitise(M + np.einsum('mabc,mc->mab', dMdx, shift)) + Itr = _energy(trial, M_trial) + if Itr < I_step: accepted = trial; Inew = Itr; break scale *= 0.5 else: - accepted = coords; Inew = prevI; scale = 0.0 + accepted = coords; Inew = I_step; scale = 0.0 + # A conjugate direction need not descend: the per-node step cap and the + # inexact line search both break conjugacy, and on a sharp metric every + # backtrack can then fail far from the minimum. That says nothing about + # the minimum, so retry along steepest descent; only a failure there + # ends the sweep. Collective: scale comes from allreduced predicates. + if scale == 0.0 and _accel == "cg" and _beta_cg > 0.0: + _prev_v = np.zeros_like(coords) + _prev_dir = np.zeros_like(coords) + continue dmax = _global_max(np.linalg.norm( (accepted - coords)[is_owned_v], axis=1).max(initial=0.0)) _prev_disp = accepted - coords # accepted move, for next-iter momentum @@ -660,8 +711,9 @@ def _gdot(a, b, mask): # a step-test can't fire; instead test the *energy* (the residual) drop # over the last `stol_k` accepted iterations -- a WINDOW (not single # step), which is immune to the line-search per-iteration noise and to - # the occasional big drop after a scale reduction. Opt-in: stol=None/0 - # preserves the previous behaviour bit-for-bit. + # the occasional big drop after a scale reduction. On by default: near + # its minimum the mover otherwise spends its whole iteration budget on + # moves too small to matter. stol=None or 0 turns it off. if stol is not None and stol > 0.0: _Iwin.append(Inew) if len(_Iwin) > stol_k: diff --git a/tests/test_0765_mmpde_descent_does_not_stall.py b/tests/test_0765_mmpde_descent_does_not_stall.py new file mode 100644 index 000000000..ac69c0772 --- /dev/null +++ b/tests/test_0765_mmpde_descent_does_not_stall.py @@ -0,0 +1,43 @@ +"""The MMPDE mover must not stall far from the minimum of its energy. + +On an annulus with a sharp thermal layer the default mover stopped at the fifth +outer iteration of 150, its energy 9 % above what plain descent reaches. Two causes: +a failed conjugate direction was taken for convergence, and the metric, interpolated +from its nearest nodes, made the energy jump where those nodes change, so even +steepest descent could not go further. Converged runs of the two descents agree to +about 1 %. +""" +import pytest +import sympy + +import underworld3 as uw + +pytestmark = [pytest.mark.level_1, pytest.mark.tier_b] + + +def _energy_trace(accel, capsys): + mesh = uw.meshing.Annulus(radiusOuter=1.0, radiusInner=0.5, cellSize=1 / 16, qdegree=3) + x, y = mesh.X + r = sympy.sqrt(x ** 2 + y ** 2) + T = uw.discretisation.MeshVariable(f"T_{accel}", mesh, 1, degree=2) + field = 0.5 * (1 - sympy.tanh((r - 0.9) / 0.03)) * (1 + 0.3 * sympy.cos(4 * sympy.atan2(y, x))) + T.array[:, 0, 0] = uw.function.evaluate(field, T.coords).reshape(-1) + rho = uw.meshing.metric_density_from_gradient( + mesh, T, refinement=5, coarsening="auto", metric_choice="front-following") + capsys.readouterr() + uw.meshing.node_redistribution( + mesh, rho, verbose=True, + method_kwargs=dict(step_frac=0.2, accel=accel, momentum=0.0, n_outer=60), + slip_surfaces=True, skip_threshold=None) + trace = capsys.readouterr().out + energy = [float(line.split("I=")[1].split()[0]) for line in trace.splitlines() + if "mmpde outer" in line] + return energy + + +def test_cg_reaches_the_energy_of_plain_descent(capsys): + cg = _energy_trace("cg", capsys) + plain = _energy_trace("none", capsys) + assert cg[-1] <= 1.01 * plain[-1], ( + f"cg stopped at I={cg[-1]:.4f} after {len(cg)} outer iterations; " + f"plain descent reached I={plain[-1]:.4f} in {len(plain)}") From 06fea901f6314229121f0705805083ffbae78de0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 15:39:19 +1100 Subject: [PATCH 2/5] Review of the mover change: a trial passed on the carried metric is confirmed on the metric read there The first-order carry can overshoot where the metric changes fast, and the SPD floor then lets the line search accept a step the true energy rejects. The read that confirms it is the next step's metric, so it adds no read, and the reported and windowed energies are the true energy again. A constant metric, as Mesh.relax passes, skips the frozen field. The test asserts how far the energy falls, not one descent against another. Underworld development team with AI support from Claude Code --- src/underworld3/meshing/smoothing/mmpde.py | 34 ++++++++++++------- .../test_0765_mmpde_descent_does_not_stall.py | 28 ++++++--------- 2 files changed, 33 insertions(+), 29 deletions(-) diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index d9ecdc976..5647040e4 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -318,7 +318,10 @@ def _eval_M(pts): w = 1.0 / np.maximum(dist, 1.0e-12) ** 2 w /= w.sum(axis=1, keepdims=True) return np.einsum('nk,nkab->nab', w, M_src[idx]) - elif metric_eval == "frozen": + elif metric_eval == "frozen" and any( + getattr(e, "free_symbols", None) for e in Msym): + # (A constant metric, as Mesh.relax gives, needs no field: the exact read + # below is free.) # The metric is a function of space, so it lives on a copy of the mesh # that does not move and uw.function.evaluate reads it there. Evaluated # on the moving mesh, a metric built from a mesh variable rides the @@ -492,6 +495,7 @@ def _min_area_frac(X): (signed_vol(X, cells_own) * orient / a0_own).min(initial=np.inf)) prevI = _energy(coords) + _M_next = None # the metric at the accepted centroids, read by the line search _Iwin = [prevI] # accepted-energy history for the stol stagnation test # Acceleration of the first-order steepest-descent direction (``accel``). # The energy+min-area line-search below stays the fold guard, so any @@ -538,17 +542,19 @@ def _gdot(a, b, mask): J = np.einsum('mij,mjk->mik', Eh, Einv) r = detEh / detE cen = coords[cells_own].mean(axis=1) - M = _eval_M(cen); Minv = np.linalg.inv(M); detM = np.linalg.det(M) + M = _M_next if _M_next is not None else _eval_M(cen) + Minv = np.linalg.inv(M); detM = np.linalg.det(M) sdetM = np.sqrt(detM) JMi = np.einsum('mij,mjk->mik', J, Minv) S = np.einsum('mij,mij->m', JMi, J) G = (theta * sdetM * S ** q + (1.0 - 2.0 * theta) * dq * r ** p * detM ** ((1 - p) / 2)) K = np.abs(detE) / fact - # The line search compares energies under a metric read once per step: M at - # the current centroids, carried to each trial centroid to first order with - # this step's ∂M/∂x. That is the M the descent direction assumes, so the two - # agree, and a trial costs no metric read. + # The line search screens each trial with M carried from the current + # centroids to first order with this step's ∂M/∂x, which costs no metric + # read, and confirms a trial that passes with the metric read at its own + # centroids: the linear carry can overshoot where the metric changes fast. + # That read is the next step's M, so the step costs no extra read. I_step = _global_sum(np.sum(K * G)) # ∂G/∂𝕁 = 2qθ√detM S^{q-1} M⁻¹ 𝕁ᵀ ; ∂G/∂r = p(1-2θ)dq detM^{(1-p)/2} r^{p-1} MinvJT = np.einsum('mij,mkj->mik', Minv, J) @@ -672,20 +678,24 @@ def _gdot(a, b, mask): # could still introduce inf/NaN) so `_energy` never queries NaN. if (np.all(np.isfinite(trial)) and _min_area_frac(trial) > float(area_floor_frac)): - shift = trial[cells_own].mean(axis=1) - cen - M_trial = _spd_sanitise(M + np.einsum('mabc,mc->mab', dMdx, shift)) - Itr = _energy(trial, M_trial) - if Itr < I_step: - accepted = trial; Inew = Itr; break + trial_cen = trial[cells_own].mean(axis=1) + M_carried = _spd_sanitise( + M + np.einsum('mabc,mc->mab', dMdx, trial_cen - cen)) + if _energy(trial, M_carried) < I_step: + M_read = _eval_M(trial_cen) + Itr = _energy(trial, M_read) + if Itr < I_step: + accepted = trial; Inew = Itr; _M_next = M_read; break scale *= 0.5 else: - accepted = coords; Inew = I_step; scale = 0.0 + accepted = coords; Inew = I_step; scale = 0.0; _M_next = M # A conjugate direction need not descend: the per-node step cap and the # inexact line search both break conjugacy, and on a sharp metric every # backtrack can then fail far from the minimum. That says nothing about # the minimum, so retry along steepest descent; only a failure there # ends the sweep. Collective: scale comes from allreduced predicates. if scale == 0.0 and _accel == "cg" and _beta_cg > 0.0: + _M_next = M _prev_v = np.zeros_like(coords) _prev_dir = np.zeros_like(coords) continue diff --git a/tests/test_0765_mmpde_descent_does_not_stall.py b/tests/test_0765_mmpde_descent_does_not_stall.py index ac69c0772..b9205af89 100644 --- a/tests/test_0765_mmpde_descent_does_not_stall.py +++ b/tests/test_0765_mmpde_descent_does_not_stall.py @@ -4,40 +4,34 @@ outer iteration of 150, its energy 9 % above what plain descent reaches. Two causes: a failed conjugate direction was taken for convergence, and the metric, interpolated from its nearest nodes, made the energy jump where those nodes change, so even -steepest descent could not go further. Converged runs of the two descents agree to -about 1 %. +steepest descent could not go further. """ import pytest import sympy import underworld3 as uw -pytestmark = [pytest.mark.level_1, pytest.mark.tier_b] +pytestmark = [pytest.mark.level_2, pytest.mark.tier_b] -def _energy_trace(accel, capsys): +def test_the_default_mover_reaches_its_minimum(capsys): + """From the first step's energy: stalled, it fell 0.5 % in 3 outer iterations; + converged, 13 % in 38.""" mesh = uw.meshing.Annulus(radiusOuter=1.0, radiusInner=0.5, cellSize=1 / 16, qdegree=3) x, y = mesh.X r = sympy.sqrt(x ** 2 + y ** 2) - T = uw.discretisation.MeshVariable(f"T_{accel}", mesh, 1, degree=2) + T = uw.discretisation.MeshVariable("T0765", mesh, 1, degree=2) field = 0.5 * (1 - sympy.tanh((r - 0.9) / 0.03)) * (1 + 0.3 * sympy.cos(4 * sympy.atan2(y, x))) T.array[:, 0, 0] = uw.function.evaluate(field, T.coords).reshape(-1) - rho = uw.meshing.metric_density_from_gradient( + density = uw.meshing.metric_density_from_gradient( mesh, T, refinement=5, coarsening="auto", metric_choice="front-following") capsys.readouterr() uw.meshing.node_redistribution( - mesh, rho, verbose=True, - method_kwargs=dict(step_frac=0.2, accel=accel, momentum=0.0, n_outer=60), + mesh, density, verbose=True, + method_kwargs=dict(step_frac=0.2, accel="cg", momentum=0.0), slip_surfaces=True, skip_threshold=None) trace = capsys.readouterr().out energy = [float(line.split("I=")[1].split()[0]) for line in trace.splitlines() if "mmpde outer" in line] - return energy - - -def test_cg_reaches_the_energy_of_plain_descent(capsys): - cg = _energy_trace("cg", capsys) - plain = _energy_trace("none", capsys) - assert cg[-1] <= 1.01 * plain[-1], ( - f"cg stopped at I={cg[-1]:.4f} after {len(cg)} outer iterations; " - f"plain descent reached I={plain[-1]:.4f} in {len(plain)}") + drop = (energy[0] - energy[-1]) / energy[0] + assert drop > 0.08, f"energy fell {drop:.1%} in {len(energy)} outer iterations" From cac06a0a1fa147604edca5e2b7ca44795219bd32 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 00:54:57 +1100 Subject: [PATCH 3/5] test_0765: parse the trace on every rank, and guard the constant-metric skip Only rank 0 prints the mover's trace, so broadcast it before parsing (H1 review F2, IndexError on rank 1 at np 2). Add a test that a constant metric, as Mesh.relax passes, builds no frozen metric field while a spatial one does; it fails with the skip in 06fea901 undone (H1 review F1, first half). Co-Authored-By: Claude Opus 5.5 --- .../test_0765_mmpde_descent_does_not_stall.py | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/tests/test_0765_mmpde_descent_does_not_stall.py b/tests/test_0765_mmpde_descent_does_not_stall.py index b9205af89..97e69204a 100644 --- a/tests/test_0765_mmpde_descent_does_not_stall.py +++ b/tests/test_0765_mmpde_descent_does_not_stall.py @@ -30,8 +30,39 @@ def test_the_default_mover_reaches_its_minimum(capsys): mesh, density, verbose=True, method_kwargs=dict(step_frac=0.2, accel="cg", momentum=0.0), slip_surfaces=True, skip_threshold=None) - trace = capsys.readouterr().out + # Only rank 0 prints the trace; every rank parses its copy. + trace = uw.mpi.comm.bcast(capsys.readouterr().out, root=0) energy = [float(line.split("I=")[1].split()[0]) for line in trace.splitlines() if "mmpde outer" in line] drop = (energy[0] - energy[-1]) / energy[0] assert drop > 0.08, f"energy fell {drop:.1%} in {len(energy)} outer iterations" + + +def _frozen_metric_fields(monkeypatch): + """Record the name of every MeshVariable built while the mover runs.""" + made = [] + cls = uw.discretisation.MeshVariable + real_init = cls.__init__ + + def recording(self, varname=None, *args, **kwargs): + made.append(varname) + real_init(self, varname, *args, **kwargs) + + monkeypatch.setattr(cls, "__init__", recording) + return made + + +def test_a_constant_metric_builds_no_frozen_field(monkeypatch): + """``Mesh.relax`` passes a constant metric, which the mover reads exactly at any + point. It skips the frozen copy of the mesh that a spatial metric needs. The + control is the same mover on a metric that varies in space.""" + mesh = uw.meshing.UnstructuredSimplexBox( + minCoords=(0.0, 0.0), maxCoords=(1.0, 1.0), cellSize=0.25, qdegree=2) + made = _frozen_metric_fields(monkeypatch) + mesh.relax() + assert "M_frozen" not in made, made + + x, y = mesh.X + uw.meshing.node_redistribution(mesh, 1.0 + 4.0 * sympy.exp(-((y - 0.5) / 0.1) ** 2)) + assert "M_frozen" in made, made + From 1e42c849118c035e43039170506241afda1e7f2d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 06:22:19 +1100 Subject: [PATCH 4/5] The MMPDE mover returns its accepted energies, and a test guards the confirmed read _mmpde_mover returns the energy of the starting mesh and of each accepted step. The new test checks the last one against the true energy a second call reads on the same mesh; with the line search's confirmation in 06fea901 undone they differ by 0.2 % (H1 review F1, second half). Co-Authored-By: Claude Opus 5.5 --- src/underworld3/meshing/smoothing/mmpde.py | 6 +++++ .../test_0765_mmpde_descent_does_not_stall.py | 22 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index 5647040e4..a0728f893 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -182,6 +182,9 @@ def _mmpde_mover(mesh, metric, pinned_labels, verbose, every mover, and MMPDE's clustering intensity comes from the metric tensor itself. Any other unexpected keyword is warned about (READ-11: it is a caller typo, not a tunable) rather than silently swallowed. + + Returns the energy of the starting mesh followed by the energy of each accepted + step, every one read with the metric at that mesh's own centroids. """ import sympy from petsc4py import PETSc @@ -497,6 +500,7 @@ def _min_area_frac(X): prevI = _energy(coords) _M_next = None # the metric at the accepted centroids, read by the line search _Iwin = [prevI] # accepted-energy history for the stol stagnation test + energies = [prevI] # Acceleration of the first-order steepest-descent direction (``accel``). # The energy+min-area line-search below stays the fold guard, so any # accelerator overshoot is backtracked — never tangles (verified fold-proof @@ -715,6 +719,7 @@ def _gdot(a, b, mask): # The legacy absolute `outer_tol` is retained as an additional, even # tighter floor for callers that set it. prevI = Inew + energies.append(Inew) # Stagnation (residual stol) exit: PETSc-`stol`-style "give up when the # meshing functional stops dropping well below the last steps". The # node-step `dmax` is capped and never shrinks on this descent mover, so @@ -741,3 +746,4 @@ def _gdot(a, b, mask): coord_dm.restoreLocalVec(vloc) coord_dm.restoreGlobalVec(vglob) + return energies diff --git a/tests/test_0765_mmpde_descent_does_not_stall.py b/tests/test_0765_mmpde_descent_does_not_stall.py index 97e69204a..b8e2f9b58 100644 --- a/tests/test_0765_mmpde_descent_does_not_stall.py +++ b/tests/test_0765_mmpde_descent_does_not_stall.py @@ -66,3 +66,25 @@ def test_a_constant_metric_builds_no_frozen_field(monkeypatch): uw.meshing.node_redistribution(mesh, 1.0 + 4.0 * sympy.exp(-((y - 0.5) / 0.1) ** 2)) assert "M_frozen" in made, made + + +def test_the_reported_energy_is_the_energy_of_the_accepted_mesh(): + """The line search screens a trial with the metric carried to first order from + the current centroids, then confirms it with the metric read at its own, and + reports that confirmed energy. A second call starts by reading the true energy of + the mesh the first left, and the two agree. Without the confirmation the first + call reports the carried energy, which a sharp metric makes the linear carry + miss. The metric is read exactly from its expression, so both calls see the same + one.""" + from underworld3.meshing.smoothing import _mmpde_mover + + mesh = uw.meshing.Annulus(radiusOuter=1.0, radiusInner=0.5, cellSize=1 / 16, qdegree=3) + x, y = mesh.X + r = sympy.sqrt(x ** 2 + y ** 2) + density = 1.0 + 60.0 * sympy.exp(-((r - 0.9) / 0.02) ** 2) + kwargs = dict(step_frac=0.2, accel="cg", momentum=0.0, metric_eval="sympy") + + moved = _mmpde_mover(mesh, density, ("Upper", "Lower"), False, n_outer=6, **kwargs) + again = _mmpde_mover(mesh, density, ("Upper", "Lower"), False, n_outer=1, **kwargs) + assert len(moved) > 2 and moved[-1] < moved[0] + assert abs(moved[-1] - again[0]) <= 1.0e-12 * again[0], (moved[-1], again[0]) From dfb4cb0671e9928086917f2fac194a3a02cbd9ad Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 07:32:04 +1100 Subject: [PATCH 5/5] The MMPDE mover returns an empty energy list on a rank with no cells Every other exit returns the list (H1 review, low). Co-Authored-By: Claude Opus 5.5 --- src/underworld3/meshing/smoothing/mmpde.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/underworld3/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index a0728f893..e8c735d77 100644 --- a/src/underworld3/meshing/smoothing/mmpde.py +++ b/src/underworld3/meshing/smoothing/mmpde.py @@ -273,7 +273,7 @@ def _dM_dx(cen, M_at_cen): # other ranks enter the collective energy/line-search reductions # below, hanging the job. Pre-existing 2D posture, inherited by 3D # (2026-07 review note); the fix is a collective emptiness check. - return + return [] fact = float(math.factorial(cdim)) # d! → |K| = |detE|/d! owned_cell = _owned_cell_mask(dm) cells_own = cells_all[owned_cell]