Models

Contents

Models#

High-level model interfaces for spatial transcriptomics analysis.

Core Models#

SpatialVAE#

class spatialvi.model.SpatialVAE(adata, n_hidden=128, n_latent=10, n_layers=1, dropout_rate=0.1, dispersion='gene', gene_likelihood='zinb', latent_distribution='normal', use_spatial=True, spatial_weight=1.0, **model_kwargs)[source]#

Bases: SpatialTrainingMixin, SpatialMixin, BaseSpatialModel

Spatial Variational Autoencoder for spatial transcriptomics.

This model combines gene expression modeling with spatial context using a VAE framework. It can be used for: - Spatially-aware dimensionality reduction - Batch effect correction in spatial data - Imputation with spatial smoothing

Parameters:
  • adata (AnnData) – AnnData object that has been registered via setup_anndata().

  • n_hidden (int) – Number of nodes per hidden layer.

  • n_latent (int) – Dimensionality of the latent space.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate for neural networks.

  • dispersion (Literal['gene', 'gene-batch', 'gene-cell']) – Dispersion parameter for negative binomial. One of: - “gene”: single dispersion per gene - “gene-batch”: dispersion per gene and batch - “gene-cell”: dispersion per gene and cell

  • gene_likelihood (Literal['zinb', 'nb', 'poisson']) – Distribution for gene expression. One of: - “zinb”: Zero-inflated negative binomial - “nb”: Negative binomial - “poisson”: Poisson

  • latent_distribution (Literal['normal', 'ln']) – Distribution for latent space. One of: - “normal”: Normal distribution - “ln”: Logistic normal

  • use_spatial (bool) – Whether to use spatial information in encoding.

  • spatial_weight (float) – Weight for spatial regularization.

  • **model_kwargs – Additional keyword arguments for SpatialVAEModule.

  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • dropout_rate (float)

  • dispersion (Literal['gene', 'gene-batch', 'gene-cell'])

  • gene_likelihood (Literal['zinb', 'nb', 'poisson'])

  • latent_distribution (Literal['normal', 'ln'])

  • use_spatial (bool)

  • spatial_weight (float)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> SpatialVAE.setup_anndata(adata, spatial_key="spatial")
>>> model = SpatialVAE(adata)
>>> model.train()
>>> latent = model.get_latent_representation()
get_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1.0, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None)[source]#

Return normalized gene expression.

Parameters:
  • adata (AnnData | None) – AnnData object with equivalent structure to initial AnnData.

  • indices (Sequence[int] | None) – Indices of cells to use.

  • transform_batch (str | Sequence[str] | None) – Batch to condition on.

  • gene_list (Sequence[str] | None) – Subset of genes to use.

  • library_size (Union[float, Literal['latent']]) – Library size to use for normalization.

  • n_samples (int) – Number of samples to draw from posterior.

  • n_samples_overall (int | None) – Total number of samples across all cells.

  • batch_size (int | None) – Batch size for data loader.

  • return_mean (bool) – Whether to return the mean of samples.

  • return_numpy (bool | None) – Whether to return numpy array.

  • adata (AnnData | None)

  • indices (Sequence[int] | None)

  • transform_batch (str | Sequence[str] | None)

  • gene_list (Sequence[str] | None)

  • library_size (float | Literal['latent'])

  • n_samples (int)

  • n_samples_overall (int | None)

  • batch_size (int | None)

  • return_mean (bool)

  • return_numpy (bool | None)

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | dict[str, ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]]

Returns:

Normalized expression array.

get_spatial_representation(adata=None, indices=None, batch_size=None)[source]#

Get spatial-aware latent representation.

This method returns a latent representation that incorporates spatial context from neighboring cells.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Spatial latent representation array.

classmethod setup_anndata(adata, layer=None, batch_key=None, labels_key=None, size_factor_key=None, categorical_covariate_keys=None, continuous_covariate_keys=None, spatial_key='spatial', neighbor_index_key=None, neighbor_dist_key=None, **kwargs)[source]#

Sets up the AnnData object for this model.

A mapping will be created between data fields used by this model to their respective locations in adata. None of the data in adata are modified. Only adds fields to adata.

Parameters:
  • adata (AnnData) – AnnData object. Rows represent cells, columns represent features.

  • layer (str | None) – if not None, uses this as the key in adata.layers for raw count data.

  • batch_key (str | None) – key in adata.obs for batch information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_batch']. If None, assigns the same batch to all the data.

  • labels_key (str | None) – key in adata.obs for label information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_labels']. If None, assigns the same label to all the data.

  • size_factor_key (str | None) – key in adata.obs for size factor information. Instead of using library size as a size factor, the provided size factor column will be used as offset in the mean of the likelihood. Assumed to be on linear scale.

  • categorical_covariate_keys (list[str] | None) – keys in adata.obs that correspond to categorical data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do _not_ want to correct for.

  • continuous_covariate_keys (list[str] | None) – keys in adata.obs that correspond to continuous data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do _not_ want to correct for.

  • spatial_key (str) – Key in adata.obsm for spatial coordinates.

  • neighbor_index_key (str | None) – Key in adata.obsm for neighbor indices. If None, neighbors will not be used during training.

  • neighbor_dist_key (str | None) – Key in adata.obsm for neighbor distances.

  • adata (AnnData)

  • layer (str | None)

  • batch_key (str | None)

  • labels_key (str | None)

  • size_factor_key (str | None)

  • categorical_covariate_keys (list[str] | None)

  • continuous_covariate_keys (list[str] | None)

  • spatial_key (str)

  • neighbor_index_key (str | None)

  • neighbor_dist_key (str | None)

