---
title: "OpenArray PCR Report"
date: "`r Sys.Date()`"
output:
    html_document:
        self_contained: true
params:
    data_path: NULL
    model_results: NULL
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
# load in data
se <- readRDS(params$data_path)

col_data <- as.data.frame(colData(se))
row_data <- as.data.frame(rowData(se))
metadata <- metadata(se)
```

## Description

A report document summarizing multiplex PCR data from a gene expression 
experiment carried out on the TaqMan OpenArray platform. Covers run metadata,
core visualizations, and PCR results for reporting. 

## Metadata

### Source File

```{r}
metadata(se)$source_file
```

### Run Information

```{r}
metadata(se)$run_info
```

## Visualizations

### Quality Control

Displays critical quality control metrics output by QuantStudio 12K Flex 
Software on 3 axes for easy identification of outlying PCR curves.

* Crt       - relative cycle threshold

* Amp Score - quality of the amplification curve

* Cq Conf   - reliability of the Crt value

```{r, fig.align='center'}
OAtools::plotQC(se)
```

For ideal sensitivity and specificity, Thermo Fisher recommends the following
quality standards:

* Crt       < 28

* Amp Score >= 1.2

* Cq Conf   >= 0.7

Results with a Crt of 28 or higher may reflect false positives. Note that 
the ideal thresholds in practice may vary slightly by the particular assay.

The following curves have been flagged for Crt value, amp score, or Cq conf:

```{r}
col_data |> 
    dplyr::select(
        sample_name:target_name, crt, amp_score:amp_status
    ) |> 
    dplyr::filter(
        (crt > 28 & !is.na(crt))
        | (amp_score < 1.2 & amp_score != 0)
        | (cq_conf < 0.7 & cq_conf != 0)
    ) |> 
    knitr::kable(
        format = "html",
        align = rep("l", ncol(col_data))
    ) |> 
    kableExtra::kable_styling(
        bootstrap_options = c("striped", "hover", "bordered"),
        full_width = TRUE
    )
```

### Amplification Overview

Summarizes the amplification status of each sample per gene target in a 
categorical matrix plot. Technical replicates are grouped into single cells, 
where the highest amplification status is displayed. That is, if one replicate 
is positive and the other negative, the cell is displayed as positive.

Allows for verification of assay control or identification of abnormal 
amplification results, contamination, etc. at a glance. 

```{r}
OAtools::plotOverview(se)
```

### Crt Distribution

Shows the distribution of observed cycle threshold values by gene target. 

```{r}
OAtools::plotCrt(se)
```

## PCR Results

Summarizes the PCR results for each sample by gene target in a tabular format. 

The logic is analogous to the overview plot: technical replicates are grouped 
into distinct rows, where the highest result is indicated. That is, if one 
replicate is positive and the other negative, the sample is displayed as 
positive for that assay.

```{r}
result_table <- col_data |> dplyr::group_by(sample_name, target_name)

# pull sample results from curve-fitting analysis, or QS 12K Flex analysis
if (params$model_results) {
    result_table <- result_table |> dplyr::summarise(
        mean_crt = mean(crt),
        high_amp_status = dplyr::case_when(
            any(.data$amp_status == "Amp") ~ "Amp",
            any(.data$amp_status == "Inconclusive") ~ "Inconclusive",
            TRUE ~ "No Amp"
        ),
        result = dplyr::case_when(
            any(.data$result == "positive") ~ "Positive",
            any(.data$result == "inconclusive") ~ "Inconclusive",
            TRUE ~ "Negative"
        ),
        .groups = "drop"
    )
} else {
    result_table <- result_table |> dplyr::summarise(
        mean_crt = mean(crt),
        high_amp_status = dplyr::case_when(
            any(.data$amp_status == "Amp") ~ "Amp",
            any(.data$amp_status == "Inconclusive") ~ "Inconclusive",
            TRUE ~ "No Amp"
        ),
        .groups = "drop"
    )
}

# formatting for PCR results
result_table |> 
    dplyr::mutate(mean_crt = round(mean_crt, 1)) |> 
    DT::datatable(
        filter = "top",
        options = list(
            pageLength = 48,
            autoWidth = TRUE,
            columnDefs = list(list(className = 'dt-center', targets = "_all"))
        )
    ) |> 
    DT::formatStyle(columns = colnames(result_table))
```
