%\documentclass[article, shortnames]{jss}
\documentclass[nojss,shortnames]{jss}
%\VignetteIndexEntry{mppR: An R Package for QTL Analysis in Multi-parent Populations}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% declarations for jss.cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% packages
\usepackage{thumbpdf,lmodern}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bm}
\usepackage{blkarray}
\usepackage{graphicx}
% \usepackage{natbib}
% \usepackage{threeparttable}
% \usepackage{Sweave}

% Extra command

\def\Big#1{\makebox(0,0){\Large#1}}

%% almost as usual
\author{Vincent Garin\\Wageningen University \And 
        Valentin Wimmer\\KWS SAAT SE \And
        Dietrich Borchardt\\KWS SAAT SE \AND
        Fred van Eeuwijk\\Wageningen University \And
        Marcos Malosetti\\Wageningen University \And
    }
    
\title{mppR: An R Package for QTL Analysis in Multi-parent Populations}

%% for pretty printing and a nice hypersummary also set:
\Plainauthor{Vincent Garin, Valentin Wimmer, Marcos Malosetti, Fred van Eeuwijk } %% comma-separated
\Plaintitle{mppR: An R Package for QTL Analysis in Multi-parent Populations using Linear Mixed Models} %% without formatting
\Shorttitle{\pkg{mppR}: QTL analysis in MPPs} %% a short title (if necessary)

%% an abstract and keywords

\Abstract{
	\pkg{mppR} is an add-on package for the statistical software \proglang{R} for QTL analyses in multi-parent populations composed of genotypes from more than one cross like NAM populations, diallels or factorial designs. \pkg{mppR} contains functions to assist the user in a range of activities of QTL analysis such as: data processing, QTL detection, visualisation of results, and estimation of QTL effects. \pkg{mppR} workflow is structured along main functions allowing to: 1) perform preliminary data quality control; 2) organize data into a single data object; 3) cluster parental lines based on ancestry; 4) perform QTL detection; 5) evaluate QTL discoveries by cross-validation; and 6) determine multi-QTL effect models. The search of QTLs can be done by 4 different models that vary with respect to the way the QTL effects are modelled (cross-specific, parental, ancestral or bi-allelic).}



\Keywords{Multi-parent populations, quantitative trait loci, mixed models, \proglang{R}}
\Plainkeywords{multi-parent populations, quantitative trait loci, mixed models, R} %% without formatting
%% at least one keyword must be supplied

%% publication information
%% NOTE: Typically, this can be left commented and will be filled out by the technical editor
%% \Volume{50}
%% \Issue{9}
%% \Month{June}
%% \Year{2012}
%% \Submitdate{2012-06-04}
%% \Acceptdate{2012-06-04}

%% The address of (at least) one author should be given
%% in the following format:

\Address{Vincent Garin \\
	E-mail: \email{vincent.garin6@gmail.com}\\
}

%% It is also possible to add a telephone and fax number
%% before the e-mail in the following format:
%% Telephone: +43/512/507-7103
%% Fax: +43/512/507-2851

%% for those who use Sweave please include the following line (with % symbols):
%% need no \usepackage{Sweave.sty}

%% end of declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\begin{document}
%\SweaveOpts{concordance=TRUE}
%\SweaveOpts{concordance=TRUE}
%\SweaveOpts{engine=R, eps=FALSE, keep.source = TRUE}

\section{Introduction}

% Software package are cited \cite{}d


Quantitative trait locus (QTL) analysis essentially consists in finding a relationship between DNA polymorphisms (e.g., SNPs) and phenotypic variation \citep{doerge2002mapping}. QTL detection methods greatly depends on the genetic properties of the population that is used. Historically, QTL detection has been performed in designed experimental populations involving two parental lines (bi-parental crosses). Several methods and software packages have been developed for QTL analysis for such populations, for a review see \citet{varshney2015analytical}. Multi-parent populations (MPPs) are an alternative type of population that can improve the chances of QTL detection while broadening the range of research questions that can be answered \citep{cavanagh2008mutations}. MPPs can be seen as a compromise between bi-parental crosses and association panels \citep{myles_2009}. Different types of MPPs have been developed including nested association mapping (NAM) populations \citep{mcmullen_2009}, diallels \citep{blanc_2006} and factorial designs \citep{bardol_2013}. More complicated MPPs can be created by intercrossing multiple founders followed by inbreeding, like in multi-parent advanced generation inter-cross (MAGIC) populations \citep{cavanagh2008mutations}. Here, we consider MPPs as a collection of genotypes that are derived by crosses between at least three different parents. In this paper, a MPP QTL analysis is akin to the joint analysis of such a population using a common marker map.


The development of an appropriate statistical methodology taking MPP properties into consideration is a \textit{sine qua non} condition to fully exploit the potential of MPP genetic resources. The most critical question is how to account for genetic relatedness between the genotypes and how to integrate this information into the statistical model. A first simple option is to treat MPPs as an association mapping panel and to apply genome-wide association study (GWAS) QTL detection methods. 

The use of a GWAS type of method presents several advantages. First, GWAS methods apply to almost any type of MPP design because the knowledge of population structure is not a prerequisite. The GWAS QTL detection is marker-based, that is, uses identity by state (IBS) information, and so generally only allows for two alleles at each tested position. A second advantage is the existence of powerful algorithms (e.g. EMMA - \citet{kang2008efficient}) that allow to scan in a reasonable amount of time large marker datasets. Finally, GWAS analyses are also based on sets of well-developed mixed models \citep{yu_2006}. These models allow to account for the population structure and the polygenic effect using a kinship matrix covering the relations between all genotypes from all populations \citep{van2010detection, rincent2014recovering}. MPP GWAS type of QTL detection can be performed using packages like \pkg{TASSEL} \citep{bradbury2007tassel} the \proglang{R} library \pkg{GAPIT} \citep{gapit2012} or the \proglang{R} packages \pkg{GenABEL} \citep{genabel2007} and \pkg{Sommer} \citep{covarrubias_sommer_2016}.

However, a major limitation of GWAS methods is that they generally use bi-allelic marker models assuming two classes of effects at the QTL position. The bi-allelic assumption represents therefore a risk of failing to reflect the allele diversity potentially present at the QTLs within MPPs \citep{garin2017type}. Indeed, several factors like multiple alleles, cross-specific linkage phase between marker and QTL alleles, or interaction effects between the QTL and genetic background may cause complex allelic series.

Other approaches use available pedigree information to model or infer DNA transmission to the final lines starting from a set of parents or ancestors. This strategy make use of identity by descent (IBD) information and gives model with more than two alleles, which can be more appropriate to model complex allelic series \citep{blanc_2006, xavierNAM2015}. For example, the \proglang{R} package \pkg{NAM} \citep{xavierNAM2015} proposes to take into consideration factors which can lead to complex allelic series like the difference of linkage phase association between marker and QTL in different crosses. \pkg{NAM} uses incidence matrices containing the number of alleles received per parent to estimate random QTL effects and to control for the polygenic background in the rest of the genome. The software package \pkg{MCQTL} \citep{jourjon_2005} functioning in a Linux environment is also an option. \pkg{MCQTL} combined with the \proglang{R} package \pkg{clusthaplo} \citep{leroux_2014} computes linear models with various assumptions about the origin and number of QTL alleles (cross-specific, parental, or ancestral).

