---
title: "Introduction to `r BiocStyle::Biocpkg('DiscoRhythm')`"
author:
- name: Matthew Carlucci
  affiliation: The Krembil Family Epigenetics Laboratory, 
    The Campbell Family Mental Health Research Institute, 
    Centre for Addiction and Mental Health
  email: matthew.carlucci@camh.ca
- name: Algimantas Kriščiūnas
  affiliation: Institute of Biotechnology, Life Sciences Center, 
    Vilnius University, Vilnius, Lithuania
- name: Haohan Li
  affiliation: The Krembil Family Epigenetics Laboratory, 
    The Campbell Family Mental Health Research Institute, 
    Centre for Addiction and Mental Health
- name: Povilas Gibas
  affiliation: Institute of Biotechnology, Life Sciences Center, 
    Vilnius University, Vilnius, Lithuania
- name: Karolis Koncevičius
  affiliation: Institute of Biotechnology, Life Sciences Center, 
    Vilnius University, Vilnius, Lithuania
- name: Art Petronis
  affiliation: 
  - The Krembil Family Epigenetics Laboratory, 
    The Campbell Family Mental Health Research Institute, 
    Centre for Addiction and Mental Health
  - Institute of Biotechnology, Life Sciences Center, 
    Vilnius University, Vilnius, Lithuania
- name: Gabriel Oh
  affiliation: The Krembil Family Epigenetics Laboratory, 
    The Campbell Family Mental Health Research Institute, 
    Centre for Addiction and Mental Health
package: DiscoRhythm
output:
  BiocStyle::html_document:
    toc: true
    toc_float: true
    css: vignette.css
vignette: >
 %\VignetteIndexEntry{Introduction to DiscoRhythm}
 %\VignetteEngine{knitr::rmarkdown}
 %\VignetteEncoding{UTF-8}
---

# Getting Started

## Accessing the Graphical User Interface

