64d4d22f36e0e57ab98bcb5c076e3fc2d212bb70
[qpalma.git] / qpalma / DatasetUtils.py
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
5 #
6 # Written (W) 2008 Fabio De Bona
7 # Copyright (C) 2008 Max-Planck-Society
8
9 import array
10 import cPickle
11 import os
12 import os.path
13 import pdb
14
15 from sequence_utils import SeqSpliceInfo,DataAccessWrapper,get_flat_file_size,unbracket_seq,create_bracket_seq,reconstruct_dna_seq
16
17 jp = os.path.join
18
19 illumina_ga_range = (-5,40)
20 #roche_454_range =
21
22
23 def processQuality(raw_qualities,prb_offset,quality_interval,perform_checks):
24 """
25 In order to save some space we use a signed char to store the
26 qualities. Each quality element can range as follows: -128 <= elem <= 127
27 """
28
29 q_values = map(lambda x: ord(x)-prb_offset,raw_qualities)
30
31 if perform_checks:
32 for entry in q_values:
33 assert quality_interval[0] <= entry <= quality_interval[1], 'Error: Your read has invalid quality values: %d' % entry
34
35 return array.array('b',q_values)
36
37
38 def checkExons(dna,exons,readAlignment,exampleKey):
39 """
40
41 """
42
43 fetched_dna_subseq = dna[exons[0,0]:exons[0,1]] + dna[exons[1,0]:exons[1,1]]
44
45 donor_elem = dna[exons[0,1]:exons[0,1]+2]
46 acceptor_elem = dna[exons[1,0]-2:exons[1,0]]
47
48 if not ( donor_elem == 'gt' or donor_elem == 'gc' ):
49 print 'invalid donor in example %d'% exampleKey
50 return False
51
52 if not ( acceptor_elem == 'ag' ):
53 print 'invalid acceptor in example %d'% exampleKey
54 return False
55
56 read = unbracket_seq(readAlignment)
57 read = read.replace('-','')
58
59 assert len(fetched_dna_subseq) == len(read), pdb.set_trace()
60
61 return True
62
63
64 def generateTrainingDataset(settings):
65 """
66 This function creates a training dataset.
67
68
69 Create lower case original ("bracketed") reads
70
71 """
72
73 dataset = []
74
75 half_window_size = settings['half_window_size']
76
77 instance_counter = 0
78
79 accessWrapper = DataAccessWrapper(settings)
80 seqInfo = SeqSpliceInfo(accessWrapper,settings['allowed_fragments'])
81
82 for line in open(map_file):
83 line = line.strip()
84 if line.startswith('#') or line == '':
85 continue
86
87 if instance_counter > 0 and instance_counter % 5000 == 0:
88 print 'processed %d examples' % instance_counter
89
90 slist = line.split()
91
92 id = int(slist[0])
93 chromo = int(slist[1])
94
95 # for the time being we only consider chromosomes 1-5
96 if not chromo in settings['allowed_fragments']:
97 continue
98
99 # convert D/P strand info to +/-
100 strand = ['-','+'][slist[2] == 'D']
101
102 seqBeginning = int(slist[3])
103 seqEnd = int(slist[4])
104
105 readAlignment = slist[5]
106 prb = processQuality(slist[6],prb_offset,quality_intervals,perform_checks)
107
108 exons = numpy.mat([0,0,0,0]).reshape((2,2))
109
110 exons[0,0] = int(slist[7])
111 exons[0,1] = int(slist[8])
112 exons[1,0] = int(slist[9])
113 exons[1,1] = int(slist[10])
114
115 dna = seqInfo.get_seq_and_scores(chr,strand,up_cut,down_cut,only_seq=True)
116 relative_exons = exons - up_cut
117
118 assert checkExons(dna,relative_exons,readAlignment,id)
119
120 dataset.setdefault(id, []).append((currentSeqInfo,readAlignment,[prb],exons))
121
122 saveData('training',dataset,settings)
123
124
125 def addToDataset(map_file,dataset,settings):
126 assert os.path.exists(map_file), 'Error: Can not find map file'
127
128 perform_checks = settings['perform_checks']
129
130 prb_offset = settings['prb_offset']
131
132 # This tuple specifies an interval for valid Illumina Genome Analyzer quality values
133 if settings['platform'] == 'IGA':
134 quality_interval = illumina_ga_range
135
136 # this means that around each vmatch hit we cut out a window of 1500 bases
137 # each up-/downstream.
138 half_window_size = settings['half_window_size']
139
140 instance_counter = 0
141
142 accessWrapper = DataAccessWrapper(settings)
143 seqInfo = SeqSpliceInfo(accessWrapper,settings['allowed_fragments'])
144
145 for line in open(map_file):
146 line = line.strip()
147 if line.startswith('#') or line == '':
148 continue
149
150 if instance_counter > 0 and instance_counter % 5000 == 0:
151 print 'processed %d examples' % instance_counter
152
153 slist = line.split()
154
155 id = int(slist[0])
156 chromo = int(slist[1])
157 pos = int(slist[2])
158
159 # for the time being we only consider chromosomes 1-5
160 if not chromo in settings['allowed_fragments']:
161 continue
162
163 # convert D/P strand info to +/-
164 strand = ['-','+'][slist[3] == 'D']
165
166 # QPalma uses lowercase characters
167 bracket_seq = slist[4].lower()
168 read_seq = unbracket_seq(bracket_seq)
169
170 # in prediction we do not have any bracketed reads anymore
171 assert not '[' in read_seq and not ']' in read_seq
172
173 # we use an area of +/- `self.half_window_size` nucleotides around the seed position
174 if pos > half_window_size+1:
175 us_offset = half_window_size
176 else:
177 us_offset = pos - 1
178
179 if pos+half_window_size < seqInfo.getFragmentSize(chromo):
180 ds_offset = half_window_size
181 else:
182 ds_offset = seqInfo.getFragmentSize(chromo)-pos-1
183
184 genomicSeq_start = pos - us_offset
185 genomicSeq_stop = pos + ds_offset
186
187 dna_seq = seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop,True)
188
189 prb = processQuality(slist[5],prb_offset,quality_interval,perform_checks)
190
191 currentSeqInfo = (id,chromo,strand,genomicSeq_start,genomicSeq_stop)
192
193 # As one single read can have several vmatch matches we store all these
194 # matches under the unique id of the read
195 dataset.setdefault(id, []).append((currentSeqInfo,read_seq,[prb]))
196
197 instance_counter += 1
198
199 print 'Total examples processed: %d' % instance_counter
200
201 return dataset
202
203
204 def generatePredictionDataset(settings):
205 """
206 This function is responsible for the prediction dataset generation for the matches of
207 the second vmatch run and the heuristic-filtered matches of the first run.
208
209 An example in our dataset consists of:
210
211 - information on the original read:
212 * id
213 * nucleotide sequence
214 * quality vectors (at the moment: prb and chastity)
215
216 - information on the target dna sequence:
217 * chromosome
218 * strand
219 * fragment start
220 * fragment end positions
221
222 this information is stored in tuples which are stored then in a dictionary
223 indexed by the reads unique id.
224
225 CAUTION: The dictionary stores a list of the above defined tuples under each
226 'id'. This is because one read can be found several times on the genome.
227 """
228
229 dataset = {}
230
231 map_file = settings['spliced_reads_fn']
232 dataset = addToDataset(map_file,dataset,settings)
233
234 map_file = jp(settings['approximation_dir'],'map.vm.spliced')
235 dataset = addToDataset(map_file,dataset,settings)
236
237 saveData('prediction',dataset,settings)
238
239
240 def saveData(prefix,dataset,settings):
241 """
242 """
243
244 if prefix == 'prediction':
245 dataset_fn = settings['prediction_dataset_fn']
246 dataset_keys_fn = settings['prediction_dataset_keys_fn']
247 elif prefix == 'training':
248 dataset_fn = settings['training_dataset_fn']
249 dataset_keys_fn = settings['training_dataset_keys_fn']
250 else:
251 assert False
252
253 #assert not os.path.exists(dataset_fn), 'The data file already exists!'
254 #assert not os.path.exists(dataset_keys_fn), 'The data keys file already exists!'
255
256 # saving new dataset and single keys as well
257 cPickle.dump(dataset,open(dataset_fn,'w+'),protocol=2)
258 cPickle.dump(dataset.keys(),open(dataset_keys_fn,'w+'),protocol=2)