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..e8c735d77 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,11 +168,23 @@ 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 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 @@ -235,16 +247,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 --------------------------- @@ -262,7 +273,7 @@ def _dM_dx(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] @@ -310,6 +321,34 @@ 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" 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 + # 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 +473,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 @@ -457,7 +498,9 @@ 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 + 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 @@ -503,13 +546,20 @@ 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 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) dGdJ = (2.0 * q * theta * sdetM * S ** (q - 1.0))[:, None, None] * MinvJT @@ -539,7 +589,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 +672,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 +682,27 @@ 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: - 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 = prevI; 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 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 @@ -654,14 +719,16 @@ 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 # 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: @@ -679,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 new file mode 100644 index 000000000..b8e2f9b58 --- /dev/null +++ b/tests/test_0765_mmpde_descent_does_not_stall.py @@ -0,0 +1,90 @@ +"""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. +""" +import pytest +import sympy + +import underworld3 as uw + +pytestmark = [pytest.mark.level_2, pytest.mark.tier_b] + + +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("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) + density = uw.meshing.metric_density_from_gradient( + mesh, T, refinement=5, coarsening="auto", metric_choice="front-following") + capsys.readouterr() + uw.meshing.node_redistribution( + mesh, density, verbose=True, + method_kwargs=dict(step_frac=0.2, accel="cg", momentum=0.0), + slip_surfaces=True, skip_threshold=None) + # 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 + + + +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])