scvi.external.MRVI#

class scvi.external.MRVI(adata, **model_kwargs)[source]#

Multi-resolution Variational Inference (MrVI) [Boyeau et al., 2024].

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

  • n_latent – Dimensionality of the latent space for z.

  • n_latent_u – Dimensionality of the latent space for u.

  • encoder_n_hidden – Number of nodes per hidden layer in the encoder.

  • encoder_n_layers – Number of hidden layers in the encoder.

  • z_u_prior – Whether to use a prior for z_u.

  • z_u_prior_scale – Scale of the prior for the difference between z and u.

  • u_prior_scale – Scale of the prior for u.

  • u_prior_mixture – Whether to use a mixture model for the u prior.

  • u_prior_mixture_k – Number of components in the mixture model for the u prior.

  • learn_z_u_prior_scale – Whether to learn the scale of the z and u difference prior during training.

  • laplace_scale – Scale parameter for the Laplace distribution in the decoder.

  • scale_observations – Whether to scale loss by the number of observations per sample.

  • px_kwargs – Keyword args for DecoderZXAttention.

  • qz_kwargs – Keyword args for EncoderUZ.

  • qu_kwargs – Keyword args for EncoderXU.

Notes

See further usage examples in the following tutorial:

  1. MrVI Quick Start Tutorial

See the user guide for this model:

  1. MrVI

See also

MRVAE

Attributes table#

adata

Data attached to model instance.

adata_manager

Manager instance associated with self.adata.

device

The current device that the module's params are on.

history

Returns computed metrics during training.

is_trained

Whether the model has been trained.

summary_string

Summary string of the model.

test_indices

Observations that are in test set.

train_indices

Observations that are in train set.

validation_indices

Observations that are in validation set.

Methods table#

compute_local_statistics(reductions[, ...])

Compute local statistics from counterfactual sample representations.

convert_legacy_save(dir_path, output_dir_path)

Converts a legacy saved model (<v0.15.0) to the updated save format.

deregister_manager([adata])

Deregisters the AnnDataManager instance associated with adata.

differential_abundance([adata, ...])

Compute the differential abundance between samples.

differential_expression([adata, ...])

Compute cell-specific multivariate differential expression.

get_aggregated_posterior([adata, sample, ...])

Compute the aggregated posterior over the u latent representations.

get_anndata_manager(adata[, required])

Retrieves the AnnDataManager for a given AnnData object.

get_from_registry(adata, registry_key)

Returns the object in AnnData associated with the key in the data registry.

get_latent_representation([adata, indices, ...])

Compute the latent representation of the data.

get_local_sample_distances([adata, ...])

Compute local sample distances.

get_local_sample_representation([adata, ...])

Compute the local sample representation of the cells in the adata object.

get_outlier_cell_sample_pairs([adata, ...])

Compute outlier cell-sample pairs.

load(dir_path[, adata, accelerator, device, ...])

Instantiate a model from the saved output.

load_registry(dir_path[, prefix])

Return the full registry saved with the model.

register_manager(adata_manager)

Registers an AnnDataManager instance with this model class.

save(dir_path[, prefix, overwrite, ...])

Save the state of the model.

setup_anndata(adata[, layer, sample_key, ...])

Sets up the AnnData object for this model.

to_device(device)

Move model to device.

train([max_epochs, accelerator, devices, ...])

Train the model.

view_anndata_setup([adata, ...])

Print summary of the setup for the initial AnnData or a given AnnData object.

view_setup_args(dir_path[, prefix])

Print args used to setup a saved model.

Attributes#

MRVI.adata[source]#

Data attached to model instance.

MRVI.adata_manager[source]#

Manager instance associated with self.adata.

MRVI.device[source]#

The current device that the module’s params are on.

MRVI.history[source]#

Returns computed metrics during training.

MRVI.is_trained[source]#

Whether the model has been trained.

MRVI.summary_string[source]#

Summary string of the model.

MRVI.test_indices[source]#

Observations that are in test set.

MRVI.train_indices[source]#

Observations that are in train set.

MRVI.validation_indices[source]#

Observations that are in validation set.

Methods#

MRVI.compute_local_statistics(reductions, adata=None, indices=None, batch_size=None, use_vmap=True, norm='l2', mc_samples=10)[source]#

Compute local statistics from counterfactual sample representations.

Local statistics are reductions over either the local counterfactual latent representations or the resulting local sample distance matrices. For a large number of cells and/or samples, this method can avoid scalability issues by grouping over cell-level covariates.

