API#

This page provides detailed API documentation for TrackCell.

Input/Output Functions#

IO module for TrackCell package.

This module provides functions for reading and writing single-cell and spatial transcriptomics data.

trackcell.io.read_hd_bin(datapath: str | Path, sample: str | None = None, binsize: int = 16, matrix_file_h5: str = 'filtered_feature_bc_matrix.h5', matrix_file_dir: str = 'filtered_feature_bc_matrix', tissue_positions_file: str = 'spatial/tissue_positions.parquet', hires_image_file: str = 'spatial/tissue_hires_image.png', lowres_image_file: str = 'spatial/tissue_lowres_image.png', scalefactors_file: str = 'spatial/scalefactors_json.json') → AnnData[source]#

Read 10X HD SpaceRanger bin-level output (2um/8um/16um) and create an AnnData object with spatial information.

This function reads the output from SpaceRanger pipeline and creates an AnnData object that includes spatial coordinates, tissue images, and scalefactors for bin-level data.

Parameters:
  • datapath (str or Path) – Path to the SpaceRanger output directory containing bin-level outputs.

  • sample (str, optional) – Sample name. If None, will be inferred from the path.

  • binsize (int, default 16) – Bin size in micrometers. Common values are 2, 8, or 16. This information will be stored in adata.uns[“spatial”][sample][“binsize”].

  • matrix_file_h5 (str, default "filtered_feature_bc_matrix.h5") – Name of the H5 matrix file. Will be tried first.

  • matrix_file_dir (str, default "filtered_feature_bc_matrix") – Name of the matrix directory. Will be used if H5 file is not available.

  • tissue_positions_file (str, default "spatial/tissue_positions.parquet") – Path to tissue positions file (parquet or csv format).

  • hires_image_file (str, default "spatial/tissue_hires_image.png") – Path to the high-resolution tissue image relative to datapath.

  • lowres_image_file (str, default "spatial/tissue_lowres_image.png") – Path to the low-resolution tissue image relative to datapath.

  • scalefactors_file (str, default "spatial/scalefactors_json.json") – Name of the scalefactors JSON file.

Returns:

AnnData object containing: - Expression matrix in .X - Cell metadata in .obs - Gene metadata in .var - Spatial coordinates in .obsm[“spatial”] - Tissue images in .uns[“spatial”][sample][“images”] - Scalefactors in .uns[“spatial”][sample][“scalefactors”] - Bin size in .uns[“spatial”][sample][“binsize”]

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.read_hd_bin("SpaceRanger4.0/Case1/outs", sample="Case1")
>>> print(adata)
AnnData object with n_obs × n_vars = 10000 × 2000
    obs: 'barcode'
    obsm: 'spatial'
    uns: 'spatial'

Notes

This function expects the SpaceRanger output to have the following structure: - filtered_feature_bc_matrix.h5 or filtered_feature_bc_matrix/: Expression matrix - spatial/tissue_positions.parquet or spatial/tissue_positions.csv: Spatial coordinates - spatial/tissue_hires_image.png: High-resolution tissue image - spatial/tissue_lowres_image.png: Low-resolution tissue image - spatial/scalefactors_json.json: Image scaling factors

trackcell.io.read_hd_cellseg(datapath: str | Path, sample: str | None = None, cell_segmentations_file: str = 'graphclust_annotated_cell_segmentations.geojson', matrix_file: str = 'filtered_feature_cell_matrix.h5', hires_image_file: str = 'spatial/tissue_hires_image.png', lowres_image_file: str = 'spatial/tissue_lowres_image.png', scalefactors_file: str = 'spatial/scalefactors_json.json') → AnnData[source]#

Read 10X HD SpaceRanger cell segmentation output and create an AnnData object with spatial information.

This function reads the output from SpaceRanger pipeline and creates an AnnData object that includes spatial coordinates, cell segmentations, and tissue images.

Parameters:
  • datapath (str or Path) – Path to the SpaceRanger output directory containing segmented outputs.

  • sample (str, optional) – Sample name. If None, will be inferred from the path.

  • cell_segmentations_file (str, default "graphclust_annotated_cell_segmentations.geojson") – Name of the cell segmentations file.

  • matrix_file (str, default "filtered_feature_cell_matrix.h5") – Name of the filtered feature-cell matrix file.

  • hires_image_file (str, default "spatial/tissue_hires_image.png") – Path to the high-resolution tissue image relative to datapath.

  • lowres_image_file (str, default "spatial/tissue_lowres_image.png") – Path to the low-resolution tissue image relative to datapath.

  • scalefactors_file (str, default "spatial/scalefactors_json.json") – Name of the scalefactors JSON file.

Returns:

AnnData object containing: - Expression matrix in .X - Cell metadata in .obs - Gene metadata in .var - Spatial coordinates in .obsm[“spatial”] - Tissue images in .uns[“spatial”][sample][“images”] - Scalefactors in .uns[“spatial”][sample][“scalefactors”] - Cell geometries in .uns[“spatial”][sample][“geometries”] (GeoDataFrame)

with no CRS: coordinates are full-resolution image pixels, the same frame as obsm["spatial"].

  • Cell geometries in .obs[“geometry”] (WKT strings for serialization)

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.read_hd_cellseg("SpaceRanger4.0/Case1/outs/segmented_outputs", sample="Case1")
>>> print(adata)
AnnData object with n_obs × n_vars = 1000 × 2000
    obs: 'cellid'
    obsm: 'spatial'
    uns: 'spatial'

Notes

This function expects the SpaceRanger output to have the following structure: - graphclust_annotated_cell_segmentations.geojson: Cell segmentation polygons - filtered_feature_cell_matrix.h5: Expression matrix - spatial/tissue_hires_image.png: High-resolution tissue image - spatial/tissue_lowres_image.png: Low-resolution tissue image - spatial/scalefactors_json.json: Image scaling factors

trackcell.io.read_xenium_cellseg(datapath: str | Path, sample: str | None = None, cells_file: str = 'cells.parquet', boundaries_file: str = 'cell_boundaries.parquet', nucleus_boundaries_file: str = 'nucleus_boundaries.parquet', matrix_file: str = 'cell_feature_matrix.h5', experiment_file: str = 'experiment.xenium', panel_file: str = 'gene_panel.json', slice_separate: bool = False, slice_eps: float = 80.0, slice_min_samples: int = 10, slice_min_cells: int = 1000, slice_start: int = 1, slice_prefix: str = 'S', build_polygons: bool = True, include_nucleus: bool = True, store_wkt: bool = True, verbose: bool = True) → AnnData[source]#

Read 10x Xenium cell segmentation output and create an AnnData object.

Reads Xenium Analyzer output files (parquet boundaries, HDF5 expression matrix) and builds a squidpy-compatible AnnData with GeoDataFrame cell polygons.

Parameters:
  • datapath (str or Path) – Path to the Xenium output directory containing: - cell_feature_matrix.h5 - cells.parquet - cell_boundaries.parquet - experiment.xenium

  • sample (str, optional) – Sample name. If None, infers from directory name.

  • cells_file (str) – Name of the cell metadata parquet file.

  • boundaries_file (str) – Name of the cell boundary parquet file (long-table format).

  • nucleus_boundaries_file (str) – Name of the nucleus boundary parquet file.

  • matrix_file (str) – Name of the HDF5 expression matrix file.

  • experiment_file (str) – Name of the experiment metadata JSON file.

  • panel_file (str) – Name of the gene panel JSON file.

  • slice_separate (bool, default False) – If True, run DBSCAN slice separation on cell centroids and add obs['slice_id'] / obs['slice_cluster'] (for Xenium TMA data).

  • slice_eps (float, default 80.0) – DBSCAN neighborhood radius in µm when slice_separate=True.

  • slice_min_samples (int, default 10) – DBSCAN min_samples when slice_separate=True.

  • slice_min_cells (int, default 1000) – Minimum cells per cluster to keep as a valid slice.

  • slice_start (int, default 1) – Starting index for slice IDs (S001 when slice_start=1).

  • slice_prefix (str, default "S") – Prefix for slice IDs.

  • build_polygons (bool, default True) – If False, skip reading cell_boundaries.parquet entirely (no polygons, no compact boundary arrays, no WKT strings).

  • include_nucleus (bool, default True) – If False, skip nucleus_boundaries.parquet.

  • store_wkt (bool, default True) – If True, store WKT strings in .obs['geometry'] for serialization.

  • verbose (bool, default True) – Print progress messages.

Returns:

AnnData object with: - Expression matrix in .X (CSR, cells × genes) - Cell metadata in .obs (centroids, area, counts, etc.) - Gene metadata in .var (gene_ids, feature_types) - Spatial coordinates in .obsm[‘spatial’] - Cell polygons in .uns[‘spatial’][sample][‘geometries’] (GeoDataFrame) - Cell boundary arrays in .uns[‘cell_boundaries’] (compact vertex arrays,

layout='offset' with a row-aligned n_vertices)

  • Nucleus boundary arrays in .uns[‘nucleus_boundaries’] (if available, same layout)

  • WKT geometry strings in .obs[‘geometry’] (for serialization)

  • Experiment metadata in .uns[‘experiment’]

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.read_xenium_cellseg("/path/to/xenium/output")
>>> print(adata)
AnnData object with n_obs × n_vars = 819023 × 10029
trackcell.io.sync_geometries_after_subset(adata, sample: str | None = None)[source]#

Synchronize geometries in adata.uns[“spatial”][sample][“geometries”] after subsetting the AnnData object.

When you subset an AnnData object (e.g., adata[mask] or adata[adata.obs[‘col’] == ‘value’]), the adata.obs[“geometry”] column is automatically subset, but the GeoDataFrame in adata.uns[“spatial”][sample][“geometries”] is not automatically updated. This function ensures that the geometries GeoDataFrame matches the subsetted cells.

Parameters:
  • adata (sc.AnnData) – AnnData object that has been subsetted.

  • sample (str, optional) – Sample name. If None, will use the first available sample in adata.uns[“spatial”].

Returns:

The same AnnData object with synchronized geometries (modified in place).

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.read_hd_cellseg("path/to/data", sample="sample1")
>>> # Subset the data
>>> adata_subset = adata[adata.obs['classification'] == 'Cluster-1'].copy()
>>> # Synchronize geometries
>>> tcio.sync_geometries_after_subset(adata_subset, sample="sample1")
>>> # Now adata_subset.uns["spatial"]["sample1"]["geometries"] only contains geometries for subsetted cells
trackcell.io.convert_annohdcell_to_trackcell(bin_h5ad_path: str | Path, output_h5ad_path: str | Path | None = None, sample: str | None = None, labels_key: str = 'labels_joint', bin_size_um: float = 2.0, create_polygons: bool = True, buffer_polygons: bool = True) → AnnData[source]#

Convert annohdcell 2μm bin h5ad to trackcell-compatible cell-level h5ad.

This function reads a bin-level h5ad file from annohdcell (with cell assignment labels) and converts it to a cell-level h5ad file compatible with trackcell visualization tools. It aggregates bin counts into cells and creates polygon geometries for each cell.

Parameters:
  • bin_h5ad_path (str or Path) – Path to the input 2μm bin h5ad file (e.g., b2c_2um.h5ad from annohdcell)

  • output_h5ad_path (str or Path, optional) – Path to save the output h5ad file. If None, will not save to disk.

  • sample (str, optional) – Sample name for spatial metadata. If None, inferred from filename.

  • labels_key (str, default "labels_joint") – Column name in .obs containing cell assignment labels (0 = unassigned)

  • bin_size_um (float, default 2.0) – Size of each bin in micrometers

  • create_polygons (bool, default True) – Whether to create polygon geometries from bin coordinates

  • buffer_polygons (bool, default True) – Whether to buffer polygons slightly to account for bin size

Returns:

Cell-level AnnData object with: - .X: Summed expression counts per cell - .obs: Cell metadata including “geometry” (WKT strings) - .obsm[“spatial”]: Cell centroid coordinates - .uns[“spatial”][sample][“geometries”]: GeoDataFrame with cell polygons - .uns[“spatial”][sample][“images”]: Tissue images (if present in input) - .uns[“spatial”][sample][“scalefactors”]: Scale factors

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.convert_annohdcell_to_trackcell(
...     "b2c_2um.h5ad",
...     output_h5ad_path="trackcell_format.h5ad",
...     sample="sample1"
... )
>>> print(adata)
>>> # Now can use trackcell visualization functions
>>> import trackcell.pl as tcpl
>>> tcpl.spatial_cell(adata, library_id="sample1")

Notes

  • Input h5ad must have .obs[labels_key] with integer cell labels (0 = unassigned)

  • Input h5ad must have .obsm[“spatial”] with bin coordinates

  • Bins with label 0 are excluded (unassigned bins)

  • Gene counts are summed across all bins in each cell

  • Cell coordinates are the mean of constituent bin coordinates

  • Polygon geometries are created using convex hull of bin coordinates

trackcell.io.add_geometries_to_annohdcell_output(bin_h5ad_path: str | Path, cell_h5ad_path: str | Path, output_h5ad_path: str | Path | None = None, sample: str | None = None, labels_key: str = 'labels_joint', bin_size_um: float = 2.0, buffer_polygons: bool = True, n_jobs: int = -1) → AnnData[source]#

Add polygon geometries to annohdcell’s final cell h5ad using bin-level data.

This function reads both the 2μm bin h5ad (with cell labels) and the final cell-level h5ad from annohdcell, then adds polygon geometries to the cell h5ad by creating convex hulls from the constituent bins of each cell.

