
message("MCQRBegin: check_mcqr_package_install")

want.mcqr.version <- "1.0.2"
want.mcqr.url <- "https://forgemia.inra.fr/-/project/1534/uploads/6550076d01dab32a562598f355b17938/MCQR_1.0.2.tar.gz"

# deb: libudunits2-dev libgdal-dev (Debian, Ubuntu, ...)
# rpm: udunits2-devel (Fedora, EPEL, ...)
# brew: udunits (OSX)

message("Create personal library directory and add it to the R library path");

dir.create(Sys.getenv("R_LIBS_USER"), recursive = TRUE)  # create personal library
.libPaths(Sys.getenv("R_LIBS_USER"))  # add to the path


message("MCQRInfo: Check package installation")

if((version[['major']] < 4) || (strsplit(version[['minor']],"\\.")[[1]][1] < 2) ) {
    message("MCQRInfo: Error MCQR requires at least R version 4.2")
    stop(paste("Error : ","MCQR requires at least R version 4.2"))
}

# R base packages for MCQR
all.packages = c('Rcpp','utf8','fansi','pkgconfig','purrr', 'backports','R6', 'glue', 'magrittr','ellipsis', 'miniUI','digest', 'tibble', 'pillar', 'mime', 'promises', 'later', 'htmltools', 'miniUI', 'htmlwidgets','httr', 'stringr','stringi',  'jsonlite', 'zoo', 'mvtnorm','rstudioapi', 'highr','lazyeval', 'multcomp', 'bitops', 'caTools', 'gplots', 'gtools', 'gdata', 'chron', 'stringi', 'reshape2', 'data.table', 'readODS', 'vcd', 'lme4', 'car', 'carData', 'robustbase', 'colorspace', 'VIM', 'ade4', 'clValid', 'agricolae', 'ggplot2', 'gridExtra', 'Hmisc', 'RColorBrewer', 'plotly', 'plyr', 'dplyr', 'ggVennDiagram', 'svglite', 'tidyr','systemfonts', 'scales', 'tidyselect', 'zip')

#bioc.packages = c('made4')

is_installed <- function(pkg, ..., version = NULL, compare = NULL) {
  check_dots_empty0(...)

  info <- pkg_version_info(pkg, version = version, compare = compare)
  all(detect_installed(info))
}
packages_cpp <- c('cpp11')

#install all packages that are not already installed
install.packages(setdiff(packages_cpp, rownames(installed.packages())), quiet = TRUE, repos = "https://pbil.univ-lyon1.fr/CRAN/")

# install all packages
packages.to.install <- setdiff(all.packages, rownames(installed.packages()))
for (pkg in packages.to.install) {
  cat("MCQRInfo: Downloading and installing", pkg)
#  if (pkg %in% bioc.packages){
#    library(BiocManager)
#    BiocManager::install(pkg)
#  }else{
    install.packages(pkg, quiet = TRUE, repos = "https://pbil.univ-lyon1.fr/CRAN/")
#  }
}

# Check if all the mandatory packages are installed
if(length(setdiff(all.packages, rownames(installed.packages()))) == 0){
  message("All packages are installed")
}else{
  message("Some packages can't be installed :")
  cat(setdiff(all.packages, rownames(installed.packages())))
}

# Check if MCQR is installed
is.installed <- function(mypkg){
    is.element(mypkg, installed.packages()[,1])
}

# check if package "MCQR" is installed
if (!is.installed("MCQR")){
    install.packages(want.mcqr.url, repo=NULL, type="source")
}
if(packageVersion("MCQR") == "0.6.11") {
    install.packages(want.mcqr.url, repo=NULL, type="source")
}
if(packageVersion("MCQR") < want.mcqr.version) {
    install.packages(want.mcqr.url, repo=NULL, type="source")
}

message("MCQREnd: check_mcqr_package_install")
message("MCQRBegin: libraries");




  capture.output(library("MCQR", verbose=FALSE), file=stderr())
  message(paste("MCQRInfo: MCQR version :", packageVersion("MCQR")))
  library("xtable")
  library("svglite")
  library("readODS")
  library(data.table)