We add a the bi-allelic model and incorporate a cross-validation strategy to evaluate the QTL detection performance of the different models. We also developed a method to build multi-QTL (MQE) models that allows QTLs with different types of effects at different loci in contrast to the more rigid approach in \pkg{MCQTL} \citep{jourjon_2005} that assumes the same type of effect across the genome. In a nutshell, \pkg{mppR} fits a wide range of models with different assumptions about the QTL effects. The current version of \pkg{mppR} is based on the linear model. A more general version of \pkg{mppR} is available from the following GitHub repository \url{https://github.com/vincentgarin/mppR}. In a mixed model context, we can allow for heterogeneity of variance present in MPPs, and other sources of random variation and/or dependence existing between genotypes. The \pkg{mppR} components that are based on mixed model technology depend on the \pkg{ASReml-R} package \citep{asreml_2009} and require a license.

This manual is organized as follows. Section~\ref{sec:2} describes the statistical methodology for the proposed MPP QTL detection procedures. Section~\ref{sec:3} illustrates in details the QTL detection procedure describing the different functions using a subset of the maize US-NAM population as example \citep{yu_2008_NAM, mcmullen_2009}.

 
\section{Statistical methodology}
\label{sec:2}


\subsection{Connectivity}

\pkg{mppR} allows to analyse any type of MPP design with minimally two crosses between at least three different parents. In such designs, the possibility to estimate QTL parameters (identifiability) is linked to the notion of connectivity of the design. It is always possible to estimate one effect per cross. Therefore, the number crosses ($n_{c}$) constitutes the largest number of QTL effects that can be estimated. The estimation of parental and ancestral effects is linked to the connectivity of the MPP design \citep{rebai_2000}. Taking for example the parental alleles, it is possible to estimate $n_{p} - 1 \leq  n_{c}$ parental alleles per connected part of the design. Design connectivity can be defined using graph theory \citep{weeks_1964}. Following graph theory, an MPP design can be represented by a graph where parents (alleles) are vertices or nodes and crosses are edges or lines (Figure \ref{fig:1}). A connected graph, is a graph where there exists a walk from any node $i$ to any other node $j$. For example, the MPP design in Figure (\ref{fig:1}) is composed of two connected parts. Ideally, MPP QTL analysis should be run using only connected populations. The joint analysis of an MPP composed of several disjunct but internally connected parts is still possible. In that case, connectedness could follow from the sharing of a common ancestor by two parents of the design. For example if parents $P_{B}$ and $P_{E}$ of the MPP design of Figure (\ref{fig:1}) would receive their allele from the same ancestor, the MPP design would consist of a single connected part. For a bi-allelic model we assume that the design is fully connected. In any case, even if disconnected parts are analysed jointly, a minimal level of connection will be assumed by assuming that cofactors are shared in the whole population.

\begin{figure}[!ht]
	\includegraphics[width=1\textwidth]{figures/connectivity_example.jpg}
	\caption{Example of a MPP design represented as a graph}
	\label{fig:1}
\end{figure}

% Figures, table and equations are referenced using \label and \ref

\subsection{General model}

We propose to describe the QTL detection model following the assumptions made on the form of the QTL effect and allele origin. Let us start by defining the following underlying single locus QTL detection model describing the relationship between the phenotypic values and genotypes coming from several crosses \citep{rebai_1993}:
 
\begin{equation}
\label{eq:1}
y_{ijk} = \mu_{ij} + \alpha_{i} + \alpha_{j} + g_{ij}  + e_{ijk}
\end{equation}


where $y_{ijk}$ represents the phenotypic value for the $k^{th}$ individual from the cross between parents $i$ and $j$. $\mu_{ij}$ is the cross mean and $\alpha_{i}$ and $\alpha_{j}$ represent the effects associated with the QTL alleles coming from parent $i$ and $j$ respectively. The QTL effects are assumed to be strictly additive (no dominance, no epistasis). $g_{ij}$ is the random polygenic effect due to QTLs elsewhere in the genome with distribution $N(0,\sigma_{g}^{2})$. Finally, $e_{ijk}$ represents the random micro-environmental effect (plot error) having distribution $N(0,\sigma_{e}^{2})$. In this model, $\sigma_{g}^{2}$ and $\sigma_{e}^{2}$ are unique meaning that the level of polygenic effect and environmental error is considered to be the same in each cross.

Model (\ref{eq:1}) can be rewritten in matrix notation: 

\begin{equation}
\label{eq:2}
\bm{y}  = \bm{X}\bm{\beta} + \bm{r}
\end{equation}

where, $\bm{y}$ is the $[N \times 1]$ vector of phenotypic values. $N = \sum_{c=1}^{n_{c}}N_{c}$ where $N_{c}$ is the number of genotypes coming from cross $i$. $\bm{X=[X_{c}|X_{Q}]}$ is the fixed effect incidence matrix and $\bm{\beta}' = [\bm{\beta_{c}}'|\bm{\beta_{Q}}']$ the vectors of cross intercepts and QTL effects. $\bm{X}$ is composed of a part that links observations to the particular cross it belongs to ($\bm{X_{c}}$ an $[N \times n_{c}]$ matrix with $n_{c}$ representing the number of crosses) and $\bm{X_{Q}}$ the part related with the QTL effect attached to the particular observation. $\bm{X_{Q}}$ is a matrix of dimensions $[N \times n_{al}]$ with $n_{al}$ the number of QTL alleles that are assumed to segregate for the particular QTL locus. Several assumptions are possible concerning $n_{al}$. They correspond to different statistical models presented in the next section. The form of $\bm{X_{Q}}$ varies according to the type of QTL effect assumed. Finally, $\bm{r}$ represents the vector of random residual terms with distribution $N(0,\bm{R})$.

\subsection{QTL effects}

The QTL effect incidence matrix $\bm{X_{Q}}$ is the central term of the model. Assuming a diploid organism, the individual elements of $\bm{X_{Q}}$, $x_{nl}$ take values between $0$ and $2$ and represent the expected number of copies of allele $l$ with $l = 1,...,n_{al}$ received by genotype $n$ at the QTL position. The column number of $\bm{X_{Q}}$ ($n_{al}$) varies with the number of alleles assumed at the QTL position. We propose four models: cross-specific, parental, ancestral, and bi-allelic. These models correspond to different assumptions concerning the type of QTL effects and the allele origin. They are characterized by different ways to model genetic relatedness between genotypes using either IBD estimates, IBS information, or a combination of both. 


\subsubsection{Cross-specific model}
\label{cr.mod}

The first model assumes that the QTL alleles that segregate within a particular cross are different from those that segregate in another cross. Cross-specific QTL effects can be seen as parental alleles interacting with the cross genetic background. Under this assumption, QTL alleles are nested within crosses and so QTL effects are estimated per cross. In the cross-specific model, $x_{nl} \in [0, 2]$ represents the expected number of allele copies received from one of the cross parents given the flanking markers. The expected number of parental allele copies is estimated using IBD probabilities computed by the package \proglang{R}/\pkg{qtl} \citep{broman_rqtl}. These probabilities are estimated with respect to the parents of each cross. For illustration purpose, let us take the following example of a MPP analysis combining material coming from two crosses: cross 1 ($P_{A} \times P_{B}$) and cross 2 ($P_{A} \times P_{C}$). In that case, we ignore the fact that the two crosses are connected since they share a common parent $P_{A}$. Therefore $\bm{X_{Q}}$ is a diagonal block structure with diagonal elements specifying the within cross allele origin. Model (\ref{eq:2}) can be re-written like that

\begin{equation}
 \label{eq:4}
 \bm{y} = \begin{pmatrix} 1 & 0 \\ 1 & 0 \\ 1 & 0 \\
0 & 1 \\ 0 & 1 \\ 0 & 1 \\ \end{pmatrix} \bm{\beta_{c}} +
\begin{blockarray}{cccc}
P_{A}\, P_{B}\, & P_{A}\, P_{C}\\ 
\begin{block}{(cccc)}
2 \quad 0 & \\
1 \quad 1 &  \Big{0} \\
0 \quad 2 &  \\
& 2 \quad 0 \\
\Big{0} & 1 \quad 1   \\
& 0 \quad 2 \\
\end{block}
\end{blockarray} \bm{\beta_{Q}} + \bm{r}
\end{equation}

It is not possible to estimate two effects per cross since the parental scores are linearly dependent. The design matrix for the QTL effect in a cross-specific model is therefore constrained by redefining the parental information of a cross as half the difference between parent $i$ and parent $j$. Therefore, for the cross-specific model, $\bm{X_{Q}}$ is of dimension $[N \times n_{c}]$ where $n_{c}$ is the number of crosses and the vector $\bm{\beta_{Q}}$ is of dimension $[n_{c} \times 1]$. The cross-specific model contains the upper limit for the number of QTL effects that can be estimated. Indeed, in connected MPPs, the maximum number of effects that can be estimated is $n_{c} \geq n_{p} -1$ where $n_{p}$ is the number of parents \citep{rebai_2000, jansen_2003}. This model corresponds to the disconnected model described in \citet{blanc_2006}.

\subsubsection{Parental model}
\label{par.mod}

In the cross-specific model, all crosses are considered unrelated. A second option is the parental model that adds the connection between crosses via the parents shared between crosses. In that case, the parental QTL incidence matrix is simply obtained by re-arranging the columns of model (\ref{eq:4}) taking into consideration the connections created by the use of common parents. This model estimates one allele effect per parental line, which is considered to be independent of the genetic background. The QTL effect of parent $p$ is assumed to be constant in all crosses where this parent has been used \citep{blanc_2006}.

In a connected MPP, if $(n_{p} -1) < n_{c}$, one expects the parental model to be more powerful than the cross-specific model because the number of parameters to estimate is reduced \citep{blanc_2006}. The reduction in the number of parameters to estimate should also help to get better estimates of the QTL effects because the sample size used to estimate these effect increases \citep{li_2005}. Full half diallels, with at least four parents, represent the most connected system where the number of crosses $n_{c} = (n_{p}*(1-n_{p}))/2$ is maximised with respect to the number of parents \citep{jansen_2003}. Coming back to the previous example (\ref{eq:4}), we integrate in the QTL incidence matrix the fact that the two crosses are connected via the common parent $P_{A}$.


\begin{equation}
\label{eq:6}
\bm{y} = \begin{pmatrix} 1 & 0 \\ 1 & 0 \\ 1 & 0 \\
0 & 1 \\ 0 & 1 \\ 0 & 1  \end{pmatrix}  \bm{\beta_{c}} + \bordermatrix{~ & P_{A} & P_{B} & P_{C}\cr
	& 2 & 0 &  \cr
	& 1 & 1 & \Big{0} \cr
	& 0 & 2 &  \cr
	& 2 &  & 0 \cr
	& 1 & \Big{0} & 1 \cr
	& 0 &  & 2 \cr } \bm{\beta_{Q}} + \bm{r}
\end{equation}\\

In the parental effect model, the matrix $\bm{X_{Q}}$ is of dimension $[N \times n_{p}]$ and $\bm{\beta_{Q}}$ is of dimension $[n_{p} \times 1]$. The parental model corresponds to the connected model described in \citet{blanc_2006}.


\subsubsection{Ancestral model}
\label{anc.mod}

The third option, called ancestral model, goes one level up in the pedigree and uses relatedness between parents to cluster them into a reduced number of ancestral groups. We assume that parents belonging to the same cluster transmit the same allele \citep{jansen_2003, leroux_2014}. Different options can be used to cluster parental lines. One of them is the \proglang{R} package \pkg{clusthaplo} \citep{leroux_2014}. \pkg{clusthaplo} is an algorithm to cluster parental lines along the genome based on genetic similarity. \pkg{clusthaplo} uses a sliding window to define ancestral classes at each marker position based on local genetic similarities using marker scores within the window. If the local marker density is not large enough, \pkg{clusthaplo} uses the global genetic similarity defined by a kinship coefficient. \pkg{mppR} contains a function to call \pkg{clusthaplo}.   

The ancestral QTL incidence matrix $\bm{X_{Q}^{*}}$ can be obtained by modifying the parental IBD QTL incidence matrix $\bm{X_{Q}}$ using \pkg{clusthaplo} results. The ancestral model uses therefore both IBD and parental relatedness IBS information. Continuing our example (\ref{eq:6}), let us assume that at the considered QTL position parents $A$ and $C$ belong to the same ancestral group $A_{1}$, and parent $B$ falls apart in group $A_2$.
 
\begin{equation}
	\label{eq:7}
\bm{X_{Q}^{*}} = \bm{X_{Q}} \times \bm{A} = 
\bordermatrix{~ & P_{A} & P_{B} & P_{C}\cr
	& 2 & 0 &  \cr
	& 1 & 1 & \Big{0} \cr
	& 0 & 2 &  \cr
	& 2 &  & 0 \cr
	& 1 & \Big{0} & 1 \cr
	& 0 &  & 2 \cr} \times
\begin{pmatrix}
1 & 0 \\
0 & 1 \\
1 & 0 \\
\end{pmatrix} =               
\bordermatrix{~ & A_{1} & A_{2} \cr
	& 2 & 0 \cr
	& 1 & 1 \cr
	& 0 & 2 \cr
	& 2 &   \cr
	& 2 & \Big{0} \cr
	& 2 &  \cr}                
\end{equation}\\

The matrix $\bm{X_{Q}^{*}}$ of the ancestral model is of dimension $[N \times n_{a}]$ where $n_{a}$ is the number of ancestral alleles. The corresponding vector $\bm{\beta_{Q}^{*}}$ is of dimension $[n_{a} \times 1]$. The elements of $\bm{\beta_{Q}^{*}}$ represent the estimates of the ancestral additive effects. The ancestral-effect model corresponds to the LDLA models used by \citet{bardol_2013} and \citet{giraud_2014}.

\subsubsection{Parental and ancestral model constraints}
\label{par_anc_const}


The estimation of parental (ancestral) QTL effect also requires the application of a constraint to the QTL incidence matrix. From a theoretical point of view, it is possible to estimate maximally $n_{p} - 1$ ($n_{a} - 1$) QTL effects per connected part of the design \citep{rebai_2000, weeks_1964}. Therefore, the QTL effects are estimated setting to zero the most frequent parental (ancestral) allele within each connected part. For example in the example of Figure (\ref{fig:1}), we could have $P_{A}$ set as reference of the first connected part and $P_{E}$ set as reference of the second connected part. An alternative is to force the QTL effects to sum to zero. The sum to zero constraint will also take place within each connected part.


\subsubsection{Bi-allelic model}
\label{biall.mod}

The last possibility is the bi-allelic model. If the marker is at the QTL position, the bi-allelic model assumes that genotypes with the same SNP score transmit the same allele. Therefore, we assume that the same allele segregates in the whole population which connects all parts of the design that were not connected before. Genetic relatedness is therefore defined based on marker IBS information only. In this model, using the most frequent allele set as reference, $\bm{X_{Q}}$ become a vector $[N \times 1]$ with values 0, 1 or 2 corresponding to the number of copies of the minor allele.

\begin{equation}
\label{eq:8}
\bm{y} = \begin{pmatrix} 1 & 0 \\ 1 & 0 \\ 1 & 0 \\
0 & 1 \\ 0 & 1 \\ 0 & 1 \\ \end{pmatrix} \bm{\beta_{c}} +
\bordermatrix{~ &SNP_{1} \cr
	&2   \cr
	&1   \cr
	&0   \cr
	&1  \cr
	&2  \cr
	&0  \cr} \bm{\beta_{Q}} + \bm{r}
\end{equation}\\

This model corresponds to association mapping models (e.g., model B in \citet{wurschum_2012_comp}). In a connected MPP, if $(n_{p} - 1) < n_{c}$, the models can be ordered from less to more parsimonious models (cross-specific, parental, ancestral, bi-allelic). 


\subsection{Variance covariance structure}
\label{VCOV}

A second important part of the QTL detection problem is the data variance covariance structure (VCOV). Several assumptions are possible concerning the VCOV of model (\ref{eq:2}) $\bm{V} =Var(\bm{y}) = Var(\bm{r}) = \bm{R}$   

\subsubsection{Homogeneous residual term}
\label{HRT}

The simplest form that can be assumed for $\bm{V}$ is a homogeneous residual term (HRT) variance. In this case, $\bm{R}=\bm{I_{N}}\sigma_{r}^{2}$. This corresponds to a linear model where residual terms are considered to be independent and to belong to the same distribution. In the HRT model, the variance of the polygenic term ($\sigma_{g}^{2}$) and the error variance ($\sigma_{e}^{2}$) of model (\ref{eq:1}) are both pooled in the unique variance residual term $\sigma_{r}^{2}$.

Other models are possible for the VCOV. You can find model with alternative VCOV in a more general version of \pkg{mppR} available from the following GitHub repository \url{https://github.com/vincentgarin/mppR}. You can find a description these models in the attached vignette.

\subsection{Test statistics}

The significance of the QTL effects $\bm{\hat{\beta}_{Q}}$ can be estimated using the Wald test \citep{wald_1943}. In the case of a HRT model, after simplification, the Wald test can be rewritten like that:

\begin{equation}
\label{eq:20}
W(\bm{\hat{\beta}}) = \bm{y}'\bm{\hat{V}}^{-1} \bm{\hat{y}}   
\end{equation}

$W(\bm{\hat{\beta}})$ is distributed as a chi-squared distribution with the degrees of freedom being equal to the number of QTL alleles. Expression (\ref{eq:20}) shows that the test statistic depends on the correlation between the observed phenotypic values ($\bm{y}$) and the model fitted values ($\bm{\hat{y}}$) and on the estimated VCOV ($\bm{\hat{V}}$). For that reason, the choice of the QTL incidence matrix ($\bm{X_{Q}}$) should be such that the phenotypic variations is captured as accurately as possible. If these variations are due to parental or cross-specific effects, corresponding QTL effects should perform better at the price of a larger number of parameters to estimate. On the other hand, if the effects are similar through the MPP, a reduced number of parameters will capture this variability and allows gains in power. The VCOV structure should also be selected to reflect local patterns of variability. If heterogeneity is present between crosses, the CSRT model will give test statistics considering this heterogeneity.


\subsection{QTL detection procedure}

The QTL detection procedure proposed in \pkg{mppR} is based on the following steps: a) Optional significance threshold determination by permutation test \citep{chur_1994}; b) cofactors selection by simple interval mapping (SIM); c) multi-QTL model search using composite interval mapping (CIM) \citep{zeng_1993, zeng_1994}; d) simultaneous evaluation of the selected candidate QTL positions after backward elimination. 


