Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/parcels/_chunk_cached_array/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def __init__(self, dask_array: dask.array.Array, max_cache_bytes: int) -> None:
self._boundaries.append(np.concatenate(([0], np.cumsum(dim_chunks))))

def get_duck_array(self):
return self.array.compute()
return self.array
Comment on lines 76 to +77

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though there is the problem that users writing interpolators should never really be using da.data when using ChunkedArrays (since it falls back to Dask, which is less performant, or (before this PR) uses Numpy, which causes eager computation of results.

Implementing get_duck_array at all could result in users writing interpolators that have really bad performance.

I'm thinking maybe the solution is just to do a raise NotImplementedError here. This would mean that users can't inspect the data using a da.data, but I think thats acceptable (users won't be inspecting this anyway).

Thoughts @erikvansebille ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that .data bypasses the chunk cache. I tested raising from get_duck_array at this head. It also makes .values and np.asarray(data_array) raise NotImplementedError; vectorized .isel(...).data still works. The API decision therefore includes whether explicit whole-array materialization should remain supported.

For test scope, the no-computation assertion fails on the original Parcels implementation because get_duck_array computes the chunks. The separate module can be reduced to a focused integration regression once the accessor contract is settled.


def _raw_vindex(self, *indices: np.ndarray) -> np.ndarray:
"""Vectorized indexing with chunk caching.
Expand Down
50 changes: 50 additions & 0 deletions tests/test_chunk_cached_array.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that this test file is necessary. FWICT its pretty much just testing that dataarray.data is a Dask array (and testing Dask functionality).

I don't think its worth including in our test suite

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import dask
import dask.array as da
import numpy as np
import xarray as xr

from parcels._chunk_cached_array import ChunkCachedArray, wrap_dataset


def test_chunk_cached_data_stays_lazy_until_explicit_materialization():
loaded = []

@dask.delayed
def chunk(index):
loaded.append(index)
return np.arange(16 * index, 16 * index + 16).reshape(4, 4)

array = da.concatenate([da.from_delayed(chunk(i), shape=(4, 4), dtype=int) for i in range(2)])
dataset = wrap_dataset(xr.Dataset({"value": (("x", "y"), array)}), max_cache_bytes=1024)

with dask.config.set(scheduler="synchronous"):
data = dataset.value.data
assert isinstance(data, da.Array)
assert loaded == []

np.testing.assert_array_equal(dataset.value.values, np.arange(32).reshape(8, 4))
assert sorted(loaded) == [0, 1]

loaded.clear()
np.testing.assert_array_equal(np.asarray(dataset.value), np.arange(32).reshape(8, 4))
assert sorted(loaded) == [0, 1]


def test_chunk_cached_vectorized_selection_reuses_cached_chunk():
loaded = []

@dask.delayed
def chunk(index):
loaded.append(index)
return np.arange(16 * index, 16 * index + 16).reshape(4, 4)

array = da.concatenate([da.from_delayed(chunk(i), shape=(4, 4), dtype=int) for i in range(2)])
dataset = wrap_dataset(xr.Dataset({"value": (("x", "y"), array)}), max_cache_bytes=1024)
assert isinstance(dataset.value.variable._data, ChunkCachedArray)
indices = {"x": xr.DataArray([0, 1], dims="points"), "y": xr.DataArray([1, 2], dims="points")}

with dask.config.set(scheduler="synchronous"):
np.testing.assert_array_equal(dataset.value.isel(indices).data, [1, 6])
assert loaded == [0]
np.testing.assert_array_equal(dataset.value.isel(indices).data, [1, 6])
assert loaded == [0]
12 changes: 12 additions & 0 deletions tests/test_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
VectorField,
particlefile_to_v3_zarr,
)
from parcels._chunk_cached_array import ChunkCachedArray
from parcels._core.index_search import _search_time_index
from parcels._core.mesh import get_mesh
from parcels._datasets.structured.generated import simple_UV_dataset
Expand Down Expand Up @@ -118,6 +119,17 @@ def test_raw_2d_interpolation(field, interpolator, t, z, y, x, expected):
np.testing.assert_equal(value, expected)


def test_linear_interpolation_with_chunk_cached_data(field):
field.model.data = field.model.data.chunk({"time": 1, "depth": 1, "lat": 2, "lon": 2})
field.model.to_chunk_cached_arrays(max_cache_bytes=1024)
assert isinstance(field.data.variable._data, ChunkCachedArray)
particle_positions = {"time": [0, 1], "z": [0, 0], "lat": [0.49, 0.49], "lon": [0.51, 0.51]}
grid_positions = field.grid.search(particle_positions["z"], particle_positions["lat"], particle_positions["lon"])
grid_positions.update(_search_time_index(field, particle_positions["time"]))

np.testing.assert_allclose(field.interp_method.interp(particle_positions, grid_positions, field), [1.49, 6.49])


@pytest.mark.parametrize("mesh", ["flat", "spherical"])
@pytest.mark.parametrize(
"func, t, z, y, x, expected",
Expand Down