# Detecting approximate nearest neighbors

Aaron Lun1

1Cancer Research UK Cambridge Institute, Cambridge, United Kingdom

#### Revised: 2 December 2018

#### Package

BiocNeighbors 1.2.0

# 1 Introduction

The BiocNeighbors package provides several algorithms for approximate neighbor searches:

- The Annoy (Approximate Nearest Neighbors Oh Yeah) method uses C++ code in the RcppAnnoy package. It works by building a tree where a random hyperplane partitions points into two child groups at each internal node. This is repeated to construct a forest of trees where the number of trees determines the accuracy of the search. Given a query data point, we identify all points in the same leaf node for each tree. We then take the union of leaf node sets across trees and search them exactly for the nearest neighbors.
- The HNSW (Hierarchical Navigable Small Worlds) method uses C++ code in the RcppHNSW package. It works by building a series of nagivable small world graphs containing links between points across the entire data set. The algorithm walks through the graphs where each step is chosen to get closer to a given query point. Different graphs contain links of different lengths, yielding a hierarchy where earlier steps are large and later steps are small. The accuracy of the search is determined by the connectivity of the graphs and the size of the intermediate list of potential neighbors.

These methods complement the exact algorithms described previously. Again, it is straightforward to switch from one algorithm to another by simply changing the `BNPARAM` argument in `findKNN` and `queryKNN`.

# 2 Identifying nearest neighbors

We perform the k-nearest neighbors search with the Annoy algorithm by specifying `BNPARAM=AnnoyParam()`.

    nobs <- 10000
    ndim <- 20
    data <- matrix(runif(nobs*ndim), ncol=ndim)

    fout <- findKNN(data, k=10, BNPARAM=AnnoyParam())
    head(fout$index)

    ##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    ## [1,] 7555 5086 9439 2364 6914 1263 1132 1391 1525  4392
    ## [2,] 2529 2859 6391 7539  233 4216 2711 1634 6769  5059
    ## [3,] 8074  856 3739 9884 7796 3206 4028 6080 7700  7368
    ## [4,] 1904 7457 1358 4981   80    8 2611 3660 5585  3059
    ## [5,] 9633 4569 6416 2109 5793  874 9853 7188 3607  9814
    ## [6,] 3332 3088 4685 4288 5344 1662 9862 6265 8395  2729

    head(fout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]     [,6]      [,7]
    ## [1,] 0.8958202 0.9145421 0.9997506 1.0046253 1.0465587 1.084979 1.0883030
    ## [2,] 0.9210045 0.9830105 1.0066934 1.0105218 1.0194305 1.030048 1.0324202
    ## [3,] 1.0312659 1.1366421 1.1463315 1.1473175 1.1486008 1.152792 1.1664172
    ## [4,] 0.9566686 1.0086507 1.0359409 1.0367854 1.0405928 1.043324 1.0659174
    ## [5,] 0.8362517 0.8495315 0.8664847 0.9435661 0.9663886 0.968679 0.9695346
    ## [6,] 0.9608857 1.0108142 1.0270232 1.0274940 1.0398604 1.052492 1.0768716
    ##           [,8]      [,9]     [,10]
    ## [1,] 1.0981938 1.1111542 1.1121014
    ## [2,] 1.0343252 1.0395184 1.0567859
    ## [3,] 1.1868104 1.1954392 1.2020642
    ## [4,] 1.0731800 1.0751356 1.0776922
    ## [5,] 0.9799066 0.9799401 0.9857247
    ## [6,] 1.0807590 1.0884249 1.0924859

We can also identify the k-nearest neighbors in one dataset based on query points in another dataset.

    nquery <- 1000
    ndim <- 20
    query <- matrix(runif(nquery*ndim), ncol=ndim)

    qout <- queryKNN(data, query, k=5, BNPARAM=AnnoyParam())
    head(qout$index)

    ##      [,1] [,2] [,3] [,4] [,5]
    ## [1,] 5659 6972 4381 6681 9156
    ## [2,] 6057 9074 1223 7648 1542
    ## [3,] 2870 4585 8511 4664 4277
    ## [4,] 9147 9979  993 2529 3087
    ## [5,] 1927 8848 1040 9185   83
    ## [6,] 1482 9859  822 9934 1933

    head(qout$distance)

    ##           [,1]      [,2]      [,3]      [,4]      [,5]
    ## [1,] 0.9738171 0.9998217 1.0388658 1.0398707 1.0481373
    ## [2,] 1.0109079 1.0819900 1.1231607 1.1254007 1.1414075
    ## [3,] 0.9531454 0.9596773 0.9623442 1.0143856 1.0283245
    ## [4,] 1.0143973 1.0554299 1.0579753 1.0639384 1.0726366
    ## [5,] 0.9490367 0.9518706 1.0136790 1.0294023 1.0444212
    ## [6,] 0.8257428 0.9519003 0.9529459 0.9810284 0.9842274

It is similarly easy to use the HNSW algorithm by setting `BNPARAM=HnswParam()`.

# 3 Further options

Most of the options described for the KMKNN algorithm are also applicable here. For example:

- `subset` to identify neighbors for a subset of points.
- `get.distance` to avoid retrieving distances when unnecessary.
- `BPPARAM` to parallelize the calculations across multiple workers.
- `BNINDEX` to build the forest once for a given data set and re-use it across calls.

The use of a pre-built `BNINDEX` is illustrated below:

    pre <- buildIndex(data, BNPARAM=AnnoyParam())
    out1 <- findKNN(BNINDEX=pre, k=5)
    out2 <- queryKNN(BNINDEX=pre, query=query, k=2)

Users are referred to the documentation of each function for specific details on the available arguments.

# 4 Saving the index files

The forest of trees form an indexing structure that is saved to file. By default, this file is located in `tempdir()`11 On HPC file systems, you can change `TEMPDIR` to a location that is more amenable to parallelized access. and will be removed when the session finishes.

    AnnoyIndex_path(pre)

    ## [1] "/tmp/RtmpvuIhM1/file63112abd05e6.idx"

If the index is to persist across sessions, the path of the index file can be directly specified in `buildIndex`. However, this means that it becomes the responsibility of the user to clean up any temporary indexing files after calculations are complete.

# 5 Session information

    sessionInfo()

    ## R version 3.6.0 (2019-04-26)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 18.04.2 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /home/biocbuild/bbs-3.9-bioc/R/lib/libRblas.so
    ## LAPACK: /home/biocbuild/bbs-3.9-bioc/R/lib/libRlapack.so
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C
    ##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
    ##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
    ##  [9] LC_ADDRESS=C               LC_TELEPHONE=C
    ## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] BiocNeighbors_1.2.0 knitr_1.22          BiocStyle_2.12.0
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] Rcpp_1.0.1          bookdown_0.9        digest_0.6.18
    ##  [4] stats4_3.6.0        magrittr_1.5        evaluate_0.13
    ##  [7] stringi_1.4.3       S4Vectors_0.22.0    rmarkdown_1.12
    ## [10] BiocParallel_1.18.0 tools_3.6.0         stringr_1.4.0
    ## [13] parallel_3.6.0      xfun_0.6            yaml_2.2.0
    ## [16] compiler_3.6.0      BiocGenerics_0.30.0 BiocManager_1.30.4
    ## [19] htmltools_0.3.6