---
title: "IRIS-FGM vignette"
subtitle: IRIS-FGM 
abstract: IRIS-FGM, integrative and interpretation system for co-expression module analysisa biclustering-based gene regulation inference and cell type prediction method for single-cell RNA-Seq data. This R package integrates in-house computational tools and provides two types of analysis, including QUBIC2 based co-expression analysis and LTMG (left-truncated mixture Gaussian model) based scRNA-Seq analysis (quick mode). IRIS-FGM contains fourfour  major steps; (i) data preprocessing and regulatory signal modelingd LTMG modeling; (ii) co-regulated expression gene module identification; (iii) cell clustering; (iv) co-expression module and differentially expressed gene analysis. 
author: Yuzhou Chang
date: "12 Aug, 2020"
output:
  BiocStyle::html_document:
    number_sections: no
    toc: yes
    highlight: pygments
vignette: >
  %\VignetteIndexEntry{IRIS-FGM vignette}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---


# Intorduction to IRIS-FGM

## General introduction 
IRIS-FGM integrates in-house and state-of-the-art computational tools and provides two analysis strategies, including bicluster-based co-expression gene analysis [(Xie, et al., 2020)](https://academic.oup.com/bioinformatics/article-abstract/36/4/1143/5567116?redirectedFrom=fulltext) and LTMG (left-truncated mixture Gaussian model)-embedded scRNA-Seq analysis [(Wan, et al., 2019)](https://academic.oup.com/nar/article/47/18/e111/5542876).

## Main function

The main idea of IRIS-FGM consists of two major strategies: 

* (i)  biclustering 
* (ii) quick mode (cluster) 



## Obejct structure 
The computational frame is constructed under the S4 data structure in R. The structure of `BRIC object` is: 

- -**BRIC_Object:** *name of object is called BRIC.*
  - -**raw_count:** *raw data matrix (gene in row, cell in columns, prefer using gene symbol).*
  - -**processed_count:** *normalized and imputation (default: FALSE).*
  - -**Meta_info:** *cell classification information based on LTMG and Bicluster.*
  - -**Discretization:** *discretized matrix based on qubic 1.0, which prepares for microarry and bulk RNA-Seq analysis.*
  - -**LTMG:** *LTMG slot is for storing relative results from first strategy.*
    - -**LTMG_discrete:** *Condition assigned matrix, which is generating from LTMG model.*
    - -**LTMG_BinarySingleSignal:** *binary matrix based on gene “on /off.”*
    - -**LTMG_BinaryMultisignal:** *binary matrix based on multiple condition.*
    - -**DimReduce:** *include three dimension loading score, including PCA, Tsne, and UMAP*
    - -**MarkerGene:** *Marker gene based on cell type identified by Seurat clustering method.*
    - -**Pathway:** *based on marker gene.*
    - -**tmp.Seurat:** *temporary Seurat object. In this Seurat Object, the starting matrix is LTMG signalling matrix.*
  - -**Bicluster:**
    - -**Coreg_gene:** *co-regulatory genes are stored in this slot as dataframe; the first column is gene name and the second column is module number.*
    - -**CoCond_cell:** *co-condition cell are stored in this slot as dataframe; the first column is cell name and the second column is module number.*
    - -**MarkerGene:** *Marker gene based on cell type identified by Markov chain clustering algorithm.*
    - -**Pathway:** *genes based on co-expression gene of gene module (from Coreg_gene).*



# Requirements
## Environment

We recommend user to install IRIS-FGM on large memory (32GB) based linux operation system if user aims at analyzing bicluster-based co-expression analysis; if user aims at analyzing data by quick mode, we recommend to install IRIS-FGM on small memeory (8GB) based Windows or linux operation system; IRIS-FGM does not support MAC. 
We will assum you have the following installed:

* R (equal or greater than 3.5)

Pre-install packge
```{r pre_install, eval = FALSE}
if(!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
# install from bioconductor
BiocManager::install(c('org.Mm.eg.db','multtest', 'org.Hs.eg.db','clusterProfiler','DEsingle', 'DrImpute', 'scater', 'scran'))
# install from cran
chooseCRANmirror()
BiocManager::install(c('devtools', 'AdaptGauss', "pheatmap", 'mixtools','MCL', 'anocva', "Polychrome", 'qgraph','Rtools','ggpubr',"ggraph", "Seurat"))

```


## Input

1. The input to IRIS-FGM is the single-cell RNA-seq expression matrix:

+ Rows correspond to genes and columns correspond to cells.
+ Expression units: the preferred expression values are RPKM/FPKM/CPM. 
+ The data file should be tab delimited.

2. IRIS-FGM also accepts output files from 10X CellRanger, includinhg a folder which contains three individual files and h5 file. 

## Others

When you perform co-expression analysis, it will output several intermediate files, thus please make sure that you have write permission to the folder where IRIS-FGM is located. 

# Installation

For installation, simply type the following command in your R console, please select option 3 when R asks user to update packages:

```{r install_IRISFGM, eval= FALSE}
BiocManager::install("IRISFGM")
```


# Example dataset

This tutorial run on a real dataset to illustrate the results obtained at each step.

As example, we will use Yan's data, a dataset containing 90 cells and 20,214 genes from human embryo, to conduct cell type prediction.

> Yan, L. et al. Single-cell RNA-Seq profiling of human preimplantation embryos and embryonic stem cells. Nat. Struct. Mol. Biol. 20, 1131-1139 (2013)

The original expression matrix was downloaded from <https://s3.amazonaws.com/scrnaseq-public-datasets/manual-data/yan/nsmb.2660-S2.csv>. The expression is provided as RPKM value. For convenience, we removed the space in the column names and deleted the second column(Transcript_ID). The processed data is available at <https://bmbl.bmi.osumc.edu/downloadFiles/Yan_expression.txt>.


# 1. Input data, create IRISCEM object, add meta information, and preprocessing. 

IRIS-FGM can accepted 10X chromium input files, including a folder (contain gene name, cell name, and sparse matrix) and .h5 file.

## Input data

1. set working directory and import library
```{r setwd, eval =TRUE, echo = TRUE}
# dir.create("your working directory",recursive = TRUE)
# setwd("your working directory")
library(IRISFGM)
```

2. Read from .h5 file. 
```{r input_h5, eval= TRUE, echo = TRUE}
# if you will use the ".h5" as input file, please uncomment the following command.
# input_matrix <- ReadFrom10X_h5("dir_to_your_hdf5_file")
```

3. Read from 10X folder, which should contain three files (barcode, gene name, and sparse matrix)

```{r input_10x, eval = TRUE, echo = TRUE}
# if you will use the 10x folder as input file, please uncomment the following command.
# input_matrix <- ReadFrom10X_folder("dir_to_10x_folder")
```

4. Read from .csv or .txt file

First, we should download data from the link, then we will use this data set as example to run the pipeline.

```{r txt, eval= TRUE, echo = TRUE}
InputMatrix <- read.table(url("https://raw.githubusercontent.com/BMEngineeR/IRISFGM-data/main/Data/Yan_expression.txt"),
                          header = TRUE, 
                          row.names = 1,
                          check.names = FALSE)
```

## Add meta information

1. For the computational efficiency, we will use subsampling data, and create IRIS-FGM object.

```{r create_object, eval= TRUE, echo = TRUE,message=TRUE}
set.seed(123)
seed_idx <- sample(1:nrow(InputMatrix),3000)
InputMatrix_sub <- InputMatrix[seed_idx,]
object <- CreateIRISFGMObject(InputMatrix_sub)
```

2. Addmeta: this step can add customized cell label by user, the format of file passing to `meta.info` is data frame of which row name should be cell ID, and column name should be cell type.    
```{r add_metadata, eval= TRUE, echo = TRUE}
my_meta <- read.table(url("https://raw.githubusercontent.com/BMEngineeR/IRISFGM-data/main/Data/Yan_cell_label.txt"),header = TRUE,row.names = 1)
object <- AddMeta(object, meta.info = my_meta)
```

3. plotmeta: plot meta information based on RNA count and Feature number. This step is for the following subset step in terms of filtering out low quality data.    
```{r plot_metadata,eval= TRUE, echo = TRUE}
PlotMeta(object)
```


4. remove low quality data based on the previous plot.
```{r subset_data,eval= TRUE, echo =  TRUE}
object <- SubsetData(object , nFeature.upper=2000,nFeature.lower=250)
```

## Preprocesing 

User can choose perform normalization or imputation based on their need. The normalization method has two options, one is the simplist CPM normalization (default `normalization = 'cpm'`). The other is from package scran and can be opened by using parameter `normalization = 'scran'`, . The imputation method is from package DrImpute and can be opened by using parameter `IsImputation = TRUE` (default as closed).
```{r ProcessData,echo = TRUE, eval= TRUE}
object <- ProcessData(object, normalization = "cpm", IsImputation = FALSE)
```


# 2. Run LTMG

The argument `Gene_use = 500` is  top 500 highlt variant genes which are selected to run LTMG. For quick mode, we recommend to use top 2000 gene (here we use top 500 gene for saving time). On the contrary, for co-expression gene analysis, we recommend to use all gene by changing `Gene_use = "all"`. 
```{r run_LTMG, echo = TRUE,eval = TRUE}
# do not show progress bar
quiet <- function(x) { 
  sink(tempfile()) 
  on.exit(sink()) 
  invisible(force(x)) 
} 
# demo only run top 500 gene for saving time.
object <- quiet(RunLTMG(object, Gene_use = "500"))
# you can get LTMG signal matrix
LTMG_Matrix <- GetLTMGmatrix(object)
LTMG_Matrix[1:5,1:5]
```


# 3. Biclustering

IRIS-FGM can provide biclustering function, which is based on our in-house novel algorithm, 
QUBIC2 (<https://github.com/maqin2001/qubic2>). Here we will show the basic biclustering 
usage of IRIS-FGM using a $500\times 87$ expression matrix generated from previous top 500 variant genes. 
However, we recommend user should use "Gene_use = all"" to generate LTMG matrix. 

## LTMG-discretized bicluster (recommend for small single cell RNA-seq data)
User can type the following command to run discretization (LTMG) + biclustering directly:
```{r biclustering_basedLTMG,eval= TRUE,echo = TRUE}
object <- CalBinaryMultiSignal(object)
# Please uncomment the following command and make sure to set a correct working directory so that the following command will generate intermeidate files.
# object <- RunBicluster(object, DiscretizationModel = "LTMG",OpenDual = FALSE,
#                        NumBlockOutput = 100, BlockOverlap = 0.5, BlockCellMin = 25)

```



(The default parameters in IRIS-FGM are BlockCellMin=15, BlockOverlap=0.7,
Extension=0.90, NumBlockOutput=100 you may use other parameters as you like, just specify them in the argument)


# 4. Cell clustering

## 4.1 Perform dimension Reduction and implement Seurat clustering method.
User can use `reduction = "umap"` or `reductopm = "tsne"` to perform dimension reduction. 
```{r Run_dimReduce, eval= TRUE, echo = TRUE}
# demo only run top 500 gene for saving time.
object <- RunDimensionReduction(object, mat.source = "UMImatrix",reduction = "umap")
object <- RunClassification(object, k.param = 20, resolution = 0.8, algorithm = 1)
```

## 4.2 Predict cell clusters based on Markove clustering

The cell cluster prediction of IRIS-FGM is based on the biclustering results. 
In short, it will construct a weighted graph based on the biclusters and then do clustering on the weighted graph. To facilitate the process, we will use the pre-generated object to perform cell clustering result based on biclustering results.
```{r cell_type, eval=TRUE, echo =TRUE}
# Please uncomment the following command and make sure your working directory is the same as the directory containing intermediate output files. 
# object <- FindClassBasedOnMC(object)
```
```{r load_example_object, eval= TRUE, echo = TRUE}
data("example_object")
getMeta(example_object)[1:5,]
```

# 5. Visualization and interpretation
## 5.1 Bicluster results
### Check gene overlapping of FGMs. The results show first 19 FMGs have overlapping genes, and there is no overlapping gene between first 1 FMGs and the 15th FGM.
```{r bicluster_network, eval=TRUE, echo =TRUE}
PlotNetwork(example_object,N.bicluster = c(1:20))
```


### Heatmap shows relations between any two biclusters (1th and 15th bicluster). 
```{r bicluster_heatmap, eval=TRUE, echo =TRUE}
PlotHeatmap(example_object,N.bicluster = c(1, 20),show.clusters = TRUE,show.annotation=TRUE)
```

### Co-expression network shows gene correlation relations in one select FGM. 
```{r bicluster_network_module, eval=TRUE, echo =TRUE}
PlotModuleNetwork(example_object,N.bicluster = 3,method = "spearman",
                  cutoff.neg = -0.5,
                  cutoff.pos = 0.5,
                  layout = "circle",
                  node.label = TRUE,
                  node.col = "black",
                  node.label.cex = 10)

```

## 5.1 cell clustering results
### Visualize cell clustering results
```{r cell_clustering_umap, eval=TRUE, echo =TRUE}
# cell clustering results based on Seurat clustering method 
PlotDimension(example_object,  reduction = "umap",idents = "Seurat_r_0.8_k_20")
# cell clustering results based on MCL clustering method 
PlotDimension(example_object, reduction = "umap",idents = "MC_Label")
```

### Find global marker based on Seurat method 
```{r cell_clustering_globalmarker, eval=TRUE, echo =TRUE}
global_marker <- FindGlobalMarkers(example_object,idents = "Seurat_r_0.8_k_20")
PlotMarkerHeatmap(Globalmarkers = global_marker,object = example_object,idents ="Seurat_r_0.8_k_20")
```



# sessioninfo
```{r}
sessionInfo()
```
