---
title: Detecting exact nearest neighbors with KMKNN
author: 
- name: Aaron Lun
  affiliation: Cancer Research UK Cambridge Institute, Cambridge, United Kingdom
date: "Revised: 27 September 2018"
output:
  BiocStyle::html_document:
    toc_float: true
package: BiocNeighbors 
vignette: >
  %\VignetteIndexEntry{1. Detecting exact nearest neighbors}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}    
bibliography: ref.bib  
---

```{r, echo=FALSE, results="hide", message=FALSE}
require(knitr)
opts_chunk$set(error=FALSE, message=FALSE, warning=FALSE)
library(BiocNeighbors)
```

# Introduction

The `r Biocpkg("BiocNeighbors")` package provides an implementation of the k-means for k-nearest neighbors (KMKNN) algorithm, as described by @wang2012fast.
For a dataset with $N$ points, the pre-training is done as follows:

1. Apply k-means clustering to all points, partitioning the data into $\sqrt{N}$ clusters.
2. Compute the distance from each data point to its cluster center.
3. Store the cluster identities and distances.

For each query point, identification of the nearest neighbors is done as follows:

1. Start with a threshold distance $d$ to the current kth-nearest neighbor (this can be set with arbitrary points).
2. Compute the distance from the query to each cluster center.
3. For any given cluster center, apply the triangle inequality on the query-center distance, the center-point distances and $d$.
Only compute query-point distances for points where the triangle inequality holds.
4. Update $d$ with the new closest kth-nearest neighbor and repeat for the next cluster.

The pre-clustering arranges the points in a manner that effectively reduces the search space, even in high-dimensional data.
Note that, while `kmeans` itself is random, the k-nearest neighbors result is fully deterministic^[Except in the presence of ties, see `?findKNN` for details.].

The algorithm is implemented in a combination of R and C++, derived from code in `r Biocpkg("cydar")` [@lun2017testing].
We observe 2-5-fold speed-ups in 20- to 50-dimensional data, compared to KD-trees in `r CRANpkg("FNN")` and `r CRANpkg("RANN")` (see https://github.com/LTLA/OkNN2018 for timings).
This is consistent with results from @wang2012fast.

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

```{r}
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).

```{r}
fout <- findKNN(data, k=10, BNPARAM=KmknnParam())
head(fout$index)
head(fout$distance)
```

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:

```{r}
fout$index[3,]
```

... with the following distances to those neighbors:

```{r}
fout$distance[3,]
```

Note that the reported neighbors are sorted by distance.

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

```{r}
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`.

```{r}
qout <- queryKNN(data, query, k=5, BNPARAM=KmknnParam())
head(qout$index)
head(qout$distance)
```

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`:

```{r}
qout$index[3,]
```

... with the following distances to those neighbors:

```{r}
qout$distance[3,]
```

Again, the reported neighbors are sorted by distance.

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

```{r}
findKNN(data, k=5, subset=3:5)
```

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.

```{r}
names(findKNN(data, k=2, get.distance=FALSE))
```

It is also simple to speed up functions by parallelizing the calculations with the `r Biocpkg("BiocParallel")` framework.

```{r}
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 `buildNNIndex()`.
The result can then be passed to multiple calls, avoiding the overhead of repeated clustering^[The algorithm type is automatically determined when `BNINDEX` is specified, so there is no need to also specify `BNPARAM` in the later functions.].

```{r}
pre <- buildNNIndex(data, BNPARAM=KmknnParam())
out1 <- findKNN(BNINDEX=pre, k=5)
out2 <- queryKNN(BNINDEX=pre, query=query, k=2)
```

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.

# Session information

```{r}
sessionInfo()
```

# References
