deltacells 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. deltacells-0.1.0/.gitignore +23 -0
  2. deltacells-0.1.0/DEVELOPING.md +100 -0
  3. deltacells-0.1.0/LICENSE +26 -0
  4. deltacells-0.1.0/MANIFEST.in +11 -0
  5. deltacells-0.1.0/Makefile +52 -0
  6. deltacells-0.1.0/PKG-INFO +208 -0
  7. deltacells-0.1.0/README.md +170 -0
  8. deltacells-0.1.0/benchmarks/bench_compression.py +65 -0
  9. deltacells-0.1.0/benchmarks/bench_decode.py +79 -0
  10. deltacells-0.1.0/benchmarks/bench_obs.py +116 -0
  11. deltacells-0.1.0/benchmarks/bench_pipeline.py +97 -0
  12. deltacells-0.1.0/benchmarks/check_against_h5ad.py +93 -0
  13. deltacells-0.1.0/benchmarks/compare_formats.py +257 -0
  14. deltacells-0.1.0/benchmarks/make_synthetic.py +116 -0
  15. deltacells-0.1.0/docs/Makefile +19 -0
  16. deltacells-0.1.0/docs/make_figures.py +210 -0
  17. deltacells-0.1.0/docs/source/_static/gap-cdf.png +0 -0
  18. deltacells-0.1.0/docs/source/_static/pattern.png +0 -0
  19. deltacells-0.1.0/docs/source/_static/size-by-order.png +0 -0
  20. deltacells-0.1.0/docs/source/_static/streams.png +0 -0
  21. deltacells-0.1.0/docs/source/benchmarks.md +181 -0
  22. deltacells-0.1.0/docs/source/conf.py +37 -0
  23. deltacells-0.1.0/docs/source/convert.md +116 -0
  24. deltacells-0.1.0/docs/source/dataloader.md +137 -0
  25. deltacells-0.1.0/docs/source/encoding.md +148 -0
  26. deltacells-0.1.0/docs/source/format.md +181 -0
  27. deltacells-0.1.0/docs/source/index.md +59 -0
  28. deltacells-0.1.0/docs/source/install.md +51 -0
  29. deltacells-0.1.0/docs/source/obs.md +156 -0
  30. deltacells-0.1.0/examples/dataloader_example.py +80 -0
  31. deltacells-0.1.0/examples/reference_loader.py +123 -0
  32. deltacells-0.1.0/pyproject.toml +97 -0
  33. deltacells-0.1.0/setup.cfg +4 -0
  34. deltacells-0.1.0/setup.py +64 -0
  35. deltacells-0.1.0/src/deltacells/__init__.py +49 -0
  36. deltacells-0.1.0/src/deltacells/__main__.py +7 -0
  37. deltacells-0.1.0/src/deltacells/_core.c +404 -0
  38. deltacells-0.1.0/src/deltacells/_core.pyi +56 -0
  39. deltacells-0.1.0/src/deltacells/backends.py +242 -0
  40. deltacells-0.1.0/src/deltacells/cli.py +237 -0
  41. deltacells-0.1.0/src/deltacells/convert.py +645 -0
  42. deltacells-0.1.0/src/deltacells/dataset.py +406 -0
  43. deltacells-0.1.0/src/deltacells/format.py +172 -0
  44. deltacells-0.1.0/src/deltacells/manifest.py +107 -0
  45. deltacells-0.1.0/src/deltacells/obs.py +711 -0
  46. deltacells-0.1.0/src/deltacells/progress.py +201 -0
  47. deltacells-0.1.0/src/deltacells/py.typed +0 -0
  48. deltacells-0.1.0/src/deltacells/reader.py +287 -0
  49. deltacells-0.1.0/src/deltacells/sink.py +259 -0
  50. deltacells-0.1.0/src/deltacells/staging.py +278 -0
  51. deltacells-0.1.0/src/deltacells/writer.py +555 -0
  52. deltacells-0.1.0/src/deltacells.egg-info/PKG-INFO +208 -0
  53. deltacells-0.1.0/src/deltacells.egg-info/SOURCES.txt +70 -0
  54. deltacells-0.1.0/src/deltacells.egg-info/dependency_links.txt +1 -0
  55. deltacells-0.1.0/src/deltacells.egg-info/entry_points.txt +2 -0
  56. deltacells-0.1.0/src/deltacells.egg-info/requires.txt +31 -0
  57. deltacells-0.1.0/src/deltacells.egg-info/scm_file_list.json +71 -0
  58. deltacells-0.1.0/src/deltacells.egg-info/scm_version.json +8 -0
  59. deltacells-0.1.0/src/deltacells.egg-info/top_level.txt +1 -0
  60. deltacells-0.1.0/tests/conftest.py +48 -0
  61. deltacells-0.1.0/tests/test_backends.py +68 -0
  62. deltacells-0.1.0/tests/test_benchmarks.py +238 -0
  63. deltacells-0.1.0/tests/test_convert.py +363 -0
  64. deltacells-0.1.0/tests/test_dataset.py +408 -0
  65. deltacells-0.1.0/tests/test_examples.py +95 -0
  66. deltacells-0.1.0/tests/test_exceptions.py +228 -0
  67. deltacells-0.1.0/tests/test_format.py +124 -0
  68. deltacells-0.1.0/tests/test_gather.py +70 -0
  69. deltacells-0.1.0/tests/test_obs.py +879 -0
  70. deltacells-0.1.0/tests/test_remote.py +505 -0
  71. deltacells-0.1.0/tests/test_roundtrip.py +245 -0
  72. deltacells-0.1.0/tests/test_torch.py +88 -0
