Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Error in aggregate over Image2DModel by Labels2DModel when transform is more complex than translation #950

Open

Description

@m-albert

Bug description

I stumbled upon an error when trying to aggregate an Image2DModel by a Labels2DModel in the case one of the two has a transform attached which is more complex than a translation.

Reproducer

import numpy as np
from spatialdata.models import Image2DModel, Labels2DModel
from spatialdata import SpatialData, transform, aggregate
from spatialdata.transformations import Identity, Translation, Scale

sdata = SpatialData()

sdata['image'] = Image2DModel.parse(
    np.ones((1, 10, 10)),
    dims=('c','y', 'x'),
    transformations={
        # 'global': Scale([0.9] * 2, axes=['y', 'x']), # doesn't work with aggregate
        # 'global': Translation([1] * 2, axes=['y', 'x']), # works with aggregate
        'global': Identity(), # works with aggregate
    }
)

labels_array = np.zeros((10, 10)).astype('int')
labels_array[5:8, 5:8] = 1  # Create a

sdata['labels'] = Labels2DModel.parse(
    labels_array,
    dims=('y', 'x'),
    transformations={
        # 'global': Translation([6] * 2, axes=['y', 'x']),
        'global': Identity(),
    }
)

sdata.aggregate(
    values='image',
    by='labels',
    target_coordinate_system='global'
)

ValueError: input arrays must have equal shapes

Activity

  1. m-albert commented on Jul 3, 2025

    @m-albert
    ContributorAuthor

    I just realised that independently of the transforms, different shapes of the image and labels element will also fail:

    import numpy as np
    from spatialdata.models import Image2DModel, Labels2DModel
    from spatialdata import SpatialData, transform, aggregate
    from spatialdata.transformations import Identity, Translation, Scale
    
    sdata = SpatialData()
    
    sdata['image'] = Image2DModel.parse(
        np.ones((1, 20, 20)),
        dims=('c','y', 'x'),
        transformations={
            'global': Identity(), # works with aggregate
        }
    )
    
    labels_array = np.zeros((10, 10)).astype('int')
    labels_array[5:8, 5:8] = 1  # Create a
    
    sdata['labels'] = Labels2DModel.parse(
        labels_array,
        dims=('y', 'x'),
        transformations={
            'global': Identity(),
        }
    )
    
    sdata.aggregate(
        values='image',
        by='labels',
        target_coordinate_system='global'
    )
  2. m-albert commented on Jul 3, 2025

    @m-albert
    ContributorAuthor

    Quick diagnosis attempt:

    In aggregate, the image and labels element are transformed into the desired target coordinate system:

    if not (by_transform == values_transform and isinstance(values_transform, Identity)):
    by_ = transform(by_, to_coordinate_system=target_coordinate_system)
    values_ = transform(values_, to_coordinate_system=target_coordinate_system)

    However, in the case of the combination of image and label elements, the resulting transformed images can have different shapes. Two possible causes aligning with the two cases reported above:

    1. the image and labels element occupy different physical extents (this could be worked around by first performing a spatial query on the elements)
    2. (floating point) differences in the calculation of the output shape (original issue reproducer).

    I guess what could fix this would be if transform() for raster elements would take the desired output origin and shape as arguments. aggregate could then calculate the required values once for the "values" element and pass these to the transform call of both elements, to continue working with precisely aligned raster elements.

  3. LucaMarconato commented on Sep 13, 2026

    @LucaMarconato
    Member

    This whole message is AI-generated. The issue was automatically discovered and reported by an AI agent (Claude) during an autonomous bug hunt on the spatialdata code base. It has not been verified or triaged by a human yet; the needs: triage label 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.

    I re-attempted to reproduce this issue on the current main branch (commit ccf1ea048d054b6624214bf618008a9f9ae223e0) as part of a triage pass over open issues, and confirmed it reproduces.

    Reproduction script (PEP 723 inline metadata; run with uv run repro.py, no other setup needed):

    # /// script
    # requires-python = ">=3.12"
    # dependencies = [
    #     "spatialdata @ git+https://github.com/scverse/spatialdata.git@ccf1ea048d054b6624214bf618008a9f9ae223e0",
    # ]
    # ///
    """#950: aggregate(image, by=labels) fails when the two rasters have a Scale transformation or different shapes."""
    import warnings
    import numpy as np
    from spatialdata import SpatialData
    from spatialdata.models import Image2DModel, Labels2DModel
    from spatialdata.transformations import Identity, Scale
    
    warnings.simplefilter("ignore")
    labels_array = np.zeros((10, 10), dtype=np.uint16)
    labels_array[5:8, 5:8] = 1
    cases = {
        "image Scale(0.9), labels Identity, same shape": (Image2DModel.parse(np.ones((1, 10, 10)), transformations={"global": Scale([0.9, 0.9], axes=["y", "x"])}), Labels2DModel.parse(labels_array, transformations={"global": Identity()})),
        "both Identity, image 20x20 vs labels 10x10": (Image2DModel.parse(np.ones((1, 20, 20)), transformations={"global": Identity()}), Labels2DModel.parse(labels_array, transformations={"global": Identity()})),
        "both Identity, same shape (control)": (Image2DModel.parse(np.ones((1, 10, 10)), transformations={"global": Identity()}), Labels2DModel.parse(labels_array, transformations={"global": Identity()})),
    }
    bug = False
    for name, (img, lab) in cases.items():
        sdata = SpatialData(images={"image": img}, labels={"labels": lab})
        try:
            out = sdata.aggregate(values="image", by="labels", target_coordinate_system="global")
            print(f"{name}: OK -> {out['table'].X.toarray().ravel().tolist()}")
        except Exception as e:  # noqa: BLE001
            print(f"{name}: {type(e).__name__}: {str(e)[:80]}")
            bug |= "control" not in name
    print("VERDICT:", "REPRODUCED" if bug else "NOT REPRODUCED")

    Environment: uv run --no-project --python 3.13, which resolves spatialdata from git+https://github.com/scverse/spatialdata.git@ccf1ea048d054b6624214bf618008a9f9ae223e0 (extra dependencies, if any, are pinned in the script's inline metadata above).

    Output (verbatim, only uv package-resolution/install log lines removed):

    image Scale(0.9), labels Identity, same shape: ValueError: input arrays must have equal shapes
    both Identity, image 20x20 vs labels 10x10: ValueError: input arrays must have equal shapes
    both Identity, same shape (control): OK -> [9.0]
    VERDICT: REPRODUCED
    exit=0
    

    Agent's severity assessment: medium (see the priority: * label added to this issue).


    Automatically generated; discovered by an AI agent (Claude) and not yet reviewed by a human.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions