Skip to content

Latest commit

 

History

History
620 lines (482 loc) · 25.2 KB

methods-reference.md

File metadata and controls

620 lines (482 loc) · 25.2 KB

Methods Reference

This page is the canonical human-readable reference for ChatSpatial tool names, method names, common defaults, accepted values, and user-facing parameter behavior. MCP clients expose the full schema for method-specific advanced options.

ChatSpatial's public interface is a set of 20 schema-validated MCP tools. Those tools orchestrate 67 spatial transcriptomics methods across 13 analytical categories. In this page, tool means the MCP entry point you or an AI client can call; method means an algorithm or analysis backend selected through a parameter such as method, analysis_type, plot_type, or subtype.


Quick Reference

Category Tools
Data load_data, preprocess_data, compute_embeddings, export_data, reload_data
Spatial analyze_spatial_statistics, find_spatial_genes, identify_spatial_domains
Cells annotate_cell_types, deconvolve_data, analyze_cell_communication
Genes find_markers, compare_conditions, analyze_enrichment
Dynamics analyze_velocity_data, analyze_trajectory_data, analyze_cnv
Multi-sample integrate_samples, register_spatial_data
Output visualize_data

Data Management

load_data

Load spatial transcriptomics data.

Parameter Type Description
data_path str Path to file or folder
data_type str visium, xenium, slide_seq, merfish, seqfish, generic
name str Optional dataset name

Supported formats: H5AD, 10X Visium folders, H5, MTX


preprocess_data

Normalize, filter, and prepare data.

Parameter Default Description
normalization pearson_residuals log, sct, pearson_residuals, scvi, none
n_hvgs 2000 Highly variable genes
filter_genes_min_cells 3 Min cells per gene
filter_cells_min_genes 30 Min genes per cell
filter_mito_pct 20.0 Max mitochondrial %
scale False Scale to unit variance before PCA

Advanced options:

Parameter Default Description
use_scrublet False Enable doublet detection (for single-cell resolution data)
normalize_target_sum None Target counts per cell (None=median, 1e4=Visium, 1e6=MERFISH)
remove_mito_genes True Exclude mito genes from HVG
batch_key batch Batch column for batch-aware normalization

Mitochondrial QC uses a boolean adata.var["mt"] annotation when supplied, including for Ensembl identifiers. Without annotations, gene symbols beginning with MT- or MT. are recognized case-insensitively. Gene identifiers are not renamed. The same annotations govern HVG exclusion and spatial-gene filtering; raw-layer annotations cover genes absent from the active matrix.

If no mitochondrial genes are identified, mitochondrial percentages are unavailable, not zero. Requested mitochondrial filtering is skipped with a warning. The result reports n_mt_genes, mito_annotation_source, mito_qc_available, and mito_filter_applied; unavailable percentage summaries are omitted. Supply a boolean annotation before saving/loading the input H5AD, or disable mitochondrial filtering for panels without mitochondrial genes.

PCA, neighbor, UMAP, and clustering parameters belong to compute_embeddings; preprocess_data does not accept or retain them.

preprocess_data does not compute PCA, UMAP, clustering, or neighbor graphs. Call compute_embeddings explicitly before cluster- or embedding-dependent tools.


compute_embeddings

Compute dimensionality reduction and clustering.

Parameter Default Description
compute_pca True Compute PCA
compute_umap True Compute UMAP
compute_clustering True Leiden clustering
compute_spatial_neighbors True Spatial graph
n_pcs 30 Principal components
clustering_resolution 1.0 Clustering resolution
force False Recompute if exists

export_data / reload_data

Export dataset for external scripts, reload after modifications.

Parameter Default Description
data_id required Dataset ID
path auto Custom path (default: ~/.chatspatial/active/{data_id}.h5ad)

Spatial Analysis

analyze_spatial_statistics

Analyze spatial patterns and autocorrelation.

Parameter Default Description
analysis_type neighborhood See types below
cluster_key None Required for group-based analyses
genes None Specific genes to analyze
n_top_genes 20 Top HVGs to analyze (if genes not specified)
gene_selection hvg hvg (top n_top_genes HVGs) or all (every gene; moran and geary only)
n_neighbors 8 Spatial neighbors

With gene_selection="all", Moran's I or Geary's C is computed for every gene of the expression matrix. The result returns the top genes only; the full per-gene table (I or C, pval_norm, FDR pval_norm_fdr, and rank, 1 = strongest autocorrelation) is stored in adata.uns[results_key] (moranI or gearyC) and exported with the dataset.

Analysis types:

Type Category Requires cluster_key
moran Gene No
local_moran Gene No
geary Gene No
getis_ord Gene No
bivariate_moran Gene No
neighborhood Group Yes
co_occurrence Group Yes
ripley Group Yes
join_count Group Yes
local_join_count Group Yes
centrality Network Yes
network_properties Network Yes
spatial_centrality Network Yes

find_spatial_genes

Identify spatially variable genes.

Parameter Default Description
method flashs sparkx, flashs, spatialde
n_top_genes None Top genes to return (None = all significant)
max_genes_tested None Optional runtime cap applied after filters; keeps the highest-expressed genes for testing
test_only_hvg True Restrict testing to highly variable genes
filter_mt_genes True Exclude mitochondrial genes before testing
filter_ribo_genes False Exclude ribosomal genes before testing

n_top_genes limits the ranked result returned to the caller; max_genes_tested limits the genes supplied to the statistical backend. Use the latter to bound SpatialDE runtime without changing the meaning of the output limit. FlashS is the default Python-native backend and is part of the standard installation; SpatialDE is installed with chatspatial[spatial-genes].


identify_spatial_domains

Find tissue domains and spatial niches.

Parameter Default Description
method spagcn spagcn, stagate, graphst, banksy, aestetik, leiden, louvain
n_domains 7 Expected number of domains
resolution 0.5 Clustering resolution
spagcn_compat spagcn-1.2.7 SpaGCN behavior: spagcn-1.2.7 or modern

SpaGCN runs in spagcn-1.2.7 mode by default and reproduces the labels of the published SpaGCN 1.2.7 implementation, whose cluster centers stay fixed during training. modern trains the centers with the DEC Student's t kernel; the SpaGCN hyperparameters were tuned for 1.2.7, so this mode gives different domains.

SpaGCN, STAGATE, and AESTETIK kmeans/bgm use n_domains. BANKSY and the Leiden/Louvain paths are resolution-driven; adjust banksy_cluster_resolution or resolution instead of expecting an exact domain count. GraphST may use graphst_n_clusters when an explicit count is required. GraphST and STAGATE publish their reusable embeddings as X_graphst and X_stagate in adata.obsm. The legacy Louvain choice is retained for compatibility and falls back to Leiden when the obsolete Louvain extension is unavailable.

AESTETIK fuses a precomputed expression embedding, a precomputed per-spot morphology embedding, and the spatial neighborhood grid. It reads both representations from adata.obsm and does not extract morphology features from tissue images. It also needs discrete lattice coordinates in adata.obs, either x_array/y_array or the Visium array_row/array_col columns.

Parameter Default Description
aestetik_transcriptomics_key X_pca obsm key with the expression embedding
aestetik_morphology_key X_pca_morphology obsm key with the morphology embedding
aestetik_morphology_weight 1.5 Morphology weight in the joint loss
aestetik_window_size 3 Odd side length of the neighborhood grid
aestetik_clustering_method kmeans bgm, kmeans, louvain, leiden. kmeans/bgm use n_domains; leiden/louvain use resolution
aestetik_latent_dim 16 Latent embedding dimension
aestetik_max_epochs 100 Training epochs
aestetik_random_seed 2023 Random seed

Install with pip install 'chatspatial[aestetik]' (Python < 3.14). Method reference: Representation learning for multi-modal spatially resolved transcriptomics data, Bioinformatics (2026).


Cell Analysis

annotate_cell_types

Assign cell types.

Parameter Default Description
method tangram See methods below
reference_data_id None Reference dataset (for transfer methods)
cell_type_key None Cell type column in reference
marker_genes None Label -> marker genes (for CellAssign and marker_score)
cluster_label None Cluster or domain column (for mLLMCellType and marker_score)
sctype_tissue None scType tissue name, required unless custom markers are provided
sctype_db_ None Local scType database path, or remote URL when explicitly allowed
sctype_custom_markers None Custom scType marker sets
sctype_scaled True Whether scType should treat the expression matrix as scaled
sctype_allow_remote False One-off opt-in to load scType remote R scripts and default marker database
sctype_allow_runtime_r_install False One-off opt-in to install missing R packages at runtime

