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,] 1466 7323 9379 4149 1439 5502 6920 3162  475  5184
## [2,] 2949 4276 1332  610 2591 4263 2378 9644 7256  5806
## [3,] 2142 3299 4588 1677 3593 5183  329 7813 8997  6772
## [4,] 5024 9917 9209 1584 6031 8772 8787 7348 2393  5844
## [5,]  544  266 4814 9393 1195 5395 3900  469 2121  1002
## [6,] 5615 7296 2612 5749 1048 2782 5527 8539 2151  7424
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]     [,7]
## [1,] 0.8724925 0.8881578 0.9376649 0.9514756 0.9523388 0.9617602 0.963069
## [2,] 0.8606351 0.9866089 0.9972676 1.0184406 1.0287061 1.0319048 1.053734
## [3,] 0.8538983 1.0081236 1.0548334 1.0870073 1.0895227 1.1022624 1.109032
## [4,] 0.8948385 1.0569385 1.0693502 1.0923736 1.1146482 1.1184669 1.125498
## [5,] 0.9188566 0.9576545 1.0227277 1.0307057 1.0594549 1.0719343 1.084865
## [6,] 0.9910316 1.0010052 1.0205824 1.0284852 1.0360433 1.0646397 1.103687
##           [,8]      [,9]     [,10]
## [1,] 0.9667453 0.9685532 0.9719257
## [2,] 1.0601885 1.0610150 1.0761425
## [3,] 1.1112807 1.1169348 1.1304533
## [4,] 1.1269405 1.1314274 1.1376382
## [5,] 1.0862718 1.0917937 1.1219018
## [6,] 1.1129467 1.1130770 1.1156273

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,] 9159 8836 4102 1945  550
## [2,] 1041 6357 6091 9395 4603
## [3,] 4818 8141 2246 8418 4699
## [4,] 9430 7532 4623 4847 4041
## [5,] 2477  986 6959 2092 9691
## [6,] 5506 7297 7926 1412 9432
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8219219 0.9332203 0.9733840 0.9963005 0.9971846
## [2,] 0.9422451 0.9831861 1.0109245 1.0526975 1.0622830
## [3,] 0.7239333 0.8303726 0.8512747 0.8759885 0.8954934
## [4,] 0.9444788 0.9941299 1.0001973 1.0142548 1.0231868
## [5,] 0.8664768 1.0036238 1.1345805 1.1485803 1.1828600
## [6,] 0.7948402 0.9059420 0.9416196 0.9886932 1.0030566

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/Rtmpu5yGBi/file273e3b40c1330a.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 Under development (unstable) (2021-10-19 r81077)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.3 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.15-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.15-bioc/R/lib/libRlapack.so
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_GB              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.13.0 knitr_1.36           BiocStyle_2.23.0    
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.7          magrittr_2.0.1      BiocGenerics_0.41.0
##  [4] BiocParallel_1.29.0 lattice_0.20-45     R6_2.5.1           
##  [7] rlang_0.4.12        fastmap_1.1.0       stringr_1.4.0      
## [10] tools_4.2.0         parallel_4.2.0      grid_4.2.0         
## [13] xfun_0.27           jquerylib_0.1.4     htmltools_0.5.2    
## [16] yaml_2.2.1          digest_0.6.28       bookdown_0.24      
## [19] Matrix_1.3-4        BiocManager_1.30.16 S4Vectors_0.33.0   
## [22] sass_0.4.0          evaluate_0.14       rmarkdown_2.11     
## [25] stringi_1.7.5       compiler_4.2.0      bslib_0.3.1        
## [28] stats4_4.2.0        jsonlite_1.7.2