---
title: DiscoRhythm v`r packageVersion("DiscoRhythm")` Report
date:
output:
  BiocStyle::html_document:
    code_download: true
    toc: true
    number_sections: true
    toc_float: true
---

<style>
.nav-tabs span.header-section-number {
    width: auto;
    padding: 0 10px;
}
</style>

The analysis below can be reproduced by one of the following methods: 

1. Running the commands in R.
2. Running `discoBatch()` with the parameters in section \@ref(parameter-settings).
3. Interactively with `discoApp()` with the parameters in \@ref(parameter-settings).

*Note: This report is static and does not perform any reactive data
processing.* 

To run commands directly in R, import the data and input parameters:

```{r}
# Choose an appropriate command for importing the data
# indata <- read.csv("path/to/input_data.csv") # From CSV file
# indata <- readRDS("path/to/input_data.RDS") # From R data file
# indata <- DiscoRhythm::discoGetSimu() # Import example dataset

# Read input parameters and put them into the global environment
# discorhythm_inputs <- readRDS('discorhythm_inputs.RDS')
# list2env(discorhythm_inputs,envir=.GlobalEnv)
```

# Data Processing

## Parameter Settings

Below is a table of all parameters input to this report.
See `?discoBatch` R documentation for parameter descriptions.

```{r echo=F}
knitr::kable(data.frame(
  "Parameter"=c("cor_threshold","cor_method","cor_threshType","pca_threshold",
                "pca_scale","pca_pcToCut","aov_method","aov_pcut","aov_Fcut",
                "avg_method","osc_method","timeType","main_per",
                "osc_period"),
  "Value"=c(cor_threshold,cor_method,cor_threshType,pca_threshold,
            pca_scale,paste(pca_pcToCut,collapse = " "),
            aov_method,aov_pcut,aov_Fcut,avg_method,
            paste(osc_method,collapse=" "),
            timeType,main_per,osc_period)
  ), format = "markdown")
```

## Main Computations

```{r echo=F}
batchscript=system.file("", "DiscoRhythm_batch.R",
                               package = "DiscoRhythm",
                               mustWork = TRUE)
```

Below is all R code necessary to generate the main DiscoRhythm results. These
results will be used in section \@ref(visualizations) for generating the
summary figures. Refer to the "Introduction to DiscoRhythm" document
for a detailed description of the workflow steps.

<!-- To run the computation code -->
```{r include=FALSE,echo=FALSE}
# local=TRUE to run within the environment used to call this Rmd
source(batchscript, local = TRUE)
```

<!-- To show the code in the report -->
```{r code = readLines(batchscript),eval=FALSE}
```

# Visualizations

Importing the DiscoRhythm plotting functions used by the web application
for use in this report. To reproduce these results, ensure you have all
necessary package versions (See \@ref(session-info)). Refer to the 
`r BiocStyle::Biocpkg('DiscoRhythm')` user's guide
or web application for details on each figure.

```{r }
source(system.file("app/code/server", "plots.R", package = "DiscoRhythm",
                   mustWork = TRUE))
```

# Process Input Data

## Design Summary

```{r }
suppressPackageStartupMessages(library(SummarizedExperiment))
knitr::kable(discoDesignSummary(colData(selectDataSE)), format = "markdown")
```

# Outlier Detection

## Inter-sample Correlations {.tabset}

### Average Correlations

```{r }
plotly::ggplotly(plotAvgCor(colData(selectDataSE),CorRes$meanCor,
                            corCut = CorRes$threshold,tUnit = "hr"))
```

### Correlation Heatmap

```{r }
plotHeatMCor(CorRes$corMat,1)
```

## PCA {.tabset}

### PC Score Distributions

```{r }
plotly::ggplotly(
  plotPCAdists(PCAres,SDfactor = pca_threshold,pcToUse = pca_pcToCut)
)
```

### One Pair

```{r }
gridExtra::grid.arrange(
  plotPCAWithShape(PCAres$x,as.data.frame(colData(selectDataSE)),
                   col = "None",1,2,
                   PCAres$outliers)+
    ggtitle("Before Outlier Removal"),
  plotPCAWithShape(PCAresAfter$x,as.data.frame(colData(selectDataSE)),
                   col = "None",1,2)+
    ggtitle("After Outlier Removal"),
  ncol=2)
```

### Scree Plot

```{r }
plotPCAstats(PCAres$table,PCAresAfter$table,pcToUse = pca_pcToCut)
```

### All Pairs {.tabset}

#### Before Outlier Removal

```{r }
plotPCAPairs(PCAres$x,c("PC1","PC2","PC3","PC4"))
```

#### After Outier Removal

```{r messages=F}
invisible(plotPCAPairsAfter(PCAresAfter$x,c("PC1","PC2","PC3","PC4"),
                            PCAres$outliers))
```

## Outlier Summary {.tabset}

### Outliers

```{r }
DT::datatable(as.data.frame(
  colData(selectDataSE)[PCAres$outliers | CorRes$outliers,]
))
```

### Remaining Samples

```{r }
knitr::kable(discoDesignSummary(colData(FilteredSE)), format = "markdown")
```

# Replicate Analysis {.tabset}
## ANOVA P-Value Histogram

```{r }
if(aov_method!='None') plotPvalues(ANOVAres$aovP,50, aov_pcut, 'ANOVA')
```

## Signal-to-noise

```{r }
if(aov_method!='None') ObsVsExpSNR(ANOVAres$allStats,aov_Fcut)
```

# Period Detection
## Period Detection

```{r }
plotPeriodDetect(PeriodRes)
```

## PC Fits to Fixed Period {.tabset}
### PC Cosinor Fits

```{r }
plotOVpcaScatter(OVpca = OVpca,colData(FinalSE),osc_period,
                 PCsToUse = paste0("PC",1:4))
```

### Cosinor Table

```{r }
pcaSE <- discoDFtoSE(data.frame("PC"=1:ncol(OVpca$x),t(OVpca$x)),
                        colData(FinalSE))
knitr::kable(
  discoODAs(pcaSE,method="CS")$CS,
  format = "markdown"
)
```

# Oscillation Detection
## Detection Summary {.tabset}
### P-value Histograms

```{r }
plotPQValueHist(discoODAres,bg = seq_len(nrow(FinalSE)),50,
                cutoff = 0.05,discoODAid2name)
```

### Acrophase Rose Diagrams

```{r }
fg <- lapply(discoODAres,function(x) which(x$pvalue<0.05))
plotAllAcroHist(discoODAres,fg,50,osc_period,TRUE,discoODAid2name)
```

### Amplitude Histogram

```{r }

plotAmpliHist(discoODAres,bg = seq_len(nrow(FinalSE)),
              fg=fg[['CS']],50,'')
```

### Intersection of Methods

```{r }
allIntersect(fg)
```

# Session Info

```{r }
sessionInfo()
```

