---
title: "Standard Genome Wide Association Study"
output:
  rmarkdown::html_vignette:
    self_contained: false
vignette: >
  %\VignetteIndexEntry{Standard GWAS}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
is_CRAN <- !identical(Sys.getenv("NOT_CRAN"), "true")
knitr::opts_chunk$set(eval = !is_CRAN)
```

In a standard GWAS analyses, a single phenotype is repeatedly regressed on each single nucleotide polymorphism (SNP) in the users genomic data file (as well as a fixed set of covariates). While there are several software packages that allow users to conduct GWAS analyses, GW-SEM is the only routine that allows users to conduct GWAS analyses that model ordinal data as a probit response, relying on a liability-threshold model to link the observed ordinal variable to a continuous underlying liability. GW-SEM can also manage quantitative (continuous) or binary (case-control) variables in the same manner as other standard GWAS software packages.

***
## Example
To demonstrate how to conduct a GWAS using GW-SEM, we use simulated data for three correlated phenotypes for 6,000 individuals with accompanying GWAS data consisting of 2,000 SNPs, as well as 6 covariates (that are a proxy for age, sex, ancestry principle components or other confounds). As we are not allowed to post the raw data online, we simulated similar data that we use in this demonstration. The first step in the analysis is to load the GW-SEM package in R.  The command load the packages is:

```{r}
library(gwsem)
```

After GW-SEM has been loaded into the R environment, you can read in the phenotypic data, examine it, and recode variables as necessary. For the current example, this can be done using the following commands:

```{r}
location <- 'https://jpritikin.github.io/gwsem/gwsemItemExample/'

# Read the phenotype data into R and look at the data
phenoData <- read.table(file.path(location, "itemPhenoData.txt"),
                        header=TRUE)
head(phenoData)

table(phenoData$tobacco)
table(phenoData$cannabis)
table(phenoData$alcohol)
```

As you can see, the tobacco variable is an categorical variable with 3 levels, cannabis is an categorical variable with 4 levels, and alcohol is an categorical variable with 5 levels. To tell R that you want to treat these variables as ordinal, you can use the following **_mxFactor()_** commands:


```{r}
phenoData$tobacco  <- mxFactor(phenoData$tobacco  , levels = 0:2)
phenoData$cannabis <- mxFactor(phenoData$cannabis , levels = 0:3)
phenoData$alcohol  <- mxFactor(phenoData$alcohol  , levels = 0:4)
```

After you are confident that the variables are recoded in the optimal manner, you can begin building the GWAS model. To being with, let's look at how to do a standard GWAS with only one item. The first step in conducting the GWAS analysis is to to build a general model. This takes a series of arguments: 

```{r}
tob <- buildItem(phenoData = phenoData,                              # the phenotypic data object
                     depVar = c("tobacco"),                          # the outcome or dependent variable 
                     covariates=c('pc1','pc2','pc3','pc4','pc5'),    # the necessary covariates
                     fitfun = "WLS")                                 # the fit function (WLS is much faster than ML)
```

After you have built the model and put it into an object (named tob), you can take this object which is technically an OpenMx model, and fit it using _**mxRun()**_"

```{r}
tobFit <- mxRun(tob)
summary(tobFit)
```

It is strongly advised to test out the model, as it is a great time to learn if your model is being specified in a way that you didn't expect or that the model is not giving you the answers that you are expecting. Now, provided that the model looks reasonable, you can plug the model that you have built into the GWAS function. To fit this function, you must tell GW-SEM :

```{r}
library(curl)
curl_download(file.path(location, 'example.pgen'),
              file.path(tempdir(),'example.pgen'))
curl_download(file.path(location, 'example.pvar'),
              file.path(tempdir(),'example.pvar'))

GWAS(model = tob,                       # where the model is
	snpData = file.path(tempdir(),'example.pgen'),       # where the snpData 
	out=file.path(tempdir(),"tob.log"))   # where you want to save the results
