1 Introduction

This tutorial demonstrates how to visualize and interpret the results from a GSFA run.

The results are a bit different from what was reported in the biorxiv version of GSFA manuscript due to slight changes in random sampling and calibration of negative control effects.

We have described how to run GSFA on CD8+ T Cell CROP-seq data here.

To recapitulate, the processed dataset consists of 10677 unstimulated T cells and 14278 stimulated T cells.
They were subject to belong to one of the 21 perturbation conditions (CRISPR knock-out of 20 regulators of T cell proliferation or immune checkpoint genes, and negative control).
Top 6000 genes ranked by deviance statistics were kept. A modified two-group GSFA was performed on the data with 20 factors specified, and perturbation effects estimated separately for cells with/without TCR stimulation.

1.1 Load necessary packages and data

library(data.table)
library(Matrix)
library(tidyverse)
library(ggplot2)
theme_set(theme_bw() + theme(plot.title = element_text(size = 14, hjust = 0.5),
                             axis.title = element_text(size = 14),
                             axis.text = element_text(size = 12),
                             legend.title = element_text(size = 13),
                             legend.text = element_text(size = 12),
                             panel.grid.minor = element_blank())
)
library(gridExtra)
library(ComplexHeatmap)
library(kableExtra)
library(WebGestaltR)
dyn.load('/software/geos-3.7.0-el7-x86_64/lib64/libgeos_c.so')
library(Seurat)

source("/project2/xinhe/yifan/Factor_analysis/analysis_website_for_Kevin/scripts/plotting_functions.R")
wkdir <- "/project2/xinhe/yifan/Factor_analysis/Stimulated_T_Cells/"
result_folder <- "gsfa_output_detect_01/all_uncorrected_by_group.use_negctrl/"

The first thing we need is the output of GSFA fit_gsfa_multivar_2groups() run. The lighter version containing just the posterior mean estimates and LFSR of perturbation-gene effects is enough.

fit <- readRDS(paste0(wkdir, result_folder,
                      "All.gibbs_obj_k20.svd_negctrl.restart.light.rds"))
gibbs_PM <- fit$posterior_means
lfsr_mat1 <- fit$lfsr1[, -ncol(fit$lfsr1)]
lfsr_mat0 <- fit$lfsr0[, -ncol(fit$lfsr0)]
total_effect1 <- fit$total_effect1[, -ncol(fit$total_effect1)]
total_effect0 <- fit$total_effect0[, -ncol(fit$total_effect0)]
KO_names <- colnames(lfsr_mat1)

We also need the cell by perturbation matrix which was used as input \(G\) for GSFA.

metadata <- readRDS(paste0(wkdir, "processed_data/metadata.all_T_cells_merged.rds"))
G_mat <- metadata[, 4:24]

Finally, we load the mapping from gene name to ENSEMBL ID for all 6k genes used in GSFA, as well as selected T cell marker genes. This is specific to this study and analysis.

# Load gene ensembl IDs and matched gene symbols.
feature.names <- data.frame(fread(paste0(wkdir, "GSE119450_RAW/D1N/genes.tsv"),
                                  header = FALSE), stringsAsFactors = FALSE)
genes_df <- feature.names[match(rownames(lfsr_mat1), feature.names$V1), ]
names(genes_df) <- c("ID", "Name")
# Load marker genes in T cells.
interest_df <- readRDS(paste0(wkdir, "processed_data/selected_tcell_markers.rds"))
interest_df <- interest_df %>%
  dplyr::filter(gene_name != "TOP2A")
interest_df <- rbind(interest_df,
                     c("TOPBP1", "Cell proliferation",
                       "DNA topoisomerase II binding protein 1", "ENSG00000163781"))

2 Factor ~ Perturbation Associations

2.1 Perturbation effects on factors (stimulated cells)

Fisrt of all, we look at the estimated effects of gene perturbations on factors inferred by GSFA.

We found that targeting of 9 genes, ARID1A, CBLB, CD5, CDKN1B, DGKA, LCP2, RASA2, SOCS1, and TCEB2, has significant effects (PIP > 0.95) on at least 1 of the 20 inferred factors.

Estimated effects of perturbations on factors (Figure S4A):

dotplot_beta_PIP(t(gibbs_PM$Gamma1_pm), t(gibbs_PM$beta1_pm),
                 marker_names = KO_names,
                 reorder_markers = c(KO_names[KO_names!="NonTarget"], "NonTarget"),
                 inverse_factors = F) +
  coord_flip()

Here is a closer look at the estimated effects of selected perturbations on selected factors (Figure 3A):

targets <- c("ARID1A", "LCP2", "CD5", "CBLB", "RASA2", 
             "TCEB2", "SOCS1", "CDKN1B")