The public server for DiscoRhythm is available 
[here](https://disco.camh.ca), however, local usage is advised 
for improved performance (see \@ref(installation)). 

See the guide in section \@ref(discorhythm-interface-walkthrough) for 
details on usage of the application.

## Installation

To run the application locally or use DiscoRhythm with R, the DiscoRhythm R 
package must be installed. 

DiscoRhythm and its dependencies can be installed by executing the following 
in R:

```
if (!requireNamespace("BiocManager", quietly=TRUE))
    install.packages("BiocManager")
BiocManager::install("DiscoRhythm")
```

*Note: Manual installation of [pandoc](https://pandoc.org/installing.html) 
is required in order to use the report generation features of DiscoRhythm.*

Running the command `library(DiscoRhythm); discoApp()` will then launch the 
application. The application can be parallelized on multiple cores 
for improved performance using `discoApp(ncores=number_of_available_cores)`.

### Run the Web Application with Docker (Optional)

Alternatively, if [docker](https://docs.docker.com/install/) is installed, the 
[DiscoRhythm container on Docker Hub](https://hub.docker.com/r/mcarlucci/discorhythm) 
can be pulled and used to run the web application locally 
avoiding the need to install DiscoRhythm and its dependencies (See instructions
on Docker Hub). 

## Using DiscoRhythm in R

The same computations performed in the web application can be executed directly 
in R. This may be necessary for: 

- Executing the workflow conveniently on multiple datasets
- Analyzing large datasets
- Adding custom R code to the workflow

Section \@ref(discorhythm-r-usage) describes this usage in more detail.

# Introduction

DiscoRhythm is a set of statistical tools for analyzing large scale temporal 
biological experiments with a hypothesized periodicity (e.g. circadian 
transcriptomic experiments). The main goal of this package is to take a 
normalized data matrix and characterize the rhythmicity of
the features. The entire workflow 
can be run interactively in the web application or run directly in R to
perform:

1. Import and cleaning of a normalized data matrix  
2. Inter-sample correlations and outlier detection  
3. Principal component analysis and outlier detection  
4. Analysis of experimental replicates (if applicable)  
5. Detection of dominant rhythmicities in the dataset  
6. Detection of feature-wise oscillation characteristics  
    - Estimating cyclical characteristics such as: period, phase, 
amplitude, and statistical significance using four methods 
(Cosinor, JTK Cycle, ARSER, and Lomb-Scargle).

Section \@ref(input-datasets) describes the expected input to the DiscoRhythm
workflow.

Next, section \@ref(discorhythm-interface-walkthrough) will describe these steps
and their use in the web application. 
Section 
\@ref(discorhythm-r-usage) will then describe how to generate the same results 
using the DiscoRhythm R package directly.

# Input Datasets

## Example Dataset

Below is a small simulated circadian transcriptomic dataset generated using the
`r BiocStyle::Githubpkg("hugheylab/simphony")` which follows the expected input 
format for DiscoRhythm. The dataset was generated to contain ~50% rhythmic
transcripts with a diversity of phases of oscillation.

```{r echo=F}
library(DiscoRhythm)

indata <- discoGetSimu()
knitr::kable(head(indata[,1:6]),format = "markdown") # Inspect the data
```

## Row Naming

The first column should contain unique feature IDs (e.g. gene names in this 
case).

```{r echo=F}
kableExtra::column_spec(knitr::kable(head(indata[,1:6])),
              1, background = "#FDB813",
              include_thead = TRUE)
```

All subsequent columns contain experimental sample data.

```{r echo=F}
kableExtra::column_spec(knitr::kable(head(indata[,1:6])),
              2:6, background = "#FDB813",
              include_thead = TRUE)
```

## Column Naming

Sample metadata is extracted from the column names of the matrix.

```{r echo=F}
kableExtra::column_spec(
kableExtra::row_spec(
  knitr::kable(head(indata[,1:6])),
              0, background = "#FDB813"),
1, background = "inherit",include_thead = TRUE)
```

Names are expected to follow the pattern:  

`Prefix` `Time`\*\_`Unique Id`\_`Replicate Id`

| Field | Description | Examples |
|----------------|----------------------|-------------|
| `Prefix` | A unit of time. The web application will use this as the unit of time by default. |  `hr`, `ZT`, `CT`|
| `Time`\* | Indicates the time of collection for the respective sample. Can only be positive values. | `20`, `2.1`, `0.3`|
| `Unique Id` | A free field used to uniquely identify samples in visualizations and summaries. | `GSM3186429`, `sample1`, `subjectA`, `AX` |
| `Replicate Id` | Used to identify each biological sample uniquely when combined with `Time`. | `1`, `A`, `rep1` |

Table: Descriptions of the naming convention used by DiscoRhythm.  
\* *Mandatory field*

`Time` is the only required field (i.e.  `32`, `CT32`, `CT32_AS_1`, `32_AS_1` 
are all valid naming styles) and the other fields are used to obtain a few 
pieces of sample metadata if necessary:

**Biological vs Technical Replicates - ** `Time` + `Replicate Id`[^1] are used to
identify independent samples collected at the same timepoint (biological 
replicates). Samples with the same `Time` and `Replicate Id` 
are assumed to be technical replicates from a single biological sample. 

[^1]: If no `Replicate Id` is provided, all samples are assumed to be 
independent biological replicates.

**Unique Sample Identity - ** Each column name should be unique such that all
samples can be uniquely identified to the user. The `Unique Id` field is 
intended for this purpose. If column 
names are not unique, the `Unique Id` field will be generated to provide 
unique sample names during usage of DiscoRhythm.

*Note: all fields should contain only alphanumeric values (with the exception
of '.' in the `Time` field which is allowed for decimal values.*

### Processed Metadata Table

The data extracted above is stored in the DiscoRhythm application as:

```{r echo=F,message=FALSE}
knitr::kable(head(SummarizedExperiment::colData(
  discoDFtoSE(indata)
)), format = "markdown")
```

--------------------------------------------------

*Note: If there are more groupings in the dataset or if the dataset does not fit
into this design, it may be appropriate to split the dataset into subgroups 
that fit this design (each subgroup as one input dataset to DiscoRhythm).*

## Time Type

DiscoRhythm defines time in an input dataset in one of two ways:  

1) Linear time  
2) Circular time  

Linear time exists in systems where an experiment start time is meaningful 
(often setting t=0 to some specific event). Circular time exists in experiments 
where the start of experiment is not meaningful or left unobserved 
(e.g. time-of-day in a cross-sectional study). One of these two types must be
specified for the input 
dataset and will influence how DiscoRhythm analysis is performed.

Example of linear time in hours: `1,2,3 ... 24,25,26`  
Example of circular time, time-of-day in hours: `1,2,3 ... 24,1,2`  

For example, a dataset obtained from mice entrained on a 12-h light,
12-h dark schedule before being released into total darkness prior to 
collection. The presence of a specific event (release into total darkness)
would make the dataset suitable for the "Linear time" setting of DiscoRhythm.  

*Note: If samples were collected during the entrainment to the light/dark 
base-cycle, "Circular time" would be appropriate as mice sampled at the 
same point in the cycle on different days may be treated as biological 
replicates.*

# DiscoRhythm Interface Walkthrough

This section will walk the user through each section of the DiscoRhythm web
application. It is recommended to keep this documentation open during 
first usage of the application to read details for each section.

## The Interface

The DiscoRhythm web interface is a dashboard
where the sections of the 
analysis can be accessed in the sidebar and progress in a sequential 
fashion with data from the previous step being
fed into the next.

There are interactive controls to set parameters for each section's analysis. 
When parameters relevant to a figure change, the corresponding figure will 
dynamically update to reflect the newly calculated results. Since DiscoRhythm 
is intended for use sequentially 
through the sections, **returning to earlier sections of the analysis and
modifying
parameters may result in unexpected behaviour.**

Various download buttons are available throughout
the application for archival of both plot outputs
and numerical results. 

```{r interface, echo=F, fig.cap="Screenshot of the initial DiscoRhythm landing page."}
knitr::include_graphics("IntroductionSS.jpg")
```

## Select Data

**Purpose:** To upload, clean, and summarize the experimental design for the 
input dataset.

An input dataset is expected to be in comma separated value (CSV) format as 
specified in section \@ref(input-datasets). Upload the dataset using the 
"upload CSV" input method.

The simulated dataset (from section \@ref(example-dataset)) is available to 
test the features of DiscoRhythm.

Messages or warnings may be seen at this point as DiscoRhythm imports 
the dataset and performs a few cleaning tasks:

- Rows where max=min (constant values) will be removed  
- Rows with missing values will be removed  
- Column names will be checked for valid formatting  
  - Duplicate column names will be deduplicated by replacing all `Unique Id`[^3]

[^3]: See \@ref(column-naming)

Specify the other analysis options for the dataset:  

**Time Type - **See \@ref(time-type).  

**Period of Interest - **The main hypothesized period should be specified in 
order to set appropriate defaults throughout the application. If unknown, set 
to the range of the sample collection times.

**Time Unit/Observation Unit - **Units to display in the axis labels throughout 
the application.

```{r echo=FALSE}
# Figure caption template
figcap="Screenshot of the '%s' section of the DiscoRhythm interface."

```

```{r selectData, echo=FALSE, fig.cap=sprintf(figcap,'Select Data')}
knitr::include_graphics("selectDataSS.jpg")
```

If the "Sampling Summary" table does not seem to accurately reflect the data, 
please refer back to section \@ref(column-naming). It is also a good idea 
to expand the "Inspect Input Data Matrix" and "Inspect Parsed Metadata" boxes 
to ensure the data has been read 
correctly.

## Outlier Removal

Experimental artifacts or errors commonly result in data from collected samples 
to be not accurately reflective of the true biological phenomenon. This can 
often be observed through systematic signals from a single sample which do not 
have biological plausibility. DiscoRhythm attempts to detect such systematic 
outliers by two methods:

- Intersample-correlations  
- Principal component analysis  

Each method is applied independently to the dataset to detect outliers and then 
the filtering summary section is used to decide which detected outliers to 
remove. A reasonable standard deviation threshold for both methods would be 
around 2 to 3. 

**By default, no outliers will be flagged for removal.** The DiscoRhythm web 
application will set the default threshold such that no outliers are flagged.

### Inter-sample Correlation

**Purpose:** Samples are pairwise correlated using either the Pearson or 
Spearman method of correlation to detect outliers. 

**Heatmap:** The values of these pairwise correlations can be visualized in this
tab, where samples with similar correlation values are grouped 
together using clustering.

**Outlier Detection:** The average correlation value for each sample is used as 
a metric of its overall similarity to all other samples and is summarized in 
this figure.  

Samples with a high deviation below the mean will be flagged as outliers where 
the user may specify a number of standard deviations below the mean to use as
a threshold.

```{r corQC, echo=FALSE, fig.cap=sprintf(figcap,'Inter-sample Correlation')}
knitr::include_graphics("IntersampleCorrelationSS.jpg")
```

### Principal Component Analysis

**Purpose:** Utilize principal component analysis (PCA) to detect outliers.

PCA is used to extract the strongest recurring patterns in the dataset. 
Outliers detected in these patterns (PC scores)
are flagged by their deviation from the mean where again the user may specify a 
threshold in units of standard deviations to use. 

**Scale Before PCA:** Whether to scale rows to a standard deviation of 1 prior
to PCA such that all rows are on an equal scale. Scaling is usually advisable.

**PCs to Use For Outlier Detection:** Click to change the list of PCs to use for
outlier removal in the
case a PC is determined inappropriate for use in outlier detection. You can 
remove unwanted PCs by pressing "delete" and add extra ones by typing 
their number.

**Before CSV/After CSV:** Downloadable summaries of the PCA before and after the
detected outliers are removed.

Figures:

**Distributions:** The distributions of PC scores 
used to detect outliers. Only the PCs colored darkly are used for the final
outlier flagging. Outliers will be shown with an 'x'. 

**Scree:** PCs are numbered where the amount of variance explained by each PC 
(therefore their 'importance') decreases with increasing PC number. 
This can be seen in the "Scree" figure. Users should choose an 
appropriate number of PCs to use for outlier detection by the 
shape of this scree plot.

**One Pair and All Pairs:** Plotting the PC scores of the components versus one 
another may reveal grouping that cannot be determined from simple analysis of 
individual PCs.

```{r pcaQC, echo=F, fig.cap=sprintf(figcap,'PCA')}
knitr::include_graphics("PCASS.jpg")
```

### Filtering Summary

**Purpose:** Determine how to proceed with outlier removal.

The user may at this point choose to remove the flagged outliers or may 
disregard these flags if it is suspected the dissimilarity of these samples may 
be biologically relevant. The user may also remove samples which they deem 
to be unreliable for further analysis by other metrics (e.g. experimental 
quality metrics).

**Raw Distributions:** A boxplot for each individual sample which can 
be used to further evaluate sample selection.

**Input and Final:** Shows summary tables for data before and after outlier removal.

```{r filteringSummary, echo=F, fig.cap=sprintf(figcap,'Filtering Summary')}
knitr::include_graphics("FilteringSummarySS.jpg")
```

## Row Selection

**Purpose:** Utilize any technical replicates present in the dataset to quantify
the signal-to-noise for each row. Combine technical replicates for downstream 
analysis.

Technical replicates are not useful for the statistical 
tests used by DiscoRhythm for oscillation detection as they are not 
representative of the populational variance of the data (i.e. do not satisfy 
the independence assumptions). They will instead be used to identify rows of 
the dataset where the biological variation is greater than the technical 
variation (i.e. high signal-to-noise). A hypothesis test is performed using 
ANOVA procedures to determine whether there may be a real biological signal in 
the row. 

**ANOVA Method:** 3 options are available for ANOVA:  

1) Equal Variance - all sets of technical replicates are assumed to have the 
same variance. Recommended in most cases.  
2) Welch - sets of technical replicates may have different variance.  
3) None - do not test rows using ANOVA.  

