---
title: "Overview of ggDoE"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Overview of ggDoE}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 4
)
```

The *ggDoE* package provides an easy approach to creating commonly used graphs in Design of Experiments with the R package *ggplot2*. The following plots are currently available in *ggDoE*:

1. Alias Matrix 
2. Box-Cox Transformation
3. Lambda Plot
4. Boxplots
5. Regression Diagnostic Plots
6. Half-Normal Plot
7. Interaction Effects Plot for a Factorial Design
8. Main Effects Plot for a Factorial Design
9. Contour Plots for Response Surface Methodology
10. Pareto Plot
11. Two Dimensional Projections of a Latin Hypercube Design


The following datasets/designs are included in *ggDoE* as tibbles:

- **adapted_epitaxial**: Adapted epitaxial layer experiment obtain from the book <br>
*"Experiments: Planning, Analysis, and Optimization, 2nd Edition"* 

```{r}
ggDoE::adapted_epitaxial
```



- **original_epitaxial**: Original epitaxial layer experiment obtain from the book <br>
*"Experiments: Planning, Analysis, and Optimization, 2nd Edition"* 


```{r}
ggDoE::original_epitaxial
```



- **aliased_design**: D-efficient minimal aliasing design obtained from the article  <br>
*"Efficient Designs With Minimal Aliasing"*

```{r}
ggDoE::aliased_design
```


```{r}
library(ggDoE)
```


## Alias Matrix

Let $X_1$ denote the model matrix for the main-effects model (including the intercept) and let $X_2$ denote the model matrix corresponding to the two-factor interactions. 

Suppose the true model is 
$$
Y = X_1 \beta_1 + X_2 \beta_2 + \epsilon
$$
where $\epsilon$ is the vector of residuals with $\mathbb{E}(\epsilon)=0$, 
$\beta_1$ is the vector consisting of the intercept and main effects coefficients and $\beta_2$ is the vector consisting of the two-factor interactions effects coefficients. 

If the experimenter employs the main effects model for estimation, it is well known that the expected value of the least squares estimator
$\hat{\beta}_1$ of $\beta_1$ is 

$$
\mathbb{E}(\hat{\beta}_1) = \beta_1 + A \beta_2
$$
where $A$ is the *alias matrix*.

We define the *alias matrix* $A$ by
$$
A = (X_1^T \, X_1)^{-1} \  X_1^T X_2
$$

One can view the color map of the absolute value of the correlations among the main effects and two-factor interaction columns using the function `alias_matrix()`

```{r}
alias_matrix(design=aliased_design)
```

For *most* functions in *ggDoE* one can choose to not display the plot and only return the data/calculations used to construct the plot by using `showplot=FALSE` argument. For example, we can simply return the correlation matrix *(not absolute)* among the main effects and two-factor interactions as follows


```{r}
alias_matrix(design=aliased_design, showplot=FALSE)
```





## Box-Cox Transformation


Box-Cox transformation is a transformation of a response variable that often is not normally distributed, to one that does follow approximately a normal distribution.
The transformation performed is as follows


$$
y(\lambda) = 
\begin{cases}
\frac{y^\lambda -1}{\lambda}, & \text{if} \, \lambda \neq 0 \\
\log y, & \text{if} \, \lambda =0
\end{cases}
$$

The "optimal value" of $\lambda$ is one which results in the best approximation of 
a normal distribution curve.

Some common Box-Cox transformations are



| $\lambda$  | $y(\lambda)$ |
|------ |------|
| -2  | $\frac{1}{y^2}$  |
|   -1| $\frac{1}{y}$  |
| -$\frac{1}{2}$ | $\frac{1}{\sqrt{y}}$ |
| 0 | $\log y$ |
| $\frac{1}{2}$ | $\sqrt{y}$ |
|1  | $y$ |
| 2 |  $y^2$|


```{r}
model <- lm(s2 ~ (A+B+C+D),data = adapted_epitaxial)
boxcox_transform(model,lambda = seq(-5,5,0.2))
```


From the above figure, the "optimal value" of $\lambda=0.253$. A good transformation to perform would then be $\log(y)$. The results can be extracted by using `showplot=FALSE` argument, if needed.

```{r}
boxcox_transform(model,lambda = seq(-5,5,0.2),
                 showplot = FALSE)
```

The transformation doesn’t always work well, so make sure to check
the diagnostics of the model with the transformed response. See `diagnostic_plots()`.


## Lambda Plot

Obtain the trace plot of the *t*-statistics calculated for each effect in the model after applying Box-Cox transformation across a specified sequence of lambda values 

```{r}
model <-  lm(s2 ~ (A+B+C)^2,data=original_epitaxial)
lambda_plot(model)
```

or alternatively,


```{r}
lambda_plot(model, showplot=FALSE)
```



## Boxplots

Using `gg_boxplots()` constructs boxplots making it easy to visually compare the shape, the central tendency, and the variability of the samples. It is important to note the `response` and `factor` arguments
for `gg_boxplots()` must be unquoted. 

```{r}
data <- ToothGrowth
data$dose <- factor(data$dose,levels = c(0.5, 1, 2),
                    labels = c("D0.5", "D1", "D2"))
```


```{r}
head(data)
```


```{r}
gg_boxplots(data,response = 'len',
            factor = 'dose')
```

We can group each sample using the `group_var` argument, again this argument must be unquoted. With `color_palette` we can change the color palette for each of the boxplots.  With `color_palette` eight options are available: *"viridis","cividis","magma","inferno","plasma","rocket","mako","turbo"*. Lastly,
one can overlay jittered points to each boxplot using `jitter_points=TRUE`.

```{r,fig.height=5,fig.width=7}
gg_boxplots(data,response = 'len',
            factor = 'dose',
            group_var = 'supp',
            color_palette = 'viridis',
            jitter_points = TRUE)
