%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Authors: Henrik Bengtsson
% Created on: 2011-09-30
% Last updated: See HISTORY below.
%
% Usage: (compiles *.tex.rsp => tex.rsp.R => *.tex => *.dvi)
%  R.rsp::rsp("PairedPSCBS.tex.rsp", path="reports,rsp/");
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

<%
library("PSCBS");
library("R.devices");
library("R.cache");
library("R.utils"); # setOption()
stopifnot(exists("rspArgs", mode="list"));
%>


<%
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
# REPORT CONFIGURATION
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
REPORT_DENSITIES <- getOption("PSCBS::reports/densities", TRUE);
REPORT_TUMORBOOST <- getOption("PSCBS::reports/TumorBoost", TRUE);
REPORT_USE_ALPHA_CHANNEL <- getOption("PSCBS::report/useAlphaChannel", TRUE);
REPORT_PER_CHROMOSOME <- getOption("PSCBS::reports/perChromosome", TRUE);
REPORT_C1C2 <- getOption("PSCBS::reports/pscnSegmentationTransitions", FALSE);
# To implement:
REPORT_PER_GENOTYPE <- getOption("PSCBS::reports/perGenotype", TRUE);
%>



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LATEX STARTUP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[twoside,12pt]{report}
\usepackage{fancyvrb}
\usepackage{xspace}
\usepackage{subfigure}  % \subfigure[<title>]{}
\usepackage[round]{natbib}

\addtolength{\oddsidemargin}{-0.5in}
\addtolength{\evensidemargin}{-0.5in}
\addtolength{\textwidth}{1in}
\addtolength{\topmargin}{-0.8in}
\addtolength{\textheight}{1.3in}

\renewcommand{\topfraction}{1.00}   % max fraction of floats at top
\renewcommand{\bottomfraction}{1.0} % max fraction of floats at bottom
\renewcommand{\textfraction}{0.00}

\usepackage{fancyhdr}
\pagestyle{fancy}
%% \fancyhead{} % clear all header fields
%% \fancyfoot{} % clear all footer fields
%% \fancyhead[LE,RO]{\slshape \rightmark}
%% \fancyfoot[C]{\thepage}

\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[RE]{\textit{\nouppercase{\leftmark}}}
\fancyhead[LO]{\textit{\nouppercase{\rightmark}}}

