---
title: "muHVT: Collection of functions used for vector quantization and construction
of hierarchical Voronoi Tessellations for data analysis in R"
author: "Meet Dave, Avinash Joshi, Zubin Dowlaty"
date: "`r Sys.Date()`"
output: 
      rmarkdown::html_vignette:
      number_sections: true
      toc: true
      toc_depth : 2
        
vignette: >
  %\VignetteIndexEntry{muHVT Package}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  out.width = "672px",
  out.height = "480px",
  fig.width = 7,
  fig.height = 5,
  fig.align = "center",
  fig.retina = 1,
  dpi = 72
)


library(muHVT)
library(dplyr)
library(kableExtra)
library(geozoo)
library(plotly)

options(expressions = 10000)



global_var <- nzchar(Sys.getenv("RUN_VIGNETTE"))
#global_var <- TRUE

scrolLimit <- function(noOfRows){
  if(noOfRows<10){
    
    swe = paste(as.character(noOfRows*50),"px")
  }
  else{
    swe = "400px"
  }
  return(swe)
}

Table <- function(data,scroll = F,limit=NULL){
  
  if(!is.null(limit)){
    data <- head(data,limit)
  }
  
  kable_table <- data %>% kable(escape = F,align = "c") %>% kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
  
  scroll <- scroll
  
  if(scroll == T){
  kable_table <- kable_table %>% scroll_box(width = "100%", height = scrolLimit(nrow(data)))
  }
  

  
  return(kable_table)
  
}

summaryTable <- function(data,scroll = T,columnName='Quant.Error',value=0.2,limit=NULL){
  
  scroll <- scroll
  summaryTable <- data %>%  dplyr::mutate_if(is.numeric, funs(round(.,2))) %>% dplyr::mutate(!!columnName:=  cell_spec(eval(parse(text = columnName)),color = ifelse(is.na(eval(parse(text = columnName))),"#333",ifelse(eval(parse(text = columnName)) < value,"red","#333"))))  
  
  return(Table(summaryTable,scroll = scroll,limit = limit))
  
}

compressionSummaryTable <- function(data,scroll = T,columnName='percentOfCellsBelowQuantizationErrorThreshold',value=0.8){
  
  
  summaryTable <- data %>%  dplyr::mutate_if(is.numeric, funs(round(.,2))) %>% dplyr::mutate(!!columnName:=  cell_spec(eval(parse(text = columnName)),color = ifelse(is.na(eval(parse(text = columnName))),"#00bb27",ifelse(eval(parse(text = columnName)) > value,"#00bb27","#333")))) 
  
  return(Table(summaryTable,scroll = scroll))
  
}