Parameters:
  • bin_h5ad_path (str or Path) – Path to the 2μm bin h5ad file (e.g., b2c_2um.h5ad) with cell labels

  • cell_h5ad_path (str or Path) – Path to the final cell h5ad file (e.g., b2c_cell.h5ad) from annohdcell

  • output_h5ad_path (str or Path, optional) – Path to save the output h5ad file. If None, will not save to disk.

  • sample (str, optional) – Sample name for spatial metadata. If None, inferred from filename.

  • labels_key (str, default "labels_joint") – Column name in bin h5ad .obs containing cell assignment labels

  • bin_size_um (float, default 2.0) – Size of each bin in micrometers

  • buffer_polygons (bool, default True) – Whether to buffer polygons slightly to account for bin size

  • n_jobs (int, default -1) – Number of parallel workers for polygon creation. -1 uses all available CPU cores, 1 disables parallelization.

Returns:

Cell-level AnnData object (copy of input cell h5ad) with added: - .obs[“geometry”]: WKT strings representing cell boundaries - .uns[“spatial”][sample][“geometries”]: GeoDataFrame with cell polygons

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> adata = tcio.add_geometries_to_annohdcell_output(
...     bin_h5ad_path="b2c_2um.h5ad",
...     cell_h5ad_path="b2c_cell.h5ad",
...     output_h5ad_path="b2c_cell_with_geom.h5ad",
...     sample="sample1"
... )
>>> # Now can use trackcell visualization
>>> import trackcell.pl as tcpl
>>> tcpl.spatial_cell(adata, library_id="sample1")

Notes

  • The cell h5ad must have .obs[“object_id”] matching labels in bin h5ad

  • Bin h5ad must have .obs[labels_key] with integer cell labels

  • Bin h5ad must have .obsm[“spatial”] with bin coordinates

  • The function preserves all data from the input cell h5ad

  • Only adds geometry information, does not modify counts or other data

trackcell.io.restore_geometries(adata: AnnData, sample: str | None = None) → AnnData[source]#

Restore GeoDataFrames from the WKT tables written by save_h5ad().

Inverse of flatten_geometries(): parses geometry back into shapely objects, keeps every attribute column, and re-attaches the CRS recorded in the <key>__crs sidecar.

Parameters:
  • adata – AnnData read back from an h5ad written with save_h5ad().

  • sample – Restrict to one library id. By default all samples are processed.

Returns:

The same object, mutated in place, with GeoDataFrames restored.

Return type:

AnnData

Examples

>>> import anndata as ad
>>> import trackcell as tcl
>>> tcl.io.save_h5ad(adata, "xenium.h5ad")
>>> adata = tcl.io.restore_geometries(ad.read_h5ad("xenium.h5ad"))
trackcell.io.flatten_geometries(adata: AnnData, sample: str | None = None, *, inplace: bool = False) → AnnData[source]#

Convert polygon GeoDataFrames to WKT-string DataFrames for h5ad output.

Parameters:
  • adata – AnnData whose uns['spatial'][sample] may contain geometries / nucleus_geometries GeoDataFrames.

  • sample – Restrict to one library id. By default all samples are processed.

  • inplace – If True, modify adata and return it; otherwise return a copy.

Returns:

Object with WKT-backed geometry tables (safe for write_h5ad).

Return type:

AnnData

trackcell.io.save_h5ad(adata: AnnData, filename: str | Path, *, compression: str | None = None, **kwargs: Any) → Path[source]#

Write an AnnData to h5ad while handling GeoDataFrame geometries.

This is a drop-in replacement for adata.write_h5ad() for objects produced by TrackCell’s spatial readers. Polygon tables are converted to WKT strings for the duration of the write and restored in memory afterwards, so the caller’s adata is left unchanged.

Parameters:
Returns:

The written path.

Return type:

pathlib.Path

Examples

>>> import trackcell as tcl
>>> adata = tcl.io.read_xenium_cellseg("/path/to/xenium")
>>> tcl.io.save_h5ad(adata, "xenium.h5ad")
>>> # adata still holds GeoDataFrames in memory
>>> adata = tcl.io.restore_geometries(__import__("anndata").read_h5ad("xenium.h5ad"))
trackcell.io.read_sto_cellbin(gef_path: str | Path, sample: str | None = None, gene_name_index: bool = True, image_path: str | Path | None = None) → AnnData[source]#

Read STOmics cellbin GEF data and create an AnnData with cell polygons.

Reads a STOmics cellbin GEF (HDF5) file containing cell segmentation boundaries, expression counts, and metadata. Produces a trackcell-compatible AnnData with polygon geometries for each cell.

Parameters:
  • gef_path (str or Path) – Path to the .cellbin.gef file, or to the directory containing it (e.g. .../041.cellcut/). When a directory is given the function auto-discovers the *cellbin*.gef file inside.

  • sample (str, optional) – Sample name. If None, inferred from the GEF filename (chip name).

  • gene_name_index (bool, default True) – If True, use gene names (symbols) as .var index.

  • image_path (str or Path, optional) – Path to the tissue image file (.tif), the register directory (e.g. .../03.register/), or None to auto-discover. When None, the function looks for 03.register/ as a sibling or parent of the GEF directory. The image is stored in .uns['spatial'][sample]['images'].

Returns:

AnnData object with: - .X: CSR expression matrix (cells × genes) - .obs: cell_id, area, dnb_count, gene_count, exp_count, geometry,

geometry_is_fallback

  • .obsm['spatial']: cell centroid coordinates

  • .obs['geometry']: WKT strings of cell polygons

  • .obs['geometry_is_fallback']: True where the polygon is fabricated rather than read from the border (see Notes)

  • .uns['spatial'][sample]['geometries']: GeoDataFrame with cell polygons

  • .uns['spatial'][sample]['images']: tissue image (if found)

  • .uns['spatial'][sample]['scalefactors'] / metadata (metadata['n_fallback_polygons'] counts fabricated boxes)

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> # Pass the file directly:
>>> adata = tcio.read_sto_cellbin(
...     "/path/to/C57_7/041.cellcut/B02825B2.cellbin.gef",
...     sample="C57_7"
... )
>>> # Or pass the directory — the function finds the right file:
>>> adata = tcio.read_sto_cellbin(
...     "/path/to/C57_7/041.cellcut/",
...     sample="C57_7"
... )
>>> # Auto-discover tissue image from register directory:
>>> adata = tcio.read_sto_cellbin(
...     "/path/to/C57_7/041.cellcut/",
...     sample="C57_7",
...     image_path="/path/to/C57_7/03.register/"
... )

Notes

  • The GEF file itself does not contain the ssDNA tissue image. The image is stored separately in the 03.register/ directory.

  • The cellBorder dataset stores up to 32 (dx, dy) offset pairs relative to the cell centroid. Trailing slots (sentinel value 32767) are stripped during geometry construction.

  • Cells whose border cannot form a polygon still receive a fabricated geometry, because a None would push a null check into every downstream area/intersect/ROI path. Which fabrication depends on the input: a 10x10 box when fewer than three vertices survive sentinel stripping, a buffered convex hull when the border self-intersects, a small disc when every vertex coincides. All of them are real to code that consumes them, so they are disclosed in .obs['geometry_is_fallback'] and counted in metadata['n_fallback_polygons'], and a RuntimeWarning names the affected count. Filter on the flag when polygon area matters.

  • Expression matrix is built directly from the cell offset table for efficient CSR construction (no intermediate dense matrix).

trackcell.io.read_sto_bin(gef_path: str | Path, bin_size: int = 100, sample: str | None = None, gene_name_index: bool = True, image_path: str | Path | None = None) → AnnData[source]#

Read STOmics squarebin GEF data and create an AnnData object.

Reads a STOmics tissue/squarebin GEF (HDF5) file and produces a bin-level AnnData with spatial coordinates.

Parameters:
  • gef_path (str or Path) – Path to the .tissue.gef file, or to the directory containing it (e.g. .../04.tissuecut/). When a directory is given the function auto-discovers the *tissue*.gef file inside.

  • bin_size (int, default 100) – Bin size in STOmics coordinate units (~500nm per unit). Merges raw 1-unit bins into larger bins.

  • sample (str, optional) – Sample name. If None, inferred from the filename.

  • gene_name_index (bool, default True) – If True, use gene names as .var index.

  • image_path (str or Path, optional) – Path to the tissue image file (.tif), the register directory (e.g. .../03.register/), or None to auto-discover.

Returns:

AnnData object with bin-level spatial data.

Return type:

sc.AnnData

Examples

>>> import trackcell.io as tcio
>>> # Pass the file directly:
>>> adata = tcio.read_sto_bin(
...     "/path/to/C57_7/04.tissuecut/B02825B2.tissue.gef",
...     bin_size=50, sample="C57_7"
... )
>>> # Or pass the directory:
>>> adata = tcio.read_sto_bin(
...     "/path/to/C57_7/04.tissuecut/",
...     bin_size=50, sample="C57_7"
... )
>>> # With tissue image auto-discovery:
>>> adata = tcio.read_sto_bin(
...     "/path/to/C57_7/04.tissuecut/",
...     bin_size=50,
...     image_path="/path/to/C57_7/03.register/"
... )

Notes

  • GEF is the preferred format (binary HDF5, fast ~15s for 95M entries).

  • GEM text (.gem / .gem.gz) files are also accepted; for large datasets the function will try to auto-redirect to the matching .gef file.

  • The GEF file does not contain the ssDNA tissue image. Images are in 03.register/ and can be loaded via image_path.

trackcell.io.atera_info(path: str | Path, verbose: bool = True) → dict[source]#

Return bundle metadata without loading the expression matrix.

This is the recommended first call on an unfamiliar 10–500 GB Atera bundle: it reports cells, genes, polygon coverage, transcript count and software version in a couple of seconds.

Examples

>>> tcl.io.atera_info("/path/to/ROI_bundle")
trackcell.io.read_atera(path: str | Path, sample: str | None = None, *, format: str = 'auto', gene_name_index: bool = True, build_polygons: bool = True, include_nucleus: bool | None = None, store_wkt: bool = False, keep_de: bool = False, load_panel: bool = False, load_groups: bool = True, region=None, n_cells: int | None = None, random_state: int = 0, verbose: bool = True) → AnnData[source]#

Read an Atera output bundle (auto-detecting preview vs official).

Parameters:
  • path – Atera output directory. This is usually one ROI bundle, not the run directory (use list_atera_rois() / iter_atera_rois() for a run).

  • sample – Key used for uns['spatial'][sample]. If None, uses experiment.spatial['region_name'] (official) or experiment.xenium['region_name'] (preview), falling back to the directory name.

  • format – 'auto' (default), 'cellseg' (official Zarr) or 'preview'.

  • gene_name_index – If True, use gene symbols as var_names and store Ensembl IDs in var['gene_ids']. If False, keep the Ensembl IDs as var_names.

  • build_polygons – Build cell polygons from cells.zarr / cell_boundaries.parquet. Has a real cost at ~400k cells (about one minute for official data).

  • include_nucleus – Also build nucleus polygons. None (default) follows build_polygons: nucleus polygons are built when cell polygons are built. Explicitly passing True with build_polygons=False raises an error.

  • store_wkt – Store WKT strings in obs['geometry']. Off by default: it costs memory and is only needed for serialization. Use add_wkt_geometry() to add it later.

  • keep_de – Keep the official per-cluster var['de_*'] columns (official data has hundreds of them and they are rarely needed at read time).

  • load_panel – Parse panel_config.json (official, ~11 MB and may contain customer information) into uns['gene_panel']. Off by default; only the path is recorded.

  • load_groups – Attach Atera’s own per-cell clustering from cell_groups.csv into obs['cell_group'] (Categorical), with the vendor palette written in the scanpy/squidpy convention: uns['cell_group_colors'] as a list aligned with obs['cell_group'].cat.categories (so sq.pl and tcl.pl both pick it up unprompted) plus the raw {group: hex} map under uns['atera_cell_group_palette']. On by default and skipped silently when the bundle has no such file, so preview and official reads stay interchangeable.

  • region – (xmin, ymin, xmax, ymax) in µm, a shapely geometry, or a mapping with xmin/ymin/xmax/ymax. Cells are subset by centroid.

  • n_cells – Randomly subset to at most this many cells (random_state).

  • random_state – Seed for n_cells.

  • verbose – Print progress information.

Returns:

With obsm['spatial'] (µm), obs['barcode'], polygons in uns['spatial'][sample]['geometries'] and normalised var columns. Official data additionally has obs['cell_id'] (uint32), obs['cell_prefix'] and obs['dataset_suffix'].

Return type:

AnnData

Examples

>>> adata = tcl.io.read_atera("/path/to/ROI_bundle")
>>> adata = tcl.io.read_atera("/path/to/preview", format="preview")
trackcell.io.read_atera_cellseg(path: str | Path, sample: str | None = None, *, gene_name_index: bool = True, build_polygons: bool = True, include_nucleus: bool | None = None, store_wkt: bool = False, keep_de: bool = False, load_panel: bool = False, load_groups: bool = True, region=None, n_cells: int | None = None, random_state: int = 0, verbose: bool = True) → AnnData[source]#

Read an official Atera 1.x bundle (AnnData Zarr + cells Zarr).

See read_atera() for the parameter documentation.

trackcell.io.read_atera_preview(path: str | Path, sample: str | None = None, *, gene_name_index: bool = True, build_polygons: bool = True, include_nucleus: bool | None = None, store_wkt: bool = False, keep_de: bool = False, load_panel: bool = False, load_groups: bool = True, region=None, n_cells: int | None = None, random_state: int = 0, verbose: bool = True) → AnnData[source]#

Read an Atera preview bundle (Xenium-v4 compatible formats).

See read_atera() for the parameter documentation. The preview bundle uses cell_feature_matrix.h5 + cells.parquet + cell_boundaries.parquet.

trackcell.io.read_atera_panel(path: str | Path) → dict[source]#

Read panel_config.json from an Atera bundle.

The file is ~11 MB and may contain customer / designer information, so read_atera() does not load it by default.

trackcell.io.list_atera_rois(run_dir: str | Path) → DataFrame[source]#

List the ROI bundles contained in an Atera run directory.

Returns a DataFrame with one row per ROI (roi, path, format, n_cells, n_features, n_gene_expression, has_transcripts).

