---
title: "Introduction"
output:
  html_document:
    toc: true
    toc_float: true
    fig_width: 5
    fig_height: 5
  pdf_document:
    toc: true
    highlight: tango
    fig_width: 3
    fig_height: 3
  rmarkdown::html_vignette:
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{1 Introduction}
  %\VignetteEncoding[UTF-8]{inputenc}
---

<!--
%\VignetteEngine{knitr::knitr}
%\\VignetteIndexEntry{mand}
-->

`r Sys.Date()` @Atsushi Kawaguchi


```{r echo=FALSE, error=FALSE}
options(warn=-1)
knitr::opts_chunk$set(eval = FALSE)
```

In this vignette, the output is omitted.
Please refer to the following book for the output.

Kawaguchi A. (2021). Multivariate Analysis for Neuroimaging Data. CRC Press.

### Preparation
The first installation of the package should be performed from the Comprehensive R Archive Network (CRAN) using the following code. 
```{r eval=FALSE}
if(!require("mand")) install.packages("mand")
```

Once the package is installed, this code is no longer required.
The package is loaded with the following command line code.
```{r eval=TRUE, echo=TRUE, message=FALSE, error=FALSE}
library(mand)
```

```{r}
library(oro.nifti) 
library(oro.dicom) 
library("imager")
```

This code must be executed every time to start the R. Other packages are also available. Some depend on the mand package being preinstalled. 

### Template 
One subject image as the template is available in the mand package.
The coad to load it is as follows.
```{r}
data(template)
```

The image is compressed because of storage and computation time. The dimension is confirmed as follows.
```{r}
dim(template)
```

The image is plotted by the `coat` function. 
```{r}
coat(template)
```

Other options with the plane argument (such as "axial," "coronal," "sagittal," and "all") are available. The default setting is "axial".
If the argument is specified as `plane="all"`, three directional slices at a certain coordinate are plotted. 
```{r fig.width = 5, fig.height = 2}
coat(x=template, plane="all")
```

### Image Data Matrix
The `imgdatamat` function reads image files saved in the nifti format and creates data matrix with subjects in row and voxel in column (this example does not work).
```{r  eval=FALSE}
fnames1 = c("data1.nii", "data2.nii")
imgmat = imgdatamat(fnames1, simscale=1/4)
```
The first argument is file names with the length equaling the number of subjects (the number of rows in the resulting data matrix).
The second argument `simscale` is the image resize scale. In this example, the all sizes (number of voxel) for three direction was reduced into its quarter size.
The output is the list form where the "S" is data matrix, the "brainpos" is a binary image indicating brain region, and the "imagedim" is image dimension.
The ROI (Region Of Interest) volume is computed in the "roi" if the ROI argument is TRUE.
```{r  eval=FALSE}
imgmat = imgdatamat(fnames1, simscale=1/4, ROI=TRUE)
```


### Overlay
The resulting map from the statistical analysis such as the t statistics map from the SPM is represented with overlapping on the template.
For example, the `mand` package has the average difference assuming Alzheimer's disease and healthy subjects with the array format. 
```{r echo=FALSE, eval=FALSE}
'
```
The overlay is implemented by the `coat` function.
```{r}
data(diffimg)
coat(template, diffimg)
```

### Atlas
Anatomical brain segmentation region is useful for the plot and the interpretation.
For example, the Automated Anatomical Labeling (AAL) atlas is used. 
The data.frame has two columns ("ROIid" and "ROIname") format. 
```{r}
data(atlasdatasets)
atlasname = "aal"
atlasdataset = atlasdatasets[[atlasname]]
head(atlasdataset)
```

It is also neccesary to prepare the array data.
```{r}
data(atlas)
tmpatlas = atlas[[atlasname]]
dim(tmpatlas)
```

It has the ROIid as the element.
```{r}
tmpatlas[11:15,11:15,10]
```

The anatomical region can be plotted by the `coat` function with regionplot=TRUE.
```{r}
coat(template, tmpatlas, regionplot=TRUE, 
atlasdataset=atlasdataset, ROIids = c(1:2, 37:40), 
regionlegend=TRUE)
```


The resulting map can be converted into the summary of the anatomical regions.
```{r}
atlastable(tmpatlas, diffimg, atlasdataset, ROIids = c(1:2, 
37:40))
```

The outputs are the number of voxel in the `sizenum` column,
the percentage of the voxel in the `sizepct` column, and
the minimum, mean, and maximum valued of the region of the overlaying map.
The order of the table row is in the larger absolute value of the minimum or maximum values.

The brain image corresponding to the region of interest can be extracted as follows.
First, we create a mask image in which the hippocampal region is represented by 1 and others by 0.
Then the product of the template and the mask image is taken for each voxel.
```{r} 
hipmask = (tmpatlas == 37) + (tmpatlas == 38)
template2 = template * hipmask
```

The images generated by these processes are plotted from left to right in one slice.
```{r fig.width = 5, fig.height = 2}
par(mfrow=c(1,3), mar=rep(1,4))
coat(template, pseq=11, paron=FALSE)
coat(hipmask, pseq=11, paron=FALSE)
coat(template2, pseq=11, paron=FALSE)
```

The template image (left) and the mask image (middle) are multiplied voxel by voxel to obtain the only hippocampus region image (right).

The sum of the voxel values in the region is calculated as follows.
```{r}
sum(template[which(hipmask==1, arr.ind = TRUE)])/1000
```

Such a value is calculated for each region and a dataset with ROI values is created.