set.seed(240)
```


# Abstract


The muHVT package is a collection of R functions for vector quantization and
construction of hierarchical voronoi tessellations as a data visualization
tool to visualize cells using quantization. The hierarchical cells are computed using
Hierarchical K-means where a quantization threshold governs the levels
in the hierarchy for a set $k$ parameter (the maximum number of cells
at each level). The package is particularly helpful to visualize rich mutlivariate data. 


This package additionally provides functions for computing the
Sammon’s projection and plotting the heat map of the variables on the tiles of the tessellations.


#Vector Quantization


This package performs vector quantization using the following algorithm - 

*  Hierarchical Vector Quantization using $k-means$ 


##Hierarchical VQ using k-means 

### k-means

1. The k-means algorithm randomly selects *k* data points as initial means.
1. *k* clusters are formed by assigning each data point to its closest cluster mean. The algorithm uses the Euclidean distance.
1. Virtual means for each cluster are calculated by using all datapoints contained in a cluster.

The second and third step is iterated until a predefined number of iteration is reached or the clusters converge. The runtime for the algorithm is O(n).

### Hierarchical VQ using k-means 

The algorithm divides the dataset recursively into cells. The $k-means$ algorithm is used by setting $k$ to say, two in order to divide the dataset into two subsets.Then, the two subsets are divided again into two subsets by setting $k$ to two to result in a total of four subsets. The recursion terminates when the cells contain single data point or a stop criterion is reached. In this case, the stop criterion is when the cell error exceeds the quantization threshold.

Following are the steps for the method :-

1. Select k(number of cells), depth and quantization error threshold
1. Perform k-means on the input dataset
1. Calculate quantization error for each of the k cells
1. Compare the quantization error for each cell to quantization threshold error
1. Repeat steps 2 to 4 for each of the k cells whose quantization error is above threshold until stop criterion is reached. The stop criterion is when the quantization error of a cell reaches below quantization error threshold or there is a single point in the cell or we have reached the user specified depth.

The quantization error for a cell is defined as follows :

$$QE  = \max_i(||A-F_i||_{p})$$ 


where 

*  $A$ is the centroid of the cell
*  $F_i$ represents a data point in the cell 
*  $m$ is the number of points in the cell.
*  $p$ is the $p$-norm metric. Here $p$ = 1 represents L1 Norm and $p$ = 2 represents L2 Norm.

### Quantization error

Let's try to understand quantization error with an example

```{r Quantization Error,echo=FALSE,warning=FALSE,fig.show='hold',message=FALSE,out.width='90%',fig.height=8,fig.cap='Figure 1: The Voronoi tessellation for level 1 shown for the 5 cells with the points overlayed'}
knitr::include_graphics('quant_explainer.png')
```

An example of 2 dimensional VQ is shown above.

In the above image, we can see that there are 5 cells and each cells contain certain number of points. The centroid for each cell is shown in blue. We can also call the centroids as codewords as they represent all the points in that cell. The set of all codewords is called a codebook.

Now we want to calculate quantization error for each cell. For the sake of simplicity, let's consider only once cell having centroid `A` and `m` data points $F_i$ for calculating quantization error.

For each point, we calculate the distance between the point and the centroid.

$$ d = ||A - F_i||_{p} $$

In the above equation, p = 1 means `L1_Norm` distance whereas p = 2 means `L2_Norm` distance.In the package, the `L1_Norm` distance is chosen by default. The user can pass either `L1_Norm` or `L2_Norm` or a custom function to calculate the distance between two points in n dimensions.

$$QE  = \max_i(||A-F_i||_{p})$$ 


Now, we take the max of the distance of all m points. This gives us the max distance of a point in the cell from the centroid which we refer to as `Quantization Error`. If the quantization error is higher than the given threshold, this means that the centroid/codevector is not a good representation for the points in the cell. Now we can perform vector quantization on this points further and repeat the steps above.

Please note that the user can select mean, max or any custom function to calculate the quantization error. The custom function takes a vector of m value (where each value is a distance between point in `n` dimensions and centroids) and returns a single value which is the quantization error for the cell.

If we select `mean` as the error metric, the above Quantization Error equation will look like this :- 

$$QE  = \frac{1}{m}\sum_{i=1}^m||A-F_i||_{p}$$ 



#Voronoi Tessellations

A Voronoi diagram is a way of dividing space into a number of regions. A set of points (called seeds, sites, or generators) is specified beforehand and for each seed there will be a corresponding region consisting of all points closer to that seed than to any other. The regions are called Voronoi cells. It is dual to the Delaunay triangulation.

##Sammon’s projection

Sammon projection is an algorithm that maps a high-dimensional space to a space of lower dimensionality by trying to preserve the structure of inter-point distances in high-dimensional space in the lower-dimension projection. It is particularly suited for use in exploratory data analysis. It is considered a non-linear approach as the mapping cannot be represented as a linear combination of the original variables. The centroids are plotted in 2D after performing Sammon’s projection at every level of the tessellation.


Denote the distance between $i^{th}$ and $j^{th}$ objects in the original space by $d_{ij}^*$, and the distance between their projections by $d_{ij}$. Sammon’s mapping aims to minimize the following error function, which is often referred to as Sammon’s stress or Sammon’s error:

$$E=\frac{1}{\sum_{i<j} d_{ij}^*}\sum_{i<j}\frac{(d_{ij}^*-d_{ij})^2}{d_{ij}^*}$$

The minimization can be performed either by gradient descent, as proposed initially, or by other means, usually involving iterative methods. The number of iterations need to be experimentally determined and convergent solutions are not always guaranteed. Many implementations prefer to use the first Principal Components as a starting configuration.

### Constructing Voronoi tesselations

In this package, we use `sammons` from the package `MASS` to project higher dimensional data to 2D space. The function `hvq` called inside from function `HVT` returns hierarchical quantized data which will be the input for construction tesselations. The data is then represented in 2d coordinates and the tessellations are plotted using these coordinates as centroids. We use the package `deldir` for this purpose. The `deldir` package computes the Delaunay triangulation (and hence the Dirichlet or Voronoi tesselation) of a planar point set according to the second (iterative) algorithm of Lee and Schacter.For subsequent levels, transformation is performed on the 2d coordinates to get all the points within its parent tile. Tessellations are plotted using these transformed points as centroids. The lines in the tessellations are chopped in places so that they do not protrude outside the parent polygon. This is done for all the subsequent levels.

####Example Usage 1

In this section, we will use the `Prices of Personal Computers` dataset. This dataset contains 6259 observations and 10 features. The dataset observes the price from 1993 to 1995 of 486 personal computers in the US. The variables are price,speed,ram,screen,cd,etc. The dataset can be downloaded from [here](https://github.com/thomaspernet/data_csv_r/blob/master/data/Computers.csv)

In this example, we will compress this dataset by using hierarhical VQ using k-means and visualize the Voronoi tesselation plots using Sammons projection. Later on, we will overlay price,speed and screen variable as heatmap to generate further insights.

Here, we load the data and store into a variable `computers`.

```{r load data computer,warning=FALSE,message=FALSE,eval = T}
set.seed(240)
# Load data from csv files
computers <- read.csv("https://raw.githubusercontent.com/thomaspernet/data_csv_r/master/data/Computers.csv")
```

Let's have a look at sample of the data

```{r sample data computer,warning=FALSE,message=FALSE,eval = T}
# Quick peek
Table(head(computers))
```


Now let us check the structure of the data

```{r data structure computer,warning=FALSE,message=FALSE,eval = global_var}
str(computers)
```

Let's get a summary of the data

```{r data summary computer,warning=FALSE,message=FALSE,eval = global_var}
summary(computers)
```

Let us first split the data into train and test. We will use 80% of the data as train and remaining as test.

```{r train-test computer,warning=FALSE,message=FALSE,eval = global_var}
noOfPoints <- dim(computers)[1]
trainLength <- as.integer(noOfPoints * 0.8)

