|
| 1 | +import functools |
| 2 | + |
| 3 | +import pystac |
| 4 | +import xarray |
| 5 | +from xarray.backends import BackendEntrypoint |
| 6 | + |
| 7 | +from .utils import _import_optional_dependency |
| 8 | + |
| 9 | + |
| 10 | +@functools.singledispatch |
| 11 | +def to_xarray(item, **kwargs) -> xarray.Dataset: |
| 12 | + if hasattr(item, "get_all_items"): |
| 13 | + item_collection = item.get_all_items() |
| 14 | + return to_xarray(item_collection) |
| 15 | + raise TypeError |
| 16 | + |
| 17 | + |
| 18 | +@to_xarray.register(pystac.Item) |
| 19 | +@to_xarray.register(pystac.ItemCollection) |
| 20 | +def _( |
| 21 | + obj: pystac.Item | pystac.ItemCollection, |
| 22 | + drop_variables: str | list[str] = None, |
| 23 | + **kwargs, |
| 24 | +) -> xarray.Dataset: |
| 25 | + stackstac = _import_optional_dependency("stackstac") |
| 26 | + if drop_variables is not None: |
| 27 | + raise KeyError("``drop_variables`` not implemented for pystac items") |
| 28 | + return stackstac.stack(obj, **kwargs).to_dataset(dim="band", promote_attrs=True) |
| 29 | + |
| 30 | + |
| 31 | +@to_xarray.register |
| 32 | +def _(obj: pystac.Asset, **kwargs) -> xarray.Dataset: |
| 33 | + open_kwargs = obj.extra_fields.get("xarray:open_kwargs", {}) |
| 34 | + |
| 35 | + if obj.media_type == pystac.MediaType.JSON and "index" in obj.roles: |
| 36 | + requests = _import_optional_dependency("requests") |
| 37 | + fsspec = _import_optional_dependency("fsspec") |
| 38 | + r = requests.get(obj.href) |
| 39 | + r.raise_for_status() |
| 40 | + try: |
| 41 | + import planetary_computer |
| 42 | + |
| 43 | + refs = planetary_computer.sign(r.json()) |
| 44 | + except ImportError: |
| 45 | + refs = r.json() |
| 46 | + mapper = fsspec.get_mapper("reference://", fo=refs) |
| 47 | + default_kwargs = {"engine": "zarr", "consolidated": False, "chunks": {}} |
| 48 | + return xarray.open_dataset(mapper, **default_kwargs, **open_kwargs, **kwargs) |
| 49 | + |
| 50 | + if obj.media_type == pystac.MediaType.COG: |
| 51 | + default_kwargs = {"engine", "rasterio"} |
| 52 | + elif obj.media_type == "application/vnd+zarr": |
| 53 | + default_kwargs = {"engine": "zarr"} |
| 54 | + else: |
| 55 | + default_kwargs = {} |
| 56 | + |
| 57 | + ds = xarray.open_dataset(obj.href, **default_kwargs, **open_kwargs, **kwargs) |
| 58 | + return ds |
| 59 | + |
| 60 | + |
| 61 | +class STACBackend(BackendEntrypoint): |
| 62 | + def open_dataset( |
| 63 | + self, |
| 64 | + obj, |
| 65 | + *, |
| 66 | + drop_variables: str | list[str] = None, |
| 67 | + **kwargs, |
| 68 | + ): |
| 69 | + return to_xarray(obj, drop_variables=drop_variables, **kwargs) |
| 70 | + |
| 71 | + open_dataset_parameters = ["obj", "drop_variables"] |
| 72 | + |
| 73 | + def guess_can_open(self, obj): |
| 74 | + return isinstance(obj, (pystac.Asset, pystac.Item, pystac.ItemCollection)) |
| 75 | + |
| 76 | + description = "Open pystac objects in Xarray" |
| 77 | + |
| 78 | + url = "https://github.com/jsignell/xpystac" |
0 commit comments