Modules#
Neural network modules implementing VAE components.
Core Modules#
SpatialVAEModule#
- class spatialvi.module.SpatialVAEModule(n_input, n_batch=0, 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, library_log_means=None, library_log_vars=None, n_cats_per_cov=None, n_continuous_cov=0, use_batch_norm='both', use_layer_norm='none', **kwargs)[source]#
Bases:
BaseSpatialModuleSpatial VAE module for gene expression modeling.
This module implements a VAE that incorporates spatial context for improved latent representations.
- Parameters:
dispersion¶ (
Literal['gene','gene-batch','gene-cell']) – Dispersion parameter type.gene_likelihood¶ (
Literal['zinb','nb','poisson']) – Distribution for gene expression.latent_distribution¶ (
Literal['normal','ln']) – Distribution for latent space.spatial_weight¶ (
float) – Weight for spatial regularization.library_log_means¶ (
ndarray|None) – Log means of library sizes.library_log_vars¶ (
ndarray|None) – Log variances of library sizes.n_cats_per_cov¶ (
list[int] |None) – Number of categories per categorical covariate.use_batch_norm¶ (
Literal['encoder','decoder','none','both']) – Whether to use batch normalization.use_layer_norm¶ (
Literal['encoder','decoder','none','both']) – Whether to use layer normalization.n_input (int)
n_batch (int)
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)
library_log_means (np.ndarray | None)
library_log_vars (np.ndarray | None)
n_continuous_cov (int)
use_batch_norm (Literal['encoder', 'decoder', 'none', 'both'])
use_layer_norm (Literal['encoder', 'decoder', 'none', 'both'])
- inference(x, batch_index=None, cont_covs=None, cat_covs=None, spatial_coords=None, neighbor_indices=None, n_samples=1, **kwargs)[source]#
Run the inference network.
- Parameters:
- Return type:
dict[str,Tensor|Distribution]- Returns:
Dictionary of inference outputs.
- generative(z, library, batch_index=None, cont_covs=None, cat_covs=None, **kwargs)[source]#
Run the generative network.
- loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#
Compute the loss.
- Parameters:
inference_outputs¶ (
dict[str,Tensor|Distribution]) – Dictionary of inference outputs.generative_outputs¶ (
dict[str,Tensor|Distribution]) – Dictionary of generative outputs.inference_outputs (dict[str, Tensor | Distribution])
generative_outputs (dict[str, Tensor | Distribution])
kl_weight (float)
- Return type:
- Returns:
LossOutput containing reconstruction loss, KL divergence, etc.
- training: bool#
External Modules#
AMICIModule#
- class spatialvi.external.amici.AMICIModule(n_input, n_labels=1, n_batch=0, 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, **kwargs)[source]#
Bases:
BaseModuleClassAMICI module implementing cross-attention for cell-cell interactions.
- Parameters:
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.n_input (int)
n_labels (int)
n_batch (int)
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)
- inference(x, batch_index=None, labels=None, neighbor_indices=None, neighbor_expr=None, **kwargs)[source]#
Run the inference network.
- Parameters:
- Return type:
dict[str,Tensor|Distribution]- Returns:
Dictionary of inference outputs.
- generative(z, interaction_context, library, batch_index=None, **kwargs)[source]#
Run the generative network.
- Parameters:
- Return type:
dict[str,Tensor|Distribution]- Returns:
Dictionary of generative outputs.
- loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#
Compute the loss.
- Parameters:
inference_outputs¶ (
dict[str,Tensor|Distribution]) – Dictionary of inference outputs.generative_outputs¶ (
dict[str,Tensor|Distribution]) – Dictionary of generative outputs.inference_outputs (dict[str, Tensor | Distribution])
generative_outputs (dict[str, Tensor | Distribution])
kl_weight (float)
- Return type:
- Returns:
LossOutput.
MRDeconv (DestVI)#
- class spatialvi.external.destvi.MRDeconv(n_spots, n_labels, n_batch, n_hidden, n_layers, n_latent, n_genes, decoder_state_dict, px_decoder_state_dict, px_r, per_ct_bias, dropout_decoder, dropout_amortization=0.03, augmentation=True, n_samples_augmentation=2, n_states_per_label=3, eps_v=0.002, mean_vprior=None, var_vprior=None, mp_vprior=None, amortization='both', prior_mode='mog', add_celltypes=1, n_latent_amortization=None, extra_encoder_kwargs=None, extra_decoder_kwargs=None)[source]#
Bases:
EmbeddingModuleMixin,BaseModuleClassModel for multi-resolution deconvolution of spatial transcriptomics.
This module learns to deconvolve spatial transcriptomics data into cell type proportions and cell state representations.
- Parameters:
n_layers¶ (
int) – Number of layers used in the encoder networks.n_latent¶ (
int) – Number of dimensions used in the latent variables.decoder_state_dict¶ (
OrderedDict) – State dict from the decoder of the CondSCVI model.px_decoder_state_dict¶ (
OrderedDict) – State dict from the px_decoder of the CondSCVI model.px_r¶ (
Tensor) – Parameters for the px_r tensor in the CondSCVI model.per_ct_bias¶ (
Tensor) – Estimates of per cell-type expression bias in the CondSCVI model.dropout_decoder¶ (
float) – Dropout rate for the decoder neural network.dropout_amortization¶ (
float) – Dropout rate for the amortization neural network.augmentation¶ (
bool) – Whether to use augmentation during training.n_samples_augmentation¶ (
int) – Number of samples used in the augmentation.n_states_per_label¶ (
int) – Number of states per cell-type in each spot.eps_v¶ (
float) – Epsilon value for each cell-type proportion used during training.mean_vprior¶ (
ndarray) – Mean parameter for each component in the empirical prior.var_vprior¶ (
ndarray) – Diagonal variance parameter for each component in the empirical prior.mp_vprior¶ (
ndarray) – Mixture proportion in cell type sub-clustering of each component.amortization¶ (
Literal['none','latent','proportion','both']) – Mode of amortization.prior_mode¶ (
Literal['mog','normal']) – Mode of the prior distribution for the latent space.add_celltypes¶ (
int) – Number of additional cell types to add to the model.n_latent_amortization¶ (
int|None) – Number of dimensions used in the latent variables for amortization.extra_encoder_kwargs¶ (
dict|None) – Extra keyword arguments passed into encoder.extra_decoder_kwargs¶ (
dict|None) – Extra keyword arguments passed into decoder.n_spots (int)
n_labels (int)
n_batch (int)
n_hidden (int)
n_layers (int)
n_latent (int)
n_genes (int)
decoder_state_dict (OrderedDict)
px_decoder_state_dict (OrderedDict)
px_r (torch.Tensor)
per_ct_bias (torch.Tensor)
dropout_decoder (float)
dropout_amortization (float)
augmentation (bool)
n_samples_augmentation (int)
n_states_per_label (int)
eps_v (float)
mean_vprior (np.ndarray)
var_vprior (np.ndarray)
mp_vprior (np.ndarray)
amortization (Literal['none', 'latent', 'proportion', 'both'])
prior_mode (Literal['mog', 'normal'])
add_celltypes (int)
n_latent_amortization (int | None)
extra_encoder_kwargs (dict | None)
extra_decoder_kwargs (dict | None)
- generative(x, ind_x, v, z, batch_index=None)[source]#
Generative step.
- Parameters:
- Return type:
- Returns:
Dictionary with generative outputs.
HarremanModule#
- class spatialvi.external.harreman.HarremanModule(n_genes, n_neighbors=20, correlation_method='pearson')[source]#
Bases:
ModuleNeural network module for Harreman metabolic exchange analysis.
This module computes spatial correlations between metabolic genes and their neighborhood expression patterns using GPU acceleration.
- Parameters:
MetabolicExchangeScorer#
- class spatialvi.external.harreman.MetabolicExchangeScorer(n_genes, n_cell_types, n_hidden=64)[source]#
Bases:
ModuleScorer for metabolic exchange between cell types.
- Parameters:
LambdaAnnotator#
- class spatialvi.external.lambda_model.LambdaAnnotator(config=None)[source]#
Bases:
objectCore annotation logic for Lambda.
This class handles the annotation pipeline including marker gene extraction, prompt generation, and result parsing.
- Parameters:
NolanModule#
- class spatialvi.external.nolan.NolanModule(input_dim, hidden_dim=128, output_dim=50, n_layers=2, dropout_rate=0.1, use_batch_norm=True, temperature=0.1)[source]#
Bases:
ModuleModule for NOLAN self-supervised niche learning.
This module implements the core components of NOLAN: - Spatial context encoder - Niche embedding network - Contrastive learning objective
- Parameters:
NicheClusteringHead#
MeanEstimator (PPI)#
- class spatialvi.external.ppi.MeanEstimator(config=None)[source]#
Bases:
objectPPI estimator for the population mean.
This estimator uses prediction-powered inference to estimate the population mean with fewer labeled samples.
- fit(y_labeled, yhat_labeled, yhat_unlabeled)[source]#
Compute PPI estimate for the mean.
- Parameters:
y_labeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – True values for labeled samples.yhat_labeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Predictions for labeled samples.yhat_unlabeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Predictions for unlabeled samples.
- Return type:
PPIResult- Returns:
PPIResult with estimate and confidence interval.
OLSEstimator (PPI)#
- class spatialvi.external.ppi.OLSEstimator(config=None)[source]#
Bases:
objectPPI estimator for OLS regression coefficients.
This estimator uses prediction-powered inference for ordinary least squares regression.
- fit(X_labeled, y_labeled, yhat_labeled, X_unlabeled, yhat_unlabeled)[source]#
Compute PPI estimates for OLS coefficients.
- Parameters:
X_labeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Features for labeled samples.y_labeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – True values for labeled samples.yhat_labeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Predictions for labeled samples.X_unlabeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Features for unlabeled samples.yhat_unlabeled¶ (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]]) – Predictions for unlabeled samples.
- Return type:
list[PPIResult]- Returns:
List of PPIResult, one per coefficient.
RESOLVAE#
- class spatialvi.external.resolvi.RESOLVAE(n_input, n_obs, n_neighbors, expression_anntorchdata, n_batch=0, n_hidden=32, n_hidden_encoder=128, n_latent=10, mixture_k=30, n_layers=2, n_cats_per_cov=None, n_labels=None, dropout_rate=0.05, dispersion='gene', gene_likelihood='nb', semisupervised=False, encode_covariates=False, deeply_inject_covariates=True, use_batch_norm='none', use_layer_norm='both', var_activation=None, classifier_parameters=None, prior_true_amount=1.0, prior_diffusion_amount=0.3, sparsity_diffusion=3.0, background_ratio=0.1, prior_proportions_rate=10.0, median_distance=1.0, downsample_counts_mean=None, downsample_counts_std=1.0, diffusion_eps=0.01, latent_distribution=None)[source]#
Bases:
PyroBaseModuleClassImplementation of ResolVI module.
This is the main module class that combines the model and guide for training with Pyro’s SVI.
- Parameters:
expression_anntorchdata¶ (
AnnTorchDataset) – AnnTorchDataset with expression data.n_hidden¶ (
int) – Number of nodes per hidden layer in decoder.n_hidden_encoder¶ (
int) – Number of nodes per hidden layer in encoder.n_cats_per_cov¶ (
Iterable[int] |None) – Number of categories for each categorical covariate.n_labels¶ (
Iterable[int] |None) – Number of cell-type labels.dispersion¶ (
Literal['gene','gene-batch']) – Dispersion mode.gene_likelihood¶ (
Literal['nb','poisson']) – Gene likelihood distribution.semisupervised¶ (
bool) – Whether to use semi-supervised mode.deeply_inject_covariates¶ (
bool) – Whether to deeply inject covariates.use_batch_norm¶ (
Literal['encoder','decoder','none','both']) – Batch norm mode.use_layer_norm¶ (
Literal['encoder','decoder','none','both']) – Layer norm mode.var_activation¶ (
Callable|None) – Variance activation function.classifier_parameters¶ (
dict|None) – Parameters for classifier.prior_diffusion_amount¶ (
float) – Prior for diffusion proportion.downsample_counts_mean¶ (
float|None) – Downsample counts mean.latent_distribution¶ (
str|None) – Placeholder for compatibility.n_input (int)
n_obs (int)
n_neighbors (int)
expression_anntorchdata (AnnTorchDataset)
n_batch (int)
n_hidden (int)
n_hidden_encoder (int)
n_latent (int)
mixture_k (int)
n_layers (int)
n_cats_per_cov (Iterable[int] | None)
n_labels (Iterable[int] | None)
dropout_rate (float)
dispersion (Literal['gene', 'gene-batch'])
gene_likelihood (Literal['nb', 'poisson'])
semisupervised (bool)
encode_covariates (bool)
deeply_inject_covariates (bool)
use_batch_norm (Literal['encoder', 'decoder', 'none', 'both'])
use_layer_norm (Literal['encoder', 'decoder', 'none', 'both'])
var_activation (Callable | None)
classifier_parameters (dict | None)
prior_true_amount (float)
prior_diffusion_amount (float)
sparsity_diffusion (float)
background_ratio (float)
prior_proportions_rate (float)
median_distance (float)
downsample_counts_mean (float | None)
downsample_counts_std (float)
diffusion_eps (float)
latent_distribution (str | None)
- property model#
Return the generative model.
- property model_corrected#
Return the corrected model.
- property model_unconditioned#
Return the unconditioned model.
- property guide#
Return the variational guide.
- property list_obs_plate_vars#
Return observation plate variables.
nicheVAE (scVIVA)#
- class spatialvi.external.scviva.nicheVAE(n_input, n_output_niche, n_batch=0, n_labels=0, n_hidden=128, n_latent=10, n_layers=1, n_layers_niche=1, n_layers_compo=1, n_hidden_niche=128, n_hidden_compo=128, n_continuous_cov=0, n_cats_per_cov=None, dropout_rate=0.1, dispersion='gene', log_variational=True, gene_likelihood='poisson', latent_distribution='normal', niche_likelihood='gaussian', cell_rec_weight=1.0, latent_kl_weight=1.0, spatial_weight=10, prior_mixture=False, prior_mixture_k=20, semisupervised=True, linear_classifier=True, inpute_covariates_niche_decoder=True, encode_covariates=False, deeply_inject_covariates=True, batch_representation='one-hot', use_batch_norm='none', use_layer_norm='both', use_size_factor_key=False, use_observed_lib_size=True, library_log_means=None, library_log_vars=None, batch_embedding_kwargs=None, extra_decoder_kwargs=None, extra_encoder_kwargs=None, **vae_kwargs)[source]#
Bases:
VAEVariational auto-encoder with niche decoders.
Extends the base VAE to model cellular microenvironments by learning niche-aware representations that capture both cell-intrinsic and neighborhood-specific factors.
- Parameters:
n_output_niche¶ (
int) – Number of output features for niche state.n_batch¶ (
int) – Number of batches. If0, no batch correction is performed.n_layers_niche¶ (
int) – Number of hidden layers in the niche state decoder.n_layers_compo¶ (
int) – Number of hidden layers in the composition decoder.n_hidden_niche¶ (
int) – Number of nodes per hidden layer in the niche state decoder.n_hidden_compo¶ (
int) – Number of nodes per hidden layer in the composition decoder.n_cats_per_cov¶ (
list[int] |None) – A list of integers containing the number of categories for each categorical covariate.dispersion¶ (
Literal['gene','gene-batch','gene-label','gene-cell']) – Flexibility of the dispersion parameter.log_variational¶ (
bool) – IfTrue, use log1p on input data before encoding.gene_likelihood¶ (
Literal['zinb','nb','poisson']) – Distribution to use for reconstruction.latent_distribution¶ (
Literal['normal','ln']) – Distribution to use for the latent space.niche_likelihood¶ (
Literal['poisson','gaussian']) – Distribution to use for the niche state.cell_rec_weight¶ (
float) – Weight of the cell reconstruction loss.latent_kl_weight¶ (
float) – Weight of the latent KL divergence.prior_mixture¶ (
bool) – IfTrue, use a mixture of Gaussians for the latent space.prior_mixture_k¶ (
int) – Number of components in the Gaussian mixture.semisupervised¶ (
bool) – IfTrue, use a classifier to predict cell type labels.linear_classifier¶ (
bool) – IfTrue, use a linear classifier.inpute_covariates_niche_decoder¶ (
bool) – IfTrue, covariates are concatenated to the input of the niche decoder.encode_covariates¶ (
bool) – IfTrue, covariates are concatenated to gene expression before encoding.deeply_inject_covariates¶ (
bool) – IfTrueandn_layers > 1, covariates are injected into hidden layers.batch_representation¶ (
Literal['one-hot','embedding']) – Method for encoding batch information.use_batch_norm¶ (
Literal['encoder','decoder','none','both']) – Specifies where to use batch normalization.use_layer_norm¶ (
Literal['encoder','decoder','none','both']) – Specifies where to use layer normalization.use_size_factor_key¶ (
bool) – IfTrue, use the size factor from obs.use_observed_lib_size¶ (
bool) – IfTrue, use observed library size for RNA.library_log_means¶ (
ndarray|None) – Means of the log library sizes for prior.library_log_vars¶ (
ndarray|None) – Variances of the log library sizes for prior.batch_embedding_kwargs¶ (
dict|None) – Keyword arguments for batch embedding.extra_decoder_kwargs¶ (
dict|None) – Additional keyword arguments for decoder.extra_encoder_kwargs¶ (
dict|None) – Additional keyword arguments for encoder.**vae_kwargs¶ – Additional keyword arguments for base VAE.
n_input (int)
n_output_niche (int)
n_batch (int)
n_labels (int)
n_hidden (int)
n_latent (int)
n_layers (int)
n_layers_niche (int)
n_layers_compo (int)
n_hidden_niche (int)
n_hidden_compo (int)
n_continuous_cov (int)
dropout_rate (float)
dispersion (Literal['gene', 'gene-batch', 'gene-label', 'gene-cell'])
log_variational (bool)
gene_likelihood (Literal['zinb', 'nb', 'poisson'])
latent_distribution (Literal['normal', 'ln'])
niche_likelihood (Literal['poisson', 'gaussian'])
cell_rec_weight (float)
latent_kl_weight (float)
spatial_weight (float)
prior_mixture (bool)
prior_mixture_k (int)
semisupervised (bool)
linear_classifier (bool)
inpute_covariates_niche_decoder (bool)
encode_covariates (bool)
deeply_inject_covariates (bool)
batch_representation (Literal['one-hot', 'embedding'])
use_batch_norm (Literal['encoder', 'decoder', 'none', 'both'])
use_layer_norm (Literal['encoder', 'decoder', 'none', 'both'])
use_size_factor_key (bool)
use_observed_lib_size (bool)
library_log_means (np.ndarray | None)
library_log_vars (np.ndarray | None)
batch_embedding_kwargs (dict | None)
extra_decoder_kwargs (dict | None)
extra_encoder_kwargs (dict | None)
- generative(z, library, batch_index, cont_covs=None, cat_covs=None, size_factor=None, y=None, transform_batch=None)[source]#
Run the generative process.
- Parameters:
- Return type:
dict[str,Distribution|None]- Returns:
Dictionary of generative outputs including distributions.
- loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0, classification_ratio=50, epsilon=1e-06, n_samples_mixture=10)[source]#
Compute the loss.
- Parameters:
inference_outputs¶ (
dict[str,Tensor|Distribution|None]) – Outputs from inference.generative_outputs¶ (
dict[str,Tensor|Distribution|None]) – Outputs from generative.classification_ratio¶ (
float) – Weight for classification loss.n_samples_mixture¶ (
int) – Number of samples for mixture prior.inference_outputs (dict[str, Tensor | Distribution | None])
generative_outputs (dict[str, Tensor | Distribution | None])
kl_weight (float)
classification_ratio (float)
epsilon (float)
n_samples_mixture (int)
- Return type:
NicheLossOutput- Returns:
NicheLossOutput with loss components.
SPARLModule#
- class spatialvi.external.sparl.SPARLModule(n_proteins, n_hidden=128, n_latent=32, n_layers=2, dropout_rate=0.1, use_spatial=True, spatial_dim=64)[source]#
Bases:
BaseModuleClassSPARL module for spatial proteomics representation learning.
- Parameters:
- loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#
Compute loss.
- Parameters:
inference_outputs¶ (
dict[str,Tensor|Distribution]) – Inference outputs.generative_outputs¶ (
dict[str,Tensor|Distribution]) – Generative outputs.inference_outputs (dict[str, Tensor | Distribution])
generative_outputs (dict[str, Tensor | Distribution])
kl_weight (float)
- Return type:
- Returns:
Loss output.
StarfyshModule#
- class spatialvi.external.starfysh.StarfyshModule(n_genes, n_cell_types, n_factors=5, n_hidden=128, n_layers=2, dropout_rate=0.1, use_histology=False, histology_dim=0)[source]#
Bases:
BaseModuleClassNeural network module for Starfysh deconvolution.
- Parameters:
- generative(proportions, factor_weights, library, **kwargs)[source]#
Run generative model.
- Parameters:
- Return type:
dict[str,Tensor|Distribution]- Returns:
Dictionary of generative outputs.
- loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#
Compute loss.
- Parameters:
inference_outputs¶ (
dict[str,Tensor|Distribution]) – Inference outputs.generative_outputs¶ (
dict[str,Tensor|Distribution]) – Generative outputs.inference_outputs (dict[str, Tensor | Distribution])
generative_outputs (dict[str, Tensor | Distribution])
kl_weight (float)
- Return type:
- Returns:
LossOutput.
VIVSModule#
- class spatialvi.external.vivs.VIVSModule(n_genes, n_scales=5, n_neighbors_base=20, use_gpu=False)[source]#
Bases:
ModuleVIVS module for computing spatial variance statistics.
This module implements the core computations for VIVS: - Multi-scale local variance computation - Permutation-based null distribution estimation - Importance score calculation
- Parameters:
- compute_null_distribution(X, neighbor_indices, n_permutations=100)[source]#
Compute null distribution via permutation.
MultiScaleVIVS#
- class spatialvi.external.vivs.MultiScaleVIVS(n_genes, scales=None, aggregation='max')[source]#
Bases:
ModuleMulti-scale VIVS for robust spatial variable gene detection.
- Parameters: