Localize¶
Localize predicts a spatial position for every cell of a dissociated (scRNA-seq) dataset, using a spatial dataset as the map. The result is a new embedding on the scRNA-seq data, so coloring, contours, territories and the other spatial tools then work on cells that never had coordinates. Every prediction comes with two scores that say how far to trust it.
Where to find it
Analyze → Spatial → Localize → Open Localize tool…
Load the spatial reference and the scRNA-seq query as two datasets first (File → Load…).
How it works¶
Localize is a k-nearest-neighbor projection. Each query cell's expression profile is compared with every reference cell's over the shared genes. The k most similar reference cells are its transcriptional neighbors, and their coordinates are combined into one predicted position. The method is transparent and its parameters are interpretable, and it fails in ways that can be measured rather than in ways hidden inside a fitted model.
The failure the tool is built around¶
Averaging the positions of k similar cells only means something if those cells sit together. A cell type scattered through the tissue (immune cells, fibroblasts) has neighbors everywhere, and their average lands in the middle of the tissue, possibly where that type never occurs. A type that sits in two distant patches is worse: the average lands in the gap. Both produce a smooth, convincing, wrong map, and nothing about the coordinate gives it away. For this reason the tool leads with confidence and accuracy rather than parameters.
Two scores per cell¶
| Score | Column | Question it answers |
|---|---|---|
| Confidence | obs['<key>_confidence'] |
Do the cell's neighbors agree on a location? The similarity-weighted spatial spread of the k neighbors, divided by the reference tissue's own radius (RMS distance of reference cells from their centroid). 1 means they sat on one spot; 0 means they were as scattered as the whole tissue. For transport, the same spread is measured over the cell's posterior across reference spots. |
| Similarity | obs['<key>_similarity'] |
Does the cell resemble anything in the reference at all? Mean similarity to its k neighbors. A cell type absent from the spatial data is still placed somewhere; a low similarity is what says so. |
The two are independent, and a prediction needs both to be trusted. After a run, color the query by <key>_confidence to see which regions of the map to believe.
Transform and similarity¶
The Expression transform is applied to each dataset separately, which is what cancels platform-level differences in per-gene capture efficiency between, say, a 10x scRNA-seq run and a Visium section.
zscore(default): standardizes each gene within its own dataset. Genes with negligible variance are damped rather than inflated to unit variance.rank: ranks genes within each cell, so a cell's profile is its gene ordering. Survives any monotone difference between platforms; withrank, raw counts and log-normalized input give identical predictions.log1p,none: for data already normalized the same way on both sides.
Similarity is Pearson correlation between cells (default), cosine, or negative Euclidean distance. Correlation on z-scored data and cosine coincide.
Aggregation: how the neighbors become one position¶
| Aggregation | What it does |
|---|---|
| weighted mean (default) | Similarity-weighted mean of the k neighbors' coordinates. The worst of the k contributes nothing. |
| median | Weighted median per axis; less pulled by a few scattered neighbors. |
| densest cluster | Averages only the tightest cluster among the neighbors. For a type in two patches it lands in one of them rather than in the gap, but it cannot tell which patch; on the bundled benchmark it picks correctly about half the time. Needs a k of about 20 to have something to cluster. |
| best match | The position of the single most similar reference cell, so a prediction is always on real tissue. k then affects only the confidence score. |
| injective (a distinct spot each) | Best match solved for all cells at once so that no two cells share a reference spot. Needs at least as many reference cells as query cells; the option is disabled otherwise. |
| transport (fills the tissue) | Entropic optimal transport between query cells and reference spots (Cuturi 2013). Each cell's position is the mean over its row of the transport plan. |
Filling the tissue and carrying a gradient are the two ends of one trade-off, and the averaging estimators and the single-location estimators sit at opposite ends. Measured on an E11.5 mouse limb pair (2,683 dissociated cells against 9,773 spots), using Map quality:
weighted mean(k = 50): the map covered 15% of the tissue area and placed the epidermis, the embryo's outermost tissue, in the middle of the bud (pattern score -0.11), while keeping the proximodistal gradient (0.24 of the 0.34 the reference itself reaches).best match: full tissue area (1.00) and the epidermis back on the rim (+0.29), with the gradient essentially gone (0.05 of 0.34).
Neither end is "more accurate". Score them under Map quality and choose against what you need.
injective: pile-up, exact and candidate-restricted solving
best match takes each cell's best spot independently, so a reference spot that is better recovered and correlates well with everything absorbs many cells. injective maximizes total similarity subject to every cell getting a distinct spot. On the limb pair it put 2,683 cells on 2,683 distinct spots, where best match used 1,522, in about a second, at a cost of a few percent of mean similarity. Its axis correlations match best match's to within noise: it fixes pile-up, not placement.
It also asserts that the query's composition matches the tissue's. Dissociation changes which cell types survive, so forcing one cell per spot pushes over-represented types into places they do not belong.
Large pairs. Solving exactly needs the whole query × reference similarity matrix in memory (12 bytes per entry during the solve; 50,000 cells against 20,000 spots would need about 12 GB). Up to 40 million entries Skopia solves exactly with scipy.optimize.linear_sum_assignment (Crouse 2016). Above that, each cell chooses among its 128 best candidate spots, seeded with a greedy one-to-one assignment so a full matching always exists, and solved as a sparse bipartite matching. Every cell still gets its own spot. On the limb pair, the candidate solution's total similarity was 0.18% below the exact optimum, 87% of cells landed on the identical spot, and Map quality could not tell the two apart (area 0.99 against 1.00, epidermis +0.285 against +0.298). A pair that used to be refused (15,000 cells against 30,000 spots) completes in about 6 seconds. The run reports which solver produced it, and the result panel says near-optimal, not optimal when the candidate path was used.
transport: the estimator between the two ends
Transport solves for all cells at once under a constraint that the predicted population occupy the reference tissue, while an entropy term lets each cell hedge across several spots. It is the one aggregation that moves along the trade-off rather than sitting at an end.
On the limb pair at the default ε = 0.05: area 0.437 over 1,774 distinct spots, the epidermis at +0.271 and the distal markers at +0.353 (against -0.256 and -0.532 for weighted mean in the same comparison), with axis fidelity better than best match on both axes. That run took 203 s.
- ε (spread) controls how much each cell may hedge. It is measured against the double-centered spread of the cost matrix, so the same value means the same thing whatever transform and similarity you chose. Lower ε fills more of the tissue and behaves more like best match; higher ε averages more and collapses toward the center. On the limb pair the useful band was about 0.03 to 0.3; at ε = 0.5 the map covered 5.5% of the tissue with the epidermis inverted again, and ε = 0.03 had not converged after 400 iterations.
- The solver runs in the log domain (stable at small ε) for up to 300 iterations and reports its iteration count and final marginal error.
- Up to 40 million query × reference entries it uses the full reference. Above that it uses a spatially stratified subsample (at least one spot per occupied bin) and says so.
- Like
injective, it assumes the query's composition matches the tissue's: a type under-represented in the query still has its share of tissue filled by something else.
weighted mean stays the default until transport has been tested on more than one tissue.
Run it¶
- Load both datasets. Open Analyze → Spatial → Localize → Open Localize tool….
- Under Datasets, check Reference (only datasets with coordinates are offered) and Query (the cells to place). Writes to shows the query and the embedding name.
- Read the gene overlap line: how many of the reference's genes the query shares. Below 10 shared genes the run is refused.
- Choose the Similarity basis (genes): all shared genes, a boolean
.varflag on the reference, or a gene set from the Gene panel. - Choose the Source matrix for each side.
- Set Parameters and read the advice that appears below them.
- Click Check accuracy on the reference and compare the error with its baselines.
- Type the output name (default
X_spatial_pred) under Apply and click Localize. - Select the new embedding in the embedding picker and color by
<key>_confidence. - After making several maps, click Score predicted maps under Map quality to compare them.
Parameters¶
| Parameter | Default | What it does |
|---|---|---|
| Similarity basis (genes) | All shared genes | Genes the similarity is computed over. The reference owns this choice because it is the dataset that shows which genes carry positional signal. spatially_variable from Spatial Autocorrelation on the reference is the principled choice; highly_variable is a stand-in. |
| Reference matrix | .X |
Which matrix on the reference the profiles come from. Each option shows the scale Skopia detects for it. |
| Query matrix | .X |
Same, for the query. |
| Neighbours (k) | 15 | How many reference cells vote on each prediction. Too few is noisy; too many pulls every prediction toward the tissue center. |
| Expression transform | z-score per dataset | zscore, rank, log1p or none, applied to each dataset separately. |
| Similarity | correlation | correlation, cosine or euclidean. |
| Aggregation | weighted mean | See the table above. |
| ε (spread) | 0.05 | Transport only. |
| Min confidence | 0 | Cells below this confidence get no coordinate (NaN) rather than a fabricated one. 0 places every cell and leaves filtering to you. |
| Reference section column | none | For a multi-section reference: each query cell is assigned the weighted-majority section among its neighbors, and its coordinate is drawn from that section only, so a position is never averaged across the gap between sections. |
| Output name (under Apply) | X_spatial_pred |
The .obsm key, and the prefix of the score columns. |
Starting points (from Show how to choose these in the tool):
| Situation | Use |
|---|---|
| scRNA-seq onto Visium or Xenium (the usual case) | zscore + correlation + weighted mean, basis spatially_variable, k about √(reference cells) |
| Platforms that differ a lot, or unknown normalization | rank + cosine: survives any monotone difference, at the cost of ignoring magnitude |
| Both datasets from the same platform and pipeline | Any transform; euclidean becomes meaningful |
Advice the tool raises¶
The tool warns about combinations that are actually bad, against the current settings:
- k below 5 (confidence is then unreliable), or above a tenth of the reference cells (every prediction drifts to the center).
none+euclideanacross platforms (sequencing depth dominates the distance), andnonewith any metric unless both datasets are normalized alike.- fewer than 30 shared genes in the basis (treat the map as coarse).
densest clusterwith k below 12, and thatbest matchno longer uses k for the coordinate.- for
injectiveandtransport, the composition assumption; ε at or above 0.5 or at or below 0.02. - a positive Min confidence: thresholds do not transfer between gene bases.
The ring or edge warning. With weighted mean selected and gene sets curated in the Gene panel, Skopia asks the reference alone, before any run, where the mean position of each set's population falls. The population is taken as the top 2%, 5%, 10% and 20% of reference cells by the set's score, and the worst case is reported. If the population forms a ring or hugs the tissue edge, its mean is a place none of its cells occupy (the mean of a ring is its hole), and weighted mean will send every query cell of that type there. The risk compares how far the mean sits from the population with how far the population's members sit from each other; at 0.5 or above, the tool names the set. On the E11.5 limb reference: skin 0.88, blood 0.70, cartilage 0.18, muscle 0.00. It does not catch a population scattered through a ring-shaped tissue; the outside column of Map quality reports that case after a run.
Source matrix and smoothing¶
Smoothing the reference over its own spatial graph (Analyze → Preprocess → Smooth on the spatial dataset, see Preprocess) averages out spot-level counting noise in the profiles every query cell is matched against. On an E11.5 hindlimb, holding out 3,000 spots and predicting them from the other 22,934 (smoothing graph built on the reference spots only), smoothing roughly tripled the share of spots placed within 10% of the tissue radius, from 2.3% to 7.9%, with little further gain past k = 20 × 2 steps. Whether the reference was smoothed on counts or on a log layer made no measurable difference, because the per-dataset transform absorbs it. Absolute accuracy was low on that tissue, which is mostly homogeneous mesenchyme, so the comparison is relative.
Check accuracy¶
Check accuracy on the reference holds out a fifth of the reference, predicts it from the other four fifths with the current parameters, and compares the predictions with the true positions. It always uses the reference's matrix on both sides. It reports:
- the median error, next to two baselines: predicting the tissue center, and predicting at random. An error reported alone cannot be judged; on a compact tissue the center baseline is strong. If the method does not beat the center, the panel says the map would not mean anything.
- the share of held-out cells within 10% of the tissue diameter.
- Structure preserved: do cells predicted near each other actually sit near each other?
- confidence tracks error: the correlation between confidence and actual error. A confidence score that does not predict error is decoration; this should be clearly negative.
Treat the result as an upper bound: both halves come from one platform, and the real scRNA-seq mapping will be worse.
Map quality¶
Score predicted maps scores every predicted embedding on the query against the reference, so parameter variants can be ranked instead of eyeballed. It scores embeddings whose names contain pred or spatial, other than spatial and X_spatial.
| Column | Meaning |
|---|---|
| area | How much of the tissue the predictions cover, relative to the reference; 1.0 is right. Well under 1 means the map collapsed toward the center, which averaging does. Highlighted below 0.5 or above 1.8. |
| outside | Share of predictions outside the tissue. A map can reach the right area by ejecting cells; this catches it. |
| spots used | Distinct reference locations the predictions land on, out of the number of cells. Few means many cells piled onto the same spots. |
| One column per Gene panel gene set | Spatial pattern fidelity: does that cell type land where it lives in the reference? This matters most. A negative value means the type was placed where it is not. Hover for the axis correlation, shown as x of y possible, where y is what the reference itself reaches. |
Every metric is rank-based, so rescaling either dataset, or a map that shrinks its coordinates, cannot move it. That is what makes maps from different settings comparable. Read pattern fidelity together with area: on a map collapsed onto a few spots, a pattern score can be high and mean nothing (ε = 2.0 on the limb pair scored the epidermis at +0.783 on a map covering 0.4% of the tissue).
Territories¶
If the reference has saved territories, a Territories section appears:
- Import territory boundaries from the reference copies the boundaries onto the query, against the predicted embedding, stamped
imported:<file>@<date>. - Assign cells to territories after localizing then labels every query cell that got a coordinate; unplaced cells stay blank. No confidence filter is applied, since
<key>_confidencesits beside the result.
What it writes¶
All on the query dataset:
| Where | What |
|---|---|
obsm['X_spatial_pred'] (or your name) |
Predicted coordinates; NaN rows for cells below Min confidence. |
obs['<key>_confidence'] |
Confidence, 0 to 1. |
obs['<key>_similarity'] |
Mean similarity to the neighbors. |
obs['<key>_section'] |
With a reference section column: the section each cell was assigned to. |
uns['skopia_territories_json'], obs['territory_<type>'] |
With the territory options. |
The result panel reports how many cells were placed, the median confidence and how many cells score below 0.2.
Tips and pitfalls¶
A smoother map is what failure looks like
Averaging many scattered neighbors gives a smooth, plausible map. Tune against Check accuracy and Map quality, not against the picture.
Use the map with the other spatial tools
The predicted embedding is not under a name the spatial tools auto-detect. Choose it as the dataset's coordinates from their prerequisite warning; see Choosing the dataset's coordinates. Every result computed on it inherits the map's error.
Bundled benchmark with exact ground truth
toy_localize_spatial.h5ad (reference) and toy_localize_scrna.h5ad (query, true positions in obsm['spatial_true'] and obs['true_x'], obs['true_y']) are built to break the method. Four region-restricted programs are the tractable case; Immune is uniformly dispersed, Bipolar sits in two distant patches sharing one program, and Circulating exists only in the query. The query is sequenced about 4 times deeper with different dropout and per-gene capture, so the transform matters. With the defaults when the tool shipped: median error 32.8 against 66.7 for the center and 86.8 at random; confidence tracked error at r = -0.66; and 386 of 900 query cells scored below 0.2 confidence, where 388 are unlocalizable by construction.
Gene basis on a targeted panel
Restricting to spatially variable genes helps most on whole-transcriptome data. On the 120-gene benchmark panel, 40 highly variable genes scored a median error of 32.7 against 33.0 for all 120.