---
title: "synapter report"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  html_document:
    mode: selfcontained
    toc: true
    toc_float:
      collapsed: false
      smooth_scroll: false
    fig_width: 10
    fig_height: 8
    fig_caption: true
    out_width: 2048px
    mathjax: null
---

```{r setup, echo=FALSE}
knitr::read_chunk(system.file("reports", "scripts", "synergise.R",
                              package="synapter"))
```

# Input {.tabset}

## Files

```{r input.files, echo=FALSE, results="asis"}
inputFiles <-
    rbind(c("Identification peptide:",   basename(obj$IdentPeptideFile),  nrow(obj$IdentPeptideData)),
          c("Identification fragments:", basename(obj$IdentFragmentFile), length(obj$IdentFragmentData)),
          c("Quantitation peptide:",     basename(obj$QuantPeptideFile),  nrow(obj$QuantPeptideData)),
          c("Quantitation Pep3D:",       basename(obj$QuantPep3DFile),    nrow(obj$QuantPep3DData)),
          c("Quantitation Spectra:",     basename(obj$QuantSpectrumFile), length(obj$QuantSpectrumData)),
          c("Fasta file:",    basename(obj$DbFastaFile), ""))
colnames(inputFiles) <- c("", "File name", "Number of features")
knitr::kable(inputFiles, align="llr")
```

## General Parameters

```{r input.parameters, echo=FALSE, results="asis"}
parameters <-
    rbind(c("Master", master),
          c("Peptide FDR", fdr),
          c("Protein FPR", fpr),
          c("Peptide Length", peplen),
          c("Missed cleavages", missedCleavages),
          c("Isoleucin equals Leucin", IisL),
          c("Identification mass tolerance (ppm)", identppm),
          c("Quantitation mass tolerance (ppm)", quantppm),
          c("Loess span (RT modelling)", span.rt),
          c("Loess span (Intensity modelling)", span.int),
          c("Filtering unique peptides", as.character(uniquepep)))
colnames(parameters) <- c("Parameter name", "Value")
knitr::kable(parameters, align="lr")
```

## Grid Search Parameters

```{r input.gridparameters, echo=FALSE, results="asis"}
gridParameters <-
    rbind(c("Mass tolerance (ppm) start", grid.ppm.from),
          c("Mass tolerance (ppm) end", grid.ppm.to),
          c("Mass tolerance (ppm) by", grid.ppm.by),
          c("Retention time stdev start", grid.nsd.from),
          c("Retention time stdev end", grid.nsd.to),
          c("Retention time stdev by", grid.nsd.by),
          c("Ion mobility start", grid.imdiffs.from),
          c("Ion mobility end", grid.imdiffs.to),
          c("Ion mobility by", grid.imdiffs.by),
          c("Feature proportion ", grid.subset),
          c("Number of features", grid.n),
          c("parameters selection", grid.param.sel))
colnames(gridParameters) <- c("Grid parameter", "Value")
knitr::kable(gridParameters, align="lr")
```

## Fragment Matching Parameters

```{r input.fmparameters, echo=FALSE, results="asis"}
fmParameters <-
    rbind(c("Fragment Matching mass tolerance (ppm)", fm.ppm),
          c("Minimal Intensity for Identification Fragments", fm.ident.minIntensity),
          c("Minimal Intensity for Quantitation Spectra", fm.quant.minIntensity),
          c("Minimum Number of Common Peaks", fm.minCommon),
          c("Minimum Number of Delta Common Peaks", fm.minDelta),
          c("Unique Matches FDR", fm.fdr.unique),
          c("Non-Unique Matches FDR", fm.fdr.nonunique))
colnames(fmParameters) <- c("Parameter name", "Value")
knitr::kable(fmParameters, align="lr")
```


# Filtering

## Peptide False Discovery Rate

### Peptide Scores

```{r synergise.filtering.pepScores, echo=FALSE}
```

### Peptide Numbers

```{r synergise.filtering.pepNumbers, echo=FALSE}
```

### Peptide FDR

```{r synergise.filtering.fdr, echo=FALSE}
```

```{r synergise.filtering.data, echo=FALSE}
```

## Mass tolerance

```{r synergise.filtering.ppmErrorPre, echo=FALSE}
```

```{r synergise.filtering.ppmErrorQsPre, echo=FALSE, results="asis"}
```

