diff --git a/.github/coverage/floors.json b/.github/coverage/floors.json index 65f2ef4a3c..39b55e6ab0 100644 --- a/.github/coverage/floors.json +++ b/.github/coverage/floors.json @@ -40,12 +40,15 @@ "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/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, @@ -134,7 +138,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 } 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/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 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/proteus/cli/run.py b/proteus/cli/run.py index 425e144d4d..61541d9b3a 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 @@ -316,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/proteus/kernels/RANS2P.py b/proteus/kernels/RANS2P.py index fb6a4f81ff..fdcae1cd7b 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,40 @@ 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.hasStrongPressureDatum = False 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) + # 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( self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False) @@ -1735,6 +1773,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 +1842,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 +2101,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 +2477,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 +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.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: + # 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/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)]) 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" 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 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]) 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/rans2p_mixed_bc_mms_mpi.py b/test/rans2p_mixed_bc_mms_mpi.py new file mode 100644 index 0000000000..d0b5b8e8fc --- /dev/null +++ b/test/rans2p_mixed_bc_mms_mpi.py @@ -0,0 +1,271 @@ +#!/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), 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. +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, declared=None): + declared = declare if declared is None else declared + 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 declared 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, 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 = {} +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()) +# 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 +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), + nullSpaceAtFirstJacobian=_firstNullSpace[0])), 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/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/sw2dcv_flags_mpi.py b/test/sw2dcv_flags_mpi.py new file mode 100644 index 0000000000..3a2caa388c --- /dev/null +++ b/test/sw2dcv_flags_mpi.py @@ -0,0 +1,110 @@ +#!/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, 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). +""" +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", + "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" + "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)) + 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=%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_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 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") diff --git a/test/test_pro_cli.py b/test/test_pro_cli.py index 02650c4b92..11a72f070c 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("""\ @@ -211,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" @@ -1156,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) diff --git a/test/test_rans2p_mixed_bc_mms.py b/test/test_rans2p_mixed_bc_mms.py new file mode 100644 index 0000000000..c8d1de2b40 --- /dev/null +++ b/test/test_rans2p_mixed_bc_mms.py @@ -0,0 +1,185 @@ +"""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) + + +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 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) diff --git a/test/test_sw2dcv_flags.py b/test/test_sw2dcv_flags.py new file mode 100644 index 0000000000..a10ece064b --- /dev/null +++ b/test/test_sw2dcv_flags.py @@ -0,0 +1,115 @@ +"""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, 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: + +- 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, 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; +- (serial, SWEs and GN) ``getJacobian`` is the mass matrix of every unknown: symmetric, total nc times the area. +""" +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", "consistent", "gn", "gn_consistent"] +DIFFERS = ["low_order_only", "no_relaxation", "linear_friction", "tailwater", "drag_law", "consistent", "gn"] +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 + + +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 + + +@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 + + +@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"]