trackcell.io.iter_atera_rois(run_dir: str | Path, rois: Sequence[str] | None = None, **read_kwargs) → Iterator[Tuple[str, AnnData]][source]#

Yield (roi_name, adata) one ROI at a time.

Unlike a dict-returning helper, this keeps peak memory at one ROI. Pass extra keyword arguments through to read_atera().

trackcell.io.concat_atera_rois(adatas: Sequence[AnnData] | Mapping[str, AnnData], offsets=None, *, names: Sequence[str] | None = None, join: str = 'inner', label: str = 'roi', assume_aligned: bool = False, index_unique: str | None = None, **concat_kwargs) → AnnData[source]#

Concatenate ROIs from the same customer.

Parameters:
  • adatas – List of AnnData objects, or a mapping {roi_name: adata}.

  • offsets – {roi_name: (dx, dy)} in µm, or a sequence matching adatas. Required unless assume_aligned=True (ROIs already share a coordinate system).

  • names – ROI names used for obs[label]. Defaults to the mapping keys or roi_0, roi_1, …

  • join – 'inner' (default) or 'outer' for variable alignment.

  • label – obs column that records the ROI name.

  • assume_aligned – Set to True only when the ROIs come from the same slide and already share coordinates. There is no reliable way to derive offsets from overview_scan_fov_locations.json (5–10 µm error), so the default is to require explicit offsets.

  • index_unique – If given (e.g. "-"), append f"{index_unique}{roi_name}" to obs_names and geometry indices so that ROIs with identical barcodes stay distinguishable. Atera barcodes can repeat across ROIs; pass this when concatenating them.

Notes

The input objects are translated in place (copying multi-GB AnnData objects is usually worse).

trackcell.io.iter_atera_transcripts(path: str | Path, *, genes: Sequence[str] | None = None, region=None, min_qv: float = 20.0, include_unassigned: bool = False, adata: AnnData | None = None, chunksize: int | None = None, verbose: bool = False) → Iterator[DataFrame][source]#

Stream Atera transcripts as DataFrames.

Parameters:
  • path – ROI bundle directory (or the transcripts.zarr.zip file itself).

  • genes – Gene symbols to keep. Uses the per-tile gene_offset index so only the requested gene ranges are read.

  • region – (xmin, ymin, xmax, ymax) in µm, a shapely geometry, or a mapping.

  • min_qv – Minimum Q-score. Use None to keep all molecules. The official cell matrix uses Q ≥ 20.

  • include_unassigned – Keep molecules with no cell assignment (cell_index = -1).

  • adata – Optional AnnData whose obs row order defines cell_index. Pass this after subsetting cells, otherwise cell_index refers to the full bundle (cells.zarr) order.

  • chunksize – Molecules per read. None picks the zarr chunk size (≥1M).

  • verbose – Print tile progress.

Yields:

DataFrame – Columns: x, y, z (µm), qv, cell_index (row in adata.obs, -1 = unassigned), cell_prefix, gene_index, gene (categorical), codeword, overlaps_nucleus. overlaps_nucleus is a nuclear-localisation flag, not an unspliced count.

Examples

>>> for chunk in tcl.io.iter_atera_transcripts(
...         roi, genes=["NPHS1", "UMOD"], min_qv=20):
...     print(chunk.head())

Notes

The returned gene column is a pandas.Categorical to keep memory low on billion-row scans.

Background grid tiles (negative keys such as "-1,0") are skipped: they only contain placeholder rows outside the ROI.

trackcell.io.read_atera_transcripts(path: str | Path, *, genes: Sequence[str] | None = None, region=None, min_qv: float = 20.0, include_unassigned: bool = False, adata: AnnData | None = None, max_rows: int | None = None, force: bool = False, verbose: bool = True) → DataFrame[source]#

Read Atera transcripts into a single DataFrame.

This is only safe for small queries. A full kidney ROI has ~1.19 billion molecules, so a query without genes or region is rejected unless max_rows or force=True is provided.

Use iter_atera_transcripts() for large scans.

trackcell.io.atera_cell_qc(adata: AnnData, compute_expression_genes: bool = True) → DataFrame[source]#

Compute cell-level QC for an Atera AnnData object.

Atera’s obs['total_counts'] includes control probes/codewords; use obs['transcript_counts'] for gene-only counts.

Returns:

Indexed by adata.obs_names with total_counts, transcript_counts, n_genes (matrix nnz per cell, includes control features), n_genes_expression (Gene Expression features only, when compute_expression_genes=True), cell_area, nucleus_area, nuclear_area_ratio and control fractions.

Return type:

DataFrame

trackcell.io.atera_transcript_qc(path: str | Path, adata: AnnData | None = None, *, min_qv: float = 20.0, bins: int = 100, region=None, verbose: bool = True) → dict[source]#

Stream the Atera point cloud and compute Q-score / nuclear / density QC.

Results are written back to adata when provided:

  • obs['tx_q20_counts'], obs['tx_nuclear_counts'], obs['nuclear_fraction']

  • uns['atera']['transcript_qc'] (summary dict)

  • uns['atera']['qscore'] (histogram)

  • uns['atera']['density'] (H, xedges, yedges)

  • uns['atera']['gene_qc'] (per-gene totals and nuclear fractions)

This makes trackcell.pl.atera_nuclear_fraction() and trackcell.pl.atera_transcript_density() re-callable, since they only read adata.

Returns:

Summary with transcript counts, Q≥min_qv fractions, assignment rate, nuclear fraction and runtime.

Return type:

dict

trackcell.io.add_wkt_geometry(adata: AnnData, sample: str | None = None, key: str = 'geometry', nucleus: bool = False) → AnnData[source]#

Add WKT polygon strings to obs[key].

This is the opt-in replacement for store_wkt=True.

trackcell.io.filter_atera_genes(adata: AnnData, inplace: bool = False) → AnnData[source]#

Keep only feature_type == 'Gene Expression' features.

Atera panels include thousands of negative-control codewords. They must be removed before HVG selection / PCA / clustering.

Examples

>>> adata = tcl.io.filter_atera_genes(adata)

Plotting Functions#

PL (Plotting) module for TrackCell package.

This module provides functions for plotting and visualizing single-cell and spatial transcriptomics data.

trackcell.pl.spatial_cell(adata, color: str | List[str] | None = None, groups: List[str] | None = None, groupby: str | None = None, library_id: str | None = None, size: float = 1.0, figsize: tuple | None = None, cmap: str = 'viridis', palette: dict | list | ndarray | None = None, vmin: float | None = None, vmax: float | None = None, img_key: str | None = None, basis: str = 'spatial', edges_width: float = 0.5, edges_color: str = 'black', edge_color: str | None = None, edge_palette: dict | list | ndarray | None = None, alpha: float = 0.8, alpha_img: float = 0.5, show: bool = True, ax: matplotlib.pyplot.Axes | None = None, legend: bool = True, xlabel: str | None = 'spatial 1', ylabel: str | None = 'spatial 2', frameon: bool | None = None, show_ticks: bool = False, invert_y: bool = True, categorical: bool | None = None, scalebar: bool | float | str | dict | None = None, **kwargs)[source]#

Plot spatial transcriptomics data with cell polygons instead of points.

This function visualizes cells as polygons (from cell segmentation) rather than simple points, providing a more accurate representation of cell boundaries. Uses GeoDataFrame.plot() for efficient rendering and automatic legend generation.

Parameters:
  • adata (AnnData) – Annotated data object with spatial information and cell geometries.

  • color (str or list of str, optional) –

    Keys for observation/categorical or continuous variables to color cells. Can be a single key or a list of keys for multiple plots. Can be: - A column name in adata.obs (metadata) - A gene name in adata.var_names (gene expression) - None: Only display the H&E background image without cell polygons.

    When None, axis ticks and labels are automatically shown.

  • groups (list of str, optional) – Subset of groups to plot. If None, plots all groups. Requires either color to be a categorical column in adata.obs or groupby to be specified.

  • groupby (str, optional) – Column name in adata.obs to use for filtering with groups parameter. If None and groups is specified, will use color if it’s a categorical column in adata.obs. This is useful when color is a continuous variable (e.g., gene expression) but you want to filter by a categorical column (e.g., ‘classification’).

  • library_id (str, optional) – Key in adata.uns[“spatial”] containing spatial information. If None, uses the first available library_id (similar to sc.pl.spatial). Default is None, which will auto-select the first library_id.

  • size (float, default 1.0) – Size scaling factor for cells (not used for polygons, kept for API compatibility). This parameter is currently not implemented for polygon-based visualization.

  • figsize (tuple, optional) – Figure size (width, height) in inches.

  • cmap (str, default "viridis") – Colormap for continuous values.

  • vmin (float, optional) – Minimum value for colormap normalization. If None, uses the minimum value in the data.

  • vmax (float, optional) – Maximum value for colormap normalization. If None, uses the maximum value in the data.

  • palette (dict, list, or array, optional) –

    Color palette for categorical variables. Can be: - A dictionary mapping category names to colors (e.g., {‘A’: ‘red’, ‘B’: ‘blue’}) - A list/array of colors that will be assigned to categories in sorted order

    (e.g., [‘red’, ‘blue’, ‘green’] will assign colors to categories alphabetically)

    • None (default): adata.uns['<color>_colors'] is used when present (scanpy convention, aligned via adata.uns['<color>_categories']), otherwise a built-in discrete palette. The same colors are used for the polygons and for the legend swatches.

  • img_key (str, optional) – Key in adata.uns[“spatial”][library_id][“images”] for background image. If None, uses “hires” if available.

  • basis (str, default "spatial") – Key in adata.obsm containing spatial coordinates (for fallback).

  • edges_width (float, default 0.5) – Width of cell polygon edges.

  • edges_color (str, default "black") – Color of cell polygon edges (when edge_color is not specified).

  • edge_color (str, optional) – Column name in adata.obs for categorical coloring of cell edges. When specified, cell edges are colored by category (e.g., cell type), while color controls the fill (typically gene expression). Overrides edges_color when set.

  • edge_palette (dict, list, or array, optional) – Color palette for edge_color categories. Same format as palette.

  • alpha (float, default 0.8) – Transparency of cell polygons.

  • alpha_img (float, default 0.5) – Transparency of background image.

  • show (bool, default True) – Whether to display the plot.

  • ax (matplotlib.Axes, optional) – Axes object to plot on. If None, creates a new figure.

  • legend (bool, default True) – Whether to show legend for categorical values or colorbar for continuous values.

  • xlabel (str, optional, default "spatial 1") – Label for the x-axis. Set to None to hide the label.

  • ylabel (str, optional, default "spatial 2") – Label for the y-axis. Set to None to hide the label.

  • frameon (bool, optional) – Whether to draw the axes frame. None (default) leaves the axes as-is, so a user-supplied ax keeps its own styling. False calls ax.axis("off") — no frame, no ticks, no axis labels — matching squidpy.pl.spatial_scatter(frameon=False). True forces the frame on.

  • show_ticks (bool, default False) – Whether to show axis ticks and tick labels. If False, ticks are hidden. Note: When color=None, ticks are automatically shown regardless of this setting.

  • invert_y (bool, default True) – Whether to invert the y-axis so spatial coordinates increase from top to bottom (image convention, matching the H&E background). Set to False to use Cartesian convention (y increases from bottom to top).

  • categorical (bool, optional) – Force categorical (legend) or continuous (colorbar) rendering of color. By default the choice is inferred once per key, from the full object, so every panel of a multi-panel figure renders the same way: Categorical/object/bool obs columns are categorical, integer obs columns are categorical when they have at most 30 distinct values (what integer-coded cluster labels look like), and gene expression is always continuous — a gene is never a label, however few integer levels a small ROI happens to contain. Pass categorical=True to colour a gene categorically, or categorical=False to force an integer obs column onto a continuous ramp.

  • scalebar (bool, float, str, or dict, optional) –

    Draw a physical scale bar (e.g. 50 µm) on the plot. Options:

    • None/False (default): no scale bar;

    • True: automatic length, ~18% of the visible width, rounded to a “nice” value (1/2/5 × 10ⁿ µm). Because it follows the visible extent, the same tissue gets 500 µm when shown whole and 10 µm when zoomed in;

    • a number: fixed length in µm;

    • a string such as "50um", "100 µm" or "20px": fixed length;

    • a dict of keyword arguments forwarded to trackcell.pl.add_scale_bar(), e.g. dict(length="auto", loc="lower left", color="white", frame=True, fontsize=12, offset=(8, 8)). Useful keys: loc (e.g. "lower right", "upper left", "center right"), pad/offset, frac, color, linewidth, fontsize, caps, label, label_position, frame/frame_color, and microns_per_unit to override unit inference.

    The µm-per-data-unit factor is inferred from the object: coord_unit metadata (Atera / trackcell readers, already µm) or scalefactors['microns_per_pixel'] (Visium / Visium HD pixels).

  • **kwargs – Additional arguments passed to GeoDataFrame.plot().

Returns:

Axes object(s) containing the plot.

Return type:

matplotlib.Axes or list of matplotlib.Axes

Examples

>>> import trackcell as tcl
>>> adata = tcl.io.read_hd_cellseg("path/to/data", sample="sample1")
>>> # Plot by metadata (categorical)
>>> tcl.pl.spatial_cell(adata, color="classification")
>>> # Plot by metadata (continuous)
>>> tcl.pl.spatial_cell(adata, color="Cluster-2_dist", cmap="Reds")
>>> # Plot by gene expression
>>> tcl.pl.spatial_cell(adata, color="PDPN", cmap="viridis")
>>> # Plot with groups filter
>>> tcl.pl.spatial_cell(adata, color="classification", groups=["Cluster-1", "Cluster-2"])
>>> # Plot only H&E image (no cell polygons)
>>> tcl.pl.spatial_cell(adata, color=None)
>>> # Add a physical scale bar (auto length follows the visible extent)
>>> tcl.pl.spatial_cell(adata, color="classification", scalebar=True)
>>> # Fixed 50 µm bar in the lower left, white with a backing box
>>> tcl.pl.spatial_cell(
...     adata,
...     color="classification",
...     scalebar=dict(length="50um", loc="lower left", color="white", frame=True),
... )
>>> # Drop the axes frame (no spines, ticks or axis labels)
>>> tcl.pl.spatial_cell(adata, color="classification", frameon=False)
trackcell.pl.spatial_squarebin(adata, color: str | List[str] | None = None, groups: List[str] | None = None, groupby: str | None = None, library_id: str | None = None, binsize: float | None = None, figsize: tuple | None = None, cmap: str = 'viridis', palette: dict | list | ndarray | None = None, vmin: float | None = None, vmax: float | None = None, img_key: str | None = None, basis: str = 'spatial', edges_width: float = 0.0, edges_color: str = 'none', alpha: float = 0.8, alpha_img: float = 0.5, show: bool = True, ax: matplotlib.pyplot.Axes | None = None, legend: bool = True, xlabel: str | None = 'spatial 1', ylabel: str | None = 'spatial 2', show_ticks: bool = False, frameon: bool | None = None, crop_coord: tuple | None = None, na_color: str = '#d3d3d3', rasterized: bool = False, invert_y: bool = True, shape: str = 'circle', scalebar: bool | float | str | dict | None = None, **kwargs)[source]#

Plot Visium HD square-bin data as circles (default) or squares over an optional H&E image.

This function is designed for outputs loaded by trackcell.io.read_hd_bin(). It mirrors the user-facing behavior of spatial_cell() where possible, but renders regular square bins instead of cell polygons.

Parameters:
  • adata – AnnData object with bin-level spatial coordinates in adata.obsm[basis] and image metadata in adata.uns['spatial'][library_id].

  • color – Observation column, gene name, or list of either. If None, only the H&E image and coordinate range are displayed.

  • groups – Optional filtering of bins, following the same semantics as spatial_cell.

  • groupby – Optional filtering of bins, following the same semantics as spatial_cell.

  • library_id – Spatial library identifier. If None, the first entry in adata.uns['spatial'] is used.

  • binsize – Bin size in micrometers. If None, uses adata.uns['spatial'][library_id]['binsize'] when available.

  • figsize

  • cmap

  • palette

  • vmin

  • vmax

  • img_key

  • basis

  • alpha

  • alpha_img

  • show

  • ax

  • legend

:param : :param xlabel: Behave similarly to spatial_cell. palette=None falls back to

adata.uns['<color>_colors'] when present.

Parameters:
  • ylabel – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • show_ticks – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • frameon – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • edges_width – Styling for square boundaries. Defaults favor performance by disabling edges.

  • edges_color – Styling for square boundaries. Defaults favor performance by disabling edges.

  • crop_coord – Optional (x_min, x_max, y_min, y_max) crop in spatial coordinates.

  • na_color – Color used for missing values.

  • rasterized – Whether to rasterize square patches for smaller vector outputs on large datasets.

  • invert_y – Whether to invert the y-axis so spatial coordinates increase from top to bottom (image convention, matching the H&E background). Default True. Set to False to use Cartesian convention (y increases from bottom to top).

  • shape – Shape of each bin marker. 'circle' (default) or 'square'.

  • scalebar – Draw a physical scale bar; see spatial_cell() and trackcell.pl.add_scale_bar(). True picks an automatic length from the cropped visible extent, so crop_coord zoom-ins get shorter bars.

  • **kwargs – Reserved for future extensions. Currently unused.

trackcell.pl.spatial_bin(adata, color: str | List[str] | None = None, groups: List[str] | None = None, groupby: str | None = None, library_id: str | None = None, binsize: float | None = None, figsize: tuple | None = None, cmap: str = 'viridis', palette: dict | list | ndarray | None = None, vmin: float | None = None, vmax: float | None = None, img_key: str | None = None, basis: str = 'spatial', edges_width: float = 0.0, edges_color: str = 'none', alpha: float = 0.8, alpha_img: float = 0.5, show: bool = True, ax: matplotlib.pyplot.Axes | None = None, legend: bool = True, xlabel: str | None = 'spatial 1', ylabel: str | None = 'spatial 2', show_ticks: bool = False, frameon: bool | None = None, crop_coord: tuple | None = None, na_color: str = '#d3d3d3', rasterized: bool = False, invert_y: bool = True, shape: str = 'circle', scalebar: bool | float | str | dict | None = None, **kwargs)#

Plot Visium HD square-bin data as circles (default) or squares over an optional H&E image.

This function is designed for outputs loaded by trackcell.io.read_hd_bin(). It mirrors the user-facing behavior of spatial_cell() where possible, but renders regular square bins instead of cell polygons.

Parameters:
  • adata – AnnData object with bin-level spatial coordinates in adata.obsm[basis] and image metadata in adata.uns['spatial'][library_id].

  • color – Observation column, gene name, or list of either. If None, only the H&E image and coordinate range are displayed.

  • groups – Optional filtering of bins, following the same semantics as spatial_cell.

  • groupby – Optional filtering of bins, following the same semantics as spatial_cell.

  • library_id – Spatial library identifier. If None, the first entry in adata.uns['spatial'] is used.

  • binsize – Bin size in micrometers. If None, uses adata.uns['spatial'][library_id]['binsize'] when available.

  • figsize

  • cmap

  • palette

  • vmin

  • vmax

  • img_key

  • basis

  • alpha

  • alpha_img

  • show

  • ax

  • legend

:param : :param xlabel: Behave similarly to spatial_cell. palette=None falls back to

adata.uns['<color>_colors'] when present.

Parameters:
  • ylabel – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • show_ticks – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • frameon – Behave similarly to spatial_cell. palette=None falls back to adata.uns['<color>_colors'] when present.

  • edges_width – Styling for square boundaries. Defaults favor performance by disabling edges.

  • edges_color – Styling for square boundaries. Defaults favor performance by disabling edges.

  • crop_coord – Optional (x_min, x_max, y_min, y_max) crop in spatial coordinates.

  • na_color – Color used for missing values.

  • rasterized – Whether to rasterize square patches for smaller vector outputs on large datasets.

  • invert_y – Whether to invert the y-axis so spatial coordinates increase from top to bottom (image convention, matching the H&E background). Default True. Set to False to use Cartesian convention (y increases from bottom to top).

  • shape – Shape of each bin marker. 'circle' (default) or 'square'.

  • scalebar – Draw a physical scale bar; see spatial_cell() and trackcell.pl.add_scale_bar(). True picks an automatic length from the cropped visible extent, so crop_coord zoom-ins get shorter bars.

  • **kwargs – Reserved for future extensions. Currently unused.

trackcell.pl.multigene_blend(adata, key: str = 'multigene_blend', *, library_id: str | None = None, figsize: tuple | None = None, show: bool = True, ax: matplotlib.pyplot.Axes | None = None, legend: bool = True, legend_title: str | None = 'genes', **kwargs) → matplotlib.pyplot.Axes[source]#

Render a blend computed by trackcell.tl.multigene_blend().

tl.multigene_blend(mode='blend') writes one hex colour per cell into adata.obs[key] plus the gene-to-colour mapping into adata.uns['{key}_params']. spatial_cell draws such a column correctly — it detects the raw-hex case and skips palette construction — but it cannot build a legend, because a column holding thousands of distinct hex strings carries no category names. The composite therefore came out with no indication of which colour meant which gene.

This function supplies that legend. It recomputes nothing: it reads adata.obs[key] and adata.uns['{key}_params'] only. Call trackcell.tl.multigene_blend() first.

Parameters:
  • adata – Annotated data object.

  • key – obs column written by trackcell.tl.multigene_blend().

  • library_id – Spatial library id, forwarded to spatial_cell().

  • figsize – Figure size, forwarded to spatial_cell().

  • show – Whether to call plt.show().

  • ax – Existing axes to draw on.

  • legend – Whether to draw the gene-to-colour legend. Only possible when the uns parameters are present; blending without inplace=True leaves nothing to read.

  • legend_title – Legend title. Pass None to omit it.

  • **kwargs – Forwarded to spatial_cell() (edges_width, alpha, scalebar, basis, …).

Return type:

The matplotlib.axes.Axes with the composite drawn on it.

Raises:
  • KeyError – If adata.obs[key] is absent, i.e. blending has not been run.

  • ValueError – If adata.obs[key] is not a column of hex colour strings.

Examples

>>> import trackcell as tcl
>>> tcl.tl.multigene_blend(adata, genes=["EPCAM", "COL1A1", "PTPRC"])
>>> tcl.pl.multigene_blend(adata)  # composite + gene/colour legend

See also

trackcell.tl.multigene_blend

computes the blended colours.

spatial_cell

draws any polygon column, including raw hex.

trackcell.pl.mark_region(ax: matplotlib.pyplot.Axes, xlim: tuple | None = None, ylim: tuple | None = None, edges_color: str = 'red', edges_width: float = 2.0, fill_color: str | None = None, fill_alpha: float = 0.15, zorder: int = 100, refresh: bool = True, show: bool = True)[source]#

Mark a rectangular region on a spatial plot by drawing a rectangle.

This function draws a rectangle on the given axes to highlight a specific spatial region. It works with any spatial plot (spatial_cell, spatial_squarebin, sc.pl.spatial) regardless of the invert_y setting.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes object to draw the rectangle on.

  • xlim (tuple, optional) – Tuple of (x_min, x_max) to define the x-range of the region. If None, uses the current x-axis limits.

  • ylim (tuple, optional) – Tuple of (y_min, y_max) to define the y-range of the region. If None, uses the current y-axis limits.

  • edges_color (str, default 'red') – Color of the rectangle edges.

  • edges_width (float, default 2.0) – Width of the rectangle edges.

  • fill_color (str, optional) – If provided, fills the rectangle with this color at fill_alpha opacity, making the region more visible against dense H&E backgrounds.

  • fill_alpha (float, default 0.15) – Opacity of the fill when fill_color is set.

  • zorder (int, default 100) – Z-order for rendering. High value ensures the rectangle is drawn on top of all other plot elements.

  • refresh (bool, default True) – If True, calls ax.figure.canvas.draw_idle() to update the display after adding the rectangle. Set to False when adding multiple regions before a single refresh.

  • show (bool, default True) – Whether to display the figure via plt.show(). Set to False when you want to defer display (e.g., when adding multiple regions or calling plt.show() manually).

Returns:

The rectangle patch object that was added to the axes.

Return type:

matplotlib.patches.Rectangle

Examples

>>> import trackcell as tcl
>>>
>>> # Simplest usage: mark_region auto-shows by default
>>> # (spatial_cell returns ax even when show=True)
>>> ax = tcl.pl.spatial_cell(adata, color="CellType")
>>> tcl.pl.mark_region(ax, xlim=(54500, 56000), ylim=(15000, 16000))
>>>
>>> # For full control, use show=False in both functions
>>> fig, ax = plt.subplots(figsize=(10, 10))
>>> tcl.pl.spatial_cell(adata, color="CellType", ax=ax, show=False)
>>> tcl.pl.mark_region(
...     ax, xlim=(54500, 56000), ylim=(15000, 16000),
...     fill_color='red',
...     edges_width=3.0
... )
>>> plt.show()
>>>
>>> # Mark multiple regions efficiently
>>> fig, ax = plt.subplots(figsize=(10, 10))
>>> tcl.pl.spatial_cell(adata, color="CellType", ax=ax, show=False)
>>> tcl.pl.mark_region(ax, xlim=(40000, 42000), ylim=(5000, 7000),
...                    edges_color='cyan', fill_color='cyan',
...                    refresh=False, show=False)
>>> tcl.pl.mark_region(ax, xlim=(55000, 57000), ylim=(15000, 17000),
...                    edges_color='yellow', fill_color='yellow',
...                    refresh=False, show=False)
>>> tcl.pl.mark_region(ax, xlim=(60000, 62000), ylim=(10000, 12000),
...                    edges_color='magenta', fill_color='magenta')
>>> # plt.show() is called by the last mark_region (show=True)
trackcell.pl.mark_circle(ax: matplotlib.pyplot.Axes, xy: tuple, radius: float, *, radius_unit: str = 'data', adata=None, library_id: str | None = None, microns_per_unit: float | None = None, edges_color: str = 'red', edges_width: float = 2.0, linestyle: str = '--', fill_color: str | None = None, fill_alpha: float = 0.15, label: str | None = None, zorder: int = 100, refresh: bool = True, show: bool = True)[source]#

Mark a circular region on a spatial plot by drawing a circle.

The circular counterpart of mark_region(), intended for annotating a radius-based selection (see trackcell.tl.cells_in_radius()) on an overview plot. It works with any spatial plot (spatial_cell, spatial_squarebin, sc.pl.spatial) regardless of invert_y.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to draw the circle on.

  • xy (tuple of float) – Circle center (x, y) in data coordinates — the same value passed as center to trackcell.tl.cells_in_radius().

  • radius (float) – Circle radius, in radius_unit.

  • radius_unit ({'data', 'um'}, default 'data') – 'data' draws a circle of radius data units (correct for Atera / Xenium, whose coordinates are µm). 'um' converts radius from micrometers using adata (or microns_per_unit), which is required when the coordinates are image pixels — Visium / Visium HD.

  • adata – AnnData used for the µm conversion when radius_unit='um'. Optional if microns_per_unit is given.

  • library_id (str, optional) – Spatial library id used for the µm conversion.

  • microns_per_unit (float, optional) – Explicit µm per data unit, overriding metadata inference.

  • edges_color (str, default 'red') – Color of the circle outline.

  • edges_width (float, default 2.0) – Outline width.

  • linestyle (str, default '--') – Outline style.

  • fill_color (str, optional) – Fill color. When None the circle is unfilled.

  • fill_alpha (float, default 0.15) – Opacity of the fill when fill_color is set.

  • label (str, optional) – Legend label for the circle (draw ax.legend() yourself).

  • zorder (int, default 100) – Z-order, high enough to sit above polygons and above the H&E image.

  • refresh (bool, default True) – Call ax.figure.canvas.draw_idle() after adding the patch.

  • show (bool, default True) – Call plt.show() after adding the patch. Set False when composing a multi-panel figure.