scType remote resources: by default, scType does not load remote R scripts or the remote default marker database. For one-off exploratory runs, pass sctype_allow_remote=true. For production or offline workflows, prefer local R scripts via CHATSPATIAL_SCTYPE_R_DIR and a local sctype_db_ path.

{
  "method": "sctype",
  "sctype_tissue": "Immune system",
  "sctype_allow_remote": true
}

Methods:

Method Requires Reference Notes
tangram Yes Spatial mapping
scanvi Yes Deep learning transfer
cellassign No Marker-based
sctype No Automatic (R)
singler No Reference-based (R)
mllmcelltype No LLM-based
marker_score No Labels groups of cluster_label by marker-gene scores
threshold No Labels observations by a cutoff on a numeric obs column

marker_score: for each label of marker_genes, in the given order, every group of cluster_label is scored by the mean log-normalized expression (log1p of counts scaled to 10,000 per observation) of the label's marker genes present in the data. Absent markers are skipped with a warning; a label with no marker present is an error. The marker_score_n_top (default 2) highest-scoring groups receive the label. With marker_score_exclusion="rank_then_drop" (default) groups already labeled are dropped from that top list, so a label can receive fewer groups; with "drop_then_rank" they are removed before ranking. Other groups receive marker_score_unassigned_label (default Other). The result reports group_labels, group_scores and markers_used, and the score table is stored in adata.uns["<output_key>_group_scores"].

{
  "method": "marker_score",
  "cluster_label": "spatial_domains_leiden",
  "marker_genes": {
    "TC": ["KRT14", "KRT5", "MKI67", "PCNA", "TOP2A"],
    "LE": ["VIM", "FN1", "COL1A1", "COL1A2", "SPARC", "TGFBI"]
  },
  "output_key": "tc_le_region"
}

threshold: labels each observation threshold_pass_label (default pass) when <value> <threshold_comparison> threshold_value holds and threshold_fail_label (default fail) otherwise; observations without a value stay unlabeled. deconvolve_data writes one proportion column per cell type, deconvolution_<method>_<cell type>, which can be thresholded directly.

{
  "method": "threshold",
  "threshold_key": "deconvolution_rctd_Tumor_cells",
  "threshold_value": 0.15,
  "threshold_comparison": ">=",
  "threshold_pass_label": "tumor_enriched",
  "threshold_fail_label": "low_tumor",
  "output_key": "tumor_class"
}

Both methods write their labels to output_key (default cell_type_marker_score or cell_type_threshold).


deconvolve_data

Estimate cell type proportions per spot.

Parameter Default Description
method flashdeconv See methods below
reference_data_id required Reference dataset
cell_type_key required Cell type column in reference

Methods:

Method Speed GPU Notes
flashdeconv Fast No Default, recommended
cell2location Slow Yes High accuracy
rctd Variable Optional R/spacexr by default; CUDA-oriented rctd-py backend
destvi Medium Yes scvi-tools
stereoscope Slow Yes Alternative DL
tangram Medium Yes Spatial mapping
spotlight Fast No R-based
card Fast No R-based, imputation

FlashDeconv uses deterministic gene weighting and automatically scales spatial regularization to the data. Set flashdeconv_lambda_spatial to a non-negative number to choose the strength explicitly (0 disables smoothing). flashdeconv_sketch_dim controls the expected gene weights, not a projected embedding dimension. Results report the backend version, resolved regularization, selected gene count, and solver convergence.

RCTD backend options:

Parameter Default Description
rctd_backend r r for spacexr or python for rctd-py
rctd_mode full full, doublet, or multi
rctd_device auto auto, cpu, or cuda; Python backend only
rctd_batch_size auto Automatic or positive spot batch size; Python backend only
rctd_dtype float64 float64 for parity or float32 to reduce GPU memory; Python backend only
rctd_sigma_override None Fix sigma instead of estimating it; Python backend only
rctd_max_cores 4 Worker limit; R backend only