Return type:

None

External Models#

AMICI#

class spatialvi.external.amici.AMICI(adata, n_hidden=128, n_latent=10, n_layers=2, n_attention_heads=4, dropout_rate=0.1, gene_likelihood='nb', use_cell_type_attention=True, interaction_layers=2, **model_kwargs)[source]#

Bases: SpatialTrainingMixin, SpatialMixin, BaseSpatialModel

AMICI model for cell-cell interaction inference.

AMICI (Attention-based Multi-scale Interaction for Cell-cell Inference) uses cross-attention mechanisms to model how neighboring cells influence gene expression through cell-cell interactions.

Parameters:
  • adata (AnnData) – AnnData object that has been registered via setup_anndata().

  • n_hidden (int) – Number of nodes per hidden layer.

  • n_latent (int) – Dimensionality of the latent space.

  • n_layers (int) – Number of hidden layers.

  • n_attention_heads (int) – Number of attention heads for cross-attention.

  • dropout_rate (float) – Dropout rate for neural networks.

  • gene_likelihood (Literal['zinb', 'nb', 'poisson']) – Distribution for gene expression.

  • use_cell_type_attention (bool) – Whether to use cell type-specific attention.

  • interaction_layers (int) – Number of interaction modeling layers.

  • **model_kwargs – Additional keyword arguments for AMICIModule.

  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • n_attention_heads (int)

  • dropout_rate (float)

  • gene_likelihood (Literal['zinb', 'nb', 'poisson'])

  • use_cell_type_attention (bool)

  • interaction_layers (int)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> AMICI.setup_anndata(
...     adata,
...     spatial_key="spatial",
...     labels_key="cell_type",
... )
>>> model = AMICI(adata)
>>> model.train()
>>> interactions = model.get_interaction_scores()
get_interaction_scores(adata=None, indices=None, batch_size=None, return_attention_weights=False)[source]#

Get cell-cell interaction scores.

Parameters:
  • adata (AnnData | None) – AnnData object.

  • indices (Sequence[int] | None) – Indices of cells to use.

  • batch_size (int | None) – Batch size for data loader.

  • return_attention_weights (bool) – Whether to return raw attention weights.

  • adata (AnnData | None)

  • indices (Sequence[int] | None)

  • batch_size (int | None)

  • return_attention_weights (bool)

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | tuple[ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]], ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]]

Returns:

  • Interaction scores array. If return_attention_weights is True,

  • also returns attention weight matrices.

get_cell_type_interactions(adata=None, aggregate='mean')[source]#

Get aggregated cell type interaction matrix.

Parameters:
  • adata (AnnData | None) – AnnData object.

  • aggregate (Literal['mean', 'sum', 'max']) – Aggregation method for interaction scores.

  • adata (AnnData | None)

  • aggregate (Literal['mean', 'sum', 'max'])

Return type:

DataFrame

Returns:

DataFrame of cell type x cell type interaction strengths.

get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#

Return the latent representation for each cell.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Latent representation array.

get_normalized_expression(adata=None, indices=None, **kwargs)[source]#

Return normalized gene expression.

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Parameters:
classmethod setup_anndata(adata, layer=None, batch_key=None, labels_key=None, spatial_key='spatial', neighbor_index_key='nn_index', neighbor_dist_key='nn_dist', **kwargs)[source]#

Sets up the AnnData object for this model.

A mapping will be created between data fields used by this model to their respective locations in adata. None of the data in adata are modified. Only adds fields to adata.

Parameters:
  • adata (AnnData) – AnnData object. Rows represent cells, columns represent features.

  • layer (str | None) – if not None, uses this as the key in adata.layers for raw count data.

  • batch_key (str | None) – key in adata.obs for batch information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_batch']. If None, assigns the same batch to all the data.

  • labels_key (str | None) – key in adata.obs for label information. Categories will automatically be converted into integer categories and saved to adata.obs['_scvi_labels']. If None, assigns the same label to all the data.

  • spatial_key (str) – Key in adata.obsm for spatial coordinates.

  • neighbor_index_key (str | None) – Key in adata.obsm for neighbor indices.

  • neighbor_dist_key (str | None) – Key in adata.obsm for neighbor distances.

  • adata (AnnData)

  • layer (str | None)

  • batch_key (str | None)

  • labels_key (str | None)

  • spatial_key (str)

  • neighbor_index_key (str | None)

  • neighbor_dist_key (str | None)

