---
title: "Dockerized R Markdown Document with Rabix Support"
author: "Nan Xiao"
date: "`r Sys.Date()`"
output:
  html_document:
    highlight: pygments
    theme: cosmo
liftr:
  from: "rocker/r-base:latest"
  maintainer: "Nan Xiao"
  maintainer_email: "nanx@uchicago.edu"
  syslib:
    - samtools
  biocpkg:
    - Rsamtools
    - Gviz
  rabix: true
  rabix_json: "https://s3.amazonaws.com/rabix/rabix-test/bwa-mem.json"
  rabix_d: "~/liftr_rabix/bwa/"
  rabix_args:
    - reference: "https://s3.amazonaws.com/rabix/rabix-test/chr20.fa"
    - reads: "https://s3.amazonaws.com/rabix/rabix-test/example_human_Illumina.pe_1.fastq"
    - reads: "https://s3.amazonaws.com/rabix/rabix-test/example_human_Illumina.pe_2.fastq"
---

## Alignment coverage visualization example

This is an R Markdown document that could be rendered under a Docker container using `liftr`. It also contains information about a Rabix tool `bwa-mem.json`, which will be ran by Rabix before rendering the document in a Docker container. In this way, the output of the Rabix tool/workflow can be used and analyzed in the document.

The document depends on the `samtools` software package in Ubuntu; `Rsamtools` and `Gviz` package on Bioconductor. `liftr` will:

  * Run the Rabix tool `bwa-mem.json` defined in the metadata;
  * Use `samtools` installed in the Docker container to convert the output of the tool, `output.sam` to a BAM file;
  * Use the Bioconductor packages `Rsamtools` and `Gviz` to index the BAM file and visualize the alignment coverage.

```{r samtools}
# convert SAM file to BAM file directly using samtools
system("samtools view -bS bwa/output.sam > bwa/output.bam")

# sort the output bam file with samtools
system("samtools sort bwa/output.bam bwa/output.sorted")
```

```{r Rsamtools}
library("Rsamtools")
indexBam("bwa/output.sorted.bam")
```

```{r bamplot}
suppressMessages(library("Gviz"))
bam = "bwa/output.sorted.bam"
dtrack = DataTrack(range = bam, genome = "hg19",
                   type = "l", name = "Coverage",
                   window = -1, chromosome = "chr20")
# plot alignment coverage at given position
plotTracks(dtrack, from = 29622700, to = 29630000)
```

## Options of liftr in this document

The document front-matter metadata includes the options for `liftr`, which is used for dockerizing the document and running the Rabix tool `bwa-mem.json`:

```{r liftrmeta}
rmarkdown::metadata$liftr
```

## System and session information

The location of `samtools` and R session information of the Docker container is shown below.

```{r session}
Sys.which("samtools")
sessionInfo()
```