complexplot_perturbation_factor(gibbs_PM$Gamma1_pm[-nrow(gibbs_PM$Gamma1_pm), ],
                                gibbs_PM$beta1_pm[-nrow(gibbs_PM$beta1_pm), ],
                                marker_names = KO_names, reorder_markers = targets,
                                reorder_factors = c(2, 4, 9, 12))

We can also assess the correlations between each pair of perturbation and inferred factor.
The distribution of correlation p values show significant signals in stimulated cells.

## Indices of stimulated cells:
stim_cells <-
  (1:nrow(G_mat))[startsWith(rownames(G_mat), "D1S") | 
                    startsWith(rownames(G_mat), "D2S")]
gibbs_res_tb <- make_gibbs_res_tb(gibbs_PM, G_mat, compute_pve = F,
                                  cell_indx = stim_cells)
heatmap_matrix <- gibbs_res_tb %>% select(starts_with("pval"))
rownames(heatmap_matrix) <- 1:nrow(heatmap_matrix)
colnames(heatmap_matrix) <- colnames(G_mat)

summ_pvalues(unlist(heatmap_matrix),
             title_text = "GSFA Stimulated\n(21 Targets x 20 Factors)")

2.2 Perturbation effects on factors (unstimulated cells)

In unstimulated cells, only three pairs of associations were detected at PIP > 0.95, which is unsurprising given the role of these targeted genes in regulating T cell responses (Figure S4B):

dotplot_beta_PIP(t(gibbs_PM$Gamma0_pm), t(gibbs_PM$beta0_pm),
                 marker_names = KO_names,
                 reorder_markers = c(KO_names[KO_names!="NonTarget"], "NonTarget"),
                 inverse_factors = F) +
  coord_flip()

3 Factor Interpretation

3.1 Correlation within factors

Since the GSFA model does not enforce orthogonality among factors, we first inspect the pairwise correlation within them to see if there is any redundancy. As we can see below, the inferred factors are mostly independent of each other.

plot_pairwise.corr_heatmap(input_mat_1 = gibbs_PM$Z_pm,
                           corr_type = "pearson",
                           name_1 = "Pairwise correlation within factors (Z)",
                           label_size = 10)

plot_pairwise.corr_heatmap(input_mat_1 = (gibbs_PM$F_pm > 0.95) * 1,
                           corr_type = "jaccard",
                           name_1 = "Pairwise correlation within \nbinarized gene loadings (F_pm > 0.95)",
                           label_size = 10)

3.2 Gene loading in factors

To understand these latent factors, we inspect the loadings (weights) of several marker genes for T cell activation or proliferation states in them.

gene_name type protein_name gene_ID
IL7R T cell resting state IL-7 receptor ENSG00000168685
CCR7 T cell resting state C-C motif chemokine receptor 7 ENSG00000126353
GZMB T cell activation Granzyme B ENSG00000100453
IFNG T cell activation Interferon gamma ENSG00000111537
CD44 T cell activation CD44 ENSG00000026508
IL2RA T cell activation IL-2 receptor ENSG00000134460
XCL1 T cell activation X-C motif chemokine ligand 1 ENSG00000143184
TNFRSF18 T cell activation GITR ENSG00000186891
ITGAL T cell activation LFA-1 ENSG00000005844
MKI67 Cell proliferation Marker of proliferation Ki-67 ENSG00000148773
CENPF Cell proliferation Centromere protein F ENSG00000117724
TOPBP1 Cell proliferation DNA topoisomerase II binding protein 1 ENSG00000163781

We visualize both the gene PIPs (dot size) and gene weights (dot color) in all factors (Figure S4C):

complexplot_gene_factor(genes_df, interest_df, gibbs_PM$F_pm, gibbs_PM$W_pm)

A closer look at some factors that are associated with perturbations (Figure 3C):

complexplot_gene_factor(genes_df, interest_df, gibbs_PM$F_pm, gibbs_PM$W_pm,
                        reorder_factors = c(2, 4, 9, 12))

3.3 GO enrichment analysis in factors

To further characterize these latent factors, we perform GO (gene ontology) enrichment analysis of genes loaded on the factors using WebGestalt.

Foreground genes: Genes w/ non-zero loadings in each factor (gene PIP > 0.95);
Background genes: all 6000 genes used in GSFA;
Statistical test: hypergeometric test (over-representation test);
Gene sets: GO Slim “Biological Process” (non-redundant).

