Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 21 additions & 5 deletions src/spatialdata_plot/pl/_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ class PercentileNormalize(Normalize):
backend contrast autoscales to the aggregate range rather than to these percentiles.
"""

# Declared for type checkers only (no runtime attribute, so Normalize's vmin/vmax properties still apply).
vmin: float | None
vmax: float | None

def __init__(self, pmin: float = 0.0, pmax: float = 100.0, clip: bool = False) -> None:
if not 0.0 <= pmin < pmax <= 100.0:
raise ValueError(f"Require 0 <= pmin < pmax <= 100, got pmin={pmin}, pmax={pmax}.")
Expand Down Expand Up @@ -523,14 +527,15 @@ def _fetch_color_source_vector(
if (
isinstance(element, GeoDataFrame)
and isinstance(element_name, str)
and isinstance(value_to_plot, str)
and table_name is not None
and table_name in sdata.tables
and origins[0].origin in ("obs", "var")
):
# Fast path: read the single aligned column directly instead of joining/copying the
# whole annotating table (the join's out-of-order sparse row-gather dominates large renders).
return _extract_color_column(
sdata[table_name],
sdata.tables[table_name],
value_to_plot,
origin=origins[0].origin,
element=element,
Expand Down Expand Up @@ -564,7 +569,7 @@ def _resolve_color_table(value_from_element: bool, table_name: str | None, sdata
return table_name
logger.warning(f"Table '{table_name}' not found in `sdata.tables`. Falling back to default behavior.")
return None
table_keys = list(sdata.tables.keys())
table_keys: list[str] = list(sdata.tables.keys())
if not table_keys:
return None
if len(table_keys) > 1:
Expand Down Expand Up @@ -819,6 +824,10 @@ def groups_keep_mask(self, groups: Any, na_color: Color) -> Any | None:
return None
if not (na_color.default_color_set or na_color.is_fully_transparent()):
return None

# needed to tell mypy that, in this case, `source_vector` is expected to be `pd.Categorical`
assert isinstance(self.source_vector, pd.Categorical)

return self.source_vector.isin(groups)

def to_rgba(self, cmap_params: CmapParams) -> np.ndarray:
Expand All @@ -833,11 +842,13 @@ def to_rgba(self, cmap_params: CmapParams) -> np.ndarray:
# categories are hex (resolution fills NaN with an na_color category -> codes >= 0),
# so parse the few categories once and gather by code instead of parsing every row
lut = np.asarray(colors.to_rgba_array(cv.categories.to_numpy()))
return lut[cv.codes]
cat_rgba: np.ndarray = lut[cv.codes]
return cat_rgba
# object vector (align_to_length pad / uniform na): factorize the distinct colours and
# gather back (factorize keeps any NaN as a real code, so the gather stays in-bounds)
codes, uniq = pd.factorize(np.asarray(cv, dtype=object), sort=False, use_na_sentinel=False)
return np.asarray(colors.to_rgba_array(list(uniq)))[codes]
obj_rgba: np.ndarray = np.asarray(colors.to_rgba_array(list(uniq)))[codes]
return obj_rgba
arr = np.asarray(self.color_vector)
if arr.ndim == 2 and arr.shape[1] in (3, 4) and np.issubdtype(arr.dtype, np.number):
return np.asarray(colors.to_rgba_array(arr))
Expand Down Expand Up @@ -881,7 +892,12 @@ def align_to_length(self, n: int, na_color: Color) -> ColorSpec:
na_hex = na_color.get_hex_with_alpha()
padded = np.concatenate([np.asarray(vec, dtype=object), np.full(pad, na_hex, dtype=object)])
if self.is_categorical:
source = pd.Categorical(list(self.source_vector) + [None] * pad, categories=self.source_vector.categories)
# needed to tell mypy that, in this case, `source_vector` is expected to be `pd.Categorical`
assert isinstance(self.source_vector, pd.Categorical)
source = pd.Categorical(
list(self.source_vector) + [None] * pad,
categories=self.source_vector.categories,
)
else: # none: source is an na array, not a Categorical — extend it with na entries
source = np.concatenate([np.asarray(self.source_vector, dtype=object), np.full(pad, na_hex, dtype=object)])
return replace(self, source_vector=source, color_vector=padded)
Expand Down
4 changes: 2 additions & 2 deletions src/spatialdata_plot/pl/_datashader.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def _ds_shade_categorical(


def _color_vector_is_uniform(color_vector: Any) -> bool:
"""True if every entry of the per-point colour vector is identical (so per-point colouring collapses).
"""Return whether every entry of the per-point colour vector is identical (so per-point colouring collapses).

Shared by the datashader categorical collapse and the matplotlib scalar-colour fast path.
"""
Expand All @@ -343,7 +343,7 @@ def _color_vector_is_uniform(color_vector: Any) -> bool:
arr = np.asarray(color_vector)
if arr.dtype.kind in "US": # fixed-width strings (the resolved-hex case): cheap vectorised compare
return bool((arr == arr[0]).all())
return pd.Series(arr).nunique(dropna=False) == 1 # object/other: hash-based, no sort
return bool(pd.Series(arr).nunique(dropna=False) == 1) # object/other: hash-based, no sort


