# 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.

Both methods involve a component of randomness during index construction, though the k-nearest neighbors result is fully deterministic1 Except in the presence of ties, see ?findKNN 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,] 8643 8050 7556 1791 4870 8307 8629 8019 9312 5341 ## [2,] 5039 9249 243 1143 6499 3085 7503 161 5712 3050 ## [3,] 7506 5840 2518 6 1088 4421 6208 7573 990 9407 ## [4,] 1027 662 5137 1460 6846 4309 9395 9133 180 4288 ## [5,] 2707 3685 8865 495 8993 3949 4583 2054 385 1070 ## [6,] 3548 7151 1351 2059 6314 4411 7116 7499 9969 5867 head(fout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 0.9928941 1.0142308 1.0616408 1.0736943 1.0908586 1.0942658 1.1019943
## [2,] 0.8132958 0.8967493 0.9023984 0.9345345 0.9748746 0.9812595 0.9867675
## [3,] 1.0829746 1.1423671 1.1580350 1.2010582 1.2023029 1.2079923 1.2112802
## [4,] 0.8652383 0.9778326 0.9925514 1.0043222 1.0069838 1.0101185 1.0245297
## [5,] 0.9143798 0.9690342 0.9991463 1.0304064 1.0421800 1.0571152 1.0595250
## [6,] 0.8284996 0.8471161 0.8522459 0.9318427 0.9468924 0.9524671 0.9531929
##           [,8]      [,9]     [,10]
## [1,] 1.1232429 1.1268754 1.1422908
## [2,] 1.0037871 1.0047605 1.0213207
## [3,] 1.2203126 1.2238721 1.2275924
## [4,] 1.0260313 1.0264183 1.0329192
## [5,] 1.0604566 1.0632011 1.0674584
## [6,] 0.9537012 0.9603866 0.9661172

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,] ##  7506 5840 2518 6 1088 4421 6208 7573 990 9407 … with the following distances to those neighbors: fout$distance[3,]
##   1.082975 1.142367 1.158035 1.201058 1.202303 1.207992 1.211280 1.220313
##   1.223872 1.227592

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,] 8811 6071 2838 1342 5033 ## [2,] 5408 2380 7810 7902 7808 ## [3,] 3144 2212 7847 8559 709 ## [4,] 8183 5403 7618 5460 8569 ## [5,] 8384 3346 4215 5805 3038 ## [6,] 597 2503 604 868 2022 head(qout$distance)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,] 0.7731231 0.7849397 0.8591461 0.9307955 0.9320467
## [2,] 0.8230939 0.8432400 0.9054017 0.9205062 0.9359921
## [3,] 0.9397287 1.0152623 1.0362824 1.0418488 1.0609618
## [4,] 0.9595535 0.9883123 1.0193167 1.0199952 1.0249624
## [5,] 0.9146208 0.9792278 0.9972007 1.0036989 1.0083684
## [6,] 1.0225860 1.0238219 1.0238623 1.0642002 1.0661172

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,] ##  3144 2212 7847 8559 709 … with the following distances to those neighbors: qout$distance[3,]
##  0.9397287 1.0152623 1.0362824 1.0418488 1.0609618

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,] 7506 5840 2518 6 1088 ## [2,] 1027 662 5137 1460 6846 ## [3,] 2707 3685 8865 495 8993 ## ##$distance
##           [,1]      [,2]      [,3]     [,4]     [,5]
## [1,] 1.0829746 1.1423671 1.1580350 1.201058 1.202303
## [2,] 0.8652383 0.9778326 0.9925514 1.004322 1.006984
## [3,] 0.9143798 0.9690342 0.9991463 1.030406 1.042180

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))
##  "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 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:
##   LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
##   LC_TIME=en_US.UTF-8        LC_COLLATE=C
##   LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
##   LC_PAPER=en_US.UTF-8       LC_NAME=C
##   LC_ADDRESS=C               LC_TELEPHONE=C
##  LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
##  stats     graphics  grDevices utils     datasets  methods   base
##
## other attached packages:
##  BiocParallel_1.19.2 BiocNeighbors_1.3.5 knitr_1.24
##  BiocStyle_2.13.2
##
## loaded via a namespace (and not attached):
##   Rcpp_1.0.2          bookdown_0.13       lattice_0.20-38
##   digest_0.6.20       grid_3.6.1          stats4_3.6.1
##   magrittr_1.5        evaluate_0.14       stringi_1.4.3
##  S4Vectors_0.23.23   Matrix_1.2-17       rmarkdown_1.15
##  tools_3.6.1         stringr_1.4.0       parallel_3.6.1
##  xfun_0.9            yaml_2.2.0          compiler_3.6.1
##  BiocGenerics_0.31.5 BiocManager_1.30.4  htmltools_0.3.6