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
|
|
10 import sys, subprocess, re, commands, time, urllib
|
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 :
|
|
130 GFF['order'] = []
|
|
131 for line in f_gff:
|
|
132 ## switch commented lines
|
|
133 line = line.split("#")[0]
|
|
134 if line != "" :
|
|
135 feature = (line.split('\t')[8]).split(';')
|
|
136 # first line is already gene line :
|
|
137 if line.split('\t')[2] == 'gene' :
|
|
138 gene = feature[0].replace("ID=","")
|
|
139 if re.search('gene',feature[2]) :
|
|
140 Name = feature[2].replace("gene=","")
|
|
141 else :
|
|
142 Name = "Unknown"
|
|
143 ##get annotation
|
|
144 note = re.sub(r".+\;Note\=(.+)\;display\=.+", r"\1", line)
|
|
145 note = urllib.unquote(str(note)).replace("\n","")
|
|
146 ## store gene information
|
|
147 GFF['order'].append(gene)
|
|
148 GFF[gene] = {}
|
|
149 GFF[gene]['chrom'] = line.split('\t')[0]
|
|
150 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
151 GFF[gene]['stop'] = int(line.split('\t')[4])
|
|
152 GFF[gene]['strand'] = line.split('\t')[6]
|
|
153 GFF[gene]['name'] = Name
|
|
154 GFF[gene]['note'] = note
|
|
155 GFF[gene]['exon'] = {}
|
|
156 GFF[gene]['exon_number'] = 0
|
|
157 #print Name
|
|
158 elif line.split('\t')[2] == 'CDS' :
|
10
|
159 gene = re.sub(r".?Parent\=(.+)\_mRNA?", r"\1", feature[0])
|
9
|
160 if GFF.has_key(gene) :
|
|
161 GFF[gene]['exon_number'] += 1
|
|
162 exon_number = GFF[gene]['exon_number']
|
|
163 GFF[gene]['exon'][exon_number] = {}
|
|
164 GFF[gene]['exon'][exon_number]['frame'] = line.split('\t')[7]
|
|
165 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
166 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
|
167
|
|
168 ## if there is a five prim UTR intron, we change start of gene
|
|
169 elif line.split('\t')[2] == 'five_prime_UTR_intron' :
|
|
170 if GFF[gene]['strand'] == "+" :
|
|
171 GFF[gene]['start'] = GFF[gene]['exon'][1]['start']
|
|
172 else :
|
|
173 GFF[gene]['stop'] = GFF[gene]['exon'][exon_number]['stop']
|
|
174 return GFF
|
|
175 except Exception,e:
|
|
176 stop_err( 'Error during gff storage : ' + str( e ) )
|
|
177
|
|
178
|
|
179 #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
|
|
180 #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
|
|
181 #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
|
|
182 #om%20the%20whole%20genome%20duplication;display=Vesicle%20membrane%20receptor%20protein%20%28v-SNARE%29;dbxref=SGD:S000000028;orf_classification=Verified
|
|
183 #chrI SGD CDS 87286 87387 . + 0 Parent=YAL030W_mRNA;Name=YAL030W_CDS;orf_classification=Verified
|
|
184 #chrI SGD CDS 87501 87752 . + 0 Parent=YAL030W_mRNA;Name=YAL030W_CDS;orf_classification=Verified
|
|
185 #chrI SGD intron 87388 87500 . + . Parent=YAL030W_mRNA;Name=YAL030W_intron;orf_classification=Verified
|
|
186
|
|
187 def store_gtf(gff):
|
|
188 '''
|
10
|
189 parse and store gtf file in a dictionnary
|
9
|
190 '''
|
|
191 try:
|
|
192 GFF = {}
|
|
193 with open(gff, 'r') as f_gff :
|
|
194 GFF['order'] = []
|
|
195 for line in f_gff:
|
|
196 ## switch commented lines
|
|
197 line = line.split("#")[0]
|
|
198 if line != "" :
|
|
199 # first line is already gene line :
|
10
|
200 if 'protein_coding' in line :
|
9
|
201 ##get name
|
10
|
202 gene = re.sub(r".+transcript_id \"([\w|-]+)\";.*", r"\1", line).rstrip()
|
|
203 Name = re.sub(r".+gene_name \"([\w|\-|\:|\.|\(|\)]+)\";.*", r"\1", line).rstrip()
|
|
204 if line.split('\t')[2] == 'CDS' :
|
9
|
205 ##if its first time we get this gene
|
|
206 if gene not in GFF.keys() :
|
|
207 ## store gene information
|
|
208 GFF['order'].append(gene)
|
|
209 GFF[gene] = {}
|
|
210 GFF[gene]['chrom'] = line.split('\t')[0]
|
|
211 GFF[gene]['strand'] = line.split('\t')[6]
|
10
|
212 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
213 GFF[gene]['stop'] = int(line.split('\t')[4])
|
9
|
214 GFF[gene]['name'] = Name
|
10
|
215 GFF[gene]['note'] = ""
|
9
|
216 GFF[gene]['exon_number'] = 1
|
|
217 GFF[gene]['exon'] = {}
|
10
|
218 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
|
219 ## some exons are non codant
|
|
220 exon_number = 1
|
9
|
221 GFF[gene]['exon'][exon_number] = {}
|
|
222 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
223 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
|
224 else :
|
|
225 ## we add exon
|
10
|
226 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
|
227 exon_number += 1
|
9
|
228 GFF[gene]['exon_number'] = exon_number
|
|
229 GFF[gene]['exon'][exon_number] = {}
|
|
230 GFF[gene]['exon'][exon_number]['start'] = int(line.split('\t')[3])
|
|
231 GFF[gene]['exon'][exon_number]['stop'] = int(line.split('\t')[4])
|
10
|
232 #elif line.split('\t')[2] == 'CDS' :
|
|
233 #exon_number = int(re.sub(r".+exon_number \"(\d+)\".+", r"\1",line).rstrip())
|
9
|
234 GFF[gene]['exon'][exon_number]['frame'] = line.split('\t')[7]
|
|
235 elif line.split('\t')[2] == 'start_codon' :
|
|
236 if GFF[gene]['strand'] == '-' :
|
10
|
237 GFF[gene]['stop'] = int(line.split('\t')[4])
|
9
|
238 else :
|
|
239 GFF[gene]['start'] = int(line.split('\t')[3])
|
|
240 elif line.split('\t')[2] == 'stop_codon' :
|
|
241 if GFF[gene]['strand'] == '-' :
|
10
|
242 GFF[gene]['start'] = int(line.split('\t')[3])
|
9
|
243 else :
|
|
244 GFF[gene]['stop'] = int(line.split('\t')[4])
|
|
245
|
10
|
246 return __reverse_coordinates__(GFF)
|
9
|
247 except Exception,e:
|
|
248 stop_err( 'Error during gff storage : ' + str( e ) )
|
|
249
|
|
250
|
|
251 ##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";
|
|
252 ## exon_id "YDL083C.1";
|
|
253 ##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";
|
|
254 ## protein_id "YDL083C";
|
|
255 ##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 "
|
|
256 ##RPS16B";
|
|
257 ##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";
|
|
258 ## exon_id "YDL083C.2";
|
|
259 ##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";
|
|
260 ## protein_id "YDL083C";
|
|
261 ##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 "
|
|
262 ##RPS16B";
|
10
|
263 def __reverse_coordinates__(GFF):
|
|
264
|
|
265 for gene in GFF['order']:
|
|
266 ## for reverse gene
|
|
267 if GFF[gene]['strand'] == "-":
|
|
268 ## if this gene have many exon and the stop of gene is the stop of first (and not last) exon, we reverse exon coordinates
|
|
269 if GFF[gene]['stop'] == GFF[gene]['exon'][1]['stop'] and GFF[gene]['exon_number'] > 1 :
|
|
270 tmp = copy(GFF[gene]['exon'])
|
|
271 exon_number = GFF[gene]['exon_number']
|
|
272 rev_index = exon_number+1
|
|
273 for z in range(1,exon_number+1):
|
|
274 rev_index -= 1
|
|
275 GFF[gene]['exon'][z] = tmp[rev_index]
|
9
|
276
|
10
|
277 ## check start
|
|
278 if GFF[gene]['start'] != GFF[gene]['exon'][1]['start'] and GFF[gene]['start']:
|
|
279 GFF[gene]['exon'][1]['start'] = GFF[gene]['start']
|
9
|
280
|
10
|
281 return GFF
|
|
282
|
9
|
283
|
|
284 def cleaning_bam(bam):
|
|
285 '''
|
|
286 Remove reads unmapped, non uniquely mapped and reads with length lower than 25 and upper than 32, and mapping quality upper than 12
|
|
287 '''
|
|
288 try :
|
|
289 header = subprocess.check_output(['samtools', 'view', '-H', bam], stderr= subprocess.PIPE)
|
|
290 #header = results.split('\n')
|
|
291
|
|
292 # check mapper for define multiple tag
|
|
293 if re.search('bowtie', header):
|
|
294 multi_tag = "XS:i:"
|
|
295 elif re.search('bwa', header):
|
|
296 multi_tag = "XT:A:R"
|
|
297 else :
|
|
298 stop_err("No PG tag find in"+bam+". Please use bowtie or bwa for mapping")
|
|
299
|
|
300 tmp_sam = tempfile.mktemp()
|
|
301 cmd = "samtools view %s > %s" % (bam, tmp_sam)
|
|
302 proc = subprocess.Popen( args=cmd, shell=True, stderr = subprocess.PIPE)
|
|
303 returncode = proc.wait()
|
|
304
|
|
305
|
|
306 with open(tempfile.mktemp(),'w') as out :
|
|
307 out.write(header)
|
|
308 with open(tmp_sam,'r') as sam :
|
|
309 for line in sam :
|
|
310 if multi_tag not in line and line.split('\t')[1] != '4' and int(line.split('\t')[4]) > 12 :
|
|
311 if len(line.split('\t')[9]) < 32 and len(line.split('\t')[9]) > 25 :
|
|
312 out.write(line)
|
|
313 bamfile = tempfile.mktemp()+'.bam'
|
|
314 cmd = "samtools view -hSb %s > %s" % (out.name,bamfile)
|
|
315 proc = subprocess.Popen( args=cmd, shell=True, stderr = subprocess.PIPE)
|
|
316 returncode = proc.wait()
|
|
317
|
|
318 return bamfile
|
|
319
|
|
320 except Exception,e:
|
|
321 stop_err( 'Error during cleaning bam : ' + str( e ) )
|
|
322 |