Install the Python backend with uv pip install 'chatspatial[rctd-python]'. It preserves the main deconvolution_rctd result contract and also stores mode-specific annotations such as rctd_status, rctd_converged, and doublet/multi outputs. The first run downloads an approximately 400 MB likelihood table to ~/.cache/rctd. Use rctd-py primarily on CUDA systems. CPU cold starts can be slower than spacexr because PyTorch compilation fallback and sigma calibration dominate small runs; rctd_sigma_override skips calibration but not compilation startup.


analyze_cell_communication

Analyze ligand-receptor interactions.

Parameter Default Description
method liana liana, fastccc, cellphonedb, cellchat_r
species required human, mouse, zebrafish
cell_type_key required Cell type column
liana_resource consensus LR database (mouseconsensus for mouse)
subset_key None obs column that restricts the analysis to some observations
subset_categories None Values of subset_key to keep (set with subset_key)

subset_key and subset_categories run every method on the selected observations only, for example the tumor-core and leading-edge spots of pooled sections labeled by their dominant deconvolved cell type:

{
  "method": "cellchat_r",
  "species": "human",
  "cell_type_key": "dominant_celltype_flashdeconv",
  "subset_key": "tc_le_region",
  "subset_categories": ["TC", "LE"]
}

LIANA is the portable default and supports human, mouse, and zebrafish. FastCCC and CellPhoneDB currently require human data. Install LIANA and CellPhoneDB with chatspatial[cell-communication], FastCCC with chatspatial[fastccc], or all three through chatspatial[full]. The maintained FastCCC runtime is composable with trajectory; it does not include the unused HTML report layer or depend on Jinja2.


Gene Analysis

find_markers

Find differentially expressed genes.

Parameter Default Description
group_key required Grouping column
group1 None First group (None = each vs rest)
group2 None Second group
method wilcoxon wilcoxon, t-test, t-test_overestim_var, logreg, pydeseq2
n_top_genes 50 Top genes per group
exclude_gene_classes [] Any of immunoglobulin, ribosomal, mitochondrial, hla
exclude_gene_patterns [] Gene-name wildcards removed before testing, e.g. MALAT1

Excluded genes are removed before ranking, so they are never reported as markers; the result reports how many genes each class or pattern removed. The class rules are the same as for analyze_cnv.

Results are grouped per comparison rather than flattened across groups. Each row reports both groups' mean expression alongside the fold change, so effect size can be interpreted in expression context.


compare_conditions

Compare experimental conditions (pseudobulk DESeq2).

Parameter Default Description
condition_key required Condition column
condition1 required Treatment group
condition2 required Control group
sample_key required Sample/patient column
cell_type_key None Stratify by cell type
n_top_genes 50 Top DEGs

analyze_enrichment

Gene set enrichment analysis.

Parameter Default Description
species required human, mouse, zebrafish
method spatial_enrichmap spatial_enrichmap, pathway_gsea, pathway_ora, pathway_enrichr, pathway_ssgsea
gene_set_database GO_Biological_Process See databases below

Databases: GO_Biological_Process, GO_Molecular_Function, GO_Cellular_Component, KEGG_Pathways, Reactome_Pathways, MSigDB_Hallmark, Cell_Type_Markers


Dynamics

analyze_velocity_data

RNA velocity analysis.

Parameter Default Description
method scvelo scvelo, velovi
scvelo_mode stochastic deterministic, stochastic, dynamical

Requires: spliced and unspliced layers


analyze_trajectory_data

Trajectory and pseudotime inference.

Parameter Default Description
method cellrank cellrank, palantir, dpt
root_cells None Starting cells
cellrank_n_states 5 Number of CellRank macrostates
cellrank_stability_threshold 0.96 Minimum stability for a macrostate to count as terminal

Note: CellRank requires velocity data and Python 3.12 or newer. When no state reaches cellrank_stability_threshold, ChatSpatial falls back to macrostate-based pseudotime and returns a warning. Palantir and DPT do not need velocity; if root_cells is omitted, the automatically selected root and any unreachable cells are reported in the tool warnings.


analyze_cnv

Copy number variation detection.

Parameter Default Description
method infercnvpy infercnvpy, numbat
reference_key required Cell type column
reference_categories required Normal cell types
gene_positions auto provided (adata.var), annotate (bundled table), auto (provided if present, else annotate)
species human human (GRCh38) or mouse (GRCm39) table for annotate
exclude_gene_classes [] Any of immunoglobulin, ribosomal, mitochondrial, hla
exclude_gene_patterns [] Gene-name wildcards removed from the CNV input, e.g. IGH*
cluster_cells False Leiden clustering of the CNV profiles
query_categories None Categories of reference_key to cluster; others get no cluster label

