Skip to content

made load_stac nicer to mismatch in band names #755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 5 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- When the bands provided to `Connection.load_stac(..., bands=[...])` do not fully match the bands the client extracted from the STAC metadata, a warning will be triggered, but the provided band names will still be used during the client-side preparation of the process graph. This is a pragmatic approach to bridge the gap between differing interpretations of band detection in STAC. Note that this might produce process graphs that are technically invalid and might not work on other backends or future versions of the backend you currently use. It is recommended to consult with the provider of the STAC metadata and openEO backend on the correct and future-proof band names. ([#752](https://github.com/Open-EO/openeo-python-client/issues/752))

### Removed

### Fixed
Expand Down
10 changes: 10 additions & 0 deletions openeo/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,16 @@ def rename_labels(self, target, source) -> Dimension:
def rename(self, name) -> Dimension:
return BandDimension(name=name, bands=self.bands)

def contains_band(self, band: Union[int, str]) -> bool:
"""
Check if the given band name or index is present in the dimension.
"""
try:
self.band_index(band)
return True
except ValueError:
return False


class GeometryDimension(Dimension):
# TODO: how to model/store labels of geometry dimension?
Expand Down
20 changes: 17 additions & 3 deletions openeo/rest/datacube.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,10 +441,24 @@ def load_stac(
graph = PGNode("load_stac", arguments=arguments)
try:
metadata = metadata_from_stac(url)
# TODO: also apply spatial/temporal filters to metadata?

if isinstance(bands, list):
# TODO: also apply spatial/temporal filters to metadata?
metadata = metadata.filter_bands(band_names=bands)
except Exception:
if not metadata.has_band_dimension():
metadata = metadata.add_dimension(
name="bands",
type="bands",
label=None,
)
unknown_bands = [b for b in bands if not metadata.band_dimension.contains_band(b)]
if len(unknown_bands) == 0:
metadata = metadata.filter_bands(band_names=bands)
else:
logging.warning(
f"The specified bands {bands} are not a subset of the bands {metadata.band_dimension.band_names} found in the STAC metadata (unknown bands: {unknown_bands}). Using specified bands as is."
)
metadata = metadata.rename_labels(dimension="bands", target=bands)
except Exception as e:
log.warning(f"Failed to extract cube metadata from STAC URL {url}", exc_info=True)
metadata = None
return cls(graph=graph, connection=connection, metadata=metadata)
Expand Down
55 changes: 52 additions & 3 deletions tests/rest/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -2957,7 +2957,40 @@ def test_load_stac_no_cube_extension_temporal_dimension(self, con120, tmp_path,
cube = con120.load_stac(str(stac_path))
assert cube.metadata.temporal_dimension == TemporalDimension(name="t", extent=dim_extent)

def test_load_stac_band_filtering(self, con120, tmp_path):
@pytest.mark.parametrize(
"bands, expected_warning",
[
(
["B04"],
"The specified bands ['B04'] are not a subset of the bands ['B01', 'B02', 'B03'] found in the STAC metadata (unknown bands: ['B04']). Using specified bands as is.",
),
(
["B03", "B04", "B05"],
"The specified bands ['B03', 'B04', 'B05'] are not a subset of the bands ['B01', 'B02', 'B03'] found in the STAC metadata (unknown bands: ['B04', 'B05']). Using specified bands as is.",
),
(["B03", "B02"], None),
(["B01", "B02", "B03"], None),
],
)
def test_load_stac_band_filtering(self, con120, tmp_path, caplog, bands, expected_warning):
stac_path = tmp_path / "stac.json"
stac_data = StacDummyBuilder.collection(
summaries={"eo:bands": [{"name": "B01"}, {"name": "B02"}, {"name": "B03"}]}
)
# TODO #738 real request mocking of STAC resources compatible with pystac?
stac_path.write_text(json.dumps(stac_data))

caplog.set_level(logging.WARNING)
# Test with non-existing bands in the collection metadata
cube = con120.load_stac(str(stac_path), bands=bands)
assert cube.metadata.band_names == bands
if expected_warning is None:
assert caplog.text == ""
else:
assert expected_warning in caplog.text
caplog.clear()

def test_load_stac_band_filtering_no_requested_bands(self, con120, tmp_path):
stac_path = tmp_path / "stac.json"
stac_data = StacDummyBuilder.collection(
summaries={"eo:bands": [{"name": "B01"}, {"name": "B02"}, {"name": "B03"}]}
Expand All @@ -2968,8 +3001,24 @@ def test_load_stac_band_filtering(self, con120, tmp_path):
cube = con120.load_stac(str(stac_path))
assert cube.metadata.band_names == ["B01", "B02", "B03"]

cube = con120.load_stac(str(stac_path), bands=["B03", "B02"])
assert cube.metadata.band_names == ["B03", "B02"]
def test_load_stac_band_filtering_no_metadata(self, con120, tmp_path, caplog):
stac_path = tmp_path / "stac.json"
stac_data = StacDummyBuilder.collection()
# TODO #738 real request mocking of STAC resources compatible with pystac?
stac_path.write_text(json.dumps(stac_data))

cube = con120.load_stac(str(stac_path))
assert cube.metadata.band_names == []

caplog.set_level(logging.WARNING)
cube = con120.load_stac(str(stac_path), bands=["B01", "B02"])
assert cube.metadata.band_names == ["B01", "B02"]
assert (
"The specified bands ['B01', 'B02'] are not a subset of the bands [] found in the STAC metadata (unknown bands: ['B01', 'B02']). Using specified bands as is."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... not a subset of the bands [] ...

hmm I'm a bit confused here: if there is no band dimension, doesn't the add_dimension() above at least define a band with name None ? How can the list of bands be empty?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

def get_band_metadata(eo_bands_location: dict) -> List[Band]:
# TODO: return None iso empty list when no metadata?
return [
Band(name=band["name"], common_name=band.get("common_name"), wavelength_um=band.get("center_wavelength"))
for band in eo_bands_location.get("eo:bands", [])
]
receives an empty dict and returns an empty lists which causes bands to be empty in
band_dimension = BandDimension(name="bands", bands=bands)

So I guess there isn't a case where the metadata has no bands dimension. I'll remove

if not metadata.has_band_dimension():
metadata = metadata.add_dimension(
name="bands",
type="bands",
label=None,
)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I guess there isn't a case where the metadata has no bands dimension

not yet, but that will be possible in the future with #743

in caplog.text
)
caplog.clear()


@pytest.mark.parametrize(
"bands",
Expand Down
22 changes: 22 additions & 0 deletions tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,28 @@ def test_band_dimension_band_index():
bdim.band_index("yellow")


def test_band_dimension_contains_band():
bdim = BandDimension(
name="spectral",
bands=[
Band("B02", "blue", 0.490),
Band("B03", "green", 0.560),
Band("B04", "red", 0.665),
],
)

# Test band names
assert bdim.contains_band("B02")
assert not bdim.contains_band("B05")

# Test indexes
assert bdim.contains_band(0)
assert not bdim.contains_band(4)

# Test common names
assert bdim.contains_band("blue")
assert not bdim.contains_band("yellow")

def test_band_dimension_band_name():
bdim = BandDimension(
name="spectral",
Expand Down