```{r synergise.filtering.ppm, echo=FALSE}
```

```{r synergise.filtering.ppmErrorPost, echo=FALSE}
```

```{r synergise.filtering.ppmErrorQsPost, echo=FALSE, results="asis"}
```

```{r synergise.filtering.fpr, echo=FALSE}
```

```{r synergise.merge, echo=FALSE}
```

# Retention Time Modelling

## Retention Time Model

```{r synergise.rtmodel.plotRt, echo=FALSE}
```

```{r synergise.rtmodel.modelling, echo=FALSE}
```

```{r synergise.rtmodel.rtdiffs, echo=FALSE}
```

```{r synergise.rtmodel.rtdiffsTable, echo=FALSE, results="asis"}
```

## Feature Space

```{r rtmodel.plotAllFeatures, echo=FALSE}
plotFeatures(obj, what="all", ionmobility=TRUE)
```

```{r synergise.rtmodel.plotSomeFeatures, echo=FALSE, dev="svg", fig.cap="Using nsd = 2 and ppm error = 10 as an example.<br />Optimal values are selected below."}
```

# Grid Optimisation

`r if(grid.n) { paste0("Using", grid.n, "features.") } else { paste0("Using ",
grid.subset * 100, "% of the data.") }`
```{r, grid.comment, echo=FALSE, eval=FALSE, results="hide"}
# abuse inline r here to show the progress bar of the gridsearch in the
# R console - regular r chunks capture stdout
```
`r if (grid.n) { searchGrid(obj, ppms=seq(grid.ppm.from, grid.ppm.to, grid.ppm.by), nsds=seq(grid.nsd.from, grid.nsd.to, grid.nsd.by), imdiffs=seq(grid.imdiffs.from, grid.imdiffs.to, grid.imdiffs.by), n=grid.n, verbose=verbose) } else { searchGrid(obj, ppms=seq(grid.ppm.from, grid.ppm.to, grid.ppm.by), nsds=seq(grid.nsd.from, grid.nsd.to, grid.nsd.by), imdiffs=seq(grid.imdiffs.from, grid.imdiffs.to, grid.imdiffs.by), subset=grid.subset, verbose=verbose) }`

## Grid Tables {.tabset}

```{r grid.table, echo=FALSE, results="asis"}
names <- c("total", "model", "details")
what <- c("total", "model", "details")
for (i in seq(along=names)){
  cat("\n####", names[i], "\n")
  cat("\n##### Image\n")
  plotGrid(obj, what=what[i])
  cat("\n\n##### Tables {.tabset}\n")
  for (j in 1:dim(getGrid(obj)[[i]])[3]) {
    cat("\n###### imdiff:", dimnames(getGrid(obj)[[i]])[[3]][j], "\n")
    print(knitr::kable(as.data.frame(t(getGrid(obj)[[i]][,,j]))))
  }
  cat("\n##### Best Grid Parameters\n")
  cat("\nBest Grid Value ", names[i], ": ", getBestGridValue(obj)[i], "\n", sep="")
  print(knitr::kable(as.data.frame(getBestGridParams(obj)[[i]])))
}
```

## Grid Details

```{r grid.details, echo=FALSE, results="asis"}
gridDetails <- do.call(rbind, getGridDetails(obj))
cond <- do.call(rbind, strsplit(rownames(gridDetails), ":"))
colnames(cond) <- c("nsd", "ppm", "imdiff")
gridDetails <- cbind(cond, gridDetails)
gridDetails[] <- as.numeric(gridDetails)
rownames(gridDetails) <- NULL
knitr::kable(as.data.frame(gridDetails))
```

## Best Grid Parameters

```{r synergise.grid.bestParamaters, echo=FALSE, results="asis"}
```

Setting best grid parameters using '`r grid.param.sel`'

  - Mass tolerance (ppm): `r obj$PpmError`
  - Number of retention time stdev: `r obj$RtNsd`

# EMRT Matching

```{r synergise.emrt.find, echo=FALSE}
findEMRTs(obj)
plotEMRTtable(obj)
```

```{r synergise.emrt.table, echo=FALSE, results="asis"}
```

# Fragment Matching

```{r, fm.comment, echo=FALSE, eval=FALSE, results="hide"}
# abuse inline r here to show the progress bar of the fragment matching in the
# R console - regular r chunks capture stdout
```

