English | 简体中文
Tissue organization and masked cell-state prediction from spatial transcriptomics
Cyto.Spatial (SUDOKU) uses gene counts and spatial coordinates to describe how cells are organized in human and mouse tissue. With all cells visible, it produces cell and neighborhood embeddings for clustering and cross-section retrieval. When some cells are masked, it predicts their states at known locations from nearby visible cells.
- Expression tokenization (top left). The expression encoder maps each cell's gene counts to a continuous embedding. Two-level vector quantization describes its state with a coarse code and a residual code. The reconstruction decoder in the diagram is used to train the tokenizer.
- Spatial backbone (left). A denoising Transformer takes the continuous embeddings of visible cells and uses 2D rotary position embeddings (2D-RoPE) to incorporate their spatial coordinates. For masked cells, the expression embedding is replaced by a learned mask token while the coordinate is kept. The two prediction heads estimate the coarse and residual codes.
- Representation (top right,
t = 0). With all inputs visible, the backbone returns contextual cell embeddings. Pooling embeddings within a neighborhood gives a niche embedding for downstream tasks such as clustering and cross-section retrieval. - Generation (bottom right,
t > 0). Inference iteratively fills masked positions, committing the most confident code pairs first and using them as context for later steps.
Results are from the manuscript. Bold marks the better score. Best baseline is selected separately for each dataset and metric from the main-text and appendix comparisons.
| Category | Task / metric | SUDOKU | Best baseline |
|---|---|---|---|
| Representation | Niche retrieval HESTA: mean AUPRC over 8 organs ↑ DLPFC: mean Pearson r over 7 junction classes ↑ |
HESTA: 0.496 DLPFC: 0.687 |
HESTA: 0.447 (GeST) DLPFC: 0.684 (QueST) |
| Representation | Multi-scale clustering Mouse brain: mean ARI over 3 levels ↑ |
0.452 | 0.295 (STAGATE) |
| Generation | Masked cell-state prediction Cell-type accuracy over all 972 questions ↑ |
0.401 | 0.385 (distance-weighted 300-NN) |
| Generation | SPAC-seq immune recruitment Mean Spearman correlation over 3 sections ↑ Median normalized clone rank error ↓ |
Spearman: 0.77 Rank error: 0.12 |
Spearman: 0.62 (direct prediction) Rank error: 0.20 (GeST) |
Retrieval examples. (a) A HESTA heart neighborhood is used to find the corresponding region in another section (AUPRC: 0.99 for SUDOKU, 0.61 for CellPLM). (b) For a DLPFC L4/L5 junction, the similarity map is compared with a reference derived from layer labels (Pearson r: 0.87 and 0.24).
Benchmark inputs, not predictions. Columns show four mask shapes at 40% masking; rows show three difficulty levels. Gray cells are visible to the model. Colors show the true types of masked cells, which are withheld from the model. Across 972 questions, zero-shot SUDOKU scores 0.355, below the distance-weighted 300-NN baseline (0.385); fine-tuning raises accuracy to 0.401.
Measured and generated cell distributions. (a) Spearman correlation between predicted and measured immune-cell fractions across clones. (b) Normalized clone rank error (lower is better). (c) In the example shown, immune cells make up 65% of the measured cells in the band around the clone, versus 63% in SUDOKU’s output and 10% in GeST’s.
Use Python 3.10 or newer. From the repository root, install the package with the Leiden extra for the graph-clustering examples:
python -m pip install '.[leiden]'
sudoku-st --helpThe two inference weight files are:
tokenizer.safetensors: the expression encoder, its inference normalization statistics, and the two VQ codebooks.spatial_model.safetensors: the spatial backbone, mask embedding, and the two prediction heads.
Use --weights-dir ./weights to load local weights. A local weights directory must contain both files under the exact names above. The loader verifies file sizes, SHA-256 hashes, and codebook alignment; it does not deserialize Python pickles. CPU is the default; use --device cuda with a CUDA-enabled PyTorch installation.
from sudoku_st import load_model
model = load_model(weights_dir="./weights", device="cpu")SUDOKU uses a custom architecture; load it with sudoku_st.load_model, not AutoModel.
| Input | Requirement |
|---|---|
| AnnData file | .h5ad, one tissue section per embed or cluster command; one window of one section per generate command. Run separate sections or windows separately. |
.X |
Raw nonnegative integer gene counts, not pre-normalized data. CSR sparse or dense is recommended on disk. SUDOKU maps genes, drops unmatched genes, and applies log1p(10,000 × count / max(sum of mapped counts, 1)) per cell. |
| Gene IDs | Unversioned Ensembl IDs in .var_names, or use --gene-id-col COLUMN for .var[COLUMN]. Set --species human or --species mouse. The included slot map has 15,903 one-to-one orthologs. Default model-side coverage floor is 50%; only lower --min-gene-coverage intentionally for targeted panels, whose performance is not established here. For duplicate mapped IDs, the first occurrence is kept. |
| Coordinates | Two finite numeric axes. .obs['x'] and .obs['y'] take precedence over .obsm['spatial']. Set --coord-scale-um to micrometers per coordinate unit, default 1. RoPE coordinates are divided by the median positive nearest-neighbor distance; pass --pitch-um to override it with the whole-section pitch, recommended for cropped windows. |
| Cell IDs | Unique .obs_names, used for all outputs and joins. |
| Output | Pick a new output path in an existing directory. The commands do not overwrite files. Optional scores are printed as JSON on stdout. |
Run each level on the same section with its own output. The presets match the manuscript's readout radii and pooling choices:
--level |
Radius | Representation |
|---|---|---|
region |
100 µm | Mean-pooled spatial neighborhood |
band |
50 µm | Mean-pooled spatial neighborhood |
cell-type |
50 µm | Contextual center-cell state |
sudoku-st cluster --weights-dir ./weights --input mouse_brain.h5ad --species mouse --level region --n-clusters 12 --out region.csv
sudoku-st cluster --weights-dir ./weights --input mouse_brain.h5ad --species mouse --level band --n-clusters 7 --out band.csv
sudoku-st cluster --weights-dir ./weights --input mouse_brain.h5ad --species mouse --level cell-type --n-clusters 32 --out cell_type.csvThe cluster counts above are examples; use values appropriate to the section. With Leiden, --n-clusters searches resolution on all cells and returns the closest number found; without it, the command uses --resolution directly. The default is Leiden on a 15-nearest-neighbor graph of the embeddings. --method kmeans --n-clusters K is a lightweight alternative, not the paper's clustering method. Optional --label-key region_label --min-class-cells 20 --min-class-fraction 0.001 reports ARI/NMI for eligible labeled cells. Labels never enter the model or resolution search. The manuscript used a class-count-matching search on the labeled subset and median aggregation over six sections; this standalone command is not a replication of that evaluator.
Supply a window with raw counts for visible cells and .obs['is_target'] true for cells to infer (or use --mask-key). Both visible and target cells need coordinates. Target expression rows may be all zeros: only visible rows are passed to the encoder. For a cropped window, replace 12.5 below with the measured whole-section pitch in micrometers.
sudoku-st generate --weights-dir ./weights --input masked_window.h5ad --species human --pitch-um 12.5 --out generated_codes.csvThis decodes with 32 scheduled steps and temperature zero. The output contains target cell IDs, two predicted code indices, and their joint confidence at the commit step. It does not predict new cell coordinates or return gene-count matrices. Use at most 1,000 cells per window by default.
For cell-type readout, supply a CSV with code0,code1,label through --code-labels. Construct it from annotated, independent reference sections from the same tissue group, not from the evaluation section. The code-map command counts labels for each code pair and picks the majority label (ties break alphabetically); it does not update the model. The reference label CSV has cell_id,label columns.
sudoku-st embed --weights-dir ./weights --input reference_section.h5ad --species human --out reference.npz
sudoku-st code-map --embeddings reference.npz --reference-labels reference_labels.csv --out code_labels.csv
sudoku-st generate --weights-dir ./weights --input masked_window.h5ad --species human --code-labels code_labels.csv --label-key cell_type --out generated_types.csvWith --label-key, truth labels are read only for scoring after inference. The accuracy denominator is all annotated target cells; unmapped code pairs count as incorrect for those cells. mapped_fraction is reported separately. For type predictions without evaluation, omit --label-key.
embed exports an NPZ archive with ids, cell (center-cell representations), niche (pooled representations), latent (pre-quantization expression latents), codes, and neighborhood metadata. The default neighborhood cap is 1,000 cells including the center. Nearest cells are retained when clipped and the command reports how many neighborhoods were clipped. Reduce --neighborhood-batch to lower attention memory usage.
sudoku-st embed --weights-dir ./weights --input query_section.h5ad --species human --radius-um 150 --out query.npz
sudoku-st embed --weights-dir ./weights --input target_section.h5ad --species human --radius-um 150 --out candidates.npz
sudoku-st retrieve --query-embeddings query.npz --query-cells query_cells.csv --candidate-embeddings candidates.npz --out retrieval.csvquery_cells.csv has a cell_id column listing the cells in one niche of interest. Their embeddings are averaged to make one query vector; candidates are ranked by cosine similarity. Use 150 µm for a HESTA-style readout or 318 µm for a DLPFC-style readout. To score a query, pass --truth truth.csv --metric ap for binary labels, or --metric pearson for continuous labels such as precomputed graph-kernel matching scores. The truth CSV has cell_id,score columns.
.
├── README.md
├── README_zh.md
├── pyproject.toml
├── examples/
│ └── smoke_test.py
└── src/sudoku_st/
├── cli.py # Task entry points and output formats
├── model.py # Weight loading, tokenizer, and spatial backbone
├── data.py # AnnData input and gene-slot mapping
├── embedding.py # Cell and niche representations
├── generation.py # Masked-state decoding
├── readouts.py # Clustering, retrieval, and metrics
└── assets/ # Gene-slot map and weight integrity manifest



