---
title: "miRNA and pathway analysis with PanomiR"
author: "Pourya Naderi, Alan Teo, Ilya Sytchev, and Winston Hide"
output: 
  BiocStyle::html_document
bibliography: references.bib  
vignette: >
  %\VignetteIndexEntry{PanomiR Tutorial}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

# Introduction

MicroRNAs (miRNAs) can target co-expressed genes to coordinate multiple 
pathways. “Pathway networks of miRNA Regulation” (PanomiR) is a
framework to support the discovery of miRNA regulators based on their targeting
of coordinated pathways. It analyzes and prioritizes multi-pathway dynamics
of miRNA-orchestrated regulation, as opposed to investigating isolated
miRNA-pathway interaction events. PanomiR uses predefined pathways, their 
co-activation, gene expression, and annotated miRNA-mRNA interactions to extract
miRNA-pathway targeting events. This vignette describes PanomiR’s functions
and analysis tools to derive these multi-pathway targeting events. 

If you use PanomiR for your research, please cite PanomiR's manuscript
[@yeganeh2022panomir]. Please send any questions/suggestions you may have to
`pnaderiy [at] bidmc [dot] harvard [dot] edu` or submit Github issues at
[https://github.com/pouryany/PanomiR]().

Naderi Yeganeh, Pourya, Yue Yang Teo, Dimitra Karagkouni,
Yered Pita-Juarez, Sarah L. Morgan, Ioannis S. Vlachos, and Winston Hide.
"PanomiR: A systems biology framework for analysis of multi-pathway targeting
by miRNAs." bioRxiv (2022). doi: [https://doi.org/10.1101/2022.07.12.499819]().

# Installation

PanomiR can be accessed via Bioconductor. To install, start R (version >= 4.2.0)
and run the following code.

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

BiocManager::install("PanomiR")
```

You can also install the latest development version of PanomiR using GitHub.

```{r installation_git, eval = FALSE}
devtools::install_github("pouryany/PanomiR")
```

# Overview

PanomiR is a framework to prioritize disease-associated miRNAs using activity 
of disease-associated pathways. The input datasets for PanomiR are (a) a gene 
expression dataset along with covariates such as disease-state and batch,
(b) a background collection of pathways/genesets, and (c) a collection of
miRNAs and their gene targets.

The workflow of PanomiR includes (a) generation of pathway summary
statistics from gene expression data, (b) detection of differentially activated
pathways, (c) finding coherent groups, or clusters, of differentially activated
pathways, and (d) detecting miRNAs that target each group of pathways. 

Individual steps of the workflow can be used in isolation to carry out specific
analyses. The following sections outline each step and the material needed to
execute PanomiR. 

# Pathway summarization

PanomiR generates pathway activity summary profiles from gene expression data
and a list of pathways. Pathway summaries are numbers that represent the overall
activity of genes that belong to each pathway. These numbers are calculated
based on a methodology previously described in part by Altschuler et al.
[@altschuler2013pathprinting;@joachim2018relative].
Briefly, genes in each sample are ranked by their expression values and then
pathway summaries are calculated as the average rank-squared of genes within a 
pathway. The summaries are then center and scaled (zNormalized) across samples.

The default list of background pathways in PanomiR is formatted into a table
(`data("path_gene_table")`). The table is based on canonical pathways collection
of Molecular Signatures Database (MSigDB) V6.2 and it contains annotated 
pathways from a variety of sources  [@liberzon2011molecular].

** Users interested in using other pathway/geneset backgrounds, such as newer 
versions of MSigDB or KEGG, should refer to the [appendix](#geneset) of
this manual.

This section uses a reduced example dataset from The Cancer Genome Atlas (TCGA)
Liver Hepatocellular Carcinoma (LIHC) dataset to generate
pathway summary statistics [@ally2017comprehensive]. **Note:** Make sure that
you select a gene representation type that matches the rownames of your
expression data. The type can be modified using the `id` argument in the
function below. The default value for this argument is `ENSEMBL`. 

```{r load_package}
library(PanomiR)

# Pathway reference from the PanomiR package
data("path_gene_table")
data("miniTestsPanomiR")
# Generating pathway summary statistics 

summaries <- pathwaySummary(miniTestsPanomiR$mini_LIHC_Exp,
                            path_gene_table, method = "x2",
                            zNormalize = TRUE, id = "ENSEMBL")

head(summaries)[,1:2]
```




# Differential Pathway activation

Once you generate the pathway activity profiles, as discussed in the last
section, there are several possible analyses that you can perform. We have
bundled some of the most important ones into standalone functions. Here, we
describe differential pathway activity profiling to determine dysregulatd
pathways. This function analyzes differences in pathway activity profiles
in user-determined conditions.

At this stage you need to provide a pathway-gene association table, an
expression dataset, and a covariates table. You need to specify covariates that
you would like to contrast. You also need to provide a contrast, as formatted in
limma [@ritchie2015limma]. If the contrast is not provided, the function assumes
the first two levels of the provided covariate are to be contrasted.
**Note:** make sure the contrast covariate is formatted as factor.


```{r differential}

output0 <- differentialPathwayAnalysis(
                        geneCounts = miniTestsPanomiR$mini_LIHC_Exp,
                        pathways =  path_gene_table,
                        covariates = miniTestsPanomiR$mini_LIHC_Cov,
                        condition = 'shortLetterCode')

de.paths <- output0$DEP

head(de.paths,3)
```

# Finding clusters of pathways

PanomiR provides a function to find groups coordinated differentially 
activated pathways based on a pathway co-expression network (PCxN) previously
described in [@pita2018pathway]. Briefly, PCxN
is a network where nodes are pathways and links are co-expression between the
nodes. It is formatted into a table were rows represent edges. The edges of PCxN
are marked by two numbers, 1- a correlation co-efficient and 2- a significance
adjusted p-value. Cut-offs for both of these numbers can be manually set using 
PanomiR functions. See function manuals for more info. 

PCxN and its associated genesets are already released and can be accessed
through following Bioconductor packages:
[pcxn](http://bioconductor.org/packages/release/bioc/html/pcxn.html) and
[pcxnData](http://bioconductor.org/packages/release/data/experiment/html/pcxnData.html).

Here we have provided a small version of PCxN for tutorial purposes. A more 
recent version of PCxN based on MSigDB V6.2 is available through the 
data repository accompanying PanomiR manuscript, which can be found
[here](https://github.com/pouryany/PanomiR_paper).


```{r pcxn}


# using an updated version of pcxn 

set.seed(2)
pathwayClustsLIHC <- mappingPathwaysClusters(
                            pcxn = miniTestsPanomiR$miniPCXN, 
                            dePathways = de.paths[1:300,],
                            topPathways = 200,
                            outDir=".",
                            plot = FALSE,
                            subplot = FALSE,
                            prefix='',
                            clusteringFunction = "cluster_louvain",
                            correlationCutOff = 0.1)


head(pathwayClustsLIHC$Clustering)

```


# Prioritizing miRNAs per cluster of pathways.

PanomiR identifies miRNAs that target clusters of pathways, as defined in the 
last section. In order to this, you would need a reference table of
miRNA-Pathway association score (enrichment). We recommend using a customized
miRNA-Pathway association table, tailored to your experimental data.
This section provides an overview of prioritization process. Readers who 
interested in knowing more about the technical details of PanomiR can access
PanomiR's accompanying publication [@yeganeh2022panomir].

## Enrichment reference
Here, we provide a pre-processed small example table of miRNA-pathway enrichment
in `miniTestsPanomiR$miniEnrich` object. This table contains enrichment analysis
results using Fisher's Exact Test between MSigDB pathways and TargetScan miRNA
targets. The individual components are accessible via `data(msigdb_c2)` and
`data(targetScan_03)` [@agarwal2015predicting; @liberzon2011molecular]. This
example table contains only a subset of the full pairwise enrichment. 
You can refer to [section 5](#geneset) of this manual to learn how to create
enrichment tables and how to customize them to your specific gene expression
data.

## Generating targeting scores
PanomiR generates individual scores for individual miRNAs, which quantify
targeting a group of pathways. These scores are generated based on the reference
enrichment table described in the previous section. We are interested in knowing
to what extent each miRNA targets clusters of pathways identified in the last
step (see previous section). 

PanomiR constructs a null distribution of the targeting score for each miRNA.
It then contrasts observed scores from a given group of pathways (clusters)
against the null distribution in order to generate a targeting p-value.
These p-values are used to rank miRNAs per cluster.

## Sampling parameter
The process described above requires repeated sampling to empirically obtain the
null distribution. The argument `sampRate` denotes the number of repeats in the
process. Note that in the example below, we use a sampling rate of 50, the
recommended rate is between 500-1000. Also, we set the `saveSampling` argument
to `FALSE`. This argument, when set `TRUE`, ensures that the null distribution
is obtained only once. This argument should be set to TRUE if you wish to save
your sampling and check for different outputs from the clustering algorithms or
pathway thresholds.


```{r miRNA}

set.seed(1)
output2 <- prioritizeMicroRNA(enriches0 = miniTestsPanomiR$miniEnrich,
                    pathClust = miniTestsPanomiR$miniPathClusts$Clustering,
                    topClust = 1,
                    sampRate = 50, 
                    method = c("aggInv"),
                    outDir = "Output/",
                    dataDir = "outData/",
                    saveSampling = FALSE,
                    runJackKnife = FALSE,
                    numCores = 1,
                    prefix = "outmiR",
                    saveCSV = FALSE)

head(output2$Cluster1)

```



# miRNA-Pathway enrichment tables 

We recommend using PanomiR with on tissue/experiment-customized datasets.
In order to do this, you need to create a customized enrichment table.
You can simply do so by using the pathway and miRNA list that we have provided
as a part of the package. Simply, plug in the name of the genes that are present
(expressed) in your experiment in the following code:



```{r customized_mir, eval = FALSE}


# using an updated version of pcxn 
data("msigdb_c2")
data("targetScan_03")


customeTableEnrich <- miRNAPathwayEnrichment(mirSets = targetScan_03,
                                              pathwaySets = msigdb_c2,
                                              geneSelection = yourGenes,
                                              mirSelection = yourMicroRNAs,
                                              fromID = "ENSEMBL",
                                              toID = "ENTREZID",
                                              minPathSize = 9,
                                              numCores = 1,
                                              outDir = ".",
                                              saveOutName = NULL)

```

In the above section, the field ```fromID``` denotes the gene representation 
format of your input list. Here is a quick example that runs fast. Note that 
the `miRNAPathwayEnrichment()` function creates a detailed report with
parameters that are used internally. To get a smaller table that is suitable 
for publication purposes, use `reportEnrichment()` function.
```{r customized_mir2}

# using an updated version of pcxn 
data("msigdb_c2")
data("targetScan_03")

tempEnrich <-miRNAPathwayEnrichment(targetScan_03[1:30],msigdb_c2[1:30])

head(reportEnrichment(tempEnrich))
```

# Customized genesets and recommendations {#geneset}

PanomiR can integrate genesets and pathways from external sources including
those annotated in MSigDB. In order to do so, you need to provide a 
`GeneSetCollection` object as defined in the `GSEABase` package. 

The example below illustrates using external sources to create your 
own customized pathway-gene association table. This customized table can
replace the `path_gene_table` input in sections 1, 2, and 5
of this manual.

```{r customized_gsc}
data("gscExample")

newPathGeneTable <-tableFromGSC(gscExample)

```

The the pathway correlation network in section 3 is build upon an MSigDB V6.2, 
canonical pathways (cp) collection dataset that includes KEGG Pathways.
KEGG prohibits distribution of its pathways by third parties. You can
access desired versions of MSigDB in gmt format via
[this link](https://www.gsea-msigdb.org/gsea/downloads_archive.jsp)
[@subramanian2005gene].

The library `msigdb` provides an programmatic interface to download different
geneset collections. Including how to add KEGG pathways or download mouse 
genesets. Use the this [MSigDB tutorial](https://bioconductor.org/packages/release/data/experiment/vignettes/msigdb/inst/doc/msigdb.html)
to create your desired gene sets.

You can also use the following code chunk to create pathway-gene association
tables from gmt files.

```{r customized_gsc2, eval = FALSE}

library(GSEABase)

yourGeneSetCollection <- getGmt("YOUR GMT FILE")
newPathGeneTable      <- tableFromGSC(yourGeneSetCollection)

```

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

```

# References