trainComputers <- computers[1:trainLength,]
testComputers <- computers[(trainLength+1):noOfPoints,]
```

K-means in not suitable for factor variables as the sample space for factor variables is discrete. A Euclidean distance function on such a space isn't really meaningful. Hence we will delete the factor variables in our dataset. 

Here we keep the original `trainComputers` and `testComputers` as we will use price variable from this dataset to overlay as heatmap and generate some insights.

```{r pre-processing data computer,warning=FALSE,message=FALSE,eval = global_var}
trainComputers <- trainComputers %>% dplyr::select(-c(X,cd,multi,premium,trend))
testComputers <- testComputers %>% dplyr::select(-c(X,cd,multi,premium,trend))
```

Let us try to understand HVT function first. 

```{r HVT function,echo = TRUE, eval= FALSE}
HVT(dataset, nclust, depth, quant.err, projection.scale, normalize = T, distance_metric = c("L1_Norm","L2_Norm"), error_metric = c("mean","max"))
```

Here I have explained all the parameters in detail

* __`dataset`__ - Dataframe. A dataframe with numeric columns 

* __`nlcust`__  - Numeric. An integer indicating the number of cells per hierarchy (level)

* __`depth`__   - An integer indicating the number of levels. (1 = No hierarchy, 2 = 2 levels, etc ...)

* __`quant.error`__ - A number indicating the quantization error threshold. A cell will only breakdown
into further cells only if the quantization error of the cell is above quantization error threshold.

* __`projection.scale`__ - A number indicating the scale factor for the tesselations so as to visualize the sub-tesselations well enough.

* __`normalize`__	- A logical value indicating if the columns in your dataset should be normalized. Default value is TRUE. The algorithm supports Z-score normalization.

* __`distance_metric`__	- The distance metric can be `L1_Norm` or `L2_Norm`. `L1_Norm` is selected by default. The distance metric is used to calculate the distance between a `n` dimensional point and centroid. The user can also pass a custom function to calculate the distance.

* __`error_metric`__ - The error metric can be `mean` or `max`. The `max` will return the max of `m` values. The `mean` will take mean of `m` values where each value is a distance between a point and centroid of the cell. Moreover, the user can also pass a custom function to calculate the error metric.


First we will perform hierarchical vector quantization at level 1 by setting the parameter depth to 1. Here level 1 signifies no hierarchy. Let's keep the no of cells as 15.

```{r level one computers,warning=FALSE,message=FALSE,results='asis',eval = global_var}
set.seed(240)
hvt.results <- list()
hvt.results <- muHVT::HVT(trainComputers,
                          nclust = 15,
                          depth = 1,
                          quant.err = 0.2,
                          projection.scale = 10,
                          normalize = T)