Return type:

None

DestVI#

class spatialvi.external.destvi.DestVI(st_adata, sc_model, **kwargs)[source]#

Bases: object

Wrapper for scvi-tools DestVI model.

DestVI performs multi-resolution spatial deconvolution, estimating both cell type proportions and continuous sub-cell-type variation within spatial transcriptomics spots.

This is a thin wrapper around the scvi-tools implementation that provides a consistent interface with spatialvi-tools.

Parameters:
  • st_adata (AnnData) – Spatial transcriptomics AnnData.

  • sc_model – Trained CondSCVI model on reference single-cell data.

  • **kwargs – Additional keyword arguments for scvi.model.DestVI.

  • st_adata (AnnData)

Examples

>>> import spatialvi
>>> # First train CondSCVI on reference
>>> sc_adata = spatialvi.data.synthetic_scrna()
>>> DestVI.setup_anndata(sc_adata, labels_key="cell_type")
>>> sc_model = spatialvi.external.CondSCVI(sc_adata)
>>> sc_model.train()
>>> # Then train DestVI on spatial
>>> st_adata = spatialvi.data.synthetic_spatial()
>>> model = DestVI.from_rna_model(st_adata, sc_model)
>>> model.train()
>>> proportions = model.get_proportions()
classmethod setup_anndata(adata, layer=None, labels_key=None, **kwargs)[source]#

Setup AnnData for DestVI (reference single-cell data).

Parameters:
  • adata (AnnData) – AnnData object (single-cell reference).

  • layer (str | None) – Layer to use for expression data.

  • labels_key (str | None) – Key for cell type labels in obs.

  • **kwargs – Additional keyword arguments.

  • adata (AnnData)

  • layer (str | None)

  • labels_key (str | None)

Return type:

None

classmethod from_rna_model(st_adata, sc_model, **kwargs)[source]#

Create DestVI from a trained CondSCVI model.

Parameters:
  • st_adata (AnnData) – Spatial transcriptomics AnnData.

  • sc_model – Trained CondSCVI model.

  • **kwargs – Additional keyword arguments.

  • st_adata (AnnData)

Return type:

DestVI

Returns:

DestVI model instance.

train(max_epochs=2500, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#

Train the model.

Parameters:
  • max_epochs (int) – Maximum number of epochs.

  • lr (float) – Learning rate.

  • accelerator (str) – Accelerator to use.

  • devices (int | str) – Devices to use.

  • **kwargs – Additional keyword arguments for training.

  • max_epochs (int)

  • lr (float)

  • accelerator (str)

  • devices (int | str)

Return type:

None

get_proportions(adata=None, indices=None, batch_size=None, return_dataframe=True)[source]#

Get estimated cell type proportions.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | DataFrame

Returns:

Cell type proportions.

get_gamma(adata=None, indices=None, batch_size=None)[source]#

Get sub-cell-type variation (gamma) per cell type.

Parameters:
Return type:

dict[str, ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]]

Returns:

Dictionary mapping cell types to gamma arrays.

get_scale_for_ct(cell_type, adata=None, indices=None, batch_size=None)[source]#

Get cell type-specific expression scale.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Expression scale array for the cell type.

get_latent_representation(adata=None, indices=None, batch_size=None)[source]#

Get latent representation.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Latent representation array.

save(dir_path, **kwargs)[source]#

Save model to disk.

Return type:

None

Parameters:

dir_path (str)

classmethod load(dir_path, adata=None, **kwargs)[source]#

Load model from disk.

Return type:

DestVI

Parameters:

Harreman#

class spatialvi.external.harreman.Harreman(adata, metabolic_genes=None, spatial_key='spatial', labels_key=None, n_neighbors=20)[source]#

Bases: object

Harreman model for metabolic exchange inference.

Harreman infers metabolic exchange between spatially proximal cells by analyzing correlations between metabolic gene expression and spatial proximity patterns.

Parameters:
  • adata (AnnData) – AnnData object with spatial transcriptomics data.

  • metabolic_genes (Sequence[str] | None) – List of metabolic genes to analyze. If None, uses a default set of metabolic pathway genes.

  • spatial_key (str) – Key in obsm for spatial coordinates.

  • labels_key (str | None) – Key in obs for cell type labels.

  • n_neighbors (int) – Number of spatial neighbors to consider.

  • adata (AnnData)

  • metabolic_genes (Sequence[str] | None)

  • spatial_key (str)

  • labels_key (str | None)

  • n_neighbors (int)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> model = Harreman(adata, labels_key="cell_type")
>>> model.fit()
>>> exchanges = model.get_metabolic_exchanges()
fit(n_permutations=100, correlation_method='spearman')[source]#

Fit the Harreman model.

