Adapted K nearest neighbors based on RcppHNSW

knn(
  query,
  ref,
  k,
  distance = "euclidean",
  same = FALSE,
  threads = 1L,
  verbose = FALSE,
  progress = FALSE,
  ...
)

Arguments

query

A data.table containing the set of query points where each row represent a point and each column a given coordinate.

ref

A numeric containing the set of reference points where each row represent a point and each column a given coordinate.

k

An integer describing the number of nearest neighbors to search for.

distance

Type of distance to calculate. "euclidean" as default. Look hnsw_knn for more options.

same

Logic. If TRUE, it delete neighbors with distance of 0, useful when the k search is based on the same query.

threads

An integer specifying the number of threads to use for parallel processing. Experiment to see what works best for your data on your hardware.

verbose

If TRUE, log messages to the console.

progress

If TRUE, log a progress bar when verbose = TRUE. Tracking progress could cause a small overhead.

...

Arguments passed to hnsw_build and hnsw_search.

Value

A data.table with three columns describing the indices of the query, ref, and k neighbors and the distances.

Details

This function is based on hnswlib C++ library (Malkov & Yashunin 2016) and its bindings for R (RcppHNSW; Melville 2020) for a fast estimation of neighbors points. It is adapted to simplify the workflow within rTLS. If you use this function, please consider cite the C++ library and RcppHNSW package.

References

Malkov, Y. A., & Yashunin, D. A. (2016). Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs. arXiv preprint arXiv:1603.09320.

See also

Author

J. Antonio Guzmán Q.

Examples


#Point cloud
data("pc_tree")

#knn search using k = 3
knn(pc_tree, pc_tree, k = 3, same = TRUE)
#>         query   ref k_index   distance
#>      1:     1     3       1 0.05085840
#>      2:     1     2       2 0.07497273
#>      3:     1    12       3 0.08123342
#>      4:     2     8       1 0.05425572
#>      5:     2     7       2 0.05703727
#>     ---                               
#> 227540: 75847 75848       2 0.05270452
#> 227541: 75847 74605       3 0.05433807
#> 227542: 75848 75847       1 0.05270452
#> 227543: 75848 75846       2 0.05628597
#> 227544: 75848 75842       3 0.06814787