Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 39 additions & 10 deletions docs/problem-specification.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
18 changes: 15 additions & 3 deletions src/ymf/closure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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
Expand Down
189 changes: 189 additions & 0 deletions src/ymf/conditions.py
Original file line number Diff line number Diff line change
@@ -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: <alias>}`` (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()]
3 changes: 3 additions & 0 deletions src/ymf/references.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
7 changes: 7 additions & 0 deletions src/ymf/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions src/ymf/symbolic/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
Loading
Loading