Skip to content
Merged
15 changes: 15 additions & 0 deletions docs/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@ rediscover why a thing is the way it is. Open gaps are in

## 2026-11

- **2026-11-17: C42 round 5, the formulation a generator and a dispatcher read (C19 spike report, C5 step 4 part 2).**
The generator spike could not generate what the spec did not say (stabilization, shock capturing, lagging, boundary
kind, porosity) and C5 could not state a dispersive model or a mesh of a box that is not square. Now the spec states
each, checked on load, carried by `split_problem`, and part of an archive's key: `stabilization: {method, tau, lagged,
shock_capturing: {factor, beta, reference, lagged}}` (`ymf.stabilization`; proteus's `lag`, `sc_beta`, `sc_uref` are
aliases; nothing is defaulted); `lagged_coefficients: {name: previous_step | previous_iterate}`; `imposed: strong |
weak | none` with a weak condition's `penalty` and `form` (`ymf.boundaries`; the kind of an alias goes to its Dirichlet
part; `split_problem` gives every condition its `kind`); a two-phase model with a `porosity` coefficient
(`dambreak_porous.ymf`) and `coefficient_roles` in each sub-problem's record; `dispersion: {closure:
hyperbolic_relaxation, closes, auxiliaries}` with the roles `relaxed_depth`, `relaxed_divergence`, `relaxed_bed_flux`
(`ymf.dispersion`; coefficient roles `dispersive_pressure`, `dispersive_bed_force`); `mesh: {cells: {x: 80, y: 40}}`
(`cells_per_axis`). One fix on the way: `_used` read the function `sign` as the coefficients `s i g n` and put the
gravity among RDLS's. Not done, listed in the handoff: a condition whose value is another sub-problem's trace, the
relaxed equations of the closure, `atan`, a state imposed on part of a boundary.

- **2026-11-16: C42 round 4, the spaces vocabulary (C8's choices).** A `finite_element` entry stated only family and
order; C8 (proteus FemTools rounds 1-5) added the basis, the node set, the Bernstein operator and the geometry order as
choices a run depends on. `ymf.spaces`: `basis` (`lagrange`, `bernstein`, `monomial`), `nodes` (`gll`, `equispaced`),
Expand Down
64 changes: 63 additions & 1 deletion docs/problem-specification.md
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,12 @@ checked on load, so that a second solver reads the same ones:
| `binds.*.meaning` | `element_size`, `dry_depth` |
| `writes_back` | `replace`, `add`, `mass_quadrature` |
| `linear_solver` | `direct`, `iterative`; `superlu`, `mumps`, `umfpack`, `petsc` |
| coefficient `role` | `density`, `dynamic_viscosity`, `kinematic_viscosity`, `gravity`, `phase_indicator`, `surface_tension`, `bed_elevation`, `manning_coefficient`, `porosity`, `linear_drag`, `quadratic_drag`, `bed_friction`, `canopy_drag`, `diffusivity` |
| coefficient `role` | `density`, `dynamic_viscosity`, `kinematic_viscosity`, `gravity`, `phase_indicator`, `surface_tension`, `bed_elevation`, `manning_coefficient`, `porosity`, `linear_drag`, `quadratic_drag`, `bed_friction`, `canopy_drag`, `diffusivity`, `dispersive_pressure`, `dispersive_bed_force` |
| `stabilization.tau` | `metric`, `element_size` |
| stabilization and shock-capturing keys | `tau`, `lagged`, `shock_capturing`; `factor`, `beta`, `reference`, `lagged` (older: `lag`, `sc_beta`, `sc_uref`) |
| `lagged_coefficients` values | `previous_step`, `previous_iterate` |
| `imposed` (boundary kind) | `strong`, `weak`, `none`; a weak one's `form`: `symmetric`, `nonsymmetric`, `incomplete` |
| `dispersion.closure`, auxiliary `role` | `hyperbolic_relaxation`; `relaxed_depth`, `relaxed_divergence`, `relaxed_bed_flux` |

A family is identified by the processes and assumptions of
`physical_model` (two-phase: `incompressible_flow`, `two_phase_flow`,
Expand Down Expand Up @@ -936,6 +941,63 @@ until it maps the new one. `dispersive_shallow_water` was identified by
the assumption `hyperbolic_relaxation`, which is how GN_SW2DCV discretizes
the model, not an assumption of it; that is still recognized.

### What a generator and a dispatcher read of the formulation (C42 round 5)

The words above name *what a sub-problem is*. A kernel generator (C19) and the app framework (C5) also need *how it is
formulated*, which used to come from a model's name or from `Parameters.py`. A spec states it, and
`split_problem` carries each statement in the sub-problem's record. Worked specs: the fixtures
`tests/fixtures/two_phase/dambreak_formulation.ymf`, `dambreak_porous.ymf` and
`tests/fixtures/shallow_water/circular_dam_dispersive.ymf`, `dam3bumps.ymf`. Nothing is defaulted by ymf: what a spec
does not state is the solver's own default (`ymf.stabilization.missing` lists what a reader that must not guess still
needs).

**Stabilization and shock capturing** (`ymf.stabilization`), per sub-problem, or per entry as the default of its
sub-problems (a sub-problem's block replaces the entry's whole):

```yaml
stabilization:
method: SUPG # or a bare word: stabilization: SUPG
tau: metric # metric (G, proteus useMetrics 1) | element_size (h, useMetrics 0)
lagged: false # the subgrid error taken from the previous step
shock_capturing: {factor: 0.5, beta: 1.5, reference: 1.0, lagged: true} # or: none
```

SUPG and ASGS read `tau`, `lagged`, `shock_capturing`; `residual_shock_capturing` reads `tau` and `shock_capturing`;
the entropy and graph viscosities read none (their parameters are the scheme's options). `beta` is in [1, 2],
`reference` positive, `factor` non-negative. `lag`, `sc_beta`, `sc_uref` (the keys proteus's dispatcher read first) are
accepted and resolve to `lagged`, `beta`, `reference`.

**Lagging** (`lagged_coefficients`): `{μ: previous_iterate, ρ: previous_step}` says which of the model's coefficients
a sub-problem freezes, in the Newton iteration (a Picard step: the Jacobian drops the dependence) or in time (a
constant of the step). A field read from another sub-problem is `lags`; a stabilization's lag is its `lagged`.

**Boundary kind** (`imposed` on a condition, `ymf.boundaries`): `strong` (rows replaced), `weak` (Nitsche: `penalty`
and `form`) or `none` (the natural condition). A Dirichlet condition is strong or weak (default strong); Neumann,
Robin and `open` are none. `split_problem` gives each condition its resolved `kind`, which is what picks a kernel's
face term (the engine's Strong, WeakDirichlet and Flux). An alias gives its kind to its Dirichlet part only.

**Porosity** is a coefficient with `role: porosity`; `dambreak_porous.ymf` states it in the two-phase model's
continuity, momentum, VOF and MCorr equations. A sub-problem's record lists the roles of the coefficients it uses
(`coefficient_roles`), so a generator finds the porosity by its role.

**The dispersive family** (`ymf.dispersion`): the model is the shallow-water one with the dispersive pressure `Pd` and bed
force `Qd` as coefficients (roles `dispersive_pressure`, `dispersive_bed_force`), and a sub-problem states the closure
that supplies them and the auxiliary unknowns it introduces:

```yaml
dispersion:
closure: hyperbolic_relaxation
closes: [Pd, Qd]
auxiliaries:
- {name: hη, role: relaxed_depth, units: m2} # initial h², boundary data of h
- {name: hw, role: relaxed_divergence, units: m2/s} # initial 0, boundary data of h (`initial:` to state another)
- {name: hβ, role: relaxed_bed_flux, units: m2/s} # initial 0, boundary data of q
```

**Cells per axis**: `mesh: {cells: {x: 80, y: 40}}`. One count (`cells: 80`) is every axis, a list is a study
(`cells: [80, 160]`), a list of maps a study of such meshes. `ymf.discretizations.cells_per_axis(cells, dim)` gives the
counts in axis order; the output key reads `cells=80x40`.

## Document state

A YMF document is the record of a progression: from a model, through a
Expand Down
13 changes: 13 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ python examples/read_archive.py /tmp/ymf-demo/heat.ymf # read one back
| [nonlinear_diffusion.ymf](nonlinear_diffusion.ymf) | A coefficient that is a function of the state: the conductivity `k = 1 + u²` names the unknown, so the problem is nonlinear and solved by Newton. Manufactured exact solution; P1 and P2 rates 2 and 3. |
| [kovasznay_flow.ymf](kovasznay_flow.ymf) | Branching: Navier–Stokes with two weak forms (Taylor–Hood, stabilized equal-order), a discretization for each, a Reynolds number computed from the scales, and a verification plan against the exact solution. |

### The formulation a generator and a dispatcher read (C42 round 5)

Worked specs live with the tests, because they extend the family files there:

| File | Shows |
|---|---|
| [two_phase/dambreak_formulation.ymf](../tests/fixtures/two_phase/dambreak_formulation.ymf) | The dam break with `stabilization` (ASGS, SUPG, shock capturing and their parameters per sub-problem) and `imposed` boundary kinds stated. |
| [two_phase/dambreak_porous.ymf](../tests/fixtures/two_phase/dambreak_porous.ymf) | The two-phase model with a porosity coefficient (`role: porosity`) in continuity, momentum, VOF and MCorr. |
| [shallow_water/circular_dam_dispersive.ymf](../tests/fixtures/shallow_water/circular_dam_dispersive.ymf) | The dispersive family: `dispersion` with the hyperbolic-relaxation closure and its three auxiliary unknowns (and [dispersive.ymf](../tests/fixtures/shallow_water/dispersive.ymf), [dispersive_numerics.ymf](../tests/fixtures/shallow_water/dispersive_numerics.ymf) it extends). |
| [shallow_water/dam3bumps.ymf](../tests/fixtures/shallow_water/dam3bumps.ymf) | Cells per axis: `mesh: {cells: {x: 80, y: 40}}`. |

`lagged_coefficients` has no fixture (no solver of the dam break freezes a coefficient); `tests/test_lagging.py` sets it.

### Composed from several files: [navier_stokes/](navier_stokes/)

One model, extended into three problems with `extends`, and one archive extended. See
Expand Down
119 changes: 119 additions & 0 deletions src/ymf/boundaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Boundary kind: how a boundary condition reaches the discrete problem (strong, weak, none), and a weak one's parameters.

A condition says *what* holds on a boundary (a value, a flux). Its ``imposed`` says *how the discrete problem enforces
it*, which is what picks the boundary term a kernel evaluates there (the engine's face kinds ``Strong``,
``WeakDirichlet`` and ``Flux``; C19's gap note G8)::

- {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: strong} # rows of the system replaced
- {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: weak, # penalty and consistency terms
penalty: 100.0, form: symmetric}
- {region: outlet, variable: φ, type: neumann, value: 0.0} # none: the natural condition

* ``strong``: the unknown's degrees of freedom on the boundary are set to the value (a Dirichlet condition).
* ``weak``: the value is enforced through terms of the weak form (Nitsche): a penalty ``penalty / h`` and, by ``form``, the
adjoint consistency term: ``symmetric`` (SIPG), ``nonsymmetric`` (NIPG) or ``incomplete`` (IIPG, none). Dirichlet only.
* ``none``: nothing constrains the solution on the boundary; the boundary integral carries the given flux (Neumann, Robin)
or leaves with the solution's own trace (``open``).

The kind is what a condition's *type* allows: a Dirichlet condition (and the Dirichlet part of ``slip``, ``inflow``,
``characteristic``) is ``strong`` or ``weak`` (default ``strong``); Neumann, Robin and ``open`` are ``none``;
``periodic`` is none of them (the faces are identified). :func:`kind_of` gives the kind of a condition, stated or the
default; :func:`check_condition` refuses what does not make sense (a strong Neumann condition, a penalty on a strong
one); :func:`kinds` lists every condition of a document with its kind.

When an alias is expanded (``ymf.conditions``) the kind goes to the Dirichlet components only: ``slip, imposed: weak`` is
a weak normal condition and a natural tangential one. ``split_problem`` gives each condition's ``kind``, and for a weak
one its ``penalty`` and ``form``, so a generator picks the face kernel from the declaration and not from the model's name.

Stdlib only, like the rest of the spec core.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

__all__ = ["BoundaryError", "BOUNDARY_KINDS", "WEAK_FORMS", "kind_of", "check_condition", "kinds"]


class BoundaryError(ValueError):
"""A boundary kind a spec states that does not make sense."""


BOUNDARY_KINDS: Dict[str, str] = {
"strong": "the degrees of freedom on the boundary are set to the value",
"weak": "the value is enforced through penalty and consistency terms of the weak form (Nitsche)",
"none": "no constraint on the solution: the boundary integral carries the given flux, or the solution's own trace",
}

WEAK_FORMS: Dict[str, str] = {
"symmetric": "SIPG: the adjoint consistency term with the sign that keeps the form symmetric",
"nonsymmetric": "NIPG: the adjoint consistency term with the opposite sign",
"incomplete": "IIPG: no adjoint consistency term",
}

#: the types a condition's kind is chosen for (the Dirichlet part), and the types that are always ``none``
_DIRICHLET = ("dirichlet", "slip", "inflow", "characteristic")
_NATURAL = ("neumann", "robin", "open")


def kind_of(condition: Dict[str, Any]) -> Optional[str]:
"""The boundary kind of a condition (an alias, or an abstract one): what it states, or its type's default. None for
``periodic``."""
kind = condition.get("type")
if kind == "periodic":
return None
stated = condition.get("imposed")
if stated is not None:
return str(stated)
return "strong" if kind in _DIRICHLET else "none"


def check_condition(condition: Dict[str, Any], where: str) -> None:
"""``imposed``, ``penalty`` and ``form`` of a condition agree with its type. Raises :class:`BoundaryError`."""
kind = condition.get("type")
stated = condition.get("imposed")
has_weak_keys = [k for k in ("penalty", "form") if condition.get(k) is not None]
if stated is not None and str(stated) not in BOUNDARY_KINDS:
raise BoundaryError("%s: imposed %s is not one of %s" % (where, stated, ", ".join(BOUNDARY_KINDS)))
if kind == "periodic":
if stated is not None or has_weak_keys:
raise BoundaryError("%s: a periodic condition identifies faces; it has no kind" % (where,))
return
if kind in _NATURAL and stated is not None and str(stated) != "none":
raise BoundaryError(
"%s: a %s condition is imposed none (the boundary integral carries it); %s is for a Dirichlet condition"
% (where, kind, stated))
if kind in _DIRICHLET and stated is not None and str(stated) == "none":
raise BoundaryError(
"%s: a %s condition imposes a value, strong or weak; to impose nothing give no condition, or open"
% (where, kind))
weak = kind_of(condition) == "weak"
if has_weak_keys and not weak:
raise BoundaryError("%s: %s belong to a weak condition (imposed: weak); this one is %s" % (
where, " and ".join(has_weak_keys), kind_of(condition)))
if condition.get("penalty") is not None:
try:
ok = float(condition["penalty"]) > 0
except (TypeError, ValueError):
ok = False
if not ok:
raise BoundaryError("%s: penalty %s is not a positive number" % (where, condition["penalty"]))
if condition.get("form") is not None and str(condition["form"]) not in WEAK_FORMS:
raise BoundaryError("%s: form %s is not one of %s" % (where, condition["form"], ", ".join(WEAK_FORMS)))


def kinds(doc: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Every boundary condition of the document, expanded, as ``{region, variable, type, [component], [only], kind,
[penalty], [form]}`` in order: what a solver reads to choose its boundary terms."""
from ymf.conditions import expand
from ymf.normalize import boundary_conditions
strong = ((expand(doc).get("model") or {}).get("strong_form") or {})
out = []
for bc in boundary_conditions(strong):
entry = {k: bc[k] for k in ("region", "variable", "type", "component", "only") if bc.get(k) is not None}
entry["kind"] = kind_of(bc)
for k in ("penalty", "form"):
if bc.get(k) is not None:
entry[k] = bc[k]
out.append(entry)
return out
6 changes: 5 additions & 1 deletion src/ymf/conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

#: the order an expanded condition's keys are written in
_ORDER = ("region", "variable", "type", "component", "only", "value", "formula", "series",
"alpha", "beta", "units", "imposed", "source", "source_url", "temporal",
"alpha", "beta", "units", "imposed", "penalty", "form", "source", "source_url", "temporal",
"expanded_from")


Expand Down Expand Up @@ -119,10 +119,14 @@ def expand_condition(bc: Dict[str, Any], rank: int = 0) -> List[Dict[str, Any]]:
given = {k: bc[k] for k in _VALUE_KEYS if bc.get(k) is not None}
shared = {k: v for k, v in bc.items()
if k not in _VALUE_KEYS and k not in ("type", "set", "expanded_from")}
# how a condition is imposed is the Dirichlet part's (ymf.boundaries): the natural parts stay natural
kind_keys = {k: shared.pop(k) for k in ("imposed", "penalty", "form") if k in shared}
out = []
for part in alias["components"]:
entry = dict(shared)
entry.update({k: v for k, v in part.items() if k not in ("takes", "default")})
if part["type"] == "dirichlet":
entry.update(kind_keys)
if part.get("takes"):
if given:
entry.update(given)
Expand Down
Loading
Loading