**F-statistic Cutoff:** The user may choose to filter rows by the magnitude
of the signal-to-noise rather than by statistical significance.

Replicates should be combined for downstream rhythmicity analysis. DiscoRhythm 
provides three methods for combining technical replicates:

- Mean - Take the mean of each set of technical replicates
- Median - Take the median of each set of technical replicates
- Random Selection - Take one of the technical replicates for each sample at 
random

*Note: Users may also choose to not combine technical replicates. This is only 
advisable if the technical replicates do in fact represent independent samples 
of the population/dataset (i.e. if they were erroneously labelled in section 
\@ref(input-datasets)).*

```{r repAnalysis, echo=F, fig.cap=sprintf(figcap,'Row Selection')}
knitr::include_graphics("RowSelectionSS.jpg")
```

## Period Detection

**Purpose:** Summarize the strength of multiple periodicities across 
the entire dataset.

### Period Detection

**Purpose:** Detecting the strength of a range of periods of oscillation across 
the entire dataset using a Cosinor based approach. 

Spectral analysis will be limited[^2] from a smallest period of 
3 times the sampling-interval up to the sampling duration and 12 periods 
will be tested evenly spaced across this range. 

[^2]: For circular time, only harmonics of the 
base-cycle will be available for testing. 

*Note: Experiments typically have a hypothesized period length (such as the 
organisms period of activity) and that period should be used for analysis in 
section \@ref(oscillation-detection) when possible. When using this tool for
determining which periodicity to use, follow up experiments may be appropriate
for validation.*

