1d907442c945ef4ef4dde2e6d172177a66f48133
[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 = 64
64 #prb_offset = 50
65
66 # This tuple specifies an interval for valid Illumina Genome Analyzer quality values
67 if settings['platform'] == 'IGA':
68 quality_interval = illumina_ga_range
69
70 # this means that around each vmatch hit we cut out a window of 1500 bases
71 # each up-/downstream.
72 half_window_size = settings['half_window_size']
73
74 instance_counter = 0
75
76 accessWrapper = DataAccessWrapper(settings)
77 seqInfo = SeqSpliceInfo(accessWrapper,settings['allowed_fragments'])
78
79 for line in open(map_file):
80 if line.startswith('#'):
81 continue
82
83 if instance_counter > 0 and instance_counter % 5000 == 0:
84 print 'processed %d examples' % instance_counter
85
86 slist = line.split()
87
88 id = int(slist[0])
89 chromo = int(slist[1])
90 pos = int(slist[2])
91
92 # for the time being we only consider chromosomes 1-5
93 if not chromo in settings['allowed_fragments']:
94 continue
95
96 # convert D/P strand info to +/-
97 strand = ['-','+'][slist[3] == 'D']
98
99 # QPalma uses lowercase characters
100 bracket_seq = slist[4].lower()
101 read_seq = unbracket_seq(bracket_seq)
102
103 # in prediction we do not have any bracketed reads anymore
104 assert not '[' in read_seq and not ']' in read_seq
105
106 # we use an area of +/- `self.half_window_size` nucleotides around the seed position
107 if pos > half_window_size+1:
108 us_offset = half_window_size
109 else:
110 us_offset = pos - 1
111
112 if pos+half_window_size < seqInfo.chromo_sizes[chromo]:
113 ds_offset = half_window_size
114 else:
115 ds_offset = seqInfo.chromo_sizes[chromo]-pos-1
116
117 genomicSeq_start = pos - us_offset
118 genomicSeq_stop = pos + ds_offset
119
120 dna_seq = seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop,True)
121
122 # In order to save some space we use a signed char to store the
123 # qualities. Each quality element can range as follows: -128 <= elem <= 127
124
125 q_values = map(lambda x: ord(x)-prb_offset,slist[5])
126
127 if settings['perform_checks']:
128 for entry in q_values:
129 assert quality_interval[0] <= entry <= quality_interval[1], 'Error: Your read has invalid quality values: %d' % entry
130
131 prb = array.array('b',q_values)
132
133 currentSeqInfo = (id,chromo,strand,genomicSeq_start,genomicSeq_stop)
134 currentQualities = [prb]
135
136 # As one single read can have several vmatch matches we store all these
137 # matches under the unique id of the read
138 dataset.setdefault(id, []).append((currentSeqInfo,read_seq,currentQualities))
139
140 instance_counter += 1
141
142 print 'Total examples processed: %d' % instance_counter
143
144 saveData('prediction',dataset,settings)
145
146
147 def saveData(prefix,dataset,settings):
148 """
149 """
150
151 if prefix == 'prediction':
152 dataset_fn = settings['prediction_dataset_fn']
153 dataset_keys_fn = settings['prediction_dataset_keys_fn']
154 elif prefix == 'training':
155 dataset_fn = settings['training_dataset_fn']
156 dataset_keys_fn = settings['training_dataset_keys_fn']
157 else:
158 assert False
159
160 #assert not os.path.exists(dataset_fn), 'The data file already exists!'
161 #assert not os.path.exists(dataset_keys_fn), 'The data keys file already exists!'
162
163 # saving new dataset and single keys as well
164 cPickle.dump(dataset,open(dataset_fn,'w+'),protocol=2)
165 cPickle.dump(dataset.keys(),open(dataset_keys_fn,'w+'),protocol=2)