scviva.tools.vision.compute_knn_weights

scviva.tools.vision.compute_knn_weights#

scviva.tools.vision.compute_knn_weights(latent_space, K=None, exact=False)[source]#

Build an exponential-kernel KNN weight matrix from a latent space.

Mirrors R VISION’s computeKNNWeights (matrix S4 method):

  1. Find the K nearest neighbors in Euclidean space.

  2. Per-cell bandwidth: σ_i = max distance among the K neighbors.

  3. Weight kernel: W_ij = exp(−d²_ij / σ²_i).

  4. Row-normalise so each row sums to 1.

Parameters:
  • latent_space (ndarray of shape (n_cells, n_dims)) – Cell coordinates (e.g. PCA scores stored in adata.obsm["X_pca"]).

  • K (int, optional) – Number of neighbors. Defaults to round(sqrt(n_cells)), matching R VISION’s default.

  • exact (bool, optional) – If True, use sklearn’s exact neighbor search instead of pynndescent. See find_knn().

Returns:

Row-normalised sparse weight matrix. Entry (i, j) is the weight cell i assigns to cell j; only KNN connections are non-zero.

Return type:

scipy.sparse.csr_matrix of shape (n_cells, n_cells)

Notes

Unlike R VISION, which returns raw (indices, weights) arrays and assembles the full sparse matrix lazily inside callers such as sigsVsProjection_pcf, this function builds the complete CSR matrix immediately. This matches the format already expected by visionpy’s existing adata.obsp["weights"] slot.