Gene positions: infercnvpy needs the chromosome, start and end of every gene. When adata.var lacks them, ChatSpatial annotates them from bundled Ensembl release 110 tables (GRCh38 or GRCm39, chromosomes 1-22/1-19, X and Y; the annotation behind the 10x Genomics 2024-A references). Genes are matched on the Ensembl gene ID when adata.var holds one (gene_ids, gene_id, ensembl_id, ensembl_gene_id, or Ensembl IDs as gene names), and the rest on the gene symbol. The result reports how many genes matched each way, and the positions are written to adata.var.

Gene exclusion: excluded genes are removed from the CNV input only; the dataset keeps them. Class rules match gene names case-insensitively: immunoglobulin covers the V, D, J and constant segments of the IGH, IGK and IGL loci (IG[HKL][VDJC]*, IGH[AGMDE]*, except IGHMBP2), JCHAIN, IGLL1 and IGLL5; ribosomal covers RPL* and RPS* except RPS6K* and RPS19BP1; mitochondrial covers MT-*; hla covers HLA-* and mouse H2-*.

Query clustering: inference always uses every observation with reference_categories as the baseline. With query_categories, only those observations are clustered, so tumor clones are not mixed with the reference.

{
  "reference_key": "tumor_class",
  "reference_categories": ["low_tumor"],
  "exclude_gene_classes": ["immunoglobulin", "ribosomal", "mitochondrial", "hla"],
  "cluster_cells": true,
  "query_categories": ["tumor_enriched"]
}

Multi-Sample

integrate_samples

Batch integration.

Parameter Default Description
data_ids required Two or more distinct dataset IDs
method harmony harmony, bbknn, scanorama, scvi
batch_key batch Batch column
batch_correction True False concatenates the samples without correction

With batch_correction=false, the samples are pooled without batch correction and need not be preprocessed: the pooled dataset keeps the genes present in every sample, their counts in layers["counts"] (from each sample's layers["counts"], else X; adata.raw only when neither holds counts), X = log1p of the counts scaled to 10,000 per observation, every obs column and the spatial coordinates; batch_key holds the source dataset ID. Use it to pool sections for cell communication.


register_spatial_data

Align spatial sections.

Parameter Default Description
source_id required Source dataset; must differ from target_id
target_id required Target dataset; must differ from source_id
method paste paste, stalign

Visualization

visualize_data

Create all plot types.

Parameter Default Description
plot_type feature See types below
subtype None Visualization variant
feature None Gene(s) or column to show
basis spatial spatial, umap
cluster_key None Grouping column
colormap coolwarm Color scheme for continuous values. Categorical features automatically use a qualitative palette such as tab10 or tab20.
dpi 300 Resolution
output_format png png, pdf, svg, eps, tiff, jpg

Plot types and subtypes:

Type Subtypes Use
feature — Gene/metadata on spatial or UMAP
expression heatmap, violin, dotplot, correlation Aggregated expression; heatmaps scale per gene by default
deconvolution spatial_multi, pie, dominant, diversity, umap, imputation Cell proportions
communication dotplot, tileplot, circle_plot LR interactions
interaction — Spatial LR pairs
trajectory pseudotime, circular, fate_map, gene_trends, fate_heatmap, palantir Pseudotime
velocity stream, phase, proportions, heatmap, paga RNA velocity
statistics neighborhood, co_occurrence, ripley, moran, centrality, getis_ord Spatial stats
enrichment barplot, dotplot Pathway results
cnv heatmap, spatial CNV results
integration batch, cluster, highlight Integration QC

GPU Acceleration

GPU acceleration is available for these methods. Most use use_gpu=True; the rctd-py backend instead uses rctd_device="cuda":

Category Methods
Preprocessing scVI normalization
Annotation Tangram, scANVI
Deconvolution Cell2location, DestVI, Stereoscope, Tangram, RCTD (rctd-py backend)
Domains STAGATE, GraphST
Velocity VeloVI
Integration scVI
CNV inferCNVpy