diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7714d47 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,101 @@ +name: release + +# Publishes ymf to TestPyPI (pre-release tags) or PyPI (final tags) with Trusted +# Publishing: GitHub mints a short-lived OIDC token per job, so there is no API +# token and no secret anywhere. It does nothing until all of these are true: +# 1. the project and this workflow are registered as a Trusted Publisher on +# test.pypi.org and pypi.org (RELEASING.md, steps 1-2: cekees's to do), +# 2. the GitHub environments `testpypi` and `pypi` exist (RELEASING.md, step 3), +# 3. a matching tag is pushed. Nothing here runs on a branch or a pull request. +# Tags: `v0.3.0rc1`, `v0.3.0a1`, `v0.3.0b2` go to TestPyPI; `v0.3.0` goes to PyPI. +# setuptools_scm turns the tag into the version, and the build job refuses to go +# on when the two disagree, so a mistyped tag cannot publish the wrong version. +on: + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+a[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+b[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+rc[0-9]+" + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + outputs: + prerelease: ${{ steps.version.outputs.prerelease }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # setuptools_scm needs the tags + persist-credentials: false + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Build, check and smoke-test the distributions + run: | + python -m pip install --upgrade pip build twine + tools/check_dist.sh "$RUNNER_TEMP/check" + mkdir dist + cp "$RUNNER_TEMP"/check/dist/* dist/ + + - name: The tag and the built version agree + id: version + run: | + python - <<'PY' + import glob, os, re + from packaging.version import Version + tag = os.environ["GITHUB_REF_NAME"] + wheel = glob.glob("dist/ymf-*.whl") + assert len(wheel) == 1, wheel + built = Version(re.match(r"ymf-([^-]+)-", os.path.basename(wheel[0])).group(1)) + assert tag == "v" + str(built), f"tag {tag} builds version {built}" + assert not built.local and not built.dev, f"not a release version: {built}" + with open(os.environ["GITHUB_OUTPUT"], "a") as f: + f.write(f"prerelease={'true' if built.is_prerelease else 'false'}\n") + print("version", built, "prerelease", built.is_prerelease) + PY + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: dist/ + if-no-files-found: error + + publish-testpypi: + needs: build + if: needs.build.outputs.prerelease == 'true' + runs-on: ubuntu-latest + environment: + name: testpypi # not created by this PR: RELEASING.md step 3 + url: https://test.pypi.org/p/ymf + permissions: + id-token: write # the OIDC token Trusted Publishing exchanges + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: https://test.pypi.org/legacy/ + + publish-pypi: + needs: build + if: needs.build.outputs.prerelease == 'false' + runs-on: ubuntu-latest + environment: + name: pypi # not created by this PR: RELEASING.md step 3 + url: https://pypi.org/p/ymf + permissions: + id-token: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..5b19ae2 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,7 @@ +# What the sdist ships: setuptools_scm adds every git-tracked file (source, +# tests with their fixtures, examples, docs, README, LICENSE), so this only +# prunes. Nothing generated or local may ride along. +prune .github +global-exclude *.pyc __pycache__ *.log .coverage .DS_Store +# What ymf_run and the examples write beside themselves +global-exclude examples/*.archive.ymf diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..ffe611c --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,68 @@ +# Releasing ymf + +A release is a git tag. `.github/workflows/release.yml` builds the sdist and +wheel from the tagged commit, checks them (`tools/check_dist.sh`: size, +contents, `twine check`, a fresh-venv install that runs), and publishes with +PyPI Trusted Publishing (OIDC: no API token, no secret). The version is +whatever `setuptools_scm` derives from the tag; the workflow refuses a tag that +does not equal `v`. + +| tag | goes to | +|---|---| +| `v0.3.0rc1`, `v0.3.0a1`, `v0.3.0b1` | TestPyPI (environment `testpypi`) | +| `v0.3.0` | PyPI (environment `pypi`) | + +The tag `v0.2.0` already exists from before this workflow; it is not re-pushed +and nothing publishes it. Pick the first published version knowing that. + +## What the maintainer does by hand (once) + +Name check, 2026-11-16: `ymf` returns 404 on pypi.org and test.pypi.org (JSON +API and simple index), so it is free today. PyPI can still refuse a name that +is confusingly close to an existing project, and a project registered +meanwhile wins: do step 1 soon. + +1. **TestPyPI**: log in at test.pypi.org (a separate account from PyPI), then + *Your account → Publishing → Add a new pending publisher*: project name + `ymf`, owner `proteustoolkit` (or `cekees` to rehearse from the fork), + repository `ymf`, workflow `release.yml`, environment `testpypi`. +2. **PyPI**: the same at pypi.org, environment `pypi`. A *pending* publisher + creates the project on the first upload, so nothing is uploaded to claim + the name. +3. **GitHub environments** on the repository that will run the workflow: + Settings → Environments → create `testpypi` and `pypi`. For `pypi`, add + yourself as a required reviewer so a final tag waits for a click; leave + `testpypi` unprotected. No secrets are added to either. +4. **Push a pre-release tag** from a commit on `main` whose CI is green: + + ```bash + git tag -a v0.3.0rc1 -m "ymf 0.3.0rc1" && git push origin v0.3.0rc1 + ``` + + Then try it the way a user would: + + ```bash + python -m venv /tmp/t && /tmp/t/bin/pip install --index-url https://test.pypi.org/simple/ \ + --extra-index-url https://pypi.org/simple/ "ymf[frontend]==0.3.0rc1" + ``` + + (the extra index supplies pyyaml and the extras' dependencies, which are + not on TestPyPI). A TestPyPI file name can never be reused: a mistake is + fixed by `rc2`, not by re-uploading. +5. When rc installs and runs, tag `v0.3.0` the same way for PyPI. + +To rehearse the build without publishing, run `tools/check_dist.sh` (set +`SETUPTOOLS_SCM_PRETEND_VERSION=0.3.0rc1` off a tag). + +## Pinning from proteus CI (not done here) + +proteus's workflows install ymf from `git+https://github.com/proteustoolkit/ymf.git@main`, +a moving branch, in the environment files and in the comment block of +`.github/workflows/sdist.yml`. After a tagged release exists, the proteus-side +change is: replace `@main` with the tag (`@v0.3.0`, or `ymf==0.3.0` from PyPI +once it is there; before that, TestPyPI needs the extra-index form above and +is not worth using in CI), in every environment file and workflow that names +it, and update the comment. The pin moves by a one-line PR per ymf release; a +ymf change that proteus needs merges in ymf, is tagged, and then the proteus PR +bumps the pin. That is a proteus change: it needs its own PR and is not part of +this one. diff --git a/docs/changes.md b/docs/changes.md index cc21f45..4ceda30 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -7,6 +7,16 @@ rediscover why a thing is the way it is. Open gaps are in ## 2026-11 +- **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`), + `bernstein_operator`, and `geometry_order` beside the spaces, each checked on load (nodes only with a Lagrange basis, + the Bernstein operator only with a Bernstein basis, the vector families RT/BDM/RTF/N1curl take neither, lowest orders + RT0, BDM1, N1curl0, geometry order >= 1); `resolve` fills the defaults proteus uses (`lagrange`, `gll`, exact + Bernstein conversion, affine geometry), so two spellings of one space resolve equal. `implemented_in_proteus` records + what FemTools has (information, never a refusal). Existing specs are unchanged. proteus CI installs ymf from + `proteustoolkit/ymf@main`, so proteus sees this only after the ymf merge. + - **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 diff --git a/docs/problem-specification.md b/docs/problem-specification.md index 1e2c30a..c0eafb7 100644 --- a/docs/problem-specification.md +++ b/docs/problem-specification.md @@ -231,7 +231,12 @@ usually `finite_element` and `from_weak_form` (a weak form's label, which may be omitted when the document has only one — see [Branching](#branching-one-problem-several-solution-paths)). `finite_element` takes `fields`, or `velocity` and `pressure` for mixed problems, each as -`{family: CG|DG|RT|BDM|RTF|N1curl, order: n}`. The `solver` block takes +`{family: CG|DG|RT|BDM|RTF|N1curl, order: n}`, and, where they apply, `basis` +(`lagrange | bernstein | monomial`), `nodes` (`gll | equispaced`, Lagrange basis) and +`bernstein_operator` (Bernstein basis); `finite_element` also takes `geometry_order` (the degree of +the mesh map, 1 = affine). The words, their defaults and the order numbering of the vector +families (RT0 is `order: 0`, BDM1 is `order: 1`) are in `ymf.spaces`, which checks them on load. +The `solver` block takes `type` (`linear | nonlinear | time_marching | saddle_point`), `linear_solver` (`direct | iterative`, or a package: `petsc | mumps | umfpack | superlu`), `petsc_options`, diff --git a/examples/poisson_spaces.ymf b/examples/poisson_spaces.ymf new file mode 100644 index 0000000..34413cf --- /dev/null +++ b/examples/poisson_spaces.ymf @@ -0,0 +1,37 @@ +# ============================================================ +# YMF Example: Poisson on the unit square, the space stated in full +# +# Extends poisson.ymf with discretizations that say which space they use +# beyond its family and order (ymf.spaces): the basis, where a Lagrange +# basis puts its nodes, how Bernstein data is imposed, the degree of the +# mesh map, and the mixed form's H(div) pair. Every default is the one +# proteus's FemTools uses, so P3_gll is `{family: CG, order: 3}` written out. +# +# python -c "import ymf.spaces as s; print(s.resolve({'family': 'CG', 'order': 3}))" +# ============================================================ + +extends: poisson.ymf + +solution_paths: + discretizations: + - name: "P3_gll" + provenance: human_specified + finite_element: + fields: {family: CG, order: 3, basis: lagrange, nodes: gll} + geometry_order: 1 + mesh: {cells: [4, 8, 16]} + solver: {type: linear, linear_solver: petsc, tolerance: 1.0e-12} + + - name: "P4_equispaced" # for comparison: the Lebesgue constant grows from p = 4 + provenance: human_specified + finite_element: + fields: {family: CG, order: 4, basis: lagrange, nodes: equispaced} + mesh: {cells: [4, 8]} + solver: {type: linear, linear_solver: petsc, tolerance: 1.0e-12} + + - name: "P3_bernstein_exact" # bounds-preserving basis, data converted exactly (order p + 1) + provenance: human_specified + finite_element: + fields: {family: CG, order: 3, basis: bernstein, bernstein_operator: false} + mesh: {cells: [4, 8, 16]} + solver: {type: linear, linear_solver: petsc, tolerance: 1.0e-12} diff --git a/examples/validate_spec.py b/examples/validate_spec.py index f0b2774..16e3f76 100644 --- a/examples/validate_spec.py +++ b/examples/validate_spec.py @@ -78,7 +78,7 @@ def describe(path: Path) -> bool: if str(disc.get("from_weak_form")) in (wf["label"], str(index)): fe = disc.get("finite_element", {}) spaces = ", ".join("%s %s%s" % (k, v["family"], v["order"]) - for k, v in fe.items()) + for k, v in fe.items() if isinstance(v, dict)) print(" discretization %r: %s; %s solver" % (disc["name"], spaces or "-", disc["solver"].get("type", "-"))) for exact in paths["analytical"]: diff --git a/pyproject.toml b/pyproject.toml index d2ced03..4e4237e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,6 @@ [build-system] -requires = ["setuptools>=68", "wheel", "setuptools_scm>=8"] +# setuptools>=77 for the SPDX `license` expression and `license-files` (PEP 639). +requires = ["setuptools>=77", "setuptools_scm>=8"] build-backend = "setuptools.build_meta" [project] @@ -8,8 +9,27 @@ dynamic = ["version"] description = "YAML Modeling Format for computational physics — problem specification, VVUQ, and multi-backend dispatch." readme = "README.md" requires-python = ">=3.10" -license = { text = "MIT" } +# Where the version comes from: setuptools_scm, from the git tag (`v0.3.0`, +# `v0.3.0rc1`). A tagged commit builds exactly the tag; any other commit builds +# a `.devN+gHASH` version, which PyPI and TestPyPI refuse (release.yml checks +# that the tag and the built version agree before it uploads). +license = "MIT" +license-files = ["LICENSE"] authors = [{ name = "cekees" }] +keywords = ["yaml", "simulation", "computational-physics", "pde", "verification", "uncertainty-quantification"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Physics", +] # Core runtime dependency, kept to exactly one on purpose: a solver that # writes YMF archives (see ymf.archive) must not inherit the validation # stack. Everything heavier sits behind the extras below, which only the @@ -18,6 +38,13 @@ dependencies = [ "pyyaml>=6.0", ] +[project.urls] +Homepage = "https://github.com/proteustoolkit/ymf" +Documentation = "https://github.com/proteustoolkit/ymf/tree/main/docs" +Source = "https://github.com/proteustoolkit/ymf" +Issues = "https://github.com/proteustoolkit/ymf/issues" +Changelog = "https://github.com/proteustoolkit/ymf/blob/main/docs/changes.md" + [project.scripts] # Converts a .ymf archive to the .xmf a viewer reads. In the core, so it # works without the ymf[spec] validation stack. @@ -39,6 +66,18 @@ frontend = ["strictyaml>=1.7", "pint>=0.23", "sympy>=1.12"] # What examples/write_archive.py and read_archive.py need to make and read # the HDF5 side of an archive. A solver brings its own. examples = ["numpy", "h5py"] +# Tests: what `pytest tests` needs so that nothing skips (CI's `dev` leg). +# There is no `docs` extra on purpose: docs/ is plain markdown with no build +# step, so there is nothing for one to install. +test = [ + "pytest>=7.0", + "pytest-cov", + "strictyaml>=1.7", + "pint>=0.23", + "numpy", + "h5py", + "sympy>=1.12", +] dev = [ "pytest>=7.0", "pytest-cov", diff --git a/src/ymf/schema.py b/src/ymf/schema.py index ab96efc..aa53790 100644 --- a/src/ymf/schema.py +++ b/src/ymf/schema.py @@ -84,11 +84,25 @@ } ) +# A space: family and order, and where they apply the basis, the nodes of a +# Lagrange basis and the Bernstein operator (ymf.spaces, checked on load). +SpaceDef = Map( + { + "family": FEFamilyEnum, + "order": Int(), + Optional("basis"): Str(), + Optional("nodes"): Str(), + Optional("bernstein_operator"): Bool(), + } +) + FiniteElementDef = Map( { - Optional("velocity"): Map({"family": FEFamilyEnum, "order": Int()}), - Optional("pressure"): Map({"family": FEFamilyEnum, "order": Int()}), - Optional("fields"): Map({"family": FEFamilyEnum, "order": Int()}), + Optional("velocity"): SpaceDef, + Optional("pressure"): SpaceDef, + Optional("fields"): SpaceDef, + # the polynomial degree of the mesh map: 1 = affine, 2 = quadratic ... (ymf.spaces) + Optional("geometry_order"): Int(), } ) diff --git a/src/ymf/spaces.py b/src/ymf/spaces.py new file mode 100644 index 0000000..9b5b1d0 --- /dev/null +++ b/src/ymf/spaces.py @@ -0,0 +1,145 @@ +"""The vocabulary of a finite element space: what a ``finite_element`` entry says beyond its family and order. + +A space is stated as ``{family, order}`` plus, where they apply, the words below:: + + fields: {family: CG, order: 3, basis: bernstein, bernstein_operator: false} + fields: {family: CG, order: 4, basis: lagrange, nodes: gll} + velocity: {family: RT, order: 0} + geometry_order: 1 # beside the spaces: the mesh map's polynomial degree + +* ``family`` (schema): CG, DG, RT, BDM, RTF, N1curl. +* ``order``: the polynomial degree p of CG and DG (CG >= 1, DG >= 0). For the vector families it numbers the family's + members, the lowest being RT0 (``order: 0``), BDM1 (``order: 1``) and N1curl (``order: 0``): ``RT, order 0`` is the + lowest-order Raviart-Thomas space, whose normal trace on a facet is constant. +* ``basis`` (CG, DG): the polynomial space is P_p on simplices (Q_p on cubes); ``lagrange`` is the nodal basis, + ``bernstein`` the Bernstein-Bezier basis (CG only: non-negative, sums to one, the dofs are control-point coefficients + and not point values), ``monomial`` the DG basis of monomials. Default: ``lagrange`` for CG, ``monomial`` for DG. +* ``nodes`` (Lagrange basis): where the nodes sit, ``gll`` (warp-and-blend with Gauss-Lobatto-Legendre edge points on + simplices, tensor GLL on cubes; well conditioned from p = 3) or ``equispaced``; they coincide for p <= 2. Default ``gll``. +* ``bernstein_operator`` (Bernstein basis): how data is put into the space. False (default) is the exact conversion of + the degree-p interpolant (order p + 1); true takes control-point values (preserves bounds, second order). +* ``geometry_order`` (beside the spaces): the polynomial degree of the map from the reference cell to the element, 1 = + affine (straight facets, constant Jacobian), 2 = quadratic, .. (iso- and super-parametric elements). Default 1. +* the vector families (RT, BDM, RTF, N1curl) have no ``basis`` or ``nodes``: their dofs are fixed by the family (normal + flux densities for RT and BDM, tangential moments for N1curl), and their elements are mapped by a Piola transform + (``contravariant_piola`` for RT, BDM, RTF; ``covariant_piola`` for N1curl; ``identity`` for CG and DG). + +:func:`resolve` returns the space with every default filled in; two specs that resolve equal state the same space. +:data:`IMPLEMENTED_IN_PROTEUS` records what proteus's ``FemTools`` carries as of cekees/main 92f24ad9 (C8 rounds 1-5), as +information: ymf does not refuse a space proteus lacks, because a spec states a problem and a solver may not have caught up. +""" + +from __future__ import annotations + +from typing import Any, Dict + +__all__ = ["SpaceError", "BASES", "NODES", "VECTOR_FAMILIES", "MAPS", "resolve", "check", "check_finite_element", + "IMPLEMENTED_IN_PROTEUS", "implemented_in_proteus"] + + +class SpaceError(ValueError): + """A space a spec states that does not make sense.""" + + +BASES: Dict[str, str] = { + "lagrange": "the nodal basis: dof i is the value at node i", + "bernstein": "the Bernstein-Bezier basis: non-negative, sums to one; dofs are control-point coefficients", + "monomial": "the basis of monomials (discontinuous spaces)", +} +NODES: Dict[str, str] = { + "gll": "warp-and-blend nodes with Gauss-Lobatto-Legendre points on the edges (tensor GLL on cubes)", + "equispaced": "equally spaced nodes (fine through p = 3; coincides with gll for p <= 2)", +} +#: family -> (lowest order, the Piola/pullback map of its elements, the bases it has) +_FAMILIES: Dict[str, Dict[str, Any]] = { + "CG": {"min_order": 1, "map": "identity", "bases": ("lagrange", "bernstein"), "default_basis": "lagrange"}, + "DG": {"min_order": 0, "map": "identity", "bases": ("monomial", "lagrange"), "default_basis": "monomial"}, + "RT": {"min_order": 0, "map": "contravariant_piola", "bases": ()}, + "BDM": {"min_order": 1, "map": "contravariant_piola", "bases": ()}, + "RTF": {"min_order": 0, "map": "contravariant_piola", "bases": ()}, + "N1curl": {"min_order": 0, "map": "covariant_piola", "bases": ()}, +} +VECTOR_FAMILIES = tuple(f for f, v in _FAMILIES.items() if not v["bases"]) +MAPS = tuple(sorted({v["map"] for v in _FAMILIES.values()})) +_KEYS = {"family", "order", "basis", "nodes", "bernstein_operator"} + +#: what proteus's FemTools carries (C8, cekees/main 92f24ad9): (family, basis) -> the orders. Information only. +IMPLEMENTED_IN_PROTEUS: Dict[Any, Any] = { + ("CG", "lagrange"): "simplices: any p >= 1 (nodes gll or equispaced); cubes: p = 1, 2", + ("CG", "bernstein"): "simplices: any p >= 1; cubes: p = 2", + ("DG", "monomial"): "simplices: p = 0..6", + ("DG", "lagrange"): "simplices: p = 1", + ("RT", None): "simplices: order 0 (RT0)", + ("BDM", None): "simplices: order 1 (BDM1)", + "geometry_order": "1 (affine) only; higher waits for C7.1", +} + + +def resolve(space: Dict[str, Any], where: str = "finite_element") -> Dict[str, Any]: + """The space with its defaults filled in: ``{family, order, basis, nodes, bernstein_operator, map}`` (``basis``, + ``nodes``, ``bernstein_operator`` only where they apply). Raises :class:`SpaceError`.""" + unknown = sorted(set(space) - _KEYS) + if unknown: + raise SpaceError("%s: no key %s in a space; its keys are %s" % (where, ", ".join(unknown), ", ".join(sorted(_KEYS)))) + family = str(space["family"]) + spec = _FAMILIES[family] + order = int(space["order"]) + if order < spec["min_order"]: + raise SpaceError("%s: order %d: the lowest order of %s is %d" % (where, order, family, spec["min_order"])) + out: Dict[str, Any] = {"family": family, "order": order, "map": spec["map"]} + if not spec["bases"]: + for key in ("basis", "nodes", "bernstein_operator"): + if key in space: + raise SpaceError("%s: %s has no %s: its dofs are fixed by the family (the %s map applies)" + % (where, family, key, spec["map"])) + return out + basis = str(space.get("basis", spec["default_basis"])) + if basis not in BASES: + raise SpaceError("%s: basis %s is not one of %s" % (where, basis, ", ".join(BASES))) + if basis not in spec["bases"]: + raise SpaceError("%s: %s has no %s basis; its bases are %s" % (where, family, basis, ", ".join(spec["bases"]))) + out["basis"] = basis + if "nodes" in space: + nodes = str(space["nodes"]) + if nodes not in NODES: + raise SpaceError("%s: nodes %s is not one of %s" % (where, nodes, ", ".join(NODES))) + if basis != "lagrange": + raise SpaceError("%s: nodes belong to a lagrange basis, and this one is %s" % (where, basis)) + if basis == "lagrange": + out["nodes"] = str(space.get("nodes", "gll")) + if "bernstein_operator" in space: + if basis != "bernstein": + raise SpaceError("%s: bernstein_operator belongs to a bernstein basis, and this one is %s" % (where, basis)) + if basis == "bernstein": + out["bernstein_operator"] = bool(space.get("bernstein_operator", False)) + return out + + +def check(space: Dict[str, Any], where: str = "finite_element") -> Dict[str, Any]: + """:func:`resolve`, under the name vocabulary checks use.""" + return resolve(space, where) + + +def check_finite_element(block: Any, where: str) -> None: + """A ``finite_element`` block: each space it states, and its ``geometry_order``.""" + if not isinstance(block, dict): + return + for key, value in block.items(): + if key == "geometry_order": + if int(value) < 1: + raise SpaceError("%s.geometry_order: %s: the map's degree is at least 1 (1 = affine)" % (where, value)) + elif isinstance(value, dict): + resolve(value, "%s.%s" % (where, key)) + + +def implemented_in_proteus(space: Dict[str, Any]) -> bool: + """Whether proteus's FemTools has this space on simplices (information, see :data:`IMPLEMENTED_IN_PROTEUS`).""" + r = resolve(space) + basis = r.get("basis") + o = r["order"] + f = r["family"] + if f == "CG": + return True + if f == "DG": + return (basis == "monomial" and o <= 6) or (basis == "lagrange" and o == 1) + return (f == "RT" and o == 0) or (f == "BDM" and o == 1) diff --git a/src/ymf/vocabulary.py b/src/ymf/vocabulary.py index 2918633..4730917 100644 --- a/src/ymf/vocabulary.py +++ b/src/ymf/vocabulary.py @@ -450,6 +450,14 @@ def _stabilization_method(s: Any) -> Any: return None +def _check_spaces(block: Any, where: str) -> None: + from ymf.spaces import SpaceError, check_finite_element + try: + check_finite_element(block, where) + except SpaceError as exc: + raise VocabularyError(str(exc)) from 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") @@ -476,6 +484,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st "%s.discretization: the scheme %s has no option %s; its options are %s" % (where, scheme, ", ".join(unread), ", ".join(list(SCHEMES[scheme]["options"]) + list(SCHEME_COMMON)))) + _check_spaces(entry.get("finite_element"), where + ".finite_element") for label, binding in list((entry.get("binds") or {}).items()): if isinstance(binding, dict) and binding.get("meaning") is not None: _word("binding_meaning", binding["meaning"], "%s.binds.%s.meaning" % (where, label)) @@ -491,6 +500,7 @@ def _check_entry(doc: Dict[str, Any], entry: Dict[str, Any], family: Optional[st if method is not None: _word("stabilization", method, here + ".stabilization.method") _check_solver(sub.get("solver"), here) + _check_spaces(sub.get("finite_element"), here + ".finite_element") 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)) diff --git a/tests/test_spaces.py b/tests/test_spaces.py new file mode 100644 index 0000000..01ec888 --- /dev/null +++ b/tests/test_spaces.py @@ -0,0 +1,101 @@ +"""ymf.spaces: what a finite_element entry says beyond family and order (C8's vocabulary), checked on load.""" + +import copy +from pathlib import Path + +import pytest + +pytest.importorskip("strictyaml") + +from ymf.schema import load_ymf # noqa: E402 +from ymf.spaces import SpaceError, implemented_in_proteus, resolve # noqa: E402 +from ymf.vocabulary import VocabularyError, check # noqa: E402 + +EXAMPLES = Path(__file__).parent.parent / "examples" + + +def test_defaults_are_the_ones_femtools_uses(): + assert resolve({"family": "CG", "order": 3}) == { + "family": "CG", "order": 3, "map": "identity", "basis": "lagrange", "nodes": "gll"} + assert resolve({"family": "CG", "order": 3, "basis": "bernstein"}) == { + "family": "CG", "order": 3, "map": "identity", "basis": "bernstein", "bernstein_operator": False} + assert resolve({"family": "DG", "order": 1})["basis"] == "monomial" + + +def test_two_ways_to_say_the_same_space_resolve_equal(): + assert resolve({"family": "CG", "order": 2}) == resolve( + {"family": "CG", "order": 2, "basis": "lagrange", "nodes": "gll"}) + + +def test_the_vector_families_have_a_map_and_no_basis(): + assert resolve({"family": "RT", "order": 0}) == {"family": "RT", "order": 0, "map": "contravariant_piola"} + assert resolve({"family": "BDM", "order": 1})["map"] == "contravariant_piola" + assert resolve({"family": "N1curl", "order": 0})["map"] == "covariant_piola" + with pytest.raises(SpaceError, match="RT has no basis"): + resolve({"family": "RT", "order": 0, "basis": "lagrange"}) + with pytest.raises(SpaceError, match="BDM has no nodes"): + resolve({"family": "BDM", "order": 1, "nodes": "gll"}) + + +@pytest.mark.parametrize("space, message", [ + ({"family": "CG", "order": 0}, "the lowest order of CG is 1"), + ({"family": "BDM", "order": 0}, "the lowest order of BDM is 1"), + ({"family": "RT", "order": -1}, "the lowest order of RT is 0"), + ({"family": "CG", "order": 2, "basis": "monomial"}, "CG has no monomial basis"), + ({"family": "CG", "order": 2, "basis": "chebyshev"}, "basis chebyshev is not one of"), + ({"family": "CG", "order": 3, "nodes": "chebyshev"}, "nodes chebyshev is not one of"), + ({"family": "CG", "order": 3, "basis": "bernstein", "nodes": "gll"}, "nodes belong to a lagrange basis"), + ({"family": "CG", "order": 3, "bernstein_operator": True}, "bernstein_operator belongs to a bernstein basis"), + ({"family": "CG", "order": 3, "nodez": "gll"}, "no key nodez"), +]) +def test_a_space_that_makes_no_sense_is_refused(space, message): + with pytest.raises(SpaceError, match=message): + resolve(space) + + +def test_proteus_status_is_information_not_a_rule(): + assert implemented_in_proteus({"family": "CG", "order": 5, "nodes": "gll"}) + assert implemented_in_proteus({"family": "RT", "order": 0}) and implemented_in_proteus({"family": "BDM", "order": 1}) + assert not implemented_in_proteus({"family": "RT", "order": 1}) + assert not implemented_in_proteus({"family": "N1curl", "order": 0}) + resolve({"family": "RT", "order": 1}) # still a well-formed space + + +@pytest.fixture(scope="module") +def example(): + return load_ymf(EXAMPLES / "poisson_spaces.ymf") + + +def test_the_example_states_the_spaces_and_loads(example): + by = {e["name"]: e["finite_element"] for e in example["solution_paths"]["discretizations"]} + assert by["P3_gll"]["fields"]["nodes"] == "gll" and by["P3_gll"]["geometry_order"] == 1 + assert by["P4_equispaced"]["fields"]["nodes"] == "equispaced" + assert by["P3_bernstein_exact"]["fields"]["bernstein_operator"] is False + for finite_element in by.values(): + resolve(finite_element["fields"]) + + +def test_a_bad_space_in_a_discretization_is_refused_on_check(example): + doc = copy.deepcopy(example) + entry = next(e for e in doc["solution_paths"]["discretizations"] if e["name"] == "P3_gll") + entry["finite_element"]["fields"]["nodes"] = "chebyshev" + with pytest.raises(VocabularyError, match=r"P3_gll\].finite_element.fields: nodes chebyshev"): + check(doc) + + +def test_the_geometry_order_is_at_least_one(example): + doc = copy.deepcopy(example) + entry = next(e for e in doc["solution_paths"]["discretizations"] if e["name"] == "P3_gll") + entry["finite_element"]["geometry_order"] = 0 + with pytest.raises(VocabularyError, match="geometry_order: 0"): + check(doc) + + +def test_the_hdiv_pair_loads_through_the_schema(tmp_path, example): + """RT0/DG0 is a mixed discretization; here only the finite_element block is exercised.""" + doc = copy.deepcopy(example) + entry = next(e for e in doc["solution_paths"]["discretizations"] if e["name"] == "P3_gll") + entry["finite_element"] = {"velocity": {"family": "RT", "order": 0}, "pressure": {"family": "DG", "order": 0}} + check(doc) # no VocabularyError + entry["finite_element"]["velocity"]["order"] = 1 + check(doc) # RT1 is well formed (proteus lacks it: information only) diff --git a/tools/check_dist.sh b/tools/check_dist.sh new file mode 100755 index 0000000..7c614df --- /dev/null +++ b/tools/check_dist.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Build ymf's sdist and wheel, check them, install the wheel into a fresh venv +# and run it. The same script runs in release.yml and by hand: +# +# tools/check_dist.sh [OUTDIR] # default: a new temporary directory +# +# Needs `python -m build` and `twine` (pip install build twine). Nothing is +# uploaded. The sdist must stay small (limit below) and carry no logs, HDF5 +# data, compiled files or CI files; a file that matters to the tests is +# tracked in git, so a failure here is a stray file or a missing prune in +# MANIFEST.in. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +OUT="${1:-$(mktemp -d)}" +LIMIT_KB="${YMF_SDIST_LIMIT_KB:-1024}" +mkdir -p "$OUT" +PY="${PYTHON:-python}" + +"$PY" -m build --outdir "$OUT/dist" "$ROOT" +"$PY" -m twine check --strict "$OUT"/dist/* + +SDIST="$(ls "$OUT"/dist/ymf-*.tar.gz)" +WHEEL="$(ls "$OUT"/dist/ymf-*.whl)" +KB=$(( $(wc -c < "$SDIST") / 1024 )) +echo "sdist: $SDIST (${KB} KB, limit ${LIMIT_KB} KB)" +echo "wheel: $WHEEL ($(( $(wc -c < "$WHEEL") / 1024 )) KB)" +[ "$KB" -le "$LIMIT_KB" ] || { echo "sdist too large"; exit 1; } + +# No accidental payload. +if tar tzf "$SDIST" | grep -E '\.(log|h5|so|pyc|o)$|\.coverage|/\.github/|\.DS_Store'; then + echo "unexpected files in the sdist (listed above)"; exit 1 +fi + +# The wheel carries the package and nothing else but its metadata. +if unzip -Z1 "$WHEEL" | grep -vE '^ymf/|^ymf-[^/]*\.dist-info/'; then + echo "unexpected files in the wheel (listed above)"; exit 1 +fi + +# Fresh venv, wheel only, run from a directory without the checkout on the path. +"$PY" -m venv "$OUT/venv" +"$OUT/venv/bin/python" -m pip install --quiet "${WHEEL}[frontend,examples]" +mkdir -p "$OUT/run" +cd "$OUT/run" +"$OUT/venv/bin/python" -I - "$ROOT" <<'PYEOF' +import sys, pathlib, ymf +root = pathlib.Path(sys.argv[1]) +print("import ymf", ymf.__version__, "from", ymf.__file__) +assert "site-packages" in ymf.__file__, "not the installed wheel" +assert ymf.__version__ not in ("0.0.0", "0.0.0+unknown"), "no version" +doc = ymf.load_ymf(root / "examples" / "poisson.ymf") +print("loaded examples/poisson.ymf:", type(doc).__name__) +PYEOF +"$OUT/venv/bin/ymf2xmf" --help > /dev/null +"$OUT/venv/bin/python" "$ROOT/examples/write_archive.py" > /dev/null +"$OUT/venv/bin/ymf2xmf" ymf-example-output/heat.ymf -o heat-check.xmf +echo "ok: build, twine check, wheel install, import, spec load, ymf2xmf" +echo "$OUT"