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,] 8548 8170 1147 2375 4570  684 6395 1089 2464  7626
## [2,] 9859 5164 3304 7042 7726 6900 6937  566 9319  6181
## [3,] 8638  499 2255 6781 2777 4380 5732 7421 6767  1527
## [4,] 5907 2001 6869 1136 9618 5919 7726 4640 4397  3815
## [5,] 3415 6838 7410 8508 6251  465 5413 6881 3997  4810
## [6,] 2381 9467 4462 1380 3608  141 4134 9900   58  5327
head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.9517188 1.0120275 1.0256116 1.0384012 1.0534431 1.0741335 1.0760807
## [2,] 0.9980683 1.0180894 1.0671076 1.0690955 1.0722303 1.1014323 1.1182870
## [3,] 0.8836277 0.9496791 1.0099357 1.0553443 1.0617758 1.0766279 1.1169646
## [4,] 0.8691962 0.8869227 0.9781138 0.9937236 1.0215335 1.0309957 1.0520850
## [5,] 0.7470980 1.0302471 1.0302728 1.0370272 1.0470924 1.0479103 1.0742189
## [6,] 0.9002295 0.9331822 0.9404964 0.9412764 0.9725459 0.9740628 0.9899004
##           [,8]      [,9]    [,10]
## [1,] 1.0766690 1.0841007 1.088716
## [2,] 1.1272091 1.1478179 1.151226
## [3,] 1.1214929 1.1259019 1.130085
## [4,] 1.0559744 1.0585030 1.064524
## [5,] 1.0766065 1.0821961 1.083857
## [6,] 0.9969236 0.9985535 1.000302

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,] 2782 7040 6627 4164 9759
## [2,] 6882 5572 8192 8435 9958
## [3,] 3665 4131 4929 8348  548
## [4,] 1281 5664 4083 1462 5347
## [5,] 7147 1255 9236 6443  522
## [6,] 3201 6894 6181 9825 1653
head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8731615 0.9428365 1.0173877 1.0224209 1.0616685
## [2,] 1.0842409 1.0942212 1.0975769 1.1120467 1.1421762
## [3,] 0.8207767 0.8316743 0.8610218 0.8639438 0.9182987
## [4,] 0.8928744 0.9140493 1.0614805 1.0651276 1.0817591
## [5,] 0.8204831 0.9043658 0.9282364 0.9384299 0.9424062
## [6,] 0.8330854 0.9642053 0.9649779 0.9775202 1.0219027

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/RtmpwATJTH/file3219755a64e34.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 4.3.0 RC (2023-04-18 r84287)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 22.04.2 LTS
## 
## Matrix products: default
## BLAS:   /home/biocbuild/bbs-3.18-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       
## 
## time zone: America/New_York
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] BiocNeighbors_1.19.0 knitr_1.42           BiocStyle_2.29.0    
## 
## loaded via a namespace (and not attached):
##  [1] cli_3.6.1           rlang_1.1.0         xfun_0.39          
##  [4] jsonlite_1.8.4      S4Vectors_0.39.0    htmltools_0.5.5    
##  [7] stats4_4.3.0        sass_0.4.5          rmarkdown_2.21     
## [10] grid_4.3.0          evaluate_0.20       jquerylib_0.1.4    
## [13] fastmap_1.1.1       yaml_2.3.7          bookdown_0.33      
## [16] BiocManager_1.30.20 compiler_4.3.0      codetools_0.2-19   
## [19] Rcpp_1.0.10         BiocParallel_1.35.0 lattice_0.21-8     
## [22] digest_0.6.31       R6_2.5.1            parallel_4.3.0     
## [25] bslib_0.4.2         Matrix_1.5-4        tools_4.3.0        
## [28] BiocGenerics_0.47.0 cachem_1.0.7