## The "WebGestaltR" tool needs Internet connection.
enrich_db <- "geneontology_Biological_Process_noRedundant"
PIP_mat <- gibbs_PM$F_pm
enrich_res_by_factor <- list()
for (i in 1:ncol(PIP_mat)){
  enrich_res_by_factor[[i]] <- 
    WebGestaltR::WebGestaltR(enrichMethod = "ORA",
                             organism = "hsapiens",
                             enrichDatabase = enrich_db,
                             interestGene = genes_df[PIP_mat[, i] > 0.95, ]$ID,
                             interestGeneType = "ensembl_gene_id",
                             referenceGene = genes_df$ID,
                             referenceGeneType = "ensembl_gene_id",
                             isOutput = F)
}

Several GO “biological process” terms related to immune responses or cell cycle are enriched in factors 2, 4, 9, and 12 (Figure 3D):

factor_indx <- 2
terms_of_interest <- c("kinetochore organization", "chromosome segregation",
                       "cell cycle G2/M phase transition", "cytokinesis")
barplot_top_enrich_terms(enrich_res_by_factor[[factor_indx]],
                         terms_of_interest = terms_of_interest,
                         str_wrap_length = 50) +
  labs(title = paste0("Factor ", factor_indx))

factor_indx <- 9
terms_of_interest <- c("microtubule cytoskeleton organization involved in mitosis",
                       "chromosome segregation", "cytokinesis", "cell cycle checkpoint")
barplot_top_enrich_terms(enrich_res_by_factor[[factor_indx]],
                         terms_of_interest = terms_of_interest,
                         str_wrap_length = 35) +
  labs(title = paste0("Factor ", factor_indx))

factor_indx <- 4
terms_of_interest <- c("response to chemokine", "cell killing", "leukocyte migration",
                       "response to interferon-gamma", "cytokine secretion")
barplot_top_enrich_terms(enrich_res_by_factor[[factor_indx]],
                         terms_of_interest = terms_of_interest,
                         str_wrap_length = 35) +
  labs(title = paste0("Factor ", factor_indx))

factor_indx <- 12
terms_of_interest <- c("leukocyte cell-cell adhesion", "extrinsic apoptotic signaling pathway",
                       "cell killing", "T cell activation", "NIK/NF-kappaB signaling")
barplot_top_enrich_terms(enrich_res_by_factor[[factor_indx]],
                         terms_of_interest = terms_of_interest,
                         str_wrap_length = 35) +
  labs(title = paste0("Factor ", factor_indx))

3.4 Visualization of factors on UMAP

# seurat_obj <- NormalizeData(seurat_obj,
#                             normalization.method = "LogNormalize",
#                             scale.factor = 1e4)
# seurat_obj <- FindVariableFeatures(seurat_obj, nfeatures = 1000)
# seurat_obj <- ScaleData(seurat_obj,
#                         vars.to.regress = c("nCount_RNA", "percent_mt"))
# seurat_obj <- RunPCA(seurat_obj, verbose = F)
# seurat_obj <- FindNeighbors(seurat_obj, reduction = "pca")
# seurat_obj <- RunUMAP(seurat_obj, reduction = "pca", dims = 1:30)
seurat_obj <- readRDS(paste0(wkdir,
                             "processed_data/seurat_obj.all_T_cells_merged.uncorrected.rds"))
# Add GSFA factor loadings to the seurat obj.
stopifnot(rownames(gibbs_PM$Z_pm) == Cells(seurat_obj))
for (i in 1:ncol(gibbs_PM$Z_pm)) {
  seurat_obj[[paste0("Factor_", i)]] <- as.numeric(gibbs_PM$Z_pm[, i])
}
# Add normalized expression of marker genes to the seurat obj.
norm_exp <- seurat_obj@assays$RNA@data
CC_genes_df <- data.frame(fread("/project2/xinhe/shared_data/cell_cycle_genes.csv"))
for (i in 1:ncol(CC_genes_df)) {
  gene_ids <- feature.names %>% filter(V2 %in% na.omit(CC_genes_df[, i])) %>% pull(V1)
  phase <- names(CC_genes_df)[i]
  phase.exp <- Matrix::colMeans(norm_exp[gene_ids, ])
  seurat_obj[[phase]] <- phase.exp
}
marker_genes <- c("IL7R", "CCR7" , "MKI67", "GZMB")
for (m in marker_genes) {
  gene_id <- feature.names$V1[feature.names$V2 == m]
  seurat_obj[[m]] <- as.numeric(norm_exp[gene_id, ])
  # Cap the expression value at 3 for convenience of coloring.
  seurat_obj[[m]][seurat_obj[[m]] > 3] <- 3
}
Mitosis_plt <- FeaturePlot(seurat_obj, features = "M") +
  scale_color_gradientn(colors = RColorBrewer::brewer.pal(n = 8, name = "Spectral")[c(8, 8, 6:1)]) +
  labs(title = "Mitosis",
       color = "Mean expression of\nmitosis marker genes") +
  theme(legend.text = element_text(size = 13))
