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,] 9081 2590 5954 4418 1130  817 3281  981 2844  6453
## [2,] 1725 1912 6848 4511 4997 9200 6798 5625 5078  7923
## [3,] 6028 2503 7839 3581 9678 8751 7938 4730 5668  2543
## [4,] 6748 2438 8109 8149 2009 5670 4039 6351 9439  3245
## [5,] 7172 5866 3101 3848 5622 8062 4351 1616 9281  7563
## [6,] 3603 8370 9748 6267 1587 2528 9607 3847 7364  9809
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]     [,5]     [,6]     [,7]
## [1,] 0.9048732 0.9290817 0.9529825 0.9718094 1.040614 1.044221 1.052413
## [2,] 0.9471796 0.9904641 0.9942391 0.9958718 1.013813 1.028707 1.067303
## [3,] 0.8956395 0.9243726 0.9508114 0.9914557 1.013266 1.017749 1.025363
## [4,] 1.0321965 1.0339187 1.0710512 1.0785786 1.086853 1.090003 1.117755
## [5,] 0.9055967 0.9482576 0.9867758 1.0314162 1.046653 1.068574 1.074425
## [6,] 0.9637915 0.9738527 1.0377030 1.0667616 1.109437 1.116790 1.128139
##          [,8]     [,9]    [,10]
## [1,] 1.107435 1.125857 1.132152
## [2,] 1.067680 1.073059 1.075594
## [3,] 1.027478 1.102310 1.107566
## [4,] 1.119587 1.125100 1.127997
## [5,] 1.090467 1.118941 1.122357
## [6,] 1.129412 1.134031 1.142335

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,] 6798 5322  528 2769 3153
## [2,] 5087 4319 5533 4649 6436
## [3,]  217 9968 8347 9055 4987
## [4,] 6285 1199 8298 5081 9354
## [5,] 3226 8620 5917  531 7216
## [6,] 1906 7503 5578 2378 9988
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.9555078 0.9862330 1.0606334 1.0909979 1.1036588
## [2,] 1.1282271 1.1333749 1.1587014 1.1678296 1.1970912
## [3,] 0.9543204 0.9695417 0.9930168 1.0178987 1.0699915
## [4,] 0.8481436 0.9094500 0.9236550 0.9614148 0.9931656
## [5,] 0.8697364 0.8794889 0.8930228 0.9075502 0.9590325
## [6,] 0.9033212 0.9847811 0.9901687 0.9988128 1.0508120

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/RtmpL2SLV0/fileaa7e427f8d.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.1 (2019-07-05)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.3 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.4 knitr_1.24          BiocStyle_2.13.2   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.2          bookdown_0.13       lattice_0.20-38    
##  [4] digest_0.6.20       grid_3.6.1          stats4_3.6.1       
##  [7] magrittr_1.5        evaluate_0.14       stringi_1.4.3      
## [10] S4Vectors_0.23.23   Matrix_1.2-17       rmarkdown_1.15     
## [13] BiocParallel_1.19.2 tools_3.6.1         stringr_1.4.0      
## [16] parallel_3.6.1      xfun_0.9            yaml_2.2.0         
## [19] compiler_3.6.1      BiocGenerics_0.31.5 BiocManager_1.30.4 
## [22] htmltools_0.3.6