\subsubsection{Significance threshold determination}

The QTL significance threshold can be determined by permutation. The use of permutation aims at reproducing the conditions of the null hypothesis (no QTL present or no association between the marker and the QTL) by breaking the link between the phenotype and the genetic markers \citep{chur_1994}. Permutations allow to build a null hypothesis for the test statistic that reflects the characteristics of the experiment and should be valid for any distribution of the quantitative trait \citep{chur_1994}. The number of permutations should be at least 1000. Alternatively, the user can also specify the significance threshold value.


\subsubsection{Multi-QTL model determination}

The determination of a multi-QTL model is done using CIM. Such a strategy is based on fitting the model using cofactors representing other QTLs than the tested QTL \citep{zeng_1993, zeng_1994}. The selection of cofactors is based on a SIM scan using the following model where $X_{c}$ is a cross-specific intercept and $X_{Q}$ model the QTL effect.

\begin{equation}
\label{eq:25}
\bm{y}  = \bm{X_{c}}\bm{\beta_{c}} + \bm{X_{Q}}\bm{\beta_{Q}} + \bm{r}
\end{equation}

Cofactors can be selected with minimum distance in between based on the -log10($p$)~value SIM profile. CIM profile is computed based on the following model 

\begin{equation}
\label{eq:26}
\bm{y}  = \bm{X_{c}}\bm{\beta_{c}} + \bm{X_{q}}\bm{\beta_{q}} + \bm{X_{Q}}\bm{\beta_{Q}} + \bm{r}
\end{equation}