Returns:

The patch added to the axes.

Return type:

matplotlib.patches.Circle

Examples

>>> center, r = (4500.0, 2600.0), 150.0
>>> ax = tcl.pl.spatial_cell(adata, color="celltype", scalebar=True, show=False)
>>> tcl.pl.mark_circle(ax, center, r, radius_unit="um", adata=adata,
...                    label=f"r = {r:.0f} µm")
>>> roi = adata[tcl.tl.cells_in_radius(adata, center, r)].copy()
trackcell.pl.nhood_enrichment(adata, cluster_key: str, connectivity_key: str = 'spatial_connectivities', cmap: str = 'RdBu_r', figsize: tuple | None = None, show: bool = True, ax: matplotlib.pyplot.Axes | None = None) → matplotlib.pyplot.Axes[source]#

Plot the neighborhood-enrichment matrix from trackcell.tl.nhood_enrichment().

Reads adata.uns['{cluster_key}_nhood_enrichment'] (written by the tl function) and renders a diverging heatmap centered at zero.

Parameters:
  • adata – Annotated data object.

  • cluster_key – Cluster-label key used when calling tl.nhood_enrichment.

  • connectivity_key – Connectivity key used when computing enrichment (only used for title).

  • cmap – Colormap for the heatmap.

  • figsize – Figure size (width, height).

  • show – Whether to call plt.show().

  • ax – Existing axes to draw on.

Return type:

The matplotlib.axes.Axes with the heatmap.

trackcell.pl.diff_nhood_enrichment(adata, cluster_key: str, condition_key: str, condition_groups: tuple | None = None, cmap: str = 'RdBu_r', figsize: tuple | None = None, show: bool = True, ax: matplotlib.pyplot.Axes | None = None) → matplotlib.pyplot.Axes[source]#

Plot differential neighborhood enrichment from trackcell.tl.diff_nhood_enrichment().

Reads adata.uns['{cluster_key}_{condition_key}_diff_nhood_enrichment'] and renders the Case−Ctr enrichment difference as a diverging heatmap, annotating permutation p-values with stars when available.

Parameters:
  • adata – Annotated data object.

  • cluster_key – Cluster-label key used when calling tl.diff_nhood_enrichment.

  • condition_key – Condition key used when calling tl.diff_nhood_enrichment.

  • condition_groups – The two compared condition values, e.g. ("Case", "Ctr"). If None, the first pair found in the stored result is used.

  • cmap – See nhood_enrichment().

  • figsize – See nhood_enrichment().

  • show – See nhood_enrichment().

  • ax – See nhood_enrichment().

Return type:

The matplotlib.axes.Axes with the heatmap.

trackcell.pl.atera_qc_summary(adata, qc=None, figsize: tuple = (11, 8), cmap: str = 'viridis', show: bool = True, axes=None)[source]#

Plot a 2×2 cell-level QC panel for Atera data.

Panels: total counts, detected genes, counts-vs-genes, spatial counts. All panels read adata.obs / adata.obsm only, so this function can be re-called at any time.

Parameters:
  • adata (AnnData) – Object returned by trackcell.io.read_atera().

  • qc (DataFrame, optional) – Pre-computed trackcell.io.atera_cell_qc() result.

  • figsize (optional) – Plot appearance.

  • cmap (optional) – Plot appearance.

  • show (optional) – Plot appearance.

  • axes (array of Axes, optional) – Existing 2×2 axes.

Return type:

numpy.ndarray of matplotlib.axes.Axes

trackcell.pl.atera_transcript_density(adata, cmap: str = 'magma', min_molecules: int = 0, figsize: tuple = (7, 5), show: bool = True, ax=None)[source]#

Plot the transcript density map stored by atera_transcript_qc.

Requires adata.uns['atera']['density']; run tcl.io.atera_transcript_qc(path, adata=adata) first.

Return type:

matplotlib.axes.Axes

trackcell.pl.atera_nuclear_fraction(adata, genes: List[str] | None = None, bin_um: float = 50.0, cmap: str = 'coolwarm', figsize: tuple = (11, 4), show: bool = True, axes=None)[source]#

Plot per-cell and spatial nuclear transcript fractions.

Requires adata.obs['nuclear_fraction'] from tcl.io.atera_transcript_qc(path, adata=adata).

Parameters:
  • adata (AnnData)

  • genes (list of str, optional) – If given, add a third panel with the per-gene nuclear fraction (uns['atera']['gene_qc']).

  • bin_um (float) – Spatial bin size in µm for the right panel.

  • cmap (optional) – Plot appearance.

  • figsize (optional) – Plot appearance.

  • show (optional) – Plot appearance.

  • axes (optional) – Plot appearance.

Return type:

numpy.ndarray of matplotlib.axes.Axes

trackcell.pl.add_scale_bar(ax: matplotlib.axes.Axes, adata: object | None = None, *, length: float | str | None = 'auto', unit: str | None = None, microns_per_unit: float | None = None, library_id: str | None = None, basis: str = 'spatial', loc: str = 'lower right', pad: float = 0.03, offset: Tuple[float, float] = (0.0, 0.0), frac: float = 0.18, color: str = 'black', linewidth: float = 2.5, alpha: float = 1.0, fontsize: float = 10, caps: bool = True, cap_size: float | None = None, label: str | None = None, label_position: str = 'auto', label_pad: float = 3.0, frame: bool = False, frame_color: str = 'white', frame_alpha: float = 0.85, frame_pad: float = 4.0, zorder: float = 20) → Dict[str, Any][source]#

Draw a physical scale bar on a spatial matplotlib.axes.Axes

The bar is positioned and sized in axes coordinates, so it survives axis inversion (invert_y), cropping, and bbox_inches='tight' saving. The drawn length is converted from µm to data units through resolve_microns_per_unit().

Parameters:
  • ax – Target axes (must already have its final data limits set).

  • adata – AnnData used to resolve the coordinate unit. Optional when microns_per_unit is provided.

  • length – Bar length. "auto"/None picks a “nice” length (1/2/5 × 10ⁿ) equal to roughly frac of the visible width. A number is interpreted in unit (µm by default); strings such as "50um", "100 µm" or "20px" are accepted.

  • unit – Unit for a numeric length. "um" (default) or "px"/"data" to use raw data units.

  • microns_per_unit – Explicit µm per data unit. Overrides metadata inference.

  • library_id – Spatial library key used for unit inference.

  • basis – Only used for the informative warning when limits are unusable.

  • loc – Anchor of the bar inside the axes: "lower right" (default), "lower left", "upper right", "upper left", "lower center", "upper center", "center", "center right", "center left", "right", "left", "top", "bottom".

  • pad – Inset from the axes border, as a fraction of the axes size.

  • offset – Extra (dx, dy) shift in points, applied to the bar and its label.

  • frac – Fraction of the visible width the auto length should occupy (default 0.18).

  • color – Bar and label color.

  • linewidth – Bar thickness in points (also the cap thickness).

  • alpha – Opacity of bar, caps, and label.

  • fontsize – Label font size in points.

  • caps – Whether to draw end caps (making the bar look like |——|).

  • cap_size – Cap height in points. Defaults to 4 × linewidth.

  • label – Custom label text. By default "<length> µm".

  • label_position – "auto" (above the bar, below for upper* anchors), "above", "below" or "none".

  • label_pad – Gap between bar and label, in points (default 3).

  • frame – Draw a translucent rounded box behind the bar and label (useful on busy H&E backgrounds).

  • frame_color – Frame face color, opacity, and padding in points.

  • frame_alpha – Frame face color, opacity, and padding in points.

  • frame_pad – Frame face color, opacity, and padding in points.

  • zorder – Matplotlib z-order of the bar (label +0.1, frame -0.1).

Returns:

Resolved properties: length (in µm), label, microns_per_unit, unit, axes_fraction (bar length as a fraction of the x range).

Return type:

dict

Examples

>>> import matplotlib.pyplot as plt
>>> import trackcell as tcl
>>> fig, ax = plt.subplots()
>>> ax.scatter(*adata.obsm["spatial"].T, s=1)                
>>> ax.set_aspect("equal")                                    
>>> tcl.pl.add_scale_bar(ax, adata, length="100um", loc="lower left")
trackcell.pl.resolve_microns_per_unit(adata: object | None = None, library_id: str | None = None, *, microns_per_unit: float | None = None, coord_unit: str | None = None) → Tuple[float, str][source]#

Resolve how many micrometers one unit of obsm['spatial'] represents.

Parameters:
  • adata – AnnData with spatial metadata. May be None when microns_per_unit is given explicitly.

  • library_id – Spatial library key used to look up per-sample metadata.

  • microns_per_unit – Explicit override (µm per data unit). Takes precedence over everything.

  • coord_unit – Explicit hint for the coordinate unit ("um" or "px").

Returns:

microns_per_unit is the conversion factor from data units to µm; unit_family is "um" (coordinates are physical) or "px" (coordinates are pixels, factor derived from scalefactors).

Return type:

(microns_per_unit, unit_family)

Notes

Resolution order:

  1. explicit microns_per_unit;

  2. a coord_unit / spatial_units metadata hint (Atera, trackcell readers);

  3. metadata['pixel_size_um'] / metadata['resolution_nm'] — a fixed physical scale for the coordinate unit (STOmics GEF: 500 nm by default);

  4. scalefactors['microns_per_pixel'] (Visium / Visium HD pixels);

  5. fallback 1.0 — coordinates are assumed to be in µm, which holds for Xenium, Atera and MERSCOPE outputs. Pass microns_per_unit explicitly to override if your object uses pixel coordinates without scalefactors.

metadata['pixel_size'] is intentionally ignored: Xenium and Atera use it for morphology images, while their centroid coordinates are already µm.

trackcell.pl.nice_scale_length(target: float) → float[source]#

Round target down to the nearest “nice” length (1, 2 or 5 × 10ⁿ).

Parameters:

target (float) – Desired length in the same unit as the return value.

Returns:

The largest value of the form {1, 2, 5} × 10ⁿ that is <= target.

Return type:

float

trackcell.pl.select_regions(adata, color: str | None = None, library_id: str | None = None, img_key: str | None = None, mode: Literal['auto', 'cellbin', 'squarebin'] = 'auto', basis: str = 'spatial', key_added: str = 'ROI', inplace: bool = True, roi_prefix: str = 'ROI', ax: matplotlib.pyplot.Axes | None = None, show: bool = True, figsize: tuple | None = None, invert_y: bool = True, **kwargs) → RegionSelector[source]#

Select spatial regions interactively in Jupyter using matplotlib widgets.

Important

For the best notebook experience run %matplotlib widget before calling this function.

No more blocking ``input()`` — ROIs are auto-named with a configurable prefix (default ROI_1, ROI_2, …). Use selector.rename_roi("ROI_1", "my_region") to rename afterwards.

An inline toolbar at the bottom of the figure provides clickable buttons:

  • ■ Rect — rectangle selector

  • ● Ellipse — ellipse / circle selector

  • ✎ Lasso — lasso / freehand selector

  • ✕ Clear — remove all ROIs

  • ↩ Undo — remove the last ROI

Keyboard shortcuts also work while the figure has focus:

  • r — rectangle

  • e — ellipse / circle

  • l — lasso / freehand

Selected cells are highlighted with coloured scatter points in real-time.

Parameters:
  • adata (AnnData) – Annotated data object.

  • color (str or None) – Column or gene used to colour the background plot.

  • library_id (str or None) – Spatial library id (auto-detected when omitted).

  • img_key (str or None) – Key for the background image in uns['spatial'].

  • mode ({'auto', 'cellbin', 'squarebin'}) – Spatial data mode. Auto-detected when 'auto'.

  • basis (str) – Key in adata.obsm for squarebin coordinates (default 'spatial').

  • key_added (str) – Column name in adata.obs where ROI labels are stored.

  • inplace (bool) – If True (default) ROI labels are written to adata.obs[key_added] after every selection. If False, results are only stored on the returned RegionSelector — use selector.to_adata() to get a copy.

  • roi_prefix (str) – Prefix for auto-generated ROI names (default 'ROI' → ROI_1, ROI_2, …).

  • ax (matplotlib.axes.Axes or None) – Pre-existing axes to draw on.

  • show (bool) – Whether to call plt.show() at the end.

  • figsize (tuple or None) – Figure size passed to plt.subplots() when ax is not provided.

  • invert_y (bool) – Match image coordinates (y increases top-to-bottom). Default True.

  • **kwargs – Forwarded to the underlying plotting function (spatial_cell or spatial_squarebin).

Returns:

Controller with .rois, .polygons, .rename_roi(), .undo(), .save(), .clear(), .to_adata(), and .disconnect().

Return type:

RegionSelector

class trackcell.pl.RegionSelector(adata, ax: matplotlib.pyplot.Axes, mode: str, basis: str, valid_ids: Index, geometries=None, use_wkt: bool = False, key_added: str = 'ROI', inplace: bool = True, roi_prefix: str = 'ROI')[source]#

Bases: object

Controller returned by select_regions().

All shape modes (rectangle, ellipse, lasso) are available via both the inline toolbar (clickable buttons at the bottom of the figure) and keyboard shortcuts (r/e/l while the figure has focus).

ROIs are auto-named (ROI_1, ROI_2, …). Use rename_roi() to change names after the fact.

rois#

Mapping of ROI names to lists of observation IDs.

Type:

dict

polygons#

Mapping of ROI names to arrays of ROI boundary vertices in data coords.

Type:

