From e2b157b8bdbd02e9dbe1cdddb5c374955dcd3194 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 31 Oct 2026 08:04:29 +1100 Subject: [PATCH 1/4] #894: test that the rotated loop smooths every iterate with its own operator With a fault interface law the rotated Newton loop hands the KSP a new operator at every iterate, and the velocity multigrid keeps the finest smoother's operator of iterate 0. The test records, after each linear solve, the operator the multigrid was handed and the finest smoother's operator, on the saddle-point and thin-sheet paths, with a viscous fault and with the frictionless contact as the control. On this commit (no fix) the viscous-fault cases fail: the operators differ by 0.77-0.87 (relative, Frobenius) at every iterate after the first, on both paths. The frictionless cases pass. Tier B, serial and parallel, one file under tests/parallel with no min_size mark (run from the serial batches beside test_1090). Underworld development team with AI support from Claude Code --- scripts/test.sh | 2 + ...088_rotated_interface_operator_parallel.py | 119 ++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 tests/parallel/test_1088_rotated_interface_operator_parallel.py diff --git a/scripts/test.sh b/scripts/test.sh index df7c057d3..7ae4fca49 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -323,6 +323,8 @@ if [ $PARALLEL_ONLY -eq 0 ]; then # The live multigrid configuration (#892) is the same check in serial and in # parallel, so it is one file under tests/parallel/ with no min_size mark too. batch 4 tests/parallel/test_1090_mg_live_configuration_parallel.py + # So is the live finest-smoother operator of the rotated Newton loop (#894). + batch 4 tests/parallel/test_1088_rotated_interface_operator_parallel.py # test_106*/test_107* were held back pending "a triage/deselect decision". That # decision is made: the band is not the unit of exclusion. Of the 243 tests in # the deferred bands only 26 are level_3 or tier_c; 55 are level_1 AND tier_a — diff --git a/tests/parallel/test_1088_rotated_interface_operator_parallel.py b/tests/parallel/test_1088_rotated_interface_operator_parallel.py new file mode 100644 index 000000000..01689660e --- /dev/null +++ b/tests/parallel/test_1088_rotated_interface_operator_parallel.py @@ -0,0 +1,119 @@ +"""The rotated Newton loop smooths every iterate with that iterate's operator (#894). + +With a fault interface law, ``solve_rotated_freeslip`` added the interface +tangent into a NEW matrix at every Newton iterate (``Atot = Ahat.copy()``, then +``axpy``) and handed it to the cached KSP. PCMG keeps the finest smoother's +operator once it is set unless the new operator is the same Mat object (the +``opsset`` check in PETSc's ``PCSetUp_MG``), so the finest smoother, and the +Galerkin coarse operators built from it, stayed at iterate 0. The answer was +unaffected; the cost was iterations. Measured on this fixture with a viscous +fault: 2, 32, 31, 26, 27 velocity iterations per increment, against 3 for the +frictionless contact, whose operator is refreshed in place. + +The test records, after every linear solve of the rotated loop, the operator the +multigrid was handed (the velocity block on the saddle-point path, the whole +rotated operator on the thin-sheet path) and the finest smoother's operator, and +checks that they agree at every iterate. A viscosity that depends on the +velocity gives the loop several iterates. The frictionless contact is the +control: it takes the other branch of the loop, and agreed before the fix. + +The fixture is test_1090's: a fault split in place over a welded base hierarchy +(1/8, 1/16), so the finest level is the split mesh and carries the FAC patch. +This file carries no ``mpi(min_size=2)`` mark: it runs in the serial suite and +in the parallel batches. + + python -m pytest tests/parallel/test_1088_rotated_interface_operator_parallel.py + mpirun -n 2 python -m pytest --with-mpi tests/parallel/test_1088_rotated_interface_operator_parallel.py +""" +import numpy as np +import pytest +import sympy +from petsc4py import PETSc + +import underworld3 as uw +from underworld3.utilities import custom_mg, rotated_bc + +pytestmark = [pytest.mark.level_2, pytest.mark.tier_b] + +TRACE = np.array([[0.3, 0.45], [0.7, 0.55]]) + + +@pytest.fixture(scope="module") +def base(): + return uw.meshing.UnstructuredSimplexBox( + minCoords=(0, 0), maxCoords=(1, 1), cellSize=1 / 8, regular=False, + qdegree=2, refinement=1) + + +def _operator_gap(mg): + """|finest smoother's operator - the operator ``mg`` was handed|_F, relative.""" + handed = mg.getOperators()[1] + finest = mg.getMGSmoother(mg.getMGLevels() - 1).getOperators()[1] + gap = handed.copy() + gap.axpy(-1.0, finest, structure=PETSc.Mat.Structure.DIFFERENT_NONZERO_PATTERN) + value = gap.norm(PETSc.NormType.FROBENIUS) / handed.norm(PETSc.NormType.FROBENIUS) + gap.destroy() + return value + + +def _solve_recording(base, path, law, monkeypatch): + """Solve on the split mesh by ``path`` with fault law ``law``; return one + ``(operator gap, velocity iterations)`` record per Newton increment.""" + records = [] + + def recorded(original, saddle): + def wrapper(*args, **kwargs): + out = original(*args, **kwargs) + ctx = out[2] + if saddle: + vel_ksp = ctx["pc"].getFieldSplitSubKSP()[0] + records.append((_operator_gap(vel_ksp.getPC()), + vel_ksp.getIterationNumber())) + else: + records.append((_operator_gap(ctx["pc"]), + ctx["ksp"].getIterationNumber())) + return out + return wrapper + + monkeypatch.setattr(rotated_bc, "_solve_rotated_iterative", + recorded(rotated_bc._solve_rotated_iterative, True)) + monkeypatch.setattr(rotated_bc, "_solve_rotated_vector", + recorded(rotated_bc._solve_rotated_vector, False)) + + levels = base._coarse_level_meshes()[:-1] + [base] + mesh = base.add_fault(("Flt", TRACE)) + x, y = mesh.X + if path == "stokes": + v = uw.discretisation.MeshVariable("v", mesh, 2, degree=2) + p = uw.discretisation.MeshVariable("p", mesh, 1, degree=1) + solver = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + for wall in ("Bottom", "Top", "Left", "Right"): + solver.add_dirichlet_bc((y - sympy.Rational(1, 2), 0), wall) + solver.petsc_use_pressure_nullspace = True + u = v + else: + solver = uw.systems.ThinSheet(mesh) + for wall in ("Bottom", "Top", "Left", "Right"): + solver.add_essential_bc([y - sympy.Rational(1, 2), 0], wall) + u = solver.u + solver.add_fault_bc(law, "Flt") + solver.constitutive_model = uw.constitutive_models.ViscousFlowModel + solver.constitutive_model.Parameters.shear_viscosity_0 = ( + 1 + 50 * (u.sym[0] ** 2 + u.sym[1] ** 2)) + solver.tolerance = 1e-6 + custom_mg.set_custom_fmg(solver, levels, field_id=0 if path == "stokes" else None) + solver.solve() + assert solver._rotated_freeslip_info["converged"], f"{path}: did not converge" + return records + + +@pytest.mark.parametrize("law", [1.0, 0], ids=["viscous_fault", "frictionless"]) +@pytest.mark.parametrize("path", ["stokes", "sheet"]) +def test_the_finest_smoother_follows_every_iterate(base, path, law, monkeypatch): + records = _solve_recording(base, path, law, monkeypatch) + # one increment would leave nothing to go stale: the test needs the iterates + assert len(records) >= 3, f"{path}: only {len(records)} Newton increments" + gaps = [gap for gap, _its in records] + assert max(gaps) < 1e-12, ( + f"{path}, law {law}: the finest smoother's operator differs from the " + f"operator the multigrid was handed, by {gaps} (relative, per increment; #894)") From 7b8223c8e8648ce13638f19a279c0fd90f55267f Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 31 Oct 2026 08:21:25 +1100 Subject: [PATCH 2/4] #894: refresh the interface-law operator in place in the rotated Newton loop With a fault interface law the loop built Ahat + Khat into a new Mat at every iterate. PCMG keeps the finest smoother's operator unless the PC's new pmat is that same object, and the fieldsplit hands over a new velocity block when the pattern changes, so the finest smoother and the Galerkin coarse operators stayed at iterate 0, on the saddle-point and the thin-sheet paths alike. The sum is now made once and refreshed in place after that: MatCopy of Ahat and MatAXPY of the tangent, both SUBSET_NONZERO_PATTERN, which insert into existing locations and leave the Mat and its nonzero state unchanged. This is what the frictionless contact already does with Ahat. The tangent's pattern is fixed by the fault facets and Ahat's by the ptap, so both stay inside the first sum's pattern. The null space attached to the first sum stays with it, so the re-attach is gone. test_1088 passes (it failed on the parent). Velocity iterations per Newton increment on its fixture, viscous fault: saddle point 2, 32, 31, 26, 27 -> 2, 2, 2, 3, 3; thin sheet 2, 27, 21, 21, 21, 20 -> 2 at every increment. The test now also bounds them at 5. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/rotated_bc.py | 28 +++++++++++-------- ...088_rotated_interface_operator_parallel.py | 22 +++++++++++---- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/underworld3/utilities/rotated_bc.py b/src/underworld3/utilities/rotated_bc.py index 7b21a6f8a..80246d5a0 100644 --- a/src/underworld3/utilities/rotated_bc.py +++ b/src/underworld3/utilities/rotated_bc.py @@ -1559,20 +1559,26 @@ def rotated_residual(uvec, keep_cartesian=False): # rates) and added to a COPY: the ptap-with-result refresh above # owns Ahat's structure, and injected entries would be # stale-or-doubled on the next refresh. + # + # The copy is made once and refreshed IN PLACE after that, so the KSP + # is handed the same Mat with the same nonzero pattern at every + # iterate, as on the contact path. A new Mat each iterate left the + # multigrid smoothing with iterate 0's operator: PCSetUp_MG keeps the + # finest smoother's operator unless it is the PC's own, and the + # fieldsplit hands over a new velocity block for a new pattern (#894). + # The tangent's pattern is fixed by the fault facets, and Ahat's by + # the ptap, so both stay inside the pattern of the first copy. if interface is not None: Khat = interface.tangent(solver, u) - if Atot is not None: - Atot.destroy() - Atot = Ahat.copy() - Atot.axpy(1.0, Khat, - structure=PETSc.Mat.Structure.DIFFERENT_NONZERO_PATTERN) + if Atot is None: + Atot = Ahat.copy() + Atot.axpy(1.0, Khat, + structure=PETSc.Mat.Structure.DIFFERENT_NONZERO_PATTERN) + else: + Ahat.copy(Atot, structure=PETSc.Mat.Structure.SUBSET_NONZERO_PATTERN) + Atot.axpy(1.0, Khat, + structure=PETSc.Mat.Structure.SUBSET_NONZERO_PATTERN) Khat.destroy() - # A recreated operator loses the null space the first solve - # attached; re-attach for iterations after the first (a nonlinear - # interface law is what reaches them). - if ctx is not None and ctx.get("nsp") is not None: - Atot.setNullSpace(ctx["nsp"]) - Atot.setTransposeNullSpace(ctx["nsp"]) Aop = Atot else: Aop = Ahat diff --git a/tests/parallel/test_1088_rotated_interface_operator_parallel.py b/tests/parallel/test_1088_rotated_interface_operator_parallel.py index 01689660e..15a903432 100644 --- a/tests/parallel/test_1088_rotated_interface_operator_parallel.py +++ b/tests/parallel/test_1088_rotated_interface_operator_parallel.py @@ -7,15 +7,23 @@ ``opsset`` check in PETSc's ``PCSetUp_MG``), so the finest smoother, and the Galerkin coarse operators built from it, stayed at iterate 0. The answer was unaffected; the cost was iterations. Measured on this fixture with a viscous -fault: 2, 32, 31, 26, 27 velocity iterations per increment, against 3 for the -frictionless contact, whose operator is refreshed in place. +fault, velocity iterations per Newton increment: + +| path | viscous fault, before | viscous fault, after | frictionless | +|---|---|---|---| +| saddle point | 2, 32, 31, 26, 27 | 2, 2, 2, 3, 3 | 3 at every increment | +| thin sheet | 2, 27, 21, 21, 21, 20 | 2 at every increment | 2 at every increment | + +The frictionless contact refreshes its operator in place, and the fix makes the +interface-law branch do the same. The test records, after every linear solve of the rotated loop, the operator the multigrid was handed (the velocity block on the saddle-point path, the whole rotated operator on the thin-sheet path) and the finest smoother's operator, and -checks that they agree at every iterate. A viscosity that depends on the -velocity gives the loop several iterates. The frictionless contact is the -control: it takes the other branch of the loop, and agreed before the fix. +checks that they agree at every iterate, then bounds the velocity iterations of +every increment at 5. A viscosity that depends on the velocity gives the loop +several iterates. The frictionless contact is the control: it takes the other +branch of the loop, and agreed before the fix. The fixture is test_1090's: a fault split in place over a welded base hierarchy (1/8, 1/16), so the finest level is the split mesh and carries the FAC patch. @@ -117,3 +125,7 @@ def test_the_finest_smoother_follows_every_iterate(base, path, law, monkeypatch) assert max(gaps) < 1e-12, ( f"{path}, law {law}: the finest smoother's operator differs from the " f"operator the multigrid was handed, by {gaps} (relative, per increment; #894)") + its = [its for _gap, its in records] + assert max(its) <= 5, ( + f"{path}, law {law}: velocity iterations per increment {its} (2-3 measured; " + f"20-32 with the stale smoother of #894)") From 7fae28e64e35aa5a5480f7ba74c68f901d248ab7 Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 31 Oct 2026 08:35:00 +1100 Subject: [PATCH 3/4] #894: the direct-LU path keeps a fresh interface-law operator each iterate The in-place refresh does not fit the direct-LU path: its pressure pin (zeroRows, without MAT_KEEP_NONZERO_PATTERN) drops the pinned row's entries from the sum, and the next MatCopy raised "new nonzero at (0,818) caused a malloc" at iterate 1. That path has no multigrid to go stale, so it builds a fresh sum as before; the in-place refresh stays on the multigrid paths. test_1088 gains the LU case. The path does not converge on a fault contact on development either (#899, filed: 50 increments, slip 4-5% off, with or without an interface law), so the case is a strict xfail on its convergence assertion only: the PETSc error above still fails it. Underworld development team with AI support from Claude Code --- src/underworld3/utilities/rotated_bc.py | 7 ++- ...088_rotated_interface_operator_parallel.py | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/underworld3/utilities/rotated_bc.py b/src/underworld3/utilities/rotated_bc.py index 80246d5a0..e9142e82e 100644 --- a/src/underworld3/utilities/rotated_bc.py +++ b/src/underworld3/utilities/rotated_bc.py @@ -1568,9 +1568,14 @@ def rotated_residual(uvec, keep_cartesian=False): # fieldsplit hands over a new velocity block for a new pattern (#894). # The tangent's pattern is fixed by the fault facets, and Ahat's by # the ptap, so both stay inside the pattern of the first copy. + # The direct-LU path still takes a fresh sum each iterate: its pressure + # pin (zeroRows) drops the pinned row's entries from the pattern, and + # it has no multigrid to go stale. if interface is not None: Khat = interface.tangent(solver, u) - if Atot is None: + if Atot is None or use_lu: + if Atot is not None: + Atot.destroy() Atot = Ahat.copy() Atot.axpy(1.0, Khat, structure=PETSc.Mat.Structure.DIFFERENT_NONZERO_PATTERN) diff --git a/tests/parallel/test_1088_rotated_interface_operator_parallel.py b/tests/parallel/test_1088_rotated_interface_operator_parallel.py index 15a903432..52d13b3bd 100644 --- a/tests/parallel/test_1088_rotated_interface_operator_parallel.py +++ b/tests/parallel/test_1088_rotated_interface_operator_parallel.py @@ -129,3 +129,50 @@ def test_the_finest_smoother_follows_every_iterate(base, path, law, monkeypatch) assert max(its) <= 5, ( f"{path}, law {law}: velocity iterations per increment {its} (2-3 measured; " f"20-32 with the stale smoother of #894)") + + +def _viscous_fault_slip(base, use_lu): + """Peak slip of the viscous-fault saddle-point solve, by the direct-LU rotated + path or by the multigrid one, solved tight enough to compare.""" + from underworld3.utilities.fault_contact import fault_slip + levels = base._coarse_level_meshes()[:-1] + [base] + mesh = base.add_fault(("Flt", TRACE)) + x, y = mesh.X + v = uw.discretisation.MeshVariable("v", mesh, 2, degree=2) + p = uw.discretisation.MeshVariable("p", mesh, 1, degree=1) + stokes = uw.systems.Stokes(mesh, velocityField=v, pressureField=p) + for wall in ("Bottom", "Top", "Left", "Right"): + stokes.add_dirichlet_bc((y - sympy.Rational(1, 2), 0), wall) + stokes.add_fault_bc(1.0, "Flt") + stokes.petsc_use_pressure_nullspace = True + stokes.constitutive_model = uw.constitutive_models.ViscousFlowModel + stokes.constitutive_model.Parameters.shear_viscosity_0 = ( + 1 + 50 * (v.sym[0] ** 2 + v.sym[1] ** 2)) + stokes.tolerance = 1e-8 + if use_lu: + stokes._rotated_use_lu = True + else: + custom_mg.set_custom_fmg(stokes, levels, field_id=0) + stokes.solve() + info = stokes._rotated_freeslip_info + assert info["converged"], f"use_lu={use_lu}: did not converge" + assert info["nonlinear_iterations"] >= 3, info["nonlinear_iterations"] + _s, slip, _leak = fault_slip(stokes, "Flt", info) + return uw.mpi.comm.allreduce(float(np.abs(slip).max()) if len(slip) else 0.0, op=max) + + +@pytest.mark.xfail(raises=AssertionError, strict=True, + reason="#899: the direct-LU path does not converge on a fault contact") +def test_the_direct_lu_path_takes_an_interface_law(base): + """The direct-LU path keeps a fresh operator at every iterate: its pressure pin + (``zeroRows``) drops the pinned row's entries, so the in-place refresh of the + multigrid paths would not fit it. An in-place refresh there raised PETSc's + "new nonzero caused a malloc" at iterate 1. + + The path does not converge on a fault contact at all (#899, on development + too), so this is a strict expected failure on the convergence ASSERTION + only: a PETSc error fails it, and so does a fix to #899, which should then + remove the mark.""" + lu = _viscous_fault_slip(base, use_lu=True) + mg = _viscous_fault_slip(base, use_lu=False) + assert abs(lu - mg) < 1e-6 * mg, (lu, mg) From 12e5fc0c045ee835db7260f099df8177a524af0a Mon Sep 17 00:00:00 2001 From: lmoresi Date: Sat, 31 Oct 2026 09:04:06 +1100 Subject: [PATCH 4/4] #894 review: the test bounds increments, covers the mesh's own tail and GAMG From the adversarial review of this branch: - The operator-gap check alone could not see an operator that is the right object holding iterate 0's values: a mutant that skips the in-place refresh passed the thin-sheet case. The test now also bounds the Newton increments (5-6 measured; the mutant takes 49 or stalls) and fails all six viscous-fault arms under that mutant. - The split mesh's own multigrid tail (no set_custom_fmg) was stale too (thin sheet 4, 30, 23, 24, 23, 22 before, 4-5 after) and is now an arm. GAMG is an arm as a control: it rebuilds from the live operator at every set-up and was never stale (31-44 before and after, gap 0). - The direct-LU case is an imperative xfail on non-convergence (#899) only, so a fix to #899 that converges to a different slip fails the test. - The comment named the wrong trigger: a new Pmat object resets the PC's nonzero state even with an identical pattern. - FAULT_CONTACT_DEPLOYMENT's trap list prescribed a rebuilt copy per iterate; it now says to refresh one copy in place, LU excepted. On the parent build the four viscous-fault multigrid arms fail and the rest pass; on this build 12 pass and the LU case xfails. Underworld development team with AI support from Claude Code --- .../FAULT_CONTACT_DEPLOYMENT_2026-08.md | 7 +- src/underworld3/utilities/rotated_bc.py | 7 +- ...088_rotated_interface_operator_parallel.py | 106 ++++++++++++------ 3 files changed, 81 insertions(+), 39 deletions(-) diff --git a/docs/developer/design/FAULT_CONTACT_DEPLOYMENT_2026-08.md b/docs/developer/design/FAULT_CONTACT_DEPLOYMENT_2026-08.md index c285c3569..a1557322d 100644 --- a/docs/developer/design/FAULT_CONTACT_DEPLOYMENT_2026-08.md +++ b/docs/developer/design/FAULT_CONTACT_DEPLOYMENT_2026-08.md @@ -220,7 +220,12 @@ prerequisite for any of the above — GAMG holds comfortably at current scale. (#497, fixed): essential DOFs are absent from the global vector. The tell is the divergence theorem failing on a field diagnostic. - Never inject interface entries into the `ptap`-refreshed rotated operator — - add them to a copy; re-attach the null space on each rebuilt copy. + add them to a copy. Make the copy once and refresh it in place (`MatCopy` and + `MatAXPY` with `SUBSET_NONZERO_PATTERN`): a new Mat at every Newton iterate + leaves the velocity multigrid smoothing with the first iterate's operator, + because PCMG keeps its finest smoother's operator unless it is the PC's own + (#894). The direct-LU path is the exception: its pressure pin (`zeroRows`) + removes the pinned row's entries, so it takes a fresh copy each iterate. - The pairing comes from the clone map only; coordinate matching is impossible-by-construction at zero distance. Protect the property that the two trace spaces are identical with exactly paired DOFs — losing it means diff --git a/src/underworld3/utilities/rotated_bc.py b/src/underworld3/utilities/rotated_bc.py index e9142e82e..d30bb516d 100644 --- a/src/underworld3/utilities/rotated_bc.py +++ b/src/underworld3/utilities/rotated_bc.py @@ -1563,9 +1563,10 @@ def rotated_residual(uvec, keep_cartesian=False): # The copy is made once and refreshed IN PLACE after that, so the KSP # is handed the same Mat with the same nonzero pattern at every # iterate, as on the contact path. A new Mat each iterate left the - # multigrid smoothing with iterate 0's operator: PCSetUp_MG keeps the - # finest smoother's operator unless it is the PC's own, and the - # fieldsplit hands over a new velocity block for a new pattern (#894). + # multigrid smoothing with iterate 0's operator (#894), even with an + # identical pattern: a new Pmat object resets the PC's nonzero state, + # so the fieldsplit builds a new velocity block, and PCSetUp_MG keeps + # the finest smoother's operator unless it is the PC's own. # The tangent's pattern is fixed by the fault facets, and Ahat's by # the ptap, so both stay inside the pattern of the first copy. # The direct-LU path still takes a fresh sum each iterate: its pressure diff --git a/tests/parallel/test_1088_rotated_interface_operator_parallel.py b/tests/parallel/test_1088_rotated_interface_operator_parallel.py index 52d13b3bd..f1b5b79e1 100644 --- a/tests/parallel/test_1088_rotated_interface_operator_parallel.py +++ b/tests/parallel/test_1088_rotated_interface_operator_parallel.py @@ -17,13 +17,18 @@ The frictionless contact refreshes its operator in place, and the fix makes the interface-law branch do the same. +The same holds on the split mesh's own multigrid tail (no ``set_custom_fmg``): +4, 30, 23, 24, 23, 22 on the thin sheet before, 4-5 after. GAMG was never +affected. + The test records, after every linear solve of the rotated loop, the operator the multigrid was handed (the velocity block on the saddle-point path, the whole rotated operator on the thin-sheet path) and the finest smoother's operator, and -checks that they agree at every iterate, then bounds the velocity iterations of -every increment at 5. A viscosity that depends on the velocity gives the loop -several iterates. The frictionless contact is the control: it takes the other -branch of the loop, and agreed before the fix. +checks that they agree at every iterate. Agreement alone cannot see an operator +that is the right object holding iterate 0's values, so the test also bounds the +Newton increments and the velocity iterations of every increment. A viscosity +that depends on the velocity gives the loop several iterates. The frictionless +contact and GAMG are controls: they agreed before the fix. The fixture is test_1090's: a fault split in place over a welded base hierarchy (1/8, 1/16), so the finest level is the split mesh and carries the FAC patch. @@ -53,6 +58,14 @@ def base(): qdegree=2, refinement=1) +@pytest.fixture(scope="module") +def flat_base(): + """The same box at the finest spacing with no refinement hierarchy, so the + split mesh owns no multigrid tail and the velocity block falls back to GAMG.""" + return uw.meshing.UnstructuredSimplexBox( + minCoords=(0, 0), maxCoords=(1, 1), cellSize=1 / 16, regular=False, qdegree=2) + + def _operator_gap(mg): """|finest smoother's operator - the operator ``mg`` was handed|_F, relative.""" handed = mg.getOperators()[1] @@ -64,9 +77,12 @@ def _operator_gap(mg): return value -def _solve_recording(base, path, law, monkeypatch): +def _solve_recording(base, path, law, hierarchy, monkeypatch): """Solve on the split mesh by ``path`` with fault law ``law``; return one - ``(operator gap, velocity iterations)`` record per Newton increment.""" + ``(operator gap, velocity iterations, velocity PC)`` record per Newton + increment. ``hierarchy`` is how the velocity block gets its multigrid: + ``set_custom_fmg`` over the base levels, the split mesh's own tail (none + registered), or GAMG (``base`` has no hierarchy).""" records = [] def recorded(original, saddle): @@ -76,10 +92,10 @@ def wrapper(*args, **kwargs): if saddle: vel_ksp = ctx["pc"].getFieldSplitSubKSP()[0] records.append((_operator_gap(vel_ksp.getPC()), - vel_ksp.getIterationNumber())) + vel_ksp.getIterationNumber(), ctx["velocity_pc"])) else: records.append((_operator_gap(ctx["pc"]), - ctx["ksp"].getIterationNumber())) + ctx["ksp"].getIterationNumber(), ctx["velocity_pc"])) return out return wrapper @@ -88,7 +104,6 @@ def wrapper(*args, **kwargs): monkeypatch.setattr(rotated_bc, "_solve_rotated_vector", recorded(rotated_bc._solve_rotated_vector, False)) - levels = base._coarse_level_meshes()[:-1] + [base] mesh = base.add_fault(("Flt", TRACE)) x, y = mesh.X if path == "stokes": @@ -109,31 +124,51 @@ def wrapper(*args, **kwargs): solver.constitutive_model.Parameters.shear_viscosity_0 = ( 1 + 50 * (u.sym[0] ** 2 + u.sym[1] ** 2)) solver.tolerance = 1e-6 - custom_mg.set_custom_fmg(solver, levels, field_id=0 if path == "stokes" else None) + if hierarchy == "set_custom_fmg": + levels = base._coarse_level_meshes()[:-1] + [base] + custom_mg.set_custom_fmg(solver, levels, field_id=0 if path == "stokes" else None) solver.solve() assert solver._rotated_freeslip_info["converged"], f"{path}: did not converge" return records +# Bounds asserted, from the fixed build on this fixture. Velocity iterations per +# Newton increment, largest measured: 3 with set_custom_fmg, 6 on the mesh's own +# tail, 44 on GAMG. The stale operator of #894 took 20-34 on both multigrid arms. +# GAMG rebuilds its hierarchy from the live operator at every set-up, so it was +# never stale (the same 31-44 before and after) and is a control here, like the +# frictionless contact. Newton increments: 5 (saddle point) and 6 (thin sheet) on +# every arm; an operator holding iterate 0's values takes 49 or stalls. +VELOCITY_ITS_MAX = {"set_custom_fmg": 5, "mesh_tail": 8, "gamg": 60} +INCREMENTS_MAX = 8 + + +@pytest.mark.parametrize("hierarchy", ["set_custom_fmg", "mesh_tail", "gamg"]) @pytest.mark.parametrize("law", [1.0, 0], ids=["viscous_fault", "frictionless"]) @pytest.mark.parametrize("path", ["stokes", "sheet"]) -def test_the_finest_smoother_follows_every_iterate(base, path, law, monkeypatch): - records = _solve_recording(base, path, law, monkeypatch) +def test_the_finest_smoother_follows_every_iterate(base, flat_base, path, law, hierarchy, + monkeypatch): + mesh = flat_base if hierarchy == "gamg" else base + records = _solve_recording(mesh, path, law, hierarchy, monkeypatch) + installed = {pc for _gap, _its, pc in records} + assert installed == {"GAMG" if hierarchy == "gamg" else "custom-FMG"}, installed # one increment would leave nothing to go stale: the test needs the iterates - assert len(records) >= 3, f"{path}: only {len(records)} Newton increments" - gaps = [gap for gap, _its in records] + assert 3 <= len(records) <= INCREMENTS_MAX, ( + f"{path}, law {law}, {hierarchy}: {len(records)} Newton increments") + gaps = [gap for gap, _its, _pc in records] assert max(gaps) < 1e-12, ( - f"{path}, law {law}: the finest smoother's operator differs from the " - f"operator the multigrid was handed, by {gaps} (relative, per increment; #894)") - its = [its for _gap, its in records] - assert max(its) <= 5, ( - f"{path}, law {law}: velocity iterations per increment {its} (2-3 measured; " - f"20-32 with the stale smoother of #894)") - - -def _viscous_fault_slip(base, use_lu): - """Peak slip of the viscous-fault saddle-point solve, by the direct-LU rotated - path or by the multigrid one, solved tight enough to compare.""" + f"{path}, law {law}, {hierarchy}: the finest smoother's operator differs " + f"from the operator the multigrid was handed, by {gaps} (relative, per " + f"increment; #894)") + its = [its for _gap, its, _pc in records] + assert max(its) <= VELOCITY_ITS_MAX[hierarchy], ( + f"{path}, law {law}, {hierarchy}: velocity iterations per increment {its} " + f"(20-34 with the stale operator of #894)") + + +def _viscous_fault_solve(base, use_lu): + """The viscous-fault saddle-point solve by the direct-LU rotated path or by the + multigrid one, solved tight enough to compare: ``(converged, peak slip)``.""" from underworld3.utilities.fault_contact import fault_slip levels = base._coarse_level_meshes()[:-1] + [base] mesh = base.add_fault(("Flt", TRACE)) @@ -155,24 +190,25 @@ def _viscous_fault_slip(base, use_lu): custom_mg.set_custom_fmg(stokes, levels, field_id=0) stokes.solve() info = stokes._rotated_freeslip_info - assert info["converged"], f"use_lu={use_lu}: did not converge" assert info["nonlinear_iterations"] >= 3, info["nonlinear_iterations"] _s, slip, _leak = fault_slip(stokes, "Flt", info) - return uw.mpi.comm.allreduce(float(np.abs(slip).max()) if len(slip) else 0.0, op=max) + peak = uw.mpi.comm.allreduce(float(np.abs(slip).max()) if len(slip) else 0.0, op=max) + return bool(info["converged"]), peak -@pytest.mark.xfail(raises=AssertionError, strict=True, - reason="#899: the direct-LU path does not converge on a fault contact") def test_the_direct_lu_path_takes_an_interface_law(base): """The direct-LU path keeps a fresh operator at every iterate: its pressure pin (``zeroRows``) drops the pinned row's entries, so the in-place refresh of the multigrid paths would not fit it. An in-place refresh there raised PETSc's - "new nonzero caused a malloc" at iterate 1. + "new nonzero caused a malloc" at iterate 1, which fails this test. The path does not converge on a fault contact at all (#899, on development - too), so this is a strict expected failure on the convergence ASSERTION - only: a PETSc error fails it, and so does a fix to #899, which should then - remove the mark.""" - lu = _viscous_fault_slip(base, use_lu=True) - mg = _viscous_fault_slip(base, use_lu=False) + too), so non-convergence alone is an expected failure. A fix to #899 that + converges to a different slip fails the test; one that agrees passes it, and + the xfail line should then go.""" + lu_converged, lu = _viscous_fault_solve(base, use_lu=True) + mg_converged, mg = _viscous_fault_solve(base, use_lu=False) + assert mg_converged + if not lu_converged: + pytest.xfail("#899: the direct-LU rotated path does not converge on a fault contact") assert abs(lu - mg) < 1e-6 * mg, (lu, mg)