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,] 1328 8209 8698 6205 7716 9755  857 4327 9395    45
## [2,] 6090 2506 9237  976 1569 9680 1681 8867 8179  5668
## [3,] 8419 8211 4708 7182 9307 1796 1413 2820 6178  6888
## [4,] 3332 3101 9827 8555 8592  946  978  695 5137  2981
## [5,] 1781 7503 4954 1183  909 6876 3900 1466 8377  2513
## [6,] 1384 4414 2217 5658 1368 6633 2442 3333 1902  9202
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]     [,6]      [,7]
## [1,] 0.9148024 0.9329432 0.9800840 0.9870709 0.9932765 1.020266 1.0272948
## [2,] 0.9413603 0.9424692 0.9471124 0.9898835 1.0161449 1.033909 1.0351001
## [3,] 0.8062516 0.9044392 0.9986783 1.0512936 1.0969270 1.101127 1.1338973
## [4,] 1.0224324 1.0302504 1.0410523 1.0695564 1.0757608 1.086630 1.0895566
## [5,] 1.0043701 1.0221999 1.0573267 1.0621514 1.0650520 1.067750 1.0919811
## [6,] 0.8912356 0.9176356 0.9455892 0.9527062 0.9715992 0.987462 0.9910966
##          [,8]     [,9]    [,10]
## [1,] 1.035586 1.036519 1.049644
## [2,] 1.048850 1.053960 1.054224
## [3,] 1.139789 1.145370 1.149950
## [4,] 1.090663 1.096204 1.098258
## [5,] 1.100330 1.102819 1.103325
## [6,] 1.019513 1.027203 1.028925

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,]  675 4392 8889 8886 3376
## [2,] 3767 8932 3018 1014 2925
## [3,] 7641 6935 2174 5336 6271
## [4,]  907 6208 4157 6608 3942
## [5,] 1437  897 4916 7940 2265
## [6,] 4734 3743 9598  450 4939
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 1.0064285 1.0237116 1.0455811 1.0669134 1.1048272
## [2,] 0.8249434 0.8834664 0.8883641 0.9491608 0.9493644
## [3,] 0.8535443 0.9548987 0.9667131 0.9706458 0.9800720
## [4,] 0.9059674 0.9100789 0.9309329 0.9332540 0.9353861
## [5,] 1.1374471 1.1422772 1.1659412 1.1734180 1.1874903
## [6,] 0.8685266 0.9359400 0.9389691 0.9567371 0.9981503

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/RtmpVD5fjS/file4387544b57c3.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) (2019-10-24 r77329)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.3 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.11-bioc/R/lib/libRblas.so
## LAPACK: /home/biocbuild/bbs-3.11-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.5.1 knitr_1.25          BiocStyle_2.15.0   
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.2          bookdown_0.14       lattice_0.20-38    
##  [4] digest_0.6.22       grid_4.0.0          stats4_4.0.0       
##  [7] magrittr_1.5        evaluate_0.14       rlang_0.4.1        
## [10] stringi_1.4.3       S4Vectors_0.25.0    Matrix_1.2-17      
## [13] rmarkdown_1.16      BiocParallel_1.21.0 tools_4.0.0        
## [16] stringr_1.4.0       parallel_4.0.0      xfun_0.10          
## [19] yaml_2.2.0          compiler_4.0.0      BiocGenerics_0.33.0
## [22] BiocManager_1.30.9  htmltools_0.4.0