Skip to content
Merged
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
35 changes: 8 additions & 27 deletions docs/supported_grids.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,30 +45,11 @@ examples for a more detailed look.
Resampled Uniform Grids
#######################

Some consumers of yt datasets, notably ``yt_idv``, require every grid to have a
constant cell spacing in each dimension and so cannot work with stretched grids
directly. For these cases, ``ds.yt.load_as_uniform_grid`` builds a new uniform
grid with a user-specified bounding box and cell spacing and interpolates the
xarray fields onto it on demand, as yt reads data. The interpolation happens in
the native coordinates of the xarray dataset (e.g., depth, latitude, longitude),
which is both cheaper and more faithful than transforming to cartesian coordinates
first. The resampled grid may be chunked into multiple yt grids with the
``chunksizes`` argument, exactly as for ``ds.yt.load_grid``.

By default the cell spacing is the smallest spacing of the stretched grid in each
dimension, so that every feature of the original grid is resolved. For grids where
the fine spacing is confined to a small region, this can be wasteful, and
``refine_grid=True`` instead builds a hierarchy of uniform grids: a coarse level 0
grid covering the whole domain with finer grids only where the stretched grid
spacing is finer than the current level's spacing. The hierarchy is planned from
the coordinate values of the stretched grid alone, so no field data is read until
yt requests it.

