vicflow 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vicflow/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """vicflow: 2D vortex-in-cell fluid simulation for generative art."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from . import image
6
+ from .grid import Grid
7
+ from .solver import Simulation
8
+
9
+ __all__ = ["Grid", "Simulation", "image"]
10
+ try:
11
+ __version__ = version("vicflow")
12
+ except PackageNotFoundError: # running from a source tree that is not installed
13
+ __version__ = "0+unknown"
vicflow/advect.py ADDED
@@ -0,0 +1,173 @@
1
+ """Semi-Lagrangian advection with M4' interpolation.
2
+
3
+ Each node looks back along the flow: an RK4 backtrace finds where its fluid
4
+ was one step earlier, and the advected fields are interpolated there with
5
+ the 4th-order M4' kernel. This is the scheme of vic2d (``moc_advect_2d``
6
+ with order 4 and M4' interpolation).
7
+
8
+ vic2d keeps the velocity frozen at its current value during the backtrace,
9
+ which is only first-order accurate in time and makes the kinetic energy
10
+ drift upwards at large time steps. Given the velocity of the previous step,
11
+ the backtrace can instead extrapolate the velocity in time, which is
12
+ second-order accurate.
13
+
14
+ Positions are expressed in grid-index units: node ``(i, j)`` is at ``(i, j)``.
15
+
16
+ Near a wall, the interpolation stencil reaches past the wall: like vic2d,
17
+ it reads the mirror nodes instead (``-i`` for ``i < 0``), which interpolates
18
+ the field's even extension across the wall. Departure points outside the
19
+ domain are handled the same way.
20
+
21
+ M4' is not monotone: at a sharp front (a density interface, a dye edge) it
22
+ overshoots, creating values outside the field's range that grow into grid-
23
+ scale ripples. The optional limiter clips each interpolated value to the
24
+ range of the 4 nodes of the cell it falls in (Bermejo & Staniforth 1992,
25
+ "quasi-monotone" semi-Lagrangian): no new extrema, at the price of some
26
+ extra numerical diffusion at fronts and the exact conservation of the
27
+ field's integral. Smooth regions are almost untouched. vic2d has no limiter
28
+ (a comment marks where it was meant to go), so it is off by default.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import numpy as np
34
+
35
+
36
+ def m4p_weights(t: np.ndarray) -> np.ndarray:
37
+ """M4' weights of the nodes at offsets -1, 0, 1, 2 from ``floor(x)``.
38
+
39
+ ``t = x - floor(x)`` is in ``[0, 1)``. Returns an array of shape
40
+ ``(4, *t.shape)``. M4' is the Catmull-Rom spline (Keys, a = -0.5), the
41
+ cubic convolution kernel that is 3rd-order accurate; the weights always
42
+ sum to 1.
43
+ """
44
+ t2 = t * t
45
+ t3 = t2 * t
46
+ return np.stack(
47
+ [
48
+ 0.5 * (-t3 + 2 * t2 - t),
49
+ 1.5 * t3 - 2.5 * t2 + 1,
50
+ -1.5 * t3 + 2 * t2 + 0.5 * t,
51
+ 0.5 * (t3 - t2),
52
+ ]
53
+ )
54
+
55
+
56
+ def node_index(i: np.ndarray, n_nodes: int, wall: bool) -> np.ndarray:
57
+ """Map any integer node index onto the stored nodes ``0 .. n_nodes - 1``.
58
+
59
+ Periodic: wrap around. Walls: reflect about both walls (``-i`` for
60
+ ``i < 0``, ``2 n - i`` beyond node ``n = n_nodes - 1``), i.e. wrap with
61
+ period ``2 n`` and fold back the second half.
62
+ """
63
+ if not wall:
64
+ return i % n_nodes
65
+ period = 2 * (n_nodes - 1)
66
+ r = i % period
67
+ return np.where(r >= n_nodes, period - r, r)
68
+
69
+
70
+ def interpolate(
71
+ fields: np.ndarray,
72
+ px: np.ndarray,
73
+ py: np.ndarray,
74
+ walls: tuple[bool, bool] = (False, False),
75
+ limit_from: int | None = None,
76
+ ) -> np.ndarray:
77
+ """Interpolate fields at arbitrary positions.
78
+
79
+ ``fields`` has shape ``(k, nx, ny)``; ``px`` and ``py`` are positions in
80
+ grid-index units, of any common shape. ``walls`` tells which axes are
81
+ walled (else periodic). Fields ``limit_from`` onwards are clipped to the
82
+ range of the 4 nodes around each position (none by default). Returns
83
+ shape ``(k, *px.shape)``.
84
+ """
85
+ if limit_from is not None and limit_from < 0:
86
+ raise ValueError(f"limit_from must be >= 0, got {limit_from}")
87
+ _, nx, ny = fields.shape
88
+ fx = np.floor(px)
89
+ fy = np.floor(py)
90
+ wx = m4p_weights(px - fx)
91
+ wy = m4p_weights(py - fy)
92
+ ix = fx.astype(np.intp) - 1
93
+ iy = fy.astype(np.intp) - 1
94
+
95
+ out = np.zeros((fields.shape[0], *px.shape), dtype=fields.dtype)
96
+ for a in range(4):
97
+ xa = node_index(ix + a, nx, walls[0])
98
+ for b in range(4):
99
+ yb = node_index(iy + b, ny, walls[1])
100
+ out += (wx[a] * wy[b]) * fields[:, xa, yb]
101
+
102
+ if limit_from is not None and limit_from < fields.shape[0]:
103
+ lim = slice(limit_from, None)
104
+ corners = [
105
+ fields[lim, node_index(ix + a, nx, walls[0]), node_index(iy + b, ny, walls[1])]
106
+ for a in (1, 2)
107
+ for b in (1, 2)
108
+ ]
109
+ lo = np.minimum.reduce(corners)
110
+ hi = np.maximum.reduce(corners)
111
+ out[lim] = np.clip(out[lim], lo, hi)
112
+ return out
113
+
114
+
115
+ def backtrace_rk4(
116
+ u: np.ndarray,
117
+ v: np.ndarray,
118
+ dt: float,
119
+ h: float,
120
+ u_prev: np.ndarray | None = None,
121
+ v_prev: np.ndarray | None = None,
122
+ walls: tuple[bool, bool] = (False, False),
123
+ ) -> tuple[np.ndarray, np.ndarray]:
124
+ """Departure points of every node after one RK4 step backwards in time.
125
+
126
+ The step goes from time ``t + dt`` (the nodes) back to ``t``. ``u, v`` are
127
+ the node velocities at ``t``, in domain units, and ``h`` is the cell size.
128
+
129
+ Without ``u_prev, v_prev`` the velocity is frozen at ``(u, v)`` over the
130
+ step, as in vic2d (first order in time). With the velocities of the
131
+ previous step, at ``t - dt``, it is extrapolated linearly in time to
132
+ ``t + dt/2`` and ``t + dt`` (second order).
133
+
134
+ Returns the departure positions in grid-index units.
135
+ """
136
+ nx, ny = u.shape
137
+ x, y = np.meshgrid(np.arange(nx, dtype=float), np.arange(ny, dtype=float), indexing="ij")
138
+ s = dt / h
139
+ vel_now = np.stack([u, v])
140
+ if u_prev is None or v_prev is None:
141
+ vel_end = vel_mid = vel_now
142
+ else:
143
+ vel_prev = np.stack([u_prev, v_prev])
144
+ vel_end = 2 * vel_now - vel_prev # at t + dt
145
+ vel_mid = 1.5 * vel_now - 0.5 * vel_prev # at t + dt/2
146
+
147
+ k1 = vel_end # the nodes themselves: no interpolation needed
148
+ k2 = interpolate(vel_mid, x - 0.5 * s * k1[0], y - 0.5 * s * k1[1], walls)
149
+ k3 = interpolate(vel_mid, x - 0.5 * s * k2[0], y - 0.5 * s * k2[1], walls)
150
+ k4 = interpolate(vel_now, x - s * k3[0], y - s * k3[1], walls)
151
+ ubar = (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]) / 6
152
+ vbar = (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]) / 6
153
+ return x - s * ubar, y - s * vbar
154
+
155
+
156
+ def advect(
157
+ fields: np.ndarray,
158
+ u: np.ndarray,
159
+ v: np.ndarray,
160
+ dt: float,
161
+ h: float,
162
+ u_prev: np.ndarray | None = None,
163
+ v_prev: np.ndarray | None = None,
164
+ walls: tuple[bool, bool] = (False, False),
165
+ limit_from: int | None = None,
166
+ ) -> np.ndarray:
167
+ """Advect fields of shape ``(k, nx, ny)`` by one time step.
168
+
169
+ See ``backtrace_rk4`` for the meaning of ``u_prev, v_prev``, and
170
+ ``interpolate`` for ``limit_from``. The velocity is never limited.
171
+ """
172
+ px, py = backtrace_rk4(u, v, dt, h, u_prev, v_prev, walls)
173
+ return interpolate(fields, px, py, walls, limit_from)
@@ -0,0 +1,38 @@
1
+ """Array backends: where and how the solver's arrays live and are computed.
2
+
3
+ ``numpy``
4
+ The reference implementation (``vicflow.poisson``, ``vicflow.advect``,
5
+ ``vicflow.diffusion``), on the CPU, float64 by default.
6
+ ``torch``
7
+ The same algorithm with PyTorch, on CUDA, Apple Silicon (MPS) or CPU,
8
+ float32 by default. Needs the ``torch`` extra: ``pip install vicflow[torch]``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Literal
14
+
15
+ from ..grid import Grid
16
+ from ..poisson import Scheme
17
+
18
+ BackendName = Literal["numpy", "torch"]
19
+
20
+
21
+ def get_backend(
22
+ name: BackendName, grid: Grid, poisson: Scheme, dtype=None, device: str | None = None
23
+ ):
24
+ if name == "numpy":
25
+ if device not in (None, "cpu"):
26
+ raise ValueError(f"the numpy backend runs on the CPU only, got device={device!r}")
27
+ from .numpy_backend import NumpyBackend
28
+
29
+ return NumpyBackend(grid, poisson, dtype)
30
+ if name == "torch":
31
+ try:
32
+ from .torch_backend import TorchBackend
33
+ except ImportError as e: # pragma: no cover - depends on the environment
34
+ raise ImportError(
35
+ "the torch backend needs PyTorch: pip install 'vicflow[torch]'"
36
+ ) from e
37
+ return TorchBackend(grid, poisson, dtype, device)
38
+ raise ValueError(f"unknown backend {name!r}, expected 'numpy' or 'torch'")
@@ -0,0 +1 @@
1
+ """Native GPU kernels for the torch backend (fused advection)."""
@@ -0,0 +1,169 @@
1
+ """Fused semi-Lagrangian advection kernel in Metal (Apple Silicon GPUs).
2
+
3
+ Same algorithm as ``triton_advect``: one GPU thread per node runs the RK4
4
+ backtrace and the final M4' interpolations in registers. Compiled at first
5
+ use through ``torch.mps.compile_shader``.
6
+
7
+ Node indices are 32-bit, so grids are limited to 46340^2 nodes; offsets
8
+ between fields are 64-bit, so any number of fields fits.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+
15
+ SOURCE = r"""
16
+ #include <metal_stdlib>
17
+ using namespace metal;
18
+
19
+ // wrap (periodic) or reflect about both walls (wall) a node index; n nodes
20
+ inline int node_index(int i, int n, bool wall) {
21
+ int period = wall ? 2 * (n - 1) : n;
22
+ int r = i % period;
23
+ if (r < 0) r += period;
24
+ return (wall && r >= n) ? period - r : r;
25
+ }
26
+
27
+ // M4' weights of the nodes at offsets -1, 0, 1, 2 from floor(x)
28
+ inline void m4p(float t, thread float w[4]) {
29
+ float t2 = t * t;
30
+ float t3 = t2 * t;
31
+ w[0] = 0.5f * (-t3 + 2.0f * t2 - t);
32
+ w[1] = 1.5f * t3 - 2.5f * t2 + 1.0f;
33
+ w[2] = -1.5f * t3 + 2.0f * t2 + 0.5f * t;
34
+ w[3] = 0.5f * (t3 - t2);
35
+ }
36
+
37
+ struct Stencil {
38
+ int row[4]; // wrapped x index times ny
39
+ int col[4]; // wrapped y index
40
+ float wx[4];
41
+ float wy[4];
42
+ };
43
+
44
+ // stencil at (ix + dx, iy + dy): integer node indices plus float offsets in
45
+ // cells, so that a small offset keeps its float32 precision at any grid size
46
+ inline Stencil stencil(int ix, int iy, float dx, float dy, int nx, int ny, bool wx, bool wy) {
47
+ Stencil s;
48
+ float fx = floor(dx);
49
+ float fy = floor(dy);
50
+ m4p(dx - fx, s.wx);
51
+ m4p(dy - fy, s.wy);
52
+ int x0 = ix + int(fx) - 1;
53
+ int y0 = iy + int(fy) - 1;
54
+ for (int a = 0; a < 4; ++a) {
55
+ s.row[a] = node_index(x0 + a, nx, wx) * ny;
56
+ s.col[a] = node_index(y0 + a, ny, wy);
57
+ }
58
+ return s;
59
+ }
60
+
61
+ inline float gather(device const float* f, thread const Stencil& s) {
62
+ float acc = 0.0f;
63
+ for (int a = 0; a < 4; ++a) {
64
+ float r = 0.0f;
65
+ for (int b = 0; b < 4; ++b) {
66
+ r += s.wy[b] * f[s.row[a] + s.col[b]];
67
+ }
68
+ acc += s.wx[a] * r;
69
+ }
70
+ return acc;
71
+ }
72
+
73
+ kernel void advect(device const float* fields [[buffer(0)]],
74
+ device float* out [[buffer(1)]],
75
+ device const float* u_now [[buffer(2)]],
76
+ device const float* v_now [[buffer(3)]],
77
+ device const float* u_mid [[buffer(4)]],
78
+ device const float* v_mid [[buffer(5)]],
79
+ device const float* u_end [[buffer(6)]],
80
+ device const float* v_end [[buffer(7)]],
81
+ constant float& s [[buffer(8)]],
82
+ constant long& nx_ [[buffer(9)]], // torch passes Python ints as int64
83
+ constant long& ny_ [[buffer(10)]],
84
+ constant long& nfields [[buffer(11)]],
85
+ constant long& walls_x [[buffer(12)]], // 1: walls on this axis, 0: periodic
86
+ constant long& walls_y [[buffer(13)]],
87
+ constant long& limit_from [[buffer(14)]], // first limited field
88
+ uint gid [[thread_position_in_grid]]) {
89
+ bool wx = walls_x != 0;
90
+ bool wy = walls_y != 0;
91
+ int nx = int(nx_);
92
+ int ny = int(ny_);
93
+ int n = nx * ny;
94
+ int i = int(gid);
95
+ if (i >= n) return;
96
+ int ix = i / ny;
97
+ int iy = i % ny;
98
+
99
+ // displacements from the node, not absolute positions (see torch_backend)
100
+ float k1u = u_end[i];
101
+ float k1v = v_end[i];
102
+ Stencil st = stencil(ix, iy, -0.5f * s * k1u, -0.5f * s * k1v, nx, ny, wx, wy);
103
+ float k2u = gather(u_mid, st);
104
+ float k2v = gather(v_mid, st);
105
+ st = stencil(ix, iy, -0.5f * s * k2u, -0.5f * s * k2v, nx, ny, wx, wy);
106
+ float k3u = gather(u_mid, st);
107
+ float k3v = gather(v_mid, st);
108
+ st = stencil(ix, iy, -s * k3u, -s * k3v, nx, ny, wx, wy);
109
+ float k4u = gather(u_now, st);
110
+ float k4v = gather(v_now, st);
111
+ float dx = -s * (k1u + 2.0f * k2u + 2.0f * k3u + k4u) / 6.0f;
112
+ float dy = -s * (k1v + 2.0f * k2v + 2.0f * k3v + k4v) / 6.0f;
113
+
114
+ st = stencil(ix, iy, dx, dy, nx, ny, wx, wy);
115
+ for (long f = 0; f < nfields; ++f) {
116
+ long base = f * long(n); // k * n can exceed 2^31 with several fields
117
+ device const float* g = fields + base;
118
+ float val = gather(g, st);
119
+ if (f >= limit_from && !isnan(val)) {
120
+ // clip to the range of the 4 nodes of the cell. A NaN anywhere in
121
+ // the 4 x 4 stencil makes val NaN: keep it, as np.clip would
122
+ float a = g[st.row[1] + st.col[1]];
123
+ float b = g[st.row[1] + st.col[2]];
124
+ float c = g[st.row[2] + st.col[1]];
125
+ float d = g[st.row[2] + st.col[2]];
126
+ val = clamp(val, min(min(a, b), min(c, d)), max(max(a, b), max(c, d)));
127
+ }
128
+ out[base + i] = val;
129
+ }
130
+ }
131
+ """
132
+
133
+ _library = None
134
+
135
+
136
+ def _lib():
137
+ global _library
138
+ if _library is None:
139
+ _library = torch.mps.compile_shader(SOURCE)
140
+ return _library
141
+
142
+
143
+ def advect(
144
+ fields: torch.Tensor,
145
+ vel_now: tuple[torch.Tensor, torch.Tensor],
146
+ vel_mid: tuple[torch.Tensor, torch.Tensor],
147
+ vel_end: tuple[torch.Tensor, torch.Tensor],
148
+ s: float,
149
+ walls: tuple[bool, bool] = (False, False),
150
+ limit_from: int | None = None,
151
+ ) -> torch.Tensor:
152
+ """Advect contiguous float32 fields ``(k, nx, ny)``; velocities are ``(nx, ny)``.
153
+
154
+ ``walls`` tells which axes are walled (mirror nodes), else periodic.
155
+ Fields ``limit_from`` onwards are clipped to the range of their cell's
156
+ nodes (see vicflow.advect).
157
+ """
158
+ if limit_from is not None and limit_from < 0:
159
+ raise ValueError(f"limit_from must be >= 0, got {limit_from}")
160
+ k, nx, ny = fields.shape
161
+ if nx * ny >= 2**31:
162
+ raise ValueError(f"grid too large for 32-bit indices: {nx}x{ny}")
163
+ fields = fields.contiguous()
164
+ out = torch.empty_like(fields)
165
+ vels = [t.contiguous() for t in (*vel_now, *vel_mid, *vel_end)]
166
+ wx, wy = (int(bool(w)) for w in walls)
167
+ first = k if limit_from is None else min(int(limit_from), k)
168
+ _lib().advect(fields, out, *vels, float(s), nx, ny, k, wx, wy, first, threads=nx * ny)
169
+ return out
@@ -0,0 +1,185 @@
1
+ """Fused semi-Lagrangian advection kernel in Triton (CUDA and ROCm GPUs).
2
+
3
+ One program instance handles a block of nodes. For each node it runs the
4
+ whole RK4 backtrace and the final M4' interpolations in registers, so the
5
+ only memory traffic is the gathered velocity and field values (mostly cache
6
+ hits) and one store per field. This replaces the ~400 elementwise kernels
7
+ and their temporaries of the pure-PyTorch path. The maths is the same as
8
+ ``vicflow.advect``; see there for details.
9
+
10
+ Node indices are 32-bit, so grids are limited to 46340^2 nodes; offsets
11
+ between fields are 64-bit, so any number of fields fits.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import torch
17
+ import triton
18
+ import triton.language as tl
19
+
20
+ BLOCK = 256
21
+
22
+
23
+ @triton.jit
24
+ def _index(i, n, WALL: tl.constexpr):
25
+ """Wrap (periodic) or reflect about both walls (WALL) a node index; n nodes."""
26
+ if WALL:
27
+ period = 2 * (n - 1)
28
+ r = i % period
29
+ r = tl.where(r < 0, r + period, r)
30
+ r = tl.where(r >= n, period - r, r)
31
+ else:
32
+ r = i % n
33
+ r = tl.where(r < 0, r + n, r)
34
+ return r
35
+
36
+
37
+ @triton.jit
38
+ def _m4p(t):
39
+ """M4' weights of the nodes at offsets -1, 0, 1, 2 from floor(x)."""
40
+ t2 = t * t
41
+ t3 = t2 * t
42
+ w0 = 0.5 * (-t3 + 2.0 * t2 - t)
43
+ w1 = 1.5 * t3 - 2.5 * t2 + 1.0
44
+ w2 = -1.5 * t3 + 2.0 * t2 + 0.5 * t
45
+ w3 = 0.5 * (t3 - t2)
46
+ return w0, w1, w2, w3
47
+
48
+
49
+ @triton.jit
50
+ def _row(ptr, row, y0, y1, y2, y3, wy0, wy1, wy2, wy3):
51
+ return (
52
+ wy0 * tl.load(ptr + row + y0)
53
+ + wy1 * tl.load(ptr + row + y1)
54
+ + wy2 * tl.load(ptr + row + y2)
55
+ + wy3 * tl.load(ptr + row + y3)
56
+ )
57
+
58
+
59
+ @triton.jit
60
+ def _interp(ptr, ix, iy, dx, dy, nx, ny, WX: tl.constexpr, WY: tl.constexpr):
61
+ """M4' interpolation of one periodic (nx, ny) field at (ix + dx, iy + dy).
62
+
63
+ ix, iy are integer node indices and dx, dy float offsets in cells: a small
64
+ offset keeps its float32 precision whatever the grid size.
65
+ """
66
+ fx = tl.floor(dx)
67
+ fy = tl.floor(dy)
68
+ wx0, wx1, wx2, wx3 = _m4p(dx - fx)
69
+ wy0, wy1, wy2, wy3 = _m4p(dy - fy)
70
+ x0 = ix + fx.to(tl.int32) - 1
71
+ y0 = iy + fy.to(tl.int32) - 1
72
+ y1 = _index(y0 + 1, ny, WY)
73
+ y2 = _index(y0 + 2, ny, WY)
74
+ y3 = _index(y0 + 3, ny, WY)
75
+ y0 = _index(y0, ny, WY)
76
+ r0 = _row(ptr, _index(x0, nx, WX) * ny, y0, y1, y2, y3, wy0, wy1, wy2, wy3)
77
+ r1 = _row(ptr, _index(x0 + 1, nx, WX) * ny, y0, y1, y2, y3, wy0, wy1, wy2, wy3)
78
+ r2 = _row(ptr, _index(x0 + 2, nx, WX) * ny, y0, y1, y2, y3, wy0, wy1, wy2, wy3)
79
+ r3 = _row(ptr, _index(x0 + 3, nx, WX) * ny, y0, y1, y2, y3, wy0, wy1, wy2, wy3)
80
+ return wx0 * r0 + wx1 * r1 + wx2 * r2 + wx3 * r3
81
+
82
+
83
+ @triton.jit
84
+ def _advect_kernel(
85
+ fields, # (n_fields, nx, ny) input
86
+ out, # (n_fields, nx, ny) output
87
+ u_now, # velocity at t, interpolated at the last RK4 stage
88
+ v_now,
89
+ u_mid, # velocity at t + dt/2, interpolated at stages 2 and 3
90
+ v_mid,
91
+ u_end, # velocity at t + dt, read at the nodes (stage 1)
92
+ v_end,
93
+ s, # dt / h: displacement in cells per unit velocity
94
+ nx,
95
+ ny,
96
+ N_FIELDS: tl.constexpr,
97
+ LIMIT_FROM: tl.constexpr, # fields from this one on are limited (N_FIELDS: none)
98
+ WX: tl.constexpr, # walls on the x axis (else periodic)
99
+ WY: tl.constexpr,
100
+ BLOCK: tl.constexpr,
101
+ ):
102
+ offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
103
+ n = nx * ny
104
+ mask = offs < n
105
+ offs = tl.where(mask, offs, 0) # keep inactive lanes on a valid node
106
+ ix = offs // ny
107
+ iy = offs % ny
108
+
109
+ # displacements from the node, not absolute positions (see torch_backend)
110
+ k1u = tl.load(u_end + offs)
111
+ k1v = tl.load(v_end + offs)
112
+ k2u = _interp(u_mid, ix, iy, -0.5 * s * k1u, -0.5 * s * k1v, nx, ny, WX, WY)
113
+ k2v = _interp(v_mid, ix, iy, -0.5 * s * k1u, -0.5 * s * k1v, nx, ny, WX, WY)
114
+ k3u = _interp(u_mid, ix, iy, -0.5 * s * k2u, -0.5 * s * k2v, nx, ny, WX, WY)
115
+ k3v = _interp(v_mid, ix, iy, -0.5 * s * k2u, -0.5 * s * k2v, nx, ny, WX, WY)
116
+ k4u = _interp(u_now, ix, iy, -s * k3u, -s * k3v, nx, ny, WX, WY)
117
+ k4v = _interp(v_now, ix, iy, -s * k3u, -s * k3v, nx, ny, WX, WY)
118
+ dx = -s * (k1u + 2.0 * k2u + 2.0 * k3u + k4u) / 6.0
119
+ dy = -s * (k1v + 2.0 * k2v + 2.0 * k3v + k4v) / 6.0
120
+
121
+ if LIMIT_FROM < N_FIELDS:
122
+ # the 4 nodes of the cell the departure point falls in
123
+ cx = ix + tl.floor(dx).to(tl.int32)
124
+ cy = iy + tl.floor(dy).to(tl.int32)
125
+ c00 = _index(cx, nx, WX) * ny + _index(cy, ny, WY)
126
+ c01 = _index(cx, nx, WX) * ny + _index(cy + 1, ny, WY)
127
+ c10 = _index(cx + 1, nx, WX) * ny + _index(cy, ny, WY)
128
+ c11 = _index(cx + 1, nx, WX) * ny + _index(cy + 1, ny, WY)
129
+
130
+ n64 = n.to(tl.int64) # k * n can exceed 2^31 with several fields
131
+ for f in tl.static_range(N_FIELDS):
132
+ ptr = fields + f * n64
133
+ val = _interp(ptr, ix, iy, dx, dy, nx, ny, WX, WY)
134
+ if f >= LIMIT_FROM:
135
+ a = tl.load(ptr + c00)
136
+ b = tl.load(ptr + c01)
137
+ c = tl.load(ptr + c10)
138
+ d = tl.load(ptr + c11)
139
+ lo = tl.minimum(tl.minimum(a, b), tl.minimum(c, d))
140
+ hi = tl.maximum(tl.maximum(a, b), tl.maximum(c, d))
141
+ # a NaN anywhere in the stencil makes val NaN: keep it, as np.clip would
142
+ val = tl.where(val != val, val, tl.minimum(tl.maximum(val, lo), hi))
143
+ tl.store(out + f * n64 + offs, val, mask=mask)
144
+
145
+
146
+ def advect(
147
+ fields: torch.Tensor,
148
+ vel_now: tuple[torch.Tensor, torch.Tensor],
149
+ vel_mid: tuple[torch.Tensor, torch.Tensor],
150
+ vel_end: tuple[torch.Tensor, torch.Tensor],
151
+ s: float,
152
+ walls: tuple[bool, bool] = (False, False),
153
+ limit_from: int | None = None,
154
+ ) -> torch.Tensor:
155
+ """Advect contiguous float32 fields ``(k, nx, ny)``; velocities are ``(nx, ny)``.
156
+
157
+ ``walls`` tells which axes are walled (mirror nodes), else periodic.
158
+ Fields ``limit_from`` onwards are clipped to the range of their cell's
159
+ nodes (see vicflow.advect).
160
+ """
161
+ if limit_from is not None and limit_from < 0:
162
+ raise ValueError(f"limit_from must be >= 0, got {limit_from}")
163
+ k, nx, ny = fields.shape
164
+ if nx * ny >= 2**31:
165
+ raise ValueError(f"grid too large for 32-bit indices: {nx}x{ny}")
166
+ fields = fields.contiguous()
167
+ out = torch.empty_like(fields)
168
+ vels = [t.contiguous() for t in (*vel_now, *vel_mid, *vel_end)]
169
+ grid = (triton.cdiv(nx * ny, BLOCK),)
170
+ # Triton launches on the current CUDA device and stream: make them the tensors'
171
+ with torch.cuda.device(fields.device):
172
+ _advect_kernel[grid](
173
+ fields,
174
+ out,
175
+ *vels,
176
+ float(s),
177
+ nx,
178
+ ny,
179
+ N_FIELDS=k,
180
+ LIMIT_FROM=k if limit_from is None else min(int(limit_from), k),
181
+ WX=bool(walls[0]),
182
+ WY=bool(walls[1]),
183
+ BLOCK=BLOCK,
184
+ )
185
+ return out
@@ -0,0 +1,43 @@
1
+ """NumPy backend: the reference implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from .. import advect as _advect
8
+ from .. import buoyancy as _buoyancy
9
+ from .. import diffusion as _diffusion
10
+ from ..grid import Grid
11
+ from ..poisson import Poisson, Scheme
12
+
13
+
14
+ class NumpyBackend:
15
+ name = "numpy"
16
+ device = "cpu"
17
+
18
+ def __init__(self, grid: Grid, poisson: Scheme, dtype=None) -> None:
19
+ self.dtype = np.dtype(np.float64 if dtype is None else dtype)
20
+ self.grid = grid
21
+ self._poisson = Poisson(grid, poisson)
22
+
23
+ def asarray(self, a) -> np.ndarray:
24
+ return np.array(a, dtype=self.dtype)
25
+
26
+ def to_numpy(self, a) -> np.ndarray:
27
+ return np.array(a, copy=True)
28
+
29
+ def stack(self, arrays):
30
+ return np.stack(arrays)
31
+
32
+ def baroclinic(self, rho, buoyancy, gravity):
33
+ return _buoyancy.baroclinic_source(rho, self.grid.h, buoyancy, gravity, self.grid.walls)
34
+
35
+ def velocity(self, omega):
36
+ return self._poisson.velocity(omega)
37
+
38
+ def diffuse(self, field, nu, dt, h):
39
+ return _diffusion.diffuse(field, nu, dt, h, self.grid.walls)
40
+
41
+ def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None):
42
+ walls = self.grid.walls
43
+ return _advect.advect(fields, u, v, dt, h, u_prev, v_prev, walls, limit_from)