---
title: 'Getting started with kdtools'
author: "Timothy H. Keitt"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with kdtools}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, echo=FALSE}
has_kdtools = require(kdtools, quietly = TRUE)
if (!has_kdtools) cat("kdtools package not installed; results not evaluted\n")
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = has_kdtools
)
```

The kdtools package can be used to search for multidimensional points in a boxed region and find nearest neighbors in 1 to 9 dimensions. The package uses binary search on a sorted sequence of values. The current package is limited to matrices of real values. If you are interested in using string or mixed types in different dimensions, see the methods vignette.

Using kdtools is straightforward. There are four steps:

##### Step 1. Convert your matrix of values into a arrayvec object

```{r}
library(kdtools)
x = matrix(runif(3e3), nc = 3)
y = matrix_to_tuples(x)
y[1:3, c(1, 3)]
```

The arrayvec object can be manipulated as if it were a matrix.

##### Step 2. Sort the data

```{r}
kd_sort(y, inplace = TRUE, parallel = TRUE)
```

##### Step 3. Search the data

```{r}
rq = kd_range_query(y, c(0, 0, 0), c(1/4, 1/4, 1/4)); rq
i = kd_nearest_neighbor(y, c(0, 0, 0)); y[i, ]
nns = kd_nearest_neighbors(y, c(0, 0, 0), 100); nns
nni = kd_nn_indices(y, c(0, 0, 0), 10); nni
```

The ```kd_nearest_neighbor``` and ```kd_nn_indices``` functions return row-indices. The other functions return arrayvec objects.

##### Step 4. Convert back to a matrix for use in R

```{r}
head(tuples_to_matrix(rq))
head(tuples_to_matrix(nns))
```

If you pass a matrix instead of an arrayvec object to any of the functions, it will be converted to an arrayvec object internally and results will be returned as matrices. This is slower and provided for convenience.

