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.
@@ -0,0 +1,347 @@
1
+ """PyTorch backend: the reference algorithm on CUDA, Apple Silicon (MPS) or CPU.
2
+
3
+ Every function mirrors its NumPy counterpart in ``vicflow.poisson``,
4
+ ``vicflow.advect`` and ``vicflow.diffusion``; see those for the maths. The
5
+ differences:
6
+
7
+ - interpolation gathers from flattened arrays, and the Fourier symbols are
8
+ built once;
9
+ - the backtrace works with displacements from the departing node instead of
10
+ absolute positions. In float32, an absolute position near index n is only
11
+ known to n * 2^-24 cells, an error that grows with the grid and exceeds the
12
+ scheme's own error at 4096^2; a displacement of a few cells is known to
13
+ about 1e-7 cells at any grid size. (The NumPy reference always computes
14
+ positions in float64, where this does not matter.)
15
+
16
+ The advection takes about 97 % of a step in pure PyTorch, so on GPUs in
17
+ float32 it runs as one fused native kernel instead (``kernels/``): Triton on
18
+ CUDA (and, untested, ROCm), Metal on Apple Silicon. When the backend is
19
+ created, the kernel is compiled and checked against the PyTorch path on a
20
+ small case; if it is missing, fails or disagrees, a warning is issued and
21
+ PyTorch is used. Set ``use_fused_kernel = False`` on a backend to force the
22
+ pure-PyTorch path, which stays the reference.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import warnings
28
+
29
+ import numpy as np
30
+ import torch
31
+
32
+ from ..diffusion import MAX_DIFFUSION_NUMBER
33
+ from ..grid import Grid
34
+ from ..poisson import Poisson, Scheme
35
+
36
+ Velocity = tuple[torch.Tensor, torch.Tensor]
37
+
38
+
39
+ def default_device() -> torch.device:
40
+ if torch.cuda.is_available():
41
+ return torch.device("cuda")
42
+ if torch.backends.mps.is_available():
43
+ return torch.device("mps")
44
+ return torch.device("cpu")
45
+
46
+
47
+ def as_torch_dtype(dtype) -> torch.dtype:
48
+ """float32 (default) or float64, given as a NumPy or a torch dtype."""
49
+ if dtype is None:
50
+ return torch.float32
51
+ if not isinstance(dtype, torch.dtype):
52
+ dtype = {np.dtype(np.float32): torch.float32, np.dtype(np.float64): torch.float64}.get(
53
+ np.dtype(dtype)
54
+ )
55
+ if dtype not in (torch.float32, torch.float64):
56
+ raise ValueError(f"unsupported dtype {dtype}, use float32 or float64")
57
+ return dtype
58
+
59
+
60
+ def m4p_weights(t: torch.Tensor) -> torch.Tensor:
61
+ """M4' weights of the nodes at offsets -1, 0, 1, 2 from floor(x); see vicflow.advect."""
62
+ t2 = t * t
63
+ t3 = t2 * t
64
+ return torch.stack(
65
+ [
66
+ 0.5 * (-t3 + 2 * t2 - t),
67
+ 1.5 * t3 - 2.5 * t2 + 1,
68
+ -1.5 * t3 + 2 * t2 + 0.5 * t,
69
+ 0.5 * (t3 - t2),
70
+ ]
71
+ )
72
+
73
+
74
+ def node_index(i: torch.Tensor, n_nodes: int, wall: bool) -> torch.Tensor:
75
+ """Wrap (periodic) or reflect (walls) node indices; see vicflow.advect.node_index."""
76
+ if not wall:
77
+ return i % n_nodes
78
+ period = 2 * (n_nodes - 1)
79
+ r = i % period
80
+ return torch.where(r >= n_nodes, period - r, r)
81
+
82
+
83
+ def interpolate(
84
+ fields: torch.Tensor,
85
+ dx: torch.Tensor,
86
+ dy: torch.Tensor,
87
+ ix: torch.Tensor | int = 0,
88
+ iy: torch.Tensor | int = 0,
89
+ walls: tuple[bool, bool] = (False, False),
90
+ limit_from: int | None = None,
91
+ ) -> torch.Tensor:
92
+ """M4' interpolation of fields ``(k, nx, ny)`` at ``(ix + dx, iy + dy)``.
93
+
94
+ Positions are in grid-index units, split into integer node indices
95
+ ``ix, iy`` and float offsets ``dx, dy`` so that small offsets from far
96
+ nodes keep their precision. With the default ``ix = iy = 0``, ``dx, dy``
97
+ are absolute positions. ``walls`` tells which axes are walled. Fields
98
+ ``limit_from`` onwards are clipped to the range of the 4 nodes of the
99
+ cell (see vicflow.advect).
100
+ """
101
+ if limit_from is not None and limit_from < 0:
102
+ raise ValueError(f"limit_from must be >= 0, got {limit_from}")
103
+ k, nx, ny = fields.shape
104
+ flat = fields.reshape(k, nx * ny)
105
+ fx = torch.floor(dx)
106
+ fy = torch.floor(dy)
107
+ wx = m4p_weights(dx - fx)
108
+ wy = m4p_weights(dy - fy)
109
+ x0 = ix + fx.to(torch.int64) - 1
110
+ y0 = iy + fy.to(torch.int64) - 1
111
+ cols = [node_index(y0 + b, ny, walls[1]) for b in range(4)]
112
+
113
+ out = torch.zeros((k, *dx.shape), dtype=fields.dtype, device=fields.device)
114
+ for a in range(4):
115
+ row = node_index(x0 + a, nx, walls[0]) * ny
116
+ for b in range(4):
117
+ out += (wx[a] * wy[b]) * flat[:, row + cols[b]]
118
+
119
+ if limit_from is not None and limit_from < k:
120
+ lim = flat[limit_from:]
121
+ corners = [
122
+ lim[:, node_index(x0 + a, nx, walls[0]) * ny + cols[b]] for a in (1, 2) for b in (1, 2)
123
+ ]
124
+ lo = torch.minimum(torch.minimum(corners[0], corners[1]), torch.minimum(*corners[2:]))
125
+ hi = torch.maximum(torch.maximum(corners[0], corners[1]), torch.maximum(*corners[2:]))
126
+ out[limit_from:] = torch.clamp(out[limit_from:], lo, hi)
127
+ return out
128
+
129
+
130
+ def odd_extension(f: torch.Tensor, axis: int) -> torch.Tensor:
131
+ """See vicflow.poisson.odd_extension."""
132
+ f = f.movedim(axis, 0)
133
+ inner = f[1:-1]
134
+ zero = torch.zeros_like(f[:1])
135
+ return torch.cat([zero, inner, zero, -inner.flip(0)]).movedim(0, axis)
136
+
137
+
138
+ def second_difference(f: torch.Tensor, axis: int, wall: bool) -> torch.Tensor:
139
+ """See vicflow.diffusion.second_difference."""
140
+ if not wall:
141
+ return torch.roll(f, 1, axis) + torch.roll(f, -1, axis) - 2 * f
142
+ g = f.movedim(axis, 0)
143
+ d = torch.empty_like(g)
144
+ d[1:-1] = g[2:] + g[:-2] - 2 * g[1:-1]
145
+ d[0] = -g[2] + 6 * g[1] - 5 * g[0]
146
+ d[-1] = -g[-3] + 6 * g[-2] - 5 * g[-1]
147
+ return d.movedim(0, axis)
148
+
149
+
150
+ def first_difference(f: torch.Tensor, axis: int, wall: bool) -> torch.Tensor:
151
+ """See vicflow.buoyancy.first_difference."""
152
+ if not wall:
153
+ return 0.5 * (torch.roll(f, -1, axis) - torch.roll(f, 1, axis))
154
+ g = f.movedim(axis, 0)
155
+ d = torch.empty_like(g)
156
+ d[1:-1] = 0.5 * (g[2:] - g[:-2])
157
+ d[0] = 0.5 * (-g[2] + 4 * g[1] - 3 * g[0])
158
+ d[-1] = 0.5 * (g[-3] - 4 * g[-2] + 3 * g[-1])
159
+ return d.movedim(0, axis)
160
+
161
+
162
+ class TorchBackend:
163
+ name = "torch"
164
+
165
+ def __init__(self, grid: Grid, poisson: Scheme, dtype=None, device=None) -> None:
166
+ self.device = default_device() if device is None else torch.device(device)
167
+ self.dtype = as_torch_dtype(dtype)
168
+ if self.device.type == "mps" and self.dtype == torch.float64:
169
+ raise ValueError("Apple's MPS backend has no float64: use dtype=np.float32")
170
+ self.grid = grid
171
+
172
+ # Fourier symbols: computed in float64 by the NumPy solver, then moved over
173
+ ref = Poisson(grid, poisson)
174
+ self._extended_shape = ref.extended_shape
175
+ cdtype = torch.complex64 if self.dtype == torch.float32 else torch.complex128
176
+ self._u_sym = torch.as_tensor(ref._u, dtype=cdtype, device=self.device)
177
+ self._v_sym = torch.as_tensor(ref._v, dtype=cdtype, device=self.device)
178
+
179
+ # integer node indices
180
+ ix = torch.arange(grid.shape[0], device=self.device)
181
+ iy = torch.arange(grid.shape[1], device=self.device)
182
+ self._ix, self._iy = torch.meshgrid(ix, iy, indexing="ij")
183
+
184
+ self._fused_advect = self._find_fused_kernel()
185
+ self._use_fused = self._fused_advect is not None
186
+
187
+ @property
188
+ def fused_kernel_name(self) -> str | None:
189
+ """``"triton"``, ``"metal"`` or None when only plain PyTorch is available."""
190
+ if self._fused_advect is None:
191
+ return None
192
+ return self._fused_advect.__module__.rsplit(".", 1)[-1].removesuffix("_advect")
193
+
194
+ @property
195
+ def use_fused_kernel(self) -> bool:
196
+ return self._use_fused
197
+
198
+ @use_fused_kernel.setter
199
+ def use_fused_kernel(self, value: bool) -> None:
200
+ if value and self._fused_advect is None:
201
+ raise ValueError(f"no fused advection kernel for {self.device} in {self.dtype}")
202
+ self._use_fused = bool(value)
203
+
204
+ def _find_fused_kernel(self):
205
+ """The native advection kernel for this device, or None to use plain PyTorch."""
206
+ if self.dtype != torch.float32 or self.device.type not in ("cuda", "mps"):
207
+ return None # no kernel is expected: no warning
208
+ try:
209
+ if self.device.type == "cuda":
210
+ from .kernels import triton_advect as module
211
+ else:
212
+ from .kernels import metal_advect as module
213
+ kernel = module.advect
214
+ # compile it now on a small case and compare with plain PyTorch, so
215
+ # that a toolchain or ABI problem shows up here as a fallback rather
216
+ # than as an exception or wrong results in the middle of a run
217
+ error = self._check_kernel(kernel)
218
+ except Exception as e:
219
+ reason = f"{e!r}"
220
+ else:
221
+ if error <= 1e-4:
222
+ return kernel
223
+ reason = f"relative error {error:.1e} against PyTorch"
224
+ warnings.warn(
225
+ f"fused advection kernel unavailable on {self.device} ({reason}); "
226
+ "the advection runs in plain PyTorch, about 20 times slower",
227
+ RuntimeWarning,
228
+ stacklevel=3,
229
+ )
230
+ return None
231
+
232
+ def _check_kernel(self, kernel) -> float:
233
+ """Relative difference between a kernel and the PyTorch path on a random case."""
234
+ # rectangular, and of the same divisibility by 16 as most grids, so that the
235
+ # Triton variant checked here is the one used: 2^k nodes, 2^k + 1 on walled axes
236
+ wx, wy = self.grid.walls
237
+ nx, ny = 16 + wx, 32 + wy
238
+ g = torch.Generator().manual_seed(0)
239
+ rand = [torch.rand((nx, ny), generator=g) * 2 - 1 for _ in range(8)]
240
+ f0, f1, u, v, u1, v1, u2, v2 = [r.to(self.device, self.dtype) for r in rand]
241
+ # two fields, the second one limited: both code paths of the kernel
242
+ args = (torch.stack([f0, f1]), (u, v), (u1, v1), (u2, v2), 1.5) # up to ~2 cells
243
+ walls = self.grid.walls # the variant this backend will use
244
+ out = kernel(*args, walls, 1)
245
+ ix, iy = torch.meshgrid(torch.arange(nx), torch.arange(ny), indexing="ij")
246
+ ref = self._advect_pytorch(*args, ix.to(self.device), iy.to(self.device), walls, 1)
247
+ return float((out - ref).abs().max() / ref.abs().max())
248
+
249
+ def _on_device_float32(self, *tensors) -> bool:
250
+ dev = self.device
251
+ return all(
252
+ t.dtype == torch.float32
253
+ and t.device.type == dev.type
254
+ and (dev.index is None or t.device.index == dev.index)
255
+ for t in tensors
256
+ if t is not None
257
+ )
258
+
259
+ def asarray(self, a) -> torch.Tensor:
260
+ """A new tensor of this backend's dtype and device, from an array or a tensor."""
261
+ if isinstance(a, torch.Tensor):
262
+ return a.detach().to(device=self.device, dtype=self.dtype, copy=True)
263
+ return torch.tensor(np.asarray(a), dtype=self.dtype, device=self.device) # a copy
264
+
265
+ def to_numpy(self, a: torch.Tensor) -> np.ndarray:
266
+ return a.detach().to("cpu", copy=True).numpy()
267
+
268
+ def stack(self, arrays) -> torch.Tensor:
269
+ return torch.stack(arrays)
270
+
271
+ def baroclinic(self, rho: torch.Tensor, buoyancy: float, gravity) -> torch.Tensor:
272
+ """See vicflow.buoyancy.baroclinic_source."""
273
+ gx, gy = gravity
274
+ out = torch.zeros_like(rho)
275
+ if gy:
276
+ out += gy * first_difference(rho, 0, self.grid.walls[0])
277
+ if gx:
278
+ out -= gx * first_difference(rho, 1, self.grid.walls[1])
279
+ return out * (buoyancy / self.grid.h)
280
+
281
+ def velocity(self, omega: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
282
+ for axis, wall in enumerate(self.grid.walls):
283
+ if wall:
284
+ omega = odd_extension(omega, axis)
285
+ w = torch.fft.rfft2(omega)
286
+ nx, ny = self.grid.shape
287
+ u = torch.fft.irfft2(w * self._u_sym, s=self._extended_shape)[:nx, :ny]
288
+ v = torch.fft.irfft2(w * self._v_sym, s=self._extended_shape)[:nx, :ny]
289
+ return u.contiguous(), v.contiguous()
290
+
291
+ def diffuse(self, field: torch.Tensor, nu: float, dt: float, h: float) -> torch.Tensor:
292
+ if nu <= 0:
293
+ return field.clone()
294
+ mult = dt * nu / h**2
295
+ nsub = 1 + int(mult / MAX_DIFFUSION_NUMBER)
296
+ m = mult / nsub
297
+ f = field.clone()
298
+ wx, wy = self.grid.walls
299
+ ax = f.dim() - 2 # the x axis: fields may be stacked, (k, nx, ny)
300
+ for _ in range(nsub):
301
+ f += m * (second_difference(f, ax, wx) + second_difference(f, ax + 1, wy))
302
+ return f
303
+
304
+ def _advect_pytorch(
305
+ self,
306
+ fields: torch.Tensor,
307
+ vel_now: Velocity,
308
+ vel_mid: Velocity,
309
+ vel_end: Velocity,
310
+ s: float,
311
+ ix: torch.Tensor | None = None,
312
+ iy: torch.Tensor | None = None,
313
+ walls: tuple[bool, bool] | None = None,
314
+ limit_from: int | None = None,
315
+ ) -> torch.Tensor:
316
+ """RK4 backtrace from every node, then M4' interpolation of the fields.
317
+
318
+ Same arguments as the fused kernels: velocities at t, t + dt/2 and
319
+ t + dt, ``s = dt / h``, and the first limited field. Works with
320
+ displacements from the nodes.
321
+ """
322
+ if ix is None or iy is None:
323
+ ix, iy = self._ix, self._iy
324
+ if walls is None:
325
+ walls = self.grid.walls
326
+ now, mid = torch.stack(vel_now), torch.stack(vel_mid)
327
+ k1 = vel_end
328
+ k2 = interpolate(mid, -0.5 * s * k1[0], -0.5 * s * k1[1], ix, iy, walls)
329
+ k3 = interpolate(mid, -0.5 * s * k2[0], -0.5 * s * k2[1], ix, iy, walls)
330
+ k4 = interpolate(now, -s * k3[0], -s * k3[1], ix, iy, walls)
331
+ dx = -s * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]) / 6
332
+ dy = -s * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]) / 6
333
+ return interpolate(fields, dx, dy, ix, iy, walls, limit_from)
334
+
335
+ def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None):
336
+ vel_now = (u, v)
337
+ if u_prev is None or v_prev is None:
338
+ vel_mid = vel_end = vel_now
339
+ else:
340
+ vel_end = (2 * u - u_prev, 2 * v - v_prev)
341
+ vel_mid = (1.5 * u - 0.5 * u_prev, 1.5 * v - 0.5 * v_prev)
342
+ if self._use_fused and self._on_device_float32(fields, u, v, u_prev, v_prev):
343
+ s, walls = dt / h, self.grid.walls
344
+ return self._fused_advect(fields, vel_now, vel_mid, vel_end, s, walls, limit_from)
345
+ return self._advect_pytorch(
346
+ fields, vel_now, vel_mid, vel_end, dt / h, limit_from=limit_from
347
+ )
vicflow/buoyancy.py ADDED
@@ -0,0 +1,45 @@
1
+ """Density and buoyancy (Boussinesq): vorticity created where density varies across gravity.
2
+
3
+ In the Boussinesq approximation the density only matters through gravity:
4
+ the vorticity grows at a rate ``buoyancy * (g_y d(rho)/dx - g_x d(rho)/dy)``
5
+ (vic2d's ``create_baroclinic_vorticity_2d``, with ``buoyancy`` its ``-b``).
6
+ With gravity pointing down, ``(0, -1)``, fluid with positive ``rho`` is heavy
7
+ and sinks.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+
14
+
15
+ def first_difference(f: np.ndarray, axis: int, wall: bool) -> np.ndarray:
16
+ """``(f[i+1] - f[i-1]) / 2`` along ``axis`` (a derivative times h).
17
+
18
+ On a wall axis, the wall nodes use one-sided 2nd-order differences,
19
+ as vic2d's ``find_gradient_of_scalar_2nd_2d``.
20
+ """
21
+ if not wall:
22
+ return 0.5 * (np.roll(f, -1, axis) - np.roll(f, 1, axis))
23
+ g = np.moveaxis(f, axis, 0)
24
+ d = np.empty_like(g)
25
+ d[1:-1] = 0.5 * (g[2:] - g[:-2])
26
+ d[0] = 0.5 * (-g[2] + 4 * g[1] - 3 * g[0])
27
+ d[-1] = 0.5 * (g[-3] - 4 * g[-2] + 3 * g[-1])
28
+ return np.moveaxis(d, 0, axis)
29
+
30
+
31
+ def baroclinic_source(
32
+ rho: np.ndarray,
33
+ h: float,
34
+ buoyancy: float,
35
+ gravity: tuple[float, float],
36
+ walls: tuple[bool, bool] = (False, False),
37
+ ) -> np.ndarray:
38
+ """Rate of vorticity creation by buoyancy, ``buoyancy * (g x grad(rho))``."""
39
+ gx, gy = gravity
40
+ out = np.zeros_like(rho)
41
+ if gy:
42
+ out += gy * first_difference(rho, 0, walls[0])
43
+ if gx:
44
+ out -= gx * first_difference(rho, 1, walls[1])
45
+ return out * (buoyancy / h)
vicflow/diffusion.py ADDED
@@ -0,0 +1,48 @@
1
+ """Explicit diffusion, periodic or with walls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ # largest diffusion number dt * nu / h**2 per explicit sub-step, as in vic2d
8
+ # (the 2D stability limit of the 5-point scheme is 0.25)
9
+ MAX_DIFFUSION_NUMBER = 0.125
10
+
11
+
12
+ def second_difference(f: np.ndarray, axis: int, wall: bool) -> np.ndarray:
13
+ """``f[i+1] - 2 f[i] + f[i-1]`` along ``axis`` (times h^2).
14
+
15
+ On a wall axis the wall nodes use vic2d's one-sided stencil
16
+ ``-f[2] + 6 f[1] - 5 f[0]`` (``diffuse_scalar_2d``).
17
+ """
18
+ if not wall:
19
+ return np.roll(f, 1, axis) + np.roll(f, -1, axis) - 2 * f
20
+ g = np.moveaxis(f, axis, 0)
21
+ d = np.empty_like(g)
22
+ d[1:-1] = g[2:] + g[:-2] - 2 * g[1:-1]
23
+ d[0] = -g[2] + 6 * g[1] - 5 * g[0]
24
+ d[-1] = -g[-3] + 6 * g[-2] - 5 * g[-1]
25
+ return np.moveaxis(d, 0, axis)
26
+
27
+
28
+ def diffuse(
29
+ field: np.ndarray, nu: float, dt: float, h: float, walls: tuple[bool, bool] = (False, False)
30
+ ) -> np.ndarray:
31
+ """Explicit 5-point diffusion over one time step.
32
+
33
+ ``field`` has shape ``(nx, ny)``, or ``(k, nx, ny)`` for a stack of fields
34
+ diffused together (e.g. color channels). The step is split into as many
35
+ equal sub-steps as needed to keep the diffusion number below
36
+ ``MAX_DIFFUSION_NUMBER`` (vic2d's ``diffuse_scalar_2d``). ``walls`` tells
37
+ which axes are walled (see ``second_difference``). Returns a new array.
38
+ """
39
+ if nu <= 0:
40
+ return field.copy()
41
+ mult = dt * nu / h**2
42
+ nsub = 1 + int(mult / MAX_DIFFUSION_NUMBER)
43
+ m = mult / nsub
44
+ f = field.copy()
45
+ ax = f.ndim - 2 # the x axis
46
+ for _ in range(nsub):
47
+ f += m * (second_difference(f, ax, walls[0]) + second_difference(f, ax + 1, walls[1]))
48
+ return f
vicflow/grid.py ADDED
@@ -0,0 +1,69 @@
1
+ """Uniform grids."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ import numpy as np
9
+
10
+ Boundary = Literal["periodic", "wall"]
11
+ BOUNDARIES = ("periodic", "wall")
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Grid:
16
+ """Grid of ``nx`` by ``ny`` square cells, with a boundary type per axis.
17
+
18
+ The longer side of the domain has length 1, as in vic2d: node ``(i, j)``
19
+ sits at ``(i * h, j * h)`` with ``h = 1 / max(nx, ny)``.
20
+
21
+ - On a ``"periodic"`` axis there are ``n`` nodes: node ``n`` would wrap
22
+ back onto node 0.
23
+ - On a ``"wall"`` axis there are ``n + 1`` nodes, and the first and last
24
+ ones lie on the walls (no-slip, impermeable).
25
+
26
+ Fields on this grid are arrays of shape ``shape`` indexed ``[ix, iy]``
27
+ (x first, y increasing upwards), like the C arrays of vic2d. vic2d's
28
+ ``-x 256 -y 256`` (walls by default) is ``Grid(256, 256, "wall", "wall")``,
29
+ 257 x 257 nodes; with ``-px -py`` it is ``Grid(256, 256)``, 256 x 256
30
+ nodes (vic2d also stores a duplicate of the first node at the end).
31
+ """
32
+
33
+ nx: int
34
+ ny: int
35
+ x_boundary: Boundary = "periodic"
36
+ y_boundary: Boundary = "periodic"
37
+
38
+ def __post_init__(self) -> None:
39
+ if self.nx < 4 or self.ny < 4:
40
+ raise ValueError(f"grid must have at least 4 cells per side, got {self.nx}x{self.ny}")
41
+ for b in (self.x_boundary, self.y_boundary):
42
+ if b not in BOUNDARIES:
43
+ raise ValueError(f"unknown boundary {b!r}, expected one of {BOUNDARIES}")
44
+
45
+ @classmethod
46
+ def square(cls, n: int, boundary: Boundary = "periodic") -> Grid:
47
+ return cls(n, n, boundary, boundary)
48
+
49
+ @property
50
+ def walls(self) -> tuple[bool, bool]:
51
+ """Whether the x and y axes are bounded by walls."""
52
+ return (self.x_boundary == "wall", self.y_boundary == "wall")
53
+
54
+ @property
55
+ def shape(self) -> tuple[int, int]:
56
+ """Number of nodes along x and y."""
57
+ wx, wy = self.walls
58
+ return (self.nx + wx, self.ny + wy)
59
+
60
+ @property
61
+ def h(self) -> float:
62
+ """Cell size."""
63
+ return 1.0 / max(self.nx, self.ny)
64
+
65
+ def coords(self) -> tuple[np.ndarray, np.ndarray]:
66
+ """Node coordinates ``x, y`` as two arrays of shape ``shape``."""
67
+ x = np.arange(self.shape[0]) * self.h
68
+ y = np.arange(self.shape[1]) * self.h
69
+ return np.meshgrid(x, y, indexing="ij")
vicflow/image.py ADDED
@@ -0,0 +1,89 @@
1
+ """PNG images to and from fields.
2
+
3
+ Fields are indexed ``[ix, iy]`` with y upwards; images are stored row by row
4
+ from the top. Pixel column ``i``, row ``r`` of an image of height ``ny`` is
5
+ node ``(i, ny - 1 - r)``: the image looks like the field plotted with y up,
6
+ as in vic2d. A color field has shape ``(channels, nx, ny)``.
7
+
8
+ Pixel values ``0 .. 2^bits - 1`` map linearly to ``[vmin, vmax]``, by default
9
+ ``[0, 1]``. This is vic2d's convention for color images (``-cf``, and the
10
+ ``out_*.png`` it writes), except that vic2d writes 8-bit images with a
11
+ factor 256 instead of 255: its 8-bit outputs read back about 0.4 % too
12
+ bright. Its grayscale images (vorticity, density) use other scales.
13
+
14
+ The image must have one pixel per node; vic2d grids have an extra node on
15
+ periodic axes (a copy of the first), so a vic2d image of an ``n``-cell
16
+ periodic axis has ``n + 1`` pixels: drop the last one (``f[:, :-1]``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from os import PathLike
22
+
23
+ import numpy as np
24
+ import png
25
+
26
+ PLANES = {1: "L", 2: "LA", 3: "RGB", 4: "RGBA"}
27
+
28
+
29
+ def read_image(path: str | PathLike, vmin: float = 0.0, vmax: float = 1.0) -> np.ndarray:
30
+ """All the channels of a PNG, as a float64 array ``(channels, nx, ny)``.
31
+
32
+ The channels are those of the file: 1 (grayscale), 2 (grayscale and
33
+ alpha), 3 (RGB) or 4 (RGBA); palette images are expanded to RGB(A).
34
+ Values are mapped from ``0 .. 2^bits - 1`` to ``[vmin, vmax]``.
35
+ """
36
+ width, height, rows, info = png.Reader(filename=str(path)).asDirect()
37
+ planes, bits = info["planes"], info["bitdepth"]
38
+ img = np.vstack([np.asarray(r, dtype=np.float64) for r in rows])
39
+ img = img.reshape(height, width, planes)
40
+ fields = np.flip(img, 0).transpose(2, 1, 0) # (channels, x, y), y up
41
+ return vmin + (vmax - vmin) * fields / (2**bits - 1)
42
+
43
+
44
+ def read_color(path: str | PathLike, vmin: float = 0.0, vmax: float = 1.0) -> np.ndarray:
45
+ """An RGB color field ``(3, nx, ny)`` from a PNG, values in ``[vmin, vmax]``.
46
+
47
+ Grayscale images give three equal channels; an alpha channel is ignored.
48
+ """
49
+ f = read_image(path, vmin, vmax)
50
+ if len(f) in (2, 4):
51
+ f = f[:-1] # drop alpha
52
+ return np.repeat(f, 3, axis=0) if len(f) == 1 else f
53
+
54
+
55
+ def write_image(
56
+ path: str | PathLike,
57
+ field,
58
+ bits: int = 8,
59
+ vmin: float = 0.0,
60
+ vmax: float = 1.0,
61
+ ) -> None:
62
+ """Write a field to a PNG of 8 or 16 bits per channel.
63
+
64
+ ``field`` is ``(nx, ny)`` (grayscale) or ``(channels, nx, ny)`` with 1 to
65
+ 4 channels (gray, gray and alpha, RGB, RGBA). NumPy arrays and torch
66
+ tensors (on any device) are accepted. ``[vmin, vmax]`` maps to
67
+ ``0 .. 2^bits - 1``; values outside are clipped, NaNs raise an error.
68
+ """
69
+ if bits not in (8, 16):
70
+ raise ValueError(f"bits must be 8 or 16, got {bits}")
71
+ if vmax == vmin:
72
+ raise ValueError("vmin and vmax must differ")
73
+ if hasattr(field, "detach"): # a torch tensor
74
+ field = field.detach().cpu().float().numpy() # float: numpy has no bfloat16
75
+ f = np.asarray(field, dtype=np.float64)
76
+ if f.ndim == 2:
77
+ f = f[None]
78
+ if f.ndim != 3 or len(f) not in PLANES:
79
+ raise ValueError(f"expected (nx, ny) or (1 to 4, nx, ny), got shape {np.shape(field)}")
80
+ if np.isnan(f).any():
81
+ raise ValueError("the field has NaNs")
82
+ top = 2**bits - 1
83
+ p = np.rint(np.clip((f - vmin) / (vmax - vmin), 0, 1) * top)
84
+ channels, nx, ny = p.shape
85
+ rows = np.flip(p.transpose(2, 1, 0), 0) # (y from the top, x, channels)
86
+ rows = rows.astype(np.uint16 if bits == 16 else np.uint8).reshape(ny, nx * channels)
87
+ writer = png.Writer(nx, ny, greyscale=channels < 3, alpha=channels in (2, 4), bitdepth=bits)
88
+ with open(path, "wb") as out:
89
+ writer.write_array(out, rows.ravel())