From 380789aa54ddb5d97f751ff8574376c53b3d69c6 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:18:36 +0100 Subject: [PATCH 1/7] Stabilization and shock capturing as data a generator and a dispatcher read (C42 round 5, 1/5) A sub-problem (or its split discretization's entry, as the default of its sub-problems) now states `stabilization` as a method word or a block: method, tau (metric | element_size), lagged (the subgrid error from the previous step) and shock_capturing {factor, beta, reference, lagged} or `none`. The keys proteus's Dispatch already reads (lag, sc_beta, sc_uref) are aliases of ymf's words (lagged, beta, reference), as round 3 did for vbdf and mannings. Nothing is defaulted: an unstated key is the solver's own default, and `ymf.stabilization.missing()` lists what a reader that must not guess (the generator) still needs. What the generator can now express: VOF and NCLS (proteus#298) took `STAB = {SUPG, tau metric, shock_capturing lagged}` from a declaration in make_inputs.py because dambreak.ymf stated none; dambreak_formulation.ymf states it for all four sub-problems that have one, with the values DispatchTable uses (RANS2P ASGS subgrid-lagged, shock 0.5 lagged; VOF and NCLS SUPG 0.5, beta 1.5, reference 1.0, lagged; RDLS SUPG 0.9 not lagged), and `split_problem` carries the resolved block in each sub-problem's record. Tests (29 new, whole suite 904 -> 933 passed, 13 skipped): resolve normalization and aliases, 16 refusals (unknown method, beta outside [1, 2], a word and its alias together, a key a method does not read, ...), `missing`, the dam break states what the dispatcher assumed and what the generator spike declared by hand, an entry default is replaced whole by a sub-problem's block, a bad value is refused on load naming its path, the strict schema refuses an unknown key, and the block survives the archive with the same input digest (and a changed value changes the digest). Co-Authored-By: Claude Sonnet 5.5 --- src/ymf/schema.py | 30 ++- src/ymf/stabilization.py | 214 ++++++++++++++++++ src/ymf/symbolic/split.py | 6 +- src/ymf/vocabulary.py | 49 +++- tests/_formulation.py | 30 +++ .../two_phase/dambreak_formulation.ymf | 38 ++++ tests/test_stabilization.py | 191 ++++++++++++++++ 7 files changed, 546 insertions(+), 12 deletions(-) create mode 100644 src/ymf/stabilization.py create mode 100644 tests/_formulation.py create mode 100644 tests/fixtures/two_phase/dambreak_formulation.ymf create mode 100644 tests/test_stabilization.py diff --git a/src/ymf/schema.py b/src/ymf/schema.py index aa53790..c1a4811 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -96,6 +96,32 @@ } ) +# A stabilization: the method alone (``SUPG``) or a block (ymf.stabilization, +# checked on load): its length scale, the lag of its subgrid error, and the +# shock-capturing viscosity with its parameters (or ``none``, stated). +ShockCapturingDef = Str() | Map( + { + Optional("factor"): Float(), + Optional("beta"): Float(), + Optional("reference"): Float(), + Optional("lagged"): Bool(), + # the older spellings proteus's dispatcher reads (ymf.vocabulary.ALIASES) + Optional("lag"): Bool(), + Optional("sc_beta"): Float(), + Optional("sc_uref"): Float(), + } +) + +StabilizationDef = Str() | Map( + { + "method": Str(), + Optional("tau"): Str(), + Optional("lagged"): Bool(), + Optional("lag"): Bool(), + Optional("shock_capturing"): ShockCapturingDef, + } +) + FiniteElementDef = Map( { Optional("velocity"): SpaceDef, @@ -211,7 +237,7 @@ Optional("regularize"): MapPattern(Str(), RegularizeDef), Optional("finite_element"): FiniteElementDef, Optional("time_integration"): Str(), - Optional("stabilization"): Any(), + Optional("stabilization"): StabilizationDef, Optional("solver"): SolverConfig, # options a dispatcher cannot infer yet, for one solver: an interim hint # it checks against what it infers, and drops once it covers them @@ -230,6 +256,8 @@ Optional("from_weak_form"): Str(), Optional("finite_element"): FiniteElementDef, Optional("discretization"): Any(), + # with sub-problems, the default of each one's stabilization + Optional("stabilization"): StabilizationDef, # with sub-problems, the default each one's own solver: refines "solver": SolverConfig, # split into sub-problems, solved in this order each step diff --git a/src/ymf/stabilization.py b/src/ymf/stabilization.py new file mode 100644 index 0000000..8caab2c --- /dev/null +++ b/src/ymf/stabilization.py @@ -0,0 +1,214 @@ +"""What a ``stabilization`` entry says: the method, its length scale, and the shock-capturing viscosity with its parameters. + +A sub-problem (or a split discretization's entry, as the default of its sub-problems) states its stabilization as a word +or as a block:: + + stabilization: SUPG # the method alone + stabilization: + method: SUPG + tau: metric # the length scale: the element metric G (proteus useMetrics 1) or the size h (0) + lagged: false # the subgrid (tau) error taken from the previous step (SubgridError lag) + shock_capturing: + factor: 0.5 # the shock-capturing viscosity's coefficient (shockCapturingFactor, sc_c) + beta: 1.5 # the exponent of the gradient it is scaled by (sc_beta; 1 = classical) + reference: 1.0 # the reference value of the unknown (sc_uref) + lagged: true # the viscosity taken from the previous step (ShockCapturing lag) + stabilization: {method: SUPG, shock_capturing: none} # none, stated: the solver adds no shock capturing + +What it is for. The generator (C19) turned VOF and NCLS into a functor each, but the SUPG tau, the shock capturing and +their lag are the engine template's, and the template took them from the model's name (``dambreak.ymf`` stated none: the +generator spike's ``STAB`` was declared in ``make_inputs.py``). A spec that states them lets the engine read them. + +The words are checked on load (:func:`check`, called by ``ymf.vocabulary``); :func:`resolve` normalizes a block (the +alias ``shock_capturing`` of the method word becomes ``residual_shock_capturing``, and the keys proteus's dispatcher +already reads become ymf's: ``lag`` -> ``lagged``, ``sc_beta`` -> ``beta``, ``sc_uref`` -> ``reference``; the bare word +becomes a block) and adds nothing: **a key the spec does not state stays unstated**, because the value a solver uses then is its own default +(``proteus.DispatchTable``'s cells), and two defaults, one in ymf and one in the solver, would be two meanings. +:func:`missing` lists what a reader that must not guess (the generator) still needs stated. + +Which keys a method takes: + +* ``SUPG``, ``ASGS``: ``tau``, ``lagged``, ``shock_capturing`` (the residual-based viscosity added to the method). +* ``residual_shock_capturing``: the shock-capturing viscosity alone: ``tau``, ``shock_capturing`` (its block says how much; + unstated, the solver's own coefficient applies). +* ``entropy_viscosity``, ``graph_viscosity_smoothness``, ``graph_viscosity_entropy_residual``: no keys here. Their + parameters (the entropy-viscosity coefficient, the lumped mass) are the scheme's options in the ``discretization:`` block. + +Stdlib only, like the rest of the spec core. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from ymf.vocabulary import SHOCK_CAPTURING_KEYS, TAU_FORMS, VocabularyError, canonical + +__all__ = ["StabilizationError", "TAU_FORMS", "TAKES", "SHOCK_CAPTURING_KEYS", "resolve", "check", "for_subproblem", "missing", + "generator_needs"] + + +class StabilizationError(ValueError): + """A stabilization a spec states that does not make sense.""" + + +#: method -> the keys of the block it reads (beside ``method``) +TAKES: Dict[str, tuple] = { + "SUPG": ("tau", "lagged", "shock_capturing"), + "ASGS": ("tau", "lagged", "shock_capturing"), + "residual_shock_capturing": ("tau", "shock_capturing"), + "entropy_viscosity": (), + "graph_viscosity_smoothness": (), + "graph_viscosity_entropy_residual": (), +} + +def _number(value: Any, where: str) -> float: + try: + return float(value) + except (TypeError, ValueError): + raise StabilizationError("%s: %r is not a number" % (where, value)) from None + + +def _bool(value: Any, where: str) -> bool: + if isinstance(value, bool): + return value + if str(value).lower() in ("true", "1"): + return True + if str(value).lower() in ("false", "0"): + return False + raise StabilizationError("%s: %r is not true or false" % (where, value)) + + +def _word(kind: str, word: Any, where: str) -> str: + try: + return canonical(kind, word) + except VocabularyError as exc: + raise StabilizationError("%s: %s" % (where, exc)) from None + + +def _method(word: Any, where: str) -> str: + return _word("stabilization", word, where) + + +def _keys(block: Dict[str, Any], kind: str, where: str) -> Dict[str, Any]: + """The block with its keys in ymf's words; a word and its alias together are refused.""" + out: Dict[str, Any] = {} + for key, value in block.items(): + try: + word = canonical(kind, key) + except VocabularyError: + word = key # not a word of the kind: the caller names what it reads + if word in out: + raise StabilizationError("%s: %s is stated twice (%s is the old spelling of %s)" + % (where, word, key if key != word else "an alias", word)) + out[word] = value + return out + + +def _shock_capturing(block: Any, where: str) -> Optional[Dict[str, Any]]: + if isinstance(block, str): + if block != "none": + raise StabilizationError("%s: %r is not a block; say none, or give factor, beta, reference, lagged" + % (where, block)) + return None + if not isinstance(block, dict): + raise StabilizationError("%s: a block of factor, beta, reference, lagged, or none" % (where,)) + block = _keys(block, "shock_capturing_key", where) + unknown = sorted(set(block) - set(SHOCK_CAPTURING_KEYS)) + if unknown: + raise StabilizationError("%s: no key %s in shock_capturing; its keys are %s" + % (where, ", ".join(unknown), ", ".join(SHOCK_CAPTURING_KEYS))) + if "factor" not in block: + raise StabilizationError("%s: factor is required (a block that states none says none)" % (where,)) + out: Dict[str, Any] = {} + out["factor"] = _number(block["factor"], where + ".factor") + if out["factor"] < 0: + raise StabilizationError("%s.factor: %g is negative" % (where, out["factor"])) + if "beta" in block: + out["beta"] = _number(block["beta"], where + ".beta") + if not 1.0 <= out["beta"] <= 2.0: + raise StabilizationError("%s.beta: %g is outside [1, 2] (1 is the classical scaling by |grad u|, " + "2 makes the viscosity independent of it)" % (where, out["beta"])) + if "reference" in block: + out["reference"] = _number(block["reference"], where + ".reference") + if out["reference"] <= 0: + raise StabilizationError("%s.reference: %g is not positive" % (where, out["reference"])) + if "lagged" in block: + out["lagged"] = _bool(block["lagged"], where + ".lagged") + return out + + +def resolve(block: Any, where: str = "stabilization") -> Dict[str, Any]: + """The stabilization as a block with ymf's words and every stated key kept: ``{method, tau?, lagged?, + shock_capturing?}``, ``shock_capturing`` a dict, or ``None`` when the spec says ``none``. Nothing is added. + Raises :class:`StabilizationError`.""" + if isinstance(block, str): + block = {"method": block} + if not isinstance(block, dict) or "method" not in block: + raise StabilizationError("%s: say the method (stabilization: SUPG), or give a block with method:" % (where,)) + block = _keys(block, "stabilization_key", where) + method = _method(block["method"], where + ".method") + takes = TAKES[method] + unread = sorted(set(block) - {"method"} - set(takes)) + if unread: + raise StabilizationError( + "%s: %s does not read %s; %s" % ( + where, method, ", ".join(unread), + ("its keys are method, " + ", ".join(takes)) if takes else + "it has no keys here (its parameters are the scheme's options in the discretization: block)")) + out: Dict[str, Any] = {"method": method} + if "tau" in block: + tau = str(block["tau"]) + if tau not in TAU_FORMS: + raise StabilizationError("%s.tau: %s is not one of %s" % (where, tau, ", ".join(TAU_FORMS))) + out["tau"] = tau + if "lagged" in block: + out["lagged"] = _bool(block["lagged"], where + ".lagged") + if "shock_capturing" in block: + out["shock_capturing"] = _shock_capturing(block["shock_capturing"], where + ".shock_capturing") + return out + + +def check(block: Any, where: str = "stabilization") -> Dict[str, Any]: + """:func:`resolve`, under the name vocabulary checks use.""" + return resolve(block, where) + + +def for_subproblem(entry: Dict[str, Any], sub: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """A sub-problem's resolved stabilization: its own block, or else its entry's (the default of every sub-problem + of the entry); a sub-problem that states one replaces the entry's whole, key by key merging would make two + blocks say a third thing. None when neither states one.""" + block = sub.get("stabilization") + if block is None: + block = entry.get("stabilization") + if block is None: + return None + return resolve(block, "sub-problem %s stabilization" % (sub.get("name", "?"),)) + + +def missing(block: Any) -> List[str]: + """The keys a reader that must not fall back on a default still needs, as dotted names: what + :func:`generator_needs` asks for, less what the block states. ``[]`` if it is complete.""" + r = resolve(block) + return [need for need in generator_needs(r["method"], r) if not _has(r, need)] + + +def generator_needs(method: str, resolved: Optional[Dict[str, Any]] = None) -> List[str]: + """What the kernel generator reads of a stabilization of ``method``: ``tau`` (and ``lagged`` for SUPG and ASGS), + and the shock-capturing block's four keys (or its explicit ``none``).""" + takes = TAKES[method] + needs = [k for k in ("tau", "lagged") if k in takes] + if "shock_capturing" in takes: + sc = (resolved or {}).get("shock_capturing", "unstated") + needs.append("shock_capturing") + if isinstance(sc, dict): + needs += ["shock_capturing." + k for k in SHOCK_CAPTURING_KEYS] + return needs + + +def _has(resolved: Dict[str, Any], dotted: str) -> bool: + here: Any = resolved + for part in dotted.split("."): + if not isinstance(here, dict) or part not in here: + return False + here = here[part] + return True diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index 31fba24..bd2302a 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -32,6 +32,7 @@ import sympy +from ymf.stabilization import for_subproblem from ymf.symbolic.adr import adr_form, to_code from ymf.symbolic.language import Space, SymbolicError, parse_equation, parse_expression @@ -132,9 +133,12 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: bound = _bind(sub.get("binds") or {}, entry_bound, dim, where + " binds") record: Dict[str, Any] = {"name": sub["name"]} for key in ("solves", "enforces", "writes_back", "pseudo_time", "spin_up", - "finite_element", "time_integration", "stabilization", "proteus"): + "finite_element", "time_integration", "proteus"): if key in sub: record[key] = sub[key] + stabilization = for_subproblem(entry, sub) + if stabilization is not None: + record["stabilization"] = stabilization record["solver"] = subproblem_solver(entry, sub) # its unknowns, and the text of every equation it classifies diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index 4730917..6ff8b71 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -40,7 +40,8 @@ import re from typing import Any, Dict, Iterable, List, Optional -__all__ = ["FAMILIES", "ROLES", "TIME_INTEGRATION", "STABILIZATION", "SCHEMES", +__all__ = ["FAMILIES", "ROLES", "TIME_INTEGRATION", "STABILIZATION", "TAU_FORMS", "STABILIZATION_KEYS", + "SHOCK_CAPTURING_KEYS", "SCHEMES", "STEP_CONTROL", "REGULARIZATIONS", "BINDING_MEANINGS", "WRITES_BACK", "INERTIA_FORMS", "LINEAR_SOLVERS", "COEFFICIENT_ROLES", "ALIASES", "canonical", "family_of", "role_of", "roles_of", "linear_solver_kind", @@ -260,6 +261,28 @@ def roles_of(doc: Dict[str, Any], entry: Dict[str, Any]) -> Dict[str, Optional[s "graph_viscosity_entropy_residual": "graph viscosity scaled by the entropy residual", } +#: the length scale of the stabilization (a sub-problem's ``stabilization.tau``) +TAU_FORMS: Dict[str, str] = { + "metric": "the element metric G (the inverse of the element's map, squared): " + "tau = 1/sqrt(4 dm_t² + a·G a + ...); proteus useMetrics = 1", + "element_size": "the element size h: tau = 1/sqrt(4 dm_t² + (2|a|/h)² + ...); proteus useMetrics = 0", +} + +#: the keys of a ``stabilization`` block beside ``method`` (ymf.stabilization says which method reads which) +STABILIZATION_KEYS: Dict[str, str] = { + "tau": "the length scale, a TAU_FORMS word", + "lagged": "the subgrid (tau) error is taken from the previous step (proteus SubgridError lag)", + "shock_capturing": "the residual-based shock-capturing viscosity: a block of SHOCK_CAPTURING_KEYS, or none", +} + +#: the keys of a ``shock_capturing`` block +SHOCK_CAPTURING_KEYS: Dict[str, str] = { + "factor": "the coefficient of the viscosity, >= 0 (proteus shockCapturingFactor)", + "beta": "the exponent the gradient is scaled by, in [1, 2]: 1 is the classical scaling (proteus sc_beta)", + "reference": "the reference value of the unknown, > 0 (proteus sc_uref)", + "lagged": "the viscosity is taken from the previous step (true) or the current iterate (false)", +} + #: an algebraic scheme stated in a discretization's ``discretization:`` block: #: its name, and the options it reads (option -> meaning). ``time_integration``, #: ``outputs`` and ``dt`` are read for every scheme. @@ -386,6 +409,8 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: "step_control": STEP_CONTROL, "regularization": REGULARIZATIONS, "binding_meaning": BINDING_MEANINGS, "writes_back": WRITES_BACK, "linear_solver": LINEAR_SOLVERS, "coefficient_role": COEFFICIENT_ROLES, + "tau_form": TAU_FORMS, "stabilization_key": STABILIZATION_KEYS, + "shock_capturing_key": SHOCK_CAPTURING_KEYS, "scheme_option": {o: m for s in SCHEMES.values() for o, m in s["options"].items()}, } @@ -396,6 +421,9 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: "stabilization": {"shock_capturing": "residual_shock_capturing"}, "role": {"pressure_initial": "pressure_spin_up"}, "scheme_option": {"entropy_viscosity_cE": "entropy_viscosity_coefficient"}, + # the keys proteus's dispatcher already reads from a stabilization block + "stabilization_key": {"lag": "lagged"}, + "shock_capturing_key": {"lag": "lagged", "sc_beta": "beta", "sc_uref": "reference"}, "coefficient_role": {"mannings": "manning_coefficient", "bathymetry": "bed_elevation", "drag_alpha": "linear_drag", "drag_beta": "quadratic_drag"}, } @@ -442,12 +470,14 @@ def _word(kind: str, word: Any, where: str) -> str: raise VocabularyError("%s: %s" % (where, exc)) from None -def _stabilization_method(s: Any) -> Any: - if isinstance(s, str): - return s - if isinstance(s, dict): - return s.get("method") - return None +def _check_stabilization(block: Any, where: str) -> None: + if block is None: + return + from ymf.stabilization import StabilizationError, check as check_stabilization + try: + check_stabilization(block, where) + except StabilizationError as exc: + raise VocabularyError(str(exc)) from None def _check_spaces(block: Any, where: str) -> None: @@ -484,6 +514,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st "%s.discretization: the scheme %s has no option %s; its options are %s" % (where, scheme, ", ".join(unread), ", ".join(list(SCHEMES[scheme]["options"]) + list(SCHEME_COMMON)))) + _check_stabilization(entry.get("stabilization"), where + ".stabilization") _check_spaces(entry.get("finite_element"), where + ".finite_element") for label, binding in list((entry.get("binds") or {}).items()): if isinstance(binding, dict) and binding.get("meaning") is not None: @@ -496,9 +527,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st here = "%s.subproblems[%s]" % (where, sub.get("name", "?")) if sub.get("time_integration") is not None: _word("time_integration", sub["time_integration"], here + ".time_integration") - method = _stabilization_method(sub.get("stabilization")) - if method is not None: - _word("stabilization", method, here + ".stabilization.method") + _check_stabilization(sub.get("stabilization"), here + ".stabilization") _check_solver(sub.get("solver"), here) _check_spaces(sub.get("finite_element"), here + ".finite_element") for label, binding in (sub.get("binds") or {}).items(): diff --git a/tests/_formulation.py b/tests/_formulation.py new file mode 100644 index 0000000..123f9a9 --- /dev/null +++ b/tests/_formulation.py @@ -0,0 +1,30 @@ +"""Shared by the round-5 formulation tests (stabilization, lagging, boundary kinds, dispersion, cells): the fixtures, +and a round trip through an archive.""" + +from pathlib import Path + +FIXTURES = Path(__file__).parent / "fixtures" +TWO_PHASE = FIXTURES / "two_phase" +SHALLOW_WATER = FIXTURES / "shallow_water" + + +def roundtrip(tmp_path, spec_path, discretization, realization): + """Load a spec, write its archive, read that back, and once more: ``(spec, again, digest)`` where the digest (the + input's key) is the same each time, so that a word a spec states is part of what an archive records and not lost + or rewritten by it.""" + from ymf import closure + spec, _, _ = closure.load(spec_path) + digest = closure.input_digest(spec, discretization, realization) + archive = tmp_path / "round.archive.ymf" + closure.write(archive, spec, {}) + again, _, _ = closure.load(archive) + assert closure.input_digest(again, discretization, realization) == digest + closure.write(archive, again, {}) + third, _, _ = closure.load(archive) + assert closure.input_digest(third, discretization, realization) == digest + return spec, again, digest + + +def subproblem(spec, discretization, name): + entry = next(e for e in spec["solution_paths"]["discretizations"] if e["name"] == discretization) + return next(s for s in entry["subproblems"] if s["name"] == name) diff --git a/tests/fixtures/two_phase/dambreak_formulation.ymf b/tests/fixtures/two_phase/dambreak_formulation.ymf new file mode 100644 index 0000000..8c4f162 --- /dev/null +++ b/tests/fixtures/two_phase/dambreak_formulation.ymf @@ -0,0 +1,38 @@ +# The dam break of dambreak.ymf with the formulation stated: what the +# generator (C19) and the dispatcher (C5) used to take from the model's +# name or from Parameters.py. Round 5 (C42) states, in the order the files +# add it: +# stabilization SUPG or ASGS per sub-problem, its length scale, and the +# shock-capturing viscosity with its parameters +# Every value is the one proteus's DispatchTable (cekees/main 92f24ad9) +# uses for the cell, so the spec states what the dispatcher already did. +extends: dambreak.ymf + +solution_paths: + discretizations: + - name: level_set_five + subproblems: + - name: flow + stabilization: + method: ASGS + tau: metric + lagged: true # RANS2P's subgrid error from the previous step + shock_capturing: {factor: 0.5, lagged: true} + - name: vof + stabilization: + method: SUPG + tau: metric + lagged: false + shock_capturing: {factor: 0.5, beta: 1.5, reference: 1.0, lagged: true} + - name: ncls + stabilization: + method: SUPG + tau: metric + lagged: false + shock_capturing: {factor: 0.5, beta: 1.5, reference: 1.0, lagged: true} + - name: rdls + stabilization: + method: SUPG + tau: metric + lagged: false + shock_capturing: {factor: 0.9, lagged: false} # redistancing's is not lagged diff --git a/tests/test_stabilization.py b/tests/test_stabilization.py new file mode 100644 index 0000000..9ba86dd --- /dev/null +++ b/tests/test_stabilization.py @@ -0,0 +1,191 @@ +"""ymf.stabilization (C42 round 5): the stabilization and shock-capturing words, their parameters, checked on load and +carried through the split problem and the archive.""" + +import pytest + +pytest.importorskip("strictyaml") +sympy = pytest.importorskip("sympy") + +from _formulation import TWO_PHASE, roundtrip, subproblem # noqa: E402 +from ymf import stabilization # noqa: E402 +from ymf.references import YmfReferenceError # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 +from ymf.stabilization import StabilizationError, missing, resolve # noqa: E402 +from ymf.symbolic import split_problem # noqa: E402 +from ymf.vocabulary import VocabularyError, canonical, check # noqa: E402 + +FORMULATION = TWO_PHASE / "dambreak_formulation.ymf" +DAMBREAK = TWO_PHASE / "dambreak.ymf" + + +# --- resolve ----------------------------------------------------------------------------------------------------- + +def test_a_bare_word_is_a_block_and_nothing_is_added(): + assert resolve("SUPG") == {"method": "SUPG"} + assert resolve({"method": "SUPG", "tau": "element_size"}) == {"method": "SUPG", "tau": "element_size"} + + +def test_the_keys_the_dispatcher_reads_are_aliases_of_ymfs(): + old = {"method": "SUPG", "lag": True, "shock_capturing": {"factor": 0.5, "sc_beta": 1.5, "sc_uref": 1.0, "lag": True}} + new = {"method": "SUPG", "lagged": True, + "shock_capturing": {"factor": 0.5, "beta": 1.5, "reference": 1.0, "lagged": True}} + assert resolve(old) == resolve(new) == new + assert canonical("shock_capturing_key", "sc_uref") == "reference" + assert resolve({"method": "shock_capturing"}) == {"method": "residual_shock_capturing"} + + +def test_shock_capturing_none_is_stated_and_is_not_absent(): + assert resolve({"method": "SUPG", "shock_capturing": "none"}) == {"method": "SUPG", "shock_capturing": None} + assert "shock_capturing" not in resolve("SUPG") + + +@pytest.mark.parametrize("block, message", [ + ({"tau": "metric"}, "say the method"), + ({"method": "GLS"}, "stabilization GLS: ymf knows"), + ({"method": "SUPG", "tau": "h"}, "tau: h is not one of metric, element_size"), + ({"method": "SUPG", "lagged": "maybe"}, "'maybe' is not true or false"), + ({"method": "SUPG", "lagged": True, "lag": False}, "lagged is stated twice"), + ({"method": "SUPG", "shock_capturing": {"factor": 0.5, "sc_beta": 1.2, "beta": 1.2}}, "beta is stated twice"), + ({"method": "SUPG", "shock_capturing": {"beta": 1.5}}, "factor is required"), + ({"method": "SUPG", "shock_capturing": {"factor": -1.0}}, "factor: -1 is negative"), + ({"method": "SUPG", "shock_capturing": {"factor": 0.5, "beta": 0.5}}, "beta: 0.5 is outside \\[1, 2\\]"), + ({"method": "SUPG", "shock_capturing": {"factor": 0.5, "beta": 2.5}}, "beta: 2.5 is outside \\[1, 2\\]"), + ({"method": "SUPG", "shock_capturing": {"factor": 0.5, "reference": 0.0}}, "reference: 0 is not positive"), + ({"method": "SUPG", "shock_capturing": {"factor": 0.5, "gamma": 1.0}}, "no key gamma in shock_capturing"), + ({"method": "SUPG", "shock_capturing": "some"}, "'some' is not a block"), + ({"method": "entropy_viscosity", "tau": "metric"}, + "entropy_viscosity does not read tau; it has no keys here .*scheme's options"), + ({"method": "graph_viscosity_smoothness", "shock_capturing": {"factor": 1.0}}, + "does not read shock_capturing"), + ({"method": "residual_shock_capturing", "lagged": True}, + "residual_shock_capturing does not read lagged; its keys are method, tau, shock_capturing"), +]) +def test_a_stabilization_that_does_not_make_sense_is_refused(block, message): + with pytest.raises(StabilizationError, match=message): + resolve(block) + + +# --- what a generator still needs stated ------------------------------------------------------------------------ + +def test_missing_says_what_the_generator_cannot_guess(): + assert missing("SUPG") == ["tau", "lagged", "shock_capturing"] + assert missing({"method": "SUPG", "tau": "metric", "lagged": False, + "shock_capturing": {"factor": 0.5, "lagged": True}}) == [ + "shock_capturing.beta", "shock_capturing.reference"] + assert missing({"method": "SUPG", "tau": "metric", "lagged": False, "shock_capturing": "none"}) == [] + assert missing("entropy_viscosity") == [] # its parameters are the scheme's + + +# --- the spec ---------------------------------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def formulation(): + return load_ymf(FORMULATION) + + +def test_the_dam_break_states_the_stabilization_the_dispatcher_used_to_assume(formulation): + split = {s["name"]: s for s in split_problem(formulation, "level_set_five")["subproblems"]} + # proteus.DispatchTable at cekees/main 92f24ad9: RANS2P ASGS, subgrid lag, shock capturing 0.5 lagged; VOF and NCLS + # SUPG with 0.5, sc_beta 1.5, sc_uref 1.0, lagged; RDLS SUPG with 0.9 not lagged; MCorr none + assert split["flow"]["stabilization"] == {"method": "ASGS", "tau": "metric", "lagged": True, + "shock_capturing": {"factor": 0.5, "lagged": True}} + for name in ("vof", "ncls"): + assert split[name]["stabilization"] == { + "method": "SUPG", "tau": "metric", "lagged": False, + "shock_capturing": {"factor": 0.5, "beta": 1.5, "reference": 1.0, "lagged": True}} + assert split["rdls"]["stabilization"]["shock_capturing"] == {"factor": 0.9, "lagged": False} + assert "stabilization" not in split["mcorr"] + + +def test_vof_and_ncls_state_what_the_generator_spike_declared_by_hand(formulation): + # generator/make_inputs.py (proteus#298): STAB = {"method": "SUPG", "tau": "metric", "shock_capturing": {"lagged": True}} + declared = {"method": "SUPG", "tau": "metric", "shock_capturing": {"lagged": True}} + split = {s["name"]: s for s in split_problem(formulation, "level_set_five")["subproblems"]} + for name in ("vof", "ncls"): + stated = split[name]["stabilization"] + assert stated["method"] == declared["method"] and stated["tau"] == declared["tau"] + assert stated["shock_capturing"]["lagged"] is declared["shock_capturing"]["lagged"] + # and what it needed beyond that, which make_inputs.py could not say + assert missing(stated) == [] + + +def test_the_dam_break_without_the_formulation_states_none_of_it(): + split = {s["name"]: s for s in split_problem(load_ymf(DAMBREAK), "level_set_five")["subproblems"]} + assert all("stabilization" not in s for s in split.values()) + + +def test_an_entry_states_the_default_of_its_sub_problems_and_a_sub_problem_replaces_it_whole(tmp_path): + doc = load_ymf(FORMULATION) + entry = doc["solution_paths"]["discretizations"][0] + entry["stabilization"] = {"method": "SUPG", "tau": "element_size"} + for sub in entry["subproblems"]: + if sub["name"] in ("vof", "ncls"): + del sub["stabilization"] + split = {s["name"]: s for s in split_problem(doc, "level_set_five")["subproblems"]} + assert split["vof"]["stabilization"] == {"method": "SUPG", "tau": "element_size"} + # a sub-problem that states one does not merge with the entry's: flow is ASGS with its own keys + assert split["flow"]["stabilization"]["method"] == "ASGS" and split["flow"]["stabilization"]["tau"] == "metric" + assert split["mcorr"]["stabilization"] == {"method": "SUPG", "tau": "element_size"} + + +# --- checked on load --------------------------------------------------------------------------------------------- + +def _state(doc, sub, block): + subproblem(doc, "level_set_five", sub)["stabilization"] = block + return doc + + +def test_a_bad_stabilization_is_refused_on_load_and_says_where(): + doc = _state(load_ymf(FORMULATION), "vof", {"method": "SUPG", "shock_capturing": {"factor": 0.5, "beta": 3.0}}) + with pytest.raises(VocabularyError, match=r"subproblems\[vof\]\.stabilization\.shock_capturing\.beta: 3 is outside"): + check(doc) + + +def test_the_strict_schema_refuses_a_key_it_does_not_know(tmp_path): + text = FORMULATION.read_text(encoding="utf-8").replace("tau: metric\n lagged: false\n shock_capturing: {factor: 0.5, beta: 1.5", + "tau: metric\n damping: 1.0\n shock_capturing: {factor: 0.5, beta: 1.5", 1) + (tmp_path / "dambreak.ymf").write_text((TWO_PHASE / "dambreak.ymf").read_text(encoding="utf-8"), encoding="utf-8") + (tmp_path / "two_phase_level_set.ymf").write_text( + (TWO_PHASE / "two_phase_level_set.ymf").read_text(encoding="utf-8"), encoding="utf-8") + (tmp_path / "bad.ymf").write_text(text, encoding="utf-8") + with pytest.raises(Exception, match="damping"): + load_ymf(tmp_path / "bad.ymf") + + +def test_a_method_word_alone_still_loads(): + doc = load_ymf(FORMULATION) + for sub in doc["solution_paths"]["discretizations"][0]["subproblems"]: + if "stabilization" in sub: + sub["stabilization"] = "SUPG" + check(doc) + + +# --- the archive --------------------------------------------------------------------------------------------------- + +def test_the_stabilization_survives_the_archive_and_is_part_of_its_key(tmp_path): + realization = {"h": 0.0322} + spec, again, digest = roundtrip(tmp_path, FORMULATION, "level_set_five", realization) + for name in ("flow", "vof", "ncls", "rdls"): + assert subproblem(again, "level_set_five", name)["stabilization"] == subproblem( + spec, "level_set_five", name)["stabilization"] + shock = subproblem(again, "level_set_five", "vof")["stabilization"]["shock_capturing"] + assert shock == {"factor": 0.5, "beta": 1.5, "reference": 1.0, "lagged": True} + # it is an input: another value is another key, and the spec that states none has another key than this one + from ymf import closure + other = load_ymf(FORMULATION) + _state(other, "vof", {"method": "SUPG", "shock_capturing": {"factor": 0.6}}) + assert closure.input_digest(other, "level_set_five", realization) != digest + plain, _, _ = closure.load(DAMBREAK) + assert closure.input_digest(plain, "level_set_five", realization) != digest + + +def test_a_spec_in_the_older_spelling_has_the_words_of_the_newer(tmp_path): + old = FORMULATION.read_text(encoding="utf-8").replace("lagged:", "lag:").replace("beta:", "sc_beta:").replace( + "reference:", "sc_uref:") + # the replacement also changed the (unused) keys of sub-problems that do not read them; the old spellings are accepted + for name in ("dambreak.ymf", "two_phase_level_set.ymf"): + (tmp_path / name).write_text((TWO_PHASE / name).read_text(encoding="utf-8"), encoding="utf-8") + (tmp_path / "old.ymf").write_text(old, encoding="utf-8") + new = split_problem(load_ymf(FORMULATION), "level_set_five") + older = split_problem(load_ymf(tmp_path / "old.ymf"), "level_set_five") + assert [s.get("stabilization") for s in older["subproblems"]] == [s.get("stabilization") for s in new["subproblems"]] From 186758502ee3b9ecd369e1614a54f3d392d9b02d Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:20:33 +0100 Subject: [PATCH 2/7] Lagged coefficients: frozen in time or in the Newton iteration (C42 round 5, 2/5) A sub-problem states `lagged_coefficients: {name: previous_step | previous_iterate}`: the coefficients of the model it freezes. The two words are different things to a kernel: a time lag makes the coefficient a constant of the step (no entry in the Jacobian), a Newton lag a constant of the iteration (a Picard step: the Jacobian drops its dependence on the unknown). Until now the spec could say only which *fields* a sub-problem reads from others (`lags`, whose `at` is previous_step or current_step) and, since commit 1, that its stabilization is lagged; a lag on the sub-problem's own state-dependent coefficient was in no spec. What the generator can now read: `split_problem` puts `lagged_coefficients` in the record, and a state coefficient (the `coefficients` entries with their dependence on the unknowns) carries `lagged: `, so a kernel emits it as a constant. A name that is not a model coefficient, or that the sub-problem already reads through `lags`, is refused on load, naming its path. No fixture states one: RANS2P freezes no coefficient (the lags of the dispatcher are the stabilization's, commit 1), and a fixture must not claim what the solver does not do; the tests set it on the dam-break flow sub-problem. Not done: the ADR form still differentiates a lagged coefficient; the generator has to drop it (listed in the handoff for C19). Tests (7 new, whole suite 933 -> 940 passed, 13 skipped): the record and the `lagged` flag on a state coefficient (mu previous_iterate, rho previous_step, chi untouched), nothing stated means nothing lagged, three refusals (bad word, not a coefficient, already in lags), and the archive keeps it, with the same digest, and a changed word changes the digest. Co-Authored-By: Claude Sonnet 5.5 --- src/ymf/schema.py | 3 ++ src/ymf/symbolic/split.py | 8 +++++ src/ymf/vocabulary.py | 33 ++++++++++++++++++-- tests/test_lagging.py | 64 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 tests/test_lagging.py diff --git a/src/ymf/schema.py b/src/ymf/schema.py index c1a4811..4dc9281 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -238,6 +238,9 @@ Optional("finite_element"): FiniteElementDef, Optional("time_integration"): Str(), Optional("stabilization"): StabilizationDef, + # coefficients of the model this sub-problem freezes: name -> previous_step + # | previous_iterate (ymf.vocabulary.LAG_WHEN), checked on load + Optional("lagged_coefficients"): MapPattern(Str(), Str()), Optional("solver"): SolverConfig, # options a dispatcher cannot infer yet, for one solver: an interim hint # it checks against what it infers, and drops once it covers them diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index bd2302a..d24b5a5 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -33,6 +33,7 @@ import sympy from ymf.stabilization import for_subproblem +from ymf.vocabulary import canonical from ymf.symbolic.adr import adr_form, to_code from ymf.symbolic.language import Space, SymbolicError, parse_equation, parse_expression @@ -247,6 +248,13 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: named[name].update(extra) record["coefficients"] = named record["named"] = form + if sub.get("lagged_coefficients"): + # each name -> when; a state coefficient (named) says it where a kernel reads its dependence + lagged = {k: canonical("lag_when", v) for k, v in sub["lagged_coefficients"].items()} + record["lagged_coefficients"] = lagged + for name, when in lagged.items(): + if name in record.get("coefficients", {}): + record["coefficients"][name]["lagged"] = when if sub.get("initial_condition"): record["initial"] = _initial(sub, own, ranks, values, functions, dim, where) if sharp: diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index 6ff8b71..d7e271c 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -41,7 +41,7 @@ from typing import Any, Dict, Iterable, List, Optional __all__ = ["FAMILIES", "ROLES", "TIME_INTEGRATION", "STABILIZATION", "TAU_FORMS", "STABILIZATION_KEYS", - "SHOCK_CAPTURING_KEYS", "SCHEMES", + "SHOCK_CAPTURING_KEYS", "LAG_WHEN", "SCHEMES", "STEP_CONTROL", "REGULARIZATIONS", "BINDING_MEANINGS", "WRITES_BACK", "INERTIA_FORMS", "LINEAR_SOLVERS", "COEFFICIENT_ROLES", "ALIASES", "canonical", "family_of", "role_of", "roles_of", "linear_solver_kind", @@ -283,6 +283,15 @@ def roles_of(doc: Dict[str, Any], entry: Dict[str, Any]) -> Dict[str, Optional[s "lagged": "the viscosity is taken from the previous step (true) or the current iterate (false)", } +#: when a lagged coefficient is evaluated (a sub-problem's ``lagged_coefficients``). A time lag and a Newton lag are +#: different things for a kernel: the first is a constant of the step (the coefficient at the old state, no +#: derivative in the Jacobian at all), the second a constant of the iteration (a Picard step: the Jacobian drops the +#: coefficient's dependence on the unknown, and the residual is evaluated at the new iterate's other terms). +LAG_WHEN: Dict[str, str] = { + "previous_step": "evaluated at the state of the previous time step; a constant of the step", + "previous_iterate": "evaluated at the previous Newton iterate; the Jacobian drops its dependence on the unknown", +} + #: an algebraic scheme stated in a discretization's ``discretization:`` block: #: its name, and the options it reads (option -> meaning). ``time_integration``, #: ``outputs`` and ``dt`` are read for every scheme. @@ -409,7 +418,7 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: "step_control": STEP_CONTROL, "regularization": REGULARIZATIONS, "binding_meaning": BINDING_MEANINGS, "writes_back": WRITES_BACK, "linear_solver": LINEAR_SOLVERS, "coefficient_role": COEFFICIENT_ROLES, - "tau_form": TAU_FORMS, "stabilization_key": STABILIZATION_KEYS, + "lag_when": LAG_WHEN, "tau_form": TAU_FORMS, "stabilization_key": STABILIZATION_KEYS, "shock_capturing_key": SHOCK_CAPTURING_KEYS, "scheme_option": {o: m for s in SCHEMES.values() for o, m in s["options"].items()}, } @@ -480,6 +489,25 @@ def _check_stabilization(block: Any, where: str) -> None: raise VocabularyError(str(exc)) from None +def _check_lagged_coefficients(doc: Dict[str, Any], sub: Dict[str, Any], where: str) -> None: + """``lagged_coefficients: {name: when}``: each name a coefficient of the model (not a field the sub-problem already + reads from another, which ``lags`` lags), each ``when`` a LAG_WHEN word.""" + lagged = sub.get("lagged_coefficients") + if not lagged: + return + coefficients = _strong(doc).get("coefficients") or {} + read = set(sub.get("lags") or {}) + for name, when in lagged.items(): + here = "%s.lagged_coefficients.%s" % (where, name) + _word("lag_when", when, here) + if name in read: + raise VocabularyError("%s: %s is a field this sub-problem reads through lags, which already says when" % ( + here, name)) + if name not in coefficients: + raise VocabularyError("%s: %s is not a coefficient of the model; its coefficients are %s" % ( + here, name, ", ".join(coefficients) or "none")) + + def _check_spaces(block: Any, where: str) -> None: from ymf.spaces import SpaceError, check_finite_element try: @@ -528,6 +556,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st if sub.get("time_integration") is not None: _word("time_integration", sub["time_integration"], here + ".time_integration") _check_stabilization(sub.get("stabilization"), here + ".stabilization") + _check_lagged_coefficients(doc, sub, here) _check_solver(sub.get("solver"), here) _check_spaces(sub.get("finite_element"), here + ".finite_element") for label, binding in (sub.get("binds") or {}).items(): diff --git a/tests/test_lagging.py b/tests/test_lagging.py new file mode 100644 index 0000000..fcbfe90 --- /dev/null +++ b/tests/test_lagging.py @@ -0,0 +1,64 @@ +"""``lagged_coefficients`` (C42 round 5): which coefficients a sub-problem freezes, in time or in the Newton iteration.""" + +import copy + +import pytest + +pytest.importorskip("strictyaml") +pytest.importorskip("sympy") + +from _formulation import TWO_PHASE, roundtrip, subproblem # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 +from ymf.symbolic import split_problem # noqa: E402 +from ymf.vocabulary import LAG_WHEN, VocabularyError, check # noqa: E402 + +DAMBREAK = TWO_PHASE / "dambreak.ymf" + + +def _lag(doc, lagged, sub="flow"): + subproblem(doc, "level_set_five", sub)["lagged_coefficients"] = lagged + return doc + + +def test_the_two_lags_are_different_words(): + assert set(LAG_WHEN) == {"previous_step", "previous_iterate"} + + +def test_a_lagged_state_coefficient_says_so_in_the_split_problem(): + doc = _lag(load_ymf(DAMBREAK), {"μ": "previous_iterate", "ρ": "previous_step"}) + flow = {s["name"]: s for s in split_problem(doc, "level_set_five")["subproblems"]}["flow"] + assert flow["lagged_coefficients"] == {"μ": "previous_iterate", "ρ": "previous_step"} + assert flow["coefficients"]["μ"]["lagged"] == "previous_iterate" + assert flow["coefficients"]["ρ"]["lagged"] == "previous_step" + assert "lagged" not in flow["coefficients"]["χ"] # not stated: not lagged here + + +def test_what_is_not_stated_is_not_lagged(): + flow = {s["name"]: s for s in split_problem(load_ymf(DAMBREAK), "level_set_five")["subproblems"]}["flow"] + assert "lagged_coefficients" not in flow + assert all("lagged" not in c for c in flow["coefficients"].values()) + + +@pytest.mark.parametrize("lagged, message", [ + ({"μ": "last_week"}, r"lagged_coefficients\.μ: lag when last_week: ymf knows previous_step, previous_iterate"), + ({"viscosity": "previous_step"}, "viscosity is not a coefficient of the model; its coefficients are"), + ({"φ": "previous_step"}, "φ is a field this sub-problem reads through lags, which already says when"), +]) +def test_a_lagging_that_does_not_make_sense_is_refused_on_load(lagged, message): + with pytest.raises(VocabularyError, match=message): + check(_lag(load_ymf(DAMBREAK), lagged)) + + +def test_lagging_survives_the_archive_and_is_part_of_the_key(tmp_path): + from ymf import closure + doc = _lag(load_ymf(DAMBREAK), {"μ": "previous_iterate"}) + path = tmp_path / "lagged.archive.ymf" + closure.write(path, doc, {}) + again, _, _ = closure.load(path) + assert subproblem(again, "level_set_five", "flow")["lagged_coefficients"] == {"μ": "previous_iterate"} + realization = {"h": 0.0322} + assert closure.input_digest(again, "level_set_five", realization) == closure.input_digest( + doc, "level_set_five", realization) + other = _lag(copy.deepcopy(doc), {"μ": "previous_step"}) + assert closure.input_digest(other, "level_set_five", realization) != closure.input_digest( + doc, "level_set_five", realization) From 72fdc6cb158324f190a8c705906470bb15ff3716 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:29:41 +0100 Subject: [PATCH 3/7] Boundary kind per condition, and the two-phase model's porosity (C42 round 5, 3/5) Boundary kind. `imposed` (strong | weak | none) says how a condition reaches the discrete problem, which is what picks a kernel's boundary term: the engine's Strong, WeakDirichlet and Flux face kinds (C19 gap note G8). A Dirichlet condition (and the Dirichlet part of slip, inflow, characteristic) is strong or weak, default strong; Neumann, Robin and open are none; periodic has none. A weak one may state `penalty` (over h) and `form` (symmetric = SIPG, nonsymmetric = NIPG, incomplete = IIPG). `imposed: none` is new; a strong Neumann condition, a penalty on a strong condition, and an imposed on a periodic one are refused on load, naming the condition. An expanded alias gives the kind to its Dirichlet component only (`slip, imposed: weak` is a weak normal and a natural tangential condition; before, the tangential part carried the word too). `split_problem` gives every condition a resolved `kind` (and `penalty`, `form`), and `ymf.boundaries.kinds` lists a document's. What the generator can now express: the face kernel from the declaration, not the model's name. dambreak_formulation.ymf states RANS2P's Dirichlet conditions weak with the symmetric adjoint and VOF's air inflow strong. Not yet expressible: NCLS's inflow penalty against another sub-problem's trace (a weak Dirichlet whose value is RDLS's face value, G8): a condition has no value source `via` a sub-problem; listed in the handoff. Porosity. dambreak_porous.ymf states the two-phase model with a porosity coefficient (`role: porosity`) in the continuity, momentum, VOF and MCorr equations as RANS2P.h, VOF and MCorr carry them (NCLS none). The split record gets `coefficient_roles` for the coefficients each sub-problem uses, so the generator finds the porosity by its role. VOF's ADR is the form the spike wrote by hand in a Space (m = theta chi, f = theta chi v). `_used` no longer reads a function's name as a run of coefficients (`sign` read as `s i g n` put the gravity `g` among RDLS's coefficients). Tests (31 new, whole suite 940 -> 971 passed, 13 skipped): the default kind of every condition type, ten refusals, the alias split, the dam break's kinds in the document and in each sub-problem's record, no kind stated means the type's default, a bad kind in a condition set refused on load with its path, the archive keeps the kinds and a changed kind changes the digest; porosity by role, which sub-problems use it, VOF's m and dm agree and NCLS equals the plain dam break's, the porosity value in open flow, in the block and at its smoothed edge, and the archive round trip. One existing expectation gained the `kind` key (test_split). Co-Authored-By: Claude Sonnet 5.5 --- src/ymf/boundaries.py | 119 +++++++++++++ src/ymf/conditions.py | 6 +- src/ymf/schema.py | 6 +- src/ymf/symbolic/split.py | 23 ++- src/ymf/vocabulary.py | 16 ++ .../two_phase/dambreak_formulation.ymf | 16 ++ tests/fixtures/two_phase/dambreak_porous.ymf | 32 ++++ tests/test_boundary_declaration.py | 160 ++++++++++++++++++ tests/test_split.py | 2 +- 9 files changed, 375 insertions(+), 5 deletions(-) create mode 100644 src/ymf/boundaries.py create mode 100644 tests/fixtures/two_phase/dambreak_porous.ymf create mode 100644 tests/test_boundary_declaration.py diff --git a/src/ymf/boundaries.py b/src/ymf/boundaries.py new file mode 100644 index 0000000..d2290b6 --- /dev/null +++ b/src/ymf/boundaries.py @@ -0,0 +1,119 @@ +"""Boundary kind: how a boundary condition reaches the discrete problem (strong, weak, none), and a weak one's parameters. + +A condition says *what* holds on a boundary (a value, a flux). Its ``imposed`` says *how the discrete problem enforces +it*, which is what picks the boundary term a kernel evaluates there (the engine's face kinds ``Strong``, +``WeakDirichlet`` and ``Flux``; C19's gap note G8):: + + - {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: strong} # rows of the system replaced + - {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: weak, # penalty and consistency terms + penalty: 100.0, form: symmetric} + - {region: outlet, variable: φ, type: neumann, value: 0.0} # none: the natural condition + +* ``strong``: the unknown's degrees of freedom on the boundary are set to the value (a Dirichlet condition). +* ``weak``: the value is enforced through terms of the weak form (Nitsche): a penalty ``penalty / h`` and, by ``form``, the + adjoint consistency term: ``symmetric`` (SIPG), ``nonsymmetric`` (NIPG) or ``incomplete`` (IIPG, none). Dirichlet only. +* ``none``: nothing constrains the solution on the boundary; the boundary integral carries the given flux (Neumann, Robin) + or leaves with the solution's own trace (``open``). + +The kind is what a condition's *type* allows: a Dirichlet condition (and the Dirichlet part of ``slip``, ``inflow``, +``characteristic``) is ``strong`` or ``weak`` (default ``strong``); Neumann, Robin and ``open`` are ``none``; +``periodic`` is none of them (the faces are identified). :func:`kind_of` gives the kind of a condition, stated or the +default; :func:`check_condition` refuses what does not make sense (a strong Neumann condition, a penalty on a strong +one); :func:`kinds` lists every condition of a document with its kind. + +When an alias is expanded (``ymf.conditions``) the kind goes to the Dirichlet components only: ``slip, imposed: weak`` is +a weak normal condition and a natural tangential one. ``split_problem`` gives each condition's ``kind``, and for a weak +one its ``penalty`` and ``form``, so a generator picks the face kernel from the declaration and not from the model's name. + +Stdlib only, like the rest of the spec core. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +__all__ = ["BoundaryError", "BOUNDARY_KINDS", "WEAK_FORMS", "kind_of", "check_condition", "kinds"] + + +class BoundaryError(ValueError): + """A boundary kind a spec states that does not make sense.""" + + +BOUNDARY_KINDS: Dict[str, str] = { + "strong": "the degrees of freedom on the boundary are set to the value", + "weak": "the value is enforced through penalty and consistency terms of the weak form (Nitsche)", + "none": "no constraint on the solution: the boundary integral carries the given flux, or the solution's own trace", +} + +WEAK_FORMS: Dict[str, str] = { + "symmetric": "SIPG: the adjoint consistency term with the sign that keeps the form symmetric", + "nonsymmetric": "NIPG: the adjoint consistency term with the opposite sign", + "incomplete": "IIPG: no adjoint consistency term", +} + +#: the types a condition's kind is chosen for (the Dirichlet part), and the types that are always ``none`` +_DIRICHLET = ("dirichlet", "slip", "inflow", "characteristic") +_NATURAL = ("neumann", "robin", "open") + + +def kind_of(condition: Dict[str, Any]) -> Optional[str]: + """The boundary kind of a condition (an alias, or an abstract one): what it states, or its type's default. None for + ``periodic``.""" + kind = condition.get("type") + if kind == "periodic": + return None + stated = condition.get("imposed") + if stated is not None: + return str(stated) + return "strong" if kind in _DIRICHLET else "none" + + +def check_condition(condition: Dict[str, Any], where: str) -> None: + """``imposed``, ``penalty`` and ``form`` of a condition agree with its type. Raises :class:`BoundaryError`.""" + kind = condition.get("type") + stated = condition.get("imposed") + has_weak_keys = [k for k in ("penalty", "form") if condition.get(k) is not None] + if stated is not None and str(stated) not in BOUNDARY_KINDS: + raise BoundaryError("%s: imposed %s is not one of %s" % (where, stated, ", ".join(BOUNDARY_KINDS))) + if kind == "periodic": + if stated is not None or has_weak_keys: + raise BoundaryError("%s: a periodic condition identifies faces; it has no kind" % (where,)) + return + if kind in _NATURAL and stated is not None and str(stated) != "none": + raise BoundaryError( + "%s: a %s condition is imposed none (the boundary integral carries it); %s is for a Dirichlet condition" + % (where, kind, stated)) + if kind in _DIRICHLET and stated is not None and str(stated) == "none": + raise BoundaryError( + "%s: a %s condition imposes a value, strong or weak; to impose nothing give no condition, or open" + % (where, kind)) + weak = kind_of(condition) == "weak" + if has_weak_keys and not weak: + raise BoundaryError("%s: %s belong to a weak condition (imposed: weak); this one is %s" % ( + where, " and ".join(has_weak_keys), kind_of(condition))) + if condition.get("penalty") is not None: + try: + ok = float(condition["penalty"]) > 0 + except (TypeError, ValueError): + ok = False + if not ok: + raise BoundaryError("%s: penalty %s is not a positive number" % (where, condition["penalty"])) + if condition.get("form") is not None and str(condition["form"]) not in WEAK_FORMS: + raise BoundaryError("%s: form %s is not one of %s" % (where, condition["form"], ", ".join(WEAK_FORMS))) + + +def kinds(doc: Dict[str, Any]) -> List[Dict[str, Any]]: + """Every boundary condition of the document, expanded, as ``{region, variable, type, [component], [only], kind, + [penalty], [form]}`` in order: what a solver reads to choose its boundary terms.""" + from ymf.conditions import expand + from ymf.normalize import boundary_conditions + strong = ((expand(doc).get("model") or {}).get("strong_form") or {}) + out = [] + for bc in boundary_conditions(strong): + entry = {k: bc[k] for k in ("region", "variable", "type", "component", "only") if bc.get(k) is not None} + entry["kind"] = kind_of(bc) + for k in ("penalty", "form"): + if bc.get(k) is not None: + entry[k] = bc[k] + out.append(entry) + return out diff --git a/src/ymf/conditions.py b/src/ymf/conditions.py index 9393856..474692f 100644 --- a/src/ymf/conditions.py +++ b/src/ymf/conditions.py @@ -44,7 +44,7 @@ #: the order an expanded condition's keys are written in _ORDER = ("region", "variable", "type", "component", "only", "value", "formula", "series", - "alpha", "beta", "units", "imposed", "source", "source_url", "temporal", + "alpha", "beta", "units", "imposed", "penalty", "form", "source", "source_url", "temporal", "expanded_from") @@ -119,10 +119,14 @@ def expand_condition(bc: Dict[str, Any], rank: int = 0) -> List[Dict[str, Any]]: given = {k: bc[k] for k in _VALUE_KEYS if bc.get(k) is not None} shared = {k: v for k, v in bc.items() if k not in _VALUE_KEYS and k not in ("type", "set", "expanded_from")} + # how a condition is imposed is the Dirichlet part's (ymf.boundaries): the natural parts stay natural + kind_keys = {k: shared.pop(k) for k in ("imposed", "penalty", "form") if k in shared} out = [] for part in alias["components"]: entry = dict(shared) entry.update({k: v for k, v in part.items() if k not in ("takes", "default")}) + if part["type"] == "dirichlet": + entry.update(kind_keys) if part.get("takes"): if given: entry.update(given) diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 4dc9281..f1ca4c5 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -389,7 +389,11 @@ # imposed (C12: a property of each condition), and what it expanded from. Optional("component"): Enum(["normal", "tangential"]), Optional("only"): Enum(["inflow", "incoming_characteristics"]), - Optional("imposed"): Enum(["strong", "weak"]), + Optional("imposed"): Enum(["strong", "weak", "none"]), + # a weak (Nitsche) condition's penalty, over h, and its adjoint term + # (ymf.boundaries); checked on load against the condition's type + Optional("penalty"): Float(), + Optional("form"): Enum(["symmetric", "nonsymmetric", "incomplete"]), Optional("expanded_from"): Map({Optional("type"): Str(), Optional("set"): Str()}), Optional("value"): Float(), # A value that varies along the boundary or in time: an expression diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index d24b5a5..eb67315 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -235,6 +235,12 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: ["%s_%d" % (name, i) for i in range(dim)]) for name, rank in own.items()} record["reads"] = reads + # what the coefficients this sub-problem uses mean (density, porosity, ...): a generator finds the porosity by + # its role, whatever the model calls it + from ymf.vocabulary import coefficient_roles + roles = {role: name for role, name in coefficient_roles(doc).items() if name in used} + if roles: + record["coefficient_roles"] = roles named = _state_coefficient_data( {k: v for k, v in values.items() if k in spec and k in used}, space) if named: @@ -350,6 +356,7 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where, for key in ("component", "only", "imposed", "expanded_from"): if bc.get(key) is not None: entry[key] = bc[key] + _kind(entry, bc) entry["components"] = ([target] if rank == 0 else ["%s_%d" % (target, i) for i in range(dim)]) kind = bc["type"] @@ -383,6 +390,15 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where, return out +def _kind(entry: Dict[str, Any], bc: Dict[str, Any]) -> None: + """The condition's boundary kind (strong, weak, none; ymf.boundaries), and a weak one's penalty and form.""" + from ymf.boundaries import kind_of + entry["kind"] = kind_of(bc) + for key in ("penalty", "form"): + if bc.get(key) is not None: + entry[key] = float(bc[key]) if key == "penalty" else bc[key] + + def _indicator_condition(bc, level_set, regions, strong, space, where) -> Dict[str, Any]: """A condition on a phase indicator, as the condition on its level set's sign (see :func:`_conditions`).""" @@ -403,6 +419,7 @@ def _indicator_condition(bc, level_set, regions, strong, space, where) -> Dict[s for key in ("only", "imposed", "expanded_from"): if bc.get(key) is not None: entry[key] = bc[key] + _kind(entry, bc) entry["components"] = [level_set] entry["sign"] = _INDICATOR_SIGN[value] entry["indicator"] = {"variable": bc["variable"], "value": value} @@ -513,12 +530,14 @@ def _used(texts: List[str], spec: Dict[str, Any], declared: set, carried=()) -> formulas; not through a ``carried`` one, which is read rather than computed. A run of letters that is not a declared name counts for each letter, as the notation reads an undeclared ``ρU`` as ``ρ·U``.""" - from ymf.symbolic.notation import tokens + from ymf.symbolic.notation import _FUNCTIONS, tokens + functions = set(_FUNCTIONS) | {"norm", "sym", "div", "grad", "lap"} def names(text): out = set() for kind, value, _ in tokens(str(text)): - if kind == "NAME": + # a function's name is not a run of coefficients (sign(φs) is not s·i·g·n) + if kind == "NAME" and value not in functions: out.update([value] if value in declared or len(value) == 1 else value) return out & set(spec) diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index d7e271c..ed123cb 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -508,6 +508,21 @@ def _check_lagged_coefficients(doc: Dict[str, Any], sub: Dict[str, Any], where: here, name, ", ".join(coefficients) or "none")) +def _check_boundary_kinds(strong: Dict[str, Any]) -> None: + """``imposed``, ``penalty`` and ``form`` of every condition (written, or a member of a condition set) agree with its + type (ymf.boundaries).""" + from ymf.boundaries import BoundaryError, check_condition + conditions = [("boundary_conditions[%d]" % i, bc) for i, bc in enumerate(strong.get("boundary_conditions") or [])] + for name, members in (strong.get("condition_sets") or {}).items(): + conditions += [("condition_sets.%s[%d]" % (name, i), bc) for i, bc in enumerate(members or [])] + for label, bc in conditions: + if isinstance(bc, dict): + try: + check_condition(bc, "model.strong_form.%s (%s on %s)" % (label, bc.get("type"), bc.get("variable"))) + except BoundaryError as exc: + raise VocabularyError(str(exc)) from None + + def _check_spaces(block: Any, where: str) -> None: from ymf.spaces import SpaceError, check_finite_element try: @@ -601,6 +616,7 @@ def check(doc: Dict[str, Any]) -> None: else: found = families_of(doc) family = found[0] if len(found) == 1 else None + _check_boundary_kinds(_strong(doc)) seen: Dict[str, str] = {} for name, entry in (_strong(doc).get("coefficients") or {}).items(): if isinstance(entry, dict) and entry.get("role") is not None: diff --git a/tests/fixtures/two_phase/dambreak_formulation.ymf b/tests/fixtures/two_phase/dambreak_formulation.ymf index 8c4f162..4cb508e 100644 --- a/tests/fixtures/two_phase/dambreak_formulation.ymf +++ b/tests/fixtures/two_phase/dambreak_formulation.ymf @@ -4,10 +4,26 @@ # add it: # stabilization SUPG or ASGS per sub-problem, its length scale, and the # shock-capturing viscosity with its parameters +# boundary kind how each condition reaches the discrete problem: RANS2P +# assembles its Dirichlet conditions weakly (Nitsche, the +# boundary adjoint of sign 1: C19 gap note G8), VOF imposes +# the air entering through the top strongly (upwind flux +# with the Dirichlet inflow) # Every value is the one proteus's DispatchTable (cekees/main 92f24ad9) # uses for the cell, so the spec states what the dispatcher already did. extends: dambreak.ymf +model: + strong_form: + # the family's sets, with the kind of each Dirichlet part stated + condition_sets: + free_slip: + - {variable: v, type: slip, imposed: weak, form: symmetric} + atmosphere: + - {variable: p, type: dirichlet, value: 0.0, imposed: weak, form: symmetric} + - {variable: v, type: open} + - {variable: χ, type: inflow, value: 1.0, imposed: strong} + solution_paths: discretizations: - name: level_set_five diff --git a/tests/fixtures/two_phase/dambreak_porous.ymf b/tests/fixtures/two_phase/dambreak_porous.ymf new file mode 100644 index 0000000..9eb9501 --- /dev/null +++ b/tests/fixtures/two_phase/dambreak_porous.ymf @@ -0,0 +1,32 @@ +# The dam break with a porous block on the floor of the right half of the +# tank: the two-phase model with porosity θ (the fraction of the volume open +# to the flow), as RANS2P, VOF and MCorr carry it. θ is a coefficient with +# the role `porosity` (ymf.vocabulary), so a generator finds it by its role: +# mass ∇·(θ v) = 0 +# momentum θ times the density, the viscous stress and the pressure force +# VOF ∂(θ χh)/∂t + ∇·(θ v χh) = 0 +# MCorr the reaction is θ (H(φ + φc) − χh) +# NCLS carries no porosity (its Hamiltonian is v·∇φ). +extends: dambreak_formulation.ymf + +model: + name: "Dam break with a porous block (2-D)" + strong_form: + equations: + - name: momentum + for: v + equation: "∂(θ ρ v)/∂t + ∇·(θ ρ v⊗v) − ∇·(2θ μ sym(∇v)) + θ ∇p = θ ρ g in Ω" + - name: continuity + for: p + equation: "∇·(θ v) = 0 in Ω" + coefficients: + θ: {formula: "1 − 0.4 heaviside(x − 2.2) heaviside(0.3 − y)", units: "1", role: porosity} + +solution_paths: + discretizations: + - name: level_set_five + subproblems: + - name: vof + equation: "∂(θ χh)/∂t + ∇·(θ v χh) = 0" + - name: mcorr + equation: "θ (heaviside(φ + φc) − χh) − ∇·(εd ∇φc) = 0" diff --git a/tests/test_boundary_declaration.py b/tests/test_boundary_declaration.py new file mode 100644 index 0000000..ad93c16 --- /dev/null +++ b/tests/test_boundary_declaration.py @@ -0,0 +1,160 @@ +"""Boundary kind (strong, weak, none) and porosity (C42 round 5): how a condition reaches the discrete problem, and the +porosity of the two-phase model, stated so that a generator picks its face kernel and its coefficient by the spec.""" + +import pytest + +pytest.importorskip("strictyaml") +pytest.importorskip("sympy") + +from _formulation import TWO_PHASE, roundtrip, subproblem # noqa: E402 +from ymf.boundaries import BoundaryError, check_condition, kind_of, kinds # noqa: E402 +from ymf.conditions import expand_condition # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 +from ymf.symbolic import split_problem # noqa: E402 +from ymf.vocabulary import VocabularyError, check, coefficient_by_role # noqa: E402 + +DAMBREAK = TWO_PHASE / "dambreak.ymf" +FORMULATION = TWO_PHASE / "dambreak_formulation.ymf" +POROUS = TWO_PHASE / "dambreak_porous.ymf" + + +# --- the kind of a condition -------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("condition, kind", [ + ({"type": "dirichlet"}, "strong"), + ({"type": "dirichlet", "imposed": "weak"}, "weak"), + ({"type": "slip"}, "strong"), ({"type": "inflow"}, "strong"), ({"type": "characteristic"}, "strong"), + ({"type": "neumann"}, "none"), ({"type": "robin"}, "none"), ({"type": "open"}, "none"), + ({"type": "open", "imposed": "none"}, "none"), + ({"type": "periodic"}, None), +]) +def test_the_kind_is_stated_or_the_types_default(condition, kind): + check_condition(condition, "c") + assert kind_of(condition) == kind + + +@pytest.mark.parametrize("condition, message", [ + ({"type": "neumann", "imposed": "strong"}, "a neumann condition is imposed none"), + ({"type": "robin", "imposed": "weak"}, "a robin condition is imposed none"), + ({"type": "open", "imposed": "weak"}, "a open condition is imposed none"), + ({"type": "dirichlet", "imposed": "none"}, "imposes a value, strong or weak"), + ({"type": "periodic", "imposed": "weak"}, "periodic condition identifies faces"), + ({"type": "dirichlet", "penalty": 10.0}, "penalty belong to a weak condition"), + ({"type": "dirichlet", "imposed": "strong", "form": "symmetric"}, "form belong to a weak condition"), + ({"type": "dirichlet", "imposed": "weak", "penalty": -1.0}, "penalty -1.0 is not a positive number"), + ({"type": "dirichlet", "imposed": "weak", "form": "complete"}, "form complete is not one of symmetric"), + ({"type": "dirichlet", "imposed": "maybe"}, "imposed maybe is not one of strong, weak, none"), +]) +def test_a_kind_that_does_not_fit_its_type_is_refused(condition, message): + with pytest.raises(BoundaryError, match=message): + check_condition(condition, "c") + + +def test_an_alias_gives_its_kind_to_the_dirichlet_part_only(): + slip = expand_condition({"variable": "v", "type": "slip", "region": "w", "imposed": "weak", "penalty": 50.0, + "form": "incomplete"}, rank=1) + normal, tangential = slip + assert normal["type"] == "dirichlet" and (normal["imposed"], normal["penalty"], normal["form"]) == ( + "weak", 50.0, "incomplete") + assert tangential["type"] == "neumann" and not {"imposed", "penalty", "form"} & set(tangential) + assert kind_of(tangential) == "none" + + +# --- the dam break ------------------------------------------------------------------------------------------------ + +def test_the_dam_break_states_how_each_condition_is_imposed(): + by = {(k["region"], k["variable"], k["type"]): k for k in kinds(load_ymf(FORMULATION))} + assert by[("walls", "v", "dirichlet")]["kind"] == "weak" and by[("walls", "v", "dirichlet")]["form"] == "symmetric" + assert by[("walls", "v", "neumann")]["kind"] == "none" + assert by[("top", "p", "dirichlet")]["kind"] == "weak" + assert by[("top", "v", "neumann")]["kind"] == "none" + assert by[("top", "χ", "dirichlet")]["kind"] == "strong" and by[("top", "χ", "dirichlet")]["only"] == "inflow" + + +def test_the_split_problem_gives_each_sub_problem_its_kinds_so_a_generator_picks_its_faces(): + split = {s["name"]: s for s in split_problem(load_ymf(FORMULATION), "level_set_five")["subproblems"]} + # VOF: the air entering through the top is strong, an upwind flux with the Dirichlet inflow (the engine's Strong) + (inflow,) = split["vof"]["boundary_conditions"] + assert (inflow["kind"], inflow["only"], inflow["carried_by"]) == ("strong", "inflow", "χh") + # RANS2P: weak Dirichlet with the symmetric adjoint (WeakDirichlet), the open part natural (Flux) + assert {(c["variable"], c["type"], c["kind"]) for c in split["flow"]["boundary_conditions"]} == { + ("v", "dirichlet", "weak"), ("v", "neumann", "none"), ("p", "dirichlet", "weak")} + assert all(c["form"] == "symmetric" for c in split["flow"]["boundary_conditions"] if c["kind"] == "weak") + + +def test_a_spec_that_states_no_kind_gets_the_types_default_in_the_split_problem(): + split = {s["name"]: s for s in split_problem(load_ymf(DAMBREAK), "level_set_five")["subproblems"]} + assert {c["kind"] for c in split["flow"]["boundary_conditions"]} == {"strong", "none"} + assert not any("form" in c or "penalty" in c for c in split["flow"]["boundary_conditions"]) + + +def test_a_bad_kind_in_a_condition_set_is_refused_on_load_and_says_where(): + doc = load_ymf(FORMULATION) + doc["model"]["strong_form"]["condition_sets"]["atmosphere"][1] = {"variable": "v", "type": "open", "imposed": "weak"} + with pytest.raises(VocabularyError, match=r"condition_sets\.atmosphere\[1\] \(open on v\).*imposed none"): + check(doc) + + +def test_the_kinds_survive_the_archive_and_are_part_of_its_key(tmp_path): + from ymf import closure + realization = {"h": 0.0322} + spec, again, digest = roundtrip(tmp_path, FORMULATION, "level_set_five", realization) + assert kinds(again) == kinds(spec) + changed = load_ymf(FORMULATION) + changed["model"]["strong_form"]["condition_sets"]["atmosphere"][2]["imposed"] = "weak" + assert closure.input_digest(changed, "level_set_five", realization) != digest + + +# --- porosity ----------------------------------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def porous(): + return load_ymf(POROUS) + + +def test_the_two_phase_model_states_its_porosity_by_role(porous): + assert coefficient_by_role(porous, "porosity") == "θ" + assert coefficient_by_role(load_ymf(DAMBREAK), "porosity") is None + + +def test_the_sub_problems_say_which_use_the_porosity(porous): + split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + assert {n for n, s in split.items() if "porosity" in s.get("coefficient_roles", {})} == {"flow", "vof", "mcorr"} + assert split["flow"]["coefficient_roles"]["density"] == "ρ" + # NCLS has none, and the plain dam break none anywhere + plain = {s["name"]: s for s in split_problem(load_ymf(DAMBREAK), "level_set_five")["subproblems"]} + assert not any("porosity" in s.get("coefficient_roles", {}) for s in plain.values()) + + +def test_vof_carries_the_porosity_in_its_mass_and_its_flux_as_the_generator_spikes_hand_made_form_did(porous): + # generator/make_inputs.py wrote "∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0" in a Space by hand (porosity ε a per-point field); + # the spec now states it, with θ inlined as the expression of the coordinates it is + split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + eq = split["vof"]["adr"]["equations"][0] + assert eq["mass"]["m"].startswith("χh*(") and "numpy.select" in eq["mass"]["m"] + numpy = pytest.importorskip("numpy") + env = {"numpy": numpy, "h": 0.0322, "x": 2.3, "y": 0.2, "χh": 1.0} + run = lambda code: eval(code, {"__builtins__": {}}, env) # noqa: S307 + assert run(eq["mass"]["dm"]["χh"]) == pytest.approx(run(eq["mass"]["m"])) # m = θ χh, so dm/dχh = θ + assert all(f.startswith("χh*") and "v_%d" % i in f for i, f in enumerate(eq["advection"]["f"])) + assert eq["mass"]["depends_on"] == {"χh": "linear"} + # NCLS is the dam break's, unchanged + plain = {s["name"]: s for s in split_problem(load_ymf(DAMBREAK), "level_set_five")["subproblems"]} + assert split["ncls"]["adr"] == plain["ncls"]["adr"] + + +def test_the_porosity_is_one_where_it_is_one_and_below_one_in_the_block(porous): + numpy = pytest.importorskip("numpy") + split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + m = split["vof"]["adr"]["equations"][0]["mass"]["dm"]["χh"] + env = {"numpy": numpy, "h": 0.0322} + at = lambda x, y: eval(m, {"__builtins__": {}}, dict(env, x=x, y=y)) # noqa: S307 + assert at(1.0, 1.0) == pytest.approx(1.0) # open flow + assert at(3.0, 0.1) == pytest.approx(0.6) # inside the block + assert 0.6 < at(2.2, 0.1) < 1.0 # the edge, smoothed over 1.5 h + + +def test_the_porosity_survives_the_archive(tmp_path): + spec, again, _ = roundtrip(tmp_path, POROUS, "level_set_five", {"h": 0.0322}) + assert coefficient_by_role(again, "porosity") == "θ" + assert subproblem(again, "level_set_five", "vof")["equation"] == "∂(θ χh)/∂t + ∇·(θ v χh) = 0" diff --git a/tests/test_split.py b/tests/test_split.py index 03d7835..f23429f 100644 --- a/tests/test_split.py +++ b/tests/test_split.py @@ -246,7 +246,7 @@ def test_a_condition_on_a_coefficient_goes_to_its_carrier(split): assert inflow == {"type": "dirichlet", "only": "inflow", "variable": "χ", "region": "top", "where": "(abs(y - 1.8) <= tol)", "carried_by": "χh", "expanded_from": {"type": "inflow", "set": "atmosphere"}, - "components": ["χh"], "value": "1.0"} + "components": ["χh"], "value": "1.0", "kind": "strong"} def test_a_condition_reaches_every_sub_problem_that_solves_for_its_variable(dambreak): From a0685a69d00a474d617e502ded8c2fbc406d5e5f Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:37:26 +0100 Subject: [PATCH 4/7] The dispersive family: hyperbolic-relaxation closure and its auxiliary unknowns (C42 round 5, 4/5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C5 step 4 part 2 found no ymf spec for a dispersive model: the family word (assumptions depth_averaged + dispersive, round 3) existed, but a spec could not say the closure, the three auxiliary unknowns GN_SW2DCV solves beside h and q (hη, hw, hβ), what each is, or which coefficients of the model the discretization supplies. A sub-problem now states dispersion: {closure: hyperbolic_relaxation, closes: [Pd, Qd], auxiliaries: [{name: hη, role: relaxed_depth, units}, {name: hw, role: relaxed_divergence, ..}, {name: hβ, role: relaxed_bed_flux, ..}]} with `initial` optional per auxiliary (default: the decks' hη = h², hw = hβ = 0; a solitary wave's hw is not 0) and each role's `boundary_like` (hη and hw take h's boundary data, hβ q's, as the decks' comment says). Checked on load: only a dispersive-family model may state it; one auxiliary per role; names not already the model's; `closes` names the model's two coefficients with roles dispersive_pressure (m3/s2) and dispersive_bed_force (m2/s2), which are new coefficient roles. The model stays closure-free: the dispersive momentum is the shallow-water one with the pressure g h²/2 + Pd and the bed force Qd ∇Z, grouped as GN_SW2DCV.h's source terms (transcribed, not run against the kernel). What C5 can now read (split_problem): `dispersion` with the resolved auxiliaries (six unknowns: h, q_0, q_1 and the three), and Pd and Qd as `reads` fields (`via: dispersion`) with their gradients in the momentum's reaction (grad_Pd_0, grad_Pd_1), so a dispersion-aware reader sees what the closure owes the momentum. Fixtures: dispersive.ymf (the family, assumptions removed and added by `remove:`), dispersive_numerics.ymf (GN_SW2DCV: the scheme states lumped_mass only, the one option the cell reads) and circular_dam_dispersive.ymf (circular_damBreak.py, sw_model 1: 49 x 49 cells, walls, the deck's auxiliary defaults). Not done: the relaxed equations and the relaxation parameter lambda (LAMBDA_MGN = 1 compiled in) are not in the spec; santos_step needs atan (its bathymetry) and conical_island a state on part of the boundary; listed in the handoff. Tests (27 new, whole suite 971 -> 998 passed, 13 skipped): defaults and the decks' roles, 13 refusals in resolve, the family and state of the case, six unknowns and the closure's fields in the split record, what the deck set by hand, five refusals on load naming their path, the strict schema, and the archive keeps it with a digest that moves when an auxiliary's initial value does. Co-Authored-By: Claude Sonnet 5.5 --- src/ymf/dispersion.py | 160 ++++++++++++++++ src/ymf/schema.py | 8 + src/ymf/symbolic/split.py | 8 + src/ymf/vocabulary.py | 15 ++ .../shallow_water/circular_dam_dispersive.ymf | 35 ++++ tests/fixtures/shallow_water/dispersive.ymf | 28 +++ .../shallow_water/dispersive_numerics.ymf | 39 ++++ tests/test_dispersion.py | 174 ++++++++++++++++++ 8 files changed, 467 insertions(+) create mode 100644 src/ymf/dispersion.py create mode 100644 tests/fixtures/shallow_water/circular_dam_dispersive.ymf create mode 100644 tests/fixtures/shallow_water/dispersive.ymf create mode 100644 tests/fixtures/shallow_water/dispersive_numerics.ymf create mode 100644 tests/test_dispersion.py diff --git a/src/ymf/dispersion.py b/src/ymf/dispersion.py new file mode 100644 index 0000000..94681f3 --- /dev/null +++ b/src/ymf/dispersion.py @@ -0,0 +1,160 @@ +"""The dispersive shallow-water family (Serre-Green-Naghdi) solved by hyperbolic relaxation: the closure, its auxiliary +unknowns and their roles. + +C5's dispatcher maps a spec onto proteus's ``GN_SW2DCV``, which solves six unknowns (h, hu, hv, hη, hw, hβ): the model's +depth and discharge, and three auxiliaries the closure introduces. The spec could not say them: the model's family +(``dispersive``, round 3) was a word, with no way to state the closure, the auxiliaries, what each is, or what the +discretization supplies of the model. A sub-problem now states:: + + dispersion: + closure: hyperbolic_relaxation + closes: [Pd, Qd] # the model's coefficients the closure supplies + auxiliaries: + - {name: hη, role: relaxed_depth, units: m2} + - {name: hw, role: relaxed_divergence, units: m2/s, initial: "0"} # optional + - {name: hβ, role: relaxed_bed_flux, units: m2/s} + +* ``closure``: how the dispersive terms are discretized. ``hyperbolic_relaxation`` (Guermond, Kees, Popov, Tovar): the + elliptic (non-hydrostatic) problem of Serre-Green-Naghdi is replaced by three transport equations that relax toward it + over a length of the element size, so the whole system is hyperbolic and one explicit scheme solves it. +* ``closes``: the model's coefficients whose values the closure computes from the auxiliaries, by role: the dispersive + pressure (``dispersive_pressure``, the non-hydrostatic part of the pressure) and the dispersive bed force + (``dispersive_bed_force``, the topography-dispersion force along ∇Z). Each must be a coefficient of the model with that + role, so the model's equations are the same whichever closure solves them. +* ``auxiliaries``: one per role of :data:`AUXILIARY_ROLES`, each once. ``name`` is the unknown's name, ``units`` its units, + ``initial`` (optional) its initial value as a formula in the model's unknowns and coordinates (a solitary wave's hw is + not 0: proteus's santos_step deck gives one); unstated, the role's + default (:data:`AUXILIARY_ROLES`) applies (proteus's decks: ``hη = h²``, ``hw = hβ = 0``). Boundary data is the role's + ``boundary_like`` (hη and hw as h, hβ as q): the auxiliary carries no condition of its own in the spec. + +Only a model of family ``dispersive_shallow_water`` may state it (checked on load by ``ymf.vocabulary``). + +Stdlib only, like the rest of the spec core. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +__all__ = ["DispersionError", "AUXILIARY_ROLES", "resolve", "check"] + + +class DispersionError(ValueError): + """A dispersion block a spec states that does not make sense.""" + + +#: role -> what the auxiliary is, the value it has when the relaxation is exact (``consistent``, as proteus's decks write +#: it: "hη -> h², hβ -> q·∇Z, hw -> h² ∇·u + 3/2 hβ"), its default initial value (the decks', which take hw and hβ as 0: +#: "often okay to take hβ = 0"), and whose boundary data it takes (``h`` or ``q``). +AUXILIARY_ROLES: Dict[str, Dict[str, str]] = { + "relaxed_depth": { + "means": "h·η, the depth's relaxed copy", + "consistent": "h^2", "initial": "h^2", "boundary_like": "h"}, + "relaxed_divergence": { + "means": "h·w, the relaxed vertical-velocity moment", + "consistent": "h^2 ∇·u + (3/2) hβ", "initial": "0", "boundary_like": "h"}, + "relaxed_bed_flux": { + "means": "h·β, the relaxed bed-slope flux", + "consistent": "q·∇Z", "initial": "0", "boundary_like": "q"}, +} + +#: the coefficient roles a closure supplies, by closure +CLOSURES: Dict[str, Dict[str, Any]] = { + "hyperbolic_relaxation": { + "means": "the non-hydrostatic problem replaced by three transport equations that relax toward it over a length " + "of the element size; one explicit hyperbolic system", + "closes": ("dispersive_pressure", "dispersive_bed_force"), + "roles": tuple(AUXILIARY_ROLES), + }, +} + +_KEYS = {"closure", "closes", "auxiliaries"} +_AUX_KEYS = {"name", "role", "units", "initial"} + + +def resolve(block: Any, where: str = "dispersion") -> Dict[str, Any]: + """The block with ymf's words, every auxiliary's default ``initial`` filled in and ``boundary_like`` added: + ``{closure, closes, auxiliaries: [{name, role, units?, initial, initial_is_default, boundary_like}]}``. Raises + :class:`DispersionError`.""" + if not isinstance(block, dict) or "closure" not in block: + raise DispersionError("%s: give closure: (%s)" % (where, ", ".join(CLOSURES))) + unknown = sorted(set(block) - _KEYS) + if unknown: + raise DispersionError("%s: no key %s; its keys are %s" % (where, ", ".join(unknown), ", ".join(sorted(_KEYS)))) + closure = str(block["closure"]) + if closure not in CLOSURES: + raise DispersionError("%s.closure: %s is not one of %s" % (where, closure, ", ".join(CLOSURES))) + spec = CLOSURES[closure] + closes = [str(c) for c in (block.get("closes") or [])] + if not closes: + raise DispersionError("%s: closes: names the model's coefficients the closure supplies (%s)" % ( + where, " and ".join(spec["closes"]))) + if len(set(closes)) != len(closes): + raise DispersionError("%s.closes: a coefficient twice" % (where,)) + auxiliaries = block.get("auxiliaries") or [] + if not isinstance(auxiliaries, list) or not auxiliaries: + raise DispersionError("%s.auxiliaries: one per role (%s)" % (where, ", ".join(spec["roles"]))) + out: List[Dict[str, Any]] = [] + seen_roles: Dict[str, str] = {} + names: List[str] = [] + for i, aux in enumerate(auxiliaries): + here = "%s.auxiliaries[%d]" % (where, i) + if not isinstance(aux, dict) or "name" not in aux or "role" not in aux: + raise DispersionError("%s: give name: and role:" % (here,)) + unread = sorted(set(aux) - _AUX_KEYS) + if unread: + raise DispersionError("%s: no key %s; its keys are %s" % (here, ", ".join(unread), ", ".join(sorted(_AUX_KEYS)))) + role = str(aux["role"]) + if role not in AUXILIARY_ROLES: + raise DispersionError("%s.role: %s is not one of %s" % (here, role, ", ".join(AUXILIARY_ROLES))) + if role not in spec["roles"]: + raise DispersionError("%s.role: %s is not an auxiliary of %s" % (here, role, closure)) + if role in seen_roles: + raise DispersionError("%s.role: %s is already the role of %s" % (here, role, seen_roles[role])) + name = str(aux["name"]) + if name in names: + raise DispersionError("%s.name: %s is already an auxiliary" % (here, name)) + seen_roles[role] = name + names.append(name) + entry: Dict[str, Any] = {"name": name, "role": role} + if aux.get("units") is not None: + entry["units"] = str(aux["units"]) + stated = aux.get("initial") + entry["initial"] = str(stated) if stated is not None else AUXILIARY_ROLES[role]["initial"] + entry["initial_is_default"] = stated is None + entry["boundary_like"] = AUXILIARY_ROLES[role]["boundary_like"] + out.append(entry) + absent = [r for r in spec["roles"] if r not in seen_roles] + if absent: + raise DispersionError("%s.auxiliaries: %s needs one for each of %s; missing %s" % ( + where, closure, ", ".join(spec["roles"]), ", ".join(absent))) + return {"closure": closure, "closes": closes, "auxiliaries": out} + + +def check(block: Any, doc: Dict[str, Any], family: Optional[str], where: str = "dispersion") -> Dict[str, Any]: + """:func:`resolve`, and the block agrees with the model: its family is dispersive, the auxiliaries' names are not + the model's, and each ``closes`` is a coefficient of the model with the role the closure supplies.""" + out = resolve(block, where) + if family != "dispersive_shallow_water": + raise DispersionError("%s: only a model of family dispersive_shallow_water has a dispersion; this one is %s" % ( + where, family or "of no family")) + strong = ((doc.get("model") or {}).get("strong_form") or {}) + taken = set((strong.get("coefficients") or {})) + for u in strong.get("unknowns") or []: + taken.add(u if isinstance(u, str) else u.get("name")) + for aux in out["auxiliaries"]: + if aux["name"] in taken: + raise DispersionError("%s: the auxiliary %s is already a name in the model" % (where, aux["name"])) + from ymf.vocabulary import coefficient_roles + by_role = {v: k for k, v in coefficient_roles(doc).items()} + wanted = list(CLOSURES[out["closure"]]["closes"]) + for name in out["closes"]: + role = by_role.get(name) + if role not in wanted: + raise DispersionError("%s.closes: %s has role %s; %s supplies %s" % ( + where, name, role or "none", out["closure"], " and ".join(wanted))) + got = sorted(by_role[n] for n in out["closes"]) + if got != sorted(wanted): + raise DispersionError("%s.closes: %s supplies %s, and these are %s" % ( + where, out["closure"], " and ".join(wanted), " and ".join(got))) + return out diff --git a/src/ymf/schema.py b/src/ymf/schema.py index f1ca4c5..121dd69 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -241,6 +241,14 @@ # coefficients of the model this sub-problem freezes: name -> previous_step # | previous_iterate (ymf.vocabulary.LAG_WHEN), checked on load Optional("lagged_coefficients"): MapPattern(Str(), Str()), + # the dispersive family's closure, the coefficients it supplies and the + # auxiliary unknowns it introduces (ymf.dispersion, checked on load) + Optional("dispersion"): Map({ + "closure": Str(), + Optional("closes"): Seq(Str()), + Optional("auxiliaries"): Seq(Map({ + "name": Str(), "role": Str(), Optional("units"): Str(), Optional("initial"): Str()})), + }), Optional("solver"): SolverConfig, # options a dispatcher cannot infer yet, for one solver: an interim hint # it checks against what it infers, and drops once it covers them diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index eb67315..057d38a 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -137,6 +137,9 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: "finite_element", "time_integration", "proteus"): if key in sub: record[key] = sub[key] + if sub.get("dispersion") is not None: + from ymf.dispersion import resolve as resolve_dispersion + record["dispersion"] = resolve_dispersion(sub["dispersion"], where + " dispersion") stabilization = for_subproblem(entry, sub) if stabilization is not None: record["stabilization"] = stabilization @@ -179,6 +182,11 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: fields[carrier] = 0 read["carried_by"] = carrier reads[name] = read + # the coefficients a dispersion closure computes (Pd, Qd) are fields the solver supplies at each point, with their + # gradients (the dispersive pressure's gradient is a force), as a field read from another sub-problem is + for name in (sub.get("dispersion") or {}).get("closes") or []: + fields[name] = 0 + reads[name] = {"via": "dispersion", "at": "current_step"} known = Space(dim, own, {}, fields).known for name, read in reads.items(): field = read.get("carried_by", name) diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index ed123cb..fcae7ca 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -409,6 +409,11 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: "canopy_drag": {"units": "m2/s2", "means": "the drag force of a canopy per unit plan area, " "over the density"}, "diffusivity": {"units": "m2/s", "means": "a diffusion coefficient"}, + # the dispersive family's two coefficients a closure supplies (ymf.dispersion) + "dispersive_pressure": {"units": "m3/s2", "means": "the non-hydrostatic part of the depth-integrated pressure " + "(ymf.dispersion: supplied by the closure)"}, + "dispersive_bed_force": {"units": "m2/s2", "means": "the topography-dispersion force per unit mass along the bed " + "gradient (supplied by the closure)"}, } #: the words of each kind, for check() and canonical() @@ -523,6 +528,14 @@ def _check_boundary_kinds(strong: Dict[str, Any]) -> None: raise VocabularyError(str(exc)) from None +def _check_dispersion(doc: Dict[str, Any], block: Any, family: Optional[str], where: str) -> None: + from ymf.dispersion import DispersionError, check as check_dispersion + try: + check_dispersion(block, doc, family, where) + except DispersionError as exc: + raise VocabularyError(str(exc)) from None + + def _check_spaces(block: Any, where: str) -> None: from ymf.spaces import SpaceError, check_finite_element try: @@ -572,6 +585,8 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st _word("time_integration", sub["time_integration"], here + ".time_integration") _check_stabilization(sub.get("stabilization"), here + ".stabilization") _check_lagged_coefficients(doc, sub, here) + if sub.get("dispersion") is not None: + _check_dispersion(doc, sub["dispersion"], family, here + ".dispersion") _check_solver(sub.get("solver"), here) _check_spaces(sub.get("finite_element"), here + ".finite_element") for label, binding in (sub.get("binds") or {}).items(): diff --git a/tests/fixtures/shallow_water/circular_dam_dispersive.ymf b/tests/fixtures/shallow_water/circular_dam_dispersive.ymf new file mode 100644 index 0000000..8ea002e --- /dev/null +++ b/tests/fixtures/shallow_water/circular_dam_dispersive.ymf @@ -0,0 +1,35 @@ +# test/SWFlow/circular_damBreak.py with sw_model = 1 (the dispersive model), +# its default: a circular dam of radius 2 m and height 0.8 m over still water +# of depth 1 m at the middle of a 20 m × 20 m flat basin, walls all round. The +# deck's 50 × 50 nodes are 49 × 49 cells. The auxiliaries take the deck's +# initial values (hη = h², hw = hβ = 0), which the spec leaves to their roles. +# The dam's edge: the deck writes (x−10)² + (y−10)² <= r² (h + 0.8 on the +# circle), ymf's heaviside is 1/2 there; the two agree off the circle. +extends: dispersive_numerics.ymf + +model: + name: "Circular dam break, dispersive, 20 m × 20 m (circular_damBreak, sw_model 1)" + physical_model: {provenance: human_specified} + strong_form: + domain: "Ω = [0, 20] × [0, 20], t ∈ (0, 20]" + boundary_regions: + - {name: all, where: "∂Ω"} + boundary_sets: + - {region: all, set: wall} + initial_conditions: + - {field: h, type: function, formula: "max(1 + 0.8 heaviside(4 − (x − 10)² − (y − 10)²) − Z, 0)", units: m} + - {field: q, type: constant, value: 0.0} + coefficients: + g: {value: 9.81} + n: {value: 0.0} + θ: {value: 1.0} + Z: {value: 0.0} + α: {value: 0.0} + β: {value: 0.0} + +solution_paths: + analytical: [] + discretizations: + - name: relaxed_convex_limited + mesh: {cells: 49} + step_control: {type: min_cfl, cfl: 0.25} diff --git a/tests/fixtures/shallow_water/dispersive.ymf b/tests/fixtures/shallow_water/dispersive.ymf new file mode 100644 index 0000000..898771d --- /dev/null +++ b/tests/fixtures/shallow_water/dispersive.ymf @@ -0,0 +1,28 @@ +# The dispersive (Serre-Green-Naghdi) shallow-water model, the family C5's +# dispatcher maps onto proteus's GN_SW2DCV (C42 round 5): the shallow_water.ymf +# model with the non-hydrostatic pressure Pd added to the hydrostatic one, and +# the topography-dispersion force Qd along the bed gradient. Both are +# coefficients the *closure* supplies: how they are computed is the +# discretization's (ymf.dispersion, `dispersion: {closure: hyperbolic_relaxation}` +# in proteus_numerics's sibling dispersive_numerics.ymf), so the model's +# equations are the same whichever closure solves them. The grouping follows +# GN_SW2DCV.h's source terms: the pressure 0.5 g h² + p̃ wherever the +# hydrostatic one stood, and (0.5 R2 − 0.25 R3) ∇Z as the bed force. +extends: shallow_water.ymf +ymf_state: abstract +remove: + - "model.physical_model.assumptions[hydrostatic]" + - "model.physical_model.assumptions[nondispersive]" + +model: + physical_model: + assumptions: [depth_averaged, dispersive] + strong_form: + equation_formulation: "Serre-Green-Naghdi equations (depth averaged, non-hydrostatic), conservative variables, porous medium" + equations: + - name: momentum + for: q + equation: "∂(θ q)/∂t + ∇·(θ q⊗q/h) + ∇(θ (g h²/2 + Pd)) − (g h²/2 + Pd)∇θ + θ g h ∇Z − θ Qd ∇Z + θ τb + Fd = 0 in Ω" + coefficients: + Pd: {units: m3/s2, role: dispersive_pressure} # the non-hydrostatic pressure, over the density, integrated over the depth + Qd: {units: m2/s2, role: dispersive_bed_force} # the topography-dispersion force, over the density, per unit ∇Z diff --git a/tests/fixtures/shallow_water/dispersive_numerics.ymf b/tests/fixtures/shallow_water/dispersive_numerics.ymf new file mode 100644 index 0000000..d7614ea --- /dev/null +++ b/tests/fixtures/shallow_water/dispersive_numerics.ymf @@ -0,0 +1,39 @@ +# How proteus solves the dispersive model: GN_SW2DCV, the shallow-water +# scheme of proteus_numerics.ymf (convex-limited graph viscosity, SSP RK3) +# on the relaxed system of six unknowns: the model's h and q, and the three +# auxiliaries the hyperbolic-relaxation closure introduces. GN_SW2DCV reads +# only lumped_mass of the scheme's options (it uses the lumped solve whatever +# it says), so the scheme states no entropy-viscosity coefficient. +extends: dispersive.ymf +ymf_state: abstract + +solution_paths: + analytical: [] + discretizations: + - name: relaxed_convex_limited + provenance: proteus_derived + binds: + he: {meaning: element_size} # the relaxation length + hε: {meaning: dry_depth} + regularize: + heaviside: {by: smoothed_heaviside, width: he} + inverse: {by: wet_dry_cutoff, of: h, width: hε} + step_control: {type: min_cfl, cfl: 0.33} + solver: {type: time_marching, linear_solver: petsc} + discretization: + scheme: graph_viscosity_convex_limiting + time_integration: ssp_rk3 + lumped_mass: false + subproblems: + - name: gn + solves: [mass, momentum] + finite_element: {fields: {family: CG, order: 1}} + time_integration: ssp_rk3 + dispersion: + closure: hyperbolic_relaxation + closes: [Pd, Qd] + auxiliaries: + - {name: hη, role: relaxed_depth, units: m2} + - {name: hw, role: relaxed_divergence, units: m2/s} + - {name: hβ, role: relaxed_bed_flux, units: m2/s} + proteus: {model: GN_SW2DCV} diff --git a/tests/test_dispersion.py b/tests/test_dispersion.py new file mode 100644 index 0000000..ea4c86d --- /dev/null +++ b/tests/test_dispersion.py @@ -0,0 +1,174 @@ +"""ymf.dispersion (C42 round 5): the dispersive shallow-water family, solved by hyperbolic relaxation, stated so that C5's +dispatcher maps it onto GN_SW2DCV: the closure, the coefficients it supplies, and the three auxiliary unknowns.""" + +import copy + +import pytest + +pytest.importorskip("strictyaml") +pytest.importorskip("sympy") + +from _formulation import SHALLOW_WATER, roundtrip, subproblem # noqa: E402 +from ymf.dispersion import AUXILIARY_ROLES, DispersionError, check, resolve # noqa: E402 +from ymf.references import YmfReferenceError # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 +from ymf.state import reached # noqa: E402 +from ymf.symbolic import split_problem # noqa: E402 +from ymf.vocabulary import VocabularyError, check as check_vocabulary, coefficient_by_role, family_of # noqa: E402 + +CIRCULAR = SHALLOW_WATER / "circular_dam_dispersive.ymf" +GN = "relaxed_convex_limited" + +BLOCK = {"closure": "hyperbolic_relaxation", "closes": ["Pd", "Qd"], "auxiliaries": [ + {"name": "hη", "role": "relaxed_depth", "units": "m2"}, + {"name": "hw", "role": "relaxed_divergence"}, + {"name": "hβ", "role": "relaxed_bed_flux"}]} + + +def _block(**changes): + out = copy.deepcopy(BLOCK) + out.update(changes) + return out + + +# --- resolve ------------------------------------------------------------------------------------------------------ + +def test_the_defaults_are_the_decks_and_each_auxiliary_says_whose_boundary_data_it_takes(): + r = resolve(BLOCK) + assert [(a["name"], a["initial"], a["initial_is_default"], a["boundary_like"]) for a in r["auxiliaries"]] == [ + ("hη", "h^2", True, "h"), ("hw", "0", True, "h"), ("hβ", "0", True, "q")] + assert r["closes"] == ["Pd", "Qd"] and r["closure"] == "hyperbolic_relaxation" + + +def test_a_stated_initial_value_replaces_the_default_and_says_so(): + # a solitary wave's hw is not 0 (test/SWFlow/santos_step.py) + aux = copy.deepcopy(BLOCK["auxiliaries"]) + aux[1]["initial"] = "-h^2 c h0 dh" + hw = resolve(_block(auxiliaries=aux))["auxiliaries"][1] + assert (hw["initial"], hw["initial_is_default"]) == ("-h^2 c h0 dh", False) + + +def test_the_three_roles_are_the_ones_of_the_decks_comment(): + # "heta -> h^2, hbeta -> q.grad(Z), hw -> h^2 div(u) + 3/2 hbeta; the BCs for heta and hw are those of h, hbeta's those of x_mom" + assert {r: (a["consistent"], a["boundary_like"]) for r, a in AUXILIARY_ROLES.items()} == { + "relaxed_depth": ("h^2", "h"), "relaxed_divergence": ("h^2 ∇·u + (3/2) hβ", "h"), + "relaxed_bed_flux": ("q·∇Z", "q")} + + +@pytest.mark.parametrize("block, message", [ + ("hyperbolic_relaxation", "give closure"), + ({"closes": ["Pd"]}, "give closure"), + (_block(closure="projection"), "closure: projection is not one of hyperbolic_relaxation"), + (_block(extra=1), "no key extra"), + (_block(closes=[]), "closes: names the model's coefficients"), + (_block(closes=["Pd", "Pd"]), "closes: a coefficient twice"), + (_block(auxiliaries=[]), "one per role"), + (_block(auxiliaries=BLOCK["auxiliaries"][:2]), "missing relaxed_bed_flux"), + (_block(auxiliaries=BLOCK["auxiliaries"] + [{"name": "hq", "role": "relaxed_depth"}]), + r"auxiliaries\[3\]\.role: relaxed_depth is already the role of hη"), + (_block(auxiliaries=[BLOCK["auxiliaries"][0], {"name": "hη", "role": "relaxed_divergence"}, + BLOCK["auxiliaries"][2]]), "name: hη is already an auxiliary"), + (_block(auxiliaries=[{"name": "hη", "role": "temperature"}] + BLOCK["auxiliaries"][1:]), + "role: temperature is not one of relaxed_depth"), + (_block(auxiliaries=[{"role": "relaxed_depth"}] + BLOCK["auxiliaries"][1:]), "give name: and role:"), + (_block(auxiliaries=[dict(BLOCK["auxiliaries"][0], damping=1)] + BLOCK["auxiliaries"][1:]), "no key damping"), +]) +def test_a_dispersion_that_does_not_make_sense_is_refused(block, message): + with pytest.raises(DispersionError, match=message): + resolve(block) + + +# --- the spec ----------------------------------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def circular(): + return load_ymf(CIRCULAR) + + +def test_the_model_is_the_dispersive_family_with_the_two_coefficients_the_closure_supplies(circular): + assert family_of(circular) == "dispersive_shallow_water" + assert circular["model"]["physical_model"]["assumptions"] == ["depth_averaged", "dispersive"] + assert coefficient_by_role(circular, "dispersive_pressure") == "Pd" + assert coefficient_by_role(circular, "dispersive_bed_force") == "Qd" + # the family is abstract, the case reaches discretized with cells per axis not yet needed: one square count + assert reached(circular)[0] == "discretized" + + +def test_the_split_problem_gives_the_six_unknowns_of_gn_sw2dcv(circular): + (gn,) = split_problem(circular, GN)["subproblems"] + # h and the two components of q from the model, and the three auxiliaries the closure introduces + assert gn["unknowns"] == {"h": ["h"], "q": ["q_0", "q_1"]} + aux = [a["name"] for a in gn["dispersion"]["auxiliaries"]] + assert aux == ["hη", "hw", "hβ"] + assert sum(len(v) for v in gn["unknowns"].values()) + len(aux) == 6 + # the closure supplies the dispersive pressure and bed force at each point, with their gradients (a force): the + # momentum reads the gradient of Pd, the mass nothing + assert gn["reads"]["Pd"] == {"via": "dispersion", "at": "current_step", "components": ["Pd"]} + assert gn["reads"]["Qd"]["components"] == ["Qd"] + momentum = {e["component"]: e for e in gn["adr"]["equations"]} + assert "grad_Pd_0" in momentum["q_0"]["reaction"]["r"] and "grad_Pd_1" in momentum["q_1"]["reaction"]["r"] + assert "reaction" not in momentum["h"] + assert gn["coefficient_roles"]["dispersive_pressure"] == "Pd" + + +def test_the_circular_dam_states_what_the_deck_set_by_hand(circular): + # test/SWFlow/circular_damBreak.py, sw_model 1: hη = h², hw = hβ = 0, walls all round, 49 × 49 cells + (gn,) = split_problem(circular, GN)["subproblems"] + assert {a["role"]: a["initial"] for a in gn["dispersion"]["auxiliaries"]} == { + "relaxed_depth": "h^2", "relaxed_divergence": "0", "relaxed_bed_flux": "0"} + assert all(c["variable"] == "q" and c["type"] in ("dirichlet", "neumann") for c in gn["boundary_conditions"]) + assert [e["mesh"]["cells"] for e in circular["solution_paths"]["discretizations"]] == [49] + + +# --- checked on load ---------------------------------------------------------------------------------------------- + +def _gn(doc): + return subproblem(doc, GN, "gn") + + +def test_a_model_that_is_not_dispersive_has_no_dispersion(tmp_path): + doc = load_ymf(SHALLOW_WATER / "torino.ymf") + entry = doc["solution_paths"]["discretizations"][0] + entry["subproblems"][0]["dispersion"] = copy.deepcopy(BLOCK) + with pytest.raises(VocabularyError, match="only a model of family dispersive_shallow_water has a dispersion; this one is shallow_water"): + check_vocabulary(doc) + + +@pytest.mark.parametrize("change, message", [ + (lambda d: d.__setitem__("closes", ["Pd", "g"]), "g has role gravity; hyperbolic_relaxation supplies"), + (lambda d: d.__setitem__("closes", ["Pd"]), "supplies dispersive_pressure and dispersive_bed_force, and these are dispersive_pressure"), + (lambda d: d.__setitem__("closes", ["Pd", "nothing"]), "nothing has role none"), + (lambda d: d["auxiliaries"][0].__setitem__("name", "h"), "the auxiliary h is already a name in the model"), + (lambda d: d["auxiliaries"][1].__setitem__("name", "Pd"), "the auxiliary Pd is already a name in the model"), +]) +def test_a_dispersion_that_disagrees_with_the_model_is_refused_on_load_and_says_where(circular, change, message): + doc = copy.deepcopy(circular) + block = _gn(doc)["dispersion"] + block["auxiliaries"] = [dict(a) for a in block["auxiliaries"]] + change(block) + with pytest.raises(VocabularyError, match=r"subproblems\[gn\]\.dispersion.*: .*" + message): + check_vocabulary(doc) + + +def test_the_strict_schema_refuses_a_key_it_does_not_know(tmp_path): + for name in ("shallow_water.ymf", "dispersive.ymf", "dispersive_numerics.ymf"): + (tmp_path / name).write_text((SHALLOW_WATER / name).read_text(encoding="utf-8"), encoding="utf-8") + text = (SHALLOW_WATER / "circular_dam_dispersive.ymf").read_text(encoding="utf-8") + (tmp_path / "bad.ymf").write_text(text, encoding="utf-8") + bad = (tmp_path / "dispersive_numerics.ymf") + bad.write_text(bad.read_text(encoding="utf-8").replace("closes: [Pd, Qd]", "closes: [Pd, Qd]\n relaxation: 1.0"), + encoding="utf-8") + with pytest.raises(Exception, match="relaxation"): + load_ymf(tmp_path / "bad.ymf") + + +# --- the archive -------------------------------------------------------------------------------------------------- + +def test_the_dispersion_survives_the_archive_and_is_part_of_its_key(tmp_path): + from ymf import closure + realization = {"cells": 49} + spec, again, digest = roundtrip(tmp_path, CIRCULAR, GN, realization) + assert resolve(_gn(again)["dispersion"]) == resolve(_gn(spec)["dispersion"]) + changed = load_ymf(CIRCULAR) + _gn(changed)["dispersion"]["auxiliaries"][1]["initial"] = "0.5" + assert closure.input_digest(changed, GN, realization) != digest From ce47e4316e52926bf9e7fb7e32c3ee1f4af1c83c Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:40:51 +0100 Subject: [PATCH 5/7] Cells per axis for a structured mesh (C42 round 5, 5/5) `mesh: {cells: {x: 80, y: 40}}` states one count per axis. C5 step 4 part 2 could only compare a deck whose box was a square count: `cells: 80` is one number for every axis, and `cells: [80, 40]` is a *study* of two meshes, so dam3Bumps (75 m x 30 m, nnx 81, nny 41) and santos_step (30 m x 2 m, 81 x 9) had no spelling. A list stays a study, a map is one mesh, and a list of maps is a study of such meshes; a map's keys are x, y, z in order with none skipped, each a whole number >= 1, and on load they must equal the axes of the box the domain states (`domain_dim` reads the box of the notation short form, `[0, 1]^3` included, or of a mapping). An output key reads `cells=80x40`; a spec with a single count or a study of counts keeps the keys it always had. `ymf.discretizations.cells_per_axis(cells, dim)` gives a reader the counts in axis order; a realization from `closure.realizations` carries the map as written, so proteus's ymf_run must read it through that helper (`int(cells)` fails on a map): that reader change is in the handoff, not made here. What C5 can now express: dam3bumps.ymf (test/SWFlow/dam3Bumps.py at refinement 4: nnx = 5 * 2^4 + 1 = 81, nny = (nnx - 1)/2 + 1 = 41, so 80 x 40 cells) is one realization `cells=80x40`; its key differs from 40x80, from 80x80 and from 80. Tests (33 new, whole suite 998 -> 1031 passed, 13 skipped): the counts in axis order, 11 refusals (a missing, extra or unknown axis, zero, a fraction, a list, no dimension), the dimension of eight domain spellings, the deck's 80 x 40 from its own refinement formula, the key, four different digests, a study of maps, an older spec keeps its keys, cells and h still alternatives, four bad values refused on load naming the discretization, the strict schema, and the archive. Co-Authored-By: Claude Sonnet 5.5 --- src/ymf/discretizations.py | 85 +++++++++++- src/ymf/schema.py | 4 +- src/ymf/vocabulary.py | 9 ++ tests/fixtures/shallow_water/dam3bumps.ymf | 35 +++++ tests/test_cells_per_axis.py | 150 +++++++++++++++++++++ 5 files changed, 280 insertions(+), 3 deletions(-) create mode 100644 tests/fixtures/shallow_water/dam3bumps.ymf create mode 100644 tests/test_cells_per_axis.py diff --git a/src/ymf/discretizations.py b/src/ymf/discretizations.py index b1592e3..e3c86ec 100644 --- a/src/ymf/discretizations.py +++ b/src/ymf/discretizations.py @@ -27,7 +27,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any, Callable, Dict, List, Tuple +from typing import Any, Callable, Dict, List, Optional, Tuple __all__ = ["Missing", "Method", "METHODS", "DEFAULT", "method_of", "missing", "subproblem_solver"] @@ -104,7 +104,7 @@ def key_parts(self, realization: Dict[str, Any]) -> List[str]: # the key format archives were first written with: cells or h, # then levels only when it is not 1 size = "cells" if "cells" in realization else "h" - parts = ["%s=%s" % (size, realization[size])] + parts = ["%s=%s" % (size, cells_text(realization[size]) if size == "cells" else realization[size])] if realization.get("levels", 1) != 1: parts.append("levels=%s" % (realization["levels"],)) else: @@ -128,6 +128,87 @@ def mesh_from_domain(domain: Any) -> bool: domain.get("kind") == "file" and domain.get("format") in MESH_FILE_FORMATS) +#: the axes of a box, in order: ``cells: {x: 80, y: 40}`` says cells along each +AXES = ("x", "y", "z") + + +class CellsError(ValueError): + """A cells-per-axis a spec states that does not make sense.""" + + +def domain_dim(domain: Any) -> Optional[int]: + """The number of space dimensions of a box domain, or None when this module cannot tell (a domain that is not a + box: its cells are a mesh's, not a box's). The notation short form is read by its factors.""" + if isinstance(domain, dict): + return len(domain["lower"]) if domain.get("kind") == "box" and "lower" in domain else None + if isinstance(domain, str) and "=" in domain: + import re + space = re.split(r",\s*t\s*∈", domain.split("=", 1)[1])[0] + power = re.search(r"\]\s*\^\s*(\d+)\s*$", space.strip()) # [0, 1]^3 + if power: + return int(power.group(1)) + return space.count("×") + 1 if "[" in space else None + return None + + +def cells_per_axis(cells: Any, dim: Optional[int] = None, where: str = "mesh.cells") -> List[int]: + """The cells along each axis of a box, in axis order: ``cells: 49`` (one count for every axis) and ``cells: {x: 80, + y: 40}`` (one per axis) are the two ways a spec states them. ``dim`` is the box's dimension (``domain_dim``); a + single count needs it, a map is checked against it. A list is a *study* (one realization per value): ``cells: + [10, 20]`` is two meshes, and ``cells: [{x: 80, y: 40}, {x: 160, y: 80}]`` two more; ask for one value's axes. + Raises :class:`CellsError`.""" + if isinstance(cells, dict): + unknown = sorted(set(map(str, cells)) - set(AXES)) + if unknown: + raise CellsError("%s: no axis %s; the axes are %s" % (where, ", ".join(unknown), ", ".join(AXES))) + stated = [a for a in AXES if a in cells] + if dim is not None and stated != list(AXES[:dim]): + raise CellsError("%s: a %dD box has the axes %s, and this gives %s" % ( + where, dim, ", ".join(AXES[:dim]), ", ".join(stated))) + if dim is None and stated != list(AXES[:len(stated)]): + raise CellsError("%s: the axes are x, then y, then z, with none skipped; this gives %s" % ( + where, ", ".join(stated))) + counts = [] + for axis in stated: + counts.append(_count(cells[axis], "%s.%s" % (where, axis))) + return counts + if isinstance(cells, (list, tuple)): + raise CellsError("%s: a list is a study, and has no axes; give one value" % (where,)) + if dim is None: + raise CellsError("%s: one count for every axis needs the box's dimension" % (where,)) + return [_count(cells, where)] * dim + + +def _count(value: Any, where: str) -> int: + try: + n = int(value) + except (TypeError, ValueError): + raise CellsError("%s: %r is not a whole number of cells" % (where, value)) from None + if n < 1 or str(n) != str(value).strip(): + raise CellsError("%s: %r is not a whole number of cells, at least 1" % (where, value)) + return n + + +def cells_text(cells: Any) -> str: + """How a cells value reads in an output key: ``49``, or ``80x40`` for one per axis (axis order).""" + if isinstance(cells, dict): + return "x".join(str(cells[a]) for a in AXES if a in cells) + return str(cells) + + +def check_cells(entry: Dict[str, Any], domain: Any = None) -> None: + """Every ``mesh.cells`` value of an entry (one, or each of a study) agrees with the box's dimension.""" + mesh = entry.get("mesh") + cells = mesh.get("cells") if isinstance(mesh, dict) else None + if cells is None: + return + values = cells if isinstance(cells, (list, tuple)) else [cells] + dim = domain_dim(domain) + where = "discretization %s mesh.cells" % (entry.get("name", "?"),) + for value in values: + cells_per_axis(value, dim, where) + + def _mesh_lacks(entry: Dict[str, Any], domain: Any = None) -> List[Missing]: mesh = entry.get("mesh") if mesh_from_domain(domain): diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 121dd69..5754ebf 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -301,7 +301,9 @@ # coarsest mesh. A list is a study: each value is one realization # (see ymf.closure). Optional("mesh"): Map({ - Optional("cells"): Int() | Seq(Int()), + # cells: one count for every axis, a study of counts, one count per + # axis ({x: 80, y: 40}), or a study of those (ymf.discretizations) + Optional("cells"): Int() | MapPattern(Str(), Int()) | Seq(Int() | MapPattern(Str(), Int())), Optional("h"): Float() | Seq(Float()), Optional("levels"): Int() | Seq(Int()), }), diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index fcae7ca..dfaab0b 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -536,6 +536,14 @@ def _check_dispersion(doc: Dict[str, Any], block: Any, family: Optional[str], wh raise VocabularyError(str(exc)) from None +def _check_cells(entry: Dict[str, Any], domain: Any) -> None: + from ymf.discretizations import CellsError, check_cells + try: + check_cells(entry, domain) + except CellsError as exc: + raise VocabularyError(str(exc)) from None + + def _check_spaces(block: Any, where: str) -> None: from ymf.spaces import SpaceError, check_finite_element try: @@ -571,6 +579,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st % (where, scheme, ", ".join(unread), ", ".join(list(SCHEMES[scheme]["options"]) + list(SCHEME_COMMON)))) _check_stabilization(entry.get("stabilization"), where + ".stabilization") + _check_cells(entry, _strong(doc).get("domain")) _check_spaces(entry.get("finite_element"), where + ".finite_element") for label, binding in list((entry.get("binds") or {}).items()): if isinstance(binding, dict) and binding.get("meaning") is not None: diff --git a/tests/fixtures/shallow_water/dam3bumps.ymf b/tests/fixtures/shallow_water/dam3bumps.ymf new file mode 100644 index 0000000..f934fce --- /dev/null +++ b/tests/fixtures/shallow_water/dam3bumps.ymf @@ -0,0 +1,35 @@ +# test/SWFlow/dam3Bumps.py as a spec, on the deck's structured mesh: a dam +# break over three conical bumps, 75 m × 30 m. At refinement 4 the deck has +# nnx = (6 − 1)·2⁴ + 1 = 81 nodes along x and nny = (nnx − 1)/2 + 1 = 41 along +# y: 80 × 40 cells, one count per axis (the box is not square, so no single +# count says it). The dam is at x = 16.05, not the deck's 16: the deck writes +# the jump as x <= 16 and ymf's heaviside is 1/2 there, so they agree off the +# jump only (as in proteus's test/dispatch/dam3bumps.ymf). +extends: proteus_numerics.ymf + +model: + name: "Dam break over three bumps, 75 m × 30 m (dam3Bumps), structured 80 × 40" + physical_model: {provenance: human_specified} + strong_form: + domain: "Ω = [0, 75] × [0, 30], t ∈ (0, 20]" + boundary_regions: + - {name: all, where: "∂Ω"} + boundary_sets: + - {region: all, set: wall} + initial_conditions: + - {field: h, type: function, formula: "max(1.875 heaviside(16.05 − x) − Z, 0)", units: m} + - {field: q, type: constant, value: 0.0} + coefficients: + g: {value: 9.81} + n: {value: 0.02} + θ: {value: 1.0} + Z: {formula: "max(0, 1 − sqrt((x − 30)² + (y − 6)²)/8, 1 − sqrt((x − 30)² + (y − 24)²)/8, 3 − 3 sqrt((x − 47.5)² + (y − 15)²)/10)"} + α: {value: 0.0} + β: {value: 0.0} + +solution_paths: + analytical: [] + discretizations: + - name: convex_limited + mesh: {cells: {x: 80, y: 40}} + step_control: {type: min_cfl, cfl: 0.25} diff --git a/tests/test_cells_per_axis.py b/tests/test_cells_per_axis.py new file mode 100644 index 0000000..aa1a09c --- /dev/null +++ b/tests/test_cells_per_axis.py @@ -0,0 +1,150 @@ +"""Cells per axis (C42 round 5): ``mesh: {cells: {x: 80, y: 40}}``, so a structured mesh of a box that is not square is +stated, and a list stays a study.""" + +import copy + +import pytest + +pytest.importorskip("strictyaml") +pytest.importorskip("sympy") + +from _formulation import FIXTURES, SHALLOW_WATER, roundtrip # noqa: E402 +from ymf import closure # noqa: E402 +from ymf.discretizations import CellsError, cells_per_axis, cells_text, domain_dim # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 +from ymf.state import reached # noqa: E402 +from ymf.vocabulary import VocabularyError, check # noqa: E402 + +DAM3BUMPS = SHALLOW_WATER / "dam3bumps.ymf" +BOX = "Ω = [0, 75] × [0, 30], t ∈ (0, 20]" + + +# --- cells_per_axis ----------------------------------------------------------------------------------------------- + +def test_one_count_is_every_axis_and_a_map_is_one_per_axis(): + assert cells_per_axis(49, 2) == [49, 49] + assert cells_per_axis(8, 3) == [8, 8, 8] + assert cells_per_axis({"x": 80, "y": 40}, 2) == [80, 40] + assert cells_per_axis({"y": 40, "x": 80}, 2) == [80, 40] # in axis order, whatever the order written + assert cells_per_axis({"x": 4, "y": 5, "z": 6}, 3) == [4, 5, 6] + assert cells_per_axis({"x": 80, "y": 40}) == [80, 40] # no dimension needed for a map + + +def test_a_key_reads_cells_per_axis_as_x_by_y(): + assert cells_text(49) == "49" and cells_text({"x": 80, "y": 40}) == "80x40" and cells_text({"y": 2, "x": 1}) == "1x2" + + +@pytest.mark.parametrize("value, dim, message", [ + ({"x": 80}, 2, "a 2D box has the axes x, y, and this gives x"), + ({"x": 80, "y": 40, "z": 10}, 2, "a 2D box has the axes x, y, and this gives x, y, z"), + ({"x": 80, "y": 40}, 3, "a 3D box has the axes x, y, z"), + ({"x": 80, "w": 40}, 2, "no axis w; the axes are x, y, z"), + ({"x": 80, "z": 40}, None, "none skipped"), + ({"x": 0, "y": 40}, 2, r"mesh\.cells\.x: 0 is not a whole number of cells, at least 1"), + ({"x": 80, "y": 4.5}, 2, r"mesh\.cells\.y: 4\.5 is not a whole number"), + ({"x": 80, "y": "many"}, 2, "'many' is not a whole number"), + ([80, 40], 2, "a list is a study, and has no axes"), + (49, None, "needs the box's dimension"), + (-3, 2, "not a whole number of cells, at least 1"), +]) +def test_cells_that_do_not_make_sense_are_refused(value, dim, message): + with pytest.raises(CellsError, match=message): + cells_per_axis(value, dim) + + +@pytest.mark.parametrize("domain, dim", [ + (BOX, 2), ("Ω = [0, 1]^3", 3), ("Ω = [0, 1]^2, t ∈ (0, 2]", 2), ("Ω = [0, 1] × [0, 2] × [0, 3]", 3), + ("Ω = [0, 25] × [0, 1]", 2), ({"kind": "box", "lower": [0, 0], "upper": [1, 1]}, 2), + ({"kind": "file", "format": "gmsh_geo"}, None), ("a disc", None), +]) +def test_the_dimension_of_a_box_is_read_without_the_symbolic_front_end(domain, dim): + assert domain_dim(domain) == dim + + +# --- the spec ----------------------------------------------------------------------------------------------------- + +@pytest.fixture(scope="module") +def dam(): + return load_ymf(DAM3BUMPS) + + +def test_dam3bumps_states_the_decks_80_by_40_cells(dam): + # test/SWFlow/dam3Bumps.py, refinement 4: nnx = 5·2⁴ + 1 = 81, nny = (nnx − 1)/2 + 1 = 41; C5 could not say it + (entry,) = dam["solution_paths"]["discretizations"] + nnx = (6 - 1) * 2 ** 4 + 1 + nny = (nnx - 1) // 2 + 1 + assert cells_per_axis(entry["mesh"]["cells"], domain_dim(dam["model"]["strong_form"]["domain"])) == [nnx - 1, nny - 1] + assert reached(dam)[0] == "discretized" + + +def test_it_is_one_realization_with_its_own_key(dam): + (entry,) = dam["solution_paths"]["discretizations"] + (realization,) = closure.realizations(entry, dam["model"]["strong_form"]["domain"]) + assert realization == {"cells": {"x": 80, "y": 40}, "levels": 1} + (key,) = [k for k, _, _ in closure.planned_outputs(dam)] + assert key.startswith("convex_limited/cells=80x40/") + + +def test_80_by_40_and_40_by_80_and_80_by_80_are_three_inputs(dam): + seen = set() + for cells in ({"x": 80, "y": 40}, {"x": 40, "y": 80}, {"x": 80, "y": 80}, 80): + doc = copy.deepcopy(dam) + doc["solution_paths"]["discretizations"][0]["mesh"]["cells"] = cells + seen.add(closure.input_digest(doc, "convex_limited", {"cells": cells, "levels": 1})) + assert len(seen) == 4 # even {x: 80, y: 80} is not 80: one says what it means, the other leaves it to the box + + +def test_a_list_of_maps_is_a_study_of_meshes(dam): + doc = copy.deepcopy(dam) + entry = doc["solution_paths"]["discretizations"][0] + entry["mesh"]["cells"] = [{"x": 80, "y": 40}, {"x": 160, "y": 80}, 20] + assert closure.realizations(entry, doc["model"]["strong_form"]["domain"]) == [ + {"cells": {"x": 80, "y": 40}, "levels": 1}, {"cells": {"x": 160, "y": 80}, "levels": 1}, {"cells": 20, "levels": 1}] + check(doc) + assert [k.split("/")[1] for k, _, _ in closure.planned_outputs(doc)] == ["cells=80x40", "cells=160x80", "cells=20"] + + +def test_an_older_spec_keeps_its_keys(): + # a spec with one count, or a study of counts, has the key it always had + doc = load_ymf(SHALLOW_WATER / "lake_at_rest.ymf") + assert [k.split("/")[1] for k, _, _ in closure.planned_outputs(doc)] == ["cells=50", "cells=100", "cells=200"] + + +def test_cells_and_h_are_still_alternatives(dam): + doc = copy.deepcopy(dam) + doc["solution_paths"]["discretizations"][0]["mesh"]["h"] = 2.0 + with pytest.raises(ValueError, match="mesh gives both cells and h"): + closure.realizations(doc["solution_paths"]["discretizations"][0], doc["model"]["strong_form"]["domain"]) + + +# --- checked on load ---------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("cells, message", [ + ({"x": 80}, "discretization convex_limited mesh.cells: a 2D box has the axes x, y"), + ({"x": 80, "y": 40, "z": 5}, "a 2D box has the axes x, y"), + ({"x": 80, "q": 40}, "no axis q"), + ([{"x": 80, "y": 40}, {"x": 80}], "a 2D box has the axes x, y"), +]) +def test_a_bad_cells_is_refused_on_load_and_names_the_discretization(dam, cells, message): + doc = copy.deepcopy(dam) + doc["solution_paths"]["discretizations"][0]["mesh"]["cells"] = cells + with pytest.raises(VocabularyError, match=message): + check(doc) + + +def test_the_strict_schema_refuses_a_cells_of_the_wrong_shape(tmp_path): + for name in ("shallow_water.ymf", "proteus_numerics.ymf"): + (tmp_path / name).write_text((SHALLOW_WATER / name).read_text(encoding="utf-8"), encoding="utf-8") + text = DAM3BUMPS.read_text(encoding="utf-8").replace("cells: {x: 80, y: 40}", "cells: {x: eighty, y: 40}") + (tmp_path / "bad.ymf").write_text(text, encoding="utf-8") + with pytest.raises(Exception, match="eighty|integer"): + load_ymf(tmp_path / "bad.ymf") + + +# --- the archive -------------------------------------------------------------------------------------------------- + +def test_cells_per_axis_survive_the_archive_and_the_key_is_the_same(tmp_path): + realization = {"cells": {"x": 80, "y": 40}, "levels": 1} + spec, again, digest = roundtrip(tmp_path, DAM3BUMPS, "convex_limited", realization) + assert again["solution_paths"]["discretizations"][0]["mesh"]["cells"] == {"x": 80, "y": 40} + assert [k for k, _, _ in closure.planned_outputs(again)] == [k for k, _, _ in closure.planned_outputs(spec)] From 78d73b49d89daf79bdf97e7d901ebeb0ac4f26cc Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:45:48 +0100 Subject: [PATCH 6/7] Docs for round 5, and the spec's porous VOF against the spike's hand-made form docs/problem-specification.md: "What a generator and a dispatcher read of the formulation" (stabilization and shock capturing, lagging, boundary kind, porosity, the dispersive family, cells per axis, with the exact keys), the new words in the dispatcher table; docs/changes.md; examples/README.md lists the worked specs (the fixtures that extend the family files). One test added: dambreak_porous.ymf's VOF ADR (theta inlined as the expression of the coordinates) equals, to round-off, the form the generator spike wrote by hand in a Space with the porosity a per-point field (m, dm, f, df, two states, a point inside the block). Whole suite 1031 -> 1032 passed, 13 skipped. Co-Authored-By: Claude Sonnet 5.5 --- docs/changes.md | 15 +++++++ docs/problem-specification.md | 64 +++++++++++++++++++++++++++++- examples/README.md | 13 ++++++ tests/test_boundary_declaration.py | 27 +++++++++++++ 4 files changed, 118 insertions(+), 1 deletion(-) diff --git a/docs/changes.md b/docs/changes.md index 4ceda30..bff31e8 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -7,6 +7,21 @@ rediscover why a thing is the way it is. Open gaps are in ## 2026-11 +- **2026-11-17: C42 round 5, the formulation a generator and a dispatcher read (C19 spike report, C5 step 4 part 2).** + The generator spike could not generate what the spec did not say (stabilization, shock capturing, lagging, boundary + kind, porosity) and C5 could not state a dispersive model or a mesh of a box that is not square. Now the spec states + each, checked on load, carried by `split_problem`, and part of an archive's key: `stabilization: {method, tau, lagged, + shock_capturing: {factor, beta, reference, lagged}}` (`ymf.stabilization`; proteus's `lag`, `sc_beta`, `sc_uref` are + aliases; nothing is defaulted); `lagged_coefficients: {name: previous_step | previous_iterate}`; `imposed: strong | + weak | none` with a weak condition's `penalty` and `form` (`ymf.boundaries`; the kind of an alias goes to its Dirichlet + part; `split_problem` gives every condition its `kind`); a two-phase model with a `porosity` coefficient + (`dambreak_porous.ymf`) and `coefficient_roles` in each sub-problem's record; `dispersion: {closure: + hyperbolic_relaxation, closes, auxiliaries}` with the roles `relaxed_depth`, `relaxed_divergence`, `relaxed_bed_flux` + (`ymf.dispersion`; coefficient roles `dispersive_pressure`, `dispersive_bed_force`); `mesh: {cells: {x: 80, y: 40}}` + (`cells_per_axis`). One fix on the way: `_used` read the function `sign` as the coefficients `s i g n` and put the + gravity among RDLS's. Not done, listed in the handoff: a condition whose value is another sub-problem's trace, the + relaxed equations of the closure, `atan`, a state imposed on part of a boundary. + - **2026-11-16: C42 round 4, the spaces vocabulary (C8's choices).** A `finite_element` entry stated only family and order; C8 (proteus FemTools rounds 1-5) added the basis, the node set, the Bernstein operator and the geometry order as choices a run depends on. `ymf.spaces`: `basis` (`lagrange`, `bernstein`, `monomial`), `nodes` (`gll`, `equispaced`), diff --git a/docs/problem-specification.md b/docs/problem-specification.md index c0eafb7..36fab6c 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -903,7 +903,12 @@ checked on load, so that a second solver reads the same ones: | `binds.*.meaning` | `element_size`, `dry_depth` | | `writes_back` | `replace`, `add`, `mass_quadrature` | | `linear_solver` | `direct`, `iterative`; `superlu`, `mumps`, `umfpack`, `petsc` | -| coefficient `role` | `density`, `dynamic_viscosity`, `kinematic_viscosity`, `gravity`, `phase_indicator`, `surface_tension`, `bed_elevation`, `manning_coefficient`, `porosity`, `linear_drag`, `quadratic_drag`, `bed_friction`, `canopy_drag`, `diffusivity` | +| coefficient `role` | `density`, `dynamic_viscosity`, `kinematic_viscosity`, `gravity`, `phase_indicator`, `surface_tension`, `bed_elevation`, `manning_coefficient`, `porosity`, `linear_drag`, `quadratic_drag`, `bed_friction`, `canopy_drag`, `diffusivity`, `dispersive_pressure`, `dispersive_bed_force` | +| `stabilization.tau` | `metric`, `element_size` | +| stabilization and shock-capturing keys | `tau`, `lagged`, `shock_capturing`; `factor`, `beta`, `reference`, `lagged` (older: `lag`, `sc_beta`, `sc_uref`) | +| `lagged_coefficients` values | `previous_step`, `previous_iterate` | +| `imposed` (boundary kind) | `strong`, `weak`, `none`; a weak one's `form`: `symmetric`, `nonsymmetric`, `incomplete` | +| `dispersion.closure`, auxiliary `role` | `hyperbolic_relaxation`; `relaxed_depth`, `relaxed_divergence`, `relaxed_bed_flux` | A family is identified by the processes and assumptions of `physical_model` (two-phase: `incompressible_flow`, `two_phase_flow`, @@ -936,6 +941,63 @@ until it maps the new one. `dispersive_shallow_water` was identified by the assumption `hyperbolic_relaxation`, which is how GN_SW2DCV discretizes the model, not an assumption of it; that is still recognized. +### What a generator and a dispatcher read of the formulation (C42 round 5) + +The words above name *what a sub-problem is*. A kernel generator (C19) and the app framework (C5) also need *how it is +formulated*, which used to come from a model's name or from `Parameters.py`. A spec states it, and +`split_problem` carries each statement in the sub-problem's record. Worked specs: the fixtures +`tests/fixtures/two_phase/dambreak_formulation.ymf`, `dambreak_porous.ymf` and +`tests/fixtures/shallow_water/circular_dam_dispersive.ymf`, `dam3bumps.ymf`. Nothing is defaulted by ymf: what a spec +does not state is the solver's own default (`ymf.stabilization.missing` lists what a reader that must not guess still +needs). + +**Stabilization and shock capturing** (`ymf.stabilization`), per sub-problem, or per entry as the default of its +sub-problems (a sub-problem's block replaces the entry's whole): + +```yaml +stabilization: + method: SUPG # or a bare word: stabilization: SUPG + tau: metric # metric (G, proteus useMetrics 1) | element_size (h, useMetrics 0) + lagged: false # the subgrid error taken from the previous step + shock_capturing: {factor: 0.5, beta: 1.5, reference: 1.0, lagged: true} # or: none +``` + +SUPG and ASGS read `tau`, `lagged`, `shock_capturing`; `residual_shock_capturing` reads `tau` and `shock_capturing`; +the entropy and graph viscosities read none (their parameters are the scheme's options). `beta` is in [1, 2], +`reference` positive, `factor` non-negative. `lag`, `sc_beta`, `sc_uref` (the keys proteus's dispatcher read first) are +accepted and resolve to `lagged`, `beta`, `reference`. + +**Lagging** (`lagged_coefficients`): `{μ: previous_iterate, ρ: previous_step}` says which of the model's coefficients +a sub-problem freezes, in the Newton iteration (a Picard step: the Jacobian drops the dependence) or in time (a +constant of the step). A field read from another sub-problem is `lags`; a stabilization's lag is its `lagged`. + +**Boundary kind** (`imposed` on a condition, `ymf.boundaries`): `strong` (rows replaced), `weak` (Nitsche: `penalty` +and `form`) or `none` (the natural condition). A Dirichlet condition is strong or weak (default strong); Neumann, +Robin and `open` are none. `split_problem` gives each condition its resolved `kind`, which is what picks a kernel's +face term (the engine's Strong, WeakDirichlet and Flux). An alias gives its kind to its Dirichlet part only. + +**Porosity** is a coefficient with `role: porosity`; `dambreak_porous.ymf` states it in the two-phase model's +continuity, momentum, VOF and MCorr equations. A sub-problem's record lists the roles of the coefficients it uses +(`coefficient_roles`), so a generator finds the porosity by its role. + +**The dispersive family** (`ymf.dispersion`): the model is the shallow-water one with the dispersive pressure `Pd` and bed +force `Qd` as coefficients (roles `dispersive_pressure`, `dispersive_bed_force`), and a sub-problem states the closure +that supplies them and the auxiliary unknowns it introduces: + +```yaml +dispersion: + closure: hyperbolic_relaxation + closes: [Pd, Qd] + auxiliaries: + - {name: hη, role: relaxed_depth, units: m2} # initial h², boundary data of h + - {name: hw, role: relaxed_divergence, units: m2/s} # initial 0, boundary data of h (`initial:` to state another) + - {name: hβ, role: relaxed_bed_flux, units: m2/s} # initial 0, boundary data of q +``` + +**Cells per axis**: `mesh: {cells: {x: 80, y: 40}}`. One count (`cells: 80`) is every axis, a list is a study +(`cells: [80, 160]`), a list of maps a study of such meshes. `ymf.discretizations.cells_per_axis(cells, dim)` gives the +counts in axis order; the output key reads `cells=80x40`. + ## Document state A YMF document is the record of a progression: from a model, through a diff --git a/examples/README.md b/examples/README.md index db16c55..f5276b7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -20,6 +20,19 @@ python examples/read_archive.py /tmp/ymf-demo/heat.ymf # read one back | [nonlinear_diffusion.ymf](nonlinear_diffusion.ymf) | A coefficient that is a function of the state: the conductivity `k = 1 + u²` names the unknown, so the problem is nonlinear and solved by Newton. Manufactured exact solution; P1 and P2 rates 2 and 3. | | [kovasznay_flow.ymf](kovasznay_flow.ymf) | Branching: Navier–Stokes with two weak forms (Taylor–Hood, stabilized equal-order), a discretization for each, a Reynolds number computed from the scales, and a verification plan against the exact solution. | +### The formulation a generator and a dispatcher read (C42 round 5) + +Worked specs live with the tests, because they extend the family files there: + +| File | Shows | +|---|---| +| [two_phase/dambreak_formulation.ymf](../tests/fixtures/two_phase/dambreak_formulation.ymf) | The dam break with `stabilization` (ASGS, SUPG, shock capturing and their parameters per sub-problem) and `imposed` boundary kinds stated. | +| [two_phase/dambreak_porous.ymf](../tests/fixtures/two_phase/dambreak_porous.ymf) | The two-phase model with a porosity coefficient (`role: porosity`) in continuity, momentum, VOF and MCorr. | +| [shallow_water/circular_dam_dispersive.ymf](../tests/fixtures/shallow_water/circular_dam_dispersive.ymf) | The dispersive family: `dispersion` with the hyperbolic-relaxation closure and its three auxiliary unknowns (and [dispersive.ymf](../tests/fixtures/shallow_water/dispersive.ymf), [dispersive_numerics.ymf](../tests/fixtures/shallow_water/dispersive_numerics.ymf) it extends). | +| [shallow_water/dam3bumps.ymf](../tests/fixtures/shallow_water/dam3bumps.ymf) | Cells per axis: `mesh: {cells: {x: 80, y: 40}}`. | + +`lagged_coefficients` has no fixture (no solver of the dam break freezes a coefficient); `tests/test_lagging.py` sets it. + ### Composed from several files: [navier_stokes/](navier_stokes/) One model, extended into three problems with `extends`, and one archive extended. See diff --git a/tests/test_boundary_declaration.py b/tests/test_boundary_declaration.py index ad93c16..785ab90 100644 --- a/tests/test_boundary_declaration.py +++ b/tests/test_boundary_declaration.py @@ -158,3 +158,30 @@ def test_the_porosity_survives_the_archive(tmp_path): spec, again, _ = roundtrip(tmp_path, POROUS, "level_set_five", {"h": 0.0322}) assert coefficient_by_role(again, "porosity") == "θ" assert subproblem(again, "level_set_five", "vof")["equation"] == "∂(θ χh)/∂t + ∇·(θ v χh) = 0" + + +def test_the_specs_vof_is_the_form_the_generator_spike_built_by_hand_with_the_porosity_a_field(porous): + # make_inputs.py: Space(2, {χ: 0}, {}, fields={v: 1, ε: 0}), "∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0": ε is a per-point input. + # The spec inlines θ(x, y); with ε := θ(x, y) the two forms agree to round-off (m, dm, f, df). + numpy = pytest.importorskip("numpy") + from ymf.symbolic import Space, adr_form, parse_equation + space = Space(2, {"χ": 0}, {}, fields={"v": 1, "ε": 0}) + by_hand = adr_form(parse_equation("∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0", space), space)["equations"][0] + spec = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]}["vof"]["adr"]["equations"][0] + theta = lambda x, y: 1 - 0.4 * (x > 2.2 + 1.5 * 0.0322) * (y < 0.3 - 1.5 * 0.0322) # away from the smoothed edges + x, y, h = 3.0, 0.1, 0.0322 + v = (0.7, -0.3) + + def run(code, **extra): + env = {"numpy": numpy, "x": x, "y": y, "h": h, "v_0": v[0], "v_1": v[1]} + env.update(extra) + return eval(code, {"__builtins__": {}}, env) # noqa: S307 + + eps = theta(x, y) + for u in (0.3, 0.9): + assert run(spec["mass"]["m"], χh=u) == pytest.approx(run(by_hand["mass"]["m"], χ=u, ε=eps)) + assert run(spec["mass"]["dm"]["χh"], χh=u) == pytest.approx(run(by_hand["mass"]["dm"]["χ"], χ=u, ε=eps)) + for k in (0, 1): + assert run(spec["advection"]["f"][k], χh=u) == pytest.approx(run(by_hand["advection"]["f"][k], χ=u, ε=eps)) + assert run(spec["advection"]["df"]["χh"][k], χh=u) == pytest.approx( + run(by_hand["advection"]["df"]["χ"][k], χ=u, ε=eps)) From 19c1107f56dc5e874cd52a28eb463eb7f8c4a025 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:49:33 +0100 Subject: [PATCH 7/7] Test: split the porous dam break once (28 s of sympy, was four times) The four porosity tests each called split_problem on dambreak_porous.ymf; a module-scoped fixture does it once. No change to what is checked. Co-Authored-By: Claude Sonnet 5.5 --- tests/test_boundary_declaration.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/test_boundary_declaration.py b/tests/test_boundary_declaration.py index 785ab90..8ca994c 100644 --- a/tests/test_boundary_declaration.py +++ b/tests/test_boundary_declaration.py @@ -112,13 +112,19 @@ def porous(): return load_ymf(POROUS) +@pytest.fixture(scope="module") +def porous_split(porous): + """The porous dam break's sub-problems by name: sympy takes ~30 s over them, so once.""" + return {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + + def test_the_two_phase_model_states_its_porosity_by_role(porous): assert coefficient_by_role(porous, "porosity") == "θ" assert coefficient_by_role(load_ymf(DAMBREAK), "porosity") is None -def test_the_sub_problems_say_which_use_the_porosity(porous): - split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} +def test_the_sub_problems_say_which_use_the_porosity(porous_split): + split = porous_split assert {n for n, s in split.items() if "porosity" in s.get("coefficient_roles", {})} == {"flow", "vof", "mcorr"} assert split["flow"]["coefficient_roles"]["density"] == "ρ" # NCLS has none, and the plain dam break none anywhere @@ -126,10 +132,10 @@ def test_the_sub_problems_say_which_use_the_porosity(porous): assert not any("porosity" in s.get("coefficient_roles", {}) for s in plain.values()) -def test_vof_carries_the_porosity_in_its_mass_and_its_flux_as_the_generator_spikes_hand_made_form_did(porous): +def test_vof_carries_the_porosity_in_its_mass_and_its_flux_as_the_generator_spikes_hand_made_form_did(porous_split): # generator/make_inputs.py wrote "∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0" in a Space by hand (porosity ε a per-point field); # the spec now states it, with θ inlined as the expression of the coordinates it is - split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + split = porous_split eq = split["vof"]["adr"]["equations"][0] assert eq["mass"]["m"].startswith("χh*(") and "numpy.select" in eq["mass"]["m"] numpy = pytest.importorskip("numpy") @@ -143,9 +149,9 @@ def test_vof_carries_the_porosity_in_its_mass_and_its_flux_as_the_generator_spik assert split["ncls"]["adr"] == plain["ncls"]["adr"] -def test_the_porosity_is_one_where_it_is_one_and_below_one_in_the_block(porous): +def test_the_porosity_is_one_where_it_is_one_and_below_one_in_the_block(porous_split): numpy = pytest.importorskip("numpy") - split = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]} + split = porous_split m = split["vof"]["adr"]["equations"][0]["mass"]["dm"]["χh"] env = {"numpy": numpy, "h": 0.0322} at = lambda x, y: eval(m, {"__builtins__": {}}, dict(env, x=x, y=y)) # noqa: S307 @@ -160,14 +166,14 @@ def test_the_porosity_survives_the_archive(tmp_path): assert subproblem(again, "level_set_five", "vof")["equation"] == "∂(θ χh)/∂t + ∇·(θ v χh) = 0" -def test_the_specs_vof_is_the_form_the_generator_spike_built_by_hand_with_the_porosity_a_field(porous): +def test_the_specs_vof_is_the_form_the_generator_spike_built_by_hand_with_the_porosity_a_field(porous_split): # make_inputs.py: Space(2, {χ: 0}, {}, fields={v: 1, ε: 0}), "∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0": ε is a per-point input. # The spec inlines θ(x, y); with ε := θ(x, y) the two forms agree to round-off (m, dm, f, df). numpy = pytest.importorskip("numpy") from ymf.symbolic import Space, adr_form, parse_equation space = Space(2, {"χ": 0}, {}, fields={"v": 1, "ε": 0}) by_hand = adr_form(parse_equation("∂(ε*χ)/∂t + ∇·(ε*χ*v) = 0", space), space)["equations"][0] - spec = {s["name"]: s for s in split_problem(porous, "level_set_five")["subproblems"]}["vof"]["adr"]["equations"][0] + spec = porous_split["vof"]["adr"]["equations"][0] theta = lambda x, y: 1 - 0.4 * (x > 2.2 + 1.5 * 0.0322) * (y < 0.3 - 1.5 * 0.0322) # away from the smoothed edges x, y, h = 3.0, 0.1, 0.0322 v = (0.7, -0.3)