def _shade_datashader_aggregate(
Expand Down
5 changes: 4 additions & 1 deletion src/spatialdata_plot/pl/_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ def _scale_geometries(geometries: np.ndarray, scale: float) -> np.ndarray:
bbox = shapely.bounds(geometries) # (n, 4): minx, miny, maxx, maxy
centre = np.column_stack([(bbox[:, 0] + bbox[:, 2]) / 2, (bbox[:, 1] + bbox[:, 3]) / 2])
coords, idx = shapely.get_coordinates(geometries, return_index=True)
return shapely.set_coordinates(geometries.copy(), (coords - centre[idx]) * scale + centre[idx])
scaled_geometries: np.ndarray = shapely.set_coordinates(
geometries.copy(), (coords - centre[idx]) * scale + centre[idx]
)
return scaled_geometries


def _normalize_geom(geom: Any) -> Any:
Expand Down
25 changes: 18 additions & 7 deletions src/spatialdata_plot/pl/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,10 @@ def _pin_norm_to_full_range(
cmap_params: CmapParams,
transfunc: Callable[..., Any] | None,
) -> None:
"""Pin ``norm`` in place to the full (pre-crop) continuous range so a cropped matplotlib zoom keeps
the uncropped plot's colours. No-op when uncropped (``full_color_spec is None``) or categorical.
"""Pin ``norm`` in place to the full (pre-crop) continuous range.

This keeps a cropped matplotlib zoom on the uncropped plot's colours.
No-op when uncropped (``full_color_spec is None``) or categorical.
"""
if full_color_spec is None:
return
Expand Down Expand Up @@ -419,15 +421,19 @@ def _add_legend_and_colorbar(
palette = color_spec.make_palette()

if color_spec.is_categorical:
color_source_vector = color_source_vector.remove_unused_categories()
# needed to tell mypy that, in this case, `source_vector` is expected to be `pd.Categorical`
assert isinstance(color_spec.source_vector, pd.Categorical)
color_source_vector = color_spec.source_vector.remove_unused_categories()

wants_colorbar = _should_request_colorbar(
colorbar, has_mappable=cax is not None, is_continuous=color_spec.is_continuous
)

if fill_has_decorations:
# Auto-title the fill legend only when an outline legend will also be drawn.
outline_legend_will_render = outline_has_decorations and outline_color_spec.is_categorical
outline_legend_will_render = (
outline_has_decorations and outline_color_spec is not None and outline_color_spec.is_categorical
)
if legend_params.legend_title is not None:
fill_title: str | None = legend_params.legend_title or None
elif outline_legend_will_render and color_spec.is_categorical:
Expand Down Expand Up @@ -460,7 +466,8 @@ def _add_legend_and_colorbar(
legend_params=legend_params,
)

if outline_has_decorations and outline_cmap_params is not None:
if outline_has_decorations and outline_color_spec is not None and outline_cmap_params is not None:
# mypy doesn't understand that `outline_has_decorations` already means `outline_color_spec is not None`
_decorate_outline(
ax=ax,
fig_params=fig_params,
Expand Down Expand Up @@ -800,6 +807,9 @@ def _render_shapes(
or next(iter(distinct_colors)) != render_params.cmap_params.na_color.get_hex_with_alpha()
)
if has_valid_color and color_spec.is_categorical and col_for_color is not None:
# needed to tell mypy that, in this case, `source_vector` is expected to be `pd.Categorical`
assert isinstance(color_spec.source_vector, pd.Categorical)

# necessary in case different shapes elements are annotated with one table
color_spec = color_spec.evolve(source_vector=color_spec.source_vector.remove_unused_categories())

Expand Down Expand Up @@ -1005,7 +1015,8 @@ def _draw_centroids(xy: np.ndarray, radius: float | None = None) -> None:
path.vertices = trans.transform(path.vertices)

# render outlines separately to ensure they are always underneath the shape
if col_for_outline_color is not None and render_params.outline_alpha[0] > 0:
if col_for_outline_color is not None and outline_color_spec is not None and render_params.outline_alpha[0] > 0:
# extra `outline_color_spec is not None` is needed only for mypy
outline_rgba = outline_color_spec.to_rgba(render_params.cmap_params)
_cax = _get_collection_shape(
shapes=shapes,
Expand Down Expand Up @@ -1818,7 +1829,7 @@ def _composite_channels(
Holds O(1) full-resolution buffers instead of the full ``(n_channels, H, W, 4)`` cube;
byte-identical to stacking then summing because the reduction is sequential.
"""
acc = channel_cmaps[0](layers[channels[0]])[:, :, :3].copy()
acc: np.ndarray = channel_cmaps[0](layers[channels[0]])[:, :, :3].copy()
for cmap, ch in zip(channel_cmaps[1:], channels[1:], strict=True):
acc += cmap(layers[ch])[:, :, :3]
return acc
Expand Down
4 changes: 2 additions & 2 deletions tests/pl/test_show.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def _legend_colors(ax):
out = {}
if leg is None:
return out
for text, handle in zip(leg.get_texts(), leg.legend_handles):
for text, handle in zip(leg.get_texts(), leg.legend_handles, strict=True):
for attr in ("get_facecolor", "get_color"):
try:
v = np.ravel(getattr(handle, attr)())
Expand Down Expand Up @@ -419,7 +419,7 @@ def test_crop_labels_no_color_reshuffle(col):
)
crop_colors = _legend_colors(cropped)
plt.close("all")
shared = [c for c in set(full_colors) & set(crop_colors)]
shared = list(set(full_colors) & set(crop_colors))
assert shared # the window keeps several categories
for c in shared:
assert full_colors[c] == pytest.approx(crop_colors[c], abs=0.02)
Expand Down
2 changes: 1 addition & 1 deletion tests/pl/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ def _rot(theta: float) -> Affine:
}
set_transformation(sdata_blobs[element], transforms[kind], "cs")
sub = SpatialData(shapes={element: sdata_blobs[element]})
kw = dict(has_images=False, has_labels=False, has_points=False)
kw = {"has_images": False, "has_labels": False, "has_points": False}
fast = _get_extent_fast(sub, "cs", **kw)
exact = get_extent(sub, "cs", exact=True, **kw)
for ax in ("x", "y"):
Expand Down
41 changes: 37 additions & 4 deletions tests/test_interactive/test_commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,16 @@ def test_point_to_circle_has_expected_centroid_and_radius():


