smoother.models.reduction._spae

Classes

SpatialLoss

Spatial loss.

AutoEncoderClass

Abstract AutoEncoder class.

SpatialAutoEncoder

Generic spatial auto-encoder.

Module Contents

class smoother.models.reduction._spae.SpatialLoss(prior, spatial_weights: List[smoother.weights.SpatialWeightMatrix] = None, rho=1, use_sparse=True, standardize_cov=False)

Bases: torch.nn.Module

Spatial loss.

The spatial smoothing loss on a spatial random variable (num_group x num_spot).

prior

The prior spatial process model, can be one of ‘sma’,’sar’, ‘car’, ‘icar’.

Type:

str

spatial_weights

Spatial weight matrix collection of length num_group or 1. If 1 then all groups will be subject to the same covariance.

Type:

List[SpatialWeightMatrix]

rho

The spatial autocorrelation parameter (for SpatialWeightMatrix.get_inv_cov).

Type:

float

use_sparse

Whether to use sparse inverse covariance matrix in the calculation.

Type:

bool

standardize_cov

Whether to standardize the covariance matrix to have same variance (1) across locations. Only proper covariance can be standardized.

Type:

bool

inv_cov

Inverse covariance (precision) matrix of spatial variables of each group, (num_group or 1) x n x n. If the first dimension has length 1, all groups will have the same covariance structure.

Type:

3D tensor

inv_cov_2d_sp

Sparse block diagonal inverse covariance (precision) matrix.

Type:

2D sparse tensor

confidences

Relative prior confidence of each group. The higher the confidence, the stronger the smoothing will be. If float, all groups will have the same confidence.

Type:

1D tensor or float

_sanity_check() None

Check whether the spatial loss is defined properly.

estimate_confidence(ref_exp, st_exp, method='lr') None

Estimate the relative confidence for each group.

The covariance matrix will be scaled accordingly.

Parameters:
  • ref_exp (2D tensor) – Bulk expression signiture matrix, num_gene x num_group.

  • st_exp (2D tensor) – Spatial expression matrix, num_gene x num_spot.

  • method (str) – Method used to estimate variance.

forward(coefs, normalize=True)

Calculate spatial loss.

Parameters:

coefs (2D tensor) – Columns of regression coefficients, num_group x num_spot.

calc_corr_decay_stats(coords, min_k=0, max_k=50, cov_ind=0, return_var=False)

Calculate spatial covariance decay over degree of neighborhoods.

Covariance measured between k-nearest neighbors. If the number of covariance matrices (i.e. self.inv_cov.shape[0]) is larger than 1, use ‘cov_ind’ to select the covariance matrix to use.

Parameters:
  • coords (2D tensor) – Coordinates of spots, num_spot x 2.

  • min_k – Minimum number of k in k-nearest neighbors. k = 0: self.

  • max_k – Maximum number of k in k-nearest neighbors.

  • cov_ind (int) – Index of the covariance matrix to use.

  • return_var (bool) – Whether to return variance stats.

Returns:

Correlation decay quantiles. var_quantiles_df (pd.DataFrame): Per-spot variance quantiles.

Return type:

corr_decay_quantiles_df (pd.DataFrame)

class smoother.models.reduction._spae.AutoEncoderClass(n_feature: int, n_latent: int = 10, spatial_loss: smoother.losses.SpatialLoss | None = None, lambda_spatial_loss=0.1, lambda_orth_loss=0.1)

Bases: torch.nn.Module

Abstract AutoEncoder class.

To mimic the behavior of PCA, the overall objective contains three losses:
  1. Reconstruction loss: reconstruction error of the observed data.

  2. Orthogonality loss: the loss of orthogonality on the hidden embeddings.

  3. Spatial loss: the spatial loss on the hidden embeddings.

load_adata(adata: anndata.AnnData, layer: str | None = None)

Load data to project.

Parameters:
  • adata (AnnData) – data to project.

  • layer (str) – layer to project. If None, use adata.X.

forward(x)
encode(x)
decode(x_enc)
get_latent_representation()

Get the latent representation of the loaded data.

abstract get_recon_loss()

Get the reconstruction loss.

abstract get_orth_loss()

Get the orthogonality loss (weighted by lambda_orth_loss).

abstract get_sp_loss()

Get the spatial loss (weighted by lambda_spatial_loss).

reduce(lr=0.01, max_epochs=1000, patience=10, tol=1e-05, optimizer='SGD', verbose=True, quite=False, clear_logs=True)
classmethod _reduce_dim_ae(ae_model, lr=0.01, max_epochs=1000, patience=10, tol=1e-05, optimizer='SGD', verbose=True, quite=False, clear_logs=False, return_model=False)

Dimension reduction using auto-encoders.

Two additional losses are added in addition to the reconstruction loss:
  1. Orthogonality loss: the loss of the orthogonality of the hidden embedding.

  2. Spatial loss: the spatial loss on the hidden embeddings.

Parameters:
  • ae_model (AutoEncoder) – The autoencoder model.

  • lr (float) – The learning rate.

  • max_epochs (int) – The maximum number of epochs.

  • patience (int) – The patience for early stopping.

  • tol (float) – The tolerated convergence error.

  • optimizer (str) – The optimizer to be used. Can be ‘SGD’ or ‘Adam’.

  • verbose (bool) – If True, print out loss while training.

  • quite (bool) – If True, no output printed.

  • clear_logs (bool) – If True, clear the logs in the autoencoder model.

  • return_model (bool) – If True, return the trained autoencoder model.

Returns:

The trained autoencoder model.

Return type:

ae_model (AutoEncoder)

class smoother.models.reduction._spae.SpatialAutoEncoder(adata: anndata.AnnData, layer: str | None = None, spatial_loss: smoother.losses.SpatialLoss | None = None, lambda_spatial_loss=0.1, lambda_orth_loss=0.1, recon_loss_mode: Literal['mse', 'poisson'] = 'poisson', n_layers: int = 1, n_hidden: int = 128, n_latent: int = 10, dropout_rate: float = 0.0, use_batch_norm: bool = True, use_activation: bool = True, activation_fn: torch.nn.Module | None = nn.ReLU, use_bias=True)

Bases: AutoEncoderClass

Generic spatial auto-encoder.

encode(x)

Project the input to the hidden space.

Parameters:

x (2D tensor) – The input matrix, num_gene x num_spot.

Returns:

The hidden embedding, num_spot x num_hidden.

Return type:

x_enc (2D tensor)

decode(x_enc)

Project the hidden embedding back to the input space.

Parameters:

x_enc (2D tensor) – The hidden embedding, num_spot x num_hidden.

Returns:

The decoded matrix, num_gene x num_spot.

Return type:

x_dec (2D tensor)

get_recon_loss()

Get the reconstruction loss.

get_orth_loss()

Get the orthogonality loss (weighted by lambda_orth_loss).

get_sp_loss()

Get the spatial loss (weighted by lambda_spatial_loss).

classmethod from_rna_model(rna_model, st_adata: anndata.AnnData, layer: str | None = None, spatial_loss: smoother.losses.SpatialLoss | None = None, lambda_spatial_loss=0.1)

Initialize a spatial model from a pre-trained RNA model.