pimg_srcsvg <- function(path,prefix) {
  for(file_svg in list.files(path = path, pattern=paste(prefix,".*\\.svg",sep=""))){
    cat(paste("<p><img src=\"",path, file_svg, "\" /></p>\n",sep=""));
  }
}

pimg_srcpng <- function(path,prefix) {
  for(file_svg in list.files(path = path, pattern=paste(prefix,".*\\.png",sep=""))){
    cat(paste("<p><img src=\"",path, file_svg, "\" /></p>\n",sep=""));
  }


}





message("MCQREnd: libraries");
setwd("/home/olangella/Téléchargements/demo");
message("MCQRBegin: load");



  cat("<h1>MCQR XIC Analysis</h1>")
  cat("<p>working directory: /home/olangella/Téléchargements/demo/</p>")

  cat("<h2>Load XIC data</h2>")

  cat("<p>Loading MassChroq data. NB: peptide intensities measured as peak areas are automatically log10-transformed.</p>")
  cat("<p>Directory names must not include a trailing backslash or slash on Windows</p>")

  XICRAW <- mcq.read.masschroq(protFile = "/home/olangella/Téléchargements/demo/proteins.tsv", pepFile = "/home/olangella/Téléchargements/demo/peptides_All_samples.tsv")

  cat("<p>Overview of the content of the 'XICRAW' object</p>")
  summary (XICRAW)
  save(XICRAW, file="/home/olangella/Téléchargements/demo/xicraw_nometadata.rdata")