Note that yt refines all dimensions together by ``refine_by``, so a region that
is finely spaced in one dimension will also be refined in the others. For a grid
that is stretched in only some dimensions, a per-dimension ``refine_by`` (e.g.,
``refine_by=(2, 1, 1)`` to only ever refine the first dimension, or
``refine_by={'x': 2, 'y': 1, 'z': 1}`` to specify it by coordinate name) avoids this. The
loader logs the cell count of the planned hierarchy next to that of a uniform grid
at the finest spacing, so it is easy to check whether refinement is worthwhile for
a given dataset.
Some consumers of yt datasets (e.g., ``yt_idv``) require a constant cell spacing
within each grid and so cannot work with stretched grids directly. For these cases,
``ds.yt.load_as_uniform_grid`` builds a new uniform grid with a specified bounding
box and cell spacing and interpolates onto it on the fly, in the native coordinates
of the xarray dataset. The new grid may be chunked into multiple yt grids or, with
``refine_grid=True``, built as a hierarchy of grids refined only where the stretched
grid spacing is fine. See :doc:`examples/example_011_stretched_grids_as_uniform`
for details and the ``load_as_uniform_grid`` docstring for all options.
32 changes: 26 additions & 6 deletions yt_xarray/accessor/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ def load_as_uniform_grid(
geometry: str | None = None,
bbox: Mapping[str, ArrayLike] | ArrayLike | None = None,
cell_spacing: Mapping[str, float] | ArrayLike | float | None = None,
pin_bbox: bool = True,
use_callable: bool = True,
sel_dict: dict[str, Any] | None = None,
sel_dict_type: str = "isel",
Expand Down Expand Up @@ -216,9 +217,9 @@ def load_as_uniform_grid(
the bounding box of the new grid in native coordinates. Either a
dictionary mapping coordinate names to (min, max) pairs or an
array of shape (ndim, 2) in the dimension order of the fields.
Defaults to the extent of the (selected) xarray data. If the
width in a dimension is not an integer multiple of the cell spacing,
the maximum is extended so that it is.
Defaults to the extent of the (selected) xarray data. See pin_bbox
for how a width that is not an integer multiple of the cell
spacing is handled.

cell_spacing : dict, ArrayLike or float
the cell spacing of the new grid in native coordinates: a dictionary
Expand All @@ -230,6 +231,15 @@ def load_as_uniform_grid(
largest spacing of the xarray grid for which the finest level
exactly resolves the smallest spacing in each dimension.

pin_bbox : bool
controls how a bbox width that is not an integer multiple of the
cell spacing is reconciled. If True (default), the bbox is kept
exactly and the cell spacing is decreased in that dimension to the
largest value that divides the width into an integer number of
cells. If False, the cell spacing is kept and the bbox maximum is
extended to the next cell boundary. With refine_grid, the adjusted
spacing is the level 0 spacing.

use_callable : bool
if True (default), then the yt dataset will interpolate on demand
from the open xarray Dataset handle. If False, interpolation is
Expand Down Expand Up @@ -308,7 +318,7 @@ def load_as_uniform_grid(
refine_by = _refine_by_dict_to_array(sel_info, refine_by)
rb = _validate_refine_by(refine_by, sel_info.ndims)
dxyz = _validate_cell_spacing(sel_info, cell_spacing, refine_grid, rb)
bbox_arr = _validate_uniform_bbox(sel_info, bbox, dxyz)
bbox_arr, dxyz = _validate_uniform_bbox(sel_info, bbox, dxyz, pin_bbox)
dims = np.round((bbox_arr[:, 1] - bbox_arr[:, 0]) / dxyz).astype(int)

if refine_grid:
Expand Down Expand Up @@ -807,7 +817,8 @@ def _validate_uniform_bbox(
sel_info: _xr_to_yt.Selection,
bbox: Mapping[str, ArrayLike] | ArrayLike | None,
dxyz: npt.NDArray[np.float64],
) -> npt.NDArray[np.float64]:
pin_bbox: bool = True,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
ndims = sel_info.ndims
bbox_arr: npt.NDArray[np.float64]
if bbox is None:
Expand All @@ -829,14 +840,23 @@ def _validate_uniform_bbox(

widths = bbox_arr[:, 1] - bbox_arr[:, 0]
dims = np.ceil(widths / dxyz - 1e-8).astype(int)
if pin_bbox:
new_dxyz = widths / dims
if not np.allclose(new_dxyz, dxyz):
ytxr_log.info(
"bbox width is not an integer multiple of cell_spacing, decreasing "
f"cell_spacing from {dxyz} to {new_dxyz} to match the bbox."
)
return bbox_arr, new_dxyz

new_max = bbox_arr[:, 0] + dims * dxyz
if not np.allclose(new_max, bbox_arr[:, 1]):
ytxr_log.info(
"bbox width is not an integer multiple of cell_spacing, extending "
f"bbox max from {bbox_arr[:, 1]} to {new_max}."
)
bbox_arr[:, 1] = new_max
return bbox_arr
return bbox_arr, dxyz


def _log_grid_plan(
Expand Down
49 changes: 47 additions & 2 deletions yt_xarray/tests/test_load_as_uniform_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,60 @@ def test_bbox_and_spacing_forms(ds_stretched):


def test_bbox_rounds_up_to_spacing(ds_stretched):
# 4 / 0.3 is not an integer: the max edge is extended
# 4 / 0.3 is not an integer: with pin_bbox=False the max edge is extended
ds_yt = ds_stretched.yt.load_as_uniform_grid(
length_unit="m", cell_spacing={"x": 0.3, "y": 0.5, "z": 0.5}
length_unit="m", cell_spacing={"x": 0.3, "y": 0.5, "z": 0.5}, pin_bbox=False
)
assert ds_yt.domain_dimensions[0] == 14
np.testing.assert_allclose(ds_yt.domain_right_edge.d[0], 14 * 0.3)
np.testing.assert_allclose(ds_yt.index.grids[0].dds.d[0], 0.3)


def test_pin_bbox_decreases_spacing(ds_stretched):
# 4 / 0.3 is not an integer: by default the bbox is kept and dx shrinks to 4 / 14
ds_yt = ds_stretched.yt.load_as_uniform_grid(
length_unit="m", cell_spacing={"x": 0.3, "y": 0.5, "z": 0.5}
)
assert tuple(ds_yt.domain_dimensions) == (14, 4, 4)
np.testing.assert_allclose(ds_yt.domain_right_edge.d, [4.0, 2.0, 1.0])
np.testing.assert_allclose(ds_yt.index.grids[0].dds.d, [4.0 / 14, 0.5, 0.5])

# an explicit bbox is also pinned exactly
bbox = np.array([[0.5, 3.5], [0.0, 2.0], [-1.0, 1.0]])
ds_yt = ds_stretched.yt.load_as_uniform_grid(
length_unit="m", bbox=bbox, cell_spacing=0.7
)
np.testing.assert_allclose(ds_yt.domain_left_edge.d, bbox[:, 0])
np.testing.assert_allclose(ds_yt.domain_right_edge.d, bbox[:, 1])
assert tuple(ds_yt.domain_dimensions) == (5, 3, 3)

# when the width is already an integer multiple, the spacing is unchanged
ds_yt = ds_stretched.yt.load_as_uniform_grid(length_unit="m", cell_spacing=0.5)
assert tuple(ds_yt.domain_dimensions) == (8, 4, 4)
np.testing.assert_allclose(ds_yt.index.grids[0].dds.d, 0.5)
_check_linear(ds_yt)


@pytest.mark.parametrize("extra_kwargs", [{"chunksizes": 3}, {"refine_grid": True}])
def test_pin_bbox_multi_grid(ds_stretched, extra_kwargs: dict[str, Any]):
ds_yt = ds_stretched.yt.load_as_uniform_grid(
length_unit="m", cell_spacing=0.3, **extra_kwargs
)
assert len(ds_yt.index.grids) > 1
np.testing.assert_allclose(ds_yt.domain_left_edge.d, [0.0, 0.0, -1.0])
np.testing.assert_allclose(ds_yt.domain_right_edge.d, [4.0, 2.0, 1.0])
assert tuple(ds_yt.domain_dimensions) == (14, 7, 7)
expected_dds = np.array([4.0 / 14, 2.0 / 7, 2.0 / 7])
for grid in ds_yt.index.grids:
np.testing.assert_allclose(
grid.dds.d, expected_dds / ds_yt.refine_by**grid.Level
)
np.testing.assert_allclose(
ds_yt.index.grid_right_edge.d.max(axis=0), [4.0, 2.0, 1.0]
)
_check_linear(ds_yt)


def test_fill_value_outside_source(ds_stretched):
bbox = np.array([[-1.0, 5.0], [0.0, 2.0], [-1.0, 1.0]])
ds_yt = ds_stretched.yt.load_as_uniform_grid(
Expand Down
Loading