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 via compute_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 via compute_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

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

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.

get_normalized_function_name

What the get normalized functions name is

history

Returns computed metrics during training.

is_trained

Whether the model has been trained.

registry

Data attached to model instance.

run_id

Returns the run id of the model.

run_name

Returns the run name of the model.

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_dataset_dependent_priors([n_small_genes])

Compute dataset-dependent priors for background ratio and median distance.

compute_neighbors(adata[, spatial_key, ...])

Compute spatial neighbor graph and store in adata.obsm.

convert_legacy_save(dir_path, output_dir_path)

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

data_registry(registry_key)

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

deregister_manager([adata])

Deregisters the AnnDataManager instance associated with adata.

differential_abundance(*args, **kwargs)

Not implemented for this model class.

differential_expression([adata, groupby, ...])

A unified method for differential expression analysis.

differential_niche_abundance([adata, ...])

A unified method for niche differential abundance analysis.

from_spatialdata(sdata[, table_key, region])

Convenience constructor from a SpatialData object.

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, ...])

Return the latent representation for each cell (Pyro path).

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

Returns the abundance of cell-types within spatial proximity of center cells.

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

Returns normalized gene expression (Pyro path).

get_normalized_expression_importance([...])

Returns importance-sampled normalized gene expression (Pyro path).

get_setup_arg(setup_arg)

Returns the string provided to setup of a specific setup_arg.

get_state_registry(registry_key)

Returns the state registry for the AnnDataField registered with this instance.

get_var_names([legacy_mudata_format])

Variable names of input data.

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

Instantiate a model from the saved output.

load_query_data([adata, reference_model, ...])

Online update of a reference model with scArches algorithm [Lotfollahi et al., 2021].

load_registry(dir_path[, prefix])

Return the full registry saved with the model.

plot_spatial_embedding([adata, basis, color])

Plot latent embedding overlaid on tissue spatial coordinates.

predict([adata, indices, soft, batch_size, ...])

Return cell label predictions.

prepare_query_anndata(adata, reference_model)

Prepare data for query integration.

prepare_query_mudata(mdata, reference_model)

Prepare multimodal dataset for query integration.

register_manager(adata_manager)

Registers an AnnDataManager instance with this model class.

sample_posterior([adata, input_dl, indices, ...])

Summarise posterior distribution.

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

Save the state of the model.

setup_annbatch([collection_path, paths, ...])

Set up a model from on-disk AnnData files via the annbatch streaming loader.

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

Sets up the AnnData object for this model.

setup_spatialdata(sdata[, table_key, region])

Register fields from a SpatialData object.

to_device(device)

Move the model to the device.

train([max_epochs, lr, lr_extra, ...])

Train the model using amortized variational inference.

transfer_fields(adata, **kwargs)

Transfer fields from a model to an AnnData object.

update_setup_method_args(setup_method_args)

Update setup method args.

view_anndata_setup([adata, ...])

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

view_registry([hide_state_registries])

Prints summary of the registry.

view_setup_args(dir_path[, prefix])

Print args used to setup a saved model.

view_setup_method_args()

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 to n_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.obsm for spatial coordinates.

coord_type str

Coordinate type passed to squidpy ("generic" or "visium"). Ignored when backend="rapids".

n_neighs int

Number of nearest neighbors.

backend Literal['squidpy', 'rapids']

"squidpy" (default): uses squidpy.gr.spatial_neighbors(). "rapids": uses cuGraph/cuML for GPU-accelerated computation.

Return type:

None

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 False and directory already exists at output_dir_path, an error will be raised.

prefix str | None

Prefix of saved file names.

**save_kwargs

Keyword arguments passed into save().

Return type:

None

ResolVI.data_registry(registry_key)[source]#

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

Parameters:
registry_key str

key of an object to get from self.data_registry

Return type:

ndarray | DataFrame

Returns:

The requested data.

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

ResolVI.differential_abundance(*args, **kwargs)[source]#

Not implemented for this model class.

Available in models that inherit from VAEMixin.

Raises:

NotImplementedError –

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 in groupby (default).

group2 str | None

If None, compare each group in group1 to the union of the rest of the groups in groupby. If a group identifier, compare with respect to this group.

idx1 Sequence[int] | Sequence[bool] | None

idx1 and idx2 can be used as an alternative to the AnnData keys. Custom identifier for group1 that 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 on adata.obs, as described in pandas.DataFrame.query() If idx1 is not None, this option overrides group1 and group2.

idx2 Sequence[int] | Sequence[bool] | None

Custom identifier for group2 that has the same properties as idx1. By default, includes all cells not specified in idx1.

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_key registered in setup_anndata, e.g. ['batch1', 'batch2', 'batch3'], for group1. Only used if batch_correction is True, and by default all categories are used.

batchid2 Iterable[str] | None

Same as batchid1 for group2. batchid2 must either have null intersection with batchid1, or be exactly equal to batchid1. When the two sets are exactly equal, cells are compared by decoding on the same batch. When sets have null intersection, cells from group1 and group2 are decoded on each group in group1 and group2, 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

Return type:

DataFrame

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 in groupby (default).

group2 str | None

If None, compare each group in group1 to the union of the rest of the groups in groupby. 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

idx1 and idx2 can be used as an alternative to the AnnData keys. Custom identifier for group1 that 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 on adata.obs, as described in pandas.DataFrame.query() If idx1 is not None, this option overrides group1 and group2.

idx2 Sequence[int] | Sequence[bool] | None

Custom identifier for group2 that has the same properties as idx1. By default, includes all cells not specified in idx1.

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

Return type:

DataFrame

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.SpatialData object.

table_key str

Key in sdata pointing 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 AnnDataManager for a given AnnData object.

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