message("MCQREnd: load");
message("MCQRBegin: merge_metadata");


  load(file="/home/olangella/Téléchargements/demo/xicraw_nometadata.rdata")

  cat("<h1>Reading metadata file</h1>")
  cat("<p>Importing the filled in metadata file</p>")
  capture.output(META <- mcq.read.metadata("/home/olangella/Téléchargements/demo/metadata.ods"), file=stderr())

  cat("<p>Attaching metadata to quantification data</p>")
  cat("<h1>Merging metadata</h1>")
  XICRAW <- mcq.add.metadata(XICRAW, metadata=META)

  cat("<p>Overview of the content of the 'XICRAW' object</p>")
  summary (XICRAW)
  save(XICRAW, file="/home/olangella/Téléchargements/demo/xicraw.rdata")
  cat("<h3>Chromatography checking</h3>")
  cat("<h4>Plot distribution of the width of chromatographic peaks</h4>")
  cat("<p>Checking the distribution of the width of chromatographic peaks. Are there many very large peaks?</p>")
  svglite("/home/olangella/Téléchargements/demo/peak_width.svg", width=14, height=12);
  capture.output(mcq.plot.peak.width(XICRAW, byFraction = FALSE), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="peak_width");

  cat("<h4>Plot distribution of the standard deviation of RT</h4>")
  cat("<p>Checking the variability of the peptide-mz retention time (RT) by plotting the distribution of the standard deviation of RT. Are there many peptides-mz showing huge variations of their RT?</p>")
  svglite("/home/olangella/Téléchargements/demo/rt_variability.svg", width=14, height=12);
  capture.output(mcq.plot.rt.variability(XICRAW, limit=), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="rt_variability");

  cat("<h3>Plot injections checking</h3>")
  cat("<h4>Plot number of peptides by tracks and fraction</h4>")
  cat("<p>Checking the number of chromatographic peaks quantified in each injection. Are there injections with much fewer peaks?</p>")
  svglite("/home/olangella/Téléchargements/demo/injection_counts.svg", width=14, height=12);
  capture.output(mcq.plot.counts(XICRAW, overlay=TRUE), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="injection_counts");

  cat("<h4>Plot intensity profiles for selected factors</h4>")
  cat("<p>Checking the median intensity along the chromatography. Are there injections showing abnormal intensity profiles?</p>")
  svglite("/home/olangella/Téléchargements/demo/intensity_profile.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.profile(XICRAW, factorToColor=c(), RTinterval=), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="intensity_profile");

  cat("<h4>Plot distribution of peptide intensities for each injection</h4>")
  cat("<p>Checking the distribution of the peptide-mz log-intensities in each injection. Are there injections where intensities are not normally distributed?</p>")
  svglite("/home/olangella/Téléchargements/demo/intensity_distribution%d.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.distribution(XICRAW), file=stderr())
  capture.output(dev.off(), file=stderr());

  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="intensity_distribution");

  unlink("/home/olangella/Téléchargements/demo/a3a1_backup_xicraw.rdata")
  unlink("/home/olangella/Téléchargements/demo/a4a1_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a4a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a5a1_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a5a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a6a1_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a6a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a7_backup_xic.rdata")





message("MCQREnd: merge_metadata");
message("MCQRBegin: a4a1_mcqr_normalization");


  if(file.exists("/home/olangella/Téléchargements/demo/a4a1_backup_xic.rdata")){
    load(file="/home/olangella/Téléchargements/demo/a4a1_backup_xic.rdata")
  } else if(file.exists("/home/olangella/Téléchargements/demo/xic.rdata")){
    load(file="/home/olangella/Téléchargements/demo/xic.rdata")
  } else {
    load(file="/home/olangella/Téléchargements/demo/xicraw.rdata")
    XIC <- XICRAW
  }
  save(XIC, file="/home/olangella/Téléchargements/demo/a4a1_backup_xic.rdata");

  cat("<h3>Normalizing peptide-mz intensities</h3>")

  cat("<p>Normalizing peptide-mz intensities to take into account possible global quantitative variations between LC-MS runs</p>")
  cat("<p>############# Normalizing peptide-mz intensities</p>")

  capture.output(XIC <- mcq.compute.normalization(XIC, method="median.RT"), file=stderr())


  cat("<h4>Control the normalization effets</h4>")
  cat("<p>Checking the median intensity along the chromatography after normalization.</p>")
  svglite("/home/olangella/Téléchargements/demo/intensity_profile_after_norm.svg", width=14, height=12);
  capture.output(mcq.plot.intensity.profile(XIC, factorToColor=c(), RTinterval=), file=stderr())
  capture.output(dev.off(), file=stderr());
  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="intensity_profile_after_norm");

  cat("<p>############# Controling the effect of normalization on intensities distribution</p>")
  cat("<p># Display of the graph of intensity distributions on the screen</p>")
  svglite("/home/olangella/Téléchargements/demo/norm_violin.svg", width=14, height=12);
  mcq.plot.intensity.violin(XIC, factorToColor=c()) ;
  capture.output(dev.off(), file=stderr());

  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="norm_violin");

  cat("<h4>Principal Component Analysis</h4>")
  cat("<p>PCA using all the samples as individuals</p>")
  capture.output(XIC_PCA <- mcq.compute.pca(XIC), file=stderr());
  cat("<p>Display of the PCA on the screen. Possibility to modify the 'factorToColor' and 'labels' arguments to change the colors and the labels of the individuals represented on the PCA.</p>")
  svglite("/home/olangella/Téléchargements/demo/xic_pca_%d.svg", width=14, height=12);
  capture.output(mcq.plot.pca(XIC_PCA, factorToColor=c(), labels=c(), tagType="label", labelSize=4), file=stderr())
  capture.output(dev.off(), file=stderr());

  pimg_srcsvg(path="/home/olangella/Téléchargements/demo/",prefix="xic_pca_");

  save(XIC, file="/home/olangella/Téléchargements/demo/xic.rdata");
  unlink("/home/olangella/Téléchargements/demo/a4a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a5a1_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a5a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a6a1_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a6a2_backup_xic.rdata")
  unlink("/home/olangella/Téléchargements/demo/a7_backup_xic.rdata")




message("MCQREnd: a4a1_mcqr_normalization");
message("MCQRBegin: a4a1_proteobench");




library(data.table)


