---
title: "PvSeroApp in R Tutorial"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{PvSeroApp in R Tutorial}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
options(rmarkdown.html_vignette.check_title = FALSE)
setup <- function() {
  needed <- c("knitr", "rmarkdown", "tidyverse", "kableExtra")
  
  lapply(needed, function(pkg) {
    if (requireNamespace(pkg, quietly = TRUE)) {
      library(pkg, character.only = TRUE)
    }
  })
}

setup()
library(SeroTrackR)
```

## Data Analysis: `runPvSeroPipeline()` 

Run this global function `runPvSeroPipeline()` embedded within the `{SeroTrackR}` R package! This function contains all of the steps in order of how to perform the *Plasmodium vivax* serology test and treat protocol as found in our [application](https://dionnecargy.shinyapps.io/PvSeroApp/)! 

### Visualisation of the PvSeroApp Pipeline

![](../man/figures/SeroTrackR_PvSeroApp.png)

### Using Tutorial Dataset: Load the Data

We will be using the build-in files in the R package for this tutorial, as shown below. 

```{r setup 1}
library(SeroTrackR)
library(tidyverse)

your_raw_data <- c(
  system.file("extdata", "example_MAGPIX_plate1.csv", package = "SeroTrackR"),
  system.file("extdata", "example_MAGPIX_plate2.csv", package = "SeroTrackR"), 
  system.file("extdata", "example_MAGPIX_plate3.csv", package = "SeroTrackR")
)
your_plate_layout <- system.file("extdata", "example_platelayout_1.xlsx", package = "SeroTrackR")
```

To run your OWN data, follow the code below and uncomment (i.e., remove the hashtags): 

```{r, exec=FALSE, eval=FALSE}
your_raw_data <- c(
  "PATH/TO/YOUR/FILE/plate1.csv",
  "PATH/TO/YOUR/FILE/plate2.csv",
  "PATH/TO/YOUR/FILE/plate3.csv"
)
your_plate_layout <- "PATH/TO/YOUR/FILE/plate_layout.xlsx"
```

### Run Classification: Yes

```{r runPvSeroPipeline with classification}
final_analysis <- runPvSeroPipeline(
  raw_data = your_raw_data, 
  plate_layout = your_plate_layout, 
  platform = "magpix", 
  location = "ETH", 
  experiment_name = "experiment1", 
  classify = "Yes", 
  algorithm_type = "antibody_model", 
  sens_spec = "balanced"
)
```

#### Classification 

This is a table containing the classification results (seropositive or seronegative) for each `SampleID`. In this case, the classification results are stored in the `pred_class_max` column as we chose the `sens_spec = "balanced"`. If you change it to another type of threshold, then the suffix of that column will change accordingly. 

You will also see the relative antibody unit (RAU) values (columns with antigen names), whether the sample passed QC check (`QC_total`) and the `plate` that they were run on. 

```{r classification tab 1}
final_analysis[[1]] %>%
  head() %>% 
  kable()
```

#### Standard Curve Plot

The standard curve plots are generated from the antibody data from the standards you indicated in your plate layout (e.g. S1-S10) and Median Fluorescent Intensity (MFI) units are displayed in log10-scale. In the case of the PvSeroTaT multi-antigen panel, the antigens will be displayed and in general your standard curves should look relatively linear (only when the y-axis is on logarithmic scale). 

```{r std curve plot tab 1}
final_analysis[[2]]
```

#### Bead Counts QC Plot

A summary of the bead counts for each plate well are displayed, with blue indicating there are sufficient beads (≥15) or red when there are not enough. If any of the wells are red, they should be double-checked manually and re-run on a new plate if required.

The function will inform you whether there are "No repeats necessary" or provide a list of samples to be re-run. In the example data, the beads in plate 2 wells A1 and A2 will need to be repeated

```{r bead counts plot tab 1}
final_analysis[[3]] # Plot
final_analysis[[4]] # Samples to repeat 
```

#### Blanks QC Plot

The Median Fluorescent Intensity (MFI) units for each antigen is displayed for your blank samples. In general, each blank sample should have ≤50 MFI for each antigen, if they are higher they should be cross-checked manually.

In the example data, blank samples recorded higher MFI values for LF005 on plate 1 and should be checked to confirm this is expected from the assay.

```{r blanks qc plot tab 1}
final_analysis[[5]]
```

#### Model Output Plot

The automated data processing in this app allows you to convert your Median Fluorescent Intensity (MFI) data into Relative Antibody Units (RAU) by fitting a 5-parameter logistic function to the standard curve on a per-antigen level. The results from this log-log conversion should look relatively linear for each antigen.

```{r model output plot tab 1}
final_analysis[[6]]
```

### Run Classification: No

```{r runPvSeroPipeline without classification}
no_classification_final_analysis <- runPvSeroPipeline(
  raw_data = your_raw_data, 
  plate_layout = your_plate_layout, 
  platform = "magpix", 
  location = "ETH", 
  experiment_name = "experiment1", 
  classify = "No", ########################## key if you do NOT want any classification performed i.e., you do not have PvSeroTaT antigens 
  algorithm_type = "antibody_model", 
  sens_spec = "balanced"
)
```


#### MFI and RAU Data 

```{r mfi and rau tab 2}
no_classification_final_analysis[[1]]  %>%
  head() %>% 
  kable()
```

#### QC Plots

Repeat the same steps as above to find the QC plots! 

```{r std curve plot tab 2}
#### Standard Curve Plot
no_classification_final_analysis[[2]]

#### Bead Counts QC Plot
no_classification_final_analysis[[3]] # Plot
no_classification_final_analysis[[4]] # Samples to repeat 

#### Blanks QC Plot
no_classification_final_analysis[[5]]

#### Model Output Plot
no_classification_final_analysis[[6]]
```


### Create a PDF Report

```{r create pdf output, exec=FALSE, eval=FALSE}
renderQCReport(
  your_raw_data, 
  your_plate_layout, 
  "magpix", 
  location = "ETH",
  path = "inst/tutorials/" # defaults to your current working directory
)
```