Parameters:
  • reductions (list[MRVIReduction]) – List of reductions to compute over local counterfactual sample representations.

  • adata (AnnData | None (default: None)) – AnnData object to use.

  • indices (Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]], None] (default: None)) – Indices of cells to use.

  • batch_size (int | None (default: None)) – Batch size to use for computing the local statistics.

  • use_vmap (bool (default: True)) – Whether to use vmap to compute the local statistics.

  • norm (str (default: 'l2')) – Norm to use for computing the distances.

  • mc_samples (int (default: 10)) – Number of Monte Carlo samples to use for computing the local statistics. Only applies if using sampled representations.

Return type:

Dataset

classmethod MRVI.convert_legacy_save(dir_path, output_dir_path, overwrite=False, prefix=None, **save_kwargs)[source]#

Converts a legacy saved model (<v0.15.0) to the updated save format.

Parameters:
  • dir_path (str) – Path to directory where legacy model is saved.

  • output_dir_path (str) – Path to save converted save files.

  • overwrite (bool (default: False)) – Overwrite existing data or not. If False and directory already exists at output_dir_path, error will be raised.

  • prefix (str | None (default: None)) – Prefix of saved file names.

  • **save_kwargs – Keyword arguments passed into save().

Return type:

None

MRVI.deregister_manager(adata=None)[source]#

Deregisters the AnnDataManager instance associated with adata.

If adata is None, deregisters all AnnDataManager instances in both the class and instance-specific manager stores, except for the one associated with this model instance.

MRVI.differential_abundance(adata=None, sample_cov_keys=None, sample_subset=None, compute_log_enrichment=False, batch_size=128)[source]#

Compute the differential abundance between samples.

Computes the logarithm of the ratio of the probabilities of each sample conditioned on the estimated aggregate posterior distribution of each cell.

Parameters:
  • adata (AnnData | None (default: None)) – The data object to compute the differential abundance for. If not given, the data object stored in the model is used.

  • sample_cov_keys (list[str] | None (default: None)) – Keys for covariates (batch, etc.) that should also be taken into account when computing the differential abundance. At the moment, only discrete covariates are supported.

  • sample_subset (list[str] | None (default: None)) – Only compute differential abundance for these sample labels.

  • compute_log_enrichment (bool (default: False)) – Whether to compute the log enrichment scores for each covariate value.

  • batch_size (int (default: 128)) – Minibatch size for computing the differential abundance.

Return type:

Dataset

Returns:

A dataset with data variables:

  • "log_probs": Array of shape (n_cells, n_samples) containing the log probabilities

    for each cell across samples.

  • "{cov_key}_log_probs": For each key in sample_cov_keys, an array of shape

    (n_cells, _cov_values) containing the log probabilities for each cell across covariate values.

MRVI.differential_expression(adata=None, sample_cov_keys=None, sample_subset=None, batch_size=128, use_vmap=True, normalize_design_matrix=True, add_batch_specific_offsets=False, mc_samples=100, store_lfc=False, store_lfc_metadata_subset=None, store_baseline=False, eps_lfc=0.0001, filter_inadmissible_samples=False, lambd=0.0, delta=0.3, **filter_samples_kwargs)[source]#

Compute cell-specific multivariate differential expression.

For every cell, we first compute all counterfactual cell-state shifts, defined as e_d = z_d - u, where z_d is the latent representation of the cell for sample d and u is the sample-unaware latent representation. Then, we fit a linear model in each cell of the form: e_d = X_d * beta_d + iid gaussian noise.

