From 6bb3786d2c4671d499884f6c87181b0bb14d4ede Mon Sep 17 00:00:00 2001 From: stanbot8 Date: Fri, 24 Jul 2026 08:21:03 -0700 Subject: [PATCH 1/4] fix: support raster labels above uint16 --- src/spatialdata/_core/operations/rasterize.py | 7 ++---- tests/core/operations/test_rasterize.py | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/spatialdata/_core/operations/rasterize.py b/src/spatialdata/_core/operations/rasterize.py index 113d26fc7..4bcb6bf48 100644 --- a/src/spatialdata/_core/operations/rasterize.py +++ b/src/spatialdata/_core/operations/rasterize.py @@ -30,7 +30,7 @@ get_axes_names, get_model, ) -from spatialdata.models._utils import get_spatial_axes +from spatialdata.models._utils import _get_uint_dtype, get_spatial_axes from spatialdata.transformations._utils import _get_scale, compute_coordinates from spatialdata.transformations.operations import get_transformation, remove_transformation, set_transformation from spatialdata.transformations.transformations import ( @@ -747,10 +747,7 @@ def rasterize_shapes_points( max_label = next(iter(reversed(label_index_to_category.keys()))) else: max_label = int(agg.max().values) - max_uint16 = np.iinfo(np.uint16).max - if max_label > max_uint16: - raise ValueError(f"Maximum label index is {max_label}. Values higher than {max_uint16} are not supported.") - agg = agg.astype(np.uint16) + agg = agg.astype(_get_uint_dtype(max_label)) return Labels2DModel.parse(agg, transformations=transformations) agg = agg.expand_dims(dim={"c": 1}).transpose("c", "y", "x") diff --git a/tests/core/operations/test_rasterize.py b/tests/core/operations/test_rasterize.py index 53d362d15..249ec94a2 100644 --- a/tests/core/operations/test_rasterize.py +++ b/tests/core/operations/test_rasterize.py @@ -446,6 +446,29 @@ def _rasterize(element: DaskDataFrame, **kwargs) -> SpatialImage: assert d[res[1, 2]] == 4 +def test_rasterize_points_selects_label_dtype(): + n_points = np.iinfo(np.uint16).max + 1 + points = PointsModel.parse( + dd.from_pandas( + pd.DataFrame({"x": np.arange(n_points), "y": np.zeros(n_points)}), + npartitions=1, + ) + ) + + result = rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[n_points, 1], + target_coordinate_system="global", + target_width=n_points, + return_regions_as_labels=True, + ) + + assert result.dtype == np.uint32 + assert result.max().compute() == n_points + + def test_rasterize_spatialdata(full_sdata): sdata = full_sdata.subset( ["image2d", "image2d_multiscale", "labels2d", "labels2d_multiscale", "points_0", "circles"] From e9ea9c7f907d77aa1ea3fef30a03daf3c07c8f10 Mon Sep 17 00:00:00 2001 From: Jan Gleixner Date: Wed, 18 Nov 2026 15:53:43 +0100 Subject: [PATCH 2/4] test: xfail rasterize labels above 2**53 (float64 precision) --- tests/core/operations/test_rasterize.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/core/operations/test_rasterize.py b/tests/core/operations/test_rasterize.py index 249ec94a2..dbf127157 100644 --- a/tests/core/operations/test_rasterize.py +++ b/tests/core/operations/test_rasterize.py @@ -469,6 +469,27 @@ def test_rasterize_points_selects_label_dtype(): assert result.max().compute() == n_points +@pytest.mark.xfail(reason="datashader aggregates in float64, so labels above 2**53 are silently rounded") +def test_rasterize_labels_above_float64_precision(): + label = 2**53 + 1 + df = pd.DataFrame({"x": [0.5, 1.5], "y": [0.5, 0.5], "label": np.array([1, label], dtype=np.uint64)}) + points = PointsModel.parse(dd.from_pandas(df, npartitions=1)) + + result = rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[2, 1], + target_coordinate_system="global", + target_width=2, + value_key="label", + agg_func="first", + return_regions_as_labels=True, + ) + + assert int(result.max().compute()) == label + + def test_rasterize_spatialdata(full_sdata): sdata = full_sdata.subset( ["image2d", "image2d_multiscale", "labels2d", "labels2d_multiscale", "points_0", "circles"] From 30b6ea1309af6bf0d2ceba74823b1ba494d9f3d1 Mon Sep 17 00:00:00 2001 From: Jan Gleixner Date: Wed, 18 Nov 2026 16:12:32 +0100 Subject: [PATCH 3/4] test: xfail rasterize labels >= 2**53, incl. summed overlaps --- tests/core/operations/test_rasterize.py | 53 +++++++++++++++++-------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/tests/core/operations/test_rasterize.py b/tests/core/operations/test_rasterize.py index dbf127157..8073d7e99 100644 --- a/tests/core/operations/test_rasterize.py +++ b/tests/core/operations/test_rasterize.py @@ -469,25 +469,46 @@ def test_rasterize_points_selects_label_dtype(): assert result.max().compute() == n_points -@pytest.mark.xfail(reason="datashader aggregates in float64, so labels above 2**53 are silently rounded") -def test_rasterize_labels_above_float64_precision(): - label = 2**53 + 1 - df = pd.DataFrame({"x": [0.5, 1.5], "y": [0.5, 0.5], "label": np.array([1, label], dtype=np.uint64)}) +_XFAIL_FLOAT64 = pytest.mark.xfail( + reason="datashader aggregates in float64, so labels of 2**53 or higher are silently rounded" +) + + +@pytest.mark.parametrize( + ("x", "labels", "agg_func", "raises"), + [ + ([0.5, 1.5], [1, 2**53 - 1], "first", False), + pytest.param([0.5, 1.5], [1, 2**53], "first", True, marks=_XFAIL_FLOAT64), + pytest.param([0.5, 1.5], [1, 2**53 + 1], "first", True, marks=_XFAIL_FLOAT64), + # overlapping labels are summed: each label is below 2**53, the sum is not + pytest.param([0.5, 0.5, 0.5], [2**52 + 1] * 3, "sum", True, marks=_XFAIL_FLOAT64), + ], +) +def test_rasterize_labels_above_float64_precision(x, labels, agg_func, raises): + # datashader aggregates in float64: from 2**53 on, values may be silently rounded, so they must raise + df = pd.DataFrame({"x": x, "y": [0.5] * len(x), "label": np.array(labels, dtype=np.uint64)}) points = PointsModel.parse(dd.from_pandas(df, npartitions=1)) - result = rasterize( - points, - axes=("x", "y"), - min_coordinate=[0, 0], - max_coordinate=[2, 1], - target_coordinate_system="global", - target_width=2, - value_key="label", - agg_func="first", - return_regions_as_labels=True, - ) + def _rasterize(): + return rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[2, 1], + target_coordinate_system="global", + target_width=2, + value_key="label", + agg_func=agg_func, + return_regions_as_labels=True, + ) - assert int(result.max().compute()) == label + if raises: + with pytest.raises(ValueError, match=r"2\*\*53"): + _rasterize() + else: + result = _rasterize() + assert result.dtype == np.uint64 + assert int(result.max().compute()) == max(labels) def test_rasterize_spatialdata(full_sdata): From 329721c80aa5666ceb21d099188ad0bded3f49ee Mon Sep 17 00:00:00 2001 From: Jan Gleixner Date: Wed, 18 Nov 2026 16:16:30 +0100 Subject: [PATCH 4/4] fix: raise for raster labels >= 2**53 instead of silently rounding --- docs/changelog.md | 1 + src/spatialdata/_core/operations/rasterize.py | 7 ++ tests/core/operations/test_rasterize.py | 80 ++++++++++--------- 3 files changed, 52 insertions(+), 36 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 89658c92a..dffc9f5d8 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -13,4 +13,5 @@ For developers, please consult the [contributing guide](https://github.com/scver ### Fixed +- `rasterize(..., return_regions_as_labels=True)` now supports more than 65,535 labels: the output dtype is `uint16`, `uint32` or `uint64` depending on the maximum label. Labels of 2**53 or higher (also from summing overlapping labels) raise a `ValueError` instead of being silently rounded (datashader aggregates in float64). - Querying a `SpatialData` object with multiple (batched) bounding boxes now raises an explicit `NotImplementedError` instead of failing with an opaque `AssertionError`. Batched queries are supported when querying a `SpatialElement` directly, but not when querying a `SpatialData` object, since that would require returning one `SpatialData` object per bounding box. diff --git a/src/spatialdata/_core/operations/rasterize.py b/src/spatialdata/_core/operations/rasterize.py index 9b5cf7d09..071f1e108 100644 --- a/src/spatialdata/_core/operations/rasterize.py +++ b/src/spatialdata/_core/operations/rasterize.py @@ -767,6 +767,13 @@ def rasterize_shapes_points( max_label = next(iter(reversed(label_index_to_category.keys()))) else: max_label = int(agg.max().values) + # datashader aggregates in float64: from 2**53 on, a value may be a rounded larger integer + # (from large input labels or from summing overlapping labels) + if max_label >= 2**53: + raise ValueError( + f"Maximum label is at least {max_label}. Labels of 2**53 or higher cannot be rasterized exactly " + "because datashader aggregates in float64." + ) agg = agg.astype(_get_uint_dtype(max_label)) return Labels2DModel.parse(agg, transformations=transformations) diff --git a/tests/core/operations/test_rasterize.py b/tests/core/operations/test_rasterize.py index 8073d7e99..56c314966 100644 --- a/tests/core/operations/test_rasterize.py +++ b/tests/core/operations/test_rasterize.py @@ -469,46 +469,54 @@ def test_rasterize_points_selects_label_dtype(): assert result.max().compute() == n_points -_XFAIL_FLOAT64 = pytest.mark.xfail( - reason="datashader aggregates in float64, so labels of 2**53 or higher are silently rounded" -) - - -@pytest.mark.parametrize( - ("x", "labels", "agg_func", "raises"), - [ - ([0.5, 1.5], [1, 2**53 - 1], "first", False), - pytest.param([0.5, 1.5], [1, 2**53], "first", True, marks=_XFAIL_FLOAT64), - pytest.param([0.5, 1.5], [1, 2**53 + 1], "first", True, marks=_XFAIL_FLOAT64), - # overlapping labels are summed: each label is below 2**53, the sum is not - pytest.param([0.5, 0.5, 0.5], [2**52 + 1] * 3, "sum", True, marks=_XFAIL_FLOAT64), - ], -) -def test_rasterize_labels_above_float64_precision(x, labels, agg_func, raises): - # datashader aggregates in float64: from 2**53 on, values may be silently rounded, so they must raise +def _rasterize_point_labels(x, labels, agg_func): df = pd.DataFrame({"x": x, "y": [0.5] * len(x), "label": np.array(labels, dtype=np.uint64)}) points = PointsModel.parse(dd.from_pandas(df, npartitions=1)) + return rasterize( + points, + axes=("x", "y"), + min_coordinate=[0, 0], + max_coordinate=[2, 1], + target_coordinate_system="global", + target_width=2, + value_key="label", + agg_func=agg_func, + return_regions_as_labels=True, + ) + + +# (x, labels, agg_func, expected maximum label) +_LARGE_LABEL_CASES = [ + ([0.5, 1.5], [1, 2**53], "first", 2**53), + ([0.5, 1.5], [1, 2**53 + 1], "first", 2**53 + 1), + # overlapping labels are summed: each label is below 2**53, the sum is not + ([0.5, 0.5], [2**53 - 1, 2], "sum", 2**53 + 1), +] - def _rasterize(): - return rasterize( - points, - axes=("x", "y"), - min_coordinate=[0, 0], - max_coordinate=[2, 1], - target_coordinate_system="global", - target_width=2, - value_key="label", - agg_func=agg_func, - return_regions_as_labels=True, - ) - if raises: - with pytest.raises(ValueError, match=r"2\*\*53"): - _rasterize() - else: - result = _rasterize() - assert result.dtype == np.uint64 - assert int(result.max().compute()) == max(labels) +def test_rasterize_labels_below_float64_precision(): + result = _rasterize_point_labels([0.5, 1.5], [1, 2**53 - 1], "first") + assert result.dtype == np.uint64 + assert int(result.max().compute()) == 2**53 - 1 + + +@pytest.mark.parametrize(("x", "labels", "agg_func", "expected"), _LARGE_LABEL_CASES) +def test_rasterize_labels_above_float64_precision_raises(x, labels, agg_func, expected): + # until rasterization is exact for large labels, they must raise instead of being silently rounded + with pytest.raises(ValueError, match=r"2\*\*53"): + _rasterize_point_labels(x, labels, agg_func) + + +@pytest.mark.xfail( + reason="datashader aggregates in float64, so labels of 2**53 or higher cannot be rasterized exactly", + strict=False, # an unexpected pass (root cause fixed) should not fail CI; the ValueError test will flag the guard +) +@pytest.mark.parametrize(("x", "labels", "agg_func", "expected"), _LARGE_LABEL_CASES) +def test_rasterize_labels_above_float64_precision(x, labels, agg_func, expected): + # the desired behaviour once the root cause is fixed; the ValueError guard and its test should then be removed + result = _rasterize_point_labels(x, labels, agg_func) + assert result.dtype == np.uint64 + assert int(result.max().compute()) == expected def test_rasterize_spatialdata(full_sdata):