GZMB_plt <- FeaturePlot(seurat_obj, features = "GZMB") +
  scale_color_gradientn(colors = RColorBrewer::brewer.pal(n = 8, name = "Spectral")[c(8,6,4:1)]) +
  labs(title = "Effector function",
       color = "GZMB expression") +
  theme(legend.text = element_text(size = 13))
factor2_plt <- FeaturePlot(seurat_obj, features = "Factor_2") +
  scale_color_gradientn(colors = RColorBrewer::brewer.pal(n = 8, name = "RdYlBu")[c(8, 8, 7, 6, 4, 3, 2)]) +
  labs(title = "Factor 2",
       color = "Factor value in cell") +
  theme(legend.text = element_text(size = 13))
factor4_plt <- FeaturePlot(seurat_obj, features = "Factor_4") +
  scale_color_gradientn(colors = RColorBrewer::brewer.pal(n = 8, name = "RdYlBu")[c(8, 8, 7, 6, 4, 3, 2)]) +
  labs(title = "Factor 4",
       color = "Factor value in cell") +
  theme(legend.text = element_text(size = 13))
grid.arrange(Mitosis_plt, GZMB_plt, factor2_plt, factor4_plt,
             nrow = 2)

4 DEG Interpretation

In GSFA, differential expression analysis can be performed based on the LFSR method. Here we evaluate the specific downstream genes affected by the perturbations detected by GSFA.

We also performed several other differential expression methods for comparison, including scMAGeCK-LR, MAST, and DESeq.

Here, we compared the DEG results within stimulated cells.

4.1 Number of DEGs detected by different methods

fdr_cutoff <- 0.05
lfsr_cutoff <- 0.05
guides <- KO_names[KO_names!="NonTarget"]
Number of DEGs detected by GSFA:
KO ARID1A BTLA C10orf54 CBLB CD3D CD5 CDKN1B
Num_genes 393 107 66 631 0 645 468
KO DGKA DGKZ HAVCR2 LAG3 LCP2 MEF2D NonTarget
Num_genes 32 113 35 1 589 15 0
KO PDCD1 RASA2 SOCS1 STAT6 TCEB2 TMEM222 TNFRSF9
Num_genes 0 277 356 1 300 4 14
deseq_list <- list()
for (m in guides){
  fname <- paste0(wkdir, "processed_data/DESeq2/all_by_stim_negctrl/gRNA_", 
                  m, ".dev_res_top6k.vs_negctrl.rds")
  res <- readRDS(fname)
  res <- as.data.frame(res@listData, row.names = res@rownames)
  res$geneID <- rownames(res)
  res <- res %>% dplyr::rename(FDR = padj, PValue = pvalue)
  deseq_list[[m]] <- res
}
deseq_signif_counts <- sapply(deseq_list, function(x){filter(x, FDR < fdr_cutoff) %>% nrow()})
mast_list <- list()
for (m in guides){
  fname <- paste0(wkdir, "processed_data/MAST/all_by_stim_negctrl/gRNA_", 
                  m, ".dev_res_top6k.vs_negctrl.rds")
  tmp_df <- readRDS(fname)
  tmp_df$geneID <- rownames(tmp_df)
  tmp_df <- tmp_df %>% dplyr::rename(FDR = fdr, PValue = pval)
  mast_list[[m]] <- tmp_df
}
mast_signif_counts <- sapply(mast_list, function(x){filter(x, FDR < fdr_cutoff) %>% nrow()})
scmageck_res <- readRDS(paste0(wkdir, "scmageck/scmageck_lr.TCells_stim.dev_res_top_6k.rds"))
colnames(scmageck_res$fdr)[colnames(scmageck_res$fdr) == "NegCtrl"] <- "NonTarget"
scmageck_signif_counts <- colSums(scmageck_res$fdr[, KO_names] < fdr_cutoff)
scmageck_signif_counts <- scmageck_signif_counts[names(scmageck_signif_counts) != "NonTarget"]
sceptre_res <- readRDS("/project2/xinhe/kevinluo/GSFA/sceptre_analysis/TCells_data_updated/simulated_data/sceptre_output/sceptre.result.rds")
sceptre_count_df <- data.frame(matrix(nrow = length(guides), ncol = 2))
colnames(sceptre_count_df) <- c("target", "num_DEG")
for (i in 1:length(guides)){
  sceptre_count_df$target[i] <- guides[i]
  tmp_pval <- sceptre_res %>% filter(gRNA_id == guides[i]) %>% pull(p_value)
  tmp_fdr <- p.adjust(tmp_pval, method = "fdr")
  sceptre_count_df$num_DEG[i] <- sum(tmp_fdr < 0.05)
}
dge_comparison_df <- data.frame(Perturbation = guides,
                                GSFA = lfsr_signif_num[guides],
                                scMAGeCK = scmageck_signif_counts,
                                DESeq2 = deseq_signif_counts,
                                MAST = mast_signif_counts,
                                SCEPTRE = sceptre_count_df$num_DEG)
