+ fixed bug in position calculation for negative strand
[qpalma.git] / scripts / createAlignmentFileFromPrediction.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 import cPickle
5 import math
6 import numpy
7 import os
8 import os.path
9 import pdb
10 import sys
11
12 import qparser
13
14 from Utils import pprint_alignment
15
16 import palma.palma_utils as pu
17 from palma.output_formating import print_results
18
19 from qpalma.sequence_utils import SeqSpliceInfo,DataAccessWrapper
20
21
22 def alignment_reconstruct(current_prediction,num_exons):
23 """
24 We reconstruct the exact alignment to infer the positions of indels and the
25 sizes of the respective exons.
26 """
27 translation = '-acgtn_' # how aligned est and dna sequence is displayed (gap_char, 5 nucleotides, intron_char)
28
29 SpliceAlign = current_prediction['spliceAlign']
30 estAlign = current_prediction['estAlign']
31
32 dna_array = current_prediction['dna_array']
33 read_array = current_prediction['read_array']
34
35 dna_array = "".join(map(lambda x: translation[int(x)],dna_array))
36 read_array = "".join(map(lambda x: translation[int(x)],read_array))
37
38 # this array holds a number for each exon indicating its number of matches
39 exonIdentities = [0]*num_exons
40 exonGaps = [0]*num_exons
41
42 gaps = 0
43 identity = 0
44 idx = 0
45
46 for ridx in range(len(read_array)):
47 read_elem = read_array[ridx]
48 dna_elem = dna_array[ridx]
49
50 if ridx > 0 and read_array[ridx-1] != '_' and read_array[ridx] == '_':
51 idx += 1
52 gaps = 0
53 identity = 0
54
55 if read_elem == '_':
56 continue
57
58 if read_elem == dna_elem:
59 identity += 1
60
61 if read_elem == '-':
62 gaps += 1
63
64 exonIdentities[idx] = identity
65 exonGaps[idx] = gaps
66
67 return exonIdentities,exonGaps
68
69
70 def create_alignment_file(current_loc,out_fname):
71
72 out_fh = open(out_fname,'w+')
73 allPredictions = cPickle.load(open(current_loc))
74 #allPredictions = current_loc
75
76 print 'Loaded %d examples' % len(allPredictions)
77
78 # fetch the data needed
79 g_dir = '/fml/ag-raetsch/share/projects/genomes/A_thaliana_best/genome/'
80 acc_dir = '/fml/ag-raetsch/home/fabio/tmp/interval_query_files/acc'
81 don_dir = '/fml/ag-raetsch/home/fabio/tmp/interval_query_files/don'
82
83 g_fmt = 'chr%d.dna.flat'
84 s_fmt = 'contig_%d%s'
85
86 num_chromo = 6
87
88 accessWrapper = DataAccessWrapper(g_dir,acc_dir,don_dir,g_fmt,s_fmt)
89 seqInfo = SeqSpliceInfo(accessWrapper,range(1,num_chromo))
90
91 # implement uniqueness filtering using alignment score for reads with
92 # several alignments
93
94 #for pred_idx,current_prediction in enumerate(allPredictions):
95
96
97 written_lines = 0
98 for pred_idx,current_prediction in enumerate(allPredictions):
99 id = current_prediction['id']
100
101 #current_ground_truth = qparser.fetch_read(id)
102 #true_cut = current_ground_truth['true_cut']
103 #seq = current_ground_truth['seq']
104 #q1 = current_ground_truth['prb']
105
106 seq = current_prediction['read']
107 dna = current_prediction['dna']
108
109 # CHECK !!!
110 q1 = 'zzz'
111
112 chromo = current_prediction['chr']
113 strand = current_prediction['strand']
114 start_pos = current_prediction['start_pos']
115 alignment = current_prediction['alignment']
116
117 DPScores = current_prediction['DPScores']
118 predExons = current_prediction['predExons']
119 predExons = [e+start_pos for e in predExons]
120
121 (qStart, qEnd, tStart, tEnd, num_exons, qExonSizes, qStarts, qEnds,\
122 tExonSizes,tStarts, tEnds) = alignment
123
124 if len(qExonSizes) != num_exons:
125 print 'BUG exon sizes %d'%id
126 continue
127
128 EST2GFF = False
129 new_line = ''
130
131 if EST2GFF:
132 predExons = numpy.mat(predExons).reshape(len(predExons)/2,2)
133
134 match = predExons[0,1] - predExons[0,0]
135 if predExons.shape == (2,2):
136 match += predExons[1,1] - predExons[1,0]
137
138 mismatch = 0
139 repmatch = 0
140 Ns = 0
141 Qgapcnt = 0
142 Qgapbs = 0
143
144 Tgapcnt = 0
145 Tgapbs = 0
146
147 if predExons.shape == (2,2):
148 Tgapbs += predExons[1,0] - predExons[0,1]
149 Tgapcnt = 1
150
151 # &strand, Qname, &Qsize,
152 # &Qstart, &Qend, Tname, &Tsize,
153 # &Tstart, &Tend, &blockcnt,exonsizes_str,Qstarts_str,Tstarts_str
154 #
155 # ATTENTION
156 #
157 # we enforce equal exons sizes for q and t because we are missing indel
158 # positions of the alignment
159
160 if qExonSizes[0] != tExonSizes[0]:
161 continue
162
163 Qname = '%d(%2.2f)'%(id,DPScores.tolist()[0][0])
164 Qsize = len(seq)
165 Qstart = qStart
166 Qend = qEnd
167 Tname = 'CHR%d'%chromo
168
169 start_pos -= 2
170
171 Tsize = tEnd+1 + start_pos
172 Tstart = tStart + start_pos
173 Tend = tEnd + start_pos
174 blockcnt = Tgapcnt+1
175 exonsizes_str = str(tExonSizes)[1:-1].replace(' ','')
176 Qstarts_str = str(qStarts)[1:-1].replace(' ','')
177 Tstarts_str = str(map(lambda x: x+start_pos,tStarts))[1:-1].replace(' ','')
178
179 new_line = "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%c\t%s\t%d\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n"\
180 % (match, mismatch, repmatch, Ns, Qgapcnt, Qgapbs,\
181 Tgapcnt, Tgapbs, strand, Qname, Qsize, Qstart, Qend,\
182 Tname, Tsize, Tstart, Tend,\
183 blockcnt,exonsizes_str,Qstarts_str,Tstarts_str) #str(predExons))
184
185 else:
186 #try:
187 exonIdentities,exonGaps = alignment_reconstruct(current_prediction,num_exons)
188 #except:
189 # print 'Bug in example %d (idx: %d)' %\
190 # (current_prediction['id'],pred_idx)
191 # continue
192
193 #t_size = tEnd - tStart
194 #read_size = 38
195 #if strand == '-':
196 # total_size = seqInfo.chromo_sizes[chromo]
197
198 # start_pos = total_size - start_pos
199
200 # qExonSizes.reverse()
201 # qStarts = [read_size-e for e in qEnds]
202 # qStarts.reverse()
203 # qEnds = [read_size-e for e in qStarts]
204 # qEnds.reverse()
205
206 # tExonSizes.reverse()
207 # tStarts = [t_size-e for e in tEnds]
208 # tStarts.reverse()
209 # tEnds = [t_size-e for e in tStarts]
210 # tEnds.reverse()
211
212 # exonIdentities.reverse()
213 # exonGaps.reverse()
214
215 pp = lambda x : str(x)[1:-1].replace(' ','')
216
217 new_line = '%d\t%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' %\
218 (id,chromo,strand,seq,str(q1)[1:-1],start_pos,qStart,qEnd,tStart,tEnd,num_exons,\
219 pp(qExonSizes),pp(qStarts),\
220 pp(qEnds),pp(tExonSizes),\
221 pp(tStarts),pp(tEnds),\
222 pp(exonIdentities),pp(exonGaps))
223
224 out_fh.write(new_line)
225 written_lines += 1
226
227 print 'Wrote out %d lines' % written_lines
228
229
230 if __name__ == '__main__':
231 current_dir = sys.argv[1]
232 out_fh = sys.argv[2]
233 create_alignment_file(current_dir,out_fh)