Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b28556f
Experimental spatial index of points (RFC 3): out-of-core builder, re…
LucaMarconato Nov 16, 2026
5c45370
Experimental spatial index of shapes (RFC 4), shapes format 0.4, real…
LucaMarconato Nov 16, 2026
8754acf
Points format 0.3 (Parquet) and 0.3-experimental (Zarr); opt-in real-…
LucaMarconato Nov 16, 2026
e1ef878
Parquet: per-row-group compact dictionaries, global categories stored…
LucaMarconato Nov 16, 2026
9779d4d
Zarr: the categories of the feature index are the enum_values of the …
LucaMarconato Nov 16, 2026
f4329b0
Real-data benchmark: the no-index baseline reads the data and subsamples
LucaMarconato Nov 16, 2026
0b22609
Parquet: store part_offsets (first row of each part file) and open on…
LucaMarconato Nov 16, 2026
a30276a
Create the element-type group (points/, shapes/) when writing an inde…
LucaMarconato Nov 16, 2026
51e918a
Shapes index: match the table through another obs column (Xenium/Ater…
LucaMarconato Nov 16, 2026
f7ee7f9
Example notebooks (executed on the Atera kidney dataset of spatialdat…
LucaMarconato Nov 16, 2026
1f2c2e4
Real-data benchmark of the shapes index and the CSC layer (RFC 4)
LucaMarconato Nov 16, 2026
f01fc44
PointsSpatialIndex.estimate_count: points expected in a box from the …
LucaMarconato Nov 16, 2026
d3a3e81
Apply the agreed RFC 3/4 changes to the implementation
LucaMarconato Nov 19, 2026
5bb474d
estimate_count: weight tiles by their part inside the data extent (co…
LucaMarconato Nov 19, 2026
a978b53
Default p of 16 bits: stop the merge rule at the coarsest level 16 bi…
LucaMarconato Nov 19, 2026
d29b412
Read indexes from remote stores (fsspec URLs, e.g. s3://) for points …
LucaMarconato Nov 19, 2026
a29d791
Remote Parquet: uncached byte-range reads of footers and column chunks
LucaMarconato Nov 19, 2026
3b61f32
Fix the band of p equal to a fraction P(l): level l holds p < P(l), s…
LucaMarconato Nov 19, 2026
5b225ed
Real-data test: current stores only, 3-D grids; notebooks: rebuild el…
LucaMarconato Nov 19, 2026
7e1e071
Example notebooks executed on the rebuilt Atera kidney store (tiled p…
LucaMarconato Nov 19, 2026
7dd04d9
Notebooks: data on /Volumes/Scratch
LucaMarconato Nov 19, 2026
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
67 changes: 67 additions & 0 deletions benchmarks/spatial_index_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""asv benchmarks of the spatial index of points (RFC 3) on synthetic data.

For real data (10x Atera) see ``spatial_index_real_data.py``.
"""

import tempfile
from pathlib import Path

import numpy as np
import pandas as pd

import spatialdata as sd
from spatialdata._io.spatial_index import PointsSpatialIndex, write_points_with_spatial_index
from spatialdata.models import PointsModel


def _points(n: int, n_genes: int = 500, seed: int = 0) -> pd.DataFrame:
rng = np.random.default_rng(seed)
xy = np.vstack([rng.normal([3000, 2000], 600, size=(n // 2, 2)), rng.uniform(0, 10_000, size=(n - n // 2, 2))])
w = 1.0 / np.arange(1, n_genes + 1) ** 1.2
genes = rng.choice(n_genes, size=n, p=w / w.sum())
return pd.DataFrame(
{
"x": xy[:, 0].astype(np.float32),
"y": xy[:, 1].astype(np.float32),
"gene": pd.Categorical.from_codes(genes, [f"g{i}" for i in range(n_genes)]),
}
)


class TimeSpatialIndexQueries:
params = (["none", "parquet", "zarr"], ["small box", "large box budget", "rare gene", "common gene in box"])
param_names = ["storage", "query"]
timeout = 600

def setup_cache(self) -> str:
tmp = Path(tempfile.mkdtemp())
df = _points(5_000_000)
pts = PointsModel.parse(df, feature_key="gene", npartitions=8)
sd.SpatialData(points={"plain": pts}).write(tmp / "data.zarr")
for storage in ("parquet", "zarr"):
write_points_with_spatial_index(pts, tmp / "data.zarr" / "points" / storage, storage=storage)
return str(tmp / "data.zarr")

def setup(self, path: str, storage: str, query: str) -> None:
self.path = Path(path)
self.storage = storage
self.index = None if storage == "none" else PointsSpatialIndex(self.path / "points" / storage)

def time_query(self, path: str, storage: str, query: str) -> None:
box = {"small box": (2900, 3100), "large box budget": (0, 6000), "common gene in box": (2500, 3500)}
features = {"rare gene": ["g400"], "common gene in box": ["g0"]}.get(query)
lo_hi = box.get(query)
if self.index is None:
import dask.dataframe as dd

filters = []
if lo_hi is not None:
lo, hi = lo_hi
filters += [("x", ">=", lo), ("x", "<=", hi), ("y", ">=", lo), ("y", "<=", hi)]
if features:
filters += [("gene", "in", features)]
len(dd.read_parquet(self.path / "points" / "plain" / "points.parquet", filters=filters or None))
return
lo, hi = (None, None) if lo_hi is None else ([lo_hi[0]] * 2, [lo_hi[1]] * 2)
budget = 0.02 if query == "large box budget" else None
self.index.query(lo, hi, budget=budget, features=features, columns=["x", "y", "gene"])
163 changes: 163 additions & 0 deletions benchmarks/spatial_index_real_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Benchmark the spatial index of points (RFC 3) on real data, against reading without an index.

Run from the repository root:

python benchmarks/spatial_index_real_data.py --original <store.zarr> --element transcripts \
--indexed <indexed_store.zarr> [<indexed_store.zarr> ...] --out results.json

Each indexed store holds the same points written with ``write_points_with_spatial_index`` (Parquet or Zarr storage,
dense or sparse feature index). Each query is run ``--repeats`` times with a fresh reader (the OS page cache is warm
after the first run; the first run is reported separately as ``first``).
"""

from __future__ import annotations

import argparse
import json
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any

import dask.dataframe as dd
import numpy as np
import pandas as pd


def _queries(md: Any, categories: list[str], counts: np.ndarray) -> list[dict[str, Any]]:
lv0 = md.levels[0]
origin = np.asarray(lv0.origin)
extent = np.asarray(lv0.tile_size) * np.asarray(lv0.grid_shape)
center = origin + extent / 2
order = np.argsort(counts)
nonzero = order[counts[order] > 0]
rare = categories[int(nonzero[len(nonzero) // 10])] # 10th percentile of the expressed features
common = [categories[int(i)] for i in order[-3:]]
medium = categories[int(nonzero[len(nonzero) // 2])]

def box(size: float) -> tuple[np.ndarray, np.ndarray]:
return center - size / 2, center + size / 2

return [
{"name": "small box 200 um, all features, level 0", "box": box(200.0)},
{"name": "medium box 1000 um, all features, level 0", "box": box(1000.0)},
{"name": "medium box 1000 um, budget 100k points", "box": box(1000.0), "max_points": 100_000},
{"name": "whole dataset, budget 100k points", "box": None, "max_points": 100_000},
{"name": f"whole dataset, rare feature {rare}", "box": None, "features": [rare]},
{"name": f"whole dataset, median feature {medium}", "box": None, "features": [medium]},
{"name": "medium box 1000 um, 3 common features", "box": box(1000.0), "features": common},
{"name": "small box 200 um, 3 common features", "box": box(200.0), "features": common},
]


def _baseline(original: Path, element: str, feature_key: str) -> Callable[[dict[str, Any]], int]:
"""Without an index: dask read_parquet of the element, with filters on the box and the features."""
path = original / "points" / element / "points.parquet"

def run(q: dict[str, Any]) -> int:
filters = []
if q.get("box") is not None:
lo, hi = q["box"]
filters += [("x", ">=", lo[0]), ("x", "<=", hi[0]), ("y", ">=", lo[1]), ("y", "<=", hi[1])]
if q.get("features"):
filters += [(feature_key, "in", list(q["features"]))]
# read the data (len() alone would be answered from the Parquet footers)
pdf = dd.read_parquet(path, columns=["x", "y", feature_key], filters=filters or None).compute()
if q.get("box") is not None: # filters prune row groups; rows still need the exact filter
lo, hi = q["box"]
pdf = pdf[(pdf.x >= lo[0]) & (pdf.x <= hi[0]) & (pdf.y >= lo[1]) & (pdf.y <= hi[1])]
if q.get("max_points") and len(pdf) > q["max_points"]:
# without an index the client reads everything in view and then subsamples
pdf = pdf.sample(q["max_points"], random_state=0)
return len(pdf)

return run


def _indexed(path: Path, element: str, use_feature_index: bool) -> Callable[[dict[str, Any]], int]:
from spatialdata._io.spatial_index import PointsSpatialIndex

def run(q: dict[str, Any]) -> int:
index = PointsSpatialIndex(path / "points" / element)
md = index.metadata
fk = md.feature_keys[0] if md.feature_keys else None
lo, hi = q["box"] if q.get("box") is not None else (None, None)
budget = None
if q.get("max_points"):
s, e = index.tile_ranges(lo, hi, 0)
n_in_view = int(np.sum(e - s))
budget = min(1.0, q["max_points"] / max(n_in_view, 1))
if q.get("features") and use_feature_index and fk is None:
raise ValueError("no feature index")
df = index.query(
lo,
hi,
budget=budget,
features=q.get("features"),
feature_key=fk,
columns=["x", "y", fk] if fk else ["x", "y"],
use_feature_index=bool(q.get("features")) and use_feature_index,
)
table = index.table(fk if (q.get("features") and use_feature_index) else None)
run.last_bytes = table.bytes_read # type: ignore[attr-defined]
run.last_row_groups = table.row_groups_read # type: ignore[attr-defined]
return len(df)

return run


def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--original", type=Path, required=True)
ap.add_argument("--element", default="transcripts")
ap.add_argument("--indexed", type=Path, nargs="+", required=True)
ap.add_argument("--repeats", type=int, default=3)
ap.add_argument("--out", type=Path, default=Path("spatial_index_benchmark.json"))
args = ap.parse_args()

from spatialdata._io.spatial_index import PointsSpatialIndex

ref = PointsSpatialIndex(args.indexed[0] / "points" / args.element)
fk = ref.metadata.feature_keys[0]
cats = ref.categories(fk)
# number of points per feature, from the whole-dataset ranges of the feature index
s, e = ref.feature_ranges(fk, list(range(len(cats))), None, None, 0)
counts = np.zeros(len(cats), dtype=np.int64)
# feature_ranges returns one range per (band, feature) in band order, features sorted
n_b = ref.metadata.n_levels
counts = (e - s).reshape(n_b, len(cats)).sum(axis=0)
queries = _queries(ref.metadata, cats, counts)

methods: dict[str, Callable[[dict[str, Any]], int]] = {"no index (dask + filters)": _baseline(args.original, args.element, fk)}
for p in args.indexed:
methods[f"{p.name}: tile-major"] = _indexed(p, args.element, use_feature_index=False)
methods[f"{p.name}: feature-major"] = _indexed(p, args.element, use_feature_index=True)

results = []
for q in queries:
for name, fn in methods.items():
if name.endswith("feature-major") and not q.get("features"):
continue
times = []
n = -1
for _ in range(args.repeats):
t0 = time.perf_counter()
n = fn(q)
times.append(time.perf_counter() - t0)
row = {
"query": q["name"],
"method": name,
"n_points": n,
"first_s": times[0],
"median_s": float(np.median(times)),
"bytes_read": getattr(fn, "last_bytes", None),
"row_groups_read": getattr(fn, "last_row_groups", None),
}
print(json.dumps(row), flush=True)
results.append(row)
args.out.write_text(json.dumps(results, indent=1))
print(pd.DataFrame(results).to_string())


if __name__ == "__main__":
main()
98 changes: 98 additions & 0 deletions benchmarks/spatial_index_shapes_real_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Benchmark the spatial index of shapes and the CSC layer (RFC 4) on real data.

python benchmarks/spatial_index_shapes_real_data.py --original <store.zarr> --indexed <store.zarr> \
--shapes cell_boundaries --table table --gene C7
"""

from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import numpy as np
import pandas as pd


def main() -> None:
import anndata
import geopandas as gpd
import shapely
import zarr

from spatialdata._io.spatial_index import ShapesSpatialIndex

ap = argparse.ArgumentParser()
ap.add_argument("--original", type=Path, required=True)
ap.add_argument("--indexed", type=Path, required=True)
ap.add_argument("--shapes", default="cell_boundaries")
ap.add_argument("--table", default="table")
ap.add_argument("--gene", required=True)
ap.add_argument("--repeats", type=int, default=3)
ap.add_argument("--out", type=Path, default=Path("spatial_index_shapes_benchmark.json"))
args = ap.parse_args()

index = ShapesSpatialIndex(args.indexed / "shapes" / args.shapes, args.indexed / "tables" / args.table)
lv0 = index.metadata.levels[0]
center = np.asarray(lv0.origin) + np.asarray(lv0.tile_size) * np.asarray(lv0.grid_shape) / 2
original_shapes = args.original / "shapes" / args.shapes / "shapes.parquet"
j = index.var_names.index(args.gene)

def no_index_box(size: float) -> int:
lo, hi = center - size / 2, center + size / 2
# WKB without a bbox column: no row-group pruning is possible, read everything and filter
gdf = gpd.read_parquet(original_shapes)
return int(gdf.intersects(shapely.box(*lo, *hi)).sum())

def index_box(size: float) -> int:
lo, hi = center - size / 2, center + size / 2
return len(ShapesSpatialIndex(index.path, index.table_path).query(lo, hi))

def gene_csr_no_index() -> int:
# without a CSC copy: one gene means reading the whole CSR matrix
X = anndata.io.read_elem(zarr.open_group(args.original / "tables" / args.table, mode="r")["X"])
return int((X[:, j] > 0).sum())

def gene_csc_existing() -> int:
g = zarr.open_group(args.original / "tables" / args.table, mode="r")
if "layers" not in g or "csc_counts" not in g["layers"]:
return -1
m = g["layers"]["csc_counts"]
a, b = (int(v) for v in m["indptr"][j : j + 2])
return int((m["data"][a:b] > 0).sum())

def gene_csc_index() -> int:
return int((index.gene_values(args.gene) > 0).sum())

def gene_in_view(size: float) -> int:
lo, hi = center - size / 2, center + size / 2
cells = index.query(lo, hi)
return int((index.gene_values(args.gene, cells["__row__"].to_numpy()) > 0).sum())

cases = {
"box 100 um: no index (read all + filter)": lambda: no_index_box(100.0),
"box 100 um: index": lambda: index_box(100.0),
"box 1 mm: no index (read all + filter)": lambda: no_index_box(1000.0),
"box 1 mm: index": lambda: index_box(1000.0),
f"gene {args.gene}, all cells: CSR X (no CSC)": gene_csr_no_index,
f"gene {args.gene}, all cells: spatialdata-db csc_counts": gene_csc_existing,
f"gene {args.gene}, all cells: X_csc": gene_csc_index,
f"gene {args.gene}, cells in 300 um box: index + X_csc": lambda: gene_in_view(300.0),
}
results = []
for name, fn in cases.items():
times, n = [], -1
for _ in range(args.repeats if "CSR X" not in name else 1):
t0 = time.perf_counter()
n = fn()
times.append(time.perf_counter() - t0)
row = {"case": name, "n": n, "first_s": times[0], "median_s": float(np.median(times))}
print(json.dumps(row), flush=True)
results.append(row)
args.out.write_text(json.dumps(results, indent=1))
print(pd.DataFrame(results).to_string())


if __name__ == "__main__":
main()
Loading
Loading