---
title: "Broad TALL project "
author: "[Guillaume Charbonnier](https://guillaumecharbonnier.github.io/)"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  bookdown::gitbook:
    split_by: rmd
    toc_depth: 5
    download: ["epub", "mobi"]
    sharing:
      facebook: false
      twitter: false
---

```{r setKnitrChunkDefaultOptions, include=FALSE}
eval_after <- c(
  "fig.cap",
  "fig.height",
  "fig.width",
  "out.height",
  "out.width"
)

knitr::opts_chunk$set(
  echo = FALSE,
  message = FALSE,
  fig.align = "center",
  eval.after = eval_after,
  cache = T
)
```


```{r loadLibraries, cache=F}
loadLibrary <- function(package) {
  if (!require(basename(package), character.only = TRUE)) BiocManager::install(package, update = FALSE)
  library(basename(package), character.only = TRUE)
}

packages <- c(
  "data.table",
  "yaml",
  "ggpubr",
  "ggrepel",
  "pheatmap",
  "limma",
  "yaml",
  "styler",
  "GenomicRanges",
  "RColorBrewer",
  "org.Hs.eg.db",
  #' BRGenomics', pausing index outside Rmd because conflit with affy R v3 VS R v4
  #' pdftools',
  #' openxlsx',
  #' biomaRt',
  #' clusterProfiler',
  #' ReactomePA',
  #' GOplot',
  #' plotly',
  #' factoextra',
  "edgeR",
  #' ggcorrplot',
  #' ggrepel',
  #' GGally',
  #' scales',
  #' UpSetR',
  #' reticulate',
  "affy",
  "affxparser",
  "barley1cdf",
  "DT",
  "R.utils", # load bz2 with fread
  "knitr"
)

invisible(lapply(packages, loadLibrary))
```

```{r loadFunctions, cache=F}
# Dependencies generated by Snakemake are defined with a path from the Metaworkflow directory using "smi" variable
# Bookdown needs to have these file available from the compilation directory and the book directory.
# This function link file from Metaworkflow directory to these two directories.
linkSmiToRmdAndBookDir <- function(smi) {
  rmd_to_mw_rel_path <- "../../.."
  smi_from_rmd <- file.path(rmd_to_mw_rel_path, smi)
  book_smi_from_rmd <- file.path(rmd_to_mw_rel_path, "out/bookdown/broad_tall", smi)
  dir.create(dirname(smi), recursive = TRUE, showWarnings = FALSE)
  dir.create(dirname(book_smi_from_rmd), recursive = TRUE, showWarnings = FALSE)

  # if (!file.exists(smi) | tools::md5sum(smi_from_rmd) != tools::md5sum(smi)) {
  if (!file.exists(smi) | file.info(smi_from_rmd)$mtime != file.info(smi)$mtime) {
    message("Copying this file: ", smi)
    # We copy date to use mtime instead of md5sum to check if file was updated
    file.copy(smi_from_rmd, smi, overwrite = TRUE, copy.date = TRUE)
    file.copy(smi_from_rmd, book_smi_from_rmd, overwrite = TRUE, copy.date = TRUE)
  }
  return(invisible(NULL))
}
# unlink("out", recursive=TRUE)
# unlink("../../../out/bookdown/plbio/out", recursive=TRUE)

# bookdown_out_dir <- file.path(mw_dir, 'out/bookdown/plbio')
# smi_out
# smi_bookdown <- file.path(bookdown_out_dir, smi)
# file.copy(smi, smi_bookdown)

# http://rstudio-pubs-static.s3.amazonaws.com/1204_67621a69f1dc465f81de9716ec063742.html
# multi.tests <- function(fun = t.test, df, vars, group.var, ...) {
# 	sapply(simplify = FALSE,                                    # sapply(simplify=T) better, elements named
# 		   vars,                                                # loop on vector of outcome variable names
# 		   function(var) {
# 			   formula <- as.formula(paste(var, "~", group.var))# create a formula with outcome and grouping var.
# 			   fun(data = df, formula, ...)                     # perform test with a given fun, default t.test
# 		   }
# 	)
# }

# Retrieve the relative path used by Bookdown as output folder
output_dir <- read_yaml("_bookdown.yml")$output_dir
rmd_to_mw_rel_path <- sub("/[^\\.].*$", "", output_dir)
outdir <- gsub("\\.\\./", "", output_dir)

source(file.path(
  rmd_to_mw_rel_path,
  "../mw-lib/src/r/functions/produceFormattedDataTable.R"
))

source("templates/applyTemplates.R")



# This function take a data object (either a matrix or a data frame)
# and produce a datatable with my favourite default settings for display.
set1Datatable <- function(data) {
  result_table <- datatable(data,
    extensions = "Buttons",
    options = list(
      dom = "Bfrtip",
      buttons = c("csv", "excel"),
      scrollX = TRUE,
      scrollY = TRUE
    ),
    class = "display nowrap",
    escape = FALSE,
    rownames = FALSE
  )
  return(result_table)
}
```

