spatialvi.external.AMICI#

class spatialvi.external.AMICI(adata, n_hidden=128, n_latent=10, n_layers=2, n_attention_heads=4, dropout_rate=0.1, gene_likelihood='nb', use_cell_type_attention=True, interaction_layers=2, **model_kwargs)[source]#

Bases: SpatialTrainingMixin, SpatialMixin, BaseSpatialModel

AMICI model for cell-cell interaction inference.

AMICI (Attention-based Multi-scale Interaction for Cell-cell Inference) uses cross-attention mechanisms to model how neighboring cells influence gene expression through cell-cell interactions.

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

  • n_hidden (int) – Number of nodes per hidden layer.

  • n_latent (int) – Dimensionality of the latent space.

  • n_layers (int) – Number of hidden layers.

  • n_attention_heads (int) – Number of attention heads for cross-attention.

  • dropout_rate (float) – Dropout rate for neural networks.

  • gene_likelihood (Literal['zinb', 'nb', 'poisson']) – Distribution for gene expression.

  • use_cell_type_attention (bool) – Whether to use cell type-specific attention.

  • interaction_layers (int) – Number of interaction modeling layers.

  • **model_kwargs – Additional keyword arguments for AMICIModule.

  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • n_attention_heads (int)

  • dropout_rate (float)

  • gene_likelihood (Literal['zinb', 'nb', 'poisson'])

  • use_cell_type_attention (bool)

  • interaction_layers (int)

Examples

>>> import spatialvi
>>> adata = spatialvi.data.synthetic_spatial()
>>> AMICI.setup_anndata(
...     adata,
...     spatial_key="spatial",
...     labels_key="cell_type",
... )
>>> model = AMICI(adata)
>>> model.train()
>>> interactions = model.get_interaction_scores()
__init__(adata, n_hidden=128, n_latent=10, n_layers=2, n_attention_heads=4, dropout_rate=0.1, gene_likelihood='nb', use_cell_type_attention=True, interaction_layers=2, **model_kwargs)[source]#
Parameters:
  • adata (AnnData)

  • n_hidden (int)

  • n_latent (int)

  • n_layers (int)

  • n_attention_heads (int)

  • dropout_rate (float)

  • gene_likelihood (Literal['zinb', 'nb', 'poisson'])

  • use_cell_type_attention (bool)

  • interaction_layers (int)

Methods

__init__(adata[, n_hidden, n_latent, ...])

compute_niche_composition(adata, labels_key)

Compute neighborhood cell type composition.

compute_spatial_neighbors(adata[, ...])

Compute spatial nearest neighbors.

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.

get_anndata_manager(adata[, required])

Retrieves the AnnDataManager for a given AnnData object.

get_cell_type_interactions([adata, aggregate])

Get aggregated cell type interaction matrix.

get_from_registry(adata, registry_key)

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

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

Get cell-cell interaction scores.

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

Return the latent representation for each cell.

get_normalized_expression([adata, indices])

Return normalized gene expression.

get_setup_arg(setup_arg)

Returns the string provided to setup of a specific setup_arg.

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

Get spatial coordinates.

get_spatial_neighbors([adata, indices])

Get spatial neighbor indices and distances.

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_registry(dir_path[, prefix])

Return the full registry saved with the model.

register_manager(adata_manager)

Registers an AnnDataManager instance with this model class.

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

Save the state of the model.

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

Sets up the AnnData object for this model.

to_device(device)

Move the model to the device.

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

Train the model.

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

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.

n_neighbors

Number of spatial neighbors.

registry

Data attached to model instance.

run_id

Returns the run id of the model.

run_name

Returns the run name of the model.

spatial_key

Key for spatial coordinates in obsm.

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.

get_interaction_scores(adata=None, indices=None, batch_size=None, return_attention_weights=False)[source]#

Get cell-cell interaction scores.

Parameters:
  • adata (AnnData | None) – AnnData object.

  • indices (Sequence[int] | None) – Indices of cells to use.

  • batch_size (int | None) – Batch size for data loader.

  • return_attention_weights (bool) – Whether to return raw attention weights.

  • adata (AnnData | None)

  • indices (Sequence[int] | None)

  • batch_size (int | None)

  • return_attention_weights (bool)

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]] | tuple[ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]], ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]]

Returns:

  • Interaction scores array. If return_attention_weights is True,

  • also returns attention weight matrices.

get_cell_type_interactions(adata=None, aggregate='mean')[source]#

Get aggregated cell type interaction matrix.

Parameters:
  • adata (AnnData | None) – AnnData object.

  • aggregate (Literal['mean', 'sum', 'max']) – Aggregation method for interaction scores.

  • adata (AnnData | None)

  • aggregate (Literal['mean', 'sum', 'max'])

Return type:

DataFrame

Returns:

DataFrame of cell type x cell type interaction strengths.

get_latent_representation(adata=None, indices=None, give_mean=True, batch_size=None)[source]#

Return the latent representation for each cell.

Parameters:
Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Returns:

Latent representation array.

get_normalized_expression(adata=None, indices=None, **kwargs)[source]#

Return normalized gene expression.

Return type:

ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]

Parameters:
classmethod setup_anndata(adata, layer=None, batch_key=None, labels_key=None, spatial_key='spatial', neighbor_index_key='nn_index', neighbor_dist_key='nn_dist', **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.

  • spatial_key (str) – Key in adata.obsm for spatial coordinates.

  • neighbor_index_key (str | None) – Key in adata.obsm for neighbor indices.

  • neighbor_dist_key (str | None) – Key in adata.obsm for neighbor distances.

  • adata (AnnData)

  • layer (str | None)

  • batch_key (str | None)

  • labels_key (str | None)

  • spatial_key (str)

  • neighbor_index_key (str | None)

  • neighbor_dist_key (str | None)

Return type:

None