-
Notifications
You must be signed in to change notification settings - Fork 1
/
enrichment_functions.R
396 lines (346 loc) · 12.7 KB
/
enrichment_functions.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
###########################################################################
#
# enrichment_functions
#
###########################################################################
# Author: Matthew Muller
# Date: 2023-12-28
# Script Name: enrichment_functions
#======================== LIBRARIES ========================#
suppressMessages(library(tidyverse))
suppressMessages(library(clusterProfiler))
suppressMessages(library(org.Hs.eg.db))
# suppressMessages(library(AnnotationDbi))
suppressMessages(library(enrichplot))
suppressMessages(library(forcats))
suppressMessages(library(ggplot2))
suppressMessages(library(msigdbr))
suppressMessages(library(ggpubr))
# LOAD FUNCTIONS
# space reserved for sourcing in functions
source("https://raw.githubusercontent.com/mattmuller0/Rtools/main/general_functions.R")
source("https://raw.githubusercontent.com/mattmuller0/Rtools/main/plotting_functions.R")
source("https://raw.githubusercontent.com/mattmuller0/Rtools/main/converting_functions.R")
#======================== CODE ========================#
#' function to get the fc list
#' Arguments:
#' res: data frame of results
#' fc_col: column of fc values
#' names: column of names (if null default to rownames)
#' Outputs:
#' vector of sorted fc values
get_fc_list <- function(res, fc_col = "log2FoldChange", names = NULL) {
if (is.null(names)) {
res[, "rownames"] <- rownames(res)
names <- "rownames"
}
# get the fc values
fc <- res %>%
as.data.frame() %>%
# get the fc values
dplyr::select(!!sym(fc_col)) %>%
# make a named vector
unlist() %>%
# name the vector
set_names(res[, names]) %>%
# order the vector
sort(decreasing = T)
# return the fc
return(fc)
}
#' Run simple enrichment with enrichGO or gseGO
#' Arguments:
#' geneList: list of genes to run enrichment on
#' outpath: path to push results to
#' keyType: key type for gene list
#' enricher: enrichment method to use (default is gseGO)
#' image_type: type of image to save (default is pdf)
#' ...: additional arguments to pass to enricher
#' Outputs:
#' Enrichment results for each level of column of interest
rna_enrichment <- function(
geneList, outpath,
keyType = NULL, enricher_function = NULL,
image_type = "pdf", ontology = "ALL",
terms2plot = c("inflam", "immune", "plat"),
...
) {
require(SummarizedExperiment)
require(clusterProfiler)
require(org.Hs.eg.db)
require(AnnotationDbi)
require(enrichplot)
# get the type of the gene list if not specified
if (is.null(keyType)) {keyType <- detect_gene_id_type(names(geneList), strip = TRUE)}
# Output directory
dir.create(outpath, showWarnings = F, recursive = T)
# Get enrichment type and go on
if (is.null(enricher_function)) {
message("No enrichment function specified, defaulting to gseGO")
enricher_function <- gseGO
}
gse <- do.call(enricher_function, list(geneList, org.Hs.eg.db, keyType = keyType, ont = ontology, pvalueCutoff = Inf, ...))
write.csv(gse@result, file.path(outpath, "enrichment_results.csv"), quote = TRUE, row.names = FALSE)
saveRDS(gse, file.path(outpath, "enrichment_results.rds"))
save_gse(gse, outpath, image_type = image_type)
return(gse)
}
#' Function to save and plot gse object
#' Arguments:
#' gse: gse object
#' outpath: path to save to
#' ...: additional arguments to pass to ggsave
#' Outputs:
#' saves the gse object to the outpath
save_gse <- function(gse, outpath, ...) {
dir.create(outpath, showWarnings = FALSE, recursive = TRUE)
require(enrichplot)
require(ggplot2)
# save the gse object
write.csv(gse@result, file.path(outpath, "enrichment_results.csv"), quote = TRUE, row.names = FALSE)
write.csv(filter(gse@result, qvalue < 0.1), file.path(outpath, "enrichment_results_sig.csv"), quote = TRUE, row.names = FALSE)
saveRDS(gse, file.path(outpath, "enrichment_results.rds"))
tryCatch({
# Dotplot
gseDot <- enrichplot::dotplot(gse, showCategory = 20) + ggtitle("Enrichment Dotplot")
ggsave(file.path(outpath, paste0("dotplot.pdf")), gseDot, ...)
}, error = function(e) {
warning("Dotplot GSEA Plots Failed")
})
tryCatch({
# cnetplot
cnet <- cnetplot(gse, node_label="category", cex_label_gene = 0.8)
ggsave(file.path(outpath, paste0("cnetplot.pdf")), cnet, ...)
}, error = function(e) {
warning("Cnetplot GSEA Plots Failed")
})
tryCatch({
# Barplot data
gse_bar <- gse %>%
as.data.frame() %>%
group_by(sign(NES)) %>%
arrange(qvalue) %>%
slice(1:10) %>%
mutate(
Description = gsub("^(REACTOME_|GO_|HALLMARK_)", "", Description),
Description = gsub("_", " ", Description),
Description = factor(stringr::str_wrap(Description, 40))
)
# Barplot
gseBar <- ggplot(gse_bar, aes(NES, fct_reorder(Description, NES), fill=qvalue)) +
geom_col(orientation = "y") +
scale_fill_continuous(low="red", high="blue", guide=guide_colorbar(reverse=TRUE)) +
labs(title="Enrichment Barplot", y = NULL) +
theme_classic2()
ggsave(file.path(outpath, paste0("barplot_all.pdf")), gseBar, ...)
}, error = function(e) {
warning("GSEA Barplot Failed")
})
tryCatch({
# Barplot data
gse_bar_bp <- gse %>%
as.data.frame() %>%
filter(ONTOLOGY == "BP") %>%
group_by(sign(NES)) %>%
arrange(qvalue) %>%
slice(1:10) %>%
mutate(
Description = gsub("^(REACTOME_|GO_|HALLMARK_)", "", Description),
Description = gsub("_", " ", Description),
Description = factor(stringr::str_wrap(Description, 40))
)
gseBar_bp <- ggplot(gse_bar_bp, aes(NES , fct_reorder(Description, NES), fill=qvalue)) +
geom_col(orientation = "y") +
scale_fill_continuous(low="red", high="blue", guide=guide_colorbar(reverse=TRUE)) +
labs(title="Enrichment Barplot", y = NULL) +
theme_classic2()
ggsave(file.path(outpath, paste0("barplot_BP.pdf")), gseBar_bp, ...)
}, error = function(e) {
warning("GSEA Barplot BP Failed")
})
tryCatch({
# cnetplot
cnet <- cnetplot(gse, node_label="category", cex_label_gene = 0.8)
ggsave(file.path(outpath, paste0("cnetplot.pdf")), cnet, ...)
}, error = function(e) {
warning("Cnetplot GSEA Plots Failed")
})
tryCatch({
# Platelet Termed Barplot
p_terms <- plot_enrichment_terms(gse, terms2plot = c("inflam", "plat", "coag"), max_terms = 12)
ggsave(file.path(outpath, paste0("barplot_terms.pdf")), p_terms, ...)
}, error = function(e) {
warning("GSEA Term Specific Barplot Failed")
})
tryCatch({
p_ridge <- ridgeplot(gse, showCategory = 15)
ggsave(file.path(outpath, paste0("ridgeplot.pdf")), p_ridge, ...)
}, error = function(e) {
warning("RidgePlot GSEA Failed")
})
tryCatch({
p_heat <- heatplot(gse, showCategory = 10)
ggsave(file.path(outpath, paste0("heatplot.pdf")), p_heat, ...)
}, error = function(e) {
warning("Heatplot GSEA Failed")
})
}
#' Run a gsea analysis
#' Arguments:
#' geneList: list of genes to run enrichment on
#' outpath: path to push results to
#' keyType: key type for gene list
#' enricher: enrichment method to use (default is gseGO)
#' image_type: type of image to save (default is pdf)
#' ...: additional arguments to pass to enricher
#' Outputs:
#' Enrichment results for each level of column of interest
gsea_analysis <- function(
geneList, outpath,
keyType = NULL,
msigdb_category = "H", # I"m going to depricate this
ontology = "ALL"
) {
require(SummarizedExperiment)
require(clusterProfiler)
require(org.Hs.eg.db)
require(AnnotationDbi)
require(enrichplot)
require(forcats)
require(ggplot2)
require(msigdbr)
# get the type of the gene list if not specified
if (is.null(keyType)) {keyType <- detect_gene_id_type(names(geneList), strip = TRUE)}
# Output directory
dir.create(outpath, showWarnings = FALSE, recursive = TRUE)
# Run GSEA on a few genesets
msigdb <- msigdbr(species = "Homo sapiens")
gse_go <- gseGO(geneList, org.Hs.eg.db, keyType = keyType, ont = ontology, pvalueCutoff = Inf)
H_t2g <- msigdb %>%
filter(gs_cat == "H") %>%
dplyr::select(gs_name, gene_symbol)
gse_h <- GSEA(geneList, TERM2GENE = H_t2g, pvalueCutoff = Inf)
reactome_t2g <- msigdb %>%
filter(gs_cat == "C2" & gs_subcat == "CP:REACTOME") %>%
dplyr::select(gs_name, gene_symbol)
gse_reactome <- GSEA(geneList, TERM2GENE = reactome_t2g, pvalueCutoff = Inf)
# gse list to loop over
gse_list <- list(
GO = gse_go,
H = gse_h,
REACTOME = gse_reactome
)
for (idx in seq_along(gse_list)) {
# get the gse and the name
gse <- gse_list[[idx]]
name <- names(gse_list)[idx]
save_gse(gse, file.path(outpath, name))
}
return(gse_list)
}
#' Function to do up and down overrepresentation analysis
#' Arguments
#' - gene_dataframe [feature, direction] (output of getGenes)
#' - method
#' - padj_cutoff
#' - max_pathways
stratified_ora <- function(
gene_dataframe,
outpath,
method = "enrichGO",
padj_cutoff = 0.05,
max_pathways = 5,
...
) {
require(clusterProfiler)
require(enrichR)
require(org.Hs.eg.db)
# get the up and down genes
up_genes <- gene_dataframe %>% filter(direction == "up") %>% pull(features)
down_genes <- gene_dataframe %>% filter(direction == "down") %>% pull(features)
# make sure the method is supported
methods <- c("enrichGO", "groupGO")
if (!(method %in% methods)) {
stop("Method not supported. Please use one of: ", paste(methods, collapse = ", "))
}
enr_fn <- switch(method,
"enrichGO" = function(x) enrichGO(x, org.Hs.eg.db, pvalueCutoff = Inf, ...),
"groupGO" = function(x) groupGO(x, org.Hs.eg.db, pvalueCutoff = Inf, ...),
)
dir.create(outpath, showWarnings = FALSE, recursive = TRUE)
out <- purrr::map_dfr(
c("up", "down"), ~{
if (.x == "up") {
enr <- enr_fn(up_genes)
} else {
enr <- enr_fn(down_genes)
}
if (is.null(enr)) {
message("No results found for ", .x)
return(NULL)
}
save_gse(enr, file.path(outpath, .x))
enr@result %>%
filter(p.adjust < padj_cutoff) %>%
arrange(p.adjust) %>%
slice(1:max_pathways) %>%
mutate(direction = .x)
}
)
write.csv(out, file.path(outpath, "ora_results.csv"), quote = TRUE, row.names = FALSE)
out$signed <- ifelse(out$direction == "up", -log10(out$p.adjust), log10(out$p.adjust))
p <- ggplot(out, aes(x = signed, y = fct_reorder(stringr::str_wrap(Description, 40), signed), fill = direction)) +
geom_col() +
labs(title = "ORA Results", x = "Signed -log10(padj)", y = NULL) +
theme_classic2()
ggplot2::ggsave(file.path(outpath, "ora_results.pdf"), p)
return(out)
}
#' Function to do up and down overrepresentation analysis
#' Arguments
#' - gene_dataframe [feature, direction] (output of getGenes)
#' - method
#' - padj_cutoff
#' - max_pathways
stratified_enrichr <- function(
gene_dataframe,
outpath,
dbs = c("GO_Biological_Process_2023", "GO_Cellular_Component_2023", "GO_Molecular_Function_2023", "WikiPathway_2023_Human", "GWAS_Catalog_2023", "Reactome_2022", "MSigDB Hallmark 2020"),
padj_cutoff = 0.05,
max_pathways = 5,
...
) {
require(clusterProfiler)
require(enrichR)
require(org.Hs.eg.db)
# get the up and down genes
up_genes <- gene_dataframe %>% filter(direction == "up") %>% pull(features)
down_genes <- gene_dataframe %>% filter(direction == "down") %>% pull(features)
dir.create(outpath, showWarnings = FALSE, recursive = TRUE)
out_dbs <- purrr::map(dbs, ~{
dir.create(file.path(outpath, .x), showWarnings = FALSE, recursive = TRUE)
enr_up <- enrichr(up_genes, .x)[[.x]] %>% mutate(direction = "up")
enr_down <- enrichr(down_genes, .x)[[.x]] %>% mutate(direction = "down")
enr <- bind_rows(enr_up, enr_down)
if (nrow(enr) == 0) {
message("No results found for ", .x)
return(NULL)
}
write.csv(enr, file.path(outpath, .x, "enrichr_results.csv"), quote = TRUE, row.names = FALSE)
sign_enr <- enr %>%
group_by(direction) %>%
filter(Adjusted.P.value < padj_cutoff) %>%
arrange(Adjusted.P.value) %>%
slice(1:max_pathways) %>%
mutate(signed = ifelse(direction == "up", -log10(Adjusted.P.value), log10(Adjusted.P.value)))
write.csv(sign_enr, file.path(outpath, .x, "enrichr_results_sig.csv"), quote = TRUE, row.names = FALSE)
p <- ggplot(sign_enr, aes(x = signed, y = fct_reorder(stringr::str_wrap(Term, 40), signed), fill = direction)) +
geom_col() +
labs(title = "ORA Results", x = "Signed -log10(padj)", y = NULL) +
theme_classic2()
ggplot2::ggsave(file.path(outpath, .x, "enrichr_results.pdf"), p)
sign_enr
})
names(out_dbs) <- dbs
return(out_dbs)
}