From f2864e3f1fdcd9c75de8a3bd05de69270f0ccdf9 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Mon, 9 Nov 2026 16:15:26 +0000 Subject: [PATCH 1/6] RFC 3: say tile-major order throughout; add the columns figure Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ezPhPHi47e4jw4nHjqtBK --- rfcs/0003-tiled-points.md | 221 +++++++++++++++++++++++++++----------- rfcs/img/0003-columns.svg | 134 +++++++++++++++++++++++ rfcs/img/0003-orders.svg | 6 +- 3 files changed, 294 insertions(+), 67 deletions(-) create mode 100644 rfcs/img/0003-columns.svg diff --git a/rfcs/0003-tiled-points.md b/rfcs/0003-tiled-points.md index 076d776..7e4e252 100644 --- a/rfcs/0003-tiled-points.md +++ b/rfcs/0003-tiled-points.md @@ -12,7 +12,7 @@ created: 2026-09-17 ## Abstract Specification for spatially indexing points, enabling optional multiscale subsampled levels, spatially chunked storage: a regular -2-D or 3-D grid of tiles, with the points stored both in tile order and in feature-major order. This enables viewers to load only the points in view, or only those of the genes shown; zoomed out, they load a +2-D or 3-D grid of tiles, with the points stored both in tile-major order and in feature-major order. This enables viewers to load only the points in view, or only those of the genes shown; zoomed out, they load a density-preserving sample. Shapes are in [RFC 4](0004-tiled-shapes.md). ## Description @@ -23,7 +23,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be interpreted a ### Scope -- In scope: points, 2-D and 3-D; spatial indexing via chunking and sorting; tile order and feature-major order; sampled levels. +- In scope: points, 2-D and 3-D; spatial indexing via chunking and sorting; tile-major order and feature-major order; sampled levels. - Out of scope: shapes ([RFC 4](0004-tiled-shapes.md)), the matrix of a table annotating the shapes and its sparse storage (CSR/CSC, RFC 4), aggregation to cells or bins (square/hexagonal), ordering inside tiles (Morton, Hilbert), ordering of the tiles other than C order (e.g. Morton). ## Data model @@ -216,12 +216,12 @@ With $N = \prod_a n_a$ tiles, $0 \le k < N$. One could instead order the tiles by Morton code (Z-order), which keeps tiles that are close in space close in the order. This is not done in this version and is left for future versions. -### Tile order and feature-major order +### Tile-major order and feature-major order At each level, the points are written in two orders, each a copy of the points with all their columns: -- tile order, required: sorted by tile id, with the order inside a tile unspecified; +- tile-major order, required: sorted by tile id, with the order inside a tile unspecified; - feature-major order, written by default (a writer may opt out): sorted by feature, then by tile id. @@ -229,21 +229,21 @@ The feature is a categorical column chosen when writing and named in the metadat transcriptomics, the gene id. A writer may choose several feature columns, for instance the gene id and the cell type, each with its own feature-major copy. It is recommended to choose only one, the column used most often to select points, for the best performance at the lowest storage cost. Any -other column can still be used to select points, from the tile-order copy: faster than without a +other column can still be used to select points, from the tile-major copy: faster than without a spatial index, with some performance penalty compared with a feature-major copy. -Only the tile order is required: a dataset may have no feature-major copy at all. A client looking +Only the tile-major order is required: a dataset may have no feature-major copy at all. A client looking for the points of a feature looks for a feature-major copy of the corresponding column and, if there -is none, falls back to the tile order. +is none, falls back to the tile-major order. -:::{dropdown} Falling back to the tile order: what changes at sampled levels +:::{dropdown} Falling back to the tile-major order: what changes at sampled levels The two orders are sampled differently (see [Sampling](#sampling)). The feature-major order -preserves densities within each feature. The tile order preserves only the global density: it +preserves densities within each feature. The tile-major order preserves only the global density: it treats all the points as equal, whatever their category. At level 0 the two orders hold all the points of every tile, so they are fully equivalent, except -for performance. At sampled levels they differ: the tile order keeps a feature with the same +for performance. At sampled levels they differ: the tile-major order keeps a feature with the same fraction as all the others, so a client that falls back to it is less useful for showing rare categories, which may keep very few points or none. @@ -254,7 +254,7 @@ a better alternative to sampling. It is out of scope for this RFC. The two orders answer two different questions with a contiguous range of rows: -- Tile order: *which points are in this region?* The points of a tile are one row range, whatever +- Tile-major order: *which points are in this region?* The points of a tile are one row range, whatever their gene. A client showing the region reads the tiles in view. - Feature-major order: *where are the points of this gene?* The points of a gene are one row range, and inside it the points of each tile are again one range, sorted by tile id. A client showing a @@ -267,10 +267,10 @@ the points. Per-tile statistics (e.g. which features a tile contains, or how man could let a client skip tiles without the feature it shows and improve performance; they are out of scope for this RFC. :::{figure} img/0003-orders.svg -:alt: Two levels. Level 0: twelve points of genes A (6), B (4) and C (2) on a 2 × 2 grid, stored grouped by tile and grouped by gene and then by tile. Level 1, a single tile: the tile-order copy keeps 4 points (P = 1/3); the feature-major copy keeps 4 points of A (P = 2/3), 2 of B (P = 2/3) and both points of C (P = 1). +:alt: Two levels. Level 0: twelve points of genes A (6), B (4) and C (2) on a 2 × 2 grid, stored grouped by tile and grouped by gene and then by tile. Level 1, a single tile: the tile-major copy keeps 4 points (P = 1/3); the feature-major copy keeps 4 points of A (P = 2/3), 2 of B (P = 2/3) and both points of C (P = 1). -The points of two levels, each in the two orders. In tile order each tile is one row range; in -feature-major order each gene is one row range, sorted by tile inside it. At level 1 the tile-order +The points of two levels, each in the two orders. In tile-major order each tile is one row range; in +feature-major order each gene is one row range, sorted by tile inside it. At level 1 the tile-major copy is sampled over all the points, with one fraction $P$, the feature-major copy per gene, with one fraction per gene: the rare gene C keeps all its points. How the fractions $P$ are chosen is explained in [Sampling](#sampling). @@ -286,9 +286,9 @@ probability, chosen so that the densest tile holds about `limit` points. Dense r than sparse ones. Each level is sampled from the level below it, which makes the levels nested. The two copies of the points (see -[Tile order and feature-major order](#tile-order-and-feature-major-order)) are sampled differently: +[Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)) are sampled differently: -- Tile order: over all the points. At a level, every feature is kept with the same fraction $P^{(l)}$. +- Tile-major order: over all the points. At a level, every feature is kept with the same fraction $P^{(l)}$. - Feature-major order: per feature. Each feature $g$ is sampled on its own, with its own fraction $P_g^{(l)}$, so that the densest tile holds about `limit` points of $g$. A rare feature keeps all its points at coarse levels instead of vanishing; an abundant one is thinned. When the @@ -341,7 +341,7 @@ $1.14\,N$ in 3-D. The bound holds for each copy. The bound shows that the data does not grow much, even though the same point appears again at several levels: the sampled levels add at most a third of the points in 2-D. The storage is -dominated by the multiple copies (the tile order and the feature-major order), which double it and +dominated by the multiple copies (the tile-major order and the feature-major order), which double it and are generally affordable (see [Levels](#levels)). ::: @@ -349,7 +349,7 @@ are generally affordable (see [Levels](#levels)). #### Showing several features together At level 0 every fraction is 1 and both copies hold every point, so any view is exact, independently -of whether it is read from the tile order or from the feature-major order. The +of whether it is read from the tile-major order or from the feature-major order. The difference matters only when a client shows a sampled level ($l \ge 1$) of the feature-major copy. There, features are kept with different fractions, so showing several features together distorts their relative abundance. For example, if an abundant feature keeps $P_A^{(l)} = 1\%$ of its points @@ -421,13 +421,23 @@ The figure shows the edge cases: the hotspot, as in (b). A future extension could address this with an adaptive grid, if the community identifies it as a need. +> **TODO(Luca), placeholder:** what happens when a tile of level 0 holds more than `limit` points +> (tiles too large for the density, case (b), or a hotspot, case (d)). As specified, level 0 always +> holds all the points ($P^{(0)} = 1$, level 0 is never sampled), so it is `limit` that is not +> respected at level 0: such a tile holds more than `limit` points, and a client zoomed in loads +> all of them. `limit` only drives the sampling of the coarser levels ($p^{(l)} = \min(1, +> \texttt{limit} / c^{(l)})$ for $l \ge 1$), where it holds on average. Consequences to spell out +> here: in Zarr, padding every chunk to the largest tile is then no longer small and bounded (see +> [Points as a tall table](#points-as-a-tall-table)); in Parquet, the row group of such a tile is +> large. To be compared against an alternative design of the points storage. + ## Storage format The data model above can be implemented both in Parquet and in Zarr, and this RFC describes both. SpatialData already stores points in Parquet, so the Parquet format is to be interpreted as the -default. Whether the Zarr format replaces it or the two coexist will be determined from user +default, and the Zarr format as experimental. Whether the Zarr format replaces it or the two coexist will be determined from user feedback and real usage; Zarr would also be more flexible for 3-D shapes (meshes, see -[RFC 4](0004-tiled-shapes.md)). +[RFC 4](0004-tiled-shapes.md)) and closer to zarr-vectors (see [Related work](#related-work)). The format is self-contained: compatible with the way OME-NGFF stores coordinate systems, but usable on its own, even outside an OME-Zarr store, because its metadata is defined as a Zarr convention. @@ -436,28 +446,37 @@ metadata. ### Points as a tall table -In both formats, each copy of a level (tile order or feature-major order) is a tall table: one row -per point, one column per attribute. Each tile is stored in one logical unit, a row group in Parquet -(one row group per tile, as in Celldega) and a chunk in Zarr, and the units are grouped into files: the part files of a multi-file Parquet +In both formats, each copy of a level (tile-major order or feature-major order) is a tall table: one row +per point, one column per attribute. Each tile is stored in one logical unit, one row group per tile in Parquet +(as in Celldega) and one chunk per tile in Zarr, and the units are grouped into files: the part files of a multi-file Parquet dataset, and shards in Zarr. Zarr chunks are regular, so each tile's chunk is padded to the size of -the largest tile; this costs little, since the tiles hold similar numbers of points (see -[When the spatial index helps](#when-the-spatial-index-helps)). +the largest tile; this adds an overhead, small and bounded, since the tiles hold similar numbers of +points, at most about `limit` when the tile size is chosen as in +[When the spatial index helps](#when-the-spatial-index-helps). An alternative storage in Zarr would be a sparse tensor in which each entry is a point. It comes with other compromises and is left for possible future exploration. Another option would come if Zarr -allowed chunks of different sizes in an array (variable chunk grids have been proposed for Zarr): -each tile would then be one chunk of its own size, without padding. +allowed chunks of different sizes in an array (variable chunk grids have been proposed for Zarr), +or if the points were stored as a ragged array: each tile would then be one chunk of its own size, without +padding. ### Metadata -The metadata is a Zarr convention, `spatial_index`, in the attributes of the points element, next -to the existing ones. The levels follow the +Both formats store the metadata in the `zarr.json` of the Zarr group of the points element. In the +Zarr format the points are Zarr arrays inside that group; in the Parquet format they are Parquet +files inside that group (see [File layout](#file-layout)): + +```text +points// +├── zarr.json # the metadata, in both formats +└── … # the points: Zarr arrays, or Parquet files +``` + +The metadata is a Zarr convention, `spatial_index`, next to the existing attributes of the element. +The levels follow the [zarr-conventions `multiscales`](https://github.com/zarr-conventions/multiscales) convention: its `layout` lists the levels, and each level object carries the grid and the sampling of that level -under the key `spatial_index`, as the convention allows additional properties. Both formats use -this metadata, in the `zarr.json` of the element: - -> ⚠️ **Work in progress.** The specification is not reviewed after this point. +under the key `spatial_index`, as the convention allows additional properties: ```json { @@ -468,7 +487,10 @@ this metadata, in the `zarr.json` of the element: "schema_url": "https://raw.githubusercontent.com/zarr-conventions/multiscales/refs/tags/v0.1/schema.json", "spec_url": "https://github.com/zarr-conventions/multiscales/blob/v0.1/README.md" }, - {"name": "spatial_index", "uuid": "…", "schema_url": "…", "spec_url": "…"} + { + "name": "spatial_index", + "spec_url": "" + } ], "spatial_index": { "coordinate_system": "global", @@ -481,14 +503,24 @@ this metadata, in the `zarr.json` of the element: "layout": [ { "asset": "0", - "spatial_index": {"origin": [0.0, 0.0, 0.0], "tile_size": [100.0, 100.0, 10.0], "grid_shape": [120, 80, 3], "n_rows": 812345678} + "spatial_index": { + "origin": [0.0, 0.0, 0.0], + "tile_size": [100.0, 100.0, 10.0], + "grid_shape": [120, 80, 3], + "n_rows": 812345678 + } }, { "asset": "1", "derived_from": "0", "transform": {"scale": [2.0, 2.0, 2.0]}, - "spatial_index": {"origin": [0.0, 0.0, 0.0], "tile_size": [200.0, 200.0, 20.0], "grid_shape": [60, 40, 2], "n_rows": 203086419, - "sampling": {"limit": 10000, "P": 0.25, "P_feature": [1.0, 0.8, 0.25]}} + "spatial_index": { + "origin": [0.0, 0.0, 0.0], + "tile_size": [200.0, 200.0, 20.0], + "grid_shape": [60, 40, 2], + "n_rows": 203086419, + "sampling": {"limit": 10000, "P": 0.25, "P_feature": [1.0, 0.8, 0.25]} + } } ] } @@ -496,42 +528,67 @@ this metadata, in the `zarr.json` of the element: ``` The `transform` of a level gives, per axis, the factor by which its tiles are larger than those of -the level it is derived from: 2 along the merged axes, 1 along the others. `P` is the fraction -$P^{(l)}$ of the tile-order copy; `P_feature` lists the fractions $P_g^{(l)}$ of the feature-major -copy, one per feature, in the order of the feature categories. +the level it is derived from: 2 along the merged axes, 1 along the others. The `resampling_method` +MUST be `density_preserving`, the only sampling defined by this RFC (see [Sampling](#sampling)); the +`multiscales` convention itself allows any value. `P` is the fraction $P^{(l)}$ of the tile-major +copy; `P_feature` lists the fractions $P_g^{(l)}$ of the feature-major copy, one per feature, in the +order of the feature categories: it has as many entries as there are categories (see +[Columns](#columns)). -> **TODO(Luca):** register the `spatial_index` convention (uuid, schema and spec URLs); align the -> `asset` paths with the file layout of each format; follow up with the OME-Zarr community. +> **TODO(Luca):** register the `spatial_index` convention (its uuid and schema URL are omitted and +> its spec URL is blank for now); align the `asset` paths with the file layout of each format. ### File layout -Parquet (backward compatible: level 0 in spatial order sits where readers look today): +Parquet (backward compatible: level 0, tile-major, sits where readers look today): ```text points// ├── zarr.json # attrs incl. spatial_index -├── points.parquet/ # level 0, spatial order, part.0.parquet, part.1.parquet, … -├── index/0/tile_offsets # Zarr int64 array -├── feature/0/points.parquet/ # optional, level 0, feature order -├── index/0/feature_offsets -├── levels/1/points.parquet/ # optional, level 1, spatial order -├── index/1/tile_offsets -└── … +├── points.parquet/ # level 0, tile-major: part.0.parquet, part.1.parquet, … +├── offsets # Zarr int64 array, the tile index of points.parquet/ +├── levels/ # optional, the sampled levels, tile-major +│ ├── 1/ +│ │ ├── points.parquet/ +│ │ └── offsets +│ └── … +└── feature/ # optional, feature-major + ├── 0/ + │ ├── points.parquet/ + │ └── offsets # the feature index + ├── 1/ + │ ├── points.parquet/ + │ └── offsets + └── … ``` -Zarr (dataframe as 1-D arrays, `df:` convention): +Zarr (the points as a dataframe, see [Columns](#columns)): ```text points// ├── zarr.json # attrs incl. spatial_index -├── 0/ -│ ├── spatial/{x,y,z,gene,…} # 1-D arrays, same length -│ ├── spatial/tile_offsets -│ ├── feature/{x,y,z,gene,…} # optional -│ └── feature/feature_offsets -└── 1/ … +├── 0/ # level 0 +│ ├── spatial/ # tile-major +│ │ ├── points/ # df: convention +│ │ │ ├── columns # ["x", "y", "z", "gene", …] +│ │ │ ├── column_0 # x +│ │ │ ├── column_1 # y +│ │ │ ├── column_2 # z +│ │ │ ├── column_3/ # gene, enum: convention +│ │ │ │ ├── codes +│ │ │ │ └── enum_values +│ │ │ └── … # the other columns +│ │ └── offsets # the tile index +│ └── feature/ # optional, feature-major +│ ├── points/ +│ └── offsets # the feature index +└── 1/ # level 1, same layout + └── … ``` +The `offsets` sit next to the dataframe, not inside it: the `df:` convention requires all the +members of the group to be columns of the same length. + > **TODO(Luca):** pick one layout per format, or prototype both (proposal 4.3). Where the offsets > live in the Parquet case (Zarr arrays as above, Parquet key-value metadata, or a sidecar Parquet). @@ -539,14 +596,44 @@ points// - `x`, `y`, `z`: float32, absolute, in the element's coordinate system. (Spacing of float32 at 10 cm in µm units is about 8 nm, well below localization error.) -- Feature: integer codes with the category list stored once (dictionary / categorical). +- Feature: integer codes with the category list stored once. In Zarr, the column follows the + [`enum:` convention](https://github.com/scverse/zarr-convention-enum): the arrays `codes` and + `enum_values`, the categories; the number of features is the length of `enum_values`. In + Parquet, a dictionary-encoded column. - Any other columns, unchanged. +In Zarr, the points of each copy of a level are a dataframe following the +[`df:` convention](https://github.com/scverse/zarr-convention-dataframe): one 1-D array, or a group +read as one, such as an `enum:` column, per column, all of the same length. + +> **TODO(Luca):** in Parquet, the dictionary is stored per row group, so the list of categories, +> which gives the order of `P_feature`, is only known after reading every row group; store it in the +> metadata? + +#### Order of the columns + +Within the storage unit of a tile, Parquet stores the values column by column: a row group holds +the values of the first column, then those of the second, and so on, in the order of the schema. +The coordinate columns SHOULD come first and next to each other, in the order of `axes`, followed by +the feature column(s), then by the other columns. A client reading the coordinates and the feature +of a tile then reads one contiguous byte range instead of one per column. + +In Zarr, each column is an array of its own, and chunk $k$ of each array holds tile $k$: a client +reads a tile with one request per column, whatever the order of the columns. The coordinate and +feature columns SHOULD still come first, in the same order as in Parquet. + +:::{figure} img/0003-columns.svg +:alt: A tall table of three columns x, y, z (blue, red, green) and three tiles of 4, 2 and 3 rows. In Parquet each tile is a row group holding all x values, then all y, then all z, in one byte range. In Zarr each column is an array of its own, column_0 to column_2, and tile 0 is chunk c/0 of each of them, padded to 4 rows. + +The bytes of three tiles in Parquet and in Zarr. Dashed cells are the padding of the regular Zarr +chunks. +::: + ### Tile index -To find the points of a tile, a reader uses the tile index of the tile-order copy of the level. Since +To find the points of a tile, a reader uses the tile index of the tile-major copy of the level. Since the rows are sorted by tile id, the points of each tile are consecutive rows. The index records where -each tile starts: an integer array `tile_offsets` ($O$, int64) with one entry per tile plus one, for +each tile starts: an integer array `offsets` ($O$, int64) with one entry per tile plus one, for the $N$ tiles of the level. The points of tile $k$ are the rows $$ @@ -562,21 +649,21 @@ column, whose first $O_{k+1} - O_k$ entries are the points and the rest padding. The feature-major copy of each level has: ```text -feature_offsets: int64[n_features + 1] -rows of feature g = [feature_offsets[g], feature_offsets[g + 1]) +offsets: int64[n_features + 1] +rows of feature g = [offsets[g], offsets[g + 1]) rows of feature g, tile k = [feature_tile_offsets[g, k], feature_tile_offsets[g, k + 1]) # optional ``` > **TODO(Luca):** Ilan suggests writing both orders by default, configurable; the proposal said > "recommended but optional". Pending his answer on the Google Doc comment (transcripts or cell > matrix?). Also: is `feature_tile_offsets` (n_features × n_tiles, can be large) worth having, or is -> `feature_offsets` enough? +> `offsets` enough? ### Reading ```python for k in tiles_intersecting(box): # tile ids, see "Tiles ordering" - yield rows(tile_offsets[k], tile_offsets[k + 1]) + yield rows(offsets[k], offsets[k + 1]) # zoomed out: choose the finest level whose expected rows in view ≤ budget ``` @@ -605,6 +692,12 @@ Considered and not chosen: - Image-pixel grid: SpatialData has no pixel space, and points can exist without an image. - Row groups by formula only: ties the index to Parquet. - Tile-relative float32 or uint16 coordinates: can come later as a codec without changing the type. +- Zarr, one 2-D array with the columns first, chunked by tile: a chunk would hold the columns of a + tile column by column, as a Parquet row group, in one request. But a Zarr array has a single data + type, and such an array is not a dataframe; the `df:` convention is used instead. +- zarr-vectors as is: its metadata is a set of top-level attributes with its own version, not a Zarr + convention. This specification is meant to be a self-contained Zarr convention, usable on its own + or next to other conventions (see [Storage format](#storage-format)). ## Implementation diff --git a/rfcs/img/0003-columns.svg b/rfcs/img/0003-columns.svg new file mode 100644 index 0000000..3f3064a --- /dev/null +++ b/rfcs/img/0003-columns.svg @@ -0,0 +1,134 @@ + +Columns of a tile in Parquet and in Zarr +tall table +x +y +z + + + + + + + + + + + + + +tile 0 + + + + + + + +tile 1 + + + + + + + + + + +tile 2 +Parquet: points.parquet/part.0.parquet + + + + + + + + + + + + + +row group 0 + + + + + + + +row group 1 + + + + + + + + + + +row group 2 +a tile is one byte range, column by column: x, then y, then z +Zarr, df: convention: one 1-D array per column +column_0 (x) + + + + + +c/0 + + + + + +c/1 + + + + + +c/2 +column_1 (y) + + + + + +c/0 + + + + + +c/1 + + + + + +c/2 +column_2 (z) + + + + + +c/0 + + + + + +c/1 + + + + + +c/2 +tile 0 (dashed) is chunk c/0 of each array: one request per column + diff --git a/rfcs/img/0003-orders.svg b/rfcs/img/0003-orders.svg index 2b94f76..e02a3cf 100644 --- a/rfcs/img/0003-orders.svg +++ b/rfcs/img/0003-orders.svg @@ -1,4 +1,4 @@ - + The two orders of the points at two levels level 0: 2 × 2 tiles @@ -21,7 +21,7 @@ B B A -tile order: rows sorted by tile id +tile-major order: rows sorted by tile id A 0 @@ -121,7 +121,7 @@ A B faded: only in the feature-major copy -tile order: rows sorted by tile id, P = 1/3 +tile-major order: rows sorted by tile id, P = 1/3 A 0 From 66f6234c319f670c6467517ef8f4483d5bc0ae10 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Mon, 16 Nov 2026 20:39:28 +0100 Subject: [PATCH 2/6] RFC 3: revised draft of tiled and multiscale points - Data model rebuilt on tiles, then a random value p per point that defines bands; levels are unions of bands. Default rates follow the ratio of tile volumes; any strictly decreasing rates are allowed. - Grids are declared per level; refinement is the only MUST, the merge rule is a recommended recipe, and a level may keep its grid. - No `limit`: offsets address rows; row groups and chunks are the writer's choice, aligned with tiles as a SHOULD. - Offsets are Zarr arrays in both formats: `tile_offsets` for the tile-major table and, per feature, for each feature-major table. - Metadata: a self-contained `spatial_index` convention with a version (0.1.0-draft), feature_keys and a list of levels; no multiscales. - New overview, levels-and-bands and orders figures; Summary table of MUST/SHOULD/MAY; related work and rejected alternatives updated. Co-Authored-By: Claude Opus 5.5 --- rfcs/0003-tiled-points.md | 804 +++++++++++++++++++-------------- rfcs/img/0003-columns.svg | 245 +++++----- rfcs/img/0003-levels-bands.svg | 34 ++ rfcs/img/0003-levels.svg | 363 --------------- rfcs/img/0003-orders.svg | 283 +++++------- rfcs/img/0003-summary.svg | 515 +++++++++++++++++++++ rfcs/img/0003-tile-size.svg | 6 +- 7 files changed, 1231 insertions(+), 1019 deletions(-) create mode 100644 rfcs/img/0003-levels-bands.svg delete mode 100644 rfcs/img/0003-levels.svg create mode 100644 rfcs/img/0003-summary.svg diff --git a/rfcs/0003-tiled-points.md b/rfcs/0003-tiled-points.md index 7e4e252..9706b40 100644 --- a/rfcs/0003-tiled-points.md +++ b/rfcs/0003-tiled-points.md @@ -12,8 +12,16 @@ created: 2026-09-17 ## Abstract Specification for spatially indexing points, enabling optional multiscale subsampled levels, spatially chunked storage: a regular -2-D or 3-D grid of tiles, with the points stored both in tile-major order and in feature-major order. This enables viewers to load only the points in view, or only those of the genes shown; zoomed out, they load a -density-preserving sample. Shapes are in [RFC 4](0004-tiled-shapes.md). +2-D or 3-D grid of tiles, with the points stored in tile-major order and, optionally, in feature-major order. Each point carries a +random value $p$, which defines the levels. This enables viewers and other processing applications to load only the points +in view, or only those of the genes shown; zoomed out, they load a density-preserving sample, with as many points as the +resources they have available allow (memory, bandwidth, rendering time). Shapes are in [RFC 4](0004-tiled-shapes.md). + +:::{figure} img/0003-summary.svg +:alt: Overview of the spatial index. Top: 44 points of genes A and B and of a rare gene C (3 points, one kept at level 1, none at level 2) on a rectangular support, shown at three levels; level 0 on a grid of 8 × 4 rectangular tiles holds all the points (p < 1), level 1 on 4 × 2 tiles holds those with p < 0.3, level 2 on 2 × 1 tiles holds those with p < 0.1. Each point has a random value p in [0, 1), shown on a ruler split into bands 2, 1 and 0 at 0.1 and 0.3. Bottom: the tile-major table holds every point once, as bands (coarsest first), tiles inside each band and rows sorted by p; tile_offsets point at the first row of each tile, and the row groups follow the tiles, with small tiles of a band sharing one row group. Two queries are shown. View 1 (dashed red), one tile of level 1 with all genes: it reads level 1, so the tile-major table reads two compact ranges, the rows of band 2 in the tile of level 2 that contains it and the rows of that tile in band 1 (5 rows). The feature-major table holds the same points sorted by gene, then band, then tile, then p: the 3 points of the rare gene C are one short range at its end. Inside each gene and band the rows are again grouped by tile, shown by separators in both tables. Its tile_offsets point at the start of each tile inside each gene's band, and its row groups follow one gene in one band, with small ones sharing a row group. For view 1 the feature-major table reads the same 5 rows, but as one range per gene and band, found through its tile_offsets. View 2 (dashed green), another region with only the rare gene C selected, drawn on all three levels: it fits, so all its bands are read, at every level. The tile-major table reads all the rows of the tiles of view 2 in every band (6 rows in 4 ranges) and discards the other genes, drawn faded, to keep 1 row of gene C; the feature-major table reads only that row. + +Overview of the spatial index; each part is described in the text. +::: ## Description @@ -23,33 +31,60 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be interpreted a ### Scope -- In scope: points, 2-D and 3-D; spatial indexing via chunking and sorting; tile-major order and feature-major order; sampled levels. -- Out of scope: shapes ([RFC 4](0004-tiled-shapes.md)), the matrix of a table annotating the shapes and its sparse storage (CSR/CSC, RFC 4), aggregation to cells or bins (square/hexagonal), ordering inside tiles (Morton, Hilbert), ordering of the tiles other than C order (e.g. Morton). +- In scope: points, 2-D and 3-D; spatial indexing via chunking and sorting; tile-major order and feature-major order; sampled levels; a per-point random value $p$. +- Out of scope: shapes ([RFC 4](0004-tiled-shapes.md)), the matrix of a table annotating the shapes and its sparse storage (CSR/CSC, RFC 4), aggregation to cells or bins (square/hexagonal), spatial orders inside tiles (Morton, Hilbert), ordering of the tiles other than C order (e.g. Morton). ## Data model -This RFC adds to the abstract data model of points: levels, a grid of tiles at each level, the -order of the tiles, and the sampling of the levels. These concepts do not depend on how the points -are stored ([Storage format](#storage-format)). +The data model does not depend on how the points are stored, in Parquet or in Zarr +([Storage format](#storage-format)). + +### Overview + +This section is an overview: it lists all the terms of the spatial index and how they relate. Each +is defined in the sections that follow, starting from the tiles, then $p$, which defines levels and +bands on top of them; [Summary](#summary) lists them again in a table, with which are required. The +terms are in three layers: the data, the data model and the storage format. -### Levels +**Data.** The points with their columns (coordinates, feature, any other) are always there, as +today. The data model and the storage format of the spatial index are optional: an element may have +no spatial index at all. If it has one, some of its parts MUST be present, others SHOULD or MAY be. -Points are organized in one or more levels. To load all the points, a reader loads the -highest-resolution level (level 0). Each other level is a subsampled version of the points of the previous level. I.e. a point present at level N, is also present in levels 0, ..., N - 1. +**Data model.** It says which tile and which level each point belongs to: -While one could design the storage so that each point is stored exactly once, this specification favors simplificity over size on disk and, shown below, will also store multiple indexes (motivations: storage of points is generally cheap, and cheaper than that of raster data such as images; clients such as viewers can fetch the data faster and more easily; readers never need to merge levels). When storing several copies of the points is not acceptable, for instance for very large datasets, aggregated data is a better choice than sampled levels (out of scope for this RFC). +- grid parameters: the axes; per axis, the origin $o_a$ and the tile size + $s_a$ of level 0; the grid of every coarser level, which refines the next one (recommended recipe: + the merge rule) ([Grid and tiles](#grid-and-tiles)); +- sampling parameters: a random value $p$ per point, and the fraction $P^{(l)}$ of each level, a + fixed rate, by default the ratio of the tile volumes of level 0 and level $l$ ($1/2^d$ per level + when all $d$ axes are merged); level $l$ holds the points with + $p < P^{(l)}$ ([Priority](#priority), [Levels and bands](#levels-and-bands), [Sampling](#sampling)); +- derived from these, the number of points per tile at each level, which guides the choice of the + tile size and the rates together ([Choosing the tile size and the rates](#choosing-the-tile-size-and-the-rates)); +- the feature column (e.g. the gene), which sorts the feature-major order + ([Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)). + +**Storage format.** It says how the points are written ([Storage format](#storage-format)), in +Parquet or in Zarr: + +- the metadata declares which parts are present: the orders (tile-major and feature-major), the + levels, and the grid and sampling of each level; +- each order is one table, with the levels as bands of rows, with offsets that address rows: + `tile_offsets` in the tile-major table (the tile index) and in each feature-major table (the + feature index), and the column `__spatialdata_p__`, which stores $p$; + the row groups (Parquet) or chunks (Zarr) are a choice of the writer. ### Grid and tiles -A grid is defined for a specific *points element* (the SpatialData term for a 2D/3D points cloud) and for a specific named coordinate system. The metadata for the grid specifies this information pair. +A grid is defined for a specific *points element* (the SpatialData term for a 2D/3D points cloud), in the coordinates of its points. The metadata MUST specify the axes of the grid. -Different elements, even if in the same coordinate system, use different grids: reusing the same grid for 2 or more elements is out of scope for this RFC ([RFC 4](0004-tiled-shapes.md) will discuss reusing the same grid for points (transcripts) and shapes (cells)). +Different elements use different grids: reusing the same grid for 2 or more elements is out of scope for this RFC ([RFC 4](0004-tiled-shapes.md) will discuss reusing the same grid for points (transcripts) and shapes (cells)). An axis $a$ is one of the spatial axes $x$, $y$ and $z$ (not the channel axis $c$). The grid has, per axis $a$, -an arbitrary origin $o_a$ (for instance the corner with the minimum coordinates of the bounding box -of all the points), one tile size $s_a$ (square tiles are a special case), and an arbitrary number of +an arbitrary origin $o_a$, which MUST be given (for instance the corner with the minimum coordinates of the bounding box +of all the points), one tile size $s_a$, which MUST be given (square tiles are a special case), and an arbitrary number of tiles $n_a$: the number of intervals into which the grid divides axis $a$, not the total number of -tiles of the grid, which is $N = \prod_a n_a$. All the tiles are identical. The tiles cover all the points. +tiles of the grid, which is $N = \prod_a n_a$. All the tiles are identical. The tiles MUST cover all the points. Each tile is to be interpreted as a semi-open hyper-interval, with the interval closed for the lowest value, and open for the highest. For example, in 2 dimensions, the tile @@ -59,19 +94,21 @@ $$ contains the points $(x, y)$ that satisfy $x_{\min} \le x < x_{\max}$ and $y_{\min} \le y < y_{\max}$. -The grid of each lower level is built deterministically from the grid of the previous level: it is -merged by a factor of 2 along one or more axes, keeping the tiles as isotropic as possible. -Therefore the initial grid determines the granularity of the spatial index at the first level and -at each subsequent level. - -:::{figure} img/0003-levels.svg -:alt: Three levels of a 2-D grid: level 0 with 4 × 4 tiles and all the points, level 1 with 2 × 2 tiles and fewer points, level 2 with a single tile and fewer points still. - -Three levels of a 2-D grid, with the points kept at each level. -::: - -Below are two examples of a merging step that keeps the tiles as isotropic as possible: one merges -along one axis, the other along two. +The grid of every level present, $0, \dots, L$, MUST be given in the metadata (see +[Metadata](#metadata)); since level 0 is always present, so is its grid. The grids of the coarser +levels are the writer's choice, with one constraint: the grid of each level $l$ MUST refine the grid +of level $l + 1$, that is every tile of level $l$ MUST lie inside a single tile of level $l + 1$, so +that no tile of a finer level overlaps several tiles of a coarser level. The grids SHOULD get coarser +with the level, but a level MAY keep the grid of the level below, since a grid refines itself: at the +limit, a single tile for the whole dataset at every level, or the same grid at all the levels, which +avoids the many small, almost empty tiles of the coarse levels of a rare feature. + +A recommended recipe, the *merge rule*, builds the grid of each coarser level from the grid of the +previous level: it is merged by a factor of 2 along one or more axes, keeping the tiles as isotropic +as possible. It satisfies the constraint, since the origin stays the same and each tile size is +either kept or doubled, and the initial grid then determines the granularity of the spatial index at +every level. Below are two merging steps that keep the tiles as isotropic as possible: in the first, by merging +along one axis; in the second, by merging along two axes. :::{figure} img/0003-merge-one-axis.svg :alt: Two tiles of size 2 × 2 × 1, stacked along z, become one tile of size 2 × 2 × 2. @@ -108,28 +145,11 @@ $$ ::: -Applied to the end, the procedure stops at the first level with $n_a = 1$ along every axis (a single -tile). A writer may also stop earlier, so the lowest-resolution level may still contain multiple +Applied to the end, the merge rule stops at the first level with $n_a = 1$ along every axis (a +single tile). A writer may also stop earlier, so the lowest-resolution level may still contain multiple tiles. -Examples. First, a simple one: a volume of 256 × 256 × 200 along (x, y, z), origin 0. - -:::{dropdown} Volume 256 × 256 × 200: initial tile size 32 × 32 × 32 - -Starting from "# tiles along axis" 7 × 8 × 8 along (z, y, x), the tiles are isotropic, so all three -axes are merged at every level, until a single tile is left: - -```text -level tile size (z, y, x) # tiles along axis (z, y, x) merged -0 32 × 32 × 32 7 × 8 × 8 - -1 64 × 64 × 64 4 × 4 × 4 z, y, x -2 128 × 128 × 128 2 × 2 × 2 z, y, x -3 256 × 256 × 256 1 × 1 × 1 z, y, x -``` - -::: - -Then an anisotropic extent, 10 × 100 × 1000 along (z, y, x), origin 0, with two initial tilings. +Example: an anisotropic extent, 10 × 100 × 1000 along (z, y, x), origin 0. :::{dropdown} Anisotropic tiles: initial tile size 1 × 10 × 100 @@ -153,25 +173,6 @@ level tile size (z, y, x) # tiles along axis (z, y, x) merged ::: -:::{dropdown} Isotropic tiles: initial tile size 10 × 10 × 10 - -Starting from "# tiles along axis" 1 × 10 × 100, z has a single tile from the start; y and x are -merged together until y has a single tile, then x alone: - -```text -level tile size (z, y, x) # tiles along axis (z, y, x) merged -0 10 × 10 × 10 1 × 10 × 100 - -1 10 × 20 × 20 1 × 5 × 50 y, x -2 10 × 40 × 40 1 × 3 × 25 y, x -3 10 × 80 × 80 1 × 2 × 13 y, x -4 10 × 160 × 160 1 × 1 × 7 y, x -5 10 × 160 × 320 1 × 1 × 4 x -6 10 × 160 × 640 1 × 1 × 2 x -7 10 × 160 × 1280 1 × 1 × 1 x -``` - -::: - ### Tiles ordering At each level, the tiles are indexed by their coordinates along the axes and ordered by a single @@ -216,179 +217,156 @@ With $N = \prod_a n_a$ tiles, $0 \le k < N$. One could instead order the tiles by Morton code (Z-order), which keeps tiles that are close in space close in the order. This is not done in this version and is left for future versions. -### Tile-major order and feature-major order +### Priority -At each level, the points are written in two orders, each a copy of the points with all their -columns: +Every point $i$ MUST have a uniformly sampled random value $p_i \in [0, 1)$, termed *priority*, adapted +from the continuous level of detail of [van Oosterom et al., 2022](#references) and +[Schütz et al., 2019](#references). It is drawn once when the points are written and MUST be +stored with them, as a column (see [Columns](#columns)). Any uniform random generator may be used, and $p$ may +be derived from a hash of the point. The priority is fixed: it defines which points are in which +level, and the order of the rows inside a tile, in both orders of the points. -- tile-major order, required: sorted by tile id, with the order inside a tile unspecified; -- feature-major order, written by default (a writer may opt out): sorted by feature, then by tile - id. +### Levels and bands -The feature is a categorical column chosen when writing and named in the metadata: for spatial -transcriptomics, the gene id. A writer may choose several feature columns, for instance the gene id -and the cell type, each with its own feature-major copy. It is recommended to choose only one, the -column used most often to select points, for the best performance at the lowest storage cost. Any -other column can still be used to select points, from the tile-major copy: faster than without a -spatial index, with some performance penalty compared with a feature-major copy. +Every point belongs to exactly one *band* $l \in \{0, \dots, L\}$, $L \ge 0$, given by its $p$ and +by fractions $1 = P^{(0)} > P^{(1)} > \dots > P^{(L)}$ (see [Sampling](#sampling)): -Only the tile-major order is required: a dataset may have no feature-major copy at all. A client looking -for the points of a feature looks for a feature-major copy of the corresponding column and, if there -is none, falls back to the tile-major order. +$$ +\text{band } L = \{\, i : p_i < P^{(L)} \,\}, \qquad +\text{band } l = \{\, i : P^{(l+1)} \le p_i < P^{(l)} \,\} \quad (l < L) +$$ -:::{dropdown} Falling back to the tile-major order: what changes at sampled levels +With $L = 0$ there is a single band, with all the points; bands $1, \dots, L$ MAY be present. The +tiles of band $l$ are those of the grid of level $l$. Level $l$ is the union of the bands +$L, L - 1, \dots, l$, the points with $p < P^{(l)}$; level 0 holds all the points. -The two orders are sampled differently (see [Sampling](#sampling)). The feature-major order -preserves densities within each feature. The tile-major order preserves only the global density: it -treats all the points as equal, whatever their category. +:::{figure} img/0003-levels-bands.svg +:alt: The axis of p from 0 to 1, cut at P(2) and P(1) into three disjoint bands, 2, 1 and 0. Below, level 2 covers band 2; level 1 covers bands 2 and 1; level 0 covers all three bands. -At level 0 the two orders hold all the points of every tile, so they are fully equivalent, except -for performance. At sampled levels they differ: the tile-major order keeps a feature with the same -fraction as all the others, so a client that falls back to it is less useful for showing rare -categories, which may keep very few points or none. +A level is the union of its band and all coarser bands. +::: -To address this at the root, aggregation (e.g. counting the points of each category per bin) can be -a better alternative to sampling. It is out of scope for this RFC. +This is the priority-band (continuous level of detail) organization of +[van Oosterom et al., 2022](#references), with discrete bands on a grid. -::: +### Tile-major order and feature-major order + +An *order* is a table with all the points and all their columns, sorted in a given way. The points +are written in exactly one tile-major order and in zero, one or more feature-major orders, one per +feature column chosen by the writer and named in the metadata: + +- tile-major order, which MUST be written: sorted by band (coarsest first, see + [Levels and bands](#levels-and-bands)), then by tile id on the grid of the band, then by $p$; +- feature-major order, optional, for a given feature column named in the metadata: sorted by + feature, then by band, then by tile id, then by $p$. The feature is a categorical column chosen + when writing: for spatial transcriptomics, usually the gene id. A writer MAY choose several feature + columns, for instance the gene id and the cell type, each with its own feature-major table; it + SHOULD choose at most one, the column used most often to select points, for the best performance + at the lowest storage cost. + +Both orders hold exactly the same points at every level; only the order of the rows differs, so a +client gets the same result from either, at a different cost. Since each order is sorted by band, +coarsest first (see [Levels and bands](#levels-and-bands)): + +- each point is stored once per order: the levels need no extra storage (up to 1.33× in 2-D if each + level were a table of its own); +- going to a finer level reads only the next band; the points already loaded stay valid; +- with the rows of each tile sorted by $p$, a client can stop reading at any budget $b$, not only + at the $P^{(l)}$ of the levels (see [Reading with a budget](#reading-with-a-budget)). The two orders answer two different questions with a contiguous range of rows: - Tile-major order: *which points are in this region?* The points of a tile are one row range, whatever their gene. A client showing the region reads the tiles in view. -- Feature-major order: *where are the points of this gene?* The points of a gene are one row range, - and inside it the points of each tile are again one range, sorted by tile id. A client showing a +- Feature-major order: *where are the points of this gene?* The points of a gene are one row range; + inside it, the points of each band are one range, and inside a band the points of each tile. A client showing a few genes reads only their points. -Without the feature-major copy, showing one gene means reading every point of the tiles in view and -discarding the other genes: the cost grows with all the points in view, not with the points of the -gene. With it, the cost grows only with the points of the genes shown. The price is a second copy of -the points. Per-tile statistics (e.g. which features a tile contains, or how many points of each) +A client looking for the points of a feature uses the feature-major table of that column if there +is one. Otherwise it falls back to the tile-major table, as for any other column: it reads every +point of the tiles in view and discards the other features, so the cost grows with all the points +in view, not with the points of the feature; zoomed out, this can be most of the data. The price of +the feature-major table is a second table of the points. Per-tile statistics (e.g. which features a tile contains, or how many points of each) could let a client skip tiles without the feature it shows and improve performance; they are out of scope for this RFC. :::{figure} img/0003-orders.svg -:alt: Two levels. Level 0: twelve points of genes A (6), B (4) and C (2) on a 2 × 2 grid, stored grouped by tile and grouped by gene and then by tile. Level 1, a single tile: the tile-major copy keeps 4 points (P = 1/3); the feature-major copy keeps 4 points of A (P = 2/3), 2 of B (P = 2/3) and both points of C (P = 1). +:alt: Eight points of genes A and B in two tiles, each with its p. Level 1 is a single tile with the points p < 0.25 (A5, B2, A3), which form band 1; the other five form band 0. Tile-major table: band 1 (A5, B2, A3), then band 0 by tile (tile 0: A1, B8; tile 1: A7, B6, B4). Feature-major table: gene A (band 1: A5, A3; band 0: A1, A7), then gene B (band 1: B2; band 0: B8, B6, B4); a second row of brackets shows the tiles inside each band of each gene (band 1: tile 0 of level 1; band 0: tiles 0 and 1). -The points of two levels, each in the two orders. In tile-major order each tile is one row range; in -feature-major order each gene is one row range, sorted by tile inside it. At level 1 the tile-major -copy is sampled over all the points, with one fraction $P$, the feature-major copy per gene, with -one fraction per gene: the rare gene C keeps all its points. How the fractions $P$ are chosen is -explained in [Sampling](#sampling). +The two orders, as bands. Each table holds every point once, in the band of the coarsest level that +holds it: band 1 is level 1 ($p < 0.25$), and both bands together are level 0. ::: ### Sampling -Sampling chooses the subset of points of each level (see [Levels](#levels)). It is -density-preserving, as in Neuroglancer -([annotation spatial index](https://github.com/google/neuroglancer/blob/master/src/datasource/precomputed/annotations.md#spatial-index)): -at each level, every point is kept with the same -probability, chosen so that the densest tile holds about `limit` points. Dense regions stay denser -than sparse ones. Each level is sampled from the level below it, which makes the levels nested. - -The two copies of the points (see -[Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)) are sampled differently: - -- Tile-major order: over all the points. At a level, every feature is kept with the same fraction $P^{(l)}$. -- Feature-major order: per feature. Each feature $g$ is sampled on its own, with its own fraction - $P_g^{(l)}$, so that the densest tile holds about `limit` points of $g$. A rare feature keeps - all its points at coarse levels instead of vanishing; an abundant one is thinned. When the - feature-major copy is written, every level has one. - -The sampling is binomial thinning, as in Neuroglancer: each point of level $l - 1$ is kept at level -$l$ or not, independently of the others and with the same probability, so no point appears twice in -a level. The `limit` is therefore met on average, not exactly: a tile can end up with slightly more -than `limit` points. For example, if the densest tile holds 10,100 points and `limit` is 10,000, -each point is kept with probability about 0.99. The tile then keeps 10,000 points on average, but by -chance more than 10,000 about half of the time (typically about 10 more). Such small excesses do not -matter: `limit` is a budget for a comfortable display, not a hard bound. -No random value or hash used to keep or reject a point is stored with the points. The metadata stores the fractions of both copies (see -[Metadata](#metadata)). - -How to choose `limit`, and the tile size of level 0 with it, is explained in -[When the spatial index helps](#when-the-spatial-index-helps). - -:::{dropdown} Sampling in formulas +Sampling chooses the fractions $P^{(l)}$ of the levels (see [Levels and bands](#levels-and-bands)). The fractions are +fixed rates: they do not depend on how many points the tiles hold, and the same $P^{(l)}$ applies to +all the points, whatever their feature, and to both orders. Level $l$ keeps the points with +$p < P^{(l)}$. -Let $c^{(l)}$ be the largest number of points of level $l - 1$ in any tile of level $l$; $p^{(l)}$ the fraction of -the points of level $l - 1$ kept at level $l$; and $P^{(l)}$ the fraction of all points kept at -level $l$: +By default, the fraction of a level is the ratio of the tile volumes (areas in 2-D) of level 0 and +of that level: $$ -\begin{aligned} -c^{(l)} &= \max_{\text{tiles } T \text{ of level } l} \bigl|\{\, i \in \text{level } l - 1 : i \in T \,\}\bigr| \\ -p^{(l)} &= \min\!\left(1, \frac{\texttt{limit}}{c^{(l)}}\right) \\ -P^{(0)} &= 1, \qquad P^{(l)} = P^{(l-1)}\, p^{(l)} -\end{aligned} +P^{(l)} = \frac{V^{(0)}}{V^{(l)}}, \qquad V^{(l)} = \prod_a s_a^{(l)} . $$ -Each point of level $l - 1$ is kept at level $l$ independently with probability $p^{(l)}$, so each -point of level 0 is in level $l$ with probability $P^{(l)}$, and the densest tile keeps -$p^{(l)} c^{(l)} = \texttt{limit}$ points on average. +A tile of level $l$ then covers $V^{(l)} / V^{(0)}$ tiles of level 0 and keeps that fraction of +their points, so it holds on average as many points as a tile of level 0 in the same region, +whatever axes were merged. With the merge rule, each level divides the fraction by 2 per merged +axis: $1 / 2^d$ per level when all $d$ axes are merged (1/4 in 2-D, 1/8 in 3-D), more when only +some are. A writer MAY choose any other rates, as long as they strictly decrease with $l$. When a +level keeps the grid of the level below, the tile volume does not change and the default would keep +the same fraction; the writer then chooses the rates, e.g. $1/2^d$ per level. Dense +regions stay denser than sparse ones: the sample is density-preserving. -For the feature-major copy, the same formulas are applied to the points of each feature $g$ -separately, giving $c_g^{(l)}$, $p_g^{(l)}$ and $P_g^{(l)}$, : each point of feature $g$ is in level $l$ of the feature-major copy with -probability $P_g^{(l)}$. +Because $p$ is uniform, keeping the points with $p < P^{(l)}$ keeps each point with probability +$P^{(l)}$, independently of the others. -Storage bound: if each level keeps at most $1/2^d$ of the points of the level below (merged along -all $d$ axes), the levels hold at most +The $P^{(l)}$ of every level present, including $P^{(0)} = 1$, MUST be given in the metadata (see +[Metadata](#metadata)); a +reader uses the values of the metadata, whatever rates the writer chose. -$$ -N \sum_{l \ge 0} 2^{-d\,l} = N \, \frac{2^d}{2^d - 1} -$$ - -points in total, for $N$ points at level 0: $1.33\,N$ in 2-D, as for a 2-D image pyramid, and -$1.14\,N$ in 3-D. The bound holds for each copy. - -The bound shows that the data does not grow much, even though the same point appears again at -several levels: the sampled levels add at most a third of the points in 2-D. The storage is -dominated by the multiple copies (the tile-major order and the feature-major order), which double it and -are generally affordable (see [Levels](#levels)). - -::: - -#### Showing several features together - -At level 0 every fraction is 1 and both copies hold every point, so any view is exact, independently -of whether it is read from the tile-major order or from the feature-major order. The -difference matters only when a client shows a sampled level ($l \ge 1$) of the feature-major copy. -There, features are kept with different fractions, so showing several features together distorts -their relative abundance. For example, if an abundant feature keeps $P_A^{(l)} = 1\%$ of its points -and a rare one keeps $P_B^{(l)} = 100\%$, a region with 10,000 points of A and 100 of B shows 100 of -each. Within each feature the view stays density-preserving. +:::{dropdown} Sampling in formulas -To show a set $S$ of features consistently, a client should sample and keep each point of a feature -$g \in S$ independently with probability +A tile of level $l$ with volume $V^{(l)}$ (area in 2-D) in a region of density $\rho$ holds on +average $$ -\frac{P_S^{(l)}}{P_g^{(l)}}, \qquad P_S^{(l)} = \min_{g \in S} P_g^{(l)}, +n^{(l)} = \rho\, V^{(l)}\, P^{(l)} $$ -which gives every feature in $S$ the same fraction $P_S^{(l)}$ of its points. The client should use -a fixed seed (e.g. derived from the coordinates of each point), so that the same points stay shown -when the view moves or reloads. Clients SHOULD do this when they show several -features together; it is not required. A client may also show each feature at its own fraction on -purpose, e.g. to compare the spatial patterns of the features rather than their abundance. +points. With the default rates $P^{(l)} = V^{(0)} / V^{(l)}$ the two factors cancel, and +$n^{(l)} = \rho\, V^{(0)} = n^{(0)}$ at every level. With the merge rule and all $d$ axes merged at +every level, $V^{(l)} = 2^{d\,l}\, V^{(0)}$ and $P^{(l)} = 2^{-d\,l}$. For example, in 2-D with tiles of 10 × 10 at level 0 and of 40 × 40 at +level 2, a tile of level 2 covers 16 tiles of level 0 and keeps 1 point in 16. + +::: A client MAY support only level 0 and ignore the sampled levels, and show zoomed-out views with other strategies, such as aggregation (see [RFC 4](0004-tiled-shapes.md#levels)). -### When the spatial index helps +### Choosing the tile size and the rates -Holding every point at level 0 does not by itself make reading fast. The spatial index helps only -if the tile size of level 0 and the `limit` suit the data and each other. +The levels and the tiles let a client read only a part of the data: the tiles in view, at a level +coarse enough for the view. This works well only if the tile size and the rates suit the data and +each other. There is no parameter for this in the format: the number of points per tile at each +level, $n^{(l)}$, follows from the density of the points, the tile size and the rates (see +[Sampling](#sampling)), and guides the choice of the two. -The `limit` is the number of points a client can comfortably load and display for one tile. The -suggested default is `limit` = 10,000, for now, while this RFC is a draft; it will be adjusted -from user feedback. The reasoning: with the coordinates and a feature code, about 16 bytes per -point, a tile is about 160 kB before compression, a comfortable size for one request, and a view of -4 × 4 tiles shows about 160,000 points, which a browser renders easily. +A good target is the number of points a client can comfortably load and display at once from one +tile, for now about 10,000, while this RFC is a draft; it will be adjusted from user feedback. The +reasoning: with the coordinates and a feature code, about 16 bytes per point, a tile is about +160 kB before compression, a comfortable size for one request, and a view of 4 × 4 tiles shows +about 160,000 points, which a browser renders easily. The target is not stored in the metadata and +is not a cap: level 0 holds all the points, and a tile may hold any number of them. -The tile size of level 0 should then be chosen so that the densest tile of level 0 holds about -`limit` points. If the densest region has $\rho$ points per unit of area (2-D) or volume (3-D), the -tile size along each of the $d$ axes is about +The tile size of level 0 should then be chosen so that the densest tile of level 0 holds about the +target number of points: $n^{(0)}$, the number of points per tile of level 0 (see +[Sampling](#sampling)), about equal to the target in the densest region. If the densest region has $\rho$ points per unit of area (2-D) or +volume (3-D), the tile size along each of the $d$ axes is about $$ -s \approx \left( \frac{\texttt{limit}}{\rho} \right)^{1/d}. +s \approx \left( \frac{n^{(0)}}{\rho} \right)^{1/d}. $$ This estimate assumes that the points are roughly uniformly distributed at the scale of a tile, and @@ -396,40 +374,55 @@ that the tiles are isotropic. Larger-scale variations are taken into account by the densest region; a hotspot smaller than a tile is not (see case (d) below). In practice, a writer can also pick a tile size, count the points of the densest tile, and adjust. -Then a client loads about `limit` points per tile at every level: at level 0 because the tiles are -small, at the coarser levels because the points are sampled. The cost of a view stays the same as -the client zooms in and out. +With the default rates, $n^{(l)} = n^{(0)}$: the densest tiles then hold about the target number of +points at every level (see [Sampling](#sampling)). What is stored per tile is a band, a part of its level: band $l$ holds a +fraction $1 - P^{(l+1)} / P^{(l)}$ of the level-$l$ points of the tile (3/4 in 2-D with all axes +merged). + +The cost of a view stays about the same as the client zooms in and out, plus one cost of the bands: +to show a small region at full detail, a client also needs the points of the coarser bands in that +region. These are stored in the larger tiles of the coarser levels, so the client reads those +larger tiles and discards the points outside the view. :::{figure} img/0003-tile-size.svg -:alt: Four panels with the same limit of 40 points per tile. (a) 4 × 4 tiles on uniform points, densest tile 37 points. (b) 2 × 2 tiles, densest tile 127 points, all tiles above the limit. (c) 16 × 16 tiles, densest tile 6 points. (d) 4 × 4 tiles with a hotspot, one tile of 220 points, the others at most 16. +:alt: Four panels with the same target of 40 points per tile. (a) 4 × 4 tiles on uniform points, densest tile 37 points. (b) 2 × 2 tiles, densest tile 127 points, all tiles above the target. (c) 16 × 16 tiles, densest tile 6 points. (d) 4 × 4 tiles with a hotspot, one tile of 220 points, the others at most 16. -The tile size of level 0 for a limit of 40 points per tile, on 400 points. +The tile size of level 0 for a target of 40 points per tile, on 400 points. ::: The figure shows the edge cases: -- (a) Tiles that fit: the densest tile holds about `limit` points. -- (b) Tiles too large: the tiles of level 0 hold far more than `limit` points, and level 0 is not - sampled, so a client zoomed in loads more points than it can comfortably display. Level 0 needs a - finer grid. +- (a) Tiles that fit: the densest tile holds about the target number of points. +- (b) Tiles too large: the tiles of level 0 hold far more points than the target. Level 0 is not + sampled, but a client zoomed in does not have to load a whole tile: its rows are sorted by $p$, + so the first rows are a fair sample of it (see [Reading with a budget](#reading-with-a-budget)), and + the storage can split it into several row groups or chunks (see + [Points as a tall table](#points-as-a-tall-table)). The cost is coarser spatial selection: a + client still reads tiles that are only partly in view. A finer grid is better. - (c) Tiles too small: many tiles with few points each, so a view needs many small requests and the - index is large. Moreover, the first coarser levels still hold fewer than `limit` points per tile, - so they are not sampled ($p^{(l)} = 1$): they are copies of level 0 on a coarser grid, which cost - storage without reducing the points to load. + index is large. With the default rates, each level keeps about as many points per tile as the level below, so the + tiles of the coarser levels hold few points too, and a view needs many small requests at every + level. - (d) Hotspot: a region much denser than the rest puts many points in a few tiles. A tile size chosen for the hotspot is too small elsewhere, as in (c); one chosen for the rest is too large in - the hotspot, as in (b). A future extension could address this with an adaptive grid, if the - community identifies it as a need. - -> **TODO(Luca), placeholder:** what happens when a tile of level 0 holds more than `limit` points -> (tiles too large for the density, case (b), or a hotspot, case (d)). As specified, level 0 always -> holds all the points ($P^{(0)} = 1$, level 0 is never sampled), so it is `limit` that is not -> respected at level 0: such a tile holds more than `limit` points, and a client zoomed in loads -> all of them. `limit` only drives the sampling of the coarser levels ($p^{(l)} = \min(1, -> \texttt{limit} / c^{(l)})$ for $l \ge 1$), where it holds on average. Consequences to spell out -> here: in Zarr, padding every chunk to the largest tile is then no longer small and bounded (see -> [Points as a tall table](#points-as-a-tall-table)); in Parquet, the row group of such a tile is -> large. To be compared against an alternative design of the points storage. + the hotspot, as in (b), and handled as in (b). A future extension could address this with an + adaptive grid, if the community identifies it as a need. + +The grid and the rates are the same for all the features, so a rare feature has few points per +tile, and at the coarser levels few or none: in the feature-major table most of its tiles are empty. +This is not a problem: an empty tile holds no rows and costs only its entry in +the `tile_offsets` of the feature-major table, and the rows of a feature are contiguous, sorted by band, so a client showing +a rare feature reads all its levels, down to level 0, as one contiguous range. + +#### Reading with a budget + +Sometimes a client does not have the resources to read all the points of the tiles in view, even at +the right level: for instance with tiles that are too large, as in case (b). Here $p$ comes into +play. With a *budget* $b \in (0, 1]$, the client reads only the points with $p < b$: since $p$ is +uniform, a representative sample of a fraction $b$ of the points, and since the rows of each tile +are sorted by $p$, the first rows of each tile. The budget is not limited to the fractions +$P^{(l)}$ of the levels: the client reads the coarsest level with $P^{(l)} \ge b$, the bands +coarser than $l$ in full and band $l$ up to $p < b$. ## Storage format @@ -441,24 +434,54 @@ feedback and real usage; Zarr would also be more flexible for 3-D shapes (meshes The format is self-contained: compatible with the way OME-NGFF stores coordinate systems, but usable on its own, even outside an OME-Zarr store, because its metadata is defined as a Zarr convention. +Compatible means that this storage of points could in the future be proposed as an OME-NGFF +extension, with the extensibility mechanism of +[NGFF RFC-8](https://ngff.openmicroscopy.org/rfc/8/index.html), and later, through an NGFF RFC, as +part of the OME-NGFF specification. This is not a goal for now: for the time being this +specification remains part of SpatialData, and is neither an official OME-NGFF extension nor +OME-NGFF compliant. Parquet has no equivalent of Zarr conventions, so the Parquet format reuses the same syntax for its metadata. -### Points as a tall table +The spatial index is optional (see [Overview](#overview)). Without it, an element is stored as today +(see [Compatibility](#compatibility)). With it, the metadata declares which parts are present (see +[Metadata](#metadata)). -In both formats, each copy of a level (tile-major order or feature-major order) is a tall table: one row -per point, one column per attribute. Each tile is stored in one logical unit, one row group per tile in Parquet -(as in Celldega) and one chunk per tile in Zarr, and the units are grouped into files: the part files of a multi-file Parquet -dataset, and shards in Zarr. Zarr chunks are regular, so each tile's chunk is padded to the size of -the largest tile; this adds an overhead, small and bounded, since the tiles hold similar numbers of -points, at most about `limit` when the tile size is chosen as in -[When the spatial index helps](#when-the-spatial-index-helps). +### Points as a tall table -An alternative storage in Zarr would be a sparse tensor in which each entry is a point. It comes with -other compromises and is left for possible future exploration. Another option would come if Zarr -allowed chunks of different sizes in an array (variable chunk grids have been proposed for Zarr), -or if the points were stored as a ragged array: each tile would then be one chunk of its own size, without -padding. +In both formats, each table of points is a tall table: one row per point, one column per attribute. +The tile index and the feature index address rows (see [Tile index](#tile-index), +[Feature index](#feature-index)). How the rows are split into row groups (Parquet) or chunks (Zarr) +is a choice of the writer, not declared by this convention: Parquet row groups may have any size, +and the footers of the files give their row counts; Zarr chunks have the chunk length of the array, +given in its metadata. A reader maps a range of rows to the row groups or chunks that overlap it: in +Zarr, with chunk length $c$, the rows $[\,a, b\,)$ are in the chunks $\lfloor a / c \rfloor, \dots, +\lfloor (b - 1) / c \rfloor$. A row group or chunk may hold several small tiles, and a large tile may +span several. The row groups are grouped into the part files of a multi-file Parquet dataset; the +chunks into shards in Zarr. + +To read a tile with few requests: + +- Parquet writers SHOULD align the boundaries of the row groups with those of the tiles: one row + group per tile of a band when the tile is large enough, several small tiles in one row group to + avoid tiny row groups, and a large tile split into several. In the feature-major table, the same + with the groups of rows of one feature in one band. +- Zarr writers SHOULD choose a chunk length close to the typical number of rows of a tile. + +These are recommendations and not requirements because no single layout fits all the data, and the +index addresses rows, so any layout is readable. In the tile-major table, one row group per tile +would give tiny row groups in sparse regions and in the coarse bands, and huge ones in hotspots. In +the feature-major table, one row group per feature, band and tile would give up to +$n_\text{features} \times N_\text{tiles} \times (L + 1)$ row groups, e.g. 500 genes × $10^5$ +tiles = up to $5 \cdot 10^7$, almost all tiny; one per feature and band gives a few thousand. + +Another option in Zarr is rectilinear chunk grids, an experimental Zarr feature that allows chunks +of different sizes along an array: each tile would then be one chunk of its own size. + +A spatial index without a spatial subdivision is a special case of this format, not a separate one: +a grid with a single tile covering all the points, the same at every level (see +[Grid and tiles](#grid-and-tiles)). Each band is then one range of rows sorted by $p$, so any first +rows of a band are a uniform sample of it, which a reader can load progressively. ### Metadata @@ -473,93 +496,73 @@ points// ``` The metadata is a Zarr convention, `spatial_index`, next to the existing attributes of the element. -The levels follow the -[zarr-conventions `multiscales`](https://github.com/zarr-conventions/multiscales) convention: its -`layout` lists the levels, and each level object carries the grid and the sampling of that level -under the key `spatial_index`, as the convention allows additional properties: +It is registered in `zarr_conventions` with its name and the URL of this specification; the uuid and +a JSON schema are optional and will be added when the convention is released. `levels` lists the +levels present, level 0 first, each with its grid and, for the coarser levels, its fraction: ```json { "zarr_conventions": [ - { - "name": "multiscales", - "uuid": "d35379db-88df-4056-af3a-620245f8e347", - "schema_url": "https://raw.githubusercontent.com/zarr-conventions/multiscales/refs/tags/v0.1/schema.json", - "spec_url": "https://github.com/zarr-conventions/multiscales/blob/v0.1/README.md" - }, { "name": "spatial_index", - "spec_url": "" + "spec_url": "https://spatialdata-spec.scverse.org/rfcs/0003-tiled-points.html", + "description": "Tiled and multiscale points" } ], "spatial_index": { - "coordinate_system": "global", + "version": "0.1.0-draft", "axes": ["x", "y", "z"], - "feature_key": "gene", - "orders": ["spatial", "feature"] - }, - "multiscales": { - "resampling_method": "density_preserving", - "layout": [ + "feature_keys": ["gene", "cell_type"], + "levels": [ { - "asset": "0", - "spatial_index": { - "origin": [0.0, 0.0, 0.0], - "tile_size": [100.0, 100.0, 10.0], - "grid_shape": [120, 80, 3], - "n_rows": 812345678 - } + "origin": [0.0, 0.0, 0.0], + "tile_size": [100.0, 100.0, 10.0], + "grid_shape": [120, 80, 3], + "P": 1.0 }, { - "asset": "1", - "derived_from": "0", - "transform": {"scale": [2.0, 2.0, 2.0]}, - "spatial_index": { - "origin": [0.0, 0.0, 0.0], - "tile_size": [200.0, 200.0, 20.0], - "grid_shape": [60, 40, 2], - "n_rows": 203086419, - "sampling": {"limit": 10000, "P": 0.25, "P_feature": [1.0, 0.8, 0.25]} - } + "origin": [0.0, 0.0, 0.0], + "tile_size": [200.0, 200.0, 20.0], + "grid_shape": [60, 40, 2], + "P": 0.125 } ] } } ``` -The `transform` of a level gives, per axis, the factor by which its tiles are larger than those of -the level it is derived from: 2 along the merged axes, 1 along the others. The `resampling_method` -MUST be `density_preserving`, the only sampling defined by this RFC (see [Sampling](#sampling)); the -`multiscales` convention itself allows any value. `P` is the fraction $P^{(l)}$ of the tile-major -copy; `P_feature` lists the fractions $P_g^{(l)}$ of the feature-major copy, one per feature, in the -order of the feature categories: it has as many entries as there are categories (see -[Columns](#columns)). - -> **TODO(Luca):** register the `spatial_index` convention (its uuid and schema URL are omitted and -> its spec URL is blank for now); align the `asset` paths with the file layout of each format. +`version` is the version of this specification that the element follows; it MUST be given, so that +readers can tell future versions (e.g. with tiles in Morton order) apart. While this RFC is a draft, +the version carries the suffix `-draft`. Following the versioning of Zarr conventions, a released +version will also be referenced by a `spec_url` (and `schema_url`) pinned to that version, e.g. a +tagged URL. `levels[l]` gives the grid of level $l$: `origin`, `tile_size` and `grid_shape` (the +number of tiles $n_a$ along each axis). `P` is the fraction $P^{(l)}$ of the level (here 1/8, the +default in 3-D), the same for both orders: level $l$ holds the points whose value of $p$ (column +`__spatialdata_p__`) is below `P`. The `P` of level 0 MUST be 1: level 0 holds all the points. +`feature_keys` lists the feature columns, here two, the gene and the cell type: each has its own +feature-major table (see [File layout](#file-layout)), and it is empty if there is none. The +tile-major table is always present. The tile index of level $l$ is `tile_offsets/` (see +[File layout](#file-layout)). ### File layout -Parquet (backward compatible: level 0, tile-major, sits where readers look today): +Parquet (backward compatible: the tile-major table, with every point once, sits where readers look +today, so unlike in Zarr it is not put inside a new group `spatial/`): ```text points// ├── zarr.json # attrs incl. spatial_index -├── points.parquet/ # level 0, tile-major: part.0.parquet, part.1.parquet, … -├── offsets # Zarr int64 array, the tile index of points.parquet/ -├── levels/ # optional, the sampled levels, tile-major -│ ├── 1/ -│ │ ├── points.parquet/ -│ │ └── offsets +├── points.parquet/ # tile-major, all bands: part.0.parquet, part.1.parquet, … +├── tile_offsets/ # Zarr int64 arrays, the tile index of each band +│ ├── 0 +│ ├── 1 │ └── … -└── feature/ # optional, feature-major - ├── 0/ +└── feature/ # optional: one feature-major table per entry of feature_keys + ├── gene/ │ ├── points.parquet/ - │ └── offsets # the feature index - ├── 1/ - │ ├── points.parquet/ - │ └── offsets - └── … + │ └── tile_offsets/ # the feature index: start of each tile of each feature, per band: 0, 1, … + └── cell_type/ + └── … ``` Zarr (the points as a dataframe, see [Columns](#columns)): @@ -567,30 +570,32 @@ Zarr (the points as a dataframe, see [Columns](#columns)): ```text points// ├── zarr.json # attrs incl. spatial_index -├── 0/ # level 0 -│ ├── spatial/ # tile-major -│ │ ├── points/ # df: convention -│ │ │ ├── columns # ["x", "y", "z", "gene", …] -│ │ │ ├── column_0 # x -│ │ │ ├── column_1 # y -│ │ │ ├── column_2 # z -│ │ │ ├── column_3/ # gene, enum: convention -│ │ │ │ ├── codes -│ │ │ │ └── enum_values -│ │ │ └── … # the other columns -│ │ └── offsets # the tile index -│ └── feature/ # optional, feature-major -│ ├── points/ -│ └── offsets # the feature index -└── 1/ # level 1, same layout - └── … +├── spatial/ # tile-major, all bands +│ ├── points/ # df: convention +│ │ ├── columns # ["x", "y", "z", "gene", "__spatialdata_p__", …] +│ │ ├── column_0 # x +│ │ ├── column_1 # y +│ │ ├── column_2 # z +│ │ ├── column_3/ # gene, enum: convention +│ │ │ ├── codes +│ │ │ └── enum_values +│ │ ├── column_4 # __spatialdata_p__ +│ │ └── … # the other columns +│ └── tile_offsets/ # the tile index of each band: 0, 1, … +└── feature/ # optional: one feature-major table per entry of feature_keys + ├── gene/ + │ ├── points/ + │ └── tile_offsets/ # the feature index: start of each tile of each feature, per band: 0, 1, … + └── cell_type/ + └── … ``` -The `offsets` sit next to the dataframe, not inside it: the `df:` convention requires all the -members of the group to be columns of the same length. - -> **TODO(Luca):** pick one layout per format, or prototype both (proposal 4.3). Where the offsets -> live in the Parquet case (Zarr arrays as above, Parquet key-value metadata, or a sidecar Parquet). +In both formats, the offsets (`tile_offsets`, of the tile-major and of the feature-major tables) are Zarr +arrays, the same in Parquet and in Zarr: chunked, so a reader fetches only the chunks of the offsets +it needs. They SHOULD be chunked so that a lookup reads one small chunk: e.g. chunks of 65,536 +entries for the 1-D arrays, and of one feature × 65,536 tiles for the 2-D `tile_offsets` of the feature-major tables, so that +the offsets of one feature are one read. In Zarr, they sit next to the dataframe, not inside it: the `df:` convention requires all +the members of the group to be columns of the same length. ### Columns @@ -600,82 +605,130 @@ members of the group to be columns of the same length. [`enum:` convention](https://github.com/scverse/zarr-convention-enum): the arrays `codes` and `enum_values`, the categories; the number of features is the length of `enum_values`. In Parquet, a dictionary-encoded column. +- $p$: float32 in $[0, 1)$, uniform, in the column `__spatialdata_p__`, a name reserved by + SpatialData, the same in every element. Ties between equal values (float32 has $2^{24}$ values in $[0, 1)$) are harmless: + levels compare $p$ with $P^{(l)}$, and ties may be in any order inside a tile. - Any other columns, unchanged. -In Zarr, the points of each copy of a level are a dataframe following the +In Zarr, each table of points is a dataframe following the [`df:` convention](https://github.com/scverse/zarr-convention-dataframe): one 1-D array, or a group read as one, such as an `enum:` column, per column, all of the same length. -> **TODO(Luca):** in Parquet, the dictionary is stored per row group, so the list of categories, -> which gives the order of `P_feature`, is only known after reading every row group; store it in the -> metadata? - #### Order of the columns -Within the storage unit of a tile, Parquet stores the values column by column: a row group holds +Within a row group, Parquet stores the values column by column: a row group holds the values of the first column, then those of the second, and so on, in the order of the schema. The coordinate columns SHOULD come first and next to each other, in the order of `axes`, followed by -the feature column(s), then by the other columns. A client reading the coordinates and the feature +the feature column(s) and `__spatialdata_p__`, then by the other columns. A client reading the coordinates and the feature of a tile then reads one contiguous byte range instead of one per column. -In Zarr, each column is an array of its own, and chunk $k$ of each array holds tile $k$: a client -reads a tile with one request per column, whatever the order of the columns. The coordinate and +In Zarr, each column is an array of its own, all with the same chunk length, so the same chunks of +each array hold the same rows: a client reads a tile with one request per column and per chunk that +overlaps the tile, whatever the order of the columns. The coordinate and feature columns SHOULD still come first, in the same order as in Parquet. :::{figure} img/0003-columns.svg -:alt: A tall table of three columns x, y, z (blue, red, green) and three tiles of 4, 2 and 3 rows. In Parquet each tile is a row group holding all x values, then all y, then all z, in one byte range. In Zarr each column is an array of its own, column_0 to column_2, and tile 0 is chunk c/0 of each of them, padded to 4 rows. +:alt: A tall table of three columns x, y, z (blue, red, green) and three tiles of 4, 2 and 3 rows. In Parquet, row group 0 holds tile 0 and row group 1 holds tiles 1 and 2; each row group holds all its x values, then all y, then all z, in one byte range. In Zarr each column is an array of its own, column_0 to column_2, cut into chunks of 4 rows independently of the tiles: chunk 0 is tile 0, chunk 1 holds tile 1 and the start of tile 2, chunk 2 the end of tile 2. -The bytes of three tiles in Parquet and in Zarr. Dashed cells are the padding of the regular Zarr -chunks. +The tiles are row ranges. In Parquet the row groups follow the tiles; in Zarr the chunks have a +fixed length and may cut a tile. ::: ### Tile index -To find the points of a tile, a reader uses the tile index of the tile-major copy of the level. Since -the rows are sorted by tile id, the points of each tile are consecutive rows. The index records where -each tile starts: an integer array `offsets` ($O$, int64) with one entry per tile plus one, for -the $N$ tiles of the level. The points of tile $k$ are the rows +To find the points of a tile, a reader uses the tile index of a band of the tile-major table. Since +the rows of a band are sorted by tile id, the points of each tile are consecutive rows. The index of +band $l$, which MUST be written, records where each tile starts: an integer array `tile_offsets/` ($O$, int64) with one entry +per tile plus one, for the $N$ tiles of the grid of level $l$, in rows of the table. The points of +tile $k$ in the band are the rows $$ -[\, O_k,\ O_{k+1} \,), \qquad O_0 = 0, \quad O_N = \text{number of rows}, +[\, O_k,\ O_{k+1} \,), \qquad O_0 = \text{first row of the band}, \quad O_N = \text{end of the band}, $$ -so tile $k$ holds $O_{k+1} - O_k$ points, and an empty tile has $O_k = O_{k+1}$. The reader then reads -the storage unit of the tile: in Parquet, the row group of tile $k$; in Zarr, chunk $k$ of each -column, whose first $O_{k+1} - O_k$ entries are the points and the rest padding. +so tile $k$ holds $n_k = O_{k+1} - O_k$ points, and an empty tile has $O_k = O_{k+1}$. The rows of +the band are $[\, O_0, O_N \,)$: the range of each band follows from its tile index. A reader +reads these rows from the row groups or chunks that overlap them (see +[Points as a tall table](#points-as-a-tall-table)). A client with a budget $b$ +reads the first rows of the tile, until it reaches a row with $p \ge b$. ### Feature index -The feature-major copy of each level has: +Each feature-major table MUST have its own `tile_offsets`, one array per band, as the tile-major +table, but with one row per feature, since inside a band the rows are grouped by feature first: ```text -offsets: int64[n_features + 1] -rows of feature g = [offsets[g], offsets[g + 1]) -rows of feature g, tile k = [feature_tile_offsets[g, k], feature_tile_offsets[g, k + 1]) # optional +tile_offsets/: int64[n_features, N_tiles(l) + 1] # per band l: where each tile of feature g starts +rows of feature g, band l, tile k = [tile_offsets[l][g, k], tile_offsets[l][g, k + 1]) +rows of feature g, band l = [tile_offsets[l][g, 0], tile_offsets[l][g, -1]) +rows of feature g, level l = [tile_offsets[L][g, 0], tile_offsets[l][g, -1]) # bands L..l, one range ``` +The table is sorted by feature, then by band, so the bands $L, \dots, l$ of a feature are one range +of rows: from the first offset of its coarsest band to the last offset of band $l$. In the example +of the orders figure (see +[Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)), with bands 1 +and 0 and the 2 tiles of level 0, gene A has `tile_offsets` [0, 2] in band 1 and [2, 3, 4] in band +0: level 1 is rows $[\,0, 2\,)$ and level 0 rows $[\,0, 4\,)$. Gene B has [4, 5] and [5, 6, 8]. + +These offsets give the rows of a feature in the tiles in view, the number of points of a selection +in view, and let a client skip the tiles where a feature is absent. They have about +$n_\text{features} \times N_\text{tiles}$ entries per band: large for band 0, e.g. about 400 MB as +int64 for 500 genes and $10^5$ tiles, and small for the coarser bands. + > **TODO(Luca):** Ilan suggests writing both orders by default, configurable; the proposal said > "recommended but optional". Pending his answer on the Google Doc comment (transcripts or cell -> matrix?). Also: is `feature_tile_offsets` (n_features × n_tiles, can be large) worth having, or is -> `offsets` enough? +> matrix?). ### Reading ```python -for k in tiles_intersecting(box): # tile ids, see "Tiles ordering" - yield rows(offsets[k], offsets[k + 1]) -# zoomed out: choose the finest level whose expected rows in view ≤ budget +b, l = budget(view, selection) # see "Reading with a budget" +for band in range(L, l - 1, -1): # coarsest band first + for k in tiles_intersecting(view, level=band): # tile ids, see "Tiles ordering" + rows = range(tile_offsets[band][k], tile_offsets[band][k + 1]) + yield prefix(rows, p < b) # rows sorted by p: all of a coarser band; a prefix of band l ``` ### Compatibility - Without `spatial_index` an element reads as today. -- Old readers of a tiled Parquet element read level 0 in spatial order (all points, different row - order) and ignore the rest. +- Old readers of a tiled Parquet element read the tile-major table: every point once, in a + different row order, with an extra column `__spatialdata_p__`. They ignore the rest. > **TODO(Luca):** confirm the current Parquet path (`points.parquet/`) and whether the extra > directories break current readers. +### Summary + +The terms of this RFC in three layers. The data is always there. The data model and the storage +format of the spatial index are optional; the requirements below apply only to an element that has +a spatial index. + +| Layer | Term | Requirement | Section | +| :- | :- | :- | :- | +| Data | the points, one row each, with their coordinates, feature and other columns | always present, as today | [Columns](#columns) | +| Data model | axes | MUST | [Grid and tiles](#grid-and-tiles) | +| | origin $o_a$ and tile size $s_a$ of level 0, per axis | MUST | [Grid and tiles](#grid-and-tiles) | +| | bands $0, \dots, L$ ($L \ge 0$): band 0 always, bands $1, \dots, L$; level $l$ = bands $L, \dots, l$ | MAY | [Levels and bands](#levels-and-bands) | +| | grid of every level present, $0, \dots, L$ | MUST | [Grid and tiles](#grid-and-tiles) | +| | grid of each level refines the grid of the next coarser level (recommended recipe: the merge rule) | MUST | +| | grids get coarser with the level (a level may keep the grid of the level below) | SHOULD | [Grid and tiles](#grid-and-tiles) | +| | tile order: C order of the tile ids | MUST | [Tiles ordering](#tiles-ordering) | +| | random value $p$ per point | MUST | [Priority](#priority) | +| | fraction $P^{(l)}$ of every level present ($P^{(0)} = 1$), a fixed rate (default: ratio of the tile volumes of level 0 and level $l$; any strictly decreasing rates allowed) | MUST | [Sampling](#sampling) | +| | feature column(s) | MAY; at most one SHOULD | [Tile-major order and feature-major order](#tile-major-order-and-feature-major-order) | +| Storage format | metadata: `spatial_index` convention, with its `version` and its `levels` | MUST | [Metadata](#metadata) | +| | Parquet (default) or Zarr (experimental) | MUST, one of them | [Storage format](#storage-format) | +| | column `__spatialdata_p__` | MUST | [Columns](#columns) | +| | tile-major table, levels as bands | MUST | [Levels and bands](#levels-and-bands) | +| | tile index: `tile_offsets` of every band | MUST | [Tile index](#tile-index) | +| | row groups aligned with the tiles (Parquet); chunk length close to the rows of a tile (Zarr) | SHOULD | [Points as a tall table](#points-as-a-tall-table) | +| | feature-major table, one per feature column | MUST, for each feature column | [Tile-major order and feature-major order](#tile-major-order-and-feature-major-order) | +| | feature index: `tile_offsets`, per band, feature and tile | MUST, with a feature-major table | [Feature index](#feature-index) | +| | offsets chunked for small reads (e.g. 65,536 entries; one feature per chunk row) | SHOULD | [File layout](#file-layout) | +| | coordinate and feature columns first | SHOULD | [Order of the columns](#order-of-the-columns) | + ## Related work | Format | Grid | Index | Levels | Second order | @@ -685,19 +738,61 @@ for k in tiles_intersecting(box): # tile ids, see "Tiles ordering" | spatiato ([cache format](https://github.com/vibspatial/spatiato/blob/main/src/spatiato/core/multi_scale_cache_points_zarr/CACHE_FORMAT.md)) | square 2-D | row numbers per level | nested, per-tile cap | feature-major (xy + id) | | Neuroglancer ([annotations](https://github.com/google/neuroglancer/blob/master/src/datasource/precomputed/annotations.md)) | per-axis chunk size, any origin | sharded by Morton code | disjoint, density-preserving | by id, by relationship (all fields) | | Luxar ([format contract](https://github.com/royerlab/luxar/tree/main/format-contract)) | chunk bounds | Hilbert order | disjoint, additive | none | -| zarr-vectors ([docs](https://zarr-vectors-py.readthedocs.io/)) | chunks + bins | chunk | centroid pyramid | none | +| zarr-vectors ([docs](https://zarr-vectors-py.readthedocs.io/)) | chunks + bins | row ranges per bin (fragments) | centroid pyramid | one attribute as chunk key | +| cLoD ([van Oosterom et al., 2022](#references)) | Morton key over (x, y, cLoD) | B+-tree (database) | continuous, random per point, each point once | none | Considered and not chosen: - Image-pixel grid: SpatialData has no pixel space, and points can exist without an image. -- Row groups by formula only: ties the index to Parquet. +- The [zarr-conventions `multiscales`](https://github.com/zarr-conventions/multiscales) convention + for the levels: it adds a dependency on an external convention without adding information. Its + per-level transformations would be the same for every grid: the scale is not used, and its + translation is the `origin` of each level, which is more explicit and fits the scope of this + specification. +- Zarr, a sparse tensor in which each entry is a point: it comes with other compromises and is left + for possible future exploration. +- Row groups by formula only, with one row group per tile, empty tiles included, as in Celldega: the + row counts in the Parquet footers are then the tile offsets, and no offsets need to be stored. + But it ties the index to Parquet, each row group adds to the footer, which is read whole on every + open, and does not scale to grids of $10^5$–$10^6$ tiles per band or to the feature-major table + (one row group per feature, band and tile); a large tile cannot be split either. +- The offsets of the Parquet format in the Parquet key-value metadata: they would be strings + (e.g. base64) in the footer, read and decoded whole on every open, without random access, one + footer per file of a multi-file dataset. +- The offsets of the Parquet format in a sidecar Parquet table: possible, with random access through + the page index, but coarser and less uniformly supported by readers than Zarr chunks, and a + second index format next to the Zarr one. - Tile-relative float32 or uint16 coordinates: can come later as a codec without changing the type. - Zarr, one 2-D array with the columns first, chunked by tile: a chunk would hold the columns of a tile column by column, as a Parquet row group, in one request. But a Zarr array has a single data type, and such an array is not a dataframe; the `df:` convention is used instead. -- zarr-vectors as is: its metadata is a set of top-level attributes with its own version, not a Zarr - convention. This specification is meant to be a self-contained Zarr convention, usable on its own - or next to other conventions (see [Storage format](#storage-format)). +- zarr-vectors (v0.9, under active development) for points. Its model groups the points of a chunk + into bins and indexes each bin by a row range, close to the tile index here, and supports 3-D and + per-axis chunk sizes. What it lacks for this use case: + - sampled levels of the original points: its point-cloud pyramid replaces the points of a bin by + their centroid, and its core does not aggregate the attributes (gene, other columns) of the + merged points; point thinning exists only in a separate tools package; + - a priority per point, or any order inside a bin that supports progressive loading; + - a second, feature-major order next to the spatial one: attribute chunking makes one attribute + (e.g. the gene) part of the chunk key instead, with one key prefix per distinct value (thousands + for genes) and a rechunk to add values; + - Parquet, which SpatialData uses for points today, and a plain dataframe: the vertices of a chunk + are stored as ragged arrays, not as `df:` columns; + - a Zarr convention: its metadata is a set of top-level attributes with its own version. This + specification is meant to be a self-contained Zarr convention, usable on its own or next to other + conventions (see [Storage format](#storage-format)). +- One table per level, each holding again the points of the coarser levels (Neuroglancer stores each + point once; merfisheyes and spatiato repeat them): no bands to combine, but up to 1.33× the points + in 2-D, and switching to a finer level reads the points already shown again. +- $p$ computed from a hash of the point id when reading, instead of stored: reproducible without + storing $p$, but ties the levels to the id and to the hash function; storing $p$ is simpler and + costs 4 bytes per point. A writer may still derive the stored $p$ from a hash (see + [Priority](#priority)). +- A fraction per feature in the feature-major order (each feature sampled on its own): shows rare + features at coarse levels, but distorts relative abundance when several features are shown + together and needs a correction in the client. With one $p$, a client shows a rare feature + completely by reading its finer levels from the feature-major table (see + [Choosing the tile size and the rates](#choosing-the-tile-size-and-the-rates)). ## Implementation @@ -713,4 +808,13 @@ Considered and not chosen: ## References - [RFC 4: Tiled and multiscale shapes](0004-tiled-shapes.md) -- [zarr-conventions multiscales](https://github.com/zarr-conventions/multiscales) +- P. van Oosterom, S. van Oosterom, H. Liu, R. Thompson, M. Meijers, E. Verbree, "Organizing and + visualizing point clouds with continuous levels of detail", *ISPRS Journal of Photogrammetry and + Remote Sensing* 194 (2022) 119–131, [doi:10.1016/j.isprsjprs.2022.10.004](https://doi.org/10.1016/j.isprsjprs.2022.10.004) + ([PDF](https://www.gdmc.nl/publications/2022/cLoD_ISPRS_Journal.pdf), open access, CC BY 4.0). + The cLoD value of a point is drawn from a continuous distribution through a uniform random number, + $l = F^{-1}(U)$; it is a monotone function of $U$, so thresholds on the cLoD value are thresholds + on a uniform priority, as here. The paper declares no patent and no competing interests. +- M. Schütz, K. Krösl, M. Wimmer, "Real-Time Continuous Level of Detail Rendering of Point Clouds", + IEEE VR 2019 ([page](https://cg.tuwien.ac.at/research/publications/2019/schuetz-2019-CLOD)): a + fixed uniform random value per point, to avoid flicker. diff --git a/rfcs/img/0003-columns.svg b/rfcs/img/0003-columns.svg index 3f3064a..f1cd2c4 100644 --- a/rfcs/img/0003-columns.svg +++ b/rfcs/img/0003-columns.svg @@ -1,134 +1,119 @@ - -Columns of a tile in Parquet and in Zarr -tall table -x -y -z - - - - - - - - - - - - + +Columns of the tiles in Parquet and in Zarr +tall table +x +y +z + + + + + + + + + + + + -tile 0 - - - - - - +tile 0 + + + + + + -tile 1 - - - - - - - - - +tile 1 + + + + + + + + + -tile 2 -Parquet: points.parquet/part.0.parquet - - - - - - - - - - - - - -row group 0 - - - - - - - -row group 1 - - - - - - - - - - -row group 2 -a tile is one byte range, column by column: x, then y, then z -Zarr, df: convention: one 1-D array per column -column_0 (x) - - - - - -c/0 - - - - - -c/1 - - - - - -c/2 -column_1 (y) - - - - - -c/0 - - - - - -c/1 - - - - - -c/2 -column_2 (z) - - - - - -c/0 - - - - - -c/1 - - - - - -c/2 -tile 0 (dashed) is chunk c/0 of each array: one request per column +tile 2 +Parquet + + + + + + + + + + + + + +row group 0 +tile 0 + + + + + + + + + + + + + + + + +row group 1 +tiles 1, 2 +Zarr + +tile 0 + +tile 1 + +tile 2 +column_0 + + + + + + + + + + +column_1 + + + + + + + + + + +column_2 + + + + + + + + + + + + +chunk 0 +chunk 1 +chunk 2 diff --git a/rfcs/img/0003-levels-bands.svg b/rfcs/img/0003-levels-bands.svg new file mode 100644 index 0000000..19ec355 --- /dev/null +++ b/rfcs/img/0003-levels-bands.svg @@ -0,0 +1,34 @@ + +Levels and bands + +bands + +2 + +1 + +0 +level 2 + +level 1 + + +level 0 + + + + + + +0 + + +P⁽²⁾ + + +P⁽¹⁾ + + +1 +p + diff --git a/rfcs/img/0003-levels.svg b/rfcs/img/0003-levels.svg deleted file mode 100644 index d899808..0000000 --- a/rfcs/img/0003-levels.svg +++ /dev/null @@ -1,363 +0,0 @@ - -Three levels of a 2-D grid with subsampled points - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -level 0: 4 × 4 tiles -240 points - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -level 1: 2 × 2 tiles -68 points - - - - - - - - - - - - - - - - - - - - - - - - -level 2: 1 × 1 tile -22 points - - diff --git a/rfcs/img/0003-orders.svg b/rfcs/img/0003-orders.svg index e02a3cf..1ea506a 100644 --- a/rfcs/img/0003-orders.svg +++ b/rfcs/img/0003-orders.svg @@ -1,174 +1,111 @@ - -The two orders of the points at two levels -level 0: 2 × 2 tiles - -tile 0 - -tile 1 - -tile 2 - -tile 3 -A -A -B -B -C -A -C -A -A -B -B -A -tile-major order: rows sorted by tile id - -A -0 - -A -0 - -B -0 - -tile 0 - -B -1 - -C -1 - -tile 1 - -A -2 - -A -2 - -C -2 - -tile 2 - -A -3 - -A -3 - -B -3 - -B -3 - -tile 3 -feature-major order: rows sorted by (gene, tile id) - -A -0 - -A -0 - -A -2 - -A -2 - -A -3 - -A -3 - -gene A - -B -0 - -B -1 - -B -3 - -B -3 - -gene B - -C -1 - -C -2 - -gene C -level 1: 1 × 1 tile - -tile 0 -A -A -B -C -C -A -A -B -faded: only in the feature-major copy -tile-major order: rows sorted by tile id, P = 1/3 - -A -0 - -A -0 - -B -0 - -C -0 - -tile 0 -feature-major order: rows sorted by (gene, tile id) - -A -0 - -A -0 - -A -0 - -A -0 - -gene A -P = 2/3 - -B -0 - -B -0 - -gene B -P = 2/3 - -C -0 - -C -0 - -gene C -P = 1 - + +The two orders of the points, as bands +points + +tile 0 + +tile 1 + +A1 +.62 +B2 +.10 +A3 +.21 +B4 +.80 +A5 +.05 +B6 +.47 +A7 +.33 +B8 +.91 +level 1: one tile, p < 0.25 +level 0: two tiles, all points +tile-major: band, tile, p + +A5 +.05 + +B2 +.10 + +A3 +.21 + +A1 +.62 + +B8 +.91 + +A7 +.33 + +B6 +.47 + +B4 +.80 + + +band 1 + +band 0 + +tile 0 + +tile 1 +feature-major: gene, band, tile, p + +A5 +.05 + +A3 +.21 + +A1 +.62 + +A7 +.33 + +B2 +.10 + +B8 +.91 + +B6 +.47 + +B4 +.80 + + +gene A + +band 1 + +tile 0 + +band 0 + +tile 0 + +tile 1 + +gene B + +band 1 + +tile 0 + +band 0 + +tile 0 + +tile 1 diff --git a/rfcs/img/0003-summary.svg b/rfcs/img/0003-summary.svg new file mode 100644 index 0000000..60321b3 --- /dev/null +++ b/rfcs/img/0003-summary.svg @@ -0,0 +1,515 @@ + +Spatial index of points + +Levels, grids and tiles +level 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +8 × 4 tiles · p < 1 +level 1 + + + + + + + + + + + + + + + + + + + + +4 × 2 tiles · p < 0.3 + +level 2 + + + + + + +2 × 1 tiles · p < 0.1 + + +view 1 + + + +view 2 +Random value p + + + +0.1 +0.3 +1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +band 0 + +gene A + +gene B + +gene C (rare) +Tables: one per order, levels as bands + +view 1, all genes + +view 2, gene C +tile-major + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +feature-major + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +band 2 + +band 1 + +band 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +tile_offsets + + + + + + + + + + + + + + + +row groups + + + +gene A + +gene B + +gene C + + + + + + +row groups + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +tile_offsets + + + + + + + + + + + + + + diff --git a/rfcs/img/0003-tile-size.svg b/rfcs/img/0003-tile-size.svg index 1336af8..e1da2c3 100644 --- a/rfcs/img/0003-tile-size.svg +++ b/rfcs/img/0003-tile-size.svg @@ -1,5 +1,5 @@ - -Tile size of level 0 and limit: four cases, limit 40 + +Tile size of level 0 and points per tile: four cases, target 40 @@ -1936,5 +1936,5 @@ 11 (d) hotspot 4 × 4 tiles, densest tile 220 points -limit = 40 points per tile; shaded: tiles above the limit +target: 40 points per tile; shaded: tiles above the target From 443f77f6ffac442379275aba7a4ce2d1b10ca642 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Tue, 17 Nov 2026 22:04:54 +0100 Subject: [PATCH 3/6] RFC 3: add Marco Varrone, Sonja Stockhaus, Brian Long, Clarence Mah to the input from list Co-Authored-By: Claude Opus 5.5 --- rfcs/0003-tiled-points.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rfcs/0003-tiled-points.md b/rfcs/0003-tiled-points.md index 9706b40..940d883 100644 --- a/rfcs/0003-tiled-points.md +++ b/rfcs/0003-tiled-points.md @@ -1,7 +1,7 @@ --- rfc: 3 title: "Tiled and multiscale points" -authors: "Luca Marconato ([@LucaMarconato](https://github.com/LucaMarconato)); input from Nicolas Fernandez ([@cornhundred](https://github.com/cornhundred)), Arne Defauw, Jonas Windhager, Ilan Gold, Ignatius Jenie, Mark Keller, Christian La France, Tim Treis" +authors: "Luca Marconato ([@LucaMarconato](https://github.com/LucaMarconato)); input from Nicolas Fernandez ([@cornhundred](https://github.com/cornhundred)), Arne Defauw, Jonas Windhager, Ilan Gold, Ignatius Jenie, Mark Keller, Christian La France, Tim Treis, Marco Varrone, Sonja Stockhaus, Brian Long, Clarence Mah" status: "draft" type: "data model; storage format" created: 2026-09-17 From 8dfbe31e537a52e73c9ff10dd943767a81522e34 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Thu, 19 Nov 2026 15:00:43 +0100 Subject: [PATCH 4/6] RFC 3 and RFC 4: changes from the Atera implementation RFC 3: sparse (CSR) feature index with a figure (dense shown as not viable); the same layout in Parquet and Zarr (spatial/, feature/), a Parquet sidecar listing the part files, their first rows and the global categories; offsets int32 or int64; p = k / 2^b stored as integers (p_bits); all axes in the grid; tile size for the typical tile and row groups of 100k-1M rows; per-row-group dictionaries; Zarr sharding; full reading pseudo-code; compatibility break; motivation from the benchmarks. RFC 4: optional, only for small shapes (rule of thumb with the kidney numbers); own grid per element, nested grids recommended; margin in spatial_index; table must annotate the shapes, rows in the order of the shapes, X_csc as a SHOULD; single level; limitations and possible extensions for large shapes. Co-Authored-By: Claude Opus 5.5 --- rfcs/0003-tiled-points.md | 471 ++++++++++++++++++++------------ rfcs/0004-tiled-shapes.md | 152 ++++++++--- rfcs/img/0003-feature-index.svg | 149 ++++++++++ 3 files changed, 566 insertions(+), 206 deletions(-) create mode 100644 rfcs/img/0003-feature-index.svg diff --git a/rfcs/0003-tiled-points.md b/rfcs/0003-tiled-points.md index 940d883..db7ed0b 100644 --- a/rfcs/0003-tiled-points.md +++ b/rfcs/0003-tiled-points.md @@ -29,6 +29,17 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be interpreted a [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119). Key words have this meaning only in capitals ([RFC 8174](https://www.rfc-editor.org/rfc/rfc8174)). +### Motivation + +Without an index, a reader can already skip the Parquet row groups whose minimum and maximum +coordinates fall outside a box, and data written in spatially grouped row groups (as by the 10x +Xenium and Atera software) then answer box queries quickly on a local disk: in a test with 1.2 billion +transcripts, a 200 µm box kept 15% of the row groups and scanned 176 million rows to return 0.5 million +points, in 0.2 s on a 14-core laptop with the data in memory. This does not hold remotely, where the +same query reads gigabytes instead of the few megabytes of the tiles in view; it cannot sample, so a +zoomed-out view reads every row group; and it cannot select features, unless the data happen to be sorted +by feature. These are the cases the index is for. + ### Scope - In scope: points, 2-D and 3-D; spatial indexing via chunking and sorting; tile-major order and feature-major order; sampled levels; a per-point random value $p$. @@ -68,7 +79,8 @@ no spatial index at all. If it has one, some of its parts MUST be present, other Parquet or in Zarr: - the metadata declares which parts are present: the orders (tile-major and feature-major), the - levels, and the grid and sampling of each level; + levels, and the grid and sampling of each level; in Parquet, a sidecar JSON file lists the part + files of each table; - each order is one table, with the levels as bands of rows, with offsets that address rows: `tile_offsets` in the tile-major table (the tile index) and in each feature-major table (the feature index), and the column `__spatialdata_p__`, which stores $p$; @@ -76,9 +88,11 @@ Parquet or in Zarr: ### Grid and tiles -A grid is defined for a specific *points element* (the SpatialData term for a 2D/3D points cloud), in the coordinates of its points. The metadata MUST specify the axes of the grid. +A grid is defined for a specific *points element* (the SpatialData term for a 2D/3D points cloud), in the coordinates of its points. The metadata MUST specify the axes of the grid, and the grid MUST have all the spatial axes of the element; it MAY have a single tile along an axis, for instance along $z$ for a thin section of tissue. -Different elements use different grids: reusing the same grid for 2 or more elements is out of scope for this RFC ([RFC 4](0004-tiled-shapes.md) will discuss reusing the same grid for points (transcripts) and shapes (cells)). +Each element has its own grid, chosen for its own data: two elements, for instance the transcripts and +the cells of a dataset, do not have to share a grid (see [RFC 4](0004-tiled-shapes.md) for the shapes, +which recommends nested grids when a client loads both tile by tile). An axis $a$ is one of the spatial axes $x$, $y$ and $z$ (not the channel axis $c$). The grid has, per axis $a$, an arbitrary origin $o_a$, which MUST be given (for instance the corner with the minimum coordinates of the bounding box @@ -224,7 +238,18 @@ from the continuous level of detail of [van Oosterom et al., 2022](#references) [Schütz et al., 2019](#references). It is drawn once when the points are written and MUST be stored with them, as a column (see [Columns](#columns)). Any uniform random generator may be used, and $p$ may be derived from a hash of the point. The priority is fixed: it defines which points are in which -level, and the order of the rows inside a tile, in both orders of the points. +level, and the order of the rows inside a tile, in both orders of the points. When an element that +already has $p$ is indexed again (another tile size, the other format, a new feature-major table), +writers MUST keep its $p$, so that the levels hold the same points. + +$p$ MUST be of the form $k / 2^{b}$, with $k$ an integer in $[0, 2^{b})$ and $b$ the precision declared +in the metadata (`p_bits`, see [Columns](#columns)): it is stored as $k$, and comparisons with the +fractions $P^{(l)}$ are then exact. Writers SHOULD draw $k$ directly as a random integer. Drawing a real +number and rounding it is a common mistake: for instance, a value $u = 0.99999999$ drawn in $[0, 1)$ in +double precision becomes exactly 1 when rounded to single precision (float32 has 24 bits of precision, +so every $u \ge 1 - 2^{-25}$ rounds to 1), and $p = 1$ belongs to no level, since level 0 holds the +points with $p < P^{(0)} = 1$. In the same way, rounding can move a value across a fraction $P^{(l)}$, +so that the band of a point computed before and after rounding disagree. ### Levels and bands @@ -360,22 +385,27 @@ reasoning: with the coordinates and a feature code, about 16 bytes per point, a about 160,000 points, which a browser renders easily. The target is not stored in the metadata and is not a cap: level 0 holds all the points, and a tile may hold any number of them. -The tile size of level 0 should then be chosen so that the densest tile of level 0 holds about the -target number of points: $n^{(0)}$, the number of points per tile of level 0 (see -[Sampling](#sampling)), about equal to the target in the densest region. If the densest region has $\rho$ points per unit of area (2-D) or -volume (3-D), the tile size along each of the $d$ axes is about +The tile size of level 0 SHOULD be chosen for the *typical* tile, not for the densest one: the median +number of points per non-empty tile of level 0 SHOULD be about the target, between 5,000 and 20,000, +which usually gives $10^4$ to $10^5$ tiles at level 0. If the typical region has $\rho$ points per unit +of area (2-D) or volume (3-D), the tile size along each of the $d$ axes is about $$ s \approx \left( \frac{n^{(0)}}{\rho} \right)^{1/d}. $$ -This estimate assumes that the points are roughly uniformly distributed at the scale of a tile, and -that the tiles are isotropic. Larger-scale variations are taken into account by using the density of -the densest region; a hotspot smaller than a tile is not (see case (d) below). In practice, a writer -can also pick a tile size, count the points of the densest tile, and adjust. - -With the default rates, $n^{(l)} = n^{(0)}$: the densest tiles then hold about the target number of -points at every level (see [Sampling](#sampling)). What is stored per tile is a band, a part of its level: band $l$ holds a +This estimate assumes that the tiles are isotropic. In practice, a writer can pick a tile size, compute +the median number of points of the non-empty tiles, and adjust. Real data are uneven: sizing the tiles +for the densest tile makes the typical tile far too small. In two 10x Atera datasets (740 million and +1.2 billion transcripts), tiles sized so that the densest tile holds 10,000 points were 7–9 µm wide, with +a median of 200–350 points per tile and 0.8 to 1.9 million tiles; tiles of 27–35 µm give a median of +6,000–9,000 points and 50,000–120,000 tiles. The densest tiles then hold about 100,000 points, which is +not a problem: the rows of a tile are sorted by $p$, so a client reads only as many of them as its budget +allows (see [Reading with a budget](#reading-with-a-budget)), and the storage splits large tiles into +several row groups or chunks (see [Points as a tall table](#points-as-a-tall-table)). + +With the default rates, $n^{(l)} = n^{(0)}$: the tiles then hold about the same number of points at +every level (see [Sampling](#sampling)). What is stored per tile is a band, a part of its level: band $l$ holds a fraction $1 - P^{(l+1)} / P^{(l)}$ of the level-$l$ points of the tile (3/4 in 2-D with all axes merged). @@ -392,7 +422,7 @@ The tile size of level 0 for a target of 40 points per tile, on 400 points. The figure shows the edge cases: -- (a) Tiles that fit: the densest tile holds about the target number of points. +- (a) Tiles that fit: the typical tile holds about the target number of points. - (b) Tiles too large: the tiles of level 0 hold far more points than the target. Level 0 is not sampled, but a client zoomed in does not have to load a whole tile: its rows are sorted by $p$, so the first rows are a fair sample of it (see [Reading with a budget](#reading-with-a-budget)), and @@ -405,13 +435,14 @@ The figure shows the edge cases: level. - (d) Hotspot: a region much denser than the rest puts many points in a few tiles. A tile size chosen for the hotspot is too small elsewhere, as in (c); one chosen for the rest is too large in - the hotspot, as in (b), and handled as in (b). A future extension could address this with an - adaptive grid, if the community identifies it as a need. + the hotspot, as in (b), and handled as in (b): this is why the tile size is chosen for the typical + tile. A future extension could address this with an adaptive grid, if the community identifies it as + a need. The grid and the rates are the same for all the features, so a rare feature has few points per tile, and at the coarser levels few or none: in the feature-major table most of its tiles are empty. -This is not a problem: an empty tile holds no rows and costs only its entry in -the `tile_offsets` of the feature-major table, and the rows of a feature are contiguous, sorted by band, so a client showing +This is not a problem: an empty tile holds no rows and costs nothing in the feature index, which +stores only the non-empty tiles of each feature (see [Feature index](#feature-index)), and the rows of a feature are contiguous, sorted by band, so a client showing a rare feature reads all its levels, down to level 0, as one contiguous range. #### Reading with a budget @@ -432,6 +463,10 @@ default, and the Zarr format as experimental. Whether the Zarr format replaces i feedback and real usage; Zarr would also be more flexible for 3-D shapes (meshes, see [RFC 4](0004-tiled-shapes.md)) and closer to zarr-vectors (see [Related work](#related-work)). +The two formats have the same layout and the same metadata; they differ only in how a table of points is +stored (Parquet files or a Zarr dataframe), and Parquet adds one file of its own, the Parquet sidecar (see +[Metadata](#metadata)). The offsets are Zarr arrays in both formats. + The format is self-contained: compatible with the way OME-NGFF stores coordinate systems, but usable on its own, even outside an OME-Zarr store, because its metadata is defined as a Zarr convention. Compatible means that this storage of points could in the future be proposed as an OME-NGFF @@ -440,8 +475,6 @@ extension, with the extensibility mechanism of part of the OME-NGFF specification. This is not a goal for now: for the time being this specification remains part of SpatialData, and is neither an official OME-NGFF extension nor OME-NGFF compliant. -Parquet has no equivalent of Zarr conventions, so the Parquet format reuses the same syntax for its -metadata. The spatial index is optional (see [Overview](#overview)). Without it, an element is stored as today (see [Compatibility](#compatibility)). With it, the metadata declares which parts are present (see @@ -451,29 +484,32 @@ The spatial index is optional (see [Overview](#overview)). Without it, an elemen In both formats, each table of points is a tall table: one row per point, one column per attribute. The tile index and the feature index address rows (see [Tile index](#tile-index), -[Feature index](#feature-index)). How the rows are split into row groups (Parquet) or chunks (Zarr) -is a choice of the writer, not declared by this convention: Parquet row groups may have any size, -and the footers of the files give their row counts; Zarr chunks have the chunk length of the array, -given in its metadata. A reader maps a range of rows to the row groups or chunks that overlap it: in -Zarr, with chunk length $c$, the rows $[\,a, b\,)$ are in the chunks $\lfloor a / c \rfloor, \dots, -\lfloor (b - 1) / c \rfloor$. A row group or chunk may hold several small tiles, and a large tile may -span several. The row groups are grouped into the part files of a multi-file Parquet dataset; the -chunks into shards in Zarr. - -To read a tile with few requests: - -- Parquet writers SHOULD align the boundaries of the row groups with those of the tiles: one row - group per tile of a band when the tile is large enough, several small tiles in one row group to - avoid tiny row groups, and a large tile split into several. In the feature-major table, the same - with the groups of rows of one feature in one band. -- Zarr writers SHOULD choose a chunk length close to the typical number of rows of a tile. - -These are recommendations and not requirements because no single layout fits all the data, and the -index addresses rows, so any layout is readable. In the tile-major table, one row group per tile -would give tiny row groups in sparse regions and in the coarse bands, and huge ones in hotspots. In -the feature-major table, one row group per feature, band and tile would give up to -$n_\text{features} \times N_\text{tiles} \times (L + 1)$ row groups, e.g. 500 genes × $10^5$ -tiles = up to $5 \cdot 10^7$, almost all tiny; one per feature and band gives a few thousand. +[Feature index](#feature-index)), so how the rows are grouped into row groups (Parquet) or chunks (Zarr) +does not change the index: a row group or a chunk may hold several small tiles, and a large tile may +span several. A reader maps a range of rows to the row groups or chunks that overlap it: in Zarr, with +chunk length $c$, the rows $[\,a, b\,)$ are in the chunks $\lfloor a / c \rfloor, \dots, +\lfloor (b - 1) / c \rfloor$; in Parquet, through the part files of the table (see +[Metadata](#metadata)) and the row counts in their footers. A range of rows MAY span several row groups, +chunks, part files or shards, and readers MUST support it. + +The row groups and chunks are a choice of the writer, guided by two costs. Each row group or chunk is +one unit of reading: a tile smaller than it costs the read of its neighbours, so they should not be much +larger than the tiles in view. Each row group also adds an entry, per column, to the footer of its +Parquet file, which a reader parses before it reads any row of that file: tiny row groups make the +footers large (with one row group of about 10,000 rows per tile, 740 million points give 67,000 row +groups and footers of about 2.6 MB per part file). Recommendations: + +- Parquet writers SHOULD use row groups of about 100,000 to 1,000,000 rows (a few MB compressed), each + holding several consecutive tiles, and SHOULD split a larger tile into several row groups. A row group + SHOULD start at the start of a tile. In the feature-major table, the same with the rows of one feature + in one band. +- Parquet writers SHOULD start a new part file only at the start of a tile of a band (tile-major table) + or of a feature in a band (feature-major table), so that the rows of a tile are in a single file. +- Zarr writers SHOULD choose a chunk length of the same order as the rows of a typical tile, and SHOULD + store the chunks in shards (Zarr sharding codec), e.g. of a few million rows: with chunks of one tile + and no shards, a table has one object per chunk and per column (about 74,000 per column for 740 + million points). Writers MUST NOT write the same shard concurrently from several processes or threads + without coordination: a partial write of a shard rewrites the whole shard. Another option in Zarr is rectilinear chunk grids, an experimental Zarr feature that allows chunks of different sizes along an array: each tile would then be one chunk of its own size. @@ -483,22 +519,42 @@ a grid with a single tile covering all the points, the same at every level (see [Grid and tiles](#grid-and-tiles)). Each band is then one range of rows sorted by $p$, so any first rows of a band are a uniform sample of it, which a reader can load progressively. -### Metadata +### File layout -Both formats store the metadata in the `zarr.json` of the Zarr group of the points element. In the -Zarr format the points are Zarr arrays inside that group; in the Parquet format they are Parquet -files inside that group (see [File layout](#file-layout)): +The two formats have the same layout; only the tables differ (Parquet files or a Zarr dataframe, see +[Columns](#columns)): ```text points// -├── zarr.json # the metadata, in both formats -└── … # the points: Zarr arrays, or Parquet files +├── zarr.json # attrs incl. spatial_index +├── spatial_index.parquet.json # Parquet only: the Parquet sidecar +├── spatial/ # tile-major order, all bands +│ ├── points.parquet/ # Parquet: part files, listed in the sidecar +│ │ ├── part.000000000000.parquet +│ │ └── … +│ ├── points/ # Zarr instead: df: convention +│ │ ├── columns # ["x", "y", "z", "gene", "__spatialdata_p__", …] +│ │ ├── column_0 # x +│ │ ├── … +│ │ └── column_3/ # gene, enum: convention (codes, enum_values) +│ └── tile_offsets/ # the tile index of each band: 0, 1, … (Zarr arrays) +└── feature/ # optional: one feature-major table per entry of feature_keys + └── gene/ + ├── points.parquet/ # Parquet; or points/ (Zarr) + └── tile_offsets/ # the feature index of each band: 0, 1, … (Zarr groups) ``` -The metadata is a Zarr convention, `spatial_index`, next to the existing attributes of the element. -It is registered in `zarr_conventions` with its name and the URL of this specification; the uuid and -a JSON schema are optional and will be added when the convention is released. `levels` lists the -levels present, level 0 first, each with its grid and, for the coarser levels, its fraction: +In Zarr, the offsets sit next to the dataframe, not inside it: the `df:` convention requires all the +members of the group to be columns of the same length. The offsets SHOULD be chunked so that a lookup +reads one small chunk, e.g. 65,536 entries. + +### Metadata + +The metadata is a Zarr convention, `spatial_index`, in the `zarr.json` of the Zarr group of the points +element, next to the existing attributes of the element, the same in both formats. It is registered in +`zarr_conventions` with its name and the URL of this specification; the uuid and a JSON schema are +optional and will be added when the convention is released. `levels` lists the levels present, level 0 +first, each with its grid and its fraction: ```json { @@ -512,21 +568,23 @@ levels present, level 0 first, each with its grid and, for the coarser levels, i "spatial_index": { "version": "0.1.0-draft", "axes": ["x", "y", "z"], - "feature_keys": ["gene", "cell_type"], + "feature_keys": ["gene"], + "p_bits": 16, "levels": [ { "origin": [0.0, 0.0, 0.0], - "tile_size": [100.0, 100.0, 10.0], - "grid_shape": [120, 80, 3], + "tile_size": [35.0, 35.0, 40.0], + "grid_shape": [280, 170, 1], "P": 1.0 }, { "origin": [0.0, 0.0, 0.0], - "tile_size": [200.0, 200.0, 20.0], - "grid_shape": [60, 40, 2], - "P": 0.125 + "tile_size": [70.0, 70.0, 40.0], + "grid_shape": [140, 85, 1], + "P": 0.25 } - ] + ], + "parquet": "spatial_index.parquet.json" } } ``` @@ -535,67 +593,51 @@ levels present, level 0 first, each with its grid and, for the coarser levels, i readers can tell future versions (e.g. with tiles in Morton order) apart. While this RFC is a draft, the version carries the suffix `-draft`. Following the versioning of Zarr conventions, a released version will also be referenced by a `spec_url` (and `schema_url`) pinned to that version, e.g. a -tagged URL. `levels[l]` gives the grid of level $l$: `origin`, `tile_size` and `grid_shape` (the -number of tiles $n_a$ along each axis). `P` is the fraction $P^{(l)}$ of the level (here 1/8, the -default in 3-D), the same for both orders: level $l$ holds the points whose value of $p$ (column -`__spatialdata_p__`) is below `P`. The `P` of level 0 MUST be 1: level 0 holds all the points. -`feature_keys` lists the feature columns, here two, the gene and the cell type: each has its own -feature-major table (see [File layout](#file-layout)), and it is empty if there is none. The -tile-major table is always present. The tile index of level $l$ is `tile_offsets/` (see -[File layout](#file-layout)). - -### File layout - -Parquet (backward compatible: the tile-major table, with every point once, sits where readers look -today, so unlike in Zarr it is not put inside a new group `spatial/`): +tagged URL. `axes` MUST list all the spatial axes of the element (see [Grid and tiles](#grid-and-tiles)). +`levels[l]` gives the grid of level $l$: `origin`, `tile_size` and `grid_shape` (the number of tiles +$n_a$ along each axis, here a single tile along z). `P` is the fraction $P^{(l)}$ of the level (here 1/4, +the default in 2-D tiles), the same for both orders: level $l$ holds the points whose value of $p$ is +below `P`. The `P` of level 0 MUST be 1: level 0 holds all the points. `p_bits` is the precision of $p$ +(see [Columns](#columns)). `feature_keys` lists the feature columns, each with its own feature-major +table (see [File layout](#file-layout)); it is empty if there is none. The tile-major table is always +present. + +`parquet` is present only in the Parquet format: the path, relative to the element, of the *Parquet +sidecar*, a JSON file that holds what exists only because the Parquet tables are split into several +files: -```text -points// -├── zarr.json # attrs incl. spatial_index -├── points.parquet/ # tile-major, all bands: part.0.parquet, part.1.parquet, … -├── tile_offsets/ # Zarr int64 arrays, the tile index of each band -│ ├── 0 -│ ├── 1 -│ └── … -└── feature/ # optional: one feature-major table per entry of feature_keys - ├── gene/ - │ ├── points.parquet/ - │ └── tile_offsets/ # the feature index: start of each tile of each feature, per band: 0, 1, … - └── cell_type/ - └── … -``` - -Zarr (the points as a dataframe, see [Columns](#columns)): - -```text -points// -├── zarr.json # attrs incl. spatial_index -├── spatial/ # tile-major, all bands -│ ├── points/ # df: convention -│ │ ├── columns # ["x", "y", "z", "gene", "__spatialdata_p__", …] -│ │ ├── column_0 # x -│ │ ├── column_1 # y -│ │ ├── column_2 # z -│ │ ├── column_3/ # gene, enum: convention -│ │ │ ├── codes -│ │ │ └── enum_values -│ │ ├── column_4 # __spatialdata_p__ -│ │ └── … # the other columns -│ └── tile_offsets/ # the tile index of each band: 0, 1, … -└── feature/ # optional: one feature-major table per entry of feature_keys - ├── gene/ - │ ├── points/ - │ └── tile_offsets/ # the feature index: start of each tile of each feature, per band: 0, 1, … - └── cell_type/ - └── … +```json +{ + "tables": { + "spatial": { + "files": ["spatial/points.parquet/part.000000000000.parquet", + "spatial/points.parquet/part.000020000564.parquet", "…"], + "first_row": [0, 20000564, "…", 740442119] + }, + "feature/gene": { + "files": ["feature/gene/points.parquet/part.000000000000.parquet", "…"], + "first_row": [0, "…", 740442119], + "categories": ["ACTA2", "CD3E", "…"] + } + } +} ``` -In both formats, the offsets (`tile_offsets`, of the tile-major and of the feature-major tables) are Zarr -arrays, the same in Parquet and in Zarr: chunked, so a reader fetches only the chunks of the offsets -it needs. They SHOULD be chunked so that a lookup reads one small chunk: e.g. chunks of 65,536 -entries for the 1-D arrays, and of one feature × 65,536 tiles for the 2-D `tile_offsets` of the feature-major tables, so that -the offsets of one feature are one read. In Zarr, they sit next to the dataframe, not inside it: the `df:` convention requires all -the members of the group to be columns of the same length. +- `files` MUST list the part files of each table, in order, relative to the element: the rows of the + table are the rows of these files, one file after the other. Readers MUST NOT rely on the order in + which a directory lists the files, and writers SHOULD zero-pad the numbers in the file names (as + above), so that tools that list and sort the directory read the files in the same order. +- `first_row[i]` is the first row of `files[i]` in the table, and the last entry is the number of rows + of the table (`len(first_row) == len(files) + 1`). A reader finds the file that holds a row from it, + and opens only the footers of the files it reads. +- `categories` (feature-major tables): the global category list of the feature column, in the order of + the codes of the feature index (see [Feature index](#feature-index)). In Zarr the global list is the + `enum_values` of the feature column, so it needs no sidecar. + +The sidecar is kept out of `zarr.json` for two reasons: it grows with the number of part files (about 45 +bytes per file, plus the categories), while `spatial_index` stays small, and keeping it apart makes clear +which parts of the format are specific to Parquet. With part files of millions of rows, it is a few +kilobytes for most datasets. ### Columns @@ -604,11 +646,26 @@ the members of the group to be columns of the same length. - Feature: integer codes with the category list stored once. In Zarr, the column follows the [`enum:` convention](https://github.com/scverse/zarr-convention-enum): the arrays `codes` and `enum_values`, the categories; the number of features is the length of `enum_values`. In - Parquet, a dictionary-encoded column. -- $p$: float32 in $[0, 1)$, uniform, in the column `__spatialdata_p__`, a name reserved by - SpatialData, the same in every element. Ties between equal values (float32 has $2^{24}$ values in $[0, 1)$) are harmless: - levels compare $p$ with $P^{(l)}$, and ties may be in any order inside a tile. -- Any other columns, unchanged. + Parquet, a dictionary-encoded column. Parquet stores the dictionary of a column once per row group, so + the dictionary of a row group SHOULD hold only the categories present in that row group, in any order: + with tens of thousands of features, a full dictionary in every row group dominates the size of the + table (9.3 GB of 23 GB in a test with 27,000 genes and one row group per tile). The codes inside a row + group are then local to it; the codes of the feature index refer to the global list of the Parquet + sidecar. Writers SHOULD keep the pandas metadata in the schema of the Parquet files, so that readers + such as dask read the column as a categorical (the per-row-group dictionaries are unified when + reading). +- $p$: in the column `__spatialdata_p__`, a name reserved by SpatialData, the same in every element, + stored as an unsigned integer $k$, with $p = k / 2^{b}$ and $b$ = `p_bits` of the metadata: uint16 for + $b = 16$ (recommended), uint32 for $b = 24$ or $32$ (see [Priority](#priority)). The levels need + $P^{(L)} \ge 2^{4 - b}$, so that the coarsest level still holds a fraction close to $P^{(L)}$: with + $b = 16$ and the default rates in 2-D, at most 6 levels besides level 0; more levels need $b = 24$. + Ties between equal values are harmless: levels compare $p$ with $P^{(l)}$, and ties may be in any + order inside a tile. +- Any other columns, unchanged. An identifier column of the points (e.g. `transcript_id`) is not needed + by the index, and writers MAY drop it: points are usually not annotated by a table, and their only + relationship, being within a cell, is either computed when needed (a spatial join) or stored as a + column of the points. Sorting by tile also removes most of the compression of a sequential identifier + (3.8 GB in the test above). In Zarr, each table of points is a dataframe following the [`df:` convention](https://github.com/scverse/zarr-convention-dataframe): one 1-D array, or a group @@ -620,7 +677,10 @@ Within a row group, Parquet stores the values column by column: a row group hold the values of the first column, then those of the second, and so on, in the order of the schema. The coordinate columns SHOULD come first and next to each other, in the order of `axes`, followed by the feature column(s) and `__spatialdata_p__`, then by the other columns. A client reading the coordinates and the feature -of a tile then reads one contiguous byte range instead of one per column. +of a tile then reads one contiguous byte range instead of one per column. This is also the column order +of the Celldega profile ([PR #423](https://github.com/scverse/spatialdata-io/pull/423)), where it makes +column projection and filtering in the browser more efficient with +[parquet-wasm](https://github.com/kylebarron/parquet-wasm/pull/811). In Zarr, each column is an array of its own, all with the same chunk length, so the same chunks of each array hold the same rows: a client reads a tile with one request per column and per chunk that @@ -638,43 +698,72 @@ fixed length and may cut a tile. To find the points of a tile, a reader uses the tile index of a band of the tile-major table. Since the rows of a band are sorted by tile id, the points of each tile are consecutive rows. The index of -band $l$, which MUST be written, records where each tile starts: an integer array `tile_offsets/` ($O$, int64) with one entry -per tile plus one, for the $N$ tiles of the grid of level $l$, in rows of the table. The points of -tile $k$ in the band are the rows +band $l$, which MUST be written, records where each tile starts: an integer array `tile_offsets/` +($O$) with one entry per tile plus one, for the $N$ tiles of the grid of level $l$, in rows of the table. +The points of tile $k$ in the band are the rows $$ [\, O_k,\ O_{k+1} \,), \qquad O_0 = \text{first row of the band}, \quad O_N = \text{end of the band}, $$ -so tile $k$ holds $n_k = O_{k+1} - O_k$ points, and an empty tile has $O_k = O_{k+1}$. The rows of -the band are $[\, O_0, O_N \,)$: the range of each band follows from its tile index. A reader -reads these rows from the row groups or chunks that overlap them (see -[Points as a tall table](#points-as-a-tall-table)). A client with a budget $b$ -reads the first rows of the tile, until it reaches a row with $p \ge b$. +so tile $k$ holds $n_k = O_{k+1} - O_k$ points. An empty tile has $O_k = O_{k+1}$: it repeats the +offset of the next tile, so that the formula holds for every $k$ and the end of a tile is always the +start of the next. The rows of the band are $[\, O_0, O_N \,)$: the range of each band follows from its +tile index. A reader reads these rows from the row groups or chunks that overlap them (see +[Points as a tall table](#points-as-a-tall-table)). A client with a budget $b$ reads the first rows of +the tile, until it reaches a row with $p \ge b$. + +The offsets are global row numbers of the table, in both formats. Their integer type MAY be the smallest +that holds the number of rows of the table: int32 below $2^{31}$ rows, int64 otherwise; readers take it +from the metadata of the Zarr array. The same holds for the arrays of the feature index. ### Feature index -Each feature-major table MUST have its own `tile_offsets`, one array per band, as the tile-major -table, but with one row per feature, since inside a band the rows are grouped by feature first: +Each feature-major table MUST have its own feature index, per band. Inside a band the rows of the table +are grouped by feature, then by tile, so the points of feature $g$ in tile $k$ are one range of rows. +Most features are absent from most tiles, and the index stores only the non-empty tiles of each +feature, as a CSR (compressed sparse row) structure over the features: a Zarr group +`tile_offsets/` with three arrays, ```text -tile_offsets/: int64[n_features, N_tiles(l) + 1] # per band l: where each tile of feature g starts -rows of feature g, band l, tile k = [tile_offsets[l][g, k], tile_offsets[l][g, k + 1]) -rows of feature g, band l = [tile_offsets[l][g, 0], tile_offsets[l][g, -1]) -rows of feature g, level l = [tile_offsets[L][g, 0], tile_offsets[l][g, -1]) # bands L..l, one range +tile_offsets//feature_ptr: [n_features + 1] # entries of feature g: feature_ptr[g] … feature_ptr[g+1] - 1 +tile_offsets//tile_ids: [nnz] # the non-empty tiles of each feature, increasing +tile_offsets//row_offsets: [nnz + n_features] # their first row, + the end of the feature in the band ``` -The table is sorted by feature, then by band, so the bands $L, \dots, l$ of a feature are one range -of rows: from the first offset of its coarsest band to the last offset of band $l$. In the example -of the orders figure (see -[Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)), with bands 1 -and 0 and the 2 tiles of level 0, gene A has `tile_offsets` [0, 2] in band 1 and [2, 3, 4] in band -0: level 1 is rows $[\,0, 2\,)$ and level 0 rows $[\,0, 4\,)$. Gene B has [4, 5] and [5, 6, 8]. +For feature $g$, with $a$ = `feature_ptr[g]` and $e$ = `feature_ptr[g+1]`, the non-empty tiles are +`tile_ids[a:e]`, and the $j$-th of them holds the rows +`[row_offsets[a + g + j], row_offsets[a + g + j + 1])`; the last entry of the feature, +`row_offsets[e + g]`, is the end of its rows in the band. This extra end entry plays the role of the +repeated offsets of the tile index: the end of a tile is the start of the next one, and the end of the +last one is given explicitly, so that every non-empty tile is one range found in one array. A feature +without points in band $l$ has no entries in `tile_ids` and a single entry in `row_offsets`: the row where +its range would start. With it, the rows of feature $g$ in band $l$ are always +`[row_offsets[a + g], row_offsets[e + g])`, and, since the table is sorted by feature then band +(coarsest first), the rows of feature $g$ at level $l$ (bands $L, \dots, l$) are one range, from the +start of $g$ in band $L$ to the end of $g$ in band $l$. + +:::{figure} img/0003-feature-index.svg +:alt: Top, a feature-major table of one band with 11 rows: gene A in tiles 0, 2 and 5 (rows 0 to 5), gene B in tile 3 (rows 6 to 9), gene C in tile 1 (row 10). Left, the dense layout, a 3 by 7 matrix with an offset for every gene and every tile; the cells of empty tiles repeat the next offset and are greyed out; for the breast dataset this would be 27,104 by 759,595 entries for band 0. Right, the sparse layout used here: feature_ptr [0, 3, 4, 5], tile_ids [0, 2, 5, 3, 1] and row_offsets [0, 2, 3, 6, 6, 10, 10, 11]. Bottom, the rows of gene A in tile 5 found both ways: rows 3 to 6. + +The feature index of one band. Left, for explanation only, a dense matrix with an offset for every +feature and every tile, the end of each tile being the start of the next. It is not part of the format: +it does not scale to whole-transcriptome panels (27,104 genes on a grid of 760,000 tiles would be +$2 \cdot 10^{10}$ entries, about 165 GB, for one band). Right, the format: only the non-empty tiles of +each feature. +::: + +The codes $g$ are the positions of the features in the global category list: the `enum_values` of the +feature column in Zarr, the `categories` of the Parquet sidecar in Parquet. In the example of the orders +figure (see [Tile-major order and feature-major order](#tile-major-order-and-feature-major-order)), +with bands 1 and 0 and the 2 tiles of level 0, band 1 has `feature_ptr` [0, 1, 2], `tile_ids` [0, 0] and +`row_offsets` [0, 2, 4, 5] (gene A: tile 0, rows 0 to 2; gene B: tile 0, rows 4 to 5), and band 0 has +`feature_ptr` [0, 2, 4], `tile_ids` [0, 1, 0, 1] and `row_offsets` [2, 3, 4, 5, 6, 8] (gene A: rows 2 to 3 +in tile 0 and 3 to 4 in tile 1; gene B: 5 to 6 and 6 to 8). Level 1 of gene A is rows +$[\,0, 2\,)$ and level 0 rows $[\,0, 4\,)$. -These offsets give the rows of a feature in the tiles in view, the number of points of a selection -in view, and let a client skip the tiles where a feature is absent. They have about -$n_\text{features} \times N_\text{tiles}$ entries per band: large for band 0, e.g. about 400 MB as -int64 for 500 genes and $10^5$ tiles, and small for the coarser bands. +The index has about one entry per non-empty pair of feature and tile: in a test with 740 million +points, 27,104 genes and 760,000 tiles, 0.5 GB for all the bands. > **TODO(Luca):** Ilan suggests writing both orders by default, configurable; the proposal said > "recommended but optional". Pending his answer on the Google Doc comment (transcripts or cell @@ -682,22 +771,40 @@ int64 for 500 genes and $10^5$ tiles, and small for the coarser bands. ### Reading +A client chooses a budget from the number of points in view, counted from the offsets without reading +any point, then reads the bands from the coarsest one, from the feature-major table if it shows only +some features and the table exists, otherwise from the tile-major table: + ```python -b, l = budget(view, selection) # see "Reading with a budget" -for band in range(L, l - 1, -1): # coarsest band first - for k in tiles_intersecting(view, level=band): # tile ids, see "Tiles ordering" - rows = range(tile_offsets[band][k], tile_offsets[band][k + 1]) - yield prefix(rows, p < b) # rows sorted by p: all of a coarser band; a prefix of band l +n = count_in_view(view, selection) # from the offsets, see below +b = min(1, max_points / n) # the budget, see "Reading with a budget" +l = coarsest level with P(l) >= b +if selection.features and selection.feature_key in feature_keys: + for band in range(L, l - 1, -1): # feature index of that table + for g in selection.features: + for k in non_empty_tiles(g, band) ∩ tiles_intersecting(view, level=band): + yield prefix(rows_of(g, k, band), p < b) +else: # tile-major table + for band in range(L, l - 1, -1): + for k in tiles_intersecting(view, level=band): + yield prefix(range(tile_offsets[band][k], tile_offsets[band][k + 1]), p < b) +# then: drop the points outside the view (tiles cross its edges), and, from the +# tile-major table, the points of the features not shown ``` -### Compatibility +`prefix(rows, p < b)`: the rows of a tile are sorted by $p$, so the points with $p < b$ are its first +rows; a reader finds where they end from the `__spatialdata_p__` column of the tile (e.g. by a binary +search). `count_in_view` sums $O_{k+1} - O_k$ over the tiles in view, each weighted by the part of the +tile that lies in the view: the tiles of the coarse bands are larger than the view, and counting them +whole overestimates the points in view by orders of magnitude when zoomed in. -- Without `spatial_index` an element reads as today. -- Old readers of a tiled Parquet element read the tile-major table: every point once, in a - different row order, with an extra column `__spatialdata_p__`. They ignore the rest. +### Compatibility -> **TODO(Luca):** confirm the current Parquet path (`points.parquet/`) and whether the extra -> directories break current readers. +- Without `spatial_index` an element is stored as today, and reads as today. +- An element with `spatial_index` is a new version of the points format (see the versions of SpatialData): + it is not readable by older readers, and the tables are under `spatial/` and `feature/`, the same + layout in Parquet and in Zarr. A reader that does not use the index can still read the points from the + tile-major table: every point once, sorted by band and tile, with the extra column `__spatialdata_p__`. ### Summary @@ -708,26 +815,30 @@ a spatial index. | Layer | Term | Requirement | Section | | :- | :- | :- | :- | | Data | the points, one row each, with their coordinates, feature and other columns | always present, as today | [Columns](#columns) | -| Data model | axes | MUST | [Grid and tiles](#grid-and-tiles) | -| | origin $o_a$ and tile size $s_a$ of level 0, per axis | MUST | [Grid and tiles](#grid-and-tiles) | +| Data model | axes: all the spatial axes of the element | MUST | [Grid and tiles](#grid-and-tiles) | +| | origin $o_a$ and tile size $s_a$ of level 0, per axis (a single tile along an axis allowed) | MUST | [Grid and tiles](#grid-and-tiles) | | | bands $0, \dots, L$ ($L \ge 0$): band 0 always, bands $1, \dots, L$; level $l$ = bands $L, \dots, l$ | MAY | [Levels and bands](#levels-and-bands) | | | grid of every level present, $0, \dots, L$ | MUST | [Grid and tiles](#grid-and-tiles) | -| | grid of each level refines the grid of the next coarser level (recommended recipe: the merge rule) | MUST | +| | grid of each level refines the grid of the next coarser level (recommended recipe: the merge rule) | MUST | [Grid and tiles](#grid-and-tiles) | | | grids get coarser with the level (a level may keep the grid of the level below) | SHOULD | [Grid and tiles](#grid-and-tiles) | | | tile order: C order of the tile ids | MUST | [Tiles ordering](#tiles-ordering) | -| | random value $p$ per point | MUST | [Priority](#priority) | +| | random value $p = k / 2^b$ per point, kept when the element is indexed again | MUST | [Priority](#priority) | | | fraction $P^{(l)}$ of every level present ($P^{(0)} = 1$), a fixed rate (default: ratio of the tile volumes of level 0 and level $l$; any strictly decreasing rates allowed) | MUST | [Sampling](#sampling) | +| | tile size for the typical tile (median of level 0 about 5,000 to 20,000 points) | SHOULD | [Choosing the tile size and the rates](#choosing-the-tile-size-and-the-rates) | | | feature column(s) | MAY; at most one SHOULD | [Tile-major order and feature-major order](#tile-major-order-and-feature-major-order) | -| Storage format | metadata: `spatial_index` convention, with its `version` and its `levels` | MUST | [Metadata](#metadata) | -| | Parquet (default) or Zarr (experimental) | MUST, one of them | [Storage format](#storage-format) | -| | column `__spatialdata_p__` | MUST | [Columns](#columns) | +| Storage format | metadata: `spatial_index` convention in `zarr.json`, with its `version`, `axes`, `p_bits` and `levels` | MUST | [Metadata](#metadata) | +| | Parquet (default) or Zarr (experimental), same layout | MUST, one of them | [File layout](#file-layout) | +| | Parquet sidecar: part files in order, their first rows, global categories | MUST, in Parquet | [Metadata](#metadata) | +| | column `__spatialdata_p__`, unsigned integer codes | MUST | [Columns](#columns) | | | tile-major table, levels as bands | MUST | [Levels and bands](#levels-and-bands) | -| | tile index: `tile_offsets` of every band | MUST | [Tile index](#tile-index) | -| | row groups aligned with the tiles (Parquet); chunk length close to the rows of a tile (Zarr) | SHOULD | [Points as a tall table](#points-as-a-tall-table) | +| | tile index: `tile_offsets` of every band (int32 or int64) | MUST | [Tile index](#tile-index) | +| | row groups of 100,000 to 1,000,000 rows, starting at tiles; part files starting at tiles (Parquet); chunks of about a tile, in shards (Zarr) | SHOULD | [Points as a tall table](#points-as-a-tall-table) | +| | per-row-group dictionaries with only the categories present (Parquet) | SHOULD | [Columns](#columns) | | | feature-major table, one per feature column | MUST, for each feature column | [Tile-major order and feature-major order](#tile-major-order-and-feature-major-order) | -| | feature index: `tile_offsets`, per band, feature and tile | MUST, with a feature-major table | [Feature index](#feature-index) | -| | offsets chunked for small reads (e.g. 65,536 entries; one feature per chunk row) | SHOULD | [File layout](#file-layout) | +| | feature index: sparse (CSR) `tile_offsets` per band | MUST, with a feature-major table | [Feature index](#feature-index) | +| | offsets chunked for small reads (e.g. 65,536 entries) | SHOULD | [File layout](#file-layout) | | | coordinate and feature columns first | SHOULD | [Order of the columns](#order-of-the-columns) | +| | identifier column of the points | MAY be dropped | [Columns](#columns) | ## Related work @@ -763,6 +874,18 @@ Considered and not chosen: the page index, but coarser and less uniformly supported by readers than Zarr chunks, and a second index format next to the Zarr one. - Tile-relative float32 or uint16 coordinates: can come later as a codec without changing the type. +- A dense feature index, one offset per feature and per tile (`int64[n_features, N_tiles + 1]` per + band): simple, but it grows with features × tiles, about $2 \cdot 10^{10}$ entries (165 GB) for one + band of a whole-transcriptome dataset; see the figure of [Feature index](#feature-index). +- Offsets as pairs (part file, row inside the file) instead of global row numbers: they would make the + part files independent of each other, but take 50% more space, differ between Parquet and Zarr, and + make counts and ranges that cross files harder to compute; the Parquet sidecar gives the same + information with one small list per table. +- The Parquet-only metadata (part files, categories) in `zarr.json`: it grows with the number of part + files, and a separate file shows which parts of the format are specific to Parquet. +- The tile-major Parquet table at the root of the element (`points.parquet/`), where readers of + points without an index look: backward compatible, but a different layout for each format; with a + new format version the two formats share one layout. - Zarr, one 2-D array with the columns first, chunked by tile: a chunk would hold the columns of a tile column by column, as a Parquet row group, in one request. But a Zarr array has a single data type, and such an array is not a dataframe; the `df:` convention is used instead. @@ -796,6 +919,10 @@ Considered and not chosen: ## Implementation +An experimental implementation of this draft (both formats, reading and writing, a napari-spatialdata +reader that loads the points in view) was tested on two 10x Atera datasets of 0.7 and 1.2 billion +transcripts; the numbers quoted in this RFC come from it. + > **TODO:** spatialdata (read/write), spatialdata-io (Celldega PR #423), tissue-map-tools (sampling), > a viewer (Celldega, Vitessce, TissUUmaps, merfisheyes, spatiato). diff --git a/rfcs/0004-tiled-shapes.md b/rfcs/0004-tiled-shapes.md index 24e314f..d85df59 100644 --- a/rfcs/0004-tiled-shapes.md +++ b/rfcs/0004-tiled-shapes.md @@ -13,49 +13,93 @@ created: 2026-10-27 ## Abstract -Sort shapes (cells) by tile, using the grid of [RFC 3](0003-tiled-points.md) on their centroids, and -store the geometry as GeoArrow. For the table annotating the shapes, store the expression matrix as -CSR and CSC. Together this gives viewers like Celldega and Vitessce what they need to load cells by -tile and color them by gene. +Sort shapes (cells) by tile, using a grid as in [RFC 3](0003-tiled-points.md) on their centroids, and +store the geometry as GeoArrow. For the table annotating the shapes, keep its rows in the order of the +shapes and store the expression matrix as CSR and CSC. Together this gives viewers like Celldega and +Vitessce what they need to load cells by tile and color them by gene. The index is optional, and only +suited to small shapes. ## Description ### Scope -- In: 2-D shapes (polygons, multipolygons, circles) much smaller than a tile; the table annotating - them. -- Out: large shapes (tissue regions, anatomical annotations), for which the centroid says little - and which would have to be split across tiles; multiscale levels (see TODO below). +- In: 2-D shapes (polygons, multipolygons, circles) much smaller than a tile, such as cells or nuclei; + the table annotating them. +- Out: large shapes (tissue regions, anatomical annotations), see [When to use it](#when-to-use-it); + multiscale levels: this version has a single level (see [Levels](#levels)). + +### When to use it + +This index is optional, and only suited to small shapes, such as cells or nuclei. It is not +recommended for shapes that are large compared to the tiles, such as anatomical structures or tissue +regions: their centroid says little about where they are, the margin (the largest overhang outside the +tile of the centroid, see [Spatial order](#spatial-order)) becomes large, and every query then reads +many tiles. Rule of thumb: use the index only if the shapes are smaller than a tile and more than 50% of +them lie entirely within the tile of their centroid; otherwise do not. Writers SHOULD check this and +choose the tile size accordingly. + +For example, for the 399,000 cells of a 10x Atera kidney section (median width 8.7 µm, 90th percentile +14.2 µm), the fraction of cells entirely within the tile of their centroid is: + +| Tile size | 6.7 µm | 13.4 µm | 26.7 µm | 53.5 µm | 107 µm | +| :- | :- | :- | :- | :- | :- | +| Cells within their tile | 0.8% | 13% | 43% | 68% | 83% | + +Tiles of 53.5 µm or more suit these cells; tiles of the size used for the transcripts of the same +dataset (27 µm, see RFC 3) are borderline, and smaller ones do not. ### Spatial order -Same grid, metadata (`spatial_index`) and `tile_offsets` as RFC 3, applied to centroids: +The grid, the metadata (`spatial_index`) and the tile index (`tile_offsets`) are those of RFC 3, with a +single level, applied to the centroids of the shapes: ```text c_i = centroid(geometry_i) # circles: the center k_i = ravel(floor((c_i − origin) / tile_size), grid_shape) rows sorted by k_i -rows of tile k = [tile_offsets[k], tile_offsets[k + 1]) +rows of tile k = [tile_offsets/0[k], tile_offsets/0[k + 1]) ``` -A shape may extend outside its tile. The writer records the largest overhang, and readers grow the -query box by it: +A shape may extend outside its tile. The writer records the largest overhang per axis, the *margin*, +in `spatial_index`, and readers grow the query box by it: ```text -margin_a = max_i max(c_i,a − bbox_min_i,a, bbox_max_i,a − c_i,a) # per axis, in metadata -tiles to read = tiles(box_min − margin, box_max + margin) +margin_a = max_i max(c_i,a − bbox_min_i,a, bbox_max_i,a − c_i,a) # per axis, in spatial_index +tiles to read = tiles intersecting [box_min − margin, box_max + margin] ``` -Shapes and points of the same dataset should use the same grid (origin and tile size), so one tile -request loads both. Fewer shapes than points per tile is fine. Several tiles can share a row group -(Parquet) or a shard (Zarr). +`margin` is one value per axis, in the order of `axes`, in the coordinates of the element, like `origin` +and `tile_size`. Writers MUST NOT record a margin smaller than the largest overhang (readers would miss +shapes at the edges of a view); a larger margin is allowed, and only makes queries slower. + +```json +"spatial_index": { + "version": "0.1.0-draft", + "axes": ["x", "y"], + "levels": [{"origin": [0.0, 0.0], "tile_size": [53.5, 53.5], "grid_shape": [226, 132], "P": 1.0}], + "margin": [30.8, 21.9], + "table": "table", + "parquet": "spatial_index.parquet.json" +} +``` -> **TODO(Luca):** require the same grid as the points, or only recommend it? +**The grid of the shapes.** Each element has its own grid (RFC 3), chosen for its own data: the shapes +by the rule of [When to use it](#when-to-use-it), the points by their density (RFC 3, "Choosing the tile +size and the rates"). The two usually want different tile sizes (in the example above, about 27 µm for +the transcripts and 53.5 µm for the cells), and the grid of each element covers its own bounding box. +When a client loads points and shapes tile by tile, writers SHOULD choose nested grids: the same origin, +and a tile size of the shapes equal to that of a level of the points (with the merge rule, a power of 2 +times the tile size of level 0), so that each tile of the shapes is a union of tiles of the points. +Several tiles can share a row group (Parquet) or a shard (Zarr). ### Geometry GeoArrow in Parquet (`geometry_encoding="geoarrow"`) instead of WKB. A column that mixes Polygon and -MultiPolygon is written as MultiPolygon. Code that already handles MultiPolygon keeps working. +MultiPolygon is written as MultiPolygon: code that handles MultiPolygon keeps working, and viewers +SHOULD draw all the parts of a MultiPolygon, not only the largest. + +The commonly used columns SHOULD come first, the geometry, then the instance id and the columns used to +color or select the shapes, as in RFC 3 ("Order of the columns"). ### Table annotating the shapes @@ -64,36 +108,62 @@ table.X CSR (cells × genes) # as today table.layers["X_csc"] CSC (same values) # gene-major: one gene for all cells in one read ``` -Celldega needs CSC to color cells by gene. Vitessce uses it for DotPlot without memory spikes. +Celldega needs CSC to color cells by gene. Vitessce uses it for DotPlot without memory spikes. The name +of the CSC layer SHOULD be `X_csc` (other names, such as `csc_counts` in spatialdata-db, are allowed). -> **TODO(Luca):** CSR + CSC both by default and configurable (Ilan), or CSC optional? Is this a -> SpatialData rule, or an AnnData convention (Ilan)? Name of the layer. An API in spatialdata, -> called by spatialdata-io readers? +The table MUST annotate the shapes (its `region` is the shapes element, its `instance_key` the index of +the shapes); if it does not, this section does not apply, and making sure it does is the responsibility +of the user. When the shapes are indexed, the rows of the table SHOULD be in the order of the shapes, so +that the tile index also slices the table: the rows of tile $k$ in the table are +`[tile_offsets/0[k], tile_offsets/0[k + 1])`. `spatial_index` then names the table (`"table"`, above); +without it, readers join on the instance id. -> **TODO(Luca):** require the table rows in the same order as the shapes, so that `tile_offsets` -> also slices the table? Otherwise readers join on the instance id. +> **TODO(Luca):** CSR + CSC both by default and configurable (Ilan), or CSC optional? Is this a +> SpatialData rule, or an AnnData convention (Ilan)? An API in spatialdata, called by spatialdata-io +> readers? ### Levels -> **TODO(Luca):** Celldega has no levels; zoomed out it aggregates (cells via CSC, hexagonal bins). -> Options: none in this RFC; simplified geometries per level; centroids only (as points, RFC 3). +This version has a single level, the grid of level 0: zoomed out, a client shows fewer shapes by other +means. Options for a future version: + +- none (Celldega aggregates when zoomed out: cells via CSC, hexagonal bins); +- simplified geometries per level; +- the centroids as points, with the levels of RFC 3. + +### Limitations and possible extensions + +The margin is a single maximum over all the shapes: a few large shapes make every query read more +tiles (in the kidney example with 6.7 µm tiles, a margin of 30.8 × 21.9 µm, 4 to 5 extra tiles on each +side). Possible extensions, not part of this version: + +- shapes larger than a few tiles in a separate range of rows, or in a coarser level, with their own + margin; +- a margin per tile; +- indexing by the overlap of the bounding box (each shape in the tile of the minimum corner of its + bounding box, with a margin equal to the largest bounding box). ### File layout +As in RFC 3, the same in Parquet and in Zarr; in Parquet with the Parquet sidecar (part files in +order and the first row of each): + ```text shapes// -├── zarr.json # attrs incl. spatial_index (+ margin) -├── shapes.parquet/ # rows sorted by tile, GeoArrow geometry, part.0.parquet, … -└── index/0/tile_offsets # as in RFC 3 +├── zarr.json # attrs incl. spatial_index (+ margin) +├── spatial_index.parquet.json # Parquet only +└── spatial/ + ├── shapes.parquet/ # rows sorted by tile, GeoArrow geometry, part files + └── tile_offsets/0 # as in RFC 3 tables// -├── X/ # CSR -└── layers/X_csc/ # CSC +├── X/ # CSR +└── layers/X_csc/ # CSC ``` ### Compatibility -Without `spatial_index` an element reads as today. Old readers read tiled shapes in a different row -order. GeoArrow needs a recent GeoPandas/pyarrow. +Without `spatial_index` an element reads as today. An element with `spatial_index` is a new version of +the shapes format, not readable by older readers. GeoArrow needs a recent GeoPandas/pyarrow. > **TODO(Luca):** the GeoArrow reader versions to require. @@ -104,8 +174,22 @@ order. GeoArrow needs a recent GeoPandas/pyarrow. transcripts and cells, `geoarrow.polygon`, `layers["X_csc"]`. - TissUUmaps: reads only CSC. +Considered and not chosen: + +- One grid shared by the points and the shapes of a dataset, with a "leftover" tile for the shapes + whose centroid falls outside the grid of the points: the two elements want different tile sizes, + every reader would have to read the leftover tile, and avoiding it would require the grid of the + points to cover the shapes. Nested grids give the same alignment. +- A rule to find the table rows of shapes annotated only indirectly (e.g. a table annotating the cell + labels, matched to the boundaries through a column): out of scope, the table must annotate the shapes. + ## Implementation +An experimental implementation (sorting by tile, GeoArrow, margin, table in the order of the shapes +with a CSC layer, a napari-spatialdata reader of the shapes in view) was tested on the 399,000 cells of +a 10x Atera kidney dataset: a box of 1 mm reads its cells in 21 ms instead of 0.22 s, and one gene for +all the cells takes 5 ms from CSC instead of 2.3 s from CSR. + > **TODO:** spatialdata (write sorted shapes, GeoArrow, CSC layer), spatialdata-io (PR #423), Celldega, > Vitessce. diff --git a/rfcs/img/0003-feature-index.svg b/rfcs/img/0003-feature-index.svg new file mode 100644 index 0000000..4ec8c9b --- /dev/null +++ b/rfcs/img/0003-feature-index.svg @@ -0,0 +1,149 @@ + +Feature index of one band: dense and sparse + +feature-major table, one band: rows sorted by gene, then tile + +A · t0 +0 + +A · t0 +1 + +A · t2 +2 + +A · t5 +3 + +A · t5 +4 + +A · t5 +5 + +B · t3 +6 + +B · t3 +7 + +B · t3 +8 + +B · t3 +9 + +C · t1 +10 +row +points per (gene, tile): +A: [2, 0, 1, 0, 0, 3] +B: [0, 0, 0, 4, 0, 0] +C: [0, 1, 0, 0, 0, 0] +Dense: for explanation only, not viable +an offset for every feature and every tile: [n_features, N_tiles + 1] +0 +1 +2 +3 +4 +5 +6 +A + +0 + +2 + +2 + +3 + +3 + +3 + +6 +B + +6 + +6 + +6 + +6 + +10 + +10 + +10 +C + +10 + +10 + +11 + +11 + +11 + +11 + +11 +k +3 × 7 = 21 entries; grey: empty tile, same offset as the next tile +breast, band 0: 27,104 × 759,595 = 2.1e10 entries ≈ 165 GB +Sparse: the format, tile_offsets/<l> +only the non-empty tiles, CSR over the genes +feature_ptr + +0 + +3 + +4 + +5 +where each gene's entries start (n_features + 1) +tile_ids + +0 + +2 + +5 + +3 + +1 +the non-empty tiles of each gene (nnz) +row_offsets + +0 + +2 + +3 + +6 + +6 + +10 + +10 + +11 +start row of each, + the end of each gene (nnz + n_features) +4 + 5 + 8 = 17 entries +breast, all 12 bands: ≈ 3.1e7 entries ≈ 0.5 GB + +Gene A in tile 5: +dense: O[A, 5] = 3, O[A, 6] = 6 → rows [3, 6) +sparse: tile_ids[ptr[A]:ptr[A+1]] = [0, 2, 5] → tile 5 is entry 2 + row_offsets[ptr[A] + A + 2], [… + 3] = 3, 6 → rows [3, 6) + \ No newline at end of file From ce6e6c077e88005bfcceb6d84d8d3c29b5b69724 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Thu, 19 Nov 2026 15:46:15 +0100 Subject: [PATCH 5/6] RFC 3: say that a point with p equal to P(l) is not in level l Co-Authored-By: Claude Opus 5.5 --- rfcs/0003-tiled-points.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rfcs/0003-tiled-points.md b/rfcs/0003-tiled-points.md index db7ed0b..c601440 100644 --- a/rfcs/0003-tiled-points.md +++ b/rfcs/0003-tiled-points.md @@ -261,7 +261,8 @@ $$ \text{band } l = \{\, i : P^{(l+1)} \le p_i < P^{(l)} \,\} \quad (l < L) $$ -With $L = 0$ there is a single band, with all the points; bands $1, \dots, L$ MAY be present. The +With $L = 0$ there is a single band, with all the points; bands $1, \dots, L$ MAY be present. The comparisons +are strict: a point with $p = P^{(l)}$ exactly is not in level $l$. The tiles of band $l$ are those of the grid of level $l$. Level $l$ is the union of the bands $L, L - 1, \dots, l$, the points with $p < P^{(l)}$; level 0 holds all the points. From 9ab078e6adc45567671c3a0cde66f85c21f0e642 Mon Sep 17 00:00:00 2001 From: Luca Marconato Date: Thu, 19 Nov 2026 22:39:44 +0100 Subject: [PATCH 6/6] RFC 4: author Luca Marconato, input from Nicolas Fernandez, Ilan Gold, Marco Varrone, Mark Keller Co-Authored-By: Claude Opus 5.5 --- rfcs/0004-tiled-shapes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rfcs/0004-tiled-shapes.md b/rfcs/0004-tiled-shapes.md index d85df59..bdfac7f 100644 --- a/rfcs/0004-tiled-shapes.md +++ b/rfcs/0004-tiled-shapes.md @@ -1,7 +1,7 @@ --- rfc: 4 title: "Tiled and multiscale shapes" -authors: "Nicolas Fernandez ([@cornhundred](https://github.com/cornhundred)), Luca Marconato ([@LucaMarconato](https://github.com/LucaMarconato)); input from Ilan Gold, Marco Varrone, Mark Keller" +authors: "Luca Marconato ([@LucaMarconato](https://github.com/LucaMarconato)); input from Nicolas Fernandez ([@cornhundred](https://github.com/cornhundred)), Ilan Gold, Marco Varrone, Mark Keller" status: "draft" type: "storage format" created: 2026-10-27