# Gene Detection Analysis for scRNA-seq
Author: Ruoxin Li, Gerald Quon
Date: 2019-10-29

#### Ruoxin Li, Gerald Quon

#### 2019-10-29

# Introduction

This tutorial provides an example analysis for modelling gene detection pattern as outlined in R.Li et al, 2018. The goal of this tutorial is to provide an overview of the cell type classification and visualization tasks by learning a low dimensional embedding through a class of gene detection models: that is BFA and Binary PCA.

## Summary of workflow

The following workflow summarizes a typical dimensionality reduction procedure performed by BFA or Binary PCA.

1. Data processing
2. Dimensionality reduction
3. Visualization

## Installation

Let’s start with the installation

    if (!requireNamespace("BiocManager", quietly = TRUE))
        install.packages("BiocManager")
    BiocManager::install("scBFA")

next we can load dependent packages

    library(zinbwave)
    library(SingleCellExperiment)
    library(ggplot2)
    library(scBFA)

## Information of example dataset

The example dataset is generated from our scRNA-seq pre-DC/cDC dataset sourced from https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE89232 After performing all quality control procedure of genes and cells (as outlined in the paper), we then select 500 most variable genes for illustration purpose. The example dataset consists of 950 cells and 500 genes

    # raw counts matrix with rows are genes and columns are cells
    data("exprdata")

    # a vector specify the ground truth of cell types provided by conquer database
    data("celltype")

## Working with SingleCellExperiment class

The design of BFA and Binary PCA allows three kinds of input object(scData):

For illustration, here we construct a singleCellExperiment class to be the input of BFA and Binary PCA.

    sce <- SingleCellExperiment(assay = list(counts = exprdata))

## Gene Detection Model analysis

### Binary Factor Analysis

Let \(N\) stands for number of cells, \(G\) stands for the number of genes, and \(K\) stands for the number of latent dimensions.

A bfa model object computes the following parameters after fitting the gene detection matrix.

1. \(Z\) is \(N\) by \(K\) embedding matrix and is named as “ZZ” in the model object
2. \(A\) is \(G\) by \(K\) loading matrix and is named as “AA” in the model object
3. \(\beta\) if there is cell-level covariates (e.g batch effect), \(\beta\) is corresponding coefficient matrix and is named as “beta” in the model object
4. \(\gamma\) if there is gene-level covariates (e.g QC measures), \(\gamma\) is corresponding coefficient matrix and is named as “gamma” in the model object

We choose 3 as number of latent dimensions and project the gene detection matrix on the embedding space.

    bfa_model = scBFA(scData = sce, numFactors = 2)

We then visualize the low dimensional embedding of BFA in tSNE space. Points are colored by their corresponding cell types.

    set.seed(5)
    df = as.data.frame(bfa_model$ZZ)
    df$celltype = celltype

    p1 <- ggplot(df,aes(x = V1,y = V2,colour = celltype))
    p1 <- p1 + geom_jitter(size=2.5,alpha = 0.8)
    colorvalue <- c("#43d5f9","#24b71f","#E41A1C", "#ffc935","#3d014c","#39ddb2",
                    "slateblue2","maroon","#f7df27","palevioletred1","olivedrab3",
                    "#377EB8","#5043c1","blue","aquamarine2","chartreuse4",
                    "burlywood2","indianred1","mediumorchid1")
    p1 <- p1 + xlab("tsne axis 1") + ylab("tsne axis 2")
    p1 <- p1 + scale_color_manual(values = colorvalue)
    p1 <- p1 + theme(panel.background = element_blank(),
                      legend.position = "right",
                      axis.text=element_blank(),
                      axis.line.x = element_line(color="black"),
                      axis.line.y = element_line(color="black"),
                      plot.title = element_blank()
                       )
    p1

### Binary PCA

    bpca = BinaryPCA(scData = sce)

We then visualize the low dimensional embedding of Binary PCA in tSNE space. Points are colored by their corresponding cell types.

    df = as.data.frame(bpca$x[,c(1:2)])
    colnames(df) = c("V1","V2")
    df$celltype = celltype

    p1 <- ggplot(df,aes(x = V1,y = V2,colour = celltype))
    p1 <- p1 + geom_jitter(size=2.5,alpha = 0.8)
    colorvalue <- c("#43d5f9","#24b71f","#E41A1C", "#ffc935","#3d014c","#39ddb2",
                    "slateblue2","maroon","#f7df27","palevioletred1","olivedrab3",
                    "#377EB8","#5043c1","blue","aquamarine2","chartreuse4",
                    "burlywood2","indianred1","mediumorchid1")
    p1 <- p1 + xlab("tsne axis 1") + ylab("tsne axis 2")
    p1 <- p1 + scale_color_manual(values = colorvalue)
    p1 <- p1 + theme(panel.background = element_blank(),
                    legend.position = "right",
                    axis.text=element_blank(),
                    axis.line.x = element_line(color="black"),
                    axis.line.y = element_line(color="black"),
                    plot.title = element_blank()
                    )
    p1

