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