diff --git a/src/spatialdata/_core/query/relational_query.py b/src/spatialdata/_core/query/relational_query.py index bb3c3c08f..af90b7d02 100644 --- a/src/spatialdata/_core/query/relational_query.py +++ b/src/spatialdata/_core/query/relational_query.py @@ -237,7 +237,7 @@ def _get_masked_element( mask_values: NDArray[Any] | pd.Index | None = ( masked_values if len(masked_values := masked_table_instance_key_column.to_numpy()) != 0 else None ) - if match_rows in ["left", "right"]: + if match_rows in ["left", "right"] and mask_values is not None: left_index, _ = _match_rows(table_instance_key_column, mask, element_indices, match_rows) if mask_values is not None and len(left_index) != len(mask_values): @@ -250,7 +250,9 @@ def _get_masked_element( mask_values = np.asarray(element_indices)[order_mask] if isinstance(element, DaskDataFrame): - masked: SpatialElement = element.map_partitions(lambda df: df.loc[mask_values], meta=element) + masked: SpatialElement = element.map_partitions( + lambda df: df.loc[mask_values if mask_values is not None else []], meta=element + ) return masked if not isinstance(element, GeoDataFrame): raise TypeError(f"Only points and shapes elements can be masked, got {type(element).__name__}.") @@ -562,6 +564,8 @@ def _match_rows( element_index_df = pd.DataFrame({"index_left": element_indices}) merged_df = pd.merge(element_index_df, instance_id_df, left_on="index_left", right_on="instance_id", how=match_rows) + if merged_df.empty: + return pd.Index([]), pd.Index([]) index_left = merged_df["index_left"] index_right = merged_df["index_right"] @@ -652,6 +656,9 @@ def join_spatialelement_table( SpatialElement(s) and a table, for each an element is returned only containing the rows that are present in both the SpatialElement and table. + If nothing matches, an empty element or a table with 0 rows is returned. `None` is only returned for the side that + an exclusive join never returns: the table for ``'left_exclusive'`` and the elements for ``'right_exclusive'``. + For Points and Shapes elements every valid join for argument how is supported. For Labels elements only the ``'left'`` and ``'right_exclusive'`` joins are supported. For Labels, the background label (0) is not included in the output and it will not be returned. diff --git a/tests/core/query/test_relational_query.py b/tests/core/query/test_relational_query.py index 07d232559..218338d25 100644 --- a/tests/core/query/test_relational_query.py +++ b/tests/core/query/test_relational_query.py @@ -9,8 +9,10 @@ import pandas as pd import pytest from anndata import AnnData +from geopandas import GeoDataFrame +from shapely.geometry import Point -from spatialdata import SpatialData, get_values, match_table_to_element +from spatialdata import SpatialData, get_element_instances, get_values, match_table_to_element from spatialdata._core.query.relational_query import ( _locate_value, _ValueOrigin, @@ -18,7 +20,7 @@ get_element_annotators, join_spatialelement_table, ) -from spatialdata.models.models import TableModel +from spatialdata.models import Labels2DModel, PointsModel, ShapesModel, TableModel from spatialdata.testing import assert_anndata_equal, assert_geodataframe_equal @@ -1468,3 +1470,47 @@ def test_filter_by_table_query_complex_combination(complex_sdata): assert ("circles", idx) in table_instance_ids for idx in result["poly"].index: assert ("poly", idx) in table_instance_ids + + +@pytest.mark.parametrize("element_type", ["shapes", "points", "labels"]) +@pytest.mark.parametrize("how", ["left", "left_exclusive", "inner", "right", "right_exclusive"]) +@pytest.mark.parametrize("match_rows", ["no", "left", "right"]) +def test_join_element_and_table_without_shared_instances( + element_type: str, how: str, match_rows: str, request: pytest.FixtureRequest +) -> None: + if element_type == "labels" and how == "inner": + # documented as unsupported: inner joins don't collect table rows for labels, so the table is None + request.applymarker(pytest.mark.xfail(reason="inner join returns no table for labels", strict=True)) + # The element has instances 1 and 2, the table annotates instances 10 and 11 of it: nothing matches. + if element_type == "shapes": + element = ShapesModel.parse( + GeoDataFrame({"geometry": [Point(0, 0), Point(1, 1)], "radius": [1.0, 1.0]}, index=[1, 2]) + ) + elif element_type == "points": + element = PointsModel.parse(pd.DataFrame({"x": [0.0, 1.0], "y": [0.0, 1.0]}, index=[1, 2])) + else: + labels = np.zeros((4, 4), dtype=np.int64) + labels[0, 0], labels[3, 3] = 1, 2 + element = Labels2DModel.parse(labels, dims=("y", "x")) + obs = pd.DataFrame({"region": pd.Categorical(["element"] * 2), "instance_id": [10, 11]}) + table = TableModel.parse( + AnnData(X=np.zeros((2, 1)), obs=obs), region="element", region_key="region", instance_key="instance_id" + ) + sdata = SpatialData(**{element_type: {"element": element}}, tables={"table": table}) + + # labels are only filtered by inner and right joins when asked to + kwargs = {"filter_label_pixels": True} if element_type == "labels" else {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) # match_rows not supported for some joins + elements, joined = join_spatialelement_table( + sdata=sdata, spatial_element_names="element", table_name="table", how=how, match_rows=match_rows, **kwargs + ) + joined_element = elements["element"] + n_element_instances = None if joined_element is None else len(get_element_instances(joined_element)) + + expected_element_instances = {"left": 2, "left_exclusive": 2, "inner": 0, "right": 0, "right_exclusive": None}[how] + expected_table_rows = {"left": 0, "left_exclusive": None, "inner": 0, "right": 2, "right_exclusive": 2}[how] + assert n_element_instances == expected_element_instances + assert (None if joined is None else joined.n_obs) == expected_table_rows + if joined is not None: + TableModel.validate(joined)