diff --git a/docs/api.rst b/docs/api.rst index 22645d3ba..76faf6b18 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -25,6 +25,7 @@ Top Level Functions open_multigrid open_mfdataset concat + map_blocks Tutorial -------- @@ -187,6 +188,7 @@ Attributes :toctree: generated/ Grid.attrs + Grid.chunks Methods @@ -254,6 +256,15 @@ Selection & Indexing UxDataArray.where +Parallel Computing +~~~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + + UxDataArray.map_blocks + + Grid Accessor ~~~~~~~~~~~~~ @@ -326,6 +337,15 @@ Selection & Indexing UxDataset.where +Parallel Computing +~~~~~~~~~~~~~~~~~~ + +.. autosummary:: + :toctree: generated/ + + UxDataset.map_blocks + + Conversion Methods ------------------ diff --git a/test/core/test_dask.py b/test/core/test_dask.py index 37edc9bbc..19560f341 100644 --- a/test/core/test_dask.py +++ b/test/core/test_dask.py @@ -1,6 +1,8 @@ import dask.array as da import numpy as np +import numpy.testing as nt +import pytest import uxarray as ux @@ -13,12 +15,43 @@ def test_grid_chunking(gridpath): assert isinstance(uxgrid._ds[var].data, np.ndarray) # chunk every data variable - uxgrid.chunk(n_node=1, n_face=2, n_edge=4) + uxgrid.chunk(n_node=1, n_face=2, n_edge=4, inplace=True) for var in uxgrid._ds: # variables should all be da.Array assert isinstance(uxgrid._ds[var].data, da.Array) +def test_grid_chunk_default_warns_and_chunks_in_place(gridpath): + """Without inplace, Grid.chunk() keeps chunking in place but warns about the coming default.""" + uxgrid = ux.open_grid(gridpath("mpas", "QU", "oQU480.231010.nc")) + + with pytest.warns(FutureWarning, match="inplace=False"): + result = uxgrid.chunk(n_face=500) + + assert result is None + assert uxgrid.chunks["n_face"] == (500, 500, 500, 291) + +def test_grid_chunk_not_in_place(gridpath): + """Grid.chunk(inplace=False) returns a new chunked grid and leaves the original untouched.""" + uxgrid = ux.open_grid(gridpath("mpas", "QU", "oQU480.231010.nc")) + + chunked = uxgrid.chunk(n_node=1000, n_edge=2000, n_face=500, inplace=False) + + assert isinstance(chunked, ux.Grid) and chunked is not uxgrid + assert dict(uxgrid.chunks) == {} + for var in uxgrid._ds: + assert isinstance(uxgrid._ds[var].data, np.ndarray) + + assert chunked.chunks["n_node"] == (1000, 1000, 1000, 947) + assert chunked.chunks["n_edge"] == (2000, 2000, 1754) + assert chunked.chunks["n_face"] == (500, 500, 500, 291) + nt.assert_array_equal(chunked.face_node_connectivity.values, uxgrid.face_node_connectivity.values) + + # a variable built lazily on the copy must not appear on the original + _ = chunked.bounds + assert "bounds" in chunked._ds + assert "bounds" not in uxgrid._ds + def test_individual_var_chunking(gridpath): """Tests the chunking of a single grid variable.""" uxgrid = ux.open_grid(gridpath("mpas", "QU", "oQU480.231010.nc")) diff --git a/test/core/test_map_blocks.py b/test/core/test_map_blocks.py new file mode 100644 index 000000000..60c47b843 --- /dev/null +++ b/test/core/test_map_blocks.py @@ -0,0 +1,250 @@ +import dask.array as da +import numpy as np +import numpy.testing as nt +import pytest +import xarray as xr + +import uxarray as ux +from uxarray.errors import DimensionError + + +@pytest.fixture +def uxds(gridpath, datasetpath): + # multi_dim_data has dims (time=8, lev=8, n_face=4) + return ux.open_dataset( + gridpath("ugrid", "quad-hexagon", "grid.nc"), + datasetpath("ugrid", "quad-hexagon", "multi_dim_data.nc"), + ) + + +def _times_face_areas(block): + return block * block.uxgrid.face_areas + + +def test_blocks_split_off_grid_get_whole_grid(uxds): + """Chunked only along time, every block carries the original grid object.""" + uxda = uxds["multi_dim_data"] + seen = [] + + def func(block): + if block.size: # skip the zero-size call xarray uses to infer the output + seen.append((type(block), block.uxgrid)) + return _times_face_areas(block) + + result = uxda.chunk(time=2).map_blocks(func) + + assert isinstance(result, ux.UxDataArray) + assert result.uxgrid is uxda.uxgrid + assert isinstance(result.data, da.Array) + nt.assert_allclose(result.values, (uxda * uxda.uxgrid.face_areas).values) + assert len(seen) == 4 + assert all(cls is ux.UxDataArray and grid is uxda.uxgrid for cls, grid in seen) + + +def test_blocks_split_along_n_face_get_matching_subgrid(uxds): + """Chunked along n_face, each block carries the sub-grid of exactly its faces.""" + uxda = uxds["multi_dim_data"] + face_lon = uxda.uxgrid.face_lon.values + + def stamp_face_lon(block): + assert block.uxgrid.n_face == block.sizes["n_face"] + return block.copy(data=np.broadcast_to(block.uxgrid.face_lon.values, block.shape).copy()) + + for n_face in (1, 3): + result = ux.map_blocks(stamp_face_lon, uxda.chunk(n_face=n_face)) + nt.assert_array_equal(result.isel(time=0, lev=0).values, face_lon) + + result = ux.map_blocks(_times_face_areas, uxda.chunk(time=4, n_face=2)) + assert result.uxgrid is uxda.uxgrid + nt.assert_allclose(result.values, (uxda * uxda.uxgrid.face_areas).values) + # nothing used to locate each block leaks into the result + assert set(result.coords) == set(uxda.coords) + + +def test_dataset_map_blocks(uxds): + result = uxds.chunk(n_face=2).map_blocks(_times_face_areas) + + assert isinstance(result, ux.UxDataset) + assert result.uxgrid is uxds.uxgrid + nt.assert_allclose( + result["multi_dim_data"].values, + (uxds["multi_dim_data"] * uxds.uxgrid.face_areas).values, + ) + + +def test_array_args_share_block_grid(uxds): + """DataArray args are split alongside obj and carry the same sub-grid as its block.""" + uxda = uxds["multi_dim_data"].chunk(n_face=2) + + def add(block, other): + assert isinstance(other, ux.UxDataArray) + assert other.uxgrid is block.uxgrid + return block + other + + result = ux.map_blocks(add, uxda, args=[uxda * 2]) + nt.assert_allclose(result.values, 3 * uxds["multi_dim_data"].values) + + +def test_template(uxds): + uxda = uxds["multi_dim_data"].chunk(n_face=2) + + result = ux.map_blocks(_times_face_areas, uxda, template=uxda) + + assert isinstance(result, ux.UxDataArray) + nt.assert_allclose(result.values, (uxda * uxda.uxgrid.face_areas).values) + + +def test_not_dask_calls_func_directly(uxds): + uxda = uxds["multi_dim_data"] + result = uxda.map_blocks(lambda block: block + 1) + assert isinstance(result.data, np.ndarray) + nt.assert_allclose(result.values, uxda.values + 1) + + +def test_rejects_plain_xarray(): + with pytest.raises(TypeError, match="UxDataArray or UxDataset"): + ux.map_blocks(lambda block: block, xr.DataArray(da.ones(3))) + + +@pytest.fixture +def mpas_grid(gridpath): + return ux.open_grid(gridpath("mpas", "QU", "oQU480.231010.nc")) + + +def _random_on(uxgrid, grid_dim, n_time=3): + rng = np.random.default_rng(0) + data = rng.random((n_time, uxgrid.sizes[grid_dim])) + return ux.UxDataArray(xr.DataArray(data, dims=["time", grid_dim]), uxgrid=uxgrid) + + +def test_node_split_coriolis(mpas_grid): + """Split along n_node, blocks keep the whole grid and get node_lat for their own nodes.""" + vorticity = _random_on(mpas_grid, "n_node") + omega = 7.292e-5 + seen = [] + + def absolute_vorticity(block, node_lat): + if block.size: # skip the zero-size call xarray uses to infer the output + seen.append((block.uxgrid, block.sizes["n_node"], node_lat.sizes["n_node"])) + return block + 2 * omega * np.sin(np.deg2rad(node_lat)) + + result = ux.map_blocks( + absolute_vorticity, vorticity.chunk(n_node=1000), args=[mpas_grid.node_lat] + ) + + assert isinstance(result, ux.UxDataArray) + assert result.uxgrid is mpas_grid + expected = vorticity + 2 * omega * np.sin(np.deg2rad(mpas_grid.node_lat)) + nt.assert_allclose(result.values, expected.values) + assert len(seen) == 4 + assert all(grid is mpas_grid and n == n_lat for grid, n, n_lat in seen) + + +def test_edge_split_transport(mpas_grid): + """Split along n_edge, blocks get the edge lengths for their own edges.""" + normal_velocity = _random_on(mpas_grid, "n_edge") + edge_length = mpas_grid.edge_node_distances + + result = normal_velocity.chunk(n_edge=2000, time=1).map_blocks( + lambda block, length: block * length, args=[edge_length] + ) + + assert result.uxgrid is mpas_grid + nt.assert_allclose(result.values, (normal_velocity * edge_length).values) + + +def test_face_split_gathers_node_args(mpas_grid): + """With n_face split, node data in args is gathered onto each block's sub-grid, + so a node-to-face aggregation per block matches the eager result.""" + node_data = _random_on(mpas_grid, "n_node") + face_template = _random_on(mpas_grid, "n_face").chunk(n_face=500, time=1) + seen = [] + + def node_to_face(block, nodes): + if block.size: # skip the zero-size call xarray uses to infer the output + seen.append((nodes.uxgrid is block.uxgrid, nodes.sizes["n_node"], block.uxgrid.n_node)) + return nodes.topological_mean(destination="face") + + # args must match obj's chunks along shared non-grid dims, as in xarray.map_blocks + result = ux.map_blocks(node_to_face, face_template, args=[node_data.chunk(time=1)]) + + expected = node_data.topological_mean(destination="face") + nt.assert_allclose(result.values, expected.values) + assert len(seen) == 12 + assert all(same_grid and n == n_grid for same_grid, n, n_grid in seen) + + +def test_face_split_gathers_chunked_node_args(mpas_grid): + """A node arg chunked along n_node is still gathered whole onto each block's sub-grid.""" + node_data = _random_on(mpas_grid, "n_node") + face_template = _random_on(mpas_grid, "n_face").chunk(n_face=500) + + result = ux.map_blocks( + lambda block, nodes: nodes.topological_mean(destination="face"), + face_template, + args=[node_data.chunk(n_node=1000)], + ) + + expected = node_data.topological_mean(destination="face") + nt.assert_allclose(result.values, expected.values) + + +def _edge_to_face_mean(edges, uxgrid): + """Mean of each face's edge values, read through the grid's face_edge_connectivity.""" + conn = uxgrid.face_edge_connectivity.values + valid = conn != ux.INT_FILL_VALUE + values = edges.values[..., np.where(valid, conn, 0)] + return (values * valid).sum(axis=-1) / valid.sum(axis=-1) + + +def test_face_split_gathers_edge_args(gridpath): + """With n_face split, edge data in args is gathered onto each block's sub-grid, + even when the grid had not built face_edge_connectivity yet.""" + uxgrid = ux.open_grid(gridpath("mpas", "QU", "oQU480.231010.nc")) + edge_data = _random_on(uxgrid, "n_edge") + face_template = _random_on(uxgrid, "n_face").chunk(n_face=500) + + def edge_to_face(block, edges): + return block.copy(data=_edge_to_face_mean(edges, block.uxgrid)) + + result = ux.map_blocks(edge_to_face, face_template, args=[edge_data]) + + nt.assert_allclose(result.values, _edge_to_face_mean(edge_data, uxgrid)) + + +def test_face_split_rejects_args_on_face_and_node(mpas_grid): + face_data = _random_on(mpas_grid, "n_face") + both = ux.UxDataset({"face": face_data, "node": _random_on(mpas_grid, "n_node")}, uxgrid=mpas_grid) + + with pytest.raises(DimensionError, match="not both"): + ux.map_blocks(lambda block, other: block, face_data.chunk(n_face=500), args=[both]) + + +def test_args_rechunked_to_match(mpas_grid): + """Grid variables chunked differently from obj are rechunked to match it.""" + face_data = _random_on(mpas_grid, "n_face").chunk(n_face=500) + areas = mpas_grid.face_areas.chunk(n_face=7) + + result = ux.map_blocks(lambda block, area: block * area, face_data, args=[areas]) + + nt.assert_allclose(result.values, (face_data * mpas_grid.face_areas).values) + + +def test_rejects_mixed_grid_dims(mpas_grid): + face_data = _random_on(mpas_grid, "n_face") + node_data = _random_on(mpas_grid, "n_node") + edge_data = _random_on(mpas_grid, "n_edge") + + # n_face split while node data is also present: the blocks cover unrelated parts of the grid + mixed = ux.UxDataset({"face": face_data, "node": node_data}, uxgrid=mpas_grid) + with pytest.raises(DimensionError, match="do not line up"): + ux.map_blocks(lambda block: block, mixed.chunk(n_face=500)) + + # two grid dimensions split at once + mixed = ux.UxDataset({"node": node_data, "edge": edge_data}, uxgrid=mpas_grid) + with pytest.raises(DimensionError, match="do not line up"): + ux.map_blocks(lambda block: block, mixed.chunk(n_node=1000, n_edge=2000)) + + # mixed grid dims split only off-grid are fine, and get the whole grid + result = mixed.chunk(time=1).map_blocks(lambda block: block + block.uxgrid.node_lon) + nt.assert_allclose(result["node"].values, (node_data + mpas_grid.node_lon).values) diff --git a/test/test_cross_sections.py b/test/test_cross_sections.py index 0ae2201af..c0ff6e7c0 100644 --- a/test/test_cross_sections.py +++ b/test/test_cross_sections.py @@ -151,7 +151,7 @@ def test_edges_at_constant_lat_lon_chunked_grid(gridpath): # leaving both the connectivity and the node coordinates dask-backed. _ = chunked.edge_node_connectivity _ = chunked.node_x, chunked.node_y, chunked.node_z - chunked.chunk(n_node=2, n_edge=4, n_face=2) + chunked.chunk(n_node=2, n_edge=4, n_face=2, inplace=True) assert isinstance(chunked.edge_node_connectivity.data, da.Array) for coord in (chunked.node_x, chunked.node_y, chunked.node_z): diff --git a/uxarray/__init__.py b/uxarray/__init__.py index e6f35f934..39ab01021 100644 --- a/uxarray/__init__.py +++ b/uxarray/__init__.py @@ -13,6 +13,7 @@ ) from .core.dataarray import UxDataArray from .core.dataset import UxDataset +from .core.parallel import map_blocks from .grid import Grid try: @@ -31,6 +32,7 @@ "concat", "errors", "list_grid_names", + "map_blocks", "open_dataset", "open_grid", "open_mfdataset", diff --git a/uxarray/core/dataarray.py b/uxarray/core/dataarray.py index f49085024..ec1668083 100644 --- a/uxarray/core/dataarray.py +++ b/uxarray/core/dataarray.py @@ -642,6 +642,17 @@ def to_xarray(self) -> xr.DataArray: dict(self._indexes), ) + def map_blocks(self, func, args=(), kwargs=None, template=None): + """Apply a function to each block of this UxDataArray, keeping the + grid attached to each block and to the result. + + Equivalent to ``ux.map_blocks(func, self, args, kwargs, template)``; + see :py:func:`uxarray.map_blocks` for details. + """ + from uxarray.core.parallel import map_blocks + + return map_blocks(func, self, args, kwargs, template) + def astype(self, dtype, **kw_super): """Copy of this uxarray object, with data cast to a specified type. Leaves coordinate dtype unchanged. diff --git a/uxarray/core/dataset.py b/uxarray/core/dataset.py index 2bab25cb4..e971420a0 100644 --- a/uxarray/core/dataset.py +++ b/uxarray/core/dataset.py @@ -983,6 +983,17 @@ def to_xarray(self, grid_format: str = "UGRID") -> xr.Dataset: result = result.rename_dims({"n_face": "cell"}) return result + def map_blocks(self, func, args=(), kwargs=None, template=None): + """Apply a function to each block of this UxDataset, keeping the grid + attached to each block and to the result. + + Equivalent to ``ux.map_blocks(func, self, args, kwargs, template)``; + see :py:func:`uxarray.map_blocks` for details. + """ + from uxarray.core.parallel import map_blocks + + return map_blocks(func, self, args, kwargs, template) + def astype(self, dtype, **kw_super): """Copy of this uxarray object, with data cast to a specified type. Leaves coordinate dtype unchanged. diff --git a/uxarray/core/parallel.py b/uxarray/core/parallel.py new file mode 100644 index 000000000..5be7aa277 --- /dev/null +++ b/uxarray/core/parallel.py @@ -0,0 +1,248 @@ +"""Grid-aware ``map_blocks`` for ``UxDataArray`` and ``UxDataset``.""" + +from __future__ import annotations + +import functools +from typing import TYPE_CHECKING, Any, Callable, Mapping, Sequence + +import dask.array as da +import xarray as xr +from dask import is_dask_collection + +from uxarray.constants import GRID_DIMS +from uxarray.errors import DimensionError + +if TYPE_CHECKING: + from uxarray.core.dataarray import UxDataArray + from uxarray.core.dataset import UxDataset + from uxarray.grid import Grid + + +def map_blocks( + func: Callable[..., UxDataArray | UxDataset], + obj: UxDataArray | UxDataset, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + template: xr.DataArray | xr.Dataset | None = None, +) -> UxDataArray | UxDataset: + """Apply a function to each block of a ``UxDataArray`` or ``UxDataset``, + keeping the grid attached. + + Behaves like :py:func:`xarray.map_blocks`, except that ``func`` receives + each block as a ``UxDataArray``/``UxDataset`` with a grid attached, and the + result is returned with ``obj.uxgrid`` attached. + + - If no grid dimension is split across chunks (e.g. chunked only along + ``time``), every block carries ``obj.uxgrid`` itself. + - If ``n_face`` is split, each block carries + ``obj.uxgrid.isel(n_face=...)`` for exactly the faces it holds. The + sub-grid is built inside the task, once per block. Node and edge data + passed in ``args`` is gathered onto the sub-grid's nodes and edges, i.e. + every node and edge of the block's faces, so it matches the block's grid. + - If ``n_node`` or ``n_edge`` is split, every block carries ``obj.uxgrid`` + itself, whose sizes do not match the block. Pass the grid variables + ``func`` needs in ``args`` instead (e.g. ``args=[uxgrid.node_lat]``): + each block then receives the values for its own nodes or edges. + + Splitting along a grid dimension is only correct for some functions; see + Notes. + + Parameters + ---------- + func : callable + Called as ``func(block, *args, **kwargs)``. Must return a + ``DataArray`` or ``Dataset`` (a ``UxDataArray``/``UxDataset`` is fine). + It must not change the length of a grid dimension. + obj : UxDataArray or UxDataset + Object whose blocks are passed to ``func``. If it is not backed by + dask, ``func(obj, *args, **kwargs)`` is returned directly. + args : sequence, optional + Passed to ``func`` after ``obj``. ``DataArray``/``Dataset`` arguments, + including grid variables such as ``uxgrid.edge_node_distances``, are + rechunked along ``obj``'s grid dimensions to match ``obj``, split into + blocks alongside it, and carry the same grid as its block. With + ``n_face`` split, node and edge data is instead passed whole to every + task and gathered onto each block's sub-grid. + kwargs : mapping, optional + Passed to ``func`` unchanged. Must not contain dask collections. + template : DataArray or Dataset, optional + Same as in :py:func:`xarray.map_blocks`. When omitted, the output is + inferred by calling ``func`` on a zero-size block that carries a + zero-face grid. + + Returns + ------- + UxDataArray or UxDataset + The assembled result, with ``obj.uxgrid`` attached. + + Raises + ------ + DimensionError + If more than one grid dimension is split across chunks, or if one is + split while ``obj`` also has another grid dimension. Blocks along + different grid dimensions cover unrelated parts of the grid. Rechunk the + split dimensions to a single chunk first. Also raised if ``n_face`` is + split and one ``args`` entry has both ``n_face`` and ``n_node`` or + ``n_edge`` dimensions; pass face and node/edge data separately. + + See Also + -------- + xarray.map_blocks + UxDataArray.map_blocks + UxDataset.map_blocks + Grid.chunks + + Notes + ----- + Splitting along a grid dimension (``n_face``, ``n_edge`` or ``n_node``) is + correct for functions that use each element's own values, such as area or + edge-length weighting, Coriolis terms, masks from coordinates, or per-face + geometry. With ``n_face`` split, it is also correct for functions that + compute each face from its own nodes and edges, such as node-to-face + topological aggregations or a flux divergence from edge velocities, when + the node or edge data is passed in ``args``. + + It is not correct for functions that read neighbouring elements of the same + kind, such as ``gradient``, ``curl``, ``divergence`` or neighbourhood + reductions, or that compute nodes or edges from faces: + + - With ``n_face`` split, each block's edge looks like a grid boundary, so + faces near it come out NaN or truncated, without an error. Face indices + are often not spatially compact, so this can affect most faces in a block. + - With ``n_node`` or ``n_edge`` split, the block's grid is the whole grid, + which does not match the block's nodes or edges. + + For those functions, keep the grid dimension in a single chunk and split + along other dimensions, e.g. ``time`` or ``lev``. + """ + from uxarray.core.dataarray import UxDataArray + from uxarray.core.dataset import UxDataset + + if not isinstance(obj, UxDataArray | UxDataset): + raise TypeError( + "ux.map_blocks expects a UxDataArray or UxDataset; " + f"got type(obj)={type(obj)}. Use xarray.map_blocks for plain xarray objects." + ) + uxgrid = obj.uxgrid + + if not is_dask_collection(obj): + return func(obj, *args, **(kwargs or {})) + + chunksizes = obj.chunksizes + split_dims = [dim for dim in GRID_DIMS if len(chunksizes.get(dim, ())) > 1] + grid_dims = [dim for dim in GRID_DIMS if dim in obj.dims] + if split_dims and grid_dims != split_dims[:1]: + single_chunk = {dim: -1 for dim in split_dims} + raise DimensionError( + "ux.map_blocks can split only one grid dimension, and only for objects with " + f"no other grid dimension. Got grid dimensions {grid_dims}, with {split_dims} " + "split across chunks. Blocks along different grid dimensions do not line up " + "(a block of faces and a block of nodes cover unrelated parts of the grid); " + f"rechunk with obj.chunk({single_chunk}) first." + ) + + # grid variables passed in args are usually in memory as a single chunk; match + # obj's chunks along its grid dimensions so xarray can split them alongside obj + grid_chunks = {dim: chunksizes[dim] for dim in grid_dims if dim in chunksizes} + if split_dims == ["n_face"]: + # node and edge data is gathered onto each block's sub-grid, so every task + # needs it whole; left chunked, xarray would split it along its own grid dim + grid_chunks.update({"n_node": -1, "n_edge": -1}) + args = [ + arg.chunk({dim: grid_chunks[dim] for dim in grid_chunks.keys() & arg.dims}) + if isinstance(arg, xr.DataArray | xr.Dataset) + else arg + for arg in args + ] + + face_positions = None + if split_dims == ["n_face"]: + arg_dims = [ + set(arg.dims) for arg in args if isinstance(arg, xr.DataArray | xr.Dataset) + ] + if any("n_face" in dims and dims & {"n_node", "n_edge"} for dims in arg_dims): + raise DimensionError( + "With 'n_face' split, each DataArray/Dataset in args must have either " + "'n_face' or 'n_node'/'n_edge' dimensions, not both: face data is split " + "into blocks while node and edge data is gathered onto each block's " + "sub-grid. Pass them as separate arguments." + ) + if any("n_edge" in dims for dims in arg_dims): + # face sub-grids keep their edges only when this connectivity exists; build + # it once here rather than racing to build it from inside the tasks + _ = uxgrid.face_edge_connectivity + + # Each face's position in the parent grid, passed as a hidden first argument: + # xarray splits it into blocks alongside obj, so a block can recover which + # faces (and so which sub-grid) it holds. + face_positions = xr.DataArray( + da.arange(obj.sizes["n_face"], chunks=(chunksizes["n_face"],)), + dims="n_face", + ) + args = [face_positions, *args] + + @functools.wraps(func) + def _block_func(block, *block_args, **block_kwargs): + block_positions = None + if face_positions is not None: + block_positions, *block_args = block_args + block_grid = _grid_for_block(block, block_positions, uxgrid) + return func( + _with_grid(block, block_grid), + *( + _arg_for_block(arg, block_grid, uxgrid, block_positions is not None) + for arg in block_args + ), + **block_kwargs, + ) + + result = xr.map_blocks(_block_func, obj, args, kwargs, template) + + if isinstance(result, xr.Dataset): + return UxDataset( + result, uxgrid=uxgrid, source_datasets=getattr(obj, "source_datasets", None) + ) + return UxDataArray(result, uxgrid=uxgrid) + + +def _grid_for_block( + block: xr.DataArray | xr.Dataset, + face_positions: xr.DataArray | None, + uxgrid: Grid, +) -> Grid: + """The grid matching one block: the sub-grid of the faces at ``face_positions`` + when ``n_face`` was split, otherwise the whole grid.""" + if face_positions is not None: + positions = face_positions.values + start = int(positions[0]) if positions.size else 0 + return uxgrid.isel(n_face=slice(start, start + positions.size)) + if any(block.sizes[dim] == 0 for dim in GRID_DIMS if dim in block.dims): + # xarray infers the output template by calling func on zero-size blocks + return uxgrid.isel(n_face=slice(0, 0)) + return uxgrid + + +def _arg_for_block(value: Any, block_grid: Grid, uxgrid: Grid, face_split: bool) -> Any: + """One ``args`` entry for one block. When ``n_face`` was split, node and edge + data arrive whole and are gathered onto the nodes and edges of the block's + face sub-grid (its halo); everything else just gets the block's grid.""" + if ( + face_split + and isinstance(value, xr.DataArray | xr.Dataset) + and {"n_node", "n_edge"} & set(value.dims) + ): + return _with_grid(value, uxgrid)._slice_from_grid(block_grid) + return _with_grid(value, block_grid) + + +def _with_grid(value: Any, uxgrid: Grid) -> Any: + """Wrap a plain xarray block as a ``UxDataArray``/``UxDataset`` on ``uxgrid``; + pass anything else through.""" + from uxarray.core.dataarray import UxDataArray + from uxarray.core.dataset import UxDataset + + if isinstance(value, xr.DataArray): + return UxDataArray(value, uxgrid=uxgrid) + if isinstance(value, xr.Dataset): + return UxDataset(value, uxgrid=uxgrid) + return value diff --git a/uxarray/grid/grid.py b/uxarray/grid/grid.py index b5e5909bb..01d05a3d5 100644 --- a/uxarray/grid/grid.py +++ b/uxarray/grid/grid.py @@ -3,7 +3,7 @@ import copy import os import warnings -from collections.abc import Sequence +from collections.abc import Hashable, Mapping, Sequence from html import escape from typing import TYPE_CHECKING @@ -1783,9 +1783,30 @@ def max_face_radius(self): self._ds["max_face_radius"] = _populate_max_face_radius(self) return self._ds["max_face_radius"] - def chunk(self, n_node="auto", n_edge="auto", n_face="auto"): + @property + def chunks(self) -> Mapping[Hashable, tuple[int, ...]]: + """Mapping from dimension name to block lengths for this grid's variables. + + Only dask-backed variables contribute; an empty mapping means the grid + holds no dask arrays. Mirrors :py:attr:`xarray.Dataset.chunks`, so it + raises ``ValueError`` if two variables are chunked differently along the + same dimension. + + See Also + -------- + Grid.chunk + """ + return self._ds.chunksizes + + def chunk( + self, + n_node="auto", + n_edge="auto", + n_face="auto", + inplace: bool | None = None, + ): """Converts all arrays to dask arrays with given chunks across grid - dimensions in-place. + dimensions. Non-dask arrays will be converted to dask arrays. Dask arrays will be chunked to the given chunk size. @@ -1835,21 +1856,50 @@ def chunk(self, n_node="auto", n_edge="auto", n_face="auto"): -1 or None as a blocksize indicate the size of the corresponding dimension. - """ - - grid_var_names = self.coordinates | self.connectivity | self.descriptors - for var_name in grid_var_names: - grid_var = getattr(self, var_name) + inplace : bool, optional + If ``False``, return a new chunked ``Grid`` and leave this one + unchanged. If ``True``, chunk this grid in place and return ``None``. + Leaving it unset currently behaves like ``True`` and emits a + ``FutureWarning``: the default will become ``False`` in a future release. - if "n_node" in grid_var.dims: - setattr(self, var_name, grid_var.chunk(chunks={"n_node": n_node})) - elif "n_edge" in grid_var.dims: - setattr(self, var_name, grid_var.chunk(chunks={"n_edge": n_edge})) - elif "n_face" in grid_var.dims: - setattr(self, var_name, grid_var.chunk(chunks={"n_face": n_face})) - else: - setattr(self, var_name, grid_var.chunk()) + Returns + ------- + Grid or None + The chunked grid when ``inplace=False``, otherwise ``None``. + """ + if inplace is None: + warnings.warn( + "Grid.chunk() currently chunks the grid in place and returns None. " + "In a future release it will return a new chunked Grid and leave this " + "one unchanged. Pass inplace=False for the new behaviour, or " + "inplace=True to keep the current one.", + FutureWarning, + stacklevel=2, + ) + inplace = True + + dim_chunks = {"n_node": n_node, "n_edge": n_edge, "n_face": n_face} + chunked_vars = {} + for var_name in self.coordinates | self.connectivity | self.descriptors: + grid_var = self._ds[var_name] + # the first grid dimension present decides the chunking, in n_node, n_edge, n_face order + grid_dim = next((dim for dim in dim_chunks if dim in grid_var.dims), None) + chunks = {grid_dim: dim_chunks[grid_dim]} if grid_dim else {} + chunked_vars[var_name] = grid_var.chunk(chunks=chunks) + + if inplace: + for var_name, grid_var in chunked_vars.items(): + setattr(self, var_name, grid_var) + return None + + chunked = copy.copy(self) + # give the copy its own caches, so filling one grid's cache never touches the other's + for attr_name, value in vars(chunked).items(): + if isinstance(value, dict): + setattr(chunked, attr_name, dict(value)) + chunked._ds = self._ds.assign(chunked_vars) + return chunked def get_ball_tree( self, @@ -2405,7 +2455,7 @@ def _compute_face_areas_and_jacobian( # Using np.issubdtype to check if the type is float # if not (int etc.), convert to float, this is to avoid numba errors x, y, z = ( - arr.astype(float) if not np.issubdtype(arr[0], np.floating) else arr + arr.astype(float) if not np.issubdtype(arr.dtype, np.floating) else arr for arr in (x, y, z) ) @@ -2424,7 +2474,7 @@ def _compute_face_areas_and_jacobian( latitude_adjusted_area, ) - min_jacobian = np.min(self._face_jacobian) + min_jacobian = np.min(self._face_jacobian, initial=np.inf) if min_jacobian < 0: _where_neg = np.where(self._face_jacobian < 0)[0]