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). 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..3825be449 --- /dev/null +++ b/docs/developer/subsystems/mesh-shape-relaxation.md @@ -0,0 +1,184 @@ +# Mesh shape relaxation + +Refinement chooses where new nodes go from **combinatorics**, never from +geometry: newest-vertex bisection puts the node on whichever edge the tagging +rule nominated, centroid (Alfeld) refinement puts it at the cell centre. Neither +rule knows anything about the problem being solved. A refined mesh therefore +carries needles and slivers that reflect the base mesh's arbitrary choices — +elements organised around the base grid's axes rather than around the feature +you refined towards. + +**Relaxation** moves those nodes to where the geometry wants them, keeping the +resolution the refinement installed: + +```python +child = mesh.adapt(metric, max_levels=3) +child.relax() +``` + +or, in one call: + +```python +child = mesh.adapt(metric, max_levels=3, relax=True) +``` + +## Why the mover could not already do this + +The obvious tool was the MMPDE mover (`mesh.redistribute_nodes`), and it moved +*nothing*: `redistribute_nodes(1)` on a distorted mesh is exactly a no-op. + +The reason is the mover's **reference frame**, not its metric. MMPDE generates +the physical mesh as the image of a fixed *computational* mesh, and that +reference is set to the mesh's own coordinates on the first call. "Distortion" +therefore means *deviation from the mesh I was handed* — so a sliver-ridden mesh +is its own optimum, and under a uniform metric the identity map already +minimises the functional. + +Relaxation swaps the reference for a **regular simplex**. Distortion now means +*deviation from equilateral in the metric*, so the distortion a mesh arrived +with is no longer self-justifying. Everything else is unchanged: same +functional, same non-folding guarantee, same parallel assembly. (This is the +target-matrix idea from the TMOP literature.) + +Three frames exist on the mover's `reference=` argument: + +| `reference` | reference element | what it does | +|---|---|---| +| `"mesh"` | the mesh at first call | **redistribution** — the classical MMPDE. Default. | +| `"ideal"` | regular simplex at *each cell's own* volume | **shape repair at fixed size**. `r = 1` at entry, so the size term starts at its optimum and only shape moves. | +| `"ideal-metric"` | regular simplex at one uniform volume | shape repair **plus** re-grading; the metric sets size. | + +`mesh.relax()` selects `"ideal"`; `mesh.relax(metric)` selects `"ideal-metric"`. + +## Relaxing is not the same as relaxing to a metric + +```{warning} +Passing a metric to `relax()` changes what is being optimised. The +ideal-metric frame re-grades as well as reshapes, and it will **trade element +shape away** to chase the size field. Measured on a 4-level graded box, the +99th-percentile maximum angle went 117.9° → 113.8° with no metric, but +117.9° → **127.4°** with one. +``` + +Use `relax()` when you want a shape guarantee. Use `relax(metric)` when the +sizes themselves are wrong and you accept shape is no longer the objective. + +## Where to put the relaxation + +Two placements, and **neither dominates** — which you prefer depends on which +property you weight: + +```python +adapt(metric, max_levels=N, relax=True) # once, at the end (default) +adapt(metric, max_levels=N, relax="per-generation") # inside the refinement loop +``` + +Measured in 2D on a gmsh base with the NVB refiner, a dipping fault segment: + +| property | unrelaxed | at end | per generation | +|---|---|---|---| +| P1 interpolation error | 2.75e-2 | 2.56e-2 | **2.38e-2** | +| 99th pct max angle | 112° | 110° | **96°** | +| on-fault size spread (p90/p10) | 2.80 | **2.31** | **2.31** | +| far-field closure halo (excess cells) | 42.8 | **27.7** | 43.9 | +| cells | 1110 | 1110 | 1186 | + +Relaxing **at the end** cannot change the topology, so the cell count is +identical to the unrelaxed mesh, and it cuts the far-field closure halo most. +Relaxing **per generation** gives the cleanest element shapes and the lowest +error, because each generation marks from already-relaxed coordinates — but it +changes which cells get marked, so it spends ~3% more cells. + +Every column beats no relaxation. The default is at-end because it is the +cheaper and less invasive of the two. + +## Multigrid: fine in 2D, can break in 3D + +In **2D** relaxation is transparent to the custom-P geometric-MG tail. The +operators need only the *topological* hierarchy, and the coarse levels keep +their own coordinates. Measured with the Stokes velocity block and with +Poisson: full `pc=mg` in every configuration, no fallback, solutions agreeing +to four significant figures, and the at-end case one Krylov iteration +*cheaper*. + +### Why relaxation can disturb it, and why it no longer costs you the hierarchy + +The custom-P prolongation is built **geometrically, not topologically**. The +`barycentric` builder re-triangulates the coarse DOF *point cloud* +(`Delaunay(coarse_coords)`) and locates each fine DOF in one simplex of it; it +never consults the parent/child refinement relation. That is deliberate — it is +exactly what lets custom-P accept non-nested coarse/fine pairs — but it means a +preserved topology buys the transfer nothing. + +So the builder has **local support**: a coarse DOF is reached only if some fine +DOF lands in a simplex touching it. Move the fine coordinates, which is what +relaxation does, and a coarse DOF can lose every fine image. Its column in `P` +goes to zero, the Galerkin coarse operator `PᵀAP` acquires a zero row and +column, and it is singular. 3D is more exposed: a Delaunay triangulation of a +graded 3D cloud is full of slivers, each simplex has only four vertices, and +proportionally more DOFs sit near the hull. + +The builder now **repairs orphaned coarse DOFs directly**: each is given its +nearest fine DOF as a pure injection (weight 1), which is the same fallback +already used for fine points outside the coarse hull. Partition of unity and +sparsity (~d+1 non-zeros per row) are both preserved, and the column is no +longer empty. Measured on a relaxed 3D adapt child: `pc=mg` at 2 iterations, +where before the repair it fell back to GAMG at 23. + +If a pathological pair still leaves an orphan, the build retries with the +global-support `rbf` builder before giving up. That is a **last resort, not a +scalable transfer**: the RBF prolongation is fully dense (measured +`nnz/row == n_coarse` exactly — 200 of 200, 800 of 800), so `PᵀAP` is dense +too. It rescues correctness on small problems; it is not something to rely on +at production sizes. + +## What relaxation cannot do + +- **It cannot rescue centroid/Alfeld refinement.** Those slivers are + *structural* — an interior point wired to a fixed parent face, producing a fan + of near-degenerate cells radiating from one vertex. Node motion cannot unpick + a topology. Measured: cells with `q < 0.3` stay at 25–28% and the worst angle + stays at 176–178° whatever the placement. Centroid refinement is a + shallow tool only — see {doc}`../design/NVB_GRADED_ADAPT`. +- **It cannot flatten the size steps along a feature.** Bisection generations + are discrete (each halves cell area), so on-feature sizes come in + powers-of-two classes. Relaxation compresses the spread (p90/p10 2.80 → 2.31) + but two size classes remain populated. +- **It does not concentrate cells on the feature.** That is refinement's job. + Relaxation holds the size distribution by construction, so the share of cells + in the band barely moves (48.9% → 51.1%). + +## 3D + +Relaxation improves 3D mesh **quality** but has not been shown to improve +accuracy. On an adapted 3D mesh it halves the near-degenerate population (cells +with `q < 0.1`: 3.6% → 1.8%), lifts median quality 0.32 → 0.39 and pulls the +99th-percentile dihedral angle back from 153° to 146° — but the interpolation +error of an *isotropic* feature is unchanged (+0.5%). + +That is consistent rather than contradictory: relaxation holds the size +distribution, so its only route to lower error is by *aligning* cells with the +feature, and an isotropic metric gives it no reason to align anything. Whether +an anisotropic (tensor) metric recovers the 2D-style accuracy gain in 3D is +open — see the tracking issue. + +Use it in 3D for element quality and conditioning, not expecting an accuracy +win. + +## Diagnostics + +Element quality alone is a poor guide here, and can actively mislead: on a +structured base the *unrelaxed* mesh scores best on median quality (every cell +is an identical right triangle) while resolving the feature worst. Four +properties are worth reporting together: + +- **gather** — share of cells within the metric band; +- **clean** — fraction of near-degenerate cells and the 99th-percentile max + angle (not the worst single element); +- **uniform** — spread of cell size along the feature; +- **leakage** — refinement added where the metric did not ask for it. + +Leakage in particular resists being reduced to one number: it is a *spatial* +property (large coherent over-refined blocks versus small scattered patches), +and per-cell maps of `log2(h / h_asked_for)` are more informative than any +scalar we have found. diff --git a/src/underworld3/discretisation/discretisation_mesh.py b/src/underworld3/discretisation/discretisation_mesh.py index 84dd00cbf..c5cf555a7 100644 --- a/src/underworld3/discretisation/discretisation_mesh.py +++ b/src/underworld3/discretisation/discretisation_mesh.py @@ -6597,8 +6597,128 @@ 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. + + 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. + ``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 + 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 + ---------- + metric : sympy expression, MeshVariable, or sympy Matrix, optional + 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 + 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 +6884,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,7 +7141,78 @@ 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. + + 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. + """ + _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 = 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): + 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 = [] + _nested_parent_cells = [] + _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 @@ -7059,8 +7252,41 @@ def sync_mask(mask): 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_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: + # 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(_relax_metric, **(relax_kwargs or {})) + current_dm.setCoordinatesLocal( + _mg.dm.getCoordinatesLocal()) level_dms.append(current_dm) if verbose: fs, fe = current_dm.getHeightStratum(0) @@ -7077,7 +7303,8 @@ def sync_mask(mask): # 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")] @@ -7100,6 +7327,7 @@ def sync_mask(mask): 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 @@ -7119,8 +7347,22 @@ def sync_mask(mask): numpy.array([nvb.coords[i] for i in _idx])) for _k, _i in enumerate(_idx): nvb.coords[_i] = _snapped[_k] - level_dms.append(nvb.to_dm(boundaries=carry, regions=rcarry, - comm=self.dm.comm)) + if _relax_mode == "per-generation": + _relax_generation(nvb, carry, rcarry) + _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") @@ -7175,6 +7417,12 @@ def sync_mask(mask): 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" @@ -7184,6 +7432,11 @@ def sync_mask(mask): # 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 + 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/meshing/smoothing/mmpde.py b/src/underworld3/meshing/smoothing/mmpde.py index c6f549400..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,11 +342,79 @@ 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 - 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 +450,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 +630,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/src/underworld3/utilities/custom_mg.py b/src/underworld3/utilities/custom_mg.py index ccd9b07cd..d4de03719 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 @@ -78,8 +111,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): @@ -318,14 +389,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) # --------------------------------------------------------------------------- # @@ -687,6 +764,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 @@ -772,8 +888,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 @@ -871,15 +992,44 @@ 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. 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 " + "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. diff --git a/src/underworld3/utilities/nvb.py b/src/underworld3/utilities/nvb.py index b76c9cd86..9308eabe5 100644 --- a/src/underworld3/utilities/nvb.py +++ b/src/underworld3/utilities/nvb.py @@ -168,6 +168,274 @@ 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_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. + + 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: + + 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)``, 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 = np.ascontiguousarray( + 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 = np.ascontiguousarray( + fine_dm.getCoordinatesLocal().array.reshape(-1, cdim)) + n_f = fvE - fvS + if fxyz.shape[0] != n_f: + return None + + # --- 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, row in enumerate(fxyz): + hit = known.get(row.tobytes()) + if hit is None: + continue + kind, i = hit + if kind == "v": + weights[r] = {int(i): 1.0} + else: + a, b = edges[i] + 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)] + 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: + still = [] + for r in unresolved: + 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] + avg = np.ascontiguousarray(0.5 * (fxyz[p_] + fxyz[q_])) + if avg.tobytes() == target: + found = (p_, q_) + break + if found: + break + if found is None: + still.append(r) + 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 = [], [], [] + 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. @@ -414,7 +682,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 @@ -439,9 +706,16 @@ 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 + # 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) @@ -803,7 +1077,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 @@ -829,10 +1102,12 @@ 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()} dm.markBoundaryFaces("All_Boundaries", 1001) 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 diff --git a/tests/test_0752_mesh_shape_relaxation.py b/tests/test_0752_mesh_shape_relaxation.py new file mode 100644 index 000000000..339de2255 --- /dev/null +++ b/tests/test_0752_mesh_shape_relaxation.py @@ -0,0 +1,186 @@ +"""``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(): + """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( + 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") diff --git a/tests/test_0753_nested_mg_prolongation.py b/tests/test_0753_nested_mg_prolongation.py new file mode 100644 index 000000000..56c38eda2 --- /dev/null +++ b/tests/test_0753_nested_mg_prolongation.py @@ -0,0 +1,222 @@ +"""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_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): + """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):] + 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 + + +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