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