Skip to content

render_images(scale='nonexistent') silently falls back to auto-resolution with no warning #623

@timtreis

Description

@timtreis

render_images(scale="nonexistent") silently falls back to auto-resolution with no warning

Environment: spatialdata-plot 0.3.4.dev (main, commit 5cfedc7), Python 3.13


Problem

When render_images(scale=...) is called with a scale name that doesn't exist in the multiscale image (e.g., a typo like scale="Scale0" instead of scale="scale0"), the parameter is silently reset to None (auto-detect) instead of raising an error or warning. The user's intent is discarded without notice and the image renders at a different resolution.

The validation at utils.py:2976–2978:

if scale and isinstance(param_dict["sdata"][el], DataTree):
    if scale not in list(param_dict["sdata"][el].keys()) and scale != "full":
        element_params[el]["scale"] = None   # silently reset, no warning

Ironically, the downstream function _multiscale_to_spatial_image does have a proper ValueError for invalid scale names — but it is never reached because the invalid scale was already cleared to None before rendering.


Minimal reproducible example

import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import dask; dask.config.set({"dataframe.query-planning": False})
import spatialdata as sd
from spatialdata.models import Image2DModel
import spatialdata_plot

full = np.random.randint(0, 255, (1, 64, 64), dtype=np.uint8)
img_ms = Image2DModel.parse(full, dims=["c", "y", "x"], c_coords=["DAPI"],
                             scale_factors=[2, 2])
print(f"Valid scales: {list(img_ms.children.keys())}")
# ['scale0', 'scale1', 'scale2']

sdata = sd.SpatialData(images={"img": img_ms})

fig, ax = plt.subplots()
# Typo: capital S — should error, but silently falls back to full resolution
sdata.pl.render_images("img", scale="Scale0").pl.show(ax=ax)
print(f"Rendered shape: {ax.images[0].get_array().shape}")  # (64, 64) — full res, no error

Expected behaviour

ValueError: Scale 'Scale0' does not exist in image 'img'.
Valid scales: ['scale0', 'scale1', 'scale2', 'full'].

(This error already exists in _multiscale_to_spatial_image — it just never gets called.)

Actual behaviour

No error, no warning. Image renders at full resolution (64×64) instead of the requested scale. For large WSI datasets this can mean loading gigabytes of data instead of a thumbnail.


Fix sketch

At utils.py:2977, replace the silent element_params[el]["scale"] = None with a warning (or error):

if scale not in list(param_dict["sdata"][el].keys()) and scale != "full":
    valid = list(param_dict["sdata"][el].keys())
    raise ValueError(
        f"Scale '{scale}' not found in image '{el}'. "
        f"Valid scales: {valid + ['full']}."
    )

A UserWarning + fallback is also acceptable, but the current silent discard is not.


Triage tier: Tier 3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions