to_circles(labels) crashes when the labels have a non-identity linear transformation (Scale/Affine) — i.e. on real data
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 394
- Forks
- 95
- Avg merge
- 4d 3h
- Merged PRs (30d)
- 7
Description
[!NOTE]
This whole message is AI-generated. The issue was automatically discovered and reported by an AI agent (Claude) during an autonomous bug hunt on thespatialdatacode base. It has not been verified or triaged by a human yet; theneeds: triagelabel is set so that a maintainer can confirm it. The reproduction script below was executed by the agent in an isolated environment (see Environment) and its output is pasted verbatim.
Summary
aggregate(values=ones, by=labels) sees two different transformations and transforms both rasters; the labels are resampled by the linear part of their affine while the ones image is not, and xrspatial.zonal_stats fails with ValueError: input arrays must have equal shapes. Also reproduced on the CosMx dataset from spatialdata-sandbox (cosmx_io, labels with an Affine). Translation works because raster transforms ignore it.
Severity (agent's assessment): medium/high — real segmentation masks essentially always carry a scale or affine to global; ImageTilesDataset calls to_circles(labels) internally
Where: src/spatialdata/_core/operations/vectorize.py::to_circles (DataArray/DataTree overload builds a ones image with the default Identity transformation and aggregates the labels by it)
Expected behaviour
to_circles(labels) works regardless of the transformation attached to the labels.
Reproduction
Save as repro.py and run uv run repro.py (the PEP 723 header pins spatialdata to the commit the bug was found on; replace the URL fragment with @main to test the current main branch).
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "spatialdata @ git+https://github.com/scverse/spatialdata.git@ccf1ea048d054b6624214bf618008a9f9ae223e0",
# ]
# ///
"""to_circles(labels) crashes when the labels have a non-identity linear transformation (Scale/Affine)."""
import warnings
import numpy as np
from spatialdata import to_circles
from spatialdata.models import Labels2DModel
from spatialdata.transformations import Identity, Scale, Translation
warnings.simplefilter("ignore")
arr = np.zeros((8, 8), dtype=np.uint16)
arr[:4, :4] = 1
arr[4:, 4:] = 2
bug = False
for name, t in [("Identity", Identity()), ("Translation", Translation([5, 5], axes=("x", "y"))), ("Scale 2", Scale([2, 2], axes=("x", "y")))]:
labels = Labels2DModel.parse(arr.copy(), transformations={"global": t})
try:
circles = to_circles(labels)
print(f"labels with {name:11s}: OK, radii {circles.radius.round(2).tolist()}")
except Exception as e: # noqa: BLE001
print(f"labels with {name:11s}: {type(e).__name__}: {e}")
bug = True
print("VERDICT:", "BUG REPRODUCED" if bug else "NOT REPRODUCED")
Observed output
labels with Identity : OK, radii [2.26, 2.26]
labels with Translation: OK, radii [2.26, 2.26]
labels with Scale 2 : ValueError: input arrays must have equal shapes
VERDICT: BUG REPRODUCED
Possible fix direction (unverified)
Give the ones image the labels' transformations, or compute areas directly with np.unique(..., return_counts=True) / bincount on the label array (no aggregate needed; _get_centroids_for_labels already computes per-label pixel counts).
Environment
uv run repro.py with the PEP 723 metadata in the script (fresh, isolated environment; spatialdata built from main @ ccf1ea0 (2026-08-28); Python 3.13, latest releases of the dependencies at run time: pandas 3.0, anndata 0.13, zarr 3.3, dask 2026.8, numpy 2.5, geopandas 1.1, shapely 2.1). macOS (arm64). Also reproduced in a second environment with pandas 2.3.3 / anndata 0.12.11 / numpy 2.4.4 / zarr 3.2.1.
Automatically generated; discovered by an AI agent (Claude) and not yet reviewed by a human.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied repro.py, then inspect src/spatialdata/_core/operations/vectorize.py::to_circles and the transformation handling used by aggregate. Confirm the failure with Scale or Affine and the successful Identity and Translation cases. Done means to_circles(labels) completes for non-identity linear transformations without the equal-shapes error and preserves the expected circle results.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- numpy, python
- Domain
- data
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Clearly specified
- Newbie friendliness
- 74/100