Modules

Contents

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: BaseSpatialModule

Spatial VAE module for gene expression modeling.

This module implements a VAE that incorporates spatial context for improved latent representations.

Parameters:
  • n_input (int) – Number of input genes.

  • n_batch (int) – Number of batches.

  • 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 type.

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

  • latent_distribution (Literal['normal', 'ln']) – Distribution for latent space.

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

  • 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.

  • n_continuous_cov (int) – Number of continuous covariates.

  • 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_cats_per_cov (list[int] | 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.

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:
Return type:

LossOutput

Returns:

LossOutput containing reconstruction loss, KL divergence, etc.

training: bool#
sample(tensors, n_samples=1)[source]#

Sample from the model.

Parameters:
Return type:

Tensor

Returns:

Sampled gene expression.

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: BaseModuleClass

AMICI module implementing cross-attention for cell-cell interactions.

Parameters:
  • n_input (int) – Number of input genes.

  • n_labels (int) – Number of cell type labels.

  • n_batch (int) – Number of batches.

  • 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.

  • dropout_rate (float) – Dropout rate.

  • 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:
Return type:

LossOutput

Returns:

LossOutput.

forward(tensors, get_inference_input_kwargs=None, get_generative_input_kwargs=None, inference_kwargs=None, generative_kwargs=None, loss_kwargs=None, compute_loss=True)[source]#

Forward pass.

Return type:

tuple[dict, dict] | tuple[dict, dict, LossOutput]

Parameters:
  • tensors (dict[str, Tensor])

  • get_inference_input_kwargs (dict | None)

  • get_generative_input_kwargs (dict | None)

  • inference_kwargs (dict | None)

  • generative_kwargs (dict | None)

  • loss_kwargs (dict | None)

  • compute_loss (bool)

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, BaseModuleClass

Model 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_spots (int) – Number of input spots.

  • n_labels (int) – Number of cell types.

  • n_batch (int) – Number of batches.

  • n_hidden (int) – Number of neurons in the hidden layers.

  • n_layers (int) – Number of layers used in the encoder networks.

  • n_latent (int) – Number of dimensions used in the latent variables.

  • n_genes (int) – Number of genes used in the decoder.

  • 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)

inference(x, ind_x)[source]#

Inference step.

Parameters:
Return type:

dict[str, Tensor]

Returns:

Dictionary with inference outputs including v and z.

generative(x, ind_x, v, z, batch_index=None)[source]#

Generative step.

Parameters:
Return type:

dict[str, Tensor]

Returns:

Dictionary with generative outputs.

loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#

Compute loss.

Parameters:
Return type:

LossOutput

Returns:

LossOutput with loss components.

get_proportions(x, ind_x=None)[source]#

Get cell type proportions.

Parameters:
Return type:

Tensor

Returns:

Cell type proportions tensor.

HarremanModule#

class spatialvi.external.harreman.HarremanModule(n_genes, n_neighbors=20, correlation_method='pearson')[source]#

Bases: Module

Neural network module for Harreman metabolic exchange analysis.

This module computes spatial correlations between metabolic genes and their neighborhood expression patterns using GPU acceleration.

Parameters:
  • n_genes (int) – Number of metabolic genes.

  • n_neighbors (int) – Number of spatial neighbors.

  • correlation_method (Literal['pearson', 'spearman']) – Method for computing correlations.

  • n_genes (int)

  • n_neighbors (int)

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

compute_neighbor_expression(X, neighbor_indices)[source]#

Compute mean neighbor expression.

Parameters:
  • X (Tensor) – Gene expression tensor of shape (n_cells, n_genes).

  • neighbor_indices (Tensor) – Neighbor indices of shape (n_cells, n_neighbors).

  • X (Tensor)

  • neighbor_indices (Tensor)

Return type:

Tensor

Returns:

Mean neighbor expression of shape (n_cells, n_genes).

compute_spatial_correlation(X, neighbor_mean)[source]#

