smoother.weights ================ .. py:module:: smoother.weights .. autoapi-nested-parse:: Calculate spatial weight matrix from coordinates, histology images, and transcriptomic data Classes ------- .. autoapisummary:: smoother.weights.SpatialWeightMatrix Functions --------- .. autoapisummary:: smoother.weights.coordinate_to_weights_knn_sparse smoother.weights.coordinate_to_weights_dist_sparse smoother.weights.coordinate_to_weights_knn_dense smoother.weights.coordinate_to_weights_dist_dense smoother.weights.sparse_weights_to_inv_cov smoother.weights.weights_to_inv_cov smoother.weights._standardize_inv_cov Module Contents --------------- .. py:function:: coordinate_to_weights_knn_sparse(coords, k=6, symmetric=True, row_scale=True) Calculate spatial weight matrix using k-nearest neighbours (sklearn). Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among k-nearest neighbours. Sparse tensor version. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param k: Number of nearest neighbours to keep. :type k: int :param symmetric: If True only keep mutual neighbors. :type symmetric: bool :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :returns: A sparse 2D tensor containing spatial weights, num_spot x num_spot. :rtype: weights .. py:function:: coordinate_to_weights_dist_sparse(coords, scale_coords=True, radius_cutoff=1.0, band_width=0.1, dist_metric='euclidean', row_scale=True) Calculate spatial weight matrix using distance band (sklearn). Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among neighbours defined by the distane threshold. Sparse tensor version. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param scale_coords: If True, scale coordinates to [0, 1]. :type scale_coords: bool :param radius_cutoff: Distance threshold (in the same unit as the coords input). :type radius_cutoff: float :param band_width: Specify the width of the Gaussian kernel, which is proportional to the inverse rate of weight distance decay. :type band_width: float :param dist_metric: Distance metric. :type dist_metric: str :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :returns: A sparse 2D tensor containing spatial weights, num_spot x num_spot. :rtype: weights .. py:function:: coordinate_to_weights_knn_dense(coords, k=6, symmetric=True, row_scale=True) Calculate spatial weight matrix using k-nearest neighbours. Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among k-nearest neighbours. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param k: Number of nearest neighbours to keep. :type k: int :param symmetric: If True only keep mutual neighbors. :type symmetric: bool :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :returns: A 2D tensor containing spatial weights, num_spot x num_spot. :rtype: weights .. py:function:: coordinate_to_weights_dist_dense(coords, scale_coords=True, q_threshold=0.001, band_width=0.1, dist_metric='euclidean', row_scale=True) Calculate spatial weight matrix using distance band. Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among neighbours defined by the distane threshold. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param scale_coords: If True, scale coordinates to [0, 1]. :type scale_coords: bool :param q_threshold: Distance quantile threshold. Number of nonzero entries in the weight matrix (edges) = num_spot^2 * q_threshold. :type q_threshold: float :param band_width: Specify the width of the Gaussian kernel, which is proportional to the inverse rate of weight distance decay. :type band_width: float :param dist_metric: Distance metric. :type dist_metric: str :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :returns: A 2D tensor containing spatial weights, num_spot x num_spot. :rtype: weights .. py:function:: sparse_weights_to_inv_cov(weights, model, rho=1, standardize=False, return_sparse=False) Convert a spatial weight matrix to an inverse covariance matrix. Sparse version. Calculate the covariance structure using spatial weights. Different spatial process models impose different structures. Check model descriptions for more details. :param weights: Spatial weight matrix (sparse), num_spot x num_spot. :type weights: Sparse tensor :param model: Spatial process model to use, can be one of 'sma','sar', 'isar', 'car', 'icar'. :type model: str :param rho: Spatial autocorrelation parameter. :type rho: float :param standardize: If True, return the standardized inverse covariance matrix (inv_corr). :type standardize: bool :param return_sparse: If True, return a sparse tensor. Note that the inverse covariance matrix of the SMA model is not sparse in general. :type return_sparse: bool :returns: An inverse covariance (precision) matrix, num_spot x num_spot. :rtype: inv_cov (2D tensor) .. py:function:: weights_to_inv_cov(weights, model, rho=1, standardize=False) Convert a spatial weight matrix to an inverse covariance matrix. Calculate the covariance structure using spatial weights. Different spatial process models impose different structures. Check model descriptions for more details. :param weights: Spatial weight matrix, num_spot x num_spot. :type weights: 2D tensor :param model: Spatial process model to use, can be one of 'sma','sar', 'isar', 'car', 'icar'. :type model: str :param rho: Spatial autocorrelation parameter. :type rho: float :param standardize: If True, return the standardized inverse covariance matrix (inv_corr). :type standardize: bool :returns: An inverse covariance (precision) matrix, num_spot x num_spot. :rtype: inv_cov (2D tensor) .. py:function:: _standardize_inv_cov(inv_cov) Standardize the inverse covariance matrix. When the inverse covariance matrix is singular, the matrix will be normalized instead to have diagonal elements of 1 (i.e. return normalized laplacian for 'icar' model). .. py:class:: SpatialWeightMatrix Spatial weight matrix. The adjacency matrix that specifies connectivities and interactions between each pair of spots. .. attribute:: swm Unscaled spatial weight matrix. :type: sparse tensor .. attribute:: swm_scaled Spatial weight matrix scaled with external information (e.g., expression, histology). :type: sparse tensor .. attribute:: inv_covs Cached inverse covariance matrices under different model settings (for debugging). :type: dict .. attribute:: config Configurations. :type: dict .. py:attribute:: swm :value: None .. py:attribute:: swm_scaled :value: None .. py:attribute:: inv_covs .. py:attribute:: config .. py:method:: _check_swm_stats(scaled=False, verbose=True) -> None Check spatial weight matrix statistics. .. py:method:: calc_weights_knn(coords, k=6, symmetric=True, row_scale=False, verbose=True) -> None Calculate spatial weight matrix using k-nearest neighbours. Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among k-nearest neighbours. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param k: Number of nearest neighbours to keep. :type k: int :param symmetric: If True only keep mutual neighbors. :type symmetric: bool :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :param verbose: If True, print out weights summary. :type verbose: bool .. py:method:: calc_weights_dist(coords, scale_coords=True, radius_cutoff=1.0, band_width=0.1, dist_metric='euclidean', row_scale=True, verbose=True) -> None Calculate spatial weight matrix using distance band. Convert spatial coordinate to a spatial weight matrix where non-zero entries represent interactions among neighbours defined by the distane threshold. :param coords: Spatial coordinates, num_spot x 2 (or 3). :type coords: 2D array :param scale_coords: If True, scale coordinates to [0, 1]. :type scale_coords: bool :param radius_cutoff: Distance threshold (in the same unit as the coords input). :type radius_cutoff: float :param band_width: Specify the width of the Gaussian kernel, which is proportional to the inverse rate of weight distance decay. :type band_width: float :param dist_metric: Distance metric. :type dist_metric: str :param row_scale: If True scale row sum of the spatial weight matrix to 1. :type row_scale: bool :param verbose: If True, print out weights summary. :type verbose: bool .. py:method:: scale_by_similarity(pairwise_sim: smoother.utils.torch.Tensor, row_scale=False, return_swm=False, verbose=True) -> None Scale spatial weight matrix by external pairwise similarity. :param pairwise_sim: External pairwise similarity, num_spot x num_spot. :type pairwise_sim: 2D tensor :param row_scale: If True, scale rowsums of spatial weight matrix to be 1. :type row_scale: bool :param return_swm: Whether to output the scaled spatial weight matrix. :type return_swm: bool :param verbose: If True, print out weights summary. :type verbose: bool .. py:method:: scale_by_identity(spot_ids, boundary_connectivity=0, row_scale=False, return_swm=False, verbose=True) -> None Scale spatial weight matrix by spot identity. :param spot_ids: Spot identity of length num_spot. :type spot_ids: 1D array :param boundary_connectivity: Connectivity of spots with different identities. If 0 (default), no interaction across identities. :type boundary_connectivity: float .. py:method:: scale_by_expr(expr, dist_metric='cosine', reduce='pca', dim=10, row_scale=False, verbose=True) -> None Scale weight matrix using transcriptional similarity. :param expr: Spatial gene expression count matrix, num_genes x num_spot. :type expr: 2D array :param dist_metric: Distance metric. :type dist_metric: str :param reduce: If `PCA`, calculate distance on the reduced PCA space. :type reduce: str :param dim: Number of dimension of the reduced space. :type dim: int :param row_scale: If True, scale rowsums of spatial weight matrix to be 1. :type row_scale: bool :param verbose: If True, print out weights summary. :type verbose: bool .. py:method:: scale_by_histology(coords, image, scale_factors: dict, dist_metric='euclidean', reduce='pca', dim=10, row_scale=False, verbose=True) -> None Calculate pairwise histology similarity between spots. :param coords: Spatial coordinate matrix (in fullres pixel), num_spot x 2. :type coords: 2D array :param image: Histology image, num_pixel x num_pixel x num_channel. :type image: 3D array :param scale_fators: The JSON dictionary from 10x Visium's `scalefactors_json.json` 'spot_diameter_fullres' (float): Spot size (fullres) 'tissue_hires_scalef' (float): Scale factor that transforms fullres image to the given image. :type scale_fators: dict :param reduce: If `PCA`, calculate distance on the reduced PCA space. :type reduce: str :param dist_metric: Distance metric used to calculate similarity. :type dist_metric: str :param dim: Number of dimension of the reduced space. :type dim: int :param row_scale: If True, scale rowsums of spatial weight matrix to be 1. :type row_scale: bool :param verbose: If True, print out weights summary. :type verbose: bool .. py:method:: get_inv_cov(model, rho=1, cached=True, standardize=False, return_sparse=True) Calculate or extract cached inverse covariance matrix. :param model: The spatial process model, can be one of 'sma','sar', 'car', 'icar'. :type model: str :param rho: The spatial autocorrelation parameter. :type rho: float :param return_sparse: If True, return sparse matrix. :type return_sparse: bool