comparison goseq.r @ 8:8b3e3657034e draft

"planemo upload for repository https://github.com/galaxyproject/tools-iuc/tree/master/tools/goseq commit 8e19f8bcaea6f607a1eaa14bb88f2d625ed63df0"
author iuc
date Fri, 06 Sep 2019 07:50:46 -0400
parents 67c29afac85f
children ef2ad746b589
comparison
equal deleted inserted replaced
7:67c29afac85f 8:8b3e3657034e
8 library("optparse") 8 library("optparse")
9 library("dplyr") 9 library("dplyr")
10 library("ggplot2") 10 library("ggplot2")
11 }) 11 })
12 12
13 sessionInfo()
14
13 option_list <- list( 15 option_list <- list(
14 make_option(c("-d", "--dge_file"), type="character", help="Path to file with differential gene expression result"), 16 make_option(c("-d", "--dge_file"), type="character", help="Path to file with differential gene expression result"),
15 make_option(c("-w","--wallenius_tab"), type="character", help="Path to output file with P-values estimated using wallenius distribution."), 17 make_option(c("-lf", "--length_file"), type="character", default=NULL, help="Path to tabular file mapping gene id to length"),
16 make_option(c("-s","--sampling_tab"), type="character", default=FALSE, help="Path to output file with P-values estimated using sampling distribution."), 18 make_option(c("-g", "--genome"), type="character", default=NULL, help="Genome [used for looking up correct gene length]"),
17 make_option(c("-n","--nobias_tab"), type="character", default=FALSE, help="Path to output file with P-values estimated using hypergeometric distribution and no correction for gene length bias."), 19 make_option(c("-i", "--gene_id"), type="character", default=NULL, help="Gene ID format of genes in DGE file"),
18 make_option(c("-l","--length_bias_plot"), type="character", default=FALSE, help="Path to length-bias plot."), 20 make_option(c("-fc", "--fetch_cats"), type="character", default=NULL, help="Categories to get can include one or more of GO:CC, GO:BP, GO:MF, KEGG"),
19 make_option(c("-sw","--sample_vs_wallenius_plot"), type="character", default=FALSE, help="Path to plot comparing sampling with wallenius p-values."), 21 make_option(c("-cat_file", "--category_file"), type="character", default=NULL, help="Path to tabular file with gene_id <-> category mapping"),
20 make_option(c("-r", "--repcnt"), type="integer", default=100, help="Number of repeats for sampling"), 22 make_option(c("-w","--wallenius_tab"), type="character", default=NULL, help="Path to output file with P-values estimated using wallenius distribution"),
21 make_option(c("-lf", "--length_file"), type="character", default="FALSE", help = "Path to tabular file mapping gene id to length"), 23 make_option(c("-n","--nobias_tab"), type="character", default=NULL, help="Path to output file with P-values estimated using hypergeometric distribution and no correction for gene length bias"),
22 make_option(c("-cat_file", "--category_file"), default="FALSE", type="character", help = "Path to tabular file with gene_id <-> category mapping."), 24 make_option(c("-r", "--repcnt"), type="integer", default=0, help="Number of repeats for sampling"),
23 make_option(c("-g", "--genome"), default=NULL, type="character", help = "Genome [used for looking up correct gene length]"), 25 make_option(c("-s","--sampling_tab"), type="character", default=NULL, help="Path to output file with P-values estimated using sampling distribution"),
24 make_option(c("-i", "--gene_id"), default=NULL, type="character", help = "Gene ID format of genes in DGE file"), 26 make_option(c("-p", "--p_adj_method"), type="character", default="BH", help="Multiple hypothesis testing correction method to use"),
25 make_option(c("-p", "--p_adj_method"), default="BH", type="character", help="Multiple hypothesis testing correction method to use"), 27 make_option(c("-cat", "--use_genes_without_cat"), type="logical", default=FALSE, help="A large number of gene may have no GO term annotated. If this option is set to FALSE, genes without category will be ignored in the calculation of p-values(default behaviour). If TRUE these genes will count towards the total number of genes outside the tested category (default behaviour prior to version 1.15.2)."),
26 make_option(c("-cat", "--use_genes_without_cat"), default=FALSE, type="logical", 28 make_option(c("-tp", "--top_plot"), type="character", default=NULL, help="Path to output PDF with top10 over-rep GO terms"),
27 help="A large number of gene may have no GO term annotated. If this option is set to FALSE, genes without category will be ignored in the calculation of p-values(default behaviour). If TRUE these genes will count towards the total number of genes outside the tested category (default behaviour prior to version 1.15.2)."), 29 make_option(c("-plots", "--make_plots"), default=FALSE, type="logical", help="Produce diagnostic plots?"),
28 make_option(c("-plots", "--make_plots"), default=FALSE, type="logical", help="produce diagnostic plots?"), 30 make_option(c("-l","--length_bias_plot"), type="character", default=NULL, help="Path to length-bias plot"),
29 make_option(c("-fc", "--fetch_cats"), default=NULL, type="character", help="Categories to get can include one or more of GO:CC, GO:BP, GO:MF, KEGG"), 31 make_option(c("-sw","--sample_vs_wallenius_plot"), type="character", default=NULL, help="Path to plot comparing sampling with wallenius p-values"),
30 make_option(c("-rd", "--rdata"), default=NULL, type="character", help="Path to RData output file."), 32 make_option(c("-rd", "--rdata"), type="character", default=NULL, help="Path to RData output file"),
31 make_option(c("-tp", "--top_plot"), default=NULL, type="logical", help="Output PDF with top10 over-rep GO terms?") 33 make_option(c("-g2g", "--categories_genes_out_fp"), type="character", default=NULL, help="Path to file with categories (GO/KEGG terms) and associated DE genes")
32 ) 34 )
33 35
34 parser <- OptionParser(usage = "%prog [options] file", option_list=option_list) 36 parser <- OptionParser(usage = "%prog [options] file", option_list=option_list)
35 args = parse_args(parser) 37 args = parse_args(parser)
36
37 # Vars:
38 dge_file = args$dge_file
39 category_file = args$category_file
40 length_file = args$length_file
41 genome = args$genome
42 gene_id = args$gene_id
43 wallenius_tab = args$wallenius_tab
44 sampling_tab = args$sampling_tab
45 nobias_tab = args$nobias_tab
46 length_bias_plot = args$length_bias_plot
47 sample_vs_wallenius_plot = args$sample_vs_wallenius_plot
48 repcnt = args$repcnt
49 p_adj_method = args$p_adj_method
50 use_genes_without_cat = args$use_genes_without_cat
51 make_plots = args$make_plots
52 rdata = args$rdata
53 38
54 if (!is.null(args$fetch_cats)) { 39 if (!is.null(args$fetch_cats)) {
55 fetch_cats = unlist(strsplit(args$fetch_cats, ",")) 40 fetch_cats = unlist(strsplit(args$fetch_cats, ","))
56 } else { 41 } else {
57 fetch_cats = "Custom" 42 fetch_cats = "Custom"
58 } 43 }
59 44
60 # format DE genes into named vector suitable for goseq 45 # format DE genes into named vector suitable for goseq
61 # check if header is present 46 # check if header is present
62 first_line = read.delim(dge_file, header = FALSE, nrow=1) 47 first_line = read.delim(args$dge_file, header=FALSE, nrow=1)
63 second_col = toupper(first_line[, ncol(first_line)]) 48 second_col = toupper(first_line[, ncol(first_line)])
64 if (second_col == TRUE || second_col == FALSE) { 49 if (second_col == TRUE || second_col == FALSE) {
65 dge_table = read.delim(dge_file, header = FALSE, sep="\t") 50 dge_table = read.delim(args$dge_file, header=FALSE, sep="\t")
66 } else { 51 } else {
67 dge_table = read.delim(dge_file, header = TRUE, sep="\t") 52 dge_table = read.delim(args$dge_file, header=TRUE, sep="\t")
68 } 53 }
69 genes = as.numeric(as.logical(dge_table[,ncol(dge_table)])) # Last column contains TRUE/FALSE 54 genes = as.numeric(as.logical(dge_table[, ncol(dge_table)])) # Last column contains TRUE/FALSE
70 names(genes) = dge_table[,1] # Assuming first column contains gene names 55 names(genes) = dge_table[,1] # Assuming first column contains gene names
71 56
72 # gene lengths, assuming last column 57 # gene lengths, assuming last column
73 if (length_file != "FALSE" ) { 58 first_line = read.delim(args$length_file, header=FALSE, nrow=1)
74 first_line = read.delim(length_file, header = FALSE, nrow=1) 59 if (is.numeric(first_line[, ncol(first_line)])) {
75 if (is.numeric(first_line[, ncol(first_line)])) { 60 length_table = read.delim(args$length_file, header=FALSE, sep="\t", check.names=FALSE)
76 length_table = read.delim(length_file, header=FALSE, sep="\t", check.names=FALSE) 61 } else {
77 } else { 62 length_table = read.delim(args$length_file, header=TRUE, sep="\t", check.names=FALSE)
78 length_table = read.delim(length_file, header=TRUE, sep="\t", check.names=FALSE) 63 }
79 } 64 row.names(length_table) = length_table[,1]
80 row.names(length_table) = length_table[,1] 65 # get vector of gene length in same order as the genes
81 gene_lengths = length_table[names(genes),][,ncol(length_table)] 66 gene_lengths = length_table[names(genes),][, ncol(length_table)]
82 } else {
83 gene_lengths = getlength(names(genes), genome, gene_id)
84 }
85 67
86 # Estimate PWF 68 # Estimate PWF
87 69 if (args$make_plots) {
88 if (make_plots != 'false') { 70 pdf(args$length_bias_plot)
89 pdf(length_bias_plot)
90 } 71 }
91 pwf=nullp(genes, genome = genome, id = gene_id, bias.data = gene_lengths, plot.fit=make_plots) 72 pwf=nullp(genes, genome=args$genome, id=args$gene_id, bias.data=gene_lengths, plot.fit=args$make_plots)
92 if (make_plots != 'false') { 73 if (args$make_plots) {
93 dev.off() 74 dev.off()
94 } 75 }
95 76
96 # Fetch GO annotations if category_file hasn't been supplied: 77 # Fetch GO annotations if category_file hasn't been supplied:
97 if (category_file == "FALSE") { 78 if (is.null(args$category_file)) {
98 go_map=getgo(genes = names(genes), genome=genome, id=gene_id, fetch.cats=fetch_cats) 79 go_map=getgo(genes=names(genes), genome=args$genome, id=args$gene_id, fetch.cats=fetch_cats)
80 } else {
81 # check for header: first entry in first column must be present in genes, else it's a header
82 first_line = read.delim(args$category_file, header=FALSE, nrow=1)
83 if (first_line[,1] %in% names(genes)) {
84 go_map = read.delim(args$category_file, header=FALSE)
99 } else { 85 } else {
100 # check for header: first entry in first column must be present in genes, else it's a header 86 go_map = read.delim(args$category_file, header=TRUE)
101 first_line = read.delim(category_file, header = FALSE, nrow=1) 87 }
102 if (first_line[,1] %in% names(genes)) {
103 go_map = read.delim(category_file, header = FALSE)
104 } else {
105 go_map = read.delim(category_file, header= TRUE)
106 }
107 } 88 }
108 89
109 results <- list() 90 results <- list()
110 91
111 # wallenius approximation of p-values 92 runGoseq <- function(pwf, genome, gene_id, goseq_method, use_genes_without_cat, repcnt, gene2cat, p_adj_method, out_fp){
112 if (wallenius_tab != FALSE) { 93 out=goseq(pwf, genome=genome, id=gene_id, method=goseq_method, use_genes_without_cat=use_genes_without_cat, gene2cat=go_map)
113 GO.wall=goseq(pwf, genome = genome, id = gene_id, use_genes_without_cat = use_genes_without_cat, gene2cat=go_map) 94 out$p.adjust.over_represented = p.adjust(out$over_represented_pvalue, method=p_adj_method)
114 GO.wall$p.adjust.over_represented = p.adjust(GO.wall$over_represented_pvalue, method=p_adj_method) 95 out$p.adjust.under_represented = p.adjust(out$under_represented_pvalue, method=p_adj_method)
115 GO.wall$p.adjust.under_represented = p.adjust(GO.wall$under_represented_pvalue, method=p_adj_method) 96 write.table(out, out_fp, sep="\t", row.names=FALSE, quote=FALSE)
116 write.table(GO.wall, args$wallenius_tab, sep="\t", row.names = FALSE, quote = FALSE) 97 return(out)
117 results[['Wallenius']] <- GO.wall
118 } 98 }
119 99
100 # wallenius approximation of p-values
101 if (!is.null(args$wallenius_tab)) results[['Wallenius']] <- runGoseq(
102 pwf,
103 genome=args$genome,
104 gene_id=args$gene_id,
105 goseq_method="Wallenius",
106 use_genes_without_cat=args$use_genes_without_cat,
107 repcnt=args$repcnt,
108 gene2cat=go_map,
109 p_adj_method=args$p_adj_method,
110 out_fp=args$wallenius_tab)
111
112
120 # hypergeometric (no length bias correction) 113 # hypergeometric (no length bias correction)
121 if (nobias_tab != FALSE) { 114 if (!is.null(args$nobias_tab)) results[['Hypergeometric']] <- runGoseq(
122 GO.nobias=goseq(pwf, genome = genome, id = gene_id, method="Hypergeometric", use_genes_without_cat = use_genes_without_cat, gene2cat=go_map) 115 pwf,
123 GO.nobias$p.adjust.over_represented = p.adjust(GO.nobias$over_represented_pvalue, method=p_adj_method) 116 genome=args$genome,
124 GO.nobias$p.adjust.under_represented = p.adjust(GO.nobias$under_represented_pvalue, method=p_adj_method) 117 gene_id=args$gene_id,
125 write.table(GO.nobias, args$nobias_tab, sep="\t", row.names = FALSE, quote = FALSE) 118 goseq_method="Hypergeometric",
126 results[['Hypergeometric']] <- GO.nobias 119 use_genes_without_cat=args$use_genes_without_cat,
120 repcnt=args$repcnt,
121 gene2cat=go_map,
122 p_adj_method=args$p_adj_method,
123 out_fp=args$nobias_tab)
124
125 # Sampling distribution
126 if (args$repcnt > 0){
127 results[['Sampling']] <- runGoseq(
128 pwf,
129 genome=args$genome,
130 gene_id=args$gene_id,
131 goseq_method="Sampling",
132 use_genes_without_cat=args$use_genes_without_cat,
133 repcnt=args$repcnt,
134 gene2cat=go_map,
135 p_adj_method=args$p_adj_method,
136 out_fp=args$sampling_tab)
137
138 # Compare sampling with wallenius
139 if (args$make_plots & !is.null(args$wallenius_tab)) {
140 pdf(args$sample_vs_wallenius_plot)
141 plot(log10(results[['Wallenius']][,2]),
142 log10(results[['Sampling']][match(results[['Sampling']][,1], results[['Wallenius']][,1]), 2]),
143 xlab="log10(Wallenius p-values)",
144 ylab="log10(Sampling p-values)",
145 xlim=c(-3,0))
146 abline(0,1,col=3,lty=2)
147 dev.off()
148 }
127 } 149 }
128 150
129 # Sampling distribution 151 # Plot the top 10
130 if (repcnt > 0) {
131
132 # capture the sampling progress so it doesn't fill stdout
133 zz <- file("/dev/null", open = "wt")
134 sink(zz)
135 GO.samp=goseq(pwf, genome = genome, id = gene_id, method="Sampling", repcnt=repcnt, use_genes_without_cat = use_genes_without_cat, gene2cat=go_map)
136 sink()
137
138 GO.samp$p.adjust.over_represented = p.adjust(GO.samp$over_represented_pvalue, method=p_adj_method)
139 GO.samp$p.adjust.under_represented = p.adjust(GO.samp$under_represented_pvalue, method=p_adj_method)
140 write.table(GO.samp, sampling_tab, sep="\t", row.names = FALSE, quote = FALSE)
141 # Compare sampling with wallenius
142 if (make_plots == TRUE) {
143 pdf(sample_vs_wallenius_plot)
144 plot(log10(GO.wall[,2]), log10(GO.samp[match(GO.samp[,1],GO.wall[,1]),2]),
145 xlab="log10(Wallenius p-values)",ylab="log10(Sampling p-values)",
146 xlim=c(-3,0))
147 abline(0,1,col=3,lty=2)
148 dev.off()
149 }
150 results[['Sampling']] <- GO.samp
151 }
152
153 if (!is.null(args$top_plot)) { 152 if (!is.null(args$top_plot)) {
154 cats_title <- gsub("GO:","", args$fetch_cats) 153 cats_title <- gsub("GO:","", args$fetch_cats)
155 # modified from https://bioinformatics-core-shared-training.github.io/cruk-summer-school-2018/RNASeq2018/html/06_Gene_set_testing.nb.html 154 # modified from https://bioinformatics-core-shared-training.github.io/cruk-summer-school-2018/RNASeq2018/html/06_Gene_set_testing.nb.html
156 pdf("top10.pdf") 155 pdf(args$top_plot)
157 for (m in names(results)) { 156 for (m in names(results)) {
158 p <- results[[m]] %>% 157 p <- results[[m]] %>%
159 top_n(10, wt=-over_represented_pvalue) %>% 158 top_n(10, wt=-over_represented_pvalue) %>%
160 mutate(hitsPerc=numDEInCat*100/numInCat) %>% 159 mutate(hitsPerc=numDEInCat*100/numInCat) %>%
161 ggplot(aes(x=hitsPerc, 160 ggplot(aes(x=hitsPerc,
163 colour=p.adjust.over_represented, 162 colour=p.adjust.over_represented,
164 size=numDEInCat)) + 163 size=numDEInCat)) +
165 geom_point() + 164 geom_point() +
166 expand_limits(x=0) + 165 expand_limits(x=0) +
167 labs(x="% DE in category", y="Category", colour="Adj P value", size="Count", title=paste("Top over-represented categories in", cats_title), subtitle=paste(m, " method")) + 166 labs(x="% DE in category", y="Category", colour="Adj P value", size="Count", title=paste("Top over-represented categories in", cats_title), subtitle=paste(m, " method")) +
168 theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5)) 167 theme(plot.title=element_text(hjust = 0.5), plot.subtitle=element_text(hjust = 0.5))
169 print(p) 168 print(p)
170 } 169 }
171 dev.off() 170 dev.off()
172 } 171 }
173 172
173 # Extract the genes to the categories (GO/KEGG terms)
174 if (!is.null(args$categories_genes_out_fp)) {
175 cat2gene = split(rep(names(go_map), sapply(go_map, length)), unlist(go_map, use.names = FALSE))
176 # extract categories (GO/KEGG terms) for all results
177 categories = c()
178 for (m in names(results)) {
179 categories = c(categories, results[[m]]$category)
180 }
181 categories = unique(categories)
182 # extract the DE genes for each catge term
183 categories_genes = data.frame(Categories=categories, DEgenes=rep('', length(categories)))
184 categories_genes$DEgenes = as.character(categories_genes$DEgenes)
185 rownames(categories_genes) = categories
186 for (cat in categories){
187 tmp = pwf[cat2gene[[cat]],]
188 tmp = rownames(tmp[tmp$DEgenes > 0, ])
189 categories_genes[cat, 'DEgenes'] = paste(tmp, collapse=',')
190 }
191 # output
192 write.table(categories_genes, args$categories_genes_out_fp, sep = "\t", row.names=FALSE, quote=FALSE)
193 }
194
174 # Output RData file 195 # Output RData file
175 if (!is.null(args$rdata)) { 196 if (!is.null(args$rdata)) {
176 save.image(file = "goseq_analysis.RData") 197 save.image(file=args$rdata)
177 } 198 }
178
179
180 sessionInfo()