0
|
1 <tool id="rgedgeRpaired" name="edgeR paired" version="0.18">
|
|
2 <description>2 level Anova for counts</description>
|
|
3 <command interpreter="python">
|
|
4 rgToolFactory.py --script_path "$runme" --interpreter "Rscript" --tool_name "edgeR"
|
|
5 --output_dir "$html_file.files_path" --output_html "$html_file" --output_tab "$outtab" --make_HTML "yes"
|
|
6 </command>
|
|
7 <inputs>
|
|
8 <param name="input1" type="data" format="tabular" label="Select an input matrix - rows are contigs, columns are counts for each sample"
|
|
9 help="Use the HTSeq based count matrix preparation tool to create these matrices from BAM/SAM files and a GTF file of genomic features"/>
|
|
10 <param name="title" type="text" value="edgeR" size="80" label="Title for job outputs" help="Supply a meaningful name here to remind you what the outputs contain">
|
|
11 <sanitizer invalid_char="">
|
|
12 <valid initial="string.letters,string.digits"><add value="_" /> </valid>
|
|
13 </sanitizer>
|
|
14 </param>
|
|
15 <param name="treatment_name" type="text" value="Treatment" size="50" label="Treatment Name"/>
|
|
16 <param name="Treat_cols" label="Select columns containing treatment." type="data_column" data_ref="input1" numerical="True"
|
|
17 multiple="true" use_header_names="true" size="120" display="checkboxes">
|
|
18 <validator type="no_options" message="Please select at least one column."/>
|
|
19 </param>
|
|
20 <param name="control_name" type="text" value="Control" size="50" label="Control Name"/>
|
|
21 <param name="Control_cols" label="Select columns containing control." type="data_column" data_ref="input1" numerical="True"
|
|
22 multiple="true" use_header_names="true" size="120" display="checkboxes" optional="true">
|
|
23 </param>
|
|
24 <param name="subjectids" type="text" optional="true" size="120"
|
|
25 label="IF SUBJECTS NOT ALL INDEPENDENT! Enter integers to indicate sample pairing for every column in input"
|
|
26 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 '1,2,1,2'">
|
|
27 <sanitizer>
|
|
28 <valid initial="string.digits"><add value="," /> </valid>
|
|
29 </sanitizer>
|
|
30 </param>
|
|
31 <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"
|
|
32 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"/>
|
|
33 <param name="useNDF" type="boolean" truevalue="T" checked='false' falsevalue="" size="1" label="Non differential filter - remove contigs below a threshold (1 per million) for half or more samples"
|
|
34 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"/>
|
|
35 <param name="priordf" type="integer" value="20" size="3" label="prior.df for tagwise dispersion - lower value = more emphasis on each tag's variance. Replaces prior.n and prior.df = prior.n * residual.df"
|
|
36 help="Zero = Use edgeR default. Use a small value to 'smooth' small samples. See edgeR docs and note below"/>
|
|
37 <param name="fdrthresh" type="float" value="0.05" size="5" label="P value threshold for FDR filtering for amily wise error rate control"
|
|
38 help="Conventional default value of 0.05 recommended"/>
|
|
39 <param name="fdrtype" type="select" label="FDR (Type II error) control method"
|
|
40 help="Use fdr or bh typically to control for the number of tests in a reliable way">
|
|
41 <option value="fdr" selected="true">fdr</option>
|
|
42 <option value="BH">Benjamini Hochberg</option>
|
|
43 <option value="BY">Benjamini Yukateli</option>
|
|
44 <option value="bonferroni">Bonferroni</option>
|
|
45 <option value="hochberg">Hochberg</option>
|
|
46 <option value="holm">Holm</option>
|
|
47 <option value="hommel">Hommel</option>
|
|
48 <option value="none">no control for multiple tests</option>
|
|
49 </param>
|
|
50 </inputs>
|
|
51 <outputs>
|
|
52 <data format="tabular" name="outtab" label="${title}.xls"/>
|
|
53 <data format="html" name="html_file" label="${title}.html"/>
|
|
54 </outputs>
|
|
55 <stdio>
|
|
56 <exit_code range="4" level="fatal" description="Number of subject ids must match total number of samples in the input matrix" />
|
|
57 </stdio>
|
|
58 <tests>
|
|
59 <test>
|
|
60 <param name='input1' value='test_bams2mx.xls' ftype='tabular' />
|
|
61 <param name='treatment_name' value='case' />
|
|
62 <param name='title' value='edgeRtest' />
|
|
63 <param name='fdrtype' value='fdr' />
|
|
64 <param name='priordf' value="0" />
|
|
65 <param name='fdrthresh' value="0.05" />
|
|
66 <param name='control_name' value='control' />
|
|
67 <param name='Treat_cols' value='3,4,5,9' />
|
|
68 <param name='Control_cols' value='2,6,7,8' />
|
|
69 <output name='outtab' file='edgeRtest1out.xls' ftype='tabular' compare='diff' />
|
|
70 <output name='html_file' file='edgeRtest1out.html' ftype='html' compare='diff' lines_diff='20' />
|
|
71 </test>
|
|
72 </tests>
|
|
73
|
|
74 <configfiles>
|
|
75 <configfile name="runme">
|
|
76 <![CDATA[
|
|
77 #
|
|
78 # edgeR.Rscript
|
|
79 # updated npv 2011 for R 2.14.0 and edgeR 2.4.0 by ross
|
|
80 # Performs DGE on a count table containing n replicates of two conditions
|
|
81 #
|
|
82 # Parameters
|
|
83 #
|
|
84 # 1 - Output Dir
|
|
85
|
|
86 # Original edgeR code by: S.Lunke and A.Kaspi
|
|
87 reallybig = log10(.Machine\$double.xmax)
|
|
88 reallysmall = log10(.Machine\$double.xmin)
|
|
89 library('stringr')
|
|
90 library('gplots')
|
|
91 library('DESeq')
|
|
92 library('edgeR')
|
|
93 hmap2 = function(cmat,nsamp=100,outpdfname='heatmap2.pdf', TName='Treatment',group=NA,myTitle='title goes here')
|
|
94 {
|
|
95 # Perform clustering for significant pvalues after controlling FWER
|
|
96 samples = colnames(cmat)
|
|
97 gu = unique(group)
|
|
98 if (length(gu) == 2) {
|
|
99 col.map = function(g) {if (g==gu[1]) "#FF0000" else "#0000FF"}
|
|
100 pcols = unlist(lapply(group,col.map))
|
|
101 } else {
|
|
102 colours = rainbow(length(gu),start=0,end=4/6)
|
|
103 pcols = colours[match(group,gu)] }
|
|
104 gn = rownames(cmat)
|
|
105 dm = cmat[(! is.na(gn)),]
|
|
106 # remove unlabelled hm rows
|
|
107 nprobes = nrow(dm)
|
|
108 # sub = paste('Showing',nprobes,'contigs ranked for evidence of differential abundance')
|
|
109 if (nprobes > nsamp) {
|
|
110 dm =dm[1:nsamp,]
|
|
111 #sub = paste('Showing',nsamp,'contigs ranked for evidence for differential abundance out of',nprobes,'total')
|
|
112 }
|
|
113 newcolnames = substr(colnames(dm),1,20)
|
|
114 colnames(dm) = newcolnames
|
|
115 pdf(outpdfname)
|
|
116 heatmap.2(dm,main=myTitle,ColSideColors=pcols,col=topo.colors(100),dendrogram="col",key=T,density.info='none',
|
|
117 Rowv=F,scale='row',trace='none',margins=c(8,8),cexRow=0.4,cexCol=0.5)
|
|
118 dev.off()
|
|
119 }
|
|
120
|
|
121 hmap = function(cmat,nmeans=4,outpdfname="heatMap.pdf",nsamp=250,TName='Treatment',group=NA,myTitle="Title goes here")
|
|
122 {
|
|
123 # for 2 groups only was
|
|
124 #col.map = function(g) {if (g==TName) "#FF0000" else "#0000FF"}
|
|
125 #pcols = unlist(lapply(group,col.map))
|
|
126 gu = unique(group)
|
|
127 colours = rainbow(length(gu),start=0.3,end=0.6)
|
|
128 pcols = colours[match(group,gu)]
|
|
129 nrows = nrow(cmat)
|
|
130 mtitle = paste(myTitle,'Heatmap: n contigs =',nrows)
|
|
131 if (nrows > nsamp) {
|
|
132 cmat = cmat[c(1:nsamp),]
|
|
133 mtitle = paste('Heatmap: Top ',nsamp,' DE contigs (of ',nrows,')',sep='')
|
|
134 }
|
|
135 newcolnames = substr(colnames(cmat),1,20)
|
|
136 colnames(cmat) = newcolnames
|
|
137 pdf(outpdfname)
|
|
138 heatmap(cmat,scale='row',main=mtitle,cexRow=0.3,cexCol=0.4,Rowv=NA,ColSideColors=pcols)
|
|
139 dev.off()
|
|
140 }
|
|
141
|
|
142 qqPlot = function(descr='Title',pvector, ...)
|
|
143 # stolen from https://gist.github.com/703512
|
|
144 {
|
|
145 o = -log10(sort(pvector,decreasing=F))
|
|
146 e = -log10( 1:length(o)/length(o) )
|
|
147 o[o==-Inf] = reallysmall
|
|
148 o[o==Inf] = reallybig
|
|
149 pdfname = paste(gsub(" ","", descr , fixed=TRUE),'pval_qq.pdf',sep='_')
|
|
150 maint = paste(descr,'QQ Plot')
|
|
151 pdf(pdfname)
|
|
152 plot(e,o,pch=19,cex=1, main=maint, ...,
|
|
153 xlab=expression(Expected~~-log[10](italic(p))),
|
|
154 ylab=expression(Observed~~-log[10](italic(p))),
|
|
155 xlim=c(0,max(e)), ylim=c(0,max(o)))
|
|
156 lines(e,e,col="red")
|
|
157 grid(col = "lightgray", lty = "dotted")
|
|
158 dev.off()
|
|
159 }
|
|
160
|
|
161 smearPlot = function(DGEList,deTags, outSmear, outMain)
|
|
162 {
|
|
163 pdf(outSmear)
|
|
164 plotSmear(DGEList,de.tags=deTags,main=outMain)
|
|
165 grid(col="blue")
|
|
166 dev.off()
|
|
167 }
|
|
168
|
|
169 boxPlot = function(rawrs,cleanrs,maint,myTitle)
|
|
170 { #
|
|
171 nc = ncol(rawrs)
|
|
172 for (i in c(1:nc)) {rawrs[(rawrs[,i] < 0),i] = NA}
|
|
173 fullnames = colnames(rawrs)
|
|
174 newcolnames = substr(colnames(rawrs),1,20)
|
|
175 colnames(rawrs) = newcolnames
|
|
176 newcolnames = substr(colnames(cleanrs),1,20)
|
|
177 colnames(cleanrs) = newcolnames
|
|
178 pdfname = paste(gsub(" ","", myTitle , fixed=TRUE),"sampleBoxplot.pdf",sep='_')
|
|
179 defpar = par(no.readonly=T)
|
|
180 pdf(pdfname,height=6,width=8)
|
|
181 #par(mfrow=c(1,2)) # 1 rows 2 col
|
|
182 l = layout(matrix(c(1,2),1,2,byrow=T))
|
|
183 print.noquote('raw contig counts by sample:')
|
|
184 print.noquote(summary(rawrs))
|
|
185 print.noquote('normalised contig counts by sample:')
|
|
186 print.noquote(summary(cleanrs))
|
|
187 boxplot(rawrs,varwidth=T,notch=T,ylab='log contig count',col="maroon",las=3,cex.axis=0.35,main=paste('Raw:',maint))
|
|
188 grid(col="blue")
|
|
189 boxplot(cleanrs,varwidth=T,notch=T,ylab='log contig count',col="maroon",las=3,cex.axis=0.35,main=paste('After ',maint))
|
|
190 grid(col="blue")
|
|
191 dev.off()
|
|
192 pdfname = paste(gsub(" ","", myTitle , fixed=TRUE),"samplehistplot.pdf",sep='_')
|
|
193 nc = ncol(rawrs)
|
|
194 print.noquote(paste('Using ncol rawrs=',nc))
|
|
195 ncroot = round(sqrt(nc))
|
|
196 if (ncroot*ncroot < nc) { ncroot = ncroot + 1 }
|
|
197 m = c()
|
|
198 for (i in c(1:nc)) {
|
|
199 rhist = hist(rawrs[,i],breaks=100,plot=F)
|
|
200 m = append(m,max(rhist\$counts))
|
|
201 }
|
|
202 ymax = max(m)
|
|
203 pdf(pdfname)
|
|
204 par(mfrow=c(ncroot,ncroot))
|
|
205 for (i in c(1:nc)) {
|
|
206 hist(rawrs[,i], main=paste("Contig logcount",i), xlab='log raw count', col="maroon",
|
|
207 breaks=100,sub=fullnames[i],cex=0.8,ylim=c(0,ymax))
|
|
208 }
|
|
209 dev.off()
|
|
210 par(defpar)
|
|
211
|
|
212 }
|
|
213
|
|
214 cumPlot = function(rawrs,cleanrs,maint,myTitle)
|
|
215 { # updated to use ecdf
|
|
216 pdfname = paste(gsub(" ","", myTitle , fixed=TRUE),"RowsumCum.pdf",sep='_')
|
|
217 defpar = par(no.readonly=T)
|
|
218 pdf(pdfname)
|
|
219 par(mfrow=c(2,1))
|
|
220 lrs = log(rawrs,10)
|
|
221 lim = max(lrs)
|
|
222 hist(lrs,breaks=100,main=paste('Before:',maint),xlab="# Reads (log)",
|
|
223 ylab="Count",col="maroon",sub=myTitle, xlim=c(0,lim),las=1)
|
|
224 grid(col="blue")
|
|
225 lrs = log(cleanrs,10)
|
|
226 hist(lrs,breaks=100,main=paste('After:',maint),xlab="# Reads (log)",
|
|
227 ylab="Count",col="maroon",sub=myTitle,xlim=c(0,lim),las=1)
|
|
228 grid(col="blue")
|
|
229 dev.off()
|
|
230 par(defpar)
|
|
231 }
|
|
232
|
|
233 cumPlot1 = function(rawrs,cleanrs,maint,myTitle)
|
|
234 { # updated to use ecdf
|
|
235 pdfname = paste(gsub(" ","", myTitle , fixed=TRUE),"RowsumCum.pdf",sep='_')
|
|
236 pdf(pdfname)
|
|
237 par(mfrow=c(2,1))
|
|
238 lastx = max(rawrs)
|
|
239 rawe = knots(ecdf(rawrs))
|
|
240 cleane = knots(ecdf(cleanrs))
|
|
241 cy = 1:length(cleane)/length(cleane)
|
|
242 ry = 1:length(rawe)/length(rawe)
|
|
243 plot(rawe,ry,type='l',main=paste('Before',maint),xlab="Log Contig Total Reads",
|
|
244 ylab="Cumulative proportion",col="maroon",log='x',xlim=c(1,lastx),sub=myTitle)
|
|
245 grid(col="blue")
|
|
246 plot(cleane,cy,type='l',main=paste('After',maint),xlab="Log Contig Total Reads",
|
|
247 ylab="Cumulative proportion",col="maroon",log='x',xlim=c(1,lastx),sub=myTitle)
|
|
248 grid(col="blue")
|
|
249 dev.off()
|
|
250 }
|
|
251
|
|
252
|
|
253
|
|
254 edgeIt = function (Count_Matrix,group,outputfilename,fdrtype='fdr',priordf=5,fdrthresh=0.05,outputdir='.',
|
|
255 myTitle='edgeR',libSize=c(),useNDF="T",filterquantile=0.2,subjects=c()) {
|
|
256
|
|
257 # Error handling
|
|
258 if (length(unique(group))!=2){
|
|
259 print("Number of conditions identified in experiment does not equal 2")
|
|
260 q()
|
|
261 }
|
|
262 require(edgeR)
|
|
263 mt = paste(unlist(strsplit(myTitle,'_')),collapse=" ")
|
|
264 allN = nrow(Count_Matrix)
|
|
265 nscut = round(ncol(Count_Matrix)/2)
|
|
266 colTotmillionreads = colSums(Count_Matrix)/1e6
|
|
267 rawrs = rowSums(Count_Matrix)
|
|
268 nonzerod = Count_Matrix[(rawrs > 0),] # remove all zero count genes
|
|
269 nzN = nrow(nonzerod)
|
|
270 nzrs = rowSums(nonzerod)
|
|
271 zN = allN - nzN
|
|
272 print('# Quantiles for non-zero row counts:',quote=F)
|
|
273 print(quantile(nzrs,probs=seq(0,1,0.1)),quote=F)
|
|
274 if (useNDF == "T")
|
|
275 {
|
|
276 gt1rpin3 = rowSums(Count_Matrix/expandAsMatrix(colTotmillionreads,dim(Count_Matrix)) >= 1) >= nscut
|
|
277 lo = colSums(Count_Matrix[!gt1rpin3,])
|
|
278 workCM = Count_Matrix[gt1rpin3,]
|
|
279 cleanrs = rowSums(workCM)
|
|
280 cleanN = length(cleanrs)
|
|
281 meth = paste( "After removing",length(lo),"contigs with fewer than ",nscut," sample read counts >= 1 per million, there are",sep="")
|
|
282 print(paste("Read",allN,"contigs. Removed",zN,"contigs with no reads.",meth,cleanN,"contigs"),quote=F)
|
|
283 maint = paste('Filter >=1/million reads in >=',nscut,'samples')
|
|
284 }
|
|
285 else {
|
|
286 useme = (nzrs > quantile(nzrs,filterquantile))
|
|
287 workCM = nonzerod[useme,]
|
|
288 lo = colSums(nonzerod[!useme,])
|
|
289 cleanrs = rowSums(workCM)
|
|
290 cleanN = length(cleanrs)
|
|
291 meth = paste("After filtering at count quantile =",filterquantile,", there are",sep="")
|
|
292 print(paste('Read',allN,"contigs. Removed",zN,"with no reads.",meth,cleanN,"contigs"),quote=F)
|
|
293 maint = paste('Filter below',filterquantile,'quantile')
|
|
294 }
|
|
295 cumPlot(rawrs=rawrs,cleanrs=cleanrs,maint=maint,myTitle=myTitle)
|
|
296 allgenes <- rownames(workCM)
|
|
297 print(paste("# Total low count contigs per sample = ",paste(lo,collapse=',')),quote=F)
|
|
298 rsums = rowSums(workCM)
|
|
299 TName=unique(group)[1]
|
|
300 CName=unique(group)[2]
|
|
301 # Setup DGEList object
|
|
302 DGEList = DGEList(counts=workCM, group = group)
|
|
303 if (length(subjects) == 0)
|
|
304 {
|
|
305 doDESEQ = T
|
|
306 mydesign = model.matrix(~group)
|
|
307 }
|
|
308 else {
|
|
309 doDESEQ = F
|
|
310 subjf = factor(subjects)
|
|
311 mydesign = model.matrix(~subjf+group) # we block on subject so make group last to simplify finding it
|
|
312 }
|
|
313 print.noquote(paste('Using samples:',paste(colnames(workCM),collapse=',')))
|
|
314 print.noquote('Using design matrix:')
|
|
315 print.noquote(mydesign)
|
|
316 DGEList = estimateGLMCommonDisp(DGEList,mydesign)
|
|
317 comdisp = DGEList\$common.dispersion
|
|
318 DGEList = estimateGLMTrendedDisp(DGEList,mydesign)
|
|
319 if (priordf > 0) {
|
|
320 print.noquote(paste("prior.df =",priordf))
|
|
321 DGEList = estimateGLMTagwiseDisp(DGEList,mydesign,prior.df = priordf)
|
|
322 } else {
|
|
323 DGEList = estimateGLMTagwiseDisp(DGEList,mydesign)
|
|
324 }
|
|
325 DGLM = glmFit(DGEList,design=mydesign)
|
|
326 efflib = DGEList\$samples\$lib.size*DGEList\$samples\$norm.factors
|
|
327 normData = (1e+06*DGEList\$counts/efflib)
|
|
328 co = length(colnames(mydesign))
|
|
329 DE = glmLRT(DGLM,coef=co) # always last one - subject is first if needed
|
|
330 uoutput = cbind(
|
|
331 Name=as.character(rownames(DGEList\$counts)),
|
|
332 DE\$table,
|
|
333 adj.p.value=p.adjust(DE\$table\$PValue, method=fdrtype),
|
|
334 Dispersion=DGEList\$tagwise.dispersion,totreads=rsums,normData,
|
|
335 DGEList\$counts
|
|
336 )
|
|
337 soutput = uoutput[order(DE\$table\$PValue),] # sorted into p value order - for quick toptable
|
|
338 goodness = gof(DGLM, pcutoff=fdrthresh)
|
|
339 if (sum(goodness\$outlier) > 0) {
|
|
340 print.noquote('GLM outliers:')
|
|
341 print(paste(rownames(DGLM)[(goodness\$outlier != 0)],collapse=','),quote=F)
|
|
342 z = limma::zscoreGamma(goodness\$gof.statistic, shape=goodness\$df/2, scale=2)
|
|
343 pdf(paste(mt,"GoodnessofFit.pdf",sep='_'))
|
|
344 qq = qqnorm(z, panel.first=grid(), main="tagwise dispersion")
|
|
345 abline(0,1,lwd=3)
|
|
346 points(qq\$x[goodness\$outlier],qq\$y[goodness\$outlier], pch=16, col="dodgerblue")
|
|
347 dev.off()
|
|
348 } else { print('No GLM fit outlier genes found\n')}
|
|
349 estpriorn = getPriorN(DGEList)
|
|
350 print(paste("Common Dispersion =",comdisp,"CV = ",sqrt(comdisp),"getPriorN = ",estpriorn),quote=F)
|
|
351 efflib = DGEList\$samples\$lib.size*DGEList\$samples\$norm.factors
|
|
352 normData = (1e+06*DGEList\$counts/efflib)
|
|
353 uniqueg = unique(group)
|
|
354 # Plot MDS
|
|
355 sample_colors = match(group,levels(group))
|
|
356 pdf(paste(mt,"MDSplot.pdf",sep='_'))
|
|
357 sampleTypes = levels(group)
|
|
358 plotMDS.DGEList(DGEList,main=paste("MDS Plot for",myTitle),cex=0.5,col=sample_colors,pch=sample_colors)
|
|
359 legend(x="topleft", legend = sampleTypes,col=c(1:length(sampleTypes)), pch=19)
|
|
360 grid(col="blue")
|
|
361 dev.off()
|
|
362 colnames(normData) = paste( colnames(normData),'N',sep="_")
|
|
363 print(paste('Raw sample read totals',paste(colSums(nonzerod,na.rm=T),collapse=',')))
|
|
364 nzd = data.frame(log(nonzerod + 1e-2,10))
|
|
365 boxPlot(rawrs=nzd,cleanrs=log(normData,10),maint='TMM Normalisation',myTitle=myTitle)
|
|
366 if (doDESEQ)
|
|
367 {
|
|
368 # DESeq
|
|
369 deSeqDatcount <- newCountDataSet(workCM, group)
|
|
370 deSeqDatsizefac <- estimateSizeFactors(deSeqDatcount)
|
|
371 deSeqDatdisp <- estimateDispersions(deSeqDatsizefac)
|
|
372 rDESeq <- nbinomTest(deSeqDatdisp, levels(group)[1], levels(group)[2])
|
|
373 rDESeq <- rDESeq[order(rDESeq\$pval), ]
|
|
374 write.table(rDESeq,paste(mt,'DESeq_TopTable.xls',sep='_'), quote=FALSE, sep="\t",row.names=F)
|
|
375 topresults.DESeq <- rDESeq[which(rDESeq\$padj < fdrthresh), ]
|
|
376 DESeqcountsindex <- which(allgenes %in% topresults.DESeq\$id)
|
|
377 DESeqcounts <- rep(0, length(allgenes))
|
|
378 DESeqcounts[DESeqcountsindex] <- 1
|
|
379 }
|
|
380 DGEList = calcNormFactors(DGEList)
|
|
381 norm.factor = DGEList\$samples\$norm.factors
|
|
382 pdf(paste(mt,"voomplot.pdf",sep='_'))
|
|
383 dat.voomed <- voom(DGEList, mydesign, plot = TRUE, lib.size = colSums(workCM) * norm.factor)
|
|
384 dev.off()
|
|
385 # Use limma to fit data
|
|
386 fit <- lmFit(dat.voomed, mydesign)
|
|
387 fit <- eBayes(fit)
|
|
388 rvoom <- topTable(fit, coef = length(colnames(mydesign)), adj = "BH", n = Inf)
|
|
389 write.table(rvoom,paste(mt,'VOOM_topTable.xls',sep='_'), quote=FALSE, sep="\t",row.names=F)
|
|
390 # Use an FDR cutoff to find interesting samples for edgeR, DESeq and voom/limma
|
|
391 topresults.voom <- rvoom[which(rvoom\$adj.P.Val < fdrthresh), ]
|
|
392 topresults.edgeR <- soutput[which(soutput\$adj.p.value < fdrthresh), ]
|
|
393 # Create venn diagram of hits
|
|
394 edgeRcountsindex <- which(allgenes %in% rownames(topresults.edgeR))
|
|
395 voomcountsindex <- which(allgenes %in% topresults.voom\$ID)
|
|
396 edgeRcounts <- rep(0, length(allgenes))
|
|
397 edgeRcounts[edgeRcountsindex] <- 1
|
|
398 voomcounts <- rep(0, length(allgenes))
|
|
399 voomcounts[voomcountsindex] <- 1
|
|
400 if (doDESEQ) {
|
|
401 vennmain = paste(mt,'Voom,edgeR and DESeq overlap at FDR=',fdrthresh)
|
|
402 counts.dataframe <- data.frame(edgeRcounts = edgeRcounts, DESeqcounts = DESeqcounts,
|
|
403 voomcounts = voomcounts, row.names = allgenes)
|
|
404 } else {
|
|
405 vennmain = paste(mt,'Voom and edgeR overlap at FDR=',fdrthresh)
|
|
406 counts.dataframe <- data.frame(edgeRcounts = edgeRcounts, voomcounts = voomcounts, row.names = allgenes)
|
|
407 }
|
|
408 counts.venn <- vennCounts(counts.dataframe)
|
|
409 vennf = paste(mt,'venn.pdf',sep='_')
|
|
410 pdf(vennf)
|
|
411 vennDiagram(counts.venn,main=vennmain,col="maroon")
|
|
412 dev.off()
|
|
413 #Prepare our output file
|
|
414 nreads = soutput\$totreads # ordered same way
|
|
415 print('# writing output',quote=F)
|
|
416 write.table(soutput,outputfilename, quote=FALSE, sep="\t",row.names=F)
|
|
417 rn = uoutput\$Name
|
|
418 reg = "^chr([0-9]+):([0-9]+)-([0-9]+)"
|
|
419 org="hg19"
|
|
420 genecards="<a href='http://www.genecards.org/index.php?path=/Search/keyword/"
|
|
421 ucsc = paste("<a href='http://genome.ucsc.edu/cgi-bin/hgTracks?db=",org,sep='')
|
|
422 testreg = str_match(rn,reg)
|
|
423 nreads = uoutput\$totreads # ordered same way
|
|
424 if (sum(!is.na(testreg[,1]))/length(testreg[,1]) > 0.8) # is ucsc style string
|
|
425 {
|
|
426 urls = paste(ucsc,'&position=chr',testreg[,2],':',testreg[,3],"-",testreg[,4],"'>",rn,'</a>',sep='')
|
|
427 } else {
|
|
428 urls = paste(genecards,rn,"'></a>",rn,'</a>',sep="")
|
|
429 }
|
|
430 print.noquote('# urls')
|
|
431 cat(head(urls))
|
|
432 tt = uoutput
|
|
433 cat("# Top tags\n")
|
|
434 tt = cbind(tt,ntotreads=nreads,URL=urls) # add to end so table isn't laid out strangely
|
|
435 tt = tt[order(DE\$table\$PValue),]
|
|
436 options(width = 500)
|
|
437 print.noquote(tt[1:50,])
|
|
438 pdf(paste(mt,"BCV_vs_abundance.pdf",sep='_'))
|
|
439 plotBCV(DGEList, cex=0.3, main="Biological CV vs abundance")
|
|
440 dev.off()
|
|
441 # Plot MAplot
|
|
442 deTags = rownames(uoutput[uoutput\$adj.p.value < fdrthresh,])
|
|
443 nsig = length(deTags)
|
|
444 print(paste('#',nsig,'tags significant at adj p=',fdrthresh),quote=F)
|
|
445 print('# deTags',quote=F)
|
|
446 print(head(deTags))
|
|
447 dg = DGEList[order(DE\$table\$PValue),]
|
|
448 #normData = (1e+06 * dg\$counts/expandAsMatrix(dg\$samples\$lib.size, dim(dg)))
|
|
449 efflib = dg\$samples\$lib.size*dg\$samples\$norm.factors
|
|
450 normData = (1e+06*dg\$counts/efflib)
|
|
451 outpdfname=paste(mt,"heatmap.pdf",sep='_')
|
|
452 hmap2(normData,nsamp=100,TName=TName,group=group,outpdfname=outpdfname,myTitle=myTitle)
|
|
453 outSmear = paste(mt,"Smearplot.pdf",sep='_')
|
|
454 outMain = paste("Smear Plot for ",TName,' Vs ',CName,' (FDR@',fdrthresh,' N = ',nsig,')',sep='')
|
|
455 smearPlot(DGEList=DGEList,deTags=deTags, outSmear=outSmear, outMain = outMain)
|
|
456 qqPlot(descr=myTitle,pvector=DE\$table\$PValue)
|
|
457 if (doDESEQ) {
|
|
458 cat("# DESeq top 50\n")
|
|
459 print(rDESeq[1:50,])
|
|
460 }
|
|
461 cat("# VOOM top 50\n")
|
|
462 print(rvoom[1:50,])
|
|
463 # need a design matrix and glm to use this
|
|
464 goodness = gof(DGLM, pcutoff=fdrthresh)
|
|
465 nout = sum(goodness\$outlier)
|
|
466 if (nout > 0) {
|
|
467 print.noquote(paste('Found',nout,'Goodness of fit outliers'))
|
|
468 rownames(DGLM)[goodness\$outlier]
|
|
469 z = limma::zscoreGamma(goodness\$gof.statistic, shape=goodness\$df/2, scale=2)
|
|
470 pdf(paste(mt,"GoodnessofFit.pdf",sep='_'))
|
|
471 qq = qqnorm(z, panel.first=grid(), main="tagwise dispersion")
|
|
472 abline(0,1,lwd=3)
|
|
473 points(qq\$x[goodness\$outlier],qq\$y[goodness\$outlier], pch=16, col="dodgerblue")
|
|
474 dev.off()
|
|
475 }
|
|
476 #Return our main table
|
|
477 uoutput
|
|
478
|
|
479 } #Done
|
|
480 sink(stdout(),append=T,type="message")
|
|
481 options(width=512)
|
|
482 Out_Dir = "$html_file.files_path"
|
|
483 Input = "$input1"
|
|
484 TreatmentName = "$treatment_name"
|
|
485 TreatmentCols = "$Treat_cols"
|
|
486 ControlName = "$control_name"
|
|
487 ControlCols= "$Control_cols"
|
|
488 outputfilename = "$outtab"
|
|
489 fdrtype = "$fdrtype"
|
|
490 priordf = $priordf
|
|
491 fdrthresh = $fdrthresh
|
|
492 useNDF = "$useNDF"
|
|
493 fQ = $fQ # non-differential centile cutoff
|
|
494 myTitle = "$title"
|
|
495 subjects = c($subjectids)
|
|
496 nsubj = length(subjects)
|
|
497 #Set our columns
|
|
498 TCols = as.numeric(strsplit(TreatmentCols,",")[[1]])-1
|
|
499 CCols = as.numeric(strsplit(ControlCols,",")[[1]])-1
|
|
500 cat('# got TCols=')
|
|
501 cat(TCols)
|
|
502 cat('; CCols=')
|
|
503 cat(CCols)
|
|
504 cat('\n')
|
|
505 useCols = c(TCols,CCols)
|
|
506 # Create output dir if non existent
|
|
507 if (file.exists(Out_Dir) == F) dir.create(Out_Dir)
|
|
508
|
|
509 Count_Matrix = read.table(Input,header=T,row.names=1,sep='\t') #Load tab file assume header
|
|
510 snames = colnames(Count_Matrix)
|
|
511 nsamples = length(snames)
|
|
512 if (nsubj > 0 & nsubj != nsamples) {
|
|
513 options("show.error.messages"=T)
|
|
514 mess = paste('Fatal error: Supplied subject id list',paste(subjects,collapse=','),'has length',nsubj,'but there are',nsamples,'samples',paste(snames,collapse=','))
|
|
515 write(mess, stderr())
|
|
516 #print(mess)
|
|
517 quit(save="no",status=4)
|
|
518 }
|
|
519
|
|
520 Count_Matrix = Count_Matrix[,useCols] # reorder columns
|
|
521 if (length(subjects) != 0) {subjects = subjects[useCols]}
|
|
522 rn = rownames(Count_Matrix)
|
|
523 islib = rn %in% c('librarySize','NotInBedRegions')
|
|
524 LibSizes = Count_Matrix[subset(rn,islib),][1] # take first
|
|
525 Count_Matrix = Count_Matrix[subset(rn,! islib),]
|
|
526 group = c(rep(TreatmentName,length(TCols)), rep(ControlName,length(CCols)) ) #Build a group descriptor
|
|
527 group = factor(group, levels=c(ControlName,TreatmentName))
|
|
528 colnames(Count_Matrix) = paste(group,colnames(Count_Matrix),sep="_") #Relable columns
|
|
529 results = edgeIt(Count_Matrix=Count_Matrix,group=group,outputfilename=outputfilename,fdrtype=fdrtype,priordf=priordf,fdrthresh=fdrthresh,
|
|
530 outputdir=Out_Dir,myTitle=myTitle,libSize=c(),useNDF=useNDF,filterquantile=fQ,subjects=subjects)
|
|
531 #Run the main function
|
|
532 # for the log
|
|
533 sessionInfo()
|
|
534 ]]>
|
|
535 </configfile>
|
|
536 </configfiles>
|
|
537 <help>
|
|
538 **What it does**
|
|
539
|
|
540 Performs digital gene expression analysis between a treatment and control on a count matrix.
|
|
541 Optionally adds a term for subject if not all samples are independent or if some other factor needs to be blocked in the design.
|
|
542
|
|
543 **Input**
|
|
544
|
|
545 A matrix consisting of non-negative integers. The matrix must have a unique header row identifiying the samples, and a unique set of row names
|
|
546 as the first column. Typically the row names are gene symbols or probe id's for downstream use in GSEA and other methods.
|
|
547
|
|
548 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),
|
|
549 put a comma separated list of indicators for every sample (whether modelled or not!) indicating (eg) the subject number or
|
|
550 A list of integers, one for each subject or an empty string if samples are all independent.
|
|
551 If not empty, there must be exactly as many integers in the supplied integer list as there are columns (samples) in the count matrix.
|
|
552 Integers for samples that are not in the analysis *must* be present in the string as filler even if not used.
|
|
553
|
|
554 So if you have 2 pairs out of 6 samples, you need to put in unique integers for the unpaired ones
|
|
555 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
|
|
556 8,9,1,1,2,2
|
|
557 as subject IDs to indicate two paired samples from the same subject in columns 3/4 and 5/6
|
|
558
|
|
559 **Output**
|
|
560
|
|
561 A matrix which consists the original data and relative expression levels and some helpful plots
|
|
562
|
|
563 **Note on edgeR versions**
|
|
564
|
|
565 The edgeR authors made a small cosmetic change in the name of one important variable (from p.value to PValue)
|
|
566 breaking this and all other code that assumed the old name for this variable,
|
|
567 between edgeR2.4.4 and 2.4.6 (the version for R 2.14 as at the time of writing).
|
|
568 This means that all code using edgeR is sensitive to the version. I think this was a very unwise thing
|
|
569 to do because it wasted hours of my time to track down and will similarly cost other edgeR users dearly
|
|
570 when their old scripts break. This tool currently now works with 2.4.6.
|
|
571
|
|
572 **Note on prior.N**
|
|
573
|
|
574 http://seqanswers.com/forums/showthread.php?t=5591 says:
|
|
575
|
|
576 *prior.n*
|
|
577
|
|
578 The value for prior.n determines the amount of smoothing of tagwise dispersions towards the common dispersion.
|
|
579 You can think of it as like a "weight" for the common value. (It is actually the weight for the common likelihood
|
|
580 in the weighted likelihood equation). The larger the value for prior.n, the more smoothing, i.e. the closer your
|
|
581 tagwise dispersion estimates will be to the common dispersion. If you use a prior.n of 1, then that gives the
|
|
582 common likelihood the weight of one observation.
|
|
583
|
|
584 In answer to your question, it is a good thing to squeeze the tagwise dispersions towards a common value,
|
|
585 or else you will be using very unreliable estimates of the dispersion. I would not recommend using the value that
|
|
586 you obtained from estimateSmoothing()---this is far too small and would result in virtually no moderation
|
|
587 (squeezing) of the tagwise dispersions. How many samples do you have in your experiment?
|
|
588 What is the experimental design? If you have few samples (less than 6) then I would suggest a prior.n of at least 10.
|
|
589 If you have more samples, then the tagwise dispersion estimates will be more reliable,
|
|
590 so you could consider using a smaller prior.n, although I would hesitate to use a prior.n less than 5.
|
|
591
|
|
592
|
|
593 From Bioconductor Digest, Vol 118, Issue 5, Gordon writes:
|
|
594
|
|
595 Dear Dorota,
|
|
596
|
|
597 The important settings are prior.df and trend.
|
|
598
|
|
599 prior.n and prior.df are related through prior.df = prior.n * residual.df,
|
|
600 and your experiment has residual.df = 36 - 12 = 24. So the old setting of
|
|
601 prior.n=10 is equivalent for your data to prior.df = 240, a very large
|
|
602 value. Going the other way, the new setting of prior.df=10 is equivalent
|
|
603 to prior.n=10/24.
|
|
604
|
|
605 To recover old results with the current software you would use
|
|
606
|
|
607 estimateTagwiseDisp(object, prior.df=240, trend="none")
|
|
608
|
|
609 To get the new default from old software you would use
|
|
610
|
|
611 estimateTagwiseDisp(object, prior.n=10/24, trend=TRUE)
|
|
612
|
|
613 Actually the old trend method is equivalent to trend="loess" in the new
|
|
614 software. You should use plotBCV(object) to see whether a trend is
|
|
615 required.
|
|
616
|
|
617 Note you could also use
|
|
618
|
|
619 prior.n = getPriorN(object, prior.df=10)
|
|
620
|
|
621 to map between prior.df and prior.n.
|
|
622
|
|
623 </help>
|
|
624
|
|
625 </tool>
|
|
626
|
|
627
|