diff --git a/benchmarks/spatialdata_benchmark.py b/benchmarks/spatialdata_benchmark.py index 2dd453fc4..a31124c93 100644 --- a/benchmarks/spatialdata_benchmark.py +++ b/benchmarks/spatialdata_benchmark.py @@ -109,3 +109,65 @@ def time_bbquery_scale_transform(self, n_repeats: int) -> None: max_coordinate=[x_max, y_max], target_coordinate_system="global", ) + + +class TimeJoins: + """Time `join_spatialelement_table` for an element whose instances are all annotated by the table. + + The table rows are in a different order than the element rows, so `match_rows` has to reorder. The cases cover + the element masking and row matching code. For points, the joined element is computed, since masking a dask frame + is lazy. + """ + + params = [ + "shapes left/left", + "shapes inner/left", + "shapes inner/right", + "shapes right/right", + "points inner/no", + "points right/right", + ] + param_names = ["element_type how/match_rows"] + n_instances = 200_000 + number = 1 + repeat = 5 + rounds = 1 + warmup_time = 0 + + def setup(self, case: str) -> None: + import geopandas as gpd + import pandas as pd + from anndata import AnnData + + from spatialdata.models import PointsModel, ShapesModel, TableModel + + element_type = case.split()[0] + n = self.n_instances + rng = np.random.default_rng(0) + coordinates = rng.random((n, 2)) + index = pd.Index(rng.permutation(n)) + if element_type == "shapes": + element = ShapesModel.parse( + gpd.GeoDataFrame( + {"radius": np.ones(n)}, + geometry=gpd.points_from_xy(coordinates[:, 0], coordinates[:, 1]), + index=index, + ) + ) + else: + element = PointsModel.parse(pd.DataFrame(coordinates, columns=["x", "y"], index=index)) + obs = pd.DataFrame({"region": pd.Categorical(["element"] * n), "instance_id": rng.permutation(n)}) + table = TableModel.parse(AnnData(obs=obs), region="element", region_key="region", instance_key="instance_id") + self.sdata = sd.SpatialData(**{element_type: {"element": element}}, tables={"table": table}) + + def teardown(self, *_args: object) -> None: + del self.sdata + + def time_join(self, case: str) -> None: + element_type, join = case.split() + how, match_rows = join.split("/") + elements, _ = sd.join_spatialelement_table( + sdata=self.sdata, spatial_element_names="element", table_name="table", how=how, match_rows=match_rows + ) + if element_type == "points": + elements["element"].compute() diff --git a/src/spatialdata/_core/query/relational_query.py b/src/spatialdata/_core/query/relational_query.py index af90b7d02..747ecabcf 100644 --- a/src/spatialdata/_core/query/relational_query.py +++ b/src/spatialdata/_core/query/relational_query.py @@ -1,6 +1,5 @@ from __future__ import annotations -import math import warnings from collections import defaultdict from dataclasses import dataclass @@ -234,29 +233,20 @@ def _get_masked_element( """ mask = np.isin(table_instance_key_column.to_numpy(), element_indices) masked_table_instance_key_column = table_instance_key_column[mask] - 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"] 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): - mask = left_index.isin(mask_values) - mask_values = left_index[mask] - else: - mask_values = left_index - elif mask_values is not None: + mask_values: NDArray[Any] | pd.Index = masked_table_instance_key_column.to_numpy() + if match_rows in ["left", "right"]: + left_index, right_index = _match_rows(table_instance_key_column, mask, element_indices, match_rows) + mask_values = left_index[right_index.notna()] # drop element rows without a table row + else: order_mask = np.isin(element_indices, mask_values) mask_values = np.asarray(element_indices)[order_mask] if isinstance(element, DaskDataFrame): - masked: SpatialElement = element.map_partitions( - lambda df: df.loc[mask_values if mask_values is not None else []], meta=element - ) + masked: SpatialElement = element.map_partitions(lambda df: df.loc[mask_values], meta=element) return masked if not isinstance(element, GeoDataFrame): raise TypeError(f"Only points and shapes elements can be masked, got {type(element).__name__}.") - masked_shapes: GeoDataFrame = element.loc[mask_values if mask_values is not None else [], :] + masked_shapes: GeoDataFrame = element.loc[mask_values, :] return masked_shapes @@ -564,19 +554,7 @@ 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"] - - # With labels it can be that index 0 is NaN - if isinstance(index_left.iloc[0], float) and math.isnan(index_left.iloc[0]): - index_left = index_left.iloc[1:] - - if isinstance(index_right.iloc[0], float) and math.isnan(index_right.iloc[0]): - index_right = index_right.iloc[1:] - - return pd.Index(index_left), pd.Index(index_right) + return pd.Index(merged_df["index_left"]), pd.Index(merged_df["index_right"]) class JoinTypes(Enum):