---
title: "FROGSSTAT DESeq2: Visualization (version 3.2.1)"
output: 
  html_notebook:
    code_folding: hide
params:
  # Path to phyloseq_object
  phyloseq_data:
    value: x
  # DESeq2 preprocessed input
  dds:
    value: x
  # tested variable
  var:
    value: x
  # optionnal value 1 of the variable to be compared, default== "None"
  mod1:
    value: x
  # optionnal value 2 of the variable to be compared, default== "None"
  mod2:
    value: x
  # adjusted pvalue threshold
  padj:
    value: x
---

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
Phyloseq `r packageVersion("phyloseq")` and DESeq2 `r packageVersion("DESeq2")`

# {.tabset .tabset-fade .tabset-pills}
## Diferentially abundant OTU table

```{r packages, code_folding="show"}
library(phyloseq)
# dealing with plots
library(ggplot2)
# dealing with table
library(formattable) ## implies DT to be installed
library(dplyr)
```

Since we only have a binary factor we can use the following syntax to format the log2 fold change from the fitted model
if not, we will use the other syntax with contrast=c()

```{r import}
# Import input files
phyloseq_input <- get(load(params$phyloseq_data))
dds_input     <- get(load(params$dds))
result_names <- DESeq2::resultsNames(dds_input)
if(length(result_names) == 2 || params$mod1 == "None"){
     results <- DESeq2::results(dds, name = result_names[1] )
}else if(length(result_names)>=3){
     results <- DESeq2::results(dds_input, contrast = c(params$var, params$mod1, params$mod2) ) 
}

```

Then we extract significant OTUs at the p-value adjusted threshold level (after correction) and enrich results with taxonomic informations and sort taxa by pvalue.
```{r da_otus}

da.otus_table <- results %>% as_tibble(rownames = "OTU") %>% 
	inner_join(tax_table(phyloseq_input) %>% as.data.frame() %>% mutate(OTU = taxa_names(phyloseq_input)), by = "OTU") %>% 
    filter(padj < params$padj) %>%  
    arrange(padj)

```

Using customize datatable we can explore the table of differentially expressed OTUs
```{r datatable, message=FALSE}

# function to attribute a color in function of a score, here negativ, 0 and positiv
sign_formatter <- formatter("span", style = x ~ style(color = ifelse(x > 0, "red", ifelse(x < 0, "green", "black"))))

DT_foldchange <- da.otus_table %>% formattable(list(
				   log2FoldChange = sign_formatter, 
                   baseMean = color_tile("transparent", "lightpink"),
                   lfcSE    = color_tile("lightblue", "transparent" ),
                   padj     = color_tile("lightblue", "transparent" ),
                   pvalue   = color_tile("lightblue", "transparent")
                   )
              ) %>%  as.datatable(filter = "top",                # ==> add filter for each column
                                  extensions = 'Buttons' , 
                                  options = list(dom = '<fBtlip>', 
                                                 # lengthMenu = list(c(5,10,25,50,100,-1),c(5,10,25,50,100,"All")), # ==> trop couteux en mémoire, même sur petit jeu
                                                 buttons = list(list(
                                                   extend = 'collection',
                                                   buttons = c('csv', 'excel'),
                                                   text = 'Download')
                                                 ))
              )

DT_foldchange
```

## Pie chart
```{r pie, fig.width=8, fig.height=6}

da_pie <- data.frame(
    OTUs=c("Differentially Abundant (log-fold change > 0)",
            "Differentially Abundant (log-fold change < 0)",
            "Not Differentiallly Abundant"
        ),
    Number=c(sum(da.otus_table$log2FoldChange > 0), 
        sum(da.otus_table$log2FoldChange < 0), 
        nrow(results) - nrow(da.otus_table)
        )
    )

Pie <- ggplot(da_pie, aes(x="", y=Number, fill=OTUs)) + 
           geom_bar(stat = "identity") + 
           coord_polar("y", start=0) + 
           scale_fill_manual(values=c('#FF0000', '#008000', '#C0C0C0')) + 
           geom_text(aes(label = Number), position = position_stack(vjust = 0.5), color = "white") +
           labs(x = NULL, y = NULL, fill = NULL, title = "Pie chart to view OTUs number of Differential Abundance test") +
           theme_classic() + theme(
                axis.line = element_blank(), 
                axis.text = element_blank(),
                axis.ticks = element_blank())

Pie
```

