Spatial¶
Imaging-based and spot-based assays: Xenium, Visium, CosMx and MERSCOPE. The
container mirrors Seurat v5's — an FOV holding Centroids, Segmentation
and Molecules boundaries, or a VisiumV2 holding the H&E image and its
ScaleFactors.
radius on a Visium FOV
Seurat stores spot_diameter_fullres in the FOV's radius slot — a
diameter where a radius is named — and Radius() on its own VisiumV2
returns NULL. load_visium stores a radius. The slide's fixed 100 µm spot
pitch is what settles which reading is right; the working is in
the Visium vignette.
find_spatially_variable_features computes Moran's I on R's inverse-square
distance weights, not on a kNN graph. Those give different answers, and the kNN
version was the bug.
Loading¶
load_xenium
¶
load_xenium(path: Union[str, Path], assay: str = 'Xenium', fov_column: Optional[str] = None, project: str = 'Xenium', keep_controls: bool = False)
Load a 10x Xenium output bundle into a Truecell object with images.
Expects (from the Xenium output folder):
* cell_feature_matrix/ — 10x MTX triplet (barcodes/features/matrix)
* cells.parquet or cells.csv[.gz] — with cell_id,
x_centroid, y_centroid (and optionally fov / transcript QC)
By default only Gene Expression features are kept in the assay (matching
Seurat's LoadXenium, which routes Negative Control / Blank codewords to
separate assays); set keep_controls=True to retain every feature row.
fov_column, if given and present in the cells table, splits the object
into one image per FOV; otherwise a single image is created.
Source code in truecell/spatial/loaders.py
load_visium
¶
load_visium(path: Union[str, Path], assay: str = 'Spatial', project: str = 'Visium', image: bool = True, image_resolution: str = 'lowres', filter_by_tissue: bool = True, slice_name: str = 'slice1')
Load a 10x Visium output into a Truecell object with spot coordinates.
Expects:
* filtered_feature_bc_matrix/ — 10x MTX triplet
* spatial/tissue_positions.csv (or tissue_positions_list.csv) with
barcode, in_tissue, array row/col and pixel row/col columns
Optionally (image=True, the default) also reads
spatial/tissue_{hires,lowres}_image.png and spatial/scalefactors_json.json,
producing a VisiumV2 image that carries the H&E
tissue photo — what spatial_dim_plot / spatial_feature_plot draw on. A
bundle with no PNG still loads; you just get a plain FOV, as before.
Parameters:
-
image(bool, default:True) –read the tissue image + scale factors (default True).
-
image_resolution(str, default:'lowres') –'lowres' (default) or 'hires'; falls back to whichever is present. Matches
Read10X_Image'simage.name = "tissue_lowres_image.png". -
filter_by_tissue(bool, default:True) –keep only spots with
in_tissue == 1(default True), matchingRead10X_Image'sfilter.matrix = TRUE. -
slice_name(str, default:'slice1') –key for the FOV in
obj.images(default"slice1", the nameLoad10X_Spatialuses).
Notes
Spot coordinates stay in full-resolution pixels, matching
tissue_positions.csv. The scale factors convert them to image pixels —
see VisiumV2.scale_coordinates.
The three defaults above changed to match Seurat. Reading a bundle the way
earlier versions did is load_visium(path, image_resolution="hires",
filter_by_tissue=False, slice_name="spatial").
Source code in truecell/spatial/loaders.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
load_cosmx
¶
load_cosmx(path: Union[str, Path], expr_file: Optional[str] = None, meta_file: Optional[str] = None, assay: str = 'Nanostring', fov_column: str = 'fov', project: str = 'CosMx')
Load NanoString CosMx output (exprMat + metadata CSVs) into a Truecell object.
expr_file is a cell×gene CSV (rows = cells, first columns cell/fov ids);
meta_file carries CenterX_global_px / CenterY_global_px and a FOV
column. If names are omitted, *exprMat_file.csv / *metadata_file.csv
are auto-detected in path.
Source code in truecell/spatial/loaders.py
load_merscope
¶
load_merscope(path: Union[str, Path], expr_file: Optional[str] = None, meta_file: Optional[str] = None, assay: str = 'Vizgen', fov_column: str = 'fov', project: str = 'MERSCOPE', keep_controls: bool = False)
Load a Vizgen MERSCOPE output into a Truecell object with images.
Mirrors Seurat's LoadVizgen. Expects, in path:
* cell_by_gene.csv — cell × gene counts (leading column = cell id)
* cell_metadata.csv — with center_x / center_y (and usually
fov, volume)
Blank/control barcodes (Blank-* columns) are dropped by default, matching
LoadVizgen; set keep_controls=True to retain them.
fov_column, if present in the metadata, splits the object into one image
per FOV; otherwise a single image is created.
Source code in truecell/spatial/loaders.py
Containers¶
FOV
¶
FOV(boundaries: Optional[dict[str, BoundaryType]] = None, molecules: Optional[dict[str, Molecules]] = None, coords_x_orientation: str = 'horizontal', assay: str = '', key: str = 'fov_', misc: Optional[dict] = None)
Bases: SpatialImage
Field of view — modern container for spatially-resolved single-cell coordinates.
Mirrors R's FOV class from fov.R. Can hold multiple segmentation boundaries (Centroids, Segmentation) and molecule-level FISH data (Molecules).
Slots
molecules(dict[str, Molecules])boundaries(dict[str, BoundaryType])coords_x_orientation(str) — which axis x maps to in visualisation
Source code in truecell/spatial/fov.py
overlay
¶
Return cells from self whose centroids fall within any boundary of query.
Source code in truecell/spatial/fov.py
create_fov
¶
create_fov(coords: DataFrame, type_: str = 'centroids', nsides: int = 0, radius: Optional[float] = None, theta: Optional[float] = None, assay: str = '', key: str = 'fov_') -> FOV
Create an FOV from a coordinate DataFrame.
type_ : 'centroids' | 'segmentation' | 'molecules'
Source code in truecell/spatial/fov.py
create_fovs
¶
create_fovs(coords: DataFrame, fov: Optional[Union[str, 'pd.Series', Sequence]] = None, assay: str = '', default_name: str = 'fov') -> dict[str, FOV]
Build a {name: FOV} dict of centroid FOVs from a coordinate frame.
coords must have columns x, y, cell. When fov is given (a column
name in coords or a per-row array of labels) the cells are split into one
FOV per distinct label — matching a multi-FOV Xenium/CosMx run. Otherwise a
single FOV named default_name is returned.
Shared by the spatial loaders and from_anndata so both build identical,
accessor-ready seurat.images structures.
Source code in truecell/spatial/fov.py
Centroids
¶
Centroids(coords: DataFrame, nsides: int = 0, radius: Optional[float] = None, theta: Optional[float] = None, assay: str = '', key: str = 'centroids_', misc: Optional[dict] = None)
Bases: SpatialImage
Cell centroid coordinates.
Mirrors R's Centroids class from centroids.R. Stores one (x, y) coordinate per cell representing the center of that cell.
Slots
_coords(pd.DataFrame) — columns: x, y, cellnsides(int) — number of polygon sides (0 = circle)radius_(Optional[float]) — spot radius (for spot-based technologies)theta_(Optional[float]) — angle offset
Source code in truecell/spatial/centroids.py
create_centroids
¶
create_centroids(coords: DataFrame, nsides: int = 0, radius: Optional[float] = None, theta: Optional[float] = None, assay: str = '', key: str = 'centroids_') -> Centroids
Source code in truecell/spatial/centroids.py
Segmentation
¶
Segmentation(coords: DataFrame, assay: str = '', key: str = 'segmentation_', misc: Optional[dict] = None)
Bases: SpatialImage
Cell boundary polygon coordinates.
Mirrors R's Segmentation class from segmentation.R. Each cell may have multiple (x, y) polygon vertices.
Slots
_coords(pd.DataFrame) — columns: x, y, cell (multiple rows per cell)
Source code in truecell/spatial/segmentation.py
simplify
¶
Reduce polygon vertex count by removing vertices closer than tol.
Simple Douglas–Peucker–style approximation per cell.
Source code in truecell/spatial/segmentation.py
create_segmentation
¶
create_segmentation(coords: DataFrame, assay: str = '', key: str = 'segmentation_') -> Segmentation
Molecules
¶
Bases: SpatialImage
Spatially-resolved molecule (FISH) data.
Mirrors R's Molecules class from molecules.R. Each row represents one molecule detection event.
Slots
_coords(pd.DataFrame) — columns: x, y, gene, [cell] 'cell' is optional (not all FISH protocols assign cells)
Source code in truecell/spatial/molecules.py
create_molecules
¶
create_molecules(coords: DataFrame, assay: str = '', key: str = 'molecules_') -> Molecules
SpatialImage
¶
Bases: KeyMixin, ABC
Abstract base class for all spatial image objects.
Mirrors R's SpatialImage virtual class from spatial.R. Subclasses must implement: cells, dim, get_tissue_coordinates, rename_cells, subset.
Slots
assay(str) — associated assay namemisc(dict) — miscellaneous storage_key(str) — inherited from KeyMixin
Source code in truecell/spatial/base.py
VisiumV2
¶
VisiumV2(boundaries: Optional[dict] = None, molecules: Optional[dict[str, Molecules]] = None, image: Optional[ndarray] = None, scale_factors: Optional[ScaleFactors] = None, image_resolution: str = 'lowres', coords_x_orientation: str = 'horizontal', assay: str = '', key: str = 'slice1_', misc: Optional[dict] = None)
Bases: FOV
An FOV that also carries the Visium tissue image and its scale factors.
Mirrors Seurat v5's VisiumV2. Behaves as a normal FOV everywhere (its
coordinates stay in fullres pixels); the extra slots are what
spatial_dim_plot / spatial_feature_plot need to draw spots on tissue.
Slots
image(np.ndarray) — (H, W[, C]), or Nonescale_factors(ScaleFactors) — or Noneimage_resolution(str) —'hires'or'lowres', which image is stored
Source code in truecell/spatial/visium.py
from_fov
classmethod
¶
from_fov(fov: FOV, image: Optional[ndarray] = None, scale_factors: Optional[ScaleFactors] = None, image_resolution: str = 'lowres') -> 'VisiumV2'
Upgrade a plain FOV in place-ish: same boundaries, plus the image.
Source code in truecell/spatial/visium.py
get_image
¶
radius
¶
Spot radius in full-resolution pixels (half the spot diameter).
scale_factor
¶
Fullres → image-pixel multiplier for the stored (or given) resolution.
Source code in truecell/spatial/visium.py
scale_coordinates
¶
Tissue coordinates rescaled into the pixel space of the stored image.
Same frame as get_tissue_coordinates, with x/y multiplied
by the scale factor — i.e. ready to overlay on get_image.
Source code in truecell/spatial/visium.py
spot_radius
¶
Spot radius in the pixel space of the stored image (None if unknown).
ScaleFactors
dataclass
¶
The four values in a Visium spatial/scalefactors_json.json.
spot : spot diameter in full-resolution pixels fiducial : fiducial-marker diameter in full-resolution pixels hires : multiply a fullres coordinate by this to land on tissue_hires_image.png lowres : ditto for tissue_lowres_image.png
Spatial analysis¶
get_tissue_coordinates
¶
Return centroid coordinates for the object, concatenated across images.
Mirrors object-level GetTissueCoordinates. Returns a DataFrame with
columns x, y, cell, image (one row per cell per image).
Source code in truecell/spatial/analysis.py
spatial_knn
¶
spatial_knn(coords: ndarray, k: int = 10, query: Optional[ndarray] = None) -> tuple[ndarray, ndarray]
k-nearest-neighbour distances and indices on a set of coordinates.
Mirrors FNN::get.knn (query=None, self excluded) and
FNN::get.knnx (query given, searched against coords).
Returns (distances, indices) each shape (n_query, k); indices point
into coords.
Source code in truecell/spatial/analysis.py
nearest_neighbor_distance
¶
nearest_neighbor_distance(seurat, group_by: str, reference, target=None, image: Optional[Union[str, Sequence[str]]] = None) -> DataFrame
Distance from each reference cell to the nearest target cell.
Computed per image (so distances never cross FOVs), then concatenated.
If target is None it defaults to reference (nearest same-type cell,
self excluded) — this is the mast-to-nearest-mast idiom.
Returns a DataFrame: cell, image, reference, target, distance.
Source code in truecell/spatial/analysis.py
local_neighborhood
¶
local_neighborhood(seurat, group_by: str, reference=None, k: int = 10, image: Optional[Union[str, Sequence[str]]] = None) -> DataFrame
Composition of each cell's k nearest neighbours (self excluded).
For every reference cell (all cells if reference is None) returns
the count and proportion of each group_by category among its k spatial
neighbours. Columns: cell, image, n_<group>…, prop_<group>….
prop_<reference> is the "local density" of that type; the n_<group>
columns are the raw neighbourhood composition.
Source code in truecell/spatial/analysis.py
build_niche_assay
¶
build_niche_assay(seurat, group_by: str, image: Optional[Union[str, Sequence[str]]] = None, k: int = 20, niches: int = 4, assay_name: str = 'niche', cluster: bool = True, seed: int = 0) -> 'object'
Build a neighbourhood-composition assay and cluster cells into niches.
Mirrors Seurat v5's BuildNicheAssay: each cell's feature vector is the
count of every group_by category among its k spatial neighbours.
The composition matrix is stored as a new assay (assay_name); when
cluster is True the proportions are k-means clustered into niches
groups and written to meta_data['niches'].
Source code in truecell/spatial/analysis.py
find_spatially_variable_features
¶
find_spatially_variable_features(seurat, features: Optional[list[str]] = None, method: str = 'moransi', k: int = 10, weights: str = 'inverse_square', assay: Optional[str] = None, layer: Optional[str] = None, image: Optional[Union[str, Sequence[str]]] = None, r_metric: float = 5.0, bandwidth: float = 1.0) -> DataFrame
Rank features by how spatially structured their expression is.
Mirrors R's FindSpatiallyVariableFeatures(obj, method = ...).
Parameters:
-
features(Optional[list[str]], default:None) –restrict to these genes (default: all in the assay). Passing the variable features keeps this fast on large panels.
-
method(str, default:'moransi') –"moransi"(default) or"markvariogram". -
weights(str, default:'inverse_square') –moransi only —
"inverse_square"(default) reproduces R exactly: 1/d² between every pair of cells, row-standardised."knn"uses a k-nearest-neighbour graph instead, an approximation that trades R's O(n²) cost for O(nk). Prefer it only when the slide is too large to wait on; see the note below on how far the two answers drift apart. -
k(int, default:10) –moransi only, weights="knn" only — neighbours per cell.
-
r_metric(float, default:5.0) –markvariogram only — the distance at which to read the variogram, in units of the median nearest-neighbour spacing. The default of 5 therefore means "five cells apart".
-
bandwidth(float, default:1.0) –markvariogram only — half-width of the distance band around
r_metric, in the same units. Widen it if the slide is sparse and the band catches too few pairs to average over. -
layer(Optional[str], default:None) –expression layer (default: the normalized
data). -
image(Optional[Union[str, Sequence[str]]], default:None) –image name(s) to draw coordinates from (default: all).
Returns:
-
DataFrame indexed by gene, sorted so that rank 1 is the most spatially– -
variable, with the columns for the chosen method:– -
``moransi``–moransi(I; +ve = spatially clustered),moransi_pval(two-sided, normality assumption),moransi_padj(Benjamini-Hochberg) andmoransi_rank. -
``markvariogram``–markvariogram(γ atr_metric; lower = more spatially structured, ≈ 1 = none) andmarkvariogram_rank. There is no p-value — the variogram has no closed-form null, and R does not offer one either. -
The same columns are also written into the assay's feature-level metadata,– -
as ``find_variable_features`` does.–
Notes
Run this on log-normalized data (the default). Be aware that when a few
strongly spatial genes dominate a cell's library size, log-normalization
divides every gene by a spatially-structured total and leaks that structure
into otherwise-flat genes — inflating their score. That is a property of
compositional normalization, not of either statistic; it is negligible on
real panels but can bite on small synthetic ones.
The moransi statistic matches R to ~1e-15 with the default weights.
The p-value deliberately does not. R runs a 999-permutation test through
Rfast2::moranI, which on a 248-gene panel returns just 14 distinct values
and ties 233 genes at its 1/1025 floor — it cannot separate the most spatially
variable gene from the two-hundredth. The normal-approximation p-value here is
continuous, deterministic, and standard for Moran's I, so it is kept; matching
R would cost information and gain nothing. weights="knn" changes the
statistic itself, not just its cost. It is a decent approximation — on 2,000
Xenium cells it tracks R at Pearson 0.986 and recovers 46 of R's top 50 genes
— but it runs a median 1.23× high, differs by up to 0.14 in absolute I, and
agrees on only 7 of R's top 10. Close enough to mislead, not close enough to
call parity, which is why it is no longer the default.
markvariogram differs from R's in two deliberate ways. R passes
r.metric straight through to spatstat in raw coordinate units, so the
same script gives different answers on pixel and micron coordinates; here r
is measured in nearest-neighbour spacings and is scale-free. And γ is a
kernel-weighted ratio estimator rather than spatstat's
translation-corrected one, so the absolute γ values are close to but not
identical with R's. The gene ranking — the thing the function is for — is
what carries over.
Source code in truecell/spatial/variable_features.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
composition_test
¶
composition_test(seurat, group_by: str, split_by: str, reference: Optional[str] = None) -> DataFrame
Directional abundance test of group_by categories across split_by.
Mirrors the enrichment table an analyst builds by hand: for a two-level
split_by (e.g. condition), each group_by category (e.g. cluster) gets
a log2(prop_test / prop_reference) and a Fisher exact p (that category vs
all others). p-values are BH-adjusted. The overall chi-square p is stored in
df.attrs['chisq_p'].
Parameters:
-
group_by(str) –categorical metadata column tested for enrichment (rows).
-
split_by(str) –metadata column with exactly two levels (the conditions).
-
reference(Optional[str], default:None) –which
split_bylevel is the denominator (default: the first sorted level). log2 > 0 ⇒ enriched in the other level.
Returns:
-
A DataFrame ordered by ``log2_ratio``, with the columns ``group``,– -
``n_<ref>``, ``n_<test>``, ``prop_<ref>``, ``prop_<test>``, ``log2_ratio``,– -
``odds_ratio``, ``p``, ``padj``, ``sig`` and ``enriched_in``.–