# 1 Introduction

The BiocNeighbors package implements a few algorithms for exact nearest neighbor searching:

• The k-means for k-nearest neighbors (KMKNN) algorithm (Wang 2012) uses k-means clustering to create an index. Within each cluster, the distance of each of that cluster’s points to the cluster center are computed and used to sort all points. Given a query point, the distance to each cluster center is determined and the triangle inequality is applied to determine which points in each cluster warrant a full distance calculation.
• The vantage point (VP) tree algorithm (Yianilos 1993) involves constructing a tree where each node is located at a data point and is associated with a subset of neighboring points. Each node progressively partitions points into two subsets that are either closer or further to the node than a given threshold. Given a query point, the triangle inequality is applied at each node in the tree to determine if the child nodes warrant searching.
• The exhaustive search is a simple brute-force algorithm that computes distances to between all data and query points. This has the worst computational complexity but can actually be faster than the other exact algorithms in situations where indexing provides little benefit, e.g., data sets with few points and/or a very large number of dimensions.

Both KMKNN and VP-trees involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic1 Except in the presence of ties, see ?"BiocNeighbors-ties" for details..

# 2 Identifying k-nearest neighbors

The most obvious application is to perform a k-nearest neighbors search. We’ll mock up an example here with a hypercube of points, for which we want to identify the 10 nearest neighbors for each point.

nobs <- 10000
ndim <- 20
data <- matrix(runif(nobs*ndim), ncol=ndim)

The findKNN() method expects a numeric matrix as input with data points as the rows and variables/dimensions as the columns. We indicate that we want to use the KMKNN algorithm by setting BNPARAM=KmknnParam() (which is also the default, so this is not strictly necessary here). We could use a VP tree instead by setting BNPARAM=VptreeParam().

fout <- findKNN(data, k=10, BNPARAM=KmknnParam())
head(fout$index) ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] ## [1,] 6966 2345 364 3357 7940 9245 7127 4398 8060 1524 ## [2,] 4734 8999 5529 1019 4445 2926 4423 1349 9865 9417 ## [3,] 892 5574 7938 1864 6285 4712 4053 7120 5279 5856 ## [4,] 5452 8153 9156 4311 8217 9885 5835 5393 8735 5570 ## [5,] 8937 7156 348 4433 737 1821 9405 4796 9552 5320 ## [6,] 6907 8536 1748 5598 6960 1325 462 7171 4685 9313 head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.7776973 0.8700537 0.8767963 0.9216974 0.9359180 0.9810369 1.0016293
## [2,] 0.8343875 0.8807644 0.8924630 0.9629362 0.9719044 0.9952023 1.0051994
## [3,] 0.8718748 0.8791429 0.9288298 0.9432348 0.9455646 0.9587024 0.9705848
## [4,] 0.9330762 0.9427364 0.9471808 0.9680147 0.9697401 0.9730751 0.9940062
## [5,] 0.8051788 0.9064191 0.9518347 0.9707240 0.9765485 0.9979195 1.0006756
## [6,] 0.8496153 0.8615198 0.8711364 0.9073039 0.9105365 0.9390790 0.9486337
##           [,8]      [,9]     [,10]
## [1,] 1.0169742 1.0260894 1.0283572
## [2,] 1.0102552 1.0130979 1.0206382
## [3,] 0.9831783 1.0023356 1.0119333
## [4,] 0.9997092 1.0105132 1.0121907
## [5,] 1.0107289 1.0108943 1.0116958
## [6,] 0.9630361 0.9700085 0.9819331

Each row of the index matrix corresponds to a point in data and contains the row indices in data that are its nearest neighbors. For example, the 3rd point in data has the following nearest neighbors:

fout$index[3,] ## [1] 892 5574 7938 1864 6285 4712 4053 7120 5279 5856 … with the following distances to those neighbors: fout$distance[3,]
##  [1] 0.8718748 0.8791429 0.9288298 0.9432348 0.9455646 0.9587024 0.9705848
##  [8] 0.9831783 1.0023356 1.0119333

Note that the reported neighbors are sorted by distance.

# 3 Querying k-nearest neighbors

Another application is to identify the k-nearest neighbors in one dataset based on query points in another dataset. Again, we mock up a small data set:

nquery <- 1000
ndim <- 20
query <- matrix(runif(nquery*ndim), ncol=ndim)