Parameters:
  • n_permutations (int) – Number of permutations for null distribution.

  • correlation_method (Literal['pearson', 'spearman']) – Correlation method to use.

  • n_permutations (int)

  • correlation_method (Literal['pearson', 'spearman'])

Return type:

Harreman

Returns:

Self.

get_metabolic_exchanges(fdr_threshold=0.05)[source]#

Get significant metabolic exchange genes.

Parameters:
  • fdr_threshold (float) – FDR threshold for significance.

  • fdr_threshold (float)

Return type:

DataFrame

Returns:

DataFrame with exchange scores and statistics.

get_cell_type_exchanges(min_cells=10)[source]#

Get metabolic exchanges between cell types.

Parameters:
  • min_cells (int) – Minimum cells per cell type.

  • min_cells (int)

Return type:

DataFrame

Returns:

DataFrame with cell type pair exchanges.

to_adata()[source]#

Store results in AnnData object.

Return type:

None

Lambda#

class spatialvi.external.lambda_model.Lambda(adata, location=None, organism=None, provider='openai', num_parallel=10, n_top_genes=50, resolution=0.5, **kwargs)[source]#

Bases: object

Language-model based cell type annotation.

LAMBDA uses large language models to automatically annotate cell clusters based on differentially expressed marker genes.

Parameters:
  • adata (AnnData) – AnnData with log-normalised expression data; gene symbols must be present in adata.var.index.

  • location (str | None) – Optional text describing the anatomical location of the sample (e.g. “cerebral cortex”). Passed to the LLM to guide annotation.

  • organism (str | None) – Optional species name (e.g. “human” or “mouse”). Passed to the LLM.

  • provider (str) – Backend used for the language model. Possible values include “openai” and “google”. Ensure that the corresponding API key is set in the environment.

  • num_parallel (int) – Number of clusters to annotate concurrently.

  • n_top_genes (int) – Number of differentially expressed genes used for annotation.

  • resolution (float) – Resolution parameter for Leiden clustering when LAMBDA performs automatic clustering.

  • **kwargs (Any) – Additional arguments passed directly to Agent.

  • adata (AnnData)

  • location (str | None)

  • organism (str | None)

  • provider (str)

  • num_parallel (int)

  • n_top_genes (int)

  • resolution (float)

  • kwargs (Any)

Examples

>>> import scanpy as sc
>>> from spatialvi.external import Lambda
>>> adata = sc.read("data.h5ad")
>>> model = Lambda(adata, organism="human", location="brain")
>>> model.train()  # Prepares the agent
>>> adata = model.predict()  # Annotates clusters
>>> print(adata.obs["lambda_0"].value_counts())
train(*args, **kwargs)[source]#

Prepare the LAMBDA agent.

LAMBDA does not have a trainable model in the usual sense. This method instantiates an Agent and stores it for subsequent predictions.

Return type:

None

Parameters:
predict(group_key='leiden', groups=None, key_is_hierarchical=False, level=0, store_key_prefix='lambda', **kwargs)[source]#

Annotate clusters of the dataset with cell type names.

Parameters:
  • group_key (str | Iterable[str] | None) – Key(s) in adata.obs defining the clusters to annotate. If None, the agent will perform its own clustering. If a sequence of strings is provided, it encodes a hierarchy of levels.

  • groups (str | Iterable[str] | None) – Subset of groups to annotate. None means annotate all groups.

  • key_is_hierarchical (bool) – Whether group_key encodes a hierarchy.

  • level (int) – If a hierarchy is present, index of the level to return results for.

  • store_key_prefix (str) – Prefix under which to store the annotations in adata.obs. Two columns will be created: f"{store_key_prefix}_{level}" for the raw label and f"{store_key_prefix}_score_{level}" for the confidence score.

  • **kwargs (Any) – Additional keyword arguments forwarded to Agent.annotate.

  • group_key (str | Iterable[str] | None)

  • groups (str | Iterable[str] | None)

  • key_is_hierarchical (bool)

  • level (int)

  • store_key_prefix (str)

  • kwargs (Any)

Return type:

AnnData

Returns:

The input AnnData with annotation columns added to obs.

get_annotations(level=0)[source]#

Get the annotation results for a specific level.

Parameters:
  • level (int) – The hierarchical level to retrieve.

  • level (int)

Return type:

dict[str, Any]

Returns:

Dictionary containing annotation results.

Nolan#

class spatialvi.external.nolan.Nolan(adata, emb_key='X_scVI', spatial_key='spatial', batch_key=None, num_niches=50, **model_kwargs)[source]#

Bases: object

High-level interface to the NOLAN spatial niche model.

NOLAN (NO Label ANalysis) uses self-supervised learning to identify spatial niches without requiring cell type annotations.

