---
title: "treekoR"
date: "`r BiocStyle::doc_date()`"
author:
- name: Adam Chan
  affiliation:  
  - School of Mathematics and Statistics, The University of Sydney, Sydney, New South Wales, Australia
  email: adam.s.chan@sydney.edu.au
- name: Ellis Patrick
  affiliation:
  - &WIMR Westmead Institute for Medical Research, University of Sydney, Australia
  - School of Mathematics and Statistics, The University of Sydney, Sydney, New South Wales, Australia
output:
  BiocStyle::html_document:
    toc: true
    toc_depth: 2
vignette: >
  %\VignetteIndexEntry{vignette}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
# Load required packages
suppressPackageStartupMessages({
  library(treekoR)
  library(SingleCellExperiment)
  library(ggtree)
})
```

# Installation
```{r eval=F}
# Install the development version from GitHub:
# install.packages("devtools")
devtools::install_github("adam2o1o/treekoR")
library(treekoR)
```

# Overview
treekoR is a novel framework that aims to utilise the hierarchical nature of single cell cytometry data, to find robust and interpretable associations between cell subsets and patient clinical end points. This is achieved by deriving the tree structure of cell clusters, followed by measuring the %parent (proportions of each node in the tree relative to the number of cells belonging to the immediate parent node), in addition to the %total (proportion of cells in each node relative to all cells). These proportions are then used in significance testing and classification models to determine which cell subpopulation proportions most correlated with the patient clinical outcome of interest. treekoR then provides an interactive visualisation which helps to highlight these results.

# Usage
## Example Data
- DeBiasi_COVID_CD8_samp:
A `SingleCellExperiment` containing samples of flow cytometry expression data from 39 patients. This data represents a subset of a dataset that was originally used by De Biasi et al. (2020) for the characterisation of CD8+ T cells, comparing between COVID-19 patients and healthy controls.

```{r}
data(COVIDSampleData)

sce <- DeBiasi_COVID_CD8_samp
```

## Set up
treekoR requires the following information in the variables:

- `exprs`: Single cell expression data ($n \times p$), where $p$ is the number of markers, and $n$ is the number of cells 
- `clusters`: a vector of length $n$ representing the cell type or cluster of each cell (can be `character` or `numeric`)
- `classes`: a vector of length $n$ containing the patient outcome/class each cell belongs to
- `samples`: a vector of length $n$ identifying the patient each cell belongs to

In this example: the `clusters` contain 100 clusters generated by FlowSOM; `classes` identify whether the cell belongs to a COVID-19 or healthy patient; and `samples` identify which cell the patient comes from.

```{r}
exprs <- t(assay(sce, "exprs"))
clusters <- colData(sce)$cluster_id
classes <- colData(sce)$condition
samples <- colData(sce)$sample_id
```


## Construction of Hierarchy of Clusters

The scaled median marker expression for each cluster is calculated which is used to construct a hierarchical tree. 

In this step, the choice of hierarchical aggregation method (which determines the structure of the tree) is determined. By default the framework chooses HOPACH to construct the tree via the `hierarchy_method` argument, however any of the methods in `hclust` can be used (see \@ref(hc-methods)).

```{r}
clust_tree <- getClusterTree(exprs,
                             clusters,
                             hierarchy_method="hopach")
```

## Significance testing of Cell Subpopulations

Proportions of each cell cluster in the tree are calculated - both the proportion relative to all and proportion relative to the hierarchical parent. These proportions are used in a two sample t-test, testing for equal means between the patient clinical outcome using both types of proportions.

```{r}
tested_tree <- testTree(phylo=clust_tree$clust_tree,
                      clusters=clusters,
                      samples=samples,
                      classes=classes,
                      pos_class_name=NULL)
