---
title: "Applying PROGENy on single-cell RNA-seq data"
author:
- name: Alberto Valdeolivas
  affiliation: Institute for Computational Biomedicine, Heidelberg University
  email: alberto.valdeolivas@bioquant.uni-heidelberg.de
- name: Igor Bulanov
  affiliation: Institute for Computational Biomedicine, Heidelberg University
- name: Christian Holland 
  affiliation: Institute for Computational Biomedicine, Heidelberg University
- name: Julio Saez-Rodriguez 
  affiliation: Institute for Computational Biomedicine, Heidelberg University 
   
package: progeny
output:
  BiocStyle::html_document
bibliography: Mybib2.bib
abstract: |
  This vignette describes how to infer the activity of 14 relevant signaling 
  pathways by running PROGENy on single-cell RNA-seq data. 
license: GNU-GLPv3, please check http://www.gnu.org/licenses/
vignette: |
  %\VignetteIndexEntry{Applying PROGENy on single-cell RNA-seq data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Introduction

Conventional pathway analysis methods rely on the gene expression of the pathway 
members. However, this approach overlook the effect of post-translational 
modifications and only captures very specific experimental conditions. 
To overcome these limitations, **PROGENy** (Pathway RespOnsive GENes) estimates 
the activity of relevant signaling pathways based on consensus gene signatures 
obtained from perturbation experiments, in other words, the footprint of the 
pathway on gene expression [@Schubert2018 ,@dugourd2019].

**PROGENy** initially contained 11 pathways and was developed for the 
application to human transcriptomics data. It has been recently shown that
**PROGENy** is also applicable to mouse data [@HOLLAND2019194431] and to single 
cell RNAseq data [@Holland2019]. In addition, they expanded human and mouse 
**PROGENy** to 14 pathways.

This vignette shows an example on how to apply **PROGENy** in a well known 
single-cell dataset. To analyse the data, we followed the standard procedures of
the `r CRANpkg("Seurat")` toolkit for single cell genomics [@Stuart2019]. 

# Installation

First of all, you need a current version of R (http://www.r-project.org). 
`r Biocpkg("progeny")` is a freely available annotation package deposited on 
http://bioconductor.org/ and https://https://github.com/saezlab/progeny.  

You can install it by running the following commands on an R console:

```{r, eval=FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("progeny")

## To install the new version until it is submitted to Bioconductor use:
devtools::install_github("saezlab/progeny")
```

We also load here the packages required to run this script. 

```{r, message=FALSE}
library(progeny)
library(dplyr)
library(Seurat)
library(ggplot2)
library(tidyr)
library(readr)
library(pheatmap)
library(tibble)
```

# Example of usage

In the following paragraphs, we provide examples describing how to run 
**PROGENy** on a scRNA-seq dataset. In particular, we use the 
`r CRANpkg("Seurat")` toolkit for single cell genomics [@Stuart2019]. For the 
sake of simplicity, we follow the example provided in the following 
`r CRANpkg("Seurat")` vignette:  

https://satijalab.org/seurat/v3.1/pbmc3k_tutorial.html 

The dataset contains 2,700 Peripheral Blood Mononuclear Cells (PBMC) that were 
sequenced on the Illumina NextSeq 500. This dataset is freely available in 
10X Genomics: 

https://s3-us-west-2.amazonaws.com/10x.files/samples/cell/pbmc3k/pbmc3k_filtered_gene_bc_matrices.tar.gz

```{r, eval=FALSE}
## Load the PBMC dataset
pbmc.data <- 
    Read10X(data.dir = "../data/pbmc3k/filtered_gene_bc_matrices/hg19/")
## Initialize the Seurat object with the raw (non-normalized data).
pbmc <- 
    CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, 
    min.features = 200)
```

```{r, eval=TRUE , include=FALSE}
pbmc <- 
    readRDS(url("https://github.com/alberto-valdeolivas/ProgenyVignette/raw/master/SeuratObject.rds"))
```

## Pre-processing, normalization and identification of highly variable features

We follow the standard pre-processing steps as described in the aforementioned 
`r CRANpkg("Seurat")` vignette before going deeper into the data analysis. 
These steps carry out the selection and filtration of cells based on quality
control metrics, the data normalization and scaling, and the detection of highly
variable features (see https://satijalab.org/seurat/v3.1/pbmc3k_tutorial.html). 

```{r, message=FALSE}
## Identification of mithocondrial genes
pbmc[["percent.mt"]] <- PercentageFeatureSet(pbmc, pattern = "^MT-")

## Filtering cells following standard QC criteria.
pbmc <- subset(pbmc, subset = nFeature_RNA > 200 & nFeature_RNA < 2500 & 
    percent.mt < 5)

## Normalizing the data
pbmc <- NormalizeData(pbmc, normalization.method = "LogNormalize", 
    scale.factor = 10000)

pbmc <- NormalizeData(pbmc)

## Identify the 2000 most highly variable genes
pbmc <- FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000)

## In addition we scale the data
all.genes <- rownames(pbmc)
pbmc <- ScaleData(pbmc, features = all.genes)
```

## Clustering cells

One of the most relevant steps in scRNA-seq data analysis is clustering. Cells
are grouped based on the similarity of their transcriptomic profiles. We first 
apply the `r CRANpkg("Seurat")` v3 classical approach as described in their 
aforementioned vignette. We visualize the cell clusters using UMAP: 

```{r, message=FALSE, warning=FALSE}
pbmc <- 
    RunPCA(pbmc, features = VariableFeatures(object = pbmc), verbose = FALSE)
pbmc <- FindNeighbors(pbmc, dims = 1:10, verbose = FALSE)
pbmc <- FindClusters(pbmc, resolution = 0.5, verbose = FALSE)
pbmc <- RunUMAP(pbmc, dims = 1:10,  umap.method = 'uwot', metric='cosine')
```

```{r}
DimPlot(pbmc, reduction = "umap")
```

## Pathway activity per cell population

Following again `r CRANpkg("Seurat")` protocol, we next find the markers 
that help to identify and discriminate the different cell popualations 
present in the dataset under study.

```{r, message = FALSE}
## Finding differentially expressed features (cluster biomarkers)
pbmc.markers <- FindAllMarkers(pbmc, only.pos = TRUE, min.pct = 0.25, 
    logfc.threshold = 0.25, verbose = FALSE)

## Assigning cell type identity to clusters
new.cluster.ids <- c("Naive CD4 T", "Memory CD4 T", "CD14+ Mono", "B", "CD8 T", 
    "FCGR3A+ Mono", "NK", "DC", "Platelet")
names(new.cluster.ids) <- levels(pbmc)
pbmc <- RenameIdents(pbmc, new.cluster.ids)

## We create a data frame with the specification of the cells that belong to 
## each cluster to match with the Progeny scores.
CellsClusters <- data.frame(Cell = names(Idents(pbmc)), 
    CellType = as.character(Idents(pbmc)),
    stringsAsFactors = FALSE)
```

We plot again the clusters along with their cell type labels

```{r, message = FALSE, warning = FALSE}
DimPlot(pbmc, reduction = "umap", label = TRUE, pt.size = 0.5) + NoLegend()
```

Finally, we compute **PROGENy** pathway activity scores on the scRNA-seq data, 
and we then characterice the different cell populations based on these scores. 

```{r, message = FALSE}
## We compute the Progeny activity scores and add them to our Seurat object
## as a new assay called Progeny. 
pbmc <- progeny(pbmc, scale=FALSE, organism="Human", top=500, perm=1, 
    return_assay = TRUE)

## We can now directly apply Seurat functions in our Progeny scores. 
## For instance, we scale the pathway activity scores. 
pbmc <- Seurat::ScaleData(pbmc, assay = "progeny") 

## We transform Progeny scores into a data frame to better handling the results
progeny_scores_df <- 
    as.data.frame(t(GetAssayData(pbmc, slot = "scale.data", 
        assay = "progeny"))) %>%
    rownames_to_column("Cell") %>%
    gather(Pathway, Activity, -Cell) 

## We match Progeny scores with the cell clusters.
progeny_scores_df <- inner_join(progeny_scores_df, CellsClusters)

## We summarize the Progeny scores by cellpopulation
summarized_progeny_scores <- progeny_scores_df %>% 
    group_by(Pathway, CellType) %>%
    summarise(avg = mean(Activity), std = sd(Activity))
```

We plot the different pathway activities for the different cell populations

```{r, message=FALSE}
## We prepare the data for the plot
summarized_progeny_scores_df <- summarized_progeny_scores %>%
    dplyr::select(-std) %>%   
    spread(Pathway, avg) %>%
    data.frame(row.names = 1, check.names = FALSE, stringsAsFactors = FALSE) 
```

```{r}
paletteLength = 100
myColor = colorRampPalette(c("Darkblue", "white","red"))(paletteLength)

progenyBreaks = c(seq(min(summarized_progeny_scores_df), 0, 
                      length.out=ceiling(paletteLength/2) + 1),
                  seq(max(summarized_progeny_scores_df)/paletteLength, 
                      max(summarized_progeny_scores_df), 
                      length.out=floor(paletteLength/2)))
progeny_hmap = pheatmap(t(summarized_progeny_scores_df[,-1]),fontsize=14, 
                        fontsize_row = 10, 
                        color=myColor, breaks = progenyBreaks, 
                        main = "PROGENy (500)", angle_col = 45,
                        treeheight_col = 0,  border_color = NA)
```

# Session info {.unnumbered}

```{r sessionInfo, echo=FALSE}
sessionInfo()
```

# References