---
title: DeLorean analysis of Kouno et al. THP-1 human myeloid monocytic leukemia data
author: John Reid
bibliography: DeLorean.bib
output:
  html_document:
    toc: true
    fig_caption: true
---

```{r build, echo=FALSE, eval=FALSE}
devtools::load_all('..')
fit.model <- TRUE
rmarkdown::render('Kouno-DeLorean.Rmd')

```

<!--
%\VignetteEngine{knitr::rmarkdown}
%\VignetteIndexEntry{DeLorean analysis of THP-1 human myeloid monocytic leukemia data}
-->


```{r config, echo=FALSE, message=FALSE}
library(knitr)
library(knitcitations)
library(rmarkdown)
#
# knitr options
#
opts_chunk$set(
    fig.path = 'figures/Kouno-',
    stop_on_error = TRUE,
    fig.width = 12.5,
    fig.height = 8)
#
# Citations
#
cleanbib()
cite_options(
    # hyperlink = 'to.doc',
    hyperlink = TRUE,
    # style = 'html',
    # citation_format = 'text',
    citation_format = "pandoc",
    cite.style = "numeric",
    check.entries = TRUE)
    # hyperlink = TRUE)
bib <- read.bibtex("DeLorean.bib")
if (file.exists("config.R")) {
    source("config.R")
}
source(system.file("scripts/shared.R", package="DeLorean"))

```

```{r loadLibs, echo=FALSE, message=FALSE}
# suppressMessages(loadfonts())
library(DeLorean)
#
# Stylesheet
#
options(markdown.HTML.stylesheet = system.file(file.path('Rmd', 'foghorn.css'),
                                               package="DeLorean"))
font.family <- "Verdana"
font.theme <- theme_update(text=element_text(family=font.family))
theme_set(font.theme)

```

`r date()`


`r citet(bib[["kouno_temporal_2013"]])` assayed 120 single cells at each
of 8 time points.


# Data

Kouno et al.'s data is available in the `DeLorean` R package.
```{r loadLib, eval=fit.model}
library(DeLorean)
data(KounoDeLorean)

```


Adjust the observed capture times to distances similar to Kouno et al.'s
MDS plot.
```{r adjustCaptureTimes}
kouno.cell.meta.adj.time <- (
    kouno.cell.meta
    %>% mutate(obstime=ifelse(capture== "0h",  0,
                       ifelse(capture== "1h",  6,
                       ifelse(capture== "6h", 10,
                       ifelse(capture=="12h", 11,
                       ifelse(capture=="24h", 12,
                       ifelse(capture=="48h", 13,
                       ifelse(capture=="72h", 14,
                       ifelse(capture=="96h", 15,
                              NA))))))))))

```

Build the `DeLorean` object.
```{r buildDL, eval=fit.model}
dl <- de.lorean(
    kouno.expr,
    kouno.gene.meta,
    kouno.cell.meta.adj.time)

```

This will load a 45 (genes) by 960 (cells) matrix containing the expression
measurements.
```{r exprDim, eval=fit.model}
dim(dl)
```
and two data frames of meta data for the genes and cells.
```{r meta, eval=fit.model}
sample_n(dl$gene.meta, 15)
sample_n(dl$cell.meta, 15)
```
```{r child=report.file("data")}
```


# Estimate hyperparameters

Examine data for empirical Bayes estimation of hyperparameters.
```{r empiricalBayes, eval=fit.model}
dl <- estimate.hyper(dl, sigma.tau=3)
```
```{r child=report.file("hyper-parameters")}
```


# Choose genes and cells

Choose genes.
```{r filterGenes, eval=fit.model}
set.seed(1)
max.genes <- min(getOption("Kouno.num.genes", nrow(dl$gene.meta)))
genes.for.stan <- sample(dl$gene.meta$gene, max.genes)
gene.filter <- function(genes) genes %in% genes.for.stan
dl <- filter.genes(dl, gene.filter)

```

Choose a few cells from each stage.
```{r filterCells, eval=fit.model}
num.at.each.stage <- getOption("Kouno.num.each.stage", 7)
sampled.cells <- (
    dl$cell.meta
    %>% group_by(capture)
    %>% do(sample_n(., num.at.each.stage))
)
cell.filter <- function(cells) cells %in% sampled.cells$cell
dl <- filter.cells(dl, cell.filter)
```


Save expression data and meta data.
```{r saveInput, eval=fit.model}
saveRDS(list(expr = dl$expr, cell.meta = dl$cell.map, gene.meta=dl$gene.map),
        file='Data/Kouno-input.rds')

```

Format the data for Stan and fit the model.
```{r fitModel, eval=fit.model}
dl <- prepare.for.stan(dl)
dl <- compile.model(dl)
dl <- find.best.tau(dl)
system.time(dl <- fit.model(dl, num.cores=getOption("DL.num.cores")))

```


# Examine convergence.

```{r examConv}
dl <- examine.convergence(dl)
```
```{r child=report.file("convergence")}
```


# Analyse posterior

Examine posterior.
```{r posterior}
dl <- process.posterior(dl)
dl <- analyse.noise.levels(dl)

```
```{r child=report.file("posterior")}
```


# Profiles

Calculate expression profiles.
```{r makePredictions}
dl <- make.predictions(dl)
```
```{r child=report.file("profiles")}
```



```{r echo=FALSE}
# Save DeLorean object without fit component
saveRDS({dl2 <- dl; dl2$fit <- NULL; dl2}, "Data/Kouno.rds")
```


R version and packages used:
```{r Rversion}
date()
sessionInfo()
```