def test_collect_geoms_orders_rois_polygons_points():
f_args = dict(xmin=0.0, xmax=100.0, y_lo=0.0, y_hi=100.0, image_w=100, image_h=100, point_radius=1.0)
f_args = {
"xmin": 0.0,
"xmax": 100.0,
"y_lo": 0.0,
"y_hi": 100.0,
"image_w": 100,
"image_h": 100,
"point_radius": 1.0,
}

viewer = SimpleNamespace(
_rois_data=[{"x": 0, "y": 0, "width": 10, "height": 10}],
_polygons_data=[{"points": [{"x": 20, "y": 20}, {"x": 30, "y": 20}, {"x": 30, "y": 30}]}],
Expand All @@ -91,7 +100,15 @@ def test_collect_geoms_orders_rois_polygons_points():


def test_collect_geoms_silently_skips_invalid_entries():
f_args = dict(xmin=0.0, xmax=10.0, y_lo=0.0, y_hi=10.0, image_w=10, image_h=10, point_radius=0.5)
f_args = {
"xmin": 0.0,
"xmax": 10.0,
"y_lo": 0.0,
"y_hi": 10.0,
"image_w": 10,
"image_h": 10,
"point_radius": 0.5,
}
viewer = SimpleNamespace(
_rois_data=[{"x": 0, "y": 0}], # missing width/height
_polygons_data=[{"points": [{"x": 0, "y": 0}]}], # only 1 vertex
Expand All @@ -101,14 +118,30 @@ def test_collect_geoms_silently_skips_invalid_entries():


def test_collect_geoms_handles_none_buffers():
f_args = dict(xmin=0.0, xmax=10.0, y_lo=0.0, y_hi=10.0, image_w=10, image_h=10, point_radius=0.5)
f_args = {
"xmin": 0.0,
"xmax": 10.0,
"y_lo": 0.0,
"y_hi": 10.0,
"image_w": 10,
"image_h": 10,
"point_radius": 0.5,
}
viewer = SimpleNamespace(_rois_data=None, _polygons_data=None, _points_data=None)
assert collect_geoms_from_viewer(viewer, **f_args) == []


def test_collect_geoms_returns_polygon_typed_geometries():
"""All three input categories should produce Polygons (points → buffered circles)."""
f_args = dict(xmin=0.0, xmax=10.0, y_lo=0.0, y_hi=10.0, image_w=10, image_h=10, point_radius=0.5)
f_args = {
"xmin": 0.0,
"xmax": 10.0,
"y_lo": 0.0,
"y_hi": 10.0,
"image_w": 10,
"image_h": 10,
"point_radius": 0.5,
}
viewer = SimpleNamespace(
_rois_data=[{"x": 1, "y": 1, "width": 1, "height": 1}],
_polygons_data=[{"points": [{"x": 4, "y": 4}, {"x": 5, "y": 4}, {"x": 5, "y": 5}]}],
Expand Down