132
|
1 <tool id="rgdifferentialcount" name="Differential_Count" version="0.28">
|
|
2 <description>models using BioConductor packages</description>
|
|
3 <requirements>
|
|
4 <requirement type="package" version="3.1.2">R</requirement>
|
|
5 <requirement type="package" version="1.3.18">graphicsmagick</requirement>
|
|
6 <requirement type="package" version="9.10">ghostscript</requirement>
|
|
7 <requirement type="package" version="2.14">biocbasics</requirement>
|
|
8 </requirements>
|
|
9
|
|
10 <command interpreter="python">
|
|
11 rgToolFactory.py --script_path "$runme" --interpreter "Rscript" --tool_name "Differential_Counts"
|
|
12 --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"
|
|
13 </command>
|
|
14 <inputs>
|
|
15 <param name="input1" type="data" format="tabular" label="Select an input matrix - rows are contigs, columns are counts for each sample"
|
|
16 help="Use the HTSeq based count matrix preparation tool to create these matrices from BAM/SAM files and a GTF file of genomic features"/>
|
|
17 <param name="title" type="text" value="Differential Counts" size="80" label="Title for job outputs"
|
|
18 help="Supply a meaningful name here to remind you what the outputs contain">
|
|
19 <sanitizer invalid_char="">
|
|
20 <valid initial="string.letters,string.digits"><add value="_" /> </valid>
|
|
21 </sanitizer>
|
|
22 </param>
|
|
23 <param name="treatment_name" type="text" value="Treatment" size="50" label="Treatment Name"/>
|
|
24 <param name="Treat_cols" label="Select columns containing treatment." type="data_column" data_ref="input1" numerical="True"
|
|
25 multiple="true" use_header_names="true" size="120" display="checkboxes" force_select="True">
|
|
26 <validator type="no_options" message="Please select at least one column."/>
|
|
27 </param>
|
|
28 <param name="control_name" type="text" value="Control" size="50" label="Control Name"/>
|
|
29 <param name="Control_cols" label="Select columns containing control." type="data_column" data_ref="input1" numerical="True"
|
|
30 multiple="true" use_header_names="true" size="120" display="checkboxes" force_select="True">
|
|
31 </param>
|
|
32 <param name="subjectids" type="text" optional="true" size="120" value = ""
|
|
33 label="IF SUBJECTS NOT ALL INDEPENDENT! Enter comma separated strings to indicate sample labels for (eg) pairing - must be one for every column in input"
|
|
34 help="Leave blank if no pairing, but eg if data from sample id A99 is in columns 2,4 and id C21 is in 3,5 then enter 'A99,C21,A99,C21'">
|
|
35 <sanitizer>
|
|
36 <valid initial="string.letters,string.digits"><add value="," /> </valid>
|
|
37 </sanitizer>
|
|
38 </param>
|
|
39 <param name="fQ" type="float" value="0.3" size="5" label="Non-differential contig count quantile threshold - zero to analyze all non-zero read count contigs"
|
|
40 help="May be a good or a bad idea depending on the biology and the question. EG 0.3 = sparsest 30% of contigs with at least one read are removed before analysis"/>
|
|
41 <param name="useNDF" type="boolean" truevalue="T" falsevalue="F" checked="false" size="1"
|
|
42 label="Non differential filter - remove contigs below a threshold (1 per million) for half or more samples"
|
|
43 help="May be a good or a bad idea depending on the biology and the question. This was the old default. Quantile based is available as an alternative"/>
|
|
44
|
|
45 <conditional name="edgeR">
|
|
46 <param name="doedgeR" type="select"
|
|
47 label="Run this model using edgeR"
|
|
48 help="edgeR uses a negative binomial model and seems to be powerful, even with few replicates">
|
|
49 <option value="F">Do not run edgeR</option>
|
|
50 <option value="T" selected="true">Run edgeR</option>
|
|
51 </param>
|
|
52 <when value="T">
|
|
53 <param name="edgeR_priordf" type="integer" value="10" size="3"
|
|
54 label="prior.df for tagwise dispersion - larger value = more squeezing of tag dispersions to common dispersion. Replaces prior.n and prior.df = prior.n * residual.df"
|
|
55 help="10 = edgeR default. Use a larger value to 'smooth' small samples. See edgeR docs and note below"/>
|
|
56 <param name="edgeR_robust_method" type="select" value="20" size="3"
|
|
57 label="Use robust dispersion method"
|
|
58 help="Use ordinary, anscombe or deviance robust deviance estimates">
|
|
59 <option value="ordinary" selected="true">Use ordinary deviance estimates</option>
|
|
60 <option value="deviance">Use robust deviance estimates</option>
|
|
61 <option value="anscombe">use Anscombe robust deviance estimates</option>
|
|
62 </param>
|
|
63 </when>
|
|
64 <when value="F"></when>
|
|
65 </conditional>
|
|
66 <conditional name="DESeq2">
|
|
67 <param name="doDESeq2" type="select"
|
|
68 label="Run the same model with DESeq2 and compare findings"
|
|
69 help="DESeq2 is an update to the DESeq package. It uses different assumptions and methods to edgeR">
|
|
70 <option value="F" selected="true">Do not run DESeq2</option>
|
|
71 <option value="T">Run DESeq2</option>
|
|
72 </param>
|
|
73 <when value="T">
|
|
74 <param name="DESeq_fitType" type="select">
|
|
75 <option value="parametric" selected="true">Parametric (default) fit for dispersions</option>
|
|
76 <option value="local">Local fit - this will automagically be used if parametric fit fails</option>
|
|
77 <option value="mean">Mean dispersion fit- use this if you really understand what you're doing - read the fine manual linked below in the documentation</option>
|
|
78 </param>
|
|
79 </when>
|
|
80 <when value="F"> </when>
|
|
81 </conditional>
|
|
82 <param name="doVoom" type="select"
|
|
83 label="Run the same model with Voom/limma and compare findings"
|
|
84 help="Voom uses counts per million and a precise transformation of variance so count data can be analysed using limma">
|
|
85 <option value="F" selected="true">Do not run VOOM</option>
|
|
86 <option value="T">Run VOOM</option>
|
|
87 </param>
|
|
88 <param name="fdrthresh" type="float" value="0.05" size="5" label="P value threshold for FDR filtering for amily wise error rate control"
|
|
89 help="Conventional default value of 0.05 recommended"/>
|
|
90 <param name="fdrtype" type="select" label="FDR (Type II error) control method"
|
|
91 help="Use fdr or bh typically to control for the number of tests in a reliable way">
|
|
92 <option value="fdr" selected="true">fdr</option>
|
|
93 <option value="BH">Benjamini Hochberg</option>
|
|
94 <option value="BY">Benjamini Yukateli</option>
|
|
95 <option value="bonferroni">Bonferroni</option>
|
|
96 <option value="hochberg">Hochberg</option>
|
|
97 <option value="holm">Holm</option>
|
|
98 <option value="hommel">Hommel</option>
|
|
99 <option value="none">no control for multiple tests</option>
|
|
100 </param>
|
|
101 </inputs>
|
|
102 <outputs>
|
|
103 <data format="tabular" name="out_edgeR" label="${title}_topTable_edgeR.xls">
|
|
104 <filter>edgeR['doedgeR'] == "T"</filter>
|
|
105 </data>
|
|
106 <data format="tabular" name="out_DESeq2" label="${title}_topTable_DESeq2.xls">
|
|
107 <filter>DESeq2['doDESeq2'] == "T"</filter>
|
|
108 </data>
|
|
109 <data format="tabular" name="out_VOOM" label="${title}_topTable_VOOM.xls">
|
|
110 <filter>doVoom == "T"</filter>
|
|
111 </data>
|
|
112 <data format="html" name="html_file" label="${title}.html"/>
|
|
113 </outputs>
|
|
114 <stdio>
|
|
115 <exit_code range="4" level="fatal" description="Number of subject ids must match total number of samples in the input matrix" />
|
|
116 </stdio>
|
|
117 <tests>
|
|
118 <test>
|
|
119 <param name='input1' value='test_bams2mx.xls' ftype='tabular' />
|
|
120 <param name='treatment_name' value='liver' />
|
|
121 <param name='title' value='edgeRtest' />
|
|
122 <param name='useNDF' value='' />
|
|
123 <param name='doedgeR' value='T' />
|
|
124 <param name='doVoom' value='T' />
|
|
125 <param name='doDESeq2' value='T' />
|
|
126 <param name='fdrtype' value='fdr' />
|
|
127 <param name='edgeR_priordf' value="8" />
|
|
128 <param name='edgeR_robust' value="ordinary" />
|
|
129 <param name='fdrthresh' value="0.05" />
|
|
130 <param name='control_name' value='heart' />
|
|
131 <param name='subjectids' value='' />
|
|
132 <param name='Control_cols' value='3,4,5,9' />
|
|
133 <param name='Treat_cols' value='2,6,7,8' />
|
|
134 <output name='out_edgeR' file='edgeRtest1out.xls' compare='diff' />
|
|
135 <output name='html_file' file='edgeRtest1out.html' compare='diff' lines_diff='20' />
|
|
136 </test>
|
|
137 </tests>
|
|
138
|
|
139 <configfiles>
|
|
140 <configfile name="runme">
|
|
141 <![CDATA[
|
|
142 #
|
|
143 # edgeR.Rscript
|
|
144 # updated feb 2014 adding outlier-robust deviance estimate options by ross for R 3.0.2/bioc 2.13
|
|
145 # updated npv 2011 for R 2.14.0 and edgeR 2.4.0 by ross
|
|
146 # Performs DGE on a count table containing n replicates of two conditions
|
|
147 #
|
|
148 # Parameters
|
|
149 #
|
|
150 # 1 - Output Dir
|
|
151
|
|
152 # Original edgeR code by: S.Lunke and A.Kaspi
|
|
153 reallybig = log10(.Machine\$double.xmax)
|
|
154 reallysmall = log10(.Machine\$double.xmin)
|
|
155 library("gplots")
|
|
156 library("edgeR")
|
|
157 hmap2 = function(cmat,nsamp=100,outpdfname='heatmap2.pdf', TName='Treatment',group=NA,myTitle='title goes here')
|
|
158 {
|
|
159 # Perform clustering for significant pvalues after controlling FWER
|
|
160 samples = colnames(cmat)
|
|
161 gu = unique(group)
|
|
162 gn = rownames(cmat)
|
|
163 if (length(gu) == 2) {
|
|
164 col.map = function(g) {if (g==gu[1]) "#FF0000" else "#0000FF"}
|
|
165 pcols = unlist(lapply(group,col.map))
|
|
166 } else {
|
|
167 colours = rainbow(length(gu),start=0,end=4/6)
|
|
168 pcols = colours[match(group,gu)] }
|
|
169 dm = cmat[(! is.na(gn)),]
|
|
170 # remove unlabelled hm rows
|
|
171 nprobes = nrow(dm)
|
|
172 # sub = paste('Showing',nprobes,'contigs ranked for evidence of differential abundance')
|
|
173 if (nprobes > nsamp) {
|
|
174 dm =dm[1:nsamp,]
|
|
175 #sub = paste('Showing',nsamp,'contigs ranked for evidence for differential abundance out of',nprobes,'total')
|
|
176 }
|
|
177 newcolnames = substr(colnames(dm),1,20)
|
|
178 colnames(dm) = newcolnames
|
|
179 pdf(outpdfname)
|
|
180 heatmap.2(dm,main=myTitle,ColSideColors=pcols,col=topo.colors(100),dendrogram="col",key=T,density.info='none',
|
|
181 Rowv=F,scale='row',trace='none',margins=c(8,8),cexRow=0.4,cexCol=0.5)
|
|
182 dev.off()
|
|
183 }
|
|
184
|
|
185 hmap = function(cmat,nmeans=4,outpdfname="heatMap.pdf",nsamp=250,TName='Treatment',group=NA,myTitle="Title goes here")
|
|
186 {
|
|
187 # for 2 groups only was
|
|
188 #col.map = function(g) {if (g==TName) "#FF0000" else "#0000FF"}
|
|
189 #pcols = unlist(lapply(group,col.map))
|
|
190 gu = unique(group)
|
|
191 colours = rainbow(length(gu),start=0.3,end=0.6)
|
|
192 pcols = colours[match(group,gu)]
|
|
193 nrows = nrow(cmat)
|
|
194 mtitle = paste(myTitle,'Heatmap: n contigs =',nrows)
|
|
195 if (nrows > nsamp) {
|
|
196 cmat = cmat[c(1:nsamp),]
|
|
197 mtitle = paste('Heatmap: Top ',nsamp,' DE contigs (of ',nrows,')',sep='')
|
|
198 }
|
|
199 newcolnames = substr(colnames(cmat),1,20)
|
|
200 colnames(cmat) = newcolnames
|
|
201 pdf(outpdfname)
|
|
202 heatmap(cmat,scale='row',main=mtitle,cexRow=0.3,cexCol=0.4,Rowv=NA,ColSideColors=pcols)
|
|
203 dev.off()
|
|
204 }
|
|
205
|
|
206 qqPlot = function(descr='qqplot',pvector, outpdf='qqplot.pdf',...)
|
|
207 # stolen from https://gist.github.com/703512
|
|
208 {
|
|
209 o = -log10(sort(pvector,decreasing=F))
|
|
210 e = -log10( 1:length(o)/length(o) )
|
|
211 o[o==-Inf] = reallysmall
|
|
212 o[o==Inf] = reallybig
|
|
213 maint = descr
|
|
214 pdf(outpdf)
|
|
215 plot(e,o,pch=19,cex=1, main=maint, ...,
|
|
216 xlab=expression(Expected~~-log[10](italic(p))),
|
|
217 ylab=expression(Observed~~-log[10](italic(p))),
|
|
218 xlim=c(0,max(e)), ylim=c(0,max(o)))
|
|
219 lines(e,e,col="red")
|
|
220 grid(col = "lightgray", lty = "dotted")
|
|
221 dev.off()
|
|
222 }
|
|
223
|
|
224 smearPlot = function(myDGEList,deTags, outSmear, outMain)
|
|
225 {
|
|
226 pdf(outSmear)
|
|
227 plotSmear(myDGEList,de.tags=deTags,main=outMain)
|
|
228 grid(col="lightgray", lty="dotted")
|
|
229 dev.off()
|
|
230 }
|
|
231
|
|
232 boxPlot = function(rawrs,cleanrs,maint,myTitle,pdfname)
|
|
233 {
|
|
234 nc = ncol(rawrs)
|
|
235 ##### for (i in c(1:nc)) {rawrs[(rawrs[,i] < 0),i] = NA}
|
|
236 fullnames = colnames(rawrs)
|
|
237 newcolnames = substr(colnames(rawrs),1,20)
|
|
238 colnames(rawrs) = newcolnames
|
|
239 newcolnames = substr(colnames(cleanrs),1,20)
|
|
240 colnames(cleanrs) = newcolnames
|
|
241 defpar = par(no.readonly=T)
|
|
242 print.noquote('@@@ Raw contig counts by sample:')
|
|
243 print.noquote(summary(rawrs))
|
|
244 print.noquote('@@@ Library size contig counts by sample:')
|
|
245 print.noquote(summary(cleanrs))
|
|
246 pdf(pdfname)
|
|
247 par(mfrow=c(1,2))
|
|
248 boxplot(rawrs,varwidth=T,notch=T,ylab='log contig count',col="maroon",las=3,cex.axis=0.35,main='log2 raw counts')
|
|
249 grid(col="lightgray",lty="dotted")
|
|
250 boxplot(cleanrs,varwidth=T,notch=T,ylab='log contig count',col="maroon",las=3,cex.axis=0.35,main=paste('log2 counts after ',maint))
|
|
251 grid(col="lightgray",lty="dotted")
|
|
252 dev.off()
|
|
253 pdfname = "sample_counts_histogram.pdf"
|
|
254 nc = ncol(rawrs)
|
|
255 print.noquote(paste('Using ncol rawrs=',nc))
|
|
256 ncroot = round(sqrt(nc))
|
|
257 if (ncroot*ncroot < nc) { ncroot = ncroot + 1 }
|
|
258 m = c()
|
|
259 for (i in c(1:nc)) {
|
|
260 rhist = hist(rawrs[,i],breaks=100,plot=F)
|
|
261 m = append(m,max(rhist\$counts))
|
|
262 }
|
|
263 ymax = max(m)
|
|
264 ncols = length(fullnames)
|
|
265 if (ncols > 20)
|
|
266 {
|
|
267 scale = 7*ncols/20
|
|
268 pdf(pdfname,width=scale,height=scale)
|
|
269 } else {
|
|
270 pdf(pdfname)
|
|
271 }
|
|
272 par(mfrow=c(ncroot,ncroot))
|
|
273 for (i in c(1:nc)) {
|
|
274 hist(rawrs[,i], main=paste("Contig logcount",i), xlab='log raw count', col="maroon",
|
|
275 breaks=100,sub=fullnames[i],cex=0.8,ylim=c(0,ymax))
|
|
276 }
|
|
277 dev.off()
|
|
278 par(defpar)
|
|
279
|
|
280 }
|
|
281
|
|
282 cumPlot = function(rawrs,cleanrs,maint,myTitle)
|
|
283 { # updated to use ecdf
|
|
284 pdfname = "Differential_rowsum_bar_charts.pdf"
|
|
285 defpar = par(no.readonly=T)
|
|
286 lrs = log(rawrs,10)
|
|
287 lim = max(lrs)
|
|
288 pdf(pdfname)
|
|
289 par(mfrow=c(2,1))
|
|
290 hist(lrs,breaks=100,main=paste('Before:',maint),xlab="# Reads (log)",
|
|
291 ylab="Count",col="maroon",sub=myTitle, xlim=c(0,lim),las=1)
|
|
292 grid(col="lightgray", lty="dotted")
|
|
293 lrs = log(cleanrs,10)
|
|
294 hist(lrs,breaks=100,main=paste('After:',maint),xlab="# Reads (log)",
|
|
295 ylab="Count",col="maroon",sub=myTitle,xlim=c(0,lim),las=1)
|
|
296 grid(col="lightgray", lty="dotted")
|
|
297 dev.off()
|
|
298 par(defpar)
|
|
299 }
|
|
300
|
|
301 cumPlot1 = function(rawrs,cleanrs,maint,myTitle)
|
|
302 { # updated to use ecdf
|
|
303 pdfname = paste(gsub(" ","", myTitle , fixed=TRUE),"RowsumCum.pdf",sep='_')
|
|
304 pdf(pdfname)
|
|
305 par(mfrow=c(2,1))
|
|
306 lastx = max(rawrs)
|
|
307 rawe = knots(ecdf(rawrs))
|
|
308 cleane = knots(ecdf(cleanrs))
|
|
309 cy = 1:length(cleane)/length(cleane)
|
|
310 ry = 1:length(rawe)/length(rawe)
|
|
311 plot(rawe,ry,type='l',main=paste('Before',maint),xlab="Log Contig Total Reads",
|
|
312 ylab="Cumulative proportion",col="maroon",log='x',xlim=c(1,lastx),sub=myTitle)
|
|
313 grid(col="blue")
|
|
314 plot(cleane,cy,type='l',main=paste('After',maint),xlab="Log Contig Total Reads",
|
|
315 ylab="Cumulative proportion",col="maroon",log='x',xlim=c(1,lastx),sub=myTitle)
|
|
316 grid(col="blue")
|
|
317 dev.off()
|
|
318 }
|
|
319
|
|
320
|
|
321
|
|
322 doGSEAold = function(y=NULL,design=NULL,histgmt="",
|
|
323 bigmt="/data/genomes/gsea/3.1/Abetterchoice_nocgp_c2_c3_c5_symbols_all.gmt",
|
|
324 ntest=0, myTitle="myTitle", outfname="GSEA.xls", minnin=5, maxnin=2000,fdrthresh=0.05,fdrtype="BH")
|
|
325 {
|
|
326 sink('Camera.log')
|
|
327 genesets = c()
|
|
328 if (bigmt > "")
|
|
329 {
|
|
330 bigenesets = readLines(bigmt)
|
|
331 genesets = bigenesets
|
|
332 }
|
|
333 if (histgmt > "")
|
|
334 {
|
|
335 hgenesets = readLines(histgmt)
|
|
336 if (bigmt > "") {
|
|
337 genesets = rbind(genesets,hgenesets)
|
|
338 } else {
|
|
339 genesets = hgenesets
|
|
340 } # use only history if no bi
|
|
341 }
|
|
342 print.noquote(paste("@@@read",length(genesets), 'genesets from',histgmt,bigmt))
|
|
343 genesets = strsplit(genesets,'\t') # tabular. genesetid\tURLorwhatever\tgene_1\t..\tgene_n
|
|
344 outf = outfname
|
|
345 head=paste(myTitle,'edgeR GSEA')
|
|
346 write(head,file=outfname,append=F)
|
|
347 ntest=length(genesets)
|
|
348 urownames = toupper(rownames(y))
|
|
349 upcam = c()
|
|
350 downcam = c()
|
|
351 for (i in 1:ntest) {
|
|
352 gs = unlist(genesets[i])
|
|
353 g = gs[1] # geneset_id
|
|
354 u = gs[2]
|
|
355 if (u > "") { u = paste("<a href=\'",u,"\'>",u,"</a>",sep="") }
|
|
356 glist = gs[3:length(gs)] # member gene symbols
|
|
357 glist = toupper(glist)
|
|
358 inglist = urownames %in% glist
|
|
359 nin = sum(inglist)
|
|
360 if ((nin > minnin) && (nin < maxnin)) {
|
|
361 ### print(paste('@@found',sum(inglist),'genes in glist'))
|
|
362 camres = camera(y=y,index=inglist,design=design)
|
|
363 if (! is.null(camres)) {
|
|
364 rownames(camres) = g # gene set name
|
|
365 camres = cbind(GeneSet=g,URL=u,camres)
|
|
366 if (camres\$Direction == "Up")
|
|
367 {
|
|
368 upcam = rbind(upcam,camres) } else {
|
|
369 downcam = rbind(downcam,camres)
|
|
370 }
|
|
371 }
|
|
372 }
|
|
373 }
|
|
374 uscam = upcam[order(upcam\$PValue),]
|
|
375 unadjp = uscam\$PValue
|
|
376 uscam\$adjPValue = p.adjust(unadjp,method=fdrtype)
|
|
377 nup = max(10,sum((uscam\$adjPValue < fdrthresh)))
|
|
378 dscam = downcam[order(downcam\$PValue),]
|
|
379 unadjp = dscam\$PValue
|
|
380 dscam\$adjPValue = p.adjust(unadjp,method=fdrtype)
|
|
381 ndown = max(10,sum((dscam\$adjPValue < fdrthresh)))
|
|
382 write.table(uscam,file=paste('camera_up',outfname,sep='_'),quote=F,sep='\t',row.names=F)
|
|
383 write.table(dscam,file=paste('camera_down',outfname,sep='_'),quote=F,sep='\t',row.names=F)
|
|
384 print.noquote(paste('@@@@@ Camera up top',nup,'gene sets:'))
|
|
385 write.table(head(uscam,nup),file="",quote=F,sep='\t',row.names=F)
|
|
386 print.noquote(paste('@@@@@ Camera down top',ndown,'gene sets:'))
|
|
387 write.table(head(dscam,ndown),file="",quote=F,sep='\t',row.names=F)
|
|
388 sink()
|
|
389 }
|
|
390
|
|
391
|
|
392
|
|
393
|
|
394 doGSEA = function(y=NULL,design=NULL,histgmt="",
|
|
395 bigmt="/data/genomes/gsea/3.1/Abetterchoice_nocgp_c2_c3_c5_symbols_all.gmt",
|
|
396 ntest=0, myTitle="myTitle", outfname="GSEA.xls", minnin=5, maxnin=2000,fdrthresh=0.05,fdrtype="BH")
|
|
397 {
|
|
398 sink('Camera.log')
|
|
399 genesets = c()
|
|
400 if (bigmt > "")
|
|
401 {
|
|
402 bigenesets = readLines(bigmt)
|
|
403 genesets = bigenesets
|
|
404 }
|
|
405 if (histgmt > "")
|
|
406 {
|
|
407 hgenesets = readLines(histgmt)
|
|
408 if (bigmt > "") {
|
|
409 genesets = rbind(genesets,hgenesets)
|
|
410 } else {
|
|
411 genesets = hgenesets
|
|
412 } # use only history if no bi
|
|
413 }
|
|
414 print.noquote(paste("@@@read",length(genesets), 'genesets from',histgmt,bigmt))
|
|
415 genesets = strsplit(genesets,'\t') # tabular. genesetid\tURLorwhatever\tgene_1\t..\tgene_n
|
|
416 outf = outfname
|
|
417 head=paste(myTitle,'edgeR GSEA')
|
|
418 write(head,file=outfname,append=F)
|
|
419 ntest=length(genesets)
|
|
420 urownames = toupper(rownames(y))
|
|
421 upcam = c()
|
|
422 downcam = c()
|
|
423 incam = c()
|
|
424 urls = c()
|
|
425 gsids = c()
|
|
426 for (i in 1:ntest) {
|
|
427 gs = unlist(genesets[i])
|
|
428 gsid = gs[1] # geneset_id
|
|
429 url = gs[2]
|
|
430 if (url > "") { url = paste("<a href=\'",url,"\'>",url,"</a>",sep="") }
|
|
431 glist = gs[3:length(gs)] # member gene symbols
|
|
432 glist = toupper(glist)
|
|
433 inglist = urownames %in% glist
|
|
434 nin = sum(inglist)
|
|
435 if ((nin > minnin) && (nin < maxnin)) {
|
|
436 incam = c(incam,inglist)
|
|
437 gsids = c(gsids,gsid)
|
|
438 urls = c(urls,url)
|
|
439 }
|
|
440 }
|
|
441 incam = as.list(incam)
|
|
442 names(incam) = gsids
|
|
443 allcam = camera(y=y,index=incam,design=design)
|
|
444 allcamres = cbind(geneset=gsids,allcam,URL=urls)
|
|
445 for (i in 1:ntest) {
|
|
446 camres = allcamres[i]
|
|
447 res = try(test = (camres\$Direction == "Up"))
|
|
448 if ("try-error" %in% class(res)) {
|
|
449 cat("test failed, camres = :")
|
|
450 print.noquote(camres)
|
|
451 } else { if (camres\$Direction == "Up")
|
|
452 { upcam = rbind(upcam,camres)
|
|
453 } else { downcam = rbind(downcam,camres)
|
|
454 }
|
|
455
|
|
456 }
|
|
457 }
|
|
458 uscam = upcam[order(upcam\$PValue),]
|
|
459 unadjp = uscam\$PValue
|
|
460 uscam\$adjPValue = p.adjust(unadjp,method=fdrtype)
|
|
461 nup = max(10,sum((uscam\$adjPValue < fdrthresh)))
|
|
462 dscam = downcam[order(downcam\$PValue),]
|
|
463 unadjp = dscam\$PValue
|
|
464 dscam\$adjPValue = p.adjust(unadjp,method=fdrtype)
|
|
465 ndown = max(10,sum((dscam\$adjPValue < fdrthresh)))
|
|
466 write.table(uscam,file=paste('camera_up',outfname,sep='_'),quote=F,sep='\t',row.names=F)
|
|
467 write.table(dscam,file=paste('camera_down',outfname,sep='_'),quote=F,sep='\t',row.names=F)
|
|
468 print.noquote(paste('@@@@@ Camera up top',nup,'gene sets:'))
|
|
469 write.table(head(uscam,nup),file="",quote=F,sep='\t',row.names=F)
|
|
470 print.noquote(paste('@@@@@ Camera down top',ndown,'gene sets:'))
|
|
471 write.table(head(dscam,ndown),file="",quote=F,sep='\t',row.names=F)
|
|
472 sink()
|
|
473 }
|
|
474
|
|
475
|
|
476 edgeIt = function (Count_Matrix=c(),group=c(),out_edgeR=F,out_Voom=F,out_DESeq2=F,fdrtype='fdr',priordf=5,
|
|
477 fdrthresh=0.05,outputdir='.', myTitle='Differential Counts',libSize=c(),useNDF=F,
|
|
478 filterquantile=0.2, subjects=c(),TreatmentName="Rx",ControlName="Ctrl",mydesign=NULL,
|
|
479 doDESeq2=T,doVoom=T,doCamera=T,doedgeR=T,org='hg19',
|
|
480 histgmt="", bigmt="/data/genomes/gsea/3.1/Abetterchoice_nocgp_c2_c3_c5_symbols_all.gmt",
|
|
481 doCook=F,DESeq_fitType="parameteric",robust_meth='ordinary')
|
|
482 {
|
|
483
|
|
484 logf = file('Differential.log', open = "a")
|
|
485 sink(logf,type = c("output", "message"))
|
|
486
|
|
487
|
|
488 run_edgeR = function(workCM,pdata,subjects,group,priordf,robust_meth,mydesign,mt,cmrowsums,out_edgeR,nonzerod)
|
|
489 {
|
|
490 logf = file('edgeR.log', open = "a")
|
|
491 sink(logf,type = c("output", "message"))
|
|
492 #### Setup myDGEList object
|
|
493 myDGEList = DGEList(counts=workCM, group = group)
|
|
494 myDGEList = calcNormFactors(myDGEList)
|
|
495 if (robust_meth == 'ordinary') {
|
|
496 myDGEList = estimateGLMCommonDisp(myDGEList,mydesign)
|
|
497 myDGEList = estimateGLMTrendedDisp(myDGEList,mydesign)
|
|
498 if (priordf > 0) { myDGEList = estimateGLMTagwiseDisp(myDGEList,mydesign,prior.df = priordf)
|
|
499 } else { myDGEList = estimateGLMTagwiseDisp(myDGEList,mydesign) }
|
|
500 comdisp = myDGEList\$common.dispersion
|
|
501 estpriorn = getPriorN(myDGEList)
|
|
502 print(paste("Common Dispersion =",comdisp,"CV = ",sqrt(comdisp),"getPriorN = ",estpriorn),quote=F)
|
|
503 } else {
|
|
504 myDGEList = estimateGLMRobustDisp(myDGEList,design=mydesign, prior.df = priordf, maxit = 6, residual.type = robust_meth)
|
|
505 }
|
|
506
|
|
507
|
|
508 DGLM = glmFit(myDGEList,design=mydesign)
|
|
509 DE = glmLRT(DGLM,coef=ncol(DGLM\$design)) # always last one - subject is first if needed
|
|
510 normData = cpm(myDGEList)
|
|
511 uoutput = cbind(
|
|
512 Name=as.character(rownames(myDGEList\$counts)),
|
|
513 DE\$table,
|
|
514 adj.p.value=p.adjust(DE\$table\$PValue, method=fdrtype),
|
|
515 Dispersion=myDGEList\$tagwise.dispersion,totreads=cmrowsums,normData,
|
|
516 myDGEList\$counts
|
|
517 )
|
|
518 soutput = uoutput[order(DE\$table\$PValue),] # sorted into p value order - for quick toptable
|
|
519 goodness = gof(DGLM, pcutoff=fdrthresh)
|
|
520 if (sum(goodness\$outlier) > 0) {
|
|
521 print.noquote('GLM outliers:')
|
|
522 print(paste(rownames(DGLM)[(goodness\$outlier)],collapse=','),quote=F)
|
|
523 } else {
|
|
524 print('No GLM fit outlier genes found\n')
|
|
525 }
|
|
526 z = limma::zscoreGamma(goodness\$gof.statistic, shape=goodness\$df/2, scale=2)
|
|
527 pdf(paste("edgeR",mt,"GoodnessofFit.pdf",sep='_'))
|
|
528 qq = qqnorm(z, panel.first=grid(), main="tagwise dispersion")
|
|
529 abline(0,1,lwd=3)
|
|
530 points(qq\$x[goodness\$outlier],qq\$y[goodness\$outlier], pch=16, col="maroon")
|
|
531 dev.off()
|
|
532 uniqueg = unique(group)
|
|
533 write.table(soutput,file=out_edgeR, quote=FALSE, sep="\t",row.names=F)
|
|
534 tt = cbind(
|
|
535 Name=as.character(rownames(myDGEList)),
|
|
536 DE\$table,
|
|
537 adj.p.value=p.adjust(DE\$table\$PValue, method=fdrtype),
|
|
538 Dispersion=myDGEList\$tagwise.dispersion,totreads=cmrowsums
|
|
539 )
|
|
540 tt = cbind(tt,URL=contigurls) # add to end so table isn't laid out strangely
|
|
541 stt = tt[order(DE\$table\$PValue),]
|
|
542 print.noquote("@@ edgeR Top tags\n")
|
|
543 print.noquote(stt[1:50,])
|
|
544 deTags = rownames(uoutput[uoutput\$adj.p.value < fdrthresh,])
|
|
545 nsig = length(deTags)
|
|
546 print.noquote(paste('@@',nsig,'tags significant at adj p=',fdrthresh))
|
|
547 deColours = ifelse(deTags,'red','black')
|
|
548 pdf(paste("edgeR",mt,"BCV_vs_abundance.pdf",sep="_"))
|
|
549 plotBCV(myDGEList, cex=0.3, main="Biological CV vs abundance")
|
|
550 dev.off()
|
|
551 dg = myDGEList[order(DE\$table\$PValue),]
|
|
552 outpdfname= paste("edgeR",mt,"top_100_heatmap.pdf",sep="_")
|
|
553 ocpm = normData[order(DE\$table\$PValue),]
|
|
554 ocpm = ocpm[c(1:100),]
|
|
555 hmap2(ocpm,TName=TName,group=group,outpdfname=outpdfname,myTitle=paste(myTitle,'Heatmap'))
|
|
556 outSmear = paste("edgeR",mt,"smearplot.pdf",sep="_")
|
|
557 outMain = paste("Smear Plot for ",TName,' Vs ',CName,' (FDR@',fdrthresh,' N = ',nsig,')',sep='')
|
|
558 smearPlot(myDGEList=myDGEList,deTags=deTags, outSmear=outSmear, outMain = outMain)
|
|
559 qqPlot(descr=paste(myTitle,'edgeR adj p QQ plot'),pvector=tt\$adj.p.value,outpdf=paste('edgeR',mt,'qqplot.pdf',sep='_'))
|
|
560 topresults.edgeR = soutput[which(soutput\$adj.p.value < fdrthresh), ]
|
|
561 edgeRcountsindex = which(allgenes %in% rownames(topresults.edgeR))
|
|
562 edgeRcounts = rep(0, length(allgenes))
|
|
563 edgeRcounts[edgeRcountsindex] = 1 # Create venn diagram of hits
|
|
564 sink()
|
|
565 return(list(myDGEList=myDGEList,edgeRcounts=edgeRcounts))
|
|
566 } ### run_edgeR
|
|
567
|
|
568
|
|
569 run_DESeq2 = function(workCM,pdata,subjects,group,out_DESeq2,mt,DESeq_fitType)
|
|
570
|
|
571 {
|
|
572 logf = file("DESeq2.log", open = "a")
|
|
573 sink(logf,type = c("output", "message"))
|
|
574 # DESeq2
|
|
575 require('DESeq2')
|
|
576 library('RColorBrewer')
|
|
577 if (length(subjects) == 0)
|
|
578 {
|
|
579 pdata = data.frame(Name=colnames(workCM),Rx=group,row.names=colnames(workCM))
|
|
580 deSEQds = DESeqDataSetFromMatrix(countData = workCM, colData = pdata, design = formula(~ Rx))
|
|
581 } else {
|
|
582 pdata = data.frame(Name=colnames(workCM),Rx=group,subjects=subjects,row.names=colnames(workCM))
|
|
583 deSEQds = DESeqDataSetFromMatrix(countData = workCM, colData = pdata, design = formula(~ subjects + Rx))
|
|
584 }
|
|
585 deSeqDatsizefac = estimateSizeFactors(deSEQds)
|
|
586 deSeqDatdisp = estimateDispersions(deSeqDatsizefac,fitType=DESeq_fitType)
|
|
587 resDESeq = nbinomWaldTest(deSeqDatdisp)
|
|
588 rDESeq = as.data.frame(results(resDESeq))
|
|
589 rDESeq = cbind(Contig=rownames(workCM),rDESeq,NReads=cmrowsums,URL=contigurls)
|
|
590 srDESeq = rDESeq[order(rDESeq\$pvalue),]
|
|
591 qqPlot(descr=paste(myTitle,'DESeq2 adj p qq plot'),pvector=rDESeq\$padj,outpdf=paste('DESeq2',mt,'qqplot.pdf',sep="_"))
|
|
592 cat("# DESeq top 50\n")
|
|
593 print.noquote(srDESeq[1:50,])
|
|
594 write.table(srDESeq,file=out_DESeq2, quote=FALSE, sep="\t",row.names=F)
|
|
595 topresults.DESeq = rDESeq[which(rDESeq\$padj < fdrthresh), ]
|
|
596 DESeqcountsindex = which(allgenes %in% rownames(topresults.DESeq))
|
|
597 DESeqcounts = rep(0, length(allgenes))
|
|
598 DESeqcounts[DESeqcountsindex] = 1
|
|
599 pdf(paste("DESeq2",mt,"dispersion_estimates.pdf",sep='_'))
|
|
600 plotDispEsts(resDESeq)
|
|
601 dev.off()
|
|
602 ysmall = abs(min(rDESeq\$log2FoldChange))
|
|
603 ybig = abs(max(rDESeq\$log2FoldChange))
|
|
604 ylimit = min(4,ysmall,ybig)
|
|
605 pdf(paste("DESeq2",mt,"MA_plot.pdf",sep="_"))
|
|
606 plotMA(resDESeq,main=paste(myTitle,"DESeq2 MA plot"),ylim=c(-ylimit,ylimit))
|
|
607 dev.off()
|
|
608 rlogres = rlogTransformation(resDESeq)
|
|
609 sampledists = dist( t( assay(rlogres) ) )
|
|
610 sdmat = as.matrix(sampledists)
|
|
611 pdf(paste("DESeq2",mt,"sample_distance_plot.pdf",sep="_"))
|
|
612 heatmap.2(sdmat,trace="none",main=paste(myTitle,"DESeq2 sample distances"),
|
|
613 col = colorRampPalette( rev(brewer.pal(9, "RdBu")) )(255))
|
|
614 dev.off()
|
|
615 result = try( (ppca = plotPCA( varianceStabilizingTransformation(deSeqDatdisp,blind=T), intgroup=c("Rx","Name")) ) )
|
|
616 if ("try-error" %in% class(result)) {
|
|
617 print.noquote('DESeq2 plotPCA failed.')
|
|
618 } else {
|
|
619 pdf(paste("DESeq2",mt,"PCA_plot.pdf",sep="_"))
|
|
620 #### wtf - print? Seems needed to get this to work
|
|
621 print(ppca)
|
|
622 dev.off()
|
|
623 }
|
|
624 sink()
|
|
625 return(DESeqcounts)
|
|
626 }
|
|
627
|
|
628
|
|
629 run_Voom = function(workCM,pdata,subjects,group,mydesign,mt,out_Voom)
|
|
630 {
|
|
631 logf = file('VOOM.log', open = "a")
|
|
632 sink(logf,type = c("output", "message"))
|
|
633 if (doedgeR == F) {
|
|
634 #### Setup myDGEList object
|
|
635 myDGEList = DGEList(counts=workCM, group = group)
|
|
636 myDGEList = calcNormFactors(myDGEList)
|
|
637 myDGEList = estimateGLMCommonDisp(myDGEList,mydesign)
|
|
638 myDGEList = estimateGLMTrendedDisp(myDGEList,mydesign)
|
|
639 myDGEList = estimateGLMTagwiseDisp(myDGEList,mydesign)
|
|
640 }
|
|
641 pdf(paste("VOOM",mt,"mean_variance_plot.pdf",sep='_'))
|
|
642 dat.voomed <- voom(myDGEList, mydesign, plot = TRUE, normalize.method="quantil", lib.size = NULL)
|
|
643 dev.off()
|
|
644 # Use limma to fit data
|
|
645 fit = lmFit(dat.voomed, mydesign)
|
|
646 fit = eBayes(fit)
|
|
647 rvoom = topTable(fit, coef = length(colnames(mydesign)), adj = fdrtype, n = Inf, sort="none")
|
|
648 qqPlot(descr=paste(myTitle,'VOOM-limma adj p QQ plot'),pvector=rvoom\$adj.P.Val,outpdf=paste('VOOM',mt,'qqplot.pdf',sep='_'))
|
|
649 rownames(rvoom) = rownames(workCM)
|
|
650 rvoom = cbind(Contig=rownames(workCM),rvoom,NReads=cmrowsums,URL=contigurls)
|
|
651 srvoom = rvoom[order(rvoom\$P.Value),]
|
|
652 cat("# VOOM top 50\n")
|
|
653 print(srvoom[1:50,])
|
|
654 write.table(srvoom,file=out_Voom, quote=FALSE, sep="\t",row.names=F)
|
|
655 # Use an FDR cutoff to find interesting samples for edgeR, DESeq and voom/limma
|
|
656 topresults.voom = rvoom[which(rvoom\$adj.P.Val < fdrthresh), ]
|
|
657 voomcountsindex <- which(allgenes %in% rownames(topresults.voom))
|
|
658 voomcounts = rep(0, length(allgenes))
|
|
659 voomcounts[voomcountsindex] = 1
|
|
660 sink()
|
|
661 return(voomcounts)
|
|
662 }
|
|
663
|
|
664
|
|
665 #### data cleaning and analsis control starts here
|
|
666
|
|
667
|
|
668 # Error handling
|
|
669 nugroup = length(unique(group))
|
|
670 if (nugroup!=2){
|
|
671 print("Number of conditions identified in experiment does not equal 2")
|
|
672 q()
|
|
673 }
|
|
674 require(edgeR)
|
|
675 options(width = 512)
|
|
676 mt = paste(unlist(strsplit(myTitle,'_')),collapse=" ")
|
|
677 allN = nrow(Count_Matrix)
|
|
678 nscut = round(ncol(Count_Matrix)/2) # half samples
|
|
679 colTotmillionreads = colSums(Count_Matrix)/1e6
|
|
680 counts.dataframe = as.data.frame(c())
|
|
681 rawrs = rowSums(Count_Matrix)
|
|
682 nonzerod = Count_Matrix[(rawrs > 0),] # remove all zero count genes
|
|
683 nzN = nrow(nonzerod)
|
|
684 nzrs = rowSums(nonzerod)
|
|
685 zN = allN - nzN
|
|
686 print('@@@ Quantiles for non-zero row counts:',quote=F)
|
|
687 print(quantile(nzrs,probs=seq(0,1,0.1)),quote=F)
|
|
688 if (useNDF == T)
|
|
689 {
|
|
690 gt1rpin3 = rowSums(Count_Matrix/expandAsMatrix(colTotmillionreads,dim(Count_Matrix)) >= 1) >= nscut
|
|
691 lo = colSums(Count_Matrix[!gt1rpin3,])
|
|
692 workCM = Count_Matrix[gt1rpin3,]
|
|
693 cleanrs = rowSums(workCM)
|
|
694 cleanN = length(cleanrs)
|
|
695 meth = paste( "After removing",length(lo),"contigs with fewer than ",nscut," sample read counts >= 1 per million, there are",sep="")
|
|
696 print(paste("Read",allN,"contigs. Removed",zN,"contigs with no reads.",meth,cleanN,"contigs"),quote=F)
|
|
697 maint = paste('Filter >=1/million reads in >=',nscut,'samples')
|
|
698 } else {
|
|
699 useme = (nzrs > quantile(nzrs,filterquantile))
|
|
700 workCM = nonzerod[useme,]
|
|
701 lo = colSums(nonzerod[!useme,])
|
|
702 cleanrs = rowSums(workCM)
|
|
703 cleanN = length(cleanrs)
|
|
704 meth = paste("After filtering at count quantile =",filterquantile,", there are",sep="")
|
|
705 print(paste('Read',allN,"contigs. Removed",zN,"with no reads.",meth,cleanN,"contigs"),quote=F)
|
|
706 maint = paste('Filter below',filterquantile,'quantile')
|
|
707 }
|
|
708 cumPlot(rawrs=rawrs,cleanrs=cleanrs,maint=maint,myTitle=myTitle)
|
|
709 allgenes = rownames(workCM)
|
|
710 reg = "^chr([0-9]+):([0-9]+)-([0-9]+)" # ucsc chr:start-end regexp
|
|
711 genecards="<a href=\'http://www.genecards.org/index.php?path=/Search/keyword/"
|
|
712 ucsc = paste("<a href=\'http://genome.ucsc.edu/cgi-bin/hgTracks?db=",org,sep='')
|
|
713 testreg = str_match(allgenes,reg)
|
|
714 if (sum(!is.na(testreg[,1]))/length(testreg[,1]) > 0.8) # is ucsc style string
|
|
715 {
|
|
716 print("@@ using ucsc substitution for urls")
|
|
717 contigurls = paste0(ucsc,"&position=chr",testreg[,2],":",testreg[,3],"-",testreg[,4],"\'>",allgenes,"</a>")
|
|
718 } else {
|
|
719 print("@@ using genecards substitution for urls")
|
|
720 contigurls = paste0(genecards,allgenes,"\'>",allgenes,"</a>")
|
|
721 }
|
|
722 print.noquote(paste("@@ Total low count contigs per sample = ",paste(table(lo),collapse=',')))
|
|
723 cmrowsums = rowSums(workCM)
|
|
724 TName=unique(group)[1]
|
|
725 CName=unique(group)[2]
|
|
726 if (is.null(mydesign)) {
|
|
727 if (length(subjects) == 0)
|
|
728 {
|
|
729 mydesign = model.matrix(~group)
|
|
730 }
|
|
731 else {
|
|
732 subjf = factor(subjects)
|
|
733 mydesign = model.matrix(~subjf+group) # we block on subject so make group last to simplify finding it
|
|
734 }
|
|
735 }
|
|
736 print.noquote(paste('Using samples:',paste(colnames(workCM),collapse=',')))
|
|
737 print.noquote('Using design matrix:')
|
|
738 print.noquote(mydesign)
|
|
739 normData = cpm(workCM)*1e6
|
|
740 colnames(normData) = paste( colnames(workCM),'N',sep="_")
|
|
741 print(paste('Raw sample read totals',paste(colSums(nonzerod,na.rm=T),collapse=',')))
|
|
742
|
|
743 if (doedgeR == T) {
|
|
744 eres = run_edgeR(workCM,pdata,subjects,group,priordf,robust_meth,mydesign,mt,cmrowsums,out_edgeR,nonzerod)
|
|
745 myDGEList = eres\$myDGEList
|
|
746 edgeRcounts = eres\$edgeRcounts
|
|
747 #### Plot MDS
|
|
748 sample_colors = match(group,levels(group))
|
|
749 sampleTypes = levels(factor(group))
|
|
750 print.noquote(sampleTypes)
|
|
751 pdf(paste("edgeR",mt,"MDSplot.pdf",sep='_'))
|
|
752 plotMDS.DGEList(myDGEList,main=paste("MDS for",myTitle),cex=0.5,col=sample_colors,pch=sample_colors)
|
|
753 legend(x="topleft", legend = sampleTypes,col=c(1:length(sampleTypes)), pch=19)
|
|
754 grid(col="blue")
|
|
755 dev.off()
|
|
756 scale <- myDGEList\$samples\$lib.size*myDGEList\$samples\$norm.factors
|
|
757 normCounts <- round(t(t(myDGEList\$counts)/scale)*mean(scale))
|
|
758 try({boxPlot(rawrs=nzd,cleanrs=log2(normCounts+1),maint='Effects of TMM size normalisation',myTitle=myTitle,pdfname=paste("edgeR",mt,"raw_norm_counts_box.pdf",sep='_'))},T)
|
|
759 }
|
|
760 if (doDESeq2 == T) { DESeqcounts = run_DESeq2(workCM,pdata,subjects,group,out_DESeq2,mt,DESeq_fitType) }
|
|
761 if (doVoom == T) { voomcounts = run_Voom(workCM,pdata,subjects,group,mydesign,mt,out_Voom) }
|
|
762
|
|
763
|
|
764 if (doCamera) {
|
|
765 doGSEA(y=myDGEList,design=mydesign,histgmt=histgmt,bigmt=bigmt,ntest=20,myTitle=myTitle,
|
|
766 outfname=paste("GSEA_Camera",mt,"table.xls",sep="_"),fdrthresh=fdrthresh,fdrtype=fdrtype)
|
|
767 }
|
|
768 counts.dataframe = c()
|
|
769 vennmain = 'no venn'
|
|
770 if ((doDESeq2==T) || (doVoom==T) || (doedgeR==T)) {
|
|
771 if ((doVoom==T) && (doDESeq2==T) && (doedgeR==T)) {
|
|
772 vennmain = paste(mt,'Voom,edgeR and DESeq2 overlap at FDR=',fdrthresh)
|
|
773 counts.dataframe = data.frame(edgeR = edgeRcounts, DESeq2 = DESeqcounts,
|
|
774 VOOM_limma = voomcounts, row.names = allgenes)
|
|
775 } else if ((doDESeq2==T) && (doedgeR==T)) {
|
|
776 vennmain = paste(mt,'DESeq2 and edgeR overlap at FDR=',fdrthresh)
|
|
777 counts.dataframe = data.frame(edgeR = edgeRcounts, DESeq2 = DESeqcounts, row.names = allgenes)
|
|
778 } else if ((doVoom==T) && (doedgeR==T)) {
|
|
779 vennmain = paste(mt,'Voom and edgeR overlap at FDR=',fdrthresh)
|
|
780 counts.dataframe = data.frame(edgeR = edgeRcounts, VOOM_limma = voomcounts, row.names = allgenes)
|
|
781 }
|
|
782
|
|
783 if (nrow(counts.dataframe > 1)) {
|
|
784 counts.venn = vennCounts(counts.dataframe)
|
|
785 vennf = paste("Differential_venn",mt,"significant_genes_overlap.pdf",sep="_")
|
|
786 pdf(vennf)
|
|
787 vennDiagram(counts.venn,main=vennmain,col="maroon")
|
|
788 dev.off()
|
|
789 }
|
|
790 } #### doDESeq2 or doVoom
|
|
791 sink()
|
|
792 }
|
|
793 #### Done
|
|
794 ]]>
|
|
795 builtin_gmt = ""
|
|
796 history_gmt = ""
|
|
797 history_gmt_name = ""
|
|
798 out_edgeR = F
|
|
799 out_DESeq2 = F
|
|
800 out_Voom = "$out_VOOM"
|
|
801 edgeR_robust_meth = "ordinary"
|
|
802 doDESeq2 = $DESeq2.doDESeq2
|
|
803 doVoom = $doVoom
|
|
804 doCamera = F
|
|
805 doedgeR = $edgeR.doedgeR
|
|
806 edgeR_priordf = 10
|
|
807
|
|
808
|
|
809 #if $doVoom == "T":
|
|
810 out_Voom = "$out_VOOM"
|
|
811 #end if
|
|
812
|
|
813 #if $DESeq2.doDESeq2 == "T":
|
|
814 out_DESeq2 = "$out_DESeq2"
|
|
815 doDESeq2 = T
|
|
816 DESeq_fitType = "$DESeq2.DESeq_fitType"
|
|
817 #end if
|
|
818
|
|
819 #if $edgeR.doedgeR == "T":
|
|
820 out_edgeR = "$out_edgeR"
|
|
821 edgeR_priordf = $edgeR.edgeR_priordf
|
|
822 edgeR_robust_meth = "$edgeR.edgeR_robust_method"
|
|
823 #end if
|
|
824
|
|
825
|
|
826 if (sum(c(doedgeR,doVoom,doDESeq2)) == 0)
|
|
827 {
|
|
828 write("No methods chosen - nothing to do! Please try again after choosing one or more methods", stderr())
|
|
829 quit(save="no",status=2)
|
|
830 }
|
|
831
|
|
832 Out_Dir = "$html_file.files_path"
|
|
833 Input = "$input1"
|
|
834 TreatmentName = "$treatment_name"
|
|
835 TreatmentCols = "$Treat_cols"
|
|
836 ControlName = "$control_name"
|
|
837 ControlCols= "$Control_cols"
|
|
838 org = "$input1.dbkey"
|
|
839 if (org == "") { org = "hg19"}
|
|
840 fdrtype = "$fdrtype"
|
|
841 fdrthresh = $fdrthresh
|
|
842 useNDF = $useNDF
|
|
843 fQ = $fQ # non-differential centile cutoff
|
|
844 myTitle = "$title"
|
|
845 sids = strsplit("$subjectids",',')
|
|
846 subjects = unlist(sids)
|
|
847 nsubj = length(subjects)
|
|
848 TCols = as.numeric(strsplit(TreatmentCols,",")[[1]])-1
|
|
849 CCols = as.numeric(strsplit(ControlCols,",")[[1]])-1
|
|
850 cat('Got TCols=')
|
|
851 cat(TCols)
|
|
852 cat('; CCols=')
|
|
853 cat(CCols)
|
|
854 cat('\n')
|
|
855 <![CDATA[
|
|
856 useCols = c(TCols,CCols)
|
|
857 if (file.exists(Out_Dir) == F) dir.create(Out_Dir)
|
|
858 Count_Matrix = read.table(Input,header=T,row.names=1,sep='\t')
|
|
859 snames = colnames(Count_Matrix)
|
|
860 nsamples = length(snames)
|
|
861 if (nsubj > 0 & nsubj != nsamples) {
|
|
862 options("show.error.messages"=T)
|
|
863 mess = paste('Fatal error: Supplied subject id list',paste(subjects,collapse=','),
|
|
864 'has length',nsubj,'but there are',nsamples,'samples',paste(snames,collapse=','))
|
|
865 write(mess, stderr())
|
|
866 quit(save="no",status=4)
|
|
867 }
|
|
868 if (length(subjects) != 0) {subjects = subjects[useCols]}
|
|
869 Count_Matrix = Count_Matrix[,useCols] ### reorder columns
|
|
870 rn = rownames(Count_Matrix)
|
|
871 islib = rn %in% c('librarySize','NotInBedRegions')
|
|
872 LibSizes = Count_Matrix[subset(rn,islib),][1] # take first
|
|
873 Count_Matrix = Count_Matrix[subset(rn,! islib),]
|
|
874 group = c(rep(TreatmentName,length(TCols)), rep(ControlName,length(CCols)) )
|
|
875 group = factor(group, levels=c(ControlName,TreatmentName))
|
|
876 colnames(Count_Matrix) = paste(group,colnames(Count_Matrix),sep="_")
|
|
877 results = edgeIt(Count_Matrix=Count_Matrix,group=group, out_edgeR=out_edgeR, out_Voom=out_Voom, out_DESeq2=out_DESeq2,
|
|
878 fdrtype='BH',mydesign=NULL,priordf=edgeR_priordf,fdrthresh=fdrthresh,outputdir='.',
|
|
879 myTitle=myTitle,useNDF=F,libSize=c(),filterquantile=fQ,subjects=subjects,TreatmentName=TreatmentName,ControlName=ControlName,
|
|
880 doDESeq2=doDESeq2,doVoom=doVoom,doCamera=doCamera,doedgeR=doedgeR,org=org,
|
|
881 histgmt=history_gmt,bigmt=builtin_gmt,DESeq_fitType=DESeq_fitType,robust_meth=edgeR_robust_meth)
|
|
882 sessionInfo()
|
|
883
|
|
884 sink()
|
|
885 ]]>
|
|
886 </configfile>
|
|
887 </configfiles>
|
|
888 <help>
|
|
889
|
|
890 **What it does**
|
|
891
|
|
892 Allows short read sequence counts from controlled experiments to be analysed for differentially expressed genes.
|
|
893 Optionally adds a term for subject if not all samples are independent or if some other factor needs to be blocked in the design.
|
|
894
|
|
895 **Input**
|
|
896
|
|
897 Requires a count matrix as a tabular file. These are best made using the companion HTSeq_ based counter Galaxy wrapper
|
|
898 and your fave gene model to generate inputs. Each row is a genomic feature (gene or exon eg) and each column the
|
|
899 non-negative integer count of reads from one sample overlapping the feature.
|
|
900
|
|
901 The matrix must have a header row uniquely identifying the source samples, and unique row names in
|
|
902 the first column. Typically the row names are gene symbols or probe ids for downstream use in GSEA and other methods.
|
|
903 They must be unique and R names or they will be mangled - please read the fine R docs for the rules on identifiers.
|
|
904
|
|
905 **Specifying comparisons**
|
|
906
|
|
907 This is basically dumbed down for two factors - case vs control.
|
|
908
|
|
909 More complex interfaces are possible but painful at present.
|
|
910 Probably need to specify a phenotype file to do this better.
|
|
911 Work in progress. Send code.
|
|
912
|
|
913 If you have (eg) paired samples and wish to include a term in the GLM to account for some other factor (subject in the case of paired samples),
|
|
914 put a comma separated list of indicators for every sample (whether modelled or not!) indicating (eg) the subject number or
|
|
915 A list of integers, one for each subject or an empty string if samples are all independent.
|
|
916 If not empty, there must be exactly as many integers in the supplied integer list as there are columns (samples) in the count matrix.
|
|
917 Integers for samples that are not in the analysis *must* be present in the string as filler even if not used.
|
|
918
|
|
919 So if you have 2 pairs out of 6 samples, you need to put in unique integers for the unpaired ones
|
|
920 eg if you had 6 samples with the first two independent but the second and third pairs each being from independent subjects. you might use
|
|
921 8,9,1,1,2,2
|
|
922 as subject IDs to indicate two paired samples from the same subject in columns 3/4 and 5/6
|
|
923
|
|
924 **Methods available**
|
|
925
|
|
926 You can run 3 popular Bioconductor packages available for count data.
|
|
927
|
|
928 edgeR - see edgeR_ for details
|
|
929
|
|
930 VOOM/limma - see limma_VOOM_ for details
|
|
931
|
|
932 DESeq2 - see DESeq2_ for details
|
|
933
|
|
934 and optionally camera in edgeR which works better if MSigDB is installed.
|
|
935
|
|
936 **Outputs**
|
|
937
|
|
938 Some helpful plots and analysis results. Note that most of these are produced using R code
|
|
939 suggested by the excellent documentation and vignettes for the Bioconductor
|
|
940 packages invoked. The Tool Factory is used to automatically lay these out for you to enjoy.
|
|
941
|
|
942 **Note on Voom**
|
|
943
|
|
944 The voom from limma version 3.16.6 help in R includes this from the authors - but you should read the paper to interpret this method.
|
|
945
|
|
946 This function is intended to process RNA-Seq or ChIP-Seq data prior to linear modelling in limma.
|
|
947
|
|
948 voom is an acronym for mean-variance modelling at the observational level.
|
|
949 The key concern is to estimate the mean-variance relationship in the data, then use this to compute appropriate weights for each observation.
|
|
950 Count data almost show non-trivial mean-variance relationships. Raw counts show increasing variance with increasing count size, while log-counts typically show a decreasing mean-variance trend.
|
|
951 This function estimates the mean-variance trend for log-counts, then assigns a weight to each observation based on its predicted variance.
|
|
952 The weights are then used in the linear modelling process to adjust for heteroscedasticity.
|
|
953
|
|
954 In an experiment, a count value is observed for each tag in each sample. A tag-wise mean-variance trend is computed using lowess.
|
|
955 The tag-wise mean is the mean log2 count with an offset of 0.5, across samples for a given tag.
|
|
956 The tag-wise variance is the quarter-root-variance of normalized log2 counts per million values with an offset of 0.5, across samples for a given tag.
|
|
957 Tags with zero counts across all samples are not included in the lowess fit. Optional normalization is performed using normalizeBetweenArrays.
|
|
958 Using fitted values of log2 counts from a linear model fit by lmFit, variances from the mean-variance trend were interpolated for each observation.
|
|
959 This was carried out by approxfun. Inverse variance weights can be used to correct for mean-variance trend in the count data.
|
|
960
|
|
961
|
|
962 Author(s)
|
|
963
|
|
964 Charity Law and Gordon Smyth
|
|
965
|
|
966 References
|
|
967
|
|
968 Law, CW (2013). Precision weights for gene expression analysis. PhD Thesis. University of Melbourne, Australia.
|
|
969
|
|
970 Law, CW, Chen, Y, Shi, W, Smyth, GK (2013). Voom! Precision weights unlock linear model analysis tools for RNA-seq read counts.
|
|
971 Technical Report 1 May 2013, Bioinformatics Division, Walter and Eliza Hall Institute of Medical Reseach, Melbourne, Australia.
|
|
972 http://www.statsci.org/smyth/pubs/VoomPreprint.pdf
|
|
973
|
|
974 See Also
|
|
975
|
|
976 A voom case study is given in the edgeR User's Guide.
|
|
977
|
|
978 vooma is a similar function but for microarrays instead of RNA-seq.
|
|
979
|
|
980
|
|
981 ***old rant on changes to Bioconductor package variable names between versions***
|
|
982
|
|
983 The edgeR authors made a small cosmetic change in the name of one important variable (from p.value to PValue)
|
|
984 breaking this and all other code that assumed the old name for this variable,
|
|
985 between edgeR2.4.4 and 2.4.6 (the version for R 2.14 as at the time of writing).
|
|
986 This means that all code using edgeR is sensitive to the version. I think this was a very unwise thing
|
|
987 to do because it wasted hours of my time to track down and will similarly cost other edgeR users dearly
|
|
988 when their old scripts break. This tool currently now works with 2.4.6.
|
|
989
|
|
990 **Note on prior.N**
|
|
991
|
|
992 http://seqanswers.com/forums/showthread.php?t=5591 says:
|
|
993
|
|
994 *prior.n*
|
|
995
|
|
996 The value for prior.n determines the amount of smoothing of tagwise dispersions towards the common dispersion.
|
|
997 You can think of it as like a "weight" for the common value. (It is actually the weight for the common likelihood
|
|
998 in the weighted likelihood equation). The larger the value for prior.n, the more smoothing, i.e. the closer your
|
|
999 tagwise dispersion estimates will be to the common dispersion. If you use a prior.n of 1, then that gives the
|
|
1000 common likelihood the weight of one observation.
|
|
1001
|
|
1002 In answer to your question, it is a good thing to squeeze the tagwise dispersions towards a common value,
|
|
1003 or else you will be using very unreliable estimates of the dispersion. I would not recommend using the value that
|
|
1004 you obtained from estimateSmoothing()---this is far too small and would result in virtually no moderation
|
|
1005 (squeezing) of the tagwise dispersions. How many samples do you have in your experiment?
|
|
1006 What is the experimental design? If you have few samples (less than 6) then I would suggest a prior.n of at least 10.
|
|
1007 If you have more samples, then the tagwise dispersion estimates will be more reliable,
|
|
1008 so you could consider using a smaller prior.n, although I would hesitate to use a prior.n less than 5.
|
|
1009
|
|
1010
|
|
1011 From Bioconductor Digest, Vol 118, Issue 5, Gordon writes:
|
|
1012
|
|
1013 Dear Dorota,
|
|
1014
|
|
1015 The important settings are prior.df and trend.
|
|
1016
|
|
1017 prior.n and prior.df are related through prior.df = prior.n * residual.df,
|
|
1018 and your experiment has residual.df = 36 - 12 = 24. So the old setting of
|
|
1019 prior.n=10 is equivalent for your data to prior.df = 240, a very large
|
|
1020 value. Going the other way, the new setting of prior.df=10 is equivalent
|
|
1021 to prior.n=10/24.
|
|
1022
|
|
1023 To recover old results with the current software you would use
|
|
1024
|
|
1025 estimateTagwiseDisp(object, prior.df=240, trend="none")
|
|
1026
|
|
1027 To get the new default from old software you would use
|
|
1028
|
|
1029 estimateTagwiseDisp(object, prior.n=10/24, trend=TRUE)
|
|
1030
|
|
1031 Actually the old trend method is equivalent to trend="loess" in the new
|
|
1032 software. You should use plotBCV(object) to see whether a trend is
|
|
1033 required.
|
|
1034
|
|
1035 Note you could also use
|
|
1036
|
|
1037 prior.n = getPriorN(object, prior.df=10)
|
|
1038
|
|
1039 to map between prior.df and prior.n.
|
|
1040
|
|
1041 ----
|
|
1042
|
|
1043 **Attributions**
|
|
1044
|
|
1045 edgeR - edgeR_
|
|
1046
|
|
1047 VOOM/limma - limma_VOOM_
|
|
1048
|
|
1049 DESeq2 - DESeq2_ for details
|
|
1050
|
|
1051 See above for Bioconductor package documentation for packages exposed in Galaxy by this tool and app store package.
|
|
1052
|
|
1053 Galaxy_ (that's what you are using right now!) for gluing everything together
|
|
1054
|
|
1055 Otherwise, all code and documentation comprising this tool was written by Ross Lazarus and is
|
|
1056 licensed to you under the LGPL_ like other rgenetics artefacts
|
|
1057
|
|
1058 .. _LGPL: http://www.gnu.org/copyleft/lesser.html
|
|
1059 .. _HTSeq: http://www-huber.embl.de/users/anders/HTSeq/doc/index.html
|
|
1060 .. _edgeR: http://www.bioconductor.org/packages/release/bioc/html/edgeR.html
|
|
1061 .. _DESeq2: http://www.bioconductor.org/packages/release/bioc/html/DESeq2.html
|
|
1062 .. _limma_VOOM: http://www.bioconductor.org/packages/release/bioc/html/limma.html
|
|
1063 .. _Galaxy: http://getgalaxy.org
|
|
1064 </help>
|
|
1065
|
|
1066 </tool>
|
|
1067
|
|
1068
|