spateo.alignment.methods.deprecated_utils

Attributes

Functions

check_backend([device, dtype, verbose])

Check the proper backend for the device.

check_spatial_coords(→ numpy.ndarray)

Check and return the spatial coordinate information from an AnnData object.

check_exp(→ numpy.ndarray)

Check expression matrix.

check_obs(→ Optional[str])

Check that the number of occurrences of 'obs' in the list of representation fields is no more than one.

check_rep_layer(→ bool)

Check if specified representations exist in the .layers, .obsm, or .obs attributes of AnnData objects.

check_label_transfer_dict(catA, catB, label_transfer_dict)

Check the label transfer dictionary for consistency with given categories.

check_label_transfer(→ List[Union[numpy.ndarray, ...)

Check and generate label transfer matrices for the given samples.

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

Generate a label transfer dictionary with normalized values.

get_rep(→ numpy.ndarray)

Get the specified representation from the AnnData object.

filter_common_genes(→ list)

Filters for the intersection of genes between all samples.

normalize_coords(→ Tuple[List[Union[numpy.ndarray, ...)

Normalize the spatial coordinate.

normalize_exps(→ List[List[Union[numpy.ndarray, ...)

Normalize the gene expression matrices.

align_preprocess(...)

Preprocess the data before alignment.

guidance_pair_preprocess(→ List[Union[torch.Tensor, ...)

Preprocess guidance pairs by normalizing them.

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

Compute the pairwise KL divergence between all pairs of samples in matrices X and Y.

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

Compute the pairwise cosine similarity between all pairs of samples in matrices X and Y.

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

Compute the pairwise Euclidean distance between all pairs of samples in matrices X and Y.

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

Generate a matrix of size (N, M) by indexing into the label_transfer matrix using the values in X and Y.

_correlation_distance_backend(X, Y)

_jaccard_distance_backend(X, Y)

_chebyshev_distance_backend(X, Y)

_canberra_distance_backend(X, Y)

_braycurtis_distance_backend(X, Y)

_hamming_distance_backend(X, Y)

_minkowski_distance_backend(X, Y)

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_probability(→ Union[numpy.ndarray, torch.Tensor])

Calculate probability based on the distance matrix and specified probability type.

get_P_core(nx, type_as, Dim, spatial_dist, exp_dist, ...)

Compute assignment matrix P and additional results based on given distances and parameters.

get_P(nx, type_as, Dim, spatial_dist, exp_dist, ...[, ...])

get_P_sparse(nx, type_as, Dim, spatial_XA, spatial_XB, ...)

Calculate sparse assignment matrix P using spatial and expression / representation distances.

update_Sp(nx, type_as, step_size, batch_size, ...)

update_gamma(nx, type_as, gamma, batch_size, gamma_a, ...)

update_alpha(nx, type_as, step_size, alpha, kappa, NA, ...)

update_nonrigid(nx, type_as, SVI_mode, ...)

update_rigid(nx, type_as)

update_sigma2()

update_assignment_P()

con_K(→ 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).

con_K_geodist()

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

Construct a kernel matrix for spatial data.

kl_divergence_backend(X, Y[, probabilistic])

Returns pairwise KL divergence (over all pairs of samples) of two matrices X and Y.

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

Calculate the KL distance between two vectors

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

Calculate expression dissimilarity.

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

Calculate the distance between two vectors

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

Calculate the matrix multiplication of two matrices

get_optimal_R(coordsA, coordsB, P, R_init)

Get the optimal rotation matrix R

_cal_cosine_similarity(tensor1, tensor2[, dim, eps])

_cos_similarity(mat1, mat2)

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

coarse_rigid_alignment(→ Tuple[Any, Any, Any, Any, ...)

coarse_rigid_alignment(→ Tuple[Any, Any, Any, Any, ...)

inlier_from_NN(train_x, train_y, distance)

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

inlier_from_NN_debug(train_x, train_y, distance)

voxel_data(nx, coords, gene_exp[, voxel_size, voxel_num])

Voxelization of the data.

_init_guess_sigma2(XA, XB[, subsample])

_init_probability_parameters(exp_layer_A, exp_layer_B)

Initialize probability parameters for the given expression layers.

_get_anneling_factor(nx, type_as, start, end, iter)

_init_guess_beta2(nx, XA, XB[, dissimilarity, ...])

_dense_to_sparse(mat[, sparse_method, threshold, ...])

empty_cache([device])

torch_like_split(arr, size[, dim])

Module Contents

spateo.alignment.methods.deprecated_utils.intersect_lsts[source]
spateo.alignment.methods.deprecated_utils.to_dense_matrix[source]
spateo.alignment.methods.deprecated_utils.extract_data_matrix[source]
spateo.alignment.methods.deprecated_utils.check_backend(device: str = 'cpu', dtype: str = 'float32', verbose: bool = True)[source]

Check the proper backend for the device.

Parameters:
device

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

dtype

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

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.

Return type:

backend

spateo.alignment.methods.deprecated_utils.check_spatial_coords(sample: anndata.AnnData, spatial_key: str = 'spatial') numpy.ndarray[source]

Check and return the spatial coordinate information from an AnnData object.

Parameters:
sample AnnData

An AnnData object containing the sample data.

spatial_key str, optional

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

Returns:

The spatial coordinates.

Return type:

np.ndarray

Raises:

KeyError – If the specified spatial_key is not found in sample.obsm.

spateo.alignment.methods.deprecated_utils.check_exp(sample: anndata.AnnData, layer: str = 'X') numpy.ndarray[source]

Check expression matrix.

Parameters:
sample AnnData

An AnnData object containing the sample data.

layer str, optional

The key in .layers that corresponds to the expression matrix. Defaults to “X”.

Returns:

The expression matrix.

Raises:

KeyError – If the specified layer is not found in sample.layers.

spateo.alignment.methods.deprecated_utils.check_obs(rep_layer: List[str], rep_field: List[str]) str | None[source]

Check that the number of occurrences of ‘obs’ in the list of representation fields is no more than one.

Parameters:
rep_layer List[str]

A list of representations to check.

rep_field List[str]

A list of representation types corresponding to the representations in rep_layer.

Returns:

The representation key if ‘obs’ occurs exactly once, otherwise None.

Return type:

Optional[str]

Raises:

ValueError – If ‘obs’ occurs more than once in the list.

spateo.alignment.methods.deprecated_utils.check_rep_layer(samples: List[anndata.AnnData], rep_layer: str | List[str] = 'X', rep_field: str | List[str] = 'layer') bool[source]

Check if specified representations exist in the .layers, .obsm, or .obs attributes of AnnData objects.

Parameters:
samples List[AnnData]

A list of AnnData objects containing the data samples.

rep_layer Union[str, List[str]], optional

The representation layer(s) to check. Defaults to “X”.

rep_field Union[str, List[str]], optional

The field(s) indicating the type of representation. Acceptable values are “layer”, “obsm”, and “obs”. Defaults to “layer”.

Returns:

True if all specified representations exist in the corresponding attributes of all AnnData objects, False otherwise.

Return type:

bool

Raises:

ValueError – If the specified representation is not found in the specified attribute or if the attribute type is invalid.

spateo.alignment.methods.deprecated_utils.check_label_transfer_dict(catA: List[str], catB: List[str], label_transfer_dict: Dict[str, Dict[str, float]])[source]

Check the label transfer dictionary for consistency with given categories.

Parameters:
catA List[str]

List of category labels from the first dataset.

catB List[str]

List of category labels from the second dataset.

label_transfer_dict Dict[str, Dict[str, float]]

Dictionary defining the transfer probabilities between categories.

Raises:
  • KeyError – If a category from catA is not found in label_transfer_dict.

  • KeyError – If a category from catB is not found in the nested dictionary of label_transfer_dict.

spateo.alignment.methods.deprecated_utils.check_label_transfer(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, samples: List[anndata.AnnData], obs_key: str, label_transfer_dict: List[Dict[str, Dict[str, float]]] | None = None) List[numpy.ndarray | torch.Tensor][source]

Check and generate label transfer matrices for the given samples.

Parameters:
nx module

Backend module (e.g., numpy or torch).

type_as type

Type to which the output should be cast.

samples List[AnnData]

List of AnnData objects containing the samples.

obs_key str

The key in .obs that corresponds to the labels.

label_transfer_dict Optional[List[Dict[str, Dict[str, float]]]], optional

List of dictionaries defining the label transfer cost between categories of each pair of samples. Defaults to None.

Returns:

List of label transfer matrices, each as either a NumPy array or torch Tensor.

Return type:

List[Union[np.ndarray, torch.Tensor]]

Raises:

ValueError – If the length of label_transfer_dict does not match len(samples) - 1.

spateo.alignment.methods.deprecated_utils.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_positve_value: float = 10.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.

Returns:

A normalized label transfer dictionary.

Return type:

Dict[str, Dict[str, float]]

spateo.alignment.methods.deprecated_utils.get_rep(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, sample: anndata.AnnData, rep: str = 'X', rep_field: str = 'layer', genes: list | numpy.ndarray | None = None) numpy.ndarray[source]

Get the specified representation from the AnnData object.

Parameters:
nx module

Backend module (e.g., numpy or torch).

type_as type

Type to which the output should be cast.

sample AnnData

The AnnData object containing the sample data.

rep str, optional

The name of the representation to retrieve. Defaults to “X”.

rep_field str, optional

The type of representation. Acceptable values are “layer”, “obs” and “obsm”. Defaults to “layer”.

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

List of genes to filter if rep_field is “layer”. Defaults to None.

Returns:

The requested representation from the AnnData object, cast to the specified type.

Return type:

Union[np.ndarray, torch.Tensor]

Raises:
  • ValueError – If rep_field is not one of the expected values.

  • KeyError – If the specified representation is not found in the AnnData object.

spateo.alignment.methods.deprecated_utils.filter_common_genes(*genes, verbose: bool = True) list[source]

Filters for the intersection of genes between all samples.

Parameters:
genes

List of genes.

verbose

If True, print progress updates.

spateo.alignment.methods.deprecated_utils.normalize_coords(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, coords: List[numpy.ndarray | torch.Tensor], verbose: bool = True, separate_scale: bool = True, separate_mean: bool = True) Tuple[List[numpy.ndarray | torch.Tensor], List[numpy.ndarray | torch.Tensor], List[numpy.ndarray | torch.Tensor]][source]

Normalize the spatial coordinate.

Parameters:
coords List[Union[np.ndarray, torch.Tensor]]

Spatial coordinates of the samples. Each element in the list can be a numpy array or a torch tensor.

nx Union[ot.backend.TorchBackend, ot.backend.NumpyBackend], optional

The backend to use for computations. Default is ot.backend.NumpyBackend.

verbose bool, optional

If True, print progress updates. Default is True.

separate_scale bool, optional

If True, normalize each coordinate axis independently. When doing the global refinement, this weill be set to False. Default is True.

separate_mean bool, optional

If True, normalize each coordinate axis to have zero mean independently. When doing the global refinement, this weill be set to False. Default is True.

Returns:

A tuple containing: - coords: List of normalized spatial coordinates. - normalize_scales: List of normalization scale factors applied to each coordinate axis. - normalize_means: List of mean values used for normalization of each coordinate axis.

Return type:

Tuple[List[Union[np.ndarray, torch.Tensor]], List[Union[np.ndarray, torch.Tensor]], List[Union[np.ndarray, torch.Tensor]]]

spateo.alignment.methods.deprecated_utils.normalize_exps(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, exp_layers: List[List[numpy.ndarray | torch.Tensor]], rep_field: str | List[str] = 'layer', verbose: bool = True) List[List[numpy.ndarray | torch.Tensor]][source]

Normalize the gene expression matrices.

Parameters:
nx Union[ot.backend.TorchBackend, ot.backend.NumpyBackend], optional

The backend to use for computations. Defaults to ot.backend.NumpyBackend.

exp_layers List[List[Union[np.ndarray, torch.Tensor]]]

Gene expression and optionally the representation matrices of the samples. Each element in the list can be a numpy array or a torch tensor.

rep_field Union[str, List[str]], optional

Field(s) indicating the type of representation. If ‘layer’, normalization can be applied. Defaults to “layer”.

verbose bool, optional

If True, print progress updates. Default is True.

Returns:

A list of lists containing normalized gene expression matrices. Each matrix in the list is a numpy array or a torch tensor.

Return type:

List[List[Union[np.ndarray, torch.Tensor]]]

spateo.alignment.methods.deprecated_utils.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[ot.backend.TorchBackend | ot.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.methods.deprecated_utils.guidance_pair_preprocess(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, guidance_pair: List[numpy.ndarray], normalize_scales: torch.Tensor | numpy.ndarray, normalize_means: torch.Tensor | numpy.ndarray) List[torch.Tensor | numpy.ndarray][source]

Preprocess guidance pairs by normalizing them.

Parameters:
nx Union[ot.backend.TorchBackend, ot.backend.NumpyBackend], optional

Backend module for computations (e.g., numpy or torch). Defaults to ot.backend.NumpyBackend.

type_as Union[torch.Tensor, np.ndarray]

Type to which the output should be cast.

guidance_pair List[np.ndarray]

List containing the guidance pairs as numpy arrays.

normalize_scales Union[torch.Tensor, np.ndarray]

Tensor or array of normalization scales.

normalize_means Union[torch.Tensor, np.ndarray]

Tensor or array of normalization means.

Returns:

List containing the normalized guidance pairs.

Return type:

List[Union[torch.Tensor, np.ndarray]]

spateo.alignment.methods.deprecated_utils._kl_distance_backend(X: numpy.ndarray | torch.Tensor, Y: numpy.ndarray | torch.Tensor, probabilistic: bool = True, eps: float = 1e-08) numpy.ndarray | torch.Tensor[source]

Compute the pairwise KL divergence between all pairs of samples in matrices X and Y.

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.

probabilistic bool, optional

If True, normalize the rows of X and Y to sum to 1 (to interpret them as probabilities). Default is True.

eps float, optional

A small value to avoid division by zero. Default is 1e-8.

Returns:

Pairwise KL divergence matrix with shape (N, M).

Return type:

np.ndarray

Raises:

AssertionError – If the number of features in X and Y do not match.

spateo.alignment.methods.deprecated_utils._cosine_distance_backend(X: numpy.ndarray | torch.Tensor, Y: numpy.ndarray | torch.Tensor, eps: float = 1e-08) numpy.ndarray | torch.Tensor[source]

Compute the pairwise cosine similarity between all pairs of samples in matrices X and Y.

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.

eps float, optional

A small value to avoid division by zero. Default is 1e-8.

Returns:

Pairwise cosine similarity 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.

spateo.alignment.methods.deprecated_utils._euc_distance_backend(X: numpy.ndarray | torch.Tensor, Y: numpy.ndarray | torch.Tensor, squared: bool = True) numpy.ndarray | torch.Tensor[source]

Compute the pairwise Euclidean distance between all pairs of samples in matrices X and Y.

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.

squared bool, optional

If True, return squared Euclidean distances. Default is True.

Returns:

Pairwise Euclidean 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.

spateo.alignment.methods.deprecated_utils._label_distance_backend(X: numpy.ndarray | torch.Tensor, Y: numpy.ndarray | torch.Tensor, label_transfer: numpy.ndarray | torch.Tensor) numpy.ndarray | torch.Tensor[source]

Generate a matrix of size (N, M) by indexing into the label_transfer matrix using the values in X and Y.

Parameters:
X np.ndarray or torch.Tensor

Array with shape (N, ) containing integer values ranging from 0 to K.

Y np.ndarray or torch.Tensor

Array with shape (M, ) containing integer values ranging from 0 to L.

label_transfer np.ndarray or torch.Tensor

Matrix with shape (K, L) containing the label transfer cost.

Returns:

Matrix with shape (N, M) where each element is the value from label_transfer indexed by the corresponding values in X and Y.

Return type:

np.ndarray or torch.Tensor

Raises:

AssertionError – If the shape of X or Y is not one-dimensional or if they contain non-integer values.

spateo.alignment.methods.deprecated_utils._correlation_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._jaccard_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._chebyshev_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._canberra_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._braycurtis_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._hamming_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils._minkowski_distance_backend(X, Y)[source]
spateo.alignment.methods.deprecated_utils.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.methods.deprecated_utils.calc_probability(distance_matrix: numpy.ndarray | torch.Tensor, probability_type: str = 'gauss', probability_parameter: float | None = None) numpy.ndarray | torch.Tensor[source]

Calculate probability based on the distance matrix and specified probability type.

Parameters:
distance_matrix np.ndarray or torch.Tensor

The distance matrix.

probability_type str, optional

The type of probability to calculate. Options are ‘Gauss’, ‘cos_prob’, and ‘prob’. Default is ‘Gauss’.

probability_parameter Optional[float], optional

The parameter for the probability calculation. Required for certain probability types. Default is None.

Returns:

The calculated probability matrix.

Return type:

np.ndarray or torch.Tensor

Raises:

ValueError – If probability_type is not one of the supported types or if required parameters are missing.

spateo.alignment.methods.deprecated_utils.get_P_core(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, Dim: torch.Tensor | numpy.ndarray, spatial_dist: numpy.ndarray | torch.Tensor, exp_dist: List[numpy.ndarray | torch.Tensor], sigma2: int | float | numpy.ndarray | torch.Tensor, model_mul: numpy.ndarray | torch.Tensor, gamma: float | numpy.ndarray | torch.Tensor, samples_s: List[float] | None = None, sigma2_variance: float = 1, probability_type: str | List[str] = 'Gauss', probability_parameters: List | None = None, eps: float = 1e-08, sparse_calculation_mode: bool = False, top_k: int = -1)[source]

Compute assignment matrix P and additional results based on given distances and parameters.

Parameters:
nx module

Backend module (e.g., numpy or torch).

type_as type

Type to which the output should be cast.

spatial_dist np.ndarray or torch.Tensor

Spatial distance matrix.

exp_dist List[np.ndarray or torch.Tensor]

List of expression distance matrices.

sigma2 int, float, np.ndarray or torch.Tensor

Sigma squared value.

alpha np.ndarray or torch.Tensor

Alpha values.

gamma float, np.ndarray or torch.Tensor

Gamma value.

Sigma np.ndarray or torch.Tensor

Sigma values.

samples_s Optional[List[float]], optional

Samples. Default is None.

sigma2_variance float, optional

Sigma squared variance. Default is 1.

probability_type Union[str, List[str]], optional

Probability type. Default is ‘Gauss’.

probability_parameters Optional[List[float]], optional

Probability parameters. Default is None.

Returns:

  • np.ndarray or torch.Tensor – Assignment matrix P.

  • dict – Additional results.

spateo.alignment.methods.deprecated_utils.get_P(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, Dim: torch.Tensor | numpy.ndarray, spatial_dist: numpy.ndarray | torch.Tensor, exp_dist: List[numpy.ndarray | torch.Tensor], sigma2: int | float | numpy.ndarray | torch.Tensor, alpha: numpy.ndarray | torch.Tensor, gamma: float | numpy.ndarray | torch.Tensor, Sigma: numpy.ndarray | torch.Tensor, samples_s: List[float] | None = None, sigma2_variance: float = 1, probability_type: str | List[str] = 'Gauss', probability_parameters: List[float] | None = None)[source]
spateo.alignment.methods.deprecated_utils.get_P_sparse(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, type_as: torch.Tensor | numpy.ndarray, Dim: torch.Tensor | numpy.ndarray, spatial_XA: numpy.ndarray | torch.Tensor, spatial_XB: numpy.ndarray | torch.Tensor, exp_layer_A: List[numpy.ndarray | torch.Tensor], exp_layer_B: List[numpy.ndarray | torch.Tensor], label_transfer: numpy.ndarray | torch.Tensor, sigma2: int | float | numpy.ndarray | torch.Tensor, alpha: numpy.ndarray | torch.Tensor, gamma: float | numpy.ndarray | torch.Tensor, Sigma: numpy.ndarray | torch.Tensor, samples_s: List[float] | None = None, sigma2_variance: float = 1, probability_type: str | List[str] = 'Gauss', probability_parameters: List[float] | None = None, use_chunk: bool = False, chunk_capacity_scale: int = 1, top_k: int = 1024, metrics: str | List[str] = 'kl')[source]

Calculate sparse assignment matrix P using spatial and expression / representation distances.

Parameters:
nx module

Backend module (e.g., numpy or torch).

type_as type

Type to which the output should be cast.

Dim int

Dimensionality of the spatial data.

spatial_XA np.ndarray or torch.Tensor

Spatial coordinates of sample A.

spatial_XB np.ndarray or torch.Tensor

Spatial coordinates of sample B.

exp_layer_A np.ndarray or torch.Tensor

Expression / representation data of sample A.

exp_layer_B np.ndarray or torch.Tensor

Expression / representation data of sample B.

label_transfer np.ndarray or torch.Tensor

Label transfer cost matrix.

sigma2 int, float, np.ndarray or torch.Tensor

Sigma squared value.

alpha np.ndarray or torch.Tensor

Alpha values.

gamma float, np.ndarray or torch.Tensor

Gamma value.

Sigma np.ndarray or torch.Tensor

Sigma values.

samples_s Optional[List[float]], optional

Samples. Default is None.

sigma2_variance float, optional

Sigma squared variance. Default is 1.

probability_type Union[str, List[str]], optional

Probability type. Default is ‘Gauss’.

probability_parameters Optional[List[float]], optional

Probability parameters. Default is None.

use_chunk bool, optional

Whether to use chunking for large datasets. Default is False.

chunk_capacity_scale int, optional

Scale factor for chunk capacity. Default is 1.

top_k int, optional

Number of top elements to keep in the sparse matrix. Default is 1024.

metrics Union[str, List[str]], optional

Distance metrics to use. Default is ‘kl’.

Returns:

  • Union[np.ndarray, torch.Tensor] – Sparse assignment matrix P.

  • dict – Additional results.

spateo.alignment.methods.deprecated_utils.update_Sp(nx, type_as, step_size, batch_size, SVI_mode, assignment_results, Sp, Sp_spatial, Sp_sigma2)[source]
spateo.alignment.methods.deprecated_utils.update_gamma(nx, type_as, gamma, batch_size, gamma_a, gamma_b, Sp_spatial, SVI_mode)[source]
spateo.alignment.methods.deprecated_utils.update_alpha(nx, type_as, step_size, alpha, kappa, NA, assignment_results)[source]
spateo.alignment.methods.deprecated_utils.update_nonrigid(nx, type_as, SVI_mode, guidance_effect, SigmaInv, step_size, sigma2, lambdaVF, GammaSparse, U, K_NA, PXB_term, P, coordsB, RnA, guidance_epsilon, U_I, R_AI, X_BI)[source]
spateo.alignment.methods.deprecated_utils.update_rigid(nx, type_as)[source]
spateo.alignment.methods.deprecated_utils.update_sigma2()[source]
spateo.alignment.methods.deprecated_utils.update_assignment_P()[source]
spateo.alignment.methods.deprecated_utils.con_K(X: numpy.ndarray | torch.Tensor, Y: numpy.ndarray | torch.Tensor, beta: int | float = 0.01) numpy.ndarray | torch.Tensor[source]

con_K constructs the Squared Exponential (SE) kernel, where K(i,j)=k(X_i,Y_j)=exp(-beta*||X_i-Y_j||^2).

Parameters:
X

The first vector Xinmathbb{R}^{N imes d}

Y

The second vector Xinmathbb{R}^{M imes d}

beta

The length-scale of the SE kernel.

use_chunk bool, optional

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.

Returns:

The kernel Kinmathbb{R}^{N imes M}

Return type:

K

spateo.alignment.methods.deprecated_utils.con_K_geodist()[source]
spateo.alignment.methods.deprecated_utils.get_kernel(spatial_coords: numpy.ndarray | torch.Tensor, inducing_variables_num: int, kernel_bandwidth: float, sampling_method: str, kernel_type: str = 'euc', add_evaluation_points: numpy.ndarray | torch.Tensor | None = None) Tuple[numpy.ndarray | torch.Tensor, numpy.ndarray | torch.Tensor, numpy.ndarray | torch.Tensor, numpy.ndarray | torch.Tensor, numpy.ndarray | torch.Tensor | None][source]

Construct a kernel matrix for spatial data.

Parameters:
spatial_coords Union[np.ndarray, torch.Tensor]

The spatial coordinates of the data points.

inducing_variables_num int

The number of inducing variables to sample.

sampling_method str

The method to use for sampling inducing variables.

kernel_bandwidth float

The bandwidth parameter for the kernel.

kernel_type str

The type of kernel to construct. Currently supports “euc”.

add_evaluation_points Optional[Union[np.ndarray, torch.Tensor]], optional

Additional points to evaluate the kernel at. Defaults to None.

Returns:

A tuple containing the inducing variables, their indices, the sparse kernel matrix, the kernel matrix for spatial coordinates, and the evaluation kernel matrix (if provided).

Return type:

Tuple[Union[np.ndarray, torch.Tensor], Union[np.ndarray, torch.Tensor], Union[np.ndarray, torch.Tensor], Union[np.ndarray, torch.Tensor], Optional[Union[np.ndarray, torch.Tensor]]]

Raises:

NotImplementedError – If the specified kernel type is not implemented.

spateo.alignment.methods.deprecated_utils.kl_divergence_backend(X, Y, probabilistic=True)[source]

Returns pairwise KL divergence (over all pairs of samples) of two matrices X and Y. Takes advantage of POT backend to speed up computation. :param X: np array with dim (n_samples by n_features) :param Y: np array with dim (m_samples by n_features)

Returns:

np array with dim (n_samples by m_samples). Pairwise KL divergence matrix.

Return type:

D

spateo.alignment.methods.deprecated_utils.kl_distance(X_A: numpy.ndarray | torch.Tensor, X_B: numpy.ndarray | torch.Tensor, use_gpu: bool = True, chunk_num: int = 1, symmetry: bool = True) numpy.ndarray | torch.Tensor[source]

Calculate the KL distance between two vectors

Parameters:
X_A Union[np.ndarray, torch.Tensor]

The first input vector with shape n x d

X_B Union[np.ndarray, torch.Tensor]

The second input vector with shape m x d

use_gpu bool, optional

Whether to use GPU for chunk. Defaults to True.

chunk_num int, optional

The number of chunks. The larger the number, the smaller the GPU memory usage, but the slower the calculation speed. Defaults to 20.

symmetry bool, optional

Whether to use symmetric KL divergence. Defaults to True.

Returns:

KL distance matrix of two vectors with shape n x m.

Return type:

Union[np.ndarray, torch.Tensor]

spateo.alignment.methods.deprecated_utils.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.methods.deprecated_utils.cal_dist(X_A: numpy.ndarray | torch.Tensor, X_B: numpy.ndarray | torch.Tensor, use_gpu: bool = True, chunk_num: int = 1, return_gpu: bool = True) numpy.ndarray | torch.Tensor[source]

Calculate the distance between two vectors

Parameters:
X_A Union[np.ndarray, torch.Tensor]

The first input vector with shape n x d

X_B Union[np.ndarray, torch.Tensor]

The second input vector with shape m x d

use_gpu bool, optional

Whether to use GPU for chunk. Defaults to True.

chunk_num int, optional

The number of chunks. The larger the number, the smaller the GPU memory usage, but the slower the calculation speed. Defaults to 1.

Returns:

Distance matrix of two vectors with shape n x m.

Return type:

Union[np.ndarray, torch.Tensor]

spateo.alignment.methods.deprecated_utils.cal_dot(mat1: numpy.ndarray | torch.Tensor, mat2: numpy.ndarray | torch.Tensor, use_chunk: bool = False, use_gpu: bool = True, chunk_num: int = 20) numpy.ndarray | torch.Tensor[source]

Calculate the matrix multiplication of two matrices

Parameters:
mat1 Union[np.ndarray, torch.Tensor]

The first input matrix with shape n x d

mat2 Union[np.ndarray, torch.Tensor]

The second input matrix with shape d x m. We suppose m << n and does not require chunk.

use_chunk bool, optional

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.

use_gpu bool, optional

Whether to use GPU for chunk. Defaults to True.

chunk_num int, optional

The number of chunks. The larger the number, the smaller the GPU memory usage, but the slower the calculation speed. Defaults to 20.

Returns:

Matrix multiplication result with shape n x m

Return type:

Union[np.ndarray, torch.Tensor]

spateo.alignment.methods.deprecated_utils.get_optimal_R(coordsA: numpy.ndarray | torch.Tensor, coordsB: numpy.ndarray | torch.Tensor, P: numpy.ndarray | torch.Tensor, R_init: numpy.ndarray | torch.Tensor)[source]

Get the optimal rotation matrix R

Parameters:
coordsA Union[np.ndarray, torch.Tensor]

The first input matrix with shape n x d

coordsB Union[np.ndarray, torch.Tensor]

The second input matrix with shape n x d

P Union[np.ndarray, torch.Tensor]

The optimal transport matrix with shape n x n

Returns:

The optimal rotation matrix R with shape d x d

Return type:

Union[np.ndarray, torch.Tensor]

spateo.alignment.methods.deprecated_utils._cal_cosine_similarity(tensor1, tensor2, dim=1, eps=1e-08)[source]
spateo.alignment.methods.deprecated_utils._cos_similarity(mat1: numpy.ndarray | torch.Tensor, mat2: numpy.ndarray | torch.Tensor)[source]
spateo.alignment.methods.deprecated_utils._dist(mat1: numpy.ndarray | torch.Tensor, mat2: numpy.ndarray | torch.Tensor, metric: str = 'euc') numpy.ndarray | torch.Tensor[source]
spateo.alignment.methods.deprecated_utils.coarse_rigid_alignment(nx, type_as, samples: List[anndata.AnnData], coordsA: numpy.ndarray | torch.Tensor, coordsB: numpy.ndarray | torch.Tensor, init_layer: str = 'X', init_field: str = 'layer', genes: list | numpy.ndarray | None = None, top_K: int = 10, allow_flip: bool = False, verbose: bool = True, n_sampling: int | None = 20000)[source]
spateo.alignment.methods.deprecated_utils.coarse_rigid_alignment(coordsA: numpy.ndarray | torch.Tensor, coordsB: numpy.ndarray | torch.Tensor, X_A: numpy.ndarray | torch.Tensor, X_B: numpy.ndarray | torch.Tensor, transformed_points: numpy.ndarray | torch.Tensor | None = None, dissimilarity: str = 'kl', top_K: int = 10, allow_flip: bool = False, verbose: bool = True) Tuple[Any, Any, Any, Any, numpy.ndarray | Any, numpy.ndarray | Any][source]
spateo.alignment.methods.deprecated_utils.inlier_from_NN(train_x, train_y, distance)[source]
spateo.alignment.methods.deprecated_utils.coarse_rigid_alignment_debug(coordsA: numpy.ndarray | torch.Tensor, coordsB: numpy.ndarray | torch.Tensor, DistMat: numpy.ndarray | torch.Tensor, nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, sub_sample_num: int = -1, top_K: int = 10, transformed_points: numpy.ndarray | torch.Tensor | None = None) numpy.ndarray | torch.Tensor[source]
spateo.alignment.methods.deprecated_utils.inlier_from_NN_debug(train_x, train_y, distance)[source]
spateo.alignment.methods.deprecated_utils.voxel_data(nx: ot.backend.TorchBackend | ot.backend.NumpyBackend, coords: numpy.ndarray | torch.Tensor, gene_exp: numpy.ndarray | torch.Tensor, voxel_size: float | None = None, voxel_num: int | None = 10000)[source]

Voxelization of the data. :param coords: The coordinates of the data points. :type coords: np.ndarray or torch.Tensor :param gene_exp: The gene expression of the data points. :type gene_exp: np.ndarray or torch.Tensor :param voxel_size: The size of the voxel. :type voxel_size: float :param voxel_num: The number of voxels. :type voxel_num: int

Returns:

  • voxel_coords (np.ndarray or torch.Tensor) – The coordinates of the voxels.

  • voxel_gene_exp (np.ndarray or torch.Tensor) – The gene expression of the voxels.

spateo.alignment.methods.deprecated_utils._init_guess_sigma2(XA, XB, subsample=20000)[source]
spateo.alignment.methods.deprecated_utils._init_probability_parameters(exp_layer_A: List[numpy.ndarray | torch.Tensor], exp_layer_B: List[numpy.ndarray | torch.Tensor], dissimilarity: str | List[str] = 'kl', probability_type: str | List[str] = 'gauss', probability_parameters: float | List[float] | None = None, subsample=20000)[source]

Initialize probability parameters for the given expression layers.

Parameters:
exp_layer_A List[np.ndarray]

List of expression layers for dataset A.

exp_layer_B List[np.ndarray]

List of expression layers for dataset B.

dissimilarity List[str]

List of dissimilarity metrics.

probability_type List[str]

List of probability types.

probability_parameters List[Optional[float]]

List of probability parameters to be initialized.

subsample int, optional

Number of subsamples to use. Defaults to 20000.

Returns:

List of initialized probability parameters.

Return type:

List[Optional[float]]

spateo.alignment.methods.deprecated_utils._get_anneling_factor(nx, type_as, start, end, iter)[source]
spateo.alignment.methods.deprecated_utils._init_guess_beta2(nx, XA, XB, dissimilarity='kl', partial_robust_level=1, beta2=None, beta2_end=None, subsample=5000, verbose=False)[source]
spateo.alignment.methods.deprecated_utils._dense_to_sparse(mat: numpy.ndarray | torch.Tensor, sparse_method: str = 'topk', threshold: int | float = 100, axis: int = 0, descending=False)[source]
spateo.alignment.methods.deprecated_utils.empty_cache(device: str = 'cpu')[source]
spateo.alignment.methods.deprecated_utils.nx_torch[source]
spateo.alignment.methods.deprecated_utils._cat[source]
spateo.alignment.methods.deprecated_utils._unique[source]
spateo.alignment.methods.deprecated_utils._var[source]
spateo.alignment.methods.deprecated_utils._data[source]
spateo.alignment.methods.deprecated_utils._unsqueeze[source]
spateo.alignment.methods.deprecated_utils._mul[source]
spateo.alignment.methods.deprecated_utils._power[source]
spateo.alignment.methods.deprecated_utils._psi[source]
spateo.alignment.methods.deprecated_utils._pinv[source]
spateo.alignment.methods.deprecated_utils._dot[source]
spateo.alignment.methods.deprecated_utils._identity[source]
spateo.alignment.methods.deprecated_utils._linalg[source]
spateo.alignment.methods.deprecated_utils._prod[source]
spateo.alignment.methods.deprecated_utils._pi[source]
spateo.alignment.methods.deprecated_utils._chunk[source]
spateo.alignment.methods.deprecated_utils._randperm[source]
spateo.alignment.methods.deprecated_utils._roll[source]
spateo.alignment.methods.deprecated_utils._choice[source]
spateo.alignment.methods.deprecated_utils._topk[source]
spateo.alignment.methods.deprecated_utils._dstack[source]
spateo.alignment.methods.deprecated_utils._vstack[source]
spateo.alignment.methods.deprecated_utils._hstack[source]
spateo.alignment.methods.deprecated_utils._split[source]
spateo.alignment.methods.deprecated_utils.torch_like_split(arr, size, dim=0)[source]