spateo.alignment

Submodules

Classes

Mesh_correction

A class to perform 3D reconstruction correction from slices using a mesh.

Functions

grid_deformation(model[, spatial_key, vecfld_key, ...])

align_preprocess(...)

Preprocess the data before alignment.

calc_distance(→ Union[numpy.ndarray, torch.Tensor])

Calculate the distance between all pairs of samples in matrices X and Y using the specified metric.

calc_exp_dissimilarity(→ Union[numpy.ndarray, ...)

Calculate expression dissimilarity.

generate_label_transfer_dict(→ Dict[str, Dict[str, float]])

Generate a label transfer dictionary with normalized values.

morpho_align(→ Tuple[List[anndata.AnnData], ...)

Continuous alignment of spatial transcriptomic coordinates based on Morpho.

morpho_align_apply_transformation(models[, ...])

Apply the transformation to the models.

morpho_align_ref(→ Tuple[List[anndata.AnnData], ...)

Continuous alignment of spatial transcriptomic coordinates with the reference models based on Morpho.

morpho_align_transformation(models[, models_path, ...])

Continuous alignment of spatial transcriptomic coordinates based on Morpho, and return the transformation matrix.

paste_align(→ Tuple[List[anndata.AnnData], ...)

Align spatial coordinates of models.

paste_align_ref(→ Tuple[List[anndata.AnnData], ...)

Align the spatial coordinates of one model list through the affine transformation matrix obtained from another model list.

BA_transform(vecfld, quary_points[, ...])

Apply non-rigid transform to the quary points

BA_transform_and_assignment(samples, vecfld[, layer, ...])

paste_transform(→ anndata.AnnData)

Align the space coordinates of the new model with the transformation matrix obtained from PASTE.

downsampling(→ Union[List[anndata.AnnData], ...)

generate_label_transfer_prior(cat1, cat2[, ...])

get_labels_based_on_coords(→ pandas.DataFrame)

Obtain the label information in anndata.obs[key] corresponding to the coords.

get_optimal_mapping_relationship(X, Y, pi[, keep_all])

group_pca(→ None)

Perform PCA on a concatenated set of AnnData objects and store the results back in each individual AnnData.

mapping_aligned_coords(→ Tuple[dict, dict])

Optimal mapping coordinates between X and Y.

mapping_center_coords(→ dict)

Optimal mapping coordinates between X and Y based on intermediate coordinates.

rigid_transformation(adata, spatial_key, key_added[, ...])

solve_RT_by_correspondence(...)

Solve for the rotation matrix R and translation vector t that best align the points in X to the points in Y.

split_slice(adata, spatial_key[, split_num, axis])

tps_deformation(adata, spatial_key, key_added[, ...])

Package Contents

spateo.alignment.grid_deformation(model: anndata.AnnData, spatial_key: str = 'spatial', vecfld_key: str = 'VecFld_morpho', key_added: str = 'deformation', deformation_scale: int = 3, grid_num: numpy.asarray | None = None, dtype: str = 'float64', device: str = 'cpu')[source]
class spateo.alignment.Mesh_correction(slices: List[anndata.AnnData], z_heights: List | numpy.ndarray, mesh: pyvista.PolyData, spatial_key: str = 'spatial', key_added: str = 'align_spatial', normalize_spatial: bool = False, init_rotation: numpy.ndarray | None = np.array([0.0, 0.0, 0.0]), init_translation: numpy.ndarray | None = 0.0, init_scaling: numpy.ndarray | None = 1.0, max_rotation_angle: float = 180, max_translation_scale: float = 0.5, max_scaling: float = 1.5, min_rotation_angle: float = 10, min_translation_scale: float = 1, min_scaling: float = 1.1, label_num: int = 15, fastpd_iter: int = 100, max_iter: int = 10, anneal_rate: float = 0.7, multi_processing: bool = False, subsample_slices: int | None = None, verbose: bool = False)[source]

A class to perform 3D reconstruction correction from slices using a mesh.

slices

A list of aligned slices by Spateo or other methods.

Type:

List[AnnData]

z_heights

The z-coordinates for each slice.

Type:

Union[List, np.ndarray]

mesh

The mesh used for correction.

Type:

PolyData

spatial_key

The key to access spatial coordinates in the AnnData objects. The spatial coordinates under this key should be pre-aligned.

Type:

str

key_added

The key under which the corrected spatial coordinates will be added.

Type:

str

normalize_spatial

Flag indicating if spatial coordinates will be normalized.

Type:

bool

init_rotation

Initial rotation angles (in degrees) for the correction.

Type:

np.ndarray

init_translation

Initial translation vector for the correction.

Type:

np.ndarray

init_scaling

Initial scaling factor for the correction.

Type:

np.ndarray

max_rotation_angle

Maximum rotation angle allowed during the correction process.

Type:

float

max_translation_scale

Maximum translation scale allowed during the correction process.

Type:

float

max_scaling

Maximum scaling factor allowed during the correction process.

Type:

float

label_num

Number of labels used for optimization.

Type:

int

fastpd_iter

Number of iterations for the fastPD algorithm.

Type:

int

max_iter

Maximum number of iterations for the correction process.

Type:

int

anneal_rate

Annealing rate for the optimization process.

Type:

float

multi_processing

Flag indicating if multiprocessing will be used for the correction process.

Type:

bool

n_slices
slices_spatial
z_heights
mesh
key_added = 'align_spatial'
normalize_spatial = False
max_rotation_angle = 180
max_translation_scale = 0.5
max_scaling = 1.5
min_rotation_angle = 10
min_translation_scale = 1
min_scaling = 1.1
label_num = 15
fastpd_iter = 100
max_iter = 10
anneal_rate = 0.7
multi_processing = False
subsample_slices = None
verbose = False
contours
set_init_parameters(init_rotation: numpy.ndarray | None = np.array([0.0, 0.0, 0.0]), init_translation: numpy.ndarray | None = 0.0, init_scaling: numpy.ndarray | None = 1.0)[source]

Sets the initial transformation parameters for the mesh.

Parameters:
init_rotation Optional[np.ndarray], optional

Initial rotation angles (in degrees) for the mesh. Defaults to np.array([0., 0., 0.]).

init_translation Optional[np.ndarray], optional

Initial translation vector for the mesh. Defaults to 0.

init_scaling Optional[np.ndarray], optional

Initial scaling factor for the mesh. Defaults to 1.

normalize_mesh_spatial_coordinates()[source]

Normalizes the spatial coordinates of the mesh to align with the slices’ spatial scale.

This method calculates the scaling factor based on the maximum spatial extent of the slices and the z-height range, then applies this scaling to the mesh points. It also centers the mesh points along the z-axis to match the mean z-height of the slices.

extract_contours(method: Literal['opencv', 'alpha_shape'] = 'alpha_shape', n_sampling: int | None = None, smoothing: bool = True, window_size: int = 5, filter_contours: bool = True, contour_filter_threshold: int = 20, opencv_kwargs: Dict | None = None, alpha_shape_kwargs: Dict | None = None)[source]

Extracts contours of slices using the specified method.

Parameters:
method Literal["opencv", "alpha_shape"], optional

Method to extract contours. Defaults to “alpha_shape”.

n_sampling Optional[int], optional

Number of points to sample from each slice. Defaults to None.

smoothing bool, optional

Whether to smooth the contours. Defaults to True.

window_size int, optional

Window size for contour smoothing. Defaults to 5.

filter_contours bool, optional

Whether to filter the contours based on the threshold. Defaults to True.

contour_filter_threshold int, optional

Threshold for filtering contours based on the number of points. Defaults to 20.

opencv_kwargs Optional[Dict], optional

Additional arguments for the OpenCV method. Defaults to None.

alpha_shape_kwargs Optional[Dict], optional

Additional arguments for the alpha shape method. Defaults to None.

run_discrete_optimization() None[source]

Runs the discrete optimization process to find the best transformation parameters.

discrete_optimization_step() Tuple[float, numpy.ndarray][source]

Performs a discrete optimization step to find the best transformation.

Returns:

The loss and the best transformation found.

Return type:

Tuple[float, np.ndarray]

generate_labels() numpy.ndarray[source]

Generates discrete labels for rotation, translation, and scaling.

Returns:

An array of discrete transformation labels.

Return type:

np.ndarray

perform_correction()[source]

Performs the correction using the best transformation found.

spateo.alignment.align_preprocess(samples: List[anndata.AnnData], rep_layer: str | List[str] = 'X', rep_field: str | List[str] = 'layer', genes: list | numpy.ndarray | None = None, spatial_key: str = 'spatial', label_transfer_dict: dict | List[dict] | None = None, normalize_c: bool = False, normalize_g: bool = False, dtype: str = 'float64', device: str = 'cpu', verbose: bool = True) Tuple[spateo.alignment.methods.backend.TorchBackend | spateo.alignment.methods.backend.NumpyBackend, torch.Tensor | numpy.ndarray, List[List[numpy.ndarray | torch.Tensor]], List[numpy.ndarray | torch.Tensor], torch.Tensor | numpy.ndarray, torch.Tensor | numpy.ndarray, torch.Tensor | numpy.ndarray][source]

Preprocess the data before alignment.

Parameters:
samples List[AnnData]

A list of AnnData objects containing the data samples.

genes Optional[Union[list, np.ndarray]], optional

Genes used for calculation. If None, use all common genes for calculation. Default is None.

spatial_key str, optional

The key in .obsm that corresponds to the raw spatial coordinates. Default is “spatial”.

layer str, optional

If ‘X’, uses sample.X to calculate dissimilarity between spots, otherwise uses the representation given by sample.layers[layer]. Default is “X”.

use_rep Optional[Union[str, List[str]]], optional

Specify the representation to use. If None, do not use the representation.

rep_type Optional[Union[str, List[str]]], optional

Specify the type of representation. Accept types: “obs” and “obsm”. If None, use the “obsm” type.

normalize_c bool, optional

Whether to normalize spatial coordinates. Default is False.

normalize_g bool, optional

Whether to normalize gene expression. Default is False.

dtype str, optional

The floating-point number type. Only float32 and float64 are allowed. Default is “float64”.

device str, optional

The device used to run the program. Can specify the GPU to use, e.g., ‘0’. Default is “cpu”.

verbose bool, optional

If True, print progress updates. Default is True.

Returns:

A tuple containing the following elements: - backend: The backend used for computations (TorchBackend or NumpyBackend). - type_as: The type used for computations which contains the dtype and device. - exp_layers: A list of processed expression layers. - spatial_coords: A list of spatial coordinates. - normalize_scales: Optional scaling factors for normalization. - normalize_means: Optional mean values for normalization.

Return type:

Tuple

Raises:
  • ValueError – If the specified representation is not found in the attributes of the AnnData objects.

  • AssertionError – If the spatial coordinate dimensions are different.

spateo.alignment.calc_distance(X: List[numpy.ndarray | torch.Tensor] | numpy.ndarray | torch.Tensor, Y: List[numpy.ndarray | torch.Tensor] | numpy.ndarray | torch.Tensor, metric: List[str] | str = 'euc', label_transfer: numpy.ndarray | torch.Tensor | None = None) numpy.ndarray | torch.Tensor[source]

Calculate the distance between all pairs of samples in matrices X and Y using the specified metric.

Parameters:
X np.ndarray or torch.Tensor

Matrix with shape (N, D), where each row represents a sample.

Y np.ndarray or torch.Tensor

Matrix with shape (M, D), where each row represents a sample.

metric str, optional

The metric to use for calculating distances. Options are ‘euc’, ‘euclidean’, ‘square_euc’, ‘square_euclidean’, ‘kl’, ‘sym_kl’, ‘cos’, ‘cosine’, ‘label’. Default is ‘euc’.

label_transfer Optional[np.ndarray or torch.Tensor], optional

Matrix with shape (K, L) containing the label transfer cost. Required if metric is ‘label’. Default is None.

Returns:

Pairwise distance matrix with shape (N, M).

Return type:

np.ndarray or torch.Tensor

Raises:

AssertionError – If the number of features in X and Y do not match. If metric is not one of the supported metrics. If label_transfer is required but not provided.

spateo.alignment.calc_exp_dissimilarity(X_A: numpy.ndarray | torch.Tensor, X_B: numpy.ndarray | torch.Tensor, dissimilarity: str = 'kl', chunk_num: int = 1) numpy.ndarray | torch.Tensor[source]

Calculate expression dissimilarity. :param X_A: Gene expression matrix of sample A. :param X_B: Gene expression matrix of sample B. :param dissimilarity: Expression dissimilarity measure: 'kl', 'euclidean', 'euc', 'cos', or 'cosine'.

Returns:

The dissimilarity matrix of two feature samples.

Return type:

Union[np.ndarray, torch.Tensor]

spateo.alignment.generate_label_transfer_dict(cat1: List[str], cat2: List[str], positive_pairs: List[Dict[str, List[str] | float]] | None = None, negative_pairs: List[Dict[str, List[str] | float]] | None = None, default_positive_value: float = 10.0, default_negative_value: float = 1.0) Dict[str, Dict[str, float]][source]

Generate a label transfer dictionary with normalized values.

Parameters:
cat1 List[str]

List of categories from the first dataset.

cat2 List[str]

List of categories from the second dataset.

positive_pairs Optional[List[Dict[str, Union[List[str], float]]]], optional

List of positive pairs with transfer values. Each dictionary should have ‘left’, ‘right’, and ‘value’ keys. Defaults to None.

negative_pairs Optional[List[Dict[str, Union[List[str], float]]]], optional

List of negative pairs with transfer values. Each dictionary should have ‘left’, ‘right’, and ‘value’ keys. Defaults to None.

default_positive_value float, optional

Default value for positive pairs if none are provided. Defaults to 10.0.

default_negative_value float, optional

Default value for negative pairs if none are provided. Defaults to 1.0.

Returns:

A normalized label transfer dictionary.

Return type:

Dict[str, Dict[str, float]]

spateo.alignment.morpho_align(models: List[anndata.AnnData], rep_layer: str | List[str] = 'X', rep_field: str | List[str] = 'layer', genes: List[str] | numpy.ndarray | None = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: str | None = 'iter_spatial', vecfld_key_added: str = 'VecFld_morpho', mode: Literal['SN-N', 'SN-S'] = 'SN-S', dissimilarity: str | List[str] = 'kl', max_iter: int = 200, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True, **kwargs) Tuple[List[anndata.AnnData], List[numpy.ndarray]][source]

Continuous alignment of spatial transcriptomic coordinates based on Morpho.

Parameters:
models

List of models (AnnData Object).

layer

If 'X', uses .X to calculate dissimilarity between spots, otherwise uses the representation given by .layers[layer].

genes

Genes used for calculation. If None, use all common genes for calculation.

spatial_key

The key in .obsm that corresponds to the raw spatial coordinate.

key_added

.obsm key under which to add the aligned spatial coordinate.

iter_key_added

.uns key under which to add the result of each iteration of the iterative process. If iter_key_added is None, the results are not saved.

vecfld_key_added

The key that will be used for the vector field key in .uns. If vecfld_key_added is None, the results are not saved.

mode

The method of alignment. Available mode are: 'SN-N', and 'SN-S'.

  • 'SN-N': use both rigid and non-rigid alignment to keep the overall shape unchanged, while including local non-rigidity, and finally returns a non-rigid aligned result;

  • 'SN-S': use both rigid and non-rigid alignment to keep the overall shape unchanged, while including local non-rigidity, and finally returns a rigid aligned result. The non-rigid is used here to solve the optimal mapping, thus returning a more accurate rigid transformation. The default is 'SN-S'.

dissimilarity

Expression dissimilarity measure: 'kl' or 'euclidean'.

max_iter

Max number of iterations for morpho alignment.

dtype

The floating-point number type. Only float32 and float64.

device

Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'.

verbose

If True, print progress updates.

**kwargs

Additional parameters that will be passed to BA_align function.

Returns:

List of models (AnnData Object) after alignment. pis: List of pi matrices. sigma2s: List of sigma2.

Return type:

align_models

spateo.alignment.morpho_align_apply_transformation(models: List[anndata.AnnData | str], models_path: str | None = None, transformation: List[dict] = None, transformation_path: str | None = './Spateo_transformation', spatial_key: str = 'spatial', key_added: str = 'align_spatial', save_models_path: str | None = None, verbose: bool = True)[source]

Apply the transformation to the models.

Parameters:
models List[AnnData]

_description_

transformation List[dict]

_description_

Returns:

_description_

Return type:

_type_

spateo.alignment.morpho_align_ref(models: List[anndata.AnnData], models_ref: List[anndata.AnnData] | None = None, n_sampling: int | None = 2000, sampling_method: str = 'random', rep_layer: str | List[str] = 'X', rep_field: str | List[str] = 'layer', genes: list | numpy.ndarray | None = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: str | None = 'iter_spatial', vecfld_key_added: str | None = 'VecFld_morpho', mode: Literal['SN-N', 'SN-S'] = 'SN-S', dissimilarity: str | List[str] = 'kl', max_iter: int = 200, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True, **kwargs) Tuple[List[anndata.AnnData], List[anndata.AnnData], List[numpy.ndarray], List[numpy.ndarray]][source]

Continuous alignment of spatial transcriptomic coordinates with the reference models based on Morpho.

Parameters:
models

List of models (AnnData Object).

models_ref

Another list of models (AnnData Object).

n_sampling

When models_ref is None, new data containing n_sampling coordinate points will be automatically generated for alignment.

sampling_method

The method to sample data points, can be one of ["trn", "kmeans", "random"].

layer

If 'X', uses .X to calculate dissimilarity between spots, otherwise uses the representation given by .layers[layer].

genes

Genes used for calculation. If None, use all common genes for calculation.

spatial_key

The key in .obsm that corresponds to the raw spatial coordinate.

key_added

.obsm key under which to add the aligned spatial coordinate.

iter_key_added

.uns key under which to add the result of each iteration of the iterative process. If iter_key_added is None, the results are not saved.

vecfld_key_added

The key that will be used for the vector field key in .uns. If vecfld_key_added is None, the results are not saved.

mode

The method of alignment. Available mode are: 'SN-N', and 'SN-S'.

  • 'SN-N': use both rigid and non-rigid alignment to keep the overall shape unchanged, while including local non-rigidity, and finally returns a non-rigid aligned result;

  • 'SN-S': use both rigid and non-rigid alignment to keep the overall shape unchanged, while including local non-rigidity, and finally returns a rigid aligned result. The non-rigid is used here to solve the optimal mapping, thus returning a more accurate rigid transformation. The default is 'SN-S'.

dissimilarity

Expression dissimilarity measure: 'kl' or 'euclidean'.

max_iter

Max number of iterations for morpho alignment.

SVI_mode

Whether to use stochastic variational inferential (SVI) optimization strategy.

dtype

The floating-point number type. Only float32 and float64.

device

Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'.

verbose

If True, print progress updates.

**kwargs

Additional parameters that will be passed to BA_align function.

Returns:

List of models (AnnData Object) after alignment. align_models_ref: List of models_ref (AnnData Object) after alignment. pis: List of pi matrices for models. pis_ref: List of pi matrices for models_ref. sigma2s: List of sigma2.

Return type:

align_models

spateo.alignment.morpho_align_transformation(models: List[anndata.AnnData | str], models_path: str | None = None, save_transformation: bool = False, transformation_path: str | None = './Spateo_transformation', resume: bool = False, rep_layer: str | List[str] = 'X', rep_field: str | List[str] = 'layer', genes: List[str] | numpy.ndarray | None = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: str | None = 'iter_spatial', vecfld_key_added: str = 'VecFld_morpho', dissimilarity: str | List[str] = 'kl', max_iter: int = 200, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True, **kwargs)[source]

Continuous alignment of spatial transcriptomic coordinates based on Morpho, and return the transformation matrix.

Parameters:
models List[AnnData]

_description_

Returns:

_description_

Return type:

_type_

spateo.alignment.paste_align(models: List[anndata.AnnData], layer: str = 'X', genes: list | numpy.ndarray | None = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', mapping_key_added: str = 'models_align', alpha: float = 0.1, numItermax: int = 200, numItermaxEmd: int = 100000, dtype: str = 'float64', device: str = 'cpu', verbose: bool = True, **kwargs) Tuple[List[anndata.AnnData], List[numpy.ndarray | numpy.ndarray]][source]

Align spatial coordinates of models.

Parameters:
models

List of models (AnnData Object).

layer

If 'X', uses .X to calculate dissimilarity between spots, otherwise uses the representation given by .layers[layer].

genes

Genes used for calculation. If None, use all common genes for calculation.

spatial_key

The key in .obsm that corresponds to the raw spatial coordinate.

key_added

.obsm key under which to add the aligned spatial coordinates.

mapping_key_added

.uns key under which to add the alignment info.

alpha

Alignment tuning parameter. Note: 0 <= alpha <= 1.

When alpha = 0 only the gene expression data is taken into account, while when alpha =1 only the spatial coordinates are taken into account.

numItermax

Max number of iterations for cg during FGW-OT.

numItermaxEmd

Max number of iterations for emd during FGW-OT.

dtype

The floating-point number type. Only float32 and float64.

device

Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'.

verbose

If True, print progress updates.

**kwargs

Additional parameters that will be passed to pairwise_align function.

Returns:

List of models (AnnData Object) after alignment. pis: List of pi matrices.

Return type:

align_models

spateo.alignment.paste_align_ref(models: List[anndata.AnnData], models_ref: List[anndata.AnnData] | None = None, n_sampling: int | None = 2000, sampling_method: str = 'trn', layer: str = 'X', genes: list | numpy.ndarray | None = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', mapping_key_added: str = 'models_align', alpha: float = 0.1, numItermax: int = 200, numItermaxEmd: int = 100000, dtype: str = 'float64', device: str = 'cpu', verbose: bool = True, **kwargs) Tuple[List[anndata.AnnData], List[anndata.AnnData], List[numpy.ndarray | numpy.ndarray]][source]

Align the spatial coordinates of one model list through the affine transformation matrix obtained from another model list.

Parameters:
models

List of models (AnnData Object).

models_ref

Another list of models (AnnData Object).

n_sampling

When models_ref is None, new data containing n_sampling coordinate points will be automatically generated for alignment.

sampling_method

The method to sample data points, can be one of ["trn", "kmeans", "random"].

layer

If 'X', uses .X to calculate dissimilarity between spots, otherwise uses the representation given by .layers[layer].

genes

Genes used for calculation. If None, use all common genes for calculation.

spatial_key

The key in .obsm that corresponds to the raw spatial coordinates.

key_added

.obsm key under which to add the aligned spatial coordinates.

mapping_key_added

.uns key under which to add the alignment info.

alpha

Alignment tuning parameter. Note: 0 <= alpha <= 1.

When alpha = 0 only the gene expression data is taken into account, while when alpha =1 only the spatial coordinates are taken into account.

numItermax

Max number of iterations for cg during FGW-OT.

numItermaxEmd

Max number of iterations for emd during FGW-OT.

dtype

The floating-point number type. Only float32 and float64.

device

Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'.

verbose

If True, print progress updates.

**kwargs

Additional parameters that will be passed to models_align function.

Returns:

List of models (AnnData Object) after alignment. align_models_ref: List of models_ref (AnnData Object) after alignment. pis: The list of pi matrices from align_models_ref.

Return type:

align_models

spateo.alignment.BA_transform(vecfld, quary_points, deformation_scale: int = 1, dtype: str = 'float64', device: str = 'cpu')[source]

Apply non-rigid transform to the quary points

Parameters:
vecfld

A dictionary containing information about vector fields

quary_points

deformation_scale

If deformation_scale is greater than 1, increase the degree of deformation.

dtype

The floating-point number type. Only float32 and float64.

device

Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'.

spateo.alignment.BA_transform_and_assignment(samples, vecfld, layer: str = 'X', genes: List | torch.Tensor | None = None, spatial_key: str = 'spatial', small_variance: bool = False, dtype: str = 'float64', device: str = 'cpu', verbose: bool = False)[source]
spateo.alignment.paste_transform(adata: anndata.AnnData, adata_ref: anndata.AnnData, spatial_key: str = 'spatial', key_added: str = 'align_spatial', mapping_key: str = 'models_align') anndata.AnnData[source]

Align the space coordinates of the new model with the transformation matrix obtained from PASTE.

Parameters:
adata

The anndata object that need to be aligned.

adata_ref

The anndata object that have been aligned by PASTE.

spatial_key

The key in .obsm that corresponds to the raw spatial coordinates.

key_added

.obsm key under which to add the aligned spatial coordinates.

mapping_key

The key in .uns that corresponds to the alignment info from PASTE.

Returns:

The anndata object that have been to be aligned.

Return type:

adata

spateo.alignment.downsampling(models: List[anndata.AnnData] | anndata.AnnData, n_sampling: int | None = 2000, sampling_method: str = 'trn', spatial_key: str = 'spatial') List[anndata.AnnData] | anndata.AnnData[source]
spateo.alignment.generate_label_transfer_prior(cat1, cat2, positive_pairs=None, negative_pairs=None)[source]
spateo.alignment.get_labels_based_on_coords(model: anndata.AnnData, coords: numpy.ndarray, labels_key: str | List[str], spatial_key: str = 'align_spatial') pandas.DataFrame[source]

Obtain the label information in anndata.obs[key] corresponding to the coords.

spateo.alignment.get_optimal_mapping_relationship(X: numpy.ndarray, Y: numpy.ndarray, pi: numpy.ndarray, keep_all: bool = False)[source]
spateo.alignment.group_pca(adatas: List[anndata.AnnData], batch_key: str = 'batch', pca_key: str = 'X_pca', use_hvg: bool = True, hvg_key: str = 'highly_variable', **args) None[source]

Perform PCA on a concatenated set of AnnData objects and store the results back in each individual AnnData.

Parameters:

adatasList[AnnData]

A list of AnnData objects to be concatenated and processed.

batch_keystr, optional

The key to distinguish different batches in the concatenated AnnData object (default is ‘batch’).

pca_keystr, optional

The key under which to store the PCA results in each AnnData’s .obsm attribute (default is ‘X_pca’).

use_hvgbool, optional

Whether to perform PCA using only highly variable genes (default is True).

hvg_keystr, optional

The key under which highly variable genes are marked in .var (default is ‘highly_variable’).

**args

Additional arguments to pass to sc.tl.pca.

Raises:

ValueError:

If the specified batch_key already exists in any of the input AnnData objects. If no highly variable genes are found when use_hvg is True.

spateo.alignment.mapping_aligned_coords(X: numpy.ndarray, Y: numpy.ndarray, pi: numpy.ndarray, keep_all: bool = False) Tuple[dict, dict][source]

Optimal mapping coordinates between X and Y.

Parameters:
X

Aligned spatial coordinates.

Y

Aligned spatial coordinates.

pi

Mapping between the two layers output by PASTE.

keep_all

Whether to retain all the optimal relationships obtained only based on the pi matrix, If keep_all is False, the optimal relationships obtained based on the pi matrix and the nearest coordinates.

Returns:

Two dicts of mapping_X, mapping_Y, pi_index, pi_value.

mapping_X is X coordinates aligned with Y coordinates. mapping_Y is the Y coordinate aligned with X coordinates. pi_index is index between optimal mapping points in the pi matrix. pi_value is the value of optimal mapping points.

spateo.alignment.mapping_center_coords(modelA: anndata.AnnData, modelB: anndata.AnnData, center_key: str) dict[source]

Optimal mapping coordinates between X and Y based on intermediate coordinates.

Parameters:
modelA

modelA aligned with center model.

modelB

modelB aligned with center model.

center_key

The key in .uns that corresponds to the alignment info between modelA/modelB and center model.

Returns:

A dict of raw_X, raw_Y, mapping_X, mapping_Y, pi_value.

raw_X is the raw X coordinates. raw_Y is the raw Y coordinates. mapping_X is the Y coordinates aligned with X coordinates. mapping_Y is the X coordinates aligned with Y coordinates. pi_value is the value of optimal mapping points.

spateo.alignment.rigid_transformation(adata, spatial_key, key_added, theta=None, translation=None, inplace=True)[source]
spateo.alignment.solve_RT_by_correspondence(X: numpy.ndarray, Y: numpy.ndarray, return_scale: bool = False) Tuple[numpy.ndarray, numpy.ndarray] | Tuple[numpy.ndarray, numpy.ndarray, float][source]

Solve for the rotation matrix R and translation vector t that best align the points in X to the points in Y.

Parameters:
X np.ndarray

Source points, shape (N, D).

Y np.ndarray

Target points, shape (N, D).

return_scale bool, optional

Whether to return the scale factor. Defaults to False.

Returns:

If return_scale is False, returns the rotation matrix R and translation vector t. If return_scale is True, also returns the scale factor s.

Return type:

Union[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray, float]]

spateo.alignment.split_slice(adata, spatial_key, split_num=5, axis=2)[source]
spateo.alignment.tps_deformation(adata, spatial_key, key_added, grid_num=2, tps_noise_scale=25, add_corner_points=True, alpha=0.1, inplace=True)[source]