Skip to content

pynndescent error when trying to use a custom metric with scanpy neghbors #2139

Closed

Description

@polklin

Hello everyone !

I would like to use a custom distance when trying to compute the neighbors graph with scanpy.pp.neighbors.
So let's suppose I have a pre-existing distance matrix somewhere, and I just want to use it in the graph generation.

Currently, I am getting an error when exceeding 4096 observations in my AnnData object.
I do not have such error when directly using theumap python package.

Full error

Traceback (most recent call last):
  File "/home/paul/Documents/Curie/Immunopeptidomics/minimal_bug_scanpy.py", line 72, in <module>
    sc.pp.neighbors(xd,
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/scanpy/neighbors/__init__.py", line 139, in neighbors
    neighbors.compute_neighbors(
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/scanpy/neighbors/__init__.py", line 791, in compute_neighbors
    knn_indices, knn_distances, forest = compute_neighbors_umap(
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/scanpy/neighbors/__init__.py", line 305, in compute_neighbors_umap
    knn_indices, knn_dists, forest = nearest_neighbors(
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/umap/umap_.py", line 328, in nearest_neighbors
    knn_search_index = NNDescent(
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/pynndescent/pynndescent_.py", line 875, in __init__
    self._neighbor_graph = nn_descent(
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/numba/core/dispatcher.py", line 468, in _compile_for_args
    error_rewrite(e, 'typing')
  File "/home/paul/venv/xomx/lib/python3.9/site-packages/numba/core/dispatcher.py", line 409, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
non-precise type pyobject
During: typing of argument at /home/paul/venv/xomx/lib/python3.9/site-packages/pynndescent/pynndescent_.py (330)

File "../pynndescent/pynndescent_.py", line 330:
def nn_descent(
    <source elided>

    if init_graph[0].shape[0] == 1:  # EMPTY_GRAPH
    ^ 

This error may have been caused by the following argument(s):
- argument 4: Cannot determine Numba type of <class 'function'>

Minimal code sample to reproduce the error

import scanpy as sc
import numpy as np

def custom_distance(x1, x2):
    return dist_mat[int(x1), int(x2)]

n = 4096

# generate a fake distance matrix for n elements
dist_mat = np.random.rand(n, n)
# make it symmetrical
dist_mat= np.tril(dist_mat) + np.tril(dist_mat, -1).T
# zeros on the diagonal
for i in range(len(dist_mat)):
    dist_mat[i][i] = 0.

xd = sc.AnnData(shape=(n, 1))
xd.obs_names = [i for i in range(n)]
xd.X = np.empty((xd.n_obs, xd.n_vars))
for i in range(xd.n_obs):
    xd.X[i, 0] = i
print("computing connectivity graph...")
rng = np.random.RandomState(0)
sc.pp.neighbors(xd,
                n_neighbors=10,
                n_pcs=None,
                use_rep='X',
                random_state=rng,
                metric=custom_distance)

print("Success")

Versions

Details

anndata 0.7.8
scanpy 1.8.2
sinfo 0.3.4

PIL 8.4.0
beta_ufunc NA
binom_ufunc NA
cffi 1.15.0
cycler 0.10.0
cython_runtime NA
dateutil 2.8.2
defusedxml 0.7.1
h5py 3.6.0
igraph 0.9.8
joblib 1.1.0
kiwisolver 1.3.2
leidenalg 0.8.8
llvmlite 0.38.0
louvain 0.7.1
matplotlib 3.5.1
mpl_toolkits NA
natsort 8.0.2
nbinom_ufunc NA
numba 0.55.1
numexpr 2.8.1
numpy 1.21.5
packaging 21.3
pandas 1.3.5
pkg_resources NA
pyexpat NA
pyparsing 3.0.6
pytz 2021.3
scipy 1.7.3
sitecustomize NA
six 1.16.0
sklearn 1.0.1
tables 3.6.1
texttable 1.6.4
threadpoolctl 3.0.0
typing_extensions NA
wcwidth 0.2.5

Python 3.9.9 (main, Nov 16 2021, 03:08:02) [GCC 9.3.0]
Linux-5.4.0-99-generic-x86_64-with-glibc2.31
8 logical CPU cores, x86_64

Activity

  1. ivirshup commented on Feb 23, 2022

    @ivirshup
    Member

    Thanks for the report

    Could you also provide an example of this working when you use UMAP directly? It looks like what you're doing is providing a precomputed distance matrix, right?

  2. added
    Needs info❔
    on Feb 23, 2022
  3. polklin commented on Feb 25, 2022

    @polklin
    Author

    Hello @ivirshup,
    yes the goal would be to use a precomputed distance matrix exactly. umap allows such behavior by specifying metric='precomputed' as an argument (see lmcinnes/umap#348).

    A minimal code, using umap:

    import numpy as np
    import umap
    
    def custom_distance(x1, x2):
        '''Returns the distance between two peptides encoded as floats (base 21)'''
        return dist_mat[int(x1), int(x2)]
    
    n = 4096
    
    # generate a fake distance matrix for n elements
    dist_mat = np.random.rand(n, n)
    # make it symmetrical
    dist_mat= np.tril(dist_mat) + np.tril(dist_mat, -1).T
    # zeros on the diagonal
    for i in range(len(dist_mat)):
        dist_mat[i][i] = 0.
    
    ### USING UMAP ###
    my_model = umap.UMAP(metric='precomputed')
    my_model.fit(dist_mat)
  4. ivirshup commented on Feb 25, 2022

    @ivirshup
    Member

    It should definitely be easier to use a precomputed distance matrix. I believe this has been talked about before, but not implemented. As a workaround, you should be able to get something working like this:

    import scanpy as sc
    import numpy as np
    
    n = 4096
    k = 10
    adata = sc.AnnData(shape=(n, 1))
    
    dist_mat = np.random.rand(n, n)
    # make it symmetrical
    dist_mat= np.tril(dist_mat) + np.tril(dist_mat, -1).T
    np.fill_diagonal(dist_mat, 0)
    
    adata.obsp["distances"], adata.obsp["connectivities"] = sc.neighbors._compute_connectivities_umap(
        *sc.neighbors._get_indices_distances_from_dense_matrix(dist_mat, k),
        dist_mat.shape[0],
        k,
    )
    adata.uns["neighbors"] = {"connectivities_key": "connectivities", "distances_key": "distances", "params": {"method": None}}
    
    sc.tl.umap(adata)
  5. polklin commented on Feb 28, 2022

    @polklin
    Author

    thanks for your reply @ivirshup !

  6. ivirshup commented on Feb 28, 2022

    @ivirshup
    Member

    No worries.

    I'm going to close this issue as I've opened a more focused one (referenced above)

  7. AlSzmigiel commented on Jan 19, 2024

    @AlSzmigiel

    how to do it with a precomputed adjacency matrix and 'gauss' method for computing connectivities?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs info❔

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions