+ extended documentation
[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,reverse_complement,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 generateTrainingDataset(settings):
24 """
25 This function creates a training dataset.
26 """
27 dataset = []
28
29 saveData('training',dataset,settings)
30
31
32 def addToDataset(map_file,dataset,settings):
33 assert os.path.exists(map_file), 'Error: Can not find map file'
34
35 prb_offset = settings['prb_offset']
36
37 # This tuple specifies an interval for valid Illumina Genome Analyzer quality values
38 if settings['platform'] == 'IGA':
39 quality_interval = illumina_ga_range
40
41 # this means that around each vmatch hit we cut out a window of 1500 bases
42 # each up-/downstream.
43 half_window_size = settings['half_window_size']
44
45 instance_counter = 0
46
47 accessWrapper = DataAccessWrapper(settings)
48 seqInfo = SeqSpliceInfo(accessWrapper,settings['allowed_fragments'])
49
50 for line in open(map_file):
51 if line.startswith('#'):
52 continue
53
54 if instance_counter > 0 and instance_counter % 5000 == 0:
55 print 'processed %d examples' % instance_counter
56
57 slist = line.split()
58
59 id = int(slist[0])
60 chromo = int(slist[1])
61 pos = int(slist[2])
62
63 # for the time being we only consider chromosomes 1-5
64 if not chromo in settings['allowed_fragments']:
65 continue
66
67 # convert D/P strand info to +/-
68 strand = ['-','+'][slist[3] == 'D']
69
70 # QPalma uses lowercase characters
71 bracket_seq = slist[4].lower()
72 read_seq = unbracket_seq(bracket_seq)
73
74 # in prediction we do not have any bracketed reads anymore
75 assert not '[' in read_seq and not ']' in read_seq
76
77 # we use an area of +/- `self.half_window_size` nucleotides around the seed position
78 if pos > half_window_size+1:
79 us_offset = half_window_size
80 else:
81 us_offset = pos - 1
82
83 if pos+half_window_size < seqInfo.getFragmentSize(chromo):
84 ds_offset = half_window_size
85 else:
86 ds_offset = seqInfo.chromo_sizes[chromo]-pos-1
87
88 genomicSeq_start = pos - us_offset
89 genomicSeq_stop = pos + ds_offset
90
91 dna_seq = seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop,True)
92
93 # In order to save some space we use a signed char to store the
94 # qualities. Each quality element can range as follows: -128 <= elem <= 127
95
96 q_values = map(lambda x: ord(x)-prb_offset,slist[5])
97
98 if settings['perform_checks']:
99 for entry in q_values:
100 assert quality_interval[0] <= entry <= quality_interval[1], 'Error: Your read has invalid quality values: %d' % entry
101
102 prb = array.array('b',q_values)
103
104 currentSeqInfo = (id,chromo,strand,genomicSeq_start,genomicSeq_stop)
105 currentQualities = [prb]
106
107 # As one single read can have several vmatch matches we store all these
108 # matches under the unique id of the read
109 dataset.setdefault(id, []).append((currentSeqInfo,read_seq,currentQualities))
110
111 instance_counter += 1
112
113 print 'Total examples processed: %d' % instance_counter
114
115 return dataset
116
117
118 def generatePredictionDataset(settings):
119 """
120 This function is responsible for the prediction dataset generation for the matches of
121 the second vmatch run and the heuristic-filtered matches of the first run.
122
123 An example in our dataset consists of:
124
125 - information on the original read:
126 * id
127 * nucleotide sequence
128 * quality vectors (at the moment: prb and chastity)
129
130 - information on the target dna sequence:
131 * chromosome
132 * strand
133 * fragment start
134 * fragment end positions
135
136 this information is stored in tuples which are stored then in a dictionary
137 indexed by the reads unique id.
138
139 CAUTION: The dictionary stores a list of the above defined tuples under each
140 'id'. This is because one read can be found several times on the genome.
141 """
142
143 dataset = {}
144
145 map_file = settings['spliced_reads_fn']
146 dataset = addToDataset(map_file,dataset,settings)
147
148 map_file = jp(settings['approximation_dir'],'map.vm.spliced')
149 dataset = addToDataset(map_file,dataset,settings)
150
151 saveData('prediction',dataset,settings)
152
153
154 def saveData(prefix,dataset,settings):
155 """
156 """
157
158 if prefix == 'prediction':
159 dataset_fn = settings['prediction_dataset_fn']
160 dataset_keys_fn = settings['prediction_dataset_keys_fn']
161 elif prefix == 'training':
162 dataset_fn = settings['training_dataset_fn']
163 dataset_keys_fn = settings['training_dataset_keys_fn']
164 else:
165 assert False
166
167 #assert not os.path.exists(dataset_fn), 'The data file already exists!'
168 #assert not os.path.exists(dataset_keys_fn), 'The data keys file already exists!'
169
170 # saving new dataset and single keys as well
171 cPickle.dump(dataset,open(dataset_fn,'w+'),protocol=2)
172 cPickle.dump(dataset.keys(),open(dataset_keys_fn,'w+'),protocol=2)