---
title: "Single Factor Genome Wide Association Study"
output:
  rmarkdown::html_vignette:
    self_contained: false
vignette: >
  %\VignetteIndexEntry{Single Factor 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)
```

The One Factor model is a natural extension of univariate genome-wide association study (GWAS).

In 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). The One Factor Model in GW-SEM  allows users to regress a latent factor on each SNP (as well as a fixed set of covariates). This allows users to explicitly construct a measurement model (i.e., factor analysis) within the GWAS context, and go beyond thinking of phenotypes as directly measured variables or case-control status, opening up a whole array of innovative applications. A general schematic depiction of the one factor model is presented in the figure below, but users should keep in mind that the number of items in the analysis and the specific parameterization of the model can be adjusted to suit the specific research question. 

In the Figure below, the latent factor (F<sub>1</sub>) is the underlying (unmeasured) cause the observed items (x<sub>k</sub>). The association between the latent factor and the observed indicators are estimated by the factor loadings (&lambda;<sub>k</sub>). The residual variances (&delta;<sub>k</sub>) indicate the remaining variance in (x<sub>k</sub>) that is not shared with the latent factor. The regression of the latent factor on the SNP (for all SNPs in the analysis) is depicted by (&beta;<sub>k</sub>). For a one factor model to be identified, you will need at least three items, but more items will improve the accuracy of the latent variable. While there are statistical tricks that can be used to identify latent variables with two indicators, GW-SEM does not offer ready-made models that incorporate these tricks. 

***

![Schematic Depiction of the One-Factor GWAS Model](https://jpritikin.github.io/gwsem/exampleFigs/singleFactor.jpg)


***
## Example
To demonstrate how to use these function, we use simulated data for a one factor GWAS model with 6,000 individuals consisting of 2,000 SNPs, three correlated items and 6 covariates (that are a proxy for age, sex, ancestry principle components or other confounds). The simulated data are loosely based upon the data used in the demonstration of Pritikin et al (under review). In the paper, we examined the association a latent substance use frequency variable that used tobacco, cannabis, and alcohol as indicators.  The latent variable was regressed on each SNP with a minor allele frequency larger than 1%.  As we are not allowed to post the raw data online, we simulated similar data that for this demonstration.

## Running the One-Factor GWAS

The first step is opening R and loading the GW-SEM package into the R computing environment (which will also load all of the dependencies, such as OpenMx), which can be achieved by using the command below:

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

The next step is to load the phenotypic data. This will include any items that define the latent variable or necessary covariates that you will include in the analysis, such as age, sex, or ancestry principle components. Once the phenotypic data has been loaded, it is advisable to make sure the data has been loaded properly. This can be done in a number of ways. For example, you can use the `head` command to inspect the first few lines of data, look at the means and variances, construct tables of ordinal variables, etc.  If your data didn't load properly, it will likely cause problems for the analysis and for the interpretation of the results.

```{r}
location <- 'https://jpritikin.github.io/gwsem/gwsemOneFacExample'
phenoData <- read.table(file.path(location, "oneFacphenoData.txt"), header=TRUE)
head(phenoData)
```

Once the data is loaded into R, you can recode the data, transform it, and tell R if we have ordinal or binary indicators using mxFactor(). The data for this example are simulated and continuous, and therefore, we will not be doing anything now, but if you would like to `cut` the indicators up into binary or ordinal variables, this would be when you would do it.


After you are satisfied the data is in the appropriate shape we can build a one factor GWAS model with the following command: 

```{r}
                                                                                     # You must tell GW-SEM:
addFac <- buildOneFac(phenoData = phenoData,                                         # what the data object is (which you read in above)
                     itemNames = c("tobacco", "cannabis", "alcohol"),                # what the items of the latent factor are
                     covariates=c('pc1','pc2','pc3','pc4','pc5'),                    # what covariates that you want to include in the analysis
                     fitfun = "WLS")                                                 # and the fit function that you would like to use (WLS is much faster than ML)