where $\bm{X_{q}}$ represents the selected cofactors. During the CIM scan, an exclusion window can be set around the tested QTL position to remove cofactors and avoid too strong collinearity between the cofactors and the tested position. Finally, the selected candidate QTLs can be simultaneously tested after a backward elimination. An optional confidence interval for each QTL position can be obtained using a -log10($p$)~value drop-off interval taking a CIM profile and excluding cofactors on the scanned chromosome. 


\subsection{Multi-QTL effect (MQE) model}
\label{MQE}

A variation on the common QTL model with a single type of effect is the multi-QTL effect (MQE) model. In the MQE model, the QTLs present in the final model can have different types of effects (cross-specific, parental, ancestral or bi-allelic). To build an MQE model we use a forward selection procedure. For each QTL to be added, genome wide profiles with a consistent QTL effect are calculated for each types of QTL effects that have been specified by the user. The model that is fitted at each position within a profile is:

\begin{equation}
	\label{eq:30}
	\bm{y}  =  \bm{X_{c}}\bm{\beta_{c}} + \bm{X_{Q1}}\bm{\beta_{Q1}} + \bm{r}
\end{equation}

Where the (first) QTL ($\bm{X_{Q1}}\bm{\beta_{Q}}$) has an effect that is either cross-specific, parental, ancestral, or bi-allelic along the genome. From each of these profiles, the most significant position based on the -log10($p$)~value statistic is selected (e.g., $\bm{X_{Q1.cr}}$, $\bm{X_{Q1.par}}$, $\bm{X_{Q1.anc}}$, $\bm{X_{Q1.biall}}$). Note that the selected QTL positions for the different types of effects can be different. The QTL that increases most the $R_{adj}^{2}$ (\ref{eq:29}) is selected, with it type of effect, and added to the model as a cofactor for the next set of genome wide scans. If at step 1 we selected a bi-allelic QTL, then at step 2 the QTL profiles will be based on the following models:

\begin{equation}
	\label{eq:31}
	\bm{y}  =  \bm{X_{c}}\bm{\beta_{c}} + \bm{X_{q1.biall}}\bm{\beta_{q1}} + \bm{X_{Q2}}\bm{\beta_{Q2}} + \bm{r}
\end{equation}

For the set of QTL effects specified by the user, genome wide scans are performed via a test for the QTL effect in the term $\bm{X_{Q2}}\bm{\beta_{Q2}}$. The forward selection process stops when no further significant QTLs can be identified. At this point, a final list of QTLs is compiled by a backward elimination. A final model with $t$ QTLs could look like:

\begin{equation}
	\label{eq:32}
	\bm{y}  =  \bm{X_{c}}\bm{\beta_{c}} + \bm{X_{Q1.biall}}\bm{\beta_{Q1}} + ... + \bm{X_{Q(t-1).par}}\bm{\beta_{Q(t-1)}} + \bm{X_{Qt.anc}}\bm{\beta_{Qt}}  + \bm{r}  
\end{equation}\\

\subsection{QTL effect estimation}
\label{Q_eff_est}

Once a final list of QTLs is determined, the estimates for the regression coefficients in the corresponding multi-QTL model provide the QTL effects. For this model a global goodness of fit can also be calculated using $R^{2}$. Partial $R^{2}$ statistics are indicators of the contributions of each individual QTLs.

\subsubsection{Genetic effect estimation and interpretation}

In the cross-specific model (\ref{cr.mod}), the genetic predictors for the additive effects represent half the difference between the second parent and the first parent for their conditional QTL genotype probabilities. The elements of $\bm{\beta_{Q}}$ represent the within cross allele substitution effect.

For the parental (\ref{par.mod}) and the ancestral (\ref{anc.mod}) models, from a theoretical point of view, it is possible to estimate a maximum of $n_{p} - 1$ ($n_{a} - 1$) QTL effects per connected part of the design \citep{rebai_2000}. Within each connected part, the most frequent parental (ancestral) allele is used as reference. The estimated parental (ancestral) QTL effects must be interpreted as a deviation with respect to the connected part reference. Referring again to the example in Figure (\ref{fig:1}), if $P_{A}$ is set as reference of the first connected part, its value will be zero and the other parent alleles effects ($P_{B}$, $P_{C}$ and $P_{D}$) will represent deviations with respect to $P_{A}$ allele. If the second part ($P_{E}$, $P_{F}$, and $P_{G}$) was analysed jointly with the first part, the effect of alleles $P_{F}$ and $P_{G}$ will represent deviation with respect to $P_{E}$ and will be independent of the first part parental effects.

An alternative is to use a sum to zero constraint. In that case the parental (ancestral) QTL effects are forced to sum to zero. The individual QTL effects represent a deviation with respect to the central tendency. Here also, the constraints are defined within each connected part. For the bi-allelic model (\ref{biall.mod}), the estimated genetic effect represents the additive effect of one allele copy of the minor allele with respect to the most frequent allele set as reference.


\subsubsection{Global $R^{2}$}

To compute the $R^{2}$ statistics, we compare the residual sums of squares of a full model with QTL(s), to the one of a reduced model without QTLs.

\begin{equation}
\label{eq:27}
R^{2} = 1 - \frac{\sum_{n=1}^{N}{r_{n(full)}^{2}}}{\sum_{n=1}^{N}{r_{n(red)}^{2}}}
\end{equation}

The $R^{2}$ measurement can be adjusted to take into consideration the number of parameters used.

\begin{equation}
\label{eq:29}
R_{adj}^{2} = 1 - \frac{\sum_{n=1}^{N}{r_{n(full)}^{2}}/df_{full}}{\sum_{n=1}^{N}{r_{n(red)}^{2}}/df_{red}}
\end{equation}

Where $df_{full}$ and $df_{red}$ represent the degrees of freedom of the full and reduced model, respectively.

\subsubsection{Partial $R^{2}$}
\label{part.R2}

For each single QTL, a partial $R^{2}$ can be calculated by the difference between the $R^{2}$ of the full model (all QTL positions) and the $R^{2}$ of the model that drops that particular QTL (difference $R^{2}$). \pkg{mppR} also calculates partial $R^{2}$ by comparing a model without QTLs with single locus QTL models (single $R^{2}$). These estimates can also be adjusted using formula (\ref{eq:29}). The partial $R^{2}$ is an estimation of the individual QTL contribution to the phenotypic variation. The difference and single $R^{2}$ give estimates of the lower and upper bound explained variance by individual QTLs.


\subsection{Cross-validation}
\label{CV}

A cross-validation (CV) approach can be used to evaluate the performance of the QTL detection process and to assess the QTL effect in a pseudo-independent population \citep{utz_2000}. CV allows to assess predictability of QTL effects in data not used for model training. The proposed CV procedure is an adaptation of \citet{utz_2000} procedure to the MPP context. A single run of CV is composed of the following steps:

\begin{enumerate}
	
	\item \textbf{Partitioning of the dataset}. The full dataset $(\bm{y_{DS}}, \bm{X_{DS}})$ is partitioned \textit{within cross} into $k$ subsets. Then for the k repetitions each $k$ subset is successively used as validation set (VS) $(\bm{y_{VS}}, \bm{X_{VS}})$, the other ($k-1$) subsets go into the training set (TS) $(\bm{y_{TS}}, \bm{X_{TS}})$.
	
	\item \textbf{Explained genetic variance in the TS}. The training set is used to detect QTLs. These QTLs allow to evaluate the proportion of explained genetic variance in the TS using $\hat{p}_{TS} = \frac{R_{adj.TS}^{2}}{h^{2}}$ where $R_{adj.TS}^{2}$ is the adjusted $R^{2}$ (\ref{eq:29}) and $h^{2}$ the heritability to be specified by the user.
	
	\item \textbf{Predicted genetic variance in the VS}. We can now use the estimated QTL effects in the TS ($\bm{\hat{\beta}_{TS}}$) to predict phenotypic values in the VS ($\bm{\hat{y}_{VS}} = \bm{X_{VS}} \bm{\hat{\beta}_{TS}}$). The proportion of predicted genetic variance in the VS is $\hat{p}_{VS} = \frac{R_{VS}^{2}}{h^{2}}$, where $R_{VS}^{2}$ is the squared Pearson correlation between the observed and predicted values. $\hat{p}_{VS}$ is computed within cross. A measurement at the whole MPP level is obtained by calculating the weighted average of the within cross values ($\bar{p}_{VS}$) accounting for the cross sizes. The relative bias between $\hat{p}_{TS}$ and $\bar{p}_{VS}$ is $1-(\frac{\bar{p}_{VS}}{\hat{p}_{TS}})$.
	
\end{enumerate}


\section{Illustration: US-NAM population QTL analysis}
\label{sec:3}

\subsection{Overview}

\pkg{mppR} contains functions to perform all steps of an MPP QTL analysis, starting from the data processing to the visualisation of results. Figure~\ref{fig:2} shows a schematic representation of the \pkg{mppR} workflow. The first part concerns the raw data processing to gather all required data in a single \code{mppData} object. The \code{mppData} object can be used in the functions: \code{mpp_proc()}, \code{mpp_CV()} and \code{MQE_proc()} which are generic functions to perform QTL analyses, cross-validation, and multi-QTL effect model computations respectively.


\begin{figure}[!ht]
	\includegraphics[width=1\textwidth]{figures/Workflow2.jpg}
	\caption{mppR workflow.}
	\label{fig:2}
\end{figure}

\subsection{US-NAM data and raw data format}
\label{raw_data_form}

We included a subset of the maize US-NAM population \citep{mcmullen_2009} within the \pkg{mppR} package as example dataset to illustrate the different functions. We introduce these data and the required format to be used in the workflow presented in Figure~\ref{fig:2}.

<<package_load>>=
library(mppR)
@

The data consist of three parts obtained from \url{www.panzea.org}. \code{USNAM\_geno} is a random sample of the US-NAM population including the marker information of 506 genotypes and 102 markers. The entries include the parents and 500 recombinant inbred lines (RIL) coming from 5 crosses between the central line B73 and the peripheral parents CML103, CML322, CML52, Hp301, and M37W.

