1 Introduction

The BiocNeighbors package provides several algorithms for approximate neighbor searches:

  • The Annoy (Approximate Nearest Neighbors Oh Yeah) method uses C++ code from the RcppAnnoy package. It works by building a tree where a random hyperplane partitions a group of 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 from 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 move 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,] 8194  619 6670 4289 4534 3166 7252 7770 2440  6402
## [2,] 8898 8450 2717 2920 7772 1515 7537 6429 2111  9780
## [3,] 9118 2387 9490  210 2213 1039 4378 7079 3621  8989
## [4,] 1311 6064 9293 2387 9991 1662 4043 1179 1983  3622
## [5,] 7241 5182 8445  389 8586  238 1072 3983 2645  9378
## [6,] 3219 2822 3204 8332 2104 1195 6817 9323 2277  6354
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.8527822 0.8851885 0.9104590 0.9223309 0.9371058 0.9480842 0.9553182
## [2,] 1.0157385 1.0449945 1.0828638 1.0839001 1.0952017 1.1070888 1.1221418
## [3,] 0.6642309 0.8655371 0.9684739 1.0483724 1.0545970 1.0622003 1.0821905
## [4,] 0.8963934 0.8982547 0.9109026 0.9251589 0.9453899 0.9458044 0.9578203
## [5,] 0.8683872 0.9179463 0.9367086 0.9423220 0.9633026 0.9795543 0.9865378
## [6,] 0.7528054 0.7622614 0.7674942 0.7960816 0.7972231 0.8102095 0.8113514
##           [,8]      [,9]     [,10]
## [1,] 0.9799060 0.9932882 1.0003920
## [2,] 1.1298681 1.1482346 1.1489100
## [3,] 1.1287400 1.1439441 1.1442665
## [4,] 0.9618394 0.9720966 0.9775182
## [5,] 0.9953822 0.9983048 1.0033733
## [6,] 0.8482193 0.8532856 0.8971366

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,]  698 5118  508 6525 2105
## [2,] 7930 3095 7626 2434 9766
## [3,] 9814 5402  570  444 2629
## [4,] 5839 7092 4750 4723 3159
## [5,] 7764 1918 5878 5084  571
## [6,] 6831 7620 2498 6160 4395
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]     [,5]
## [1,] 0.9129354 0.9807994 1.0153899 1.0388646 1.064679
## [2,] 0.8585815 0.9797043 0.9921426 0.9956636 1.037067
## [3,] 0.9155663 0.9408196 0.9538341 0.9933146 1.017889
## [4,] 0.8947770 0.9982160 1.0424412 1.0491548 1.065321
## [5,] 0.9345800 0.9965523 1.0030229 1.0059097 1.013265
## [6,] 0.9897190 1.0037705 1.0112482 1.0272404 1.036877

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

3 Further options

Most of the options described for the exact methods 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)

Both Annoy and HNSW perform searches based on the Euclidean distance by default. Searching by Manhattan distance is done by simply setting distance="Manhattan" in AnnoyParam() or HnswParam().

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

4 Saving the index files

Both Annoy and HNSW generate indexing structures - a forest of trees and series of graphs, respectively - that are saved to file when calling buildIndex(). By default, this file is located in tempdir()1 On HPC file systems, you can change TEMPDIR to a location that is more amenable to concurrent access. and will be removed when the session finishes.

AnnoyIndex_path(pre)
## [1] "/tmp/RtmpIcWnh3/file4ff91977c2f5.idx"

If the index is to persist across sessions, the path of the index file can be directly specified in buildIndex. This can be used to construct an index object directly using the relevant constructors, e.g., AnnoyIndex(), HnswIndex(). However, 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.10-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.10-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.3.2 knitr_1.23          BiocStyle_2.13.1   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.1          bookdown_0.11       lattice_0.20-38    
##  [4] digest_0.6.19       grid_3.6.0          stats4_3.6.0       
##  [7] magrittr_1.5        evaluate_0.14       stringi_1.4.3      
## [10] S4Vectors_0.23.10   Matrix_1.2-17       rmarkdown_1.13     
## [13] BiocParallel_1.19.0 tools_3.6.0         stringr_1.4.0      
## [16] parallel_3.6.0      xfun_0.7            yaml_2.2.0         
## [19] compiler_3.6.0      BiocGenerics_0.31.3 BiocManager_1.30.4 
## [22] htmltools_0.3.6