dict

ax, fig

Matplotlib axes and figure.

add_roi(vertices: ndarray, name: str | None = None) → str[source]#

Manually add a ROI (programmatic use).

Parameters:
  • vertices (np.ndarray) – N×2 array of polygon vertices.

  • name (str or None) – ROI name. Auto-generated (<prefix>_N) when None.

Returns:

The assigned ROI name.

Return type:

str

rename_roi(old_name: str, new_name: str) → None[source]#

Rename a previously created ROI.

Parameters:
  • old_name (str) – Current ROI name.

  • new_name (str) – New ROI name (must not already exist).

undo() → None[source]#

Remove the last added ROI (boundary, highlight, and data).

save(key_added: str | None = None) → None[source]#

Force-write current ROI labels to adata.obs (useful with inplace=False).

to_adata()[source]#

Return a copy of the AnnData object with the ROI column added.

This is the primary way to retrieve results when inplace=False.

clear() → None[source]#

Remove all ROIs, visual patches, and highlights.

disconnect() → None[source]#

Disconnect all selectors, toolbar buttons, and keyboard callback.

Tools Functions#

TL (Tools) module for TrackCell package.

This module provides utility and helper functions for single-cell and spatial transcriptomics data analysis.

trackcell.tl.atera_cell_qc(adata: AnnData, compute_expression_genes: bool = True) → DataFrame[source]#

Compute cell-level QC for an Atera AnnData object.

Atera’s obs['total_counts'] includes control probes/codewords; use obs['transcript_counts'] for gene-only counts.

Returns:

Indexed by adata.obs_names with total_counts, transcript_counts, n_genes (matrix nnz per cell, includes control features), n_genes_expression (Gene Expression features only, when compute_expression_genes=True), cell_area, nucleus_area, nuclear_area_ratio and control fractions.

Return type:

DataFrame

trackcell.tl.filter_atera_genes(adata: AnnData, inplace: bool = False) → AnnData[source]#

Keep only feature_type == 'Gene Expression' features.

Atera panels include thousands of negative-control codewords. They must be removed before HVG selection / PCA / clustering.

Examples

>>> adata = tcl.io.filter_atera_genes(adata)
trackcell.tl.sctransform(adata: AnnData, *, layer: str | None = None, n_top_genes: int | None = 3000, variable_features_rv_th: float = 1.3, n_cells: int = 5000, n_genes: int = 2000, do_correct_umi: bool = True, do_center: bool = True, do_scale: bool = False, clip_range: tuple[float, float] | None = None, res_clip_range: tuple[float, float] | None = None, return_only_var_genes: bool = True, residual_features: Sequence[str] | None = None, conserve_memory: bool = False, reference_sct_model: dict | None = None, vars_to_regress: Sequence[str] | None = None, latent_var: Sequence[str] | None = None, batch_var: str | None = None, batch_key: str | None = None, latent_var_nonreg: Sequence[str] | None = None, residual_type: str = 'pearson', model_use: str = 'linear', vst_flavor: str | None = None, v2_backend: str = 'python', seed: int = 1448145, key_added: str = 'sct', store_residuals_in: str = 'obsm', save_reference_model: bool = True, inplace: bool = True, copy: bool = False, cells_step1: Sequence[str] | None = None, genes_step1: Sequence[str] | None = None, subsample_indices: dict[str, dict[str, Sequence[str]]] | None = None, batch_n_jobs: int = 1) → AnnData | None[source]#

Normalize UMI counts with SCTransform (Seurat 4.4.0).

Uses a pure-Python implementation of the regularized negative-binomial normalization workflow. vst_flavor="v2" is supported via a built-in vectorised NB GLM (inspired by shanuz), with optional pyglmGamPoi acceleration when the package is installed.

Parameters:
  • adata – Annotated data matrix with raw UMI counts in adata.X or layer.

  • layer – Layer containing raw counts. Uses adata.X when None.

  • batch_key – Column in adata.obs identifying biological batches/replicates. Runs independent SCT models per batch (Seurat SplitObject equivalent) and stores them in adata.uns[key_added]['batch_models'].

  • vst_flavor – When "v2", use SCT v2 defaults (fixed depth slope, exclude_poisson=True, min_variance='umi_median', n_cells=2000).

  • v2_backend – Explicit SCT v2 step-1 fitter. "python" (default) uses the bundled NB offset implementation. "pyglmGamPoi" uses the optional package and raises when it is not installed. No automatic backend switching.

  • batch_var – Column in adata.obs for batch-aware VST fitting within a single object. Do not combine with batch_key.

  • cells_step1 – Fixed cell/gene subsample indices for VST step 1 (Seurat vst parity). When set, random subsampling is skipped for the provided dimension(s).

  • genes_step1 – Fixed cell/gene subsample indices for VST step 1 (Seurat vst parity). When set, random subsampling is skipped for the provided dimension(s).

  • subsample_indices – Per-batch fixed subsample indices when using batch_key. Each entry maps a batch label to {"cells_step1": [...], "genes_step1": [...]}.

  • batch_n_jobs – Parallel workers for per-batch SCT when batch_key is set. 1 runs batches serially (default); -1 uses all CPUs; N > 1 uses at most N workers (capped by batch count).

  • inplace – If True (default) write results into the input adata and return None. inplace=False requires copy=True.

  • copy – If True, run on a deep copy and return it. The input is left untouched; this also implies a return value even when inplace is left at its default.

Notes

adata.obsm['X_{key_added}'] columns follow the order of adata.uns[key_added]['variable_features'] (Seurat residual-variance order), which is not the same as adata.var_names order. Use variable_features when mapping columns back to genes. The layer written by store_residuals_in='layer' is aligned to adata.var_names.

trackcell.tl.pack_sct_model(vst_out: dict[str, Any], clip_range: tuple[float, float] | None = None) → dict[str, Any][source]#

Serialize a VST result for reuse as a reference SCT model.

trackcell.tl.select_integration_features(adata: AnnData, *, batch_key: str, sct_key: str = 'sct', n_features: int = 2000, features: Sequence[str] | None = None, method: Literal['seurat', 'xgboost'] = 'seurat', layer: str | None = None, seed: int = 0, return_importance: bool = False)[source]#

Choose anchor genes for SCT integration.

The two method values answer different questions and their results are not comparable. This is the most important thing to know about this function:

method='seurat' (default) — Seurat SelectIntegrationFeatures: genes most often selected as VariableFeatures across the per-batch SCT models, with Seurat tie-breaking. Selects genes that vary reproducibly within batches.

method='xgboost' — genes that best separate batches, ranked by gain importance from a classifier trained on per-cell SCT residuals. On the same input this ranking points in close to the opposite direction to the default: a gene whose variance is purely batch-driven ranks high here and low under 'seurat', and vice versa. Running both and comparing the resulting integrated embeddings therefore compares two different feature spaces, not two implementations of one method.

'xgboost' is an experiment, not a Seurat equivalent. Its importances are in-sample (no held-out fold, no cross-validation), and anchors found on batch-discriminating features can match cells by batch structure rather than by cell identity. 'seurat' remains the supported path for reciprocal PCA. Use return_importance=True to inspect the ranking it produces.

Parameters:

return_importance – Only meaningful for method='xgboost'. Return (genes, table), where table is a DataFrame of gene / importance sorted descending. For method='seurat' the flag is ignored and a plain list is returned, because that method has no single importance score.

Return type:

list of str, or (list of str, DataFrame)

trackcell.tl.prep_sct_integration(adata: AnnData, *, batch_key: str, anchor_features: Sequence[str], sct_key: str = 'sct', layer: str | None = None, key_added: str = 'sct_prep') → AnnData[source]#

Compute Pearson residuals for anchor genes per batch (Seurat PrepSCTIntegration).

Matches Seurat GetResidualSCTModel / PrepSCTIntegration: reuse stored per-batch scale.data for anchor genes already present, compute pearson residuals (row-centered) only for missing genes.

Stores a cells x genes residual matrix in adata.obsm[f'X_{key_added}'] and per-batch metadata in adata.uns[key_added].

trackcell.tl.run_sct_integration(adata: AnnData, *, batch_key: str, anchor_features: Sequence[str] | None = None, n_features: int = 2000, sct_key: str = 'sct', prep_key: str = 'sct_prep', layer: str | None = None, feature_method: Literal['seurat', 'xgboost'] | None = None, seed: int = 0, run_prep: bool = True, require_sct_models: bool = True, run_sct: bool | None = None, sct_vst_flavor: str | None = 'v2', sct_v2_backend: Literal['python', 'pyglmGamPoi'] = 'python', n_sct_hvg: int = 3000, sct_seed: int = 1448145, sct_batch_n_jobs: int = 1, clip_range: tuple[float, float] | None = None, res_clip_range: tuple[float, float] | None = None, copy: bool = False) → AnnData[source]#

Run SCT + SelectIntegrationFeatures + PrepSCTIntegration (Seurat Steps 1–3).

Stores per-batch SCT models in adata.uns[sct_key] and anchor-gene Pearson residuals in adata.obsm[f'X_{prep_key}']. The prep matrix is suitable input for integrate_rpca(), Harmony, BBKNN, or other methods.

See sct_prep_matrix() to extract the matrix and feature names.

trackcell.tl.release_sct_integration_cache(adata: AnnData, *, sct_key: str = 'sct', prep_key: str = 'sct_prep', what: Literal['scale_data', 'batch_models', 'sct_uns'] = 'scale_data', require_prep: bool = True) → dict[str, int | str][source]#

Explicitly drop SCT caches from adata.uns after prep is finalised.

Opt-in only — nothing is removed unless you call this. integrate_rpca / Seurat-parity RPCA use obsm['X_{prep_key}'] only; releasing caches does not change integrated output if prep is already stored.

Parameters:
  • what – 'scale_data' — remove per-batch scale_data (largest cache). 'batch_models' — remove all batch_models (keeps params). 'sct_uns' — remove entire adata.uns[sct_key].

  • require_prep – If True (default), require prep_key and obsm['X_{prep_key}'].

Returns:

Summary: what, n_batches, bytes_estimate (rough lower bound).

Return type:

dict

trackcell.tl.sct_prep_matrix(adata: AnnData, prep_key: str = 'sct_prep') → tuple[ndarray, list[str]][source]#

Return SCT prep residuals and anchor feature names for external integrators.

Use with Harmony, BBKNN, scVI, etc.:

run_sct_integration(adata, batch_key='orig.ident')
matrix, genes = sct_prep_matrix(adata)
adata.obsm['X_pca'] = ...  # PCA on matrix, then harmony / bbknn
trackcell.tl.integrate_rpca(adata: AnnData, *, batch_key: str, prep_key: str = 'sct_prep', sct_key: str = 'sct', anchor_features: Sequence[str] | None = None, dims: int = 30, k_anchor: int = 5, k_score: int = 30, k_weight: int = 100, sd_weight: float = 1.0, l2_norm: bool = True, n_trees: int = 50, n_trees_weight: int | None = None, weight_query_chunk_size: int = 8192, integration_dtype: Literal['float32', 'float64'] = 'float32', preserve_order: bool = False, method: Literal['seurat', 'xgboost'] = 'seurat', xgb_n_delta_pcs: int = 20, xgb_n_estimators: int = 150, xgb_max_depth: int = 4, seed: int = 0, key_added: str = 'sct_integrated', copy: bool = False) → AnnData[source]#

RPCA anchor finding + IntegrateData on existing SCT prep residuals.

Expects run_sct_integration (or manual prep_sct_integration) to have stored anchor residuals in adata.obsm[f'X_{prep_key}'].

Workflow#

  1. FindIntegrationAnchors(reduction='rpca', normalization.method='SCT')

  2. IntegrateData(normalization.method='SCT')

Stores integrated residuals in adata.obsm[f'X_{key_added}'].

trackcell.tl.integrate_sct_rpca(adata: AnnData, *, batch_key: str, anchor_features: Sequence[str] | None = None, n_features: int = 2000, sct_key: str = 'sct', prep_key: str = 'sct_prep', layer: str | None = None, dims: int = 30, k_anchor: int = 5, k_score: int = 30, k_weight: int = 100, sd_weight: float = 1.0, l2_norm: bool = True, n_trees: int = 50, n_trees_weight: int | None = None, weight_query_chunk_size: int = 8192, integration_dtype: Literal['float32', 'float64'] = 'float32', preserve_order: bool = False, method: Literal['seurat', 'xgboost'] = 'seurat', feature_method: Literal['seurat', 'xgboost'] | None = None, xgb_n_delta_pcs: int = 20, xgb_n_estimators: int = 150, xgb_max_depth: int = 4, seed: int = 0, key_added: str = 'sct_integrated', run_prep: bool = True, require_sct_models: bool = True, run_sct: bool | None = None, sct_vst_flavor: str | None = 'v2', sct_v2_backend: Literal['python', 'pyglmGamPoi'] = 'python', n_sct_hvg: int = 3000, sct_seed: int = 1448145, sct_batch_n_jobs: int = 1, clip_range: tuple[float, float] | None = None, res_clip_range: tuple[float, float] | None = None, copy: bool = False) → AnnData[source]#

SCT integration with reciprocal PCA anchors (Seurat v4 workflow).

Convenience wrapper around run_sct_integration() (Steps 1–3) and integrate_rpca() (Steps 4–5). For Harmony / BBKNN, call run_sct_integration only and use sct_prep_matrix or adata.obsm['X_{prep_key}'].

See run_sct_integration() and integrate_rpca() for parameter details.

trackcell.tl.hd_labeldist(adata, groupby: str, label: str, inplace: bool = True, method: str = 'kdtree', coordinate_system: str = 'auto', library_id: str | None = None, microns_per_pixel: float | None = None, hires_scale: float | None = None)[source]#

Compute the distance from every cell to the nearest cell annotated with a specific label.