```



## Regression Diagnostic Plots

1. Residual vs. Fitted Values
2. Normal-QQ plot
3. Scale-Location plot
4. Residual vs. Leverage
5. Cook's Distance
6. Collinearity

```{r,fig.height=6,fig.width=8}
model <- lm(mpg ~ wt + am + gear + vs * cyl, data = mtcars)
```

The default plots in `diagnostic_plots()` are the first four in the list mentioned above. However, one can choose any of the six plots they need. For example if one needs all six plots use `which_plots=1:6`. 

```{r,fig.height=8,fig.width=9}
diagnostic_plots(model, which_plots=1:6)
```


Another example, if one simply requires the  Residual vs. Fitted Values and Cook's Distance plots, use `which_plots = c(1,5)`. If one wants to display confidence intervals, use `standard_error=TRUE` 

```{r,fig.height=6,fig.width=9}
diagnostic_plots(model, which_plots=c(1,5),
                 standard_errors = TRUE)
```


## Half-Normal Plot

The Half-Normal plot is a graphical tool used to help identify which experiment factors have significant effects on the response. In addition, cutoff line(s) are added for the margin of error (ME) and the simultaneous margin of error (SME) of the effects. These values are obtained using `unrepx::ME()`. 


```{r}
m1 <- lm(lns2 ~ (A+B+C+D)^4,data=original_epitaxial)
half_normal(m1)
```


With the `method` argument there are seven construction methods to obtain the pseudo standard errors in order to calculate (ME) and (SME). These methods are 
*"Daniel", "Dong", "JuanPena", "Lenth" (Default), "RMS", "SMedian", "Zahn", "WZahn"*. See `?ggDoE::half_normal` for more details and references on each of the methods.


```{r}
half_normal(m1,method='Daniel',alpha=0.1,
            ref_line=TRUE,label_active=TRUE,
            margin_errors=TRUE)
```

You can change the significance level used to obtain (ME) and (SME) and determine which factors are active using the `alpha` argument. Default is `alpha=0.05`. Using `label_active` argument will only label the active factors in the experiment. 

Using `showplot=FALSE` will return the needed information to reproduce/change the above half-normal plot

```{r}
half_normal(m1,method='Daniel',alpha=0.1,
            showplot=FALSE)
```


## Interaction Effects Plot for a Factorial Design

Interaction effects plot between two factors in a factorial design


```{r,fig.width=8,fig.height=6}
interaction_effects(adapted_epitaxial,response = 'ybar',
                    exclude_vars = c('s2','lns2'))
```



```{r,fig.width=9,fig.height=4}
interaction_effects(adapted_epitaxial,response = 'ybar',
                    exclude_vars = c('A','s2','lns2'),
                    n_columns=3)
```


## Main Effects Plot for a Factorial Design

Main effect plots for each factor in a factorial design


```{r}
main_effects(original_epitaxial,
             response='s2',
             exclude_vars = c('ybar','lns2'))
```



```{r}
main_effects(original_epitaxial,
             response='s2',
             exclude_vars = c('A','ybar','lns2'),
             color_palette = 'viridis',
             n_columns=3)
```




## Contour Plots for Response Surface Methodology


```{r}
heli.rsm <- rsm::rsm(ave ~ SO(x1, x2, x3, x4), 
                     data = rsm::heli)
```

Using `gg_rsm` we can obtain contour plots that display the fitted surface for an `rsm` object. It is best to use `rsm` object such as the one defined above, as the plots below are produced using information from an `rsm` object. `gg_rsm` includes an `...` argument for additional arguments from  `rsm::contour.lm`, see `rsm::contour.lm` for more details on its arguments.

By default the contour plots produce will be in black and white color

```{r,fig.height=8,fig.width=10}
gg_rsm(heli.rsm,form = ~x1+x2+x3,
       at = rsm::xs(heli.rsm),
       n_columns=2)
```

with `filled=TRUE`, a viridis color scheme is applied.


```{r,fig.height=8,fig.width=10}
gg_rsm(heli.rsm,form = ~x1+x2+x3,
       at = rsm::xs(heli.rsm),
       filled = TRUE,
       n_columns=2)
```


## Pareto Plot

Pareto plot is a bar graph with the bars ordered by the size of the effect. In addition, cutoff line(s) are added for the margin of error (ME) and the simultaneous margin of error (SME) of the effects.


```{r}
m1 <- lm(lns2 ~ (A+B+C+D)^4,data=original_epitaxial)
pareto_plot(m1)
```

As in the `half_normal()` function there are seven methods to compute the pseudo standard errors. For example, we consider 'Daniel' construction method using a significance level of $\alpha=0.1$. Default arguments for `method` is "Lenth" and `alpha = 0.05`.

```{r}
pareto_plot(m1,method='Daniel',alpha=0.1)
```


If one uses the `showplot=FALSE` argument, a list will be returned with the calculated 
PSE,ME,SME as well as the data used to construct the pareto plot.

```{r}
pareto_plot(m1,method='Daniel',
            alpha=0.1, showplot=FALSE)
```



## Two Dimensional Projections 

This function will output all two dimensional projections from a Latin hypercube design.

Below is an example from generating a random Latin hypercube design using the R package
`lhs`

```{r,fig.height=6,fig.width=8}
set.seed(10)
random_LHS <- lhs::randomLHS(n=15, k=4)
twoD_projections(random_LHS,n_columns=3,grid = TRUE)
```

Below is an example of a maximin Latin hypercube design with red color points and no grid (default setting)

```{r,fig.height=6,fig.width=8}
maximin_LHS <- lhs::maximinLHS(n=15, k=4)
twoD_projections(maximin_LHS,n_columns=3,point_color = 'red')
```




