%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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");
stopifnot(exists("rspArgs", mode="list"));
%>


<%
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# REPORT CONFIGURATION
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
REPORT_DENSITIES <- getOption("PSCBS::reports/densities", FALSE);
REPORT_TUMORBOOST <- getOption("PSCBS::reports/TumorBoost", FALSE);
REPORT_USE_ALPHA_CHANNEL <- getOption("PSCBS::report/useAlphaChannel", TRUE);
REPORT_PER_CHROMOSOME <- getOption("PSCBS::reports/perChromosome", TRUE);
REPORT_C1C2 <- getOption("PSCBS::reports/pscnSegmentationTransitions", TRUE);
REPORT_C1C2_DESHEARING <- getOption("PSCBS::reports/c1C2Deshearing", TRUE);
REPORT_C1C2_DESHEARING_KAPPA <- getOption("PSCBS::reports/c1C2DeshearingKappa", TRUE);

# 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,5), 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 <- theme_text(colour="grey50", size=20, hjust=1, lineheight=0.9);
ynbrOpts <- theme_text(colour="grey50", size=20, vjust=1, lineheight=0.9);
xlabOpts <- theme_text(colour="black", size=28, hjust=0.5);
ylabOpts <- theme_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 '<%=sampleName%>' in data set '<%=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));
}
%>
\begin{figure}[htbp]
 \begin{center}
<%
 fields <- c("CT", "betaN", "betaT", "rho", "c1", "c2", "betaTN", "rhoN", "c1N", "c2N");
%>
<% 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);
%>
\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" && 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 + opts(legend.position=c(0.97, 0.75),
                          legend.justification = 1,
                          legend.direction="vertical",
                          legend.title=theme_text(size=0),
                          legend.text=theme_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 + opts(axis.text.x=xnbrOpts, axis.text.y=ynbrOpts);
          gg <- gg + opts(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}
<% } # signalDensities() %>

<%=signalDensities(fit)%>


% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% BEFORE AND AFTER TUMORBOOST
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<% beforeAndAfterTumorBoost <- function(fit, ...) { %>
<% 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");
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));
}
%>
<%
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 + opts(#legend.position=c(0.97, 0.85),
                        #legend.justification = 1,
                        legend.direction="vertical",
                        legend.title=theme_text(size=0),
                        legend.text=theme_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 + opts(axis.text.x=xnbrOpts, axis.text.y=ynbrOpts);
        gg <- gg + opts(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, chromosomes=NULL, ...) { %>
\clearpage
<%
postMethods <- names(fit$postMethods);
deShearC1C2 <- is.element("deShearC1C2", postMethods);
bgCorrection <- is.element("backgroundCorrection", postMethods);

if (!is.null(chromosomes)) {
  fit <- extractChromosomes(fit, chromosomes=chromosomes);
}
%>
<% if (deShearC1C2 && bgCorrection) { %>
\section{PSCN segments after de-shearing and background correction}
\label{sec:PSCNSegmentationTracksAfterDeshearingAndBgCorrection}
<% } else if (deShearC1C2) { %>
\section{PSCN segments after de-shearing}
\label{sec:PSCNSegmentationTracksAfterDeshearing}
<% } else { %>
\section{PSCN segments}
\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{<%={
      # saveObject(fit, file="fool.Rbin")
      tags <- c(chrsTags, "PairedPSCBS", gsub("[*-]", "", track), getChecksum(fit));
      nChrs <- nbrOfChromosomes(fit);
      mar <- c(1.4,4,0.6,1)+0.1;
      if (nChrs == 1) mar <- c(2.0,4,1.1,1)+0.1;
      toPNG(name=sampleName, tags=tags, width=1024, aspectRatio=0.25, par=list(mar=mar, cex=1.5), {
        scatter <- if (deShearC1C2) NULL else "*";
        calls <- if (deShearC1C2) NULL else "*";
        plotTracks(fit, tracks=track, scatter=scatter, calls=calls, lwd=5, Clim=Clim, add=(nChrs > 1));
      }, force=FALSE);
    }%>}%
  }%
  \\
  <% } # for (track ...) %>
 \end{center}
 \caption{
   Results of Paired PSCBS segmentation
   <%=ifelse(deShearC1C2, "after de-shearing", "")%>
   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, chromosomes=NULL, kappa=NULL, ...) { %>
<% if (!REPORT_C1C2) return(); %>
\clearpage
<%
postMethods <- names(fit$postMethods);
deShearC1C2 <- is.element("deShearC1C2", postMethods);
bgCorrection <- is.element("backgroundCorrection", postMethods);

# Get deShear model fit, iff exists
modelFitD <- fit$postMethods$deShearC1C2$modelFit;
cpAngleDensityD <- modelFitD$debug$cpAngleDensity;

# Subset by chromosome?
if (!is.null(chromosomes)) {
  fit <- extractChromosomes(fit, chromosomes=chromosomes);
}
%>
<% if (deShearC1C2 && bgCorrection) { %>
\section{PSCN transitions after de-shearing and background correction}
\label{sec:PSCNSegmentationTransitionsAfterDeshearingAndBgCorrection}
<% } else if (deShearC1C2) { %>
\section{PSCN transitions after de-shearing}
\label{sec:PSCNSegmentationTransitionsAfterDeshearing}
<% } else { %>
\section{PSCN transitions}
\label{sec:PSCNSegmentationTransitions}
<% } %>

<%
# plotC1C2Grid() is needed
require("aroma.cn") || throw("Package not loaded: aroma.cn");

# Estimate CP angular density
modelFit <- fitDeltaC1C2ShearModel(fit, onError="return");
cpAngleDensity <- modelFit$debug$cpAngleDensity;

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}
  \parbox[t]{0.6\textwidth}{\vspace{0pt}%
  \resizebox{0.6\textwidth}{!}{%
    \includegraphics{<%={
      tags <- c(chrsTags, "PairedPSCBS", "C1C2");
      if (deShearC1C2) {
        tags <- c(tags, "deSheared");
      }
      tags <- c(tags, getChecksum(fit));
      toPNG(name=sampleName, tags=tags, width=640, aspectRatio=1, par=list(mar=c(4,4,1.02,1)+0.1, cex=2), {
        plotC1C2Grid(fit, Clim=ClimX, pch=19, col="#00000011");
        stext(side=3, pos=1, chrsTags, cex=0.8);
        linesC1C2(fit, lwd=2, col="#00000011");
        if (!is.null(kappa)) {
          abline(v=kappa, col="red", lty=3, lwd=2);
        }
      }, force=FALSE);
    }%>}%
  }%
  }% \parbox[t]{0.6\textwidth}
%%
  \parbox[t]{0.38\textwidth}{\vspace{0pt}%
  <% if (!is.null(cpAngleDensity)) { %>
  \resizebox{0.38\textwidth}{!}{%
    \includegraphics{<%={
      tags <- c(chrsTags, "PairedPSCBS", "CPAngleDensity", getChecksum(fit));
      toPNG(name=sampleName, tags=tags, width=640, aspectRatio=0.7, par=list(mar=c(4,4,2,2)+0.1, cex=2), {
        debug <- modelFit$debug;
        maxY <- max(c(cpAngleDensity$y, cpAngleDensityD$y), na.rm=TRUE);
        plot(cpAngleDensity, ylim=c(0,maxY), lwd=2, main="");
        if (!is.null(cpAngleDensityD)) lines(cpAngleDensityD, lwd=2, col="lightblue");
        lines(cpAngleDensity, lwd=2);
        expected <- debug$expected;
        if (!is.null(expected)) {
          abline(v=expected);
          text(x=expected, y=par("usr")[4], names(expected), adj=c(0.5,-0.5), cex=1.5, xpd=TRUE);
        }
 
        # Annotate called peaks, iff possible
        pfpD <- modelFitD$debug$pfp;
        expectedD <- modelFitD$debug$expected;
        if (!is.null(pfpD) && !is.null(expectedD)) {
          idxs <- match(pfpD$call, expectedD);
          text(x=pfpD$x, y=pfpD$density, names(expectedD)[idxs], adj=c(0.5,-0.5), cex=1.5, xpd=TRUE, col="blue");
        }

##        stext(side=4, pos=0, sampleName);
##        stext(side=4, pos=1, nCPsTag);
      }, force=FALSE);
    }%>}%
  }\\%
  <% } # if (!is.null(cpAngleDensity)) %>
  ~
  }%\parbox[t]{0.38\textwidth}
 \end{center}
 \caption{
   \textbf{Left:}
   A graph representation of the minor ($C_1$) and major ($C_2$)
   copy-number segmentation on <%=chromosomesH%><%=if (deShearC1C2) " after de-shearing"%>,
   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).
   <% if (!is.null(kappa)) { %>
   The background signal was estimated to $\kappa=<%=sprintf("%.3f", kappa)%>$ (vertical dashed red line).
   <% } %>
   \textbf{Right:}
   The empirical density of the directions of the ($P=<%=nbrOfChangePoints(fit)%>$) change points in ($C_1,C_2$) in copy-number segmentation on <%=chromosomesH%><%=if (deShearC1C2) " after de-shearing"%>.
   <% if (is.null(cpAngleDensity)) { %>
   \emph{There were too change points for estimating the density.}
   <% } # if (is.null(cpAngleDensity)) %>
 }
 \label{fig:C1C2}
\end{figure}
<% } # pscnSegmentationTransitions() %>

<%
kappa <- estimateKappa(fit);
%>
<%=pscnSegmentationTransitions(fit, kappa=kappa)%>

<%
if (REPORT_C1C2_DESHEARING) {
  fitD <- deShearC1C2(fit);
  kappaD <- estimateKappa(fitD);
  pscnSegmentationTracks(fitD, kappa=kappaD);
  pscnSegmentationTransitions(fitD, kappa=kappaD);
}
%>

<%
if (REPORT_C1C2_DESHEARING_KAPPA) {
  # Remove background and rescale
  fitDn <- backgroundCorrect(fitD, targetMedian=2);

  # Estimate background for rescale data
  kappaDn <- estimateKappa(fitDn);

  pscnSegmentationTracks(fitDn, kappa=kappaDn);
  pscnSegmentationTransitions(fitDn, kappa=kappaDn);
}
%>



% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% 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(fit, chromosomes=chr)%>

<%=pscnSegmentationTransitions(fit, chromosomes=chr, kappa=kappa)%>

<%
if (REPORT_C1C2_DESHEARING) {
  pscnSegmentationTracks(fitD, chromosomes=chr);
  pscnSegmentationTransitions(fitD, chromosomes=chr, kappa=kappaD);
}
%>

<%
if (REPORT_C1C2_DESHEARING_KAPPA) {
  pscnSegmentationTracks(fitDn, chromosomes=chr, kappa=kappaDn);
  pscnSegmentationTransitions(fitDn, chromosomes=chr, kappa=kappaDn);
}
%>


<% } # 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:
# 2013-04-08
# o Now loading R.devices package.
# 2012-09-23
# o Now display background and rescale corrected.
# 2012-09-22
# o Now displaying raw, desheared, and kappa corrected.
# 2012-09-19
% o Created from PairedPSCBS report template.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