Works for Visium HD (obsm['spatial'] in image pixels) and for platforms whose coordinates already have a physical scale: Xenium / Atera (µm) and STOmics GEF (resolution units, typically 500 nm). The conversion factor is resolved through trackcell.pl.resolve_microns_per_unit(), so it cannot disagree with scale bars or cells_in_radius() on the same object.

Distances are reported both in the pixel coordinate system stored in .obsm[“spatial”] (SpaceRanger target/hires layer) and in microns using the scalefactors embedded in adata.uns[“spatial”].

By default, the function preserves the previous auto-detection heuristic for hires vs full-res coordinates. For reproducible distances, pass coordinate_system='fullres' or coordinate_system='hires' explicitly.

Parameters:
  • adata (sc.AnnData) – Annotated data matrix with spatial coordinates and SpaceRanger scalefactors.

  • groupby (str) – Column name in adata.obs that contains the annotation labels.

  • label (str) – Target label within groupby for which distances will be computed.

  • inplace (bool, default True) – If True, the function adds two columns to adata.obs: {label}_px (distance in the raw coordinate units of obsm[‘spatial’]: pixels for Visium HD, µm for Xenium / Atera, resolution units for STOmics) and {label}_dist (physical distance in microns). If False, the function returns a dataframe with the two columns.

  • method (str, default "kdtree") –

    Method to use for distance computation: - “kdtree”: Use KDTree spatial indexing (recommended, O(n log n) time, O(n) memory).

    Best for large datasets with many cells.

    • ”cdist”: Use scipy’s cdist function (O(n*m) time and memory, where m is number of label cells).

      Faster for small datasets but memory-intensive for large ones.

  • coordinate_system ({'auto', 'fullres', 'hires'}, default 'auto') – Pixel coordinate system used by adata.obsm[‘spatial’]. fullres uses microns_per_pixel directly; hires divides by hires_scale; auto uses a heuristic and warns when ambiguous. Only meaningful for pixel coordinates: when the object declares a physical unit (µm / resolution units), auto resolves to 'data', fullres is ignored with a warning, and hires raises.

  • library_id (str, optional) – Spatial library id in adata.uns[‘spatial’]. Defaults to the first one.

  • microns_per_pixel (float, optional) – Explicit pixel size (µm per pixel). Treated as a pixel-coordinate factor, so fullres/hires handling stays available. Do not pass it for Xenium / Atera objects, whose coordinates are already µm.

  • hires_scale (float, optional) – Override tissue_hires_scalef / regist_target_img_scalef.

Returns:

Returns a DataFrame with {label}_px and {label}_dist when inplace=False. Otherwise, modifies adata.obs in place and returns None.

Return type:

pandas.DataFrame | None

trackcell.tl.cells_in_radius(adata: Any, center, radius: float, *, radius_unit: str = 'um', basis: str = 'spatial', library_id: str | None = None, microns_per_unit: float | None = None, include_boundary: bool = True, return_distances: bool = False) → Any[source]#

Select cells inside a circle defined by a center point and a physical radius.

The intended workflow is to draw an overview plot, pick a point in the tissue (ax.transData.inverted() on a click, plt.ginput, or plain coordinates), and then keep every cell within a given distance of it. Because radius is a physical length by default, the same call means the same thing on data whose coordinates are µm (Xenium, Atera, MERSCOPE) and on data whose coordinates are image pixels (Visium, Visium HD).

Parameters:
  • adata – Annotated data object with spatial coordinates in adata.obsm[basis].

  • center (tuple of float) – Circle center (x, y) in the coordinate system of ``adata.obsm[basis]`` — i.e. the numbers you read off the plot.

  • radius (float) – Circle radius, in radius_unit.

  • radius_unit ({'um', 'data'}, default 'um') – 'um' interprets radius as micrometers and converts it to data units through trackcell.pl.resolve_microns_per_unit(). 'data' uses raw obsm units, which is what you want if the coordinates are already in µm and you prefer to say so explicitly.

  • basis (str, default 'spatial') – Key in adata.obsm holding the 2D coordinates.

  • library_id (str, optional) – Spatial library id used for the µm conversion (defaults to the first).

  • microns_per_unit (float, optional) – Explicit µm per data unit, overriding metadata inference.

  • include_boundary (bool, default True) – Whether cells at distance == radius are kept (<= vs <).

  • return_distances (bool, default False) – When True return (mask, distances) with distances in µm.

Returns:

Boolean mask aligned with adata.obs_names, usable directly as adata[mask].copy(). With return_distances=True, also the distance of every cell to center in µm.

Return type:

numpy.ndarray or tuple

Examples

>>> import trackcell as tcl
>>> center = (4500.0, 2600.0)          # µm, read off the overview plot
>>> mask = tcl.tl.cells_in_radius(adata, center, radius=150)
>>> roi = adata[mask].copy()
>>> tcl.pl.spatial_cell(roi, color="celltype", scalebar=True)

Notes

For Visium HD pixel coordinates radius=150 means 150 µm, not 150 px: scalefactors['microns_per_pixel'] is applied automatically.

trackcell.tl.multigene_blend(adata, genes: List[str], mode: str = 'blend', colors: List[str] | None = None, layer: str | None = None, vmin_percentile: float = 1.0, vmax_percentile: float = 99.0, gamma: float = 1.0, background: str = '#e0e0e0', key_added: str = 'multigene_blend', ncols: int = 3, figsize: tuple | None = None, edges_width: float = 0.3, edges_color: str = '#cccccc30', alpha_facet: float = 0.8, show: bool = True, ax=None, library_id: str | None = None, inplace: bool = True)[source]#

Multi-gene co-expression visualization with two modes.

Mode ‘blend’ (default): Computes blended hex colors by weighted RGB averaging of per-gene base colors. The result is a hex color per cell stored in adata.obs[key_added], usable with spatial_cell(color=key_added).

The blend encodes relative composition, not absolute expression level: because the per-gene weights sum to 1, a cell with one UMI of gene A and a cell with 1,000 UMIs of gene A get the same colour when no other gene is expressed. Use mode='facet' (or a single-gene spatial_cell plot) when intensity matters.

Mode ‘facet’: Draws faceted subplots, one gene per panel, each using a single-hue colormap (white → gene color). Returns matplotlib axes.