# dge_comparison_df$Perturbation[dge_comparison_df$Perturbation == "NonTarget"] <- "NegCtrl"

Number of DEGs detected under each perturbation using 4 different methods (Figure 4A):
Compared with other differential expression analysis methods, GSFA detected the most DEGs for 15 gene targets.

dge_plot_df <- reshape2::melt(dge_comparison_df, id.var = "Perturbation",
                              variable.name = "Method", value.name = "Num_DEGs")
dge_plot_df$Perturbation <- factor(dge_plot_df$Perturbation,
                                   levels = guides)
                                   # levels = c("NegCtrl", KO_names[KO_names!="NonTarget"]))
dge_plt <- ggplot(dge_plot_df,
                  aes(x = Perturbation, y = Num_DEGs+1, fill = Method)) +
  geom_bar(position = "dodge", stat = "identity") +
  geom_text(aes(label = Num_DEGs),
            position = position_dodge(width = 0.9), vjust = -0.25) +
  geom_hline(yintercept = 100, color = "grey50", linetype = "dotted") +
  scale_y_log10() +
  scale_fill_brewer(palette = "Set2") +
  labs(x = "Target gene",
       y = "Number of DEGs",
       title = "Number of DEGs detected by different methods") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 12),
        legend.position = "bottom",
        legend.text = element_text(size = 13))
dge_plt

4.2 Perturbation effects on marker genes

To better understand the functions of these 9 target genes, we examined their effects on marker genes for T cell activation or proliferation states.

4.2.1 GSFA

Here are the summarized effects of perturbations on marker genes estimated by GSFA (Figure 4D).

# Only keep target genes with > 100 DEGs to simplify plot.
targets <- c("ARID1A", "LCP2", "BTLA", "CD5", "CBLB", "RASA2",
             "TCEB2", "SOCS1", "CDKN1B", "DGKZ")
complexplot_gene_perturbation(genes_df, interest_df,
                              targets = targets,
                              lfsr_mat = lfsr_mat1,
                              effect_mat = total_effect1)

Cell cycle:
As we can see, knockout of SOCS1 or CDKN1B has positive effects on cell proliferation markers, indicating increased cell proliferation.

T cell activation and immune response:
Knockout of CD5, CBLB, RASA2 or TCEB2 has mostly positive effects on effector markers, indicating T cell activation; knockout of ARID1A has the opposite pattern.

This next plot expanded the gRNA targets to all that have DEGs detected:

complexplot_gene_perturbation(genes_df, interest_df,
                              targets = names(lfsr_signif_num)[lfsr_signif_num > 0],
                              lfsr_mat = lfsr_mat1,
                              effect_mat = total_effect1)

4.2.2 scMAGeCK

Here are scMAGeCK estimated effects of perturbations on marker genes (Figure 4E):

score_mat <- scmageck_res$score
fdr_mat <- scmageck_res$fdr
complexplot_gene_perturbation(genes_df, interest_df,
                              targets = targets,
                              lfsr_mat = fdr_mat, lfsr_name = "FDR",
                              effect_mat = score_mat, 
                              effect_name = "scMAGeCK\nselection score",
                              score_break = c(-0.2, 0, 0.2),
                              color_break = c("blue3", "grey90", "red3"))

4.2.3 DESeq2

FC_mat <- matrix(nrow = nrow(interest_df), ncol = length(targets))
rownames(FC_mat) <- interest_df$gene_name
colnames(FC_mat) <- targets
fdr_mat <- FC_mat
for (m in targets){
  FC_mat[, m] <- deseq_list[[m]]$log2FoldChange[match(interest_df$gene_ID, 
                                                      deseq_list[[m]]$geneID)]
  fdr_mat[, m] <- deseq_list[[m]]$FDR[match(interest_df$gene_ID, 
                                            deseq_list[[m]]$geneID)]
}

Here are DESeq2 estimated effects of perturbations on marker genes (Figure S4D):

complexplot_gene_perturbation(genes_df, interest_df,
                              targets = targets,
                              lfsr_mat = fdr_mat, lfsr_name = "FDR",
                              effect_mat = FC_mat, effect_name = "DESeq2 log2FC",
                              score_break = c(-0.4, 0, 0.4),
                              color_break = c("blue3", "grey90", "red3"))

4.2.4 MAST