```

Now let's try to understand plotHVT function. Here I have explained all the parameters in detail

```{r plotHVT function,echo = TRUE, eval= FALSE}
plotHVT(hvt.results, line.width, color.vec, pch1 = 21, centroid.size = 3, title = NULL)
```

* __`hvt.results`__ -  A list containing the ouput of HVT function which has the details of the tessellations to be plotted

* __`line.width`__	- A vector indicating the line widths of the tessellation boundaries for each level

* __`color.vec`__	- A vector indicating the colors of the boundaries of the tessellations at each level

* __`pch1`__	- Symbol type of the centroids of the tessellations (parent levels). Refer points. (default = 21)

* __`centroid.size`__	- Size of centroids of first level tessellations. (default = 3)

* __`title`__	- Set a title for the plot. (default = NULL)

Let's plot the voronoi tesselation

```{r plot level one computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 2: The Voronoi tessellation for level 1 shown for the 15 cells in the dataset ’computers’',eval = global_var}
# Voronoi tesselation plot for level one
plotHVT(hvt.results,
        line.width = c(1.2), 
        color.vec = c("#141B41"))
```

As per the manual, __`hvt.results[[3]]`__ gives us detailed information about the hierarchical vector quantized data

__`hvt.results[[3]][['summary']]`__ gives a nice tabular data containing no of points, quantization error and the codebook.

Now let us understand what each column in the summary table means

* __`Segment Level`__ - Level of the cell. In this case, we have performed vector quantization for depth 1. Hence Segment Level is 1

* __`Segment Parent`__ - Parent Segment of the cell

* __`Segment Child`__ - The children of a particular cell. In this case, first level has 15 cells Hence, we can see Segment Child 1,2,3,4,5 ,..,15.

* __`n`__ - No of points in each cell

* __`Quant.Error`__ - Quantization error for each cell

All the columns after this will contains centroids for each cell for all the variables. They can be also called as codebook as is the collection of centroids for all cells (codewords)


```{r summary level one computers,warning=FALSE,eval = global_var}
summaryTable(hvt.results[[3]][['summary']])
```


Let's have a look at `Quant.Error` variable in the above table. It seems that none of the cells have hit the quantization threshold error.

Now let's check the compression summary. The table below shows no of cells, no of cells having quantization error below threshold and percentage of cells having quantization error below threshold for each level.

```{r compression summary level one computers,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.results[[3]]$compression_summary)
```

As it can be seen in the table above, percentage of cells in level1 having quantization error below threshold is `0%`. Hence we can go one level deeper and try to compress it further.

We will now overlay the `Quant.Error` variable as heatmap over the voronoi tesselation plot to visualize the quantization error better.

Let's have look at the function `hvtHmap` which we will use to overlay a variable as heatmap.

```{r hvtHmap function,echo = TRUE, eval= FALSE}
hvtHmap(hvt.results, dataset, child.level, hmap.cols, color.vec ,line.width, palette.color = 6)
```

* __`hvt.results`__ - A list of hvt.results obtained from the HVT function.

* __`dataset`__	- A dataframe containing the variables that you want to overlay as heatmap. The user can pass an external dataset or the dataset that was used to perform hierarchical vector quantization. The dataset should have same number of points as the dataset used to perform hierarchical vector quantization in the HVT function

* __`child.level`__	- A number indicating the level for which the heat map is to be plotted.

* __`hmap.cols`__	- The column number of column name from the dataset indicating the variables for which the heat map is to be plotted. To plot the quantization error as heatmap, pass `'quant_error'`. Similary to plot the no of points in each cell as heatmap, pass `'no_of_points'` as a parameter

* __`color.vec`__	- A color vector such that length(color.vec) = child.level (default = NULL)

* __`line.width`__ - A line width vector such that length(line.width) = child.level. (default = NULL)

* __`palette.color`__ - A number indicating the heat map color palette. 1 - rainbow, 2 - heat.colors, 3 - terrain.colors, 4 - topo.colors, 5 - cm.colors, 6 - BlCyGrYlRd (Blue,Cyan,Green,Yellow,Red) color. (default = 6)

* __`show.points`__ - A boolean indicating if the centroids should be plotted on the tesselations. (default = FALSE)


Now let's plot the quantization error for each cell at level one as heatmap.

```{r hmp level one quantization computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 3: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’computers’ dataset',eval = global_var}
hvtHmap(hvt.results, 
        trainComputers, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.2),
        color.vec = c("#141B41"),
        palette.color = 6,
        centroid.size = 3,
        show.points = T)
```

Now let's go one level deeper and perform hierarchical vector quantization.

```{r level two computers,warning=FALSE,message=FALSE,results="hide",eval = global_var}
set.seed(240)
hvt.results2 <- list()
# depth=2 is used for level2 in the hierarchy
hvt.results2 <- muHVT::HVT(trainComputers,
                           nclust = 15,
                           depth = 2,
                           quant.err = 0.2,
                           projection.scale = 10,
                           normalize = T)
```

Let's plot the voronoi tesselation for both the levels.

```{r plot level two computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 4: The Voronoi tessellation for level 2 shown for the 225 cells in the dataset ’computers’',eval = global_var}
# Voronoi tesselation plot for level two
plotHVT(hvt.results2, 
        line.width = c(1.2, 0.8), 
        color.vec = c("#141B41","#0582CA"))
```

In the table below, Segment Level signifies the depth.

Level 1 has 15 cells

Level 2 has 225 cells .i.e. each cell in level1 is divided into 225 cells

Let's analyze the summary table again for `Quant.Error` and see if any of the cells in the 2nd level have quantization error below quantization error threshold. In the table below, the values for `Quant.Error` of the cells which have hit the quantization error threshold are shown in red. Here we are showing just top 50 rows for the sake of brevity.

```{r summary level two computers,warning=FALSE,eval = global_var}
summaryTable(hvt.results2[[3]][['summary']],limit = 50)
```

The users can look at the compression summary to get a quick summary on the compression as it becomes quite cumbersome to look at the summary table above as we go deeper.

```{r compression summary level two computers,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.results2[[3]]$compression_summary)
```

As it can be seen in the table above, only `5%` cells in the 2nd level have quantization error below threshold. Therefore, we can go one more level deeper and try to compress the data further.

We will look at the heatmap for quantization error for level 2.

```{r hmp level two quantization computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 5: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’computers’ dataset',eval = global_var}
hvtHmap(hvt.results2, 
        trainComputers, 
        child.level = 2,
        hmap.cols = "quant_error", 
        line.width = c(0.8,0.2),
        color.vec = c("#141B41","#0582CA"),
        palette.color = 6,
        centroid.size = 2,
        show.points = T)
```

As the quantization error criteria is not met, let's do hierarchical vector quantization at level 3.

```{r level three computers,warning=FALSE,message=FALSE,results="hide",eval = global_var}
set.seed(240)
hvt.results3 <- list()
# depth=3 is used for level3 in the hierarchy
hvt.results3 <- muHVT::HVT(trainComputers,
                           nclust = 15,
                           depth = 3,
                           quant.err = 0.2,
                           projection.scale = 10,
                           normalize = T)
```

Let's plot the voronoi tesselation for all 3 levels.

```{r plot level three computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 6: The Voronoi tessellation for level 3 shown for the 1905 cells in the dataset ’computers’',eval = global_var}
# Voronoi tesselation plot for level three
plotHVT(hvt.results3,
        line.width = c(1.2,0.8,0.4),
        color.vec = c("#141B41","#0582CA","#8BA0B4"),
        centroid.size = 3)
```

Each of the 225 cells whose quantization is above threshold in level 2 will break down into 15 cells each in level 3. Hence, as it can be seen below, level 3 has 3375 rows. So it will have 3615 rows in total. We will only show first 500 rows here.

```{r summary level three computers,warning=FALSE,eval = global_var}
summaryTable(hvt.results3[[3]][['summary']],scroll = T,limit = 500)
```

Let's check the compression summary to check how many cells in each level have hit the quantization error threshold

```{r compression summary level three computers,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.results3[[3]]$compression_summary)
```


As it can be seen from compression summary table above that the quantization error for most of the cells in level 3 fall below quantization threshold. Hence we were succesfully able to compress `89%` of the data.

```{r hmp level three quantization computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 7: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’computers’ dataset',eval = global_var}
hvtHmap(hvt.results3, 
        trainComputers, 
        child.level = 3,
        hmap.cols = "quant_error", 
        line.width = c(1.2,0.8,0.4),
        color.vec = c("#141B41","#6369D1","#D8D2E1"),
        palette.color = 6,
        show.points = T,
        centroid.size = 1.1)
```

###  Heatmap

Now we will try to get more insights from the cells by overlaying heatmap for variable `price` at different levels.

Let's do it for level one

In the plot below, a heatmap for variable `price` is overlayed on level one tesselation plot.We calculate the mean price for each cell and represent it as heatmap. 

The heatmap for `price` variable for different cells at level 1 can be seen in the plot below.

```{r hmp level one computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 8: The Voronoi tessellation with the heat map overlaid for variable ’price’ at level 1 from ’computers’ dataset',eval = global_var}
hvtHmap(hvt.results, 
        trainComputers, 
        child.level = 1,
        hmap.cols = "price", 
        line.width = c(0.2),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```


Now we will go one level deeper and overlay heatmap for `price` at level 2. This should give us better insight about the price distribution for different cells.

In the plot below, we have overlayed heatmap for variable `price` on level 2. 

```{r hmp level two computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 9: The Voronoi tessellation with the heat map overlaid for the variable ’price’ at level 2 from the ’computer’ dataset',eval = global_var}
hvtHmap(hvt.results2, 
        trainComputers, 
        child.level = 2, 
        hmap.cols = "price",
        line.width = c(0.8,0.2),
        color.vec = c("#141B41","#0582CA"),
        palette.color = 6,
        show.points = T,
        centroid.size = 2)
```

Let us go one level deeper and overlay heatmap for `price` at level 3. 

In the plot below, we have overlayed heatmap for variable `price` on level 3. 

```{r hmp level three computers,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 10: The Voronoi tessellation with the heat map overlaid for the variable ’price’ at level 3 from the ’computer’ dataset',eval = global_var}
hvtHmap(hvt.results3, 
        trainComputers, 
        child.level = 3, 
        hmap.cols = "price",
        line.width = c(1.2,0.8,0.4),
        color.vec = c("#141B41","#6369D1","#D8D2E1"),
        palette.color = 6,
        show.points = T,
        centroid.size = 1.1)
```

Let's repeat the steps above for `speed` variable

The heatmap for `speed` variable for different cells at level 1 can be seen in the plot below.

```{r hmp level one computers speed,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 11: The Voronoi tessellation with the heat map overlaid for variable ’speed’ at level 1 from ’computers’ dataset',eval = global_var}
hvtHmap(hvt.results, 
        trainComputers, 
        child.level = 1,
        hmap.cols = "speed", 
        line.width = c(0.2),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```


Now we will go one level deeper and overlay heatmap for `speed` at level 2

```{r hmp level two computers speed,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 12: The Voronoi tessellation with the heat map overlaid for the variable ’speed’ at level 2 from the ’computer’ dataset',eval = global_var}
hvtHmap(hvt.results2, 
        trainComputers, 
        child.level = 2, 
        hmap.cols = "speed",
        line.width = c(0.8,0.2),
        color.vec = c("#141B41","#0582CA"),
        palette.color = 6,
        show.points = T,
        centroid.size = 2)
```

Let us go one level deeper and overlay heatmap for `speed` at level 3. 

In the plot below, we have overlayed heatmap for variable `speed` on level 3. 

```{r hmp level three computers speed,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 13: The Voronoi tessellation with the heat map overlaid for the variable ’speed’ at level 3 from the ’computer’ dataset',eval = global_var}
hvtHmap(hvt.results3, 
        trainComputers, 
        child.level = 3, 
        hmap.cols = "speed",
        line.width = c(1.2,0.8,0.4),
        color.vec = c("#141B41","#6369D1","#D8D2E1"),
        palette.color = 6,
        show.points = T,
        centroid.size = 1.1)
```


### Predict

Now once we have built the model, let us try to predict using our test dataset which cell and which level each point belongs to.

Let us see predictHVT function. 

```{r predictHVT function,echo = TRUE, eval= FALSE}
predictHVT(data,hvt.results,hmap.cols = NULL,child.level = 1,...)
```

Here I will explain the important parameters for the function `predictHVT`

* __`data`__ - A dataframe containing test dataset. The dataframe should have atleast one variable used while training. The variables from this dataset can also be used to overlay as heatmap.

* __`hvt.results`__ - A list of hvt.results obtained from HVT function while performing hierarchical vector quantization on train data

* __`hmap.cols`__ - The column number of column name from the dataset indicating the variables for which the heat map is to be plotted.(Default = NULL). A heatmap won't be plotted if NULL is passed

* __`child.level`__ -A number indicating the level for which the heat map is to be plotted.(Only used if hmap.cols is not NULL)

* __`...`__ - color.vec and line.width can be passed from here

```{r predictHVT hmap computers,warning=FALSE,message=FALSE,eval = global_var}
set.seed(240)
predictions <- muHVT::predictHVT(testComputers,
                                 hvt.results3,
                                 hmap.cols = NULL,
                                 child.level = 3)
```


#### Prediction Algorithm

The prediction algorithm recursively calculates the distance between each point in the test dataset and the cell centroids for each level. The following steps explain the prediction method for a single point in test dataset :- 

1. Calculate the distance between the point and the centroid of all the cells in the first level.
2. Find the cell whose centroid has minimum distance to the point.
3. Check if the cell drills down further to form more cells.
4. If it doesn't, return the path. Or else repeat the steps 1 to 4 till we reach to the level at which the cell doesn't drill down further.

Let's see what cell and which level do each point belongs to. For the sake of brevity, we will 

```{r predictHVT pred computers,warning=FALSE,eval = global_var}
Table(predictions$predictions,scroll = T,limit = 10)
```


We can see the predictions for some of the points in the table above. The variable `cell_path` shows us the level and the cell that each point is mapped to. The centroid of the cell that the point is mapped to is the codeword (predictor) for that cell. 

The prediction algorithm will work even if some of the variables used to perform quantization are missing. Let's try it out. In the test dataset, we will remove screen and ads.

```{r predictHVT2 computers,warning=FALSE,message=FALSE,eval=global_var}
set.seed(240)
testComputers <- testComputers %>% dplyr::select(-c(screen,ads))
predictions <- muHVT::predictHVT(testComputers,
                                 hvt.results3,
                                 hmap.cols = NULL,
                                 child.level = 3)
Table(predictions$predictions,scroll = T,limit = 10)
```



### Example Usage 2

In this section, we will see how we can use the package to visualize mutlidimensional data by projecting them to two dimensions using Sammon's projection.

#### Torus (Donut)

First of all, let us see how to generate data for torus. We are using a library `geozoo` for this purpose. Geo Zoo stands for Geometric Zoo. It is a compilation of geometric objects ranging from three dimensions all the way to the 10 dimension. Geo Zoo contains regular or well-known object, eg cube and sphere, and some abstract objects, e.g. Boy's surface, Torus and Hyper-Torus. 

Here we will generate a 3D torus with 1000 points.

```{r torus generate,warning=FALSE,message=FALSE,results="hide",eval = global_var}
library(geozoo)
library(plotly)

set.seed(240)
# Here p reprensents dimension of object
# n reperesents number of points
torus <- geozoo::torus(p = 3,n = 1000)
torus_df <- data.frame(torus$points)
colnames(torus_df) <- c("x","y","z")
```

Now let's do some EDA on the data. First of all, we will see how the data looks like

```{r torus head, warning=FALSE, eval = global_var}
Table(head(torus_df))
```

Now let's have a look at summary and structure of the data.

```{r torus structure, warning=FALSE, eval = global_var}
str(torus_df)
```

```{r torus summary, warning=FALSE,eval = global_var}
summary(torus_df)
```


Now let's try to visualize the object in 3D Space.

```{r torus plot,warning=FALSE,message=FALSE,fig.show="hold",fig.cap='Figure 14: 3D Torus',eval = global_var}
#plot_torus <- plotly::plot_ly(torus_df, x= ~x, y= ~y, z = ~z, color = ~z) %>% add_markers()
#plot_torus
knitr::include_graphics('torus.png')
```


Now let's try to use the package and project the above 3D geographic object in 2D Space. We will start with number of cells as 100.

```{r torus hvt first,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 15: The Voronoi tessellation for level 1 shown for the 100 cells in the dataset ’torus’',eval = global_var}
set.seed(240)
hvt.torus <- muHVT::HVT(torus_df,
                        nclust = 100,
                        depth = 1,
                        quant.err = 0.1,
                        projection.scale = 10,
                        normalize = T)

plotHVT(hvt.torus,line.width = c(0.8),color.vec = c("#141B41"),centroid.size = 1)
```

Let's checkout the compression summary for torus

```{r compression summary torus first,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.torus[[3]]$compression_summary)
```

As it can be seen in the table above, none of the 100 cells hit the quantization threshold error.

Let's overlay the heatmap for quantization error for level 1.

```{r hmp level one quantization torus,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 16: The Voronoi tessellation for level 1 with the heat map overlaid for variable ’quant_error’ in the ’torus’ dataset',eval = global_var}
hvtHmap(hvt.torus, 
        torus_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```

Now let's double the number of cells to 200 and try again.

```{r torus hvt second,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 17: The Voronoi tessellation for level 1 shown for the 200 cells in the dataset ’torus’',eval = global_var}
set.seed(240)
hvt.torus2 <- muHVT::HVT(torus_df,
                         nclust = 200,
                         depth = 1,
                         quant.err = 0.1,
                         projection.scale = 10,
                         normalize = T)
plotHVT(hvt.torus2,line.width = c(0.8),color.vec=c("#141B41"),centroid.size = 1)
```

Let's checkout the compression summary for torus.

```{r compression summary torus second,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.torus2[[3]]$compression_summary)
```

It can be observed from the table above that only 24 cells out of 200 i.e. `12%` of the cells hit the quantization threshold error.

Let's check it visually by overlaying the heatmap for quantization error at level2.

```{r hmp level two quantization torus,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 18: The Voronoi tessellation for level 2 with the heat map overlaid for variable ’quant_error’ in the ’torus’ dataset',eval = global_var}
hvtHmap(hvt.torus2, 
        torus_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        centroid.size = 3,
        show.points = T)
```

Let's increase the number of cells to 500.

```{r torus hvt third,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 19: The Voronoi tessellation for level 1 shown for the 500 cells in the dataset ’torus’',eval = global_var}
set.seed(240)
hvt.torus3 <- muHVT::HVT(torus_df,
                         nclust = 500,
                         depth = 1,
                         quant.err = 0.1,
                         projection.scale = 10,
                         normalize = T)

plotHVT(hvt.torus3,line.width = c(0.8),color.vec = c("#141B41"),centroid.size = 1)
```


Let's checkout the compression summary for torus

```{r compression summary torus third,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.torus3[[3]]$compression_summary)
```

By increasing the number of cells to 500, we were successfully able to compress `73%` of the data.

Let's checkout the heatmap for quantization error.

```{r hmp level three quantization torus,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 20: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’torus’ dataset',eval = global_var}
hvtHmap(hvt.torus3, 
        torus_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```

Let's use our hierarchical vector quantization technique and go one level deeper. We will keep the number of cells as 20.

```{r torus hvt forth,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 21: The Voronoi tessellation for level 2 shown for the 400 cells in the dataset ’torus’',eval = global_var}
set.seed(240)
hvt.torus4 <- muHVT::HVT(torus_df,
                         nclust = 20,
                         depth = 2,
                         quant.err = 0.1,
                         projection.scale = 10,
                         normalize = T)

plotHVT(hvt.torus4,line.width = c(0.8,0.3),color.vec = c("#141B41","#0582CA"),centroid.size = 2)
```

Let's checkout the compression summary for torus

```{r compression summary torus forth,warning=FALSE,eval = global_var}
compressionSummaryTable(hvt.torus4[[3]]$compression_summary)
```

We can observe from the above table that we were able to compress `58%` of the data using hierarchical vector quantization

Here also we will observe the quantization error heatmap

```{r hmp level forth quantization torus,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 22: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’torus’ dataset',eval = global_var}
hvtHmap(hvt.torus4, 
        torus_df, 
        child.level = 2,
        hmap.cols = "quant_error", 
        line.width = c(0.8,0.4),
        color.vec = c("#141B41","#6369D1"),
        palette.color = 6,
        show.points = T,
        centroid.size = 2)
```

The similar process can be followed for sphere. The code for the same can be found in the Appendix below.

## Applications 

1. Pricing Segmentation - The package can be used to discover groups of similar customers based on the customer spend pattern and understand price sensitivity of customers. 

2. Market Segmentation - The package can be helpful in market segmentation where we have to identify micro and macro segments. The method used in this package can do both kinds of segmentation in one go.

3. Anomaly detection - This method can help us categorize system behaviour over time and help us find anomaly when there are changes in the system. For e.g. Finding fraudulent claims in healthcare insurance.

4. The package can help us understand the underlying structure of the data. Suppose we want to analyze a curved surface such as sphere or vase, we can approximate it by a lot of small low-order polygons in the form of tesselations using this package.

5. In biology, Voronoi diagrams are used to model a number of different biological structures, including cells and bone microarchitecture.

## References

1. Vector Quantization : https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-450-principles-of-digital-communications-i-fall-2006/lecture-notes/book_3.pdf

2. K-means : https://en.wikipedia.org/wiki/K-means_clustering

3. Sammon’s Projection : http://en.wikipedia.org/wiki/Sammon_mapping

4. Voronoi Tessellations : http://en.wikipedia.org/wiki/Centroidal_Voronoi_tessellation

## Appendix

The code for constructing voronoi tesselations for 3D sphere can be found here.

#### Sphere

Here also, we will generate 1000 points in 3D space to form a sphere.

```{r sphere generate,warning=FALSE,message=FALSE,results="hide",eval = F}
library(geozoo)
library(plotly)

set.seed(240)
sphere <- geozoo::sphere.hollow(p = 3, n = 1000)
sphere_df <- data.frame(sphere$points)
colnames(sphere_df) <- c("x","y","z")
```

Let's get a quick-peek of the data

```{r sphere head, warning=FALSE, eval = F}
Table(head(sphere_df))
```

Now let's have a look at summary and structure of the data.

```{r sphere structure, warning=FALSE, eval = F}
str(sphere_df)
```

```{r sphere summary, warning=FALSE,eval = F}
summary(sphere_df)
```


Now let's try to visualize the object in 3D Space.

```{r sphere plot,warning=FALSE,message=FALSE,results="asis",fig.cap='Figure 26: 3D hollow sphere',eval = F}
plot_sphere <- plotly::plot_ly(sphere_df, x= ~x, y= ~y, z = ~z, color = ~z) %>% add_markers()
plot_sphere
```


Now let's try to use the package and project the above 3D geographic object in 2D Space. Afain, we will start will number of cells as 100.


```{r sphere hvt first,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 27: The Voronoi tessellation for level 1 shown for the 100 cells in the dataset ’sphere’',eval = F}
set.seed(240)
hvt.sphere <- muHVT::HVT(sphere_df,
                         nclust = 100,
                         depth = 1,
                         quant.err = 0.1,
                         projection.scale = 10,
                         normalize = T)

plotHVT(hvt.sphere,line.width = c(0.8),color.vec = c("#141B41"),centroid.size = 1)
```

Let's checkout the compression summary for sphere

```{r compression summary sphere first,warning=FALSE,eval = F}
compressionSummaryTable(hvt.sphere[[3]]$compression_summary)
```

It can be inferred from the table above that none of the cells hit the quantization error threshold. 

Let's overlay the heatmap for quantization error for level 1.

```{r hmp level one quantization sphere,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 28: The Voronoi tessellation for level 1 with the heat map overlaid for variable ’quant_error’ in the ’sphere’ dataset',eval = F}
hvtHmap(hvt.sphere, 
        sphere_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```


Let us try again by increasing the number of cells to 200.

```{r sphere hvt second,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 29: The Voronoi tessellation for level 1 shown for the 200 cells in the dataset ’sphere’',eval = F}
set.seed(240)
hvt.sphere2 <- muHVT::HVT(sphere_df,
                          nclust = 200,
                          depth = 1,
                          quant.err = 0.1,
                          projection.scale = 10,
                          normalize = T)

plotHVT(hvt.sphere2,line.width = c(0.8),color.vec = c("#141B41"),centroid.size = 1)
```

Let's checkout the compression summary for sphere

```{r compression summary sphere two,warning=FALSE,eval = F}
compressionSummaryTable(hvt.sphere2[[3]]$compression_summary)
```

The table above shows that `9%` cells were able to hit the quantization error threshold.

Let's check the heatmap for quantization error 

```{r hmp level two quantization sphere,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 30: The Voronoi tessellation for level 1 with the heat map overlaid for variable ’quant_error’ in the ’sphere’ dataset',eval = F}
hvtHmap(hvt.sphere2, 
        sphere_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        centroid.size = 3,
        show.points = T)
```


Now let's increase the number of cells to 500.

```{r sphere hvt third,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 31: The Voronoi tessellation for level 1 shown for the 500 cells in the dataset ’sphere’',eval = F}
set.seed(240)
hvt.sphere3 <- muHVT::HVT(sphere_df,
                          nclust = 500,
                          depth = 1,
                          quant.err = 0.1,
                          projection.scale = 10,
                          normalize = T)

plotHVT(hvt.sphere3,line.width = c(0.8),color.vec = c("#141B41"),centroid.size = 1)
```

Let's checkout the compression summary for sphere

```{r compression summary sphere three,warning=FALSE,eval = F}
compressionSummaryTable(hvt.sphere3[[3]]$compression_summary)
```


As per the table above, we were able to compress `78%` of the data. 

Let's plot the heatmap for quantization error

```{r hmp level three quantization sphere,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 32: The Voronoi tessellation with the heat map overlaid for variable ’quant_error’ in the ’sphere’ dataset',eval = F}
hvtHmap(hvt.sphere3, 
        sphere_df, 
        child.level = 1,
        hmap.cols = "quant_error", 
        line.width = c(0.8),
        color.vec = c("#141B41"),
        palette.color = 6,
        show.points = T,
        centroid.size = 3)
```

We can do better here also

Let's use our hierarchical vector quantization technique and go one level deeper. We will keep the number of cells as 24.

```{r sphere hvt forth,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 33: The Voronoi tessellation for level 2 shown for the 576 cells in the dataset ’torus’',eval = F}
set.seed(240)
hvt.sphere4 <- muHVT::HVT(sphere_df,
                          nclust = 24,
                          depth = 2,
                          quant.err = 0.1,
                          projection.scale = 10,
                          normalize = T)

plotHVT(hvt.sphere4,line.width = c(0.8,0.3),color.vec = c("#141B41","#0582CA"),centroid.size = 2)
```

Let's checkout the compression summary for torus

```{r compression summary sphere forth,warning=FALSE,eval = F}
compressionSummaryTable(hvt.sphere4[[3]]$compression_summary)
```

In this case also, `87%` of the cells hit the quantization threshold error.

We will overlay the heatmap for quantization error.

```{r hmp level forth quantization sphere,warning=FALSE,fig.show='hold',results='hide',message=FALSE,fig.cap='Figure 34: The Voronoi tessellation for level 2 with the heat map overlaid for variable ’quant_error’ in the ’sphere’ dataset',eval = F}
hvtHmap(hvt.sphere4, 
        sphere_df, 
        child.level = 2,
        hmap.cols = "quant_error",
        color.vec = c("#141B41","#6369D1"),
        line.width = c(0.8,0.4),
        palette.color = 6,
        show.points = T,
        centroid.size = 2)
```