Parameters:
  • adata (AnnData) – Annotated data with gene expression.

  • genes (list of str) – Gene names. Up to 7 recommended for blend mode.

  • mode (str) – ‘blend’ (default) or ‘facet’.

  • colors (list of str, optional) – Base colors for each gene (hex). Default: perceptually distinct palette.

  • layer (str, optional) – Use adata.layers[layer] instead of adata.X.

  • vmin_percentile (float) – Lower percentile for clipping (blend & facet, default 1).

  • vmax_percentile (float) – Upper percentile for clipping (blend & facet, default 99).

  • gamma (float) – Gamma correction for blend mode (>1 darkens, <1 brightens).

  • background (str) – Background hex color for blend mode (zero-expression cells).

  • key_added (str) – obs column name for blend mode output.

  • inplace (bool) – If True (blend), stores in adata.obs. If False, returns Series.

  • parameters (**Facet-specific)

  • ncols (int) – Number of columns in facet grid (default 3).

  • figsize (tuple, optional) – Figure size. Auto-computed from ncols if None.

  • edges_width (float) – Cell edge width for facet plots (default 0.3).

  • edges_color (str) – Cell edge color for facet plots (default ‘#cccccc30’).

  • alpha_facet (float) – Cell transparency for facet plots (default 0.8).

  • show (bool) – Whether to call plt.show() (default True).

  • ax (matplotlib.Axes or array, optional) – Pre-existing axes to plot on.

  • library_id (str, optional) – Library id passed to spatial_cell.

Returns:

  • blend mode (pd.Series or None)

  • facet mode (np.ndarray of matplotlib.Axes)

Examples

>>> import trackcell as tcl
>>>
>>> # Mode 1: Blend → single composite image
>>> tcl.tl.multigene_blend(adata, genes=['EPCAM', 'PECAM1', 'VWF'])
>>> tcl.pl.spatial_cell(adata, color='multigene_blend')
>>>
>>> # Mode 2: Facet → subplots per gene
>>> tcl.tl.multigene_blend(
...     adata, genes=['EPCAM', 'PECAM1', 'VWF'],
...     mode='facet', ncols=3,
... )
trackcell.tl.spatial_cluster(adata: AnnData, mode: Literal['celltype', 'domain', 'auto'] = 'auto', lambda_celltype: float = 0.2, lambda_domain: float = 0.8, platform: Literal['visium_hd', 'sto', 'xenium', 'xenium_tma'] | None = None, k_spatial: int | None = None, k_gradient: int | None = None, k_expr: int | None = None, use_gradient: bool | None = None, gradient_mode: Literal['cosphi', 'regression'] = 'cosphi', n_pcs: int | None = None, n_layers: int = 1, resolution: float | Literal['auto'] | None = None, resolution_celltype: float | Literal['auto'] | None = None, resolution_domain: float | Literal['auto'] | None = None, method: Literal['leiden', 'gmm'] = 'leiden', n_clusters: int | None = None, n_resolution_runs: int = 5, random_state: int = 0, batch_key: str | None = None, integrate: Literal['none', 'separate', 'joint', 'bbknn'] = 'none', harmony_integrate: bool = False, graph_mode: Literal['expr', 'spatial', 'hybrid'] = 'expr', hybrid_alpha: float = 0.3, hvg_by_batch: bool = True, scale_by_batch: bool = False, layer: str | None = None, use_raw: bool = False, expression_source: Literal['x', 'sct_prep', 'sct_integrated'] = 'x', sct_prep_key: str = 'sct_prep', sct_integrated_key: str = 'sct_integrated', chunk_size: int = 500, preprocess: bool = True, n_top_genes: int | None = None, merge_clusters: bool | None = None, merge_clusters_celltype: bool | None = None, merge_clusters_domain: bool | None = None, merge_adj_p: float = 0.05, merge_max_de_tests: int | None = 2000, sketch: bool = False, sketch_threshold: int = 500000, sketch_n: int = 500000, sketch_stratified: bool = True, reuse_neighbors: bool = True, key_added: str = 'yardcluster', copy: bool = False) → AnnData | None[source]#

YardCluster spatial clustering (one-shot or dual-mode).

Multi-slice: expression_source='sct_prep' after SCT; expression_source='sct_integrated' after SCT+RPCA (M/G from prep, identity from RPCA). Use integrate='bbknn' or 'joint' (Harmony) when batch correction is not already in the embedding.

Platform presets (platform='visium_hd'|'sto'|'xenium'|'xenium_tma') fill k_spatial, n_pcs, resolution, k_expr, n_top_genes when those arguments are None.

graph_mode: 'expr' (default), 'spatial' (Leiden on spatial graph), or 'hybrid' (weighted mix; tune with hybrid_alpha).

method: 'leiden' (default) or 'gmm' (sklearn Gaussian mixture). resolution='auto' (or resolution_celltype/resolution_domain) selects the resolution by clustering stability. n_layers enables CellCharter-style multi-hop neighborhood aggregation.

trackcell.tl.spatial_neighbors(adata: AnnData, k: int = 15, batch_key: str | None = None, key_added: str = 'spatial', copy: bool = False) → AnnData | None[source]#

Build within-batch spatial kNN graph with Gaussian weights.

trackcell.tl.neighborhood_features(adata: AnnData, k_spatial: int = 15, batch_key: str | None = None, use_gradient: bool = False, gradient_mode: Literal['cosphi', 'regression'] = 'cosphi', k_gradient: int | None = None, n_layers: int = 1, layer: str | None = None, use_raw: bool = False, expression_source: Literal['x', 'sct_prep', 'sct_integrated'] = 'x', sct_prep_key: str = 'sct_prep', sct_integrated_key: str = 'sct_integrated', chunk_size: int = 500, key_added: str = 'yard', reuse_neighbors: bool = True, copy: bool = False) → AnnData | None[source]#

Compute neighborhood mean M and optional gradient G features.

n_layers controls multi-hop aggregation (CellCharter-style): when >1, M becomes the concatenation of hop 1..``n_layers`` means instead of the 1-hop mean.

trackcell.tl.yard_embed(adata: AnnData, lam: float = 0.2, n_pcs: int = 20, key_added: str = 'yard', layer: str | None = None, use_raw: bool = False, expression_source: Literal['x', 'sct_prep', 'sct_integrated'] = 'x', sct_prep_key: str = 'sct_prep', sct_integrated_key: str = 'sct_integrated', batch_key: str | None = None, harmony_integrate: bool = False, copy: bool = False) → AnnData | None[source]#

Dual-channel YardCluster embeddings and lambda-mixed representation.

trackcell.tl.yard_cluster(adata: AnnData, use_rep: str = 'X_yard_mixed', k_expr: int | None = 50, resolution: float | Literal['auto'] = 1.0, key_added: str = 'yardcluster', neighbors_key: str | None = None, merge_clusters: bool = False, merge_adj_p: float = 0.05, merge_max_de_tests: int | None = 2000, sketch: bool = False, sketch_threshold: int = 500000, sketch_n: int = 500000, sketch_stratified: bool = True, batch_key: str | None = None, neighbors_method: Literal['expr', 'spatial', 'hybrid', 'bbknn'] = 'expr', hybrid_alpha: float = 0.3, spatial_conn_key: str = 'spatial_connectivities', method: Literal['leiden', 'gmm'] = 'leiden', n_clusters: int | None = None, n_resolution_runs: int = 5, random_state: int = 0, copy: bool = False) → AnnData | None[source]#

Cluster using the YardCluster embedding.

method='leiden' (default) runs Leiden on a neighbor graph; set resolution='auto' to select the resolution by clustering stability. method='gmm' fits a Gaussian mixture (sklearn) on use_rep, with n_clusters=None picking k by BIC. Optional DE merge and sketch apply to the Leiden path.

trackcell.tl.connected_components(adata: AnnData, cluster_key: str | None = None, min_cells: int = 250, connectivity_key: str = 'spatial_connectivities', out_key: str = 'component', copy: bool = False) → AnnData | None[source]#

Split spatial clusters into connected components of the spatial graph.

A single cluster label can correspond to several physically disconnected regions (e.g. the same domain across multiple TMA cores). This function relabels each connected region as a distinct component, discarding regions smaller than min_cells (assigned NaN).

Parameters:
  • adata – Annotated data object.

  • cluster_key – Key in adata.obs with cluster labels. If None, components are computed on the whole graph.

  • min_cells – Minimum number of cells for a component to be kept.

  • connectivity_key – Key in adata.obsp with the spatial connectivities.

  • out_key – Key in adata.obs where component labels are stored.

  • copy – If True, return a modified copy.

Return type:

None or anndata.AnnData if copy=True.

trackcell.tl.nhood_enrichment(adata: AnnData, cluster_key: str, connectivity_key: str = 'spatial_connectivities', log_fold_change: bool = False, only_inter: bool = True, symmetric: bool = True, copy: bool = False) → dict | None[source]#

Neighborhood enrichment between clusters on the spatial graph.

Compares the observed weighted links between cluster pairs with the expected links under a degree-preserving (configuration-model) null. Enrichment is observed - expected by default, or log2(observed / expected) when log_fold_change=True.

Parameters:
  • adata – Annotated data object.

  • cluster_key – Key in adata.obs with cluster labels.

  • connectivity_key – Key in adata.obsp with the spatial connectivities.

  • log_fold_change – If True, report log2(observed / expected) instead of the difference.

  • only_inter – If True, ignore the diagonal (same-cluster links).

  • symmetric – If True, the enrichment matrix is symmetric; otherwise rows are normalized by the source cluster degree (directed view).

  • copy – If True, return the result dict instead of writing to adata.uns.

Return type:

None or a dict with keys 'enrichment', 'observed', 'expected'.

trackcell.tl.diff_nhood_enrichment(adata: AnnData, cluster_key: str, condition_key: str, condition_groups: tuple[str, str], connectivity_key: str = 'spatial_connectivities', library_key: str | None = None, pvalues: bool = False, n_perms: int = 1000, random_state: int = 0, log_fold_change: bool = False, copy: bool = False) → dict | None[source]#

Differential neighborhood enrichment between two conditions.

Computes the per-condition enrichment matrices and subtracts them. When pvalues=True, a permutation test shuffles the sample (library_key) labels between conditions to build the null distribution of each cluster-pair difference.

Parameters:
  • adata – Annotated data object.

  • cluster_key – Key in adata.obs with cluster labels.

  • condition_key – Key in adata.obs with the condition label.

  • condition_groups – Two condition values to compare, e.g. ("Case", "Ctr").

  • connectivity_key – Key in adata.obsp with the spatial connectivities.

  • library_key – Key in adata.obs with the sample/library id used for permutation. Required when pvalues=True.

  • pvalues – If True, compute empirical p-values via sample-label permutation.

  • n_perms – Number of permutations.

  • random_state – Seed for the permutation RNG.

  • log_fold_change – If True, use log2 ratio enrichment before differencing.

  • copy – If True, return the result dict.

Returns:

  • None or dict with key '{c1}_{c2}' containing 'enrichment' and,

  • when pvalues=True, 'pvalue' plus BH-adjusted 'pvalue_adj'.

trackcell.tl.select_resolution(adata: AnnData, *, use_rep: str | None = None, neighbors_key: str | None = None, resolutions: Sequence[float] | None = None, n_runs: int = 5, n_neighbors: int = 15, random_state: int = 0, copy: bool = False) → tuple[float, DataFrame][source]#

Pick the Leiden resolution with the highest stability.

Returns:

  • best_resolution – Resolution maximizing stability among resolutions producing >1 cluster.

  • sweep – The full sweep pandas.DataFrame.

trackcell.tl.sweep_resolutions(adata: AnnData, *, use_rep: str | None = None, neighbors_key: str | None = None, resolutions: Sequence[float] | None = None, n_runs: int = 5, n_neighbors: int = 15, random_state: int = 0, copy: bool = False) → DataFrame[source]#

Sweep Leiden resolutions and score each by clustering stability.

For each resolution the pipeline runs Leiden n_runs times with different seeds and reports the mean pairwise ARI (stability) plus the median number of clusters.

Parameters:
  • adata – Annotated data object.

  • use_rep – Key in adata.obsm used to build the neighbor graph when neighbors_key is not provided.

  • neighbors_key – Key of an existing neighbor graph (adata.uns[neighbors_key]). If None, sc.pp.neighbors is run on use_rep first.

  • resolutions – Resolution grid. Default np.arange(0.2, 2.01, 0.2).

  • n_runs – Number of repeated Leiden runs per resolution.

  • n_neighbors – kNN size used when building a new neighbor graph.

  • random_state – Base seed; run i uses random_state + i.

  • copy – If True, run on a copy of adata.

Returns:

Trim spatial-graph edges longer than a distance percentile (CellCharter-style).

Edges whose Euclidean length exceeds distance_percentile of all positive edge distances are dropped, and rows are re-normalized. This prevents kNN edges from bridging across tissue gaps.

Parameters:
  • coords – (n_obs, 2) spatial coordinates.

  • weights – Row-normalized spatial weight matrix (must share the same ordering as coords).

  • distance_percentile – Percentile of positive edge distances used as the cutoff. Default 99.0 trims the longest 1% of edges.

Returns:

A new row-normalized weight matrix. Every row sums to 1: a cell whose edges are all trimmed away receives a self loop of weight 1.0, so its neighborhood context becomes its own expression rather than zeros. build_spatial_weights uses the same fallback for a neighbour-less cell, so the two paths agree.

Return type:

scipy.sparse.csr_matrix

trackcell.tl.dbscan_slice_labels(coords: ndarray, eps: float = 80.0, min_samples: int = 10, min_cells: int = 1000, slice_start: int = 1, slice_prefix: str = 'S', debris_label: str = 'debris', sort_spatial: bool = True, n_jobs: int = -1) → tuple[ndarray, ndarray][source]#

Run DBSCAN on 2D coordinates and assign human-readable slice IDs.

Clusters with fewer than min_cells observations are labeled debris. Valid clusters receive sequential IDs {slice_prefix}{NNN} (e.g. S001).

Parameters:
  • coords – N×2 array of spatial coordinates (typically µm).

  • eps – DBSCAN neighborhood radius (µm for Xenium centroids).

  • min_samples – Minimum neighbors to form a dense region (DBSCAN min_samples).

  • min_cells – Minimum cells per cluster to keep as a valid slice.

  • slice_start – Starting index for numbered slice IDs.

  • slice_prefix – Prefix for slice IDs (default S → S001, S002, …).

  • debris_label – Label for noise and undersized clusters.

  • sort_spatial – If True, order slices by mean Y then mean X before numbering.

  • n_jobs – Parallel jobs passed to sklearn DBSCAN (-1 = all cores).

Returns:

  • slice_cluster – Integer DBSCAN labels (-1 = noise).

  • slice_id – String slice IDs including debris_label for discarded cells.

trackcell.tl.spatial_slice_cluster(adata: AnnData, eps: float = 80.0, min_samples: int = 10, min_cells: int = 1000, slice_start: int = 1, slice_prefix: str = 'S', debris_label: str = 'debris', spatial_key: str = 'spatial', key_added: str = 'slice_id', cluster_key: str = 'slice_cluster', sort_spatial: bool = True, n_jobs: int = -1, copy: bool = False, eps_unit: str = 'um', microns_per_unit: float | None = None) → AnnData | None[source]#

Annotate an AnnData object with DBSCAN-based tissue slice labels.

Intended for Xenium TMA regions where multiple tissue cores share one coordinate system. Operates on obsm[spatial_key] or obs[['x_centroid', 'y_centroid']].

Parameters:
  • adata – AnnData with spatial coordinates.

  • eps – Passed to dbscan_slice_labels() (eps after unit conversion).

  • min_samples – Passed to dbscan_slice_labels() (eps after unit conversion).

  • min_cells – Passed to dbscan_slice_labels() (eps after unit conversion).

  • slice_start – Passed to dbscan_slice_labels() (eps after unit conversion).

  • slice_prefix – Passed to dbscan_slice_labels() (eps after unit conversion).

  • debris_label – Passed to dbscan_slice_labels() (eps after unit conversion).

  • spatial_key – Key in adata.obsm for coordinates.

  • key_added – obs column for string slice IDs.

  • cluster_key – obs column for raw DBSCAN cluster integers.

  • sort_spatial – Sort slices by spatial position before numbering.

  • n_jobs – DBSCAN parallel jobs.

  • copy – If True, return a modified copy instead of updating in place.

  • eps_unit – Unit of eps: 'um' (default) converts through trackcell.pl.resolve_microns_per_unit(), so the same eps=80 means 80 µm on Xenium / Atera (factor 1), Visium HD (pixel coordinates, factor microns_per_pixel) and STOmics (resolution units). Pass 'data' to use raw coordinate units, which is what the function did before this option existed.

  • microns_per_unit – Explicit µm-per-data-unit override used when eps_unit='um'.

Returns:

Copy when copy=True; otherwise None (in-place update).

Return type:

AnnData or None

trackcell.tl.spatial_colony_cluster(adata: AnnData, eps: float = 50.0, min_samples: int = 5, min_cluster_size: int = 40, spatial_key: str = 'spatial', cluster_key: str = 'spatial_colony', metric: str = 'euclidean', n_jobs: int = -1, copy: bool = False) → AnnData | None[source]#

DBSCAN colony labels for dispersed micro-regions within one tissue section.

Intended for pre-filtered subsets (e.g. BANKSY Germinal Center B Cells or tumor ROI clusters). Clusters smaller than min_cluster_size and DBSCAN noise (-1) are stored as NaN in obs[cluster_key].

Default parameters match CCHD 54_1_GC_dist.ipynb (Xenium GC colonies).

Parameters:
  • adata – AnnData subset with spatial coordinates (typically after BANKSY).

  • eps – DBSCAN radius and density filters; small clusters → NaN.

  • min_samples – DBSCAN radius and density filters; small clusters → NaN.

  • min_cluster_size – DBSCAN radius and density filters; small clusters → NaN.

  • spatial_key – Key in adata.obsm for coordinates.

  • cluster_key – obs column for colony IDs (float categorical with NaN).

  • metric – Distance metric for DBSCAN.

  • n_jobs – DBSCAN parallel jobs.

  • copy – If True, return a modified copy instead of updating in place.

Returns:

Copy when copy=True; otherwise None (in-place update).

Return type:

AnnData or None

trackcell.tl.mark_colony_centroids(adata: AnnData, colony_key: str = 'spatial_colony', centroid_key: str = 'cell_centroid_type', centroid_label: str = 'GCC', spatial_key: str = 'spatial', copy: bool = False) → AnnData | None[source]#

Mark one representative cell per colony (nearest to the geometric centroid).

Stores obs[centroid_key] and colony metadata in uns['colony_centroids']. Default label GCC follows CCHD GC analysis.

Parameters:
  • adata – AnnData after spatial_colony_cluster().

  • colony_key – Column with colony IDs (NaN = unassigned).

  • centroid_key – New column for centroid cell labels.

  • centroid_label – Label assigned to centroid cells (e.g. GCC or TNC).

  • spatial_key – Key in adata.obsm for coordinates.

  • copy – If True, return a modified copy instead of updating in place.

Returns:

Copy when copy=True; otherwise None (in-place update).

Return type:

AnnData or None

trackcell.tl.distance_to_nearest_centroids(adata: AnnData, centroid_key: str = 'cell_centroid_type', distance_key: str = 'distance_to_nearest_centroid', centroid_label: str = 'GCC', spatial_key: str = 'spatial', copy: bool = False) → AnnData | None[source]#

Per-cell distance to the nearest marked colony centroid (cKDTree).

Parameters:
  • adata – AnnData after mark_colony_centroids() (full section or subset).

  • centroid_key – Column with centroid labels.

  • distance_key – New obs column for distances (same units as spatial_key coords).

  • centroid_label – Label identifying centroid cells in centroid_key.

  • spatial_key – Key in adata.obsm for coordinates.

  • copy – If True, return a modified copy instead of updating in place.

Returns:

Copy when copy=True; otherwise None (in-place update).

Return type:

AnnData or None

trackcell.tl.slice_cluster_summary(adata: AnnData, slice_key: str = 'slice_id', spatial_key: str = 'spatial', debris_label: str = 'debris') → DataFrame[source]#

Summarize slice assignments with cell counts and spatial extents.

Returns:

One row per slice with n_cells, x/y min/max/span, and center.

Return type:

DataFrame

trackcell.tl.split_by_slice(adata: AnnData, slice_key: str = 'slice_id', exclude: Sequence[str] = ('debris',), copy: bool = True, reindex_boundaries: bool = True) → dict[str, AnnData][source]#

Split an AnnData into one object per slice ID.

Parameters:
  • adata – Annotated AnnData (e.g. after spatial_slice_cluster()).

  • slice_key – Column in adata.obs with slice labels.

  • exclude – Slice labels to skip (default: debris).

  • copy – If True, each slice is a deep copy; if False, views where possible.

  • reindex_boundaries – Rebuild uns['cell_boundaries'] / ['nucleus_boundaries'] for each subset. Both the Xenium layout='offset' and the Atera layout='index' tables are accepted; the subset is written in the offset layout.

Returns:

Mapping slice_id → AnnData subset.

Return type:

dict

trackcell.tl.write_slice_annotation(adata: AnnData, path: str | Path, slice_key: str = 'slice_id', cluster_key: str = 'slice_cluster', spatial_key: str = 'spatial') → Path[source]#

Write slice labels to parquet (CCHD-compatible slice_annotation.parquet).

Columns: cell_id, x_centroid, y_centroid, slice_cluster, slice_id.