spateo.alignment ================ .. py:module:: spateo.alignment Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/spateo/alignment/deformation/index /autoapi/spateo/alignment/methods/index /autoapi/spateo/alignment/morpho_alignment/index /autoapi/spateo/alignment/paste_alignment/index /autoapi/spateo/alignment/transform/index /autoapi/spateo/alignment/utils/index Classes ------- .. autoapisummary:: spateo.alignment.Mesh_correction Functions --------- .. autoapisummary:: spateo.alignment.grid_deformation spateo.alignment.align_preprocess spateo.alignment.calc_distance spateo.alignment.calc_exp_dissimilarity spateo.alignment.generate_label_transfer_dict spateo.alignment.morpho_align spateo.alignment.morpho_align_apply_transformation spateo.alignment.morpho_align_ref spateo.alignment.morpho_align_transformation spateo.alignment.paste_align spateo.alignment.paste_align_ref spateo.alignment.BA_transform spateo.alignment.BA_transform_and_assignment spateo.alignment.paste_transform spateo.alignment.downsampling spateo.alignment.generate_label_transfer_prior spateo.alignment.get_labels_based_on_coords spateo.alignment.get_optimal_mapping_relationship spateo.alignment.group_pca spateo.alignment.mapping_aligned_coords spateo.alignment.mapping_center_coords spateo.alignment.rigid_transformation spateo.alignment.solve_RT_by_correspondence spateo.alignment.split_slice spateo.alignment.tps_deformation Package Contents ---------------- .. py:function:: grid_deformation(model: anndata.AnnData, spatial_key: str = 'spatial', vecfld_key: str = 'VecFld_morpho', key_added: str = 'deformation', deformation_scale: int = 3, grid_num: Optional[numpy.asarray] = None, dtype: str = 'float64', device: str = 'cpu') .. 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 :value: 'align_spatial' .. py:attribute:: normalize_spatial :value: False .. py:attribute:: max_rotation_angle :value: 180 .. py:attribute:: max_translation_scale :value: 0.5 .. py:attribute:: max_scaling :value: 1.5 .. py:attribute:: min_rotation_angle :value: 10 .. py:attribute:: min_translation_scale :value: 1 .. py:attribute:: min_scaling :value: 1.1 .. py:attribute:: label_num :value: 15 .. py:attribute:: fastpd_iter :value: 100 .. py:attribute:: max_iter :value: 10 .. py:attribute:: anneal_rate :value: 0.7 .. py:attribute:: multi_processing :value: False .. py:attribute:: subsample_slices :value: None .. py:attribute:: verbose :value: False .. 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:: 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[spateo.alignment.methods.backend.TorchBackend, spateo.alignment.methods.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:: 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:: 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: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_positive_value: float = 10.0, default_negative_value: float = 1.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 :param default_negative_value: Default value for negative pairs if none are provided. Defaults to 1.0. :type default_negative_value: float, optional :returns: A normalized label transfer dictionary. :rtype: Dict[str, Dict[str, float]] .. py:function:: morpho_align(models: List[anndata.AnnData], rep_layer: Union[str, List[str]] = 'X', rep_field: Union[str, List[str]] = 'layer', genes: Optional[Union[List[str], numpy.ndarray]] = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: Optional[str] = 'iter_spatial', vecfld_key_added: str = 'VecFld_morpho', mode: Literal['SN-N', 'SN-S'] = 'SN-S', dissimilarity: Union[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]] Continuous alignment of spatial transcriptomic coordinates based on Morpho. :param models: List of models (AnnData Object). :param layer: If ``'X'``, uses ``.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``.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 coordinate. :param key_added: ``.obsm`` key under which to add the aligned spatial coordinate. :param 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. :param 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. :param 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'``. :param dissimilarity: Expression dissimilarity measure: ``'kl'`` or ``'euclidean'``. :param max_iter: Max number of iterations for morpho alignment. :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. :param \*\*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. :rtype: align_models .. py:function:: morpho_align_apply_transformation(models: List[Union[anndata.AnnData, str]], models_path: Optional[str] = None, transformation: List[dict] = None, transformation_path: Optional[str] = './Spateo_transformation', spatial_key: str = 'spatial', key_added: str = 'align_spatial', save_models_path: Optional[str] = None, verbose: bool = True) Apply the transformation to the models. :param models: _description_ :type models: List[AnnData] :param transformation: _description_ :type transformation: List[dict] :returns: _description_ :rtype: _type_ .. py:function:: morpho_align_ref(models: List[anndata.AnnData], models_ref: Optional[List[anndata.AnnData]] = None, n_sampling: Optional[int] = 2000, sampling_method: str = 'random', 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', key_added: str = 'align_spatial', iter_key_added: Optional[str] = 'iter_spatial', vecfld_key_added: Optional[str] = 'VecFld_morpho', mode: Literal['SN-N', 'SN-S'] = 'SN-S', dissimilarity: Union[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]] Continuous alignment of spatial transcriptomic coordinates with the reference models based on Morpho. :param models: List of models (AnnData Object). :param models_ref: Another list of models (AnnData Object). :param n_sampling: When ``models_ref`` is None, new data containing n_sampling coordinate points will be automatically generated for alignment. :param sampling_method: The method to sample data points, can be one of ``["trn", "kmeans", "random"]``. :param layer: If ``'X'``, uses ``.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``.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 coordinate. :param key_added: ``.obsm`` key under which to add the aligned spatial coordinate. :param 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. :param 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. :param 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'``. :param dissimilarity: Expression dissimilarity measure: ``'kl'`` or ``'euclidean'``. :param max_iter: Max number of iterations for morpho alignment. :param SVI_mode: Whether to use stochastic variational inferential (SVI) optimization strategy. :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. :param \*\*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. :rtype: align_models .. py:function:: morpho_align_transformation(models: List[Union[anndata.AnnData, str]], models_path: Optional[str] = None, save_transformation: bool = False, transformation_path: Optional[str] = './Spateo_transformation', resume: bool = False, rep_layer: Union[str, List[str]] = 'X', rep_field: Union[str, List[str]] = 'layer', genes: Optional[Union[List[str], numpy.ndarray]] = None, spatial_key: str = 'spatial', key_added: str = 'align_spatial', iter_key_added: Optional[str] = 'iter_spatial', vecfld_key_added: str = 'VecFld_morpho', dissimilarity: Union[str, List[str]] = 'kl', max_iter: int = 200, dtype: str = 'float32', device: str = 'cpu', verbose: bool = True, **kwargs) Continuous alignment of spatial transcriptomic coordinates based on Morpho, and return the transformation matrix. :param models: _description_ :type models: List[AnnData] :returns: _description_ :rtype: _type_ .. py:function:: paste_align(models: List[anndata.AnnData], layer: str = 'X', genes: Optional[Union[list, numpy.ndarray]] = 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[Union[numpy.ndarray, numpy.ndarray]]] Align spatial coordinates of models. :param models: List of models (AnnData Object). :param layer: If ``'X'``, uses ``.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``.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 coordinate. :param key_added: ``.obsm`` key under which to add the aligned spatial coordinates. :param mapping_key_added: `.uns` key under which to add the alignment info. :param 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. :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. :param \*\*kwargs: Additional parameters that will be passed to ``pairwise_align`` function. :returns: List of models (AnnData Object) after alignment. pis: List of pi matrices. :rtype: align_models .. py:function:: paste_align_ref(models: List[anndata.AnnData], models_ref: Optional[List[anndata.AnnData]] = None, n_sampling: Optional[int] = 2000, sampling_method: str = 'trn', layer: str = 'X', genes: Optional[Union[list, numpy.ndarray]] = 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[Union[numpy.ndarray, numpy.ndarray]]] Align the spatial coordinates of one model list through the affine transformation matrix obtained from another model list. :param models: List of models (AnnData Object). :param models_ref: Another list of models (AnnData Object). :param n_sampling: When ``models_ref`` is None, new data containing n_sampling coordinate points will be automatically generated for alignment. :param sampling_method: The method to sample data points, can be one of ``["trn", "kmeans", "random"]``. :param layer: If ``'X'``, uses ``.X`` to calculate dissimilarity between spots, otherwise uses the representation given by ``.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 key_added: ``.obsm`` key under which to add the aligned spatial coordinates. :param mapping_key_added: `.uns` key under which to add the alignment info. :param 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. :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. :param \*\*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. :rtype: align_models .. py:function:: BA_transform(vecfld, quary_points, deformation_scale: int = 1, dtype: str = 'float64', device: str = 'cpu') Apply non-rigid transform to the quary points :param vecfld: A dictionary containing information about vector fields :param quary_points: :param deformation_scale: If deformation_scale is greater than 1, increase the degree of deformation. :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'``. .. py:function:: BA_transform_and_assignment(samples, vecfld, layer: str = 'X', genes: Optional[Union[List, torch.Tensor]] = None, spatial_key: str = 'spatial', small_variance: bool = False, dtype: str = 'float64', device: str = 'cpu', verbose: bool = False) .. py:function:: 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 Align the space coordinates of the new model with the transformation matrix obtained from PASTE. :param adata: The anndata object that need to be aligned. :param adata_ref: The anndata object that have been aligned by PASTE. :param spatial_key: The key in `.obsm` that corresponds to the raw spatial coordinates. :param key_added: ``.obsm`` key under which to add the aligned spatial coordinates. :param mapping_key: The key in `.uns` that corresponds to the alignment info from PASTE. :returns: The anndata object that have been to be aligned. :rtype: adata .. py:function:: downsampling(models: Union[List[anndata.AnnData], anndata.AnnData], n_sampling: Optional[int] = 2000, sampling_method: str = 'trn', spatial_key: str = 'spatial') -> Union[List[anndata.AnnData], anndata.AnnData] .. py:function:: generate_label_transfer_prior(cat1, cat2, positive_pairs=None, negative_pairs=None) .. py:function:: get_labels_based_on_coords(model: anndata.AnnData, coords: numpy.ndarray, labels_key: Union[str, List[str]], spatial_key: str = 'align_spatial') -> pandas.DataFrame Obtain the label information in anndata.obs[key] corresponding to the coords. .. py:function:: get_optimal_mapping_relationship(X: numpy.ndarray, Y: numpy.ndarray, pi: numpy.ndarray, keep_all: bool = False) .. py:function:: 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 Perform PCA on a concatenated set of AnnData objects and store the results back in each individual AnnData. Parameters: ---------- adatas : List[AnnData] A list of AnnData objects to be concatenated and processed. batch_key : str, optional The key to distinguish different batches in the concatenated AnnData object (default is 'batch'). pca_key : str, optional The key under which to store the PCA results in each AnnData's `.obsm` attribute (default is 'X_pca'). use_hvg : bool, optional Whether to perform PCA using only highly variable genes (default is True). hvg_key : str, 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. .. py:function:: mapping_aligned_coords(X: numpy.ndarray, Y: numpy.ndarray, pi: numpy.ndarray, keep_all: bool = False) -> Tuple[dict, dict] Optimal mapping coordinates between X and Y. :param X: Aligned spatial coordinates. :param Y: Aligned spatial coordinates. :param pi: Mapping between the two layers output by PASTE. :param 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. .. py:function:: mapping_center_coords(modelA: anndata.AnnData, modelB: anndata.AnnData, center_key: str) -> dict Optimal mapping coordinates between X and Y based on intermediate coordinates. :param modelA: modelA aligned with center model. :param modelB: modelB aligned with center model. :param 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. .. py:function:: rigid_transformation(adata, spatial_key, key_added, theta=None, translation=None, inplace=True) .. py:function:: solve_RT_by_correspondence(X: numpy.ndarray, Y: numpy.ndarray, return_scale: bool = False) -> Union[Tuple[numpy.ndarray, numpy.ndarray], Tuple[numpy.ndarray, numpy.ndarray, float]] Solve for the rotation matrix R and translation vector t that best align the points in X to the points in Y. :param X: Source points, shape (N, D). :type X: np.ndarray :param Y: Target points, shape (N, D). :type Y: np.ndarray :param return_scale: Whether to return the scale factor. Defaults to False. :type return_scale: bool, optional :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. :rtype: Union[Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray, float]] .. py:function:: split_slice(adata, spatial_key, split_num=5, axis=2) .. py:function:: tps_deformation(adata, spatial_key, key_added, grid_num=2, tps_noise_scale=25, add_corner_points=True, alpha=0.1, inplace=True)