6
|
1 #!/usr/bin/env python2.7.3
|
|
2 #-*- coding: utf-8 -*-
|
|
3
|
|
4 '''
|
|
5 Created on Dec. 2013
|
|
6 @author: rachel legendre
|
|
7 @copyright: rachel.legendre@igmors.u-psud.fr
|
|
8 @license: GPL v3
|
|
9 '''
|
|
10
|
|
11 import os, sys, time, optparse, shutil, re, urllib, subprocess, tempfile
|
|
12 from urllib import unquote
|
|
13 from Bio import SeqIO
|
|
14 import csv
|
|
15 import pysam
|
|
16 import HTSeq
|
|
17 #from matplotlib import pyplot as pl
|
|
18 import matplotlib
|
|
19 matplotlib.use('Agg')
|
|
20 import matplotlib.pyplot as pl
|
|
21 from numpy import arange
|
|
22 from matplotlib import ticker as t
|
|
23 from PIL import Image
|
10
|
24 import ribo_functions
|
|
25 ## suppress matplotlib warnings
|
|
26 import warnings
|
|
27
|
|
28
|
6
|
29
|
|
30 def stop_err( msg ):
|
|
31 sys.stderr.write( "%s\n" % msg )
|
|
32 sys.stderr.write( "Programme aborted at %s\n" % time.asctime(time.localtime(time.time())))
|
|
33 sys.exit()
|
|
34
|
|
35
|
|
36 def compute_rpkm(length,count_gene,count_tot) :
|
|
37
|
|
38 try :
|
|
39 rpkm = "{0:.4f}".format(count_gene*1000000.0/(count_tot*length))
|
|
40 except ArithmeticError :
|
15
|
41 stop_err( 'Illegal division by zero during computing RPKM')
|
6
|
42 return float(rpkm)
|
|
43
|
|
44
|
|
45 def find_stop(seq) :
|
|
46 '''
|
|
47 Find stop codon in a sequence and return position of first nucleotide in stop
|
|
48 '''
|
|
49 stop_codon = ['TAA','TAG','TGA']
|
|
50 for nt in range(0,len(seq)-3,3) :
|
|
51 codon = seq[nt:nt+3]
|
|
52 if codon in stop_codon :
|
|
53 return nt
|
|
54
|
|
55 return -1
|
|
56
|
|
57
|
|
58 def check_met(seq):
|
|
59 '''
|
|
60 Boolean function for testing presence or absence of methionine in 5 codons following stop codon
|
|
61 '''
|
|
62 met = 'ATG'
|
|
63 for pos in range(0,15,3) :
|
|
64 codon = seq[pos:pos+3]
|
|
65 if codon in met :
|
|
66 return True
|
|
67
|
|
68 return False
|
|
69
|
|
70
|
|
71 '''
|
|
72 feature.iv is a GenomicInterval object :
|
|
73 A GenomicInterval object has the following slots, some of which
|
|
74 are calculated from the other:
|
|
75
|
|
76 chrom: The name of a sequence (i.e., chromosome, contig, or
|
|
77 the like).
|
|
78 start: The start of the interval. Even on the reverse strand,
|
|
79 this is always the smaller of the two values 'start' and 'end'.
|
|
80 Note that all positions should be given as 0-based value!
|
|
81 end: The end of the interval. Following Python convention for
|
|
82 ranges, this in one more than the coordinate of the last base
|
|
83 that is considered part of the sequence.
|
|
84 strand: The strand, as a single character, '+' or '-'. '.' indicates
|
10
|
85 that the strand is irrelevant. (Alternatively, pass a Strand object.)
|
6
|
86 length: The length of the interval, i.e., end - start
|
|
87 start_d: The "directional start" position. This is the position of the
|
|
88 first base of the interval, taking the strand into account. Hence,
|
|
89 this is the same as 'start' except when strand == '-', in which
|
|
90 case it is end-1.
|
|
91 end_d: The "directional end": Usually, the same as 'end', but for
|
|
92 strand=='-1', it is start-1.
|
|
93
|
|
94 '''
|
10
|
95 def check_overlapping(gff_reader,chrm,start,stop,strand, name):
|
6
|
96
|
|
97 #### probleme avec les genes completement inclu...
|
|
98
|
|
99 iv2 = HTSeq.GenomicInterval(chrm,start,stop,strand)
|
|
100 for feature in gff_reader:
|
|
101 if feature.type == "gene" :
|
10
|
102 if feature.iv.overlaps(iv2) and feature.attr.get('gene_name') != name :
|
6
|
103 ## if its a reverse gene, we replace start of extension by start of previous gene
|
|
104 if strand == '-' :
|
|
105 return (feature.iv.end+3,stop)
|
|
106 ## else we replace stop of extension by start of following gene
|
|
107 else :
|
|
108 return (start,feature.iv.start-3)
|
|
109 ## if no overlap are find, we return -1
|
|
110 return (start,stop)
|
|
111
|
|
112
|
|
113 def pass_length(start,stop) :
|
|
114
|
|
115 if (stop-start) > 25 :
|
|
116 return True
|
|
117 else :
|
|
118 return False
|
|
119
|
|
120
|
|
121 def check_homo_coverage(gene,GFF,start,stop, aln) :
|
|
122
|
|
123 chrom = GFF[gene]['chrom']
|
14
|
124 ## compute number of nucleotides in CDS with a coverage equal to zero
|
6
|
125 nt_cds_cov = 0
|
|
126 nt_cds_num = 0
|
|
127 for i in range(1,GFF[gene]['exon_number']+1) :
|
|
128 for z in range(GFF[gene]['exon'][i]['start'],GFF[gene]['exon'][i]['stop']):
|
|
129 nt_cds_num += 1
|
|
130 if aln.count(chrom,z,z+1) == 0 :
|
|
131 nt_cds_cov += 1
|
|
132
|
|
133 ## compute percent of CDS no covering
|
14
|
134 if nt_cds_cov == 0 or nt_cds_num == 0:
|
|
135 percent = 0
|
|
136 else:
|
|
137 percent = nt_cds_cov*100/nt_cds_num
|
6
|
138
|
|
139 ## compute number of nucleotides with no coverage in extension
|
|
140 nt_no_cover = 0
|
|
141 for pos in range(start,stop,1) :
|
|
142 if aln.count(chrom,pos,pos+1) == 0 :
|
|
143 nt_no_cover += 1
|
|
144 #print gene, nt_cds_cov, percent, nt_no_cover
|
|
145 #percent10 = (stop-start)*50/100
|
|
146 if (nt_no_cover*100)/(stop-start) > percent :
|
|
147 return False
|
|
148 else :
|
|
149 return True
|
|
150
|
|
151 def plot_gene ( aln, gene, start_extension, stop_extension, dirout ) :
|
|
152
|
10
|
153
|
|
154 ### ignore matplotlib warnings for galaxy
|
|
155 warnings.filterwarnings('ignore')
|
6
|
156 try:
|
|
157 strand = gene['strand']
|
|
158 len_gene = gene['stop']-gene['start']
|
|
159 if strand is "-" :
|
|
160 len_ext = gene['stop']-start_extension
|
|
161 ##Â coverage in all gene + extension
|
|
162 start = start_extension-100
|
|
163 stop = gene['stop']+100
|
|
164 vector1 = [0]*(stop-start)
|
|
165 #for pileupcolumn in aln.pileup( gene['chrom'], start, stop):
|
|
166 # vector.append(pileupcolumn.n)
|
|
167 for read in aln.fetch(gene['chrom'], start, stop):
|
|
168 if read.is_reverse :
|
|
169 ## for get footprint in P-site (estimate) we take 3 nt in middle of read
|
|
170 #pos = (read.pos+13)-start
|
|
171 pos = (read.pos-start) + (read.rlen/2)-1
|
|
172 for z in range(pos,(pos+3)) :
|
|
173 ## le fetch contient des reads qui chevauchent les 30 nt de la fin du gene mais dont le site P
|
|
174 ## se trouve avant notre vector, le z devient negatif et la couverture augmente en fin de vecteur (ce qui est faux)
|
|
175 if z > 0 :
|
|
176 try :
|
|
177 vector1[z] += 1
|
|
178 except IndexError :
|
|
179 pass
|
|
180 vector1.reverse()
|
|
181 mean_read = float(sum(vector1))/float(len(vector1))
|
|
182 cov = [(x/mean_read) for x in vector1]
|
|
183 idx_tot = arange(len(cov))
|
|
184 ## coverage in extension
|
|
185 start_ext = start_extension-40
|
|
186 stop_ext = stop_extension+30
|
|
187 vector2 = [0]*(stop_ext-start_ext)
|
|
188 #for pileupcolumn in aln.pileup( gene['chrom'], start, stop):
|
|
189 # vector.append(pileupcolumn.n)
|
|
190 for read in aln.fetch(gene['chrom'], start_extension, stop_ext):
|
|
191 if read.is_reverse :
|
|
192 ## get footprint in P-site
|
|
193 #pos = (read.pos+13)-start_ext
|
|
194 pos = (read.pos-start_ext) + (read.rlen/2)-1
|
|
195 for z in range(pos,(pos+3)) :
|
|
196 if z > 0 :
|
|
197 try :
|
|
198 vector2[z] += 1
|
|
199 except IndexError :
|
|
200 pass
|
|
201 vector2.reverse()
|
|
202 #mean_read = float(sum(vector))/float(len(vector))
|
|
203 cov_ext = [(x/mean_read) for x in vector2]
|
|
204 _max = max(cov_ext[30::])
|
|
205 idx_ext = arange(len(cov_ext))
|
|
206
|
|
207 else :
|
|
208 len_ext = stop_extension-gene['start']
|
|
209 start = gene['start']-100
|
|
210 stop = stop_extension+100
|
|
211 vector = [0]*(stop-start)
|
|
212 #for pileupcolumn in aln.pileup( gene['chrom'], start, stop):
|
|
213 #vector.append(pileupcolumn.n)
|
|
214 for read in aln.fetch(gene['chrom'], start, stop):
|
|
215 if not read.is_reverse :
|
|
216 ## get footprint in P-site
|
|
217 #pos = (read.pos+12)-start
|
|
218 pos = (read.pos-start) + (read.rlen/2)-1
|
|
219 for z in range(pos,(pos+3)) :
|
|
220 if z > 0 :
|
|
221 try :
|
|
222 vector[z] += 1
|
|
223 except IndexError :
|
|
224 pass
|
|
225 mean_read = float(sum(vector))/float(len(vector))
|
|
226 cov = [(x/mean_read) for x in vector]
|
|
227 idx_tot = arange(len(cov))
|
|
228
|
|
229 ## coverage in extension
|
|
230 start_ext = gene['stop']-30
|
|
231 stop_ext = stop_extension+40
|
|
232 vector = [0]*(stop-start_ext)
|
|
233 for read in aln.fetch(gene['chrom'], start_ext, stop_extension):
|
|
234 if not read.is_reverse :
|
|
235 ## get footprint in P-site
|
|
236 pos = (read.pos-start_ext) + (read.rlen/2)-1
|
|
237 for z in range(pos,(pos+3)) :
|
|
238 if z > 0 :
|
|
239 try :
|
|
240 vector[z] += 1
|
|
241 except IndexError :
|
|
242 pass
|
|
243
|
|
244 cov_ext = [(x/mean_read) for x in vector]
|
|
245 idx_ext = arange(len(cov_ext))
|
|
246 _max = max(cov_ext[30::])
|
|
247
|
|
248 #### PLOT FIGURE ####
|
|
249
|
|
250 font = {'family' : 'serif','color': 'grey','weight' : 'normal','size' : 16 }
|
|
251
|
|
252
|
|
253 fig = pl.figure(num=1)
|
|
254 ## create a big subplot for common y axis on two last subplot
|
|
255 ax = fig.add_subplot(2,1,2)
|
|
256 ## hide all spines
|
|
257 ax.spines['top'].set_visible(False)
|
|
258 ax.spines['bottom'].set_visible(False)
|
|
259 ax.spines['left'].set_visible(False)
|
|
260 ax.spines['right'].set_visible(False)
|
|
261 ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
|
|
262
|
|
263 ## plot gene structure
|
|
264 ax1 = fig.add_subplot(3,1,1)
|
|
265 ax1.set_title(gene['name'])
|
|
266 ## hide all spines
|
|
267 ax1.spines['right'].set_color('none')
|
|
268 ax1.spines['top'].set_color('none')
|
|
269 ax1.spines['left'].set_color('none')
|
|
270 ax1.spines['bottom'].set_color('none')
|
|
271 ax1.set_ylim(0,5)
|
|
272 #set xlim as second plot with 100nt switch
|
|
273 ax1.set_xlim(-100,len(idx_tot)-100)
|
|
274 ## hide ticks
|
|
275 pl.yticks([])
|
|
276 pl.xticks([])
|
|
277 ## if it's a "simple" gene
|
|
278 if gene['exon_number'] == 1 :
|
|
279 exon = arange(len_gene)
|
|
280 x = [3]*len_gene
|
|
281 ax1.plot(exon,x,color='#9B9E9C')
|
|
282 ax1.fill_between(exon,2,x,color='#9B9E9C')
|
|
283 ## if it's a gene with introns
|
|
284 else :
|
|
285 ## plot a line representing intron
|
|
286 intron = arange(len_gene)
|
|
287 y = [2.5]*len_gene
|
|
288 ax1.plot(intron,y,color='#9B9E9C')
|
|
289
|
|
290 ## plotting each intron
|
|
291 start = gene['start']
|
|
292 if strand == '+' :
|
|
293 for exon in range(1,gene['exon_number']+1,1) :
|
|
294 len_exon = gene['exon'][exon]['stop']-gene['exon'][exon]['start']
|
|
295 idx = gene['exon'][exon]['start'] - start
|
|
296 exo = arange(idx,idx+len_exon)
|
|
297 x = [3]*len_exon
|
|
298 ax1.plot(exo,x,color='#9B9E9C')
|
|
299 ax1.fill_between(exo,2,x,color='#9B9E9C')
|
|
300 else :
|
|
301 ## if it's a reverse gene we must reverse exon's position
|
|
302 start = gene['start']
|
|
303 tabF = [2.5]*len_gene
|
|
304 tabR = [2.5]*len_gene
|
|
305 for exon in range(1,gene['exon_number']+1,1) :
|
|
306 len_exon = gene['exon'][exon]['stop']-gene['exon'][exon]['start']
|
|
307 idx = gene['exon'][exon]['start'] - start
|
|
308 exo = arange(idx,idx+len_exon)
|
|
309 for z in exo :
|
|
310 tabF[z] = 3
|
|
311 tabR[z] = 2
|
|
312 tabF.reverse()
|
|
313 tabR.reverse()
|
|
314 #pl.ylim(0,5)
|
|
315 ax1.plot(tabF,color='#9B9E9C')
|
|
316 ax1.plot(tabR,color='#9B9E9C')
|
|
317 x = arange(len(tabR))
|
|
318 ax1.fill_between(x,tabF,tabR,color='#9B9E9C')
|
|
319
|
|
320 ## insert arrows (as genome browser representation)
|
|
321 yloc = 2.5
|
|
322 narrows = 20
|
|
323 exonwidth = .8
|
|
324 spread = .4 * len_gene / narrows
|
|
325 for i in range(narrows):
|
|
326 loc = (float(i) * len_gene / narrows)+ (len(idx_tot)/100)*2
|
|
327 if strand == '+' :
|
|
328 x = [loc - spread, loc, loc - spread]
|
|
329 else:
|
|
330 x = [loc - spread, loc, loc - spread]
|
|
331 y = [yloc - exonwidth / 5, yloc, yloc + exonwidth / 5]
|
|
332 ax1.plot(x, y, lw=1.4, color='#676B69')
|
|
333
|
|
334
|
|
335 # plot coverage in all gene + extension
|
|
336 ax2 = fig.add_subplot(3,1,2)
|
|
337 ## fixe limit to length of coverage for x axis
|
|
338 ax2.set_xlim(0,len(idx_tot))
|
|
339 ## fixe 4 ticks and associated labels for y axis
|
|
340 ax2.set_yticklabels(arange(0,int(max(cov)+20),int((max(cov)+20)/4)))
|
|
341 ax2.set_yticks(arange(0,int(max(cov)+20),int((max(cov)+20)/4)))
|
|
342 ### add start and stop of gene in axe in place of number
|
|
343 ax2.set_xticks([100,(100+len_gene),(100+len_ext)])
|
|
344 ax2.set_xticklabels(["{:,}".format(gene['start']),"{:,}".format(gene['stop']),""])
|
|
345 ## hide spines and any axis
|
|
346 ax2.spines['right'].set_visible(False)
|
|
347 ax2.spines['top'].set_visible(False)
|
|
348 ax2.yaxis.set_ticks_position('left')
|
|
349 ax2.xaxis.set_ticks_position('bottom')
|
|
350 ## plot and fill
|
|
351 ax2.plot(idx_tot, cov, color="#CC0011")
|
|
352 ax2.fill_between(idx_tot, 0,cov,color="#CC0011")
|
|
353 ax2.set_title("Genomic coordinates (%s,%s)"% (gene['strand'],gene['chrom']) ,fontdict={'fontsize':'small'})
|
|
354
|
|
355 # plot zoom coverage in extension
|
|
356 ax3 = fig.add_subplot(3,1,3)
|
|
357 ## fixe limit to length of coverage for x axis
|
|
358 ax3.set_ylim(0,int(_max))
|
|
359 # we hide spines
|
|
360 ax3.spines['right'].set_visible(False)
|
|
361 ax3.spines['top'].set_visible(False)
|
|
362 ax3.yaxis.set_ticks_position('left')
|
|
363 ax3.xaxis.set_ticks_position('bottom')
|
|
364 ##Â add stop and in-frame stop in x axis
|
|
365 pl.xticks([30,( stop_extension-start_extension)+30],["stop codon","next in-frame stop"])
|
|
366 ## fixe good position for labels
|
|
367 (ax3.get_xticklabels()[0]).set_horizontalalignment('center')
|
|
368 (ax3.get_xticklabels()[1]).set_horizontalalignment('left')
|
|
369 #if max coverage is lower than 2, we have a illegal division by zero
|
|
370 if _max > 2 :
|
|
371 ax3.set_yticklabels(arange(0,int(_max+1),int((_max+1)/3)))
|
|
372 ax3.set_yticks(arange(0,int(_max+1),int((_max+1)/3)))
|
|
373 else :
|
|
374 ##
|
|
375 ax3.set_ylim(0,_max)
|
|
376 ax3.ticklabel_format(style='sci', scilimits=(-2,2), axis='y',useOffset=False)
|
|
377
|
|
378 ax3.plot(idx_ext, cov_ext, color="#CC0011")
|
|
379 ax3.fill_between(idx_ext, 0,cov_ext,color="#CC0011")
|
|
380
|
|
381
|
|
382 ## get scale of subplot 3
|
|
383 #ax3.text(ax3.get_xlim()[1]-50,ax3.get_ylim()[1]-1, r'50 nt', fontdict=font)
|
|
384 #pl.arrow( ax3.get_xlim()[1]-50, ax3.get_ylim()[1]-2, ax3.get_xlim()[1]-50, 0, fc="grey", ec="grey",lw=2)
|
|
385
|
|
386 ## set common y label
|
|
387 ax.set_ylabel('Normalized footprint counts',labelpad=20)
|
|
388
|
|
389 ## draw and save plot
|
|
390 pl.draw()
|
|
391 #pl.show()
|
|
392 pl.savefig(dirout+".png",format='png', dpi=300)
|
|
393 pl.clf()
|
|
394
|
|
395
|
|
396 ## Make thumbnail for html page
|
|
397 infile = dirout+'.png'
|
|
398 size = 128, 128
|
|
399 im = Image.open(infile)
|
|
400 im.thumbnail(size, Image.ANTIALIAS)
|
|
401 im.save(dirout+"_thumbnail.png", "PNG")
|
10
|
402 warnings.resetwarnings()
|
6
|
403
|
|
404 except Exception, e:
|
|
405 stop_err( 'Error during gene plotting : ' + str( e ) )
|
|
406
|
|
407
|
10
|
408 def compute_analysis(bam, GFF, fasta, gff, dirout, extend) :
|
6
|
409
|
|
410 try:
|
|
411 background_file = dirout+"/background_sequence.fasta"
|
|
412 file_back = open(background_file, 'w')
|
|
413 file_context = open(dirout+"/stop_context.fasta", 'w')
|
|
414 file_extension = open(dirout+"/extensions.fasta", 'w')
|
|
415 ## Opening Bam file with pysam librarie
|
|
416 pysam.index(bam)
|
|
417 aln = pysam.Samfile(bam, "rb",header=True, check_header = True)
|
|
418 ## Opening fasta file in a dict with BioPython
|
|
419 SeqDict = SeqIO.to_dict(SeqIO.parse(open(fasta,"r"),"fasta"))
|
|
420
|
|
421 ## count total read in bam file
|
|
422 cmd = "samtools view -c %s " % (bam)
|
|
423 proc = subprocess.Popen( args=cmd, shell=True, stdout = subprocess.PIPE)
|
|
424 count_tot = int(proc.stdout.read().rstrip())
|
|
425 returncode = proc.wait()
|
|
426
|
|
427 ## opening a GFF reader for check overlapping
|
|
428 gff_reader = HTSeq.GFF_Reader(gff)
|
|
429
|
|
430 with open(dirout+"/readthrough_result.csv","w") as out :
|
|
431 myheader = ['Gene','Name', 'FAIL', 'Stop context','chrom','start extension','stop extension','length extension','RPKM CDS', 'RPKM extension','ratio','Annotation','sequence']
|
|
432 writer = csv.writer(out,delimiter='\t')
|
|
433 writer.writerow(myheader)
|
|
434 for gene in GFF['order'] :
|
10
|
435 #print GFF[gene]
|
|
436 ## maybe no start position in GTF file so we must to check and replace
|
|
437 exon_number = GFF[gene]['exon_number']
|
|
438 try : GFF[gene]['start']
|
|
439 except :
|
|
440 if GFF[gene]['strand'] == '+' :
|
|
441 GFF[gene]['start'] = GFF[gene]['exon'][1]['start']
|
|
442 else :
|
|
443 GFF[gene]['start'] = GFF[gene]['exon'][exon_number]['stop']
|
|
444 ## also for stop coordinates
|
|
445 try : GFF[gene]['stop']
|
|
446 except :
|
|
447 if GFF[gene]['strand'] == '+' :
|
|
448 GFF[gene]['stop'] = GFF[gene]['exon'][exon_number]['stop']
|
|
449
|
|
450 else :
|
|
451 GFF[gene]['stop'] = GFF[gene]['exon'][1]['start']
|
|
452
|
|
453
|
6
|
454 indic = ""
|
|
455 # compute rpkm of CDS :
|
|
456 len_cds = GFF[gene]['stop']-GFF[gene]['start']
|
|
457 count_cds = 0
|
10
|
458 rpkm_cds = 0
|
|
459 count_cds = 0
|
|
460 try :
|
|
461 ### count method of pysam doesn't strand information
|
|
462 if GFF[gene]['strand'] == '+' :
|
|
463 for track in aln.fetch(GFF[gene]['chrom'],GFF[gene]['start']+12,GFF[gene]['stop']-15) :
|
|
464 if not track.is_reverse :
|
|
465 count_cds += 1
|
|
466 else :
|
|
467 for track in aln.fetch(GFF[gene]['chrom'],GFF[gene]['start']+15,GFF[gene]['stop']-12) :
|
|
468 if track.is_reverse :
|
|
469 count_cds += 1
|
|
470 rpkm_cds = compute_rpkm(len_cds,count_cds,count_tot)
|
|
471 except ValueError:
|
|
472 ## genere warning about gtf coordinates
|
|
473 #warnings.warn("Please check coordinates in GFF : maybe stop or start codon are missing" )
|
|
474 pass
|
6
|
475 ## Only if gene is translate :
|
|
476 if rpkm_cds > 0 and count_cds > 128:
|
|
477 ## search footprint in UTR3
|
|
478 count = 0
|
|
479 try :
|
|
480 if GFF[gene]['strand'] == '+' :
|
|
481 contexte_stop = str(SeqDict[GFF[gene]['chrom']].seq[GFF[gene]['stop']-6:GFF[gene]['stop']+6])
|
|
482 #print gene, contexte_stop
|
|
483 start_extension = GFF[gene]['stop']
|
|
484 stop_extension = GFF[gene]['stop']+90
|
|
485 for track in aln.fetch(GFF[gene]['chrom'],start_extension+15,stop_extension) :
|
|
486 if not track.is_reverse :
|
|
487 count += 1
|
|
488
|
|
489 ## get sequence of extension
|
|
490 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension:stop_extension])
|
|
491
|
|
492 else :
|
|
493 contexte_stop = str(SeqDict[GFF[gene]['chrom']].seq[GFF[gene]['start']-7:GFF[gene]['start']+5].reverse_complement())
|
|
494 #print gene, contexte_stop
|
|
495 start_extension = GFF[gene]['start']-90
|
|
496 stop_extension = GFF[gene]['start']
|
|
497 for track in aln.fetch(GFF[gene]['chrom'],start_extension,stop_extension-15) :
|
|
498 if track.is_reverse :
|
|
499 count += 1
|
|
500 ## get sequence of extension
|
|
501 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension:stop_extension-1].reverse_complement())
|
10
|
502
|
|
503
|
6
|
504 ## if we have coverage after cds stop codon
|
|
505 if count > 10 :
|
|
506 res = find_stop(seq)
|
|
507 if res == -1 :
|
|
508 '''
|
|
509 Write results with no stop but RPF in extension
|
|
510 '''
|
|
511 ## check if next in-frame codon is far than 90 nt extension :
|
|
512 if GFF[gene]['strand'] == '+' :
|
10
|
513 pos = check_overlapping(gff_reader,GFF[gene]['chrom'],GFF[gene]['stop']+1,GFF[gene]['stop']+extend,'+',GFF[gene]['name'])
|
6
|
514 start_extension = pos[0]-1
|
|
515 stop_extension = pos[1]
|
10
|
516 #start_extension = GFF[gene]['stop']
|
|
517 #stop_extension = GFF[gene]['stop']+extend
|
6
|
518 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension:stop_extension])
|
|
519
|
|
520 #print gene,count,pos,'\n',seq
|
|
521
|
|
522 if (seq):
|
|
523 res = find_stop(seq)
|
|
524 if res == -1 :
|
|
525 mylist = [gene,GFF[gene]['name'],'no stop',contexte_stop, GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,'-','-',GFF[gene]['note'],seq]
|
|
526 writer.writerow(mylist)
|
|
527 else :
|
|
528 indic = 'ok'
|
|
529 #print res
|
|
530 #stop_extension = start_extension + res +3
|
|
531 else :
|
10
|
532 pos = check_overlapping(gff_reader,GFF[gene]['chrom'],GFF[gene]['start']-extend,GFF[gene]['start']-1,'-',GFF[gene]['name'])
|
6
|
533 start_extension = pos[0]
|
|
534 stop_extension = pos[1]+1
|
10
|
535 #start_extension = GFF[gene]['start']-extend
|
|
536 #stop_extension = GFF[gene]['start']
|
6
|
537 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension:stop_extension-1].reverse_complement())
|
|
538
|
|
539 #print gene,count,pos,'\n',seq
|
|
540
|
|
541 if (seq):
|
|
542 res = find_stop(seq)
|
|
543 if res == -1 :
|
|
544 mylist = [gene,GFF[gene]['name'],'no stop',contexte_stop, GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,'-','-',GFF[gene]['note'],seq]
|
|
545 writer.writerow(mylist)
|
|
546 else :
|
|
547 indic = 'ok'
|
|
548 #print res
|
|
549 #start_extension = stop_extension - res -3
|
|
550 else :
|
|
551 indic = 'ok'
|
|
552
|
|
553
|
|
554 if indic == 'ok' :
|
|
555 ## We save new coordinates
|
|
556 if GFF[gene]['strand'] == '+' :
|
|
557 stop_extension = start_extension + res +3
|
|
558 #print gene, count
|
|
559 #print gene,start_extension,stop_extension
|
|
560 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension:stop_extension])
|
|
561 #print seq
|
|
562 count_stop = aln.count(GFF[gene]['chrom'],stop_extension-2,stop_extension+2)
|
|
563 if pass_length(start_extension,stop_extension) :
|
|
564 count_ext = aln.count(GFF[gene]['chrom'],start_extension+9,stop_extension-15)
|
|
565 if stop_extension > GFF[gene]['stop']+9 :
|
|
566 stop_ok = 1
|
|
567 else :
|
|
568 stop_ok = 0
|
|
569 else :
|
|
570 start_extension = stop_extension - res - 3
|
|
571 #print gene, count
|
|
572 #print gene,start_extension,stop_extension
|
|
573 seq = str(SeqDict[GFF[gene]['chrom']].seq[start_extension-1:stop_extension-1].reverse_complement())
|
|
574 #print seq
|
|
575 count_stop = aln.count(GFF[gene]['chrom'],start_extension-2,start_extension+2)
|
|
576 if pass_length(start_extension,stop_extension) :
|
|
577 count_ext = aln.count(GFF[gene]['chrom'],start_extension+15,stop_extension-9)
|
|
578 if start_extension < GFF[gene]['start']-9 :
|
|
579 stop_ok = 1
|
|
580 else :
|
|
581 stop_ok = 0
|
|
582 ## if we are no methionine in 5 codons following stop of CDS
|
|
583 if (not check_met(seq) ):
|
|
584 ## if we have footprint in stop codon extension and stop extension is further than cds_stop+9
|
|
585 if count_stop > 2 and stop_ok == 1 :
|
|
586 homo_cov = check_homo_coverage(gene,GFF,start_extension,stop_extension,aln)
|
|
587 if (homo_cov) :
|
|
588 '''
|
|
589 write result witch corresponding to readthrough
|
|
590 '''
|
|
591 ##if length of extension upper than 25 we can compute rpkm
|
|
592 if (not pass_length(start_extension,stop_extension)) :
|
|
593 len_ext = stop_extension-start_extension
|
|
594 rpkm_ext = 'nan'
|
|
595 ratio = 'nan'
|
|
596 else :
|
|
597 len_ext = stop_extension-start_extension
|
|
598 rpkm_ext = compute_rpkm(len_ext,count_ext,count_tot)
|
|
599 ## compute ratio between extension coverage and cds coverage (rpkm)
|
|
600 ratio = rpkm_ext/rpkm_cds
|
|
601 #print gene,ratio
|
|
602 #print start_extension,stop_extension
|
|
603 mylist = [gene,GFF[gene]['name'],'-',contexte_stop,GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,rpkm_ext,ratio,GFF[gene]['note'],seq]
|
|
604 writer.writerow(mylist)
|
|
605 file_context.write('>'+gene+'\n'+contexte_stop+'\n')
|
|
606 file_extension.write('>'+gene+'\n'+seq+'\n')
|
|
607 else :
|
|
608 '''
|
|
609 write result witch corresponding to readthrough but with no homogeneous coverage
|
|
610 '''
|
|
611 if (not pass_length(start_extension,stop_extension)) :
|
|
612 len_ext = stop_extension-start_extension
|
|
613 rpkm_ext = 'nan'
|
|
614 ratio = 'nan'
|
|
615 else :
|
|
616 len_ext = stop_extension-start_extension
|
|
617 rpkm_ext = compute_rpkm(len_ext,count_ext,count_tot)
|
|
618 ## compute ratio between extension coverage and cds coverage (rpkm)
|
|
619 ratio = rpkm_ext/rpkm_cds
|
|
620 mylist = [gene,GFF[gene]['name'],'hetero cov',contexte_stop, GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,rpkm_ext,ratio,GFF[gene]['note'],seq]
|
|
621 writer.writerow(mylist)
|
|
622 file_context.write('>'+gene+'\n'+contexte_stop+'\n')
|
|
623 file_extension.write('>'+gene+'\n'+seq+'\n')
|
|
624 #print ">"+gene+"\n"+contexte_stop
|
|
625
|
|
626 ## plot gene :
|
|
627 plot_gene(aln, GFF[gene], start_extension, stop_extension, dirout+"/"+gene)
|
|
628
|
|
629
|
|
630
|
|
631 else :
|
|
632 '''
|
|
633 write result with no footprint in stop codon of extension
|
|
634 '''
|
|
635 mylist = [gene,GFF[gene]['name'],'no RPF in stop',contexte_stop, GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,'-','-',GFF[gene]['note'],seq]
|
|
636 writer.writerow(mylist)
|
|
637 file_context.write('>'+gene+'\n'+contexte_stop+'\n')
|
|
638 file_extension.write('>'+gene+'\n'+seq+'\n')
|
|
639 #print ">"+gene+"\n"+contexte_stop
|
|
640 else :
|
|
641 '''
|
|
642 write result with RPF maybe result of reinitiation on a start codon
|
|
643 '''
|
|
644 if pass_length(start_extension,stop_extension) :
|
|
645 mylist = [gene,GFF[gene]['name'],'Met after stop', contexte_stop, GFF[gene]['chrom'], start_extension, stop_extension,stop_extension-start_extension,rpkm_cds,'-','-',GFF[gene]['note'],seq]
|
|
646 writer.writerow(mylist)
|
|
647 file_context.write('>'+gene+'\n'+contexte_stop+'\n')
|
|
648 file_extension.write('>'+gene+'\n'+seq+'\n')
|
|
649 #print ">"+gene+"\n"+contexte_stop
|
|
650 else :
|
|
651 ## if its not a interesting case, we get stop context of genes without readthrough
|
|
652 if GFF[gene]['strand'] == '+' :
|
|
653 contexte_stop = str(SeqDict[GFF[gene]['chrom']].seq[GFF[gene]['stop']-6:GFF[gene]['stop']+6])
|
|
654 file_back.write(contexte_stop+'\n')
|
|
655 else :
|
|
656 contexte_stop = str(SeqDict[GFF[gene]['chrom']].seq[GFF[gene]['start']-7:GFF[gene]['start']+5].reverse_complement())
|
|
657 file_back.write(contexte_stop+'\n')
|
|
658
|
|
659 ## excluded UT with incorrect positions
|
|
660 except ValueError:
|
|
661 pass
|
|
662
|
|
663
|
|
664 file_context.close()
|
|
665 file_back.close()
|
|
666 file_extension.close()
|
|
667 except Exception,e:
|
|
668 stop_err( 'Error during computing analysis : ' + str( e ) )
|
|
669
|
|
670
|
|
671
|
|
672 def write_html_page(html,subfolder) :
|
|
673
|
|
674
|
|
675 try :
|
|
676
|
|
677 gene_table = ''
|
|
678 gene_table += '<table>'
|
|
679 gene_table += '<thead><tr><th data-sort="string">Gene</th><th>Plot</th><th data-sort="string">Name</th><th>Stop context</th><th>Coordinates</th><th>RPKM CDS</th><th>RPKM extension</th><th data-sort="float">ratio</th><th>Extension</th></tr></thead><tbody>'
|
|
680
|
|
681 with open(os.path.join(subfolder,'readthrough_result.csv'), 'rb') as csvfile:
|
|
682 spamreader = csv.reader(csvfile, delimiter='\t')
|
|
683 ## skip the header
|
|
684 next(spamreader, None)
|
15
|
685 ##test if file is empty or not
|
|
686 if next(spamreader, None):
|
|
687 for row in spamreader:
|
|
688 if row[2] == '-' :
|
|
689 gene_table += '<tr><td>%s</td><td><a href="%s.png" data-lightbox="%s"><img src="%s_thumbnail.png" /></a></td><td><a title="%s">%s</a></td><td>%s</td><td>%s:%s-%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' %(row[0], row[0], row[0], row[0], row[11], row[1], row[3], row[4], row[5], row[6], row[8], row[9], row[10], row[12])
|
|
690
|
|
691 gene_table += '</tbody></table>'
|
|
692 else :
|
|
693 gene_table = 'Sorry, there are no stop codon readthrough genes in your data\n'
|
6
|
694
|
|
695
|
|
696 html_str = """
|
|
697 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
698 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
699
|
|
700 <html xmlns="http://www.w3.org/1999/xhtml">
|
|
701 <head>
|
|
702 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
|
|
703 <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
|
|
704 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
|
|
705 <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
|
|
706 <script src="lightbox/js/jquery-1.10.2.min.js"></script>
|
|
707 <script src="lightbox/js/lightbox-2.6.min.js"></script>
|
|
708 <link href="lightbox/css/lightbox.css" rel="stylesheet" />
|
|
709 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
710 <title>Dual coding result file</title>
|
|
711 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
|
|
712 <script>
|
|
713 (function(d){d.fn.stupidtable=function(b){return this.each(function(){var a=d(this);b=b||{};b=d.extend({},d.fn.stupidtable.default_sort_fns,b);var n=function(a,b){for(var f=[],c=0,e=a.slice(0).sort(b),h=0;h<a.length;h++){for(c=d.inArray(a[h],e);-1!=d.inArray(c,f);)c++;f.push(c)}return f},q=function(a,b){for(var d=a.slice(0),c=0,e=0;e<b.length;e++)c=b[e],d[c]=a[e];return d};a.on("click","th",function(){var m=a.children("tbody").children("tr"),g=d(this),f=0,c=d.fn.stupidtable.dir;a.find("th").slice(0, g.index()).each(function(){var a=d(this).attr("colspan")||1;f+=parseInt(a,10)});var e=g.data("sort-default")||c.ASC;g.data("sort-dir")&&(e=g.data("sort-dir")===c.ASC?c.DESC:c.ASC);var h=g.data("sort")||null;null!==h&&(a.trigger("beforetablesort",{column:f,direction:e}),a.css("display"),setTimeout(function(){var l=[],p=b[h];m.each(function(a,b){var c=d(b).children().eq(f),e=c.data("sort-value"),c="undefined"!==typeof e?e:c.text();l.push(c)});var k;k=e==c.ASC?n(l,p):n(l,function(a,b){return-p(a,b)}); a.find("th").data("sort-dir",null).removeClass("sorting-desc sorting-asc");g.data("sort-dir",e).addClass("sorting-"+e);k=d(q(m,k));a.children("tbody").remove();a.append("<tbody />").append(k);a.trigger("aftertablesort",{column:f,direction:e});a.css("display")},10))})})};d.fn.stupidtable.dir={ASC:"asc",DESC:"desc"};d.fn.stupidtable.default_sort_fns={"int":function(b,a){return parseInt(b,10)-parseInt(a,10)},"float":function(b,a){return parseFloat(b)-parseFloat(a)},string:function(b,a){return b<a?-1: b>a?1:0},"string-ins":function(b,a){b=b.toLowerCase();a=a.toLowerCase();return b<a?-1:b>a?1:0}}})(jQuery);
|
|
714 (function($) {
|
|
715
|
|
716 $.fn.stupidtable = function(sortFns) {
|
|
717 return this.each(function() {
|
|
718 var $table = $(this);
|
|
719 sortFns = sortFns || {};
|
|
720
|
|
721 // ==================================================== //
|
|
722 // Utility functions //
|
|
723 // ==================================================== //
|
|
724
|
|
725 // Merge sort functions with some default sort functions.
|
|
726 sortFns = $.extend({}, $.fn.stupidtable.default_sort_fns, sortFns);
|
|
727
|
|
728 // Return the resulting indexes of a sort so we can apply
|
|
729 // this result elsewhere. This returns an array of index numbers.
|
|
730 // return[0] = x means "arr's 0th element is now at x"
|
|
731 var sort_map = function(arr, sort_function) {
|
|
732 var map = [];
|
|
733 var index = 0;
|
|
734 var sorted = arr.slice(0).sort(sort_function);
|
|
735 for (var i=0; i<arr.length; i++) {
|
|
736 index = $.inArray(arr[i], sorted);
|
|
737
|
|
738 // If this index is already in the map, look for the next index.
|
|
739 // This handles the case of duplicate entries.
|
|
740 while ($.inArray(index, map) != -1) {
|
|
741 index++;
|
|
742 }
|
|
743 map.push(index);
|
|
744 }
|
|
745
|
|
746 return map;
|
|
747 };
|
|
748
|
|
749 // Apply a sort map to the array.
|
|
750 var apply_sort_map = function(arr, map) {
|
|
751 var clone = arr.slice(0),
|
|
752 newIndex = 0;
|
|
753 for (var i=0; i<map.length; i++) {
|
|
754 newIndex = map[i];
|
|
755 clone[newIndex] = arr[i];
|
|
756 }
|
|
757 return clone;
|
|
758 };
|
|
759
|
|
760 // ==================================================== //
|
|
761 // Begin execution! //
|
|
762 // ==================================================== //
|
|
763
|
|
764 // Do sorting when THs are clicked
|
|
765 $table.on("click", "th", function() {
|
|
766 var trs = $table.children("tbody").children("tr");
|
|
767 var $this = $(this);
|
|
768 var th_index = 0;
|
|
769 var dir = $.fn.stupidtable.dir;
|
|
770
|
|
771 $table.find("th").slice(0, $this.index()).each(function() {
|
|
772 var cols = $(this).attr("colspan") || 1;
|
|
773 th_index += parseInt(cols,10);
|
|
774 });
|
|
775
|
|
776 // Determine (and/or reverse) sorting direction, default `asc`
|
|
777 var sort_dir = $this.data("sort-default") || dir.ASC;
|
|
778 if ($this.data("sort-dir"))
|
|
779 sort_dir = $this.data("sort-dir") === dir.ASC ? dir.DESC : dir.ASC;
|
|
780
|
|
781 // Choose appropriate sorting function.
|
|
782 var type = $this.data("sort") || null;
|
|
783
|
|
784 // Prevent sorting if no type defined
|
|
785 if (type === null) {
|
|
786 return;
|
|
787 }
|
|
788
|
|
789 // Trigger `beforetablesort` event that calling scripts can hook into;
|
|
790 // pass parameters for sorted column index and sorting direction
|
|
791 $table.trigger("beforetablesort", {column: th_index, direction: sort_dir});
|
|
792 // More reliable method of forcing a redraw
|
|
793 $table.css("display");
|
|
794
|
|
795 // Run sorting asynchronously on a timout to force browser redraw after
|
|
796 // `beforetablesort` callback. Also avoids locking up the browser too much.
|
|
797 setTimeout(function() {
|
|
798 // Gather the elements for this column
|
|
799 var column = [];
|
|
800 var sortMethod = sortFns[type];
|
|
801
|
|
802 // Push either the value of the `data-order-by` attribute if specified
|
|
803 // or just the text() value in this column to column[] for comparison.
|
|
804 trs.each(function(index,tr) {
|
|
805 var $e = $(tr).children().eq(th_index);
|
|
806 var sort_val = $e.data("sort-value");
|
|
807 var order_by = typeof(sort_val) !== "undefined" ? sort_val : $e.text();
|
|
808 column.push(order_by);
|
|
809 });
|
|
810
|
|
811 // Create the sort map. This column having a sort-dir implies it was
|
|
812 // the last column sorted. As long as no data-sort-desc is specified,
|
|
813 // we're free to just reverse the column.
|
|
814 var theMap;
|
|
815 if (sort_dir == dir.ASC)
|
|
816 theMap = sort_map(column, sortMethod);
|
|
817 else
|
|
818 theMap = sort_map(column, function(a, b) { return -sortMethod(a, b); });
|
|
819
|
|
820 // Reset siblings
|
|
821 $table.find("th").data("sort-dir", null).removeClass("sorting-desc sorting-asc");
|
|
822 $this.data("sort-dir", sort_dir).addClass("sorting-"+sort_dir);
|
|
823
|
|
824 var sortedTRs = $(apply_sort_map(trs, theMap));
|
|
825 $table.children("tbody").remove();
|
|
826 $table.append("<tbody />").append(sortedTRs);
|
|
827
|
|
828 // Trigger `aftertablesort` event. Similar to `beforetablesort`
|
|
829 $table.trigger("aftertablesort", {column: th_index, direction: sort_dir});
|
|
830 // More reliable method of forcing a redraw
|
|
831 $table.css("display");
|
|
832 }, 10);
|
|
833 });
|
|
834 });
|
|
835 };
|
|
836
|
|
837 // Enum containing sorting directions
|
|
838 $.fn.stupidtable.dir = {ASC: "asc", DESC: "desc"};
|
|
839
|
|
840 $.fn.stupidtable.default_sort_fns = {
|
|
841 "int": function(a, b) {
|
|
842 return parseInt(a, 10) - parseInt(b, 10);
|
|
843 },
|
|
844 "float": function(a, b) {
|
|
845 return parseFloat(a) - parseFloat(b);
|
|
846 },
|
|
847 "string": function(a, b) {
|
|
848 if (a < b) return -1;
|
|
849 if (a > b) return +1;
|
|
850 return 0;
|
|
851 },
|
|
852 "string-ins": function(a, b) {
|
|
853 a = a.toLowerCase();
|
|
854 b = b.toLowerCase();
|
|
855 if (a < b) return -1;
|
|
856 if (a > b) return +1;
|
|
857 return 0;
|
|
858 }
|
|
859 };
|
|
860
|
|
861 })(jQuery);
|
|
862 $(function(){
|
|
863 var table = $("table").stupidtable();
|
|
864
|
|
865 table.on("beforetablesort", function (event, data) {
|
|
866 // data.column - the index of the column sorted after a click
|
|
867 // data.direction - the sorting direction (either asc or desc)
|
|
868 $("#msg").text("Sorting index " + data.column)
|
|
869 });
|
|
870 table.on("aftertablesort", function (event, data) {
|
|
871 var th = $(this).find("th");
|
|
872 th.find(".arrow").remove();
|
|
873 var dir = $.fn.stupidtable.dir;
|
|
874 var arrow = data.direction === dir.ASC ? "↑" : "↓";
|
|
875 th.eq(data.column).append('<span class="arrow">' + arrow +'</span>');
|
|
876 });
|
|
877 });
|
|
878 </script>
|
|
879 <style type="text/css">
|
|
880 label {
|
|
881 display: inline-block;
|
|
882 width: 5em;
|
|
883 }
|
|
884 table {
|
|
885 border-collapse: collapse;
|
|
886 }
|
|
887 th, td {
|
|
888 padding: 5px 10px;
|
|
889 border: 1px solid #999;
|
|
890 }
|
|
891 th {
|
|
892 background-color: #a7d3ff;
|
|
893 }
|
|
894 th[data-sort]{
|
|
895 cursor:pointer;
|
|
896 }
|
|
897 a[data-lightbox]{
|
|
898 cursor:zoom-in;
|
|
899 }
|
|
900 #msg {
|
|
901 color: green;
|
|
902 }
|
|
903 </style>
|
|
904 </head>
|
|
905 <body>
|
|
906 <h1>Readthrough analyse results</h1>
|
|
907 %s
|
|
908 </body>
|
|
909 </html> """ % (gene_table)
|
|
910
|
|
911 html_file = open(html,"w")
|
|
912 html_file.write(html_str)
|
|
913 html_file.close()
|
|
914
|
|
915
|
|
916 except Exception, e :
|
|
917 stop_err('Error during html page creation : ' + str( e ) )
|
|
918
|
|
919
|
|
920 def __main__():
|
|
921
|
|
922 #Parse command line options
|
|
923 parser = optparse.OptionParser()
|
|
924 parser.add_option("-g", "--gff", dest="gff", type= "string",
|
|
925 help="GFF annotation file", metavar="FILE")
|
|
926
|
|
927 parser.add_option("-f", "--fasta", dest="fasta", type= "string",
|
|
928 help="Fasta file ", metavar="FILE")
|
|
929
|
|
930 parser.add_option("-b", "--bam", dest="bamfile", type= "string",
|
|
931 help="Bam Ribo-Seq alignments ", metavar="FILE")
|
|
932
|
|
933 parser.add_option("-d", "--dirout", dest="dirout", type= "string",
|
10
|
934 help="write report in this html file and in associated directory", metavar="STR,STR")
|
|
935
|
15
|
936 parser.add_option("-e", "--extend", dest="extend", type= "int",default = 300 ,
|
10
|
937 help="Lenght of extension after stop in number of base pairs (depends on your organisme)", metavar="INT")
|
6
|
938
|
|
939 parser.add_option("-q", "--quiet",
|
|
940 action="store_false", dest="verbose", default=True,
|
|
941 help="don't print status messages to stdout")
|
|
942
|
|
943 (options, args) = parser.parse_args()
|
|
944 sys.stdout.write("Begin readthrough analysis at %s\n" % time.asctime( time.localtime(time.time())))
|
|
945
|
|
946 try:
|
|
947 (html_file, subfolder ) = options.dirout.split(",")
|
|
948 if os.path.exists(subfolder):
|
|
949 raise
|
|
950 try:
|
|
951 os.mkdir(subfolder)
|
|
952 except:
|
|
953 raise
|
10
|
954 ## identify GFF or GTF format from 9th column
|
|
955 with open (options.gff,"r") as gffile :
|
|
956 for line in gffile :
|
|
957 if '#' in line :
|
|
958 ## skip header
|
|
959 gffile.next()
|
|
960 elif 'gene_id' in line :
|
|
961 ## launch gtf reader :
|
|
962 GFF = ribo_functions.store_gtf(options.gff)
|
|
963 break
|
|
964 elif 'ID=' in line :
|
|
965 ## launch gff reader
|
|
966 GFF = ribo_functions.store_gff(options.gff)
|
|
967 break
|
|
968 else :
|
|
969 stop_err( 'Please check your annotation file is in correct format, GFF or GTF' )
|
|
970
|
|
971 #GFF = store_gff(options.gff)
|
|
972 #GFF = ribo_functions.store_gtf(options.gff)
|
|
973 ## check gff reading
|
|
974 if not GFF['order'] :
|
13
|
975 stop_err( 'Incorrect GFF file' )
|
|
976 clean_file = ribo_functions.cleaning_bam(options.bamfile)
|
10
|
977 compute_analysis(clean_file, GFF, options.fasta, options.gff, subfolder, options.extend)
|
6
|
978 if os.path.exists( clean_file ):
|
|
979 os.remove( clean_file )
|
|
980
|
|
981 write_html_page(html_file,subfolder)
|
|
982 ##paste jquery script in result directory :
|
|
983 jq_src = os.path.join(os.path.dirname(__file__),'lightbox')
|
|
984 shutil.copytree(jq_src,os.path.join(subfolder,'lightbox'))
|
|
985
|
|
986
|
|
987 sys.stdout.write("Finish readthrough analysis at %s\n" % time.asctime( time.localtime(time.time())))
|
|
988 except Exception, e:
|
|
989 stop_err( 'Error running metagene readthrough analysis : ' + str( e ) )
|
|
990
|
|
991
|
|
992 if __name__=="__main__":
|
|
993 __main__()
|