```{r setup, include=FALSE}
library(TxDb.Dmelanogaster.UCSC.dm3.ensGene)
library(BSgenome.Dmelanogaster.UCSC.dm3)
library(Biostrings)
library(plyr)
library(ggplot2)
library(GOstats)
library(org.Dm.eg.db)
library(xtable)
library(knitcitations)

# Tells knitr to stop once an error is encountered
# (default is to continue to next chunk)
opts_knit$set(stop_on_error=2L)

# Default chunk options
opts_chunk$set(echo=FALSE, 
               tidy=FALSE, 
               fig.path="zelda_analysis_figures/")

```

# Genes with Zelda motif

**Author**: Jeff Johnston

**Date**: `r format(Sys.time())`

## Background

The transcription factor Zelda was found to bind to "TAGteam" sites and play a role in the zygotic genome activation in *Drosophila* `r citep("10.1038/nature07388")`. 

## Overview

In this analysis, we will use Bioconductor `r citep("10.1186/gb-2004-5-10-r80")` tools to identify genes with multiple TAGteam motifs in their promoters and perform a GO analysis on these genes.

## Distribution of Zelda motifs in promoters

```{r load_transcripts}
txs.gr <- transcriptsBy(TxDb.Dmelanogaster.UCSC.dm3.ensGene, "gene")
txs.gr <- unlist(txs.gr)
mcols(txs.gr)$gene_id <- names(txs.gr)
names(txs.gr) <- NULL
```

```{r get_promoter_sequences, warning=FALSE}
promoter.gr <- resize(txs.gr, width=1)
promoter.gr <- resize(promoter.gr, width=500, fix="end")
promoter.seq <- getSeq(Dmelanogaster, promoter.gr)
```

``` {r count_zelda_motifs}
zld.motif <- "CAGGTAG"
counts.positive <- vcountPattern(zld.motif, promoter.seq, max.mismatch=1)
counts.negative <- vcountPattern(zld.motif, reverseComplement(promoter.seq), max.mismatch=1)
mcols(txs.gr)$zld_motif_count <- counts.positive + counts.negative
```

As we have `r length(txs.gr)` transcripts and `r length(unique(mcols(txs.gr)$gene_id))` genes, we will select a single transcript per gene using the highest Zelda motif count.

```{r select_single_trancsript_per_gene}
txs.df <- as.data.frame(txs.gr)
txs.df <- txs.df[order(txs.df$gene_id, txs.df$zld_motif_count, decreasing=TRUE), ]
genes.df <- txs.df[!duplicated(txs.df$gene_id), ]
```

The distribution of genes by Zelda motif count is plotted below:

```{r plot_histogram, fig.cap="", fig.width=6, fig.height=4, fig.cap="Figure 1."}
count.summary <- as.data.frame(table(genes.df$zld_motif_count))
names(count.summary) <- c("Zelda_Motif_Count", "Number_of_Genes")
g <- ggplot(count.summary, aes(x=as.character(Zelda_Motif_Count), y=Number_of_Genes)) + 
     geom_bar(stat="identity") +
     labs(x="Number of Zelda motifs in 500bp promoter sequence", y="Number of genes")
g
```

```{r histogram_table, results="asis"}
print(xtable(count.summary, digits=0), type="html", include.rownames=FALSE)
```

## GO analysis of genes with multiple Zelda motifs

Based on the above histogram, we will select those genes with at least 4 Zelda motifs and perform GO analysis to identify enriched GO categories using GOstats `r citep("10.1093/bioinformatics/btl567")`.

``` {r run_go}

gene_ids <- genes.df$gene_id[genes.df$zld_motif_count >= 4]
universe_ids <- genes.df$gene_id

flybase_to_eg <- function(fb_ids) {
  na.omit(unlist(mget(as.character(fb_ids), org.Dm.egFLYBASE2EG, ifnotfound=NA)))
}

gene_ids_eg <- flybase_to_eg(gene_ids)
universe_ids_eg <- flybase_to_eg(universe_ids)

go.params <- new("GOHyperGParams", 
                 geneIds=gene_ids_eg,
                 universeGeneIds=universe_ids_eg,
                 annotation="org.Dm.eg.db",
                 ontology="BP",
                 pvalueCutoff=0.001,
                 conditional=FALSE,
                 testDirection="over")
go.results <- hyperGTest(go.params)
```

Below are the over-represented GO categories among these `r length(gene_ids)` genes (p < 0.001):

``` {r go_results_table, results="asis"}
go.results.xt <- xtable(summary(go.results), digits=c(0, 0, 5, 2, 1, 0, 0, 0))
print(go.results.xt, type="html", include.rownames=FALSE)
```

## References

```{r references, echo=FALSE, results="asis"}
bibliography(style="markdown")
```

## Session info

```{r session_info, echo=FALSE}
sessionInfo()
```