```{r domPer, echo=F, fig.cap=sprintf(figcap,'Period Detection')}
knitr::include_graphics("PeriodDetectionSS.jpg")
```

### PC fits

To determine the presence of a single rhythmic pattern in the data, PCA is 
performed to visualize and test the summarized temporal signal for rhythmicity 
(using the Cosinor method).

```{r PCfits, echo=F, fig.cap=sprintf(figcap,'PC Cosinor Fits')}
knitr::include_graphics("PCfitsSS.jpg")
```

## Oscillation Detection

**Purpose:** Individually quantify rhythmicity of remaining rows of the dataset 
where each row will be tested for rhythmicity using methods suitable for the 
sample collections present.

### Rhythmicity Calculation Configuration

The user must choose a single period[^5] of oscillation to test across all rows
of the dataset. The application may show warnings/messages regarding the choice
of period. By default, the period input in the 'Select Data' section will be
chosen.

[^5]: If it is unknown which periodicity to test start with the dominant period
seen in section \@ref(period-detection).

JTK Cycle, Lomb-Scargle, and ARSER results are all obtained through the 
MetaCycle R package (meta2d function using minper=maxper). Cosinor is a built-in
function of DiscoRhythm. A brief summary of each method:

**Cosinor** - a.k.a "Harmonic Regression" Fits a sinusoid 
with a free phase parameter.  
**JTK Cycle** - non-parametric test of rhythmicity robust to outliers.  
**Lomb-Scargle** - an approach using spectral power density. 
**ARSER** - removes linear trends and performs the Cosinor test.    

**Exclusion Criteria Matrix:** A table is presented which describes the criteria
which exclude a method from use and shown are criteria which are true for 
the loaded dataset[^6]. The reasons may be due to either computational 
(causes errors under given conditions) or statistical restrictions (requirements 
of study design) of the method.

[^6]: If no criteria are present, the table will be absent.

| Criteria              | Description               |
|-----------------------------|-------------------------------------|
| missing_value | Rows contain missing values. |
| with_bio_replicate | Biological replicates are present. |
| non_integer_interval | The spacing between samples is not an integer value. |
| uneven_interval | Time between collections is not uniform. |
| circular_t | Time is circular (see \@ref(time-type)).|
| invalidPeriod | Chosen period to test is not valid. |
| invalidJTKperiod | Chosen period to test is not valid for JTK Cycle. |

```{r detOsc, echo=F, fig.cap=sprintf(figcap,'Oscillation Detection (Preview)')}
knitr::include_graphics("OscillationDetectionPrevSS.jpg")
```

### Visualizing Results

Once rhythmicity computation is completed, 3 sections become available for 
viewing the results:

**Individual Models:** Allows inspection of the raw data for individual rows
of the dataset. User may click a row of the table to display the raw data and a
fitted curve for that row. If the Cosinor method is being viewed, the line will
be the Cosinor fit, all other methods utilize a loess fit. If the error bar 
option is selected, a 95% confidence interval on the mean will be displayed for
each timepoint.