## Filtering Fragments

```{r, fm.filtering, echo=FALSE}
plotCumulativeNumberOfFragments(obj, what = "fragments.ident")
plotCumulativeNumberOfFragments(obj, what = "spectra.quant")
```
`r invisible(filterFragments(obj, what="fragments.ident", minIntensity=fm.ident.minIntensity))`
`r invisible(filterFragments(obj, what="spectra.quant", minIntensity=fm.quant.minIntensity))`

`r invisible(fragmentMatching(obj, ppm = fm.ppm))`
`r invisible({pdf(file.path(outputdir, "FragmentMatching.pdf"), width=10, height=8); plotFragmentMatching(obj); dev.off()})`

## Performance {.tabset}

```{r fm.performancePlot, echo = FALSE}
fragmentMatchingStats <- plotFragmentMatchingPerformance(obj)
```

```{r fm.performance, echo=FALSE, results="asis"}
names <- c("Unique Matches", "Non-Unique Matches")
firstColumn <- c("Number of Common Peaks", "Delta Common Peaks")
for (i in seq(along=names)){
  cat("\n####", names[i], "\n")
  tab <- as.data.frame(fragmentMatchingStats[[i]])
  colnames(tab) <- c(firstColumn[i], toupper(colnames(tab)[-1]))
  print(knitr::kable(tab))
}
```

## Best Parameters

```{r fm.selBestParam, echo = FALSE, results="asis"}
common <- c(NA, NA)
selCommon <- which(fragmentMatchingStats$unique[, "ncommon"] >= fm.minCommon &
  fragmentMatchingStats$unique[, "fdr"] <= fm.fdr.unique)[1]

if (!is.na(selCommon)) {
  common <- fragmentMatchingStats$unique[selCommon, c("ncommon", "fdr")]
  filterUniqueMatches(obj, minNumber = common[1L])
}

delta <- c(NA, NA)
selDelta <- which(fragmentMatchingStats$nonunique[, "deltacommon"] >= fm.minDelta &
  fragmentMatchingStats$nonunique[, "fdr"] <= fm.fdr.nonunique)[1]

if (!is.na(selDelta)) {
  delta <- fragmentMatchingStats$nonunique[selDelta, c("deltacommon", "fdr")]
  filterNonUniqueMatches(obj, minDelta = delta[1L])
}

filterNonUniqueIdentMatches(obj)

tab <- cbind(paste(names, firstColumn, sep=" - "), rbind(common, delta))
colnames(tab) <- c("Type", "Value", "FDR")
rownames(tab) <- NULL
print(knitr::kable(tab))
```

# EMRT Rescue

```{r emrt.rescue, echo=FALSE}
rescueEMRTs(obj, mergedEMRTs)
plotEMRTtable(obj)
```

```{r synergise.emrt.table2, echo=FALSE, results="asis"}
## @knitr synergise.emrt.table
tab <- as.data.frame(getEMRTtable(obj))
colnames(tab) <- c("Number of assigned EMRTs", "Freq")
knitr::kable(tab)
```

# Intensity Model

```{r synergise.intmodel.plotInt, echo=FALSE}
plotIntensity(obj, what="data")
```

```{r synergise.intmodel.modelling, echo=FALSE}
setLowessSpan(obj, span.int)
modelIntensity(obj)
plotIntensity(obj, what="model", nsd=1) ## better focus on model
```

# Performance

## Enrichment
```{r synergise.performance.enrichment, echo=FALSE, results="asis"}
```

## Overlap
```{r synergise.performance.overlap, echo=FALSE, results="asis"}
```

## Source
```{r synergise.performance.source, echo=FALSE, results="asis"}
```

# Exported Files

```{r synergise.export, echo=FALSE}
```

- [Identification Peptides](IdentPeptides.csv)
- [Quantitation Peptides](QuantPeptides.csv)
- [Merged Peptides](MergedPeptides.csv)
- [Matched Peptides](MatchedPeptides.csv)
- [QuantPeptides.csv](QuantPeptides.csv)
- [Grid Details](GridDetails.txt)
- [Fragment Matching Plots](FragmentMatching.pdf)
- [Saved R Object (binary)](SynapterObject.rda)

# Full Analysis Log

```{r synergise.log, echo=FALSE, results="asis"}
```

# Session Info

```{r synergise.sessionInfo, echo=FALSE}
```