## Session Info

    sessionInfo()
    #> R version 3.6.1 (2019-07-05)
    #> Platform: x86_64-pc-linux-gnu (64-bit)
    #> Running under: Ubuntu 18.04.3 LTS
    #>
    #> Matrix products: default
    #> BLAS:   /home/biocbuild/bbs-3.10-bioc/R/lib/libRblas.so
    #> LAPACK: /home/biocbuild/bbs-3.10-bioc/R/lib/libRlapack.so
    #>
    #> locale:
    #>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    #>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C
    #>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
    #>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
    #>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
    #> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
    #>
    #> attached base packages:
    #> [1] parallel  stats4    stats     graphics  grDevices utils     datasets
    #> [8] methods   base
    #>
    #> other attached packages:
    #>  [1] scBFA_1.0.0                 ggplot2_3.2.1
    #>  [3] zinbwave_1.8.0              SingleCellExperiment_1.8.0
    #>  [5] SummarizedExperiment_1.16.0 DelayedArray_0.12.0
    #>  [7] BiocParallel_1.20.0         matrixStats_0.55.0
    #>  [9] Biobase_2.46.0              GenomicRanges_1.38.0
    #> [11] GenomeInfoDb_1.22.0         IRanges_2.20.0
    #> [13] S4Vectors_0.24.0            BiocGenerics_0.32.0
    #>
    #> loaded via a namespace (and not attached):
    #>   [1] copula_0.999-19.1      backports_1.1.5        Hmisc_4.2-0
    #>   [4] plyr_1.8.4             igraph_1.2.4.1         lazyeval_0.2.2
    #>   [7] splines_3.6.1          pspline_1.0-18         listenv_0.7.0
    #>  [10] digest_0.6.22          htmltools_0.4.0        gdata_2.18.0
    #>  [13] magrittr_1.5           checkmate_1.9.4        memoise_1.1.0
    #>  [16] cluster_2.1.0          ROCR_1.0-7             limma_3.42.0
    #>  [19] globals_0.12.4         annotate_1.64.0        RcppParallel_4.4.4
    #>  [22] stabledist_0.7-1       R.utils_2.9.0          colorspace_1.4-1
    #>  [25] blob_1.2.0             ggrepel_0.8.1          xfun_0.10
    #>  [28] dplyr_0.8.3            crayon_1.3.4           RCurl_1.95-4.12
    #>  [31] jsonlite_1.6           genefilter_1.68.0      zeallot_0.1.0
    #>  [34] survival_2.44-1.1      zoo_1.8-6              ape_5.3
    #>  [37] glue_1.3.1             gtable_0.3.0           zlibbioc_1.32.0
    #>  [40] XVector_0.26.0         leiden_0.3.1           future.apply_1.3.0
    #>  [43] scales_1.0.0           mvtnorm_1.0-11         DBI_1.0.0
    #>  [46] edgeR_3.28.0           bibtex_0.4.2           Rcpp_1.0.2
    #>  [49] metap_1.1              viridisLite_0.3.0      xtable_1.8-4
    #>  [52] htmlTable_1.13.2       reticulate_1.13        rsvd_1.0.2
    #>  [55] foreign_0.8-72         bit_1.1-14             SDMTools_1.1-221.1
    #>  [58] Formula_1.2-3          tsne_0.1-3             htmlwidgets_1.5.1
    #>  [61] httr_1.4.1             gplots_3.0.1.1         RColorBrewer_1.1-2
    #>  [64] acepack_1.4.1          Seurat_3.1.1           ica_1.0-2
    #>  [67] pkgconfig_2.0.3        XML_3.98-1.20          R.methodsS3_1.7.1
    #>  [70] uwot_0.1.4             nnet_7.3-12            locfit_1.5-9.1
    #>  [73] labeling_0.3           reshape2_1.4.3         tidyselect_0.2.5
    #>  [76] rlang_0.4.1            softImpute_1.4         AnnotationDbi_1.48.0
    #>  [79] munsell_0.5.0          tools_3.6.1            RSQLite_2.1.2
    #>  [82] ggridges_0.5.1         evaluate_0.14          stringr_1.4.0
    #>  [85] yaml_2.2.0             npsurv_0.4-0           knitr_1.25
    #>  [88] bit64_0.9-7            fitdistrplus_1.0-14    caTools_1.17.1.2
    #>  [91] purrr_0.3.3            RANN_2.6.1             pbapply_1.4-2
    #>  [94] future_1.14.0          nlme_3.1-141           R.oo_1.22.0
    #>  [97] compiler_3.6.1         rstudioapi_0.10        png_0.1-7
    #> [100] plotly_4.9.0           lsei_1.2-0             tibble_2.1.3
    #> [103] geneplotter_1.64.0     pcaPP_1.9-73           gsl_2.1-6
    #> [106] stringi_1.4.3          lattice_0.20-38        Matrix_1.2-17
    #> [109] vctrs_0.2.0            pillar_1.4.2           lifecycle_0.1.0
    #> [112] ADGofTest_0.3          Rdpack_0.11-0          lmtest_0.9-37
    #> [115] RcppAnnoy_0.0.13       data.table_1.12.6      cowplot_1.0.0
    #> [118] bitops_1.0-6           irlba_2.3.3            gbRd_0.4-11
    #> [121] R6_2.4.0               latticeExtra_0.6-28    KernSmooth_2.23-16
    #> [124] gridExtra_2.3          codetools_0.2-16       MASS_7.3-51.4
    #> [127] gtools_3.8.1           assertthat_0.2.1       DESeq2_1.26.0
    #> [130] withr_2.1.2            sctransform_0.2.0      GenomeInfoDbData_1.2.2
    #> [133] grid_3.6.1             rpart_4.1-15           tidyr_1.0.0
    #> [136] rmarkdown_1.16         Rtsne_0.15             numDeriv_2016.8-1.1
    #> [139] base64enc_0.1-3