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 viasetup_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
andu
.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
andu
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:
See the user guide for this model:
See also
Attributes table#
Data attached to model instance. |
|
Manager instance associated with self.adata. |
|
The current device that the module's params are on. |
|
Returns computed metrics during training. |
|
Whether the model has been trained. |
|
Summary string of the model. |
|
Observations that are in test set. |
|
Observations that are in train set. |
|
Observations that are in validation set. |
Methods table#
|
Compute local statistics from counterfactual sample representations. |
|
Converts a legacy saved model (<v0.15.0) to the updated save format. |
|
Deregisters the |
|
Compute the differential abundance between samples. |
|
Compute cell-specific multivariate differential expression. |
|
Computes the aggregated posterior over the |
|
Retrieves the |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Compute the latent representation of the data. |
|
Compute local sample distances. |
|
Compute the local sample representation of the cells in the |
|
Compute admissibility scores for cell-sample pairs. |
|
Instantiate a model from the saved output. |
|
Return the full registry saved with the model. |
|
Registers an |
|
Save the state of the model. |
|
Sets up the |
|
Move model to device. |
|
Train the model. |
|
Print summary of the setup for the initial AnnData or a given AnnData object. |
|
Print args used to setup a saved model. |
Attributes#
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. IfFalse
and directory already exists atoutput_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:
- 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 probabilitiesfor each cell across samples.
"{cov_key}_log_probs"
: For each key insample_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
, wherez_d
is the latent representation of the cell for sampled
andu
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 inadata.obs
.adata (
AnnData
|None
(default:None
)) – AnnData object to use for computing the local sample representation. IfNone
, 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. IfNone
, 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 specifyingadata
.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 ofsample_cov_keys
. Only applies whenstore_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 theBenjamini-Hochberg procedure.
"lfc"
: Log fold changes for each covariate across cells and genes, ifstore_lfc
is
True
.
"lfc_std"
: Standard deviation of log fold changes, ifstore_lfc
isTrue
anddelta
is notNone
.
"pde"
: Posterior DE probabilities, ifstore_lfc
isTrue
anddelta
is notNone
.
"baseline_expression"
: Baseline expression levels for each covariate across cells andgenes, if
store_baseline
isTrue
.
"n_samples"
: Number of admissible samples for each cell, iffilter_inadmissible_samples
isTrue
.
- MRVI.get_aggregated_posterior(adata=None, sample=None, indices=None, batch_size=256)[source]#
Computes the aggregated posterior over the
u
latent representations.For the specified samples, it computes the aggregated posterior over the
u
latent representations. Returns a NumPyro MixtureSameFamily distribution.- 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. IfNone
, 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 anAnnDataManager
specific to this model instance.- Parameters:
- Return type:
- 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.
- 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 withuse_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 ifuse_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 admissibility scores for cell-sample pairs.
This function computes the posterior distribution for u for each cell. Then, for every cell, it computes the log-probability of the cell under the posterior of each cell each sample and takes the maximum value for a given sample as a measure of admissibility for that sample. Additionally, it computes a threshold that determines if a cell-sample pair is admissible based on the within-sample admissibility scores.
- 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 (
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.
- 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 thesetup_anndata()
class method followed up by retrieval of theAnnDataManager
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 previousAnnDataManager
.
- 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 anndatasave_kwargs (
dict
|None
(default:None
)) – Keyword arguments passed intosave()
.legacy_mudata_format (
bool
(default:False
)) – IfTrue
, saves the modelvar_names
in the legacy format if the model was trained with aMuData
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. IfNone
, defaults to a heuristic based onget_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. IfNone
, defaults to1 - train_size
. Iftrain_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
. SeeTrainer
for further options.plan_kwargs (
dict
|None
(default:None
)) – Additional keyword arguments passed intoJaxTrainingPlan
.**trainer_kwargs – Additional keyword arguments passed into
Trainer
.