---
title: "CompensAID workflow"
author: "Rosan Olsman"
date: "`r BiocStyle::doc_date()`"
vignette: >
  %\VignetteIndexEntry{Overview_CompensAID}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
package: "CompensAID"
output: 
  BiocStyle::html_document:
    toc: true
    number_sections: true
---

# Introduction
The CompensAID package provides quality control for evaluating the potential presence of reference errors in flow cytometry data. It requires pre-processed Flow Cytometry Standard (FCS) files as input.
The tool automatically calculates the standard deviation (SD) and median fluorescence intensity (MFI) in the secondary channel for both the negative and positive populations defined in the primary channel.
Next, the positive population is divided into equal segments, and for each segment, the Secondary Stain Index (SSI) is computed. 
This process allows for a more detailed assessment of marker combinations affected by reference errors. 

# Installing CompensAID
Not evaluated, run to install packages
```{r eval=FALSE}
# Install BiocManager if not already installed
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

# Install devtools if not already installed
if (!requireNamespace("devtools", quietly = TRUE))
    install.packages("devtools")

# Install ggcyto development version from GitHub - otherwise does not work with ggplot2
devtools::install_github("RGLab/ggcyto", ref = "devel")

# Install CompensAID from GitHub
devtools::install_github("Olsman/CompensAID")

# Install ggplot2 from Bioconductor - older version otherwise it ggcyto gives errors
devtools::install_version("ggplot2", version = "3.5.2", repos = "http://cran.us.r-project.org")

# Load libraries
library(ggplot2)
library(ggcyto)
library(CompensAID)
```

# Pre-processing
The CompensAID package operates on pre-processed FlowFrame objects to evaluate the presence of reference errors. Below is an example pipeline for preparing your data:
1. Removal of margin events (conventional FCS files)
2. Compensation (conventional FCS files)
3. Logicle transformation
4. Quality control using PeacoQC
Note: Doublets and debris are not removed in this pipeline. In this example, scatter channels are excluded entirely from the FCS file.
```{r eval=FALSE}
# Read flowFrame
file <- flowCore::read.FCS(system.file("extdata", "raw.68983.fcs", package = "CompensAID"))

# Remove margins (for conventional only)
file <- PeacoQC::RemoveMargins(ff = file,
                               channels = colnames(flowCore::exprs(file)),
                               output = "frame")

# Compensate data (for conventional only)
file <- flowCore::compensate(file, file@description$SPILL)

# Transform data 
file <- flowCore::transform(file,
                            flowCore::estimateLogicle(file, colnames(flowCore::keyword(file)$SPILL)))

# Run PeacoQC
file <- PeacoQC::PeacoQC(ff = file,
                       channels = colnames(flowCore::exprs(file)),
                       save_fcs = FALSE,
                       plot = FALSE,
                       report = FALSE,
                       output_directory = NULL)
file <- file$FinalFF

# Retain only markers
file <- file[, names(flowCore::markernames(file))]
```

# Final data
The data file is processed as shown above
```{r Clean}
# Pre-processed data 
file <- flowCore::read.FCS(system.file("extdata", "68983.fcs", package = "CompensAID"))
```

# CompensAID: run tool
The CompensAID tool is used here with its default parameter settings. A segment.value of four, which defines the number of segments within the positive population, was found to be suitable for both conventional and spectral flow cytometry data.
The minimum number of events per segment is set to 50 by default. If you observe segments with very negative Secondary Stain Index (SSI) values and few events, this could indicate a false-positive finding by the tool
```{r CompensAID}
# CompensAID
res.compensaid <- CompensAID::CompensAID(ff = file)
```

# Secondary Stain Index Matrix
Visualize the output of the CompensAID tool.
```{r Matrix, fig.width=5, fig.height=5}
matrix <- CompensAID::PlotMatrix(output = res.compensaid)
print(matrix)
```

# Identify flagged marker combinations 
Obtain marker combinations with a Secondary Stain Index < -1.
```{r Identification}
# Check SSI < -1
index <- which(res.compensaid[["matrix"]] < -1, arr.ind = TRUE)

# Obtain marker names
library(dplyr)
combination <- data.frame(primary.channel = rownames(res.compensaid[["matrix"]])[index[, "col"]],
                          secondary.channel = rownames(res.compensaid[["matrix"]])[index[, "row"]]) |>
  dplyr::mutate(primary.marker = flowCore::markernames(file)[primary.channel],
                secondary.marker = flowCore::markernames(file)[secondary.channel])
```

# Dot plots
Visualize the flagged marker combinations.
```{r Dotplot, fig.width=5, fig.height=5}
# Visualize dot plot with SSI scores
dotPlot <- CompensAID::PlotDotSSI(output = res.compensaid,
                                  og = file,
                                  primary = combination$primary.marker[1],
                                  secondary = combination$secondary.marker[1],
                                  showScores = TRUE)
print(dotPlot)
```

# Session info
```{r SessionInfo}
sessionInfo()
```