Compute spatial correlation for each gene.

Parameters:
Return type:

Tensor

Returns:

Correlation tensor of shape (n_genes,).

forward(X, neighbor_indices)[source]#

Run forward pass.

Parameters:
Return type:

dict[str, Tensor]

Returns:

Dictionary with spatial_correlation and neighbor_expression.

MetabolicExchangeScorer#

class spatialvi.external.harreman.MetabolicExchangeScorer(n_genes, n_cell_types, n_hidden=64)[source]#

Bases: Module

Scorer for metabolic exchange between cell types.

Parameters:
  • n_genes (int) – Number of metabolic genes.

  • n_cell_types (int) – Number of cell types.

  • n_hidden (int) – Number of hidden units.

  • n_genes (int)

  • n_cell_types (int)

  • n_hidden (int)

forward(sender_expr, receiver_expr, sender_type, receiver_type)[source]#

Compute exchange scores.

Parameters:
  • sender_expr (Tensor) – Sender cell expression.

  • receiver_expr (Tensor) – Receiver cell expression.

  • sender_type (Tensor) – Sender cell type indices.

  • receiver_type (Tensor) – Receiver cell type indices.

  • sender_expr (Tensor)

  • receiver_expr (Tensor)

  • sender_type (Tensor)

  • receiver_type (Tensor)

Return type:

Tensor

Returns:

Exchange scores per gene.

LambdaAnnotator#

class spatialvi.external.lambda_model.LambdaAnnotator(config=None)[source]#

Bases: object

Core annotation logic for Lambda.

This class handles the annotation pipeline including marker gene extraction, prompt generation, and result parsing.

Parameters:
  • config (AnnotationConfig | None) – Annotation configuration.

  • config (AnnotationConfig | None)

extract_marker_genes(adata, cluster_key, cluster_id)[source]#

Extract marker genes for a cluster.

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

  • cluster_key (str) – Key in obs for cluster assignments.

  • cluster_id (str) – Cluster to extract markers for.

  • adata (AnnData)

  • cluster_key (str)

  • cluster_id (str)

Return type:

tuple[list[str], list[float]]

Returns:

Tuple of (gene names, scores).

parse_llm_response(response)[source]#

Parse LLM response into structured annotation.

Parameters:
  • response (str) – Raw response from the LLM.

  • response (str)

Return type:

ClusterAnnotation

Returns:

Parsed annotation result.

property results: list[ClusterAnnotation]#

Get annotation results.

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: Module

Module for NOLAN self-supervised niche learning.

This module implements the core components of NOLAN: - Spatial context encoder - Niche embedding network - Contrastive learning objective

Parameters:
  • input_dim (int) – Dimension of input embeddings.

  • hidden_dim (int) – Hidden layer dimension.

  • output_dim (int) – Dimension of niche embeddings.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate.

  • use_batch_norm (bool) – Whether to use batch normalization.

  • temperature (float) – Temperature for contrastive loss.

  • input_dim (int)

  • hidden_dim (int)

  • output_dim (int)

  • n_layers (int)

  • dropout_rate (float)

  • use_batch_norm (bool)

  • temperature (float)

encode(x)[source]#

Encode input embeddings.

Parameters:
  • x (Tensor) – Input embeddings of shape (batch, input_dim).

  • x (Tensor)

Return type:

Tensor

Returns:

Encoded features of shape (batch, hidden_dim).

project(h)[source]#

Project to niche embedding space.

Parameters:
Return type:

Tensor

Returns:

Projected embeddings of shape (batch, output_dim).

forward(x, x_neighbor=None)[source]#

Forward pass.

Parameters:
  • x (Tensor) – Input embeddings of shape (batch, input_dim).

  • x_neighbor (Tensor | None) – Neighbor embeddings for contrastive learning.

  • x (Tensor)

  • x_neighbor (Tensor | None)

Return type:

dict[str, Tensor]

Returns:

Dictionary with niche_embedding and optionally contrastive outputs.