FC_mat <- matrix(nrow = nrow(interest_df), ncol = length(targets))
rownames(FC_mat) <- interest_df$gene_name
colnames(FC_mat) <- targets
fdr_mat <- FC_mat
for (m in targets){
  FC_mat[, m] <- mast_list[[m]]$logFC[match(interest_df$gene_ID, 
                                            mast_list[[m]]$geneID)]
  fdr_mat[, m] <- mast_list[[m]]$FDR[match(interest_df$gene_ID, 
                                           mast_list[[m]]$geneID)]
}

MAST estimated effects of perturbations on marker genes (Figure S4E):

complexplot_gene_perturbation(genes_df, interest_df,
                              targets = targets,
                              lfsr_mat = fdr_mat, lfsr_name = "FDR",
                              effect_mat = FC_mat, effect_name = "MAST logFC",
                              score_break = c(-0.4, 0, 0.4),
                              color_break = c("blue3", "grey90", "red3"))

4.2.5 SCEPTRE

FC_mat <- matrix(nrow = nrow(interest_df), ncol = length(targets))
rownames(FC_mat) <- interest_df$gene_name
colnames(FC_mat) <- targets
fdr_mat <- FC_mat
for (m in targets){
  sceptre_tmp_res <- sceptre_res %>% filter(gRNA_id == m)
  tmp_pval <- sceptre_tmp_res %>% pull(p_value)
  sceptre_tmp_res$FDR <- p.adjust(tmp_pval, method = "fdr")
  FC_mat[, m] <- sceptre_tmp_res$log_fold_change[match(interest_df$gene_ID, 
                                                       sceptre_tmp_res$gene_id)]
  fdr_mat[, m] <- sceptre_tmp_res$FDR[match(interest_df$gene_ID, 
                                            sceptre_tmp_res$gene_id)]
}

SCEPTRE estimated effects of perturbations on marker genes (Figure S4F):

complexplot_gene_perturbation(genes_df, interest_df,
                              targets = targets,
                              lfsr_mat = fdr_mat, lfsr_name = "FDR",
                              effect_mat = FC_mat, effect_name = "SCEPTRE logFC",
                              score_break = c(-0.4, 0, 0.4),
                              color_break = c("blue3", "grey90", "red3"))

4.3 GO enrichment in DEGs

We further examine these DEGs for enrichment of relevant biological processes through GO enrichment analysis.

Foreground genes: Genes w/ GSFA LFSR < 0.05 under each perturbation;
Background genes: all 6000 genes used in GSFA;
Statistical test: hypergeometric test (over-representation test);
Gene sets: GO Slim “Biological Process” (non-redundant).

## The "WebGestaltR" tool needs Internet connection.
enrich_db <- "geneontology_Biological_Process_noRedundant"
enrich_res <- list()
for (i in names(lfsr_signif_num)[lfsr_signif_num > 0]){
  print(i)
  interest_genes <- genes_df %>% mutate(lfsr = lfsr_mat1[, i]) %>%
    filter(lfsr < lfsr_cutoff) %>% pull(ID)
  enrich_res[[i]] <- 
    WebGestaltR::WebGestaltR(enrichMethod = "ORA",
                             organism = "hsapiens",
                             enrichDatabase = enrich_db,
                             interestGene = interest_genes,
                             interestGeneType = "ensembl_gene_id",
                             referenceGene = genes_df$ID,
                             referenceGeneType = "ensembl_gene_id",
                             isOutput = F)
}
signif_GO_list <- list()
for (i in names(enrich_res)) {
  signif_GO_list[[i]] <- enrich_res[[i]] %>%
    dplyr::filter(FDR < 0.05) %>%
    dplyr::select(geneSet, description, size, enrichmentRatio, pValue) %>%
    mutate(target = i)
}
signif_term_df <- do.call(rbind, signif_GO_list) %>%
  group_by(geneSet, description, size) %>%
  summarise(pValue = min(pValue)) %>%
  ungroup()

abs_FC_colormap <- circlize::colorRamp2(breaks = c(0, 3, 6),
                                        colors = c("grey95", "#77d183", "#255566"))
enrich_table <- data.frame(matrix(nrow = nrow(signif_term_df),
                                  ncol = length(names(enrich_res))),
                           row.names = signif_term_df$geneSet)
colnames(enrich_table) <- names(enrich_res)
for (i in 1:ncol(enrich_table)){
  m <- colnames(enrich_table)[i]
  enrich_df <- enrich_res[[m]] # %>% filter(enrichmentRatio > 2)
  enrich_table[enrich_df$geneSet, i] <- enrich_df$enrichmentRatio
}
rownames(enrich_table) <- signif_term_df$description

Here are selected GO “biological process”” terms and their folds of enrichment in DEGs detected by GSFA (Figure 4C).
(In the code below, we omitted the content in terms_of_interest_df as one can subset the enrich_table with any terms of their choice.)