**Summary:** Summarizes calculated rhythm parameters across all tested rows
by all executed methods.

**Method Comparison:** Offers pairwise comparison of rhythmic parameters
calculated by each method to determine the degree of agreement between methods.

```{r detOscResults, echo=F, fig.cap=sprintf(figcap,'Oscillation Detection')}
knitr::include_graphics("OscillationDetectionSS.jpg")
```

## Session Archiving

**Purpose:** Archive the results of the DiscoRhythm session in a reproducible 
report and download R data associated with the session.

**HTML Report** R code is provided in this report to reproduce all results. 
The data can be reprocessed in the future using this code.

**Session Results** Alternatively, data may be downloaded directly through 
the app and accessed from the disco_ro object in R.

**Session Inputs** Users may also simply download an R data file containing 
their input dataset and all parameters such that results can be reprocessed 
using the DiscoRhythm R package.

```{r batchReport, echo=F, fig.cap=sprintf(figcap,'Session Archiving')}
knitr::include_graphics("SessionArchivingSS.jpg")
```

# DiscoRhythm R Usage

This section will detail usage of the R functions used to perform the
analysis in section \@ref(discorhythm-interface-walkthrough). For each of
the sections below, refer to the DiscoRhythm R package manual for
specific technical details on usage, arguments and methods or use `?` to
access individual manual pages. For instance, 
get more 
help for the function `discoBatch()` with command `?discoBatch`.

## Data Import

`r BiocStyle::Biocpkg("SummarizedExperiment")` objects such as those generated 
by other Bioconductor packages
should be suitable inputs to DiscoRhythm functions
once modified to contain the following required data:

1) rownames(se) - The feature IDs.
2) assay(se) - A matrix containing experimental data.
3) colData(se) - Stores sample metadata (See \@ref(processed-metadata-table)).
3 columns are required:  

    - ID  
    - Time  
    - ReplicateID  

Objects with this structure will be used throughout usage of the package.  

*Note that at present DiscoRhythm will use the first assay 
(i.e. `assays(se)[[1]]`)
of the SummarizedExperiment and all others will be ignored.*

### discoDFtoSE

The CSV inputs to the DiscoRhythm web interface described in section 
\@ref(input-datasets) can be read into R as
a data.frame.
To allow for users using the web application to use the same input for
analysis in R, the function `discoDFtoSE` is available to convert the tabular 
input into an apporpriate format for analysis in R described in 
\@ref(data-import) above. 

The sample metadata will be 
extracted from the column 
names by matching the format[^4] described in section \@ref(column-naming).
The checks for validity and uniqueness mentioned in section \@ref(select-data)
will also be performed. Alternatively, this metadata may also be input directly 
to `discoDFtoSE` as a data.frame. 

[^4]: See `?discoParseMeta` for regular expression specifications.

Loading in the same example dataset as section \@ref(input-datasets) using
`discoGetSimu()` to read in the CSV system file as a data.frame:
```{r}
library(DiscoRhythm)
indata <- discoGetSimu()
knitr::kable(head(indata[,1:6]), format = "markdown") # Inspect the data
```

And importing as a `SummarizedExperiment`.

```{r}
se <- discoDFtoSE(indata)
```

### discoSEtoDF

The reverse operation, `discoSEtoDF`, is also available and is mainly intended
for the purpose of exporting data as CSV for input to the web application.

```
write.csv(discoSEtoDF(se),file = "DiscoRhythmInputFile.csv",row.names = FALSE)
```

Will export data for usage in the web application.

