---
title: "Vector Binary Tree: Manage Your Data Through Column Names"
author: "Chen ZHANG"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{intro}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## VBTree is designed for what

VBTree, short for vector binary tree, is a data structure designed to deal with the data with very structurized column names. It is not uncommon that summary tables are made by different structurized column names. In my case, I met a data collected from series experiments with 2 different data type, 7 temperature conditions, 4 different strain rate conditions and 1 deformation rate, that means there must be $2*7*4*1=56$ columns in its summary table. I have extracted the first 50 rows and save them into 'datatest'. Let's have a look what does it look like:

```{r}
library(VBTree)
dim(datatest)
head(datatest[,1:3])
colnames(datatest)
```

Sometimes I need to extract the data with fixed temperature conditions while in some other circumstances, I have to export data with fixed strain rate. While how to implement that without making defination for repeat times for the code ```for``` or ```while```? The main idea is to locate all the column names into an array or tensor with the dimension of $2*7*4*1$ through which the methods of array or tensor will be applicable. As there is regularly repeat in the names with different combination orders, it is naturally to come out the idea that make all factors in their names be splited firstly, then put them into some proper data structures which can make correct mapping between a character vector and an array, or a tensor. There for these mediate data structures, called double list and vector binary tree, are designed. Here are what them look like:

```{r}
# Save character vector into chrvec:
chrvec <- colnames(datatest)
unregdl <- chrvec2dl(chrvec) # unregularized double list
print(unregdl) # The pure numeric layers (layer2) are not sorted since all elements are treated as character
vbt <- dl2vbt(unregdl)
print(vbt) # elements in layer 2 were sorted
```

Through which column names are splited into four layers in double list and vector binary tree. The levels for each layers are 2, 7, 4 and 1 respectively. Using these data structure, we can readily convert the whole names into tensor or array from double list or vector binary tree. The demonstration:

```{r}
ts <- dl2ts(unregdl) # Convert from double list to tensor
print(ts)
arr <- vbt2arr(vbt) # Convert from vector binary tree to array
print(arr)
```

## Batch data processing through array or tensor

Because the regularized double list, vector binary tree and tensor (array) possess unique mapping relationships, a regularized double list is necessary for correct index setting:

```{r}
regdl <- vbt2dl(vbt)
print(regdl)
```

It can be seen that temperatures were save in layer 2 with 7 levels while strain rates were save in layer 3 with 4 levels. Array's methods are available now. For example, if we want to 'Stress' data (1st layer1, 2nd level) and make traversal in all temperature conditions with fixed 0.01 strain rate (3rd layer, 2nd level), execute the folloing code:

```{r}
subset1 <- datatest[, arr[2,,2,1]]
head(subset1)
```

If we want to automatically plot the Stress-Strain plot with fixed temperature (1050 for example, in 2nd layer, 4th level), traverse all strain rate conditions, try the following code:

```{r, fig.show='hold'}
xbatch <- arr[1,4,,1]
ybatch <- arr[2,4,,1]
regdl <- arr2dl(arr)

rpt <- length(xbatch)
i <- 1
for (i in 1:rpt) {
  plt <- plot(datatest[,xbatch[i]], datatest[,ybatch[i]], xlab="Strain", ylab="Stress", main=paste("in T=1050, SR=",regdl[[3]][i], sep = ""))
  plt
}
```

The methods through tensor are the same as that of array.

## Advanced batch data processing thorugh vector binary tree

If we need highly customized condition select, for example I need make traversal in the temperature range from 1000 to 1150, with 0.01 and 1 two strain rate conditions, to make the Stress-Strain plot, the vector binary tree will make sense. It supports the visit through a handmade double list which can be highly customized. Firstly let us have a look at the appearance of the full vector binary tree:

```{r}
print(vbt)
```

Well, the desired elements locate from 3rd to 7th in layer 2, the 2nd and 4th in layer 3. We can made two double list to specify and extract the desired Stress and Strain subsets. The demonstration is:

```{r}
subStrain_dl <- list(1, c(3:7), c(2,4), 1)
subStress_dl <- list(2, c(3:7), c(2,4), 1)
# make visiting from original vector binary
# tree and save them as new doube lists:
subStrain_dl2 <- advbtinq(vbt, subStrain_dl) 
subStress_dl2 <- advbtinq(vbt, subStress_dl)
print(subStrain_dl2)
print(subStress_dl2)
xbatch2 <- as.vector(dl2arr(subStrain_dl2))
ybatch2 <- as.vector(dl2arr(subStress_dl2))
print(xbatch2)
print(ybatch2)
```

Their respective order matched perfectly. The next step is similar as what we done in previous section:

```{r, fig.show='hold'}
rpt <- length(xbatch2)
i <- 1
for (i in 1:rpt) {
  plt <- plot(datatest[, xbatch2[i]], datatest[, ybatch2[i]], xlab="Strain", ylab="Stress", main=ybatch2[i])
  plt
}

```

## Advantage of VBTree

It is commonly said that R performs relative low speed compared to other popular programming languages, espcially in the situations of frequent data operations such as melt and reshape. In my opinion, an efficient logic for data management is more important rather than some amazing skills in data treatment. Although all the demos I showed from beginning to end never do any melt, bind or reshape operations on original data, but data batch processing is still can be implemented.

Lets check all object sizes we used:

```{r}
# For original data:
object.size(datatest)
# For tensor and array:
object.size(ts)
object.size(arr)
# For vector binary tree:
object.size(vbt)
# For double list:
object.size(regdl)
```

I packaged the ```datatest``` in VBTree only used first 50 rows only for demonstration. In fact, it has the scales far more than 50 rows. All these data can be structurized managed throguh VBTree, using a only 1408 bytes object minimally.