interest_enrich_table <- enrich_table[terms_of_interest_df$description, ]
interest_enrich_table[is.na(interest_enrich_table)] <- 0
# Convert only the first letter of each GO term to upper case.
rownames(interest_enrich_table) <-
  str_replace(rownames(interest_enrich_table),  "^\\w{1}", toupper)
map <- Heatmap(interest_enrich_table[, targets],
               name = "Fold of enrichment",
               col = abs_FC_colormap,
               row_title = NULL, column_title = NULL,
               cluster_rows = F, cluster_columns = F,
               show_row_dend = F, show_column_dend = F,
               show_heatmap_legend = T,
               row_names_gp = gpar(fontsize = 10.5),
               column_names_rot = 45,
               width = unit(7, "cm"))
draw(map, heatmap_legend_side = "right")

This next plot expanded the gRNA targets to all that have DEGs detected:

interest_enrich_table <- enrich_table[terms_of_interest_df$description, ]
interest_enrich_table[is.na(interest_enrich_table)] <- 0
# Convert only the first letter of each GO term to upper case.
rownames(interest_enrich_table) <-
  str_replace(rownames(interest_enrich_table),  "^\\w{1}", toupper)

map <- Heatmap(interest_enrich_table,
               name = "Fold of enrichment",
               col = abs_FC_colormap,
               row_title = NULL, column_title = NULL,
               cluster_rows = F, cluster_columns = F,
               show_row_dend = F, show_column_dend = F,
               show_heatmap_legend = T,
               row_names_gp = gpar(fontsize = 10.5),
               column_names_rot = 45,
               width = unit(10, "cm"))
draw(map, heatmap_legend_side = "right")

Similar GO enrichment analyses were performed on DEGs detected by alternative methods (FDR < 0.05).
Below summarizes the number of significant GO terms in DEGs by each method:

enrich_thres <- 0.05
enrich_dir <- paste0(wkdir, result_folder, "WebGestalt_ORA/")
enrich_res <- readRDS(paste0(enrich_dir,
                             "GO_enrich_in_GSFA_DEGs_stimulated.rds"))
gsfa_term_count <-
  sapply(enrich_res, function(x){ x %>% dplyr::filter(FDR < enrich_thres) %>% nrow()})
# Only keep target genes with > 100 DEGs to simplify plot.
gsfa_term_count <- gsfa_term_count[targets]

term_count_df <- data.frame(Perturbation = names(gsfa_term_count),
                            GSFA = as.numeric(gsfa_term_count))
for (method in c("scmageck", "DESeq2", "MAST", "sceptre")) {
  enrich_res <- readRDS(paste0(enrich_dir,
                               method, "_DEGs_fdr_0.05.go_bp_thres_1.stim.rds"))
  term_count <-
    sapply(enrich_res, function(x){ x %>% dplyr::filter(FDR < enrich_thres) %>% nrow()})
  term_count_df[[method]] <- term_count[term_count_df$Perturbation]
}
names(term_count_df)[c(3, 6)] <- c("scMAGeCK", "SCEPTRE")
term_plot_df <- term_count_df %>%
  tidyr::pivot_longer(cols = !Perturbation,
                      names_to = "Method", values_to = "Num_GO_terms") %>%
  dplyr::mutate(Method = factor(Method, levels = names(term_count_df)[-1]))
term_plot_df$Num_GO_terms <-
  tidyr::replace_na(term_plot_df$Num_GO_terms, 0)

num_terms_plt <-
  ggplot(term_plot_df, aes(x = Perturbation, y = Num_GO_terms, fill = Method)) +
  geom_bar(position = "dodge", stat = "identity") +
  geom_text(aes(label = Num_GO_terms),
            position = position_dodge(width = 0.9), vjust = -0.25) +
  scale_fill_brewer(palette = "Set2") +
  labs(x = "Target gene",
       y = "Number of enriched GO terms",
       title = "Number of GO terms enriched in DEGs detected by different methods") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 12),
        legend.text = element_text(size = 13))
num_terms_plt

5 Session Information