Parameters:
  • adata (AnnData) – AnnData object containing spatial transcriptomic data. It must have a low-dimensional embedding in obsm[emb_key] and spatial coordinates in obsm[spatial_key].

  • emb_key (str) – Key in adata.obsm pointing to a cell embedding. Defaults to "X_scVI".

  • spatial_key (str) – Key in adata.obsm with spatial coordinates. Defaults to "spatial".

  • batch_key (str | None) – Optional key in adata.obs specifying slide or batch identifiers. If provided, NOLAN will compute a grid size per batch.

  • num_niches (int) – Dimensionality of the niche representation (i.e. number of niches).

  • **model_kwargs (Any) – Additional keyword arguments forwarded to nolan.tl.NOLAN.

  • adata (AnnData)

  • emb_key (str)

  • spatial_key (str)

  • batch_key (str | None)

  • num_niches (int)

  • model_kwargs (Any)

Notes

NOLAN is distributed separately from spatialvi-tools. To use this wrapper you must install the nolan package (e.g. via pip install nolan). If the dependency is missing, the constructor will still succeed but calls to train() and predict() will raise ImportError.

Examples

>>> import scanpy as sc
>>> from spatialvi.external import Nolan
>>> adata = sc.read("spatial_data.h5ad")
>>> # Ensure embeddings exist
>>> assert "X_scVI" in adata.obsm
>>> model = Nolan(adata, num_niches=20)
>>> model.train(num_epochs=50)
>>> adata = model.predict()
train(ckpt_dir=None, num_epochs=10, **train_kwargs)[source]#

Fit the NOLAN model to the stored AnnData.

Parameters:
  • ckpt_dir (str | None) – Directory in which model checkpoints will be stored. If None, checkpoints are not saved.

  • num_epochs (int) – Number of training epochs.

  • **train_kwargs (Any) – Additional keyword arguments forwarded to the training method.

  • ckpt_dir (str | None)

  • num_epochs (int)

  • train_kwargs (Any)

Return type:

None

Notes

This method delegates to nolan.tl.NOLAN and nolan.tl.NOLAN.fit. Internally it computes a global crop radius and number of cells in global crops using nolan.pp.find_grid_size.

predict(adata=None, batch_size=2048, store_key='X_nolan', **kwargs)[source]#

Generate niche embeddings for the given AnnData.

Parameters:
  • adata (AnnData | None) – The AnnData on which to perform prediction. If None, the training AnnData is used.

  • batch_size (int) – Batch size used during prediction.

  • store_key (str) – Name under which to store the embeddings in adata.obsm.

  • **kwargs (Any) – Additional keyword arguments forwarded to nolan.tl.NOLAN.predict.

  • adata (AnnData | None)

  • batch_size (int)

  • store_key (str)

  • kwargs (Any)

Return type:

AnnData

Returns:

  • AnnData with a new obsm[store_key] containing the predicted

  • niche embeddings.

get_niche_assignments(adata=None, n_clusters=None, resolution=1.0, store_key='niche_cluster')[source]#

Cluster cells into discrete niches based on NOLAN embeddings.

Parameters:
  • adata (AnnData | None) – AnnData object. If None, uses the training data.

  • n_clusters (int | None) – Number of clusters. If None, uses Leiden clustering.

  • resolution (float) – Resolution parameter for Leiden clustering.

  • store_key (str) – Key to store cluster assignments in obs.

  • adata (AnnData | None)

  • n_clusters (int | None)

  • resolution (float)

  • store_key (str)

Return type:

AnnData

Returns:

AnnData with niche cluster assignments in obs[store_key].

PPIInference#

class spatialvi.external.ppi.PPIInference[source]#

Bases: object

Static methods for prediction-powered inference.

This class does not derive from the spatial model base because PPI operates on numerical arrays rather than AnnData objects. It exposes simple wrappers around commonly used estimands in the ppi_py package, raising informative errors if the package is not installed.

Examples

>>> import numpy as np
>>> from spatialvi.external import PPIInference
>>> # Small labeled sample
>>> y_labeled = np.array([1.2, 0.8, 1.1, 0.9, 1.0])
>>> yhat_labeled = np.array([1.1, 0.9, 1.0, 0.85, 1.05])
>>> # Large unlabeled sample with predictions
>>> yhat_unlabeled = np.random.normal(1.0, 0.2, 1000)
>>> # Compute confidence interval for mean
>>> ci = PPIInference.mean_ci(y_labeled, yhat_labeled, yhat_unlabeled)
>>> print(f"95% CI for mean: [{ci[0]:.3f}, {ci[1]:.3f}]")
static mean_ci(y, yhat, yhat_unlabeled, alpha=0.1)[source]#

Compute a prediction-powered confidence interval for the mean.

Parameters:
Return type:

tuple[float, float]

Returns:

ci_low, ci_high – Lower and upper bounds of the confidence interval.

static mean_pointestimate(y, yhat, yhat_unlabeled)[source]#

Compute a prediction-powered point estimate for the mean.

Parameters:
Return type:

float

Returns:

estimate – The estimated mean of the outcome variable.

static ols_ci(X, y, yhat, X_unlabeled, yhat_unlabeled, alpha=0.1)[source]#