get.proteobench <- function(pepq) {

   # sequence   ProForma  rawfile charge proteins
   #(containing "SPECIES" and separated with ";" if it is a protein group
  if ('ProForma' %in% names(pepq@proteins)) {
  }
  else {
    stop(paste("ProForma column is not present, please use at least MassChroQ version 2.4.5 to produce peptide quantification tables",sep=""))
  }
  data <- getdf(pepq)
  datamproteobench <-data[, c("sequence","ProForma", "z", "accession")]
  #datamsstats$sequence <- gsub("L","I",datamsstats$sequence)
  #datamsstats$sequence <- data$peptiniid
  colnames(datamproteobench) <- c("sequence","ProForma", "charge", "proteins")
  datamproteobench$charge <- data$z
  if ("label" %in% colnames(data)) {
    #datamproteobench$IsotopeLabelType <- data$label
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "light", "L")
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "heavy", "H")
    #datamproteobench$IsotopeLabelType[is.na(datamproteobench$IsotopeLabelType)] <- "L"
  }
  else {
    #datamproteobench$IsotopeLabelType <- "L"
  }

  datamproteobench$rawfile <- data$msrun
  if("areanorm" %in% colnames(data)){
    datamproteobench$area <- data$areanorm
  } else {
    datamproteobench$area <- data$area
  }
  #populate NA for missing values
  df_unique_ion <- unique(datamproteobench[c("sequence","ProForma", "charge", "proteins")])


  proteobench_conditions <- unique (datamproteobench[,c("rawfile", "proteins")])

  datamproteobench = as.data.table(datamproteobench)


  datamproteobench <- merge(cbind(pepq@metadata@injections, row=row.names(pepq@metadata@injections)), datamproteobench, by.x="row", by.y="rawfile")

  datamproteobench$row <- NULL;
  colnames(datamproteobench)[colnames(datamproteobench) == 'msrunfile'] <- 'rawfile'
  return (datamproteobench);

}


getdf <- function(object) {
	protein <- accession <- protein_description <- NULL
    temp_proteins = unique(object@proteins[,c("peptide", "protein", "accession", "protein_description")])

	shared.pep <- names(table(temp_proteins$peptide))[table(temp_proteins$peptide)>1]
	tab <- as.data.table(object@proteins[object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])
    tab <- tab[,list(protein = paste(protein, collapse=";"), accession = paste(accession, collapse=";"), protein_description = paste(protein_description, collapse=";")), by="peptide"]
	#tab <- ddply(tab, .(peptide), summarize,  protein=paste(protein, collapse=";"), accession=paste(accession, collapse=";"), protein_description=paste(protein_description, collapse=";"))
	tab <- rbind.data.frame(tab, object@proteins[!object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])

	indice <- match(object@peptides$peptide, tab$peptide)

	object@peptides$protein <- tab$protein[indice]
	object@peptides$accession <- tab$accession[indice]
	object@peptides$protein_description <- tab$protein_description[indice]
	if (nrow(object@metadata@metadata)!=0) {
		tpep <- merge(object@peptides, object@metadata@metadata, by.x="msrun", by.y="row.names")
	}

	tpep <- tpep[order(tpep$msrun,tpep$peptide),]
	colnames(tpep)[which(colnames(tpep)=="logarea")] <- "log10area"
	colnames(tpep)[which(colnames(tpep)=="lognorm")] <- "log10norm"


	if ('ProForma' %in% names(object@proteins)) {
	  tpep <- merge(tpep, object@proteins[,c("peptide","ProForma")], by.x="peptide", by.y="peptide", all.x = TRUE)
	}
	return (unique(tpep))
}

  assign('pepq', get(load (file="/home/olangella/Téléchargements/demo/xic.rdata")))
  cat("<h3>writing proteobench tsv file</h3>")

  df_proteobench <- get.proteobench(pepq)
  write.table(df_proteobench, file = "/home/olangella/Téléchargements/demo/proteobench_export.tsv", sep = "\t", row.names = F, quote = T)




message("MCQREnd: a4a1_proteobench");
