Skip to content

Commit

Permalink
Promote band-level coords to data var attributes for stackstac (#37)
Browse files Browse the repository at this point in the history
Closes #36 

As mentioned in the issue since xpystac always returns an
xarray.Dataset, it needs to be careful about the conversion of coords
that have "band" as their dim. In a DataArray each version that
`stackstac` natively returns you end up with scalar coords per-band. I
think the best way to map that onto the data variables is by using
converting scalar coords to attrs.
  • Loading branch information
jsignell authored Apr 5, 2024
1 parent 8ef17bf commit 7b77ecc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def test_to_xarray_with_pystac_client_search_passes_kwargs_through(simple_search
def test_to_xarray_with_different_stacking_library(simple_search, stacking_library):
ds = to_xarray(simple_search, stacking_library=stacking_library)
assert isinstance(ds, xr.Dataset)
assert "band" not in ds.dims


def test_to_xarray_with_drop_variables_raises(simple_search):
Expand Down
12 changes: 11 additions & 1 deletion xpystac/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,17 @@ def _(
return odc_stac.load(items, **{"chunks": {"x": 1024, "y": 1024}, **kwargs})
elif stacking_library == "stackstac":
stackstac = _import_optional_dependency("stackstac")
return stackstac.stack(obj, **kwargs).to_dataset(dim="band", promote_attrs=True)
da = stackstac.stack(obj, **kwargs)
bands = {}
for band in da.band.values:
b = da.sel(band=band)
scalar_coords = {k: v.item() for k, v in b.coords.items() if v.shape == ()}
b = b.assign_attrs(
**{k: v for k, v in scalar_coords.items() if v is not None}
)
b = b.drop_vars(scalar_coords)
bands[band] = b
return xarray.Dataset(bands, attrs=da.attrs)


@to_xarray.register
Expand Down

0 comments on commit 7b77ecc

Please sign in to comment.