|
| 1 | +"""Tests for the transparent rolling time-window cache (WindowedArray).""" |
| 2 | + |
| 3 | +import dask.array as da |
| 4 | +import numpy as np |
| 5 | +import pytest |
| 6 | +import xarray as xr |
| 7 | + |
| 8 | +from parcels import FieldSet, ParticleSet |
| 9 | +from parcels._core._windowed_array import WindowedArray, maybe_windowed |
| 10 | +from parcels._datasets.structured.generated import simple_UV_dataset |
| 11 | +from parcels.kernels import AdvectionRK2 |
| 12 | + |
| 13 | + |
| 14 | +def test_windowed_isel_matches_dask_loads_once_and_evicts(): |
| 15 | + """WindowedArray.isel must equal dask isel, load each level once, keep <=2 resident.""" |
| 16 | + ntime, n, npart = 20, 64, 200 |
| 17 | + rng = np.random.default_rng(0) |
| 18 | + base = rng.standard_normal((ntime, 3, n, n)) |
| 19 | + lazy = xr.DataArray(da.from_array(base, chunks=(1, 3, n, n)), dims=("time", "depth", "lat", "lon")) |
| 20 | + win = WindowedArray(lazy) |
| 21 | + |
| 22 | + worst, max_cache = 0.0, 0 |
| 23 | + for step in range(40): |
| 24 | + ti = min(step // 2, ntime - 2) # advancing clock, 2 sub-steps per level |
| 25 | + yi, xi = rng.integers(0, n, npart), rng.integers(0, n, npart) |
| 26 | + zi = np.zeros(npart, dtype=int) |
| 27 | + sel = dict( |
| 28 | + time=xr.DataArray(np.r_[np.full(npart, ti), np.full(npart, ti + 1)], dims="p"), |
| 29 | + depth=xr.DataArray(np.r_[zi, zi], dims="p"), |
| 30 | + lat=xr.DataArray(np.r_[yi, yi], dims="p"), |
| 31 | + lon=xr.DataArray(np.r_[xi, xi], dims="p"), |
| 32 | + ) |
| 33 | + got = win.isel(sel).data |
| 34 | + ref = lazy.isel(sel).data.compute() |
| 35 | + worst = max(worst, float(np.abs(got - ref).max())) |
| 36 | + max_cache = max(max_cache, len(win._cache)) |
| 37 | + |
| 38 | + assert worst == 0.0 # byte-identical to dask |
| 39 | + assert win.loads == ntime # each time level read exactly once |
| 40 | + assert max_cache <= 2 # only the bracketing levels resident |
| 41 | + |
| 42 | + |
| 43 | +def test_to_windowed_arrays_wraps_dask_but_not_numpy(): |
| 44 | + ds = simple_UV_dataset(mesh="flat") |
| 45 | + fs_np = FieldSet.from_sgrid_conventions(ds, mesh="flat") |
| 46 | + fs_dk = FieldSet.from_sgrid_conventions(ds.chunk({"time": 1}), mesh="flat") |
| 47 | + |
| 48 | + # construction is never windowing -- it is opt-in via the fieldset method |
| 49 | + assert not isinstance(fs_np.U.data, WindowedArray) |
| 50 | + assert not isinstance(fs_dk.U.data, WindowedArray) |
| 51 | + |
| 52 | + assert fs_np.to_windowed_arrays() is fs_np # chainable |
| 53 | + fs_dk.to_windowed_arrays() |
| 54 | + |
| 55 | + # numpy-backed field is left eager; dask-backed field gets wrapped |
| 56 | + assert not isinstance(fs_np.U.data, WindowedArray) |
| 57 | + assert isinstance(fs_dk.U.data, WindowedArray) |
| 58 | + # transparency: forwarded attributes still behave like the DataArray |
| 59 | + assert fs_dk.U.data.dims == fs_np.U.data.dims |
| 60 | + assert fs_dk.U.data.shape == fs_np.U.data.shape |
| 61 | + |
| 62 | + |
| 63 | +def test_to_windowed_arrays_is_idempotent_and_forwards_max_levels(): |
| 64 | + ds = simple_UV_dataset(mesh="flat") |
| 65 | + fs = FieldSet.from_sgrid_conventions(ds.chunk({"time": 1}), mesh="flat") |
| 66 | + |
| 67 | + fs.to_windowed_arrays(max_levels=3) |
| 68 | + first = fs.U.data |
| 69 | + assert isinstance(first, WindowedArray) |
| 70 | + assert first._max == 3 |
| 71 | + |
| 72 | + # re-wrapping returns the same object (idempotent, warm cache preserved) |
| 73 | + fs.to_windowed_arrays(max_levels=3) |
| 74 | + assert fs.U.data is first |
| 75 | + |
| 76 | + |
| 77 | +def test_maybe_windowed_passthrough_for_non_time_leading(): |
| 78 | + da_no_time = xr.DataArray(da.zeros((3, 4), chunks=(3, 4)), dims=("lat", "lon")) |
| 79 | + assert maybe_windowed(da_no_time) is da_no_time # not wrapped (no leading time dim) |
| 80 | + |
| 81 | + |
| 82 | +@pytest.mark.parametrize("mesh", ["flat", "spherical"]) |
| 83 | +def test_dask_advection_matches_numpy(mesh): |
| 84 | + """An identical advection must give identical trajectories whether the field |
| 85 | + is numpy-backed or dask-backed (windowed). |
| 86 | + """ |
| 87 | + ds = simple_UV_dataset(mesh=mesh) |
| 88 | + ds["U"].data[:] = 1.0 # steady zonal flow -> in-bounds, deterministic |
| 89 | + |
| 90 | + def run(chunked): |
| 91 | + d = ds.chunk({"time": 1}) if chunked else ds |
| 92 | + fs = FieldSet.from_sgrid_conventions(d, mesh=mesh) |
| 93 | + if chunked: |
| 94 | + fs.to_windowed_arrays() |
| 95 | + pset = ParticleSet(fs, lon=np.zeros(10), lat=np.linspace(-10, 10, 10)) |
| 96 | + pset.execute(AdvectionRK2, runtime=7200, dt=np.timedelta64(15, "m")) |
| 97 | + return np.array(pset.lon), np.array(pset.lat) |
| 98 | + |
| 99 | + lon_np, lat_np = run(False) |
| 100 | + lon_dk, lat_dk = run(True) |
| 101 | + np.testing.assert_allclose(lon_dk, lon_np, atol=1e-9) |
| 102 | + np.testing.assert_allclose(lat_dk, lat_np, atol=1e-9) |
0 commit comments