From 9b4f42a04563d09f37b3d5a1595ab6858debaa6e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 5 Aug 2026 12:52:57 +0200 Subject: [PATCH 1/4] docs[next]: add a shallow water model example notebook Port the NCAR/SWM shallow water benchmark to a single gt4py.next notebook, alongside a NumPy reference and the 16x16 reference state after the full 4000-step run. Periodicity is applied outside GT4Py for now, which keeps the example free of any src/ changes. --- examples/swm.ipynb | 443 +++++++++++++++++++++++++++++++++++++ examples/swm_numpy.py | 164 ++++++++++++++ examples/swm_reference.npz | Bin 0 -> 4785 bytes 3 files changed, 607 insertions(+) create mode 100644 examples/swm.ipynb create mode 100644 examples/swm_numpy.py create mode 100644 examples/swm_reference.npz diff --git a/examples/swm.ipynb b/examples/swm.ipynb new file mode 100644 index 0000000000..33c715dceb --- /dev/null +++ b/examples/swm.ipynb @@ -0,0 +1,443 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "GT4Py - GridTools Framework\n", + "\n", + "Copyright (c) 2014-2024, ETH Zurich\n", + "All rights reserved.\n", + "\n", + "Please, refer to the LICENSE file in the root directory.\n", + "SPDX-License-Identifier: BSD-3-Clause" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Shallow Water Model\n", + "\n", + "A doubly periodic shallow water model on an Arakawa C-grid, integrated with a leapfrog\n", + "scheme and a Robert-Asselin time filter. It is the NCAR\n", + "[SWM](https://github.com/NCAR/SWM) mini-app, a long-standing benchmark for comparing\n", + "programming models, written here as a single `gt4py.next` field operator.\n", + "\n", + "The prognostic equations are\n", + "\n", + "$$\n", + "\\frac{\\partial \\mathbf{V}}{\\partial t} + (\\zeta + f)\\,\\mathbf{k} \\times \\mathbf{V}\n", + " + \\nabla\\left(P + \\tfrac{1}{2}\\mathbf{V}\\cdot\\mathbf{V}\\right) = 0,\n", + "\\qquad\n", + "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", + "$$\n", + "\n", + "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975).\n", + "The four intermediates below are his mass fluxes $U$, $V$, potential vorticity $q$ and\n", + "Bernoulli function $H$, named `cu`, `cv`, `z`, `h` in the benchmark.\n", + "\n", + "**Provenance.** The *scheme* is from Sadourny (1975). The *configuration* --- the grid\n", + "spacing, time step, filter coefficient and initial condition --- is Paul Swarztrauber's\n", + "1984 NCAR benchmark setup, not a result from the paper." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "import gt4py.next as gtx\n", + "\n", + "import swm_numpy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Grid and backend\n", + "\n", + "Fields carry **one halo cell on every side**, so the domain runs from `-1` to `M+1`. All\n", + "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", + "the shifts inside the operators rather than by different array shapes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "I = gtx.Dimension(\"I\")\n", + "J = gtx.Dimension(\"J\")\n", + "\n", + "IJField = gtx.Field[gtx.Dims[I, J], gtx.float64]\n", + "\n", + "M = swm_numpy.M # 16\n", + "N = swm_numpy.N # 16\n", + "\n", + "DX = swm_numpy.DX # 100 km\n", + "DY = swm_numpy.DY\n", + "DT = swm_numpy.DT # 90 s\n", + "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient\n", + "\n", + "backend = None\n", + "# backend = gtx.gtfn_cpu\n", + "# backend = gtx.gtfn_gpu" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Differential operators\n", + "\n", + "Each operator comes in two variants that differ only in shift direction. The forward form\n", + "($+1$) maps an unstaggered quantity onto a staggered location, the backward form ($-1$)\n", + "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", + "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", + "\n", + "Keeping the two variants apart by hand is exactly the bookkeeping that\n", + "[staggered dimensions](../docs/development/ADRs/next/0026-Staggered_Dimensions.md) are\n", + "designed to remove; a follow-up rewrites these eight operators as four." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def avg_x(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next x-face.\"\"\"\n", + " return 0.5 * (f(I + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y(f: IJField) -> IJField:\n", + " \"\"\"Average onto the next y-face.\"\"\"\n", + " return 0.5 * (f(J + 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_x_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average an x-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(I - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def avg_y_staggered(f: IJField) -> IJField:\n", + " \"\"\"Average a y-staggered field back onto cell centres.\"\"\"\n", + " return 0.5 * (f(J - 1) + f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in x.\"\"\"\n", + " return (1.0 / dx) * (f(I + 1) - f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Forward difference in y.\"\"\"\n", + " return (1.0 / dy) * (f(J + 1) - f)\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_x_staggered(dx: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in x, for an x-staggered field.\"\"\"\n", + " return (1.0 / dx) * (f - f(I - 1))\n", + "\n", + "\n", + "@gtx.field_operator\n", + "def delta_y_staggered(dy: gtx.float64, f: IJField) -> IJField:\n", + " \"\"\"Backward difference in y, for a y-staggered field.\"\"\"\n", + " return (1.0 / dy) * (f - f(J - 1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The timestep\n", + "\n", + "One fused field operator produces all six updated fields. The first three are the leapfrog\n", + "update of the prognostic variables; the last three are the time-filtered previous level,\n", + "\n", + "$$ u^{\\text{old}} \\leftarrow u + \\alpha\\,(u^{\\text{new}} - 2u + u^{\\text{old}}) , $$\n", + "\n", + "which suppresses the computational mode of the leapfrog scheme." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def timestep(\n", + " u: IJField,\n", + " v: IJField,\n", + " p: IJField,\n", + " uold: IJField,\n", + " vold: IJField,\n", + " pold: IJField,\n", + " dx: gtx.float64,\n", + " dy: gtx.float64,\n", + " tdt: gtx.float64,\n", + " alpha: gtx.float64,\n", + ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", + " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", + " cu = avg_x(p) * u\n", + " cv = avg_y(p) * v\n", + " z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p))\n", + " h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v))\n", + "\n", + " unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt\n", + " vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt\n", + " pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt\n", + "\n", + " uold_new = u + alpha * (unew - 2.0 * u + uold)\n", + " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", + " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", + "\n", + " return unew, vnew, pnew, uold_new, vold_new, pold_new" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Periodicity\n", + "\n", + "The domain wraps in both directions. Here the halo is refreshed **outside** GT4Py, in\n", + "NumPy, after each step: the operator computes the interior only, and the halo is then\n", + "overwritten with the opposite edge.\n", + "\n", + "Rows are copied before columns, which is what fills the corners correctly.\n", + "\n", + "Expressing the wrap *inside* the field operator instead --- with `concat_where` over a\n", + "domain boundary --- is the subject of a follow-up; it needs shift offsets that are only\n", + "known at compile time rather than when the operator is traced." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", + " \"\"\"Refresh the one-cell halo of `field` in place from the opposite edge.\"\"\"\n", + " a = field.ndarray\n", + " a[0, :] = a[m, :]\n", + " a[m + 1, :] = a[1, :]\n", + " a[:, 0] = a[:, n]\n", + " a[:, n + 1] = a[:, 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Time loop\n", + "\n", + "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", + "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", + "with the filter switched off, which is how the leapfrog scheme is started." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def run(itmax: int, m: int = M, n: int = N) -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", + " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", + " domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", + " interior = gtx.domain({I: (0, m), J: (0, n)})\n", + "\n", + " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", + "\n", + " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", + " return gtx.as_field(domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend)\n", + "\n", + " u, v, p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " uold, vold, pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " unew, vnew, pnew = (gtx.zeros(domain, dtype=gtx.float64, allocator=backend) for _ in range(3))\n", + "\n", + " for cycle in range(itmax):\n", + " tdt = DT if cycle == 0 else 2.0 * DT\n", + " alpha = 0.0 if cycle == 0 else ALPHA\n", + "\n", + " timestep(\n", + " u,\n", + " v,\n", + " p,\n", + " uold,\n", + " vold,\n", + " pold,\n", + " DX,\n", + " DY,\n", + " tdt,\n", + " alpha,\n", + " out=(unew, vnew, pnew, uold, vold, pold),\n", + " domain=interior,\n", + " offset_provider={},\n", + " )\n", + "\n", + " for field in (unew, vnew, pnew):\n", + " apply_periodic(field, m, n)\n", + "\n", + " u, unew = unew, u\n", + " v, vnew = vnew, v\n", + " p, pnew = pnew, p\n", + "\n", + " return u, v, p\n", + "\n", + "\n", + "def interior_of(field: gtx.Field, m: int = M, n: int = N) -> np.ndarray:\n", + " return field.asnumpy()[1 : m + 1, 1 : n + 1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against NumPy\n", + "\n", + "The companion module `swm_numpy.py` implements the same scheme with `numpy.roll`, which\n", + "gives periodicity for free and needs no halo at all. Agreement between the two is a check\n", + "that the halo bookkeeping here is right." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "STEPS = 100\n", + "\n", + "# The two implementations sum the same terms in a different order, so they agree to\n", + "# rounding rather than bit-for-bit. Tolerances are absolute because u and v cross zero.\n", + "ATOL_UV = 1e-11 # peak |u|, |v| ~ 4\n", + "ATOL_P = 1e-8 # peak |p| ~ 5e4\n", + "\n", + "\n", + "def test_matches_numpy():\n", + " u, v, p = run(STEPS)\n", + " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", + "\n", + " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(v), v_ref, atol=ATOL_UV)\n", + " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", + "\n", + "\n", + "test_matches_numpy()\n", + "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Validation against the NCAR reference\n", + "\n", + "`swm_reference.npz` holds `u`, `v`, `p` after the full 4000-step benchmark, taken from\n", + "[NCAR/SWM](https://github.com/NCAR/SWM) `ref/16x16` (Apache-2.0). Reproducing it end to\n", + "end is the real correctness check, but it takes far longer than a notebook should in CI,\n", + "so it is opt-in." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "RUN_FULL_BENCHMARK = False\n", + "\n", + "\n", + "def test_matches_reference():\n", + " u, v, p = run(swm_numpy.ITMAX)\n", + " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", + " interior_of(u), interior_of(v), interior_of(p)\n", + " )\n", + "\n", + " reference = np.load(\"swm_reference.npz\")\n", + " np.testing.assert_allclose(u_out, reference[\"u\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(v_out, reference[\"v\"], atol=ATOL_UV)\n", + " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", + "\n", + "\n", + "if RUN_FULL_BENCHMARK:\n", + " test_matches_reference()\n", + " print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The flow\n", + "\n", + "The initial stream function sets up a pair of counter-rotating vortices; after a few\n", + "hundred steps the pressure field has developed the finer structure the scheme is meant to\n", + "handle without spurious accumulation of energy at the grid scale." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "\n", + "u, v, p = run(STEPS)\n", + "\n", + "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", + "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", + " image = ax.contourf(interior_of(field).T, levels=20)\n", + " ax.set_title(f\"{name} after {STEPS} steps\")\n", + " ax.set_aspect(\"equal\")\n", + " fig.colorbar(image, ax=ax)\n", + "fig.tight_layout()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## References\n", + "\n", + "Sadourny, R. (1975). The dynamics of finite-difference models of the shallow-water\n", + "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", + "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", + "\n", + "The benchmark descends from Sadourny's scheme via Paul Swarztrauber's 1984 NCAR\n", + "implementation, and is maintained today as [NCAR/SWM](https://github.com/NCAR/SWM)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/examples/swm_numpy.py b/examples/swm_numpy.py new file mode 100644 index 0000000000..7db27aa980 --- /dev/null +++ b/examples/swm_numpy.py @@ -0,0 +1,164 @@ +# GT4Py - GridTools Framework +# +# Copyright (c) 2014-2024, ETH Zurich +# All rights reserved. +# +# Please, refer to the LICENSE file in the root directory. +# SPDX-License-Identifier: BSD-3-Clause + +""" +NumPy reference for the shallow water model example. + +Companion to `swm.ipynb`. The model is doubly periodic, so periodicity is expressed here +with `numpy.roll` on interior-only arrays of shape `(M, N)` -- there is no halo. The +notebook's GT4Py version instead carries one halo cell per side and updates it explicitly, +which is what makes the two implementations worth comparing. +""" + +from __future__ import annotations + +import numpy as np + + +# Model constants of the NCAR/SWM benchmark configuration. +M = 16 +N = 16 +DX = 100000.0 +DY = 100000.0 +DT = 90.0 +ALPHA = 0.001 +A = 1000000.0 +P_MEAN = 50000.0 +ITMAX = 4000 + + +def avg_x(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=0) + f) + + +def avg_y(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, -1, axis=1) + f) + + +def avg_x_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=0) + f) + + +def avg_y_staggered(f: np.ndarray) -> np.ndarray: + return 0.5 * (np.roll(f, 1, axis=1) + f) + + +def delta_x(dx: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=0) - f) / dx + + +def delta_y(dy: float, f: np.ndarray) -> np.ndarray: + return (np.roll(f, -1, axis=1) - f) / dy + + +def delta_x_staggered(dx: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=0)) / dx + + +def delta_y_staggered(dy: float, f: np.ndarray) -> np.ndarray: + return (f - np.roll(f, 1, axis=1)) / dy + + +def initial_conditions( + m: int = M, n: int = N, dx: float = DX, dy: float = DY, a: float = A, p_mean: float = P_MEAN +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Return the initial `u`, `v`, `p` on the interior grid, each of shape `(m, n)`. + + The velocity field is derived from a doubly periodic stream function + `psi = a * sin(2*pi*(i+0.5)/m) * sin(2*pi*(j+0.5)/n)`. + """ + d_i = 2.0 * np.pi / m + d_j = 2.0 * np.pi / n + el = n * dx + pcf = (np.pi * np.pi * a * a) / (el * el) + + psi = ( + a + * np.sin((np.arange(0, m + 1).reshape(-1, 1) + 0.5) * d_i) + * np.sin((np.arange(0, n + 1) + 0.5) * d_j) + ) + p = ( + pcf + * (np.cos(2.0 * np.arange(0, m).reshape(-1, 1) * d_i) + np.cos(2.0 * np.arange(0, n) * d_j)) + + p_mean + ) + u = -(psi[1:, 1:] - psi[1:, :-1]) / dy + v = (psi[1:, 1:] - psi[:-1, 1:]) / dx + + return u, v, p + + +def timestep( + u: np.ndarray, + v: np.ndarray, + p: np.ndarray, + uold: np.ndarray, + vold: np.ndarray, + pold: np.ndarray, + dx: float, + dy: float, + tdt: float, + alpha: float, +) -> tuple[np.ndarray, ...]: + """One leapfrog step with a Robert-Asselin time filter. Returns the six updated fields.""" + cu = avg_x(p) * u + cv = avg_y(p) * v + z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p)) + h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v)) + + unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt + vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt + pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt + + uold_new = u + alpha * (unew - 2.0 * u + uold) + vold_new = v + alpha * (vnew - 2.0 * v + vold) + pold_new = p + alpha * (pnew - 2.0 * p + pold) + + return unew, vnew, pnew, uold_new, vold_new, pold_new + + +def run( + itmax: int, + m: int = M, + n: int = N, + dx: float = DX, + dy: float = DY, + dt: float = DT, + alpha: float = ALPHA, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Integrate `itmax` steps and return the final interior `u`, `v`, `p`.""" + u, v, p = initial_conditions(m, n, dx, dy) + uold, vold, pold = u.copy(), v.copy(), p.copy() + + for cycle in range(itmax): + # The first step is forward Euler and unfiltered; afterwards leapfrog with tdt = 2*dt. + tdt = dt if cycle == 0 else 2.0 * dt + step_alpha = 0.0 if cycle == 0 else alpha + unew, vnew, pnew, uold, vold, pold = timestep( + u, v, p, uold, vold, pold, dx, dy, tdt, step_alpha + ) + u, v, p = unew, vnew, pnew + + return u, v, p + + +def to_reference_layout( + u: np.ndarray, v: np.ndarray, p: np.ndarray +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Convert interior `(M, N)` fields to the `(M+1, N+1)` layout of the NCAR/SWM dumps. + + The extra row and column are the periodic images the original Fortran carried + explicitly; which side they sit on differs per field because of the C-grid staggering. + """ + return ( + np.pad(u, ((1, 0), (0, 1)), mode="wrap"), + np.pad(v, ((0, 1), (1, 0)), mode="wrap"), + np.pad(p, ((0, 1), (0, 1)), mode="wrap"), + ) diff --git a/examples/swm_reference.npz b/examples/swm_reference.npz new file mode 100644 index 0000000000000000000000000000000000000000..6a9ca4af2f80200ce698e0040e3fd68b90eaacd2 GIT binary patch literal 4785 zcmZWtc{J2*`&SGxm4rwlTPoopkt|6P0gBQAtyzX)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)iC3ULIZ^)Ryb*d;bLRe^rseZ~y=R literal 0 HcmV?d00001 From 5b7c29956e158f763c26df13669ca1ceee5a497b Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 5 Aug 2026 13:02:35 +0200 Subject: [PATCH 2/4] docs[next]: attribute the configuration to NCAR/SWM, not to a person The scheme is verified against Sadourny (1975) Eq. 4 -- cu, cv, h, z are his U, V, H and eta term for term. The constants are not from the paper, and the 'Swarztrauber 1984' attribution came from a code comment in NCAR/SWM rather than from any reference, so point at the benchmark repo instead. --- examples/swm.ipynb | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 33c715dceb..6f851ea438 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -33,13 +33,22 @@ "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", "$$\n", "\n", - "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975).\n", - "The four intermediates below are his mass fluxes $U$, $V$, potential vorticity $q$ and\n", - "Bernoulli function $H$, named `cu`, `cv`, `z`, `h` in the benchmark.\n", + "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", + "his Eq. 4). The four intermediates below are his mass fluxes and diagnostics,\n", "\n", - "**Provenance.** The *scheme* is from Sadourny (1975). The *configuration* --- the grid\n", - "spacing, time step, filter coefficient and initial condition --- is Paul Swarztrauber's\n", - "1984 NCAR benchmark setup, not a result from the paper." + "$$\n", + "U = \\overline{P}^{\\,x} u, \\qquad V = \\overline{P}^{\\,y} v, \\qquad\n", + "H = P + \\tfrac{1}{2}\\left(\\overline{u^2}^{\\,x} + \\overline{v^2}^{\\,y}\\right), \\qquad\n", + "\\eta = \\frac{\\delta_x v - \\delta_y u}{\\overline{P}^{\\,xy}} ,\n", + "$$\n", + "\n", + "named `cu`, `cv`, `h` and `z` here.\n", + "\n", + "**Provenance.** The *scheme* is Sadourny's. The *configuration* --- grid size, spacing,\n", + "time step, filter coefficient and initial condition --- comes from the\n", + "[NCAR/SWM](https://github.com/NCAR/SWM) benchmark rather than from the paper; Sadourny\n", + "damps the leapfrog scheme by averaging odd and even time levels every $N$ steps, not with\n", + "the per-step Robert-Asselin filter used here." ] }, { @@ -423,8 +432,9 @@ "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", "\n", - "The benchmark descends from Sadourny's scheme via Paul Swarztrauber's 1984 NCAR\n", - "implementation, and is maintained today as [NCAR/SWM](https://github.com/NCAR/SWM)." + "The benchmark itself --- its configuration, initial condition and reference data --- is\n", + "[NCAR/SWM](https://github.com/NCAR/SWM), which implements the same model across a range of\n", + "languages and programming models." ] } ], From ef0c18410fa5c051c66680ce951d4644669091f9 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 5 Aug 2026 13:43:23 +0200 Subject: [PATCH 3/4] feat[next]: allow runtime shift offsets, use them for SWM periodicity Cartesian shift offsets had to be literals, which meant a periodic wrap by a runtime grid size could not be written in the DSL. Relax the frontend to accept a non-literal integral offset, lower it, and canonicalize the resulting literal to an OffsetLiteral so domain inference sees a real offset rather than the unknown-access sentinel. Uses it in the shallow water example, whose halo update moves from NumPy into the field operator. Updates test_premap_cartesian_non_literal_offset, which pinned the old rejection, and adds the SUB and non-integral cases. --- examples/swm.ipynb | 128 ++++++++++++++---- .../ffront/foast_passes/type_deduction.py | 17 ++- src/gt4py/next/ffront/foast_to_gtir.py | 14 ++ .../iterator/transforms/normalize_shifts.py | 28 ++++ .../next/iterator/transforms/pass_manager.py | 7 +- .../ffront_tests/test_foast_to_gtir.py | 32 ++++- 6 files changed, 191 insertions(+), 35 deletions(-) diff --git a/examples/swm.ipynb b/examples/swm.ipynb index 6f851ea438..edfe59d5be 100644 --- a/examples/swm.ipynb +++ b/examples/swm.ipynb @@ -60,6 +60,7 @@ "import numpy as np\n", "\n", "import gt4py.next as gtx\n", + "from gt4py.next.experimental import concat_where\n", "\n", "import swm_numpy" ] @@ -169,6 +170,41 @@ " return (1.0 / dy) * (f - f(J - 1))" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Periodicity\n", + "\n", + "The domain wraps in both directions, and the wrap is expressed **inside** the DSL:\n", + "`concat_where` selects a sub-domain and takes its values from the opposite edge. At\n", + "$i = -1$ the field is read at $i + M$, at $i = M$ at $i - M$, and likewise in $j$.\n", + "\n", + "Each `concat_where` rebinds `f`, so the $j$ pass sees the already-$i$-corrected field\n", + "and the four corners come out right. Writing the four as one simultaneous expression\n", + "would leave them wrong.\n", + "\n", + "Note that the shift distance is `m`, a runtime argument rather than a literal. Domain\n", + "inference resolves the composition: at $i = -1$ the result comes from $i = M-1$, so the\n", + "interior is all that is ever demanded of the operator that produced it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def make_periodic(f: IJField, m: gtx.int32, n: gtx.int32) -> IJField:\n", + " \"\"\"Fill the one-cell halo of `f` from the opposite edge.\"\"\"\n", + " f = concat_where(I == -1, f(I + m), f)\n", + " f = concat_where(I == m, f(I - m), f)\n", + " f = concat_where(J == -1, f(J + n), f)\n", + " f = concat_where(J == n, f(J - n), f)\n", + " return f" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -201,6 +237,8 @@ " dy: gtx.float64,\n", " tdt: gtx.float64,\n", " alpha: gtx.float64,\n", + " m: gtx.int32,\n", + " n: gtx.int32,\n", ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", " cu = avg_x(p) * u\n", @@ -216,24 +254,23 @@ " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", "\n", - " return unew, vnew, pnew, uold_new, vold_new, pold_new" + " return (\n", + " make_periodic(unew, m, n),\n", + " make_periodic(vnew, m, n),\n", + " make_periodic(pnew, m, n),\n", + " uold_new,\n", + " vold_new,\n", + " pold_new,\n", + " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Periodicity\n", - "\n", - "The domain wraps in both directions. Here the halo is refreshed **outside** GT4Py, in\n", - "NumPy, after each step: the operator computes the interior only, and the halo is then\n", - "overwritten with the opposite edge.\n", - "\n", - "Rows are copied before columns, which is what fills the corners correctly.\n", - "\n", - "Expressing the wrap *inside* the field operator instead --- with `concat_where` over a\n", - "domain boundary --- is the subject of a follow-up; it needs shift offsets that are only\n", - "known at compile time rather than when the operator is traced." + "The prognostic fields are written over the whole domain, halo included, while the\n", + "filtered levels only need the interior. A `program` lets each output declare its own\n", + "domain." ] }, { @@ -242,13 +279,47 @@ "metadata": {}, "outputs": [], "source": [ - "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", - " \"\"\"Refresh the one-cell halo of `field` in place from the opposite edge.\"\"\"\n", - " a = field.ndarray\n", - " a[0, :] = a[m, :]\n", - " a[m + 1, :] = a[1, :]\n", - " a[:, 0] = a[:, n]\n", - " a[:, n + 1] = a[:, 1]" + "@gtx.program\n", + "def timestep_program(\n", + " u: IJField,\n", + " v: IJField,\n", + " p: IJField,\n", + " uold: IJField,\n", + " vold: IJField,\n", + " pold: IJField,\n", + " dx: gtx.float64,\n", + " dy: gtx.float64,\n", + " tdt: gtx.float64,\n", + " alpha: gtx.float64,\n", + " unew: IJField,\n", + " vnew: IJField,\n", + " pnew: IJField,\n", + " m: gtx.int32,\n", + " n: gtx.int32,\n", + "):\n", + " timestep(\n", + " u,\n", + " v,\n", + " p,\n", + " uold,\n", + " vold,\n", + " pold,\n", + " dx,\n", + " dy,\n", + " tdt,\n", + " alpha,\n", + " m,\n", + " n,\n", + " out=(unew, vnew, pnew, uold, vold, pold),\n", + " domain=(\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (0, m), J: (0, n)},\n", + " {I: (0, m), J: (0, n)},\n", + " {I: (0, m), J: (0, n)},\n", + " ),\n", + " )" ] }, { @@ -259,7 +330,9 @@ "\n", "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", - "with the filter switched off, which is how the leapfrog scheme is started." + "with the filter switched off, which is how the leapfrog scheme is started.\n", + "\n", + "Nothing here touches the halo any more --- it is filled inside the timestep." ] }, { @@ -271,7 +344,6 @@ "def run(itmax: int, m: int = M, n: int = N) -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", " domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", - " interior = gtx.domain({I: (0, m), J: (0, n)})\n", "\n", " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", "\n", @@ -282,11 +354,13 @@ " uold, vold, pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", " unew, vnew, pnew = (gtx.zeros(domain, dtype=gtx.float64, allocator=backend) for _ in range(3))\n", "\n", + " program = timestep_program.with_backend(backend) if backend is not None else timestep_program\n", + "\n", " for cycle in range(itmax):\n", " tdt = DT if cycle == 0 else 2.0 * DT\n", " alpha = 0.0 if cycle == 0 else ALPHA\n", "\n", - " timestep(\n", + " program(\n", " u,\n", " v,\n", " p,\n", @@ -297,14 +371,14 @@ " DY,\n", " tdt,\n", " alpha,\n", - " out=(unew, vnew, pnew, uold, vold, pold),\n", - " domain=interior,\n", + " unew,\n", + " vnew,\n", + " pnew,\n", + " m,\n", + " n,\n", " offset_provider={},\n", " )\n", "\n", - " for field in (unew, vnew, pnew):\n", - " apply_periodic(field, m, n)\n", - "\n", " u, unew = unew, u\n", " v, vnew = vnew, v\n", " p, pnew = pnew, p\n", diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index a96533f36a..4ec31a5c8e 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -680,11 +680,18 @@ def _deduce_binop_type( ): # e.g. `IDim+1` or `IDim+0.5` if not isinstance(right, foast.Constant): - raise errors.DSLError( - right.location, - "Cartesian offsets are only supported with a literal right-hand side, " - "e.g. 'IDim + 1', but not 'IDim + expr'.", - ) + # e.g. `IDim+offset` with a runtime `offset`; a non-literal offset can not be + # resolved to a staggered dimension, hence only integral offsets are allowed. + if not type_info.is_integral(right.type): + raise errors.DSLError( + right.location, + "Cartesian offsets with a non-literal right-hand side must be integral, " + f"but '{right.type}' is not.", + hints=[ + "Use a literal such as 'IDim + 0.5' to shift to the staggered dimension." + ], + ) + return ts.OffsetType(source=left.type.dim, target=(left.type.dim,)) offset_index = right.value if node.op == dialect_ast_enums.BinaryOperator.SUB: offset_index *= -1 diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 10bc754526..569d963146 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -322,6 +322,20 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: ) ) )(current_expr) + # `field(Dim + expr)` (where `expr` is a runtime integer) + case foast.BinOp( + op=dialect_ast_enums.BinaryOperator.ADD | dialect_ast_enums.BinaryOperator.SUB, + left=foast.LocatedNode(type=ts.DimensionType(dim=common.Dimension() as dim)), + right=right, + ): + offset = self.visit(right, **kwargs) + if arg.op == dialect_ast_enums.BinaryOperator.SUB: + offset = im.call("neg")(offset) + current_expr = im.as_fieldop( + im.lambda_("__it")( + im.deref(im.shift(im.cartesian_offset(dim), offset)("__it")) + ) + )(current_expr) # `field(Off)` case foast.Name(id=offset_name): # only a single unstructured shift is supported so returning here is fine even though we diff --git a/src/gt4py/next/iterator/transforms/normalize_shifts.py b/src/gt4py/next/iterator/transforms/normalize_shifts.py index ad3a602692..47b8f96d02 100644 --- a/src/gt4py/next/iterator/transforms/normalize_shifts.py +++ b/src/gt4py/next/iterator/transforms/normalize_shifts.py @@ -8,6 +8,8 @@ from gt4py.eve import NodeTranslator, PreserveLocationVisitor from gt4py.next.iterator import ir +from gt4py.next.iterator.ir_utils import common_pattern_matcher as cpm +from gt4py.next.type_system import type_specifications as ts class NormalizeShifts(PreserveLocationVisitor, NodeTranslator): @@ -32,3 +34,29 @@ def visit_FunCall(self, node: ir.FunCall): args=node.args[0].args, ) return node + + +class CanonicalizeShiftOffsets(PreserveLocationVisitor, NodeTranslator): + """ + Turn integral `Literal` shift offsets into `OffsetLiteral`s. + + A shift offset that is only known after inlining, e.g. a static program argument used as in + `field(IDim + offset)`, reaches the shift as an `ir.Literal`. Downstream consumers (shift + tracing, backend lowering) expect the canonical `ir.OffsetLiteral` that `ir_makers.shift` + produces for offsets that are literal from the start. + """ + + def visit_FunCall(self, node: ir.FunCall) -> ir.Node: + node = self.generic_visit(node) + if cpm.is_call_to(node, "shift"): + return ir.FunCall( + fun=node.fun, + args=[ + ir.OffsetLiteral(value=int(arg.value)) + if isinstance(arg, ir.Literal) + and arg.type.kind in (ts.ScalarKind.INT32, ts.ScalarKind.INT64) + else arg + for arg in node.args + ], + ) + return node diff --git a/src/gt4py/next/iterator/transforms/pass_manager.py b/src/gt4py/next/iterator/transforms/pass_manager.py index f8b3aa22eb..788d62b0e0 100644 --- a/src/gt4py/next/iterator/transforms/pass_manager.py +++ b/src/gt4py/next/iterator/transforms/pass_manager.py @@ -34,7 +34,10 @@ from gt4py.next.iterator.transforms.inline_lambdas import InlineLambdas from gt4py.next.iterator.transforms.inline_scalar import InlineScalar from gt4py.next.iterator.transforms.merge_let import MergeLet -from gt4py.next.iterator.transforms.normalize_shifts import NormalizeShifts +from gt4py.next.iterator.transforms.normalize_shifts import ( + CanonicalizeShiftOffsets, + NormalizeShifts, +) from gt4py.next.iterator.transforms.unroll_reduce import UnrollReduce from gt4py.next.iterator.type_system.inference import infer @@ -181,6 +184,7 @@ def apply_common_transforms( ) # domain inference does not support dynamic offsets yet ir = infer_domain_ops.InferDomainOps.apply(ir) ir = concat_where.canonicalize_domain_argument(ir) + ir = CanonicalizeShiftOffsets().visit(ir) ir = infer_domain.infer_program( ir, @@ -300,6 +304,7 @@ def apply_fieldview_transforms( ir = infer_domain_ops.InferDomainOps.apply(ir) ir = concat_where.canonicalize_domain_argument(ir) ir = ConstantFolding.apply(ir) # type: ignore[assignment] # always an itir.Program + ir = CanonicalizeShiftOffsets().visit(ir) ir = infer_domain.infer_program( ir, diff --git a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py index 407088e4f8..18cba93c30 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_foast_to_gtir.py @@ -121,10 +121,38 @@ def foo(inp: gtx.Field[[TDim], float64]): def test_premap_cartesian_non_literal_offset(): - def foo(inp: gtx.Field[[TDim], float64], i: int): + # a non-literal offset stays within the dimension: without a literal there is no + # fractional part to resolve to the staggered counterpart + def foo(inp: gtx.Field[[TDim], float64], i: gtx.int32): return inp(TDim + i) - with pytest.raises(errors.DSLError, match="literal right-hand side"): + reference = im.as_fieldop( + im.lambda_("__it")(im.deref(im.shift(im.cartesian_offset(TDim), "i")("__it"))) + )("inp") + + lowered = FieldOperatorLowering.apply(FieldOperatorParser.apply_to_function(foo)) + assert lowered.expr == reference + + +def test_premap_cartesian_non_literal_offset_negated(): + def foo(inp: gtx.Field[[TDim], float64], i: gtx.int32): + return inp(TDim - i) + + reference = im.as_fieldop( + im.lambda_("__it")( + im.deref(im.shift(im.cartesian_offset(TDim), im.call("neg")("i"))("__it")) + ) + )("inp") + + lowered = FieldOperatorLowering.apply(FieldOperatorParser.apply_to_function(foo)) + assert lowered.expr == reference + + +def test_premap_cartesian_non_literal_offset_must_be_integral(): + def foo(inp: gtx.Field[[TDim], float64], x: gtx.float64): + return inp(TDim + x) + + with pytest.raises(errors.DSLError, match="must be integral"): FieldOperatorParser.apply_to_function(foo) From a1316b768619df05714c11b9a09e5a769d945bbe Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 13:51:22 +0000 Subject: [PATCH 4/4] docs[next]: fill the SWM halo inside the field operator, in examples/swm Port of the periodicity change to the example as merged in #3038: a make_periodic field operator with runtime shifts f(I + m), a program with per-output domains, m and n as static parameters so that the jit backends can shift by them, and no halo refresh on the host. The comparison now times complete steps. The top-level copies of the example from #2749 are removed. --- examples/swm.ipynb | 527 ------------------------------------- examples/swm/swm.ipynb | 158 +++++++---- examples/swm_numpy.py | 164 ------------ examples/swm_reference.npz | Bin 4785 -> 0 bytes 4 files changed, 112 insertions(+), 737 deletions(-) delete mode 100644 examples/swm.ipynb delete mode 100644 examples/swm_numpy.py delete mode 100644 examples/swm_reference.npz diff --git a/examples/swm.ipynb b/examples/swm.ipynb deleted file mode 100644 index edfe59d5be..0000000000 --- a/examples/swm.ipynb +++ /dev/null @@ -1,527 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "GT4Py - GridTools Framework\n", - "\n", - "Copyright (c) 2014-2024, ETH Zurich\n", - "All rights reserved.\n", - "\n", - "Please, refer to the LICENSE file in the root directory.\n", - "SPDX-License-Identifier: BSD-3-Clause" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Shallow Water Model\n", - "\n", - "A doubly periodic shallow water model on an Arakawa C-grid, integrated with a leapfrog\n", - "scheme and a Robert-Asselin time filter. It is the NCAR\n", - "[SWM](https://github.com/NCAR/SWM) mini-app, a long-standing benchmark for comparing\n", - "programming models, written here as a single `gt4py.next` field operator.\n", - "\n", - "The prognostic equations are\n", - "\n", - "$$\n", - "\\frac{\\partial \\mathbf{V}}{\\partial t} + (\\zeta + f)\\,\\mathbf{k} \\times \\mathbf{V}\n", - " + \\nabla\\left(P + \\tfrac{1}{2}\\mathbf{V}\\cdot\\mathbf{V}\\right) = 0,\n", - "\\qquad\n", - "\\frac{\\partial P}{\\partial t} + \\nabla\\cdot(P\\mathbf{V}) = 0 ,\n", - "$$\n", - "\n", - "discretised with the potential-enstrophy-conserving finite differences of Sadourny (1975,\n", - "his Eq. 4). The four intermediates below are his mass fluxes and diagnostics,\n", - "\n", - "$$\n", - "U = \\overline{P}^{\\,x} u, \\qquad V = \\overline{P}^{\\,y} v, \\qquad\n", - "H = P + \\tfrac{1}{2}\\left(\\overline{u^2}^{\\,x} + \\overline{v^2}^{\\,y}\\right), \\qquad\n", - "\\eta = \\frac{\\delta_x v - \\delta_y u}{\\overline{P}^{\\,xy}} ,\n", - "$$\n", - "\n", - "named `cu`, `cv`, `h` and `z` here.\n", - "\n", - "**Provenance.** The *scheme* is Sadourny's. The *configuration* --- grid size, spacing,\n", - "time step, filter coefficient and initial condition --- comes from the\n", - "[NCAR/SWM](https://github.com/NCAR/SWM) benchmark rather than from the paper; Sadourny\n", - "damps the leapfrog scheme by averaging odd and even time levels every $N$ steps, not with\n", - "the per-step Robert-Asselin filter used here." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "\n", - "import gt4py.next as gtx\n", - "from gt4py.next.experimental import concat_where\n", - "\n", - "import swm_numpy" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Grid and backend\n", - "\n", - "Fields carry **one halo cell on every side**, so the domain runs from `-1` to `M+1`. All\n", - "three prognostic fields share this one index space; the C-grid staggering is expressed by\n", - "the shifts inside the operators rather than by different array shapes." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "I = gtx.Dimension(\"I\")\n", - "J = gtx.Dimension(\"J\")\n", - "\n", - "IJField = gtx.Field[gtx.Dims[I, J], gtx.float64]\n", - "\n", - "M = swm_numpy.M # 16\n", - "N = swm_numpy.N # 16\n", - "\n", - "DX = swm_numpy.DX # 100 km\n", - "DY = swm_numpy.DY\n", - "DT = swm_numpy.DT # 90 s\n", - "ALPHA = swm_numpy.ALPHA # Robert-Asselin filter coefficient\n", - "\n", - "backend = None\n", - "# backend = gtx.gtfn_cpu\n", - "# backend = gtx.gtfn_gpu" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Differential operators\n", - "\n", - "Each operator comes in two variants that differ only in shift direction. The forward form\n", - "($+1$) maps an unstaggered quantity onto a staggered location, the backward form ($-1$)\n", - "maps back. Which one a term needs is fixed by where its operands live: `p` and `h` sit at\n", - "cell centres, `u` and `cu` on $x$-faces, `v` and `cv` on $y$-faces, and `z` on corners.\n", - "\n", - "Keeping the two variants apart by hand is exactly the bookkeeping that\n", - "[staggered dimensions](../docs/development/ADRs/next/0026-Staggered_Dimensions.md) are\n", - "designed to remove; a follow-up rewrites these eight operators as four." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "@gtx.field_operator\n", - "def avg_x(f: IJField) -> IJField:\n", - " \"\"\"Average onto the next x-face.\"\"\"\n", - " return 0.5 * (f(I + 1) + f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def avg_y(f: IJField) -> IJField:\n", - " \"\"\"Average onto the next y-face.\"\"\"\n", - " return 0.5 * (f(J + 1) + f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def avg_x_staggered(f: IJField) -> IJField:\n", - " \"\"\"Average an x-staggered field back onto cell centres.\"\"\"\n", - " return 0.5 * (f(I - 1) + f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def avg_y_staggered(f: IJField) -> IJField:\n", - " \"\"\"Average a y-staggered field back onto cell centres.\"\"\"\n", - " return 0.5 * (f(J - 1) + f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def delta_x(dx: gtx.float64, f: IJField) -> IJField:\n", - " \"\"\"Forward difference in x.\"\"\"\n", - " return (1.0 / dx) * (f(I + 1) - f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def delta_y(dy: gtx.float64, f: IJField) -> IJField:\n", - " \"\"\"Forward difference in y.\"\"\"\n", - " return (1.0 / dy) * (f(J + 1) - f)\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def delta_x_staggered(dx: gtx.float64, f: IJField) -> IJField:\n", - " \"\"\"Backward difference in x, for an x-staggered field.\"\"\"\n", - " return (1.0 / dx) * (f - f(I - 1))\n", - "\n", - "\n", - "@gtx.field_operator\n", - "def delta_y_staggered(dy: gtx.float64, f: IJField) -> IJField:\n", - " \"\"\"Backward difference in y, for a y-staggered field.\"\"\"\n", - " return (1.0 / dy) * (f - f(J - 1))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Periodicity\n", - "\n", - "The domain wraps in both directions, and the wrap is expressed **inside** the DSL:\n", - "`concat_where` selects a sub-domain and takes its values from the opposite edge. At\n", - "$i = -1$ the field is read at $i + M$, at $i = M$ at $i - M$, and likewise in $j$.\n", - "\n", - "Each `concat_where` rebinds `f`, so the $j$ pass sees the already-$i$-corrected field\n", - "and the four corners come out right. Writing the four as one simultaneous expression\n", - "would leave them wrong.\n", - "\n", - "Note that the shift distance is `m`, a runtime argument rather than a literal. Domain\n", - "inference resolves the composition: at $i = -1$ the result comes from $i = M-1$, so the\n", - "interior is all that is ever demanded of the operator that produced it." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "@gtx.field_operator\n", - "def make_periodic(f: IJField, m: gtx.int32, n: gtx.int32) -> IJField:\n", - " \"\"\"Fill the one-cell halo of `f` from the opposite edge.\"\"\"\n", - " f = concat_where(I == -1, f(I + m), f)\n", - " f = concat_where(I == m, f(I - m), f)\n", - " f = concat_where(J == -1, f(J + n), f)\n", - " f = concat_where(J == n, f(J - n), f)\n", - " return f" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The timestep\n", - "\n", - "One fused field operator produces all six updated fields. The first three are the leapfrog\n", - "update of the prognostic variables; the last three are the time-filtered previous level,\n", - "\n", - "$$ u^{\\text{old}} \\leftarrow u + \\alpha\\,(u^{\\text{new}} - 2u + u^{\\text{old}}) , $$\n", - "\n", - "which suppresses the computational mode of the leapfrog scheme." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "@gtx.field_operator\n", - "def timestep(\n", - " u: IJField,\n", - " v: IJField,\n", - " p: IJField,\n", - " uold: IJField,\n", - " vold: IJField,\n", - " pold: IJField,\n", - " dx: gtx.float64,\n", - " dy: gtx.float64,\n", - " tdt: gtx.float64,\n", - " alpha: gtx.float64,\n", - " m: gtx.int32,\n", - " n: gtx.int32,\n", - ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", - " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", - " cu = avg_x(p) * u\n", - " cv = avg_y(p) * v\n", - " z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p))\n", - " h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v))\n", - "\n", - " unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt\n", - " vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt\n", - " pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt\n", - "\n", - " uold_new = u + alpha * (unew - 2.0 * u + uold)\n", - " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", - " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", - "\n", - " return (\n", - " make_periodic(unew, m, n),\n", - " make_periodic(vnew, m, n),\n", - " make_periodic(pnew, m, n),\n", - " uold_new,\n", - " vold_new,\n", - " pold_new,\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The prognostic fields are written over the whole domain, halo included, while the\n", - "filtered levels only need the interior. A `program` lets each output declare its own\n", - "domain." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "@gtx.program\n", - "def timestep_program(\n", - " u: IJField,\n", - " v: IJField,\n", - " p: IJField,\n", - " uold: IJField,\n", - " vold: IJField,\n", - " pold: IJField,\n", - " dx: gtx.float64,\n", - " dy: gtx.float64,\n", - " tdt: gtx.float64,\n", - " alpha: gtx.float64,\n", - " unew: IJField,\n", - " vnew: IJField,\n", - " pnew: IJField,\n", - " m: gtx.int32,\n", - " n: gtx.int32,\n", - "):\n", - " timestep(\n", - " u,\n", - " v,\n", - " p,\n", - " uold,\n", - " vold,\n", - " pold,\n", - " dx,\n", - " dy,\n", - " tdt,\n", - " alpha,\n", - " m,\n", - " n,\n", - " out=(unew, vnew, pnew, uold, vold, pold),\n", - " domain=(\n", - " {I: (-1, m + 1), J: (-1, n + 1)},\n", - " {I: (-1, m + 1), J: (-1, n + 1)},\n", - " {I: (-1, m + 1), J: (-1, n + 1)},\n", - " {I: (0, m), J: (0, n)},\n", - " {I: (0, m), J: (0, n)},\n", - " {I: (0, m), J: (0, n)},\n", - " ),\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Time loop\n", - "\n", - "`uold`, `vold` and `pold` are updated in place and never swapped; only the prognostic\n", - "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", - "with the filter switched off, which is how the leapfrog scheme is started.\n", - "\n", - "Nothing here touches the halo any more --- it is filled inside the timestep." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def run(itmax: int, m: int = M, n: int = N) -> tuple[gtx.Field, gtx.Field, gtx.Field]:\n", - " \"\"\"Integrate `itmax` steps and return the final `u`, `v`, `p` fields.\"\"\"\n", - " domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", - "\n", - " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", - "\n", - " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", - " return gtx.as_field(domain, np.pad(a, 1, mode=\"wrap\"), allocator=backend)\n", - "\n", - " u, v, p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", - " uold, vold, pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", - " unew, vnew, pnew = (gtx.zeros(domain, dtype=gtx.float64, allocator=backend) for _ in range(3))\n", - "\n", - " program = timestep_program.with_backend(backend) if backend is not None else timestep_program\n", - "\n", - " for cycle in range(itmax):\n", - " tdt = DT if cycle == 0 else 2.0 * DT\n", - " alpha = 0.0 if cycle == 0 else ALPHA\n", - "\n", - " program(\n", - " u,\n", - " v,\n", - " p,\n", - " uold,\n", - " vold,\n", - " pold,\n", - " DX,\n", - " DY,\n", - " tdt,\n", - " alpha,\n", - " unew,\n", - " vnew,\n", - " pnew,\n", - " m,\n", - " n,\n", - " offset_provider={},\n", - " )\n", - "\n", - " u, unew = unew, u\n", - " v, vnew = vnew, v\n", - " p, pnew = pnew, p\n", - "\n", - " return u, v, p\n", - "\n", - "\n", - "def interior_of(field: gtx.Field, m: int = M, n: int = N) -> np.ndarray:\n", - " return field.asnumpy()[1 : m + 1, 1 : n + 1]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Validation against NumPy\n", - "\n", - "The companion module `swm_numpy.py` implements the same scheme with `numpy.roll`, which\n", - "gives periodicity for free and needs no halo at all. Agreement between the two is a check\n", - "that the halo bookkeeping here is right." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "STEPS = 100\n", - "\n", - "# The two implementations sum the same terms in a different order, so they agree to\n", - "# rounding rather than bit-for-bit. Tolerances are absolute because u and v cross zero.\n", - "ATOL_UV = 1e-11 # peak |u|, |v| ~ 4\n", - "ATOL_P = 1e-8 # peak |p| ~ 5e4\n", - "\n", - "\n", - "def test_matches_numpy():\n", - " u, v, p = run(STEPS)\n", - " u_ref, v_ref, p_ref = swm_numpy.run(STEPS)\n", - "\n", - " np.testing.assert_allclose(interior_of(u), u_ref, atol=ATOL_UV)\n", - " np.testing.assert_allclose(interior_of(v), v_ref, atol=ATOL_UV)\n", - " np.testing.assert_allclose(interior_of(p), p_ref, atol=ATOL_P)\n", - "\n", - "\n", - "test_matches_numpy()\n", - "print(\"GT4Py and NumPy agree after\", STEPS, \"steps\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Validation against the NCAR reference\n", - "\n", - "`swm_reference.npz` holds `u`, `v`, `p` after the full 4000-step benchmark, taken from\n", - "[NCAR/SWM](https://github.com/NCAR/SWM) `ref/16x16` (Apache-2.0). Reproducing it end to\n", - "end is the real correctness check, but it takes far longer than a notebook should in CI,\n", - "so it is opt-in." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "RUN_FULL_BENCHMARK = False\n", - "\n", - "\n", - "def test_matches_reference():\n", - " u, v, p = run(swm_numpy.ITMAX)\n", - " u_out, v_out, p_out = swm_numpy.to_reference_layout(\n", - " interior_of(u), interior_of(v), interior_of(p)\n", - " )\n", - "\n", - " reference = np.load(\"swm_reference.npz\")\n", - " np.testing.assert_allclose(u_out, reference[\"u\"], atol=ATOL_UV)\n", - " np.testing.assert_allclose(v_out, reference[\"v\"], atol=ATOL_UV)\n", - " np.testing.assert_allclose(p_out, reference[\"p\"], atol=ATOL_P)\n", - "\n", - "\n", - "if RUN_FULL_BENCHMARK:\n", - " test_matches_reference()\n", - " print(\"GT4Py reproduces the NCAR reference after\", swm_numpy.ITMAX, \"steps\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The flow\n", - "\n", - "The initial stream function sets up a pair of counter-rotating vortices; after a few\n", - "hundred steps the pressure field has developed the finer structure the scheme is meant to\n", - "handle without spurious accumulation of energy at the grid scale." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "\n", - "u, v, p = run(STEPS)\n", - "\n", - "fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))\n", - "for ax, field, name in zip(axes, (u, v, p), (\"u\", \"v\", \"p\")):\n", - " image = ax.contourf(interior_of(field).T, levels=20)\n", - " ax.set_title(f\"{name} after {STEPS} steps\")\n", - " ax.set_aspect(\"equal\")\n", - " fig.colorbar(image, ax=ax)\n", - "fig.tight_layout()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## References\n", - "\n", - "Sadourny, R. (1975). The dynamics of finite-difference models of the shallow-water\n", - "equations. *Journal of the Atmospheric Sciences*, 32(4), 680-689.\n", - "[doi:10.1175/1520-0469(1975)032<0680:TDOFDM>2.0.CO;2](https://doi.org/10.1175/1520-0469(1975)032%3C0680:TDOFDM%3E2.0.CO;2)\n", - "\n", - "The benchmark itself --- its configuration, initial condition and reference data --- is\n", - "[NCAR/SWM](https://github.com/NCAR/SWM), which implements the same model across a range of\n", - "languages and programming models." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/examples/swm/swm.ipynb b/examples/swm/swm.ipynb index b30704e716..10955abeb9 100644 --- a/examples/swm/swm.ipynb +++ b/examples/swm/swm.ipynb @@ -57,6 +57,7 @@ "\n", "import gt4py.next as gtx\n", "from gt4py.next import backend as next_backend, experimental as gtx_experimental\n", + "from gt4py.next.experimental import concat_where\n", "from gt4py._core import definitions as core_defs\n", "\n", "import swm_numpy" @@ -112,7 +113,8 @@ "\n", "A program is traced again for every new field domain, so each grid size compiles once. The\n", "scalars are traced, so `tdt` and `alpha` changing after the first step do not compile\n", - "again." + "again. The grid size `m`, `n` is a static parameter of the program below, since the halo is\n", + "filled by shifting by it." ] }, { @@ -217,6 +219,41 @@ " return (f - f(J - 1)) / dy" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Periodicity\n", + "\n", + "The domain wraps in both directions, and the wrap is expressed inside the field operator:\n", + "`concat_where` selects a sub-domain and takes its values from the opposite edge. At\n", + "$i = -1$ the field is read at $i + M$, at $i = M$ at $i - M$, and likewise in $j$.\n", + "\n", + "Each `concat_where` rebinds `f`, so the $j$ pass sees the already-$i$-corrected field and\n", + "the four corners come out right. Writing the four as one simultaneous expression would\n", + "leave them wrong.\n", + "\n", + "The shift distance is `m`, an argument rather than a literal. Domain inference resolves\n", + "the composition: at $i = -1$ the result comes from $i = M-1$, so the interior is all that\n", + "is ever demanded of the operator that produced it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@gtx.field_operator\n", + "def make_periodic(f: IJField, m: gtx.int32, n: gtx.int32) -> IJField:\n", + " \"\"\"Fill the one-cell halo of `f` from the opposite edge.\"\"\"\n", + " f = concat_where(I == -1, f(I + m), f)\n", + " f = concat_where(I == m, f(I - m), f)\n", + " f = concat_where(J == -1, f(J + n), f)\n", + " f = concat_where(J == n, f(J - n), f)\n", + " return f" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -249,6 +286,8 @@ " dy: gtx.float64,\n", " tdt: gtx.float64,\n", " alpha: gtx.float64,\n", + " m: gtx.int32,\n", + " n: gtx.int32,\n", ") -> tuple[IJField, IJField, IJField, IJField, IJField, IJField]:\n", " \"\"\"Advance one leapfrog step and return (unew, vnew, pnew, uold, vold, pold).\"\"\"\n", " cu = avg_x(p) * u\n", @@ -264,21 +303,23 @@ " vold_new = v + alpha * (vnew - 2.0 * v + vold)\n", " pold_new = p + alpha * (pnew - 2.0 * p + pold)\n", "\n", - " return unew, vnew, pnew, uold_new, vold_new, pold_new" + " return (\n", + " make_periodic(unew, m, n),\n", + " make_periodic(vnew, m, n),\n", + " make_periodic(pnew, m, n),\n", + " uold_new,\n", + " vold_new,\n", + " pold_new,\n", + " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Periodicity\n", - "\n", - "The domain wraps in both directions. Here the halo is refreshed **outside** the field\n", - "operator, after each step: the operator computes the interior only, and the halo is then\n", - "overwritten with the opposite edge by assigning to the field. Field assignment works for\n", - "every array library, including JAX, whose arrays are immutable and get a new buffer.\n", - "\n", - "Rows are copied before columns, which is what fills the corners correctly." + "The prognostic fields are written over the whole domain, halo included, while the\n", + "filtered levels only need the interior. A `program` lets each output declare its own\n", + "domain." ] }, { @@ -287,20 +328,47 @@ "metadata": {}, "outputs": [], "source": [ - "def apply_periodic(field: gtx.Field, m: int = M, n: int = N) -> None:\n", - " \"\"\"Refresh the one-cell halo of `field` from the opposite edge.\"\"\"\n", - "\n", - " def copy(dst: dict, src: dict) -> None:\n", - " dst_domain = gtx.domain(dst)\n", - " src_buffer = field[gtx.domain(src)].ndarray\n", - " field[dst_domain] = type(field).from_array(src_buffer, domain=dst_domain)\n", - "\n", - " all_j = (-1, n + 1)\n", - " copy({I: (-1, 0), J: all_j}, {I: (m - 1, m), J: all_j})\n", - " copy({I: (m, m + 1), J: all_j}, {I: (0, 1), J: all_j})\n", - " all_i = (-1, m + 1)\n", - " copy({I: all_i, J: (-1, 0)}, {I: all_i, J: (n - 1, n)})\n", - " copy({I: all_i, J: (n, n + 1)}, {I: all_i, J: (0, 1)})" + "@gtx.program\n", + "def timestep_program(\n", + " u: IJField,\n", + " v: IJField,\n", + " p: IJField,\n", + " uold: IJField,\n", + " vold: IJField,\n", + " pold: IJField,\n", + " dx: gtx.float64,\n", + " dy: gtx.float64,\n", + " tdt: gtx.float64,\n", + " alpha: gtx.float64,\n", + " unew: IJField,\n", + " vnew: IJField,\n", + " pnew: IJField,\n", + " m: gtx.int32,\n", + " n: gtx.int32,\n", + "):\n", + " timestep(\n", + " u,\n", + " v,\n", + " p,\n", + " uold,\n", + " vold,\n", + " pold,\n", + " dx,\n", + " dy,\n", + " tdt,\n", + " alpha,\n", + " m,\n", + " n,\n", + " out=(unew, vnew, pnew, uold, vold, pold),\n", + " domain=(\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (-1, m + 1), J: (-1, n + 1)},\n", + " {I: (0, m), J: (0, n)},\n", + " {I: (0, m), J: (0, n)},\n", + " {I: (0, m), J: (0, n)},\n", + " ),\n", + " )" ] }, { @@ -313,11 +381,9 @@ "fields ping-pong with their `new` counterparts. The first cycle is a forward Euler step\n", "with the filter switched off, which is how the leapfrog scheme is started.\n", "\n", - "A `Model` holds the fields of one integration and the field operator bound to its backend,\n", - "so that repeated calls of `advance` continue the same integration with the same compiled\n", - "or traced operator. The halo refresh runs outside the field operator.\n", - "`advance(..., periodic=False)` skips it: the results are wrong, but the steps then run back\n", - "to back without host work in between." + "A `Model` holds the fields of one integration and the program bound to its backend, so\n", + "that repeated calls of `advance` continue the same integration with the same compiled or\n", + "traced program. Nothing here touches the halo: it is filled inside the timestep." ] }, { @@ -337,8 +403,7 @@ " ):\n", " self.m, self.n = m, n\n", " self.domain = gtx.domain({I: (-1, m + 1), J: (-1, n + 1)})\n", - " self.interior = gtx.domain({I: (0, m), J: (0, n)})\n", - " self.step = timestep.with_backend(backend)\n", + " self.step = timestep_program.with_backend(backend).with_static_params(\"m\", \"n\")\n", " self.cycle = 0\n", "\n", " def as_halo_field(a: np.ndarray) -> gtx.Field:\n", @@ -349,10 +414,12 @@ " u0, v0, p0 = swm_numpy.initial_conditions(m, n, DX, DY)\n", " self.u, self.v, self.p = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", " self.uold, self.vold, self.pold = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", - " # A valid halo in every buffer keeps `p` nonzero there when the refresh is skipped.\n", - " self.unew, self.vnew, self.pnew = as_halo_field(u0), as_halo_field(v0), as_halo_field(p0)\n", + " self.unew, self.vnew, self.pnew = (\n", + " gtx.zeros(self.domain, dtype=gtx.float64, allocator=backend, device=device)\n", + " for _ in range(3)\n", + " )\n", "\n", - " def advance(self, cycles: int, periodic: bool = True) -> None:\n", + " def advance(self, cycles: int) -> None:\n", " \"\"\"Integrate `cycles` more steps.\"\"\"\n", " for _ in range(cycles):\n", " tdt = DT if self.cycle == 0 else 2.0 * DT\n", @@ -369,15 +436,14 @@ " DY,\n", " tdt,\n", " alpha,\n", - " out=(self.unew, self.vnew, self.pnew, self.uold, self.vold, self.pold),\n", - " domain=self.interior,\n", + " self.unew,\n", + " self.vnew,\n", + " self.pnew,\n", + " self.m,\n", + " self.n,\n", " offset_provider={},\n", " )\n", "\n", - " if periodic:\n", - " for field in (self.unew, self.vnew, self.pnew):\n", - " apply_periodic(field, self.m, self.n)\n", - "\n", " self.u, self.unew = self.unew, self.u\n", " self.v, self.vnew = self.vnew, self.v\n", " self.p, self.pnew = self.pnew, self.p\n", @@ -513,10 +579,10 @@ "under `jax.jit` and `torch.compile`. Each backend is first checked against the NumPy\n", "implementation, then timed on a sweep of grid sizes.\n", "\n", - "The timed steps skip the halo refresh, which runs on the host between two steps. Their\n", - "results are therefore wrong, but the steps run back to back: GPU work is launched\n", + "The steps run back to back, with no host work in between: GPU work is launched\n", "asynchronously and the host's dispatch of the next step overlaps with the device's\n", - "execution of the previous one. This emulates real-world use cases: in more complex models the Python dispatch overhead is hidden even on smaller grids.\n", + "execution of the previous one. This emulates real-world use cases: in more complex models\n", + "the Python dispatch overhead is hidden even on smaller grids.\n", "\n", "The first steps include compilation and the first leapfrog step uses different scalars, so\n", "`WARMUP_STEPS` run before any timing; the first step is reported separately. Then\n", @@ -606,16 +672,16 @@ " model = Model(size, size, backend=backend, device=device)\n", "\n", " start = time.perf_counter()\n", - " model.advance(1, periodic=False)\n", + " model.advance(1)\n", " wait(model)\n", " first_step = time.perf_counter() - start\n", - " model.advance(WARMUP_STEPS - 1, periodic=False)\n", + " model.advance(WARMUP_STEPS - 1)\n", "\n", " per_step = []\n", " for _ in range(REPEATS):\n", " wait(model)\n", " start = time.perf_counter()\n", - " model.advance(TIMED_STEPS, periodic=False)\n", + " model.advance(TIMED_STEPS)\n", " wait(model)\n", " per_step.append((time.perf_counter() - start) / TIMED_STEPS)\n", "\n", diff --git a/examples/swm_numpy.py b/examples/swm_numpy.py deleted file mode 100644 index 7db27aa980..0000000000 --- a/examples/swm_numpy.py +++ /dev/null @@ -1,164 +0,0 @@ -# GT4Py - GridTools Framework -# -# Copyright (c) 2014-2024, ETH Zurich -# All rights reserved. -# -# Please, refer to the LICENSE file in the root directory. -# SPDX-License-Identifier: BSD-3-Clause - -""" -NumPy reference for the shallow water model example. - -Companion to `swm.ipynb`. The model is doubly periodic, so periodicity is expressed here -with `numpy.roll` on interior-only arrays of shape `(M, N)` -- there is no halo. The -notebook's GT4Py version instead carries one halo cell per side and updates it explicitly, -which is what makes the two implementations worth comparing. -""" - -from __future__ import annotations - -import numpy as np - - -# Model constants of the NCAR/SWM benchmark configuration. -M = 16 -N = 16 -DX = 100000.0 -DY = 100000.0 -DT = 90.0 -ALPHA = 0.001 -A = 1000000.0 -P_MEAN = 50000.0 -ITMAX = 4000 - - -def avg_x(f: np.ndarray) -> np.ndarray: - return 0.5 * (np.roll(f, -1, axis=0) + f) - - -def avg_y(f: np.ndarray) -> np.ndarray: - return 0.5 * (np.roll(f, -1, axis=1) + f) - - -def avg_x_staggered(f: np.ndarray) -> np.ndarray: - return 0.5 * (np.roll(f, 1, axis=0) + f) - - -def avg_y_staggered(f: np.ndarray) -> np.ndarray: - return 0.5 * (np.roll(f, 1, axis=1) + f) - - -def delta_x(dx: float, f: np.ndarray) -> np.ndarray: - return (np.roll(f, -1, axis=0) - f) / dx - - -def delta_y(dy: float, f: np.ndarray) -> np.ndarray: - return (np.roll(f, -1, axis=1) - f) / dy - - -def delta_x_staggered(dx: float, f: np.ndarray) -> np.ndarray: - return (f - np.roll(f, 1, axis=0)) / dx - - -def delta_y_staggered(dy: float, f: np.ndarray) -> np.ndarray: - return (f - np.roll(f, 1, axis=1)) / dy - - -def initial_conditions( - m: int = M, n: int = N, dx: float = DX, dy: float = DY, a: float = A, p_mean: float = P_MEAN -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """ - Return the initial `u`, `v`, `p` on the interior grid, each of shape `(m, n)`. - - The velocity field is derived from a doubly periodic stream function - `psi = a * sin(2*pi*(i+0.5)/m) * sin(2*pi*(j+0.5)/n)`. - """ - d_i = 2.0 * np.pi / m - d_j = 2.0 * np.pi / n - el = n * dx - pcf = (np.pi * np.pi * a * a) / (el * el) - - psi = ( - a - * np.sin((np.arange(0, m + 1).reshape(-1, 1) + 0.5) * d_i) - * np.sin((np.arange(0, n + 1) + 0.5) * d_j) - ) - p = ( - pcf - * (np.cos(2.0 * np.arange(0, m).reshape(-1, 1) * d_i) + np.cos(2.0 * np.arange(0, n) * d_j)) - + p_mean - ) - u = -(psi[1:, 1:] - psi[1:, :-1]) / dy - v = (psi[1:, 1:] - psi[:-1, 1:]) / dx - - return u, v, p - - -def timestep( - u: np.ndarray, - v: np.ndarray, - p: np.ndarray, - uold: np.ndarray, - vold: np.ndarray, - pold: np.ndarray, - dx: float, - dy: float, - tdt: float, - alpha: float, -) -> tuple[np.ndarray, ...]: - """One leapfrog step with a Robert-Asselin time filter. Returns the six updated fields.""" - cu = avg_x(p) * u - cv = avg_y(p) * v - z = (delta_x(dx, v) - delta_y(dy, u)) / avg_x(avg_y(p)) - h = p + 0.5 * (avg_x_staggered(u * u) + avg_y_staggered(v * v)) - - unew = uold + avg_y_staggered(z) * avg_y_staggered(avg_x(cv)) * tdt - delta_x(dx, h) * tdt - vnew = vold - avg_x_staggered(z) * avg_x_staggered(avg_y(cu)) * tdt - delta_y(dy, h) * tdt - pnew = pold - delta_x_staggered(dx, cu) * tdt - delta_y_staggered(dy, cv) * tdt - - uold_new = u + alpha * (unew - 2.0 * u + uold) - vold_new = v + alpha * (vnew - 2.0 * v + vold) - pold_new = p + alpha * (pnew - 2.0 * p + pold) - - return unew, vnew, pnew, uold_new, vold_new, pold_new - - -def run( - itmax: int, - m: int = M, - n: int = N, - dx: float = DX, - dy: float = DY, - dt: float = DT, - alpha: float = ALPHA, -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """Integrate `itmax` steps and return the final interior `u`, `v`, `p`.""" - u, v, p = initial_conditions(m, n, dx, dy) - uold, vold, pold = u.copy(), v.copy(), p.copy() - - for cycle in range(itmax): - # The first step is forward Euler and unfiltered; afterwards leapfrog with tdt = 2*dt. - tdt = dt if cycle == 0 else 2.0 * dt - step_alpha = 0.0 if cycle == 0 else alpha - unew, vnew, pnew, uold, vold, pold = timestep( - u, v, p, uold, vold, pold, dx, dy, tdt, step_alpha - ) - u, v, p = unew, vnew, pnew - - return u, v, p - - -def to_reference_layout( - u: np.ndarray, v: np.ndarray, p: np.ndarray -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - """ - Convert interior `(M, N)` fields to the `(M+1, N+1)` layout of the NCAR/SWM dumps. - - The extra row and column are the periodic images the original Fortran carried - explicitly; which side they sit on differs per field because of the C-grid staggering. - """ - return ( - np.pad(u, ((1, 0), (0, 1)), mode="wrap"), - np.pad(v, ((0, 1), (1, 0)), mode="wrap"), - np.pad(p, ((0, 1), (0, 1)), mode="wrap"), - ) diff --git a/examples/swm_reference.npz b/examples/swm_reference.npz deleted file mode 100644 index 6a9ca4af2f80200ce698e0040e3fd68b90eaacd2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4785 zcmZWtc{J2*`&SGxm4rwlTPoopkt|6P0gBQAtyzX)tyPO<9t4NVbqQ zV~H{Lb!ITkKHs07_dVzLzR!D~bKloF_kBL+TK@QauKTjL=H*l6;o;e_wdHs!pLr-k z|6VX2F`iJhI{^{fc=qtb3vRt{ttkF~*{(qr;2a^{x{B(ZF73ZIY9&)WzZS2U^~|@v zAO!hasIV>X#?3JaE5yp@iQ}sb-i)i>roXfQt-RU$^HW%C? z`w1u^)UO*Pky!08D0AMC<3Z$x((BA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