### discoCheckInput

This function performs the row-wise checks for missing values and constant 
values as mentioned in section \@ref(select-data). 

```{r}
selectDataSE <- discoCheckInput(se)
```

### discoDesignSummary

The sample collection information present in `colData(selectDataSE)` can be 
summarized by the `discoDesignSummary` function to detail the number of 
biological and technical replicates available at each collection time. Number of
technical replicates is shown in brackets.

```{r message=FALSE}
library(SummarizedExperiment)
Metadata <- colData(selectDataSE)
knitr::kable(discoDesignSummary(Metadata),format = "markdown")
```

## Outlier Detection

### discoInterCorOutliers

Performs the analysis described in \@ref(inter-sample-correlation) to
return some intermediate results and a vector indicating which samples
were determined to be outliers.

```{r}
CorRes <- discoInterCorOutliers(selectDataSE,
                                cor_method="pearson",
                                threshold=3,
                                thresh_type="sd")
```

### discoPCAoutliers

Performs the analysis described in \@ref(principal-component-analysis) to
return some intermediate results and a vector indicating which samples
were determined to be outliers.

```{r}
PCAres <- discoPCAoutliers(selectDataSE,
                           threshold=3,
                           scale=TRUE,
                           pcToCut = c("PC1","PC2","PC3","PC4"))
```

### discoPCA

A light wrapper was written for the `stats::prcomp` function for better use with
the web application and it can be utilized as:

```{r}
discoPCAres <- discoPCA(selectDataSE)
```

This returns the same output as prcomp with the addition of a reformatted 
summary table (available as `PCAresAfter$table`).

### Filtering Summary

Below the results of the outlier detection analysis (`CorRes` and `PCAres`) 
are used to subset the data to remove outliers:

```{r}
FilteredSE <- selectDataSE[,!PCAres$outliers & !CorRes$outliers]

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

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

## Row Selection

### discoRepAnalysis

Performs the analysis described in \@ref(row-selection) returning the results
of the ANOVA test and the `se` data object where technical replicates 
are combined.

```{r}
ANOVAres <- discoRepAnalysis(FilteredSE,
                             aov_method="Equal Variance",
                             aov_pcut=0.05,
                             aov_Fcut=1,
                             avg_method="Median")

FinalSE <- ANOVAres$se
```

## Dominant Rhythmicities  

### discoPeriodDetection

Performs the analysis described in \@ref(period-detection) to return a 
data.frame of Cosinor fits across a range of periods.

```{r}
PeriodRes <- discoPeriodDetection(FinalSE,
                                  timeType="linear",
                                  main_per=24)
```

The main period of interest is fit using a Cosinor model to principal component 
scores as described in \@ref(period-detection).

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

## Oscillation Detection

### discoODAs

Performs the analysis described in \@ref(rhythmicity-calculation-configuration) 
using just the Cosinor method. 
`discoODAs` will automatically run all appropraite methods
if none are provided.

```{r}
discoODAres <- discoODAs(FinalSE,
                         period=24,
                         method="CS",
                         ncores=1,
                         circular_t=FALSE)
```

## Batch Execution

### discoBatch

The entire analysis performed in section \@ref(discorhythm-r-usage) may be 
run through a single call to `discoBatch()` to obtain the final `discoODAres`
results.

```
discoBatch(indata=indata,
  report="discoBatch_example.html",
  ncores=1,
  main_per=24,
  timeType="linear",
  cor_threshold=3,
  cor_method="pearson",
  cor_threshType="sd",
  pca_threshold=3,
  pca_scale=TRUE,
  pca_pcToCut=paste0("PC",seq_len(4)),
  aov_method="None",
  aov_pcut=0.05,
  aov_Fcut=0,
  avg_method="Median",
  osc_method="CS",
  osc_period=24)
```

This command will generate an html report called "discoBatch_example.html"
which includes the 
visualizations seen in the DiscoRhythm application. `indata` may be in either
of the two input formats described in \@ref(data-import) (`data.frame` or
`SummarizedExperiment`).

# Session Info

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