<<genotype_data>>=
data("USNAM_geno", package = "mppR")
dim(USNAM_geno)
rownames(USNAM_geno)[1:6]
table(substr(rownames(USNAM_geno)[-c(1:6)], 1, 4))
@

\subsubsection{Genotypic data}

Raw genotypic data used in \pkg{mppR} must be bi-allelic markers. The genotypic data are expected to be formatted as a \code{character matrix}, with one letter for each allele. So, when using the ACTG coding all possible genotypes are AA, CC, AC, etc. Missing values must always be coded \code{NA}. We impose a strict data format to make mppR functioning smoothly. Any deviation from this format will produce an informative error message. 

To start the data processing, the genotypic data must be split into offspring and parent genotype scores. These matrices represent the \code{geno.off} and \code{geno.par} arguments in the \code{create.mppData()} function. For these two arguments, the genotypes define the rows with genotype identifiers as row names and the markers are in columns with the marker identifiers as column names. The order of the markers must be the same as the one in the \code{map} argument. The \code{geno.off} genotypes list must also be in the same order as the one of the \code{pheno} argument.


<<off_par_genotype_data>>=
geno.off <- USNAM_geno[7:506, ]
geno.par <- USNAM_geno[1:6, ]
@

\subsubsection{Map data}

\code{USNAM\_map} is a three columns genetic map with marker indicator, chromosomes and map positions given in centi-Morgan (cM). It has the required format for the argument \code{map} in function \code{create.mppData()}. The marker identifiers must be \code{character}. The chromosomes and genetic positions must be \code{numeric}. The list of markers must be column names of the \code{geno.off} and \code{geno.par} arguments.

<<map_data>>=
data("USNAM_map", package = "mppR")
head(USNAM_map)
map <- USNAM_map
@

\subsubsection{Phenotypic data}

The file \code{USNAM\_pheno} is a \code{numeric matrix} containing the phenotypic measurements of 500 offspring genotypes for the trait upper leaf angle (ULA). The row names represent the genotype identifiers. They must be identical to the row names of \code{geno.off}. \code{USNAM\_pheno} can be used as \code{pheno} argument for the \code{create.mppData()} function. The \code{pheno} argument can contain several traits. A cross indicator \code{character vector} can be formed by subsetting the genotype names. It specifies to which cross each genotype belongs and can be used for the \code{cross.ind} argument in \code{create.mppData()}.

<<phenotype_data>>=
data("USNAM_pheno", package = "mppR")
head(USNAM_pheno)
pheno <-  USNAM_pheno
cross.ind <- substr(rownames(pheno), 1, 4)
@

\subsubsection{Cross parents information}

The last raw data source is provided via the \code{par.per.cross} argument. It is a three column \code{character matrix} with one row per cross specifying: 1) the cross indicator that must be identical and appear in the same order with the one used in \code{cross.ind} ; 2-3) the parents 1 and 2 of the crosses. The parents' identifiers must be identical to the row names of \code{geno.par}.

<<par.per.cross>>=
par.per.cross <- cbind(unique(cross.ind), rep("B73", 5),
                       rownames(geno.par)[2:6])
@

The \code{par.per.cross} matrix can be used in the \code{design_connectivity()} function to obtain and visualize the connected parts. For example using the illustration of Figure (\ref{fig:1}), we have

<<design_connectivity>>=
ppc_ex <- cbind(paste0("c", 1:7),
                c("PA", "PA", "PB", "PA", "PE", "PE", "PG"),
                c("PB", "PC", "PC", "PD", "PF", "PG", "PF"))

design_connectivity(ppc_ex)
@

For the next part of the illustration, we assume that the \code{geno.off}, \code{geno.par}, \code{map}, \code{pheno}, \code{cross.ind}, and \code{par.per.cross} objects are loaded in the global environment.

\subsection{Data processing}

The initial step is the processing of the raw data to gather all required data in a single \code{mppData} object. The functions \code{create.mppData()}, \code{QC.mppData()}, \code{IBS.mppData()}, \code{IBD.mppData()}, and \code{parent_cluster.mppData()} must be called in the defined sequence to form a complete \code{mppData} object. Any deviation from this sequence will be signaled by an error message.

\subsubsection{create a mppData object}

The function \code{create.mppData()} creates a unified \code{mppData} object containing all raw data sources.

<<create.mppData>>=
mppData <- create.mppData(geno.off = geno.off, geno.par = geno.par,
                          map = map, pheno = pheno, cross.ind = cross.ind,
                          par.per.cross = par.per.cross)
@

\subsubsection{Marker quality control - QC}
 
Before QTL analysis, the raw data should go through a quality control (QC). This procedure will ensure that marker format is correct and that markers are informative, meaning that their segregation rate is sufficient to provide a reliable basis to investigate and estimate the QTL effects. The function \code{QC.mppData()} performs a default QC.

The user should be aware that it is difficult to propose general settings for QC that will be suitable for all MPPs. Moreover, the type of model fitted should also guide the QC. For example, if the user wants to give more emphasis to the cross-specific model, the QC should ensure that there is enough within cross segregation. On the other hand, the bi-allelic model assumes that the QTLs segregate in the whole population. Therefore for this model, minimum segregation can be evaluated at the whole population level. The procedure implemented in \code{QC.mppData()} is the following:

\begin{enumerate}

\item Remove markers with more than two alleles.

\item Remove markers that are monomorphic or fully missing in the parents.

\item Remove markers with a missing rate higher than \code{mk.miss} across the entire MPP.

\item Remove genotypes with more missing markers than \code{gen.miss}.

\item Remove crosses with less than \code{n.lim} genotypes.

\item Keep only the most polymorphic marker when multiple markers map at the same position. 

\item Filter markers based on minor allele frequency (MAF). Different options are possible.

A) The first one filter marker based on MAF at the whole population
level, and/or on MAF within crosses. The markers with a MAF below a threshold given by \code{MAF.pop.lim} at the whole population level will be discarded.

The user can specify the  critical values for MAF within cross using \code{MAF.cr.lim}. By default, the within cross MAF values are defined by the following function of the cross-size $N_{c}$: $MAF(N_{c}) = 0.5$ if $N_{c} \in [0, 10]$ and $MAF(N_{c}) = (4.5/N_{c}) + 0.05$ if $N_{c} > 10$. This means that up to $10$ genotypes, the critical within cross MAF is set to $50\%$. Then it decreases when the number of genotype increases until $5\%$ set as a lower bound. 

If the within cross MAF is below the limit in at least one cross, then marker scores of the problematic cross are either put as missing (\code{MAF.cr.miss = TRUE}) or the whole marker is discarded (\code{MAF.cr.miss = FALSE}). By default, \code{MAF.cr.miss = TRUE}, which allows to include a larger number of markers and to cover a wider genetic diversity.

B) An alternative is to select only markers that segregate in at least one cross at the \code{MAF.cr.lim2} rate.

\end{enumerate}

<<QC.mppData>>=
mppData <- QC.mppData(mppData = mppData, n.lim = 15, MAF.pop.lim = 0.05,
                      MAF.cr.miss = TRUE, mk.miss = 0.1,
                      gen.miss = 0.25, verbose = TRUE)
@

\subsubsection{IBS processing}

To compute a bi-allelic model, the user needs to convert genotype data into IBS format using \code{IBS.mppData()}. This function transforms genotype scores into 0, 1, 2 coding where the score represents the number of minor allele copies.
%The user can also perform imputation of the missing values (\code{impute = TRUE}). Different options are available, some of them rely on the \code{codeGeno()} function from the package \pkg{synbreed} \citep{wimmer2012synbreed}.

