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,BaseSpatialModelSpatial 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 viasetup_anndata().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 cellgene_likelihood¶ (
Literal['zinb','nb','poisson']) – Distribution for gene expression. One of: - “zinb”: Zero-inflated negative binomial - “nb”: Negative binomial - “poisson”: Poissonlatent_distribution¶ (
Literal['normal','ln']) – Distribution for latent space. One of: - “normal”: Normal distribution - “ln”: Logistic normaluse_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.transform_batch¶ (
str|Sequence[str] |None) – Batch to condition on.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.return_mean¶ (
bool) – Whether to return the mean of samples.return_numpy¶ (
bool|None) – Whether to return numpy array.adata (AnnData | None)
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.
- 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
AnnDataobject 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 notNone, uses this as the key inadata.layersfor raw count data.batch_key¶ (
str|None) – key inadata.obsfor batch information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_batch']. IfNone, assigns the same batch to all the data.labels_key¶ (
str|None) – key inadata.obsfor label information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_labels']. IfNone, assigns the same label to all the data.size_factor_key¶ (
str|None) – key inadata.obsfor 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 inadata.obsthat 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 inadata.obsthat 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 inadata.obsmfor spatial coordinates.neighbor_index_key¶ (
str|None) – Key inadata.obsmfor neighbor indices. If None, neighbors will not be used during training.neighbor_dist_key¶ (
str|None) – Key inadata.obsmfor neighbor distances.adata (AnnData)
layer (str | None)
batch_key (str | None)
labels_key (str | None)
size_factor_key (str | None)
spatial_key (str)
neighbor_index_key (str | None)
neighbor_dist_key (str | None)
- Return type:
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,BaseSpatialModelAMICI 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 viasetup_anndata().n_attention_heads¶ (
int) – Number of attention heads for cross-attention.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:
- 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.
- get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#
Return the latent representation for each cell.
- get_normalized_expression(adata=None, indices=None, **kwargs)[source]#
Return normalized gene expression.
- 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
AnnDataobject 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 notNone, uses this as the key inadata.layersfor raw count data.batch_key¶ (
str|None) – key inadata.obsfor batch information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_batch']. IfNone, assigns the same batch to all the data.labels_key¶ (
str|None) – key inadata.obsfor label information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_labels']. IfNone, assigns the same label to all the data.spatial_key¶ (
str) – Key inadata.obsmfor spatial coordinates.neighbor_index_key¶ (
str|None) – Key inadata.obsmfor neighbor indices.neighbor_dist_key¶ (
str|None) – Key inadata.obsmfor 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:
DestVI#
- class spatialvi.external.destvi.DestVI(st_adata, sc_model, **kwargs)[source]#
Bases:
objectWrapper 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:
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:
- Return type:
- classmethod from_rna_model(st_adata, sc_model, **kwargs)[source]#
Create DestVI from a trained CondSCVI model.
- train(max_epochs=2500, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#
Train the model.
- Parameters:
- Return type:
- get_proportions(adata=None, indices=None, batch_size=None, return_dataframe=True)[source]#
Get estimated cell type proportions.
- get_gamma(adata=None, indices=None, batch_size=None)[source]#
Get sub-cell-type variation (gamma) per cell type.
- get_scale_for_ct(cell_type, adata=None, indices=None, batch_size=None)[source]#
Get cell type-specific expression scale.
Harreman#
- class spatialvi.external.harreman.Harreman(adata, metabolic_genes=None, spatial_key='spatial', labels_key=None, n_neighbors=20)[source]#
Bases:
objectHarreman 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.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()
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:
objectLanguage-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 inadata.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 toAgent.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
Agentand stores it for subsequent predictions.
- 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) inadata.obsdefining the clusters to annotate. IfNone, 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.Nonemeans annotate all groups.key_is_hierarchical¶ (
bool) – Whethergroup_keyencodes 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 inadata.obs. Two columns will be created:f"{store_key_prefix}_{level}"for the raw label andf"{store_key_prefix}_score_{level}"for the confidence score.**kwargs¶ (
Any) – Additional keyword arguments forwarded toAgent.annotate.key_is_hierarchical (bool)
level (int)
store_key_prefix (str)
kwargs (Any)
- Return type:
- Returns:
The input AnnData with annotation columns added to
obs.
Nolan#
- class spatialvi.external.nolan.Nolan(adata, emb_key='X_scVI', spatial_key='spatial', batch_key=None, num_niches=50, **model_kwargs)[source]#
Bases:
objectHigh-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 inobsm[emb_key]and spatial coordinates inobsm[spatial_key].emb_key¶ (
str) – Key inadata.obsmpointing to a cell embedding. Defaults to"X_scVI".spatial_key¶ (
str) – Key inadata.obsmwith spatial coordinates. Defaults to"spatial".batch_key¶ (
str|None) – Optional key inadata.obsspecifying 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 tonolan.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
nolanpackage (e.g. viapip install nolan). If the dependency is missing, the constructor will still succeed but calls totrain()andpredict()will raiseImportError.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:
- Return type:
Notes
This method delegates to
nolan.tl.NOLANandnolan.tl.NOLAN.fit. Internally it computes a global crop radius and number of cells in global crops usingnolan.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. IfNone, the training AnnData is used.store_key¶ (
str) – Name under which to store the embeddings inadata.obsm.**kwargs¶ (
Any) – Additional keyword arguments forwarded tonolan.tl.NOLAN.predict.adata (AnnData | None)
batch_size (int)
store_key (str)
kwargs (Any)
- Return type:
- Returns:
AnnData with a new
obsm[store_key]containing the predictedniche 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.adata (AnnData | None)
n_clusters (int | None)
resolution (float)
store_key (str)
- Return type:
- Returns:
AnnData with niche cluster assignments in
obs[store_key].
PPIInference#
- class spatialvi.external.ppi.PPIInference[source]#
Bases:
objectStatic 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_pypackage, 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:
- 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:
- 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:
- 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:
- Returns:
coefficients – Point estimates for each regression coefficient.
ResolVI#
- class spatialvi.external.resolvi.ResolVI(adata, n_hidden=128, n_latent=10, n_layers=1, dropout_rate=0.1, **kwargs)[source]#
Bases:
objectWrapper 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:
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.
- train(max_epochs=400, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#
Train the model.
- Parameters:
- Return type:
- get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#
Get latent representation.
- get_denoised_expression(adata=None, indices=None, n_samples=1, batch_size=None)[source]#
Get denoised expression.
- get_background_fraction(adata=None, indices=None, batch_size=None)[source]#
Get estimated background fraction per cell.
scVIVA#
- class spatialvi.external.scviva.scVIVA(adata, n_hidden=128, n_latent=10, n_layers=1, dropout_rate=0.1, **kwargs)[source]#
Bases:
objectWrapper 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:
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.
- train(max_epochs=400, lr=0.001, accelerator='auto', devices='auto', **kwargs)[source]#
Train the model.
- Parameters:
- Return type:
- get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#
Get latent representation.
- get_niche_effects(adata=None, indices=None, batch_size=None)[source]#
Get niche effects for each cell.
SPARL#
- class spatialvi.external.sparl.SPARL(adata, spatial_key='spatial', layer=None, n_latent=32, **model_params)[source]#
Bases:
objectInterface 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 inadata.obsmfor spatial coordinates.layer¶ (
str|None) – Layer inadata.layersto use. If None, usesadata.X.**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
sparlpackage.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:
- Return type:
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.
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:
objectStarfysh 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_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.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.
VIVS#
- class spatialvi.external.vivs.VIVS(adata, spatial_key='spatial', layer=None, n_neighbors=20, n_scales=5)[source]#
Bases:
objectVIVS 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:
Examples
>>> import spatialvi >>> adata = spatialvi.data.synthetic_spatial() >>> model = VIVS(adata, spatial_key="spatial") >>> model.fit() >>> svg = model.get_spatially_variable_genes()
- get_spatially_variable_genes(n_top=None, fdr_threshold=0.05)[source]#
Get spatially variable genes.
- Parameters:
- Return type:
- Returns:
DataFrame with gene names, importance scores, and p-values.