```

When you execute this command, you will begin running your GWAS.  

After you finish running the GWAS analysis, the next step is to read the results in to R so that you can examine them, plot them, prepare them to be used by other software packages, etc. While you are unlikely to want to read all of the output into R, it is useful to do this on a small test GWAS analysis to ensure that you are getting reasonable results. To do so, you can use the base R function **_read.delim_**.  This is didactically useful, but it contains much more information than most people want

```{r}
TobFullResult <- read.delim(file.path(tempdir(), "tob.log"))  
```
Note that the results file is tab separated (with dates and times for each snp), so read.table will tell you that the the number of column names does not match the number of data columns.


More reasonably, we will want to examine the results for a specific parameter using the _**loadResults**_ function. This function takes takes two arguments: the path to the data and the column in the results 
# file for the parameter that you want to examine.

```{r}
succinct <- loadResults(path = file.path(tempdir(), "tob.log"),
                        focus =  "snp_to_tobacco")
```

In the post analysis section, I will give you a way to read several files into a single R object.

After you have read the results into R, you can manipulate them to your heart's content.  Here is a quick function to plot the p-values as a Manhattan plot:

```{r}
plot(succinct)
```






As you will probably be conducting the GWAS analysis on a cluster, here are the essential components of the R script that you will need in your *.R file to run the GWAS.
```{r}
library(gwsem)

# Read the phenotype data into R and look at the data
phenoData <- read.table(file.path(location, "itemPhenoData.txt"), header=TRUE)
phenoData$tobacco  <- mxFactor(phenoData$tobacco  , levels = 0:2)
phenoData$cannabis <- mxFactor(phenoData$cannabis , levels = 0:3)
phenoData$alcohol  <- mxFactor(phenoData$alcohol  , levels = 0:4)

tob <- buildItem(phenoData = phenoData, depVar = c("tobacco"), 
                 covariates=c('pc1','pc2','pc3','pc4','pc5'),
                 fitfun = "WLS") 

GWAS(model = tob,
     snpData = file.path(tempdir(), 'example.pgen'),
     out= file.path(tempdir(), "tob.log"))
```

# The Multivariate GWAS Model

The process for conducting a multiple dependent variable GWAS is very similar to that for conducting a standard GWAS. The only substantive difference is that instead of telling GW-SEM that you have a single dependent variable, as we did above, we provide a list of dependent variables. GW-SEM will then regress multiple items on each SNP.

To conduct the multivariate GWAS model,  the first thing that we would want to do is build a general model. 

```{r}
multi   <- buildItem(phenoData,                               # the data object
              depVar = c("tobacco", "cannabis", "alcohol"),   # the dependent variables
              covariates=c('pc1','pc2','pc3','pc4','pc5'),    # the covariates
              fitfun = "WLS")                                 # the fit function
```

Again, You can take this object (multi) which is technically an OpenMx model, and simply fit it using mxRun() 

```{r}
multiFit <- mxRun(multi)
summary(multiFit)
```

Then you will use the same function that we used for the latent variable model, with a different model object

```{r}
GWAS(model = multi,
     snpData = file.path(tempdir(), 'example.pgen'),
     out=file.path(tempdir(), "multi.log"))
```

Now that we have run the residual's model, we have multiple parameters that we want to load into R (three in this case). The function to do this is the same as for one parameter, but you need to do it several times (once for each parameter). This gives several R objects.

```{r}
succinctTob <- loadResults(path = file.path(tempdir(), "multi.log"),
                           focus =  "snp_to_tobacco")
succinctCan <- loadResults(path = file.path(tempdir(), "multi.log"),
                           focus =  "snp_to_cannabis")
succinctAlc <- loadResults(path = file.path(tempdir(), "multi.log"),
                           focus =  "snp_to_alcohol")
```

# Now we can plot all the residual manhattan plots

```{r}
plot(succinctTob)
plot(succinctCan)
plot(succinctAlc)
```
