scviva.model.ResolVI#
- class scviva.model.ResolVI(adata, n_hidden=32, n_hidden_encoder=128, n_latent=10, n_layers=2, dropout_rate=0.05, dispersion='gene', gene_likelihood='nb', background_ratio=None, median_distance=None, semisupervised=False, mixture_k=50, downsample_counts=True, **model_kwargs)[source]#
ResolVI addresses noise and bias in single-cell resolved spatial transcriptomics data.
- Parameters:
- adata
AnnData AnnData object that has been registered via
setup_anndata().- n_hidden
int Number of nodes per hidden layer.
- n_hidden_encoder
int Number of nodes per hidden layer in the encoder.
- n_latent
int Dimensionality of the latent space.
- n_layers
int Number of hidden layers used for encoder and decoder NNs.
- dropout_rate
float Dropout rate for neural networks.
- dispersion
Literal['gene','gene-batch'] One of the following:
'gene'- dispersion parameter of NB is constant per gene across cells'gene-batch'- dispersion can differ between different batches
- gene_likelihood
Literal['nb','poisson'] One of:
'nb'- Negative binomial distribution'poisson'- Poisson distribution
- background_ratio
Prior for the background proportion. If
None, estimated from the data viacompute_dataset_dependent_priors().- median_distance
Kernel size in the RBF kernel used to weight distances between cells and their neighbors. If
None, estimated from the data viacompute_dataset_dependent_priors().- semisupervised
Whether to use a semi-supervised model using the labels registered via
labels_key.- mixture_k
Number of components in the Mixture-of-Gaussian prior.
- downsample_counts
Whether to downsample counts during training using a log-normal library size distribution estimated from the data.
- **model_kwargs
Keyword args for
RESOLVAE
- adata
Examples
>>> adata = anndata.read_h5ad(path_to_anndata) >>> ResolVI.setup_anndata(adata, batch_key="batch") >>> model = ResolVI(adata) >>> model.train() >>> adata.obsm["X_resolVI"] = model.get_latent_representation() >>> adata.layers["X_normalized_resolVI"] = model.get_normalized_expression()
Attributes table
Data attached to model instance. |
|
Manager instance associated with self.adata. |
|
The current device that the module's params are on. |
|
What the get normalized functions name is |
|
Returns computed metrics during training. |
|
Whether the model has been trained. |
|
Data attached to model instance. |
|
Returns the run id of the model. |
|
Returns the run name of the model. |
|
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 dataset-dependent priors for background ratio and median distance. |
|
Compute spatial neighbor graph and store in |
|
Converts a legacy saved model (<v0.15.0) to the updated save format. |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Deregisters the |
|
Not implemented for this model class. |
|
A unified method for differential expression analysis. |
|
A unified method for niche differential abundance analysis. |
|
Convenience constructor from a SpatialData object. |
|
Retrieves the |
|
Returns the object in AnnData associated with the key in the data registry. |
|
Return the latent representation for each cell (Pyro path). |
|
Returns the abundance of cell-types within spatial proximity of center cells. |
|
Returns normalized gene expression (Pyro path). |
Returns importance-sampled normalized gene expression (Pyro path). |
|
|
Returns the string provided to setup of a specific setup_arg. |
|
Returns the state registry for the AnnDataField registered with this instance. |
|
Variable names of input data. |
|
Instantiate a model from the saved output. |
|
Online update of a reference model with scArches algorithm [Lotfollahi et al., 2021]. |
|
Return the full registry saved with the model. |
|
Plot latent embedding overlaid on tissue spatial coordinates. |
|
Return cell label predictions. |
|
Prepare data for query integration. |
|
Prepare multimodal dataset for query integration. |
|
Registers an |
|
Summarise posterior distribution. |
|
Save the state of the model. |
|
Set up a model from on-disk AnnData files via the annbatch streaming loader. |
|
Sets up the |
|
Register fields from a SpatialData object. |
|
Move the model to the device. |
|
Train the model using amortized variational inference. |
|
Transfer fields from a model to an AnnData object. |
|
Update setup method args. |
|
Print summary of the setup for the initial AnnData or a given AnnData object. |
|
Prints summary of the registry. |
|
Print args used to setup a saved model. |
Prints setup kwargs used to produce a given registry. |
Attributes
- ResolVI.adata#
Data attached to model instance.
- ResolVI.adata_manager#
Manager instance associated with self.adata.
- ResolVI.device#
The current device that the module’s params are on.
- ResolVI.get_normalized_function_name#
What the get normalized functions name is
- ResolVI.history#
Returns computed metrics during training.
- ResolVI.is_trained#
Whether the model has been trained.
- ResolVI.registry#
Data attached to model instance.
- ResolVI.run_id#
Returns the run id of the model. Used in MLFlow
- ResolVI.run_name#
Returns the run name of the model. Used in MLFlow
- ResolVI.summary_string#
Summary string of the model.
- ResolVI.test_indices#
Observations that are in test set.
- ResolVI.train_indices#
Observations that are in train set.
- ResolVI.validation_indices#
Observations that are in validation set.
Methods
- ResolVI.compute_dataset_dependent_priors(n_small_genes=None)[source]#
Compute dataset-dependent priors for background ratio and median distance.
- Parameters:
- n_small_genes
Number of lowest-total-count genes whose per-cell mean expression (relative to the cell’s mean expression over all genes) is averaged to estimate the background ratio. If
None, defaults ton_genes // 50.
- Returns:
Dictionary with keys
"background_ratio","median_distance","mean_log_counts"and"std_log_counts".
- ResolVI.compute_neighbors(adata, spatial_key='spatial', coord_type='generic', n_neighs=6, backend='squidpy')[source]#
Compute spatial neighbor graph and store in
adata.obsm.- Parameters:
- adata
AnnData AnnData object with spatial coordinates in
adata.obsm[spatial_key].- spatial_key
str Key in
adata.obsmfor spatial coordinates.- coord_type
str Coordinate type passed to squidpy (
"generic"or"visium"). Ignored whenbackend="rapids".- n_neighs
int Number of nearest neighbors.
- backend
Literal['squidpy','rapids'] "squidpy"(default): usessquidpy.gr.spatial_neighbors()."rapids": uses cuGraph/cuML for GPU-accelerated computation.
- adata
- Return type:
- classmethod ResolVI.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 the directory where the legacy model is saved.
- output_dir_path
str Path to save converted save files.
- overwrite
bool Overwrite existing data or not. If
Falseand directory already exists atoutput_dir_path, an error will be raised.- prefix
str|None Prefix of saved file names.
- **save_kwargs
Keyword arguments passed into
save().
- dir_path
- Return type:
- ResolVI.data_registry(registry_key)[source]#
Returns the object in AnnData associated with the key in the data registry.
- ResolVI.deregister_manager(adata=None)[source]#
Deregisters the
AnnDataManagerinstance associated withadata.If
adataisNone, deregisters allAnnDataManagerinstances in both the class and instance-specific manager stores, except for the one associated with this model instance.
- ResolVI.differential_abundance(*args, **kwargs)[source]#
Not implemented for this model class.
Available in models that inherit from
VAEMixin.- Raises:
- ResolVI.differential_expression(adata=None, groupby=None, group1=None, group2=None, idx1=None, idx2=None, subset_idx=None, mode='change', delta=0.25, batch_size=None, all_stats=True, batch_correction=False, batchid1=None, batchid2=None, fdr_target=0.05, silent=False, weights='uniform', filter_outlier_cells=False, n_samples=5, size_scaling=False, library_scaling=False, **kwargs)[source]#
A unified method for differential expression analysis.
Implements
"vanilla"DE [Lopez et al., 2018] and"change"mode DE [Boyeau et al., 2019].- Parameters:
- adata
AnnData|None AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.
- groupby
str|None The key of the observations grouping to consider.
- group1
Iterable[str] |None Subset of groups, e.g. [
'g1','g2','g3'], to which comparison shall be restricted, or all groups ingroupby(default).- group2
str|None If
None, compare each group ingroup1to the union of the rest of the groups ingroupby. If a group identifier, compare with respect to this group.- idx1
Sequence[int] |Sequence[bool] |None idx1andidx2can be used as an alternative to the AnnData keys. Custom identifier forgroup1that can be of three sorts: (1) a boolean mask, (2) indices, or (3) a string. If it is a string, then it will query indices that verifies conditions onadata.obs, as described inpandas.DataFrame.query()Ifidx1is notNone, this option overridesgroup1andgroup2.- idx2
Sequence[int] |Sequence[bool] |None Custom identifier for
group2that has the same properties asidx1. By default, includes all cells not specified inidx1.- subset_idx
Sequence[int] |None Can be of three types. First, it can corresponds to a boolean mask that has the same shape as adata. It can also corresponds to a list of indices. Last, it can correspond to string query of adata.obs columns.
- mode
Literal['vanilla','change'] Method for differential expression. See user guide for full explanation.
- delta
float specific case of region inducing differential expression. In this case, we suppose that \(R \setminus [-\delta, \delta]\) does not induce differential expression (change model default case).
- batch_size
int|None Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- all_stats
bool Concatenate count statistics (e.g., mean expression group 1) to DE results.
- batch_correction
bool Whether to correct for batch effects in DE inference.
- batchid1
Iterable[str] |None Subset of categories from
batch_keyregistered insetup_anndata, e.g. ['batch1','batch2','batch3'], forgroup1. Only used ifbatch_correctionisTrue, and by default all categories are used.- batchid2
Iterable[str] |None Same as
batchid1for group2.batchid2must either have null intersection withbatchid1, or be exactly equal tobatchid1. When the two sets are exactly equal, cells are compared by decoding on the same batch. When sets have null intersection, cells fromgroup1andgroup2are decoded on each group ingroup1andgroup2, respectively.- fdr_target
float Tag features as DE based on posterior expected false discovery rate.
- silent
bool If True, disables the progress bar. Default: False.
- weights
Optional[Literal['uniform','importance']] Precomputed weight for importance sampling.
- filter_outlier_cells
bool Whether to filter outlier cells.
- n_samples
int Number of posterior samples to use for estimation.
- size_scaling
bool If True, will scale normalized expression by size factors.
- library_scaling
bool If True, will scale normalized expression to library size.
- **kwargs
Keyword args for DifferentialComputation.get_bayes_factors
- adata
- Return type:
- Returns:
Differential expression DataFrame.
- ResolVI.differential_niche_abundance(adata=None, groupby=None, group1=None, group2=None, neighbor_key=None, idx1=None, idx2=None, subset_idx=None, mode='change', delta=0.25, batch_size=None, fdr_target=0.05, silent=False, filter_outlier_cells=False, pseudocounts=0.001, **kwargs)[source]#
A unified method for niche differential abundance analysis.
- Parameters:
- adata
AnnData|None AnnData object with equivalent structure to initial AnnData. If None, defaults to the AnnData object used to initialize the model.
- groupby
str|None The key of the observations grouping to consider.
- group1
Iterable[str] |None Subset of groups, e.g. [
'g1','g2','g3'], to which comparison shall be restricted, or all groups ingroupby(default).- group2
str|None If
None, compare each group ingroup1to the union of the rest of the groups ingroupby. If a group identifier, compare with respect to this group.- neighbor_key
str|None Obsm key containing the spatial neighbors of each cell.
- idx1
Sequence[int] |Sequence[bool] |None idx1andidx2can be used as an alternative to the AnnData keys. Custom identifier forgroup1that can be of three sorts: (1) a boolean mask, (2) indices, or (3) a string. If it is a string, then it will query indices that verifies conditions onadata.obs, as described inpandas.DataFrame.query()Ifidx1is notNone, this option overridesgroup1andgroup2.- idx2
Sequence[int] |Sequence[bool] |None Custom identifier for
group2that has the same properties asidx1. By default, includes all cells not specified inidx1.- subset_idx
Sequence[int] |None Can be of three types. First, it can corresponds to a boolean mask that has the same shape as adata. It can also corresponds to a list of indices. Last, it can correspond to string query of adata.obs columns.
- mode
Literal['vanilla','change'] Method for differential expression. See user guide for full explanation.
- delta
float specific case of region inducing differential expression. In this case, we suppose that \(R \setminus [-\delta, \delta]\) does not induce differential expression (change model default case).
- batch_size
int|None Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- fdr_target
float Tag features as DE based on posterior expected false discovery rate.
- silent
bool If True, disables the progress bar. Default: False.
- filter_outlier_cells
bool Whether to filter outlier cells.
- pseudocounts
float pseudocount offset used for the mode
change.- **kwargs
Keyword args for DifferentialComputation.get_bayes_factors
- adata
- Return type:
- Returns:
Differential expression DataFrame.
- classmethod ResolVI.from_spatialdata(sdata, table_key='table', region=None, **model_kwargs)[source]#
Convenience constructor from a SpatialData object.
Calls
setup_spatialdata()then constructs and returns the model.- Parameters:
- sdata
A
spatialdata.SpatialDataobject.- table_key
str Key in
sdatapointing to the AnnData table.- region
str|None Region name to subset.
- **model_kwargs
Passed to the model constructor.
- Returns:
Instantiated model.
- ResolVI.get_anndata_manager(adata, required=False)[source]#
Retrieves the
AnnDataManagerfor a given AnnData object.Requires
self.idhas been set. Checks for anAnnDataManagerspecific to this model instance.- Parameters:
- Return type:
- ResolVI.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_anndatamethod.
- ResolVI.get_latent_representation(adata=None, indices=None, give_mean=True, mc_samples=1, batch_size=None, return_dist=False, backend='cpu')[source]#
Return the latent representation for each cell (Pyro path).
- Parameters:
- adata
AnnData|None AnnData object. If
None, defaults to the model’s registered adata.- indices
Sequence[int] |None Indices of cells in adata to use. If
None, all cells are used.- give_mean
bool Give mean of distribution or sample from it.
- mc_samples
int Ignored (kept for API consistency with scVI).
- batch_size
int|None Minibatch size. Defaults to
scvi.settings.batch_size.- return_dist
bool Return distribution parameters instead of sampled values.
- backend
str "cpu"(default) returnsndarrayoutput;"rapids"returnscupy.ndarrayoutput (requirescupy).
- adata
- Return type:
- Returns:
Latent representation or
(mean, variance)tuple ifreturn_dist=True.
- ResolVI.get_neighbor_abundance(adata=None, indices=None, neighbor_key=None, n_samples=1, n_samples_overall=None, batch_size=None, summary_frequency=2, weights=None, return_mean=True, return_numpy=None, **kwargs)[source]#
Returns the abundance of cell-types within spatial proximity of center cells.
Uses Pyro posterior sampling (
PyroSampleMixin.sample_posterior). Models without a Pyro module should override this method in their class body.- Parameters:
- adata
AnnData|None AnnData object. If
None, uses the model’s registered adata.- indices
Sequence[int] |None Cell indices. If
None, all cells are used.- neighbor_key
str|None Obsm key containing the spatial neighbors of each cell.
- n_samples
int Number of posterior samples.
- n_samples_overall
int Number of posterior samples. Overrides
n_samples.- batch_size
int|None Minibatch size for data loading.
- summary_frequency
int Compute summary after this many batches (reduces memory footprint).
- weights
str|None Spatial weights per neighbor. If
None, no spatial weighting is applied.- return_mean
bool Return the mean over samples.
- return_numpy
bool|None - **kwargs
Additional keyword arguments (ignored, for compatibility).
- adata
- Return type:
- Returns:
Cell-type abundance array or DataFrame of shape
(n_cells, n_cell_types).
- ResolVI.get_normalized_expression(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1, size_scaling=False, n_samples=1, n_samples_overall=None, batch_size=None, return_mean=True, return_numpy=None, silent=True, **kwargs)[source]#
Returns normalized gene expression (Pyro path).
- Parameters:
- adata
AnnData|None AnnData object. If
None, defaults to the model’s registered adata.- indices
Sequence[int] |None Indices of cells to use.
- transform_batch
Sequence[int|str] |None Batch to condition on.
- gene_list
Sequence[str] |None Subset of genes to return.
- library_size
float|None Scale expression to this common library size.
- size_scaling
bool Divide by size factor (requires
size_factor_keyinsetup_anndata).- n_samples
int Number of posterior samples.
- n_samples_overall
int Overrides
n_samples.- batch_size
int|None Minibatch size.
- return_mean
bool Return the mean over samples.
- return_numpy
bool|None - silent
bool Suppress progress bar.
- **kwargs
Additional keyword arguments. Currently unused.
- adata
- Return type:
- Returns:
Normalized expression array or DataFrame of shape
(n_cells, n_genes).
- ResolVI.get_normalized_expression_importance(adata=None, indices=None, transform_batch=None, gene_list=None, library_size=1, n_samples=30, n_samples_overall=None, batch_size=None, weights=None, return_mean=True, return_numpy=None, library_scaling=False, size_scaling=False)[source]#
Returns importance-sampled normalized gene expression (Pyro path).
- Parameters:
- adata
AnnData|None AnnData object. If
None, defaults to the model’s registered adata.- indices
Sequence[int] |None Indices of cells to use.
- transform_batch
Sequence[int|str] |None Not supported. Kept for API consistency.
- gene_list
Sequence[str] |None Subset of genes to return.
- library_size
float|None Scale expression to this common library size.
- n_samples
int Number of posterior samples.
- n_samples_overall
int Overrides
n_samples; returns a flat sample array.- batch_size
int|None Minibatch size.
- weights
str|ndarray|None Precomputed importance weights.
"uniform"disables importance sampling.- return_mean
bool Return the mean over samples.
- return_numpy
bool|None - library_scaling
bool Multiply decoded expression by library size.
- size_scaling
bool Divide by size factor (requires
size_factor_keyinsetup_anndata).
- adata
- Return type:
- Returns:
Normalized expression array or DataFrame of shape
(n_cells, n_genes).
- ResolVI.get_setup_arg(setup_arg)[source]#
Returns the string provided to setup of a specific setup_arg.
- Return type:
- ResolVI.get_state_registry(registry_key)[source]#
Returns the state registry for the AnnDataField registered with this instance.
- Return type:
- ResolVI.get_var_names(legacy_mudata_format=False)[source]#
Variable names of input data.
- Return type:
- classmethod ResolVI.load(dir_path, adata=None, accelerator='auto', device='auto', prefix=None, backup_url=None, datamodule=None, allowed_classes_names_list=None)[source]#
Instantiate a model from the saved output.
- Parameters:
- dir_path
str Path to saved outputs.
- adata
AnnData|MuData|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
scvisetup dictionary. If None, will check for and load anndata saved with the model. If False, will load the model without AnnData.- accelerator
str Supports passing different accelerator types
("cpu", "gpu", "tpu", "ipu", "hpu", "mps, "auto")as well as custom accelerator instances.- device
int|str The device to use. Can be set to a non-negative index (
intorstr) or"auto"for automatic selection based on the chosen accelerator. If set to"auto"andacceleratoris not determined to be"cpu", thendevicewill be set to the first available device.- prefix
str|None Prefix of saved file names.
- backup_url
str|None URL to retrieve saved outputs from if not present on disk.
- datamodule
LightningDataModule|None EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.- allowed_classes_names_list
list[str] |None list of allowed classes names to be loaded (besides the original class name)
- dir_path
- Returns:
Model with loaded state dictionaries.
Examples
>>> model = ModelClass.load(save_path, adata) >>> model.get_....
- classmethod ResolVI.load_query_data(adata=None, reference_model=None, registry=None, inplace_subset_query_vars=False, accelerator='auto', device='auto', unfrozen=False, freeze_dropout=False, freeze_expression=True, freeze_decoder_first_layer=True, freeze_batchnorm_encoder=True, freeze_batchnorm_decoder=False, freeze_classifier=True, transfer_batch=True, datamodule=None)[source]#
Online update of a reference model with scArches algorithm [Lotfollahi et al., 2021].
- Parameters:
- adata
AnnData|MuData 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
registry.- reference_model
str|BaseModelClass Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- inplace_subset_query_vars
bool Whether to subset and rearrange query vars inplace based on vars used to train the reference model.
- accelerator
str Supports passing different accelerator types
("cpu", "gpu", "tpu", "ipu", "hpu", "mps, "auto")as well as custom accelerator instances.- device
int|str The device to use. Can be set to a non-negative index (
intorstr) or"auto"for automatic selection based on the chosen accelerator. If set to"auto"andacceleratoris not determined to be"cpu", thendevicewill be set to the first available device.- unfrozen
bool Override all other freeze options for a fully unfrozen model
- freeze_dropout
bool Whether to freeze dropout during training
- freeze_expression
bool Freeze neurons corresponding to expression in first layer
- freeze_decoder_first_layer
bool Freeze neurons corresponding to first layer in decoder
- freeze_batchnorm_encoder
bool Whether to freeze batchnorm weight and bias during training for encoder
- freeze_batchnorm_decoder
bool Whether to freeze batchnorm weight and bias during training for decoder
- freeze_classifier
bool Whether to freeze classifier completely. Only applies to
SCANVI.- transfer_batch
bool Allow for surgery on the batch covariate. Only applies to
SYSVI.- datamodule
LightningDataModule|None EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.
- adata
- static ResolVI.load_registry(dir_path, prefix=None)[source]#
Return the full registry saved with the model.
- ResolVI.plot_spatial_embedding(adata=None, basis='spatial', color=None, **kwargs)[source]#
Plot latent embedding overlaid on tissue spatial coordinates.
A thin wrapper around
scanpy.pl.embedding()that defaultsbasisto the spatial coordinate key so cells are displayed in tissue space.- Parameters:
- adata
AnnData object. If None, uses the model’s registered adata.
- basis
str Key in
adata.obsmcontaining 2D spatial coordinates.- color
Keys to color cells by (obs columns, gene names, etc.).
- **kwargs
Forwarded to
scanpy.pl.embedding().
- ResolVI.predict(adata=None, indices=None, soft=False, batch_size=500, num_samples=30)[source]#
Return cell label predictions.
- Parameters:
- adata
AnnData|None AnnData object that has been registered via setup_anndata.
- indices
Sequence[int] |None Subsample AnnData to these indices.
- soft
bool If True, returns per class probabilities
- batch_size
int|None Minibatch size for data loading into the model.
- num_samples
int|None Samples to draw from the posterior for cell-type prediction.
- adata
- Return type:
- static ResolVI.prepare_query_anndata(adata, reference_model, return_reference_var_names=False, inplace=True)[source]#
Prepare data for query integration.
This function will return a new AnnData object with padded zeros for missing features, as well as correctly sorted features.
- Parameters:
- adata
AnnData 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
registry.- reference_model
str|BaseModelClass Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- return_reference_var_names
bool Only load and return reference var names if True.
- inplace
bool Whether to subset and rearrange query vars inplace or return new AnnData.
- adata
- Return type:
- Returns:
Query adata ready to use in
load_query_dataunlessreturn_reference_var_namesin which case a pd.Index of reference var names is returned.
- static ResolVI.prepare_query_mudata(mdata, reference_model, return_reference_var_names=False, inplace=True)[source]#
Prepare multimodal dataset for query integration.
This function will return a new MuData object such that the AnnData objects for individual modalities are given padded zeros for missing features, as well as correctly sorted features.
- Parameters:
- mdata
MuData MuData organized in the same way as data used to train the model. It is not necessary to run setup_mudata, as MuData is validated against the
registry.- reference_model
str|BaseModelClass Either an already instantiated model of the same class or a path to saved outputs for the reference model.
- return_reference_var_names
bool Only load and return reference var names if True.
- inplace
bool Whether to subset and rearrange query vars inplace or return new MuData.
- mdata
- Return type:
- Returns:
Query mudata ready to use in
load_query_dataunlessreturn_reference_var_namesin which case a dictionary of pd.Index of reference var names is returned.
- classmethod ResolVI.register_manager(adata_manager)[source]#
Registers an
AnnDataManagerinstance with this model class.Stores the
AnnDataManagerreference in a class-specific manager store. Intended for use in thesetup_anndata()class method followed up by retrieval of theAnnDataManagervia the_get_most_recent_anndata_manager()method in the model init method.Notes
Subsequent calls to this method with an
AnnDataManagerinstance referring to the same underlying AnnData object will overwrite the reference to previousAnnDataManager.
- ResolVI.sample_posterior(adata=None, input_dl=None, indices=None, num_samples=1000, return_sites=None, accelerator='auto', device='auto', batch_size=None, return_observed=False, return_samples=False, summary_frequency=None, summary_fun=None, **sample_kwargs)[source]#
Summarise posterior distribution.
Generate samples from posterior distribution for each parameter and compute mean, 5th/95th quantiles, standard deviation.
- Parameters:
- adata
AnnData|None AnnData object to use for sampling. If
None, uses the registered AnnData object.- input_dl
AnnDataLoader|None DataLoader object to use for sampling. If
None, creates one based onadata.- indices
ndarray|None Indices of cells to use for sampling. If
None, uses all cells.- num_samples
int Number of posterior samples to generate.
- return_sites
list|None List of variables for which to generate posterior samples, defaults to all variables.
- accelerator
str Supports passing different accelerator types
("cpu", "gpu", "tpu", "ipu", "hpu", "mps, "auto")as well as custom accelerator instances.- device
int|str The device to use. Can be set to a non-negative index (
intorstr) or"auto"for automatic selection based on the chosen accelerator. If set to"auto"andacceleratoris not determined to be"cpu", thendevicewill be set to the first available device.- batch_size
int|None Minibatch size for data loading into model. Defaults to
scvi.settings.batch_size.- return_observed
bool Return observed sites/variables? Observed count matrix can be very large so not returned by default.
- return_samples
bool Return all generated posterior samples in addition to sample mean, 5th/95th quantile and SD?
- summary_frequency
int|None Compute summary_fn after summary_frequency batches. Reduces memory footprint.
- summary_fun
dict[str,Callable] |None a dict in the form {“means”: np.mean, “std”: np.std} which specifies posterior distribution summaries to compute and which names to use. See below for default returns.
- sample_kwargs
Keyword arguments for
_get_posterior_samples.
- adata
- Returns:
- post_sample_meansdict[str, numpy.ndarray]
Mean of the posterior distribution for each variable, a dictionary of numpy arrays for each variable;
- post_sample_q05dict[str, numpy.ndarray]
5th quantile of the posterior distribution for each variable;
- post_sample_q95dict[str, numpy.ndarray]
95th quantile of the posterior distribution for each variable;
- post_sample_stdsdict[str, numpy.ndarray]
Standard deviation of the posterior distribution for each variable;
- posterior_samplesdict[str, numpy.ndarray], optional
Posterior distribution samples for each variable as numpy arrays of shape
(n_samples, ...).
Notes
Note for developers: requires overwritten
list_obs_plate_varsproperty, which lists observation/minibatch plate name and variables. Seelist_obs_plate_varsfor details of the variables it should contain. This dictionary can be returned by model class propertyself.module.model.list_obs_plate_varsto keep all model-specific variables in one place.
- ResolVI.save(dir_path, prefix=None, overwrite=False, save_anndata=False, save_kwargs=None, legacy_mudata_format=False, datamodule=None, **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 Prefix to prepend to saved file names.
- overwrite
bool Overwrite existing data or not. If
Falseand directory already exists atdir_path, an error will be raised.- save_anndata
bool If True, also saves the anndata
- save_kwargs
dict|None Keyword arguments passed into
save().- legacy_mudata_format
bool If
True, saves the modelvar_namesin the legacy format if the model was trained with aMuDataobject. 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.- datamodule
LightningDataModule|None EXPERIMENTALALightningDataModuleinstance to use for training in place of the defaultDataSplitter. Can only be passed in if the model was not initialized withAnnData.- anndata_write_kwargs
Kwargs for
write()
- dir_path
- classmethod ResolVI.setup_annbatch(collection_path=None, paths=None, batch_key=None, labels_key=None, sample_key=None, unlabeled_category='Unknown', layer=None, categorical_covariate_keys=None, continuous_covariate_keys=None, rebuild=True, batch_size=4096, chunk_size=256, preload_nchunks=32, preload_to_gpu=True, dataset_size='20GB', shuffle=False, var_subset=None, merge=None, adatas=None, use_class_sampler=False, class_sampler_key=None, class_weights=None)[source]#
Set up a model from on-disk AnnData files via the annbatch streaming loader.
Builds (or reuses) a zarr-backed
DatasetCollectionfrom the supplied h5ad file paths, then wraps it in aAnnbatchDataModuleready for training.- Parameters:
- collection_path
str|None Directory where the zarr collection is written (or already exists). If
None(default), a path is auto-generated as"./{ModelName}_annbatch.zarr"in the current working directory.- paths
list[str] |None Paths to h5ad files that make up the training dataset. If
None, an existing collection atcollection_pathis opened without rebuilding — useful when the zarr store was created by a previous call. Must be provided when the store does not exist yet.- batch_key
str|None Column in
obsto use as the batch variable.- labels_key
str|None Column in
obsto use as the cell-type / label variable.- sample_key
str|None Column in
obsto use as the sample variable. Used by models like MrVI.- unlabeled_category
str Value used to mark unlabeled cells in
labels_key. Required by semi-supervised models such as SCANVI. Defaults to"Unknown".- layer
str|None Layer in the h5ad files to use as the count matrix.
Noneusesadata.X(falling back toadata.raw.Xwhen a raw slot exists).- categorical_covariate_keys
list[str] |None Additional categorical covariate columns in
obs.- continuous_covariate_keys
list[str] |None Additional continuous covariate columns in
obs.- rebuild
bool If
True, always rebuild the zarr collection even if it already exists on disk. IfFalse(default), reuse an existing collection and skip the (potentially expensive)add_adatasstep.- batch_size
int Number of cells per batch yielded by the
Loader.- chunk_size
int Number of cells loaded from disk contiguously per read.
- preload_nchunks
int Number of chunks to preload and shuffle in memory.
- preload_to_gpu
bool Whether the loader should move data to GPU before yielding.
- dataset_size
int|str Number of observations to load into memory for shuffling / pre-processing when building the collection, or annbatch’s human-readable size strings, e.g.
"20GB".- shuffle
bool Whether to pre-shuffle cells when building the collection.
- var_subset
list[str] |None Optional list of gene names to restrict the collection to (passed as
var_subsettoadd_adatas).- merge
Optional[Literal['same','unique','first','only']] How annbatch should merge
varmetadata across inputs. Passed through toannbatch.DatasetCollection.add_adatas().
- collection_path
- Returns:
AnnbatchDataModuleA configured datamodule whoseregistrycan be passed directly to the model constructor, e.g.model = SCVI(registry=dm.registry).
Notes
After training, saving and reloading the model requires reconstructing the datamodule manually and passing it to
load()via thedatamoduleargument — the same pattern used by all custom datamodules.
- classmethod ResolVI.setup_anndata(adata, layer=None, batch_key=None, labels_key=None, size_factor_key=None, categorical_covariate_keys=None, prepare_data=True, prepare_data_kwargs=None, unlabeled_category='unknown', **kwargs)[source]#
Sets up the
AnnDataobject 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 if not
None, uses this as the key inadata.layersfor raw count data.- batch_key
str|None key in
adata.obsfor batch information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_batch']. IfNone, assigns the same batch to all the data.- labels_key
str|None key in
adata.obsfor label information. Categories will automatically be converted into integer categories and saved toadata.obs['_scvi_labels']. IfNone, assigns the same label to all the data.- size_factor_key
str|None Key in
adata.obscorresponding to pre-computed size factors.- categorical_covariate_keys
list[str] |None keys in
adata.obsthat correspond to categorical data. These covariates can be added in addition to the batch covariate and are also treated as nuisance factors (i.e., the model tries to minimize their effects on the latent space). Thus, these should not be used for biologically-relevant factors that you do _not_ want to correct for.- prepare_data
bool|None If
True, automatically compute spatial neighbors via_prepare_data(). Set toFalseif neighbors are already inadata.obsm.- prepare_data_kwargs
dict|None Keyword args for
_prepare_data()(e.g.n_neighbors,spatial_rep).- unlabeled_category
str value in
adata.obs[labels_key]that indicates unlabeled observations.- **kwargs
Keyword args for
register_fields().
- adata
- classmethod ResolVI.setup_spatialdata(sdata, table_key='table', region=None, **kwargs)[source]#
Register fields from a SpatialData object.
Extracts the AnnData table at
sdata[table_key]and callssetup_anndata(). Follows the same classmethod convention assetup_anndata()— call this before constructing the model.- Parameters:
- sdata
A
spatialdata.SpatialDataobject.- table_key
str Key in
sdatapointing to the AnnData table.- region
str|None Region name to subset (stored in
sdata[table_key].obs). If None, the full table is used.- **kwargs
Passed to
setup_anndata().
- Return type:
- ResolVI.to_device(device)[source]#
Move the model to the device.
- Parameters:
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
- ResolVI.train(max_epochs=50, lr=0.003, lr_extra=0.01, extra_lr_parameters=('per_neighbor_diffusion_map', 'u_prior_means'), batch_size=512, weight_decay=0.0, eps=0.0001, n_steps_kl_warmup=None, n_epochs_kl_warmup=20, plan_kwargs=None, expose_params=(), **kwargs)[source]#
Train the model using amortized variational inference.
- Parameters:
- max_epochs
int Number of passes through the dataset.
- lr
float Learning rate for optimization.
- lr_extra
float Learning rate for parameters (non-amortized and custom ones)
- extra_lr_parameters
tuple List of parameters to train with
lr_extralearning rate.- batch_size
int Minibatch size to use during training.
- weight_decay
float weight decay regularization term for optimization
- eps
float Optimizer eps
- n_steps_kl_warmup
int|None Number of training steps (minibatches) to scale weight on KL divergences from 0 to 1. Only activated when
n_epochs_kl_warmupis set to None.- n_epochs_kl_warmup
int|None Number of epochs to scale weight on KL divergences from 0 to 1. Overrides
n_steps_kl_warmupwhen both are notNone.- plan_kwargs
dict|None Keyword args for the Pyro training plan.
- expose_params
list List of parameters to train if running model in Arches mode.
- **kwargs
Other keyword args for the Trainer.
- max_epochs
Notes
RESOLVI trains with Pyro SVI and maintains per-cell global parameters, so it does not support a held-out validation set.
train_sizemust be1.0andearly_stoppingis not available.
- ResolVI.transfer_fields(adata, **kwargs)[source]#
Transfer fields from a model to an AnnData object.
- Return type:
- ResolVI.update_setup_method_args(setup_method_args)[source]#
Update setup method args.
- Parameters:
- setup_method_args
dict This is a bit of a misnomer, this is a dict representing kwargs of the setup method that will be used to update the existing values in the registry of this instance.
- setup_method_args
- ResolVI.view_anndata_setup(adata=None, hide_state_registries=False)[source]#
Print summary of the setup for the initial AnnData or a given AnnData object.