contrastive_loss(z, z_pos, z_neg=None)[source]#

Compute contrastive loss.

Parameters:
Return type:

Tensor

Returns:

Contrastive loss value.

NicheClusteringHead#

class spatialvi.external.nolan.NicheClusteringHead(input_dim, n_clusters=20, soft_assignment=True)[source]#

Bases: Module

Clustering head for discrete niche assignment.

Parameters:
  • input_dim (int) – Input embedding dimension.

  • n_clusters (int) – Number of niche clusters.

  • soft_assignment (bool) – Whether to use soft cluster assignment.

  • input_dim (int)

  • n_clusters (int)

  • soft_assignment (bool)

forward(z)[source]#

Assign cells to niches.

Parameters:
  • z (Tensor) – Niche embeddings of shape (batch, input_dim).

  • z (Tensor)

Return type:

dict[str, Tensor]

Returns:

Dictionary with assignments and distances.

MeanEstimator (PPI)#

class spatialvi.external.ppi.MeanEstimator(config=None)[source]#

Bases: object

PPI estimator for the population mean.

This estimator uses prediction-powered inference to estimate the population mean with fewer labeled samples.

Parameters:
  • config (PPIConfig | None) – PPI configuration.

  • config (PPIConfig | None)

fit(y_labeled, yhat_labeled, yhat_unlabeled)[source]#

Compute PPI estimate for the mean.

Parameters:
Return type:

PPIResult

Returns:

PPIResult with estimate and confidence interval.

OLSEstimator (PPI)#

class spatialvi.external.ppi.OLSEstimator(config=None)[source]#

Bases: object

PPI estimator for OLS regression coefficients.

This estimator uses prediction-powered inference for ordinary least squares regression.

Parameters:
  • config (PPIConfig | None) – PPI configuration.

  • config (PPIConfig | None)

fit(X_labeled, y_labeled, yhat_labeled, X_unlabeled, yhat_unlabeled)[source]#

Compute PPI estimates for OLS coefficients.

Parameters:
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: PyroBaseModuleClass

Implementation of ResolVI module.

This is the main module class that combines the model and guide for training with Pyro’s SVI.

Parameters:
  • n_input (int) – Number of input genes.

  • n_obs (int) – Number of total input cells.

  • n_neighbors (int) – Number of spatial neighbors.

  • expression_anntorchdata (AnnTorchDataset) – AnnTorchDataset with expression data.

  • n_batch (int) – Number of batches.

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

  • n_hidden_encoder (int) – Number of nodes per hidden layer in encoder.

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

  • mixture_k (int) – Number of mixture components.

  • n_layers (int) – Number of hidden layers.

  • n_cats_per_cov (Iterable[int] | None) – Number of categories for each categorical covariate.

  • n_labels (Iterable[int] | None) – Number of cell-type labels.

  • dropout_rate (float) – Dropout rate.

  • dispersion (Literal['gene', 'gene-batch']) – Dispersion mode.

  • gene_likelihood (Literal['nb', 'poisson']) – Gene likelihood distribution.

  • semisupervised (bool) – Whether to use semi-supervised mode.

  • encode_covariates (bool) – Whether to encode covariates.

  • 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_true_amount (float) – Prior for true proportion.

  • prior_diffusion_amount (float) – Prior for diffusion proportion.

  • sparsity_diffusion (float) – Sparsity diffusion prior.

  • background_ratio (float) – Background ratio prior.

  • prior_proportions_rate (float) – Prior proportions rate.

  • median_distance (float) – Median distance for kernel.

  • downsample_counts_mean (float | None) – Downsample counts mean.

  • downsample_counts_std (float) – Downsample counts std.

  • diffusion_eps (float) – Diffusion epsilon.

  • 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: VAE

