From e4cbca9bd89c4731ae37c5a2962cccdf77e77a4a Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:33:41 -0600 Subject: [PATCH 01/17] pro run: read a conditionally assigned pnList as an so file model_kind() called a file an so module only if pnList is assigned directly at module level. The air-water-vv so files choose it with an option (`if tank3D.useOnlyVF: pnList = ... else: pnList = ...`), so pro run took 25 of the 31 *_so.py files in air-water-vv (cekees/air-water-vv proteus-2.0.x-update, including 3d/bathyduck and 45DEG_R1) for TwoPhaseFlow case modules and failed before reading the model (Carpenter, main 266eb974, 576 ranks, 9 s, exit 143; parun on the same deck ran to completion). model_kind now looks through the module-level if/try/with/loop blocks, not into a function or class. Before: 6 of 31 awvv so files read as 'so'. After: 31 of 31. test_pro_cli.py: 9 parametrized cases (if/else, try/except, with, plain, annotated, and function/class/no assignment staying 'case'); 3 fail before the change, all 12 model_kind tests pass after. The rest of the file is unchanged (9 failed / 90 passed after; the 9 fail the same way on cekees/main 80ddeacb). Co-Authored-By: Claude Sonnet 5.5 --- proteus/cli/run.py | 23 +++++++++++++++++++++-- test/test_pro_cli.py | 19 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/proteus/cli/run.py b/proteus/cli/run.py index 425e144d4d..254486ea34 100644 --- a/proteus/cli/run.py +++ b/proteus/cli/run.py @@ -134,15 +134,34 @@ def add_parser(subparsers): return p +def _module_level_statements(body): + """Every statement that runs when the module is imported: the module's own, and those inside its ``if``, + ``try``, ``with`` and loop blocks, but not inside a function or class.""" + for node in body: + yield node + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + continue + for field in ("body", "orelse", "finalbody"): + inner = getattr(node, field, None) + if isinstance(inner, list): + yield from _module_level_statements(inner) + for handler in getattr(node, "handlers", ()): + yield from _module_level_statements(handler.body) + + def model_kind(path): - """'so' if the file assigns ``pnList`` at module level, else 'case'. + """'so' if the file assigns ``pnList`` when it is imported, else 'case'. + + ``pnList`` may be assigned in an ``if``/``else`` or ``try`` at module level, as the air-water-vv so + files do (``if tank3D.useOnlyVF: pnList = ... else: pnList = ...``); an assignment inside a function + or class does not count. Read from the source, so nothing is imported (an import would run the model before the context options are set). """ with open(path) as f: tree = ast.parse(f.read(), path) - for node in tree.body: + for node in _module_level_statements(tree.body): targets = [] if isinstance(node, ast.Assign): targets = node.targets diff --git a/test/test_pro_cli.py b/test/test_pro_cli.py index 02650c4b92..3ad286f7c5 100644 --- a/test/test_pro_cli.py +++ b/test/test_pro_cli.py @@ -83,6 +83,25 @@ def test_model_kind(tmp_path): assert model_kind(str(case)) == "case" +@pytest.mark.parametrize("source, kind", [ + # the air-water-vv shape: pnList chosen by an option, assigned in an if/else + ("import tank3D\nif tank3D.useOnlyVF:\n pnList = [('a_p', 'a_n')]\nelse:\n pnList = [('a_p', 'a_n'), ('b_p', 'b_n')]\n", "so"), + ("try:\n pnList = [('a_p', 'a_n')]\nexcept ImportError:\n pnList = []\n", "so"), + ("import os\nwith open(os.devnull) as f:\n pnList = [('a_p', 'a_n')]\n", "so"), + ("pnList = [('a_p', 'a_n')]\n", "so"), + ("pnList: list = [('a_p', 'a_n')]\n", "so"), + # not an so file: pnList only inside a function or a class, or never + ("def build():\n pnList = [('a_p', 'a_n')]\n return pnList\n", "case"), + ("class C:\n pnList = [('a_p', 'a_n')]\n", "case"), + ("if True:\n def f():\n pnList = 1\n", "case"), + ("myTpFlowProblem = None\n", "case"), +]) +def test_model_kind_sees_a_conditional_pnlist(tmp_path, source, kind): + f = tmp_path / "m.py" + f.write_text(source) + assert model_kind(str(f)) == kind + + def test_petsc_argv(tmp_path): f = tmp_path / "petsc.options" f.write_text(textwrap.dedent("""\ From 37f8e31cd41c82484b1f8a45448cfd181822f1a4 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:33:41 -0600 Subject: [PATCH 02/17] pro msh: set Profiling.procID before opening its log pro msh called Profiling.openLog without setting Profiling.procID, which Comm.init() leaves unset and openLog asserts on ("Initialize Comm and set Profiling.procID before opening log"). pro run sets it at the same point. Every pro msh at the default log level (-l 1) therefore died after about 7 s; the tests all pass -l 0, which skips openLog, so none saw it (found running the air-water-vv bathyduck and 45DEG_R1 decks on Carpenter, main 266eb974). The fix is the one line pro run has. New test: pro msh at the default log level writes _msh.log and the mesh manifest; it fails before the change with the assertion, and passes after. Co-Authored-By: Claude Sonnet 5.5 --- proteus/cli/msh.py | 2 ++ test/test_pro_cli.py | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/proteus/cli/msh.py b/proteus/cli/msh.py index bedeb790f5..d2f4d93da0 100644 --- a/proteus/cli/msh.py +++ b/proteus/cli/msh.py @@ -74,6 +74,8 @@ def run(args): return 2 from proteus import Context, Profiling + # Comm.init() starts PETSc without setting it, and openLog asserts on it (pro run sets it the same way) + Profiling.procID = comm.rank() if args.verbose: Profiling.verbose = True if args.log_level > 0: diff --git a/test/test_pro_cli.py b/test/test_pro_cli.py index 3ad286f7c5..d485a17ccb 100644 --- a/test/test_pro_cli.py +++ b/test/test_pro_cli.py @@ -230,6 +230,18 @@ def test_mesh_files_plan(): assert plan["outputs"] == ["plc.ele", "plc.node", "plc.face"] +@pytest.mark.skipif(shutil.which("tetgen") is None, reason="tetgen not on PATH") +def test_pro_msh_opens_its_log_at_the_default_log_level(tmp_path): + # every other pro msh test passes -l 0, which skips openLog; at the default level it asserted that + # Profiling.procID was unset (found running the air-water-vv decks on Carpenter, 2026-11-21) + work = tmp_path / "pro" + _copy_ci_models(work) + made = pro("msh", *TETGEN_MODEL, cwd=work) + assert made.returncode == 0, made.stderr[-2000:] + assert (work / "poisson_3d_tetgen_p_msh.log").exists() + assert (work / "meshNoVessel.mesh.ymf").exists() + + @pytest.mark.skipif(shutil.which("tetgen") is None, reason="tetgen not on PATH") def test_msh_then_run_without_meshing(tmp_path): work = tmp_path / "pro" From b78910ede6c2f281c6ad59cfc6e719620dd47a39 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:46:39 -0600 Subject: [PATCH 03/17] pro run: check the mesh only after every rank has loaded the model pro run hashes the generator's input (the .poly) on rank 0 right after it loads the model. A model that rewrites that file on every rank at import (air-water-vv 45DEG_R1 calls domain.writePoly("mesh") on each rank) has it truncated and rewritten by the other ranks while rank 0 hashes it, so a current mesh reads as stale. Found on Carpenter (main 266eb974, 3072 ranks): pro msh made the mesh (1165 s, manifest written, `pro st` on one rank: "mesh: current"); the pro run that followed with --no-mesh stopped after 13 s with "the mesh is stale (the generator's inputs or command changed)", and the .poly on disk was byte-identical to the one in the manifest (sha256 795bb3dc...). Without --no-mesh it would have re-meshed 49 M tets on rank 0 of a 16-node allocation. A comm.barrier() before the check, once the early return for models that give their own mesh has passed (every rank takes that branch alike). test_pro_run_checks_the_mesh_after_every_rank_has_loaded_the_model: 2 ranks; rank 1 truncates and rewrites the .poly 3 s after loading. Before: exit 2 with the Carpenter message; after: exit 0. test_pro_cli.py: 9 failed / 91 passed (the same 9 fail on cekees/main 80ddeacb). Co-Authored-By: Claude Sonnet 5.5 --- proteus/cli/run.py | 3 +++ test/test_pro_cli.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/proteus/cli/run.py b/proteus/cli/run.py index 254486ea34..61541d9b3a 100644 --- a/proteus/cli/run.py +++ b/proteus/cli/run.py @@ -335,6 +335,9 @@ def _bring_mesh_up_to_date(args, comm, pList, nList, log): domain, meshOptions, plan = plan_for(pList, nList) if plan is None or not meshOptions.genMesh: return None + # Every rank has loaded the model, so none is still writing the generator's input: a model that rewrites its .poly on + # every rank at import (air-water-vv 45DEG_R1, 3072 ranks) had it hashed mid-rewrite, and a current mesh read as stale. + comm.barrier() error = None if comm.isMaster(): state, reason = mesh.state(plan) diff --git a/test/test_pro_cli.py b/test/test_pro_cli.py index d485a17ccb..11a72f070c 100644 --- a/test/test_pro_cli.py +++ b/test/test_pro_cli.py @@ -1187,6 +1187,31 @@ def pro_on(ranks, *args, cwd): timeout=600, env=env) +@needs_mpiexec +@pytest.mark.skipif(shutil.which("tetgen") is None, reason="tetgen not on PATH") +def test_pro_run_checks_the_mesh_after_every_rank_has_loaded_the_model(tmp_path): + # A model that rewrites its .poly on the ranks other than 0 after loading (air-water-vv 45DEG_R1 writes it on + # every rank): rank 0 hashed the file while it was being rewritten and found a current mesh stale (3072 ranks, + # Carpenter, 2026-11-21: "the generator's inputs or command changed" with --no-mesh). + work = tmp_path / "pro" + _copy_ci_models(work) + made = pro("msh", *TETGEN_MODEL, "-l", "0", cwd=work) + assert made.returncode == 0, made.stderr[-2000:] + p = work / "poisson_3d_tetgen_p.py" + source = p.read_text() + old = " comm.barrier()\ndomain.MeshOptions.genMesh=genMesh" + assert old in source + p.write_text(source.replace(old, " comm.barrier()\n" + " if not comm.isMaster():\n" + " import time\n" + " open(polyfile + '.poly', 'w').close()\n" + " time.sleep(3)\n" + " domain.writePoly(polyfile)\n" + "domain.MeshOptions.genMesh=genMesh")) + ran = pro_on(2, "run", *TETGEN_MODEL, "--no-mesh", "-l", "0", cwd=work) + assert ran.returncode == 0, ran.stderr[-2000:] + + def _outputs(path): from ymf import closure _, outputs, _ = closure.load(str(path), check_state=False) From b7775eb088a408e35088e12989fc272045aae816 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:53:02 -0600 Subject: [PATCH 04/17] C49 R3: first tests of the Galerkin shallow water kernel SW2D (serial and two ranks, plain and SUPG) proteus/kernels/SW2D.py (718 statements) ran only on import: nothing in the tree builds it (the SWE decks use SW2DCV and GN_SW2DCV; test/SWFlow/parab1D.py imports it and never uses it). The helper builds its LevelModel on a 1.0/0.5 depth step on the unit square, three BackwardEuler/Newton steps, with options.try_supg_stabilization 0 and 1; the test checks the bound entry points (calculateResidual/Jacobian vs _supg), finite and bounded depth, that the two variants differ, and that 2 ranks give the serial answer (measured 6e-17 plain, 7e-13 SUPG). SW2D.py uses TC_base, NonlinearEquation, Quadrature, logEvent, cfemIntegrals, memory, Comm, DOFBoundaryConditions and FluxBoundaryConditions without importing them, so it cannot be built as written; the helper puts those names in the module's namespace (kernel not edited, report in the round's handoff). Measured (statement coverage of the new tests alone, against the CI baseline of main 8b864938): kernels/SW2D.py 6.3% (45/718) -> 88.4% (635/718) +590 statements aggregate kernels/ 75.72% (23716/31319) -> 77.6% (24306/31319) Co-Authored-By: Claude Sonnet 5.5 --- test/sw2d_galerkin_mpi.py | 102 +++++++++++++++++++++++++++++++++++++ test/test_sw2d_galerkin.py | 94 ++++++++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 test/sw2d_galerkin_mpi.py create mode 100644 test/test_sw2d_galerkin.py diff --git a/test/sw2d_galerkin_mpi.py b/test/sw2d_galerkin_mpi.py new file mode 100644 index 0000000000..1783742206 --- /dev/null +++ b/test/sw2d_galerkin_mpi.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python +"""SW2D (the Galerkin shallow water kernel, nothing else in the tree builds it) on a small dam break, for test_sw2d_galerkin.py. + +Flat bottom (the coefficients leave the bathymetry at zero), a 1.0 / 0.5 depth step across x = 0.5 of the unit +square, no flow initially, no flow through the walls (u = v = 0 on the whole boundary), BackwardEuler with Newton, +a few fixed steps. SUPG=1 sets ``options.try_supg_stabilization`` (calculateResidual_supg / calculateJacobian_supg), +otherwise the plain Galerkin residual and Jacobian. Run in an empty directory (serially or under mpiexec); rank 0 leaves +sw2d.npz: the depth h, hu, hv (the three dofs of the owned nodes, sorted by x, y), the nodes' x, y, and the names of the residual and Jacobian entry points the model bound. +""" +import os +from proteus import Comm +comm = Comm.init() +import numpy as np +from proteus import (Domain, MeshTools, NumericalSolution, StepControl, TimeIntegration, default_s, defaults) +from proteus.FemTools import C0_AffineLinearOnSimplexWithNodalBasis +from proteus.iproteus import opts +from proteus.kernels import SW2D +from proteus.NonlinearSolvers import Newton +from proteus.NumericalFlux import Advection_DiagonalUpwind_Diffusion_IIPG_exterior +from proteus.LinearAlgebraTools import SparseMatrix +from proteus.LinearSolvers import LU, KSP_petsc4py +from proteus.Quadrature import SimplexGaussQuadrature + +import proteus.Transport +# SW2D.py uses the bare names below and imports none of them (the star import of cSW2D does not provide them), so +# neither its Coefficients nor its LevelModel can be built as written; the other kernels take them from +# proteus.Transport. They are put in the kernel's namespace here; the report is in HANDOFF_2026-11-23_c49-r3-done.md. +# Drop this loop when SW2D.py imports them. +for _name in ("TC_base", "NonlinearEquation", "Quadrature", "logEvent", "cfemIntegrals", "memory", "Comm", + "DOFBoundaryConditions", "FluxBoundaryConditions"): + if _name not in SW2D.__dict__: + setattr(SW2D, _name, getattr(proteus.Transport, _name)) +SUPG = bool(int(os.environ.get("SUPG", "0"))) +NN = int(os.environ.get("NN", "11")) +NSTEPS = int(os.environ.get("NSTEPS", "3")) +DT = float(os.environ.get("DT", "0.005")) + +domain = Domain.RectangularDomain(L=(1.0, 1.0), x=(0.0, 0.0), name="box") +o = domain.MeshOptions +o.nnx = o.nny = o.nn = NN +o.triangleFlag = 0 +o.parallelPartitioningType = MeshTools.MeshParallelPartitioningTypes.node +o.nLayersOfOverlapForParallel = 1 + + +class Init(object): + def __init__(self, ci): + self.ci = ci + + def uOfXT(self, x, t): + return (1.0 if x[0] < 0.5 else 0.5) if self.ci == 0 else 0.0 + + +p = defaults.Physics_base(nd=2, name="sw2d") +p.domain = domain +p.LevelModelType = SW2D.LevelModel +p.coefficients = SW2D.Coefficients(g=9.81, nu=1.0e-3, nd=2) +p.initialConditions = {0: Init(0), 1: Init(1), 2: Init(2)} +p.dirichletConditions = {0: lambda x, flag: None, 1: lambda x, flag: lambda x, t: 0.0, 2: lambda x, flag: lambda x, t: 0.0} +p.advectiveFluxBoundaryConditions = {} +p.diffusiveFluxBoundaryConditions = {0: {}, 1: {}, 2: {}} +p.fluxBoundaryConditions = {0: 'outFlow', 1: 'outFlow', 2: 'outFlow'} +n = defaults.Numerics_base() +n.timeIntegration = TimeIntegration.BackwardEuler +n.stepController = StepControl.FixedStep +n.DT = DT +n.femSpaces = {0: C0_AffineLinearOnSimplexWithNodalBasis, 1: C0_AffineLinearOnSimplexWithNodalBasis, + 2: C0_AffineLinearOnSimplexWithNodalBasis} +n.elementQuadrature = SimplexGaussQuadrature(2, 3) +n.elementBoundaryQuadrature = SimplexGaussQuadrature(1, 3) +n.multilevelNonlinearSolver = n.levelNonlinearSolver = Newton +n.fullNewtonFlag = True +n.numericalFluxType = SW2D.NumericalFlux +n.matrix = SparseMatrix +n.multilevelLinearSolver = n.levelLinearSolver = LU if comm.size() == 1 else KSP_petsc4py +n.linear_solver_options_prefix = 'sw2d_' +n.linearSolverConvergenceTest = 'r-true' +n.tolFac = 0.0 +n.nl_atol_res = 1e-10 +n.l_atol_res = 1e-12 +n.maxNonlinearIts = 30 +n.try_supg_stabilization = SUPG +n.subgridError = SW2D.SubgridError(p.coefficients, 2) +n.shockCapturing = SW2D.ShockCapturing(p.coefficients, 2, shockCapturingFactor=0.25, lag=False) +n.parallelPartitioningType = o.parallelPartitioningType +n.nLayersOfOverlapForParallel = o.nLayersOfOverlapForParallel +so = defaults.System_base(name="sw2d", pnList=[(p, n)], sList=[default_s]) +so.tnList = [0.0] + [DT * (i + 1) for i in range(NSTEPS)] +ns = NumericalSolution.NS_base(so, [p], [n], so.sList, opts) +m = ns.modelList[0].levelModelList[-1] +nOwned = m.mesh.nNodes_owned + + +ns.calculateSolution("sw2d") +cols = [m.mesh.nodeArray[:nOwned, :2]] + [m.u[i].dof[:nOwned, None] for i in range(3)] +mpi = comm.comm.tompi4py() +gathered = mpi.gather(np.hstack(cols), root=0) +if mpi.rank == 0: + a = np.vstack(gathered) + a = a[np.lexsort((a[:, 1], a[:, 0]))] + np.savez("sw2d.npz", x=a[:, 0], y=a[:, 1], h=a[:, 2], hu=a[:, 3], hv=a[:, 4], residual=m.calculateResidual.__name__, + jacobian=m.calculateJacobian.__name__, residual_calls=m.nonlinear_function_evaluations) diff --git a/test/test_sw2d_galerkin.py b/test/test_sw2d_galerkin.py new file mode 100644 index 0000000000..59c6cd8e3d --- /dev/null +++ b/test/test_sw2d_galerkin.py @@ -0,0 +1,94 @@ +"""SW2D, the Galerkin shallow water kernel, builds a model, steps it, and gives the serial answer on two ranks. + +Nothing else in the tree builds ``proteus.kernels.SW2D`` (the shallow water decks use SW2DCV and GN_SW2DCV), so before +this file its 718 statements ran only on import. ``try_supg_stabilization`` on the numerics options selects the SUPG +residual and Jacobian (``calculateResidual_supg``, ``calculateJacobian_supg``) over the plain Galerkin ones. The helper +(sw2d_galerkin_mpi.py) runs a 1.0 / 0.5 depth step on the unit square for three fixed steps with the flat bottom the +coefficients give (no bathymetry), u = v = 0 on the walls, and the tests check: + +- the entry points the model bound are the ones the option names (a mutation that swaps them fails here); +- the answer is finite, the depth stays inside its initial range for the plain scheme (it overshoots by < 2% with SUPG) + and the two variants differ, so the SUPG branch ran; +- two ranks give the serial answer (to 1e-9; measured 6e-13 SUPG, 6e-17 plain). + +The module as it stands cannot be built: it uses ``TC_base``, ``NonlinearEquation``, ``Quadrature``, ``logEvent``, +``cfemIntegrals``, ``memory``, ``Comm``, ``DOFBoundaryConditions`` and ``FluxBoundaryConditions`` without importing +them. The helper puts them in the module's namespace (the other kernels import them from proteus.Transport); the +report for the kernel's owner is in HANDOFF_2026-11-23_c49-r3-done.md. +""" +import importlib.util +import os +import shutil +import sys + +import numpy +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("launch_output", os.path.join(HERE, "launch_output.py")) +launch_output = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(launch_output) +HELPER = os.path.join(HERE, "sw2d_galerkin_mpi.py") + + +def _mpiexec(): + bindir = os.path.dirname(sys.executable) + for name in ("mpiexec", "mpirun"): + candidate = os.path.join(bindir, name) + if os.path.exists(candidate): + return candidate + return shutil.which("mpiexec") or shutil.which("mpirun") + + +MPIEXEC = _mpiexec() + + +def _run(ranks, cwd, **overrides): + env = dict(os.environ, OMP_NUM_THREADS="1") + env.setdefault("FI_PROVIDER", "tcp") + env.setdefault("OMPI_MCA_rmaps_base_oversubscribe", "1") + env.setdefault("PRTE_MCA_rmaps_default_mapping_policy", ":oversubscribe") + env["PETSC_OPTIONS"] = (env.get("PETSC_OPTIONS", "") + " -mat_partitioning_type current").strip() + env["PYTHONPATH"] = os.pathsep.join([p for p in sys.path if p] + [HERE, env.get("PYTHONPATH", "")]).strip(os.pathsep) + env.update({k: str(v) for k, v in overrides.items()}) + argv = [sys.executable, HELPER, "-l1"] if ranks == 1 else [MPIEXEC, "-n", str(ranks), sys.executable, HELPER, "-l1"] + launch_output.run(argv, cwd=cwd, env=env, timeout=900) + return numpy.load(os.path.join(str(cwd), "sw2d.npz")) + + +@pytest.fixture(scope="module") +def serial(tmp_path_factory): + out = {} + for supg in (0, 1): + d = tmp_path_factory.mktemp("serial%d" % supg) + r = _run(1, d, SUPG=supg) + out[supg] = {k: r[k] for k in r.files} + return out + + +def test_the_option_selects_the_supg_entry_points(serial): + assert str(serial[0]["residual"]) == "calculateResidual" and str(serial[0]["jacobian"]) == "calculateJacobian" + assert str(serial[1]["residual"]) == "calculateResidual_supg" and str(serial[1]["jacobian"]) == "calculateJacobian_supg" + assert serial[0]["residual_calls"] > 0 and serial[1]["residual_calls"] > 0 + + +def test_both_variants_step_and_differ(serial): + plain, supg = serial[0], serial[1] + assert plain["h"].size == 121 + for r in (plain, supg): + for k in ("h", "hu", "hv"): + assert numpy.isfinite(r[k]).all(), k + assert plain["h"].min() >= 0.5 - 1e-12 and plain["h"].max() <= 1.0 + 1e-12 + assert 0.48 < supg["h"].min() and supg["h"].max() < 1.02 + assert numpy.abs(plain["h"] - supg["h"]).max() > 1e-4, "the SUPG variant gave the plain answer" + + +@pytest.mark.skipif(MPIEXEC is None, reason="mpiexec not available") +@pytest.mark.parametrize("supg", [0, 1]) +def test_two_ranks_give_the_serial_answer(serial, tmp_path, supg): + two = _run(2, tmp_path, SUPG=supg) + one = serial[supg] + assert numpy.array_equal(one["x"], two["x"]) and numpy.array_equal(one["y"], two["y"]) + for k in ("h", "hu", "hv"): + err = numpy.abs(one[k] - two[k]).max() + assert err < 1e-9, (k, "two ranks differ from serial by %.3e" % err) From 5fdb67f515bcb2d2afa1b3b2c988a0e67cdf01f5 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:55:09 -0600 Subject: [PATCH 05/17] C49 R3: the four MCorr correction solvers of the vortex2D deck (correctionType dg, dgp0, global, none) ls_consrv_vortex_2d_n.py maps correctionType to MCorr.ElementNewton, ElementConstantNewton, GlobalConstantNewton and DummyNewton; no test ran any of them. In-process test (two steps of the deck each, as test_mcorr_bisection.py). 'none' runs and zeroes the correction. The other three raise "RuntimeError: key r_l2g not found" inside the C++ call: MCorr.elementSolve, elementConstantSolve and globalConstantRJ do not put r_l2g in the arguments (residual and Jacobian do, MCorr.py:703 and :854). They are strict xfails that run the Python up to the call; the kernel is not edited (report in the round's handoff). Measured (new tests alone against the CI baseline of main 8b864938): kernels/MCorr.py 66.1% (783/1184) -> 85.7% (1015/1184) +232 statements Co-Authored-By: Claude Sonnet 5.5 --- .../vortex2D/test_mcorr_correction_types.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 test/levelset/vortex2D/test_mcorr_correction_types.py diff --git a/test/levelset/vortex2D/test_mcorr_correction_types.py b/test/levelset/vortex2D/test_mcorr_correction_types.py new file mode 100644 index 0000000000..8bd240d1e9 --- /dev/null +++ b/test/levelset/vortex2D/test_mcorr_correction_types.py @@ -0,0 +1,75 @@ +"""MCorr correctionType 'dg', 'dgp0', 'global' and 'none' of the vortex2D deck: the four level solvers that were never run. + +ls_consrv_vortex_2d_n.py picks the level solver of the mass corrector from ``correctionType``: ``MCorr.ElementNewton`` +('dg': an element-by-element solve), ``ElementConstantNewton`` ('dgp0': one constant per element), ``GlobalConstantNewton`` +('global': one constant for the domain) and ``DummyNewton`` ('none': no correction). 'cg' (Newton) and 'bisect' +(test_mcorr_bisection.py) are the other two. Run in-process (as test_mcorr_bisection.py) so the corrector's Python is measured by the +coverage job; two steps of the deck each. + +Only 'none' runs. MCorr.elementSolve, elementConstantSolve and globalConstantRJ (so 'dg', 'dgp0' and 'global') do not put +``r_l2g`` in the arguments of the C++ call (residual and Jacobian do, MCorr.py:703 and :854), which the C++ side reads: all three raise +"RuntimeError: key r_l2g not found". The tests are strict xfails: they run the Python up to the call, and when the kernel is fixed +they pass and the marks have to go. The report for the kernel's owner is in HANDOFF_2026-11-23_c49-r3-done.md. +""" +from importlib import reload + +import numpy as np +import pytest + +from proteus import NumericalSolution +from . import (vortex2D, ls_vortex_2d_p, redist_vortex_2d_p, vof_vortex_2d_p, ls_consrv_vortex_2d_p, ls_vortex_2d_n, + redist_vortex_2d_n, vof_vortex_2d_n, ls_consrv_vortex_2d_n, ls_vortex_2d_so) + + +def _decks(correction): + reload(vortex2D) + vortex2D.correctionType = correction + reload(ls_consrv_vortex_2d_p) + reload(ls_consrv_vortex_2d_n) + + +@pytest.fixture +def correction_decks(request): + _decks(request.param) + yield request.param + _decks("cg") # the other vortex2D tests import these modules: put the defaults back + + +def _run_two_steps(opts, name): + from proteus import default_s + reload(default_s) + so = ls_vortex_2d_so + tnList, soname = so.tnList, so.name + so.tnList = tnList[:3] + try: + ns = NumericalSolution.NS_base(so, [ls_vortex_2d_p, redist_vortex_2d_p, vof_vortex_2d_p, ls_consrv_vortex_2d_p], + [ls_vortex_2d_n, redist_vortex_2d_n, vof_vortex_2d_n, ls_consrv_vortex_2d_n], + [default_s] * len(so.pnList), opts) + ns.calculateSolution(soname + "_" + name) + finally: + so.tnList = tnList + return ns + + +_R_L2G = pytest.mark.xfail(strict=True, raises=RuntimeError, reason="MCorr does not pass r_l2g to elementSolve, elementConstantSolve, globalConstantRJ") + + +@pytest.mark.parametrize("correction_decks, solver", [pytest.param("dg", "ElementNewton", marks=_R_L2G), + pytest.param("dgp0", "ElementConstantNewton", marks=_R_L2G), + pytest.param("global", "GlobalConstantNewton", marks=_R_L2G), + ("none", "DummyNewton")], + indirect=["correction_decks"]) +def test_the_level_solver_the_deck_names_runs(opts, tmp_path, monkeypatch, correction_decks, solver): + from proteus.kernels import MCorr + monkeypatch.chdir(tmp_path) + ns = _run_two_steps(opts, correction_decks) + m = [m for m in ns.modelList if type(m.levelModelList[-1]).__module__.endswith("MCorr")][0] + mc = m.levelModelList[-1] + assert type(m.solver.solverList[-1]) is getattr(MCorr, solver) + u = mc.u[0].dof + assert np.isfinite(u).all() + assert np.isfinite(mc.coefficients.massConservationError) + if correction_decks == "none": + assert np.all(mc.q[('u', 0)] == 0.0) and np.all(mc.q[('r', 0)] == 0.0) + if correction_decks == "global": + assert np.all(u == u[0]), "the global correction is one constant for every dof" From 988aacb0703efe718c24b96a3f55c09beebae7ce Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:01:56 -0600 Subject: [PATCH 06/17] C49 R3: the MCorr3P level solvers other than Newton (rising bubble, serial) MCorr3P carries ElementNewton, ElementConstantNewton, GlobalConstantNewton and DummyNewton and no deck selected any. mcorr3p_correction_mpi.py runs the 2D rising-bubble deck (RANS3PF, VOF3P, NCLS3P, RDLS, MCorr3P) to t = 0.004 with MCorr3P on the named solver (multilevel solver NLNI). Tests: 'none', 'dg', 'dgp0' run with the named class and finite dofs, 'none' leaves the level set at 0, Newton conserves the VOF mass to 3e-17. Two kernel findings are pinned, not fixed (kernel not edited; report in the round's handoff): - 'global' fails in MCorr3P.globalConstantRJ, line 977: R = np.array(dtype=float) raises TypeError; - 'dg' and 'dgp0' end with the mass error of 'none' (0.0155 vs 3e-17 for Newton) and one value in every dof: they apply no correction. The tests expect that and fail when it changes. Measured (new tests alone against the CI baseline of main 8b864938): kernels/MCorr3P.py 50.9% (485/952) -> 71.4% (678/952) +193 statements Co-Authored-By: Claude Sonnet 5.5 --- test/mcorr3p_correction_mpi.py | 57 +++++++++++++++++++++++++ test/test_mcorr3p_correction.py | 75 +++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 test/mcorr3p_correction_mpi.py create mode 100644 test/test_mcorr3p_correction.py diff --git a/test/mcorr3p_correction_mpi.py b/test/mcorr3p_correction_mpi.py new file mode 100644 index 0000000000..48794b2b99 --- /dev/null +++ b/test/mcorr3p_correction_mpi.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +"""twophaseflow_partition_mpi.py on the 2D rising bubble (RANS3PF, VOF3P, NCLS3P, RDLS, MCorr3P) with the level solver of MCorr3P named by CORRECTION, for test_mcorr3p_correction.py. + +CORRECTION = newton (the deck's own), dg (MCorr3P.ElementNewton), dgp0 (ElementConstantNewton), global (GlobalConstantNewton) +or none (DummyNewton), the same names as the ``correctionType`` of the vortex2D deck. After the run rank 0 writes mcorr3p.json: the solver class the model +used, the model's mass conservation error and the number of distinct values of its dofs. +""" +import json +import os +import runpy +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +os.environ.update(DIR="surface_tension/rising_bubble_rans3p", SO="risingBubble_so.py", + OPTS="nd=2 USE_SUPG_NS=1 ARTIFICIAL_VISCOSITY_NS=1", DIRECT="1", ATOL="1e-10", MAXITS="200", + FT=os.environ.get("FT", "0.004")) +sys.path.insert(0, HERE) +import numpy as np +from proteus import NumericalSolution as NS +from proteus import Comm +from proteus.kernels import MCorr3P +from proteus.NonlinearSolvers import NLNI + +CLASSES = {"dg": MCorr3P.ElementNewton, "dgp0": MCorr3P.ElementConstantNewton, "global": MCorr3P.GlobalConstantNewton, + "none": MCorr3P.DummyNewton} +CORRECTION = os.environ.get("CORRECTION", "newton") +_init = NS.NS_base.__init__ + + +def init(self, so, pList, nList, *args, **kwargs): + if CORRECTION in CLASSES: + for p, n in zip(pList, nList): + if getattr(p.LevelModelType, "__module__", "").endswith("MCorr3P"): + n.multilevelNonlinearSolver = NLNI + n.levelNonlinearSolver = CLASSES[CORRECTION] + return _init(self, so, pList, nList, *args, **kwargs) + + +NS.NS_base.__init__ = init +_calc = NS.NS_base.calculateSolution + + +def calc(self, *a, **k): + r = _calc(self, *a, **k) + m = [m for m in self.modelList if type(m.levelModelList[-1]).__module__.endswith("MCorr3P")][0] + mc = m.levelModelList[-1] + if Comm.get().rank() == 0: + with open("mcorr3p.json", "w") as f: + json.dump(dict(solver=type(m.solver.solverList[-1]).__name__, + mass_error=float(mc.coefficients.massConservationError), + finite=bool(np.isfinite(mc.u[0].dof).all()), + distinct=int(len(np.unique(mc.u[0].dof[:mc.mesh.nNodes_owned])))), f) + return r + + +NS.NS_base.calculateSolution = calc +runpy.run_path(os.path.join(HERE, "twophaseflow_partition_mpi.py"), run_name="__main__") diff --git a/test/test_mcorr3p_correction.py b/test/test_mcorr3p_correction.py new file mode 100644 index 0000000000..c66bffbf84 --- /dev/null +++ b/test/test_mcorr3p_correction.py @@ -0,0 +1,75 @@ +"""The MCorr3P level solvers other than Newton (ElementNewton, ElementConstantNewton, GlobalConstantNewton, DummyNewton) on the 2D rising bubble. + +MCorr.py has a deck switch for them (``correctionType`` of the vortex2D deck, test/levelset/vortex2D/test_mcorr_correction_types.py); +MCorr3P.py carries the same four classes and no deck selected any. mcorr3p_correction_mpi.py runs the rising-bubble deck +(RANS3PF, VOF3P, NCLS3P, RDLS, MCorr3P; t = 0.004) with MCorr3P on the solver named by CORRECTION. What is checked: + +- 'none', 'dg' and 'dgp0' run: the model used the named class, its dofs are finite; +- 'none' leaves the level set uncorrected (every dof 0); +- Newton (the deck's own) conserves the VOF mass to roundoff (3e-17), as the reference the others are read against. + +Two findings, pinned here so that a fix is noticed (report for the kernel's owner in HANDOFF_2026-11-23_c49-r3-done.md): + +- 'global' fails in MCorr3P.globalConstantRJ with ``R = np.array(dtype=float)`` (TypeError: array() missing required + argument 'object'), line 977: the test expects that error and fails when it is fixed; +- 'dg' and 'dgp0' end with the mass error of 'none' (0.0155 against 3e-17 for Newton) and one value in every dof, i.e. + they apply no correction; the test records that (``test_dg_and_dgp0_apply_no_correction``) and fails when they do. +""" +import importlib.util +import json +import os +import shutil +import sys + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("launch_output", os.path.join(HERE, "launch_output.py")) +launch_output = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(launch_output) +HELPER = os.path.join(HERE, "mcorr3p_correction_mpi.py") + + +def _run(cwd, correction): + env = dict(os.environ, OMP_NUM_THREADS="1", CORRECTION=correction) + env.setdefault("FI_PROVIDER", "tcp") + env["PYTHONPATH"] = os.pathsep.join([p for p in sys.path if p] + [HERE, env.get("PYTHONPATH", "")]).strip(os.pathsep) + launch_output.run([sys.executable, HELPER], cwd=cwd, env=env, timeout=900) + return json.load(open(os.path.join(str(cwd), "mcorr3p.json"))) + + +@pytest.fixture(scope="module") +def runs(tmp_path_factory): + out = {} + for correction in ("newton", "none", "dg", "dgp0"): + d = tmp_path_factory.mktemp(correction) + out[correction] = _run(d, correction) + return out + + +def test_newton_conserves_the_mass(runs): + assert runs["newton"]["solver"] == "Newton" + assert runs["newton"]["mass_error"] < 1e-12 + + +@pytest.mark.parametrize("correction, solver", [("none", "DummyNewton"), ("dg", "ElementNewton"), ("dgp0", "ElementConstantNewton")]) +def test_the_named_level_solver_runs(runs, correction, solver): + assert runs[correction]["solver"] == solver + assert runs[correction]["finite"] + + +def test_none_leaves_the_level_set_uncorrected(runs): + assert runs["none"]["distinct"] == 1 + + +def test_dg_and_dgp0_apply_no_correction(runs): + # when this fails, ElementNewton / ElementConstantNewton correct the mass: replace it with a conservation test + for correction in ("dg", "dgp0"): + assert runs[correction]["distinct"] == 1 + assert runs[correction]["mass_error"] == pytest.approx(runs["none"]["mass_error"], rel=1e-6) + + +def test_global_correction_fails_in_globalconstantrj(tmp_path): + # when this fails, MCorr3P.globalConstantRJ works: replace it with a test that the shift conserves the mass + with pytest.raises(AssertionError, match=r"array\(\) missing required argument 'object'"): + _run(tmp_path, "global") From b0a88af08dac954ba2bf6ae81687ed2e37a28b4e Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:03:20 -0600 Subject: [PATCH 07/17] C49 R3: RDLS.PsiTC, the pseudo-transient controller of the redistancing model (vortex2D deck) redist_vortex_2d_n.py takes the Newton branch unless the deck sets redist_Newton False; no test did, so RDLS.PsiTC (updateSubstep, stepExact_model, initialize_dt_model, choose_dt_model) never ran. In-process, two steps of the vortex2D level set transport with redistancing by pseudo-time continuation: the controller is PsiTC, its updateSubstep and choose_dt_model are called at least twice (counted), the redistanced field is finite, within 0.1 he of the level set and of its sign away from the interface. Measured (new test alone against the CI baseline of main 8b864938): kernels/RDLS.py 67.4% (634/941) -> 74.7% (703/941) +69 statements Co-Authored-By: Claude Sonnet 5.5 --- test/levelset/vortex2D/test_redist_psitc.py | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 test/levelset/vortex2D/test_redist_psitc.py diff --git a/test/levelset/vortex2D/test_redist_psitc.py b/test/levelset/vortex2D/test_redist_psitc.py new file mode 100644 index 0000000000..960bdbd169 --- /dev/null +++ b/test/levelset/vortex2D/test_redist_psitc.py @@ -0,0 +1,62 @@ +"""RDLS.PsiTC, the pseudo-transient step controller of the redistancing model, on the vortex2D deck. + +redist_vortex_2d_n.py takes the Newton branch (``redist_Newton`` True, the default) unless the deck sets it False; no test did, so the controller +(``RDLS.PsiTC``: updateSubstep, stepExact_model, initialize_dt_model, choose_dt_model) never ran. Run in-process (as test_mcorr_bisection.py), two steps of the +level set transport, redistancing by pseudo-time continuation each. Checked: the model's controller is PsiTC, it substepped (updateSubstep and choose_dt_model called at least once per step), the redistanced field is finite, and has the sign of the level set it came from, up to the corrector's shift of it (< 0.1 he). +""" +from importlib import reload + +import numpy as np +import pytest + +from proteus import NumericalSolution +from . import (vortex2D, ls_vortex_2d_p, redist_vortex_2d_p, vof_vortex_2d_p, ls_consrv_vortex_2d_p, ls_vortex_2d_n, + redist_vortex_2d_n, vof_vortex_2d_n, ls_consrv_vortex_2d_n, ls_vortex_2d_so) + + +def _decks(newton): + reload(vortex2D) + vortex2D.redist_Newton = newton + reload(redist_vortex_2d_n) + + +@pytest.fixture +def psitc_decks(): + _decks(False) + yield + _decks(True) # the other vortex2D tests import these modules: put the defaults back + + +def test_the_pseudo_transient_controller_redistances_the_level_set(opts, tmp_path, monkeypatch, psitc_decks): + from proteus import default_s + from proteus.kernels import RDLS + monkeypatch.chdir(tmp_path) + calls = {"updateSubstep": 0, "choose_dt_model": 0} + for name in calls: + def counted(self, _f=getattr(RDLS.PsiTC, name), _n=name): + calls[_n] += 1 + return _f(self) + monkeypatch.setattr(RDLS.PsiTC, name, counted) + reload(default_s) + so = ls_vortex_2d_so + tnList = so.tnList + so.tnList = tnList[:3] + try: + ns = NumericalSolution.NS_base(so, [ls_vortex_2d_p, redist_vortex_2d_p, vof_vortex_2d_p, ls_consrv_vortex_2d_p], + [ls_vortex_2d_n, redist_vortex_2d_n, vof_vortex_2d_n, ls_consrv_vortex_2d_n], + [default_s] * len(so.pnList), opts) + ns.calculateSolution(so.name + "_psitc") + finally: + so.tnList = tnList + rd = [m for m in ns.modelList if type(m.levelModelList[-1]).__module__.endswith("RDLS")][0] + ls = [m for m in ns.modelList if type(m.levelModelList[-1]).__module__.endswith("NCLS")][0] + assert type(rd.stepController) is RDLS.PsiTC + assert calls["updateSubstep"] >= 2 and calls["choose_dt_model"] >= 2 + d = rd.levelModelList[-1].u[0].dof + phi = ls.levelModelList[-1].u[0].dof + assert np.isfinite(d).all() + he = float(vortex2D.he) + flipped = np.sign(d) != np.sign(phi) + # the mass corrector shifts the level set by a constant after the redistancing: only nodes within that shift of the interface may differ in sign + assert np.abs(phi[flipped]).max(initial=0.0) < 0.1 * he, "redistancing changed the sign of the level set away from the interface" + assert np.abs(d - phi).max() < 0.1 * he From 20e7394235683d8ce6f743243832c27c9e1ed78f Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:05:13 -0600 Subject: [PATCH 08/17] C49 R3: unit tests of the lines of the three gwvd step classes the 2dbox deck does not reach NonConservativeBackwardEuler.calculateGeneralizedInterpolationCoefficients (skipped unless integrateInterpolationPoints; m_t = dm (u - u_last)/dt, dm_t = dm/dt, dm_t_sge), Fixed_dt_controller_systemit.choose_dt_model (the first step stays dt_model_last) and stepExact_model, ISO_fixed_MinModelStep.setFromOptions (atol_iso, velocity_Postprocess) and SysNorm (the signed maximum, kept from the 2012 code). Bare instances made with object.__new__. Measured (new tests alone against the CI baseline of main 8b864938; these classes are measured individually, not in the kernels aggregate): TimeIntegration.py::NonConservativeBackwardEuler 65.1% (28/43) -> 100% (43/43) StepControl.py::Fixed_dt_controller_systemit 92.0% (23/25) -> 100% (25/25) SplitOperator.py::ISO_fixed_MinModelStep 97.1% (34/35) -> 100% (35/35) Co-Authored-By: Claude Sonnet 5.5 --- test/gwvd/test_gwvd_classes.py | 106 +++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 test/gwvd/test_gwvd_classes.py diff --git a/test/gwvd/test_gwvd_classes.py b/test/gwvd/test_gwvd_classes.py new file mode 100644 index 0000000000..762dd56208 --- /dev/null +++ b/test/gwvd/test_gwvd_classes.py @@ -0,0 +1,106 @@ +"""The three gwvd step classes beyond what the 2dbox deck reaches, as unit tests on bare instances. + +``test_gwvd_2dbox.py`` runs the deck that uses ``TimeIntegration.NonConservativeBackwardEuler``, +``StepControl.Fixed_dt_controller_systemit`` and ``SplitOperator.ISO_fixed_MinModelStep``; it leaves a few lines of each +unrun, the ones that depend on options or state the deck does not set. The instances here are made with ``object.__new__`` +(the constructors need a whole model) and given the attributes the method under test reads: + +- ``ISO_fixed_MinModelStep.setFromOptions`` reads ``atol_iso`` and ``velocity_Postprocess`` from the options object when it has them and + resets ``velocity_Postprocess`` otherwise; ``SysNorm`` is the signed maximum of the residuals (the 2012 code's choice, kept for fidelity), + so a large negative residual does not block convergence; +- ``Fixed_dt_controller_systemit.choose_dt_model`` sets the model step to ``DT`` (and keeps the first one as ``dt_model_last``), + ``stepExact_model`` leaves the step alone; +- ``NonConservativeBackwardEuler.calculateGeneralizedInterpolationCoefficients`` does nothing without ``integrateInterpolationPoints``, and + with it gives m_t = dm (u - u_last) / dt and dm_t = dm / dt at the interpolation points. +""" +import numpy +import pytest + +from proteus.SplitOperator import ISO_fixed_MinModelStep +from proteus.StepControl import Fixed_dt_controller_systemit +from proteus.TimeIntegration import NonConservativeBackwardEuler + + +class _Options(object): + pass + + +def _iso(): + iso = object.__new__(ISO_fixed_MinModelStep) + iso.atol_iso, iso.velocity_Postprocess = 1.0e-8, True + return iso + + +def test_iso_reads_its_options(): + iso = _iso() + options = _Options() + iso.setFromOptions(options) + assert iso.atol_iso == 1.0e-8 and iso.velocity_Postprocess is False + options.atol_iso, options.velocity_Postprocess = 3.0e-5, True + iso.setFromOptions(options) + assert iso.atol_iso == 3.0e-5 and iso.velocity_Postprocess is True + + +def test_iso_norm_is_the_signed_maximum(opts): + # opts starts Proteus (the MPI communicator globalMax reduces over) + iso = _iso() + assert iso.SysNorm([numpy.array([-5.0, -3.0]), numpy.array([1.0e-9, -2.0])]) == 1.0e-9 + assert iso.SysNorm([numpy.array([2.0, -3.0])]) == 2.0 + + +def test_fixed_dt_controller_sets_the_model_step(): + log = [] + c = object.__new__(Fixed_dt_controller_systemit) + c.dt, c.dt_model_last, c.t_model = 0.25, None, 3.5 + c.saveSolution = lambda: log.append("save") + c.set_dt_allLevels = lambda: log.append("set_dt") + c.setSubsteps = lambda substeps: log.append(("substeps", list(substeps))) + c.choose_dt_model() + assert c.dt_model == 0.25 and c.dt_model_last == 0.25 and c.solverFailures == 0 and c.errorFailures == 0 + assert log == ["save", "set_dt", ("substeps", [3.5])] + c.dt = 0.5 + c.choose_dt_model() + assert c.dt_model == 0.5 and c.dt_model_last == 0.25, "the first step stays dt_model_last" + c.stepExact_model(10.0) + assert c.dt_model == 0.5 + + +def _backward_euler(integrate): + t = object.__new__(NonConservativeBackwardEuler) + t.integrateInterpolationPoints, t.dt, t.nc = integrate, 0.5, 2 + t.m_ip_last = {0: numpy.array([[1.0, 2.0]]), 1: numpy.array([[0.5, 0.5]])} + t.m_ip_tmp = {0: numpy.zeros((1, 2)), 1: numpy.zeros((1, 2))} + return t + + +def _cip(): + cip = {} + for ci in range(2): + cip[('u', ci)] = numpy.array([[3.0 + ci, 4.0 + ci]]) + cip[('mt', ci)] = numpy.zeros((1, 2)) + for cj in range(2): + cip[('dm', ci, cj)] = numpy.full((1, 2), 2.0 + ci + 10 * cj) + cip[('dmt', 0, 0)] = numpy.zeros((1, 2)) + cip[('dmt', 1, 0)] = numpy.zeros((1, 2)) + cip[('dm_sge', 0, 1)] = numpy.full((1, 2), 6.0) + cip[('dmt_sge', 0, 1)] = numpy.zeros((1, 2)) + return cip + + +def test_interpolation_point_coefficients_are_skipped_unless_asked_for(): + t, cip = _backward_euler(False), _cip() + before = {k: v.copy() for k, v in cip.items()} + t.calculateGeneralizedInterpolationCoefficients(cip) + assert all(numpy.array_equal(cip[k], before[k]) for k in cip) + assert all(not v.any() for v in t.m_ip_tmp.values()) + + +def test_interpolation_point_coefficients_are_the_non_conservative_time_derivative(): + t, cip = _backward_euler(True), _cip() + t.calculateGeneralizedInterpolationCoefficients(cip) + # m_t = dm (u - u_last) / dt with the diagonal dm + assert numpy.allclose(cip[('mt', 0)], 2.0 * (numpy.array([[3.0, 4.0]]) - numpy.array([[1.0, 2.0]])) / 0.5) + assert numpy.allclose(cip[('mt', 1)], 13.0 * (numpy.array([[4.0, 5.0]]) - numpy.array([[0.5, 0.5]])) / 0.5) + assert numpy.allclose(cip[('dmt', 0, 0)], 2.0 / 0.5) and numpy.allclose(cip[('dmt', 1, 0)], 3.0 / 0.5) + assert numpy.allclose(cip[('dmt_sge', 0, 1)], 6.0 / 0.5) + assert numpy.array_equal(t.m_ip_tmp[0], cip[('u', 0)]) and numpy.array_equal(t.m_ip_tmp[1], cip[('u', 1)]) From 988b97edde2d98654ec03e6ab970309f2011c88c Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:08:25 -0600 Subject: [PATCH 09/17] C49 R3: SW2DCV switches no deck sets (low order only, star states, wall Riemann, nodal h bounds, bounds relaxation, linear friction, tailwater, walls function, drag law) circular_damBreak (SWEs, lumped mass matrix, unstructured he 0.6, t 0.3) with one switch on, serially and on 2 ranks (partition pinned to a slanted cut). Per variant: finite, depth >= 0, water volume (sum ML h) conserved to 1e-11 on a closed domain, and falling when a tailwater edge sits below the still depth; LOW_ORDER_ONLY, no bounds relaxation, linear friction, tailwater and the drag law change the answer by > 1e-8; 2 ranks give the serial answer to 1e-9. NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS and the walls function give the default's answer to the last bit on this case (the dam does not reach a wall and the states stay smooth): for them only the run, the conservation and the two-rank comparison are checked. Measured (new tests alone against the CI baseline of main 8b864938; the flags act in the C++ kernel, which is not measured): kernels/SW2DCV.py 87.2% (1190/1365) -> 89.5% (1222/1365) +32 statements Co-Authored-By: Claude Sonnet 5.5 --- test/sw2dcv_flags_mpi.py | 95 +++++++++++++++++++++++++++++++++++++++ test/test_sw2dcv_flags.py | 93 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 test/sw2dcv_flags_mpi.py create mode 100644 test/test_sw2dcv_flags.py diff --git a/test/sw2dcv_flags_mpi.py b/test/sw2dcv_flags_mpi.py new file mode 100644 index 0000000000..413f319cd3 --- /dev/null +++ b/test/sw2dcv_flags_mpi.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +"""SW2DCV circular_damBreak (SWEs, lumped mass matrix) to t = 0.3 with one of the switches no deck sets, for test_sw2dcv_flags.py. + +VARIANT names the switch (VARIANTS below): the numerical flags LOW_ORDER_ONLY, NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS, +BOUNDS_RELAXATION=0 with BOUNDS_EXCLUDE_SELF=1, LINEAR_FRICTION, a tailwater stage on the right edge, a walls function that leaves +the right edge open, a porosity with a Darcy-Forchheimer drag law. Unstructured mesh (he = 0.6) with the slanted pinned cut of +sw2dcv_partition_mpi.py. Run in an empty directory, serially or under mpiexec; rank 0 leaves u.csv (the owned nodes, sorted by x, y: +x, y, h, hu, hv, ML) and total.txt (the water volume at the start and at the end). +""" +import os, shutil, sys, runpy +import numpy as np +from proteus import Comm +import rank_staging + +HERE = os.path.dirname(os.path.abspath(__file__)) +VARIANT = os.environ["VARIANT"] +VARIANTS = { + "default": "", + "low_order_only": "mySWFlowProblem.swe_parameters['LOW_ORDER_ONLY'] = 1", + "no_star_states": "mySWFlowProblem.swe_parameters['NO_STAR_STATES'] = 1", + "wall_riemann": "mySWFlowProblem.swe_parameters['WALL_RIEMANN'] = 1", + "nodal_h_bounds": "mySWFlowProblem.swe_parameters['NODAL_H_BOUNDS'] = 1", + "no_relaxation": "mySWFlowProblem.swe_parameters['BOUNDS_RELAXATION'] = 0\n" + "mySWFlowProblem.swe_parameters['BOUNDS_EXCLUDE_SELF'] = 1", + "linear_friction": "mySWFlowProblem.physical_parameters['LINEAR_FRICTION'] = 1\n" + "mySWFlowProblem.physical_parameters['mannings'] = 0.05", + "tailwater": "boundaryConditions['tailwater'] = {'where': lambda X: X[0] > 19.99,\n" + " 'stage': lambda x, y, t: 0.9 + 0.0 * x}", + "walls_function": "boundaryConditions['walls'] = lambda X: X[0] < 19.99", + "drag_law": "mySWFlowProblem.physical_parameters['porosity'] = 0.8\n" + "mySWFlowProblem.physical_parameters['drag_alpha'] = 0.5\n" + "mySWFlowProblem.physical_parameters['drag_beta'] = 0.2\n" + "mySWFlowProblem.physical_parameters['drag_law'] = lambda s: 0.2 + 0.1 * np.minimum(s['age'], 1.0)", +} +EXTRA = VARIANTS[VARIANT] +# the mySWFlowProblem line of the deck is the last statement but the physical parameter line: the extras go before the problem is built +# when they set boundaryConditions, after it otherwise; one place serves both because the problem reads boundaryConditions by reference +_deck = open(os.path.join(HERE, "SWFlow", "circular_damBreak.py")).read() +if "boundaryConditions[" in EXTRA: + _marker = "# ********************************** #\n# ***** Create mySWFlowProblem ***** #" + assert _deck.count(_marker) == 1 + _deck = _deck.replace(_marker, EXTRA + "\n" + _marker) + EXTRA_AFTER = "" +else: + EXTRA_AFTER = EXTRA +rank_staging.write("circular_damBreak.py", _deck + "\nmySWFlowProblem.swe_parameters['LUMPED_MASS_MATRIX'] = 1\n" + EXTRA_AFTER + "\n") +rank_staging.write("__init__.py", "") + +from proteus import MeshTools as MT +_partition = MT.Mesh.partitionMesh +def partitionMesh(self, nLayersOfOverlap=1, parallelPartitioningType=MT.MeshParallelPartitioningTypes.node, + nodeOwners=None, elementOwners=None, nodeWeights=None): + # a slanted cut through the dam, which the graph partitioner would not reproduce from run to run + if (nodeOwners is None and Comm.get().size() > 1 + and parallelPartitioningType == MT.MeshParallelPartitioningTypes.node): + nodeOwners = (self.nodeArray[:, 0] + 0.37 * self.nodeArray[:, 1] >= 10.3).astype(np.intc) + return _partition(self, nLayersOfOverlap=nLayersOfOverlap, parallelPartitioningType=parallelPartitioningType, + nodeOwners=nodeOwners, elementOwners=elementOwners, nodeWeights=nodeWeights) +MT.Mesh.partitionMesh = partitionMesh + +from proteus import NumericalSolution as NS +_init = NS.NS_base.__init__ +_volumes = [] +def init(self, so, pList, nList, *args, **kwargs): + for n in nList: + n.nl_atol_res, n.l_atol_res, n.l_rtol_res, n.linTolFac, n.tolFac = 1.0e-13, 1.0e-15, 0.0, 0.0, 0.0 + return _init(self, so, pList, nList, *args, **kwargs) +NS.NS_base.__init__ = init + +def volume(m): + nOwned = m.mesh.nNodes_owned + return Comm.get().globalSum(float(np.dot(m.ML[:nOwned], m.u[0].dof[:nOwned]))) + +_calc = NS.NS_base.calculateSolution +def calc(self, *a, **k): + m = self.modelList[0].levelModelList[-1] + r = _calc(self, *a, **k) + nOwned = m.mesh.nNodes_owned + X = m.mesh.nodeArray[:nOwned] + h0 = 1.0 + 0.8 * (((X[:, 0] - 10.0) ** 2 + (X[:, 1] - 10.0) ** 2) <= 4.0) # the deck's initial depth + v0 = Comm.get().globalSum(float(np.dot(m.ML[:nOwned], h0))) + comm = Comm.get().comm.tompi4py() + cols = [m.mesh.nodeArray[:nOwned, :2]] + [m.u[i].dof[:nOwned, None] for i in range(3)] + [m.ML[:nOwned, None]] + gathered = comm.gather(np.hstack(cols), root=0) + v1 = volume(m) + if comm.rank == 0: + a = np.vstack(gathered) + np.savetxt("u.csv", a[np.lexsort((a[:, 1], a[:, 0]))], delimiter=",", header="x,y,h,hu,hv,ML") + with open("total.txt", "w") as f: + f.write("%.17g %.17g\n" % (v0, v1)) + return r +NS.NS_base.calculateSolution = calc + +sys.argv = ['parun', '--SWEs', 'circular_damBreak.py', '-l1', '-C', 'sw_model=0 final_time=0.3 dt_output=0.3 structured=False he=0.6'] +runpy.run_path(shutil.which('parun'), run_name='__main__') diff --git a/test/test_sw2dcv_flags.py b/test/test_sw2dcv_flags.py new file mode 100644 index 0000000000..665038ad48 --- /dev/null +++ b/test/test_sw2dcv_flags.py @@ -0,0 +1,93 @@ +"""SW2DCV switches no deck sets: LOW_ORDER_ONLY, NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS, no bounds relaxation, linear friction, +a tailwater, a walls function, a porosity with a drag law. + +sw2dcv_flags_mpi.py runs the circular_damBreak deck (SWEs, lumped mass matrix, unstructured mesh he = 0.6, t = 0.3) with one +of them on, serially and on two ranks (partition pinned to a slanted cut). Checked, per variant: + +- the run is finite and the depth non-negative (to roundoff); +- on a closed domain the water volume (sum of ML h, ML carrying the porosity) is conserved to 1e-11 relative; with a tailwater (open + edge, stage 0.9 below the still depth 1.0) it is not: the volume falls; +- the answer differs from the default's by more than 1e-8 where the switch changes the scheme (LOW_ORDER_ONLY, + BOUNDS_RELAXATION 0, LINEAR_FRICTION, tailwater, drag law), so the branch ran; NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS and the + walls function give the default's answer here to the last bit (the dam does not reach a wall in 0.3 s and the states stay smooth), so + for them the run, the conservation and the two-rank comparison are what is checked; +- two ranks give the serial answer to 1e-9. +""" +import importlib.util +import os +import shutil +import sys + +import numpy +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("launch_output", os.path.join(HERE, "launch_output.py")) +launch_output = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(launch_output) +HELPER = os.path.join(HERE, "sw2dcv_flags_mpi.py") + +CLOSED = ["default", "low_order_only", "no_star_states", "wall_riemann", "nodal_h_bounds", "no_relaxation", + "linear_friction", "walls_function", "drag_law"] +DIFFERS = ["low_order_only", "no_relaxation", "linear_friction", "tailwater", "drag_law"] +VARIANTS = CLOSED + ["tailwater"] + + +def _mpiexec(): + bindir = os.path.dirname(sys.executable) + for name in ("mpiexec", "mpirun"): + candidate = os.path.join(bindir, name) + if os.path.exists(candidate): + return candidate + return shutil.which("mpiexec") or shutil.which("mpirun") + + +MPIEXEC = _mpiexec() + + +def _run(ranks, cwd, variant): + env = dict(os.environ, OMP_NUM_THREADS="1", VARIANT=variant) + env.setdefault("FI_PROVIDER", "tcp") + env.setdefault("OMPI_MCA_rmaps_base_oversubscribe", "1") + env.setdefault("PRTE_MCA_rmaps_default_mapping_policy", ":oversubscribe") + env["PETSC_OPTIONS"] = (env.get("PETSC_OPTIONS", "") + " -mat_partitioning_type current").strip() + env["PYTHONPATH"] = os.pathsep.join([p for p in sys.path if p] + [HERE, env.get("PYTHONPATH", "")]).strip(os.pathsep) + argv = [sys.executable, HELPER] if ranks == 1 else [MPIEXEC, "-n", str(ranks), sys.executable, HELPER] + launch_output.run(argv, cwd=cwd, env=env, timeout=1800) + u = numpy.loadtxt(os.path.join(str(cwd), "u.csv"), delimiter=",", skiprows=1) + v0, v1 = [float(x) for x in open(os.path.join(str(cwd), "total.txt")).read().split()] + return u, v0, v1 + + +@pytest.fixture(scope="module") +def serial(tmp_path_factory): + out = {} + for variant in VARIANTS: + d = tmp_path_factory.mktemp("serial_" + variant) + out[variant] = _run(1, d, variant) + return out + + +@pytest.mark.parametrize("variant", VARIANTS) +def test_the_variant_runs_and_keeps_the_water_volume(serial, variant): + u, v0, v1 = serial[variant] + assert numpy.isfinite(u).all() + assert u[:, 2].min() > -1e-10 + if variant == "tailwater": + assert v1 < v0 - 1.0, "water leaves through the tailwater edge (stage 0.9 < depth 1.0)" + else: + assert abs(v1 - v0) < 1e-11 * v0 + + +@pytest.mark.parametrize("variant", DIFFERS) +def test_the_variant_changes_the_answer(serial, variant): + assert numpy.abs(serial[variant][0][:, 2:5] - serial["default"][0][:, 2:5]).max() > 1e-8 + + +@pytest.mark.skipif(MPIEXEC is None, reason="mpiexec not available") +@pytest.mark.parametrize("variant", VARIANTS) +def test_two_ranks_give_the_serial_answer(serial, tmp_path, variant): + two, _, _ = _run(2, tmp_path, variant) + one = serial[variant][0] + assert one.shape == two.shape and numpy.abs(one[:, :2] - two[:, :2]).max() == 0 + assert numpy.abs(one[:, 2:5] - two[:, 2:5]).max() < 1e-9 From f56cdfb8edd233f66063b4932d44ee3cdbe13658 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:11:40 -0600 Subject: [PATCH 10/17] C49 R3: SW2DCV and GN_SW2DCV: the consistent mass matrix, the dispersive model and getJacobian Adds to the SW2DCV switches test: the consistent mass matrix, GN_SW2DCV (sw_model=1) with the lumped and the consistent mass matrix (conservation, serial vs 2 ranks to 1e-9, differs from SWEs) and, serially, the model's getJacobian, which the explicit SSP scheme never asks for: for SWEs and GN it is the mass matrix of every unknown (symmetric, entries add up to nc times the area). The helper calls it at the end of a serial run. Measured (new tests alone against the CI baseline of main 8b864938; this commit adds 169 to GN_SW2DCV; with the previous commit's 32 for SW2DCV the file's total is 201): kernels/GN_SW2DCV.py 78.5% (1229/1565) -> 89.3% (1398/1565) +169 statements Co-Authored-By: Claude Sonnet 5.5 --- test/sw2dcv_flags_mpi.py | 19 +++++++++++++++++-- test/test_sw2dcv_flags.py | 32 +++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/test/sw2dcv_flags_mpi.py b/test/sw2dcv_flags_mpi.py index 413f319cd3..3a2caa388c 100644 --- a/test/sw2dcv_flags_mpi.py +++ b/test/sw2dcv_flags_mpi.py @@ -3,7 +3,7 @@ VARIANT names the switch (VARIANTS below): the numerical flags LOW_ORDER_ONLY, NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS, BOUNDS_RELAXATION=0 with BOUNDS_EXCLUDE_SELF=1, LINEAR_FRICTION, a tailwater stage on the right edge, a walls function that leaves -the right edge open, a porosity with a Darcy-Forchheimer drag law. Unstructured mesh (he = 0.6) with the slanted pinned cut of +the right edge open, a porosity with a Darcy-Forchheimer drag law, the consistent mass matrix, the dispersive model (gn, gn_consistent: sw_model=1). Unstructured mesh (he = 0.6) with the slanted pinned cut of sw2dcv_partition_mpi.py. Run in an empty directory, serially or under mpiexec; rank 0 leaves u.csv (the owned nodes, sorted by x, y: x, y, h, hu, hv, ML) and total.txt (the water volume at the start and at the end). """ @@ -27,6 +27,9 @@ "tailwater": "boundaryConditions['tailwater'] = {'where': lambda X: X[0] > 19.99,\n" " 'stage': lambda x, y, t: 0.9 + 0.0 * x}", "walls_function": "boundaryConditions['walls'] = lambda X: X[0] < 19.99", + "consistent": "mySWFlowProblem.swe_parameters['LUMPED_MASS_MATRIX'] = 0", + "gn": "mySWFlowProblem.GN_swe_parameters['LUMPED_MASS_MATRIX'] = 1", + "gn_consistent": "mySWFlowProblem.GN_swe_parameters['LUMPED_MASS_MATRIX'] = 0", "drag_law": "mySWFlowProblem.physical_parameters['porosity'] = 0.8\n" "mySWFlowProblem.physical_parameters['drag_alpha'] = 0.5\n" "mySWFlowProblem.physical_parameters['drag_beta'] = 0.2\n" @@ -88,8 +91,20 @@ def calc(self, *a, **k): np.savetxt("u.csv", a[np.lexsort((a[:, 1], a[:, 0]))], delimiter=",", header="x,y,h,hu,hv,ML") with open("total.txt", "w") as f: f.write("%.17g %.17g\n" % (v0, v1)) + if comm.size == 1: + # serial: the Newton Jacobian the explicit SSP scheme never asks for (an implicit time integration would): the + # model's own getJacobian, whose rows are the (consistent) mass matrix of every unknown + import json + m.getJacobian(m.jacobian) + rowptr, colind, nz = m.jacobian.getCSRrepresentation() + rows = np.repeat(np.arange(len(rowptr) - 1), np.diff(rowptr)) + J = dict(zip(zip(rows.tolist(), colind.tolist()), nz.tolist())) + asym = max(abs(v - J.get((j, i), 0.0)) for (i, j), v in J.items()) + with open("jacobian.json", "w") as f: + json.dump(dict(n=len(rowptr) - 1, nnz=int(len(nz)), total=float(nz.sum()), area=float(m.ML.sum()), + nc=int(m.nc), asymmetry=float(asym), finite=bool(np.isfinite(nz).all())), f) return r NS.NS_base.calculateSolution = calc -sys.argv = ['parun', '--SWEs', 'circular_damBreak.py', '-l1', '-C', 'sw_model=0 final_time=0.3 dt_output=0.3 structured=False he=0.6'] +sys.argv = ['parun', '--SWEs', 'circular_damBreak.py', '-l1', '-C', 'sw_model=%d final_time=0.3 dt_output=0.3 structured=False he=0.6' % (1 if VARIANT.startswith('gn') else 0)] runpy.run_path(shutil.which('parun'), run_name='__main__') diff --git a/test/test_sw2dcv_flags.py b/test/test_sw2dcv_flags.py index 665038ad48..a10ece064b 100644 --- a/test/test_sw2dcv_flags.py +++ b/test/test_sw2dcv_flags.py @@ -1,5 +1,5 @@ """SW2DCV switches no deck sets: LOW_ORDER_ONLY, NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS, no bounds relaxation, linear friction, -a tailwater, a walls function, a porosity with a drag law. +a tailwater, a walls function, a porosity with a drag law, the consistent mass matrix (KSP/LU solves, a getJacobian), and the dispersive model GN_SW2DCV with the lumped and the consistent mass matrix. sw2dcv_flags_mpi.py runs the circular_damBreak deck (SWEs, lumped mass matrix, unstructured mesh he = 0.6, t = 0.3) with one of them on, serially and on two ranks (partition pinned to a slanted cut). Checked, per variant: @@ -8,10 +8,11 @@ - on a closed domain the water volume (sum of ML h, ML carrying the porosity) is conserved to 1e-11 relative; with a tailwater (open edge, stage 0.9 below the still depth 1.0) it is not: the volume falls; - the answer differs from the default's by more than 1e-8 where the switch changes the scheme (LOW_ORDER_ONLY, - BOUNDS_RELAXATION 0, LINEAR_FRICTION, tailwater, drag law), so the branch ran; NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS and the + BOUNDS_RELAXATION 0, LINEAR_FRICTION, tailwater, drag law, consistent mass matrix, GN against SWEs), so the branch ran; NO_STAR_STATES, WALL_RIEMANN, NODAL_H_BOUNDS and the walls function give the default's answer here to the last bit (the dam does not reach a wall in 0.3 s and the states stay smooth), so for them the run, the conservation and the two-rank comparison are what is checked; -- two ranks give the serial answer to 1e-9. +- two ranks give the serial answer to 1e-9; +- (serial, SWEs and GN) ``getJacobian`` is the mass matrix of every unknown: symmetric, total nc times the area. """ import importlib.util import os @@ -28,8 +29,8 @@ HELPER = os.path.join(HERE, "sw2dcv_flags_mpi.py") CLOSED = ["default", "low_order_only", "no_star_states", "wall_riemann", "nodal_h_bounds", "no_relaxation", - "linear_friction", "walls_function", "drag_law"] -DIFFERS = ["low_order_only", "no_relaxation", "linear_friction", "tailwater", "drag_law"] + "linear_friction", "walls_function", "drag_law", "consistent", "gn", "gn_consistent"] +DIFFERS = ["low_order_only", "no_relaxation", "linear_friction", "tailwater", "drag_law", "consistent", "gn"] VARIANTS = CLOSED + ["tailwater"] @@ -59,12 +60,22 @@ def _run(ranks, cwd, variant): return u, v0, v1 +def _jacobian(cwd): + import json + return json.load(open(os.path.join(str(cwd), "jacobian.json"))) + + +JACOBIANS = {} + + @pytest.fixture(scope="module") def serial(tmp_path_factory): out = {} for variant in VARIANTS: d = tmp_path_factory.mktemp("serial_" + variant) out[variant] = _run(1, d, variant) + if variant in ("default", "gn"): + JACOBIANS[variant] = _jacobian(d) return out @@ -91,3 +102,14 @@ def test_two_ranks_give_the_serial_answer(serial, tmp_path, variant): one = serial[variant][0] assert one.shape == two.shape and numpy.abs(one[:, :2] - two[:, :2]).max() == 0 assert numpy.abs(one[:, 2:5] - two[:, 2:5]).max() < 1e-9 + + +@pytest.mark.parametrize("variant, nc", [("default", 3), ("gn", 6)]) +def test_the_newton_jacobian_is_the_mass_matrix_of_every_unknown(serial, variant, nc): + """getJacobian (the explicit scheme never calls it; an implicit time integration would): a symmetric matrix whose entries add up to + nc times the water-plane area (the mass matrix of each of the nc unknowns, whose entries add up to the area).""" + j = JACOBIANS[variant] + assert j["nc"] == nc and j["finite"] + assert j["total"] == pytest.approx(nc * j["area"], rel=1e-10) + assert j["asymmetry"] < 1e-12 + assert j["nnz"] > j["n"] From 5404b69e90f38e28b1be82e8206fed749449842e Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:14:39 -0600 Subject: [PATCH 11/17] C49 R3: m_comp_co2 options no regression case sets (CO2 injection, FCT, trapping, end-point permeability) test_m_comp_co2.py's cases run the deck with the constructor's defaults for most options. The same segregation case now runs with FCT on, with residual gas (S_gr_types), with end-point gas relative permeability (krn_end_types) and with a CO2 injection port as the lumped disk and as the consistent point source. Checked: CO2 and H2O conserved to 1e-6 (the case's own drifts are 1e-10) for the gas options; the point source adds rate pi r^2 T of CO2 to 5% (the doc's "mesh-exact total": 0.01386 against 0.01414), the disk 0.0104 (74%, the nodes do not tile the disk), neither moves the H2O total. LUMPED_MASS_MATRIX needs the explicit lumped solver (the constructor asserts it) and is not run here. Measured (new test alone against the CI baseline of main 8b864938): kernels/m_comp_co2.py 41.8% (1132/2707) -> 47.2% (1277/2707) +145 statements Co-Authored-By: Claude Sonnet 5.5 --- test/m_comp_co2/test_m_comp_co2_options.py | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 test/m_comp_co2/test_m_comp_co2_options.py diff --git a/test/m_comp_co2/test_m_comp_co2_options.py b/test/m_comp_co2/test_m_comp_co2_options.py new file mode 100644 index 0000000000..470490d371 --- /dev/null +++ b/test/m_comp_co2/test_m_comp_co2_options.py @@ -0,0 +1,74 @@ +"""m_comp_co2 options no regression case sets, on the segregation column (closed, STAB 2, a free gas pool). + +The cases of test_m_comp_co2.py leave most of ``m_comp_co2.Coefficients``' options at their defaults. Here the same deck +(case 'segregation', loaded and run by test_m_comp_co2.py's own helpers) runs with one option changed through the +constructor, and what each option promises is checked on the run's totals: + +- ``injection_ports`` (a CO2 source at a point of the column): the CO2 total grows, the H2O total does not; +- the lumped-disk and the consistent point-source injections put in the same CO2 (the point source is "mesh-exact"); +- options that change the physics of the gas (``S_gr_types``, ``krn_end_types``, ``mu_n``) leave the conservation of CO2 and H2O + to the tolerance of the segregation case. +""" +import importlib.util +import os +import sys +from pathlib import Path + +import numpy as np +import pytest + +HERE = Path(__file__).resolve().parent +_spec = importlib.util.spec_from_file_location("m_comp_co2_cases", str(HERE / "test_m_comp_co2.py")) +cases = importlib.util.module_from_spec(_spec) +sys.modules["m_comp_co2_cases"] = cases +_spec.loader.exec_module(cases) +from proteus.kernels import m_comp_co2 + + +def _run_with(options, tmp_path, monkeypatch): + init = m_comp_co2.Coefficients.__init__ + + def patched(self, *args, **kwargs): + kwargs.update(options) + init(self, *args, **kwargs) + monkeypatch.setattr(m_comp_co2.Coefficients, "__init__", patched) + return cases._run("case='segregation'", tmp_path, monkeypatch) + + +RATE, RADIUS = 1.0e-4, 0.03 +PORT = [(0.05, 0.2, RATE, RADIUS, 0.0, 1.0e9)] + + +@pytest.fixture(scope="module") +def runs(tmp_path_factory): + """Each option run once on the segregation column: {name: totals}.""" + out = {} + options = { + "fct": dict(FCT=True, num_fct_iter=1), + "trapping": dict(S_gr_types=np.array([0.1])), + "endpoint": dict(krn_end_types=np.array([0.5])), + "inject_disk": dict(injection_ports=PORT), + "inject_point": dict(injection_ports=PORT, injection_point_source=True), + } + for name, opts in options.items(): + with pytest.MonkeyPatch.context() as mp: + _, totals = _run_with(opts, tmp_path_factory.mktemp(name), mp) + out[name] = totals + return out + + +@pytest.mark.parametrize("name", ["fct", "trapping", "endpoint"]) +def test_the_gas_options_conserve_co2_and_h2o(runs, name): + drift = cases._drifts(runs[name]) + assert drift["co2_drift"] < 1e-6 and drift["h2o_drift"] < 1e-6, drift + + +def test_the_point_source_puts_in_the_mesh_exact_amount(runs): + """rate * pi * radius^2 per unit time (the doc of injection_point_source), in the same units as the totals' CO2 column; the H2O total + does not move. The disk source over the nodes within the radius puts in less on this mesh (the nodes do not tile the disk).""" + expected = RATE * np.pi * RADIUS ** 2 * (runs["inject_point"][-1, 0] - runs["inject_point"][0, 0]) + added = {k: runs[k][-1, 1] - runs[k][0, 3] for k in ("inject_disk", "inject_point")} + assert added["inject_point"] == pytest.approx(expected, rel=0.05) + assert 0.5 * expected < added["inject_disk"] < added["inject_point"] + for k in ("inject_disk", "inject_point"): + assert abs(runs[k][-1, 2] - runs[k][0, 2]) < 1e-6 * abs(runs[k][0, 2]) From c9369a8e0b97b9985f6a76605b071ba7f1c87058 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:01:00 -0600 Subject: [PATCH 12/17] RANS2P reads the boundary kind per face (3D and 2D): strong rows on the strong faces, weak elsewhere, 'none' open RANS2P.py (the LevelModel of RANS2P.h and RANS2P2D.h): implementsBoundaryKinds; a declared setter turns on the python-side row replacement (dirichletConditionsForceDOF from the strong faces only, per declared component, decided by the declaration for the parallel authority); kernelIsDOFBoundary(ci) hands the kernels the weak faces AND the strong ones (a strong face keeps imposing its datum in the flux, as forceStrongDirichlet always did; the flux class's own isDOFBoundary stays weak-only, so a strong face never also gets the flux class's weak term); forceStrongDirichlet of the coefficients together with a declared setter is refused; the constant-pressure null space check reads the legacy flag, not the per-face one. NO kernel edit: unlike TADR's scalar forceStrongConditions, RANS2P.h/RANS2P2D.h have no force-strong flag, they read isDOFBoundary per face point; the changed branch (the strong union in kernelIsDOFBoundary, strong points > 0) runs in cRANS2P2D (2D) and cRANS2P (3D). Nothing changes without a declared setter. test/rans2p_mixed_bc_mms_mpi.py + test_rans2p_mixed_bc_mms.py (12 tests): manufactured divergence-free Navier-Stokes solution (stream function, sympy forcing, nu 0.1, P1/P1 with the model's stabilization; velocity strong left/top (/back), weak bottom (/front), 'none' right with the pressure as weak datum there; the exact solution has no stress on x = 1). 2D mixed, h 1/16 -> 1/32 -> 1/64: L2 rates u 1.88/1.94, v 1.96/1.97, p 1.60/1.59; H1 u, v 1.01/1.00, p 0.83/0.74. 3D mixed, h 1/8 -> 1/16: L2 u 1.84, v 1.91, w 2.29, p 1.63; H1 u 1.01, v 1.02, w 1.83, p 0.89. as accurate as the all-weak run (2D, 32 elements/side: L2 u 7.8e-4 vs 6.2e-4, v 9.4e-4 vs 6.6e-4, p 4.0e-3 vs 4.6e-3). dofs of the strong walls hold the data to 0.0; no face point is both weak and strong (2D, 3D). every face strong == legacy forceStrongDirichlet bit for bit (2D h 1/16: L2 u 3.0737520031092805e-3, p 1.2080950812986014e-2, both; 3D same); a bare function in a declared setter == the undeclared run bit for bit. serial = 2 and 3 ranks, node and element partitions (-mat_partitioning_type current): relative differences of every L2/H1 norm <= 3.3e-14; 3D 2 ranks within 1e-9. Existing BC suite and the RANS2P users (test_mixed_bc_mms, cube/simplex/weak_dirichlet mms, rank_interface, strong dirichlet, numerical flux, step retry, twophaseflow partition independence, hotstart, dispatch, solver_tests, cylinder2D, rans2p_ib, periodic, CLSVOF, TADR, multilevel, post_processing + the new file): 1159 passed, 8 skipped, 0 failed (Mac, arm64; CI is the oracle). Found, not fixed: RANS2P2D segfaults in calculateResidual with a P2 velocity space on some meshes (NN=13 4/4, plain undeclared setters, test/rans2p_mixed_bc_mms_mpi.py SPACE=p1p2), P1/P1 never: the tests use P1/P1. The coefficients' `stokes` flag is not read by the kernels. Co-Authored-By: Claude Sonnet 5.5 --- proteus/kernels/RANS2P.py | 64 ++++++-- test/rans2p_mixed_bc_mms_mpi.py | 255 +++++++++++++++++++++++++++++++ test/test_rans2p_mixed_bc_mms.py | 165 ++++++++++++++++++++ 3 files changed, 474 insertions(+), 10 deletions(-) create mode 100644 test/rans2p_mixed_bc_mms_mpi.py create mode 100644 test/test_rans2p_mixed_bc_mms.py diff --git a/proteus/kernels/RANS2P.py b/proteus/kernels/RANS2P.py index fb6a4f81ff..75a9c35f36 100644 --- a/proteus/kernels/RANS2P.py +++ b/proteus/kernels/RANS2P.py @@ -20,6 +20,7 @@ from proteus import cArgumentsDict from proteus.csparsity import CSR_INDEX_DTYPE import proteus.NumericalFlux +from proteus import BoundaryKinds import proteus.Profiling import proteus.ShockCapturing import proteus.SubgridError @@ -1125,6 +1126,11 @@ def archiveFields(self, lm): class LevelModel(proteus.Transport.OneLevelTransport): nCalls = 0 + # per-face boundary kinds (BoundaryKinds): a face that says 'strong' has the rows of its dofs replaced and no weak + # term from the flux class, a face that says 'none' is open. The kernels need no flag of their own: they read + # isDOFBoundary per component, which kernelIsDOFBoundary() gives them as the weak faces and the strong ones + # (a strong face keeps imposing its datum in the flux, as forceStrongDirichlet always did). + implementsBoundaryKinds = True def __init__(self, uDict, @@ -1702,8 +1708,29 @@ def __init__(self, # cek/ido todo replace python loops in modules with optimized code if possible/necessary logEvent("dirichlet conditions") self.forceStrongConditions = coefficients.forceStrongDirichlet + # forceStrongDirichlet of the coefficients makes EVERY Dirichlet face strong; the kernels' isDOFBoundary then + # carries all of them. A declared setter says per face instead (BoundaryKinds). + self.forceStrongAllFaces = bool(self.forceStrongConditions) self.dirichletConditionsForceDOF = {} - if self.forceStrongConditions: + self.declaredBoundaryKinds = [BoundaryKinds.declaresKinds(dofBoundaryConditionsSetterDict.get(cj)) for cj in range(self.nc)] + if any(self.declaredBoundaryKinds): + if self.forceStrongAllFaces: + raise ValueError("RANS2P: forceStrongDirichlet makes every Dirichlet face strong; a setter that declares " + "per-face kinds (BoundaryKinds.declare) says which faces are strong itself: drop " + "forceStrongDirichlet") + # the faces that say 'strong' have the rows of their dofs replaced (the dofs stay unknowns: the layout of a + # weak class, which is also the parallel one); a bare function stays weak, as it always was. Decided by + # the declaration, not by what this rank holds (the parallel authority of a shared dof is collective). + self.forceStrongConditions = True + for cj in range(self.nc): + if self.declaredBoundaryKinds[cj]: + self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions( + self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False, + strongFacesOnly=True) + else: + self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions( + self.u[cj].femSpace, None, weakDirichletConditions=True) + elif self.forceStrongConditions: for cj in range(self.nc): self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions( self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False) @@ -1735,6 +1762,8 @@ def __init__(self, self.offset.append(self.offset[2]) self.stride.append(self.stride[2]) self.numericalFlux.isDOFBoundary[3] = self.numericalFlux.isDOFBoundary[2].copy() + self.numericalFlux.isStrongBoundary[3] = self.numericalFlux.isStrongBoundary[2].copy() + self.numericalFlux.isOpenBoundary[3] = self.numericalFlux.isOpenBoundary[2].copy() self.numericalFlux.ebqe[('u', 3)] = self.numericalFlux.ebqe[('u', 2)].copy() logEvent("calling cRANS2P2D_base ctor") self.rans2p = cRANS2P2D_base(self.nSpace_global, @@ -1802,6 +1831,21 @@ def _warnParticleSurfaceDegree(self): "surface integrals (error 8e-2..2e-1 of the block's largest entry, any quadrature degree); " "see test/test_gf_surface_degree.py", level=0) + def kernelIsDOFBoundary(self, ci): + """isDOFBoundary of component ci for the kernels: the weak faces AND the strong ones. A strong face has + isDOFBoundary 0 in the flux class (it must not get the weak term in the flux's own arrays) but the kernel + keeps imposing its datum there, as forceStrongDirichlet always did (the rows of its dofs are replaced, so + the weak terms of the face only reach rows that are replaced); a face that declared itself open has neither.""" + nf = self.numericalFlux + strong = nf.isStrongBoundary.get(ci) + if strong is None or not strong.any(): + return nf.isDOFBoundary[ci] + cache = self.__dict__.setdefault('_kernelIsDOFBoundary', {}) + if ci not in cache or cache[ci].shape != strong.shape: + cache[ci] = numpy.zeros(strong.shape, 'i') + numpy.maximum(nf.isDOFBoundary[ci], strong, out=cache[ci]) + return cache[ci] + def getResidual(self, u, r): """ Calculate the element residuals and add in to the global residual @@ -2046,10 +2090,10 @@ def getResidual(self, u, r): argsDict["ebqe_porosity_ext"] = self.coefficients.ebqe_porosity argsDict["ebqe_turb_var_0"] = self.coefficients.ebqe_turb_var[0] argsDict["ebqe_turb_var_1"] = self.coefficients.ebqe_turb_var[1] - argsDict["isDOFBoundary_p"] = self.numericalFlux.isDOFBoundary[0] - argsDict["isDOFBoundary_u"] = self.numericalFlux.isDOFBoundary[1] - argsDict["isDOFBoundary_v"] = self.numericalFlux.isDOFBoundary[2] - argsDict["isDOFBoundary_w"] = self.numericalFlux.isDOFBoundary[3] + argsDict["isDOFBoundary_p"] = self.kernelIsDOFBoundary(0) + argsDict["isDOFBoundary_u"] = self.kernelIsDOFBoundary(1) + argsDict["isDOFBoundary_v"] = self.kernelIsDOFBoundary(2) + argsDict["isDOFBoundary_w"] = self.kernelIsDOFBoundary(3) argsDict["isAdvectiveFluxBoundary_p"] = self.ebqe[('advectiveFlux_bc_flag', 0)] argsDict["isAdvectiveFluxBoundary_u"] = self.ebqe[('advectiveFlux_bc_flag', 1)] argsDict["isAdvectiveFluxBoundary_v"] = self.ebqe[('advectiveFlux_bc_flag', 2)] @@ -2422,10 +2466,10 @@ def getJacobian(self, jacobian): argsDict["ebqe_porosity_ext"] = self.coefficients.ebqe_porosity argsDict["ebqe_turb_var_0"] = self.coefficients.ebqe_turb_var[0] argsDict["ebqe_turb_var_1"] = self.coefficients.ebqe_turb_var[1] - argsDict["isDOFBoundary_p"] = self.numericalFlux.isDOFBoundary[0] - argsDict["isDOFBoundary_u"] = self.numericalFlux.isDOFBoundary[1] - argsDict["isDOFBoundary_v"] = self.numericalFlux.isDOFBoundary[2] - argsDict["isDOFBoundary_w"] = self.numericalFlux.isDOFBoundary[3] + argsDict["isDOFBoundary_p"] = self.kernelIsDOFBoundary(0) + argsDict["isDOFBoundary_u"] = self.kernelIsDOFBoundary(1) + argsDict["isDOFBoundary_v"] = self.kernelIsDOFBoundary(2) + argsDict["isDOFBoundary_w"] = self.kernelIsDOFBoundary(3) argsDict["isAdvectiveFluxBoundary_p"] = self.ebqe[('advectiveFlux_bc_flag', 0)] argsDict["isAdvectiveFluxBoundary_u"] = self.ebqe[('advectiveFlux_bc_flag', 1)] argsDict["isAdvectiveFluxBoundary_v"] = self.ebqe[('advectiveFlux_bc_flag', 2)] @@ -2496,7 +2540,7 @@ def getJacobian(self, jacobian): argsDict["isActiveElement_last"] = self.isActiveElement_last self.rans2p.calculateJacobian(argsDict) assert(np.all(np.isfinite(jacobian.getCSRrepresentation()[2]))) - if not self.forceStrongConditions and max(numpy.linalg.norm(self.u[1].dof, numpy.inf), numpy.linalg.norm(self.u[2].dof, numpy.inf), numpy.linalg.norm(self.u[3].dof, numpy.inf)) < 1.0e-8: + if not self.forceStrongAllFaces and max(numpy.linalg.norm(self.u[1].dof, numpy.inf), numpy.linalg.norm(self.u[2].dof, numpy.inf), numpy.linalg.norm(self.u[3].dof, numpy.inf)) < 1.0e-8: self.pp_hasConstantNullSpace = True else: self.pp_hasConstantNullSpace = False diff --git a/test/rans2p_mixed_bc_mms_mpi.py b/test/rans2p_mixed_bc_mms_mpi.py new file mode 100644 index 0000000000..c45b9c13df --- /dev/null +++ b/test/rans2p_mixed_bc_mms_mpi.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python +"""RANS2P (single phase Navier-Stokes, 2D and 3D) with a DIFFERENT boundary kind on each wall and each component (C12, per-face +strong | weak | none; ``proteus.BoundaryKinds``), against a manufactured solution. Run by test_rans2p_mixed_bc_mms.py, +serially and under mpiexec. + + (u . grad) u - NU laplacian(u) + grad(p) = F, div(u) = 0 on the unit square or cube, rho = 1, + + stream function psi = f(x) y + m(x) q(y) h(z), u = psi_y, v = -psi_x, w = 0 (div u = 0 exactly), + f = 2 + (1 - x)^4 / 2, m = (1 - x)^3 cos(pi x) / 2, q = sin(K y) / K, h = 1 + 0.3 cos(K z) (h = 1 in 2D), + p = cos(pi x) cos(K y) (cos(K z)), + +so on the wall x = 1 the velocity is (f(1), 0, 0) with f' = f'' = m = m' = m'' = 0 there: u > 0 (outflow), the full viscous stress +(the symmetric gradient RANS2P uses) has no shear and no normal part, and a face declared ``none`` for the velocity there (no +value, no datum, the natural condition) is consistent with the exact solution; the pressure datum on that wall closes the problem +(no null space). F is evaluated from the exact solution by sympy. Every strong and weak +wall carries the exact solution as its data. + +Environment: ND (2|3), NN (nodes per direction), NU, KINDS (velocity: ``left=strong,bottom=weak,...``; a wall that is not +named has no condition), PKINDS (pressure: the same), DECLARE (0: plain setters, the kinds are not read: every named wall is +then weak, the baseline every existing problem is), ALL (strong: coefficients.forceStrongDirichlet, the legacy all-strong +model), SPACE (p1p1: equal order with the model's stabilization, the decks' choice; p1p2: P2 velocity, which crashes +RANS2P2D::calculateResidual on some meshes, not used by the tests), SGE (1: the subgrid error terms, 0: off), PART_TYPE, NLAYERS. +Rank 0 prints one line ``RESULT {json}``. +""" +import json +import os + +from proteus import runtime +comm = runtime.start() +from proteus import Profiling +Profiling.logLevel = int(os.environ.get('LOGLEVEL', '1')) +Profiling.verbose = Profiling.logLevel > 1 + +import numpy as np +import sympy as sp +from petsc4py import PETSc +from proteus import (BoundaryKinds as bk, Domain, FemTools, MeshTools, NumericalSolution, Quadrature, default_s, defaults) +from proteus.LinearAlgebraTools import SparseMatrix +from proteus.LinearSolvers import KSP_petsc4py +from proteus.NonlinearSolvers import Newton +from proteus.TimeIntegration import NoIntegration +from proteus.kernels import RANS2P + +nd = int(os.environ.get("ND", "2")) +nn = int(os.environ.get("NN", "9")) +NU = float(os.environ.get("NU", "0.1")) +kinds = dict(kv.split("=") for kv in os.environ.get("KINDS", "left=strong,bottom=weak,top=strong,right=none").split(",") if kv) +pkinds = dict(kv.split("=") for kv in os.environ.get("PKINDS", "right=weak").split(",") if kv) +declare = os.environ.get("DECLARE", "1") == "1" +allStrong = os.environ.get("ALL") == "strong" +space = os.environ.get("SPACE", "p1p1") +part = {"element": MeshTools.MeshParallelPartitioningTypes.element, + "node": MeshTools.MeshParallelPartitioningTypes.node}[os.environ.get("PART_TYPE", "node")] +layers = int(os.environ.get("NLAYERS", "1")) + +K = 1.5 * np.pi +X, Y, Z = sp.symbols("x y z") +f = 2 + (1 - X) ** 4 / 2 +m = (1 - X) ** 3 * sp.cos(sp.pi * X) / 2 +q = sp.sin(K * Y) / K +h = 1 + sp.Rational(3, 10) * sp.cos(K * Z) if nd == 3 else sp.Integer(1) +psi = f * Y + m * q * h +u_ = sp.diff(psi, Y) +v_ = -sp.diff(psi, X) +w_ = sp.Integer(0) +p_ = sp.cos(sp.pi * X) * sp.cos(K * Y) * (sp.cos(K * Z) if nd == 3 else 1) +vel_ = [u_, v_, w_][:nd] +coords = [X, Y, Z][:nd] +assert sp.expand(sum(sp.diff(vel_[i], coords[i]) for i in range(nd))) == 0 +# rho = 1: (u.grad)u - NU lap(u) + grad(p) = F (the kernel's mom_source = -g - force; its convection is always on: +# the coefficients' ``stokes`` flag is not read) +force_ = [sum(vel_[j] * sp.diff(vel_[i], coords[j]) for j in range(nd)) + - NU * sum(sp.diff(vel_[i], c, 2) for c in coords) + sp.diff(p_, coords[i]) for i in range(nd)] +lam = lambda e: sp.lambdify((X, Y, Z), e, "numpy") +u_f, v_f, w_f, p_f = lam(u_), lam(v_), lam(w_), lam(p_) +vel_f = [u_f, v_f, w_f][:nd] +force_f = [lam(e) for e in force_] +grad_vel_f = [[lam(sp.diff(vel_[i], c)) for c in coords] for i in range(nd)] +grad_p_f = [lam(sp.diff(p_, c)) for c in coords] + + +def _xyz(x): + x = np.asarray(x) + return x[..., 0], x[..., 1], (x[..., 2] if nd == 3 else 0.0 * x[..., 0]) + + +domain = Domain.RectangularDomain(L=(1.0,) * nd, x=(0.0,) * nd, name="box") +tag = {v: k for k, v in domain.boundaryTags.items()} +_kind = {"strong": bk.strong, "weak": bk.weak} + + +def make_setter(table, fun): + data = lambda x, t: float(fun(*_xyz(x))) + + def setter(x, flag): + name = tag.get(flag) + k = table.get(name) + if k is None: + return None + if k == "none": + return bk.OPEN if declare else None + if k == "bare": + return data + return _kind[k](data) if declare else data + return bk.declare(setter) if declare else setter + + +o = domain.MeshOptions +o.nnx = o.nny = o.nnz = o.nn = nn +o.triangleFlag = 0 +o.parallelPartitioningType = part +o.nLayersOfOverlapForParallel = layers + +p = defaults.Physics_base(nd=nd, name="rans2p_mixed_bc") +p.domain = domain +p.LevelModelType = RANS2P.LevelModel +p.coefficients = RANS2P.Coefficients(epsFact=0.0, rho_0=1.0, nu_0=NU, rho_1=1.0, nu_1=NU, g=np.zeros(nd), nd=nd, LS_model=None, + epsFact_density=0.0, stokes=True, useVF=0.0, useRBLES=0.0, useMetrics=1.0, + forceStrongDirichlet=allStrong, NONCONSERVATIVE_FORM=1.0, + MOMENTUM_SGE=float(os.environ.get("SGE", "1.0")), PRESSURE_SGE=float(os.environ.get("SGE", "1.0")), + VELOCITY_SGE=float(os.environ.get("SGE", "1.0")), + PRESSURE_PROJECTION_STABILIZATION=0.0, eb_penalty_constant=float(os.environ.get("PENALTY", "100.0")), + force_x=lambda x: float(force_f[0](*_xyz(x))), + force_y=lambda x: float(force_f[1](*_xyz(x))), + force_z=(lambda x: float(force_f[2](*_xyz(x)))) if nd == 3 else None) +p.initialConditions = {i: type("Zero", (), {"uOfXT": lambda self, x, t: 0.0})() for i in range(nd + 1)} +p.dirichletConditions = {0: make_setter(pkinds, p_f)} +for i, fn in enumerate(vel_f): + p.dirichletConditions[i + 1] = make_setter(kinds, fn) +p.advectiveFluxBoundaryConditions = {} +p.diffusiveFluxBoundaryConditions = {i: {} for i in range(nd + 1)} +p.fluxBoundaryConditions = {i: "outFlow" for i in range(nd + 1)} + +n = defaults.Numerics_base() +n.timeIntegration = NoIntegration +if space == "p1p1": + basis = lambda mesh, nd_: FemTools.C0_AffineLinearOnSimplexWithNodalBasis(mesh, nd_) + n.femSpaces = {i: basis for i in range(nd + 1)} +else: + n.femSpaces = {0: FemTools.C0_AffineLinearOnSimplexWithNodalBasis} + n.femSpaces.update({i + 1: FemTools.C0_AffineQuadraticOnSimplexWithNodalBasis for i in range(nd)}) +n.elementQuadrature = Quadrature.SimplexGaussQuadrature(nd, 5) +n.elementBoundaryQuadrature = Quadrature.SimplexGaussQuadrature(nd - 1, 5) +n.multilevelNonlinearSolver = n.levelNonlinearSolver = Newton +n.maxNonlinearIts = 20 +n.fullNewtonFlag = True +n.tolFac = 0.0 +n.nl_atol_res = 1.0e-9 +n.matrix = SparseMatrix +n.numericalFluxType = RANS2P.NumericalFlux +n.multilevelLinearSolver = n.levelLinearSolver = KSP_petsc4py +n.linear_solver_options_prefix = "rans2p_" +n.linearSmoother = None +n.linearSolverConvergenceTest = "r-true" +n.linTolFac = 0.0 +n.l_atol_res = 1.0e-11 +n.subgridError = RANS2P.SubgridError(p.coefficients, nd, lag=False, hFactor=1.0) +n.shockCapturing = RANS2P.ShockCapturing(p.coefficients, nd, 0.0, lag=False) +options = PETSc.Options() +options.setValue("rans2p_ksp_type", "gmres") +options.setValue("rans2p_ksp_rtol", 1.0e-10) +options.setValue("rans2p_ksp_atol", 1.0e-11) +options.setValue("rans2p_ksp_max_it", 50) +options.setValue("rans2p_pc_type", "lu") +options.setValue("rans2p_pc_factor_mat_solver_type", os.environ.get("LU", "superlu_dist" if comm.size() > 1 else "superlu")) +n.parallelPartitioningType = part +n.nLayersOfOverlapForParallel = layers + +so = defaults.System_base(name="rans2p_mixed_bc", pnList=[(p, n)], sList=[default_s]) +so.tnList = [0.0, 1.0] +ns = NumericalSolution.NS_base(so, [p], [n], so.sList, runtime.RunOptions()) +if os.environ.get("FAULT"): + import faulthandler + faulthandler.enable(all_threads=True) # replaces the PUMI signal handler, which prints no Python frames +ns.calculateSolution("rans2p_mixed_bc") + +model = ns.modelList[0].levelModelList[-1] +mesh = model.mesh +nOwned = mesh.nElements_owned +en = np.asarray(mesh.elementNodesArray) +Xn = np.asarray(mesh.nodeArray) +e = np.arange(nOwned) +bary_nodes = Xn[en[e]] +J = (Xn[en[e, 1:]] - Xn[en[e, :1]])[:, :, :nd].transpose(0, 2, 1) +detJ = np.abs(np.linalg.det(J)) +Jinv = np.linalg.inv(J) +quad = Quadrature.SimplexGaussQuadrature(nd, 8) +xi = np.array([q[:nd] for q in quad.points]) +wq = np.array(quad.weights) +bary = np.column_stack([1.0 - xi.sum(axis=1), xi]) +xq = np.einsum("qv,evc->eqc", bary, bary_nodes) +xs = [xq[..., i] for i in range(3)] if nd == 3 else [xq[..., 0], xq[..., 1], 0.0 * xq[..., 0]] + + +def errors(ci, exact, exact_grads): + fs = model.u[ci].femSpace + dof = np.asarray(model.u[ci].dof) + l2g = np.asarray(fs.dofMap.l2g) + lfs = fs.referenceFiniteElement.localFunctionSpace + vals = np.array([[b(x) for b in lfs.basis] for x in xi]) + grads = np.array([[gb(x)[:nd] for gb in lfs.basisGradients] for x in xi]) + uh = np.einsum("qi,ei->eq", vals, dof[l2g[e]]) + grad_ref = np.einsum("qid,ei->eqd", grads, dof[l2g[e]]) + grad = np.einsum("eqd,edk->eqk", grad_ref, Jinv) + gex = np.stack([exact_grads[k](*xs) * np.ones_like(uh) for k in range(nd)], axis=-1) + return (float(np.einsum("q,e,eq->", wq, detJ, (uh - exact(*xs)) ** 2)), + float(np.einsum("q,e,eqk->", wq, detJ, (grad - gex) ** 2))) + + +res = {} +res["p"] = errors(0, p_f, grad_p_f) +for i in range(nd): + res["u%d" % i] = errors(i + 1, vel_f[i], grad_vel_f[i]) + +# what the model did: the rows it replaced, and the faces it gave the flux +nf = model.numericalFlux +force = model.dirichletConditionsForceDOF +forcedErr = 0.0 +nForced = 0 +for cj, d in (force.items() if hasattr(force, "items") else []): + dof = np.asarray(model.u[cj].dof) + nForced += len(d.DOFBoundaryConditionsDict) + for dN, g_ in d.DOFBoundaryConditionsDict.items(): + forcedErr = max(forcedErr, abs(float(dof[dN]) - g_(d.DOFBoundaryPointDict[dN], 0.0))) +faces = {} +for ci in range(nd + 1): + faces[ci] = dict(weak=int(nf.isDOFBoundary[ci].sum()), strong=int(nf.isStrongBoundary[ci].sum()), + open=int(nf.isOpenBoundary[ci].sum()), + both=int((nf.isDOFBoundary[ci] * nf.isStrongBoundary[ci]).sum())) +from mpi4py import MPI +mc = comm.comm.tompi4py() +tot = {k: (mc.allreduce(v[0], MPI.SUM) ** 0.5, mc.allreduce(v[1], MPI.SUM) ** 0.5) for k, v in res.items()} +forcedErr = mc.allreduce(forcedErr, MPI.MAX) +nForcedAll = mc.allreduce(nForced, MPI.SUM) +for ci in faces: + for k in faces[ci]: + faces[ci][k] = mc.allreduce(faces[ci][k], MPI.SUM) +nElements = mc.allreduce(int(nOwned), MPI.SUM) +# first and last Newton residual of the (single) solve, for the Jacobian-consistency reading +if comm.rank() == 0: + print("RESULT " + json.dumps(dict( + nd=nd, nn=nn, kinds=kinds, pkinds=pkinds, declare=declare, all=allStrong, space=space, ranks=comm.size(), + h=1.0 / (nn - 1), nElements=nElements, + L2={k: v[0] for k, v in tot.items()}, H1={k: v[1] for k, v in tot.items()}, + faces=faces, forcedDofs=nForcedAll, forcedValueErr=forcedErr, + forceStrongConditions=bool(model.forceStrongConditions))), flush=True) + +if os.environ.get("DIAG") and comm.rank() == 0: + nodes = np.asarray(mesh.nodeArray) + pd = np.asarray(model.u[0].dof) + pe = p_f(*(nodes[:len(pd), i] for i in range(3))) + print("DIAG p_h - p_exact: min %g max %g ; corr(p_h, p_exact) %g ; lstsq p_h = a p_exact + b: %s" % ( + (pd - pe).min(), (pd - pe).max(), np.corrcoef(pd, pe)[0, 1], np.linalg.lstsq(np.c_[pe, np.ones_like(pe)], pd, rcond=None)[0])) + ud = np.asarray(model.u[1].dof) + print("DIAG u dofs: max %g ; exact range at nodes %g" % (abs(ud).max(), abs(u_f(*(nodes[:, i] for i in range(3)))).max())) diff --git a/test/test_rans2p_mixed_bc_mms.py b/test/test_rans2p_mixed_bc_mms.py new file mode 100644 index 0000000000..069a22e76f --- /dev/null +++ b/test/test_rans2p_mixed_bc_mms.py @@ -0,0 +1,165 @@ +"""Per-face strong | weak | none boundary kinds (C12) in RANS2P, 2D and 3D, on a manufactured Navier-Stokes solution. + +`rans2p_mixed_bc_mms_mpi.py` solves single phase Navier-Stokes (P1/P1 with the model's stabilization, nu = 0.1) on the unit +square or cube against a divergence-free manufactured field whose velocity on the wall x = 1 carries no stress, with a +DIFFERENT kind on each wall: the velocity is strong on the left and top (and back, in 3D), weak on the bottom (and front), and +declared open ('none') on the right, where the pressure is the weak datum. The exact solution is the data of every strong and +weak wall. + +* the mixed problem converges at the rates of the element (u: L2 2, H1 1; p: L2 about 1.6) and is as accurate as the all-weak one; +* a strong face gets no weak term from the flux class (no face point is both) and the dofs of the strong walls hold the data to + round-off (their rows are replaced, they stay unknowns); +* every face declared strong reproduces the legacy ``forceStrongDirichlet`` model bit for bit; a function that names no kind in + a declared setter stays weak, bit for bit the undeclared run; +* serial = 2 and 3 ranks (node and element partitions); +* ``forceStrongDirichlet`` together with a declared setter is refused. + +RANS2P's kernels have no kind flag of their own: they read ``isDOFBoundary`` per component, which ``kernelIsDOFBoundary`` fills with the +weak faces and the strong ones (the datum a strong face keeps imposing, as ``forceStrongDirichlet`` always did). +""" +import importlib.util +import json +import math +import os +import shutil +import sys + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("launch_output", os.path.join(HERE, "launch_output.py")) +launch_output = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(launch_output) + + +def _mpiexec(): + bindir = os.path.dirname(sys.executable) + for name in ("mpiexec", "mpirun"): + candidate = os.path.join(bindir, name) + if os.path.exists(candidate): + return candidate + return shutil.which("mpiexec") or shutil.which("mpirun") + + +MPIEXEC = _mpiexec() +MIXED2 = "left=strong,bottom=weak,top=strong,right=none" +MIXED3 = MIXED2 + ",front=weak,back=strong" +ALLWEAK2 = "left=weak,bottom=weak,top=weak,right=none" +ALLSTRONG2 = "left=strong,bottom=strong,top=strong,right=none" +ALLSTRONG3 = ALLSTRONG2 + ",front=strong,back=strong" +BARE2 = "left=bare,bottom=bare,top=bare,right=none" + + +def _run(tmp_path_factory, ranks=1, **case): + cwd = tmp_path_factory.mktemp("_".join("%s%s" % (k, str(v).replace("=", "").replace(",", "")) for k, v in sorted(case.items())) + "_r%d" % ranks) + env = dict(os.environ, OMP_NUM_THREADS="1") + env.setdefault("FI_PROVIDER", "tcp") + env.setdefault("OMPI_MCA_rmaps_base_oversubscribe", "1") + env.setdefault("PRTE_MCA_rmaps_default_mapping_policy", ":oversubscribe") + env["PYTHONPATH"] = os.pathsep.join([p for p in sys.path if p] + [env.get("PYTHONPATH", "")]).strip(os.pathsep) + env["PETSC_OPTIONS"] = "-mat_partitioning_type current" + env.update({k: str(v) for k, v in case.items()}) + script = os.path.join(HERE, "rans2p_mixed_bc_mms_mpi.py") + argv = [sys.executable, script] if ranks == 1 else [MPIEXEC, "-n", str(ranks), sys.executable, script] + out = launch_output.run(argv, cwd=cwd, env=env, timeout=1800) + results = [json.loads(line[len("RESULT "):]) for line in out.stdout.splitlines() if line.startswith("RESULT ")] + assert len(results) == 1, out.stdout[-2000:] + out.stderr[-2000:] + return results[0] + + +@pytest.fixture(scope="module") +def run(tmp_path_factory): + cache = {} + + def go(ranks=1, **case): + key = (ranks, tuple(sorted(case.items()))) + if key not in cache: + cache[key] = _run(tmp_path_factory, ranks, **case) + return cache[key] + return go + + +def _rate(a, b, ha, hb): + return math.log(a / b) / math.log(ha / hb) + + +def test_mixed_kinds_converge_at_the_rates_of_the_element_2d(run): + mid, fine = run(ND=2, NN=17, KINDS=MIXED2), run(ND=2, NN=33, KINDS=MIXED2) + for k in ("u0", "u1"): + assert _rate(mid["L2"][k], fine["L2"][k], mid["h"], fine["h"]) > 1.7, (mid, fine) + assert _rate(mid["H1"][k], fine["H1"][k], mid["h"], fine["h"]) > 0.9, (mid, fine) + assert _rate(mid["L2"]["p"], fine["L2"]["p"], mid["h"], fine["h"]) > 1.4, (mid, fine) + + +def test_the_mixed_problem_is_as_accurate_as_the_all_weak_one_2d(run): + mixed = run(ND=2, NN=33, KINDS=MIXED2) + weak = run(ND=2, NN=33, KINDS=ALLWEAK2) + for k in mixed["L2"]: + assert mixed["L2"][k] < 2.0 * weak["L2"][k] and mixed["H1"][k] < 1.5 * weak["H1"][k], (mixed, weak) + + +def test_a_strong_face_gets_no_weak_term_and_holds_the_data_2d(run): + r = run(ND=2, NN=17, KINDS=MIXED2) + for ci in ("1", "2"): # u and v + f = r["faces"][ci] + assert f["strong"] > 0 and f["weak"] > 0 and f["open"] > 0 and f["both"] == 0 + assert r["faces"]["0"]["weak"] > 0 and r["faces"]["0"]["strong"] == 0 # the pressure datum of the right wall + assert r["forcedDofs"] == 66 and r["forcedValueErr"] == 0.0 # 33 dofs of the left wall + 33 of the top, for u and v, corners shared + assert r["forceStrongConditions"] is True + + +def test_every_face_strong_is_the_legacy_force_strong_model_2d(run): + declared = run(ND=2, NN=17, KINDS=ALLSTRONG2, PKINDS="right=strong") + legacy = run(ND=2, NN=17, KINDS=ALLSTRONG2, PKINDS="right=strong", DECLARE=0, ALL="strong") + assert declared["L2"] == legacy["L2"] and declared["H1"] == legacy["H1"], (declared, legacy) + assert declared["forcedDofs"] == legacy["forcedDofs"] > 0 + + +def test_a_function_that_names_no_kind_stays_weak_exactly_2d(run): + bare = run(ND=2, NN=17, KINDS=BARE2, PKINDS="right=bare") + undeclared = run(ND=2, NN=17, KINDS=BARE2, PKINDS="right=bare", DECLARE=0) + assert bare["L2"] == undeclared["L2"] and bare["H1"] == undeclared["H1"], (bare, undeclared) + assert bare["forcedDofs"] == 0 and bare["faces"]["1"]["strong"] == 0 + + +@pytest.mark.parametrize("part", ["node", "element"]) +@pytest.mark.parametrize("ranks", [2, 3]) +def test_ranks_give_the_serial_errors_2d(run, part, ranks): + s = run(ND=2, NN=17, KINDS=MIXED2, PART_TYPE=part) + r = run(ranks=ranks, ND=2, NN=17, KINDS=MIXED2, PART_TYPE=part) + assert r["ranks"] == ranks + for q in ("L2", "H1"): + for k in s[q]: + assert abs(r[q][k] - s[q][k]) < 1.0e-9 * s[q][k], (q, k, s, r) + assert r["forcedValueErr"] == 0.0 + + +def test_mixed_kinds_converge_and_match_the_serial_run_in_3d(run): + coarse, fine = run(ND=3, NN=9, KINDS=MIXED3), run(ND=3, NN=17, KINDS=MIXED3) + for k in ("u0", "u1"): + assert _rate(coarse["L2"][k], fine["L2"][k], coarse["h"], fine["h"]) > 1.5, (coarse, fine) + assert _rate(coarse["H1"][k], fine["H1"][k], coarse["h"], fine["h"]) > 0.9, (coarse, fine) + assert _rate(coarse["L2"]["p"], fine["L2"]["p"], coarse["h"], fine["h"]) > 1.0, (coarse, fine) + weak = run(ND=3, NN=9, KINDS=ALLWEAK2 + ",front=weak,back=weak") + for k in coarse["L2"]: + assert coarse["L2"][k] < 2.0 * weak["L2"][k], (coarse, weak) + for ci in ("1", "2", "3"): + f = fine["faces"][ci] + assert f["strong"] > 0 and f["weak"] > 0 and f["open"] > 0 and f["both"] == 0 + two = run(ranks=2, ND=3, NN=9, KINDS=MIXED3) + for q in ("L2", "H1"): + for k in coarse[q]: + assert abs(two[q][k] - coarse[q][k]) < 1.0e-9 * coarse[q][k], (q, k, coarse, two) + assert two["forcedValueErr"] == 0.0 + + +def test_every_face_strong_is_the_legacy_force_strong_model_3d(run): + declared = run(ND=3, NN=5, KINDS=ALLSTRONG3, PKINDS="right=strong") + legacy = run(ND=3, NN=5, KINDS=ALLSTRONG3, PKINDS="right=strong", DECLARE=0, ALL="strong") + assert declared["L2"] == legacy["L2"] and declared["H1"] == legacy["H1"], (declared, legacy) + + +def test_force_strong_dirichlet_with_a_declared_setter_is_refused(tmp_path_factory): + with pytest.raises(AssertionError) as e: + _run(tmp_path_factory, ND=2, NN=5, KINDS=MIXED2, ALL="strong") + assert "forceStrongDirichlet makes every Dirichlet face strong" in str(e.value) From 9a796324c9d9da838e4e6ef26da84298aff474b9 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:26:05 -0600 Subject: [PATCH 13/17] RANS2P kinds: the constant-pressure null space follows a strong pressure datum; periodic dofs leave the forced rows Review of c9369a8e, two findings: 1. pp_hasConstantNullSpace tested `not forceStrongAllFaces`, so a declared problem with a strongly imposed pressure datum and u = 0 at the start got True where legacy forceStrongDirichlet gives False. Old behaviour, kept: legacy forceStrongDirichlet never declares the null space; every other problem (weak or no pressure datum) declares it while the velocity is zero. Now a declared setter whose pressure has a strong datum anywhere (collective over ranks, computed once in the constructor: hasStrongPressureDatum) gives False too; nothing else moves. 2. The declared branch did not remove the dofs of a periodic pair from dirichletConditionsForceDOF as OneLevelTransport does (Transport.py): copied the loop (periodicity wins over a Dirichlet value). Only the empty periodicDOFDict path is exercised by the tests (no periodic RANS2P case with a declared setter exists). Not done (nits): the declared branch is not gated on the flux class (RANS2P always builds its weak NavierStokes flux; the flux class refuses a 'weak' face under a class without a weak term); isStrongBoundary[3]/isOpenBoundary[3] in 2D are one-time copies of component 2, like the pre-existing isDOFBoundary[3]. Tests (14 now): the flag read at the first Jacobian (the driver records it; zero velocity): weak velocity + weak pressure datum True (declared and undeclared, the old behaviour), weak velocity + strong pressure datum False, legacy all-strong False, 2 ranks with the strong pressure datum False on both; a declared velocity setter with a bare undeclared pressure setter == the declared weak pressure run bit for bit (2D h 1/16: L2 p 1.2023600021764112e-2). Re-measured: the BC suite and every RANS2P user (same list as before + the new file): 1161 passed, 8 skipped, 0 failed (1159 + the 2 new tests); serial = 2 and 3 ranks to 3.3e-14 (test_ranks_give_the_serial_errors_2d, unchanged and green). Co-Authored-By: Claude Sonnet 5.5 --- proteus/kernels/RANS2P.py | 17 ++++++++++++++++- test/rans2p_mixed_bc_mms_mpi.py | 26 +++++++++++++++++++++----- test/test_rans2p_mixed_bc_mms.py | 20 ++++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/proteus/kernels/RANS2P.py b/proteus/kernels/RANS2P.py index 75a9c35f36..fdcae1cd7b 100644 --- a/proteus/kernels/RANS2P.py +++ b/proteus/kernels/RANS2P.py @@ -1711,6 +1711,7 @@ def __init__(self, # forceStrongDirichlet of the coefficients makes EVERY Dirichlet face strong; the kernels' isDOFBoundary then # carries all of them. A declared setter says per face instead (BoundaryKinds). self.forceStrongAllFaces = bool(self.forceStrongConditions) + self.hasStrongPressureDatum = False self.dirichletConditionsForceDOF = {} self.declaredBoundaryKinds = [BoundaryKinds.declaresKinds(dofBoundaryConditionsSetterDict.get(cj)) for cj in range(self.nc)] if any(self.declaredBoundaryKinds): @@ -1730,6 +1731,16 @@ def __init__(self, else: self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions( self.u[cj].femSpace, None, weakDirichletConditions=True) + # A DOF of a periodic pair is one unknown shared with its partner, and periodicity wins over a + # Dirichlet value there, as it does in OneLevelTransport (Transport.py) and where Dirichlet DOFs are + # eliminated. + for nodeSet in self.dirichletConditions[cj].periodicDOFDict.values(): + for dofN in nodeSet: + self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.pop(dofN, None) + self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict.pop(dofN, None) + # Whether the pressure is strongly imposed anywhere (collective: a rank may hold none of its dofs): the + # constant-pressure null space check in getJacobian reads it. + self.hasStrongPressureDatum = bool(globalMax(int(len(self.dirichletConditionsForceDOF[0].DOFBoundaryConditionsDict) > 0))) elif self.forceStrongConditions: for cj in range(self.nc): self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions( @@ -2540,7 +2551,11 @@ def getJacobian(self, jacobian): argsDict["isActiveElement_last"] = self.isActiveElement_last self.rans2p.calculateJacobian(argsDict) assert(np.all(np.isfinite(jacobian.getCSRrepresentation()[2]))) - if not self.forceStrongAllFaces and max(numpy.linalg.norm(self.u[1].dof, numpy.inf), numpy.linalg.norm(self.u[2].dof, numpy.inf), numpy.linalg.norm(self.u[3].dof, numpy.inf)) < 1.0e-8: + # Constant pressure is a null space of a problem whose velocity is zero and whose pressure is not imposed. Legacy: + # forceStrongDirichlet never declares it; otherwise (weak or no pressure datum: the old weak behaviour, kept) it + # is declared while the velocity is zero. A declared setter says per face: a strongly imposed pressure datum + # anywhere is what forceStrongDirichlet's False stood for, so it gives False too. + if not self.forceStrongAllFaces and not self.hasStrongPressureDatum and max(numpy.linalg.norm(self.u[1].dof, numpy.inf), numpy.linalg.norm(self.u[2].dof, numpy.inf), numpy.linalg.norm(self.u[3].dof, numpy.inf)) < 1.0e-8: self.pp_hasConstantNullSpace = True else: self.pp_hasConstantNullSpace = False diff --git a/test/rans2p_mixed_bc_mms_mpi.py b/test/rans2p_mixed_bc_mms_mpi.py index c45b9c13df..d0b5b8e8fc 100644 --- a/test/rans2p_mixed_bc_mms_mpi.py +++ b/test/rans2p_mixed_bc_mms_mpi.py @@ -16,7 +16,7 @@ wall carries the exact solution as its data. Environment: ND (2|3), NN (nodes per direction), NU, KINDS (velocity: ``left=strong,bottom=weak,...``; a wall that is not -named has no condition), PKINDS (pressure: the same), DECLARE (0: plain setters, the kinds are not read: every named wall is +named has no condition), PKINDS (pressure: the same), PDECLARE (0: the pressure setter is not declared while the velocity ones are), DECLARE (0: plain setters, the kinds are not read: every named wall is then weak, the baseline every existing problem is), ALL (strong: coefficients.forceStrongDirichlet, the legacy all-strong model), SPACE (p1p1: equal order with the model's stabilization, the decks' choice; p1p2: P2 velocity, which crashes RANS2P2D::calculateResidual on some meshes, not used by the tests), SGE (1: the subgrid error terms, 0: off), PART_TYPE, NLAYERS. @@ -89,7 +89,8 @@ def _xyz(x): _kind = {"strong": bk.strong, "weak": bk.weak} -def make_setter(table, fun): +def make_setter(table, fun, declared=None): + declared = declare if declared is None else declared data = lambda x, t: float(fun(*_xyz(x))) def setter(x, flag): @@ -102,7 +103,7 @@ def setter(x, flag): if k == "bare": return data return _kind[k](data) if declare else data - return bk.declare(setter) if declare else setter + return bk.declare(setter) if declared else setter o = domain.MeshOptions @@ -124,7 +125,7 @@ def setter(x, flag): force_y=lambda x: float(force_f[1](*_xyz(x))), force_z=(lambda x: float(force_f[2](*_xyz(x)))) if nd == 3 else None) p.initialConditions = {i: type("Zero", (), {"uOfXT": lambda self, x, t: 0.0})() for i in range(nd + 1)} -p.dirichletConditions = {0: make_setter(pkinds, p_f)} +p.dirichletConditions = {0: make_setter(pkinds, p_f, declared=declare and os.environ.get("PDECLARE", "1") == "1")} for i, fn in enumerate(vel_f): p.dirichletConditions[i + 1] = make_setter(kinds, fn) p.advectiveFluxBoundaryConditions = {} @@ -169,6 +170,20 @@ def setter(x, flag): so = defaults.System_base(name="rans2p_mixed_bc", pnList=[(p, n)], sList=[default_s]) so.tnList = [0.0, 1.0] ns = NumericalSolution.NS_base(so, [p], [n], so.sList, runtime.RunOptions()) +# the constant-pressure null space flag at the FIRST Jacobian (zero velocity: where it can be True); later ones see the solution +_model = ns.modelList[0].levelModelList[-1] +_firstNullSpace = [] +_getJacobian = _model.getJacobian + + +def _recordingGetJacobian(jacobian): + out = _getJacobian(jacobian) + if not _firstNullSpace: + _firstNullSpace.append(bool(_model.pp_hasConstantNullSpace)) + return out + + +_model.getJacobian = _recordingGetJacobian if os.environ.get("FAULT"): import faulthandler faulthandler.enable(all_threads=True) # replaces the PUMI signal handler, which prints no Python frames @@ -243,7 +258,8 @@ def errors(ci, exact, exact_grads): h=1.0 / (nn - 1), nElements=nElements, L2={k: v[0] for k, v in tot.items()}, H1={k: v[1] for k, v in tot.items()}, faces=faces, forcedDofs=nForcedAll, forcedValueErr=forcedErr, - forceStrongConditions=bool(model.forceStrongConditions))), flush=True) + forceStrongConditions=bool(model.forceStrongConditions), + nullSpaceAtFirstJacobian=_firstNullSpace[0])), flush=True) if os.environ.get("DIAG") and comm.rank() == 0: nodes = np.asarray(mesh.nodeArray) diff --git a/test/test_rans2p_mixed_bc_mms.py b/test/test_rans2p_mixed_bc_mms.py index 069a22e76f..c8d1de2b40 100644 --- a/test/test_rans2p_mixed_bc_mms.py +++ b/test/test_rans2p_mixed_bc_mms.py @@ -163,3 +163,23 @@ def test_force_strong_dirichlet_with_a_declared_setter_is_refused(tmp_path_facto with pytest.raises(AssertionError) as e: _run(tmp_path_factory, ND=2, NN=5, KINDS=MIXED2, ALL="strong") assert "forceStrongDirichlet makes every Dirichlet face strong" in str(e.value) + + +def test_a_declared_velocity_setter_with_a_bare_undeclared_pressure_setter_is_the_weak_pressure_2d(run): + undeclared_p = run(ND=2, NN=17, KINDS=MIXED2, PKINDS="right=bare", PDECLARE=0) + declared_weak_p = run(ND=2, NN=17, KINDS=MIXED2, PKINDS="right=weak") + assert undeclared_p["L2"] == declared_weak_p["L2"] and undeclared_p["H1"] == declared_weak_p["H1"], (undeclared_p, declared_weak_p) + assert undeclared_p["forcedDofs"] == declared_weak_p["forcedDofs"] > 0 and undeclared_p["faces"]["0"]["strong"] == 0 + + +def test_the_constant_pressure_null_space_flag_follows_a_strong_pressure_datum(run): + # read at the first Jacobian (zero velocity). Old behaviour, kept: forceStrongDirichlet never declares the null space; any + # other problem (a weak or absent pressure datum) declares it while the velocity is zero. A declared setter with a strongly + # imposed pressure datum is what forceStrongDirichlet's False stood for. + weak_vel = "left=weak,bottom=weak,top=weak,right=none" + assert run(ND=2, NN=9, KINDS=weak_vel, PKINDS="right=weak")["nullSpaceAtFirstJacobian"] is True + assert run(ND=2, NN=9, KINDS=weak_vel, PKINDS="right=weak", DECLARE=0)["nullSpaceAtFirstJacobian"] is True + assert run(ND=2, NN=9, KINDS=weak_vel, PKINDS="right=strong")["nullSpaceAtFirstJacobian"] is False + legacy = run(ND=2, NN=9, KINDS=ALLSTRONG2, PKINDS="right=strong", DECLARE=0, ALL="strong") + assert legacy["nullSpaceAtFirstJacobian"] is False + assert run(ranks=2, ND=2, NN=9, KINDS=weak_vel, PKINDS="right=strong")["nullSpaceAtFirstJacobian"] is False # collective: both ranks From 9dc2fe9d5ce648ca933fda9ba5f060941d9b5b1f Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:43:12 -0600 Subject: [PATCH 14/17] CI environments: keep conda-forge yaml below 0.2.6 (macOS import of petsc4py/pyyaml failed) conda-forge yaml 0.2.6 (build h602ebc4_0) ships lib/libyaml-0.1.dylib. pyyaml 6.0.3 (py312h05c94ff_4, built against yaml 0.2.5) and PETSc.abi3.so link @rpath/libyaml-0.2.dylib, so a freshly solved macOS env imports neither. On 2026-11-23 the self-hosted chewbacca-1/-2 legs of #344, #350 and #351 all failed at the Smoke test step with "Library not loaded: @rpath/libyaml-0.2.dylib" before any test ran. The three environment files now constrain `yaml >=0.2.5,<0.2.6`, written as a range so the off-lock legs' pin-to-floor rewrite (sdist.yml) leaves it alone. Measured: on chewbacca, `conda install -n proteus-dev yaml=0.2.5` restored libyaml-0.2.dylib, `yaml.__with_libyaml__` True and `import petsc4py` ok (host fix, already applied). Not measured here: the macOS CI legs with this pin (they run after this PR is pushed). Co-Authored-By: Claude Sonnet 5.5 --- environment-dev-up.yml | 4 ++++ environment-mpich-dev.yml | 4 ++++ environment-openmpi-dev.yml | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/environment-dev-up.yml b/environment-dev-up.yml index 838754af8a..acda5bab69 100644 --- a/environment-dev-up.yml +++ b/environment-dev-up.yml @@ -68,6 +68,10 @@ dependencies: # errors without it, because the pure-Python dumper is ~3.2x slower and the # archive is written every timestep. conda-forge's pyyaml is built with it. - pyyaml >=6.0.2 + # conda-forge yaml 0.2.6 ships libyaml-0.1.dylib, but pyyaml 6.0.3 and petsc4py are built against libyaml-0.2.dylib + # (yaml >=0.2.5,<0.3): on macOS a fresh solve gets 0.2.6 and `import petsc4py` fails with 'Library not loaded: + # @rpath/libyaml-0.2.dylib'. Written as a range so the off-lock legs' pin-to-floor rewrite leaves it alone. + - yaml >=0.2.5,<0.2.6 - sympy >=1.13.2 - strictyaml >=1.7.3 # provides `dot` for the docs inheritance diagrams diff --git a/environment-mpich-dev.yml b/environment-mpich-dev.yml index 73f9eb2a35..a0e5a2e55b 100644 --- a/environment-mpich-dev.yml +++ b/environment-mpich-dev.yml @@ -96,6 +96,10 @@ dependencies: # errors without it, because the pure-Python dumper is ~3.2x slower and the # archive is written every timestep. conda-forge's pyyaml is built with it. - pyyaml =6.0.2 + # conda-forge yaml 0.2.6 ships libyaml-0.1.dylib, but pyyaml 6.0.3 and petsc4py are built against libyaml-0.2.dylib + # (yaml >=0.2.5,<0.3): on macOS a fresh solve gets 0.2.6 and `import petsc4py` fails with 'Library not loaded: + # @rpath/libyaml-0.2.dylib'. Written as a range so the off-lock legs' pin-to-floor rewrite leaves it alone. + - yaml >=0.2.5,<0.2.6 # ymf itself has no conda-forge feedstock yet, so it is installed from PyPI # with pip, at a floor (not a moving git branch): ymf 0.3.0 at @main broke # main's test/dispatch for half a day on 2026-11-17/18 and every run that diff --git a/environment-openmpi-dev.yml b/environment-openmpi-dev.yml index 905b7ac41b..c75a41ab12 100644 --- a/environment-openmpi-dev.yml +++ b/environment-openmpi-dev.yml @@ -81,6 +81,10 @@ dependencies: # errors without it, because the pure-Python dumper is ~3.2x slower and the # archive is written every timestep. conda-forge's pyyaml is built with it. - pyyaml =6.0.2 + # conda-forge yaml 0.2.6 ships libyaml-0.1.dylib, but pyyaml 6.0.3 and petsc4py are built against libyaml-0.2.dylib + # (yaml >=0.2.5,<0.3): on macOS a fresh solve gets 0.2.6 and `import petsc4py` fails with 'Library not loaded: + # @rpath/libyaml-0.2.dylib'. Written as a range so the off-lock legs' pin-to-floor rewrite leaves it alone. + - yaml >=0.2.5,<0.2.6 # ymf itself has no conda-forge feedstock yet, so it is installed from PyPI # with pip, at a floor (not a moving git branch): ymf 0.3.0 at @main broke # main's test/dispatch for half a day on 2026-11-17/18 and every run that From 5866423c2d6f240ce31ec46e73debc4db785f8ec Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:57:16 -0600 Subject: [PATCH 15/17] coverage ratchet: floors for an aggregate (proteus/kernels/) and for single classes cekees decided 2026-11-22 that C49's kernels are floored as one aggregate and that the modules which moved into proteus/ (the gwvd step classes among them) are measured and floored individually, not inside it. The ratchet knew only modules. A floors.json key ending in "/" is now an aggregate over every module under it, a key :: is one class of a module (the report's lines between the class's first and last line, found by parsing the file under the report's source directory). Both are checked, raised by --write-floors and reported as no longer measured exactly like a module floor; the tables still list modules only. Checked on the real combined report of main 8b864938 (cekees/proteus run 45099441761, green): output identical to the old ratchet with the unchanged floors.json (rc 0, 150 modules, 65.8% of 91,735 statements); with test floors added the class numbers equal C49 R3's baseline table (NonConservativeBackwardEuler 65.1%, Fixed_dt_controller_systemit 92.0%, ISO_fixed_MinModelStep 97.1%) and proteus/kernels/ reads 75.7% of 31,319. test/test_coverage_ratchet.py (5 tests, new file): holds at the measured values; an aggregate drop with every module at its floor fails; a class drop fails; a class that is gone is reported; --write-floors raises a part only a point above and adds none. 3 of the 5 fail against the old ratchet. Co-Authored-By: Claude Sonnet 5.5 --- .github/coverage/ratchet.py | 76 +++++++++++++++++++++++----- test/test_coverage_ratchet.py | 93 +++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 11 deletions(-) create mode 100644 test/test_coverage_ratchet.py diff --git a/.github/coverage/ratchet.py b/.github/coverage/ratchet.py index 327dcd834c..c73b5ec782 100644 --- a/.github/coverage/ratchet.py +++ b/.github/coverage/ratchet.py @@ -19,12 +19,18 @@ -- the modules in the "at least a point above the floor" table -- so a floor never chases the tenths a run's MPI timing can move. Every other floor stays. +A floor can also name a part of the package instead of one module, for the code a decision measures on its own: +a key ending in "/" is an aggregate (``"proteus/kernels/"``: every module under it counted together, one number for +the kernel package), a key ``::`` is one class of a module (``"proteus/StepControl.py::Fixed_dt_controller_systemit"``: +the statements between the class's first and last line). They are checked and raised like a module's floor. + A floor may instead be a string: the module is measured and listed with that reason, but not checked (a module waiting for its first test, or one excluded until a campaign decides its fate). --write-floors leaves those entries as they are; turning one into a number is a reviewed edit. """ import argparse +import ast import json import math import os @@ -51,18 +57,62 @@ def module_name(filename, source=''): return path -def measure(report): - """{module: (statements, covered)} from a Cobertura report.""" - modules = {} +def read_report(report): + """({module: (statements, covered)}, {module: {line number: hits}}, source directory) from a Cobertura report.""" + modules, lines_of = {}, {} root = ET.parse(report).getroot() sources = [s.text or '' for s in root.iter('source')] source = sources[0] if len(sources) == 1 else '' for cls in root.iter('class'): - lines = [int(line.get('hits')) for line in cls.iter('line')] name = module_name(cls.get('filename'), source) + lines = {int(line.get('number')): int(line.get('hits')) for line in cls.iter('line')} statements, covered = modules.get(name, (0, 0)) - modules[name] = (statements + len(lines), covered + sum(1 for hits in lines if hits > 0)) - return modules + modules[name] = (statements + len(lines), covered + sum(1 for hits in lines.values() if hits > 0)) + lines_of.setdefault(name, {}).update(lines) + return modules, lines_of, source + + +def measure(report): + """{module: (statements, covered)} from a Cobertura report.""" + return read_report(report)[0] + + +def class_span(path, class_name): + """(first, last) line of a top-level class in a Python file, or None.""" + try: + with open(path) as f: + tree = ast.parse(f.read()) + except (OSError, SyntaxError): + return None + for node in tree.body: + if isinstance(node, ast.ClassDef) and node.name == class_name: + return node.lineno, node.end_lineno + return None + + +def parts(floors, modules, lines_of, source): + """{floor key: (statements, covered)} for the floors that name a part of the package (see the docstring): + an aggregate ("proteus/kernels/") or one class ("proteus/StepControl.py::Fixed_dt_controller_systemit"). + A part that cannot be found is left out, so it is reported as a floor for something no longer measured.""" + found = {} + for key in floors: + if key.endswith('/'): + members = [v for name, v in modules.items() if name.startswith(key)] + if members: + found[key] = (sum(s for s, _ in members), sum(c for _, c in members)) + elif '::' in key: + module, _, class_name = key.partition('::') + if module not in lines_of: + continue + # the report's file names are relative to its (a combined report) or absolute (one run's) + path = os.path.join(source, module[len('proteus/'):]) if source else module + span = class_span(path, class_name) + if span is None: + continue + lines = [h for n, h in lines_of[module].items() if span[0] <= n <= span[1]] + if lines: + found[key] = (len(lines), sum(1 for h in lines if h > 0)) + return found def percent(statements, covered): @@ -160,21 +210,25 @@ def main(argv=None): parser.add_argument('--partial', action='store_true') parser.add_argument('--write-floors', action='store_true') args = parser.parse_args(argv) - modules = measure(args.report) + modules, lines_of, source = read_report(args.report) floors = {} if os.path.exists(args.floors): with open(args.floors) as f: floors = json.load(f) - drops, rises, new, unchecked, gone = compare(modules, floors) + # the floors of parts (aggregates, classes) are checked beside the modules'; the tables list modules only + named = parts(floors, modules, lines_of, source) + drops, rises, new, unchecked, gone = compare({**modules, **named}, floors) + new = [n for n in new if n[0] in modules] sys.stdout.write(tables(modules, drops, rises, new, unchecked, gone, args.partial)) # a report whose module names do not match the floors' checks nothing, and would pass - if floors and not args.write_floors and len(set(floors) & set(modules)) < len(floors) // 2: + module_floors = [k for k in floors if not (k.endswith('/') or '::' in k)] + if module_floors and not args.write_floors and len(set(module_floors) & set(modules)) < len(module_floors) // 2: sys.stderr.write('only %d of %d floors name a module in this report (first module: %s): ' 'the report and the floors disagree about module names\n' - % (len(set(floors) & set(modules)), len(floors), min(modules) if modules else 'none')) + % (len(set(module_floors) & set(modules)), len(module_floors), min(modules) if modules else 'none')) return 1 if args.write_floors: - write_floors(args.floors, modules, floors) + write_floors(args.floors, {**modules, **named}, floors) return 0 if drops: sys.stderr.write('%d module(s) below their coverage floor: %s\n' diff --git a/test/test_coverage_ratchet.py b/test/test_coverage_ratchet.py new file mode 100644 index 0000000000..e70e703d62 --- /dev/null +++ b/test/test_coverage_ratchet.py @@ -0,0 +1,93 @@ +"""The coverage ratchet (.github/coverage/ratchet.py) checks parts of the package, not only modules. + +A floor whose key ends in "/" is an aggregate (every module under it, counted together), a key +``::`` is one class of a module. Both are checked like a module's floor: below it +(by more than the tolerance) fails the run, a class or a package that cannot be found is reported +as no longer measured. Built here on a small Cobertura report and a two-class module, so the +branches that the real report exercises only partly (a drop in an aggregate, a class that moved) +are pinned. +""" +import importlib.util +import json +import os +import textwrap + +import pytest + +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RATCHET = os.path.join(REPO_ROOT, ".github", "coverage", "ratchet.py") +if not os.path.exists(RATCHET): # an installed package's tests run without the CI directory + pytest.skip("the checkout has no .github/coverage/ratchet.py", allow_module_level=True) + +spec = importlib.util.spec_from_file_location("ratchet_under_test", RATCHET) +ratchet = importlib.util.module_from_spec(spec) +spec.loader.exec_module(ratchet) + +# Steps.py: class Fast on lines 3-203 (200 statements), class Slow on lines 205-405 (200 statements). The units are +# this large because a small one is allowed to sit two statements under its floor, which is a large share of it. +STEPS = "import os\n\nclass Fast:\n" + " pass\n" * 200 + "\nclass Slow:\n" + " pass\n" * 200 + + +def report(tmp_path, kernels_hits): + """A combined report: proteus/Steps.py (Fast fully covered, Slow not) and two files under proteus/kernels/.""" + src = tmp_path / "proteus" + (src / "kernels").mkdir(parents=True) + (src / "Steps.py").write_text(STEPS) + lines = lambda numbers, hits: "".join('' % (n, hits(n)) for n in numbers) + steps = lines(range(4, 204), lambda n: 1) + lines(range(206, 406), lambda n: 0) + k1 = lines(range(1, 201), lambda n: kernels_hits if n <= 100 else 1) # 200 of 200, or 100 of 200 + k2 = lines(range(1, 201), lambda n: 1 if n <= 100 else 0) # 100 of 200 + xml = ('%s' + '%s' + '%s' + '%s' + '' % (src, steps, k1, k2)) + path = tmp_path / "coverage.xml" + path.write_text(xml) + return str(path) + + +def run(tmp_path, floors, kernels_hits=1, extra=()): + floors_path = tmp_path / "floors.json" + floors_path.write_text(json.dumps(floors)) + return ratchet.main([report(tmp_path, kernels_hits), str(floors_path), *extra]), floors_path + + +def test_an_aggregate_and_a_class_floor_hold_at_the_measured_values(tmp_path, capsys): + # kernels: 300 of 400 statements = 75.0%; Fast 200 of 200; Slow 0 of 200 + rc, _ = run(tmp_path, {"proteus/kernels/": 75.0, "proteus/Steps.py::Fast": 100.0, "proteus/Steps.py::Slow": 0.0, + "proteus/Steps.py": 50.0, "proteus/kernels/A.py": 100.0, "proteus/kernels/B.py": 50.0}) + assert rc == 0, capsys.readouterr().out + + +def test_an_aggregate_below_its_floor_fails_though_every_module_holds_its_own(tmp_path, capsys): + # A.py drops from 200 to 100 covered statements (50%, its floor): the aggregate falls from 75% to 50% + rc, _ = run(tmp_path, {"proteus/kernels/": 70.0, "proteus/kernels/A.py": 50.0, "proteus/kernels/B.py": 50.0, + "proteus/Steps.py": 50.0}, kernels_hits=0) + out = capsys.readouterr() + assert rc == 1 + assert "`proteus/kernels/`" in out.out + + +def test_a_class_below_its_floor_fails_and_its_neighbour_is_not_counted(tmp_path, capsys): + # Slow is at 0%; a floor of 60 on it fails, while the module as a whole (200 of 400 = 50%) holds its own floor + rc, _ = run(tmp_path, {"proteus/Steps.py": 50.0, "proteus/Steps.py::Slow": 60.0, "proteus/Steps.py::Fast": 100.0}) + out = capsys.readouterr() + assert rc == 1 + assert "proteus/Steps.py::Slow" in out.out and "proteus/Steps.py::Fast" not in out.out.split("Below the recorded floor")[1].split("###")[0] + + +def test_a_class_that_is_gone_is_reported_not_failed(tmp_path, capsys): + rc, _ = run(tmp_path, {"proteus/Steps.py": 50.0, "proteus/Steps.py::Renamed": 100.0}) + assert rc == 0 + assert "Floors for modules no longer measured" in capsys.readouterr().out + + +def test_write_floors_raises_a_part_only_when_it_is_a_point_above_and_adds_no_new_one(tmp_path): + rc, floors_path = run(tmp_path, {"proteus/kernels/": 70.0, "proteus/Steps.py::Fast": 99.5, + "proteus/Steps.py": 50.0}, extra=("--write-floors",)) + assert rc == 0 + written = json.loads(floors_path.read_text()) + assert written["proteus/kernels/"] == 75.0 # 5 points above: raised + assert written["proteus/Steps.py::Fast"] == 99.5 # half a point above: kept + assert "proteus/Steps.py::Slow" not in written # a part has a floor only when someone writes one From ab9fb08c3530b4b95b3624051d956c089cbea32d Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:57:39 -0600 Subject: [PATCH 16/17] coverage floors: SpatialTools 56.0 -> 57.0, mbd/BodyDynamics 52.2 -> 58.9 (main 8b864938) The four modules that moved into proteus/ are floored individually (cekees 2026-11-22). Measured on the real combined report of main 8b864938 (cekees/proteus run 45099441761, all legs and the coverage job green; recorded with the ratchet's own --write-floors, only these two of its changes taken): | module | statements | old floor | main 8b864938 | new floor | |---|---:|---:|---:|---:| | SpatialTools.py | 1,943 | 56.0 | 57.1 | 57.0 | | mbd/BodyDynamics.py | 817 | 52.2 | 59.0 | 58.9 | | BoundaryConditions.py (Cython-traced) | 1,001 | 70.7 | 70.7 | 70.7 (unchanged) | | MoveMeshMonitor.py | 305 | 65.9 | 65.9 | 65.9 (unchanged) | --write-floors on the same report would also raise ~90 other floors (StepControl, TimeIntegration, SplitOperator among them); those are not touched here. Ratchet on the report with this floors.json: rc 0, no drop. Co-Authored-By: Claude Sonnet 5.5 --- .github/coverage/floors.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/coverage/floors.json b/.github/coverage/floors.json index 65f2ef4a3c..4fea43bea0 100644 --- a/.github/coverage/floors.json +++ b/.github/coverage/floors.json @@ -40,7 +40,7 @@ "proteus/SWFlow/utils/SWEs_so.py": 0.0, "proteus/ShockCapturing.py": 36.1, "proteus/SimTools.py": 11.9, - "proteus/SpatialTools.py": 56.0, + "proteus/SpatialTools.py": 57.0, "proteus/SplitOperator.py": 46.1, "proteus/StepControl.py": 36.0, "proteus/SubgridError.py": 19.6, @@ -134,7 +134,7 @@ "proteus/kernels/__init__.py": 100.0, "proteus/kernels/beamFEM.py": 9.2, "proteus/kernels/m_comp_co2.py": "test pending (deck from Arnob; not legacy, #1282)", - "proteus/mbd/BodyDynamics.py": 52.2, + "proteus/mbd/BodyDynamics.py": 58.9, "proteus/petsc_optional.py": 91.6, "proteus/runtime.py": 100.0 } From 6f174e033abbe249aaacbb90b1f1b282eda7c48e Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:52:19 -0600 Subject: [PATCH 17/17] coverage floors: proteus/kernels aggregate 80.0 and the three gwvd step classes at 100.0 Measured on the coverage leg of dev push run 45359350052 (dev e50b0524, after #350 and #344): proteus/kernels/ 80.3% of 31,319 statements (main 8b864938 had 75.72%, run 45099441761). Floor 80.0 leaves 0.3 points under the tolerance (max(0.5 pp, 2 statements)). The ratchet on that report with the new floors exits 0; with the kernels floor at 90.0 it exits 1 naming proteus/kernels/ (80.3%), so the aggregate key is evaluated. The three class floors (StepControl Fixed_dt_controller_systemit, SplitOperator ISO_fixed_MinModelStep, TimeIntegration NonConservativeBackwardEuler) are at 100.0, as #350's tests cover them completely. Only these four keys change; no other floor is rewritten. Co-Authored-By: Claude Sonnet 5.5 --- .github/coverage/floors.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/coverage/floors.json b/.github/coverage/floors.json index 4fea43bea0..39b55e6ab0 100644 --- a/.github/coverage/floors.json +++ b/.github/coverage/floors.json @@ -42,10 +42,13 @@ "proteus/SimTools.py": 11.9, "proteus/SpatialTools.py": 57.0, "proteus/SplitOperator.py": 46.1, + "proteus/SplitOperator.py::ISO_fixed_MinModelStep": 100.0, "proteus/StepControl.py": 36.0, + "proteus/StepControl.py::Fixed_dt_controller_systemit": 100.0, "proteus/SubgridError.py": 19.6, "proteus/SubsurfaceTransportCoefficients.py": 18.6, "proteus/TimeIntegration.py": 22.6, + "proteus/TimeIntegration.py::NonConservativeBackwardEuler": 100.0, "proteus/Transport.py": 63.4, "proteus/TransportCoefficients.py": 18.1, "proteus/TwoPhaseFlow/TwoPhaseFlowProblem.py": 94.6, @@ -101,6 +104,7 @@ "proteus/defaults.py": 88.8, "proteus/deim_utils.py": 60.4, "proteus/iproteus.py": 76.9, + "proteus/kernels/": 80.0, "proteus/kernels/ADR.py": 90.6, "proteus/kernels/AddedMass.py": 76.2, "proteus/kernels/ArchiveBeams.py": 7.8,