```{r loadCommonVars}
symnumargs <- list(cutpoints = c(0, 1e-04, 0.001, 0.01, 0.05, 1), symbols = c("∗∗∗∗", "∗∗∗", "∗∗", "∗", "ns"))
# symnumargs <- list(cutpoints = c(0,  1e-10,  1e-09,  1e-08,  1e-07,  1e-06,  1e-05,  1e-04, 0.001, 0.01, 0.05, 1), symbols = c("∗∗∗∗", "∗∗∗", "∗∗", "∗", "ns"))
```


```{r definePlotViolinBoxplot}
# This palette is used to fit the one from DeepTools plotHeatmap

deeptools_4_colors_palette <- c(
  "#1A1A8C",
  "#1A8CFF",
  "#8AFF87",
  "#FF9E1A"
)

plotViolinBoxplot <- function(data,
                              output_dir_from_rmd = output_dir,
                              pdf_dir_from_bookdown = file.path(
                                "pdf",
                                opts_current$get("label")
                              ),
                              y_lim = NULL,
                              facet_type = c("grid", "wrap"),
                              color_palette = deeptools_4_colors_palette,
                              comparisons_method = c("t.test", "wilcox", "none"),
                              comparisons_alternative = c("two.sided", "less", "greater"),
                              comparisons_pairs = comparisons_list,
                              outlier_alpha = 0.4) {
  comparisons_method <- match.arg(comparisons_method)
  comparisons_alternative <- match.arg(comparisons_alternative)
  facet_type <- match.arg(facet_type)

  if (is.null(color_palette)) {
    p <- ggplot(data, aes(x = peak_type, y = log2_ratio))
  } else {
    p <- ggplot(data, aes(x = peak_type, y = log2_ratio, color = peak_type))
    p <- p + scale_color_manual(values = color_palette)
  }

  if (facet_type == "grid") {
    p <- p + facet_grid(~sample)
  } else {
    p <- p + facet_wrap(
      ~sample,
      nrow = 1,
      ncol = length(unique(data$sample)),
      scales = "free_y"
    )
  }
  p <- p + geom_violin()
  p <- p + geom_boxplot(
    width = 0.3,
    outlier.alpha = outlier_alpha
  )
  if (outlier_alpha == 0) {
    fig_cap_outlier <- "Outliers are hidden. "
  } else {
    fig_cap_outlier <- ""
  }

  p <- p + stat_summary(
    fun = mean,
    colour = "darkred",
    geom = "point",
    shape = 18,
    size = 3,
    show.legend = FALSE
  )

  if (comparisons_method %in% c("t.test", "wilcox")) {
    p <- p + stat_compare_means(
      label = "p.signif",
      label.x = 1.5,
      method = comparisons_method,
      method.args = list(alternative = comparisons_alternative),
      comparisons = comparisons_pairs
    )
    if (comparisons_method == "t.test") {
      readable_test <- "T-test"
    }
    if (comparisons_method == "wilcox") {
      readable_test <- "Wilcoxon test"
    }

    fig_cap_comparisons <- paste0(
      "Comparison using ",
      readable_test,
      " with ",
      comparisons_alternative,
      " alternative. "
    )
  } else if (comparisons_method == "none") {
    fig_cap_comparisons <- ""
  }

  p <- p + theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
  if (is.null(y_lim)) {
    fig_cap_zoom <- ""
  } else {
    p <- p + coord_cartesian(ylim = y_lim)
    fig_cap_zoom <- paste0(
      "Zoom on the ",
      y_lim[1],
      ":",
      y_lim[2],
      " y-scale. "
    )
  }
  p <- p + theme_bw()
  print(p)

  pdf_dir <- file.path(
    output_dir_from_rmd,
    pdf_dir_from_bookdown
  )
  dir.create(pdf_dir, recursive = TRUE, showWarnings = FALSE)

  plot_height <- 4
  plot_width <- 8

  for (plot_height in 4:7) {
    for (plot_width in 7:10) {
      plot_filename <- paste0(
        pdf_dir,
        "/height",
        plot_height,
        "_width",
        plot_width,
        ".pdf"
      )

      ggsave(
        filename = plot_filename,
        plot = p,
        height = plot_height,
        width = plot_width
      )
    }
  }

  fig_cap <- paste0(
    fig_cap_outlier,
    fig_cap_zoom,
    fig_cap_comparisons,
    "Alternative dimensions available [here](",
    pdf_dir_from_bookdown,
    ")."
  )
  return(fig_cap)
}
```