Compute prediction-powered CI for OLS regression coefficients.

Parameters:
Return type:

tuple[ndarray, ndarray]

Returns:

ci_low, ci_high – Lower and upper bounds for each regression coefficient.

static ols_pointestimate(X, y, yhat, X_unlabeled, yhat_unlabeled)[source]#

Compute prediction-powered point estimates for OLS coefficients.

Parameters:
Return type:

ndarray

Returns:

coefficients – Point estimates for each regression coefficient.

static classical_mean_ci(y, alpha=0.1)[source]#

Compute classical confidence interval for the mean (no predictions).

This is a utility method for comparison with PPI intervals.

Parameters:
Return type:

tuple[float, float]

Returns:

ci_low, ci_high – Lower and upper bounds of the confidence interval.

ResolVI#

class spatialvi.external.resolvi.ResolVI(adata, n_hidden=128, n_latent=10, n_layers=1, dropout_rate=0.1, **kwargs)[source]#

Bases: object

Wrapper for scvi-tools ResolVI model.

ResolVI denoises cellular-resolved spatial transcriptomics data by modeling background contamination and segmentation errors. Suitable for Xenium, MERFISH, CosMx, and similar technologies.

This is a thin wrapper around the scvi-tools implementation that provides a consistent interface with spatialvi-tools.

Parameters:
  • adata (AnnData) – AnnData object that has been registered via setup_anndata().

  • n_hidden (int) – Number of nodes per hidden layer.

  • n_latent (int) – Dimensionality of the latent space.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate for neural networks.

  • **kwargs – Additional keyword arguments for scvi.external.RESOLVI.

  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • dropout_rate (float)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.load_xenium()
>>> ResolVI.setup_anndata(adata, spatial_key="spatial")
>>> model = ResolVI(adata)
>>> model.train()
>>> denoised = model.get_denoised_expression()
classmethod setup_anndata(adata, layer=None, batch_key=None, labels_key=None, spatial_key='spatial', **kwargs)[source]#

Setup AnnData for ResolVI.

Parameters:
  • adata (AnnData) – AnnData object.

  • layer (str | None) – Layer to use for expression data.

  • batch_key (str | None) – Key for batch information in obs.

  • labels_key (str | None) – Key for cell type labels in obs.

  • spatial_key (str) – Key for spatial coordinates in obsm.

  • **kwargs – Additional keyword arguments.

  • adata (AnnData)

  • layer (str | None)

  • batch_key (str | None)

  • labels_key (str | None)

  • spatial_key (str)

Return type:

None

