---
title: "ChIP-Seq Workflow Template"
author: "Author: Daniela Cassol (danielac@ucr.edu) and Thomas Girke (thomas.girke@ucr.edu)"
date: "Last update: `r format(Sys.time(), '%d %B, %Y')`"
output:
BiocStyle::html_document:
toc_float: true
code_folding: show
BiocStyle::pdf_document: default
package: systemPipeR
vignette: |
%\VignetteEncoding{UTF-8}
%\VignetteIndexEntry{ChIP-Seq Workflow Template}
%\VignetteEngine{knitr::rmarkdown}
fontsize: 14pt
bibliography: bibtex.bib
---
```{css, echo=FALSE}
pre code {
white-space: pre !important;
overflow-x: scroll !important;
word-break: keep-all !important;
word-wrap: initial !important;
}
```
```{r style, echo = FALSE, results = 'asis'}
BiocStyle::markdown()
options(width=60, max.print=1000)
knitr::opts_chunk$set(
eval=as.logical(Sys.getenv("KNITR_EVAL", "TRUE")),
cache=as.logical(Sys.getenv("KNITR_CACHE", "TRUE")),
tidy.opts=list(width.cutoff=60), tidy=TRUE)
```
```{r setup, echo=FALSE, messages=FALSE, warnings=FALSE, eval=FALSE}
suppressPackageStartupMessages({
library(systemPipeR)
library(BiocParallel)
library(Biostrings)
library(Rsamtools)
library(GenomicRanges)
library(ggplot2)
library(GenomicAlignments)
library(ShortRead)
library(ape)
library(batchtools)
})
```
# Introduction
Users want to provide here background information about the design of their ChIP-Seq project.
## Background and objectives
This report describes the analysis of several ChIP-Seq experiments
studying the DNA binding patterns of the transcriptions factors ... from *organism* ....
## Experimental design
Typically, users want to specify here all information relevant for the
analysis of their NGS study. This includes detailed descriptions of
FASTQ files, experimental design, reference genome, gene annotations,
etc.
# Workflow environment
## Generate workflow environment
Load workflow environment with sample data into your current working
directory. The sample data are described
[here](http://www.bioconductor.org/packages/devel/bioc/vignettes/systemPipeR/inst/doc/systemPipeR.html#load-sample-data-and-workflow-templates).
```{r genChip_workflow, eval=FALSE}
library(systemPipeRdata)
genWorkenvir(workflow="chipseq")
setwd("chipseq")
```
Alternatively, this can be done from the command-line as follows:
```{sh genChip_workflow_command_line, eval=FALSE}
Rscript -e "systemPipeRdata::genWorkenvir(workflow='chipseq')"
```
In the workflow environments generated by `genWorkenvir` all data inputs are stored in
a `data/` directory and all analysis results will be written to a separate
`results/` directory, while the `systemPipeChIPseq.Rmd` script and the `targets` file are expected to be located in the parent directory. The R session is expected to run from this parent directory. Additional parameter files are stored under `param/`.
To work with real data, users want to organize their own data similarly
and substitute all test data for their own data. To rerun an established
workflow on new data, the initial `targets` file along with the corresponding
FASTQ files are usually the only inputs the user needs to provide.
## Run workflow
Now open the R markdown script `systemPipeChIPseq.Rmd` in your R IDE (_e.g._ vim-r or RStudio) and run the workflow as outlined below.
### Run R session on computer node
After opening the `Rmd` file of this workflow in Vim and attaching a connected
R session via the `F2` (or other) key, use the following command sequence to run your R
session on a computer node.
```{r closeR, eval=FALSE}
q("no") # closes R session on head node
```
```{bash node_environment, eval=FALSE}
srun --x11 --partition=short --mem=2gb --cpus-per-task 4 --ntasks 1 --time 2:00:00 --pty bash -l
module load R/3.4.2
R
```
Now check whether your R session is running on a computer node of the cluster and assess your environment.
```{r r_environment, eval=FALSE}
system("hostname") # should return name of a compute node starting with i or c
getwd() # checks current working directory of R session
dir() # returns content of current working directory
```
The `systemPipeR` package needs to be loaded to perform the analysis steps shown in
this report [@H_Backman2016-bt].
```{r load_systempiper, eval=TRUE}
library(systemPipeR)
```
If applicable users can load custom functions not provided by `systemPipeR`. Skip
this step if this is not the case.
```{r load_custom_fct, eval=FALSE}
source("systemPipeChIPseq_Fct.R")
```
# Read preprocessing
## Experiment definition provided by `targets` file
The `targets` file defines all FASTQ files and sample comparisons of the analysis workflow.
```{r load_targets_file, eval=TRUE}
targetspath <- system.file("extdata", "targets_chip.txt", package="systemPipeR")
targets <- read.delim(targetspath, comment.char = "#")
targets[1:4,-c(5,6)]
```
## Read quality filtering and trimming
The following example shows how one can design a custom read
preprocessing function using utilities provided by the `ShortRead` package, and then
apply it with `preprocessReads` in batch mode to all FASTQ samples referenced in the
corresponding `SYSargs` instance (`args` object below). More detailed information on
read preprocessing is provided in `systemPipeR's` main vignette.
```{r proprocess_reads, eval=FALSE, messages=FALSE, warning=FALSE, cache=TRUE}
args <- systemArgs(sysma="param/trim.param", mytargets="targets_chip.txt")
filterFct <- function(fq, cutoff=20, Nexceptions=0) {
qcount <- rowSums(as(quality(fq), "matrix") <= cutoff, na.rm=TRUE)
fq[qcount <= Nexceptions]
# Retains reads where Phred scores are >= cutoff with N exceptions
}
preprocessReads(args=args, Fct="filterFct(fq, cutoff=20, Nexceptions=0)",
batchsize=100000)
writeTargetsout(x=args, file="targets_chip_trim.txt", overwrite=TRUE)
```
## FASTQ quality report
The following `seeFastq` and `seeFastqPlot` functions generate and plot a series of useful quality statistics for a set of FASTQ files including per cycle quality box
plots, base proportions, base-level quality trends, relative k-mer
diversity, length and occurrence distribution of reads, number of reads
above quality cutoffs and mean quality distribution. The results are
written to a PDF file named `fastqReport.pdf`.
```{r fastq_report, eval=FALSE}
args <- systemArgs(sysma="param/tophat.param", mytargets="targets_chip.txt")
library(BiocParallel); library(batchtools)
f <- function(x) {
library(systemPipeR)
args <- systemArgs(sysma="param/tophat.param", mytargets="targets_chip.txt")
seeFastq(fastq=infile1(args)[x], batchsize=100000, klength=8)
}
moduleload(modules(args)) # Skip if a module system is not used
resources <- list(walltime=120, ntasks=1, ncpus=cores(args), memory=1024)
param <- BatchtoolsParam(workers = 4, cluster = "slurm", template = "batchtools.slurm.tmpl", resources = resources)
fqlist <- bplapply(seq(along=args), f, BPPARAM = param)
pdf("./results/fastqReport.pdf", height=18, width=4*length(fqlist))
seeFastqPlot(unlist(fqlist, recursive=FALSE))
dev.off()
```
![](results/fastqReport.png)
Figure 1: FASTQ quality report for 18 samples
# Alignments
## Read mapping with `Bowtie2`
The NGS reads of this project will be aligned with `Bowtie2` against the
reference genome sequence [@Langmead2012-bs]. The parameter settings of the
aligner are defined in the `bowtieSE.param` file. In ChIP-Seq experiments it is
usually more appropriate to eliminate reads mapping to multiple locations. To
achieve this, users want to remove the argument setting `-k 50 non-deterministic`
in the `bowtieSE.param` file.
The following submits 18 alignment jobs via a scheduler to a computer cluster.
```{r bowtie2_align, eval=FALSE}
args <- systemArgs(sysma="param/bowtieSE.param",
mytargets="targets_chip_trim.txt")
sysargs(args)[1] # Command-line parameters for first FASTQ file
moduleload(modules(args)) # Skip if a module system is not used
system("bowtie2-build ./data/tair10.fasta ./data/tair10.fasta")
# Indexes reference genome
resources <- list(walltime=120, ntasks=1, ncpus=cores(args), memory=1024)
reg <- clusterRun(args, conffile = ".batchtools.conf.R", Njobs=18, template = "batchtools.slurm.tmpl", runid="01", resourceList=resources)
getStatus(reg=reg)
waitForJobs(reg=reg)
writeTargetsout(x=args, file="targets_bam.txt", overwrite=TRUE)
```
Alternatively, one can run the alignments sequentially on a single system.
```{r bowtie2_align_seq, eval=FALSE}
runCommandline(args)
```
Check whether all BAM files have been created
```{r check_files_exist, eval=FALSE}
file.exists(outpaths(args))
```
## Read and alignment stats
The following provides an overview of the number of reads in each sample
and how many of them aligned to the reference.
```{r align_stats, eval=FALSE}
read_statsDF <- alignStats(args=args)
write.table(read_statsDF, "results/alignStats.xls", row.names=FALSE,
quote=FALSE, sep="\t")
read.delim("results/alignStats.xls")
```
## Create symbolic links for viewing BAM files in IGV
The `symLink2bam` function creates symbolic links to view the BAM alignment files in a
genome browser such as IGV without moving these large files to a local
system. The corresponding URLs are written to a file with a path
specified under `urlfile`, here `IGVurl.txt`.
```{r symbol_links, eval=FALSE}
symLink2bam(sysargs=args, htmldir=c("~/.html/", "somedir/"),
urlbase="http://biocluster.ucr.edu/~tgirke/",
urlfile="./results/IGVurl.txt")
```
# Utilities for coverage data
The following introduces several utilities useful for ChIP-Seq data. They are not part of the actual workflow.
## Rle object stores coverage information
```{r rle_object, eval=FALSE}
library(rtracklayer); library(GenomicRanges)
library(Rsamtools); library(GenomicAlignments)
aligns <- readGAlignments(outpaths(args)[1])
cov <- coverage(aligns)
cov
```
## Resizing aligned reads
```{r resize_align, eval=FALSE}
trim(resize(as(aligns, "GRanges"), width = 200))
```
## Naive peak calling
```{r rle_slice, eval=FALSE}
islands <- slice(cov, lower = 15)
islands[[1]]
```
## Plot coverage for defined region
```{r plot_coverage, eval=FALSE}
library(ggbio)
myloc <- c("Chr1", 1, 100000)
ga <- readGAlignments(outpaths(args)[1], use.names=TRUE,
param=ScanBamParam(which=GRanges(myloc[1],
IRanges(as.numeric(myloc[2]), as.numeric(myloc[3])))))
autoplot(ga, aes(color = strand, fill = strand), facets = strand ~ seqnames,
stat = "coverage")
```
# Peak calling with MACS2
## Merge BAM files of replicates prior to peak calling
Merging BAM files of technical and/or biological replicates can improve
the sensitivity of the peak calling by increasing the depth of read
coverage. The `mergeBamByFactor` function merges BAM files based on grouping information
specified by a `factor`, here the `Factor` column of the imported targets file. It
also returns an updated `SYSargs` object containing the paths to the
merged BAM files as well as to any unmerged files without replicates.
This step can be skipped if merging of BAM files is not desired.
```{r merge_bams, eval=FALSE}
args <- systemArgs(sysma=NULL, mytargets="targets_bam.txt")
args_merge <- mergeBamByFactor(args, overwrite=TRUE)
writeTargetsout(x=args_merge, file="targets_mergeBamByFactor.txt", overwrite=TRUE)
```
```{r call_peaks_macs_envVar_settings, eval=FALSE}
# Skip if a module system is not used
module("list")
module("unload", "miniconda2")
module("load", "python/2.7.14") # Make sure to set up your enviroment variable for MACS2
```
## Peak calling without input/reference sample
MACS2 can perform peak calling on ChIP-Seq data with and without input
samples [@Zhang2008-pc]. The following performs peak calling without
input on all samples specified in the corresponding `args` object. Note, due to
the small size of the sample data, MACS2 needs to be run here with the
`nomodel` setting. For real data sets, users want to remove this parameter
in the corresponding `*.param` file(s).
```{r call_peaks_macs_noref, eval=FALSE}
args <- systemArgs(sysma="param/macs2_noinput.param",
mytargets="targets_mergeBamByFactor.txt")
sysargs(args)[1] # Command-line parameters for first FASTQ file
runCommandline(args)
file.exists(outpaths(args))
writeTargetsout(x=args, file="targets_macs.txt", overwrite=TRUE)
```
## Peak calling with input/reference sample
To perform peak calling with input samples, they can be most
conveniently specified in the `SampleReference` column of the initial
`targets` file. The `writeTargetsRef` function uses this information to create a `targets`
file intermediate for running MACS2 with the corresponding input samples.
```{r call_peaks_macs_withref, eval=FALSE}
writeTargetsRef(infile="targets_mergeBamByFactor.txt",
outfile="targets_bam_ref.txt", silent=FALSE, overwrite=TRUE)
args_input <- systemArgs(sysma="param/macs2.param",
mytargets="targets_bam_ref.txt")
sysargs(args_input)[1] # Command-line parameters for first FASTQ file
runCommandline(args_input)
file.exists(outpaths(args_input))
writeTargetsout(x=args_input, file="targets_macs_input.txt", overwrite=TRUE)
```
The peak calling results from MACS2 are written for each sample to
separate files in the `results` directory. They are named after the corresponding
files with extensions used by MACS2.
## Identify consensus peaks
The following example shows how one can identify consensus preaks among two peak sets sharing either a minimum absolute overlap and/or minimum relative overlap using the `subsetByOverlaps` or `olRanges` functions, respectively. Note, the latter is a custom function imported below by sourcing it.
```{r consensus_peaks, eval=FALSE}
source("http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/My_R_Scripts/rangeoverlapper.R")
peak_M1A <- outpaths(args)["M1A"]
peak_M1A <- as(read.delim(peak_M1A, comment="#")[,1:3], "GRanges")
peak_A1A <- outpaths(args)["A1A"]
peak_A1A <- as(read.delim(peak_A1A, comment="#")[,1:3], "GRanges")
(myol1 <- subsetByOverlaps(peak_M1A, peak_A1A, minoverlap=1))
# Returns any overlap
myol2 <- olRanges(query=peak_M1A, subject=peak_A1A, output="gr")
# Returns any overlap with OL length information
myol2[values(myol2)["OLpercQ"][,1]>=50]
# Returns only query peaks with a minimum overlap of 50%
```
# Annotate peaks with genomic context
## Annotation with `ChIPpeakAnno` package
The following annotates the identified peaks with genomic context information using the `ChIPpeakAnno` and `ChIPseeker` packages, respectively [@Zhu2010-zo; @Yu2015-xu].
```{r chip_peak_anno, eval=FALSE}
library(ChIPpeakAnno); library(GenomicFeatures)
args <- systemArgs(sysma="param/annotate_peaks.param",
mytargets="targets_macs.txt")
# txdb <- loadDb("./data/tair10.sqlite")
txdb <- makeTxDbFromGFF(file="data/tair10.gff", format="gff", dataSource="TAIR",
organism="Arabidopsis thaliana")
ge <- genes(txdb, columns=c("tx_name", "gene_id", "tx_type"))
for(i in seq(along=args)) {
peaksGR <- as(read.delim(infile1(args)[i], comment="#"), "GRanges")
annotatedPeak <- annotatePeakInBatch(peaksGR, AnnotationData=genes(txdb))
df <- data.frame(as.data.frame(annotatedPeak),
as.data.frame(values(ge[values(annotatedPeak)$feature,])))
write.table(df, outpaths(args[i]), quote=FALSE, row.names=FALSE, sep="\t")
}
writeTargetsout(x=args, file="targets_peakanno.txt", overwrite=TRUE)
```
```{r chip_peak_anno_full_annotation, include=FALSE, eval=FALSE}
## Perform previous step with full genome annotation from Biomart
# txdb <- makeTxDbFromBiomart(biomart = "plants_mart", dataset = "athaliana_eg_gene", host="plants.ensembl.org")
# tx <- transcripts(txdb, columns=c("tx_name", "gene_id", "tx_type"))
# ge <- genes(txdb, columns=c("tx_name", "gene_id", "tx_type")) # works as well
# seqlevels(ge) <- c("Chr1", "Chr2", "Chr3", "Chr4", "Chr5", "ChrC", "ChrM")
# table(mcols(tx)$tx_type)
# tx <- tx[!duplicated(unstrsplit(values(tx)$gene_id, sep=","))] # Keeps only first transcript model for each gene]
# annotatedPeak <- annotatePeakInBatch(peaksGR, AnnotationData = tx)
```
The peak annotation results are written for each peak set to separate
files in the `results` directory. They are named after the corresponding peak
files with extensions specified in the `annotate_peaks.param` file,
here `*.peaks.annotated.xls`.
## Annotation with `ChIPseeker` package
Same as in previous step but using the `ChIPseeker` package for annotating the peaks.
```{r chip_peak_seeker, eval=FALSE}
library(ChIPseeker)
for(i in seq(along=args)) {
peakAnno <- annotatePeak(infile1(args)[i], TxDb=txdb, verbose=FALSE)
df <- as.data.frame(peakAnno)
write.table(df, outpaths(args[i]), quote=FALSE, row.names=FALSE, sep="\t")
}
writeTargetsout(x=args, file="targets_peakanno.txt", overwrite=TRUE)
```
Summary plots provided by the `ChIPseeker` package. Here applied only to one sample
for demonstration purposes.
```{r chip_peak_seeker_plots, eval=FALSE}
peak <- readPeakFile(infile1(args)[1])
covplot(peak, weightCol="X.log10.pvalue.")
peakHeatmap(outpaths(args)[1], TxDb=txdb, upstream=1000, downstream=1000,
color="red")
plotAvgProf2(outpaths(args)[1], TxDb=txdb, upstream=1000, downstream=1000,
xlab="Genomic Region (5'->3')", ylab = "Read Count Frequency")
```
# Count reads overlapping peaks
The `countRangeset` function is a convenience wrapper to perform read counting
iteratively over serveral range sets, here peak range sets. Internally,
the read counting is performed with the `summarizeOverlaps` function from the
`GenomicAlignments` package. The resulting count tables are directly saved to
files, one for each peak set.
```{r count_peak_ranges, eval=FALSE}
library(GenomicRanges)
args <- systemArgs(sysma="param/count_rangesets.param",
mytargets="targets_macs.txt")
args_bam <- systemArgs(sysma=NULL, mytargets="targets_bam.txt")
bfl <- BamFileList(outpaths(args_bam), yieldSize=50000, index=character())
countDFnames <- countRangeset(bfl, args, mode="Union", ignore.strand=TRUE)
writeTargetsout(x=args, file="targets_countDF.txt", overwrite=TRUE)
```
# Differential binding analysis
The `runDiff` function performs differential binding analysis in batch mode for
several count tables using `edgeR` or `DESeq2` [@Robinson2010-uk; @Love2014-sh].
Internally, it calls the functions `run_edgeR` and `run_DESeq2`. It also returns
the filtering results and plots from the downstream `filterDEGs` function using
the fold change and FDR cutoffs provided under the `dbrfilter` argument.
```{r diff_bind_analysis, eval=FALSE}
args_diff <- systemArgs(sysma="param/rundiff.param",
mytargets="targets_countDF.txt")
cmp <- readComp(file=args_bam, format="matrix")
dbrlist <- runDiff(args=args_diff, diffFct=run_edgeR,
targets=targetsin(args_bam), cmp=cmp[[1]],
independent=TRUE, dbrfilter=c(Fold=2, FDR=1))
writeTargetsout(x=args_diff, file="targets_rundiff.txt", overwrite=TRUE)
```
# GO term enrichment analysis
The following performs GO term enrichment analysis for each annotated peak set.
```{r go_enrich, eval=FALSE}
args <- systemArgs(sysma="param/macs2.param", mytargets="targets_bam_ref.txt")
args_anno <- systemArgs(sysma="param/annotate_peaks.param",
mytargets="targets_macs.txt")
annofiles <- outpaths(args_anno)
gene_ids <- sapply(names(annofiles),
function(x) unique(as.character
(read.delim(annofiles[x])[,"gene_id"])), simplify=FALSE)
load("data/GO/catdb.RData")
BatchResult <- GOCluster_Report(catdb=catdb, setlist=gene_ids, method="all",
id_type="gene", CLSZ=2, cutoff=0.9,
gocats=c("MF", "BP", "CC"), recordSpecGO=NULL)
```
# Motif analysis
## Parse DNA sequences of peak regions from genome
Enrichment analysis of known DNA binding motifs or _de novo_ discovery
of novel motifs requires the DNA sequences of the identified peak
regions. To parse the corresponding sequences from the reference genome,
the `getSeq` function from the `Biostrings` package can be used. The
following example parses the sequences for each peak set and saves the
results to separate FASTA files, one for each peak set. In addition, the
sequences in the FASTA files are ranked (sorted) by increasing p-values
as expected by some motif discovery tools, such as `BCRANK`.
```{r parse_peak_sequences, eval=FALSE}
library(Biostrings); library(seqLogo); library(BCRANK)
args <- systemArgs(sysma="param/annotate_peaks.param",
mytargets="targets_macs.txt")
rangefiles <- infile1(args)
for(i in seq(along=rangefiles)) {
df <- read.delim(rangefiles[i], comment="#")
peaks <- as(df, "GRanges")
names(peaks) <- paste0(as.character(seqnames(peaks)), "_", start(peaks),
"-", end(peaks))
peaks <- peaks[order(values(peaks)$X.log10.pvalue., decreasing=TRUE)]
pseq <- getSeq(FaFile("./data/tair10.fasta"), peaks)
names(pseq) <- names(peaks)
writeXStringSet(pseq, paste0(rangefiles[i], ".fasta"))
}
```
## Motif discovery with `BCRANK`
The Bioconductor package `BCRANK` is one of the many tools available for
_de novo_ discovery of DNA binding motifs in peak regions of ChIP-Seq
experiments. The given example applies this method on the first peak
sample set and plots the sequence logo of the highest ranking motif.
```{r bcrank_enrich, eval=FALSE}
set.seed(0)
BCRANKout <- bcrank(paste0(rangefiles[1], ".fasta"), restarts=25,
use.P1=TRUE, use.P2=TRUE)
toptable(BCRANKout)
topMotif <- toptable(BCRANKout, 1)
weightMatrix <- pwm(topMotif, normalize = FALSE)
weightMatrixNormalized <- pwm(topMotif, normalize = TRUE)
pdf("results/seqlogo.pdf")
seqLogo(weightMatrixNormalized)
dev.off()
```
![](results/seqlogo.png)
Figure 2: One of the motifs identified by `BCRANK`
# Version Information
```{r sessionInfo}
sessionInfo()
```
# Funding
This project was supported by funds from the National Institutes of
Health (NIH) and the National Science Foundation (NSF).
# References