```

### Extracting significance results

- `node`: unique identifier for each node in the hierarchical tree
- `parent`: the node of the parent
- `isTip`: whether the node is a leaf node in the tree
- `clusters`: the clusters belonging to the corresponding node
- `stat_all`: test statistic obtained from testing between conditions using the proportion of the node relative to all cells (%total) in each sample. `pval_total` is the corresponding p-value (unadjusted)
- `stat_parent`: test statistic obtained from testing between conditions using the proportion of the node relative to cells in the parent node (%parent) in each sample. `pval_parent` is the corresponding p-value (unadjusted)


```{r}
res_df <- getTreeResults(tested_tree)

head(res_df, 10)
```


## Interactive Visualisation

The results of the previous steps are visualised by a coloured tree with a corresponding heatmap. The heatmap displays the median scaled marker expressions of each cluster to help understand what cell type each cluster may represent, and the tree not only reveals how clusters have been hierarchically aggregated, but is coloured on each node by the test statistic obtained when testing using the proportions relative to all of that node, with the branch connecting the child to the parent coloured by the test statistic obtained when testing using the proportions relative to parent of the child node. 


```{r}
plotInteractiveHeatmap(tested_tree,
                       clust_med_df = clust_tree$median_freq,
                       clusters=clusters)
```

### Using different hierarchical aggregations {#hc-methods}

Below we change the hierarchical aggregation technique to average-linkage hierarchical clustering.
The available options include any of the available ethods in the `hclust()` function, ie, one of `"ward.D"`, `"ward.D2"`, `"single"`, `"complete"`, `"average"`, `"mcquitty"`, `"median"` or `"centroid"`

```{r}
clust_tree <- getClusterTree(exprs,
                             clusters,
                             hierarchy_method="average")

tested_tree <- testTree(clust_tree$clust_tree,
                      clusters=clusters,
                      samples=samples,
                      classes=classes,
                      pos_class_name=NULL)

plotInteractiveHeatmap(tested_tree,
                       clust_med_df = clust_tree$median_freq,
                       clusters=clusters)
```

### Using counts models for significance testing 

Below we change the significance test to use count models instead of a t-test/Wilcoxon test. The available methods are `"GLMM"` or `"edgeR"`

```{r}
clust_tree <- getClusterTree(exprs,
                             clusters,
                             hierarchy_method="hopach")

tested_tree_edgeR <- testTree(clust_tree$clust_tree,
                      clusters=clusters,
                      samples=samples,
                      classes=classes,
                      sig_test="edgeR",
                      pos_class_name="COV")

plotInteractiveHeatmap(tested_tree_edgeR,
                       clust_med_df = clust_tree$median_freq,
                       clusters=clusters)
```
You can also extract edgeR FDR values as so:
```{r}
head(tested_tree_edgeR$data[,c("parent", "node", "isTip", "clusters", "FDR_parent", "FDR_total")])
```


## Feature extraction
Extract cell type proportions (both %total and %parent), as well as the geometric mean of each marker per cell type. These can then be used for further investigation via visualisation or machine learning.

### Extracting Proportions
The function below returns a dataframe containing the absolute proportions and proportions to parent for each cell type for each sample.

`perc_parent_n_celltype` denotes the proportion of the cell type relative to its parent (%parent) n generations away, ie. `perc_parent_1_2` is the proportion of cluster 2 relative to its direct parent in the hierarchical tree. 

`perc_total_celltype` denotes the proportion of the cell type relative all cells (%total)
```{r}
prop_df <- getCellProp(phylo=clust_tree$clust_tree,
                       clusters=clusters,
                       samples=samples,
                       classes=classes)

head(prop_df[,1:8])
```

### Extracting Expression Geometric Means
The function below returns a dataframe containing the geometric mean for each marker for each cell type for each sample.

`m_gmean_celltype` denotes the geometric mean of marker m in the cell type per sample
```{r}
means_df <- getCellGMeans(clust_tree$clust_tree,
                          exprs=exprs,
                          clusters=clusters,
                          samples=samples,
                          classes=classes)

head(means_df[,1:8])
```


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