@@ -0,0 +1,23 @@
1
+ __pycache__/
2
+ .DS_Store
3
+ .ipynb_checkpoints
4
+ .mypy_cache/
5
+ .idea/
6
+ .ruff_cache/
7
+ .pytest_cache/
8
+ .vscode/
9
+ docs/build/
10
+ docs/source/examples/
11
+ docs/source/tutorials/
12
+ eggs/
13
+ *.egg*
14
+ .idea/
15
+ build/
16
+ *.h5ad
17
+ *.csv
18
+ *.csv.gz
19
+ *.tsv
20
+ *.tsv.gz
21
+ *.ckpt
22
+ CLAUDE.md
23
+ *.so
@@ -0,0 +1,100 @@
1
+ # Developing deltacells
2
+
3
+ ## Build
4
+
5
+ The package has one C extension (`src/deltacells/_core.c`) that links against **libzstd** (headers and library). The build
6
+ looks for it in `$ZSTD_ROOT`, `$CONDA_PREFIX`, `sys.prefix`, Homebrew, `/usr/local` and `/usr`.
7
+
8
+ ```bash
9
+ conda install zstd # or: brew install zstd / apt install libzstd-dev
10
+ pip install -e ".[test]" # editable install (builds the extension); the obs features need pyarrow and pandas (extra: obs)
11
+ # or, without installing, build the extension next to the sources:
12
+ python setup.py build_ext --inplace
13
+ ```
14
+
15
+ `DELTACELLS_STATIC_ZSTD=1` links `libzstd.a` statically (self-contained wheels). Supported: Linux and macOS, little-endian,
16
+ Python >= 3.10.
17
+
18
+ ## Test
19
+
20
+ ```bash
21
+ pytest tests # from this directory
22
+ pytest deltacells/tests # from a parent repository, after an in-place build or an install
23
+ ```
24
+
25
+ `tests/conftest.py` makes the tests importable straight after `build_ext --inplace`, and skips collecting them when the package
26
+ is not available, so a parent repository's `pytest` run does not fail on a machine without the extension. Tests that need
27
+ `torch` or `anndata` are skipped when those are missing.
28
+
29
+ `make lint` (ruff), `make typecheck` (mypy) and `make test` are what CI runs (`.github/workflows/ci.yml`).
30
+
31
+ ## Documentation
32
+
33
+ The documentation is a Sphinx project (Markdown pages in `docs/source`, the Book theme), published at
34
+ https://cellarium-ai.github.io/deltacells/ by `.github/workflows/docs.yml` on every push to `main`. To build it locally:
35
+
36
+ ```bash
37
+ pip install -e ".[docs]"
38
+ make docs # the output is in docs/build/html; warnings are errors
39
+ python -m http.server -d docs/build/html # then open http://localhost:8000 (open it over http, not as a file)
40
+ ```
41
+
42
+ The figures of the encoding page are generated from a real shard by `docs/make_figures.py` (it needs matplotlib and anndata) and
43
+ the PNGs are committed, so building the docs needs no data.
44
+
45
+ ## Releasing
46
+
47
+ To release, create a GitHub release with a new tag (`v1.2.3` or `1.2.3`): the tag is the version, and nothing in the repository is
48
+ edited. The version is not stored anywhere in the sources: [setuptools-scm](https://setuptools-scm.readthedocs.io) reads it from
49
+ git when the package is built, so a checkout between tags is `<next version>.devN`, and `deltacells.__version__` reports the
50
+ installed version (reinstall after pulling new tags to update it in an editable install).
51
+
52
+ Publishing the release runs `.github/workflows/pypi.yml`: it builds the sdist, builds the wheels from it (Linux x86_64 /
53
+ aarch64 and macOS arm64, CPython 3.10-3.13, libzstd linked statically; see `[tool.cibuildwheel]` in `pyproject.toml`), checks
54
+ that they all have the tag's version and uploads them to PyPI with trusted publishing. This needs the `pypi` environment in the
55
+ GitHub repository and this workflow listed as a trusted publisher on PyPI. Run the workflow by hand to build the artifacts
56
+ without publishing.
57
+
58
+ ## Benchmarks
59
+
60
+ ```bash
61
+ python benchmarks/make_synthetic.py /tmp/syn --n-cells 50000 --n-genes 30000 # synthetic data, no h5ad needed
62
+ deltacells convert --h5ad-glob "shards/*.h5ad" --output /tmp/real # or convert real shards
63
+ python benchmarks/bench_decode.py /tmp/real
64
+ python benchmarks/make_synthetic.py /tmp/syn --obs-columns 20 # synthetic data with obs
65
+ python benchmarks/bench_obs.py /tmp/real --columns cell_type,donor_id # obs: bytes read, localization time, lookup latency
66
+ python benchmarks/compare_formats.py shard.h5ad # h5ad vs TileDB-SOMA vs BPCells vs deltacells, one shard
67
+ benchmarks/bpcells_decode/build.sh # optional: BPCells' own C++ decoder for that comparison
68
+ python benchmarks/bench_pipeline.py /tmp/real --workers 0,1,2,4
69
+ python benchmarks/bench_pipeline.py /tmp/real --workers 2 --bandwidth-mbps 150 --latency-ms 50 # emulate a remote store
70
+ python benchmarks/bench_compression.py /tmp/real --levels 3,12,19 --chunks 1,8
71
+ python benchmarks/check_against_h5ad.py /tmp/real "shards/*.h5ad" # cell-by-cell comparison with the source
72
+ ```
73
+
74
+ `make benchmark` runs all of these that need no real data (synthetic data, then decode, compression, obs and pipeline benchmarks);
75
+ see the comment above that target in the `Makefile` for the settings (`BENCH_DIR`, `BENCH_CELLS`, `BENCH_GENES`, ...).
76
+
77
+ Benchmarking notes: run on an otherwise idle machine (the pipeline benchmark needs a few GB of free RAM per worker); the
78
+ `bench_pipeline` timing stops at the last received batch so that DataLoader worker shutdown is not counted, and very small
79
+ datasets give very short timed windows.
80
+
81
+ ## Layout of the code
82
+
83
+ | file | role |
84
+ |---|---|
85
+ | `src/deltacells/_core.c` | decode a chunk, gather rows, compress a stream (all release the GIL) |
86
+ | `format.py` | binary layout constants, header / chunk-table parsing and validation |
87
+ | `writer.py` | `encode_tile`, `write_tile`, `DatasetWriter`, `permute_columns` |
88
+ | `reader.py` | `Tile` (parse, verify, decode), `DecodedTile`, `SparseBatch`, row gather |
89
+ | `manifest.py` | `Manifest` (dataset JSON) |
90
+ | `backends.py` | `LocalBackend`, `GCSBackend`, `ThrottledBackend` |
91
+ | `dataset.py` | `DeltaCellsDataset`: tile prefetch, decoded-tile cache with buffer reuse, `get_batch`, `obs`, `var` |
92
+ | `obs.py` | per-cell metadata: `ObsSchema`, tile-aligned parquet shards, `ObsStore` (localization to a per-column Arrow cache, `take`, `to_pandas`) |
93
+ | `convert.py`, `cli.py` | h5ad conversion and the `deltacells` command |
94
+ | `examples/` | a reference `IterableDataset` and a runnable example |
95
+ | `benchmarks/bpcells_decode/` | C++ harness timing BPCells' decoders directly (downloads a pinned BPCells at build time; nothing vendored) |
96
+
97
+ ## Changing the format
98
+
99
+ Bump `VERSION` in `format.py` and `manifest.py`, keep readers rejecting versions they do not know, and update `docs/source/format.md`
100
+ and the tests in `tests/test_format.py`.
@@ -0,0 +1,26 @@
1
+ Copyright (c) 2026, Broad Institute
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this
7
+ list of conditions and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice,
10
+ this list of conditions and the following disclaimer in the documentation
11
+ and/or other materials provided with the distribution.
12
+
13
+ 3. Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,11 @@
1
+ include LICENSE README.md DEVELOPING.md
2
+ recursive-include src *.c *.py *.pyi py.typed
3
+ recursive-include docs *.md *.py *.png Makefile
4
+ # the tests, which the wheel builds run against the installed wheel (they need the examples and benchmarks)
5
+ recursive-include tests *.py
6
+ recursive-include examples *.py
7
+ recursive-include benchmarks *.py
8
+
9
+ # setuptools-scm also adds every file tracked by git to the sdist; leave out what is not part of the package
10
+ prune .github
11
+ prune benchmarks/bpcells_decode
@@ -0,0 +1,52 @@
1
+ .PHONY: install uninstall lint docs format typecheck test test-dataloader benchmark FORCE
2
+
3
+ install: FORCE
4
+ pip install -e .[dev]
5
+
6
+ uninstall: FORCE
7
+ pip uninstall deltacells
8
+
9
+ lint: FORCE
10
+ ruff check .
11
+ ruff format --check .
12
+
13
+ docs: FORCE
14
+ cd docs && make html
15
+
16
+ format: FORCE
17
+ ruff check --fix .
18
+ ruff format .
19
+
20
+ typecheck: FORCE
21
+ mypy src tests examples benchmarks
22
+
23
+ test: FORCE
24
+ pytest -v tests
25
+
26
+ test-dataloader: FORCE
27
+ python examples/dataloader_example.py
28
+
29
+ # Run all the benchmarks that need no external data on a synthetic dataset (see DEVELOPING.md for what each one measures).
30
+ # Run it on an otherwise idle machine; the pipeline benchmark needs a few GB of free RAM per worker. Override the settings on
31
+ # the command line, for example: make benchmark BENCH_CELLS=20000 BENCH_GENES=10000 BENCH_THREADS=1,2,4
32
+ # BENCH_DIR where the synthetic dataset is written (replaced on every run)
33
+ # BENCH_CELLS, BENCH_GENES, BENCH_NNZ size of the dataset: cells, genes, mean nonzeros per cell
34
+ # BENCH_THREADS decode threads to compare; BENCH_WORKERS DataLoader workers to compare
35
+ # Not included, because they need real data or other tools: benchmarks/compare_formats.py (one h5ad shard; optionally TileDB-SOMA
36
+ # and BPCells) and benchmarks/check_against_h5ad.py (a dataset converted from h5ad files, against those files).
37
+ BENCH_DIR ?= /tmp/deltacells_bench
38
+ BENCH_CELLS ?= 50000
39
+ BENCH_GENES ?= 30000
40
+ BENCH_NNZ ?= 3000
41
+ BENCH_THREADS ?= 1,2,4,8
42
+ BENCH_WORKERS ?= 0,1,2,4
43
+
44
+ benchmark: FORCE
45
+ python benchmarks/make_synthetic.py $(BENCH_DIR) --n-cells $(BENCH_CELLS) --n-genes $(BENCH_GENES) --mean-nnz $(BENCH_NNZ) --obs-columns 20 --overwrite
46
+ python benchmarks/bench_decode.py $(BENCH_DIR) --threads $(BENCH_THREADS)
47
+ python benchmarks/bench_compression.py $(BENCH_DIR) --levels 3,12,19 --chunks 1,8
48
+ python benchmarks/bench_obs.py $(BENCH_DIR)
49
+ python benchmarks/bench_pipeline.py $(BENCH_DIR) --workers $(BENCH_WORKERS)
50
+ python benchmarks/bench_pipeline.py $(BENCH_DIR) --workers 2 --bandwidth-mbps 150 --latency-ms 50 # emulate a remote store
51
+
52
+ FORCE:
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: deltacells
3
+ Version: 0.1.0
4
+ Summary: Fast, compact, cloud-friendly tiles of single-cell count matrices: delta-coded gene gaps + zstd, decoded by a small C core.
5
+ Author: Cellarium contributors
6
+ Author-email: Stephen Fleming <sfleming@broadinstitute.org>
7
+ License-Expression: BSD-3-Clause
8
+ Project-URL: Documentation, https://cellarium-ai.github.io/deltacells/
9
+ Project-URL: Source, https://github.com/cellarium-ai/deltacells
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: scipy
15
+ Provides-Extra: torch
16
+ Requires-Dist: torch; extra == "torch"
17
+ Provides-Extra: h5ad
18
+ Requires-Dist: anndata; extra == "h5ad"
19
+ Provides-Extra: obs
20
+ Requires-Dist: pyarrow; extra == "obs"
21
+ Requires-Dist: pandas; extra == "obs"
22
+ Provides-Extra: gcs
23
+ Requires-Dist: google-cloud-storage; extra == "gcs"
24
+ Requires-Dist: fsspec; extra == "gcs"
25
+ Requires-Dist: gcsfs; extra == "gcs"
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest; extra == "test"
28
+ Requires-Dist: mypy; extra == "test"
29
+ Requires-Dist: ruff; extra == "test"
30
+ Provides-Extra: docs
31
+ Requires-Dist: myst-parser; extra == "docs"
32
+ Requires-Dist: sphinx; extra == "docs"
33
+ Requires-Dist: sphinx-book-theme; extra == "docs"
34
+ Requires-Dist: sphinx-copybutton; extra == "docs"
35
+ Provides-Extra: dev
36
+ Requires-Dist: deltacells[docs,gcs,h5ad,obs,test,torch]; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # deltacells
40
+
41
+ [![build](https://github.com/cellarium-ai/deltacells/actions/workflows/ci.yml/badge.svg)](https://github.com/cellarium-ai/deltacells/actions/workflows/ci.yml)
42
+
43
+ **Fast, compact tiles of single-cell count matrices, built for feeding a training `DataLoader`.**
44
+
45
+ **Documentation: https://cellarium-ai.github.io/deltacells/**
46
+
47
+ Training a model on tens of millions of cells means reading raw counts over and over, and the format they are stored in decides
48
+ how fast that goes and how much disk it takes. deltacells stores a count matrix as a directory (or bucket prefix) of *tiles* of
49
+ about 10,000 cells. Each tile is one self-contained object that a small C library decodes straight into CSR arrays.
50
+
51
+ ## Why deltacells
52
+
53
+ * **Very fast data loading.** A 10,000-cell tile decodes in about 0.1 s on one core and 0.02 s on eight, with no intermediate
54
+ AnnData or Arrow objects. A PyTorch `DataLoader` reading shuffled batches on a laptop sustains 45,000 to 95,000 cells per
55
+ second, depending on the number of workers.
56
+ * **Small on disk.** A dataset is about 40% smaller than the same data in [BPCells](https://github.com/bnprks/BPCells) (3.8 vs
57
+ 6.7 kB per cell) and roughly a third of the size of a gzip-compressed h5ad file. The key idea is to store genes in order of
58
+ decreasing total counts, which makes the values that remain to be compressed small and repetitive.
59
+ * **Fast enough to keep a GPU fed.** On a single thread, decoding is slower than BPCells' decoder (about 2.6 times as long per
60
+ tile), in exchange for the smaller files. With a few `DataLoader` workers, each decoding on its own core, deltacells is
61
+ designed to keep a GPU busy, as in the data loading of [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml). Smaller
62
+ files also mean less to download when the dataset lives in a bucket.
63
+
64
+ One real 10,000-cell shard (38,094 genes), counts only, read from a local file into memory on an M2 Pro laptop:
65
+
66
+ | format | size on disk | decode, 1 thread | decode, 8 threads |
67
+ |---|---|---|---|
68
+ | h5ad (gzip) | 12.5 kB per cell | 1170 ms | single-threaded reader |
69
+ | BPCells (C++ decoder) | 6.7 kB per cell | **48 ms** | **30 ms** |
70
+ | **deltacells** | **3.8 kB per cell** | 125 ms | 39 ms |
71
+
72
+ The [benchmarks page](https://cellarium-ai.github.io/deltacells/benchmarks.html) has the details, other hardware, the DataLoader
73
+ throughput, and how to reproduce all of it.
74
+
75
+ **Status: alpha.** CI runs on Linux x86-64 (Python 3.10 to 3.13) and macOS arm64 (Python 3.12). Reading tiles from Google Cloud
76
+ Storage and converting h5ad files from and to a bucket have been exercised against real buckets. See
77
+ [Limitations](#limitations).
78
+
79
+ ## Install
80
+
81
+ ```bash
82
+ pip install deltacells
83
+ ```
84
+
85
+ Prebuilt wheels are available for Linux (x86-64 and aarch64) and macOS (arm64) on Python 3.10 to 3.13. On other platforms, pip
86
+ builds the package from source, which needs a C compiler and libzstd. Optional extras: `h5ad` (to convert h5ad files), `obs` (cell
87
+ metadata), `torch` and `gcs` (`gs://` paths). For example, `pip install "deltacells[h5ad,obs,gcs]"`. See the
88
+ [install page](https://cellarium-ai.github.io/deltacells/install.html).
89
+
90
+ ## Quick start
91
+
92
+ Convert h5ad shards of any size into a dataset of exact-size tiles (this sorts the genes, re-chunks the cells and compresses):
93
+
94
+ ```bash
95
+ deltacells convert --h5ad-glob "shards/*.h5ad" --output /data/my_dataset
96
+ deltacells info /data/my_dataset
97
+ deltacells verify /data/my_dataset # checks the CRC of every tile and decodes it
98
+ ```
99
+
100
+ The input and the output can also be `gs://` paths. All files must have the same genes, and `X` must hold raw integer counts.
101
+ The [conversion page](https://cellarium-ai.github.io/deltacells/convert.html) covers the options, Google Cloud Storage, disk
102
+ space and safety.
103
+
104
+ Read it:
105
+
106
+ ```python
107
+ import numpy as np
108
+ from deltacells import open_dataset
109
+
110
+ ds = open_dataset("/data/my_dataset") # or "gs://bucket/prefix"
111
+ ds.n_cells, ds.n_genes, ds.limits # limits: cumulative number of cells per tile
112
+ batch = ds.get_batch(np.array([5, 99_000, 12])) # any global cell indices, in any order; returns a CSR SparseBatch
113
+ batch.indptr, batch.indices, batch.values # int64, int32, float32 numpy arrays
114
+ x = batch.to_torch_csr() # torch.sparse_csr tensor sharing memory (needs torch)
115
+ batch.to_scipy()
116
+ ds.var_names, ds.gene_order # gene names, and the original column of each stored gene
117
+ ```
118
+
119
+ Write your own data:
120
+
121
+ ```python
122
+ from deltacells import DatasetWriter
123
+
124
+ with DatasetWriter("/data/out", n_genes=n_genes, tile_size=10_000, gene_order=order, var_names=names) as w:
125
+ for block in blocks: # scipy CSR, or anything scipy can convert; integer counts in [0, 2**31 - 1]
126
+ w.add_tile(block) # every tile but the last must have exactly tile_size cells
127
+ ```
128
+
129
+ For single tiles there is a lower-level interface: `encode_tile(matrix) -> bytes`, `write_tile(path, matrix)`,
130
+ `Tile(bytes).decode(threads=4)` and `read_tile(path)`.
131
+
132
+ ## Documentation
133
+
134
+ * [Install](https://cellarium-ai.github.io/deltacells/install.html): wheels, extras, building from source.
135
+ * [Converting h5ad files](https://cellarium-ai.github.io/deltacells/convert.html): `deltacells convert` for local and
136
+ `gs://` data.
137
+ * [Using a dataset in a PyTorch DataLoader](https://cellarium-ai.github.io/deltacells/dataloader.html): a worked example, and the
138
+ pointer to [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml) for a full PyTorch Lightning setup.
139
+ * [Cell metadata (obs) and genes (var)](https://cellarium-ai.github.io/deltacells/obs.html): what is stored, how to read it in
140
+ training, and the local cache.
141
+ * [Benchmarks](https://cellarium-ai.github.io/deltacells/benchmarks.html): size, decode speed, comparison with other formats,
142
+ DataLoader throughput, and how to reproduce them with `make benchmark`.
143
+ * [How the encoding works](https://cellarium-ai.github.io/deltacells/encoding.html): why sorting the genes makes the data compress
144
+ so well, with figures from a real shard.
145
+ * [Format specification](https://cellarium-ai.github.io/deltacells/format.html): the exact layout of a tile and a dataset.
146
+
147
+ ## Cell metadata (obs) and genes (var)
148
+
149
+ A dataset can also hold the cell metadata (`obs`) and the gene table (`var`), stored beside the tiles so that a loader that needs
150
+ no metadata pays nothing for it. The converter stores them from the h5ad files. In training, you choose the obs columns you need
151
+ and they are copied once into a local, memory-mapped cache, after which looking up a batch takes about 0.2 ms:
152
+
153
+ ```python
154
+ ds = open_dataset("gs://bucket/prefix", obs_columns=["cell_type", "donor_id"])
155
+ codes = ds.obs.take(
156
+ cell_indices, ["cell_type", "donor_id"]
157
+ ) # integer codes; ds.obs.categories("cell_type") is the vocabulary
158
+ ds.var # the gene table (pandas), in the stored column order
159
+ ```
160
+
161
+ See [Cell metadata (obs) and genes (var)](https://cellarium-ai.github.io/deltacells/obs.html) for what is stored, how it is read and
162
+ cached, and what it costs.
163
+
164
+ ## Limitations
165
+
166
+ * **Integer counts only**: integers in [0, 2^31 - 1] (float32 batches are exact up to 2^24). Counts above 65535, and gaps above
167
+ 65535 between a cell's consecutive expressed genes (possible with more than 65,536 genes), are stored as exceptions and must be
168
+ rare: the writer refuses a tile with more than `max(1024, nnz / 200)` of either kind, which is not what raw counts look like.
169
+ Sparse feature spaces such as ATAC peaks are out of scope, and so are normalized or float data.
170
+ * **Conversion has no resume.** A failed conversion is started again with `--overwrite` (see
171
+ [Converting h5ad files](https://cellarium-ai.github.io/deltacells/convert.html)).
172
+ * **Platforms.** Linux and macOS, little-endian hosts only. CI covers Linux x86-64 (Python 3.10 to 3.13) and macOS arm64
173
+ (Python 3.12). Windows is not supported.
174
+ * **Obs needs `pyarrow` and `pandas`.** Categorical, numeric, boolean and string columns are supported; exclude others, such as
175
+ datetimes. The ranged reads used to fetch obs from a bucket (`GCSBackend.read_range`) have not been tested against a real
176
+ bucket. The local obs cache is uncompressed Arrow, several times the size of the stored parquet for small-integer columns.
177
+ * **Concurrent `get_batch` calls** on one dataset object, from several threads, are serialized by a lock (use one dataset object
178
+ per worker process).
179
+ * **Gene order depends on the files sampled for it** (up to `--sort-genes-max-files`, spread evenly over the inputs). The same
180
+ cells split into a different number of files can sort the genes slightly differently when there are more files than that. With
181
+ `--no-sort-genes`, or when every file is used, the result depends only on the cell order and the tile size.
182
+ * **The converter does not shuffle.** A tile holds consecutive cells (a tile that spans the end of one file and the start of the
183
+ next mixes just those two). If the input is sorted by donor, tissue or similar, shuffle the cells across files first (for example
184
+ with `annslicer`).
185
+ * **Compression time.** Level 19 takes about 5 s per 10,000-cell tile with 8 threads (about 24 s with one chunk). Lower levels
186
+ trade size for speed (level 12: about 1.3 s, level 3: about 0.7 s, at files 6% and 11% larger).
187
+ * **Reference loader.** `examples/reference_loader.py` shows how to call the dataset from a `DataLoader`. It is an example, not
188
+ part of the package API, and it does not provide resume-from-checkpoint, DDP padding or `drop_last_indices`; for training, use
189
+ [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml).
190
+
191
+ ## Development
192
+
193
+ ```bash
194
+ make test # the test suite: format validation, round trips and edge cases, gather, dataset (prefetch, caching, pickling,
195
+ # corruption), obs, backends, h5ad conversion, CLI, torch / DataLoader, benchmark smoke tests
196
+ make lint # ruff
197
+ make typecheck # mypy
198
+ make docs # the documentation (needs the docs extra), built into docs/build/html
199
+ make benchmark # all benchmarks that need no real data, on a synthetic dataset
200
+ ```
201
+
202
+ [DEVELOPING.md](https://github.com/cellarium-ai/deltacells/blob/main/DEVELOPING.md) describes building from source, the code
203
+ layout, how to change the format, how the documentation is built, and how releases are made.
204
+
205
+ ## License
206
+
207
+ BSD-3-Clause (see [LICENSE](https://github.com/cellarium-ai/deltacells/blob/main/LICENSE)). deltacells links libzstd, which is
208
+ dual-licensed BSD-3-Clause / GPL-2.0 and is used under the BSD license.
@@ -0,0 +1,170 @@
1
+ # deltacells
2
+
3
+ [![build](https://github.com/cellarium-ai/deltacells/actions/workflows/ci.yml/badge.svg)](https://github.com/cellarium-ai/deltacells/actions/workflows/ci.yml)
4
+
5
+ **Fast, compact tiles of single-cell count matrices, built for feeding a training `DataLoader`.**
6
+
7
+ **Documentation: https://cellarium-ai.github.io/deltacells/**
8
+
9
+ Training a model on tens of millions of cells means reading raw counts over and over, and the format they are stored in decides
10
+ how fast that goes and how much disk it takes. deltacells stores a count matrix as a directory (or bucket prefix) of *tiles* of
11
+ about 10,000 cells. Each tile is one self-contained object that a small C library decodes straight into CSR arrays.
12
+
13
+ ## Why deltacells
14
+
15
+ * **Very fast data loading.** A 10,000-cell tile decodes in about 0.1 s on one core and 0.02 s on eight, with no intermediate
16
+ AnnData or Arrow objects. A PyTorch `DataLoader` reading shuffled batches on a laptop sustains 45,000 to 95,000 cells per
17
+ second, depending on the number of workers.
18
+ * **Small on disk.** A dataset is about 40% smaller than the same data in [BPCells](https://github.com/bnprks/BPCells) (3.8 vs
19
+ 6.7 kB per cell) and roughly a third of the size of a gzip-compressed h5ad file. The key idea is to store genes in order of
20
+ decreasing total counts, which makes the values that remain to be compressed small and repetitive.
21
+ * **Fast enough to keep a GPU fed.** On a single thread, decoding is slower than BPCells' decoder (about 2.6 times as long per
22
+ tile), in exchange for the smaller files. With a few `DataLoader` workers, each decoding on its own core, deltacells is
23
+ designed to keep a GPU busy, as in the data loading of [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml). Smaller
24
+ files also mean less to download when the dataset lives in a bucket.
25
+
26
+ One real 10,000-cell shard (38,094 genes), counts only, read from a local file into memory on an M2 Pro laptop:
27
+
28
+ | format | size on disk | decode, 1 thread | decode, 8 threads |
29
+ |---|---|---|---|
30
+ | h5ad (gzip) | 12.5 kB per cell | 1170 ms | single-threaded reader |
31
+ | BPCells (C++ decoder) | 6.7 kB per cell | **48 ms** | **30 ms** |
32
+ | **deltacells** | **3.8 kB per cell** | 125 ms | 39 ms |
33
+
34
+ The [benchmarks page](https://cellarium-ai.github.io/deltacells/benchmarks.html) has the details, other hardware, the DataLoader
35
+ throughput, and how to reproduce all of it.
36
+
37
+ **Status: alpha.** CI runs on Linux x86-64 (Python 3.10 to 3.13) and macOS arm64 (Python 3.12). Reading tiles from Google Cloud
38
+ Storage and converting h5ad files from and to a bucket have been exercised against real buckets. See
39
+ [Limitations](#limitations).
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install deltacells
45
+ ```
46
+
47
+ Prebuilt wheels are available for Linux (x86-64 and aarch64) and macOS (arm64) on Python 3.10 to 3.13. On other platforms, pip
48
+ builds the package from source, which needs a C compiler and libzstd. Optional extras: `h5ad` (to convert h5ad files), `obs` (cell
49
+ metadata), `torch` and `gcs` (`gs://` paths). For example, `pip install "deltacells[h5ad,obs,gcs]"`. See the
50
+ [install page](https://cellarium-ai.github.io/deltacells/install.html).
51
+
52
+ ## Quick start
53
+
54
+ Convert h5ad shards of any size into a dataset of exact-size tiles (this sorts the genes, re-chunks the cells and compresses):
55
+
56
+ ```bash
57
+ deltacells convert --h5ad-glob "shards/*.h5ad" --output /data/my_dataset
58
+ deltacells info /data/my_dataset
59
+ deltacells verify /data/my_dataset # checks the CRC of every tile and decodes it
60
+ ```
61
+
62
+ The input and the output can also be `gs://` paths. All files must have the same genes, and `X` must hold raw integer counts.
63
+ The [conversion page](https://cellarium-ai.github.io/deltacells/convert.html) covers the options, Google Cloud Storage, disk
64
+ space and safety.
65
+
66
+ Read it:
67
+
68
+ ```python
69
+ import numpy as np
70
+ from deltacells import open_dataset
71
+
72
+ ds = open_dataset("/data/my_dataset") # or "gs://bucket/prefix"
73
+ ds.n_cells, ds.n_genes, ds.limits # limits: cumulative number of cells per tile
74
+ batch = ds.get_batch(np.array([5, 99_000, 12])) # any global cell indices, in any order; returns a CSR SparseBatch
75
+ batch.indptr, batch.indices, batch.values # int64, int32, float32 numpy arrays
76
+ x = batch.to_torch_csr() # torch.sparse_csr tensor sharing memory (needs torch)
77
+ batch.to_scipy()
78
+ ds.var_names, ds.gene_order # gene names, and the original column of each stored gene
79
+ ```
80
+
81
+ Write your own data:
82
+
83
+ ```python
84
+ from deltacells import DatasetWriter
85
+
86
+ with DatasetWriter("/data/out", n_genes=n_genes, tile_size=10_000, gene_order=order, var_names=names) as w:
87
+ for block in blocks: # scipy CSR, or anything scipy can convert; integer counts in [0, 2**31 - 1]
88
+ w.add_tile(block) # every tile but the last must have exactly tile_size cells
89
+ ```
90
+
91
+ For single tiles there is a lower-level interface: `encode_tile(matrix) -> bytes`, `write_tile(path, matrix)`,
92
+ `Tile(bytes).decode(threads=4)` and `read_tile(path)`.
93
+
94
+ ## Documentation
95
+
96
+ * [Install](https://cellarium-ai.github.io/deltacells/install.html): wheels, extras, building from source.
97
+ * [Converting h5ad files](https://cellarium-ai.github.io/deltacells/convert.html): `deltacells convert` for local and
98
+ `gs://` data.
99
+ * [Using a dataset in a PyTorch DataLoader](https://cellarium-ai.github.io/deltacells/dataloader.html): a worked example, and the
100
+ pointer to [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml) for a full PyTorch Lightning setup.
101
+ * [Cell metadata (obs) and genes (var)](https://cellarium-ai.github.io/deltacells/obs.html): what is stored, how to read it in
102
+ training, and the local cache.
103
+ * [Benchmarks](https://cellarium-ai.github.io/deltacells/benchmarks.html): size, decode speed, comparison with other formats,
104
+ DataLoader throughput, and how to reproduce them with `make benchmark`.
105
+ * [How the encoding works](https://cellarium-ai.github.io/deltacells/encoding.html): why sorting the genes makes the data compress
106
+ so well, with figures from a real shard.
107
+ * [Format specification](https://cellarium-ai.github.io/deltacells/format.html): the exact layout of a tile and a dataset.
108
+
109
+ ## Cell metadata (obs) and genes (var)
110
+
111
+ A dataset can also hold the cell metadata (`obs`) and the gene table (`var`), stored beside the tiles so that a loader that needs
112
+ no metadata pays nothing for it. The converter stores them from the h5ad files. In training, you choose the obs columns you need
113
+ and they are copied once into a local, memory-mapped cache, after which looking up a batch takes about 0.2 ms:
114
+
115
+ ```python
116
+ ds = open_dataset("gs://bucket/prefix", obs_columns=["cell_type", "donor_id"])
117
+ codes = ds.obs.take(
118
+ cell_indices, ["cell_type", "donor_id"]
119
+ ) # integer codes; ds.obs.categories("cell_type") is the vocabulary
120
+ ds.var # the gene table (pandas), in the stored column order
121
+ ```
122
+
123
+ See [Cell metadata (obs) and genes (var)](https://cellarium-ai.github.io/deltacells/obs.html) for what is stored, how it is read and
124
+ cached, and what it costs.
125
+
126
+ ## Limitations
127
+
128
+ * **Integer counts only**: integers in [0, 2^31 - 1] (float32 batches are exact up to 2^24). Counts above 65535, and gaps above
129
+ 65535 between a cell's consecutive expressed genes (possible with more than 65,536 genes), are stored as exceptions and must be
130
+ rare: the writer refuses a tile with more than `max(1024, nnz / 200)` of either kind, which is not what raw counts look like.
131
+ Sparse feature spaces such as ATAC peaks are out of scope, and so are normalized or float data.
132
+ * **Conversion has no resume.** A failed conversion is started again with `--overwrite` (see
133
+ [Converting h5ad files](https://cellarium-ai.github.io/deltacells/convert.html)).
134
+ * **Platforms.** Linux and macOS, little-endian hosts only. CI covers Linux x86-64 (Python 3.10 to 3.13) and macOS arm64
135
+ (Python 3.12). Windows is not supported.
136
+ * **Obs needs `pyarrow` and `pandas`.** Categorical, numeric, boolean and string columns are supported; exclude others, such as
137
+ datetimes. The ranged reads used to fetch obs from a bucket (`GCSBackend.read_range`) have not been tested against a real
138
+ bucket. The local obs cache is uncompressed Arrow, several times the size of the stored parquet for small-integer columns.
139
+ * **Concurrent `get_batch` calls** on one dataset object, from several threads, are serialized by a lock (use one dataset object
140
+ per worker process).
141
+ * **Gene order depends on the files sampled for it** (up to `--sort-genes-max-files`, spread evenly over the inputs). The same
142
+ cells split into a different number of files can sort the genes slightly differently when there are more files than that. With
143
+ `--no-sort-genes`, or when every file is used, the result depends only on the cell order and the tile size.
144
+ * **The converter does not shuffle.** A tile holds consecutive cells (a tile that spans the end of one file and the start of the
145
+ next mixes just those two). If the input is sorted by donor, tissue or similar, shuffle the cells across files first (for example
146
+ with `annslicer`).
147
+ * **Compression time.** Level 19 takes about 5 s per 10,000-cell tile with 8 threads (about 24 s with one chunk). Lower levels
148
+ trade size for speed (level 12: about 1.3 s, level 3: about 0.7 s, at files 6% and 11% larger).
149
+ * **Reference loader.** `examples/reference_loader.py` shows how to call the dataset from a `DataLoader`. It is an example, not
150
+ part of the package API, and it does not provide resume-from-checkpoint, DDP padding or `drop_last_indices`; for training, use
151
+ [cellarium-ml](https://github.com/cellarium-ai/cellarium-ml).
152
+
153
+ ## Development
154
+
155
+ ```bash
156
+ make test # the test suite: format validation, round trips and edge cases, gather, dataset (prefetch, caching, pickling,
157
+ # corruption), obs, backends, h5ad conversion, CLI, torch / DataLoader, benchmark smoke tests
158
+ make lint # ruff
159
+ make typecheck # mypy
160
+ make docs # the documentation (needs the docs extra), built into docs/build/html
161
+ make benchmark # all benchmarks that need no real data, on a synthetic dataset
162
+ ```
163
+
164
+ [DEVELOPING.md](https://github.com/cellarium-ai/deltacells/blob/main/DEVELOPING.md) describes building from source, the code
165
+ layout, how to change the format, how the documentation is built, and how releases are made.
166
+
167
+ ## License
168
+
169
+ BSD-3-Clause (see [LICENSE](https://github.com/cellarium-ai/deltacells/blob/main/LICENSE)). deltacells links libzstd, which is
170
+ dual-licensed BSD-3-Clause / GPL-2.0 and is used under the BSD license.
@@ -0,0 +1,65 @@
1
+ # Copyright Contributors to the Cellarium project.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ """
5
+ Size / speed trade-offs of the encoder on one tile of an existing dataset: zstd level, number of chunks, and the effect of gene order.
6
+
7
+ python benchmarks/bench_compression.py DATASET [--tile 0] [--levels 3,12,19] [--chunks 1,8]
8
+
9
+ The tile is decoded, then re-encoded with each setting (with the stored gene order, and with a random gene order to show what
10
+ sorting genes by expression buys). Decode times are single-threaded.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import statistics
17
+ import time
18
+
19
+ import numpy as np
20
+
21
+ from deltacells import LocalBackend, Tile, encode_tile, permute_columns
22
+ from deltacells.manifest import MANIFEST_NAME, Manifest
23
+
24
+
25
+ def main(argv=None) -> int:
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("dataset")
28
+ parser.add_argument("--tile", type=int, default=0)
29
+ parser.add_argument("--levels", default="3,12,19")
30
+ parser.add_argument("--chunks", default="1,8")
31
+ parser.add_argument("--threads", type=int, default=8, help="Encoder threads.")
32
+ args = parser.parse_args(argv)
33
+
34
+ backend = LocalBackend(args.dataset)
35
+ Manifest.from_json(bytes(backend.read(MANIFEST_NAME))) # validates the manifest
36
+ matrix = Tile(backend.read(Manifest.tile_name(args.tile))).to_scipy()
37
+ shuffled = permute_columns(matrix, np.random.default_rng(0).permutation(matrix.shape[1]))
38
+ n = matrix.shape[0]
39
+ print(f"tile {args.tile}: {n} cells, {matrix.nnz} nonzeros ({matrix.nnz / n:.0f}/cell)")
40
+ print(
41
+ f"{'gene order':<10}{'level':>6}{'chunks':>8}{'size MB':>9}{'kB/cell':>9}{'B/nnz':>7}{'encode s':>10}{'decode ms (1 thr)':>19}"
42
+ )
43
+ for label, m in (("sorted", matrix), ("random", shuffled)):
44
+ for level in [int(x) for x in args.levels.split(",")]:
45
+ for chunks in [int(x) for x in args.chunks.split(",")]:
46
+ t0 = time.perf_counter()
47
+ blob = encode_tile(m, n_chunks=chunks, level=level, threads=args.threads)
48
+ t_enc = time.perf_counter() - t0
49
+ tile = Tile(blob)
50
+ out_i, out_v = np.empty(tile.nnz, np.int32), np.empty(tile.nnz, np.int32)
51
+ scratch = np.empty(tile.info.scratch_nbytes, dtype=np.uint8)
52
+ tile.decode(out_indices=out_i, out_values=out_v, scratch=scratch)
53
+ times = []
54
+ for _ in range(5):
55
+ t0 = time.perf_counter()
56
+ tile.decode(out_indices=out_i, out_values=out_v, scratch=scratch)
57
+ times.append(time.perf_counter() - t0)
58
+ print(
59
+ f"{label:<10}{level:>6}{chunks:>8}{len(blob) / 1e6:>9.1f}{len(blob) / n / 1e3:>9.2f}{len(blob) / m.nnz:>7.3f}{t_enc:>10.1f}{statistics.median(times) * 1e3:>19.0f}"
60
+ )
61
+ return 0
62
+
63
+
64
+ if __name__ == "__main__":
65
+ raise SystemExit(main())