Skip to content

Commit

Permalink
Support nodata= in mosaic
Browse files Browse the repository at this point in the history
Closes #92. Copied from microsoft/PlanetaryComputer#17 (comment) mostly.
  • Loading branch information
gjoseph92 committed Jan 20, 2022
1 parent 0bcb36c commit 83ad070
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions stackstac/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import xarray as xr


# TODO `fill_value`s besides NaN
def _mosaic(arr, axis, reverse: bool = False):
def _mosaic(arr, axis, reverse: bool = False, nodata: Union[int, float] = np.nan):
ax_length = arr.shape[axis]

# "normal" means last -> first, "reversed" means first -> last,
Expand All @@ -14,7 +13,8 @@ def _mosaic(arr, axis, reverse: bool = False):

for i in indices:
layer = np.take(arr, i, axis=axis)
out = np.where(np.isnan(out), layer, out)
where = np.isnan(out) if np.isnan(nodata) else out == nodata
out = np.where(where, layer, out)
return out


Expand All @@ -23,9 +23,10 @@ def mosaic(
dim: Union[None, Hashable, Sequence[Hashable]] = None,
axis: Union[None, int, Sequence[int]] = 0,
reverse: bool = False,
nodata: Union[int, float] = np.nan,
):
"""
Flatten a dimension of a `~xarray.DataArray` by picking the first non-NaN pixel.
Flatten a dimension of a `~xarray.DataArray` by picking the first valid pixel.
The order of mosaicing is from last to first, meaning the last item is on top.
Expand All @@ -41,10 +42,19 @@ def mosaic(
reverse:
If False (default), the last item along the dimension is on top.
If True, the first item in the dimension is on top.
nodata:
The value to treat as invalid. Default: NaN.
Returns
-------
xarray.DataArray:
The mosaicked `~xarray.DataArray`.
"""
return arr.reduce(_mosaic, dim=dim, axis=axis, keep_attrs=True, reverse=reverse)
return arr.reduce(
_mosaic,
dim=dim,
axis=axis,
keep_attrs=True,
reverse=reverse,
nodata=nodata,
)

0 comments on commit 83ad070

Please sign in to comment.