## Volcano plot
```{r volcano, fig.width=10, fig.height=8}
## Volcano plot by DESeq2
# Add OTU names
# Add the -log10 pvalue 
# Add the pre-calculated log2 fold change
da_volcano <- data.frame(
    otu      = row.names(results),
    evidence = -log10(results$padj), 
    lfc      = results$log2FoldChange)

# Remove rows that have NA values
da_volcano <- na.omit(da_volcano)
# add a threshol line
y_axix_volcano_line <- -log10(params$padj)

# Modify dataset to add new coloumn of colors
da_volcano <- da_volcano %>%
    mutate(
    	color = case_when(
    		lfc > 0 & evidence > y_axix_volcano_line ~ "More", 
    		lfc < 0 & evidence > y_axix_volcano_line ~ "Less", 
    		TRUE                                     ~ "Equal"
    	)
    )

# Color corresponds to fold change directionality
volcano_plot <- ggplot(da_volcano, aes(x = lfc, y = evidence)) + 
    geom_point(aes(color = factor(color)), size = 1.75, alpha = 0.8, na.rm = T) + # add gene points
    theme_bw(base_size = 16) +                                                    # clean up theme
    theme(legend.position = "none") +                                             # remove legend 
    ggtitle(label = "Volcano Plot", subtitle = "Colored by effect sign") +        # add title
    xlab(expression(log[2]("FoldChange"))) +                                      # x-axis label
    ylab(expression(-log[10]("adjusted p-value"))) +                              # y-axis label
    geom_vline(xintercept = 0, colour = "grey80", linetype = 2) +                                # add line at 0
    geom_hline(aes(yintercept = y_axix_volcano_line), yintercept = y_axix_volcano_line, colour = "grey80", linetype = 2) +
    annotate(geom = "text", 
        label = paste("padj =", params$padj), 
        x = min(da_volcano$lfc), 
        y = y_axix_volcano_line + 0.25, 
        size = 4,
        colour = "black",
        vjust = 0,
        hjust = 0) + # add pvalue threshold           
    scale_color_manual(values = c("More" = "#FF0000", "Less" = "#008000", "Equal" = "#C0C0C0")) # change colors

# Plot figure
volcano_plot + scale_y_continuous(trans = "log1p")
```

## MA plot
```{r ma}

## Could do with built-in DESeq2 function:
DESeq2::plotMA(results, ylim = c(-10,10),
    ylab = "log2 fold change",
    cex  = 1,
    main = "Post Normalization DESeq2: MA plot of log2FoldChange",
    legend = TRUE)
```

## Heatmap plot
```{r heatmap, fig.width=10, fig.height=8}

da.otus_table <- da.otus_table %>% arrange(log2FoldChange)

if ( length(result_names)==2 || params$mod1 != "None"){

    subtitle <- result_names[2]
    if ( params$mod1!= "None" ){
    	phyloseq_input <- prune_samples(get_variable(phyloseq_input, params$var) %in% c(params$mod1, params$mod2), phyloseq_input)
        subtitle <- paste(sep="", params$var, "_", params$mod1, "_vs_", params$mod2)
    }

    ##Heatmap plot with 2 conditions
	hplot <- plot_heatmap(prune_taxa(da.otus_table$OTU, phyloseq_input), 
						  taxa.label = NULL,
						  taxa.order = da.otus_table$OTU, low = "yellow", high = "red", na.value = "white") + 
				facet_grid(as.formula(paste("~", params$var)), scales = "free_x") + 
				ggtitle("Heatmap plot of DA otus, between 2 conditions", subtitle = subtitle)
## Quantitative variable
} else {
    idx <- order(get_variable(phyloseq_input, params$var))
    my.sample.order <- sample_names(phyloseq_input)[idx]
    ##Heatmap plot with all conditions of variable
    hplot <- plot_heatmap(prune_taxa(da.otus_table$OTU, phyloseq_input), 
    					  taxa.label = NULL,
    	                  taxa.order = da.otus_table$OTU, sample.order = my.sample.order, 
    	                  low = "yellow", high = "red", na.value = "white") + 
             ggtitle(paste0("Heatmap plot of DA otus with samples ordered according to ", params$var))
}
# ggplotly(hplot)
hplot
```