Parameters:
adata AnnData | MuData

AnnData object to find a manager instance for.

required bool

If True, errors on missing manager. Otherwise, returns None when manager is missing.

Return type:

AnnDataManager | None

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_anndata method.

Parameters:
registry_key str

key of object to get from the data registry.

adata AnnData | MuData

AnnData to pull data from.

Return type:

ndarray

Returns:

The requested data as a NumPy array.

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) returns ndarray output; "rapids" returns cupy.ndarray output (requires cupy).

Return type:

ndarray | tuple[ndarray, ndarray]

Returns:

Latent representation or (mean, variance) tuple if return_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

Return ndarray instead of DataFrame.

**kwargs

Additional keyword arguments (ignored, for compatibility).

Return type:

ndarray | DataFrame

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_key in setup_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

Return ndarray instead of DataFrame.

silent bool

Suppress progress bar.

**kwargs

Additional keyword arguments. Currently unused.

Return type:

ndarray | DataFrame

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

Return ndarray instead of DataFrame.

library_scaling bool

Multiply decoded expression by library size.

size_scaling bool

Divide by size factor (requires size_factor_key in setup_anndata).

Return type:

ndarray | DataFrame

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:

attrdict

ResolVI.get_state_registry(registry_key)[source]#

Returns the state registry for the AnnDataField registered with this instance.

Return type:

attrdict

ResolVI.get_var_names(legacy_mudata_format=False)[source]#

Variable names of input data.

Return type:

dict

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 scvi setup 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 (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

Prefix of saved file names.

backup_url str | None

URL to retrieve saved outputs from if not present on disk.

datamodule LightningDataModule | None

EXPERIMENTAL A LightningDataModule instance to use for training in place of the default DataSplitter. Can only be passed in if the model was not initialized with AnnData.

allowed_classes_names_list list[str] | None

list of allowed classes names to be loaded (besides the original class name)

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

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

EXPERIMENTAL A LightningDataModule instance to use for training in place of the default DataSplitter. Can only be passed in if the model was not initialized with AnnData.

static ResolVI.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

Prefix of saved file names.

Return type:

dict

Returns:

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 defaults basis to 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.obsm containing 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.

Return type:

ndarray | DataFrame

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.

Return type:

AnnData | Index | None

Returns:

Query adata ready to use in load_query_data unless return_reference_var_names in 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.

Return type:

MuData | dict[str, Index] | None

Returns:

Query mudata ready to use in load_query_data unless return_reference_var_names in which case a dictionary of pd.Index of reference var names is returned.

classmethod ResolVI.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.

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 on adata.

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

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.

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_vars property, which lists observation/minibatch plate name and variables. See list_obs_plate_vars for details of the variables it should contain. This dictionary can be returned by model class property self.module.model.list_obs_plate_vars to 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 False and directory already exists at dir_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 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.

datamodule LightningDataModule | None

EXPERIMENTAL A LightningDataModule instance to use for training in place of the default DataSplitter. Can only be passed in if the model was not initialized with AnnData.

anndata_write_kwargs

Kwargs for write()

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 DatasetCollection from the supplied h5ad file paths, then wraps it in a AnnbatchDataModule ready 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 at collection_path is 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 obs to use as the batch variable.

labels_key str | None

Column in obs to use as the cell-type / label variable.

sample_key str | None

Column in obs to 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. None uses adata.X (falling back to adata.raw.X when 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. If False (default), reuse an existing collection and skip the (potentially expensive) add_adatas step.

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_subset to add_adatas).

merge Optional[Literal['same', 'unique', 'first', 'only']]

How annbatch should merge var metadata across inputs. Passed through to annbatch.DatasetCollection.add_adatas().

Returns:

AnnbatchDataModule A configured datamodule whose registry can 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 the datamodule argument — 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 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

if not None, uses this as the key in adata.layers for raw count data.

batch_key str | 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

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.

size_factor_key str | None

Key in adata.obs corresponding to pre-computed size factors.

categorical_covariate_keys list[str] | None

keys in adata.obs that 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 to False if neighbors are already in adata.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().

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 calls setup_anndata(). Follows the same classmethod convention as setup_anndata() — call this before constructing the model.

Parameters:
sdata

A spatialdata.SpatialData object.

table_key str

Key in sdata pointing 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:

None

ResolVI.to_device(device)[source]#

Move the model to the device.

Parameters:
device str | int | device

Device to move model to. Options: ‘cpu’ for CPU, integer GPU index (e.g., 0), ‘cuda:X’ where X is the GPU index (e.g. ‘cuda:0’), or a torch.device object (including XLA devices for TPU). 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
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_extra learning 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_warmup is 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_warmup when both are not None.

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.

Notes

RESOLVI trains with Pyro SVI and maintains per-cell global parameters, so it does not support a held-out validation set. train_size must be 1.0 and early_stopping is not available.

ResolVI.transfer_fields(adata, **kwargs)[source]#

Transfer fields from a model to an AnnData object.

Return type:

AnnData

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.

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.

Parameters:
adata AnnData | MuData | None

AnnData object setup with setup_anndata or transfer_fields().

hide_state_registries bool

If True, prints a shortened summary without details of each state registry.

Return type:

None

ResolVI.view_registry(hide_state_registries=False)[source]#

Prints summary of the registry.

Parameters:
hide_state_registries bool

If True, prints a shortened summary without details of each state registry.

Return type:

None

static ResolVI.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

Prefix of saved file names.

Return type:

None

ResolVI.view_setup_method_args()[source]#

Prints setup kwargs used to produce a given registry.

Parameters:
registry

Registry produced by an AnnDataManager.

Return type:

None