From 912e3df8162bbe7a2fcd808be725cc95d2de5eb2 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:26 +0100 Subject: [PATCH 1/8] linear_solver: direct / iterative, shared by every solver path C5 decision 19 (Q3): on proteus's TwoPhaseFlow path `superlu` means useSuperlu (SuperLU serial, SuperLU_DIST parallel), SWFlow ignores the spec, and the ADR path refuses superlu on > 1 rank. The spec now says what is asked of the linear solve: `direct` (a factorization, the solver picks the package) or `iterative` (Krylov + preconditioner, refined by petsc_options). Each path maps the two words and refuses what it cannot honour. A package name is a request of its kind: superlu, mumps, umfpack direct; petsc iterative unless petsc_options give pc_type lu/cholesky with ksp_type preonly. - schema: linear_solver takes direct, iterative (the packages stay). - ymf.vocabulary (new): LINEAR_SOLVERS, linear_solver_kind. - guide: the solver paragraph. Measured (macOS arm64, petsc-dev env): ymf suite 866 -> 879 passed, 2 skipped (13 new in test_linear_solver). No spec changes meaning: the 17 examples and fixtures of main 3a3a061 plan the same output keys. Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 12 +++++++- src/ymf/schema.py | 6 +++- src/ymf/vocabulary.py | 54 +++++++++++++++++++++++++++++++++++ tests/test_linear_solver.py | 32 +++++++++++++++++++++ 4 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 src/ymf/vocabulary.py create mode 100644 tests/test_linear_solver.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 48cec6e..31e892c 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -233,7 +233,8 @@ may be omitted when the document has only one — see `fields`, or `velocity` and `pressure` for mixed problems, each as `{family: CG|DG|RT|BDM|RTF|N1curl, order: n}`. The `solver` block takes `type` (`linear | nonlinear | time_marching | saddle_point`), -`linear_solver` (`petsc | mumps | umfpack | superlu`), `petsc_options`, +`linear_solver` (`direct | iterative`, or a package: `petsc | mumps | umfpack +| superlu`), `petsc_options`, `nonlinear_solver` (`newton | broyden | line_search`), `tolerance` and `max_iterations`. `petsc_options` are PETSc options without the leading dash, as strings (`{ksp_type: cg, pc_type: gamg, ksp_rtol: "1e-10"}`; an @@ -243,6 +244,15 @@ serial LU, `mumps` a direct solve through PETSc, and `petsc` a PETSc Krylov solve set by `petsc_options` (PETSc's defaults without them); `umfpack` is refused, as it has no Proteus solver. Omitted, Proteus picks its serial LU, or MUMPS when the operator has a null space. +`direct` and `iterative` say what is asked of the linear solve rather than +which package does it: a direct factorization (serial or distributed, the +solver's choice), or a Krylov method with a preconditioner that +`petsc_options` refine. Every solver path of a solver reads the same two +words and maps them to its own options, and refuses what it cannot honour +instead of overriding the spec. A package name is a request of its kind +(`superlu`, `mumps` and `umfpack` direct; `petsc` iterative, unless +`petsc_options` give `pc_type: lu` or `cholesky` with `ksp_type: preonly`): +`ymf.vocabulary.linear_solver_kind` says which. `mesh: {cells, levels}` gives the meshes: cells along each side of the domain's box, and levels of uniform refinement (the solution is on the finest). A region that is not a box (`kind: piecewise_linear`) gives diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 56df5f7..32d1bee 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -98,7 +98,11 @@ ["linear", "nonlinear", "time_marching", "saddle_point"] ), Optional("nonlinear_solver"): Enum(["newton", "broyden", "line_search"]), - Optional("linear_solver"): Enum(["petsc", "mumps", "umfpack", "superlu"]), + # direct or iterative: what is asked of the linear solve, which each + # solver maps to its own options (or refuses); or a package, which + # is a request of its kind (ymf.vocabulary.LINEAR_SOLVERS) + Optional("linear_solver"): Enum(["direct", "iterative", + "petsc", "mumps", "umfpack", "superlu"]), # PETSc options, without the leading dash, for linear_solver petsc # or mumps: {ksp_type: cg, pc_type: gamg}. Values are passed as # written; an option that takes none is given "". diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py new file mode 100644 index 0000000..ce52209 --- /dev/null +++ b/src/ymf/vocabulary.py @@ -0,0 +1,54 @@ +"""The words a spec states and a solver maps: ymf's vocabulary. + +Each kind is a mapping ``{word: meaning}``. So far: :data:`LINEAR_SOLVERS`, +``direct`` and ``iterative`` and the packages a spec may still name, and +:func:`linear_solver_kind`. Stdlib only, like the rest of the spec core. +""" + +from __future__ import annotations + +from typing import Any, Dict, Optional + +__all__ = ["LINEAR_SOLVERS", "linear_solver_kind", "VocabularyError"] + + +class VocabularyError(ValueError): + """A word the vocabulary does not have, or one used where it cannot be.""" + + +# --------------------------------------------------------------------------- +# Linear solvers +# --------------------------------------------------------------------------- + +#: ``direct`` and ``iterative`` say what is asked of the linear solve; each +#: solver maps them to its own options and refuses what it cannot honour. A +#: package name says which implementation, and is a request of its kind. +LINEAR_SOLVERS: Dict[str, Dict[str, Any]] = { + "direct": {"kind": "direct", "means": "a direct factorization; the solver picks the package " + "(serial or distributed)"}, + "iterative": {"kind": "iterative", "means": "a Krylov method with a preconditioner; " + "petsc_options refine it"}, + "superlu": {"kind": "direct", "means": "SuperLU (SuperLU_DIST in parallel)"}, + "mumps": {"kind": "direct", "means": "MUMPS"}, + "umfpack": {"kind": "direct", "means": "UMFPACK (serial)"}, + "petsc": {"kind": "iterative", "means": "a PETSc KSP; direct if petsc_options ask for " + "pc_type lu or cholesky with ksp_type preonly"}, +} + +_DIRECT_PC = ("lu", "cholesky") + + +def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: + """``direct``, ``iterative``, or None when the solver block names no + linear solver.""" + if not solver or solver.get("linear_solver") is None: + return None + word = str(solver["linear_solver"]) + if word not in LINEAR_SOLVERS: + raise VocabularyError("linear_solver %s: ymf knows %s" % (word, ", ".join(LINEAR_SOLVERS))) + if word == "petsc": + options = solver.get("petsc_options") or {} + if (str(options.get("pc_type")) in _DIRECT_PC + and str(options.get("ksp_type", "preonly")) == "preonly"): + return "direct" + return LINEAR_SOLVERS[word]["kind"] diff --git a/tests/test_linear_solver.py b/tests/test_linear_solver.py new file mode 100644 index 0000000..e440c62 --- /dev/null +++ b/tests/test_linear_solver.py @@ -0,0 +1,32 @@ +"""linear_solver: direct / iterative (C42 round 3, decision 19): what is +asked of the linear solve, shared by every solver path; a package name is a +request of its kind. +""" + +import pytest + +from ymf.vocabulary import VocabularyError, linear_solver_kind + + +@pytest.mark.parametrize("solver, kind", [ + ({"linear_solver": "direct"}, "direct"), + ({"linear_solver": "iterative"}, "iterative"), + ({"linear_solver": "superlu"}, "direct"), + ({"linear_solver": "mumps"}, "direct"), + ({"linear_solver": "umfpack"}, "direct"), + ({"linear_solver": "petsc"}, "iterative"), + ({"linear_solver": "petsc", "petsc_options": {"ksp_type": "gmres", "pc_type": "asm"}}, "iterative"), + ({"linear_solver": "petsc", "petsc_options": {"ksp_type": "preonly", "pc_type": "lu"}}, "direct"), + ({"linear_solver": "petsc", "petsc_options": {"pc_type": "cholesky"}}, "direct"), + ({"linear_solver": "petsc", "petsc_options": {"ksp_type": "cg", "pc_type": "lu"}}, "iterative"), + ({"nonlinear_solver": "newton"}, None), + (None, None), +]) +def test_the_kind_of_a_linear_solve(solver, kind): + assert linear_solver_kind(solver) == kind + + +def test_an_unknown_linear_solver_is_refused(): + with pytest.raises(VocabularyError, match="linear_solver hypre: ymf knows direct, iterative"): + linear_solver_kind({"linear_solver": "hypre"}) + From 37c433cda0b1fb0d48ce48842055a654cf894f76 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:27 +0100 Subject: [PATCH 2/8] vocabulary: the dispatch table's labels are ymf words, stated and checked C5 decision 16 (F3): proteus's DispatchTable coined the words it matched on: sub-problem roles, families, stabilization methods, time integration, the SWE scheme. They live in ymf.vocabulary now; the spec states them, ymf checks them on load (ymf.references), and the closed spec writes the derived ones, so the table only maps them. - FAMILIES + family_of: two_phase_level_set, shallow_water, dispersive_shallow_water. DSWE is identified by depth_averaged + dispersive; the table's `hyperbolic_relaxation` (GN_SW2DCV's discretization, not an assumption) is still recognized. - ROLES + role_of: proteus's Dispatch.role_of rules, moved; `role:` on a sub-problem is checked against the structure. pressure_initial is pressure_spin_up (ymf's word is spin_up). - TIME_INTEGRATION (backward_euler, bdf2, ssp_rk3, none), STABILIZATION (ASGS, SUPG, residual_shock_capturing, entropy_viscosity, graph_viscosity_smoothness, graph_viscosity_entropy_residual), SCHEMES (graph_viscosity_convex_limiting and its options), STEP_CONTROL, REGULARIZATIONS, BINDING_MEANINGS, WRITES_BACK, INERTIA_FORMS. - Renamed, old word kept as an alias (ALIASES, canonical): vbdf -> bdf2, SSP_RK3 -> ssp_rk3, shock_capturing -> residual_shock_capturing, entropy_viscosity_cE -> entropy_viscosity_coefficient. Aliases are not rewritten on load or in the closed spec, so proteus's table keeps working until C5 step 3 maps the new words. - schema: physical_model.family and a sub-problem's role (optional). - explicit: the closed spec writes family and roles; without_derived drops them, so neither counts towards an output's key (stated or not). - tests/fixtures/two_phase/dambreak_clsvof.ymf: RANS2P + CLSVOF. Measured (petsc-dev): ymf suite 879 -> 930 passed, 2 skipped (51 new in test_vocabulary, one per dispatch-table label among them). Main's 17 examples and fixtures, closed by main and by this branch: same output keys, same closed spec without derived keys, same ADR and split plain data (petsc-dev sympy 1.14 and proteus-bc-261025 sympy 1.13.2). Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 40 ++ src/ymf/explicit.py | 61 ++- src/ymf/references.py | 5 + src/ymf/schema.py | 7 + src/ymf/vocabulary.py | 452 ++++++++++++++++++- tests/fixtures/two_phase/dambreak_clsvof.ymf | 32 ++ tests/test_linear_solver.py | 12 + tests/test_vocabulary.py | 231 ++++++++++ 8 files changed, 830 insertions(+), 10 deletions(-) create mode 100644 tests/fixtures/two_phase/dambreak_clsvof.ymf create mode 100644 tests/test_vocabulary.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 31e892c..4c86dff 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -856,6 +856,46 @@ solves for, and those on a coefficient its introduced unknown carries expanded. A condition on a field a sub-problem only reads is another's. A solver maps a sub-problem onto its own modules (a dispatcher); `proteus:` blocks are interim hints for it, carried as text. +### The words a dispatcher maps + +A solver's dispatcher maps the spec onto its modules by the words the spec +states, and those words are ymf's ([`ymf.vocabulary`](../src/ymf/vocabulary.py)), +checked on load, so that a second solver reads the same ones: + +| kind | words | +|---|---| +| model family (`physical_model.family`) | `two_phase_level_set`, `shallow_water`, `dispersive_shallow_water` | +| sub-problem role (`role`) | two-phase: `velocity_pressure`, `velocity`, `pressure_increment`, `pressure`, `pressure_spin_up`, `volume_fraction`, `level_set`, `level_set_redistanced`, `redistancing`, `mass_correction`; shallow water: `shallow_water` | +| `time_integration` | `backward_euler`, `bdf2`, `ssp_rk3`, `none` | +| `stabilization.method` | `ASGS`, `SUPG`, `residual_shock_capturing`, `entropy_viscosity`, `graph_viscosity_smoothness`, `graph_viscosity_entropy_residual` | +| `discretization.scheme` and its options | `graph_viscosity_convex_limiting`: `entropy_viscosity_coefficient`, `lumped_mass`, `bounds_relaxation` (and `time_integration`, `outputs`, `dt` for every scheme) | +| `step_control.type` | `min_cfl`, `fixed` | +| `regularize.*.by` | `smoothed_heaviside`, `smoothed_sign`, `wet_dry_cutoff` | +| `binds.*.meaning` | `element_size`, `dry_depth` | +| `writes_back` | `replace`, `add`, `mass_quadrature` | +| `linear_solver` | `direct`, `iterative`; `superlu`, `mumps`, `umfpack`, `petsc` | + +A family is identified by the processes and assumptions of +`physical_model` (two-phase: `incompressible_flow`, `two_phase_flow`, +`interface_transport`; shallow water: `hydrostatic`, `depth_averaged`, +`nondispersive`; dispersive: `depth_averaged`, `dispersive`). A role is +read from the sub-problem's structure: what it solves (the unknowns its +equations are for), enforces, introduces and spins up. Both may be stated +(`family:`, `role:`), and are then checked against what the model and the +structure say; a closed spec writes both out (`ymf.explicit`), and neither +counts towards an output's key, since each follows from what does. + +Some words were first the dispatch table's, named after a solver's class +or flag; ymf's word replaces them and the old one is still read as an +alias (`ymf.vocabulary.ALIASES`, `canonical`): `vbdf` is `bdf2`, `SSP_RK3` +is `ssp_rk3`, `shock_capturing` (the method) is `residual_shock_capturing`, +`pressure_initial` is `pressure_spin_up`, `entropy_viscosity_cE` is +`entropy_viscosity_coefficient`. A spec using an alias +loads, and is not rewritten: a reader keyed on the old word keeps working +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. + ## Document state A YMF document is the record of a progression: from a model, through a diff --git a/src/ymf/explicit.py b/src/ymf/explicit.py index 44ff9d9..310d498 100644 --- a/src/ymf/explicit.py +++ b/src/ymf/explicit.py @@ -23,7 +23,11 @@ refined by its own), its regularization (the entry's, function by function replaced by its own), and each lag as ``{at, via, of, carried_by}``, where ``carried_by`` names the introduced unknown that - carries a lagged coefficient (``χ`` via VOF is read as ``χh``). + carries a lagged coefficient (``χ`` via VOF is read as ``χh``); +* the model's **family** (``physical_model.family``) when its processes and + assumptions identify one, and each sub-problem's **role** in it + (ymf.vocabulary), so a dispatcher maps the words the spec states instead + of reading them off the structure itself. Applying it twice changes nothing, and a spec with none of the shorthand (no aliases, no coefficients of the state, no sub-problems) is returned @@ -42,6 +46,11 @@ #: do not count towards an output's key (ymf.closure.input_slice) DERIVED_KEYS = ("depends_on",) +#: the same, on a sub-problem; and the model's family when its processes and +#: assumptions identify exactly one (a family stated to choose between +#: several is input) +DERIVED_SUBPROBLEM_KEYS = ("role",) + def _strong(doc: Dict[str, Any]) -> Dict[str, Any]: return ((doc.get("model") or {}).get("strong_form") or {}) @@ -142,19 +151,63 @@ def explicit(doc: Dict[str, Any]) -> Dict[str, Any]: paths["discretizations"] = [split_out(e) if isinstance(e, dict) else e for e in entries] doc["solution_paths"] = paths + return _name_roles(doc) + + +def _name_roles(doc: Dict[str, Any]) -> Dict[str, Any]: + """The model's family and each sub-problem's role, written out.""" + from ymf.vocabulary import VocabularyError, family_of, role_of + try: + family = family_of(doc) + except VocabularyError: + return doc # several: refused on load, or stated + if family is None: + return doc + doc = dict(doc) + model = dict(doc["model"]) + model["physical_model"] = dict(model.get("physical_model") or {}, family=family) + doc["model"] = model + entries = (doc.get("solution_paths") or {}).get("discretizations") or [] + if any(isinstance(e, dict) and e.get("subproblems") for e in entries): + out = [] + for entry in entries: + if isinstance(entry, dict) and entry.get("subproblems"): + entry = dict(entry) + subs = [] + for sub in entry["subproblems"]: + role = role_of(sub, doc, family) + subs.append(dict(sub, role=role) if role else sub) + entry["subproblems"] = subs + out.append(entry) + doc["solution_paths"] = dict(doc["solution_paths"], discretizations=out) return doc def without_derived(doc: Dict[str, Any]) -> Dict[str, Any]: """``doc`` with the keys :func:`explicit` derives from the rest removed.""" + from ymf.vocabulary import families_of strong = _strong(doc) coefficients = strong.get("coefficients") or {} - if not any(isinstance(e, dict) and any(k in e for k in DERIVED_KEYS) - for e in coefficients.values()): + physical = (doc.get("model") or {}).get("physical_model") or {} + family = physical.get("family") is not None and len(families_of(doc)) == 1 + entries = (doc.get("solution_paths") or {}).get("discretizations") or [] + roles = any(isinstance(s, dict) and any(k in s for k in DERIVED_SUBPROBLEM_KEYS) + for e in entries if isinstance(e, dict) for s in e.get("subproblems") or []) + if not family and not roles and not any( + isinstance(e, dict) and any(k in e for k in DERIVED_KEYS) + for e in coefficients.values()): return doc doc = copy.deepcopy(doc) - for entry in doc["model"]["strong_form"]["coefficients"].values(): + for entry in ((doc["model"].get("strong_form") or {}).get("coefficients") or {}).values(): if isinstance(entry, dict): for key in DERIVED_KEYS: entry.pop(key, None) + if family: + doc["model"]["physical_model"].pop("family") + for entry in (doc.get("solution_paths") or {}).get("discretizations") or []: + if isinstance(entry, dict): + for sub in entry.get("subproblems") or []: + if isinstance(sub, dict): + for key in DERIVED_SUBPROBLEM_KEYS: + sub.pop(key, None) return doc diff --git a/src/ymf/references.py b/src/ymf/references.py index ea2571e..0b3d5d3 100644 --- a/src/ymf/references.py +++ b/src/ymf/references.py @@ -463,6 +463,11 @@ def resolve(doc: Dict[str, Any]) -> None: for entry in _paths(doc).get("discretizations") or []: if isinstance(entry, dict): _check_split(doc, entry) + from ymf.vocabulary import VocabularyError, check as check_vocabulary + try: + check_vocabulary(doc) + except VocabularyError as exc: + raise YmfReferenceError(str(exc)) from None labels = weak_form_labels(doc) discretizations = discretization_names(doc) diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 32d1bee..3c429b5 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -188,6 +188,10 @@ Optional("writes_back"): MapPattern(Str(), Str()), Optional("pseudo_time"): Enum(["steady"]), Optional("spin_up"): Bool(), + # what it does, a word of ymf.vocabulary.ROLES for the model's family; + # read from the structure above and written by closure, so a stated + # role is checked against it (ymf.vocabulary.check) + Optional("role"): Str(), Optional("binds"): MapPattern(Str(), SymbolBinding), # replaces the entry's regularize: for this sub-problem's sharp functions Optional("regularize"): MapPattern(Str(), RegularizeDef), @@ -293,6 +297,9 @@ "provenance": ProvenanceEnum, Optional("processes"): Seq(Str()), Optional("assumptions"): Seq(Str()), + # the model family (ymf.vocabulary.FAMILIES) the processes and + # assumptions identify; written by closure, checked if stated + Optional("family"): Str(), Optional("source_document"): Str(), Optional("notes"): Str(), } diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index ce52209..61baefe 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -1,21 +1,313 @@ -"""The words a spec states and a solver maps: ymf's vocabulary. +"""The words a spec states and a solver maps: ymf's vocabulary for model +families, sub-problem roles, discretization options and coefficient roles. -Each kind is a mapping ``{word: meaning}``. So far: :data:`LINEAR_SOLVERS`, -``direct`` and ``iterative`` and the packages a spec may still name, and -:func:`linear_solver_kind`. Stdlib only, like the rest of the spec core. +A dispatcher (proteus's ``DispatchTable``) maps a spec onto modules and +flags. It used to coin the words it matched on -- a sub-problem's role, a +stabilization method, a time integration -- which meant the spec could not +say them and a second solver could not read them. They live here instead +(C42 round 3, cekees 2026-11-06, decision 16): the spec states them, ymf +checks them on load, the closed spec writes the ones it derives, and a +solver's table only maps them. + +Each kind is a mapping ``{word: meaning}``. Where the dispatch table's word +was a solver's name for the thing (``vbdf``, ``SSP_RK3``), +ymf's word replaces it and the old one is accepted as an alias +(:data:`ALIASES`): a spec using it still loads, and :func:`canonical` gives +ymf's word. Aliases are not rewritten on load or in the closed spec yet, so +that a reader keyed on the old word keeps working until it maps the new one. + +What is here: + +* :data:`FAMILIES` -- model families, by the ``physical_model`` processes and + assumptions that identify them; :func:`family_of`. +* :data:`ROLES` -- what a sub-problem of a split discretization does, by + family; :func:`role_of` reads it from the sub-problem's structure. +* :data:`TIME_INTEGRATION`, :data:`STABILIZATION`, :data:`SCHEMES`, + :data:`STEP_CONTROL`, :data:`REGULARIZATIONS`, :data:`BINDING_MEANINGS`, + :data:`WRITES_BACK`, :data:`INERTIA_FORMS` -- the discretization's words. +* :data:`LINEAR_SOLVERS` -- ``direct`` and ``iterative``, and the packages a + spec may still name; :func:`linear_solver_kind`. + +:func:`check` is called on load (ymf.references). Stdlib only, like the rest +of the spec core. """ from __future__ import annotations -from typing import Any, Dict, Optional +import re +from typing import Any, Dict, Iterable, List, Optional -__all__ = ["LINEAR_SOLVERS", "linear_solver_kind", "VocabularyError"] +__all__ = ["FAMILIES", "ROLES", "TIME_INTEGRATION", "STABILIZATION", "SCHEMES", + "STEP_CONTROL", "REGULARIZATIONS", "BINDING_MEANINGS", "WRITES_BACK", + "INERTIA_FORMS", "LINEAR_SOLVERS", "ALIASES", + "canonical", "family_of", "role_of", "roles_of", "linear_solver_kind", + "check", "VocabularyError"] class VocabularyError(ValueError): """A word the vocabulary does not have, or one used where it cannot be.""" +# --------------------------------------------------------------------------- +# Model families +# --------------------------------------------------------------------------- + +#: a model belongs to a family when its physical_model lists every process +#: and assumption the family names +FAMILIES: Dict[str, Dict[str, Any]] = { + "two_phase_level_set": { + "processes": ["incompressible_flow", "two_phase_flow", "interface_transport"], + "means": "incompressible two-phase flow with a sharp interface carried by a level set", + }, + "shallow_water": { + "assumptions": ["hydrostatic", "depth_averaged", "nondispersive"], + "means": "the hydrostatic shallow-water equations (Saint-Venant)", + }, + # The dispersive model (Serre-Green-Naghdi) is depth averaged and not + # hydrostatic. The dispatch table keyed it on "hyperbolic_relaxation", + # which is how GN_SW2DCV discretizes it, not an assumption of the model; + # that spelling is still recognized (FAMILY_ALIASES). + "dispersive_shallow_water": { + "assumptions": ["depth_averaged", "dispersive"], + "means": "the dispersive (Serre-Green-Naghdi) shallow-water equations", + }, +} + +#: older ways of identifying a family, still recognized +FAMILY_ALIASES: Dict[str, List[Dict[str, List[str]]]] = { + "dispersive_shallow_water": [{"assumptions": ["depth_averaged", "hyperbolic_relaxation"]}], +} + + +def _physical(doc: Dict[str, Any]) -> Dict[str, Any]: + return ((doc.get("model") or {}).get("physical_model") or {}) + + +def _matches(needs: Dict[str, Any], have: Dict[str, set]) -> bool: + return all(set(needs.get(key) or []) <= have[key] for key in ("processes", "assumptions")) + + +def families_of(doc: Dict[str, Any]) -> List[str]: + """Every family the model's physical_model identifies, in table order.""" + physical = _physical(doc) + have = {"processes": set(physical.get("processes") or []), + "assumptions": set(physical.get("assumptions") or [])} + return [name for name, needs in FAMILIES.items() + if _matches(needs, have) + or any(_matches(alt, have) for alt in FAMILY_ALIASES.get(name, []))] + + +def family_of(doc: Dict[str, Any]) -> Optional[str]: + """The model's family: the one it states (``physical_model.family``), or + the one its processes and assumptions identify; None if none does. + Raises :class:`VocabularyError` if several do and the model states none.""" + stated = _physical(doc).get("family") + if stated is not None: + return str(stated) + found = families_of(doc) + if len(found) > 1: + raise VocabularyError( + "model.physical_model identifies the families %s; say which (family: ...)" + % ", ".join(found)) + return found[0] if found else None + + +# --------------------------------------------------------------------------- +# Sub-problem roles +# --------------------------------------------------------------------------- + +#: what a sub-problem does, by family. role_of reads it from what the +#: sub-problem solves, enforces, introduces and spins up. +ROLES: Dict[str, Dict[str, str]] = { + "two_phase_level_set": { + "velocity_pressure": "solves the equations for the velocity and the pressure together", + "velocity": "solves the momentum equation alone (a projection scheme's velocity step)", + "pressure_increment": "enforces a divergence-free velocity (the projection)", + "pressure": "solves the continuity equation for the pressure alone (the pressure update)", + "pressure_spin_up": "a spin-up solve for the initial pressure", + "volume_fraction": "introduces a conservative carrier of heaviside(level set) and transports it", + "level_set": "solves the interface equation for the level set", + "level_set_redistanced": "solves the interface equation and enforces |∇(level set)| = 1 " + "in one solve", + "redistancing": "enforces |∇(level set)| = 1 to steady state, writing the level set back", + "mass_correction": "introduces a correction of the level set so that heaviside(level set) " + "matches the carrier", + }, + "shallow_water": { + "shallow_water": "solves the mass and momentum equations together", + }, + "dispersive_shallow_water": { + "shallow_water": "solves the mass and momentum equations together", + }, +} + +_HEAVISIDE = re.compile(r"^\s*heaviside\(\s*([^\s()]+)\s*\)\s*$") + + +def _strong(doc: Dict[str, Any]) -> Dict[str, Any]: + return ((doc.get("model") or {}).get("strong_form") or {}) + + +def _ranks(strong: Dict[str, Any]) -> Dict[str, int]: + out = {} + for u in strong.get("unknowns") or []: + if isinstance(u, str): + out[u] = 0 + elif isinstance(u, dict): + out[u["name"]] = int(u.get("rank") or 0) + return out + + +def heaviside_of(doc: Dict[str, Any]) -> Dict[str, str]: + """``{coefficient: unknown}`` for each coefficient that is heaviside of an + unknown (``χ := heaviside(φ)`` gives ``{χ: φ}``): a phase indicator.""" + strong = _strong(doc) + ranks = _ranks(strong) + out = {} + for name, entry in (strong.get("coefficients") or {}).items(): + formula = entry.get("formula") if isinstance(entry, dict) else entry + m = _HEAVISIDE.match(str(formula or "")) + if m and m.group(1) in ranks: + out[name] = m.group(1) + return out + + +def _normal(text: Any) -> str: + return re.sub(r"\s+", "", str(text or "")) + + +def _is_eikonal(enforces: Any, level_sets: Iterable[str]) -> bool: + text = _normal(enforces) + return any(text in ("norm(∇%s)=1" % phi, "|∇%s|=1" % phi) for phi in level_sets) + + +def _is_divergence_free(enforces: Any, ranks: Dict[str, int]) -> bool: + text = _normal(enforces) + return any(rank == 1 and text == "∇·%s=0" % name for name, rank in ranks.items()) + + +def role_of(sub: Dict[str, Any], doc: Dict[str, Any], + family: Optional[str] = None) -> Optional[str]: + """What one sub-problem does (a word of :data:`ROLES`), read from its + structure; None if no role of the family fits. ``family`` defaults to + :func:`family_of`. A role the sub-problem states is not consulted: this + is what its structure says (:func:`check` compares the two).""" + family = family if family is not None else family_of(doc) + strong = _strong(doc) + ranks = _ranks(strong) + equations = {e.get("name"): e for e in strong.get("equations") or [] if isinstance(e, dict)} + solved = [equations[e].get("for") for e in sub.get("solves") or [] if e in equations] + vectors = [u for u in solved if ranks.get(u) == 1] + scalars = [u for u in solved if ranks.get(u) == 0] + phase = heaviside_of(doc) + level_sets = set(phase.values()) + new = sub.get("introduces") or {} + enforces = sub.get("enforces") + if family == "two_phase_level_set": + if solved: + if len(vectors) == 1 and len(scalars) == 1 and not set(scalars) & level_sets: + return "velocity_pressure" + if len(vectors) == 1 and not scalars: + return "velocity" + if not vectors and len(scalars) == 1 and scalars[0] in level_sets: + return "level_set_redistanced" if _is_eikonal(enforces, level_sets) else "level_set" + if not vectors and len(scalars) == 1: + return "pressure" + return None + if new.get("approximates") in phase: + return "volume_fraction" + if new.get("correction_of") in level_sets: + return "mass_correction" + if _is_eikonal(enforces, level_sets): + return "redistancing" + if _is_divergence_free(enforces, ranks): + return "pressure_increment" + if sub.get("spin_up"): + return "pressure_spin_up" + return None + if family in ("shallow_water", "dispersive_shallow_water"): + if solved and set(solved) == set(ranks): + return "shallow_water" + return None + + +def roles_of(doc: Dict[str, Any], entry: Dict[str, Any]) -> Dict[str, Optional[str]]: + """``{sub-problem: role}`` for one split discretization entry.""" + family = family_of(doc) + return {s["name"]: role_of(s, doc, family) for s in entry.get("subproblems") or []} + + +# --------------------------------------------------------------------------- +# The discretization's words +# --------------------------------------------------------------------------- + +TIME_INTEGRATION: Dict[str, str] = { + "backward_euler": "backward (implicit) Euler, first order", + "bdf2": "the second-order backward differentiation formula, variable step", + "ssp_rk3": "the three-stage, third-order strong-stability-preserving Runge-Kutta method", + "none": "the sub-problem has no time derivative (a constraint, a projection)", +} + +STABILIZATION: Dict[str, str] = { + "ASGS": "algebraic subgrid scale stabilization (variational multiscale)", + "SUPG": "streamline-upwind Petrov-Galerkin", + "residual_shock_capturing": "residual-based shock-capturing viscosity alone", + "entropy_viscosity": "entropy viscosity (Guermond, Pasquetti, Popov)", + "graph_viscosity_smoothness": "graph viscosity scaled by a smoothness indicator", + "graph_viscosity_entropy_residual": "graph viscosity scaled by the entropy residual", +} + +#: 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. +SCHEMES: Dict[str, Dict[str, Any]] = { + "graph_viscosity_convex_limiting": { + "means": "low-order graph viscosity with convex limiting toward the high-order " + "(entropy-viscosity) solution", + "options": { + "entropy_viscosity_coefficient": "the high-order solution's entropy-viscosity " + "coefficient (cE)", + "lumped_mass": "a lumped (true) or consistent (false) mass matrix", + "bounds_relaxation": "relax the convex-limiting bounds (true) or not", + }, + }, +} + +#: read in every scheme block +SCHEME_COMMON = {"scheme": "the scheme's name", "time_integration": "a TIME_INTEGRATION word", + "outputs": "the number of output intervals", "dt": "the time step"} + +STEP_CONTROL: Dict[str, str] = { + "min_cfl": "each sub-problem proposes a step from its CFL number; the system takes the " + "smallest", + "fixed": "a fixed step, dt", +} + +REGULARIZATIONS: Dict[str, str] = { + "smoothed_heaviside": "H_ε(φ) = (1 + φ/ε + sin(πφ/ε)/π)/2 on |φ| ≤ ε", + "smoothed_sign": "2 H_ε − 1", + "wet_dry_cutoff": "1/h -> 2h/(h² + max(h, hε)²)", +} + +BINDING_MEANINGS: Dict[str, str] = { + "element_size": "the size of each element of the mesh", + "dry_depth": "the depth below which a node is dry (set by the solver)", +} + +WRITES_BACK: Dict[str, str] = { + "replace": "the sub-problem's solution replaces the field", + "add": "the sub-problem's solution is added to the field (a correction)", + "mass_quadrature": "the field's values at the quadrature points are reset from it", +} + +#: weak-form labels with a meaning dispatchers share: the inertia form of a +#: momentum equation. Both are formulations of the same strong form when the +#: velocity is divergence free. +INERTIA_FORMS: Dict[str, str] = { + "conservative_inertia": "∂(ρv)/∂t + ∇·(ρ v⊗v)", + "nonconservative_inertia": "ρ (∂v/∂t + v·∇v)", +} + # --------------------------------------------------------------------------- # Linear solvers # --------------------------------------------------------------------------- @@ -52,3 +344,151 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: and str(options.get("ksp_type", "preonly")) == "preonly"): return "direct" return LINEAR_SOLVERS[word]["kind"] + + +#: the words of each kind, for check() and canonical() +_KINDS: Dict[str, Dict[str, Any]] = { + "family": FAMILIES, "role": {r: m for fam in ROLES.values() for r, m in fam.items()}, + "time_integration": TIME_INTEGRATION, "stabilization": STABILIZATION, "scheme": SCHEMES, + "step_control": STEP_CONTROL, "regularization": REGULARIZATIONS, + "binding_meaning": BINDING_MEANINGS, "writes_back": WRITES_BACK, + "linear_solver": LINEAR_SOLVERS, + "scheme_option": {o: m for s in SCHEMES.values() for o, m in s["options"].items()}, +} + +#: kind -> {older word: ymf's word}. The older words are the dispatch table's +#: (proteus's class or flag names); a spec may still use them. +ALIASES: Dict[str, Dict[str, str]] = { + "time_integration": {"vbdf": "bdf2", "SSP_RK3": "ssp_rk3"}, + "stabilization": {"shock_capturing": "residual_shock_capturing"}, + "role": {"pressure_initial": "pressure_spin_up"}, + "scheme_option": {"entropy_viscosity_cE": "entropy_viscosity_coefficient"}, +} + + +def canonical(kind: str, word: Any) -> str: + """ymf's word for ``word`` of ``kind`` (itself, or what its alias means); + raises :class:`VocabularyError` if ymf does not know it.""" + words = _KINDS[kind] + word = str(word) + if word in words: + return word + alias = ALIASES.get(kind, {}).get(word) + if alias is not None: + return alias + raise VocabularyError("%s %s: ymf knows %s" % ( + kind.replace("_", " "), word, + ", ".join(list(words) + ["%s (= %s)" % kv for kv in ALIASES.get(kind, {}).items()]))) + + +# --------------------------------------------------------------------------- +# The check on load +# --------------------------------------------------------------------------- + +def _word(kind: str, word: Any, where: str) -> str: + try: + return canonical(kind, word) + except VocabularyError as exc: + 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_solver(solver: Any, where: str) -> None: + if isinstance(solver, dict) and solver.get("linear_solver") is not None: + _word("linear_solver", solver["linear_solver"], where + ".solver.linear_solver") + + +def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[str]) -> None: + where = "solution_paths.discretizations[%s]" % (entry.get("name", "?"),) + _check_solver(entry.get("solver"), where) + step = entry.get("step_control") + if isinstance(step, dict) and step.get("type") is not None: + _word("step_control", step["type"], where + ".step_control.type") + block = entry.get("discretization") + if isinstance(block, dict): + if block.get("time_integration") is not None: + _word("time_integration", block["time_integration"], + where + ".discretization.time_integration") + if block.get("scheme") is not None: + scheme = _word("scheme", block["scheme"], where + ".discretization.scheme") + known = set(SCHEME_COMMON) | set(SCHEMES[scheme]["options"]) | { + a for a, w in ALIASES["scheme_option"].items() if w in SCHEMES[scheme]["options"]} + unread = sorted(set(block) - known) + if unread: + raise VocabularyError( + "%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)))) + for label, binding in list((entry.get("binds") or {}).items()): + if isinstance(binding, dict) and binding.get("meaning") is not None: + _word("binding_meaning", binding["meaning"], "%s.binds.%s.meaning" % (where, label)) + for function, rule in (entry.get("regularize") or {}).items(): + if isinstance(rule, dict) and rule.get("by") is not None: + _word("regularization", rule["by"], "%s.regularize.%s.by" % (where, function)) + roles = ROLES.get(family or "", {}) + for sub in entry.get("subproblems") or []: + 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_solver(sub.get("solver"), here) + for label, binding in (sub.get("binds") or {}).items(): + if isinstance(binding, dict) and binding.get("meaning") is not None: + _word("binding_meaning", binding["meaning"], "%s.binds.%s.meaning" % (here, label)) + for function, rule in (sub.get("regularize") or {}).items(): + if isinstance(rule, dict) and rule.get("by") is not None: + _word("regularization", rule["by"], "%s.regularize.%s.by" % (here, function)) + for field, how in (sub.get("writes_back") or {}).items(): + _word("writes_back", how, "%s.writes_back.%s" % (here, field)) + if sub.get("role") is not None: + stated = _word("role", sub["role"], here + ".role") + if family is None: + raise VocabularyError("%s.role: %s is a role of a model family, and the model " + "belongs to none" % (here, stated)) + if stated not in roles: + raise VocabularyError("%s.role: %s is not a role in family %s; its roles are %s" + % (here, stated, family, ", ".join(roles))) + derived = role_of(sub, doc, family) + if derived != stated: + raise VocabularyError( + "%s.role says %s, but what it %s makes it %s" % ( + here, stated, "solves, enforces and introduces", + derived if derived else "no role of family %s" % family)) + + +def check(doc: Dict[str, Any]) -> None: + """Every vocabulary word the document states is ymf's (or an alias of + one); a stated family or sub-problem role agrees with what the model and + the sub-problem's structure say. + Raises :class:`VocabularyError`.""" + physical = _physical(doc) + family = None + if physical.get("family") is not None: + family = _word("family", physical["family"], "model.physical_model.family") + found = families_of(doc) + if family not in found: + raise VocabularyError( + "model.physical_model.family is %s, but its processes and assumptions %s" + % (family, "identify %s" % ", ".join(found) if found else + "identify no family (%s needs %s)" % (family, _needs(family)))) + else: + found = families_of(doc) + family = found[0] if len(found) == 1 else None + for entry in ((doc.get("solution_paths") or {}).get("discretizations") or []): + if isinstance(entry, dict): + _check_entry(doc, entry, family) + + +def _needs(family: str) -> str: + needs = FAMILIES[family] + return "; ".join("%s %s" % (k, ", ".join(needs[k])) for k in ("processes", "assumptions") + if needs.get(k)) diff --git a/tests/fixtures/two_phase/dambreak_clsvof.ymf b/tests/fixtures/two_phase/dambreak_clsvof.ymf new file mode 100644 index 0000000..e26fec8 --- /dev/null +++ b/tests/fixtures/two_phase/dambreak_clsvof.ymf @@ -0,0 +1,32 @@ +# The dam break of dambreak.ymf with RANS2P and CLSVOF in place of the four +# interface solves (damBreakLevelSet.py with interface=1). No sub-problem +# carries χ here, so the atmosphere's χ inflow (what enters is air) is a +# condition on the sign of the φ CLSVOF solves (ymf.symbolic.split). +extends: dambreak.ymf + +solution_paths: + analytical: [] + discretizations: + - name: level_set_clsvof + provenance: proteus_derived + mesh: {h: 0.0322} + binds: + h: {meaning: element_size} + ε: {formula: "1.5 h"} + regularize: + heaviside: {by: smoothed_heaviside, width: ε} + step_control: {type: min_cfl, cfl: 0.25, step_exact: true} + solver: {type: nonlinear, nonlinear_solver: newton, linear_solver: iterative, max_iterations: 50} + subproblems: + - name: flow + solves: [momentum, continuity] + lags: {φ: previous_step, χ: {via: clsvof, at: previous_step}} + finite_element: {velocity: {family: CG, order: 1}, pressure: {family: CG, order: 1}} + time_integration: backward_euler + solver: {max_iterations: 100} + - name: clsvof + solves: [interface] + enforces: "norm(∇φ) = 1" + lags: {v: {via: flow, at: current_step}} + finite_element: {fields: {family: CG, order: 1}} + time_integration: backward_euler diff --git a/tests/test_linear_solver.py b/tests/test_linear_solver.py index e440c62..c57d6ee 100644 --- a/tests/test_linear_solver.py +++ b/tests/test_linear_solver.py @@ -3,6 +3,8 @@ request of its kind. """ +from pathlib import Path + import pytest from ymf.vocabulary import VocabularyError, linear_solver_kind @@ -30,3 +32,13 @@ def test_an_unknown_linear_solver_is_refused(): with pytest.raises(VocabularyError, match="linear_solver hypre: ymf knows direct, iterative"): linear_solver_kind({"linear_solver": "hypre"}) + +def test_the_schema_takes_direct_and_iterative(): + pytest.importorskip("strictyaml") + from ymf.schema import load_ymf + doc = load_ymf(Path(__file__).parent / "fixtures" / "two_phase" / "dambreak_clsvof.ymf") + entry = next(e for e in doc["solution_paths"]["discretizations"] + if e["name"] == "level_set_clsvof") + assert entry["solver"]["linear_solver"] == "iterative" + from ymf.discretizations import subproblem_solver + assert linear_solver_kind(subproblem_solver(entry, entry["subproblems"][0])) == "iterative" diff --git a/tests/test_vocabulary.py b/tests/test_vocabulary.py new file mode 100644 index 0000000..df884d2 --- /dev/null +++ b/tests/test_vocabulary.py @@ -0,0 +1,231 @@ +"""ymf's vocabulary (C42 round 3): the words a spec states and a solver's +dispatcher maps -- model families, sub-problem roles, the discretization's +words -- checked on load, derived ones written by closure. +""" + +import copy +from pathlib import Path + +import pytest + +pytest.importorskip("strictyaml") + +from ymf import vocabulary as v # noqa: E402 +from ymf.closure import input_digest # noqa: E402 +from ymf.explicit import explicit, without_derived # noqa: E402 +from ymf.references import YmfReferenceError, resolve # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 + +FIXTURES = Path(__file__).parent / "fixtures" +TWO_PHASE = FIXTURES / "two_phase" +SHALLOW = FIXTURES / "shallow_water" + + +@pytest.fixture +def dambreak(): + return load_ymf(TWO_PHASE / "dambreak.ymf") + + +@pytest.fixture +def clsvof(): + return load_ymf(TWO_PHASE / "dambreak_clsvof.ymf") + + +def _entry(doc, name): + return next(e for e in doc["solution_paths"]["discretizations"] if e["name"] == name) + + +def _sub(doc, entry, name): + return next(s for s in _entry(doc, entry)["subproblems"] if s["name"] == name) + + +# --- families ---------------------------------------------------------------- + +def test_the_families_are_identified_by_processes_and_assumptions(dambreak): + assert v.family_of(dambreak) == "two_phase_level_set" + assert v.family_of(load_ymf(SHALLOW / "lake_at_rest.ymf")) == "shallow_water" + assert v.family_of(load_ymf(Path(__file__).parents[1] / "examples" / "poisson.ymf")) is None + + +def test_the_dispersive_family_and_its_older_key(): + doc = {"model": {"physical_model": {"assumptions": ["depth_averaged", "dispersive"]}}} + assert v.family_of(doc) == "dispersive_shallow_water" + # the dispatch table keyed it on how GN_SW2DCV discretizes it + old = {"model": {"physical_model": {"assumptions": ["depth_averaged", "hyperbolic_relaxation"]}}} + assert v.family_of(old) == "dispersive_shallow_water" + + +def test_a_stated_family_is_checked(dambreak): + doc = copy.deepcopy(dambreak) + doc["model"]["physical_model"]["family"] = "two_phase_level_set" + resolve(doc) + doc["model"]["physical_model"]["family"] = "shallow_water" + with pytest.raises(YmfReferenceError, match="family is shallow_water, but its processes"): + resolve(doc) + doc["model"]["physical_model"]["family"] = "two_phase" + with pytest.raises(YmfReferenceError, match="family two_phase: ymf knows"): + resolve(doc) + + +# --- roles --------------------------------------------------------------------- + +def test_the_five_model_split_has_the_dispatch_tables_roles(dambreak): + assert v.roles_of(dambreak, _entry(dambreak, "level_set_five")) == { + "flow": "velocity_pressure", "vof": "volume_fraction", "ncls": "level_set", + "rdls": "redistancing", "mcorr": "mass_correction"} + + +def test_clsvof_solves_and_redistances_in_one_role(clsvof): + assert v.roles_of(clsvof, _entry(clsvof, "level_set_clsvof")) == { + "flow": "velocity_pressure", "clsvof": "level_set_redistanced"} + + +def test_the_projection_schemes_roles(dambreak): + """damBreak.py's clsvof_projection: CLSVOF, then the velocity step, the + pressure increment, the pressure update and a pressure spin-up.""" + subs = [{"name": "clsvof", "solves": ["interface"], "enforces": "norm(∇φ) = 1"}, + {"name": "flow", "solves": ["momentum"]}, + {"name": "pressureInc", "enforces": "∇·v = 0"}, + {"name": "pressure", "solves": ["continuity"]}, + {"name": "pressureInit", "spin_up": True}] + assert [v.role_of(s, dambreak) for s in subs] == [ + "level_set_redistanced", "velocity", "pressure_increment", "pressure", "pressure_spin_up"] + + +def test_the_shallow_water_role(): + doc = load_ymf(SHALLOW / "lake_at_rest.ymf") + assert v.roles_of(doc, doc["solution_paths"]["discretizations"][0]) == {"swe": "shallow_water"} + + +def test_a_stated_role_is_checked_against_the_structure(dambreak): + doc = copy.deepcopy(dambreak) + _sub(doc, "level_set_five", "vof")["role"] = "volume_fraction" + _sub(doc, "level_set_five", "mcorr")["role"] = "mass_correction" + resolve(doc) + _sub(doc, "level_set_five", "ncls")["role"] = "redistancing" + with pytest.raises(YmfReferenceError, match="ncls.*role says redistancing, but what it .* " + "makes it level_set"): + resolve(doc) + _sub(doc, "level_set_five", "ncls")["role"] = "shallow_water" + with pytest.raises(YmfReferenceError, match="not a role in family two_phase_level_set"): + resolve(doc) + # the old word for the spin-up is read as ymf's + assert v.canonical("role", "pressure_initial") == "pressure_spin_up" + + +def test_closure_writes_the_family_and_the_roles_out_without_rekeying(dambreak): + closed = explicit(dambreak) + assert closed["model"]["physical_model"]["family"] == "two_phase_level_set" + assert [s["role"] for s in _entry(closed, "level_set_five")["subproblems"]] == [ + "velocity_pressure", "volume_fraction", "level_set", "redistancing", "mass_correction"] + assert explicit(closed) == closed # idempotent + # derived: neither counts towards an output's key, stated or not + assert without_derived(closed)["model"]["physical_model"].get("family") is None + stated = copy.deepcopy(dambreak) + stated["model"]["physical_model"]["family"] = "two_phase_level_set" + _sub(stated, "level_set_five", "ncls")["role"] = "level_set" + realization = {"h": 0.0322} + assert (input_digest(stated, "level_set_five", realization) + == input_digest(dambreak, "level_set_five", realization)) + + +def test_a_model_of_no_family_closes_as_before(): + doc = load_ymf(Path(__file__).parents[1] / "examples" / "poisson.ymf") + closed = explicit(doc) + assert "family" not in (closed["model"].get("physical_model") or {}) + + +# --- the discretization's words ------------------------------------------------ + +#: every label proteus's DispatchTable (cekees/proteus main 74d453d3) matches +#: on, with ymf's word for it: the table maps these, and C5 step 3 switches it +#: to the right-hand side +DISPATCH_TABLE_LABELS = [ + ("family", "two_phase_level_set", "two_phase_level_set"), + ("family", "shallow_water", "shallow_water"), + ("family", "dispersive_shallow_water", "dispersive_shallow_water"), + ("role", "velocity_pressure", "velocity_pressure"), + ("role", "velocity", "velocity"), + ("role", "pressure_increment", "pressure_increment"), + ("role", "pressure", "pressure"), + ("role", "pressure_initial", "pressure_spin_up"), + ("role", "volume_fraction", "volume_fraction"), + ("role", "level_set", "level_set"), + ("role", "level_set_redistanced", "level_set_redistanced"), + ("role", "redistancing", "redistancing"), + ("role", "mass_correction", "mass_correction"), + ("role", "shallow_water", "shallow_water"), + ("time_integration", "backward_euler", "backward_euler"), + ("time_integration", "vbdf", "bdf2"), + ("time_integration", "none", "none"), + ("time_integration", "SSP_RK3", "ssp_rk3"), + ("stabilization", "ASGS", "ASGS"), + ("stabilization", "SUPG", "SUPG"), + ("stabilization", "graph_viscosity_smoothness", "graph_viscosity_smoothness"), + ("stabilization", "graph_viscosity_entropy_residual", "graph_viscosity_entropy_residual"), + ("stabilization", "entropy_viscosity", "entropy_viscosity"), + ("stabilization", "shock_capturing", "residual_shock_capturing"), + ("scheme", "graph_viscosity_convex_limiting", "graph_viscosity_convex_limiting"), + ("scheme_option", "entropy_viscosity_cE", "entropy_viscosity_coefficient"), + ("scheme_option", "lumped_mass", "lumped_mass"), + ("scheme_option", "bounds_relaxation", "bounds_relaxation"), + ("step_control", "min_cfl", "min_cfl"), + ("regularization", "smoothed_heaviside", "smoothed_heaviside"), + ("binding_meaning", "element_size", "element_size"), +] + + +@pytest.mark.parametrize("kind, label, word", DISPATCH_TABLE_LABELS) +def test_every_dispatch_table_label_is_ymf_vocabulary(kind, label, word): + assert v.canonical(kind, label) == word + assert v.canonical(kind, word) == word + + +def test_the_inertia_forms_are_named(): + assert set(v.INERTIA_FORMS) == {"conservative_inertia", "nonconservative_inertia"} + + +@pytest.mark.parametrize("path, value, message", [ + (("subproblems", "flow", "time_integration"), "crank_nicolson", + "flow].time_integration: time integration crank_nicolson: ymf knows backward_euler"), + (("subproblems", "flow", "stabilization"), {"method": "GLS"}, + "flow].stabilization.method: stabilization GLS"), + (("subproblems", "rdls", "writes_back"), {"φ": "overwrite"}, "writes_back.φ: writes back overwrite"), + (("subproblems", "rdls", "regularize"), {"sign": {"by": "tanh", "width": "εr"}}, + "regularization tanh"), + (("step_control",), {"type": "max_cfl"}, "step control max_cfl"), + (("binds",), {"h": {"meaning": "cell_size"}, "ε": {"formula": "1.5 h"}}, "binding meaning cell_size"), +]) +def test_a_word_ymf_does_not_have_is_refused(dambreak, path, value, message): + doc = copy.deepcopy(dambreak) + entry = _entry(doc, "level_set_five") + if path[0] == "subproblems": + _sub(doc, "level_set_five", path[1])[path[2]] = value + else: + entry[path[0]] = value + with pytest.raises(YmfReferenceError, match=message): + resolve(doc) + + +def test_the_old_words_still_load(dambreak): + doc = copy.deepcopy(dambreak) + _sub(doc, "level_set_five", "flow")["time_integration"] = "vbdf" + _sub(doc, "level_set_five", "vof")["stabilization"] = {"method": "shock_capturing"} + resolve(doc) + + +def test_a_scheme_and_its_options(): + doc = load_ymf(SHALLOW / "lake_at_rest.ymf") + block = doc["solution_paths"]["discretizations"][0]["discretization"] + assert block["scheme"] == "graph_viscosity_convex_limiting" + resolve(doc) + block["limiter"] = "minmod" + with pytest.raises(YmfReferenceError, match="has no option limiter; its options are " + "entropy_viscosity_coefficient"): + resolve(doc) + del block["limiter"] + block["entropy_viscosity_coefficient"] = block.pop("entropy_viscosity_cE") + resolve(doc) + block["scheme"] = "muscl" + with pytest.raises(YmfReferenceError, match="scheme muscl: ymf knows"): + resolve(doc) From dd9cb1b2c03757d9a8437703d245e8b30c405ab9 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:27 +0100 Subject: [PATCH 3/8] coefficient roles: a solver finds the density by its role, not its name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C5 decision 20 (Q4): proteus's realizer reads ρ, μ, g (two-phase) and g, n, θ, α, β, Z (SWE) by name from the family file. A coefficient now states what it means: `ρ: {formula: ..., role: density}`. - ymf.vocabulary.COEFFICIENT_ROLES (density, dynamic_viscosity, kinematic_viscosity, gravity, phase_indicator, surface_tension, bed_elevation, manning_coefficient, porosity, linear_drag, quadratic_drag, bed_friction, canopy_drag, diffusivity), each with its SI dimension; coefficient_roles, coefficient_by_role. The table's mannings, bathymetry, drag_alpha, drag_beta are aliases. - Checked on load: the role is known and used once per model. ymf.units.check refuses units of another dimension than the role's. - Fixtures: the two-phase and shallow-water family files state their roles. Measured (petsc-dev): ymf suite 930 -> 943 passed, 2 skipped. The two family fixtures are new input (their keys change); main's specs without a role close as before. Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 13 +++- src/ymf/schema.py | 4 ++ src/ymf/units.py | 14 ++++ src/ymf/vocabulary.py | 68 +++++++++++++++++-- .../fixtures/shallow_water/shallow_water.ymf | 16 ++--- .../two_phase/two_phase_level_set.ymf | 10 +-- tests/test_coefficient_roles.py | 67 ++++++++++++++++++ tests/test_explicit.py | 3 +- tests/test_vocabulary.py | 8 +++ 9 files changed, 184 insertions(+), 19 deletions(-) create mode 100644 tests/test_coefficient_roles.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 4c86dff..17023f5 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -874,6 +874,7 @@ 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` | A family is identified by the processes and assumptions of `physical_model` (two-phase: `incompressible_flow`, `two_phase_flow`, @@ -885,12 +886,22 @@ equations are for), enforces, introduces and spins up. Both may be stated structure say; a closed spec writes both out (`ymf.explicit`), and neither counts towards an output's key, since each follows from what does. +A **coefficient role** says what a coefficient means whatever the model +calls it: `ρ: {formula: "ρw (1 − χ) + ρa χ", units: kg/m3, role: density}`. +A solver that needs the density, the gravity or the bed finds it by its +role (`ymf.vocabulary.coefficient_by_role(doc, "density")`), not by the +name the family file happens to use. A role is used by one coefficient of +a model, and `ymf.units.check` refuses units of another dimension than the +role's. + Some words were first the dispatch table's, named after a solver's class or flag; ymf's word replaces them and the old one is still read as an alias (`ymf.vocabulary.ALIASES`, `canonical`): `vbdf` is `bdf2`, `SSP_RK3` is `ssp_rk3`, `shock_capturing` (the method) is `residual_shock_capturing`, `pressure_initial` is `pressure_spin_up`, `entropy_viscosity_cE` is -`entropy_viscosity_coefficient`. A spec using an alias +`entropy_viscosity_coefficient`, and the coefficient roles `mannings`, +`bathymetry`, `drag_alpha`, `drag_beta` are `manning_coefficient`, +`bed_elevation`, `linear_drag`, `quadratic_drag`. A spec using an alias loads, and is not rewritten: a reader keyed on the old word keeps working until it maps the new one. `dispersive_shallow_water` was identified by the assumption `hyperbolic_relaxation`, which is how GN_SW2DCV discretizes diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 3c429b5..ab96efc 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -459,6 +459,10 @@ # the unknowns a formula follows, directly or through another # coefficient; written by closure (ymf.explicit), checked on load Optional("depends_on"): Seq(Str()), + # what the coefficient means, a word of + # ymf.vocabulary.COEFFICIENT_ROLES (density, gravity, bed_elevation): + # a solver finds a coefficient by its role, not its name + Optional("role"): Str(), } ) diff --git a/src/ymf/units.py b/src/ymf/units.py index 11310ed..97343f8 100644 --- a/src/ymf/units.py +++ b/src/ymf/units.py @@ -183,6 +183,8 @@ def check(doc: Dict[str, Any], missing_units: str = "skip") -> UnitCheckResult: is the diffusive flux of the variable's equation. - Each ``initial_conditions[].units`` is dimensionally compatible with the ``unknowns[].units`` of the field it initializes. + - A coefficient with a ``role`` (ymf.vocabulary.COEFFICIENT_ROLES) and + ``units`` has the role's dimension. - A ``density`` or ``viscosity`` scale given as a number while a ``rho`` (``ρ``) or ``mu`` (``μ``) coefficient is also given: ``error`` if they differ, ``warning`` if they agree. Derive the scale from the coefficient @@ -245,6 +247,18 @@ def _check_against_unknown(entries, var_key, location_fmt): to_pint_unit(spec["units"]) except UnitParseError as exc: result.issues.append(UnitIssue("error", f"coefficients[{name}]", str(exc))) + continue + role = spec.get("role") + if role is not None: + from ymf.vocabulary import COEFFICIENT_ROLES, VocabularyError, canonical + try: + expected = COEFFICIENT_ROLES[canonical("coefficient_role", role)]["units"] + except VocabularyError: + continue # refused on load (ymf.references) + if not units_compatible(spec["units"], expected): + result.issues.append(UnitIssue( + "error", f"coefficients[{name}]", + f"units {spec['units']} are not those of its role {role} ({expected})")) # A scale stated as a number beside a coefficient for the same quantity # is one value written twice, and the copies drift apart when someone diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index 61baefe..2918633 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -10,7 +10,7 @@ solver's table only maps them. Each kind is a mapping ``{word: meaning}``. Where the dispatch table's word -was a solver's name for the thing (``vbdf``, ``SSP_RK3``), +was a solver's name for the thing (``vbdf``, ``SSP_RK3``, ``mannings``), ymf's word replaces it and the old one is accepted as an alias (:data:`ALIASES`): a spec using it still loads, and :func:`canonical` gives ymf's word. Aliases are not rewritten on load or in the closed spec yet, so @@ -27,6 +27,9 @@ :data:`WRITES_BACK`, :data:`INERTIA_FORMS` -- the discretization's words. * :data:`LINEAR_SOLVERS` -- ``direct`` and ``iterative``, and the packages a spec may still name; :func:`linear_solver_kind`. +* :data:`COEFFICIENT_ROLES` -- what a coefficient means (``density``, + ``gravity``, ``bed_elevation``), so a solver finds the density by its + role, not by the name the family file gives it; :func:`coefficient_by_role`. :func:`check` is called on load (ymf.references). Stdlib only, like the rest of the spec core. @@ -39,9 +42,9 @@ __all__ = ["FAMILIES", "ROLES", "TIME_INTEGRATION", "STABILIZATION", "SCHEMES", "STEP_CONTROL", "REGULARIZATIONS", "BINDING_MEANINGS", "WRITES_BACK", - "INERTIA_FORMS", "LINEAR_SOLVERS", "ALIASES", + "INERTIA_FORMS", "LINEAR_SOLVERS", "COEFFICIENT_ROLES", "ALIASES", "canonical", "family_of", "role_of", "roles_of", "linear_solver_kind", - "check", "VocabularyError"] + "coefficient_by_role", "coefficient_roles", "check", "VocabularyError"] class VocabularyError(ValueError): @@ -346,13 +349,43 @@ def linear_solver_kind(solver: Optional[Dict[str, Any]]) -> Optional[str]: return LINEAR_SOLVERS[word]["kind"] +# --------------------------------------------------------------------------- +# Coefficient roles +# --------------------------------------------------------------------------- + +#: what a coefficient means, independent of the name a model gives it. A +#: model gives a coefficient a role (``ρ: {formula: ..., role: density}``) and +#: a solver that needs the density finds it by the role. ``units`` is the SI +#: dimension a coefficient of that role has (checked by ymf.units). +COEFFICIENT_ROLES: Dict[str, Dict[str, str]] = { + "density": {"units": "kg/m3", "means": "mass per unit volume (of the mixture, in two-phase " + "flow)"}, + "dynamic_viscosity": {"units": "Pa*s", "means": "the dynamic viscosity μ"}, + "kinematic_viscosity": {"units": "m2/s", "means": "the kinematic viscosity ν = μ/ρ"}, + "gravity": {"units": "m/s2", "means": "the gravitational acceleration (a vector, or its " + "magnitude in a depth-averaged model)"}, + "phase_indicator": {"units": "1", "means": "0 in phase 0, 1 in phase 1: heaviside of the level " + "set"}, + "surface_tension": {"units": "N/m", "means": "the surface tension coefficient σ"}, + "bed_elevation": {"units": "m", "means": "the bed (bathymetry) Z"}, + "manning_coefficient": {"units": "s/m^(1/3)", "means": "Manning's n in the bed friction"}, + "porosity": {"units": "1", "means": "the fraction of the volume (or plan area) open to the " + "flow"}, + "linear_drag": {"units": "1/s", "means": "the linear (Darcy) drag coefficient α"}, + "quadratic_drag": {"units": "1/m", "means": "the quadratic (Forchheimer) drag coefficient β"}, + "bed_friction": {"units": "m2/s2", "means": "the bed shear stress over the density, τb"}, + "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 words of each kind, for check() and canonical() _KINDS: Dict[str, Dict[str, Any]] = { "family": FAMILIES, "role": {r: m for fam in ROLES.values() for r, m in fam.items()}, "time_integration": TIME_INTEGRATION, "stabilization": STABILIZATION, "scheme": SCHEMES, "step_control": STEP_CONTROL, "regularization": REGULARIZATIONS, "binding_meaning": BINDING_MEANINGS, "writes_back": WRITES_BACK, - "linear_solver": LINEAR_SOLVERS, + "linear_solver": LINEAR_SOLVERS, "coefficient_role": COEFFICIENT_ROLES, "scheme_option": {o: m for s in SCHEMES.values() for o, m in s["options"].items()}, } @@ -363,6 +396,8 @@ 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"}, + "coefficient_role": {"mannings": "manning_coefficient", "bathymetry": "bed_elevation", + "drag_alpha": "linear_drag", "drag_beta": "quadratic_drag"}, } @@ -381,6 +416,21 @@ def canonical(kind: str, word: Any) -> str: ", ".join(list(words) + ["%s (= %s)" % kv for kv in ALIASES.get(kind, {}).items()]))) +def coefficient_roles(doc: Dict[str, Any]) -> Dict[str, str]: + """``{role: coefficient name}`` of the model's coefficients that state one + (roles in ymf's words).""" + out = {} + for name, entry in (_strong(doc).get("coefficients") or {}).items(): + if isinstance(entry, dict) and entry.get("role") is not None: + out[canonical("coefficient_role", entry["role"])] = name + return out + + +def coefficient_by_role(doc: Dict[str, Any], role: str) -> Optional[str]: + """The name of the model's coefficient with ``role``, or None.""" + return coefficient_roles(doc).get(canonical("coefficient_role", role)) + + # --------------------------------------------------------------------------- # The check on load # --------------------------------------------------------------------------- @@ -468,7 +518,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st def check(doc: Dict[str, Any]) -> None: """Every vocabulary word the document states is ymf's (or an alias of one); a stated family or sub-problem role agrees with what the model and - the sub-problem's structure say. + the sub-problem's structure say; a coefficient role is used once. Raises :class:`VocabularyError`.""" physical = _physical(doc) family = None @@ -483,6 +533,14 @@ def check(doc: Dict[str, Any]) -> None: else: found = families_of(doc) family = found[0] if len(found) == 1 else None + 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: + where = "model.strong_form.coefficients.%s.role" % (name,) + role = _word("coefficient_role", entry["role"], where) + if role in seen: + raise VocabularyError("%s: %s is already the role of %s" % (where, role, seen[role])) + seen[role] = name for entry in ((doc.get("solution_paths") or {}).get("discretizations") or []): if isinstance(entry, dict): _check_entry(doc, entry, family) diff --git a/tests/fixtures/shallow_water/shallow_water.ymf b/tests/fixtures/shallow_water/shallow_water.ymf index 3732992..6969ec1 100644 --- a/tests/fixtures/shallow_water/shallow_water.ymf +++ b/tests/fixtures/shallow_water/shallow_water.ymf @@ -28,14 +28,14 @@ model: for: q equation: "∂(θ q)/∂t + ∇·(θ q⊗q/h) + ∇(θ g h²/2) − (g h²/2)∇θ + θ g h ∇Z + θ τb + Fd = 0 in Ω" coefficients: - τb: {formula: "g n² norm(q) q / h^(7/3)"} # Manning bed friction - Fd: {formula: "(α + β norm(q)/h) q"} # Darcy-Forchheimer drag, per unit plan area - g: {units: m/s2} - n: {units: s/m^(1/3)} - θ: {units: "1"} # porosity: 1 - m π D²/4 in a canopy, 1 elsewhere - Z: {units: m} # the bed - α: {units: 1/s} - β: {units: 1/m} + τb: {formula: "g n² norm(q) q / h^(7/3)", role: bed_friction} # Manning + Fd: {formula: "(α + β norm(q)/h) q", role: canopy_drag} # Darcy-Forchheimer, per unit plan area + g: {units: m/s2, role: gravity} + n: {units: s/m^(1/3), role: manning_coefficient} + θ: {units: "1", role: porosity} # porosity: 1 - m π D²/4 in a canopy, 1 elsewhere + Z: {units: m, role: bed_elevation} # the bed + α: {units: 1/s, role: linear_drag} + β: {units: 1/m, role: quadratic_drag} condition_sets: wall: # a no-flux wall (SW2DCV's integrated-by-parts walls) - {variable: q, type: slip} diff --git a/tests/fixtures/two_phase/two_phase_level_set.ymf b/tests/fixtures/two_phase/two_phase_level_set.ymf index 1036d7b..5cb9426 100644 --- a/tests/fixtures/two_phase/two_phase_level_set.ymf +++ b/tests/fixtures/two_phase/two_phase_level_set.ymf @@ -28,15 +28,17 @@ model: - name: interface for: φ equation: "∂φ/∂t + v·∇φ = 0 in Ω" + # a role says what a coefficient means (ymf.vocabulary), so a solver + # finds the density by its role, not by the name this file gives it coefficients: - χ: {formula: "heaviside(φ)", units: "1"} - ρ: {formula: "ρw (1 − χ) + ρa χ", units: kg/m3} - μ: {formula: "ρw νw (1 − χ) + ρa νa χ", units: Pa*s} + χ: {formula: "heaviside(φ)", units: "1", role: phase_indicator} + ρ: {formula: "ρw (1 − χ) + ρa χ", units: kg/m3, role: density} + μ: {formula: "ρw νw (1 − χ) + ρa νa χ", units: Pa*s, role: dynamic_viscosity} ρw: {units: kg/m3} νw: {units: m2/s} ρa: {units: kg/m3} νa: {units: m2/s} - g: {units: m/s2} + g: {units: m/s2, role: gravity} # what the cases' walls and tops mean, written once (Proteus's # BC_RANS.setFreeSlip and setAtmosphere, for this model's unknowns) condition_sets: diff --git a/tests/test_coefficient_roles.py b/tests/test_coefficient_roles.py new file mode 100644 index 0000000..31b507d --- /dev/null +++ b/tests/test_coefficient_roles.py @@ -0,0 +1,67 @@ +"""Coefficient roles (C42 round 3, decision 20): what a coefficient means, +whatever the model calls it, so a solver finds the density, the gravity or +the bed by its role and not by name. +""" + +import copy +from pathlib import Path + +import pytest + +pytest.importorskip("strictyaml") + +from ymf import vocabulary as v # noqa: E402 +from ymf.references import YmfReferenceError, resolve # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 + +FIXTURES = Path(__file__).parent / "fixtures" + + +def test_the_two_phase_family_states_its_roles(): + doc = load_ymf(FIXTURES / "two_phase" / "dambreak.ymf") + assert v.coefficient_roles(doc) == {"phase_indicator": "χ", "density": "ρ", + "dynamic_viscosity": "μ", "gravity": "g"} + assert v.coefficient_by_role(doc, "density") == "ρ" + assert v.coefficient_by_role(doc, "surface_tension") is None + + +def test_the_shallow_water_family_states_its_roles(): + doc = load_ymf(FIXTURES / "shallow_water" / "lake_at_rest.ymf") + roles = v.coefficient_roles(doc) + assert roles == {"bed_friction": "τb", "canopy_drag": "Fd", "gravity": "g", + "manning_coefficient": "n", "porosity": "θ", "bed_elevation": "Z", + "linear_drag": "α", "quadratic_drag": "β"} + # the dispatch table's names for them are aliases + assert v.coefficient_by_role(doc, "mannings") == "n" + assert v.coefficient_by_role(doc, "bathymetry") == "Z" + + +def test_a_role_is_the_closed_specs_too(): + from ymf.explicit import explicit + closed = explicit(load_ymf(FIXTURES / "two_phase" / "dambreak.ymf")) + assert closed["model"]["strong_form"]["coefficients"]["ρ"]["role"] == "density" + + +def test_a_role_is_used_once_and_must_be_known(): + doc = load_ymf(FIXTURES / "two_phase" / "dambreak.ymf") + bad = copy.deepcopy(doc) + bad["model"]["strong_form"]["coefficients"]["ρw"]["role"] = "density" + with pytest.raises(YmfReferenceError, match="ρw.role: density is already the role of ρ"): + resolve(bad) + bad = copy.deepcopy(doc) + bad["model"]["strong_form"]["coefficients"]["ρw"]["role"] = "water_density" + with pytest.raises(YmfReferenceError, match="coefficient role water_density: ymf knows density"): + resolve(bad) + + +def test_units_must_be_the_roles(): + pytest.importorskip("pint") + from ymf.units import check + doc = load_ymf(FIXTURES / "two_phase" / "dambreak.ymf") + assert check(doc).ok + bad = copy.deepcopy(doc) + bad["model"]["strong_form"]["coefficients"]["μ"]["units"] = "m2/s" + result = check(bad) + assert not result.ok + assert any("units m2/s are not those of its role dynamic_viscosity (Pa*s)" in i.message + for i in result) diff --git a/tests/test_explicit.py b/tests/test_explicit.py index 6ece518..a28c180 100644 --- a/tests/test_explicit.py +++ b/tests/test_explicit.py @@ -109,7 +109,8 @@ def test_explicit_is_idempotent_and_leaves_plain_specs_alone(): def test_the_closed_dam_break_names_its_coefficients_of_the_state(): closed = explicit(load_composed(DAMBREAK)) coefficients = closed["model"]["strong_form"]["coefficients"] - assert coefficients["χ"] == {"formula": "heaviside(φ)", "units": "1", "depends_on": ["φ"]} + assert coefficients["χ"] == {"formula": "heaviside(φ)", "units": "1", "role": "phase_indicator", + "depends_on": ["φ"]} assert coefficients["ρ"]["depends_on"] == ["φ"] assert coefficients["μ"]["depends_on"] == ["φ"] assert "depends_on" not in coefficients["ρw"] diff --git a/tests/test_vocabulary.py b/tests/test_vocabulary.py index df884d2..cd4629a 100644 --- a/tests/test_vocabulary.py +++ b/tests/test_vocabulary.py @@ -172,6 +172,14 @@ def test_a_model_of_no_family_closes_as_before(): ("step_control", "min_cfl", "min_cfl"), ("regularization", "smoothed_heaviside", "smoothed_heaviside"), ("binding_meaning", "element_size", "element_size"), + ("coefficient_role", "density", "density"), + ("coefficient_role", "dynamic_viscosity", "dynamic_viscosity"), + ("coefficient_role", "gravity", "gravity"), + ("coefficient_role", "mannings", "manning_coefficient"), + ("coefficient_role", "porosity", "porosity"), + ("coefficient_role", "drag_alpha", "linear_drag"), + ("coefficient_role", "drag_beta", "quadratic_drag"), + ("coefficient_role", "bathymetry", "bed_elevation"), ] From 8752771276a09a5a146ab58f44cdbdfbfae6a514 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:27 +0100 Subject: [PATCH 4/8] split: a condition on an uncarried phase indicator is its level set's sign MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C5 decision 18 (Q2): with CLSVOF solving the level set alone (no VOF carrying χ), split_problem dropped the atmosphere's χ inflow, the two-condition signature matched no BC_RANS setter, and proteus refuses level_set_clsvof there. ymf now states it: a condition on χ := heaviside(φ) that no sub-problem carries goes to the sub-problem solving φ, as a condition on φ's sign (heaviside(φ) = 1 says φ > 0 and no more): {variable: φ, type: dirichlet, only: inflow, sign: 1, indicator: {variable: χ, value: 1.0}}, no value; a solver imposing one picks it with that sign (Proteus's CLSVOF gets vof_air = 1). A formula or a value other than 0, 1/2, 1 is refused. Measured (petsc-dev): ymf suite 943 -> 949 passed, 2 skipped. level_set_clsvof: clsvof gets φ inflow sign +1 on `top`, flow keeps p = 0 and the open velocity. level_set_five unchanged: VOF's χh inflow 1.0, ncls and rdls none (as damBreakLevelSet.py). Proteus is unaffected until it maps the new entry: its atmosphere signature still needs χ, so it keeps refusing. Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 16 +++++++- src/ymf/symbolic/split.py | 54 ++++++++++++++++++++++-- tests/test_indicator_conditions.py | 66 ++++++++++++++++++++++++++++++ 3 files changed, 131 insertions(+), 5 deletions(-) create mode 100644 tests/test_indicator_conditions.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 17023f5..5212c8c 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -853,8 +853,20 @@ regularizations it used, an introduced unknown's initial condition, its effective solver, and its **boundary conditions**: those on the unknowns it solves for, and those on a coefficient its introduced unknown carries (atmosphere's `χ` inflow is VOF's `χh` inflow), with condition sets -expanded. A condition on a field a sub-problem only reads is another's. A solver maps a sub-problem onto its own modules (a -dispatcher); `proteus:` blocks are interim hints for it, carried as text. +expanded. A condition on a field a sub-problem only reads is another's. +A condition on a **phase indicator no sub-problem carries** (`χ := +heaviside(φ)` with no VOF, as when CLSVOF solves the level set alone) is a +condition on the sign of the level set, given to the sub-problem that +solves it: `heaviside(φ) = 1` says `φ > 0` and no more. Its entry has +`variable: φ`, `sign` (`1` for χ = 1, `-1` for 0, `0` for 1/2), the +indicator's own `{variable, value}` and no `value`; a solver that imposes a +Dirichlet value picks one with that sign. So the atmosphere's `χ` inflow +of 1 (what enters is air) is VOF's `χh` inflow in `level_set_five` and the +positive `φ` inflow of CLSVOF in `level_set_clsvof` +([`dambreak_clsvof.ymf`](../tests/fixtures/two_phase/dambreak_clsvof.ymf)). +Anything else on such an indicator (a formula, another value) is refused. +A solver maps a sub-problem onto its own modules (a dispatcher); `proteus:` +blocks are interim hints for it, carried as text. ### The words a dispatcher maps diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index e8dcf42..31fba24 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -110,6 +110,10 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: approximates = {s["introduces"]["approximates"]: s["introduces"]["name"] for s in subproblems if (s.get("introduces") or {}).get("approximates")} entry_bound = _bind(entry.get("binds") or {}, {}, dim, "the discretization's binds") + # phase indicators (χ := heaviside(φ)) no sub-problem carries: a condition + # on one is the sub-problem solving its level set's (C5 decision 18) + from ymf.vocabulary import heaviside_of + uncarried = {c: u for c, u in heaviside_of(doc).items() if c not in approximates} numbers = _coefficients(spec, dim, strict=False) domain = strong["domain"] @@ -252,8 +256,9 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: raise SymbolicError("%s, enforces: %s" % (where, exc)) from exc carried = {(s.get("introduces") or {}).get("approximates"): sub["introduces"]["name"] for s in [sub] if (s.get("introduces") or {}).get("approximates")} + indicators = {c: u for c, u in uncarried.items() if u in own} record["boundary_conditions"] = _conditions(strong, own, carried, space, dim, - lower, upper, where) + lower, upper, where, indicators) out_subs.append(record) initial = {} @@ -277,12 +282,25 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: "initial": initial, "subproblems": out_subs} -def _conditions(strong, own, carried, space, dim, lower, upper, where) -> List[Dict[str, Any]]: +#: a phase indicator's value -> the sign of its level set there +_INDICATOR_SIGN = {0.0: -1, 0.5: 0, 1.0: 1} + + +def _conditions(strong, own, carried, space, dim, lower, upper, where, + indicators=None) -> List[Dict[str, Any]]: """The boundary conditions one sub-problem imposes, as plain data. Those on its own unknowns, and those on a coefficient its introduced unknown carries (atmosphere's χ inflow is VOF's χh inflow). Conditions on - what it only reads are another sub-problem's. Each entry has ``type``, + what it only reads are another sub-problem's. + + ``indicators`` maps a phase indicator no sub-problem carries to the level + set this one solves (χ := heaviside(φ), with no VOF): a condition on χ is + then a condition on φ's sign, since heaviside(φ) = 1 says φ > 0 and no + more. Such an entry has ``variable`` φ, ``sign`` (1, -1, or 0 for χ = + 1/2), ``indicator: {variable: χ, value}`` and no ``value``: a solver that + imposes a value picks one with that sign. Atmosphere's χ inflow of 1 + (air enters) is CLSVOF's φ inflow, positive. Each entry has ``type``, ``variable``, ``region``, ``where`` (boolean code using ``tol``, None for the whole boundary), ``set`` if it came from one, the ``components`` it acts on, and its data: ``value`` (code; per component for a vector, @@ -305,6 +323,10 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where) -> List[D target, rank = variable, own[variable] elif variable in carried: target, rank = carried[variable], 0 + elif variable in (indicators or {}): + out.append(_indicator_condition(bc, indicators[variable], regions, strong, + space, where)) + continue else: continue here = "%s, boundary condition %s on %s" % (where, bc["type"], bc["region"]) @@ -349,6 +371,32 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where) -> List[D return out +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`).""" + from ymf.symbolic.problem import _selector + here = "%s, boundary condition %s on %s" % (where, bc["type"], bc["region"]) + if bc["type"] != "dirichlet" or bc.get("value") is None or bc.get("component"): + raise SymbolicError( + "%s: %s is heaviside(%s), and no sub-problem carries it, so the condition is on " + "%s's sign; only a constant value (0, 1/2 or 1, inflow or dirichlet) says one" + % (here, bc["variable"], level_set, level_set)) + value = float(bc["value"]) + if value not in _INDICATOR_SIGN: + raise SymbolicError( + "%s: %s is heaviside(%s), whose values are 0, 1/2 and 1; %g says no sign of %s" + % (here, bc["variable"], level_set, value, level_set)) + entry: Dict[str, Any] = {"type": "dirichlet", "variable": level_set, "region": bc["region"], + **_selector(regions[bc["region"]], strong["domain"], space)} + for key in ("only", "imposed", "expanded_from"): + if bc.get(key) is not None: + entry[key] = bc[key] + entry["components"] = [level_set] + entry["sign"] = _INDICATOR_SIGN[value] + entry["indicator"] = {"variable": bc["variable"], "value": value} + return entry + + def _bind(binds: Dict[str, Any], outer: Dict[str, Any], dim: int, where: str) -> Dict[str, Any]: """Resolve ``binds``: a symbol with only a ``meaning`` stays a symbol the solver supplies (h, the element size); one with a formula or value is diff --git a/tests/test_indicator_conditions.py b/tests/test_indicator_conditions.py new file mode 100644 index 0000000..f000f3b --- /dev/null +++ b/tests/test_indicator_conditions.py @@ -0,0 +1,66 @@ +"""A condition on a phase indicator no sub-problem carries (C42 round 3, +decision 18): with CLSVOF solving the level set alone, the atmosphere's +χ inflow (air enters) is a condition on the sign of φ. +""" + +import copy +from pathlib import Path + +import pytest + +pytest.importorskip("sympy") +pytest.importorskip("strictyaml") + +from ymf.schema import load_ymf # noqa: E402 +from ymf.symbolic.language import SymbolicError # noqa: E402 +from ymf.symbolic.split import split_problem # noqa: E402 + +TWO_PHASE = Path(__file__).parent / "fixtures" / "two_phase" + + +@pytest.fixture +def doc(): + return load_ymf(TWO_PHASE / "dambreak_clsvof.ymf") + + +def _conditions(split, name): + return next(s for s in split["subproblems"] if s["name"] == name)["boundary_conditions"] + + +def test_clsvof_takes_the_atmospheres_inflow_as_the_sign_of_phi(doc): + split = split_problem(doc, "level_set_clsvof") + (bc,) = _conditions(split, "clsvof") + assert bc["variable"] == "φ" and bc["components"] == ["φ"] + assert (bc["type"], bc["only"], bc["region"], bc["sign"]) == ("dirichlet", "inflow", "top", 1) + assert bc["indicator"] == {"variable": "χ", "value": 1.0} + assert "value" not in bc + assert bc["expanded_from"] == {"type": "inflow", "set": "atmosphere"} + # the flow keeps its own: p = 0 and the open velocity, nothing on χ + assert {c["variable"] for c in _conditions(split, "flow")} == {"p", "v"} + + +def test_with_a_carrier_nothing_changes(doc): + """level_set_five: VOF carries χ, so the inflow is its χh's, and the + level set and its redistancing take none (as the deck).""" + split = split_problem(doc, "level_set_five") + (vof,) = _conditions(split, "vof") + assert (vof["variable"], vof["carried_by"], vof["value"]) == ("χ", "χh", "1.0") + assert _conditions(split, "ncls") == [] and _conditions(split, "rdls") == [] + + +@pytest.mark.parametrize("value, sign", [(0.0, -1), (0.5, 0), (1.0, 1)]) +def test_each_value_of_the_indicator_is_a_sign(doc, value, sign): + doc = copy.deepcopy(doc) + atmosphere = doc["model"]["strong_form"]["condition_sets"]["atmosphere"] + next(c for c in atmosphere if c["variable"] == "χ")["value"] = value + (bc,) = _conditions(split_problem(doc, "level_set_clsvof"), "clsvof") + assert bc["sign"] == sign + + +def test_a_value_no_sign_says_is_refused(doc): + doc = copy.deepcopy(doc) + atmosphere = doc["model"]["strong_form"]["condition_sets"]["atmosphere"] + next(c for c in atmosphere if c["variable"] == "χ")["value"] = 0.3 + with pytest.raises(SymbolicError, match="χ is heaviside.φ., whose values are 0, 1/2 and 1; " + "0.3 says no sign of φ"): + split_problem(doc, "level_set_clsvof") From c839f9e7da72760ef04a2cd425ddfdb0b98a6c5a Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:28 +0100 Subject: [PATCH 5/8] archive: the spec part reads back as written (Y1) C5 finding Y1: a free-form value `eb_penalty_constant: 1.0e6` under a `proteus:` hint loads from the spec as '1.0e6'. The archive was read with pyyaml (YAML 1.2 floats), re-dumped, and validated: '1000000.0'. Another input digest, so `--check` found no record and planned a new output. compose._read now reads an archive's specification part (up to the top-level `outputs:`, which the writer puts last) with pyyaml's base loader, every scalar the string it is written as, before strictyaml types it; the typed read still supplies outputs and composition. Measured: dambreak with hints {1.0e6, 1e-3, true, '0x10', 007}: input digest ee257dfd -> cf8edbd4 across write+load before, 0848213f both ways after, and the same after a second round trip. Typed values keep their types. Archives already written with such a value now match their keys again. ymf suite 949 -> 951 passed, 2 skipped. Co-Authored-By: Claude Opus 5.5 --- src/ymf/compose.py | 25 ++++++++++- tests/test_archive_spec_as_written.py | 62 +++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 tests/test_archive_spec_as_written.py diff --git a/src/ymf/compose.py b/src/ymf/compose.py index 5459ea1..c970db2 100644 --- a/src/ymf/compose.py +++ b/src/ymf/compose.py @@ -404,6 +404,20 @@ def _read_text(path: Path) -> str: return text +_OUTPUTS_LINE = re.compile(r"^outputs:", re.M) + + +def _as_written(text: str) -> Dict[str, Any]: + """An archive's mappings and lists with every scalar the string it is + written as (pyyaml's base loader), up to its top-level ``outputs:``: the + writer puts them last, and they hold the arrays.""" + m = _OUTPUTS_LINE.search(text) + head = text[:m.start()] if m else text + loader = getattr(yaml, "CBaseLoader", yaml.BaseLoader) + data = yaml.load(head, Loader=loader) + return data if isinstance(data, dict) else {} + + def _read(path: Path) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]: """Validate one file against the partial schema; return (data, outputs). @@ -421,8 +435,15 @@ def _read(path: Path) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]: document = read_document(path) outputs = document.pop("outputs", None) document.pop("ymf", None) - spec_text = _dump(document, allow_unicode=True, sort_keys=False, - default_flow_style=False, width=1000) + # The specification part as written, every scalar a string: strictyaml + # types what the schema types, and a free-form (Any) value stays the text + # it was in the spec. Re-dumping pyyaml's typed values instead gave + # "1.0e6" back as "1000000.0", another input digest (C5 finding Y1). + spec_part = _as_written(text) + spec_part.pop("ymf", None) + spec_part.pop("outputs", None) + spec_text = _dump(spec_part, allow_unicode=True, sort_keys=False, + default_flow_style=False, width=1000) data = strictyaml.dirty_load(spec_text, PARTIAL_YMF_SCHEMA, label=str(path), allow_flow_style=_ALLOW_FLOW_STYLE).data if "composition" in document: diff --git a/tests/test_archive_spec_as_written.py b/tests/test_archive_spec_as_written.py new file mode 100644 index 0000000..52f7cdd --- /dev/null +++ b/tests/test_archive_spec_as_written.py @@ -0,0 +1,62 @@ +"""An archive's specification part reads back as written (C5 finding Y1). + +The archive is read with pyyaml, which typed a free-form value: ``1.0e6`` +under a ``proteus:`` hint came back as the float 1e6, was written again as +``1000000.0``, and strictyaml read that string -- another input than the +spec's ``'1.0e6'``, so the archive's outputs no longer matched their key and +``--check`` found nothing to check.""" + +from pathlib import Path + +import pytest + +pytest.importorskip("strictyaml") +pytest.importorskip("yaml") + +from ymf import closure # noqa: E402 + +TWO_PHASE = Path(__file__).parent / "fixtures" / "two_phase" + +HINTS = "proteus: {model: RANS2P, useVF: 1.0, eb_penalty_constant: 1.0e6, tol: 1e-3, " \ + "on: true, mask: '0x10', n: 007}" + + +def _write(tmp_path): + for name in ("two_phase_level_set.ymf", "dambreak.ymf"): + text = (TWO_PHASE / name).read_text(encoding="utf-8") + text = text.replace("proteus: {model: RANS2P, useVF: 1.0}", HINTS) + (tmp_path / name).write_text(text, encoding="utf-8") + return tmp_path / "dambreak.ymf" + + +def _hints(spec): + entry = spec["solution_paths"]["discretizations"][0] + return entry["subproblems"][0]["proteus"] + + +def test_free_form_values_and_the_key_survive_the_archive(tmp_path): + spec, _, _ = closure.load(_write(tmp_path)) + realization = {"h": 0.0322} + before = closure.input_digest(spec, "level_set_five", realization) + assert _hints(spec)["eb_penalty_constant"] == "1.0e6" + archive = tmp_path / "dambreak.archive.ymf" + closure.write(archive, spec, {}) + again, _, _ = closure.load(archive) + assert _hints(again) == _hints(spec) + assert closure.input_digest(again, "level_set_five", realization) == before + # and once more: an archive of the archive is the same input + closure.write(archive, again, {}) + third, _, _ = closure.load(archive) + assert closure.input_digest(third, "level_set_five", realization) == before + + +def test_typed_values_keep_their_types(tmp_path): + spec, _, _ = closure.load(_write(tmp_path)) + archive = tmp_path / "dambreak.archive.ymf" + closure.write(archive, spec, {}) + again, _, _ = closure.load(archive) + coefficients = again["model"]["strong_form"]["coefficients"] + assert coefficients["νw"]["value"] == 1.004e-6 + entry = again["solution_paths"]["discretizations"][0] + assert entry["mesh"]["h"] == 0.0322 and entry["step_control"]["step_exact"] is True + assert entry["subproblems"][0]["solver"]["max_iterations"] == 100 From 285a69d851c31baa7aa416805e18de175ba546bc Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:28 +0100 Subject: [PATCH 6/8] notation: a power of a sum keeps its decimals as written (Y2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C5 finding Y2: dam3bumps' bed `3 − 3 sqrt((x − 47.5)² + (y − 15)²)/10` came out as `3 − 14.25 sqrt((0.0210526 x − 1)² + 0.000443 (y − 15)²)`. Cause: sympy 1.13's Add._eval_power factors the largest coefficient out of a power of a sum with any Float coefficient ((2.0 + 4x)**e -> 4**e (0.5 + x)**e), so even (x − 47.5)² becomes 2256.25 (0.0210526 x − 1)². sympy 1.14 dropped it; proteus pins 1.13.2, so ymf cannot require 1.14. The notation builds such a power unevaluated (sqrt, ², ^, norm), a no-op on 1.14. Derivatives sympy takes later are its own; the guide says so (write 95/2 if those must match bitwise too). Measured: Z of dam3bumps prints numpy.sqrt((x - 47.5)**2 + (y - 15)**2) on sympy 1.13.2 and 1.14.0 (before: 14.25*sqrt(...) on 1.13.2). Main's 17 examples and fixtures: same ADR and split plain data on both. New test fails 4 of 6 on main's notation under 1.13.2, passes 6 of 6 here. ymf suite 951 -> 957 passed, 2 skipped (petsc-dev); 886 passed, 13 skipped under proteus-bc-261025 (sympy 1.13.2, final branch). Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 12 ++++++++++++ src/ymf/symbolic/notation.py | 31 ++++++++++++++++++++++++++---- tests/test_decimals_as_written.py | 32 +++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 tests/test_decimals_as_written.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 5212c8c..3fc21c2 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -374,6 +374,18 @@ solution_paths: | `y = 0 or x = 0 and y = H` | a boundary region; `∂Ω` is the whole boundary | | `Ω = [a, b] × [c, d], t ∈ (t0, t1]` | the domain, a box, and the time interval of a transient problem | +**Decimals are kept as written.** A numeral is an IEEE double, and a +formula that must match code computing the same thing should compute it the +same way. sympy before 1.14 rewrites a power of a sum with a decimal in it +by factoring out the largest coefficient (`(x − 47.5)²` as +`2256.25 (0.0210526 x − 1)²`, `sqrt` of a sum of such squares as `47.5 +sqrt(...)`): the same number, other arithmetic. The notation builds such a +power as written, so `sqrt((x − 47.5)² + (y − 15)²)` prints as itself +whichever sympy runs (Proteus pins 1.13). What sympy derives from it later, +a derivative in an ADR form for example, it evaluates itself, so on sympy +1.13 a derivative of such a power may still be factored; a spec that needs +those bitwise as well writes the decimal as a ratio (`95/2`). + Names are the coordinates `x y z`, time `t`, `π`, the unknowns and the coefficients. A coefficient may be any name, Greek or not (`κ`, `ρ`, `μ`, `G`), and a coefficient's value may itself be a formula in the others and diff --git a/src/ymf/symbolic/notation.py b/src/ymf/symbolic/notation.py index 69c3cf3..94456c0 100644 --- a/src/ymf/symbolic/notation.py +++ b/src/ymf/symbolic/notation.py @@ -59,9 +59,32 @@ #: words that join predicates; never names, never implicit factors _KEYWORDS = {"and", "or", "in"} +def _pow(base, exponent): + """``base ** exponent``, keeping the decimals of a sum as written. + + sympy before 1.14 rewrites a power of a sum whose terms have a decimal + coefficient by factoring out the largest one: ``(x − 47.5)²`` becomes + ``2256.25 (0.0210526 x − 1)²``, and ``sqrt`` of a sum of such squares + ``47.5 sqrt(...)``. The same number, other arithmetic, so a formula could + not match code that computes it as written (C5 finding Y2; proteus pins + sympy 1.13). Such a power is built unevaluated; sympy 1.14 leaves it as + written anyway, so this changes nothing there. What sympy derives from + it later (a derivative, a substitution) it evaluates itself. + """ + exponent = sympy.sympify(exponent) + if (isinstance(base, sympy.Add) and exponent.is_Number and exponent not in (0, 1, -1) + and any(c.is_Float for c, _ in (a.as_coeff_Mul() for a in base.args))): + return sympy.Pow(base, exponent, evaluate=False) + return base ** exponent + + +def _sqrt(a): + return _pow(a, sympy.S.Half) if isinstance(a, sympy.Add) else sympy.sqrt(a) + + _FUNCTIONS = { "sin": sympy.sin, "cos": sympy.cos, "tan": sympy.tan, "exp": sympy.exp, - "log": sympy.log, "sqrt": sympy.sqrt, "sinh": sympy.sinh, "cosh": sympy.cosh, + "log": sympy.log, "sqrt": _sqrt, "sinh": sympy.sinh, "cosh": sympy.cosh, "tanh": sympy.tanh, "abs": sympy.Abs, # sqrt(a² + b²) rounded once (C99 hypot), so that a formula can match code # that computes a distance with it bit for bit @@ -79,7 +102,7 @@ def _norm(v): if isinstance(v, sympy.MatrixBase): if v.shape[1] != 1: raise ValueError("norm needs a vector, got a %dx%d tensor" % v.shape) - return sympy.sqrt(sum(e ** 2 for e in v)) + return _sqrt(sum(_pow(e, 2) for e in v)) return sympy.Abs(v) @@ -208,9 +231,9 @@ def _power(self): while True: tok = self._peek() if tok[1] in _SUPERSCRIPTS: - self._take(); base = base ** _SUPERSCRIPTS[tok[1]] + self._take(); base = _pow(base, _SUPERSCRIPTS[tok[1]]) elif tok[1] in ("^", "**"): - self._take(); base = base ** self._unary() + self._take(); base = _pow(base, self._unary()) else: return base diff --git a/tests/test_decimals_as_written.py b/tests/test_decimals_as_written.py new file mode 100644 index 0000000..d13e988 --- /dev/null +++ b/tests/test_decimals_as_written.py @@ -0,0 +1,32 @@ +"""Decimals under a power are kept as written (C5 finding Y2): sympy before +1.14 factors the largest coefficient out of a power of a sum with a decimal +in it ((x − 47.5)² -> 2256.25 (0.0210526 x − 1)²), which is the same number +by other arithmetic. dam3Bumps' bed is the case that showed it.""" + +import pytest + +pytest.importorskip("sympy") + +from ymf.symbolic.adr import to_code # noqa: E402 +from ymf.symbolic.language import Space, parse_expression # noqa: E402 + + +def _code(text): + return to_code(parse_expression(text, Space(2, {}, {}))) + + +@pytest.mark.parametrize("text, code", [ + ("(x − 47.5)²", "(x - 47.5)**2"), + ("sqrt((x − 47.5)² + (y − 15)²)", "numpy.sqrt((x - 47.5)**2 + (y - 15)**2)"), + ("3 − 3 sqrt((x − 47.5)² + (y − 15)²)/10", "3 - 3/10*numpy.sqrt((x - 47.5)**2 + (y - 15)**2)"), + ("(2.5 x + 1)^(1/3)", "(2.5*x + 1)**(1/3)"), + ("norm((x − 0.5, y))", "numpy.sqrt(y**2 + (x - 0.5)**2)"), +]) +def test_a_power_of_a_sum_keeps_its_decimals(text, code): + assert _code(text) == code + + +def test_integers_and_rationals_evaluate_as_before(): + assert _code("(x + 1)²") == "(x + 1)**2" + assert _code("(x + 1)^0") == "1" + assert _code("sqrt(4)") == "2" From 97edb3d6297297617c7cbd5ea95d6cdf06367adb Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:29 +0100 Subject: [PATCH 7/8] compose: extends pairs initial conditions by field (Y3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C5 finding Y3: an extending file's initial_conditions replaced the parent's list whole, so dambreak_short.ymf restated all three to change φ. initial_conditions now pair up by `field`: an entry for a field the parent has replaces that entry whole (its type and value go together, so a constant's value does not survive into a function), recorded as an override; others are inherited in the parent's order; new ones are appended; `remove: model.strong_form.initial_conditions[p]` works. Measured: restating φ and p over dambreak.ymf gives [v, p, φ] with v inherited (before: [φ, p]). Main's 17 examples and fixtures: same keys. ymf suite 957 -> 959 passed, 2 skipped. proteus's dambreak_short.ymf, which restates all three, composes as before. Co-Authored-By: Claude Opus 5.5 --- docs/problem-specification.md | 6 ++- src/ymf/compose.py | 17 +++++++- tests/test_extends_initial_conditions.py | 55 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 tests/test_extends_initial_conditions.py diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 3fc21c2..1e2c30a 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -1034,7 +1034,11 @@ solution_paths: {...} **Merge rules.** Mappings merge key by key. Lists of entries with a `label` or `name` (unknowns, weak forms, discretizations, boundary regions) -merge entry by entry on it, and new entries are appended. Lists of strings +merge entry by entry on it, and new entries are appended. Initial +conditions pair up by `field`: an extending file that states the initial +condition of one field replaces that entry whole (its type and value go +together) and leaves the others as inherited, and `remove:` can name one +(`model.strong_form.initial_conditions[φ]`). Lists of strings (`processes`, `assumptions`) are unioned. Anything else the child sets replaces the parent's value. Every file in a chain is checked against the partial schema as it is read, so an error is reported against the file and diff --git a/src/ymf/compose.py b/src/ymf/compose.py index c970db2..2c16375 100644 --- a/src/ymf/compose.py +++ b/src/ymf/compose.py @@ -88,7 +88,13 @@ def _refuse_old_kind(text: str, path: Path) -> None: "'ymf_state: abstract' for 'kind: model', and drop 'kind: problem' " "(or write 'ymf_state: well-posed'). See ymf.state." % (path,)) #: Keys that identify an entry in a list of mappings, in order of preference. -_IDENTITY_KEYS = ("label", "name") +_IDENTITY_KEYS = ("label", "name", "field") + +#: identity keys whose entries an extending file replaces whole rather than +#: merges key by key: an initial condition is one statement, and merging +#: {type: function, formula} onto {type: constant, value} would keep a value +#: that no longer means anything +_REPLACED_WHOLE = ("field",) class YmfCompositionError(ValueError): @@ -257,7 +263,14 @@ def _merge(parent: Any, child: Any, path: str, source: str, key = _identity(entry)[1] where = "%s[%s]" % (path, key) _note_writer(provenance, where, source) - if key in index: + if key in index and _identity(entry)[0] in _REPLACED_WHOLE: + i = index[key] + if parent[i] != entry: + overrides.append({"path": where, "was": parent[i], "now": entry, + "set_by": source}) + merged[i] = entry + _record_paths(entry, where, source, provenance) + elif key in index: i = index[key] merged[i] = _merge(parent[i], entry, where, source, overrides, provenance) diff --git a/tests/test_extends_initial_conditions.py b/tests/test_extends_initial_conditions.py new file mode 100644 index 0000000..2823c41 --- /dev/null +++ b/tests/test_extends_initial_conditions.py @@ -0,0 +1,55 @@ +"""``extends`` pairs initial conditions by field (C5 finding Y3): a file +that restates one field's initial condition replaces that one, and inherits +the rest.""" + +from pathlib import Path + +import pytest + +pytest.importorskip("strictyaml") + +from ymf.schema import load_ymf # noqa: E402 + +TWO_PHASE = Path(__file__).parent / "fixtures" / "two_phase" + + +def _ics(doc): + return {ic["field"]: ic for ic in doc["model"]["strong_form"]["initial_conditions"]} + + +def test_one_field_restated_the_others_inherited(tmp_path): + for name in ("two_phase_level_set.ymf", "dambreak.ymf"): + (tmp_path / name).write_text((TWO_PHASE / name).read_text(encoding="utf-8"), + encoding="utf-8") + (tmp_path / "column.ymf").write_text( + "extends: dambreak.ymf\n" + "model:\n" + " strong_form:\n" + " initial_conditions:\n" + " - {field: φ, type: function, formula: \"y − 0.6\", units: m}\n" + " - {field: p, type: function, formula: \"998.2*9.8*(0.6 − y)\"}\n", + encoding="utf-8") + doc = load_ymf(tmp_path / "column.ymf") + ics = _ics(doc) + assert list(ics) == ["v", "p", "φ"] # the parent's order + assert ics["v"] == {"field": "v", "type": "constant", "value": 0.0} + # replaced whole: a constant's value does not survive into a function + assert ics["p"] == {"field": "p", "type": "function", "formula": "998.2*9.8*(0.6 − y)"} + assert ics["φ"]["formula"] == "y − 0.6" + overrides = doc["composition"]["overrides"] + assert {o["path"] for o in overrides} >= {"model.strong_form.initial_conditions[φ]", + "model.strong_form.initial_conditions[p]"} + + +def test_a_new_field_is_appended_and_one_can_be_removed(tmp_path): + for name in ("two_phase_level_set.ymf", "dambreak.ymf"): + (tmp_path / name).write_text((TWO_PHASE / name).read_text(encoding="utf-8"), + encoding="utf-8") + (tmp_path / "drop.ymf").write_text( + "extends: dambreak.ymf\n" + "ymf_state: abstract\n" + "remove:\n" + " - \"model.strong_form.initial_conditions[p]\"\n", + encoding="utf-8") + doc = load_ymf(tmp_path / "drop.ymf") + assert list(_ics(doc)) == ["v", "φ"] From 201cea4656e52407c3f83ec8c1dbeab1a4c57e94 Mon Sep 17 00:00:00 2001 From: cekees <613654+cekees@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:27:54 +0100 Subject: [PATCH 8/8] changes: C42 round 3 The round's entry in docs/changes.md: the vocabulary, coefficient roles, linear_solver direct/iterative, the uncarried phase indicator, and Y1-Y3. Co-Authored-By: Claude Opus 5.5 --- docs/changes.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/changes.md b/docs/changes.md index e214ef8..cc21f45 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -7,6 +7,25 @@ rediscover why a thing is the way it is. Open gaps are in ## 2026-11 +- **2026-11-08: C42 round 3, the words a dispatcher maps (C5 decisions + 16, 18-21 of 2026-11-06).** proteus's DispatchTable coined the labels it + matched on; they are `ymf.vocabulary` now, stated by the spec, checked on + load, and the derived ones (a model's `family`, each sub-problem's + `role`) written by closure without counting towards a key. Renamed where + ymf had a better word, the old one kept as an alias: `vbdf` -> `bdf2`, + `SSP_RK3` -> `ssp_rk3`, `shock_capturing` -> `residual_shock_capturing`, + `pressure_initial` -> `pressure_spin_up`, `entropy_viscosity_cE` -> + `entropy_viscosity_coefficient`. Coefficients carry a `role` (`density`, + `gravity`, `bed_elevation`, ...), so a solver stops looking them up by + name. `linear_solver: direct | iterative`, shared by every solver path. A + condition on a phase indicator no sub-problem carries (χ with no VOF) is a + condition on its level set's sign, so CLSVOF gets the atmosphere's air + inflow. Three fixes: an archive's spec part reads back as written (`1.0e6` + had come back `'1000000.0'`, another input digest: `--check` broke); a + power of a sum keeps its decimals on sympy 1.13 (`(x − 47.5)²` had become + `2256.25 (0.0210526 x − 1)²`); `extends` pairs `initial_conditions` by + `field`. + - **2026-11-06: `hypot(a, b)` in the notation.** C5 step 2 (proteus runs a split discretization from the spec and compares it bitwise with the deck): the dam break's initial signed distance written `sqrt(max(x − 1.2, 0)² +