Parameters:
  • sample_cov_keys (list[str] | None (default: None)) – List of sample covariates to consider for the multivariate analysis. These keys should be present in adata.obs.

  • adata (AnnData | None (default: None)) – AnnData object to use for computing the local sample representation. If None, the analysis is performed on all cells in the dataset.

  • sample_subset (list[str] | None (default: None)) – Optional list of samples to consider for the multivariate analysis. If None, all samples are considered.

  • batch_size (int (default: 128)) – Batch size to use for computing the local sample representation.

  • use_vmap (bool (default: True)) – Whether to use vmap for computing the local sample representation.

  • normalize_design_matrix (bool (default: True)) – Whether to normalize the design matrix.

  • add_batch_specific_offsets (bool (default: False)) – Whether to offset the design matrix by adding batch-specific offsets to the design matrix. Setting this option to True is recommended when considering multi-site datasets.

  • mc_samples (int (default: 100)) – How many MC samples should be taken for computing betas.

  • store_lfc (bool (default: False)) – Whether to store the log-fold changes in the module. Storing log-fold changes is memory-intensive and may require to specify a smaller set of cells to analyze, e.g., by specifying adata.

  • store_lfc_metadata_subset (list[str] | None (default: None)) – Specifies a subset of metadata for which log-fold changes are computed. These keys must be a subset of sample_cov_keys. Only applies when store_lfc=True.

  • store_baseline (bool (default: False)) – Whether to store the expression in the module if logfoldchanges are computed.

  • eps_lfc (float (default: 0.0001)) – Epsilon to add to the log-fold changes to avoid detecting genes with low expression.

  • filter_inadmissible_samples (bool (default: False)) – Whether to filter out-of-distribution samples prior to performing the analysis.

  • lambd (float (default: 0.0)) – Regularization parameter for the linear model.

  • delta (float | None (default: 0.3)) – LFC threshold used to compute posterior DE probabilities. If None does not compute them to save memory consumption.

  • filter_samples_kwargs – Keyword arguments to pass to get_outlier_cell_sample_pairs().

Return type:

Dataset

Returns:

A dataset containing the results of the differential expression analysis:

  • "beta": Coefficients for each covariate across cells and latent dimensions.

  • "effect_size": Effect sizes for each covariate across cells.

  • "pvalue": P-values for each covariate across cells.

  • "padj": Adjusted P-values for each covariate across cells using the

    Benjamini-Hochberg procedure.

  • "lfc": Log fold changes for each covariate across cells and genes, if store_lfc

    is True.

  • "lfc_std": Standard deviation of log fold changes, if store_lfc is True and

    delta is not None.

  • "pde": Posterior DE probabilities, if store_lfc is True and delta is not

    None.

  • "baseline_expression": Baseline expression levels for each covariate across cells and

    genes, if store_baseline is True.

  • "n_samples": Number of admissible samples for each cell, if

    filter_inadmissible_samples is True.

MRVI.get_aggregated_posterior(adata=None, sample=None, indices=None, batch_size=256)[source]#

Compute the aggregated posterior over the u latent representations.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object to use. Defaults to the AnnData object used to initialize the model.

  • sample (str | int | None (default: None)) – Name or index of the sample to filter on. If None, uses all cells.

  • indices (Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]], None] (default: None)) – Indices of cells to use.

  • batch_size (int (default: 256)) – Batch size to use for computing the latent representation.

Return type:

Distribution

Returns:

A mixture distribution of the aggregated posterior.

MRVI.get_anndata_manager(adata, required=False)[source]#

Retrieves the AnnDataManager for a given AnnData object.

Requires self.id has been set. Checks for an AnnDataManager specific to this model instance.

Parameters:
  • adata (Union[AnnData, MuData]) – AnnData object to find manager instance for.

  • required (bool (default: False)) – If True, errors on missing manager. Otherwise, returns None when manager is missing.

Return type:

AnnDataManager | None

MRVI.get_from_registry(adata, registry_key)[source]#

Returns the object in AnnData associated with the key in the data registry.

AnnData object should be registered with the model prior to calling this function via the self._validate_anndata method.

Parameters:
  • registry_key (str) – key of object to get from data registry.

  • adata (Union[AnnData, MuData]) – AnnData to pull data from.

Return type:

ndarray

Returns:

The requested data as a NumPy array.

MRVI.get_latent_representation(adata=None, indices=None, batch_size=None, use_mean=True, give_z=False)[source]#

Compute the latent representation of the data.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object to use. Defaults to the AnnData object used to initialize the model.

  • indices (Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]], None] (default: None)) – Indices of cells to use.

  • batch_size (int | None (default: None)) – Batch size to use for computing the latent representation.

  • use_mean (bool (default: True)) – Whether to use the mean of the distribution as the latent representation.

  • give_z (bool (default: False)) – Whether to return the z latent representation or the u latent representation.

Return type:

ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]

Returns:

The latent representation of the data.

MRVI.get_local_sample_distances(adata=None, batch_size=256, use_mean=True, normalize_distances=False, use_vmap=True, groupby=None, keep_cell=True, norm='l2', mc_samples=10)[source]#

Compute local sample distances.

