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,] 9866 7518 4756 3842 1456 2269 3439 2499  802  2321
## [2,] 7224 5350  332 3537  617 2964 1778 7220 6569   640
## [3,] 6705 9278 3218 5443 1836  724 6902 5480 8829  3313
## [4,] 2676 8900 9297 4803 6534 8510 5919 4353 5627  4044
## [5,] 6396 4821 1296 5563 7661 6595 5437 2457 6167  7383
## [6,] 1069 5635 6372 2653 1150  823 8300 8996  477  1470
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]     [,7]
## [1,] 0.7450066 0.8928455 0.9116275 0.9658435 0.9843141 0.9860314 1.012022
## [2,] 0.7924141 1.0188470 1.0221066 1.0242867 1.0391637 1.0418665 1.046720
## [3,] 1.0196005 1.0384713 1.0491340 1.0730190 1.0833956 1.1087339 1.109174
## [4,] 0.9431304 1.0078888 1.0089601 1.0282644 1.0555941 1.0587438 1.072987
## [5,] 0.8566526 0.9208388 0.9412658 0.9420074 0.9506510 0.9945374 1.027609
## [6,] 0.9302255 0.9809710 1.0448747 1.0491840 1.0550045 1.0611384 1.070897
##          [,8]     [,9]    [,10]
## [1,] 1.012406 1.016742 1.025078
## [2,] 1.056480 1.085512 1.113182
## [3,] 1.109988 1.116979 1.139740
## [4,] 1.087294 1.093189 1.096771
## [5,] 1.049951 1.058990 1.068638
## [6,] 1.077246 1.081762 1.083358

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,] 1704 7289 4135 4331 5576
## [2,]  453 4588 4078 2151 9916
## [3,] 5099 6793 2872 1308  876
## [4,] 8589 1071 9502 7490 8050
## [5,]  506 7519 2850 4428 2916
## [6,] 1401 6609 7278 8916 3154
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]     [,5]
## [1,] 0.9467111 0.9493620 0.9565585 0.9974049 1.012537
## [2,] 0.8646357 0.8977119 1.0165380 1.0246235 1.026733
## [3,] 0.9899039 1.0024135 1.0150857 1.0419708 1.050240
## [4,] 0.9836898 1.0528934 1.0557081 1.0760640 1.100133
## [5,] 0.9086869 0.9621921 0.9643368 1.0310971 1.045303
## [6,] 1.0013589 1.0132027 1.0680091 1.1230057 1.138605

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/Rtmpi4vbDU/file2e404c612d07a1.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) (2022-10-25 r83175)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 22.04.1 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.17-bioc/R/lib/libRblas.so
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
## 
## 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.17.1 knitr_1.40           BiocStyle_2.27.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.4.1           rlang_1.0.6         xfun_0.34          
##  [4] stringi_1.7.8       jsonlite_1.8.3      S4Vectors_0.37.0   
##  [7] htmltools_0.5.3     stats4_4.3.0        sass_0.4.2         
## [10] rmarkdown_2.18      grid_4.3.0          evaluate_0.18      
## [13] jquerylib_0.1.4     fastmap_1.1.0       yaml_2.3.6         
## [16] bookdown_0.30       BiocManager_1.30.19 stringr_1.4.1      
## [19] compiler_4.3.0      codetools_0.2-18    Rcpp_1.0.9         
## [22] BiocParallel_1.33.4 lattice_0.20-45     digest_0.6.30      
## [25] R6_2.5.1            parallel_4.3.0      magrittr_2.0.3     
## [28] bslib_0.4.1         Matrix_1.5-1        tools_4.3.0        
## [31] BiocGenerics_0.45.0 cachem_1.0.6