train(max_epochs=400, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#

Train the model.

Parameters:
  • max_epochs (int) – Maximum number of epochs.

  • lr (float) – Learning rate.

  • accelerator (str) – Accelerator to use.

  • devices (int | str) – Devices to use.

  • **kwargs – Additional keyword arguments for training.

  • max_epochs (int)

  • lr (float)

  • accelerator (str)

  • devices (int | str)

Return type:

None

get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#

Get latent representation.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Latent representation array.

get_denoised_expression(adata=None, indices=None, n_samples=1, batch_size=None)[source]#

Get denoised expression.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Denoised expression array.

get_background_fraction(adata=None, indices=None, batch_size=None)[source]#

Get estimated background fraction per cell.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Background fraction array.

predict(adata=None, indices=None, batch_size=None)[source]#

Predict cell types.

Parameters:
Return type:

DataFrame

Returns:

DataFrame with predictions.

save(dir_path, **kwargs)[source]#

Save model to disk.

Return type:

None

Parameters:

dir_path (str)

classmethod load(dir_path, adata=None, **kwargs)[source]#

Load model from disk.

Return type:

ResolVI

Parameters:

scVIVA#

class spatialvi.external.scviva.scVIVA(adata, n_hidden=128, n_latent=10, n_layers=1, dropout_rate=0.1, **kwargs)[source]#

Bases: object

Wrapper for scvi-tools scVIVA model.

scVIVA models cellular microenvironments by learning niche-aware representations that capture both cell-intrinsic and neighborhood-specific factors.

This is a thin wrapper around the scvi-tools implementation that provides a consistent interface with spatialvi-tools.

Parameters:
  • adata (AnnData) – AnnData object that has been registered via setup_anndata().

  • n_hidden (int) – Number of nodes per hidden layer.

  • n_latent (int) – Dimensionality of the latent space.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate for neural networks.

  • **kwargs – Additional keyword arguments for scvi.external.SCVIVA.

  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • dropout_rate (float)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> scVIVA.setup_anndata(adata, spatial_key="spatial")
>>> model = scVIVA(adata)
>>> model.train()
>>> niche_effects = model.get_niche_effects()
classmethod setup_anndata(adata, layer=None, batch_key=None, labels_key=None, spatial_key='spatial', **kwargs)[source]#

Setup AnnData for scVIVA.

Parameters:
  • adata (AnnData) – AnnData object.

  • layer (str | None) – Layer to use for expression data.

  • batch_key (str | None) – Key for batch information in obs.

  • labels_key (str | None) – Key for cell type labels in obs.

  • spatial_key (str) – Key for spatial coordinates in obsm.

  • **kwargs – Additional keyword arguments.

  • adata (AnnData)

  • layer (str | None)

  • batch_key (str | None)

  • labels_key (str | None)

  • spatial_key (str)

Return type:

None

train(max_epochs=400, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#

Train the model.

Parameters:
  • max_epochs (int) – Maximum number of epochs.

  • lr (float) – Learning rate.

  • accelerator (str) – Accelerator to use.

  • devices (int | str) – Devices to use.

  • **kwargs – Additional keyword arguments for training.

  • max_epochs (int)

  • lr (float)

  • accelerator (str)

  • devices (int | str)

Return type:

None

get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#

Get latent representation.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Latent representation array.

get_niche_effects(adata=None, indices=None, batch_size=None)[source]#

Get niche effects for each cell.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Niche effects array.

differential_niche_expression(groupby, group1, group2=None, **kwargs)[source]#

Perform niche-aware differential expression.

Parameters:
Return type:

DataFrame

Returns:

DataFrame with DE results.

save(dir_path, **kwargs)[source]#

Save model to disk.

Return type:

None

Parameters:

dir_path (str)

classmethod load(dir_path, adata=None, **kwargs)[source]#

Load model from disk.

Return type:

scVIVA

Parameters:

SPARL#

class spatialvi.external.sparl.SPARL(adata, spatial_key='spatial', layer=None, n_latent=32, **model_params)[source]#

Bases: object

Interface to the SPARL representation learning model.

SPARL learns spatial-aware representations of protein expression data from spatial proteomics technologies.

Parameters:
  • adata (AnnData) – AnnData object containing spatial proteomics data. The main expression matrix (X or a layer) should contain protein measurements. Spatial coordinates should be in obsm.

  • spatial_key (str) – Key in adata.obsm for spatial coordinates.

  • layer (str | None) – Layer in adata.layers to use. If None, uses adata.X.

  • n_latent (int) – Dimensionality of the latent space.

  • **model_params (Any) – Additional parameters passed to the SPARL model.

  • adata (AnnData)

  • spatial_key (str)

  • layer (str | None)

  • n_latent (int)

  • model_params (Any)

Notes

SPARL is distributed separately from spatialvi-tools. To use this wrapper you must install the sparl package.

Examples

>>> from spatialvi.external import SPARL
>>> # Load CODEX data
>>> adata = sc.read("codex_data.h5ad")
>>> model = SPARL(adata, n_latent=20)
>>> model.train(max_epochs=100)
>>> # Get latent representation
>>> adata.obsm["X_sparl"] = model.get_latent_representation()
train(max_epochs=100, batch_size=128, lr=0.001, **train_kwargs)[source]#

Train the SPARL model.

Parameters:
  • max_epochs (int) – Maximum number of training epochs.

  • batch_size (int) – Batch size for training.

  • lr (float) – Learning rate.

  • **train_kwargs (Any) – Additional keyword arguments for training.

  • max_epochs (int)

  • batch_size (int)

  • lr (float)

  • train_kwargs (Any)

Return type:

None

Notes

Currently this wrapper provides a placeholder implementation. Full training functionality will be added when the SPARL API stabilizes.

get_latent_representation(adata=None, batch_size=256)[source]#

Get latent representations for cells.

Parameters:
  • adata (AnnData | None) – AnnData object. If None, uses the training data.

  • batch_size (int) – Batch size for inference.

  • adata (AnnData | None)

  • batch_size (int)

Return type:

ndarray

Returns:

Latent representation array of shape (n_cells, n_latent).

predict(adata=None, store_key='X_sparl')[source]#

Compute and store latent representations.

Parameters:
  • adata (AnnData | None) – AnnData object. If None, uses the training data.

  • store_key (str) – Key to store latent representation in obsm.

  • adata (AnnData | None)

  • store_key (str)

Return type:

AnnData

Returns:

AnnData with latent representation stored in obsm.

reconstruct(adata=None, batch_size=256)[source]#

Reconstruct protein expression from latent space.

Parameters:
  • adata (AnnData | None) – AnnData object. If None, uses the training data.

  • batch_size (int) – Batch size for inference.

  • adata (AnnData | None)

  • batch_size (int)

Return type:

ndarray

Returns:

Reconstructed expression array of shape (n_cells, n_proteins).

impute_proteins(adata=None, store_layer='sparl_imputed')[source]#

Impute missing protein values using the trained model.

Parameters:
  • adata (AnnData | None) – AnnData object. If None, uses the training data.

  • store_layer (str) – Key to store imputed expression in layers.

  • adata (AnnData | None)

  • store_layer (str)

Return type:

AnnData

Returns:

AnnData with imputed expression stored in layers.

Starfysh#

class spatialvi.external.starfysh.Starfysh(adata_spatial, adata_ref, cell_type_key, spatial_key='spatial', n_factors=5, n_hidden=128, use_histology=False)[source]#

Bases: object

Starfysh model for spatial deconvolution with histology.

Starfysh deconvolves spatial transcriptomics spots into cell type proportions using reference single-cell data. It can optionally integrate histology images for improved accuracy.

Parameters:
  • adata_spatial (AnnData) – Spatial transcriptomics AnnData.

  • adata_ref (AnnData) – Reference single-cell AnnData with cell type annotations.

  • cell_type_key (str) – Key in adata_ref.obs for cell type labels.

  • spatial_key (str) – Key in adata_spatial.obsm for spatial coordinates.

  • n_factors (int) – Number of archetypal factors per cell type.

  • n_hidden (int) – Number of hidden units.

  • use_histology (bool) – Whether to integrate histology features.

  • adata_spatial (AnnData)

  • adata_ref (AnnData)

  • cell_type_key (str)

  • spatial_key (str)

  • n_factors (int)

  • n_hidden (int)

  • use_histology (bool)

Examples

>>> import spatialvi
>>> adata_sp = spatialvi.data.synthetic_spatial()
>>> adata_sc = spatialvi.data.synthetic_scrna()
>>> model = Starfysh(adata_sp, adata_sc, cell_type_key="cell_type")
>>> model.fit()
>>> proportions = model.get_proportions()
fit(max_epochs=500, lr=0.001, batch_size=256, early_stopping=True, patience=20, device='auto')[source]#

Fit the Starfysh model.

Parameters:
  • max_epochs (int) – Maximum number of training epochs.

  • lr (float) – Learning rate.

  • batch_size (int) – Batch size for training.

  • early_stopping (bool) – Whether to use early stopping.

  • patience (int) – Patience for early stopping.

  • device (str) – Device to use (“auto”, “cpu”, “cuda”).

  • max_epochs (int)

  • lr (float)

  • batch_size (int)

  • early_stopping (bool)

  • patience (int)

  • device (str)

Return type:

Starfysh

Returns:

Self.

get_proportions(return_dataframe=True)[source]#

Get estimated cell type proportions.

Parameters:
  • return_dataframe (bool) – Whether to return as DataFrame.

  • return_dataframe (bool)

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | DataFrame

Returns:

Cell type proportions.

get_reconstruction()[source]#

Get reconstructed expression.

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Reconstructed expression array.

to_adata()[source]#

Store results in spatial AnnData.

Adds proportions to adata_spatial.obsm[“starfysh_proportions”].

Return type:

None

VIVS#

class spatialvi.external.vivs.VIVS(adata, spatial_key='spatial', layer=None, n_neighbors=20, n_scales=5)[source]#

Bases: object

VIVS model for identifying spatially variable genes.

VIVS (Variable Importance via Variance Statistics) identifies genes with significant spatial patterns by comparing observed and expected variance under different spatial scales.

Parameters:
  • adata (AnnData) – AnnData object with spatial transcriptomics data.

  • spatial_key (str) – Key in obsm for spatial coordinates.

  • layer (str | None) – Layer in adata to use. If None, uses X.

  • n_neighbors (int) – Number of spatial neighbors to consider.

  • n_scales (int) – Number of spatial scales to analyze.

  • adata (AnnData)

  • spatial_key (str)

  • layer (str | None)

  • n_neighbors (int)

  • n_scales (int)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> model = VIVS(adata, spatial_key="spatial")
>>> model.fit()
>>> svg = model.get_spatially_variable_genes()
fit(n_permutations=100, batch_size=100, use_gpu=False)[source]#

Fit the VIVS model.

Parameters:
  • n_permutations (int) – Number of permutations for null distribution.

  • batch_size (int) – Batch size for processing genes.

  • use_gpu (bool) – Whether to use GPU acceleration.

  • n_permutations (int)

  • batch_size (int)

  • use_gpu (bool)

Return type:

VIVS

Returns:

Self.

get_spatially_variable_genes(n_top=None, fdr_threshold=0.05)[source]#

Get spatially variable genes.

Parameters:
  • n_top (int | None) – Number of top genes to return. If None, returns all genes below FDR threshold.

  • fdr_threshold (float) – FDR threshold for significance.

  • n_top (int | None)

  • fdr_threshold (float)

Return type:

DataFrame

Returns:

DataFrame with gene names, importance scores, and p-values.

get_scale_contributions(gene_names=None)[source]#

Get contribution of each scale to gene importance.

Parameters:
Return type:

DataFrame

Returns:

DataFrame with scale contributions per gene.

to_adata()[source]#

Store results in AnnData object.

Adds the following to adata.var: - ‘vivs_importance’: Importance scores - ‘vivs_pvalue’: P-values - ‘vivs_fdr’: FDR-adjusted p-values

Return type:

None