Computes cell-specific distances between samples, of size (n_sample, n_sample), stored as a Dataset, with variable name "cell", of size (n_cell, n_sample, n_sample). If in addition, groupby is provided, distances are also aggregated by group. In this case, the group-specific distances via group name key.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object to use for computing the local sample representation.

  • batch_size (int (default: 256)) – Batch size to use for computing the local sample representation.

  • use_mean (bool (default: True)) – Whether to use the mean of the latent representation as the local sample representation.

  • normalize_distances (bool (default: False)) – Whether to normalize the local sample distances. Normalizes by the standard deviation of the original intra-sample distances. Only works with use_mean=False.

  • use_vmap (bool (default: True)) – Whether to use vmap for computing the local sample representation. Disabling vmap can be useful if running out of memory on a GPU.

  • groupby (list[str] | str | None (default: None)) – List of categorical keys or single key of the anndata that is used to group the cells.

  • keep_cell (bool (default: True)) – Whether to keep the original cell sample-sample distance matrices.

  • norm (str (default: 'l2')) – Norm to use for computing the local sample distances.

  • mc_samples (int (default: 10)) – Number of Monte Carlo samples to use for computing the local sample distances. Only relevant if use_mean=False.

Return type:

Dataset

MRVI.get_local_sample_representation(adata=None, indices=None, batch_size=256, use_mean=True, use_vmap=True)[source]#

Compute the local sample representation of the cells in the adata object.

For each cell, it returns a matrix of size (n_sample, n_features).

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object to use for computing the local sample representation.

  • batch_size (int (default: 256)) – Batch size to use for computing the local sample representation.

  • use_mean (bool (default: True)) – Whether to use the mean of the latent representation as the local sample representation.

  • use_vmap (bool (default: True)) – Whether to use vmap for computing the local sample representation. Disabling vmap can be useful if running out of memory on a GPU.

Return type:

DataArray

MRVI.get_outlier_cell_sample_pairs(adata=None, subsample_size=5000, quantile_threshold=0.05, admissibility_threshold=0.0, batch_size=256)[source]#

Compute outlier cell-sample pairs.

This function fits a GMM for each sample based on the latent representation of the cells in the sample or computes an approximate aggregated posterior for each sample. Then, for every cell, it computes the log-probability of the cell under the approximated posterior of each sample as a measure of admissibility.

Parameters:
  • adata (AnnData | None (default: None)) – AnnData object containing the cells for which to compute the outlier cell-sample pairs.

  • subsample_size (int (default: 5000)) – Number of cells to use from each sample to approximate the posterior. If None, uses all of the available cells.

  • quantile_threshold (float (default: 0.05)) – Quantile of the within-sample log probabilities to use as a baseline for admissibility.

  • admissibility_threshold (float (default: 0.0)) – Threshold for admissibility. Cell-sample pairs with admissibility below this threshold are considered outliers.

  • batch_size (int (default: 256)) – Size of the batch to use for computing outlier cell-sample pairs.

Return type:

Dataset

classmethod MRVI.load(dir_path, adata=None, accelerator='auto', device='auto', prefix=None, backup_url=None)[source]#

Instantiate a model from the saved output.

Parameters:
  • dir_path (str) – Path to saved outputs.

  • adata (Union[AnnData, MuData, None] (default: None)) – AnnData organized in the same way as data used to train model. It is not necessary to run setup_anndata, as AnnData is validated against the saved scvi setup dictionary. If None, will check for and load anndata saved with the model.

  • accelerator (str (default: 'auto')) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “ipu”, “hpu”, “mps, “auto”) as well as custom accelerator instances.

  • device (int | str (default: 'auto')) – The device to use. Can be set to a non-negative index (int or str) or “auto” for automatic selection based on the chosen accelerator. If set to “auto” and accelerator is not determined to be “cpu”, then device will be set to the first available device.

  • prefix (str | None (default: None)) – Prefix of saved file names.

  • backup_url (str | None (default: None)) – URL to retrieve saved outputs from if not present on disk.

Returns:

Model with loaded state dictionaries.

Examples

>>> model = ModelClass.load(save_path, adata)
>>> model.get_....
static MRVI.load_registry(dir_path, prefix=None)[source]#

Return the full registry saved with the model.

Parameters:
  • dir_path (str) – Path to saved outputs.

  • prefix (str | None (default: None)) – Prefix of saved file names.

Return type:

dict

Returns:

The full registry saved with the model

classmethod MRVI.register_manager(adata_manager)[source]#

Registers an AnnDataManager instance with this model class.

Stores the AnnDataManager reference in a class-specific manager store. Intended for use in the setup_anndata() class method followed up by retrieval of the AnnDataManager via the _get_most_recent_anndata_manager() method in the model init method.

Notes

Subsequent calls to this method with an AnnDataManager instance referring to the same underlying AnnData object will overwrite the reference to previous AnnDataManager.