sessionInfo()
R version 4.2.0 (2022-04-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /software/openblas-0.3.13-el7-x86_64/lib/libopenblas_haswellp-r0.3.13.so

locale:
 [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C         LC_TIME=C           
 [4] LC_COLLATE=C         LC_MONETARY=C        LC_MESSAGES=C       
 [7] LC_PAPER=C           LC_NAME=C            LC_ADDRESS=C        
[10] LC_TELEPHONE=C       LC_MEASUREMENT=C     LC_IDENTIFICATION=C 

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] lattice_0.20-45       sp_1.4-7              SeuratObject_4.1.0   
 [4] Seurat_4.1.1          WebGestaltR_0.4.4     kableExtra_1.3.4     
 [7] ComplexHeatmap_2.12.1 gridExtra_2.3         forcats_0.5.1        
[10] stringr_1.4.0         dplyr_1.0.9           purrr_0.3.4          
[13] readr_2.1.2           tidyr_1.2.0           tibble_3.1.7         
[16] ggplot2_3.3.6         tidyverse_1.3.2       Matrix_1.4-1         
[19] data.table_1.14.2    

loaded via a namespace (and not attached):
  [1] readxl_1.4.0          backports_1.4.1       circlize_0.4.15      
  [4] systemfonts_1.0.4     plyr_1.8.7            igraph_1.3.1         
  [7] lazyeval_0.2.2        splines_4.2.0         listenv_0.8.0        
 [10] scattermore_0.8       digest_0.6.29         foreach_1.5.2        
 [13] htmltools_0.5.2       fansi_1.0.3           magrittr_2.0.3       
 [16] tensor_1.5            googlesheets4_1.0.0   cluster_2.1.3        
 [19] doParallel_1.0.17     ROCR_1.0-11           tzdb_0.3.0           
 [22] globals_0.15.0        modelr_0.1.8          matrixStats_0.62.0   
 [25] svglite_2.1.0         spatstat.sparse_2.1-1 colorspace_2.0-3     
 [28] rvest_1.0.2           ggrepel_0.9.1         haven_2.5.0          
 [31] xfun_0.30             crayon_1.5.1          jsonlite_1.8.0       
 [34] spatstat.data_2.2-0   progressr_0.10.0      survival_3.3-1       
 [37] zoo_1.8-10            iterators_1.0.14      glue_1.6.2           
 [40] polyclip_1.10-0       gtable_0.3.0          gargle_1.2.0         
 [43] webshot_0.5.3         leiden_0.4.2          GetoptLong_1.0.5     
 [46] future.apply_1.9.0    shape_1.4.6           BiocGenerics_0.42.0  
 [49] apcluster_1.4.10      abind_1.4-5           scales_1.2.0         
 [52] DBI_1.1.2             rngtools_1.5.2        spatstat.random_2.2-0
 [55] miniUI_0.1.1.1        Rcpp_1.0.8.3          xtable_1.8-4         
 [58] viridisLite_0.4.0     clue_0.3-61           spatstat.core_2.4-2  
 [61] reticulate_1.24       stats4_4.2.0          htmlwidgets_1.5.4    
 [64] httr_1.4.3            RColorBrewer_1.1-3    ellipsis_0.3.2       
 [67] ica_1.0-2             farver_2.1.0          pkgconfig_2.0.3      
 [70] uwot_0.1.11           deldir_1.0-6          sass_0.4.1           
 [73] dbplyr_2.1.1          utf8_1.2.2            labeling_0.4.2       
 [76] reshape2_1.4.4        tidyselect_1.1.2      rlang_1.0.5          
 [79] later_1.3.0           munsell_0.5.0         cellranger_1.1.0     
 [82] tools_4.2.0           cli_3.3.0             generics_0.1.2       
 [85] broom_0.8.0           ggridges_0.5.3        evaluate_0.15        
 [88] fastmap_1.1.0         goftest_1.2-3         yaml_2.3.5           
 [91] knitr_1.39            fs_1.5.2              fitdistrplus_1.1-8   
 [94] pander_0.6.5          RANN_2.6.1            nlme_3.1-157         
 [97] pbapply_1.5-0         future_1.25.0         doRNG_1.8.2          
[100] whisker_0.4           mime_0.12             xml2_1.3.3           
[103] compiler_4.2.0        rstudioapi_0.13       plotly_4.10.0        
[106] png_0.1-7             spatstat.utils_2.3-1  reprex_2.0.1         
[109] bslib_0.3.1           stringi_1.7.6         highr_0.9            
[112] rgeos_0.5-9           vctrs_0.4.1           pillar_1.7.0         
[115] lifecycle_1.0.1       spatstat.geom_2.4-0   lmtest_0.9-40        
[118] jquerylib_0.1.4       GlobalOptions_0.1.2   RcppAnnoy_0.0.19     
[121] cowplot_1.1.1         irlba_2.3.5           patchwork_1.1.1      
[124] httpuv_1.6.5          R6_2.5.1              promises_1.2.0.1     
[127] KernSmooth_2.23-20    IRanges_2.30.0        parallelly_1.31.1    
[130] codetools_0.2-18      MASS_7.3-56           assertthat_0.2.1     
[133] rjson_0.2.21          withr_2.5.0           sctransform_0.3.3    
[136] S4Vectors_0.34.0      mgcv_1.8-40           parallel_4.2.0       
[139] hms_1.1.1             rpart_4.1.16          rmarkdown_2.14       
[142] googledrive_2.0.0     Rtsne_0.16            shiny_1.7.1          
[145] lubridate_1.8.0