## ----echo=FALSE, results="hide"-----------------------------------------------
knitr::opts_chunk$set(error=FALSE, message=FALSE, warning=FALSE, comment = "")
library(BiocStyle)
self <- Biocpkg("augere.core")

## ----echo=FALSE, comment=""---------------------------------------------------
template <- "# Data loading

~~~{r}
:BEGIN data
:END
~~~

# Preprocessing

~~~{r}
y <- SummarizedExperiment::assay(se)
d <- edgeR::DGEList(y)
d <- d[edgeR::filterByExpr(d),]
d <- edgeR::normLibSizes(d)
d$samples
~~~

# Variance modelling

~~~{r}
design <- model.matrix(<%= FORMULA %>, colData(se))
v <- limma::voom(d, design, plot=TRUE)
fit <- limma::lmFit(v, design)
fit <- limma::eBayes(fit, robust=<%= ROBUST %>)
~~~

# Testing for differences

~~~{r}
res <- limma::topTable(fit, n=Inf)
~~~

Saving the result:

~~~{r saveme}
write.csv(res, 'de.csv')
~~~"
template <- gsub("~~~", "```", template)
cat(template)

## -----------------------------------------------------------------------------
library(augere.core)
demo.pipeline <- function(
    x,
    formula,
    output.dir='.',
    robust=TRUE,
    dry.run=FALSE,
    save.results=TRUE
) {
    restore.cache <- resetInputCache()
    on.exit(restore.cache(), add=TRUE, after=FALSE)

    report.text <- parseRmdTemplate(template)
    report.text[["data"]] <- processInputCommands(x, "se")
    report.text <- replacePlaceholders(
        report.text,
        c(
            FORMULA=paste(as.character(formula), collapse=""),
            ROBUST=deparseToString(robust)
        )
    )

    dir.create(output.dir, showWarnings=FALSE, recursive=TRUE)
    fname <- file.path(output.dir, "report.Rmd")
    writeRmd(report.text, fname)
    if (dry.run) {
        return(invisible(NULL))
    }

    env <- new.env()
    to.skip <- NULL
    if (!save.results) {
        to.skip <- "saveme"
    }
    compileReport(fname, env, skip.chunks=to.skip)
    env$res
}

## ----fig.show="hide"----------------------------------------------------------
library(airway)
data(airway)
output.dir <- tempfile()
res <- demo.pipeline(airway, formula=~dex, output.dir=output.dir)
head(res)

## -----------------------------------------------------------------------------
# Looking at the top few lines of the report.
fname <- file.path(output.dir, "report.Rmd")
contents <- readLines(fname)
cat(head(contents, 30), sep="\n")

## -----------------------------------------------------------------------------
sessionInfo()