<<IBS.mppData>>=
mppData <- IBS.mppData(mppData = mppData)

@

\subsubsection{IBD processing}

The other models (cross-specific, parental, and ancestral) use IBD probabilities. The function \code{IBD.mppData()} estimates IBD probabilities after converting the marker genotype data into within cross ABH format. For each cross, the maker scores of the two cross parents are used as reference. Homozygous offspring genotype scores similar to parent 1 get score \code{"A"} (\code{"B"} for parent 2). Heterozygous genotypes are scored \code{"H"}. If at least one of the parents is missing or the parents are monomorphic, the offspring will receive \code{NA}. The regular ABH conversion assumes that the reference parent scores are fully homozygous or missing. However, if some parent marker scores are heterozygous, the ABH conversion can still be performed setting argument \code{het.miss.par = TRUE}. In that case, when a parent score is heterozygous or missing and the other parent is homozygous, the function will try to infer the score of the allele that was transmitted by the heterozygous or the missing parent looking at the segregation pattern. Then the computation of the IBD probabilities is done by calling the function \code{calc.genoprob()} of the \proglang{R}/\pkg{qtl} package \citep{broman_rqtl}. For that purpose a temporary csv file, which can be loaded by \proglang{R}/\pkg{qtl}, will be saved at the location specified in \code{dir}.

The type of population must be specified in argument \code{type}. Different population types are possible: F-type ("F"), back-cross ("BC"), backcross followed by selfing ("BCsFt"), double haploid ("DH"), and recombinant imbred lines ("RIL"). The number of F and BC generations can be specified using \code{F.gen} and \code{BC.gen}. The agument \code{type.mating} specifies if F and RIL populations were obtained by selfing or by sibling mating. DH and RIL populations are read as back-cross by R/qtl. For these two population types, heterozygous scores will be treated as missing values.

<<IBD.mppData>>=
mppData <- IBD.mppData(mppData = mppData, het.miss.par = TRUE, type = 'RIL',
                       type.mating = 'selfing')
@

\subsubsection{Parent clustering}

The final step of data processing is to integrate the parent clustering information to the \code{mppData} object using the function \code{parent_cluster.mppData()}. The clustering of the parental lines is necessary to calculate the ancestral model. If the parent clustering is skipped, the other models (cross-specific, parental, bi-allelic) can still be computed.

At a single marker position, two parents can be grouped into a similar ancestral classes if we assume that they receive there allele from a common ancetor. The parent clustering information (\code{par.clu}) describe parental relatedness and which parent belong to which ancestral group. For example, at marker i, we could have five parents (pA, pB, pC, pD, pE) and the following clustering information (1, 2, 1, 2, 3). This means that pA and pC received their allele from the same ancetor (A1). pB and pD also have a shared ancestor (A2) who is different from (A1). And pE was not included in any group and can be seen as an indepedent ancestral group (A3).

The parent clustering information is provided via \code{par.clu}. It is an \code{interger matrix} with markers in row and parents in columns. At a particular marker position, parents with the same value are assumed to inherit from the same ancestor.

