spateo.alignment.methods ======================== .. py:module:: spateo.alignment.methods Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/spateo/alignment/methods/backend/index /autoapi/spateo/alignment/methods/backend_ot/index /autoapi/spateo/alignment/methods/deprecated_morpho/index /autoapi/spateo/alignment/methods/deprecated_morpho_sparse/index /autoapi/spateo/alignment/methods/deprecated_morpho_sparse_utils/index /autoapi/spateo/alignment/methods/deprecated_utils/index /autoapi/spateo/alignment/methods/mesh_correction_utils/index /autoapi/spateo/alignment/methods/morpho_class/index /autoapi/spateo/alignment/methods/morpho_mesh_correction/index /autoapi/spateo/alignment/methods/paste/index /autoapi/spateo/alignment/methods/sampling/index /autoapi/spateo/alignment/methods/utils/index Attributes ---------- .. autoapisummary:: spateo.alignment.methods._chunk spateo.alignment.methods._data spateo.alignment.methods._dot spateo.alignment.methods._mul spateo.alignment.methods._pi spateo.alignment.methods._power spateo.alignment.methods._prod spateo.alignment.methods._unsqueeze spateo.alignment.methods.intersect_lsts Classes ------- .. autoapisummary:: spateo.alignment.methods.NumpyBackend spateo.alignment.methods.TorchBackend spateo.alignment.methods.Morpho_pairwise spateo.alignment.methods.Mesh_correction Functions --------- .. autoapisummary:: spateo.alignment.methods.align_preprocess spateo.alignment.methods.cal_dist spateo.alignment.methods.cal_dot spateo.alignment.methods.calc_exp_dissimilarity spateo.alignment.methods.generalized_procrustes_analysis spateo.alignment.methods.paste_center_align spateo.alignment.methods.paste_pairwise_align spateo.alignment.methods.calc_distance spateo.alignment.methods.check_backend spateo.alignment.methods.check_exp spateo.alignment.methods.con_K spateo.alignment.methods.empty_cache spateo.alignment.methods.filter_common_genes spateo.alignment.methods.generate_label_transfer_dict Package Contents ---------------- .. py:class:: NumpyBackend Bases: :py:obj:`Backend` NumPy implementation of the backend. - `__name__` is "numpy" - `__type__` is np.ndarray .. py:attribute:: __name__ :value: 'numpy' .. py:attribute:: __type__ .. py:attribute:: __type_list__ .. py:attribute:: rng_ .. py:method:: _to_numpy(a) Returns the numpy version of a tensor .. py:method:: _from_numpy(a, type_as=None) Creates a tensor cloning a numpy array, with the given precision (defaulting to input's precision) and the given device (in case of GPUs) .. py:method:: zeros(shape, type_as=None) Creates a tensor full of zeros. This function follows the api from :any:`numpy.zeros` See: https://numpy.org/doc/stable/reference/generated/numpy.zeros.html .. py:method:: einsum(subscripts, *operands) Evaluates the Einstein summation convention on the operands. This function follows the api from :any:`numpy.einsum` See: https://numpy.org/doc/stable/reference/generated/numpy.einsum.html .. py:method:: mean(a, axis=None) Computes the arithmetic mean of a tensor along given dimensions. This function follows the api from :any:`numpy.mean` See: https://numpy.org/doc/stable/reference/generated/numpy.mean.html .. py:method:: full(shape, fill_value, type_as=None) Creates a tensor with given shape, filled with given value. This function follows the api from :any:`numpy.full` See: https://numpy.org/doc/stable/reference/generated/numpy.full.html .. py:method:: sqrt(a) Returns the non-ngeative square root of a tensor, element-wise. This function follows the api from :any:`numpy.sqrt` See: https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html .. py:method:: ones(shape, type_as=None) Creates a tensor full of ones. This function follows the api from :any:`numpy.ones` See: https://numpy.org/doc/stable/reference/generated/numpy.ones.html .. py:method:: maximum(a, b) Returns element-wise maximum of array elements. This function follows the api from :any:`numpy.maximum` See: https://numpy.org/doc/stable/reference/generated/numpy.maximum.html .. py:method:: minimum(a, b) Returns element-wise minimum of array elements. This function follows the api from :any:`numpy.minimum` See: https://numpy.org/doc/stable/reference/generated/numpy.minimum.html .. py:method:: max(a, axis=None, keepdims=False) Returns the maximum of an array or maximum along given dimensions. This function follows the api from :any:`numpy.amax` See: https://numpy.org/doc/stable/reference/generated/numpy.amax.html .. py:method:: min(a, axis=None, keepdims=False) Returns the maximum of an array or maximum along given dimensions. This function follows the api from :any:`numpy.amin` See: https://numpy.org/doc/stable/reference/generated/numpy.amin.html .. py:method:: eye(N, M=None, type_as=None) Creates the identity matrix of given size. This function follows the api from :any:`numpy.eye` See: https://numpy.org/doc/stable/reference/generated/numpy.eye.html .. py:method:: argsort(a, axis=-1) Returns the indices that would sort a tensor. This function follows the api from :any:`numpy.argsort` See: https://numpy.org/doc/stable/reference/generated/numpy.argsort.html .. py:method:: exp(a) .. py:method:: log(a) Computes the natural logarithm, element-wise. This function follows the api from :any:`numpy.log` See: https://numpy.org/doc/stable/reference/generated/numpy.log.html .. py:method:: concatenate(arrays, axis=0) Joins a sequence of tensors along an existing dimension. This function follows the api from :any:`numpy.concatenate` See: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html .. py:method:: sum(a, axis=None, keepdims=False) Sums tensor elements over given dimensions. This function follows the api from :any:`numpy.sum` See: https://numpy.org/doc/stable/reference/generated/numpy.sum.html .. py:method:: arange(stop, start=0, step=1, type_as=None) Returns evenly spaced values within a given interval. This function follows the api from :any:`numpy.arange` See: https://numpy.org/doc/stable/reference/generated/numpy.arange.html .. py:method:: data(a, type_as=None) .. py:method:: unique(a, return_index, return_inverse=False, axis=None) Finds unique elements of given tensor. This function follows the api from :any:`numpy.unique` See: https://numpy.org/doc/stable/reference/generated/numpy.unique.html .. py:method:: unsqueeze(a, axis=-1) .. py:method:: multiply(a, b) .. py:method:: power(a, exponents) First tensor elements raised to powers from second tensor, element-wise. This function follows the api from :any:`numpy.power` See: https://numpy.org/doc/stable/reference/generated/numpy.power.html .. py:method:: dot(a, b) Returns the dot product of two tensors. This function follows the api from :any:`numpy.dot` See: https://numpy.org/doc/stable/reference/generated/numpy.dot.html .. py:method:: prod(a, axis=0) Return the product of all elements. See: https://numpy.org/doc/stable/reference/generated/numpy.prod.html .. py:method:: pi(type_as=None) Return the value of pi. See: https://numpy.org/doc/stable/reference/constants.html .. py:method:: chunk(a, chunk_num, axis=0) Split the tensor into a list of sub-tensors. See: https://numpy.org/doc/stable/reference/generated/numpy.array_split.html .. py:method:: randperm(length) Returns a random permutation of integers from 0 to length - 1. See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.permutation.html .. py:method:: roll(a, shift, axis=None) Roll array elements along a given axis. See: https://numpy.org/doc/stable/reference/generated/numpy.roll.html .. py:method:: choice(a, size, replace=False) Generates a random sample from a given 1-D array. See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html .. py:method:: topk(a, topk, axis=-1) Returns the indices of the topk elements along a given axis. See: https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html .. py:method:: dstack(a) Stack arrays in sequence along the third axis. See: https://numpy.org/doc/stable/reference/generated/numpy.dstack.html .. py:method:: vstack(a) Stack arrays in sequence vertically (row wise). See: https://numpy.org/doc/stable/reference/generated/numpy.vstack.html .. py:method:: hstack(a) Stack arrays in sequence horizontally (column wise). See: https://numpy.org/doc/stable/reference/generated/numpy.hstack.html .. py:method:: stack(arrays, axis=0) Joins a sequence of tensors along a new dimension. This function follows the api from :any:`numpy.stack` See: https://numpy.org/doc/stable/reference/generated/numpy.stack.html .. py:method:: where(condition, x=None, y=None) Returns elements chosen from x or y depending on condition. This function follows the api from :any:`numpy.where` See: https://numpy.org/doc/stable/reference/generated/numpy.where.html .. py:method:: copy(a) Returns a copy of the given tensor. This function follows the api from :any:`numpy.copy` See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html .. py:method:: repeat(a, repeats, axis=None) Repeats elements of a tensor. This function follows the api from :any:`numpy.repeat` See: https://numpy.org/doc/stable/reference/generated/numpy.repeat.html .. py:method:: sort2(a, axis=-1, descending=False) Return the sorted array and the indices to sort the array See: https://pytorch.org/docs/stable/generated/torch.sort.html .. py:method:: coo_matrix(data, rows, cols, shape=None, type_as=None) Creates a sparse tensor in COOrdinate format. This function follows the api from :any:`scipy.sparse.coo_matrix` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html .. py:method:: issparse(a) Checks whether or not the input tensor is a sparse tensor. This function follows the api from :any:`scipy.sparse.issparse` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.issparse.html .. py:method:: eliminate_zeros(a, threshold=0.0) Removes entries smaller than the given threshold from the sparse tensor. This function follows the api from :any:`scipy.sparse.csr_matrix.eliminate_zeros` See: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.eliminate_zeros.html .. py:method:: todense(a) Converts a sparse tensor to a dense tensor. This function follows the api from :any:`scipy.sparse.csr_matrix.toarray` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.toarray.html .. py:method:: dtype_device(a) Returns the dtype and the device of the given tensor. .. py:class:: TorchBackend Bases: :py:obj:`Backend` PyTorch implementation of the backend - `__name__` is "torch" - `__type__` is torch.Tensor .. py:attribute:: __name__ :value: 'torch' .. py:attribute:: __type__ .. py:attribute:: __type_list__ :value: None .. py:attribute:: rng_ :value: None .. py:attribute:: ValFunction .. py:method:: _to_numpy(a) Returns the numpy version of a tensor .. py:method:: _from_numpy(a, type_as=None) Creates a tensor cloning a numpy array, with the given precision (defaulting to input's precision) and the given device (in case of GPUs) .. py:method:: zeros(shape, type_as=None) Creates a tensor full of zeros. This function follows the api from :any:`numpy.zeros` See: https://numpy.org/doc/stable/reference/generated/numpy.zeros.html .. py:method:: einsum(subscripts, *operands) Evaluates the Einstein summation convention on the operands. This function follows the api from :any:`numpy.einsum` See: https://numpy.org/doc/stable/reference/generated/numpy.einsum.html .. py:method:: mean(a, axis=None) Computes the arithmetic mean of a tensor along given dimensions. This function follows the api from :any:`numpy.mean` See: https://numpy.org/doc/stable/reference/generated/numpy.mean.html .. py:method:: full(shape, fill_value, type_as=None) Creates a tensor with given shape, filled with given value. This function follows the api from :any:`numpy.full` See: https://numpy.org/doc/stable/reference/generated/numpy.full.html .. py:method:: sqrt(a) Returns the non-ngeative square root of a tensor, element-wise. This function follows the api from :any:`numpy.sqrt` See: https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html .. py:method:: ones(shape, type_as=None) Creates a tensor full of ones. This function follows the api from :any:`numpy.ones` See: https://numpy.org/doc/stable/reference/generated/numpy.ones.html .. py:method:: arange(stop, start=0, step=1, type_as=None) Returns evenly spaced values within a given interval. This function follows the api from :any:`numpy.arange` See: https://numpy.org/doc/stable/reference/generated/numpy.arange.html .. py:method:: maximum(a, b) Returns element-wise maximum of array elements. This function follows the api from :any:`numpy.maximum` See: https://numpy.org/doc/stable/reference/generated/numpy.maximum.html .. py:method:: minimum(a, b) Returns element-wise minimum of array elements. This function follows the api from :any:`numpy.minimum` See: https://numpy.org/doc/stable/reference/generated/numpy.minimum.html .. py:method:: max(a, axis=None, keepdims=False) Returns the maximum of an array or maximum along given dimensions. This function follows the api from :any:`numpy.amax` See: https://numpy.org/doc/stable/reference/generated/numpy.amax.html .. py:method:: min(a, axis=None, keepdims=False) Returns the maximum of an array or maximum along given dimensions. This function follows the api from :any:`numpy.amin` See: https://numpy.org/doc/stable/reference/generated/numpy.amin.html .. py:method:: eye(N, M=None, type_as=None) Creates the identity matrix of given size. This function follows the api from :any:`numpy.eye` See: https://numpy.org/doc/stable/reference/generated/numpy.eye.html .. py:method:: argsort(a, axis=-1) Returns the indices that would sort a tensor. This function follows the api from :any:`numpy.argsort` See: https://numpy.org/doc/stable/reference/generated/numpy.argsort.html .. py:method:: exp(a) .. py:method:: log(a) Computes the natural logarithm, element-wise. This function follows the api from :any:`numpy.log` See: https://numpy.org/doc/stable/reference/generated/numpy.log.html .. py:method:: concatenate(arrays, axis=0) Joins a sequence of tensors along an existing dimension. This function follows the api from :any:`numpy.concatenate` See: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html .. py:method:: sum(a, axis=None, keepdims=False) Sums tensor elements over given dimensions. This function follows the api from :any:`numpy.sum` See: https://numpy.org/doc/stable/reference/generated/numpy.sum.html .. py:method:: data(a, type_as=None) .. py:method:: unique(a, return_index=False, return_inverse=False, axis=None) Finds unique elements of given tensor. This function follows the api from :any:`numpy.unique` See: https://numpy.org/doc/stable/reference/generated/numpy.unique.html .. py:method:: unsqueeze(a, axis=-1) .. py:method:: multiply(a, b) .. py:method:: power(a, exponents) First tensor elements raised to powers from second tensor, element-wise. This function follows the api from :any:`numpy.power` See: https://numpy.org/doc/stable/reference/generated/numpy.power.html .. py:method:: dot(a, b) Returns the dot product of two tensors. This function follows the api from :any:`numpy.dot` See: https://numpy.org/doc/stable/reference/generated/numpy.dot.html .. py:method:: prod(a, axis=0) Return the product of all elements. See: https://numpy.org/doc/stable/reference/generated/numpy.prod.html .. py:method:: pi(type_as=None) Return the value of pi. See: https://numpy.org/doc/stable/reference/constants.html .. py:method:: chunk(a, chunk_num, axis=0) Split the tensor into a list of sub-tensors. See: https://numpy.org/doc/stable/reference/generated/numpy.array_split.html .. py:method:: randperm(length) Returns a random permutation of integers from 0 to length - 1. See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.permutation.html .. py:method:: roll(a, shift, axis=None) Roll array elements along a given axis. See: https://numpy.org/doc/stable/reference/generated/numpy.roll.html .. py:method:: choice(a, size, replace=False) Generates a random sample from a given 1-D array. See: https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html .. py:method:: topk(a, topk, axis=-1) Returns the indices of the topk elements along a given axis. See: https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html .. py:method:: dstack(a) Stack arrays in sequence along the third axis. See: https://numpy.org/doc/stable/reference/generated/numpy.dstack.html .. py:method:: vstack(a) Stack arrays in sequence vertically (row wise). See: https://numpy.org/doc/stable/reference/generated/numpy.vstack.html .. py:method:: hstack(a) Stack arrays in sequence horizontally (column wise). See: https://numpy.org/doc/stable/reference/generated/numpy.hstack.html .. py:method:: stack(arrays, axis=0) Joins a sequence of tensors along a new dimension. This function follows the api from :any:`numpy.stack` See: https://numpy.org/doc/stable/reference/generated/numpy.stack.html .. py:method:: where(condition, x=None, y=None) Returns elements chosen from x or y depending on condition. This function follows the api from :any:`numpy.where` See: https://numpy.org/doc/stable/reference/generated/numpy.where.html .. py:method:: copy(a) Returns a copy of the given tensor. This function follows the api from :any:`numpy.copy` See: https://numpy.org/doc/stable/reference/generated/numpy.copy.html .. py:method:: repeat(a, repeats, axis=None) Repeats elements of a tensor. This function follows the api from :any:`numpy.repeat` See: https://numpy.org/doc/stable/reference/generated/numpy.repeat.html .. py:method:: sort2(a, axis=-1, descending=False) Return the sorted array and the indices to sort the array See: https://pytorch.org/docs/stable/generated/torch.sort.html .. py:method:: coo_matrix(data, rows, cols, shape=None, type_as=None) Creates a sparse tensor in COOrdinate format. This function follows the api from :any:`scipy.sparse.coo_matrix` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html .. py:method:: issparse(a) Checks whether or not the input tensor is a sparse tensor. This function follows the api from :any:`scipy.sparse.issparse` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.issparse.html .. py:method:: eliminate_zeros(a, threshold=0.0) Removes entries smaller than the given threshold from the sparse tensor. This function follows the api from :any:`scipy.sparse.csr_matrix.eliminate_zeros` See: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.eliminate_zeros.html .. py:method:: todense(a) Converts a sparse tensor to a dense tensor. This function follows the api from :any:`scipy.sparse.csr_matrix.toarray` See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.toarray.html .. py:method:: dtype_device(a) Returns the dtype and the device of the given tensor. .. py:function:: align_preprocess(samples: List[anndata.AnnData], rep_layer: Union[str, List[str]] = 'X', rep_field: Union[str, List[str]] = 'layer', genes: Optional[Union[list, numpy.ndarray]] = None, spatial_key: str = 'spatial', label_transfer_dict: Optional[Union[dict, List[dict]]] = None, normalize_c: bool = False, normalize_g: bool = False, dtype: str = 'float64', device: str = 'cpu', verbose: bool = True) -> Tuple[Union[ot.backend.TorchBackend, ot.backend.NumpyBackend], Union[torch.Tensor, numpy.ndarray], List[List[Union[numpy.ndarray, torch.Tensor]]], List[Union[numpy.ndarray, torch.Tensor]], Union[torch.Tensor, numpy.ndarray], Union[torch.Tensor, numpy.ndarray], Union[torch.Tensor, numpy.ndarray]] Preprocess the data before alignment. :param samples: A list of AnnData objects containing the data samples. :type samples: List[AnnData] :param genes: Genes used for calculation. If None, use all common genes for calculation. Default is None. :type genes: Optional[Union[list, np.ndarray]], optional :param spatial_key: The key in `.obsm` that corresponds to the raw spatial coordinates. Default is "spatial". :type spatial_key: str, optional :param layer: If 'X', uses `sample.X` to calculate dissimilarity between spots, otherwise uses the representation given by `sample.layers[layer]`. Default is "X". :type layer: str, optional :param use_rep: Specify the representation to use. If None, do not use the representation. :type use_rep: Optional[Union[str, List[str]]], optional :param rep_type: Specify the type of representation. Accept types: "obs" and "obsm". If None, use the "obsm" type. :type rep_type: Optional[Union[str, List[str]]], optional :param normalize_c: Whether to normalize spatial coordinates. Default is False. :type normalize_c: bool, optional :param normalize_g: Whether to normalize gene expression. Default is False. :type normalize_g: bool, optional :param dtype: The floating-point number type. Only float32 and float64 are allowed. Default is "float64". :type dtype: str, optional :param device: The device used to run the program. Can specify the GPU to use, e.g., '0'. Default is "cpu". :type device: str, optional :param verbose: If True, print progress updates. Default is True. :type verbose: bool, optional :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. :rtype: Tuple :raises ValueError: If the specified representation is not found in the attributes of the AnnData objects. :raises AssertionError: If the spatial coordinate dimensions are different. .. py:function:: cal_dist(X_A: Union[numpy.ndarray, torch.Tensor], X_B: Union[numpy.ndarray, torch.Tensor], use_gpu: bool = True, chunk_num: int = 1, return_gpu: bool = True) -> Union[numpy.ndarray, torch.Tensor] Calculate the distance between two vectors :param X_A: The first input vector with shape n x d :type X_A: Union[np.ndarray, torch.Tensor] :param X_B: The second input vector with shape m x d :type X_B: Union[np.ndarray, torch.Tensor] :param use_gpu: Whether to use GPU for chunk. Defaults to True. :type use_gpu: bool, optional :param chunk_num: The number of chunks. The larger the number, the smaller the GPU memory usage, but the slower the calculation speed. Defaults to 1. :type chunk_num: int, optional :returns: Distance matrix of two vectors with shape n x m. :rtype: Union[np.ndarray, torch.Tensor] .. py:function:: cal_dot(mat1: Union[numpy.ndarray, torch.Tensor], mat2: Union[numpy.ndarray, torch.Tensor], use_chunk: bool = False, use_gpu: bool = True, chunk_num: int = 20) -> Union[numpy.ndarray, torch.Tensor] Calculate the matrix multiplication of two matrices :param mat1: The first input matrix with shape n x d :type mat1: Union[np.ndarray, torch.Tensor] :param mat2: The second input matrix with shape d x m. We suppose m << n and does not require chunk. :type mat2: Union[np.ndarray, torch.Tensor] :param use_chunk: Whether to use chunk to reduce the GPU memory usage. Note that if set to ``True'' it will slow down the calculation. Defaults to False. :type use_chunk: bool, optional :param use_gpu: Whether to use GPU for chunk. Defaults to True. :type use_gpu: bool, optional :param chunk_num: The number of chunks. The larger the number, the smaller the GPU memory usage, but the slower the calculation speed. Defaults to 20. :type chunk_num: int, optional :returns: Matrix multiplication result with shape n x m :rtype: Union[np.ndarray, torch.Tensor] .. py:function:: calc_exp_dissimilarity(X_A: Union[numpy.ndarray, torch.Tensor], X_B: Union[numpy.ndarray, torch.Tensor], dissimilarity: str = 'kl', chunk_num: int = 1) -> Union[numpy.ndarray, torch.Tensor] 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. :rtype: Union[np.ndarray, torch.Tensor] .. py:class:: Morpho_pairwise(sampleA: anndata.AnnData, sampleB: anndata.AnnData, rep_layer: Union[str, List[str]] = 'X', rep_field: Union[str, List[str]] = 'layer', genes: Optional[Union[List[str], numpy.ndarray, torch.Tensor]] = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: Optional[str] = None, save_concrete_iter: bool = False, vecfld_key_added: Optional[str] = None, dissimilarity: Union[str, List[str]] = 'kl', probability_type: Union[str, List[str]] = 'gauss', probability_parameters: Optional[Union[float, List[float]]] = None, label_transfer_dict: Optional[Union[dict, List[dict]]] = None, nn_init: bool = True, init_transform: bool = True, allow_flip: bool = False, init_layer: str = 'X', init_field: str = 'layer', nn_init_top_K: int = 10, nn_init_weight: float = 1.0, max_iter: int = 200, nonrigid_start_iter: int = 80, SVI_mode: bool = True, batch_size: Optional[int] = None, pre_compute_dist: bool = True, sparse_calculation_mode: bool = False, sparse_top_k: int = 1024, lambdaVF: Union[int, float] = 100.0, beta: Union[int, float] = 0.01, K: Union[int, float] = 15, kernel_type: str = 'euc', graph: Optional[networkx.Graph] = None, graph_knn: int = 10, sigma2_init_scale: Optional[Union[int, float]] = 0.1, sigma2_end: Optional[Union[int, float]] = None, gamma_a: float = 1.0, gamma_b: float = 1.0, kappa: Union[float, numpy.ndarray] = 1.0, partial_robust_level: float = 10, normalize_c: bool = True, normalize_g: bool = False, separate_mean: bool = True, separate_scale: bool = False, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True, guidance_pair: Optional[Union[List[numpy.ndarray], numpy.ndarray]] = None, guidance_effect: Optional[Union[bool, str]] = False, guidance_weight: float = 1.0, use_chunk: bool = False, chunk_capacity: float = 1.0, return_mapping: bool = False) A class to align two spatial transcriptomics AnnData objects using the Spateo alignment algorithm. .. attribute:: sampleA The first AnnData object that acts as the reference. :type: AnnData .. attribute:: sampleB The second AnnData object that acts as the reference. :type: AnnData .. attribute:: rep_layer Representation layer(s) used for alignment. Default is "X". :type: Union[str, List[str]] .. attribute:: rep_field Representation layer field(s) in AnnData to be used for alignment. "layer" means gene expression, "obsm" means embdedding like pca or VAE, "obs" means discrete label annotation. Note that Spateo only accept one label annotation. Defaults to "layer". :type: Union[str, List[str]] .. attribute:: genes List or tensor of genes to be used for alignment. For example, you can input the genes you are interested or spatially variabe genes here. Defaults to None. :type: Optional[Union[List[str], torch.Tensor]] .. attribute:: spatial_key Key in `.obsm` of AnnData corresponding to the spatial coordinates. Defaults to "spatial". :type: str .. attribute:: key_added Key under which the aligned spatial coordinates are added in `.obsm`. Defaults to "align_spatial". :type: str .. attribute:: iter_key_added Key under which to store intermediate iteration results in `.uns`. Defaults to None. :type: Optional[str] .. attribute:: save_concrete_iter Whether to save more concrete intermediate iteration results. Default is False. :type: bool .. attribute:: vecfld_key_added Key under which to store vector field results in `.uns`. Defaults to None. :type: Optional[str] .. attribute:: dissimilarity Measure(s) of pairwise dissimilarity of each observation to be used. Defaults to "kl". :type: Union[str, List[str]] .. attribute:: probability_type Type(s) of probability distribution used. Defaults to "gauss". :type: Union[str, List[str]] .. attribute:: probability_parameters Parameters for the probability distribution. Defaults to None. :type: Optional[Union[float, List[float]]] .. attribute:: label_transfer_dict Dictionary that stores the label transfer probability. Defaults to None. :type: Optional[Union[dict, List[dict]]] .. attribute:: nn_init Whether to use nearest neighbor matching to initialize the alignment. Default is True. :type: bool .. attribute:: allow_flip Whether to allow flipping of coordinates. Default is False. :type: bool .. attribute:: init_layer Layer for initialize alignment. Defaults to "X". :type: str .. attribute:: init_field Layer field for initialize alignment. Defaults to 'layer'. :type: str .. attribute:: nn_init_weight Weight for nn_init guidance. Larger means that the nn_init guidance has more impact on the alignment, vice versa. Default is 1.0. :type: float .. attribute:: nn_init_top_K The number of top K nearest neighbors to consider in the nn_init. Defaults to 10. :type: int, optional .. attribute:: guidance_pair List of guidance pairs for alignment. Default is None. :type: Optional[Union[List[np.ndarray], np.ndarray]] .. attribute:: guidance_effect Effect of guidance for the transformation. Valid value: False, "rigid", "nonrigid", and "both". Default is False. :type: Optional[Union[bool, str]] .. attribute:: guidance_weight Weight for guidance. Larger means that the guidance has more impact on the alignment, vice versa. Default is 1. :type: float .. attribute:: max_iter Maximum number of iterations. Defaults to 200. :type: int .. attribute:: SVI_mode Whether to use Stochastic Variational Inference mode. Default is True. :type: bool .. attribute:: batch_size Size of the mini-batch of SVI. Default is 1000. :type: int .. attribute:: pre_compute_dist Whether to precompute the distance matrix when using SVI mode. This will significantly speed up the calculation process but will also take more (GPU) memory. Default is True. :type: bool .. attribute:: sparse_calculation_mode Whether to use sparse matrix calculation. This will significantly reduce the (GPU) memory but will also slow down the speed. Default is False. :type: bool .. attribute:: sparse_top_k The top k elements to keep in sparse calculation mode. Default is 1024. :type: int .. attribute:: use_chunk Whether to use chunking in calculations. This will reduce the (GPU) memory but will also slow down the speed. Default is False. :type: bool .. attribute:: chunk_capacity Chunk size scale to the chunk_base. :type: float .. attribute:: lambdaVF Regularization parameter for the vector field of the non-rigid transformation. Smaller means that non-rigid deformation gets fewer constraints, then deformation can be larger and more flexible, vice versa. Default is 1e2. Recommended setting range [1e-1, 1e4]. :type: Union[int, float] .. attribute:: beta Length-scale of the SE kernel. Larger means less correlation between points and more flexible non-rigid deformation, and vice versa. Default is 0.01. Recommended setting range [1e-4, 1e0]. :type: Union[int, float] .. attribute:: K Number of sparse inducing points used for Nyström approximation for the kernel. Default is 15. :type: Union[int, float] .. attribute:: kernel_type Type of kernel used. Default is "euc". :type: str .. attribute:: sigma2_init_scale Initial value for the spatial dispersion level. Default is 0.1. :type: Optional[Union[int, float]] .. attribute:: partial_robust_level Robust level of partial alignment. Default is 10. :type: float .. attribute:: normalize_c Whether to normalize spatial coordinates. Default is True. :type: bool .. attribute:: normalize_g Whether to normalize gene expression. Default is True. :type: bool .. attribute:: dtype Data type for computations. Default is "float32". :type: str .. attribute:: device Device used to run the program. Default is "cpu". :type: str .. attribute:: verbose Whether to print verbose messages. Default is True. :type: bool .. py:attribute:: verbose .. py:attribute:: sampleA .. py:attribute:: sampleB .. py:attribute:: rep_layer .. py:attribute:: rep_field .. py:attribute:: genes .. py:attribute:: spatial_key .. py:attribute:: key_added .. py:attribute:: iter_key_added .. py:attribute:: save_concrete_iter .. py:attribute:: vecfld_key_added .. py:attribute:: dissimilarity .. py:attribute:: probability_type .. py:attribute:: probability_parameters .. py:attribute:: label_transfer_dict .. py:attribute:: nn_init .. py:attribute:: init_transform .. py:attribute:: nn_init_top_K .. py:attribute:: max_iter .. py:attribute:: allow_flip .. py:attribute:: init_layer .. py:attribute:: init_field .. py:attribute:: SVI_mode .. py:attribute:: batch_size .. py:attribute:: pre_compute_dist .. py:attribute:: sparse_calculation_mode .. py:attribute:: sparse_top_k .. py:attribute:: beta .. py:attribute:: lambdaVF .. py:attribute:: K .. py:attribute:: kernel_type .. py:attribute:: kernel_bandwidth .. py:attribute:: graph .. py:attribute:: graph_knn .. py:attribute:: sigma2_init_scale .. py:attribute:: sigma2_end .. py:attribute:: partial_robust_level .. py:attribute:: normalize_c .. py:attribute:: normalize_g .. py:attribute:: separate_mean .. py:attribute:: separate_scale .. py:attribute:: dtype .. py:attribute:: device .. py:attribute:: guidance_pair .. py:attribute:: guidance_effect .. py:attribute:: guidance_weight .. py:attribute:: use_chunk .. py:attribute:: chunk_capacity .. py:attribute:: nn_init_weight .. py:attribute:: gamma_a .. py:attribute:: gamma_b .. py:attribute:: kappa .. py:attribute:: nonrigid_start_iter .. py:attribute:: return_mapping .. py:method:: run() Run the pairwise alignment process for spatial transcriptomics data. Steps involved: 1. Perform coarse rigid alignment if nearest neighbor (nn) initialization is enabled. 2. Calculate the pairwise distance matrix for representations if pre-computation is enabled or not in SVI mode. 3. Initialize iteration variables and structures. 4. Perform iterative variational updates for alignment, including assignment P, gamma, alpha, sigma2, rigid and non-rigid updates. 5. Retrieve the full cell-cell assignment after the iterative process and calculate the optimal rigid transformation :returns: The final cell-cell assignment matrix. :rtype: np.ndarray .. py:method:: _check() Validate and initialize various attributes for the Morpho_pairwise object. This method performs several checks and initializations, including: - Representation layers and fields in AnnData objects - Spatial keys in AnnData objects - Label transfer dictionaries - Dissimilarity metrics - Probability types and parameters - Initialization layers and fields - Guidance effects :raises ValueError: If any of the validations fail or required attributes are missing. :raises KeyError: If the specified spatial key is not found in the AnnData objects. .. py:method:: _align_preprocess(dtype: str = 'float32', device: str = 'cpu') Preprocess the data for alignment. This method performs several preprocessing steps, including: - Determining the backend (CPU/GPU) for computation. - Extracting common genes from the samples. - Extracting gene expression or representations from the samples. - Checking and generating the label transfer matrix from the dictionary. - Extracting and normalizing spatial coordinates. - Normalizing gene expression if required. - Preprocessing guidance pairs if provided. :param dtype: The data type for computations. Defaults to "float32". :type dtype: str, optional :param device: The device used for computation (e.g., "cpu" or "cuda:0"). Defaults to "cpu". :type device: str, optional :raises AssertionError: If the spatial coordinate dimensions of the samples are different. .. py:method:: _guidance_pair_preprocess() Preprocess the guidance pairs for alignment. This method converts the guidance pairs to the backend type (e.g., NumPy, Torch) and normalizes them if required. The normalization is based on the means and scales of the spatial coordinates. :raises ValueError: If `self.guidance_pair` is not properly formatted. .. py:method:: _normalize_coords() Normalize the spatial coordinates of the samples. This method normalizes the spatial coordinates of the samples to have zero mean and unit variance. It can normalize the coordinates separately or globally based on the provided arguments. :raises AssertionError: If the dimensionality of the coordinates does not match. .. py:method:: _normalize_exps() Normalize the gene expression matrices. This method normalizes the gene expression matrices for the samples if the representation field is 'layer' and the dissimilarity metric is not 'kl'. The normalization ensures that the matrices have a consistent scale across the samples. :raises ValueError: If the normalization scale cannot be calculated. .. py:method:: _initialize_variational_variables() Initialize variational variables for the alignment process. This method sets initial guesses for various parameters, initializes variational variables, and configures the Stochastic Variational Inference (SVI) mode if enabled. :param sigma2_init_scale: Initial scaling factor for sigma2. Defaults to 1.0. :type sigma2_init_scale: float, optional :raises ValueError: If any initialization fails. .. py:method:: _init_probability_parameters(subsample: int = 20000) Initialize probability parameters for the alignment process. This method calculates initial values for probability parameters based on the provided subsampling size and the specified dissimilarity and probability types. :param subsample: The number of subsamples to use for initialization. Defaults to 20000. :type subsample: int, optional :raises ValueError: If an unsupported probability type is encountered. .. py:method:: _construct_kernel(inducing_variables_num, sampling_method) Construct the kernel matrix for the alignment process. This method generates inducing variables from the spatial coordinates, constructs the sparse kernel matrix, and handles different kernel types. It raises an error if the kernel type is not implemented. :param inducing_variables_num: Number of inducing variables to sample. :type inducing_variables_num: int :param sampling_method: Method used for sampling the inducing variables. :type sampling_method: str :raises NotImplementedError: If the specified kernel type is not implemented. .. py:method:: _update_batch(iter: int) Update the batch for Stochastic Variational Inference (SVI). This method updates the batch indices and step size for each iteration during the SVI process. It ensures that the batch permutation is rolled to provide a new batch for each iteration. :param iter: The current iteration number. :type iter: int :raises ValueError: If batch size exceeds the number of available data points. .. py:method:: _coarse_rigid_alignment(n_sampling=20000) Perform coarse rigid alignment between two sets of spatial coordinates. This method performs downsampling, voxelization, and matching pairs construction based on brute force mutual K-nearest neighbors (K-NN). It calculates the similarity distance based on gene expression and performs a coarse alignment using inlier estimation. Optionally, it allows flipping the data for better alignment. :param n_sampling: The number of samples to use for downsampling. Defaults to 20000. :type n_sampling: int, optional :raises ValueError: If any required representation is not found in the AnnData objects. :raises RuntimeError: If coarse rigid alignment fails after reducing top_K. .. py:method:: _save_iter(iter: int) Save the current iteration's alignment results. This method saves the current transformed coordinates and the sigma2 value for the specified iteration. It normalizes the coordinates if normalization is enabled. :param iter: The current iteration number. :type iter: int :raises KeyError: If `key_added` or "sigma2" key is not found in `iter_added`. .. py:method:: _update_assignment_P() Update the assignment matrix P. This method calculates the assignment matrix P, which represents the probability of cells in the sampleB are generated by the cells in sampleA. It considers both spatial and expression / representation distances and updates variational parameters accordingly. :param None: :raises ValueError: If any required representation is not found in the AnnData objects. .. py:method:: _update_gamma() Update the gamma parameter. This method updates the gamma parameter based on the current state of the alignment process. It adjusts gamma using the digamma function (_psi) and ensures that gamma remains within the range [0.01, 0.99]. .. py:method:: _update_alpha() Update the gamma parameter. This method updates the gamma parameter based on the current state of the alignment process. It adjusts gamma using the digamma function (_psi) and ensures that gamma remains within the range [0.01, 0.99]. .. py:method:: _update_nonrigid() Update the non-rigid transformation parameters. This method updates the non-rigid transformation parameters using the current state of the alignment process. It computes the Sigma inverse matrix, the PXB term, and updates the variational parameters for the non-rigid alignment. .. py:method:: _update_rigid() Update the rigid transformation parameters. This method updates the rigid transformation parameters using the current state of the alignment process. It solves for rotation and translation using the SVD formula and incorporates guidance and nearest neighbor initialization if applicable. .. py:method:: _update_sigma2(iter: int) Update the sigma2 parameter. This method updates the sigma2 parameter based on the current state of the alignment process. It ensures that sigma2 remains above a certain threshold to prevent numerical instability. :param iter: The current iteration number. :type iter: int :raises ValueError: If sigma2 is not properly updated. .. py:method:: _get_optimal_R() Compute the optimal rotation matrix R and translation vector t. This method computes the optimal rotation matrix and translation vector for aligning the coordinates of sample A to sample B. It uses the SVD formula to determine the optimal rotation and ensures that the transformation maintains the correct orientation. :raises ValueError: If the SVD decomposition fails or if the determinant check fails. .. py:method:: _wrap_output() Wrap the output after the alignment process. This method denormalizes the aligned coordinates, converts them to numpy arrays, and saves them in the instance. It also prepares a dictionary containing the transformation parameters and metadata if `vecfld_key_added` is not None. .. py:class:: Mesh_correction(slices: List[anndata.AnnData], z_heights: Union[List, numpy.ndarray], mesh: pyvista.PolyData, spatial_key: str = 'spatial', key_added: str = 'align_spatial', normalize_spatial: bool = False, init_rotation: Optional[numpy.ndarray] = np.array([0.0, 0.0, 0.0]), init_translation: Optional[numpy.ndarray] = 0.0, init_scaling: Optional[numpy.ndarray] = 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: Optional[int] = None, verbose: bool = False) A class to perform 3D reconstruction correction from slices using a mesh. .. attribute:: slices A list of aligned slices by Spateo or other methods. :type: List[AnnData] .. attribute:: z_heights The z-coordinates for each slice. :type: Union[List, np.ndarray] .. attribute:: mesh The mesh used for correction. :type: PolyData .. attribute:: spatial_key The key to access spatial coordinates in the AnnData objects. The spatial coordinates under this key should be pre-aligned. :type: str .. attribute:: key_added The key under which the corrected spatial coordinates will be added. :type: str .. attribute:: normalize_spatial Flag indicating if spatial coordinates will be normalized. :type: bool .. attribute:: init_rotation Initial rotation angles (in degrees) for the correction. :type: np.ndarray .. attribute:: init_translation Initial translation vector for the correction. :type: np.ndarray .. attribute:: init_scaling Initial scaling factor for the correction. :type: np.ndarray .. attribute:: max_rotation_angle Maximum rotation angle allowed during the correction process. :type: float .. attribute:: max_translation_scale Maximum translation scale allowed during the correction process. :type: float .. attribute:: max_scaling Maximum scaling factor allowed during the correction process. :type: float .. attribute:: label_num Number of labels used for optimization. :type: int .. attribute:: fastpd_iter Number of iterations for the fastPD algorithm. :type: int .. attribute:: max_iter Maximum number of iterations for the correction process. :type: int .. attribute:: anneal_rate Annealing rate for the optimization process. :type: float .. attribute:: multi_processing Flag indicating if multiprocessing will be used for the correction process. :type: bool .. py:attribute:: n_slices .. py:attribute:: slices_spatial .. py:attribute:: z_heights .. py:attribute:: mesh .. py:attribute:: key_added .. py:attribute:: normalize_spatial .. py:attribute:: max_rotation_angle .. py:attribute:: max_translation_scale .. py:attribute:: max_scaling .. py:attribute:: min_rotation_angle .. py:attribute:: min_translation_scale .. py:attribute:: min_scaling .. py:attribute:: label_num .. py:attribute:: fastpd_iter .. py:attribute:: max_iter .. py:attribute:: anneal_rate .. py:attribute:: multi_processing .. py:attribute:: subsample_slices .. py:attribute:: verbose .. py:attribute:: contours .. py:method:: set_init_parameters(init_rotation: Optional[numpy.ndarray] = np.array([0.0, 0.0, 0.0]), init_translation: Optional[numpy.ndarray] = 0.0, init_scaling: Optional[numpy.ndarray] = 1.0) Sets the initial transformation parameters for the mesh. :param init_rotation: Initial rotation angles (in degrees) for the mesh. Defaults to np.array([0., 0., 0.]). :type init_rotation: Optional[np.ndarray], optional :param init_translation: Initial translation vector for the mesh. Defaults to 0. :type init_translation: Optional[np.ndarray], optional :param init_scaling: Initial scaling factor for the mesh. Defaults to 1. :type init_scaling: Optional[np.ndarray], optional .. py:method:: normalize_mesh_spatial_coordinates() 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. .. py:method:: extract_contours(method: Literal['opencv', 'alpha_shape'] = 'alpha_shape', n_sampling: Optional[int] = None, smoothing: bool = True, window_size: int = 5, filter_contours: bool = True, contour_filter_threshold: int = 20, opencv_kwargs: Optional[Dict] = None, alpha_shape_kwargs: Optional[Dict] = None) Extracts contours of slices using the specified method. :param method: Method to extract contours. Defaults to "alpha_shape". :type method: Literal["opencv", "alpha_shape"], optional :param n_sampling: Number of points to sample from each slice. Defaults to None. :type n_sampling: Optional[int], optional :param smoothing: Whether to smooth the contours. Defaults to True. :type smoothing: bool, optional :param window_size: Window size for contour smoothing. Defaults to 5. :type window_size: int, optional :param filter_contours: Whether to filter the contours based on the threshold. Defaults to True. :type filter_contours: bool, optional :param contour_filter_threshold: Threshold for filtering contours based on the number of points. Defaults to 20. :type contour_filter_threshold: int, optional :param opencv_kwargs: Additional arguments for the OpenCV method. Defaults to None. :type opencv_kwargs: Optional[Dict], optional :param alpha_shape_kwargs: Additional arguments for the alpha shape method. Defaults to None. :type alpha_shape_kwargs: Optional[Dict], optional .. py:method:: run_discrete_optimization() -> None Runs the discrete optimization process to find the best transformation parameters. .. py:method:: discrete_optimization_step() -> Tuple[float, numpy.ndarray] Performs a discrete optimization step to find the best transformation. :returns: The loss and the best transformation found. :rtype: Tuple[float, np.ndarray] .. py:method:: generate_labels() -> numpy.ndarray Generates discrete labels for rotation, translation, and scaling. :returns: An array of discrete transformation labels. :rtype: np.ndarray .. py:method:: perform_correction() Performs the correction using the best transformation found. .. py:function:: generalized_procrustes_analysis(X, Y, pi) Finds and applies optimal rotation between spatial coordinates of two layers (may also do a reflection). :param X: np array of spatial coordinates. :param Y: np array of spatial coordinates. :param pi: mapping between the two layers output by PASTE. :returns: Aligned spatial coordinates of X, Y and the mapping relations. .. py:function:: paste_center_align(init_center_sample: anndata.AnnData, samples: List[anndata.AnnData], layer: str = 'X', genes: Optional[Union[list, numpy.ndarray]] = None, spatial_key: str = 'spatial', lmbda: Optional[numpy.ndarray] = None, alpha: float = 0.1, n_components: int = 15, threshold: float = 0.001, max_iter: int = 10, numItermax: int = 200, numItermaxEmd: int = 100000, dissimilarity: str = 'kl', norm: bool = False, random_seed: Optional[int] = None, pis_init: Optional[List[numpy.ndarray]] = None, distributions: Optional[List[numpy.ndarray]] = None, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True) -> Tuple[anndata.AnnData, List[numpy.ndarray]] Computes center alignment of slices. :param init_center_sample: Sample to use as the initialization for center alignment; Make sure to include gene expression and spatial information. :param samples: List of samples to use in the center alignment. :param layer: If `'X'`, uses ``sample.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``sample.layers[layer]``. :param genes: Genes used for calculation. If None, use all common genes for calculation. :param spatial_key: The key in `.obsm` that corresponds to the raw spatial coordinates. :param lmbda: List of probability weights assigned to each slice; If ``None``, use uniform weights. :param alpha: Alignment tuning parameter. Note: 0 <= alpha <= 1. When α = 0 only the gene expression data is taken into account, while when α =1 only the spatial coordinates are taken into account. :param n_components: Number of components in NMF decomposition. :param threshold: Threshold for convergence of W and H during NMF decomposition. :param max_iter: Maximum number of iterations for our center alignment algorithm. :param numItermax: Max number of iterations for cg during FGW-OT. :param numItermaxEmd: Max number of iterations for emd during FGW-OT. :param dissimilarity: Expression dissimilarity measure: ``'kl'`` or ``'euclidean'``. :param norm: If ``True``, scales spatial distances such that neighboring spots are at distance 1. Otherwise, spatial distances remain unchanged. :param random_seed: Set random seed for reproducibility. :param pis_init: Initial list of mappings between 'A' and 'slices' to solver. Otherwise, default will automatically calculate mappings. :param distributions: Distributions of spots for each slice. Otherwise, default is uniform. :param dtype: The floating-point number type. Only float32 and float64. :param device: Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'. :param verbose: If ``True``, print progress updates. :returns: - Inferred center sample with full and low dimensional representations (W, H) of the gene expression matrix. - List of pairwise alignment mappings of the center sample (rows) to each input sample (columns). .. py:function:: paste_pairwise_align(sampleA: anndata.AnnData, sampleB: anndata.AnnData, layer: str = 'X', genes: Optional[Union[list, numpy.ndarray]] = None, spatial_key: str = 'spatial', alpha: float = 0.1, dissimilarity: str = 'kl', G_init=None, a_distribution=None, b_distribution=None, norm: bool = False, numItermax: int = 200, numItermaxEmd: int = 100000, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True) -> Tuple[numpy.ndarray, Optional[int]] Calculates and returns optimal alignment of two slices. :param sampleA: Sample A to align. :param sampleB: Sample B to align. :param layer: If `'X'`, uses ``sample.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``sample.layers[layer]``. :param genes: Genes used for calculation. If None, use all common genes for calculation. :param spatial_key: The key in `.obsm` that corresponds to the raw spatial coordinates. :param alpha: Alignment tuning parameter. Note: 0 <= alpha <= 1. When α = 0 only the gene expression data is taken into account, while when α =1 only the spatial coordinates are taken into account. :param dissimilarity: Expression dissimilarity measure: ``'kl'`` or ``'euclidean'``. :param G_init: Initial mapping to be used in FGW-OT, otherwise default is uniform mapping. :param a_distribution: Distribution of sampleA spots, otherwise default is uniform. :param b_distribution: Distribution of sampleB spots, otherwise default is uniform. :param norm: If ``True``, scales spatial distances such that neighboring spots are at distance 1. Otherwise, spatial distances remain unchanged. :param numItermax: Max number of iterations for cg during FGW-OT. :param numItermaxEmd: Max number of iterations for emd during FGW-OT. :param dtype: The floating-point number type. Only float32 and float64. :param device: Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'. :param verbose: If ``True``, print progress updates. :returns: Alignment of spots. obj: Objective function output of FGW-OT. :rtype: pi .. py:data:: _chunk .. py:data:: _data .. py:data:: _dot .. py:data:: _mul .. py:data:: _pi .. py:data:: _power .. py:data:: _prod .. py:data:: _unsqueeze .. py:function:: calc_distance(X: Union[List[Union[numpy.ndarray, torch.Tensor]], Union[numpy.ndarray, torch.Tensor]], Y: Union[List[Union[numpy.ndarray, torch.Tensor]], Union[numpy.ndarray, torch.Tensor]], metric: Union[List[str], str] = 'euc', label_transfer: Optional[Union[numpy.ndarray, torch.Tensor]] = None) -> Union[numpy.ndarray, torch.Tensor] Calculate the distance between all pairs of samples in matrices X and Y using the specified metric. :param X: Matrix with shape (N, D), where each row represents a sample. :type X: np.ndarray or torch.Tensor :param Y: Matrix with shape (M, D), where each row represents a sample. :type Y: np.ndarray or torch.Tensor :param metric: The metric to use for calculating distances. Options are 'euc', 'euclidean', 'square_euc', 'square_euclidean', 'kl', 'sym_kl', 'cos', 'cosine', 'label'. Default is 'euc'. :type metric: str, optional :param label_transfer: Matrix with shape (K, L) containing the label transfer cost. Required if metric is 'label'. Default is None. :type label_transfer: Optional[np.ndarray or torch.Tensor], optional :returns: Pairwise distance matrix with shape (N, M). :rtype: 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. .. py:function:: check_backend(device: str = 'cpu', dtype: str = 'float32', verbose: bool = True) Check the proper backend for the device. :param device: Equipment used to run the program. You can also set the specified GPU for running. E.g.: '0'. :param dtype: The floating-point number type. Only float32 and float64. :param verbose: If ``True``, print progress updates. :returns: The proper backend. type_as: The type_as.device is the device used to run the program and the type_as.dtype is the floating-point number type. :rtype: backend .. py:function:: check_exp(sample: anndata.AnnData, layer: str = 'X') -> numpy.ndarray Check expression matrix. :param sample: An AnnData object containing the sample data. :type sample: AnnData :param layer: The key in `.layers` that corresponds to the expression matrix. Defaults to "X". :type layer: str, optional :returns: The expression matrix. :raises KeyError: If the specified layer is not found in `sample.layers`. .. py:function:: con_K(X: Union[numpy.ndarray, torch.Tensor], Y: Union[numpy.ndarray, torch.Tensor], beta: Union[int, float] = 0.01) -> Union[numpy.ndarray, torch.Tensor] con_K constructs the Squared Exponential (SE) kernel, where K(i,j)=k(X_i,Y_j)=exp(-beta*||X_i-Y_j||^2). :param X: The first vector X\in\mathbb{R}^{N imes d} :param Y: The second vector X\in\mathbb{R}^{M imes d} :param beta: The length-scale of the SE kernel. :param use_chunk: Whether to use chunk to reduce the GPU memory usage. Note that if set to ``True'' it will slow down the calculation. Defaults to False. :type use_chunk: bool, optional :returns: The kernel K\in\mathbb{R}^{N imes M} :rtype: K .. py:function:: empty_cache(device: str = 'cpu') .. py:function:: filter_common_genes(*genes, verbose: bool = True) -> list Filters for the intersection of genes between all samples. :param genes: List of genes. :param verbose: If ``True``, print progress updates. .. py:function:: generate_label_transfer_dict(cat1: List[str], cat2: List[str], positive_pairs: Optional[List[Dict[str, Union[List[str], float]]]] = None, negative_pairs: Optional[List[Dict[str, Union[List[str], float]]]] = None, default_positve_value: float = 10.0) -> Dict[str, Dict[str, float]] Generate a label transfer dictionary with normalized values. :param cat1: List of categories from the first dataset. :type cat1: List[str] :param cat2: List of categories from the second dataset. :type cat2: List[str] :param positive_pairs: List of positive pairs with transfer values. Each dictionary should have 'left', 'right', and 'value' keys. Defaults to None. :type positive_pairs: Optional[List[Dict[str, Union[List[str], float]]]], optional :param negative_pairs: List of negative pairs with transfer values. Each dictionary should have 'left', 'right', and 'value' keys. Defaults to None. :type negative_pairs: Optional[List[Dict[str, Union[List[str], float]]]], optional :param default_positive_value: Default value for positive pairs if none are provided. Defaults to 10.0. :type default_positive_value: float, optional :returns: A normalized label transfer dictionary. :rtype: Dict[str, Dict[str, float]] .. py:data:: intersect_lsts