diff --git a/docs/changes.md b/docs/changes.md index eefa6c8..f168403 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -7,6 +7,19 @@ rediscover why a thing is the way it is. Open gaps are in ## 2026-11 +- **2026-11-04: aliases expand into the abstract forms, and closure records + the expansion.** cekees's review note: `slip`, `open`, `inflow`, + `characteristic` and condition sets had their meaning only in code + (`split.py`, `units.py`, a solver's dispatch), so a closed spec saying + `type: slip` did not say what was solved. `ymf.conditions.ALIASES` now + defines each alias as Dirichlet/Neumann/Robin components on a variable or + its `normal`/`tangential` part, `only` where the flow or the + characteristics enter where it applies; `expand` writes them out, with + `expanded_from`, removing `condition_sets` and `boundary_sets`. + `closure.write` writes the expansion and `closure.input_slice` keys by it + (a spec without aliases keeps its keys); `adr_problem`, `split_problem` + and `ymf.units` read only the expansion. New condition keys: `component`, + `only`, `imposed` (strong or weak, per condition, C12), `expanded_from`. - **2026-11-04: `discrete` domains are posed (D4).** A mesh as ymf stores one (`topology`, `geometry`, and the tagged `facets` and `provenance` of cekees/ymf#6) is a domain: `adr_problem` poses it whole, with bounds from diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 7899ff6..aeed823 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -138,21 +138,49 @@ that is a Dirichlet condition, and belongs where it can be imposed strongly. `periodic` conditions need a box, or a region whose two faces are translations of each other (see [The domain](#the-domain)). -Four more kinds are for a [split discretization](#splitting-a-discretization-into-sub-problems)'s -solver; one ADR system (`adr_problem`) runs none of them and says so: +**Aliases, and what is solved.** Dirichlet, Neumann and Robin (and +periodic pairing) are the abstract forms; each is complete with its +expression. Four more kinds are **aliases**, shorthand for particular +combinations of them, defined as data in `ymf.conditions.ALIASES`: -| type | means | value | +| alias | expands to | value | |---|---|---| -| `slip` | on a vector: its normal component is the value (0 if none is given), its tangential traction zero -- a free-slip wall | optional | -| `open` | a declared open boundary: the natural flux applies, nothing is imposed | none | -| `inflow` | the value, imposed only where the flow enters -- the phase that comes in through an open top | required | -| `characteristic` | a state imposed through the incoming characteristics only -- a tailwater stage that a supercritical outflow ignores | required | +| `slip` (a vector) | `dirichlet` on the `normal` component, the value (0 if none is given); `neumann` on the `tangential` component, 0 (no tangential traction) | optional | +| `open` | `neumann` 0: the natural condition, declared (C12's open boundary) | none | +| `inflow` | `dirichlet`, the value, `only: inflow` (where the flow enters) | required | +| `characteristic` | `dirichlet`, the value, `only: incoming_characteristics` (a tailwater stage that a supercritical outflow ignores) | required | + +A spec may write the aliases. **What is solved, and what the closure of +the spec records, is the expansion**: `ymf.conditions.expand` replaces +every alias, and every applied condition set, with its abstract +conditions, each marked with what it came from: + +```yaml +# boundary_sets: [{region: walls, set: free_slip}] closes as +boundary_conditions: + - {region: walls, variable: v, type: dirichlet, component: normal, value: 0.0, + expanded_from: {type: slip, set: free_slip}} + - {region: walls, variable: v, type: neumann, component: tangential, value: 0.0, + expanded_from: {type: slip, set: free_slip}} +``` + +The archive of a spec holds the expansion, its output keys are computed +from it (so a spec and its archive key alike, and a spec without aliases +keeps its keys), and `adr_problem`, `split_problem` and `ymf.units` read +only it. Otherwise two solvers could close the same spec differently and +the archive could not show which. An expanded condition may say how it is +`imposed`, `strong` or `weak`: C12 makes that a property of each +condition. One ADR system (`adr_problem`) runs Dirichlet, Neumann and +Robin on whole variables; a condition on a component, restricted with +`only`, or imposed weakly is for a split discretization's solver, and +`adr_problem` says so. A condition may also name a coefficient of the state rather than an unknown: `{variable: χ, type: inflow, value: 1.0}` says the fluid entering is air, whatever carries `χ` in a given discretization. Checked on load: -the region exists, the variable is an unknown or a coefficient, `slip` is -on a vector, and a kind gets a value exactly when it takes one. +the region exists, the variable is an unknown or a coefficient, `slip` and +a `component` are on a vector, and a kind gets a value exactly when it +takes one. **Condition sets.** What a free-slip wall or an open top means is part of the model: written once there, over its own unknowns and coefficients, and @@ -179,7 +207,8 @@ condition written out under `boundary_conditions` for the same region and variable replaces the set's member, so a case can apply `atmosphere` and give the pressure its own value; two sets that both decide one region's variable are an error, as is a set nobody defines. A set's members are -checked where they are defined, as any condition is. +checked where they are defined, as any condition is. Like an alias, a set is +input shorthand: the closure writes its members out (above). A value is given as a number (`value`), an expression (`formula`), or a table, `series: [[t, value], ...]` with `t` ascending: a measured or design diff --git a/src/ymf/closure.py b/src/ymf/closure.py index dfb14ab..972af06 100644 --- a/src/ymf/closure.py +++ b/src/ymf/closure.py @@ -161,7 +161,15 @@ def used_weak_form(doc: Dict[str, Any], discretization: Dict[str, Any] def input_slice(doc: Dict[str, Any], discretization: str, realization: Dict[str, Any]) -> Dict[str, Any]: - """The part of the input one output depends on (see the module docstring).""" + """The part of the input one output depends on (see the module docstring). + + Taken from the document with its boundary-condition aliases and condition + sets expanded (ymf.conditions): what is solved is the expansion, so a + spec and the archive it closes into, which holds the expansion, key + their outputs alike; a spec with no shorthand is unchanged by it. + """ + from ymf.conditions import expand + doc = expand(doc) paths = doc.get("solution_paths") or {} entry = _discretization(doc, discretization) return plain({ @@ -312,9 +320,13 @@ def archive_stem(path: str | Path) -> str: def write(path: str | Path, spec: Dict[str, Any], outputs: Dict[str, Any]) -> None: """Write an archive: ``ymf:``, its ``ymf_state``, the realized spec, then ``outputs``. The state is the one the archive reaches (see ymf.state), - whatever its input declared.""" + whatever its input declared. The realized spec has its boundary-condition + aliases and condition sets expanded (ymf.conditions).""" + from ymf.conditions import expand from ymf.state import reached - document = dict(plain(spec)) + # the closure records what was solved: the conditions expanded, each + # with the alias and the set it came from (ymf.conditions) + document = dict(plain(expand(spec))) document.pop("outputs", None) document.pop("ymf_state", None) document.pop("generated", None) # it describes the input file, not this one diff --git a/src/ymf/conditions.py b/src/ymf/conditions.py new file mode 100644 index 0000000..9393856 --- /dev/null +++ b/src/ymf/conditions.py @@ -0,0 +1,189 @@ +"""Boundary-condition aliases, and their expansion into the abstract forms. + +Dirichlet, Neumann and Robin conditions (and periodic pairing) are the +abstract forms; each is complete with its expression. The other kinds a spec +may write -- ``slip``, ``open``, ``inflow``, ``characteristic`` -- and the +named condition sets of a model (``free_slip``, ``atmosphere``) are +shorthand for particular combinations of them. A spec may use the shorthand; +what is solved, and what a closed spec and its archive record, is the +expansion (cekees, 2026-11-04): otherwise two solvers could close the same +spec differently and the archive could not show which, and the run would not +be reproducible from its record. + +An expanded condition is one of the abstract forms, on + +* the whole variable, or a ``component`` of a vector: its ``normal`` or + ``tangential`` part on the boundary; +* the whole region, or ``only`` the part of it where the flow enters + (``inflow``) or where characteristics enter (``incoming_characteristics``); + +with its value (``value``, ``formula`` or ``series``), optionally how it is +``imposed`` (``strong`` or ``weak``: C12 makes that a property of each +condition), and ``expanded_from``, the alias and the condition set it came +from. + +:data:`ALIASES` is the definition, as data. :func:`expand` applies it to a +document; it is idempotent, and a document with no alias and no condition set +comes back unchanged, so the outputs it keys keep their keys. + +This module is stdlib only, like the rest of the spec core. +""" + +from __future__ import annotations + +import copy +from typing import Any, Dict, List, Tuple + +__all__ = ["ALIASES", "ABSTRACT", "expand", "expand_condition", "has_shorthand", "describe"] + +#: the abstract forms: what an expansion is made of +ABSTRACT = ("dirichlet", "neumann", "robin", "periodic") + +#: the keys that carry a condition's value +_VALUE_KEYS = ("value", "formula", "series", "units") + +#: the order an expanded condition's keys are written in +_ORDER = ("region", "variable", "type", "component", "only", "value", "formula", "series", + "alpha", "beta", "units", "imposed", "source", "source_url", "temporal", + "expanded_from") + + +def _ordered(entry: Dict[str, Any]) -> Dict[str, Any]: + head = {k: entry[k] for k in _ORDER if k in entry} + head.update({k: v for k, v in entry.items() if k not in head}) + return head + +#: alias -> what it means. Each component is an abstract condition; ``takes`` +#: says it receives the alias's value (value, formula or series), and +#: ``default`` what it is when the alias gives none. ``needs`` restricts the +#: alias to a vector variable (a normal and a tangential part). +ALIASES: Dict[str, Dict[str, Any]] = { + # a free-slip wall: no flow through it, no tangential traction on it + "slip": { + "needs": "vector", + "means": "the normal component is the value (0 if none is given) and the " + "tangential traction (the diffusive flux of the tangential part) is zero", + "components": [ + {"type": "dirichlet", "component": "normal", "takes": True, "default": 0.0}, + {"type": "neumann", "component": "tangential", "value": 0.0}, + ], + }, + # a declared open boundary (C12): the natural condition, stated + "open": { + "means": "zero diffusive flux, the natural condition, declared: the advective " + "flux leaves with the solution's own trace", + "components": [ + {"type": "neumann", "value": 0.0}, + ], + }, + # a value imposed where the flow comes in, nothing where it leaves + "inflow": { + "means": "the value, imposed only where the flow enters", + "components": [ + {"type": "dirichlet", "only": "inflow", "takes": True}, + ], + }, + # a state imposed through the characteristics that enter (a tailwater) + "characteristic": { + "means": "the value, imposed only through the incoming characteristics (so a " + "supercritical outflow ignores it)", + "components": [ + {"type": "dirichlet", "only": "incoming_characteristics", "takes": True}, + ], + }, +} + + +def expand_condition(bc: Dict[str, Any], rank: int = 0) -> List[Dict[str, Any]]: + """One condition as the abstract conditions it means. + + An abstract condition comes back as itself; an alias as its components, + each with the condition's region and variable, its value where the + component takes one, and ``expanded_from: {type: }`` (and the set, + when the condition came from one). ``rank`` is the variable's (1 for a + vector), which an alias such as ``slip`` needs. + """ + kind = bc.get("type") + origin = {} + if bc.get("set") is not None: + origin["set"] = bc["set"] + if kind in ABSTRACT or kind not in ALIASES: + out = {k: v for k, v in bc.items() if k != "set"} + if origin: + out["expanded_from"] = dict(out.get("expanded_from") or {}, **origin) + return [out] + alias = ALIASES[kind] + if alias.get("needs") == "vector" and rank != 1: + raise ValueError("a %s condition is on a vector, and %s is not one" + % (kind, bc.get("variable"))) + given = {k: bc[k] for k in _VALUE_KEYS if bc.get(k) is not None} + shared = {k: v for k, v in bc.items() + if k not in _VALUE_KEYS and k not in ("type", "set", "expanded_from")} + out = [] + for part in alias["components"]: + entry = dict(shared) + entry.update({k: v for k, v in part.items() if k not in ("takes", "default")}) + if part.get("takes"): + if given: + entry.update(given) + elif "default" in part: + entry["value"] = part["default"] + entry["expanded_from"] = dict({"type": kind}, **origin) + out.append(entry) + return out + + +def has_shorthand(strong_form: Dict[str, Any]) -> bool: + """Whether a strong form uses an alias or a condition set.""" + if strong_form.get("boundary_sets") or strong_form.get("condition_sets"): + return True + return any(isinstance(bc, dict) and bc.get("type") in ALIASES + for bc in strong_form.get("boundary_conditions") or []) + + +def expand(doc: Dict[str, Any]) -> Dict[str, Any]: + """``doc`` with every alias and condition set expanded (see the module). + + The strong form's ``boundary_conditions`` become the abstract conditions, + in order (written ones first, then the applied sets', each alias replaced + by its components), and ``condition_sets`` and ``boundary_sets`` go, their + meaning now written out and their names kept in ``expanded_from``. A + document without either comes back as the same object, unchanged. + Raises ``ValueError`` for what does not expand (an undefined set, two sets + deciding one region's variable, a vector alias on a scalar). + """ + model = doc.get("model") if isinstance(doc, dict) else None + strong = (model or {}).get("strong_form") if isinstance(model, dict) else None + if not isinstance(strong, dict) or not has_shorthand(strong): + return doc + from ymf.normalize import boundary_conditions, normalize_unknowns + ranks: Dict[str, int] = {} + for u in strong.get("unknowns") or []: + if isinstance(u, dict): + ranks[u["name"]] = int(u.get("rank") or 0) + for u in normalize_unknowns(strong.get("unknowns") or []): + ranks.setdefault(u["name"], 0) + expanded: List[Dict[str, Any]] = [] + for bc in boundary_conditions(strong): + expanded.extend(_ordered(e) for e in + expand_condition(bc, ranks.get(bc.get("variable"), 0))) + out = copy.copy(doc) + out["model"] = dict(model) + new_strong = {k: v for k, v in strong.items() + if k not in ("condition_sets", "boundary_sets", "boundary_conditions")} + # keep the strong form's key order: the conditions where they were + ordered: Dict[str, Any] = {} + for k in strong: + if k == "boundary_conditions" or (k == "boundary_sets" + and "boundary_conditions" not in strong): + ordered["boundary_conditions"] = expanded + elif k in new_strong: + ordered[k] = new_strong[k] + ordered.setdefault("boundary_conditions", expanded) + out["model"]["strong_form"] = ordered + return out + + +def describe() -> List[Tuple[str, str, List[Dict[str, Any]]]]: + """``(alias, what it means, its components)`` for the documentation.""" + return [(name, a["means"], copy.deepcopy(a["components"])) for name, a in ALIASES.items()] diff --git a/src/ymf/references.py b/src/ymf/references.py index 3a37f9f..8d6adfc 100644 --- a/src/ymf/references.py +++ b/src/ymf/references.py @@ -303,6 +303,9 @@ def _check_conditions(doc: Dict[str, Any]) -> None: raise YmfReferenceError("%s: %s is neither an unknown nor a coefficient" % (where, variable)) given = any(bc.get(k) is not None for k in ("value", "formula", "series")) + if bc.get("component") and variable in unknowns and unknowns[variable] != 1: + raise YmfReferenceError("%s: a %s component is a vector's, and %s is a scalar" + % (where, bc["component"], variable)) if kind == "slip" and variable in unknowns and unknowns[variable] != 1: raise YmfReferenceError("%s: slip gives the normal component of a vector, and " "%s is a scalar" % (where, variable)) diff --git a/src/ymf/schema.py b/src/ymf/schema.py index 5c7e0bb..77e435a 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -321,6 +321,13 @@ _CONDITION_FIELDS = { "variable": Str(), "type": BCTypeEnum, + # Where an alias expands (ymf.conditions): which part of a vector the + # condition is on, which part of the region it holds on, how it is + # imposed (C12: a property of each condition), and what it expanded from. + Optional("component"): Enum(["normal", "tangential"]), + Optional("only"): Enum(["inflow", "incoming_characteristics"]), + Optional("imposed"): Enum(["strong", "weak"]), + Optional("expanded_from"): Map({Optional("type"): Str(), Optional("set"): Str()}), Optional("value"): Float(), # A value that varies along the boundary or in time: an expression # in x, y, z, t and the coefficients; "(a, b)" for a vector variable. diff --git a/src/ymf/symbolic/problem.py b/src/ymf/symbolic/problem.py index 64675dd..1f32fae 100644 --- a/src/ymf/symbolic/problem.py +++ b/src/ymf/symbolic/problem.py @@ -549,8 +549,13 @@ def adr_problem(doc: Dict[str, Any], hamiltonian_gradients=()) -> Dict[str, Any] ``hamiltonian_gradients``: see :func:`ymf.symbolic.adr.classify`. """ + from ymf.conditions import expand from ymf.symbolic.notation import NotationError, Parser + try: + doc = expand(doc) # aliases and condition sets: only their expansion is solved + except ValueError as exc: + raise SymbolicError(str(exc)) from exc strong, box, region, ranks, coefficients, space, residuals = _posed(doc) domain = strong["domain"] dim = space.dim @@ -587,6 +592,17 @@ def adr_problem(doc: Dict[str, Any], hamiltonian_gradients=()) -> Dict[str, Any] "boundary condition that runs in one ADR system (%s " "conditions are for a split discretization's solver)" % (bc["region"], bc["type"], bc["type"])) + restricted = [k for k in ("component", "only") if bc.get(k) is not None] + if restricted or bc.get("imposed") == "weak": + what = ("on the %s component" % bc["component"] if bc.get("component") else + "only on %s" % bc["only"].replace("_", " ") if bc.get("only") else + "imposed weakly") + raise SymbolicError( + "boundary condition on %s: a %s condition %s%s runs in a split " + "discretization's solver, not in one ADR system" + % (bc["region"], bc["type"], what, + " (expanded from %s)" % bc["expanded_from"]["type"] + if (bc.get("expanded_from") or {}).get("type") else "")) name = bc["variable"] if name not in ranks: raise SymbolicError("boundary condition on %s: %s is not an unknown%s" diff --git a/src/ymf/symbolic/split.py b/src/ymf/symbolic/split.py index 1a04a09..417e2b5 100644 --- a/src/ymf/symbolic/split.py +++ b/src/ymf/symbolic/split.py @@ -76,6 +76,11 @@ def split_problem(doc: Dict[str, Any], discretization: str) -> Dict[str, Any]: the run up, or enforces a constraint it gives no equation for) has ``"classified": False`` and the reason instead of ``adr``. """ + from ymf.conditions import expand + try: + doc = expand(doc) # aliases and condition sets: only their expansion is solved + except ValueError as exc: + raise SymbolicError(str(exc)) from exc from ymf.discretizations import subproblem_solver from ymf.normalize import normalize_equations from ymf.symbolic.problem import _coefficients, _frame, _state_coefficient_data @@ -281,8 +286,9 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where) -> List[D **_selector(regions[bc["region"]], strong["domain"], space)} if target != variable: entry["carried_by"] = target - if bc.get("set"): - entry["set"] = bc["set"] + for key in ("component", "only", "imposed", "expanded_from"): + if bc.get(key) is not None: + entry[key] = bc[key] entry["components"] = ([target] if rank == 0 else ["%s_%d" % (target, i) for i in range(dim)]) kind = bc["type"] @@ -302,18 +308,16 @@ def _conditions(strong, own, carried, space, dim, lower, upper, where) -> List[D entry.update(alpha=_robin_part(bc, "alpha", space), beta=_robin_part(bc, "beta", space), g=_robin_rhs(bc, space)) elif bc.get("series") is not None: - entry["series"] = _series(bc, target, 0 if kind == "slip" else rank) + entry["series"] = _series(bc, target, 0 if bc.get("component") else rank) elif bc.get("formula") is not None or bc.get("value") is not None: value = (parse_expression(bc["formula"], space) if bc.get("formula") is not None else _number(bc["value"])) - if kind == "slip" or rank == 0: + if bc.get("component") or rank == 0: # a projection is one number entry["value"] = to_code(_given(value, space, here)) else: if not isinstance(value, sympy.MatrixBase): value = sympy.Matrix([value] * dim) entry["value"] = _components(value, target, rank, space, here) - elif kind == "slip": - entry["value"] = "0.0" out.append(entry) return out diff --git a/src/ymf/units.py b/src/ymf/units.py index e5efd9b..11310ed 100644 --- a/src/ymf/units.py +++ b/src/ymf/units.py @@ -194,6 +194,11 @@ def check(doc: Dict[str, Any], missing_units: str = "skip") -> UnitCheckResult: if missing_units not in MISSING_UNITS: raise ValueError("missing_units must be one of %s, not %r" % (", ".join(MISSING_UNITS), missing_units)) + from ymf.conditions import expand + try: + doc = expand(doc) # check what is solved: the expanded conditions + except ValueError: + pass # what does not expand is reported on load result = UnitCheckResult() problem = doc.get("model") or {} strong_form = problem.get("strong_form") or {} @@ -355,10 +360,6 @@ def _check_state_coefficients_in_scales(problem, strong_form, result) -> None: f"from a constant coefficient instead")) -#: conditions whose g is a value of the variable itself, like dirichlet's -_VALUE_KINDS = ("slip", "inflow", "characteristic") - - #: What :func:`check` does with a boundary condition it cannot check for #: want of declared units: say nothing, warn, or call it an error. MISSING_UNITS = ("skip", "warn", "error") @@ -498,8 +499,9 @@ def _check_boundary_conditions(strong_form: Dict[str, Any], result: "UnitCheckRe ``units`` on a condition is the units of g, its right-hand side. - - dirichlet, u = g: ``[g] = [u]``; so too slip (the normal component - of u), inflow and characteristic. open has no g. + - dirichlet, u = g: ``[g] = [u]`` (also on a projection, u.n = g). + Conditions are checked as expanded (ymf.conditions): a slip is a + dirichlet on the normal component and a neumann on the tangential one. - neumann, q.n = g, where q = -a grad u is the diffusive flux of the variable's own equation: ``[g] = [a][u]/[L]``. - robin, alpha u + beta q.n = g: ``[alpha][u] = [beta][q.n] = [g]``. @@ -519,7 +521,7 @@ def _check_boundary_conditions(strong_form: Dict[str, Any], result: "UnitCheckRe except ValueError: return # an undefined set: reported on load bcs = [bc for bc in conditions - if bc.get("type") in ("dirichlet", "neumann", "robin") + _VALUE_KINDS] + if bc.get("type") in ("dirichlet", "neumann", "robin")] if not bcs: return dims = _Dimensions() @@ -550,8 +552,11 @@ def report(location, verdict): for bc in bcs: var, kind = bc.get("variable"), bc["type"] location = f"boundary_conditions[region={bc.get('region')!r}, variable={var!r}]" - if bc.get("set"): - location += f" (set {bc['set']})" + origin = bc.get("expanded_from") or {} + if origin: + location += " (%s)" % ", ".join("%s %s" % (k, v) for k, v in + (("expanded from", origin.get("type")), + ("set", origin.get("set"))) if v) if var not in unknown_dims: continue try: @@ -560,7 +565,7 @@ def report(location, verdict): result.issues.append(UnitIssue("error", location, str(exc))) continue u = unknown_dims[var] - if kind == "dirichlet" or kind in _VALUE_KINDS: + if kind == "dirichlet": verdict = dims.compare(g, u) if verdict and verdict[0] == "error": declared = _unknown_units(unknowns, var) diff --git a/tests/test_boundary_kinds.py b/tests/test_boundary_kinds.py index f92752f..b01d785 100644 --- a/tests/test_boundary_kinds.py +++ b/tests/test_boundary_kinds.py @@ -83,7 +83,8 @@ def test_slip_on_a_vector_needs_no_value(poiseuille): def test_one_adr_system_runs_none_of_them(heat, poiseuille): pytest.importorskip("sympy") from ymf.symbolic import SymbolicError, adr_problem - with pytest.raises(SymbolicError, match="slip conditions are for a split discretization"): + with pytest.raises(SymbolicError, match="a dirichlet condition on the normal component " + "\\(expanded from slip\\) runs in a split"): adr_problem(_with(poiseuille, {"region": "walls", "variable": "v", "type": "slip"})) with pytest.raises(SymbolicError, match="a condition on a coefficient is for a split"): adr_problem(_with(heat, {"region": "walls", "variable": "κ", "type": "dirichlet", diff --git a/tests/test_condition_expansion.py b/tests/test_condition_expansion.py new file mode 100644 index 0000000..ba8d381 --- /dev/null +++ b/tests/test_condition_expansion.py @@ -0,0 +1,187 @@ +"""Boundary-condition aliases expand into the abstract forms (cekees, 2026-11-04). + +slip, open, inflow and characteristic, and a model's condition sets, are +shorthand; what is solved, and what a closed spec records, is Dirichlet, +Neumann and Robin conditions on a variable or a projection of it, with their +values and with what they expanded from. ymf.conditions holds the meaning as +data (ALIASES) and expands a document (expand). +""" + +import copy +from pathlib import Path + +import pytest + +from ymf.conditions import ALIASES, expand, expand_condition + +FIXTURES = Path(__file__).parent / "fixtures" + + +@pytest.mark.parametrize("alias, rank, given, expected", [ + ("slip", 1, {}, [ + {"type": "dirichlet", "component": "normal", "value": 0.0}, + {"type": "neumann", "component": "tangential", "value": 0.0}]), + ("slip", 1, {"formula": "(t, 0)"}, [ + {"type": "dirichlet", "component": "normal", "formula": "(t, 0)"}, + {"type": "neumann", "component": "tangential", "value": 0.0}]), + ("open", 0, {}, [{"type": "neumann", "value": 0.0}]), + ("inflow", 0, {"value": 1.0, "units": "1"}, [ + {"type": "dirichlet", "only": "inflow", "value": 1.0, "units": "1"}]), + ("characteristic", 0, {"series": [[0.0, 0.1], [5.0, 0.2]]}, [ + {"type": "dirichlet", "only": "incoming_characteristics", + "series": [[0.0, 0.1], [5.0, 0.2]]}]), +]) +def test_each_alias_expands_to_its_documented_components(alias, rank, given, expected): + bc = dict({"region": "r", "variable": "u", "type": alias}, **given) + parts = expand_condition(bc, rank) + assert [{k: v for k, v in p.items() if k not in ("region", "variable", "expanded_from")} + for p in parts] == expected + assert all(p["region"] == "r" and p["variable"] == "u" for p in parts) + assert all(p["expanded_from"] == {"type": alias} for p in parts) + + +def test_every_alias_is_made_of_abstract_forms_only(): + for name, alias in ALIASES.items(): + assert alias["means"] + assert {c["type"] for c in alias["components"]} <= {"dirichlet", "neumann", "robin"} + + +def test_an_abstract_condition_is_itself(): + bc = {"region": "r", "variable": "u", "type": "robin", "alpha": "1", "beta": "2", + "value": 0.5} + assert expand_condition(bc) == [bc] + + +def test_slip_needs_a_vector(): + with pytest.raises(ValueError, match="a slip condition is on a vector, and h is not one"): + expand_condition({"region": "r", "variable": "h", "type": "slip"}, 0) + + +def _strong(**kw): + return {"model": {"name": "m", "strong_form": dict( + {"unknowns": [{"name": "v", "rank": 1}, "p"], "domain": "Ω = [0, 1] × [0, 1]", + "boundary_regions": [{"name": "walls", "where": "y = 0"}, + {"name": "top", "where": "y = 1"}]}, **kw)}} + + +def test_a_document_without_shorthand_comes_back_unchanged(): + doc = _strong(boundary_conditions=[{"region": "walls", "variable": "v", + "type": "dirichlet", "value": 0.0}]) + assert expand(doc) is doc + + +def test_sets_and_aliases_expand_in_order_and_the_sets_go(): + doc = _strong( + boundary_conditions=[{"region": "walls", "variable": "p", "type": "neumann", + "value": 0.0}], + condition_sets={"atmosphere": [{"variable": "p", "type": "dirichlet", "value": 0.0}, + {"variable": "v", "type": "open"}]}, + boundary_sets=[{"region": "top", "set": "atmosphere"}]) + strong = expand(doc)["model"]["strong_form"] + assert "condition_sets" not in strong and "boundary_sets" not in strong + assert strong["boundary_conditions"] == [ + {"region": "walls", "variable": "p", "type": "neumann", "value": 0.0}, + {"region": "top", "variable": "p", "type": "dirichlet", "value": 0.0, + "expanded_from": {"set": "atmosphere"}}, + {"region": "top", "variable": "v", "type": "neumann", "value": 0.0, + "expanded_from": {"type": "open", "set": "atmosphere"}}] + + +def test_expanding_is_idempotent_and_leaves_its_input_alone(): + doc = _strong(boundary_conditions=[{"region": "walls", "variable": "v", "type": "slip"}]) + before = copy.deepcopy(doc) + once = expand(doc) + assert doc == before + assert expand(once) is once + + +def test_what_does_not_expand_is_refused(): + with pytest.raises(ValueError, match="no condition set named 'nowhere'"): + expand(_strong(boundary_sets=[{"region": "top", "set": "nowhere"}])) + + +# --- in closure ------------------------------------------------------------------------- + +strictyaml = pytest.importorskip("strictyaml") +from ymf import closure # noqa: E402 +from ymf.schema import load_ymf # noqa: E402 + + +def _keys(doc): + return sorted(k for k, _, _ in closure.planned_outputs(doc)) + + +@pytest.mark.parametrize("fixture", ["two_phase/dambreak.ymf", "shallow_water/torino.ymf", + "shallow_water/lake_at_rest.ymf"]) +def test_a_closed_spec_holds_the_expansion_and_round_trips(fixture, tmp_path): + spec = load_ymf(FIXTURES / fixture) + archive = tmp_path / "closed.archive.ymf" + closure.write(archive, spec, {}) + reloaded, outputs, dropped = closure.load(archive) + strong = reloaded["model"]["strong_form"] + assert "boundary_sets" not in strong and "condition_sets" not in strong + assert all(bc["type"] in ("dirichlet", "neumann", "robin", "periodic") + for bc in strong["boundary_conditions"]) + assert strong["boundary_conditions"] == expand(spec)["model"]["strong_form"][ + "boundary_conditions"] + assert _keys(reloaded) == _keys(spec) # the spec and its closure key alike + closure.write(tmp_path / "again.archive.ymf", reloaded, {}) + assert (tmp_path / "again.archive.ymf").read_text() == archive.read_text() + + +def _without_provenance(doc): + doc = copy.deepcopy(doc) + for bc in doc["model"]["strong_form"]["boundary_conditions"]: + bc.pop("expanded_from", None) + return doc + + +def test_aliases_and_the_same_conditions_written_out_close_alike(tmp_path): + """The dam break with its sets, and with what they mean written by hand.""" + aliased = load_ymf(FIXTURES / "two_phase" / "dambreak.ymf") + (tmp_path / "two_phase_level_set.ymf").write_text( + (FIXTURES / "two_phase" / "two_phase_level_set.ymf").read_text(encoding="utf-8") + .split(" # what the cases' walls and tops mean")[0], encoding="utf-8") + text = (FIXTURES / "two_phase" / "dambreak.ymf").read_text(encoding="utf-8") + text = text.replace(''' boundary_sets: + - {region: walls, set: free_slip} + - {region: top, set: atmosphere}''', ''' boundary_conditions: + - {region: walls, variable: v, type: dirichlet, component: normal, value: 0.0} + - {region: walls, variable: v, type: neumann, component: tangential, value: 0.0} + - {region: top, variable: p, type: dirichlet, value: 0.0} + - {region: top, variable: v, type: neumann, value: 0.0} + - {region: top, variable: χ, type: dirichlet, only: inflow, value: 1.0}''') + (tmp_path / "dambreak.ymf").write_text(text, encoding="utf-8") + by_hand = load_ymf(tmp_path / "dambreak.ymf") + a = _without_provenance(expand(aliased)) + b = _without_provenance(expand(by_hand)) + a.pop("composition", None) + b.pop("composition", None) + assert a == b + closure.write(tmp_path / "a.archive.ymf", aliased, {}) + closure.write(tmp_path / "b.archive.ymf", by_hand, {}) + closed = [] + for name in ("a", "b"): + doc, _, _ = closure.load(tmp_path / ("%s.archive.ymf" % name)) + doc = _without_provenance(doc) + doc.pop("composition", None) + closed.append(doc) + assert closed[0] == closed[1] # the two closed documents, provenance aside + + +def test_a_projection_is_of_a_vector(): + from ymf.references import YmfReferenceError, resolve + doc = load_ymf(FIXTURES.parent.parent / "examples" / "heat_equation.ymf") + doc["model"]["strong_form"]["boundary_conditions"][0].update(component="normal") + with pytest.raises(YmfReferenceError, match="a normal component is a vector's, and T is " + "a scalar"): + resolve(doc) + + +def test_a_reader_sees_only_the_expansion(): + """split_problem and adr_problem expand first; units checks the expansion.""" + pytest.importorskip("sympy") + from ymf.symbolic import SymbolicError, adr_problem + doc = load_ymf(FIXTURES / "shallow_water" / "lake_at_rest.ymf") + with pytest.raises(SymbolicError, match="normal component \\(expanded from slip\\)"): + adr_problem(doc) diff --git a/tests/test_shallow_water.py b/tests/test_shallow_water.py index e7031dc..0f7036f 100644 --- a/tests/test_shallow_water.py +++ b/tests/test_shallow_water.py @@ -61,7 +61,9 @@ def test_shallow_water_is_one_adr_system(lake): assert "q_0*numpy.sqrt(q_0**2 + q_1**2)/h**(7/3)" in momentum["reaction"]["r"] assert swe["coefficients"]["τb"]["depends_on"] == { "h": "nonlinear", "q_0": "nonlinear", "q_1": "nonlinear"} - assert [(c["type"], c["variable"]) for c in swe["boundary_conditions"]] == [("slip", "q")] + # the wall set's slip, expanded: q.n = 0 and no tangential traction + assert [(c["type"], c["variable"], c.get("component")) for c in swe["boundary_conditions"]] == [ + ("dirichlet", "q", "normal"), ("neumann", "q", "tangential")] def test_the_lake_at_rest_solves_the_model_exactly(lake): @@ -97,7 +99,7 @@ def test_the_torino_canopy(torino): assert math.isclose(_evaluate(mass, h=1.0, x=7.0, he=0.0725), porosity, rel_tol=1e-12) assert _evaluate(mass, h=1.0, x=2.0, he=0.0725) == 1.0 assert [(c["type"], c["region"]) for c in swe["boundary_conditions"]] == [ - ("slip", "walls"), ("open", "open_end")] + ("dirichlet", "walls"), ("neumann", "walls"), ("neumann", "open_end")] def test_the_torino_drag_is_the_decks_froude_law(torino): diff --git a/tests/test_split.py b/tests/test_split.py index 26b705f..03d7835 100644 --- a/tests/test_split.py +++ b/tests/test_split.py @@ -230,11 +230,12 @@ def test_a_name_is_an_unknown_or_a_known_field_not_both(): def test_each_sub_problem_imposes_the_conditions_on_what_it_solves(split): - flow = [(c["type"], c["variable"], c["region"], c.get("set")) + flow = [(c["type"], c["variable"], c["region"], c["expanded_from"].get("set")) for c in _sub(split, "flow")["boundary_conditions"]] - assert flow == [("slip", "v", "walls", "free_slip"), + assert flow == [("dirichlet", "v", "walls", "free_slip"), # slip, expanded + ("neumann", "v", "walls", "free_slip"), ("dirichlet", "p", "top", "atmosphere"), - ("open", "v", "top", "atmosphere")] + ("neumann", "v", "top", "atmosphere")] # open, expanded slip = _sub(split, "flow")["boundary_conditions"][0] assert slip["components"] == ["v_0", "v_1"] and slip["value"] == "0.0" assert _sub(split, "ncls")["boundary_conditions"] == [] @@ -242,9 +243,10 @@ def test_each_sub_problem_imposes_the_conditions_on_what_it_solves(split): def test_a_condition_on_a_coefficient_goes_to_its_carrier(split): (inflow,) = _sub(split, "vof")["boundary_conditions"] - assert inflow == {"type": "inflow", "variable": "χ", "region": "top", + assert inflow == {"type": "dirichlet", "only": "inflow", "variable": "χ", "region": "top", "where": "(abs(y - 1.8) <= tol)", "carried_by": "χh", - "set": "atmosphere", "components": ["χh"], "value": "1.0"} + "expanded_from": {"type": "inflow", "set": "atmosphere"}, + "components": ["χh"], "value": "1.0"} def test_a_condition_reaches_every_sub_problem_that_solves_for_its_variable(dambreak):