\newcommand{\code}[1]{\texttt{#1}\xspace}


\newcommand{\TCN}{TCN\xspace}
\newcommand{\BAF}{\BAF\xspace}
\newcommand{\BAFN}{BAF$_{N}$\xspace}
\newcommand{\BAFT}{BAF$_{T}$\xspace}
\newcommand{\BAFTN}{BAF$^*_{T}$\xspace}


<% pairedPSCBSReport <- function(fit, sampleName=NULL, dataSet=NULL, studyName="PairedPSCBS", Clim=c(0,4), Blim=c(0,1), reportPath=file.path("reports", studyName), figPath=file.path(reportPath, "figures"), ..., figForce=FALSE) { %>
<%
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Validate arguments
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Argument 'fit':
fit <- Arguments$getInstanceOf(fit, "PairedPSCBS");

# Argument 'sampleName':
if (is.null(sampleName)) {
  sampleName <- sampleName(fit);
}
sampleName <- Arguments$getCharacter(sampleName);

# Argument 'dataSet':
if (!is.null(dataSet)) {
  dataSet <- Arguments$getCharacter(dataSet);
}

# Argument 'studyName':
studyName <- Arguments$getCharacter(studyName);

# Argument 'reportPath':
reportPath <- Arguments$getWritablePath(reportPath);

# Argument 'figPath':
figPath <- Arguments$getWritablePath(figPath);

# Argument 'figForce':
figForce <- Arguments$getLogical(figForce);
%>

<%
oFigPath <- setOption("devEval/args/path", figPath);
on.exit({
  setOption("devEval/args/path", oFigPath);
}, add=TRUE);

oPar <- setOption("devNew/args/par", list(lwd=2));
on.exit({
  setOption("devNew/args/par", oPar);
}, add=TRUE);
%>

<%
studyLbl <- sprintf("Study: %s\\\\", toLatex(studyName));
if (!is.null(dataSet)) {
  dataSetLbl <- sprintf("Data set: %s\\\\", toLatex(dataSet));
} else {
  dataSetLbl <- "";
}
%>

\title{Paired PSCBS Report:\\<%=studyLbl%><%=dataSetLbl%>Sample: <%=toLatex(sampleName)%>}
\author{Report template by Henrik Bengtsson}

% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% GRAPHICS SETTINGS
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<%
setOption("devEval/args/force", figForce);
%>
\usepackage{graphicx}
\graphicspath{{<%=figPath%>/} {../<%=figPath%>/}} 

<%
# GGPLOT2 SETTINGS
ClimX <- Clim + c(-1,1)*diff(Clim)*0.08;
BlimX <- Blim + c(-1,1)*diff(Blim)*0.08;

muNCols <- c("#999999", "#000000", "#999999");

require("ggplot2") || throw("Package not loaded: ggplot2");
xnbrOpts <- element_text(colour="grey50", size=20, hjust=1, lineheight=0.9);
ynbrOpts <- element_text(colour="grey50", size=20, vjust=1, lineheight=0.9);
xlabOpts <- element_text(colour="black", size=28, hjust=0.5);
ylabOpts <- element_text(colour="black", size=28, vjust=0.5, angle=90);

labList <- list(
  CT    = expression(C[T]),
  betaN = expression(beta[N]),
  betaT = expression(beta[T]),
  betaTN = expression(tilde(beta)[T]),
  rho = expression(rho),
  rhoN = expression(tilde(rho)),
  c1 = expression(C[1]),
  c2 = expression(C[2]),
  c1N = expression(tilde(C)[1]),
  c2N = expression(tilde(C)[2])
);

symbolList <- list(
  CT    = "$C_{T}$",
  betaN = "$\\beta_{N}$",
  betaT = "$\\beta_{T}$",
  betaTN = "$\\tilde{\\beta}_{T}$",
  rho = "$\\rho$",
  rhoN = "$\\tilde{\\rho}$",
  c1 = "$C_{1}$",
  c2 = "$C_{2}$",
  c1N = "$\\tilde{C}_{1}$",
  c2N = "$\\tilde{C}_{2}$"
);
%>

\begin{document}

\maketitle
\begin{abstract}
This is a quality control (QC) report on the paired tumor-normal sample '<%=toLatex(sampleName)%>' in data set '<%=toLatex(dataSet)%>'.
\end{abstract}

\tableofcontents

\clearpage


%>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Introduction}

\chapter{Data}
\label{ch:Data}

\section{Samples}

\section{Microarray data}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% METHODS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Methods}
\label{ch:Methods}

\section{Segmentation}
\label{sec:Segmentation}
We use the Paired PSCBS segmentation method~\citep{OlshenA_etal_2011} with TumorBoost normalization~\citep{BengtssonH_etal_2010} to partion the genome into segments such that all signals in a particular segment are likely to originate from the same underlying parent-specific copy-number state.
Germline genotypes are called based on the normal allele B fractions (BAFs), cf.~\citet{BengtssonH_etal_2010}.


<%--
\section{Post-segmentation pruning}
\label{sec:PostSegmentationPruning}
<%
fitP <- pruneByHClust(fit, h=0.25);
#print(fitP);
%>
--%>



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RESULTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% WHOLE-GENOME RESULTS
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
\chapter{Whole-Genome Results}
\label{ch:WholeGenomeResults}


% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% SUMMARY ANNOTATION AND GENOTYPE CALLS
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% summaryOfAnnotationAndGenotypeCalls <- function(fit, ...) { %>
\section{Summary of annotation and genotype calls}
<%
data <- getLocusData(fit, fields="full");
nbrOfLoci <- nrow(data);
nbrOfSNPs <- sum(data$isSNP, na.rm=TRUE);
nbrOfHets <- sum(data$isHet, na.rm=TRUE);

chromosomes <- getChromosomes(fit);
nbrOfChromosomes <- length(chromosomes);
chromosomesH <- seqToHumanReadable(chromosomes);
chromosomesH <- if (nbrOfChromosomes == 1) {
  sprintf("Chr %s", chromosomesH);
} else {
  sprintf("Chrs %s", chromosomesH);
}
chrsTags <- if (nbrOfChromosomes == 1) {
  sprintf("chr%02d", chromosomes[1]);
} else {
  sprintf("chrs%02d-%02d", min(chromosomes), max(chromosomes));
}
%>

\begin{table}[htbp]
 \begin{center}
  \begin{tabular}{lrr}
   Description & Count & Fraction \\
   \hline
   Number of loci & <%=nbrOfLoci%> & 100.00\% \\
   Number of SNPs & <%=nbrOfSNPs%> & <%=sprintf("%.2f", 100*nbrOfSNPs/nbrOfLoci)%>\% \\
   Number of heterozygous SNPs* & <%=nbrOfHets%> & <%=sprintf("%.2f", 100*nbrOfHets/nbrOfSNPs)%>\% \\
   Number of non-polymorphic loci & <%=nbrOfLoci-nbrOfSNPs%> & <%=sprintf("%.2f", 100*(1-nbrOfSNPs/nbrOfLoci))%>\% \\
   Number of chromosomes & <%=nbrOfChromosomes%> & - \\
  \end{tabular}
  \caption{
  Summary of the locus-level data on <%=chromosomesH%>.
  A locus is considered to be a SNP if it has either a non-missing BAF for either the tumor or the normal.
  (*) Genotype calls are based on (whole-genome) naive genotyping of the germline BAFs.
  }
  \label{tbl:LocusStats}
 \end{center}
\end{table}

<% } # summaryOfAnnotationAndGenotypeCalls() %>


<%=summaryOfAnnotationAndGenotypeCalls(fit)%>


% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% SIGNAL DENSITIES
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% signalDensities <- function(fit, ...) { %>
<% if (!REPORT_DENSITIES) return(); %>
\clearpage
\section{Signal densities}
\label{sec:SignalDensities}
<%
require("ggplot2") || throw("Package not loaded: ggplot2");
data <- getLocusData(fit, fields="full");
chromosomes <- getChromosomes(fit);
nbrOfChromosomes <- length(chromosomes);
chromosomesH <- seqToHumanReadable(chromosomes);
chromosomesH <- if (nbrOfChromosomes == 1) {
  sprintf("Chr %s", chromosomesH);
} else {
  sprintf("Chrs %s", chromosomesH);
}
chrsTags <- if (nbrOfChromosomes == 1) {
  sprintf("chr%02d", chromosomes[1]);
} else {
  sprintf("chrs%02d-%02d", min(chromosomes), max(chromosomes));
}
%>
<% if (nrow(data) >= 2L) { %>
\begin{figure}[htbp]
 \begin{center}
<%
 fields <- c("CT", "betaN", "betaT", "rho", "c1", "c2", "betaTN", "rhoN", "c1N", "c2N");
 fields <- intersect(fields, colnames(data))
%>
<% for (ff in fields) { %>
<%
  symbol <- symbolList[[ff]];
  panelTitle <- switch(ff, CT="\\TCN", betaN="\\BAFN", betaT="\\BAFT", betaTN="\\BAFTN", "NNN");
  lim <- switch(ff, CT=ClimX, c1=ClimX, c2=ClimX, c1N=ClimX, c2N=ClimX, BlimX);
  nbrOfSNPs <- sum(data$isSNP, na.rm=TRUE)
%>
\raisebox{4ex}{<%=symbol%>}
<% for (by in c("all", "muN")) { %>
<%
  tags <- c(chrsTags, by, ff);
%>
    \resizebox{0.33\textwidth}{!}{%
      \includegraphics{<%={
        toPNG(name=sampleName, tags=tags, width=640, aspectRatio=0.3, {
          gg <- ggplot(data, aes_string(x=ff, y="..count.."));

          if (by == "all") {
            if (ff == "CT" && nbrOfSNPs > 0 && any(!data$isSNP, na.rm=TRUE)) {
              gg <- gg + aes(group=type, colour=type);
            }
          } else if (by == "muN") {
            gg <- gg + aes_string(group="muNx", colour="muNx");
            gg <- gg + scale_color_manual(values=muNCols);
          }
 
          # See https://github.com/hadley/ggplot2/wiki/Legend-Attributes
          gg <- gg + theme(legend.position=c(0.97, 0.75),
                           legend.justification = 1,
                           legend.direction="vertical",
                           legend.title=element_text(size=0),
                           legend.text=element_text(size=16));
 
          gg <- gg + geom_density(size=2, na.rm=TRUE);
          gg <- gg + xlab(NULL);
          gg <- gg + ylab(NULL);
          gg <- gg + xlim(lim);
          gg <- gg + theme(axis.text.x=xnbrOpts, axis.text.y=ynbrOpts);
          gg <- gg + theme(axis.title.x=xlabOpts, axis.title.y=ylabOpts);
          suppressWarnings({
            print(gg);
          });
        }, force=FALSE);
      }%>}%
    }%
<% } # for (by ...) %>
\\ %
<% } # for (ff ...) %>
 \end{center}
 \caption{
   Density estimates of locus-level signals on <%=chromosomesH%> with and without TumorBoost normalization.  The signals in the left and right panels are without and with stratification on genotype calls (AA and BB in gray and AB in black).
   We expect to see three genotype groups for the normal BAFs ($\beta_{N}$).
   The tumor BAFs ($\beta_{T}$) should be more distinct after normalization
    ($\tilde{\beta}_{T}$), particularly for homozygous SNPs.
   If there are no allelic imbalances in the tumor, then the density of 
   the tumor should be similar to that of the normal.
 }
 \label{fig:SignalDensity}
\end{figure}
<% } else { %>
NOTE: No density plots produced for <%= chromosomesH %> because there are fewer than two loci.
<% } ## if (nrow(data) >= 2L) %>
<% } # signalDensities() %>

<%=signalDensities(fit)%>


% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% BEFORE AND AFTER TUMORBOOST
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% beforeAndAfterTumorBoost <- function(fit, ...) { %>
<%
data <- getLocusData(fit, fields="full");
## Nothing to do?
if (!all(is.element(c("betaN", "betaT", "type"), colnames(data)))) return()
%>
<% if (!REPORT_TUMORBOOST) return(); %>
\clearpage
\section{Before and after TumorBoost}
\label{sec:BeforeAndAfterTumorBoost}
\begin{figure}[htbp]
 \begin{center}
<%
require("ggplot2") || throw("Package not loaded: ggplot2");
chromosomes <- getChromosomes(fit);
nbrOfChromosomes <- length(chromosomes);
chromosomesH <- seqToHumanReadable(chromosomes);
chromosomesH <- if (nbrOfChromosomes == 1) {
  sprintf("Chr %s", chromosomesH);
} else {
  sprintf("Chrs %s", chromosomesH);
}
chrsTags <- if (nbrOfChromosomes == 1) {
  sprintf("chr%02d", chromosomes[1]);
} else {
  sprintf("chrs%02d-%02d", min(chromosomes), max(chromosomes));
}
%>
<%
dataT <- subset(data, type == "SNP");
%>
<% for (ff in c("betaT", "betaTN")) { %>
  \resizebox{0.40\textwidth}{!}{%
    \includegraphics{<%={
      tags <- c(chrsTags, sprintf("%s-vs-betaN", ff));
      toPNG(name=sampleName, tags=tags, width=640, aspectRatio=0.85, {
        gg <- ggplot(dataT, aes_string(x="betaN", y=ff));
        gg <- gg + aes_string(group="muNx", colour="muNx");
        gg <- gg + scale_color_manual(values=muNCols);

        # See https://github.com/hadley/ggplot2/wiki/Legend-Attributes
        gg <- gg + theme(#legend.position=c(0.97, 0.85),
                         #legend.justification = 1,
                         legend.direction="vertical",
                         legend.title=element_text(size=0),
                         legend.text=element_text(size=16));

        if (REPORT_USE_ALPHA_CHANNEL) {
          gg <- gg + geom_point(alpha=min(10e3/nrow(dataT), 0.5), na.rm=TRUE);
        } else {
          gg <- gg + geom_point(na.rm=TRUE);
        }
        gg <- gg + xlab(labList[["betaN"]]) + ylab(labList[[ff]]);
        gg <- gg + xlim(BlimX) + ylim(BlimX);
        gg <- gg + theme(axis.text.x=xnbrOpts, axis.text.y=ynbrOpts);
        gg <- gg + theme(axis.title.x=xlabOpts, axis.title.y=ylabOpts);
        print(gg);
      });
    }%>}%
  }%
<% } # for (ff ...) %>
 \end{center}
 \caption{
   Tumor-normal BAFs before (left) and after (right) TumorBoost normalization
   on <%=chromosomesH%>.
   We expect to see only two homozygote groups.  If there are more, then the
   tumor and the normal BAFs are not from the same individual.
   If there are no allelic imbalances in the tumor, then there is
   also only one heterozygous group.
 }
 \label{fig:BAFBAF}
\end{figure}
<% } # beforeAndAfterTumorBoost() %>

<%=beforeAndAfterTumorBoost(fit)%>



% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% PARENT-SPECIFIC COPY-NUMBER SEGMENTATION TRACKS
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% pscnSegmentationTracks <- function(fit, ...) { %>
\clearpage
\section{Parent-specific copy-number segmentation tracks}
\label{sec:PSCNSegmentationTracks}
<%
chromosomes <- getChromosomes(fit);
nbrOfChromosomes <- length(chromosomes);
chromosomesH <- seqToHumanReadable(chromosomes);
chromosomesH <- if (nbrOfChromosomes == 1) {
  sprintf("Chr %s", chromosomesH);
} else {
  sprintf("Chrs %s", chromosomesH);
}
chrsTags <- if (nbrOfChromosomes == 1) {
  sprintf("chr%02d", chromosomes[1]);
} else {
  sprintf("chrs%02d-%02d", min(chromosomes), max(chromosomes));
}
%>
\begin{figure}[htbp]
 \begin{center}
  <% for (track in c("tcn", "dh", "tcn,c1,c2")) { %>
<%-- <% for (track in c("tcn*", "betaT", "betaTN*", "dh*", "tcn*,c1*,c2-*")) { %> --%>
  \resizebox{\textwidth}{!}{%
    \includegraphics{<%={
      tags <- c(chrsTags, "PairedPSCBS", gsub("[*-]", "", track), getChecksum(fit));
      toPNG(name=sampleName, tags=tags, width=1024, aspectRatio=0.25, par=list(mar=c(2.8,4,1,1)+0.1, cex=1.5), {
        plotTracks(fit, tracks=track, lwd=5, Clim=Clim);
#        plotTrack2(fit, panels=track, lwd=5, Clim=Clim);
      }, force=FALSE);
    }%>}%
  }%
  \\
  <% } # for (track ...) %>
 \end{center}
 \caption{
   Results of Paired PSCBS segmentation on <%=chromosomesH%> projected onto
   TCN (top), \BAFT (row 2), \BAFTN (row 3), DH (row 4), as well as TCN, $C_1$ and $C_2$ (bottom).
   Paired PSCBS segmentation is always done on TCN and DH data.
   There are in total $S=<%=nbrOfSegments(fit, splitters=FALSE)%>$ segments. 
 }
 \label{fig:PairedPSCBS}
\end{figure}
<% } # pscnSegmentationTracks() %>

<%=pscnSegmentationTracks(fit)%>



% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% PARENT-SPECIFIC COPY-NUMBER TRANSITIONS
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% pscnSegmentationTransitions <- function(fit, ...) { %>
<% if (!REPORT_C1C2) return(); %>
\clearpage
\section{Parent-specific copy-number transitions}
\label{sec:PSCNSegmentationTransitions}
<%
# plotC1C2Grid()
require("aroma.cn") || throw("Package not loaded: aroma.cn");

chromosomes <- getChromosomes(fit);
nbrOfChromosomes <- length(chromosomes);
chromosomesH <- seqToHumanReadable(chromosomes);
chromosomesH <- if (nbrOfChromosomes == 1) {
  sprintf("Chr %s", chromosomesH);
} else {
  sprintf("Chrs %s", chromosomesH);
}
chrsTags <- if (nbrOfChromosomes == 1) {
  sprintf("chr%02d", chromosomes[1]);
} else {
  sprintf("chrs%02d-%02d", min(chromosomes), max(chromosomes));
}
%>
\begin{figure}[htbp]
 \begin{center}
  \resizebox{0.6\textwidth}{!}{%
    \includegraphics{<%={
      tags <- c(chrsTags, "PairedPSCBS", "C1C2", getChecksum(fit));
      toPNG(name=sampleName, tags=tags, width=640, aspectRatio=1, par=list(mar=c(4,4,1,1)+0.1, cex=2), {
        plotC1C2Grid(fit, Clim=ClimX);
        linesC1C2(fit, lwd=2);
      }, force=FALSE);
    }%>}%
  }%
 \end{center}
 \caption{
   A graph representation of the minor ($C_1$) and major ($C_2$) 
   copy-number segmentation on <%=chromosomesH%>,
   where the nodes represent ($S=<%=nbrOfSegments(fit, splitters=FALSE)%>$)
   segments and the lines change points.
   The size of a node reflects the length of the corresponding segment.
   The marginal distributions (gray curves) of the minor and the major CNs 
   are projected onto the horizontal and vertical axis, respectively.
   To easy a visual comparison, the latter is also projected onto the
   horizontal axis (light blue curve).
 }
 \label{fig:C1C2}
\end{figure}
<% } # pscnSegmentationTransitions() %>

<%=pscnSegmentationTransitions(fit)%>


% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% NORMAL CONTAMINATION
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% pscnNormalContamination <- function(fit, ...) { %>
\clearpage
\section{Normal contamination}
\label{sec:PSCNNormalContamination}
<%
## Attempt to estimate kappa
kappa <- tryCatch(estimateKappa(fit, ...), error = identity)
if (inherits(kappa, "error")) { %>
The estimation of normal contamination failed, which typically happens when the parent-specific copy numbers are too noisy or when there are too few parent-specific copy-number events occuring in the tumor.  Details: The reason reported by \code{estimateKappa()} was: <%= conditionMessage(kappa) %>.
<% } else { %>
The estimated amount of normal contamination of this sample is <%= sprintf("%.1f", 100*kappa) %>\% ($\kappa = <%= sprintf("%.3f", kappa) %>$).  This estimate, which is provided due to popular demand, is also affected by other types of background signals, which may be specific to sample or batch.  Because of this, great care should be taken when interpreting this estimate and using it in downstream analysis.  Being conservative, we recommend to \emph{not} to use it as an accurate estimate of the \emph{true} amount of normal contamination.  However, if the sample and batch-specific effects are small, estimates from multiple samples may compared with each other, i.e. samples can be ranked by their \emph{relative amount of normal contamination} (which might be done also when the absolute values cannot be trusted).
<% } %>
<% } # pscnNormalContamination() %>

<%=pscnNormalContamination(fit)%>



% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% PER CHROMOSOME SEGMENTATION
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
<% if (REPORT_PER_CHROMOSOME && nbrOfChromosomes(fit) > 1) { %>
<% for (chr in getChromosomes(fit)) { %>
\chapter{Chromosome <%=chr%> Results}
\label{sec:Chromosome<%=chr%>Results}
<%
fitT <- extractChromosome(fit, chromosome=chr);
%>
<%=summaryOfAnnotationAndGenotypeCalls(fitT)%>

<%=signalDensities(fitT)%>

<%=beforeAndAfterTumorBoost(fitT)%>

<%=pscnSegmentationTracks(fitT)%>

<%=pscnSegmentationTransitions(fitT)%>
<% } # for (chr ...) %>
<% } # if (REPORT_PER_CHROMOSOME && nbrOfChromosomes(fit) > 1) %>


<%--
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% PRUNED: WHOLE-GENOME SEGMENTATION
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
\section{Hierarchical pruning}
\label{sec:HierarchicalPruning}

% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% PRUNED: PER CHROMOSOME SEGMENTATION
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
--%>


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% REFERENCES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \clearpage
\bibliography{bioinformatics-journals-abbr,PSCBS}
%\bibliographystyle{plain}
\bibliographystyle{natbib}


\appendix
\chapter{Appendix}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Session information
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \clearpage
\section*{Session information}
<%=toLatex(sessionInfo())%>
This report was automatically generated using \code{rsp()} of the R.rsp package.
The template for this report was created by Henrik Bengtsson on April 20, 2012.
\end{document}

<% } # pairedPSCBSReport() %>

<%=do.call("pairedPSCBSReport", args=rspArgs)%>



<%
######################################################################
# RSP CLOSEUP
######################################################################
# Function for renaming report afterwards
assign("renamePDF", function() {
  filename <- sprintf("%s,report.pdf", studyName);
  pathname <- file.path(reportPath, filename);
  file.rename("report.pdf", pathname);
}, envir=globalenv());
%>

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HISTORY:
% 2016-05-11
% o Updated to handle PairedPSCBS objects with only 'rho' but no
%   'betaN' and 'betaT'.
% 2014-05-24
% o Replaced a deprecated opts() of ggplot2 with theme().
% 2013-10-18
% o BUG FIX: Report template assumed that R.utils was attached.
% 2012-11-03
% o Replaced deprecated ggplot2 functions.
% 2012-09-16
% o Added easy report configuration at the very top.
% 2012-05-30
% o Removed ggplot2 warnings on missing values.
% 2012-02-28
% o Now it is possible to turn off usage of the alpha channel in
%   plots, e.g. setOption("PSCBS::report/useAlphaChannel", FALSE).
%   This is useful for if the alpha channel is not supported.
% 2012-02-27
% o First successful run with real data.
% o Now all of the report uses a PairedPSCBS object.
% o Now making more use of templates.
% o Now passing a data frame to segmentByPairedCBS().
% 2011-09-30
% o Created.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