MRVI.save(dir_path, prefix=None, overwrite=False, save_anndata=False, save_kwargs=None, legacy_mudata_format=False, **anndata_write_kwargs)[source]#

Save the state of the model.

Neither the trainer optimizer state nor the trainer history are saved. Model files are not expected to be reproducibly saved and loaded across versions until we reach version 1.0.

Parameters:
  • dir_path (str) – Path to a directory.

  • prefix (str | None (default: None)) – Prefix to prepend to saved file names.

  • overwrite (bool (default: False)) – Overwrite existing data or not. If False and directory already exists at dir_path, error will be raised.

  • save_anndata (bool (default: False)) – If True, also saves the anndata

  • save_kwargs (dict | None (default: None)) – Keyword arguments passed into save().

  • legacy_mudata_format (bool (default: False)) – If True, saves the model var_names in the legacy format if the model was trained with a MuData object. The legacy format is a flat array with variable names across all modalities concatenated, while the new format is a dictionary with keys corresponding to the modality names and values corresponding to the variable names for each modality.

  • anndata_write_kwargs – Kwargs for write()

classmethod MRVI.setup_anndata(adata, layer=None, sample_key=None, batch_key=None, labels_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 (default: None)) – if not None, uses this as the key in adata.layers for raw count data.

  • sample_key (str | None (default: None)) – key in adata.obs for sample information. Categories will automatically be converted into integer categories and saved to adata.obs[‘_scvi_sample’]. If None, assigns the same sample to all the data.

  • batch_key (str | None (default: 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 (default: 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.

  • **kwargs – Additional keyword arguments passed into register_fields().

MRVI.to_device(device)[source]#

Move model to device.

Parameters:

device – Device to move model to. Options: ‘cpu’ for CPU, integer GPU index (eg. 0), or ‘cuda:X’ where X is the GPU index (eg. ‘cuda:0’). See torch.device for more info.

Examples

>>> adata = scvi.data.synthetic_iid()
>>> model = scvi.model.SCVI(adata)
>>> model.to_device('cpu')      # moves model to CPU
>>> model.to_device('cuda:0')   # moves model to GPU 0
>>> model.to_device(0)          # also moves model to GPU 0
MRVI.train(max_epochs=None, accelerator='auto', devices='auto', train_size=0.9, validation_size=None, batch_size=128, early_stopping=False, plan_kwargs=None, **trainer_kwargs)[source]#

Train the model.

Parameters:
  • max_epochs (int | None (default: None)) – Maximum number of epochs to train the model. The actual number of epochs may be less if early stopping is enabled. If None, defaults to a heuristic based on get_max_epochs_heuristic().

  • accelerator (str | None (default: 'auto')) – Supports passing different accelerator types (“cpu”, “gpu”, “tpu”, “ipu”, “hpu”, “mps, “auto”) as well as custom accelerator instances.

  • devices (int | list[int] | str (default: 'auto')) – The devices to use. Can be set to a non-negative index (int or str), a sequence of device indices (list or comma-separated str), the value -1 to indicate all available devices, or “auto” for automatic selection based on the chosen accelerator. If set to “auto” and accelerator is not determined to be “cpu”, then devices will be set to the first available device.

  • train_size (float (default: 0.9)) – Size of training set in the range [0.0, 1.0].

  • validation_size (float | None (default: None)) – Size of the validation set. If None, defaults to 1 - train_size. If train_size + validation_size < 1, the remaining cells belong to a test set.

  • batch_size (int (default: 128)) – Minibatch size to use during training.

  • early_stopping (bool (default: False)) – Perform early stopping. Additional arguments can be passed in through **kwargs. See Trainer for further options.

  • plan_kwargs (dict | None (default: None)) – Additional keyword arguments passed into JaxTrainingPlan.

  • **trainer_kwargs – Additional keyword arguments passed into Trainer.

MRVI.view_anndata_setup(adata=None, hide_state_registries=False)[source]#

Print summary of the setup for the initial AnnData or a given AnnData object.

Parameters:
  • adata (Union[AnnData, MuData, None] (default: None)) – AnnData object setup with setup_anndata or transfer_fields().

  • hide_state_registries (bool (default: False)) – If True, prints a shortened summary without details of each state registry.

Return type:

None

static MRVI.view_setup_args(dir_path, prefix=None)[source]#

Print args used to setup a saved model.

Parameters:
  • dir_path (str) – Path to saved outputs.

  • prefix (str | None (default: None)) – Prefix of saved file names.

Return type:

None