diff --git a/src/spatialdata_plot/pl/_color.py b/src/spatialdata_plot/pl/_color.py index a62981f6..ca771245 100644 --- a/src/spatialdata_plot/pl/_color.py +++ b/src/spatialdata_plot/pl/_color.py @@ -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}.") @@ -523,6 +527,7 @@ 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") @@ -530,7 +535,7 @@ def _fetch_color_source_vector( # 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, @@ -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: @@ -769,6 +774,13 @@ class ColorSpec: def is_categorical(self) -> bool: return self.colortype == "categorical" + @property + def categorical_source_vector(self) -> pd.Categorical: + """``source_vector``, when :attr:`is_categorical` is True and ``source_vector`` is categorical,.""" + assert self.is_categorical, f"categorical_source requested on a {self.colortype!r} color spec" + assert isinstance(self.source_vector, pd.Categorical), "categorical color spec without a pd.Categorical source" + return self.source_vector + @property def is_continuous(self) -> bool: return self.colortype == "continuous" @@ -819,7 +831,7 @@ 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 - return self.source_vector.isin(groups) + return self.categorical_source_vector.isin(groups) def to_rgba(self, cmap_params: CmapParams) -> np.ndarray: """Map this layer's color to an ``(N, 4)`` RGBA array; the one fill+outline mapping. @@ -833,11 +845,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)) @@ -881,7 +895,10 @@ 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) + source = pd.Categorical( + list(self.categorical_source_vector) + [None] * pad, + categories=self.categorical_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) diff --git a/src/spatialdata_plot/pl/_datashader.py b/src/spatialdata_plot/pl/_datashader.py index dd6fd15e..f2d5b056 100644 --- a/src/spatialdata_plot/pl/_datashader.py +++ b/src/spatialdata_plot/pl/_datashader.py @@ -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. """ @@ -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( diff --git a/src/spatialdata_plot/pl/_geometry.py b/src/spatialdata_plot/pl/_geometry.py index eedb9dda..5e7ea171 100644 --- a/src/spatialdata_plot/pl/_geometry.py +++ b/src/spatialdata_plot/pl/_geometry.py @@ -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: diff --git a/src/spatialdata_plot/pl/render.py b/src/spatialdata_plot/pl/render.py index 644827af..c8ad3611 100644 --- a/src/spatialdata_plot/pl/render.py +++ b/src/spatialdata_plot/pl/render.py @@ -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 @@ -419,7 +421,7 @@ def _add_legend_and_colorbar( palette = color_spec.make_palette() if color_spec.is_categorical: - color_source_vector = color_source_vector.remove_unused_categories() + color_source_vector = color_spec.categorical_source_vector.remove_unused_categories() wants_colorbar = _should_request_colorbar( colorbar, has_mappable=cax is not None, is_continuous=color_spec.is_continuous @@ -427,7 +429,9 @@ def _add_legend_and_colorbar( 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: @@ -460,7 +464,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, @@ -801,7 +806,7 @@ def _render_shapes( ) if has_valid_color and color_spec.is_categorical and col_for_color is not None: # 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()) + color_spec = color_spec.evolve(source_vector=color_spec.categorical_source_vector.remove_unused_categories()) shapes = gpd.GeoDataFrame(shapes, geometry="geometry") @@ -1005,7 +1010,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, @@ -1818,7 +1824,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 diff --git a/test.Dockerfile b/test.Dockerfile index 042b98f8..f0f5271a 100644 --- a/test.Dockerfile +++ b/test.Dockerfile @@ -43,6 +43,6 @@ RUN python3 -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN pip install --upgrade pip wheel -RUN pip install -e ".[dev,test]" +RUN pip install -e . --group dev --group test CMD ["pytest", "-v", "tests/pl/test_render.py"] diff --git a/tests/pl/test_show.py b/tests/pl/test_show.py index 1e80d945..178599d5 100644 --- a/tests/pl/test_show.py +++ b/tests/pl/test_show.py @@ -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)()) @@ -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) diff --git a/tests/pl/test_utils.py b/tests/pl/test_utils.py index 7eeb4bb4..5fe325ee 100644 --- a/tests/pl/test_utils.py +++ b/tests/pl/test_utils.py @@ -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"): diff --git a/tests/test_interactive/test_commit.py b/tests/test_interactive/test_commit.py index 66c87d0e..2db5d381 100644 --- a/tests/test_interactive/test_commit.py +++ b/tests/test_interactive/test_commit.py @@ -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}]}], @@ -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 @@ -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}]}],