We then use the queryKNN() function to identify the 5 nearest neighbors in data for each point in query.

qout <- queryKNN(data, query, k=5, BNPARAM=KmknnParam())
head(qout$index) ## [,1] [,2] [,3] [,4] [,5] ## [1,] 4748 5143 2161 985 190 ## [2,] 4546 9512 2101 2162 9874 ## [3,] 4234 6441 7670 437 3072 ## [4,] 7029 2987 108 5280 4646 ## [5,] 195 8004 7419 4412 9147 ## [6,] 4247 7508 234 6288 1893 head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8355364 0.8644510 0.9067951 0.9255964 0.9310698
## [2,] 0.9912407 1.0027198 1.0245590 1.0943507 1.1120131
## [3,] 0.9718264 1.0067038 1.0408267 1.0863400 1.0937376
## [4,] 0.7152471 0.8082353 0.9812473 0.9949586 1.0013448
## [5,] 0.8899148 1.0029292 1.0320386 1.0928665 1.1086294
## [6,] 0.8579169 0.9291671 0.9555271 0.9624404 0.9944201

Each row of the index matrix contains the row indices in data that are the nearest neighbors of a point in query. For example, the 3rd point in query has the following nearest neighbors in data:

qout$index[3,] ## [1] 4234 6441 7670 437 3072 … with the following distances to those neighbors: qout$distance[3,]
## [1] 0.9718264 1.0067038 1.0408267 1.0863400 1.0937376

Again, the reported neighbors are sorted by distance.

# 4 Further options

Users can perform the search for a subset of query points using the subset= argument. This yields the same result as but is more efficient than performing the search for all points and subsetting the output.

findKNN(data, k=5, subset=3:5)
## $index ## [,1] [,2] [,3] [,4] [,5] ## [1,] 892 5574 7938 1864 6285 ## [2,] 5452 8153 9156 4311 8217 ## [3,] 8937 7156 348 4433 737 ## ##$distance
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.8718748 0.8791429 0.9288298 0.9432348 0.9455646
## [2,] 0.9330762 0.9427364 0.9471808 0.9680147 0.9697401
## [3,] 0.8051788 0.9064191 0.9518347 0.9707240 0.9765485

If only the indices are of interest, users can set get.distance=FALSE to avoid returning the matrix of distances. This will save some time and memory.

names(findKNN(data, k=2, get.distance=FALSE))
## [1] "index"

It is also simple to speed up functions by parallelizing the calculations with the BiocParallel framework.

library(BiocParallel)
out <- findKNN(data, k=10, BPPARAM=MulticoreParam(3))

For multiple queries to a constant data, the pre-clustering can be performed in a separate step with buildIndex(). The result can then be passed to multiple calls, avoiding the overhead of repeated clustering2 The algorithm type is automatically determined when BNINDEX is specified, so there is no need to also specify BNPARAM in the later functions..

pre <- buildIndex(data, BNPARAM=KmknnParam())
out1 <- findKNN(BNINDEX=pre, k=5)
out2 <- queryKNN(BNINDEX=pre, query=query, k=2)

The default setting is to search on the Euclidean distance. Alternatively, we can use the Manhattan distance by setting distance="Manhattan" in the BiocNeighborParam object.

out.m <- findKNN(data, k=5, BNPARAM=KmknnParam(distance="Manhattan"))

Advanced users may also be interested in the raw.index= argument, which returns indices directly to the precomputed object rather than to data. This may be useful inside package functions where it may be more convenient to work on a common precomputed object.

# 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
## [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] BiocParallel_1.33.4  BiocNeighbors_1.17.1 knitr_1.40
## [4] 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] lattice_0.20-45     digest_0.6.30       R6_2.5.1
## [25] parallel_4.3.0      magrittr_2.0.3      bslib_0.4.1
## [28] Matrix_1.5-1        tools_4.3.0         BiocGenerics_0.45.0
## [31] cachem_1.0.6

# References

Wang, X. 2012. “A Fast Exact k-Nearest Neighbors Algorithm for High Dimensional Search Using k-Means Clustering and Triangle Inequality.” Proc Int Jt Conf Neural Netw 43 (6): 2351–8.

Yianilos, P. N. 1993. “Data Structures and Algorithms for Nearest Neighbor Search in General Metric Spaces.” In SODA, 93:311–21. 194.