---
title: "Dimensionality Reduction"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Dimensionality Reduction}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  markdown: 
    wrap: 72
---

```{r setup, warning=FALSE, message=FALSE}
library(cyCONDOR)
```

In this vignette we showcase `cyCONDOR` functions for dimensionality reduction. We exemplify how to perform Principle Component Analysis (PCA) and calculate Uniform Manifold Approximation and Projection (UMAP), t-Distributed Stochastic Neighbor Embedding (tSNE) and Diffusion Map (DM). 

All functions need the `condor` object as `fcd` input and the `data_slot` to be used for the calculation. The `runPCA` function always uses the `expr` slot for the calculation, for non-linear dimensionality reduction (UMAP, tSNE, DM) the user can decide to use the `expr` data or the `pca` result as `input_type`. 

Additionally, the user has the option to specifically state which markers should be used for the calculation by listing them under `markers`. The list can be either written out manually or be extracted directly from the `condor` object using the implemented functions `measured_markers` and `used_markers` By default all available markers from the `condor` object are used. If the `discard` option is set to TRUE, all markers **except** the ones listed under `markers` are used for calculation. This enables the exclusion of single markers. When using `pca` as input is possible to specify the number of PCs to be used.

By defining a `prefix` which gets incorporated into the slot name of the output, each function can be run with different settings and the results will be saved accordingly.

The functions return a fcd with an additional data frame corresponding to the chosen dimensionality reduction method saved in `fcd$reduction_method`. The name of the output consists of the `prefix` (if given) and the `data_slot`.


# Marker selection using the `marker` and `discard` variables

It is possible to specify the markers which should be the basis for the calculation using a combination of the `markers` variable and the `discard` flag in all dimensionality reduction functions. `markers` takes a vector of marker names as an input that should be included (positive selection) or excluded (negative selection). The user can choose to either discard the specified markers by setting the `discard` flag to TRUE (negative selection) or to keep only the specified markers by using the default setting of the `discard` flag (positive selection). 

The marker names should correspond to a specific column in the expression table and can be given manually or can be extracted from the condor object using the `cyCONDOR` function `used_markers`. When performing a marker selection the user should make sure that a prefix for the output name is set to avoid overwriting a previously calculated matrix. 

The option of marker selection is implemented in all dimensionality reduction functions but we only demonstrate it for PCA.

# Load an example dataset
```{r}
condor <- readRDS("../.test_files/conodr_example_016.rds")
```

# Principal Component Analysis (PCA)

The calculation of the Principle Components is based on the `prcomp` function from the R Stats package (https://rdocumentation.org/packages/stats/versions/3.6.2).

```{r}
condor <- runPCA(fcd = condor,
                 data_slot = "orig",
                 seed = 91)
```
The output data frame of the PCA can be accessed with `condor$pca$orig`.

As a demonstration the following code shows a positive and negative selection with the corresponding `discard` flag setting.

### PCA (Positive selection: Specifying the markers to be used as basis for the calculation)

```{r}
condor <- runPCA(fcd = condor,
                 data_slot = "orig",
                 seed = 91,
                 prefix =  "Tcell",
                 markers = c("CD3", "CD4", "CD8"),
                 discard = FALSE)
```
The output data frame of the PCA with positive marker selection can be accessed with `condor$pca$Tcell_orig`.

### PCA (Negative selection: Excluding a specific marker from the calculation)


```{r}
condor <- runPCA(fcd = condor,
                 data_slot = "orig",
                 seed = 91,
                 prefix =  "scatter_exclusion",
                 markers = c("FSC-A", "SSC-A"),
                 discard = TRUE)
```
The output data frame of the PCA with negative marker selection can be accessed with `condor$pca$scatter_exclusion_orig`.


# UMAP

The calculation of the UMAP is based on the `umap` function from the uwot package. For more details see: Melville J (2023). "uwot: The Uniform Manifold Approximation and Projection (UMAP) Method for Dimensionality Reduction" <https://github.com/jlmelville/uwot>.

Besides important metrics that can be set in the uwot umap function (e.g. number of items that define a neighborhood around each point (`nNeighbors`) and minimum distance between embedded points (`min_dist`)) the `runUMAP` function implemented in `cyCondor` has additional parameters that can be adjusted. Next to the selection of `markers` and an output `prefix` the user can specify the number of PCs that should be used for the umap calculation (`nPC`) and has the option to save the umap model for future data projection (`ret_model`).

```{r, eval=FALSE}
condor <- runUMAP(fcd = condor, 
                  input_type = "pca", 
                  data_slot = "orig", 
                  seed = 91)
```
The output data frame of the UMAP coordinates can be accessed with `condor$umap$pca_orig`.


# tSNE

The tSNE calculation is based on the function `Rtsne` from the package `Rtsne`. The implementation in `cyCondor` allows for the  definition of the perplexity used in the tSNE calculation. This parameter controls how many nearest neighbors should be taken into account when constructing the embedding. The user has the option, similar as in the UMAP function, to select the number of PCs which should be used for the calculation. For more details see: Jesse H. Krijthe (2015). "Rtsne: T-Distributed Stochastic Neighbor Embedding using a Barnes-Hut Implementation" <https://github.com/jkrijthe/Rtsne>.


```{r, eval=FALSE}
condor <- runtSNE(fcd = condor, 
                  input_type = "pca", 
                  data_slot = "orig", 
                  seed = 91, 
                  perplexity = 30)
```
The output data frame of the tSNE coordinates can be accessed with `condor$tSNE$pca_orig`.

# Diffusion Map

The calculation of DM is based on the function `DiffusionMap` from the package `destiny`. The number of nearest neighbors to be considered can be specified with `k`. Here, the user has as well the option to select the number of PCs which should be used for the calculation. For more deatils see: Philipp Angerer et al. (2015). "destiny: diffusion maps for large-scale single-cell data in R." Helmholtz-Zentrum München.<http://bioinformatics.oxfordjournals.org/content/32/8/1241>.

```{r, eval=FALSE}
condor <- runDM(fcd = subset_fcd(condor, 5000), 
                input_type = "pca", 
                data_slot = "orig", 
                k = 10, 
                seed = 91)
```
The output data frame of the DM can be accessed with `condor$diffmap$pca_orig`.


# Session Info
```{r}
info <- sessionInfo()

info
```

