---
title: "TPMplt package introduction"
author: "ZHANG Chen"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{TPMplt Package Introduction}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

## Main functions

TPMplt is a tool-kit for building and visualizing the dynmaic materials model (DMM), suggested by [Prasad and Gegel](https://link.springer.com/article/10.1007/BF02664902). It provides an easy approach to calculate constructive functions and other related material constants based on a given strain condiiton. 2D and 3D processing-maps with temperature as its x axis, while logarithm strain rate as its y axis are also available.

## Input data

Valid data for TPMplt strictly obey the management logic in [VBTree package](https://CRAN.R-project.org/package=VBTree). Additionally, factors for temperature (celsius) and strain rates should be written in the format of pure numeric. All different variables are desired to be connected using "-" symbol. For example, if there's a strain data collected in the conditions of 900 celsius, $10^{-3}$ strain rate, "0.001-Strain-900" is one of available column names for this data, rather than "10e-3_Strain_T900C", "SR0.001-Strain-1173K" or such like. If your data contains some unnecessary patterns, a certain degree of data cleaning for column names is required.

The following codes partially display a typical valid data for TPMplt:

```{r}
library(TPMplt)
head(TPMdata[,1:3])

```

Users can apply any applicable tools to make the summary table for TPMplt, with the format as above-showed.

Besides, it is common to obtain multiple exported files based on different experiments. TPMplt affords two functions to automatically generate a summary table from multiple exported files. For details, please check the R documents for ```API4TMZ``` and ```TMZdatainput```.

## Conceptual knowledge about VBTree data frame

It is necessary to build the conceptions for layers and levels in layer for variables, defined by [VBTree package](https://CRAN.R-project.org/package=VBTree). For example, run the following codes to check all column names in the demo dataset in TPMplt pacakge:

```{r}
colnames(TPMdata)
```

As we seen, all column names are arranged by the style of "(Strain&Stress)-(Temperature)-(Strain Rate)-(Other)". Under this circumstance, we call the layer for temperature is 2, while the layer for strain rate is 3.

The function ```epsExtract``` is capable to export a strain rate-temperature table by specifying ```eps``` as the strain condition. However, ```lyT``` and ```lySR```, the two necessary arguments corresponding to layers for temperature and strain rate respectively, require correct declaration as well.

Executinge the following codes:

```{r}
require(VBTree)
dl2vbt(chrvec2dl(colnames(TPMdata)))
```

The complete structure for all variables is showed. As the result showed above, there're 7 temperatures and 4 strain rates in our summary table, therefore the numbers of level for temperature and strain rate are 7 and 4 respectively. Based on all introduced knowledge, we can easily find that all factors will be corresponded with a unique identity with the format as (layer, level). For example, we can define the factor "950" is located in layer 2, level 2.

## Auto plots for stress-strain curves

```SSplots``` is automatic completion for stress-strain curve plots, using [VBTree package](https://CRAN.R-project.org/package=VBTree) group strategy. The argument ```grpby``` determines the group methods for plots. As an instance, stress-strain curves grouped by strain rates, separated by temperature condition in each individual plot is very common. Since the layer for strain rate is 3, we can simply set the argument ```grpby``` as 3 then run the code ```SSplots(TPMdata, 3, mfrow=c(3, 3))``` to obtain the following plots (7 figures, therefore it is reasonable to use a 3*3 division to display):

<img src="img/Img1.png" width="660">

Grouped by temperature is also available, by running ```SSplots(TPMdata, 2, mfrow=c(2, 2))```, four figures will be exported as:

<img src="img/Img2.png" width="660">

But pay attention, multiple plots export using ```graphics``` is very sensitive to the Plots pane's area. Before plotting, please zoom in this pane large enough to obtain correct export.

## Applying multi-function linear fitting

Generally, curves of flow stress as function of flow strain will be of high vibration, therefore the fitting process for all data is necessary. However, in most circumstances, raw stress-strain curves always present too complicated appreance to be fitted by a single linear model. The function ```AllPF()``` in this package is designed to solve this problem. From the aforementioned raw stress-strain curves generated by ```SSplots(TPMdata, 2, mfrow=c(2, 2))```, it is not difficult to find for most curves, from start to where the strain is 0.015, elastic deformation occur; for the strain ranged from 0.015 to 0.2, the linear relationship collapses, tested samples are in yield region; in the region for the strain is above 0.2, there is mainly plastic deformation. Empirically, it is reasonable to set 3 subsections and utilizing polynomial fitting one by one, by setting the argument ```subsec``` as ```c(0.015, 0.2)```:

```{r, fig.show='hide'}
Fitted_data <- AllPF(TPMdata, subsec = c(0.015, 0.2))
SSplots(Fitted_data, 2, mfrow=c(2, 2))
```

<img src="img/Img3.png" width="660">

Compared to the raw curves, we can find the fitted curves keep the most appearance with no vibrations or noises. You can see the documents for ```basicPF()``` and ```AllPF()```, try out an most optimized combination of arguments (specially for the argument ```subsec```) for your own experimental data.

## Temperature correction

After the receivable arguments for fitting are obtained, we can use the function ```TCorrect()``` to output the temperature-corrected data by adding some necessary material contants. Take the conventional steel as the example, the heat capacity constant and material density are 510.7896 and 8050 in SI base. Set the argument ```subsec()``` as ```c(0.015, 0.2)``` and the power efficiency ```CorrCons``` as 0.9:

The 2nd and 3rd argument in ```TCorrect()``` are integers to specify the layer for strain rates and temperatures.

```{r, fig.show='hide'}
TCorrect_data <- TCorrect(TPMdata, 3, 2, 510.7896, 8050, CorrCons = 0.9, subsec=c(0.015, 0.2))
SSplots(TCorrect_data, 2, mfrow=c(2, 2))
```

<img src="img/Img4.png" width="660">

After temperature correction, it is noted that flow stress increase significantly in low temperature, high strain rate. This result is experientially corresponding to our common sense that working hardening effect will be even obvious, in the condition of low temperature or high strain rate.

## Extraction based on given strain

Based on previous introduction, it is not difficult to find the layer 2 is for temperature while the layer 3 is for strain rate in ```TPMdata```. Therefore the two arguments, ```lyT``` and ```lySR``` will be set as 2 and 3 respectively. If we want the strain rate-temperature table in condition of 0.7 strain, by running the following codes the result will be returned automatically:

```{r}
epstable <- epsExtract(TCorrect_data, eps = 0.7, lyT = 2, lySR = 3)
epstable
```

Pay attention, for correct exporting, the number of levels for Strain and Stress must be 2 in our input data.

Additionally, although the function ```epsExtract``` can automatically read the layer and levels in this layer for Strain and Stress using some specific regexs in most conditions, it is not guaranteed to be matched correctly everytime. If mismatch occurs, please manually set the argument ```manual``` in ```epsExtract``` according to its R document.

## Automatic calculation

On the basis of dynamic materials modeling (DMM), constructive function and all material constants can be calculated from a certain strain rate-temperature table. The function ```DMMprocess``` includes all steps for DMM processing. Applying it on our previous result (strain rate-temperature table by specific value of strain), the complete output can be observed as following:

```{r}
DMM <- DMMprocess(epstable)
DMM
```

If the constructive function is the only thing we concerned about, set the argument ```ConsFunc``` in ```DMMprocess``` as TRUE:

```{r}
DMM <- DMMprocess(epstable, ConsFunc = TRUE)
```

Additionally, if we set the argument ```InteractMode``` as TRUE, all computation process and corresponding fitting figures can be output step by step. There shows some results in following figures:

<img src="img/Img5.png" width="460">

<img src="img/Img6.png" width="460">

<img src="img/Img7.png" width="460">

<img src="img/Img8.png" width="460">

<img src="img/Img9.png" width="460">

<img src="img/Img10.png" width="460">

<img src="img/Img11.png" width="460">

All workflow control will be prompted in the console, something like:

<img src="img/Img12.png" width="560">


## Preparation for visualization

As we can see, the "etatable" and "xitable" in tablelist are two key parts for building processing-map. The former is for power dissipation efficiency factor eta, and the later is for rheological stability coefficient xi. However, since the values in both are discrete, regression process for these tables is necessary.

Support vector regression ([SVR](https://link.springer.com/article/10.1023/B:STCO.0000035301.49549.88)) is recommanded. The function ```SVRModel``` will return a regression result which can be utilized by ploting functions.

The following demonstration save the returned result into the vairable "PLTbd", for the meaning of "Plots builder".

```{r}
PLTbd <- SVRModel(DMM)
```

## 2D processing map visualization

Function ```TPM2dplt``` can generate a thermal processing map from regression result easily. Following codes demonstrates the processing map from "PLTbd" with default settings:

```{r, fig.show='hold', fig.height=4, fig.width=6}
TPM2dplt(PLTbd)
```

From the plot we can find that power dissipation efficiency factor eta is denoted by contour with gradient blue, while the rheological stability coefficient xi is represented by a gradient colours from green (high) to red (low). Annotation in top-left show the strain condition for current processing map.

Locations for annotation, gradient colors for rheological stability coefficient xi is customizable in ```TPM2dplt``` function. But since the color for eta is fixed, please try not to use blue or such like, to avoid obtaining an ambiguous result.

## 3D processing map visualization

Function ```TPM3dplt``` can build a thermal processing results as similar as ```TPM2dplt``` did. The difference is, eta and xi will be separately plotted.

By running the following code, we can easily obtain the results as shown in the next figure.

```{r}
TPM3dplt(PLTbd)
```

<img src="img/Img13.png" width="660">

These two 3d surfaces are generated through the rgl package, therefore it will be very convenient to utilize 3d rotation on our plots for further analysis in details.

Especially, the xi plots is coupled with a specific plane, z=0, in order to make divisions for the stable and unstable regions (doesn't included in demo fig). If the prediction for xi contained certain negative values, this plan will be visible in 3d surface plot.