The parent clustering can be performed using the R package \pkg{clusthaplo} that can be found there: \url{https://cran.r-project.org/src/contrib/Archive/clusthaplo/}.
The clusthaplo option is not integrated in this version of mppR. However, a version of mppR with function calling clusthaplo can be found on github \url{https://github.com/vincentgarin/mppR}.


<<parent_clustering2>>=
data("par_clu", package = "mppR")

mppData <- parent_cluster.mppData(mppData = mppData, par.clu  = par_clu)

@

A summary of the \code{mppData} objects can be obtained calling the generic function \code{summary()}.

<<summary_mppData>>=
summary(mppData)
@


\subsection{mppData manipulation}

Subsets from \code{mppData} objects can be obtained using the generic fuction \code{subset()}. The \code{mppData} objects can be subsetted by markers (\code{mk.list}) and/or by genotypes (\code{gen.list}).

<<subset_mppData>>=
mppData_sub <- subset(x = mppData, mk.list = mppData$map[, 2] == 1,
                      gen.list = sample(mppData$geno.id, 200))
@


\subsection{QTL analysis}
  
When all data elements are ready, the user can start the QTL analysis. In all functions involving the computation of a QTL model (\code{mpp_CIM()}, \code{mpp_CV()}, \code{mpp_perm()}, \code{mpp_proc()}, \code{mpp_SIM()}, \code{MQE_proc()}, \code{QTL_gen_effects()}, etc.), the arguments \code{Q.eff} describes the type of QTL effect. \code{Q.eff} takes the values \code{"cr"}, \code{"par"}, \code{"anc"}, \code{"biall"} for the cross-specific, parental, ancestral, and bi-allelic model, respectively. A complete QTL analysis can be performed using the generic function \code{mpp_proc()}. This is a wrapping function for individual functions, indicated in parenthesis, performing each a part of the following QTL detection procedure:
  
\begin{enumerate}

\item SIM scan to select cofactors (\code{mpp_SIM()}).  In that case, we fit an ancestral model (\code{Q.eff = "anc"}).

\item Cofactor selection with SIM -log10($p$)~value above the \code{threshold} value with a minimum distance (\code{win.cof}) between selected positions (\code{QTL_select()}). The cofactor selection procedure is done per chromosome. It first selects the most significant position and then removes the positions in the neighbourhood of the selected position from the candidate list of QTLs/cofactors. The process continues until no position is significant anymore. The threshold (\code{thre.cof} or \code{thre.QTL}) values can be determined by permutation using \code{mpp_perm()}.

\item CIM scan (\code{mpp_CIM()}) using the selected cofactors except within an exclusion window (\code{window}) around the selected cofactors where they are excluded from the model. It is possible to perform several consecutive run of CIM using \code{N.cim} .

\item Selection of QTL candidates with CIM -log10($p$)~value above \code{thre.QTL} and a minimum distance (\code{win.QTL}) between the selected positions (\code{QTL_select()}). The selection procedure is the same as for the cofactors.

\item If \code{backward = TRUE}, backward elimination on the list of selected QTL positions (\code{mpp_back_elim()}).

\item Estimation of the QTLs genetic effects (\code{QTL_gen_effects()}), the global and partial QTLs $R^{2}$ (\code{QTL_R2()}).

\item If \code{CI = TRUE}, computation of QTL confidence intervals from a CIM- profile (excluding cofactors on the scanned chromosome). The confidence interval is based on a -log10($p$)~value drop-off value (\code{drop}).

\item plot of the -log10($p$)~value CIM QTL profile (\code{plot.QTLprof()}) and if \code{plot.gen.eff = TRUE}, visualisation of the genome-wide significance of the QTL effect per cross or per parent.

\end{enumerate}

<<mpp_proc>>=
QTL_proc <- mpp_proc(pop.name = "USNAM", trait.name = "ULA", trait = "ULA",
                     mppData = mppData, Q.eff = "anc",
                     plot.gen.eff = TRUE, N.cim = 1, thre.cof = 3,
                     win.cof = 20, window = 20, thre.QTL = 3,
                     win.QTL = 20, CI = TRUE, drop = 1.5,
                     verbose = FALSE, output.loc = tempdir())
@

The results of \code{mpp_proc()} are returned as a list of \proglang{R} objects. These results are also saved in different files at the location specified in argument \code{output.loc}. The created folder contains a report (QTL\_REPORT.txt) with a summary of results such as the number of detected QTL, the global $R^{2}$, and for each QTL the estimated genetic effects per cross or parent.

\subsection{Multi QTL Effect (MQE) model}

A multi-QTL effects model~\ref{MQE} can be determined using \code{MQE_proc()}. The user has to specify the types of tested QTL effects in the argument \code{Q.eff}. The \code{window} argument specifies the distance on both sides of an already detected QTL position where the search will be forbidden. A backward elimination on the final list of detected QTLs can be performed using (\code{backward = TRUE}). The results of the last MQE CIM run can be plotted using the function \code{MQE_plot()}. This \code{MQE_plot()} will colour the QTL positions corresponding to the type of QTL effect assumed at the position. This will be automatically done by \code{MQE_proc()} if \code{plot.MQE = TRUE}. The plot (plot\_MQE.pdf) will be saved with the other results at \code{output.loc}.

<<MQE, eval=FALSE, print=TRUE>>=
MQE <- MQE_proc(pop.name = "USNAM", trait.name = "ULA", mppData = mppData,
                Q.eff = c("par", "anc", "biall"), window = 20, verbose = FALSE,
                output.loc = tempdir())
@

\subsection{QTL effects estimation}

Once a list of QTL candidates has been determined, it is possible to estimate the QTL effect per cross or per parents (parental, ancestral, and bi-allelic model) using the function \code{QTL_gen_effects()}. For the cross-specific model (\code{Q.eff = "cr"}) (\ref{cr.mod}), the effects are given in absolute value and represent the substitution effect of one allele copy from the parent increasing the trait.

For the parental and ancestral models (\code{Q.eff = "par"} (\ref{par.mod}) or \code{Q.eff = "anc"} (\ref{anc.mod})), the QTL effects are given per parents and must be interpreted as deviation with respect to most frequent allele within the connected part set as reference. For the parental and ancestral models, the parental alleles are listed from the most (top) to the least frequent (bottom). For the ancestral model, parents with the same score correspond to the same ancestral allele according to \pkg{clusthaplo} results.

The QTL effects can also be calculated using the sum to zero constraint (\code{sum_zero = TRUE}). In that case individual parental (ancestral) allele effect represent deviation with respect to the average allelic effects. In a NAM population, all crosses are connected via the central parent (B73), which is the most frequent allele, and was therefore set as reference.

<<QTL_effect>>=
SIM <- mpp_SIM(mppData = mppData, Q.eff = "anc")
cofactors <- QTL_select(Qprof = SIM)
CIM <- mpp_CIM(mppData = mppData, Q.eff = "anc", cofactors = cofactors,
               plot.gen.eff = TRUE)
QTL <- QTL_select(Qprof = CIM)
gen.eff <- QTL_gen_effects(mppData = mppData, QTL = QTL, Q.eff = "anc")

summary(gen.eff, QTL = 1)
@


For the bi-allelic model (\ref{biall.mod}), the estimated genetic effect represents the additive effect of the minor allele with respect to the most frequent one, the latter set as reference. When parental genotype information is given, the results are given for each parent by multiplying the allele additive effect by the number of parent allele copies.

\subsubsection{Results visualisation}

A QTL profile can be obtained by passing the \code{mpp_SIM()} or \code{mpp_CIM()} results to the \code{x} argument of the function \code{plot.QTLprof()} (Figure~\ref{fig:3}). QTL or cofactors positions can also be plotted on the graph (dashed lines) using the argument \code{QTL}.

<<QTL_profile>>=
plot(x = CIM, QTL = QTL, type = "l")
@

\begin{figure}[!ht]
\includegraphics[width=1\textwidth]{figures/QTL_profile.pdf}
\caption{CIM QTL profile from an ancestral model using HRT. The cofactors positions are represented by vertical dashed lines.}
\label{fig:3}
\end{figure}

\code{Mpp_SIM()} or \code{mpp_CIM()} results obtained with \code{plot.gen.eff = TRUE} can also be passed to the function \code{plot.QTLprof()} with argument \code{gen.eff = TRUE} to obtain a visualisation of the genetic effect distribution along the genome (Figure~\ref{fig:4}). Once again, the positions passed to the \code{QTL} argument will be drawn on the graph.

<<gen_eff_plot>>=
plot(x = CIM, gen.eff = TRUE, mppData = mppData, QTL = QTL, Q.eff = "anc", main = 'QTL genetic effect plot')
@

\begin{figure}[!ht]
\includegraphics[width=1\textwidth]{figures/gen_eff2.pdf}
\caption{Visualisation genome-wide genetic effect significance from a CIM ancestral model using HRT. The vertical dashed lines represent the detected QTL positions.}
\label{fig:4}
\end{figure}

The interpretation of the genetic effect plot depends on the type of QTL effects. For a cross-specific model, blue colour means that the allele coming from parent 1(A) increases the trait value, red means that allele coming from parent 2(B) increases the trait.

For the parental and ancestral models, the effect must be interpreted as deviation with respect to the reference within a connected part. The reference allele is always defined as the most frequent allele. It can change at different positions. Therefore, it is not possible to establish a unique reference allele for the whole genome. The parental alleles significances are assessed per connected part. The blue (red) colour means that the parental allele decrease (increase) the trait value. Parents are ordered from the top to the bottom given the number of times their allele was set as reference in the whole genome. For example the upper parent was the one for which its allele was the highest number of times set as reference in the whole genome. These plots should be interpreted as a rough indication of signal distribution.

\subsection{Cross-validation}

The cross-validation procedure (\ref{CV}) can be performed by the function \code{mpp_CV()}. The arguments \code{Rep} and \code{k} represent the number of repetitions of the k-fold procedure. The heritability, allowing to express $R^{2}$ in terms of percentage of the explained genotypic variance, can be specified in \code{her}. By default \code{her = 1}, therefore the results are expressed in terms of phenotypic variation. The results of the CV procedure will be saved in a folder at \code{output.loc}. A transparency plot of the CV QTL profiles (Figure~\ref{fig:5})  will also be saved at \code{output.loc}.



<<CV_proc>>=
set.seed(89341)

CV <- mpp_CV(pop.name = "USNAM", trait.name = "ULA", mppData = mppData,
             Q.eff = "cr", her = 0.4, Rep = 1, k = 3, verbose = FALSE,
             output.loc = tempdir())
@

\begin{figure}[!ht]
\includegraphics[width=1\textwidth]{figures/plot_CV.pdf}
\caption{Transparency plot of CV results representing an overlay of QTL profiles. The black bars are proportional to the number of times a position was detected as QTL.}
\label{fig:5}
\end{figure}


\subsection{Parallelization}

All functions involving genome scan(s) (\code{mpp_perm()}, \code{mpp_SIM()}, \code{mpp_CIM()}, \code{mpp_proc()}, \code{mpp_CV()} or \code{MQE_proc()}) can be executed in parallel. The number of cores can be specified using \code{n.cores}. Parallelization is done using functions from the \pkg{parallel} library.


\section{Summary}

\pkg{mppR} is a package for QTL analysis in multi-parent populations working in the \proglang{R} environment. It can analyse any type of MPP design composed of more than one cross between at least three parents like NAM populations, diallels or factorial designs, where individual crosses are of the Fx, BCx, BCsFt, RIL or DH type. It contains functions to perform all the steps of the QTL detection from the data processing to the results visualisation.


\section*{Acknowledgements}

The development of \pkg{mppR} is part of a project financed by KWS Saat SE.


%% include your article here, just as usual
%% Note that you should use the \pkg{}, \proglang{} and \code{} commands.

% Bibliography

\bibliography{bibliography/Bibliography_Bibtex}

\end{document}