Variational 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_input (int) – Number of input features.

  • n_output_niche (int) – Number of output features for niche state.

  • n_batch (int) – Number of batches. If 0, no batch correction is performed.

  • n_labels (int) – Number of labels.

  • 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_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_continuous_cov (int) – Number of continuous covariates.

  • n_cats_per_cov (list[int] | None) – A list of integers containing the number of categories for each categorical covariate.

  • dropout_rate (float) – Dropout rate.

  • dispersion (Literal['gene', 'gene-batch', 'gene-label', 'gene-cell']) – Flexibility of the dispersion parameter.

  • log_variational (bool) – If True, 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.

  • spatial_weight (float) – Weight of the spatial losses.

  • prior_mixture (bool) – If True, use a mixture of Gaussians for the latent space.

  • prior_mixture_k (int) – Number of components in the Gaussian mixture.

  • semisupervised (bool) – If True, use a classifier to predict cell type labels.

  • linear_classifier (bool) – If True, use a linear classifier.

  • inpute_covariates_niche_decoder (bool) – If True, covariates are concatenated to the input of the niche decoder.

  • encode_covariates (bool) – If True, covariates are concatenated to gene expression before encoding.

  • deeply_inject_covariates (bool) – If True and n_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) – If True, use the size factor from obs.

  • use_observed_lib_size (bool) – If True, 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)

  • n_cats_per_cov (list[int] | None)

  • 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:
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: BaseModuleClass

SPARL module for spatial proteomics representation learning.

Parameters:
  • n_proteins (int) – Number of protein channels.

  • n_hidden (int) – Number of hidden units.

  • n_latent (int) – Latent dimension.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate.

  • use_spatial (bool) – Whether to use spatial context.

  • spatial_dim (int) – Dimension of spatial features.

  • n_proteins (int)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • dropout_rate (float)

  • use_spatial (bool)

  • spatial_dim (int)

inference(x, spatial=None, **kwargs)[source]#

Run inference network.

Parameters:
Return type:

dict[str, Tensor | Distribution]

Returns:

Inference outputs.

generative(z, **kwargs)[source]#

Run generative network.

Parameters:
Return type:

dict[str, Tensor | Distribution]

Returns:

Generative outputs.

loss(tensors, inference_outputs, generative_outputs, kl_weight=1.0)[source]#

Compute loss.

Parameters:
Return type:

LossOutput

Returns:

Loss output.

forward(tensors, get_inference_input_kwargs=None, get_generative_input_kwargs=None, inference_kwargs=None, generative_kwargs=None, loss_kwargs=None, compute_loss=True)[source]#

Forward pass.

Return type:

tuple[dict, dict] | tuple[dict, dict, LossOutput]

Parameters:
  • tensors (dict[str, Tensor])

  • get_inference_input_kwargs (dict | None)

  • get_generative_input_kwargs (dict | None)

  • inference_kwargs (dict | None)

  • generative_kwargs (dict | None)

  • loss_kwargs (dict | None)

  • compute_loss (bool)

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: BaseModuleClass

Neural network module for Starfysh deconvolution.

Parameters:
  • n_genes (int) – Number of genes.

  • n_cell_types (int) – Number of cell types.

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

  • n_hidden (int) – Number of hidden units.

  • n_layers (int) – Number of hidden layers.

  • dropout_rate (float) – Dropout rate.

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

  • histology_dim (int) – Dimension of histology features (if used).

  • n_genes (int)

  • n_cell_types (int)

  • n_factors (int)

  • n_hidden (int)

  • n_layers (int)

  • dropout_rate (float)

  • use_histology (bool)

  • histology_dim (int)

inference(x, histology=None, **kwargs)[source]#

Run inference.

Parameters:
Return type:

dict[str, Tensor | Distribution]

Returns:

Dictionary of inference outputs.

generative(proportions, factor_weights, library, **kwargs)[source]#

Run generative model.

Parameters:
  • proportions (Tensor) – Cell type proportions.

  • factor_weights (Tensor) – Factor weights per cell type.

  • library (Tensor) – Library size.

  • proportions (Tensor)

  • factor_weights (Tensor)

  • library (Tensor)

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:
Return type:

LossOutput

Returns:

LossOutput.

forward(tensors, get_inference_input_kwargs=None, get_generative_input_kwargs=None, inference_kwargs=None, generative_kwargs=None, loss_kwargs=None, compute_loss=True)[source]#

Forward pass.

Return type:

tuple[dict, dict] | tuple[dict, dict, LossOutput]

Parameters:
  • tensors (dict[str, Tensor])

  • get_inference_input_kwargs (dict | None)

  • get_generative_input_kwargs (dict | None)

  • inference_kwargs (dict | None)

  • generative_kwargs (dict | None)

  • loss_kwargs (dict | None)

  • compute_loss (bool)

VIVSModule#

class spatialvi.external.vivs.VIVSModule(n_genes, n_scales=5, n_neighbors_base=20, use_gpu=False)[source]#

Bases: Module

VIVS 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:
  • n_genes (int) – Number of genes.

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

  • n_neighbors_base (int) – Base number of neighbors for the smallest scale.

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

  • n_genes (int)

  • n_scales (int)

  • n_neighbors_base (int)

  • use_gpu (bool)

compute_local_variance(X, neighbor_indices)[source]#

Compute local variance for each gene.

Parameters:
  • X (Tensor) – Expression tensor of shape (n_cells, n_genes).

  • neighbor_indices (Tensor) – Neighbor indices of shape (n_cells, n_neighbors).

  • X (Tensor)

  • neighbor_indices (Tensor)

Return type:

Tensor

Returns:

Local variance tensor of shape (n_genes,).

compute_null_distribution(X, neighbor_indices, n_permutations=100)[source]#

Compute null distribution via permutation.

Parameters:
  • X (Tensor) – Expression tensor.

  • neighbor_indices (Tensor) – Neighbor indices.

  • n_permutations (int) – Number of permutations.

  • X (Tensor)

  • neighbor_indices (Tensor)

  • n_permutations (int)

Return type:

tuple[Tensor, Tensor]

Returns:

Tuple of (null_mean, null_std).

forward(X, neighbor_indices, n_permutations=100)[source]#

Run VIVS analysis for a single scale.

Parameters:
  • X (Tensor) – Expression tensor of shape (n_cells, n_genes).

  • neighbor_indices (Tensor) – Neighbor indices of shape (n_cells, n_neighbors).

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

  • X (Tensor)

  • neighbor_indices (Tensor)

  • n_permutations (int)

Return type:

dict[str, Tensor]

Returns:

Dictionary with z_scores and local_variance.

MultiScaleVIVS#

class spatialvi.external.vivs.MultiScaleVIVS(n_genes, scales=None, aggregation='max')[source]#

Bases: Module

Multi-scale VIVS for robust spatial variable gene detection.

Parameters:
  • n_genes (int) – Number of genes.

  • scales (list[int] | None) – List of neighbor counts for each scale.

  • aggregation (Literal['max', 'mean', 'weighted']) – How to aggregate across scales.

  • n_genes (int)

  • scales (list[int] | None)

  • aggregation (Literal['max', 'mean', 'weighted'])

aggregate_scores(scale_scores)[source]#

Aggregate z-scores across scales.

Parameters:
  • scale_scores (Tensor) – Tensor of shape (n_genes, n_scales).

  • scale_scores (Tensor)

Return type:

Tensor

Returns:

Aggregated scores of shape (n_genes,).

forward(X, neighbor_indices_list, n_permutations=100)[source]#

Run multi-scale VIVS analysis.

Parameters:
  • X (Tensor) – Expression tensor.

  • neighbor_indices_list (list[Tensor]) – List of neighbor indices for each scale.

  • n_permutations (int) – Number of permutations.

  • X (Tensor)

  • neighbor_indices_list (list[Tensor])

  • n_permutations (int)

Return type:

dict[str, Tensor]

Returns:

Dictionary with importance_scores and scale_scores.