9
|
1 #!/usr/bin/env python2.7
|
|
2
|
|
3 '''
|
|
4 Created on Jan. 2014
|
|
5 @author: rachel legendre
|
|
6 @copyright: rachel.legendre@igmors.u-psud.fr
|
|
7 @license: GPL v3
|
|
8 '''
|
|
9
|
13
|
10 import sys, subprocess, re, commands, time, urllib, tempfile
|
10
|
11 from copy import copy
|
|
12
|
9
|
13
|
|
14 def stop_err( msg ):
|
|
15 sys.stderr.write( "%s\n" % msg )
|
|
16 sys.stderr.write( "Programme aborted at %s\n" % time.asctime(time.localtime(time.time())))
|
|
17 sys.exit()
|
|
18
|
|
19 def split_bam(bamfile,tmpdir):
|
|
20 '''
|
|
21 split bam by chromosome and write sam file in tmpdir
|
|
22 '''
|
|
23 try:
|
|
24 #get header
|
|
25 results = subprocess.check_output(['samtools', 'view', '-H',bamfile])
|
|
26 header = results.split('\n')
|
|
27
|
|
28 #define genome size
|
|
29 genome = []
|
|
30 for line in header:
|
|
31 result = re.search('SN', line)
|
|
32 if result :
|
|
33 #print line
|
|
34 feat = line.split('\t')
|
|
35 chrom = re.split(":", feat[1])
|
|
36 #print feat[1]
|
|
37 genome.append(chrom[1])
|
|
38
|
|
39 #split sam by chrom
|
|
40 n = 0
|
|
41 for chrm in genome:
|
|
42 with open(tmpdir+'/'+chrm+'.sam', 'w') as f :
|
|
43 #write header correctly for each chromosome
|
|
44 f.write(header[0]+'\n')
|
|
45 expr = re.compile(chrm+'\t')
|
|
46 el =[elem for elem in header if expr.search(elem)][0]
|
|
47 f.write(el+'\n')
|
|
48 f.write(header[-2]+'\n')
|
|
49 #write all reads for each chromosome
|
|
50 reads = subprocess.check_output(["samtools", "view", bamfile, chrm])
|
|
51 f.write(reads)
|
|
52 # calculate number of reads
|
|
53 n += reads.count(chrm)
|
|
54
|
|
55 sys.stdout.write("%d reads are presents in your bam file\n" % n)
|
|
56
|
|
57 except Exception, e:
|
|
58 stop_err( 'Error during bam file splitting : ' + str( e ) )
|
|
59
|
|
60
|
|
61
|
|
62 def get_first_base(tmpdir,kmer):
|
|
63 '''
|
|
64 write footprint coverage file for each sam file in tmpdir
|
|
65 '''
|
|
66 global total_mapped_read
|
|
67 try:
|
|
68 file_array = (commands.getoutput('ls '+tmpdir)).split('\n')
|
|
69 ##write coverage for each sam file in tmpdir
|
|
70 for samfile in file_array:
|
|
71 with open(tmpdir+'/'+samfile, 'r') as sam :
|
|
72 ##get chromosome name
|
|
73 chrom = samfile.split(".")[0]
|
|
74
|
|
75 for line in sam:
|
|
76 #initialize dictionnary
|
|
77 if re.search('@SQ', line) :
|
|
78 size = int(line.split('LN:')[1])
|
|
79 genomeF = [0]*size
|
|
80 genomeR = [0]*size
|
|
81 # define multiple reads keys from mapper
|
|
82 elif re.search('@PG', line) :
|
|
83 if re.search('bowtie', line):
|
|
84 multi_tag = "XS:i:"
|
|
85 elif re.search('bwa', line):
|
|
86 multi_tag = "XT:A:R"
|
|
87 else :
|
|
88 stop_err("No PG tag find in"+samfile+". Please use bowtie or bwa for mapping")
|
|
89
|
|
90 # get footprint
|
|
91 elif re.search('^[^@].+', line) :
|
|
92 #print line.rstrip()
|
|
93 read_pos = int(line.split('\t')[3])
|
|
94 read_sens = int(line.split('\t')[1])
|
|
95 #len_read = len(line.split('\t')[9])
|
|
96 if line.split('\t')[5] == kmer+'M' and multi_tag not in line:
|
|
97 ###if line.split('\t')[5] == '28M' :
|
|
98 # print line.rstrip()
|
|
99 total_mapped_read +=1
|
|
100 #if it's a forward read
|
|
101 if read_sens == 0 :
|
|
102 #get P-site : start read + 12 nt
|
|
103 read_pos += 12
|
|
104 genomeF[read_pos] += 1
|
|
105 #if it's a reverse read
|
|
106 elif read_sens == 16 :
|
|
107 #get P-site
|
|
108 read_pos += 15
|
|
109 genomeR[read_pos] += 1
|
|
110
|
|
111 #try:
|
|
112 #write coverage in files
|
|
113 with open(tmpdir+'/assoCov_'+chrom+'.txt', 'w') as cov :
|
|
114 for i in range(0,size):
|
|
115 cov.write(str(genomeF[i])+'\t-'+str(genomeR[i])+'\n')
|
|
116 #except Exception,e:
|
|
117 # stop_err( 'Error during coverage file writting : ' + str( e ) )
|
|
118
|
|
119 sys.stdout.write("%d reads are used for frame analysis\n" % total_mapped_read)
|
|
120 except Exception, e:
|
|
121 stop_err( 'Error during footprinting : ' + str( e ) )
|
|
122
|
|
123 def store_gff(gff):
|
|
124 '''
|
|
125 parse and store gff file in a dictionnary
|
|
126 '''
|
|
127 try:
|
|
128 GFF = {}
|
|
129 with open(gff, 'r') as f_gff :
|
13
|
130
|
9
|
131 GFF['order'] = []
|
13
|
132 #for line in itertools.islice( f_gff, 25 ):
|
9
|
133 for line in f_gff:
|
|
134 ## switch commented lines
|
|
135 line = line.split("#")[0]
|
|
136 if line != "" :
|
|
137 feature = (line.split('\t')[8]).split(';')
|
|
138 # first line is already gene line :
|
|
139 if line.split('\t')[2] == 'gene' :
|
|
140 gene = feature[0].replace("ID=","")
|
13
|
141 if 'Name' in line :
|
|
142 regex = re.compile('(Name=)([^;]*);')
|
|
143 res = regex.search(line.split('\t')[8])
|
|
144 Name = res.group(2)
|
|
145 Name = Name.rstrip()
|
9
|
146 else :
|
|
147 Name = "Unknown"
|
|
148 ##get annotation
|
13
|
149 if 'Note' in line :
|
|
150 regex = re.compile('(Note=)([^;]*);')
|
|
151 res = regex.search(line.split('\t')[8])
|
|
152 note = res.group(2)
|
|
153 note = urllib.unquote(str(note)).replace("\n","")
|
|
154 else :
|
|
155 note = ""
|
9
|
156 ## store gene information
|
|
157 GFF['order'].append(gene)
|
|
158 GFF[gene] = {}
|
|
159 GFF[gene]['chrom'] = line.split('\t')[0]
|
|
160 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
161 GFF[gene]['stop'] = int(line.split('\t')[4])
|
|
162 GFF[gene]['strand'] = line.split('\t')[6]
|
|
163 GFF[gene]['name'] = Name
|
|
164 GFF[gene]['note'] = note
|
|
165 GFF[gene]['exon'] = {}
|
|
166 GFF[gene]['exon_number'] = 0
|
|
167 #print Name
|
|
168 elif line.split('\t')[2] == 'CDS' :
|
13
|
169 regex = re.compile('(Parent=)([^;]*);')
|
|
170 res = regex.search(line.split('\t')[8])
|
|
171 gene = res.group(2)
|
|
172 if 'mRNA' in gene:
|
|
173 gene = re.sub(r"(.*)(\_mRNA)", r"\1", gene)
|
9
|
174 if GFF.has_key(gene) :
|
|
175 GFF[gene]['exon_number'] += 1
|
|
176 exon_number = GFF[gene]['exon_number']
|
|
177 GFF[gene]['exon'][exon_number] = {}
|
|
178 GFF[gene]['exon'][exon_number]['frame'] = line.split('\t')[7]
|
|
179 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
180 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
|
181
|
|
182 ## if there is a five prim UTR intron, we change start of gene
|
13
|
183 elif line.split('\t')[2] == 'five_prime_UTR_intron' :
|
9
|
184 if GFF[gene]['strand'] == "+" :
|
|
185 GFF[gene]['start'] = GFF[gene]['exon'][1]['start']
|
|
186 else :
|
|
187 GFF[gene]['stop'] = GFF[gene]['exon'][exon_number]['stop']
|
|
188 return GFF
|
|
189 except Exception,e:
|
|
190 stop_err( 'Error during gff storage : ' + str( e ) )
|
|
191
|
|
192
|
|
193 #chrI SGD gene 87286 87752 . + . ID=YAL030W;Name=YAL030W;gene=SNC1;Alias=SNC1;Ontology_term=GO:0005484,GO:0005768,GO:0005802,GO:0005886,GO:0005935,GO:0006887,GO:0006893,GO:000689
|
|
194 #7,GO:0006906,GO:0030658,GO:0031201;Note=Vesicle%20membrane%20receptor%20protein%20%28v-SNARE%29%3B%20involved%20in%20the%20fusion%20between%20Golgi-derived%20secretory%20vesicles%20with%20the%20plasma%20membra
|
|
195 #ne%3B%20proposed%20to%20be%20involved%20in%20endocytosis%3B%20member%20of%20the%20synaptobrevin%2FVAMP%20family%20of%20R-type%20v-SNARE%20proteins%3B%20SNC1%20has%20a%20paralog%2C%20SNC2%2C%20that%20arose%20fr
|
|
196 #om%20the%20whole%20genome%20duplication;display=Vesicle%20membrane%20receptor%20protein%20%28v-SNARE%29;dbxref=SGD:S000000028;orf_classification=Verified
|
|
197 #chrI SGD CDS 87286 87387 . + 0 Parent=YAL030W_mRNA;Name=YAL030W_CDS;orf_classification=Verified
|
|
198 #chrI SGD CDS 87501 87752 . + 0 Parent=YAL030W_mRNA;Name=YAL030W_CDS;orf_classification=Verified
|
|
199 #chrI SGD intron 87388 87500 . + . Parent=YAL030W_mRNA;Name=YAL030W_intron;orf_classification=Verified
|
|
200
|
|
201 def store_gtf(gff):
|
|
202 '''
|
10
|
203 parse and store gtf file in a dictionnary
|
9
|
204 '''
|
|
205 try:
|
|
206 GFF = {}
|
|
207 with open(gff, 'r') as f_gff :
|
|
208 GFF['order'] = []
|
|
209 for line in f_gff:
|
|
210 ## switch commented lines
|
|
211 line = line.split("#")[0]
|
|
212 if line != "" :
|
|
213 # first line is already gene line :
|
10
|
214 if 'protein_coding' in line :
|
9
|
215 ##get name
|
13
|
216 gene = re.sub(r".+transcript_id \"([\w|-|\.]+)\";.*", r"\1", line).rstrip()
|
10
|
217 Name = re.sub(r".+gene_name \"([\w|\-|\:|\.|\(|\)]+)\";.*", r"\1", line).rstrip()
|
|
218 if line.split('\t')[2] == 'CDS' :
|
9
|
219 ##if its first time we get this gene
|
|
220 if gene not in GFF.keys() :
|
|
221 ## store gene information
|
|
222 GFF['order'].append(gene)
|
|
223 GFF[gene] = {}
|
|
224 GFF[gene]['chrom'] = line.split('\t')[0]
|
|
225 GFF[gene]['strand'] = line.split('\t')[6]
|
10
|
226 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
227 GFF[gene]['stop'] = int(line.split('\t')[4])
|
9
|
228 GFF[gene]['name'] = Name
|
10
|
229 GFF[gene]['note'] = ""
|
9
|
230 GFF[gene]['exon_number'] = 1
|
|
231 GFF[gene]['exon'] = {}
|
10
|
232 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
|
233 ## some exons are non codant
|
|
234 exon_number = 1
|
9
|
235 GFF[gene]['exon'][exon_number] = {}
|
|
236 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
237 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
|
238 else :
|
|
239 ## we add exon
|
10
|
240 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
|
241 exon_number += 1
|
9
|
242 GFF[gene]['exon_number'] = exon_number
|
|
243 GFF[gene]['exon'][exon_number] = {}
|
|
244 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
245 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
10
|
246 #elif line.split('\t')[2] == 'CDS' :
|
|
247 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
9
|
248 GFF[gene]['exon'][exon_number]['frame'] = line.split('\t')[7]
|
|
249 elif line.split('\t')[2] == 'start_codon' :
|
|
250 if GFF[gene]['strand'] == '-' :
|
10
|
251 GFF[gene]['stop'] = int(line.split('\t')[4])
|
9
|
252 else :
|
|
253 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
254 elif line.split('\t')[2] == 'stop_codon' :
|
|
255 if GFF[gene]['strand'] == '-' :
|
10
|
256 GFF[gene]['start'] = int(line.split('\t')[3])
|
9
|
257 else :
|
|
258 GFF[gene]['stop'] = int(line.split('\t')[4])
|
|
259
|
10
|
260 return __reverse_coordinates__(GFF)
|
9
|
261 except Exception,e:
|
13
|
262 stop_err( 'Error during gtf storage : ' + str( e ) )
|
9
|
263
|
|
264
|
|
265 ##IV protein_coding exon 307766 307789 . - . gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "1"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "RPS16B";
|
|
266 ## exon_id "YDL083C.1";
|
|
267 ##IV protein_coding CDS 307766 307789 . - 0 gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "1"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "RPS16B";
|
|
268 ## protein_id "YDL083C";
|
|
269 ##IV protein_coding start_codon 307787 307789 . - 0 gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "1"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "
|
|
270 ##RPS16B";
|
|
271 ##IV protein_coding exon 306926 307333 . - . gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "2"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "RPS16B";
|
|
272 ## exon_id "YDL083C.2";
|
|
273 ##IV protein_coding CDS 306929 307333 . - 0 gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "2"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "RPS16B";
|
|
274 ## protein_id "YDL083C";
|
|
275 ##IV protein_coding stop_codon 306926 306928 . - 0 gene_id "YDL083C"; transcript_id "YDL083C"; exon_number "2"; gene_name "RPS16B"; gene_biotype "protein_coding"; transcript_name "
|
|
276 ##RPS16B";
|
10
|
277 def __reverse_coordinates__(GFF):
|
|
278
|
|
279 for gene in GFF['order']:
|
|
280 ## for reverse gene
|
|
281 if GFF[gene]['strand'] == "-":
|
|
282 ## if this gene have many exon and the stop of gene is the stop of first (and not last) exon, we reverse exon coordinates
|
|
283 if GFF[gene]['stop'] == GFF[gene]['exon'][1]['stop'] and GFF[gene]['exon_number'] > 1 :
|
|
284 tmp = copy(GFF[gene]['exon'])
|
|
285 exon_number = GFF[gene]['exon_number']
|
|
286 rev_index = exon_number+1
|
|
287 for z in range(1,exon_number+1):
|
|
288 rev_index -= 1
|
|
289 GFF[gene]['exon'][z] = tmp[rev_index]
|
9
|
290
|
10
|
291 ## check start
|
|
292 if GFF[gene]['start'] != GFF[gene]['exon'][1]['start'] and GFF[gene]['start']:
|
|
293 GFF[gene]['exon'][1]['start'] = GFF[gene]['start']
|
9
|
294
|
10
|
295 return GFF
|
|
296
|
9
|
297
|
|
298 def cleaning_bam(bam):
|
|
299 '''
|
|
300 Remove reads unmapped, non uniquely mapped and reads with length lower than 25 and upper than 32, and mapping quality upper than 12
|
|
301 '''
|
|
302 try :
|
|
303 header = subprocess.check_output(['samtools', 'view', '-H', bam], stderr= subprocess.PIPE)
|
|
304 #header = results.split('\n')
|
13
|
305 ## tags by default
|
|
306 multi_tag = "XS:i:"
|
|
307 tag = "IH:i:1"
|
9
|
308 # check mapper for define multiple tag
|
13
|
309 if 'bowtie' in header:
|
9
|
310 multi_tag = "XS:i:"
|
13
|
311 elif 'bwa' in header:
|
9
|
312 multi_tag = "XT:A:R"
|
13
|
313 elif 'TopHat' in header:
|
|
314 tag = "NH:i:1"
|
9
|
315 else :
|
13
|
316 stop_err("No PG tag find in "+samfile+". Please use bowtie, bwa or Tophat for mapping")
|
|
317
|
9
|
318 tmp_sam = tempfile.mktemp()
|
|
319 cmd = "samtools view %s > %s" % (bam, tmp_sam)
|
|
320 proc = subprocess.Popen( args=cmd, shell=True, stderr = subprocess.PIPE)
|
|
321 returncode = proc.wait()
|
|
322
|
|
323
|
|
324 with open(tempfile.mktemp(),'w') as out :
|
|
325 out.write(header)
|
|
326 with open(tmp_sam,'r') as sam :
|
|
327 for line in sam :
|
13
|
328 if (multi_tag not in line or tag in line) and line.split('\t')[1] != '4' and int(line.split('\t')[4]) > 12 :
|
9
|
329 if len(line.split('\t')[9]) < 32 and len(line.split('\t')[9]) > 25 :
|
|
330 out.write(line)
|
|
331 bamfile = tempfile.mktemp()+'.bam'
|
|
332 cmd = "samtools view -hSb %s > %s" % (out.name,bamfile)
|
|
333 proc = subprocess.Popen( args=cmd, shell=True, stderr = subprocess.PIPE)
|
|
334 returncode = proc.wait()
|
|
335
|
|
336 return bamfile
|
|
337
|
|
338 except Exception,e:
|
|
339 stop_err( 'Error during cleaning bam : ' + str( e ) )
|
|
340 |