+ changed parameter transfer to support array of plifs
[qpalma.git] / python / qpalma.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 ###########################################################
5 #
6 #
7 #
8 ###########################################################
9
10 import sys
11 import subprocess
12 import scipy.io
13 import pdb
14
15 from numpy.matlib import mat,zeros,ones,inf
16 from numpy.linalg import norm
17
18 import QPalmaDP
19
20 from SIQP_CPX import SIQPSolver
21
22 from paths_load_data import *
23 from paths_load_data_pickle import *
24
25 from computeSpliceWeights import *
26 from set_param_palma import *
27 from computeSpliceAlign import *
28 from penalty_lookup_new import *
29 from compute_donacc import *
30 from TrainingParam import Param
31 from export_param import *
32
33 import Configuration
34
35
36
37 def initializeQualityScoringFunctions(numPlifs,numSuppPoints):
38
39 min_intron_len=20
40 max_intron_len=1000
41 min_svm_score=-5
42 max_svm_score=5
43
44 qualityPlifs = [None]*numPlifs
45
46 for idx in range(numPlifs):
47
48 curPlif = Plf()
49 curPlif.limits = linspace(min_svm_score,max_svm_score,numSuppPoints)
50 curPlif.penalties = [0]*numSuppPoints
51 curPlif.transform = ''
52 curPlif.name = ''
53 curPlif.max_len = 100
54 curPlif.min_len = -100
55 curPlif.id = 1
56 curPlif.use_svm = 0
57 curPlif.next_id = 0
58
59 if idx == 0:
60 curPlif.penalties[0] = 11
61 curPlif.penalties[1] = 22
62 curPlif.penalties[2] = 33
63
64 if idx == 1:
65 curPlif.penalties[0] = 99
66 curPlif.penalties[1] = 100
67 curPlif.penalties[2] = 101
68
69 curPlif = curPlif.convert2SWIG()
70 qualityPlifs[idx] = curPlif
71
72 qualityPlifs = QPalmaDP.createPenaltyArrayFromList(qualityPlifs)
73 return qualityPlifs
74
75 class QPalma:
76 """
77 A training method for the QPalma project
78 """
79
80 def __init__(self):
81 self.ARGS = Param()
82
83 self.logfh = open('qpalma.log','w+')
84 gen_file= '%s/genome.config' % self.ARGS.basedir
85
86 cmd = ['']*4
87 cmd[0] = 'addpath /fml/ag-raetsch/home/fabio/svn/tools/utils'
88 cmd[1] = 'addpath /fml/ag-raetsch/home/fabio/svn/tools/genomes'
89 cmd[2] = 'genome_info = init_genome(\'%s\')' % gen_file
90 cmd[3] = 'save genome_info.mat genome_info'
91 full_cmd = "matlab -nojvm -nodisplay -r \"%s; %s; %s; %s; exit\"" % (cmd[0],cmd[1],cmd[2],cmd[3])
92
93 obj = subprocess.Popen(full_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
94 out,err = obj.communicate()
95 assert err == '', 'An error occured!\n%s'%err
96
97 ginfo = scipy.io.loadmat('genome_info.mat')
98 self.genome_info = ginfo['genome_info']
99
100 self.plog('genome_info.basedir is %s\n'%self.genome_info.basedir)
101
102 self.C=1.0
103
104 # 'normal' means work like Palma
105 # 'using_quality_scores' means work like Palma plus using sequencing
106 # quality scores
107 self.mode = 'normal'
108 #self.mode = 'using_quality_scores'
109
110 # Here we specify the total number of parameters.
111 # When using quality scores our scoring function is defined as
112 #
113 # f: S x R x S -> R
114 #
115 # as opposed to a usage without quality scores when we only have
116 #
117 # f: S x S -> R
118 #
119 self.numDonSuppPoints = 30
120 self.numAccSuppPoints = 30
121 self.numLengthSuppPoints = 30
122 if self.mode == 'normal':
123 self.sizeMMatrix = 36
124 elif self.mode == 'using_quality_scores':
125 self.sizeMMatrix = 728
126 else:
127 assert False, 'Wrong operation mode specified'
128
129 # this number defines the number of support points for one tuple (a,b)
130 # where 'a' comes with a quality score
131 self.numQualSuppPoints = 10
132 self.numQualSuppPoints = 0
133
134 self.numFeatures = self.numDonSuppPoints + self.numAccSuppPoints\
135 + self.numLengthSuppPoints + self.sizeMMatrix
136
137 self.plog('Initializing problem...\n')
138
139
140 def plog(self,string):
141 self.logfh.write(string)
142
143
144 def run(self):
145 # Load the whole dataset
146 #Sequences, Acceptors, Donors, Exons, Ests, Noises = paths_load_data('training',self.genome_info,self.ARGS)
147 Sequences, Acceptors, Donors, Exons, Ests, Noises = paths_load_data_pickle('training',self.genome_info,self.ARGS)
148
149 # number of training instances
150 N = len(Sequences)
151 self.numExamples = N
152 assert N == len(Acceptors) and N == len(Acceptors) and N == len(Exons)\
153 and N == len(Ests), 'The Seq,Accept,Donor,.. arrays are of different lengths'
154 self.plog('Number of training examples: %d\n'% N)
155
156 #iteration_steps = 200 ; #upper bound on iteration steps
157 iteration_steps = 2 ; #upper bound on iteration steps
158
159 remove_duplicate_scores = False
160 print_matrix = False
161 anzpath = 2
162
163 # Initialize parameter vector
164 # param = numpy.matlib.rand(126,1)
165 param = Configuration.fixedParam
166
167 # Set the parameters such as limits penalties for the Plifs
168 [h,d,a,mmatrix] = set_param_palma(param,self.ARGS.train_with_intronlengthinformation)
169
170 # delete splicesite-score-information
171 if not self.ARGS.train_with_splicesitescoreinformation:
172 for i in range(len(Acceptors)):
173 if Acceptors[i] > -20:
174 Acceptors[i] = 1
175 if Donors[i] >-20:
176 Donors[i] = 1
177
178 # Initialize solver
179 if not __debug__:
180 solver = SIQPSolver(self.numFeatures,self.numExamples,self.C,self.logfh)
181
182 # stores the number of alignments done for each example (best path, second-best path etc.)
183 num_path = [anzpath]*N
184 # stores the gap for each example
185 gap = [0.0]*N
186
187 qualityMatrix = zeros((self.numQualSuppPoints,1))
188
189 numPlifs = 24
190 numSuppPoints = 30
191
192 #############################################################################################
193 # Training
194 #############################################################################################
195 self.plog('Starting training...\n')
196
197 iteration_nr = 0
198
199 while True:
200 if iteration_nr == iteration_steps:
201 break
202
203 for exampleIdx in range(self.numExamples):
204 if (exampleIdx%10) == 0:
205 print 'Current example nr %d' % exampleIdx
206
207 dna = Sequences[exampleIdx]
208 est = Ests[exampleIdx]
209
210 exons = Exons[exampleIdx]
211 # NoiseMatrix = Noises[exampleIdx]
212 don_supp = Donors[exampleIdx]
213 acc_supp = Acceptors[exampleIdx]
214
215 # Berechne die Parameter des wirklichen Alignments (but with untrained d,a,h ...)
216 trueSpliceAlign, trueWeightMatch = computeSpliceAlign(dna, exons)
217
218 # Calculate the weights
219 trueWeightDon, trueWeightAcc, trueWeightIntron = computeSpliceWeights(d, a, h, trueSpliceAlign, don_supp, acc_supp)
220 trueWeight = numpy.vstack([trueWeightIntron, trueWeightDon, trueWeightAcc, trueWeightMatch, qualityMatrix ])
221
222 currentPhi = zeros((self.numFeatures,1))
223 currentPhi[0:30] = mat(d.penalties[:]).reshape(30,1)
224 currentPhi[30:60] = mat(a.penalties[:]).reshape(30,1)
225 currentPhi[60:90] = mat(h.penalties[:]).reshape(30,1)
226 currentPhi[90:126] = mmatrix[:]
227 currentPhi[126:] = qualityMatrix[:]
228
229 # Calculate w'phi(x,y) the total score of the alignment
230 trueAlignmentScore = (trueWeight.T * currentPhi)[0,0]
231
232 # The allWeights vector is supposed to store the weight parameter
233 # of the true alignment as well as the weight parameters of the
234 # num_path[exampleIdx] other alignments
235 allWeights = zeros((self.numFeatures,num_path[exampleIdx]+1))
236 allWeights[:,0] = trueWeight[:,0]
237
238 AlignmentScores = [0.0]*(num_path[exampleIdx]+1)
239 AlignmentScores[0] = trueAlignmentScore
240
241 ################## Calculate wrong alignment(s) ######################
242
243 # Compute donor, acceptor with penalty_lookup_new
244 # returns two double lists
245 donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
246
247 #myalign wants the acceptor site on the g of the ag
248 acceptor = acceptor[1:]
249 acceptor.append(-inf)
250
251 dna = str(dna)
252 est = str(est)
253 dna_len = len(dna)
254 est_len = len(est)
255 ps = h.convert2SWIG()
256
257 prb = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
258 chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
259
260 matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
261 mm_len = 36
262
263 d_len = len(donor)
264 donor = QPalmaDP.createDoubleArrayFromList(donor)
265 a_len = len(acceptor)
266 acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
267
268 currentAlignment = QPalmaDP.Alignment()
269 qualityMat = QPalmaDP.createDoubleArrayFromList(qualityMatrix)
270 currentAlignment.setQualityMatrix(qualityMat,self.numQualSuppPoints)
271
272 qualityPlifs = initializeQualityScoringFunctions(numPlifs,numSuppPoints)
273
274 # pdb.set_trace()
275
276 #print 'PYTHON: Calling myalign...'
277 # calculates SpliceAlign, EstAlign, weightMatch, Gesamtscores, dnaest
278 currentAlignment.myalign( num_path[exampleIdx], dna, dna_len,\
279 est, est_len, prb, chastity, ps, matchmatrix, mm_len, donor, d_len,\
280 acceptor, a_len, qualityPlifs, remove_duplicate_scores, print_matrix)
281 #print 'PYTHON: After myalign call...'
282
283 c_SpliceAlign = QPalmaDP.createIntArrayFromList([0]*(dna_len*num_path[exampleIdx]))
284 c_EstAlign = QPalmaDP.createIntArrayFromList([0]*(est_len*num_path[exampleIdx]))
285 c_WeightMatch = QPalmaDP.createIntArrayFromList([0]*(mm_len*num_path[exampleIdx]))
286 c_AlignmentScores = QPalmaDP.createDoubleArrayFromList([.0]*num_path[exampleIdx])
287
288 currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign, c_WeightMatch, c_AlignmentScores)
289 del currentAlignment
290
291 newSpliceAlign = zeros((num_path[exampleIdx]*dna_len,1))
292 newWeightMatch = zeros((num_path[exampleIdx]*mm_len,1))
293
294 print 'spliceAlign'
295 for i in range(dna_len*num_path[exampleIdx]):
296 newSpliceAlign[i] = c_SpliceAlign[i]
297 # print '%f' % (spliceAlign[i])
298
299 print 'weightMatch'
300 for i in range(mm_len*num_path[exampleIdx]):
301 newWeightMatch[i] = c_WeightMatch[i]
302 # print '%f' % (weightMatch[i])
303
304 for i in range(num_path[exampleIdx]):
305 AlignmentScores[i+1] = c_AlignmentScores[i]
306
307 newSpliceAlign = newSpliceAlign.reshape(num_path[exampleIdx],dna_len)
308 newWeightMatch = newWeightMatch.reshape(num_path[exampleIdx],mm_len)
309 # Calculate weights of the respective alignments Note that we are
310 # calculating n-best alignments without any hamming loss, so we
311 # have to keep track which of the n-best alignments correspond to
312 # the true one in order not to incorporate a true alignment in the
313 # constraints. To keep track of the true and false alignments we
314 # define an array true_map with a boolean indicating the
315 # equivalence to the true alignment for each decoded alignment.
316 true_map = [0]*(num_path[exampleIdx]+1)
317 true_map[0] = 1
318 path_loss = [0]*(num_path[exampleIdx]+1)
319
320 for pathNr in range(num_path[exampleIdx]):
321 #dna_numbers = dnaest{1,pathNr}
322 #est_numbers = dnaest{2,pathNr}
323
324 weightDon, weightAcc, weightIntron = computeSpliceWeights(d, a, h, newSpliceAlign[pathNr,:].flatten().tolist()[0], don_supp, acc_supp)
325
326 # sum up positionwise loss between alignments
327 for alignPosIdx in range(len(newSpliceAlign[pathNr,:])):
328 if newSpliceAlign[pathNr,alignPosIdx] != trueSpliceAlign[alignPosIdx]:
329 path_loss[pathNr+1] += 1
330
331 # Gewichte in restliche Zeilen der Matrix speichern
332 wp = numpy.vstack([weightIntron, weightDon, weightAcc, newWeightMatch[pathNr,:].T, qualityMatrix ])
333 allWeights[:,pathNr+1] = wp
334
335 hpen = mat(h.penalties).reshape(len(h.penalties),1)
336 dpen = mat(d.penalties).reshape(len(d.penalties),1)
337 apen = mat(a.penalties).reshape(len(a.penalties),1)
338
339 features = numpy.vstack([hpen , dpen , apen , mmatrix[:]])
340 AlignmentScores[pathNr+1] = (allWeights[:,pathNr+1].T * features)[0,0]
341
342 # Check wether scalar product + loss equals viterbi score
343 #assert math.fabs(newAlignmentScores[pathNr] - AlignmentScores[pathNr+1]) < 1e-6,\
344 #'Scalar prod + loss is not equal Viterbi score. Respective values are %f, %f' % \
345 #(newAlignmentScores[pathNr],AlignmentScores[pathNr+1])
346
347 # # if the pathNr-best alignment is very close to the true alignment consider it as true
348 if norm( allWeights[:,0] - allWeights[:,pathNr+1] ) < 1e-5:
349 true_map[pathNr+1] = 1
350
351 # the true label sequence should not have a larger score than the maximal one WHYYYYY?
352
353 # this means that all n-best paths are to close to each other
354 # we have to extend the n-best search to a (n+1)-best
355 if len([elem for elem in true_map if elem == 1]) == len(true_map):
356 num_path[exampleIdx] = num_path[exampleIdx]+1
357
358 # Choose true and first false alignment for extending A
359 firstFalseIdx = -1
360 for map_idx,elem in enumerate(true_map):
361 if elem == 0:
362 firstFalseIdx = map_idx
363 break
364
365 # if there is at least one useful false alignment add the
366 # corresponding constraints to the optimization problem
367 if firstFalseIdx != -1:
368 trueWeights = allWeights[:,0]
369 firstFalseWeights = allWeights[:,firstFalseIdx]
370
371 # LMM.py code:
372 deltas = firstFalseWeights - trueWeights
373 if not __debug__:
374 const_added = solver.addConstraint(deltas, exampleIdx)
375 objValue,w,self.slacks = solver.solve()
376
377 sum_xis = 0
378 for elem in self.slacks:
379 sum_xis += elem
380
381 for i in range(len(param)):
382 param[i] = w[i]
383
384 [h,d,a,mmatrix] = set_param_palma(param,self.ARGS.train_with_intronlengthinformation)
385
386 #
387 # end of one example processing
388 #
389 #if exampleIdx == 100:
390 # break
391
392 #break
393
394 #
395 # end of one iteration through all examples
396 #
397 iteration_nr += 1
398
399 #
400 # end of optimization
401 #
402 export_param('elegans.param',h,d,a,mmatrix)
403 self.logfh.close()
404 print 'Training completed'
405
406 if __name__ == '__main__':
407 qpalma = QPalma()
408 qpalma.run()