```

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

```{r}
addFacFit <- mxRun(addFac)
summary(addFacFit)
```

This is strongly advised, as it is a great time to test whether the model is being specified the way you want it to be and that you are not getting unrealistic estimates.

Provided that the model looks reasonable, you can plug the model that you have built into the GWAS function using the command below:

```{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 = addFac,                                                                 # what model object you would like to fit
	snpData = file.path(tempdir(), 'example.pgen'),                                                        # that path to the snpData file.
	out=file.path(tempdir(), "latFac.log"),                                                                # the file that you would like to save the full results into
	SNP=1:200)                                                                       # the index of the snps (how many) you would like to fit
```

**Note about the snpData argument:** The path to your snpData will likely include switching to a different directory (as you will likely do your analysis in a different folder than your SNP data). All you need to do is point to the data using relative paths. Further, it is able to take plink bed/bim/fam or pgen/psam/pvar data or bgen data (Oxford format)

**Note about the SNP argument:** This can be used to run a limited number of SNP (i.e. not the whole snp file). This is particularly useful if you would like to chop up a chr into several parts without cutting you actual genotype data into separate files.

While the GWAS function will take a while and frequently be executed on a computing cluster, it is very useful to run a few SNPs (say 10 or 50) in an interactive session to make sure that: all of your relative file paths to the genotypes are correct, the model is taking a reasonable amount of time (i.e., 1-2 seconds/snp), the SNPs are giving sensible estimates, etc., as the results from a few SNPs can often tell you if there is a problem and that you are running a nonsensical model. 

While most computing clusters have unique queue submission systems (and I would strongly advise you to run GWAS on a computing cluster), the R script that you provide will typically be similar to the one below:

```{r}
library(gwsem)

phenoData <- read.table(file.path(location, "oneFacphenoData.txt"), header=TRUE)
head(phenoData)

addFac <- buildOneFac(phenoData = phenoData,                                         # what the data object is (which you read in above)
                     itemNames = c("tobacco", "cannabis", "alcohol"),                # what the items of the latent factor are
                     covariates=c('pc1','pc2','pc3','pc4','pc5'),                    # what covariates that you want to include in the analysis
                     fitfun = "WLS")                                                 # and the fit function that you would like to use (WLS is much faster than ML)

GWAS(model = addFac,                                                                 # what model object you would like to fit
	snpData = file.path(tempdir(), 'example.pgen'),                                                    # that path to the snpData file.
	out=file.path(tempdir(), "latFac.log"))                                                            # the file that you would like to save the full results 
```

The next step is to read the results into R. The output from the GWAS function contains all of the estimates and standard errors for all parameters in the model (for each SNP), as well as other general model fitting information.  While you are unlikely to want to read all of this output into R, it is useful to do this on a small test GWAS analysis to ensure that you are getting reasonable results and to familiarize yourself with what information is available, in case you need to explore a specific parameter or model in more detail. This can be done using the command below:  

```{r}
FullResult <- read.delim(file.path(tempdir(), "latFac.log"))
```

More likely, you are going to want to read the results into R for SNP regression coefficients. 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(), "latFac.log"), focus =  "snp_to_F")
```

We can then construct a Manhattan plot using the GW-SEM plot() function. 

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

The loadResults() function formats the summary statistics from the analyses so that the data object can be seamlessly used by qqman, LDhub, and other post GWAS processing software.



***

## Suggestions for Conducting the Analysis

Before running any sort of analysis in GW-SEM, users should have an understanding of the phenotypic relationships between the traits that you are interested in examining. Specifically, for the one-factor model, the items that load onto the latent variable should be established prior to running the GWAS, or the user risks conducting an analysis that does not test their intended hypothesis.  For example, if the structure of the latent factor differs from the model written in GW-SEM (model misspecification), any conclusions that are drawn from the analysis are questionable.  Alternatively, if there are items that do not load onto the latent factor, this may dilute the GWAS signal.  The best, and most interpretable, results will come from a clearly defined, well specified, phenotypic model. 

