Skip to content
Draft
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
4 changes: 3 additions & 1 deletion ci/doc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ channels:
dependencies:
- cupy-core!=14.0.0,!=14.0.1 # https://github.com/cupy/cupy/issues/9777
- pip
- python=3.10
- python=3.11
- rasterix
- sphinx
- sphinx-design
- sphinx-copybutton
Expand All @@ -18,3 +19,4 @@ dependencies:
- pip:
# relative to this file. Needs to be editable to be accepted.
- --editable ..
- rumi-eo
116 changes: 116 additions & 0 deletions cupy_xarray/rumi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""
`rumi` backend for xarray to read rumi files directly into CuPy arrays in GPU memory.
"""

import os
from collections.abc import Iterable

import cupy as cp
import numpy as np
import pandas as pd
import rasterix
import rumi
import xarray as xr
from affine import Affine
from xarray.backends import BackendEntrypoint


# %%
class RumiBackendEntrypoint(BackendEntrypoint):
"""
Xarray backend to read rumi files using 'rumi' engine.

When using :py:func:`xarray.open_dataarray` with ``engine="rumi"``, the optional
``device_id`` parameter can be set to the CUDA GPU id to do the decoding on.

"""

description = "Use .rumi files in Xarray"
open_dataset_parameters = (
"filename_or_obj",
"header",
"drop_variables",
"device_id",
)
url = "https://asterisk.coop/rumi/api-python.html"

def open_dataset(
self,
filename_or_obj: str,
header: bytes | bytearray | memoryview[int],
*,
drop_variables: str | Iterable[str] | None = None,
device_id: int | None = None,
# other backend specific keyword arguments
# `chunks` and `cache` DO NOT go here, they are handled by xarray
mask_and_scale=None,
) -> xr.Dataset:
"""
Backend open_dataset method used by Xarray in :py:func:`xarray.open_dataset`.

Parameters
----------
filename_or_obj : str
File path or url to a rumi (.rumi) image file that can be read by rumi.
header : bytes | bytearray | memoryview[int]
Rumi external header loaded as a byte stream.
device_id : int | None
CUDA device ID on which to place the created cupy array. Default is None,
which means device_id will be inferred via
:py:func:`cupy.cuda.runtime.getDevice`.

Returns
-------
xarray.Dataset

"""
if device_id is None:
device_id: int = cp.cuda.runtime.getDevice()

with cp.cuda.Stream(ptds=True): # using default stream segfaults
dlpack = rumi.read(
source=filename_or_obj,
header=header,
pattern=None, # default is (T, B, Y, X)
framework="dlpack",
device=f"cuda:{device_id}",
decode_backend="auto",
)
array: cp.ndarray = cp.from_dlpack(dlpack)

info = rumi.info(source=filename_or_obj, header=header)
# Band/Channel coordinates
match array.ndim:
case 3:
bands, height, width = array.shape
bc_coords = {"band": np.arange(bands, dtype=np.uint8)}
case 4:
time, bands, height, width = array.shape
bc_coords = {
"time": pd.Series(info.time),
"band": np.arange(bands, dtype=np.uint8),
}
# Height/Width coordinates
try:
affine = Affine(*info.transform)
index = rasterix.RasterIndex.from_transform(
affine=affine, width=width, height=height, crs=info.crs
)
xy_coords = xr.Coordinates.from_xindex(index=index)
except TypeError: # missing Affine transform
xy_coords = {"y": np.arange(height), "x": np.arange(width)}

dataarray: xr.DataArray = xr.DataArray(
data=array,
coords=xr.Coordinates(coords={**bc_coords, **xy_coords}),
name=None,
attrs=None,
)
return dataarray.to_dataset(name="raster")

def guess_can_open(self, filename_or_obj):
try:
_, ext = os.path.splitext(filename_or_obj)
except TypeError:
return False
return ext in {".rumi"}
74 changes: 74 additions & 0 deletions cupy_xarray/tests/test_rumi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""
Tests for xarray 'rumi' backend engine.
"""

import datetime as dt
from urllib.request import Request, urlopen

import cupy as cp
import pytest
import xarray as xr

rumi = pytest.importorskip("rumi")

from cupy_xarray.rumi import RumiBackendEntrypoint # noqa: E402, F401


# %%
def test_entrypoint():
assert "rumi" in xr.backends.list_engines()


def test_xarray_backend_open_dataarray_chw():
"""
Ensure that passing engine='rumi' to xarray.open_dataarray works to read a 3-D
(channels, height, width) rumi file (and its external header loaded as bytes) from a
http url.
"""
header_url = (
"https://data.source.coop/asterisk-labs/rumi-api-fixtures/headers/s2-00-chunky.header"
)
request = Request(url=header_url, headers={"User-Agent": "rumi-example"})
header: bytes = urlopen(url=request).read()

with xr.open_dataarray(
filename_or_obj="https://data.source.coop/asterisk-labs/rumi-api-fixtures/data/s2-00-chunky.rumi",
header=header,
engine="rumi",
device_id=0,
) as da:
assert isinstance(da.data, cp.ndarray)
assert da.sizes == {"band": 4, "y": 512, "x": 512}
assert da.x.min() == 384425.0
assert da.x.max() == 389535.0
assert da.y.min() == 3947065.0
assert da.y.max() == 3952175.0
assert da.dtype == "uint16"


def test_xarray_backend_open_dataarray_tchw():
"""
Ensure that passing engine='rumi' to xarray.open_dataarray works to read a 4-D
(time, channels, height, width) rumi file (and its external header loaded as bytes)
from a http url.
"""
header_url = (
"https://data.source.coop/asterisk-labs/rumi-api-fixtures/headers/era5-t2m-00-time.header"
)
request = Request(url=header_url, headers={"User-Agent": "rumi-example"})
header: bytes = urlopen(url=request).read()

with xr.open_dataarray(
filename_or_obj="https://data.source.coop/asterisk-labs/rumi-api-fixtures/data/era5-t2m-00-time.rumi",
header=header,
engine="rumi",
device_id=0,
) as da:
assert isinstance(da.data, cp.ndarray)
assert da.sizes == {"time": 24, "band": 1, "y": 721, "x": 1440}
assert all(da.time.dt.date == dt.date(2023, 1, 15)) # ensure .dt accessor works
assert da.x.min() == 0
assert da.x.max() == 1439
assert da.y.min() == 0
assert da.y.max() == 720
assert da.dtype == "uint16"
17 changes: 17 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,20 @@ Methods

Dataset.cupy.as_cupy
Dataset.cupy.as_numpy



Backends
--------

rumi
~~~~

.. currentmodule:: cupy_xarray

.. automodule:: cupy_xarray.rumi

.. autosummary::
:toctree: generated/

RumiBackendEntrypoint
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ dependencies = [
"xarray>=2024.02.0",
]

[project.entry-points."xarray.backends"]
rumi = "cupy_xarray.rumi:RumiBackendEntrypoint"

[project.optional-dependencies]

[dependency-groups]
Expand Down
Loading