---
title: "SpatialKDE quickstart"
author: "Jan Caha"
date: "`r Sys.time()`"
output: 
  rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{SpatialKDE quickstart}
  %\usepackage[utf8]{inputenc}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Inspiration

SpatialKDE implements kernel density estimation for spatial data with all the necessary settings, including selection of bandwidth, kernel type and underlying grid (cell size and shape). The algorithm is based on [Heatmap tool](https://docs.qgis.org/testing/en/docs/user_manual/processing_algs/qgis/interpolation.html#heatmap-kernel-density-estimation) from [QGIS](https://qgis.org/en/site/). The tool is adapted directly from [source code](https://github.com/qgis/QGIS/blob/b3d2619976a69d7fb67b884492da491dfaba287c/src/analysis/raster/qgskde.cpp). Example tutorial about the QGIS tool is [available here](https://grindgis.com/software/heat-map-using-qgis).

## Example

First we load all necessary packages.

```{r, message=FALSE}
library(SpatialKDE)
library(sp)
library(sf)
library(dplyr)
library(tmap)
```

Then we load the example dataset and prepare it into expected format of `sf` `data.frame`.

```{r}
data(meuse)

meuse <- meuse %>%
  st_as_sf(coords = c("x", "y"), dim = "XY") %>%
  st_set_crs(28992) %>%
  select()
```

Let's define variables necessary for KDE estimation, cell size of the resulting grid and band width of points.

```{r}
cell_size <- 100
band_width <- 150
```

### Vector grid

Now we can prepare grid for KDE estimation. We prepare rectangular grid (hexagonal is the second option) with given cell size which is slightly bigger than convex hull of the data.

```{r}
grid_meuse <- meuse %>%
  create_grid_rectangular(cell_size = cell_size, side_offset = band_width)
```

At this moment it is possible to calculate KDE using `kde()` function with specified settings.

```{r}
kde <- meuse %>%
  kde(band_width = band_width, kernel = "quartic", grid = grid_meuse)
```

The result can be visualized using `tmap` package.

```{r}
tm_shape(kde) +
  tm_polygons(col = "kde_value", palette = "viridis", title = "KDE Estimate") +
  tm_shape(meuse) +
  tm_bubbles(size = 0.1, col = "red")
```

### Raster

Now we can prepare raster for KDE estimation. We prepare raster with given cell size which is slightly bigger than convex hull of the data.

```{r}
raster_meuse <- meuse %>%
  create_raster(cell_size = cell_size, side_offset = band_width)
```

At this moment it is possible to calculate KDE using `kde()` function with specified settings.

```{r}
kde <- meuse %>%
  kde(band_width = band_width, kernel = "triweight", grid = raster_meuse)
```

The result can be visualized using `tmap` package.

```{r}
tm_shape(kde) +
  tm_raster(palette = "viridis", title = "KDE Estimate") +
  tm_shape(meuse) +
  tm_bubbles(size = 0.1, col = "red") +
  tm_layout(legend.outside = TRUE)
```
