+ adapted training method to use new dataset standard
[qpalma.git] / scripts / qpalma_main.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 ###########################################################
5 #
6 # The QPalma project aims at extending the Palma project
7 # to be able to use Solexa reads together with their
8 # quality scores.
9 #
10 # This file represents the conversion of the main matlab
11 # training loop for Palma to Python.
12 #
13 # Author: Fabio De Bona
14 #
15 ###########################################################
16
17 import sys
18 import cPickle
19 import pdb
20 import re
21 import os.path
22
23 from compile_dataset import getSpliceScores, get_seq_and_scores
24
25 import numpy
26 from numpy.matlib import mat,zeros,ones,inf
27 from numpy.linalg import norm
28
29 import QPalmaDP
30 import qpalma
31
32 from qpalma.SIQP_CPX import SIQPSolver
33 #from qpalma.SIQP_CVXOPT import SIQPSolver
34
35 from qpalma.DataProc import *
36 from qpalma.computeSpliceWeights import *
37 from qpalma.set_param_palma import *
38 from qpalma.computeSpliceAlignWithQuality import *
39 from qpalma.penalty_lookup_new import *
40 from qpalma.compute_donacc import *
41 from qpalma.TrainingParam import Param
42 from qpalma.Plif import Plf
43
44 from qpalma.Configuration import *
45
46 # this two imports are needed for the load genomic resp. interval query
47 # functions
48 from Genefinding import *
49 from genome_utils import load_genomic
50 from Utils import calc_stat, calc_info, pprint_alignment, get_alignment
51
52 class SpliceSiteException:
53 pass
54
55
56 def unbracket_est(est):
57 new_est = ''
58 e = 0
59
60 while True:
61 if e >= len(est):
62 break
63
64 if est[e] == '[':
65 new_est += est[e+2]
66 e += 4
67 else:
68 new_est += est[e]
69 e += 1
70
71 return "".join(new_est).lower()
72
73
74 def getData(training_set,exampleKey,run):
75 currentSeqInfo,currentExons,original_est,currentQualities = training_set[exampleKey]
76 id,chr,strand,up_cut,down_cut = currentSeqInfo
77
78 est = original_est
79 est = "".join(est)
80 est = est.lower()
81 est = unbracket_est(est)
82 est = est.replace('-','')
83
84 assert len(est) == run['read_size'], pdb.set_trace()
85 est_len = len(est)
86
87 #original_est = OriginalEsts[exampleIdx]
88 original_est = "".join(original_est)
89 original_est = original_est.lower()
90
91 dna_flat_files = '/fml/ag-raetsch/share/projects/genomes/A_thaliana_best/genome/'
92 dna, acc_supp, don_supp = get_seq_and_scores(chr,strand,up_cut,down_cut,dna_flat_files)
93
94 # splice score is located at g of ag
95 ag_tuple_pos = [p for p,e in enumerate(dna) if p>1 and dna[p-1]=='a' and dna[p]=='g' ]
96 assert ag_tuple_pos == [p for p,e in enumerate(acc_supp) if e != -inf and p > 1], pdb.set_trace()
97
98 gt_tuple_pos = [p for p,e in enumerate(dna) if p>0 and p<len(dna)-1 and e=='g' and (dna[p+1]=='t' or dna[p+1]=='c')]
99 assert gt_tuple_pos == [p for p,e in enumerate(don_supp) if e != -inf and p > 0], pdb.set_trace()
100
101 #original_exons = Exons[exampleIdx]
102 original_exons = currentExons
103 exons = original_exons - (up_cut-1)
104 exons[0,0] -= 1
105 exons[1,0] -= 1
106
107 if exons.shape == (2,2):
108 fetched_dna_subseq = dna[exons[0,0]:exons[0,1]] + dna[exons[1,0]:exons[1,1]]
109
110 donor_elem = dna[exons[0,1]:exons[0,1]+2]
111 acceptor_elem = dna[exons[1,0]-2:exons[1,0]]
112
113 if not ( donor_elem == 'gt' or donor_elem == 'gc' ):
114 print 'invalid donor in example %d'% exampleKey
115 raise SpliceSiteException
116
117 if not ( acceptor_elem == 'ag' ):
118 print 'invalid acceptor in example %d'% exampleKey
119 raise SpliceSiteException
120
121 assert len(fetched_dna_subseq) == len(est), pdb.set_trace()
122
123 return dna,est,acc_supp,don_supp,exons,original_est,currentQualities
124
125
126
127 class QPalma:
128 """
129 This class wraps the training and prediction functions for
130 the alignment.
131 """
132
133 def __init__(self):
134 self.ARGS = Param()
135
136
137 def plog(self,string):
138 self.logfh.write(string)
139 self.logfh.flush()
140
141
142 def do_alignment(self,dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,current_num_path,prediction_mode):
143 """
144 Given the needed input this method calls the QPalma C module which
145 calculates a dynamic programming in order to obtain an alignment
146 """
147 run = self.run
148
149 dna_len = len(dna)
150 est_len = len(est)
151
152 prb = QPalmaDP.createDoubleArrayFromList(quality)
153 chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
154
155 matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
156 mm_len = run['matchmatrixRows']*run['matchmatrixCols']
157
158 d_len = len(donor)
159 donor = QPalmaDP.createDoubleArrayFromList(donor)
160 a_len = len(acceptor)
161 acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
162
163 # Create the alignment object representing the interface to the C/C++ code.
164 currentAlignment = QPalmaDP.Alignment(run['numQualPlifs'],run['numQualSuppPoints'], self.use_quality_scores)
165 c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList([elem.convert2SWIG() for elem in qualityPlifs])
166 # calculates SpliceAlign, EstAlign, weightMatch, Gesamtscores, dnaest
167 currentAlignment.myalign( current_num_path, dna, dna_len,\
168 est, est_len, prb, chastity, ps, matchmatrix, mm_len, donor, d_len,\
169 acceptor, a_len, c_qualityPlifs, remove_duplicate_scores,
170 print_matrix)
171
172 c_SpliceAlign = QPalmaDP.createIntArrayFromList([0]*(dna_len*current_num_path))
173 c_EstAlign = QPalmaDP.createIntArrayFromList([0]*(est_len*current_num_path))
174 c_WeightMatch = QPalmaDP.createIntArrayFromList([0]*(mm_len*current_num_path))
175 c_DPScores = QPalmaDP.createDoubleArrayFromList([.0]*current_num_path)
176
177 c_qualityPlifsFeatures = QPalmaDP.createDoubleArrayFromList([.0]*(run['totalQualSuppPoints']*current_num_path))
178
179 if prediction_mode:
180 # part that is only needed for prediction
181 result_len = currentAlignment.getResultLength()
182 c_dna_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
183 c_est_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
184
185 currentAlignment.getAlignmentArrays(c_dna_array,c_est_array)
186
187 dna_array = [0.0]*result_len
188 est_array = [0.0]*result_len
189
190 for r_idx in range(result_len):
191 dna_array[r_idx] = c_dna_array[r_idx]
192 est_array[r_idx] = c_est_array[r_idx]
193
194 else:
195 dna_array = None
196 est_array = None
197
198 currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign,\
199 c_WeightMatch, c_DPScores, c_qualityPlifsFeatures)
200
201 newSpliceAlign = zeros((current_num_path*dna_len,1))
202 newEstAlign = zeros((est_len*current_num_path,1))
203 newWeightMatch = zeros((current_num_path*mm_len,1))
204 newDPScores = zeros((current_num_path,1))
205 newQualityPlifsFeatures = zeros((run['totalQualSuppPoints']*current_num_path,1))
206
207 for i in range(dna_len*current_num_path):
208 newSpliceAlign[i] = c_SpliceAlign[i]
209
210 for i in range(est_len*current_num_path):
211 newEstAlign[i] = c_EstAlign[i]
212
213 for i in range(mm_len*current_num_path):
214 newWeightMatch[i] = c_WeightMatch[i]
215
216 for i in range(current_num_path):
217 newDPScores[i] = c_DPScores[i]
218
219 if self.use_quality_scores:
220 for i in range(run['totalQualSuppPoints']*current_num_path):
221 newQualityPlifsFeatures[i] = c_qualityPlifsFeatures[i]
222
223 del c_SpliceAlign
224 del c_EstAlign
225 del c_WeightMatch
226 del c_DPScores
227 del c_qualityPlifsFeatures
228 del currentAlignment
229
230 return newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
231 newQualityPlifsFeatures, dna_array, est_array
232
233
234 def train(self,run,training_set):
235 self.run = run
236
237 full_working_path = os.path.join(run['alignment_dir'],run['name'])
238
239 #assert not os.path.exists(full_working_path)
240 if not os.path.exists(full_working_path):
241 os.mkdir(full_working_path)
242
243 assert os.path.exists(full_working_path)
244
245 # ATTENTION: Changing working directory
246 os.chdir(full_working_path)
247
248 self.logfh = open('_qpalma_train.log','w+')
249
250 self.plog("Settings are:\n")
251 self.plog("%s\n"%str(run))
252
253 if self.run['mode'] == 'normal':
254 self.use_quality_scores = False
255
256 elif self.run['mode'] == 'using_quality_scores':
257 self.use_quality_scores = True
258 else:
259 assert(False)
260
261 numExamples = len(training_set)
262 self.plog('Number of training examples: %d\n'% numExamples)
263
264 self.noImprovementCtr = 0
265 self.oldObjValue = 1e8
266
267 iteration_steps = run['iter_steps']
268 remove_duplicate_scores = run['remove_duplicate_scores']
269 print_matrix = run['print_matrix']
270 anzpath = run['anzpath']
271
272 # Initialize parameter vector /
273 #param = Conf.fixedParam[:run['numFeatures']]
274 param = numpy.matlib.rand(run['numFeatures'],1)
275
276 lengthSP = run['numLengthSuppPoints']
277 donSP = run['numDonSuppPoints']
278 accSP = run['numAccSuppPoints']
279 mmatrixSP = run['matchmatrixRows']*run['matchmatrixCols']
280 numq = run['numQualSuppPoints']
281 totalQualSP = run['totalQualSuppPoints']
282
283 # no intron length model
284 if not run['enable_intron_length']:
285 param[:lengthSP] *= 0.0
286
287 # Set the parameters such as limits penalties for the Plifs
288 [h,d,a,mmatrix,qualityPlifs] = set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
289
290 # Initialize solver
291 self.plog('Initializing problem...\n')
292
293 try:
294 solver = SIQPSolver(run['numFeatures'],numExamples,run['C'],self.logfh,run)
295 except:
296 self.plog('Got no license. Telling queue to reschedule job...\n')
297 sys.exit(99)
298
299 #solver.enforceMonotonicity(lengthSP,lengthSP+donSP)
300 #solver.enforceMonotonicity(lengthSP+donSP,lengthSP+donSP+accSP)
301
302 # stores the number of alignments done for each example (best path, second-best path etc.)
303 num_path = [anzpath]*numExamples
304 # stores the gap for each example
305 gap = [0.0]*numExamples
306 #############################################################################################
307 # Training
308 #############################################################################################
309 self.plog('Starting training...\n')
310
311 currentPhi = zeros((run['numFeatures'],1))
312 totalQualityPenalties = zeros((totalQualSP,1))
313
314 numConstPerRound = run['numConstraintsPerRound']
315 solver_call_ctr = 0
316
317 suboptimal_example = 0
318 iteration_nr = 0
319 param_idx = 0
320 const_added_ctr = 0
321
322 featureVectors = zeros((run['numFeatures'],numExamples))
323
324 # the main training loop
325 while True:
326 if iteration_nr == iteration_steps:
327 break
328
329 for exampleIdx,example_key in enumerate(training_set.keys()):
330 print 'Current example %d' % example_key
331 try:
332 dna,est,acc_supp,don_supp,exons,original_est,currentQualities =\
333 getData(training_set,example_key,run)
334 except SpliceSiteException:
335 continue
336
337 dna_len = len(dna)
338
339 if run['mode'] == 'normal':
340 quality = [40]*len(est)
341
342 if run['mode'] == 'using_quality_scores':
343 quality = currentQualities[0]
344
345 if not run['enable_quality_scores']:
346 quality = [40]*len(est)
347
348 if not run['enable_splice_signals']:
349 for idx,elem in enumerate(don_supp):
350 if elem != -inf:
351 don_supp[idx] = 0.0
352
353 for idx,elem in enumerate(acc_supp):
354 if elem != -inf:
355 acc_supp[idx] = 0.0
356
357 # Berechne die Parameter des wirklichen Alignments (but with untrained d,a,h ...)
358 if run['mode'] == 'using_quality_scores':
359 trueSpliceAlign, trueWeightMatch, trueWeightQuality ,dna_calc =\
360 computeSpliceAlignWithQuality(dna, exons, est, original_est,\
361 quality, qualityPlifs,run)
362 else:
363 trueSpliceAlign, trueWeightMatch, trueWeightQuality = computeSpliceAlignWithQuality(dna, exons)
364
365 dna_calc = dna_calc.replace('-','')
366
367 #print 'right before computeSpliceWeights exampleIdx %d' % exampleIdx
368 # Calculate the weights
369 trueWeightDon, trueWeightAcc, trueWeightIntron =\
370 computeSpliceWeights(d, a, h, trueSpliceAlign, don_supp, acc_supp)
371 trueWeight = numpy.vstack([trueWeightIntron, trueWeightDon, trueWeightAcc, trueWeightMatch, trueWeightQuality])
372
373 currentPhi[0:lengthSP] = mat(h.penalties[:]).reshape(lengthSP,1)
374 currentPhi[lengthSP:lengthSP+donSP] = mat(d.penalties[:]).reshape(donSP,1)
375 currentPhi[lengthSP+donSP:lengthSP+donSP+accSP] = mat(a.penalties[:]).reshape(accSP,1)
376 currentPhi[lengthSP+donSP+accSP:lengthSP+donSP+accSP+mmatrixSP] = mmatrix[:]
377
378 if run['mode'] == 'using_quality_scores':
379 totalQualityPenalties = param[-totalQualSP:]
380 currentPhi[lengthSP+donSP+accSP+mmatrixSP:] = totalQualityPenalties[:]
381
382 # Calculate w'phi(x,y) the total score of the alignment
383 trueAlignmentScore = (trueWeight.T * currentPhi)[0,0]
384
385 # The allWeights vector is supposed to store the weight parameter
386 # of the true alignment as well as the weight parameters of the
387 # num_path[exampleIdx] other alignments
388 allWeights = zeros((run['numFeatures'],num_path[exampleIdx]+1))
389 allWeights[:,0] = trueWeight[:,0]
390
391 AlignmentScores = [0.0]*(num_path[exampleIdx]+1)
392 AlignmentScores[0] = trueAlignmentScore
393
394 ################## Calculate wrong alignment(s) ######################
395 # Compute donor, acceptor with penalty_lookup_new
396 # returns two double lists
397 donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
398
399 #myalign wants the acceptor site on the g of the ag
400 #acceptor = acceptor[1:]
401 #acceptor.append(-inf)
402
403 #donor = [-inf] + donor[:-1]
404
405 ps = h.convert2SWIG()
406
407 _newSpliceAlign, _newEstAlign, _newWeightMatch, _newDPScores,\
408 _newQualityPlifsFeatures, unneeded1, unneeded2 =\
409 self.do_alignment(dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,num_path[exampleIdx],False)
410 mm_len = run['matchmatrixRows']*run['matchmatrixCols']
411
412 newSpliceAlign = _newSpliceAlign
413 newEstAlign = _newEstAlign
414 newWeightMatch = _newWeightMatch
415 newDPScores = _newDPScores
416 newQualityPlifsFeatures = _newQualityPlifsFeatures
417
418 newSpliceAlign = newSpliceAlign.reshape(num_path[exampleIdx],dna_len)
419 newWeightMatch = newWeightMatch.reshape(num_path[exampleIdx],mm_len)
420
421 newQualityPlifsFeatures = newQualityPlifsFeatures.reshape(num_path[exampleIdx],run['totalQualSuppPoints'])
422 # Calculate weights of the respective alignments. Note that we are
423 # calculating n-best alignments without hamming loss, so we
424 # have to keep track which of the n-best alignments correspond to
425 # the true one in order not to incorporate a true alignment in the
426 # constraints. To keep track of the true and false alignments we
427 # define an array true_map with a boolean indicating the
428 # equivalence to the true alignment for each decoded alignment.
429 true_map = [0]*(num_path[exampleIdx]+1)
430 true_map[0] = 1
431
432 for pathNr in range(num_path[exampleIdx]):
433 weightDon, weightAcc, weightIntron = computeSpliceWeights(d, a,\
434 h, newSpliceAlign[pathNr,:].flatten().tolist()[0], don_supp,\
435 acc_supp)
436
437 decodedQualityFeatures = zeros((run['totalQualSuppPoints'],1))
438 decodedQualityFeatures = newQualityPlifsFeatures[pathNr,:].T
439 # Gewichte in restliche Zeilen der Matrix speichern
440 allWeights[:,pathNr+1] = numpy.vstack([weightIntron, weightDon, weightAcc, newWeightMatch[pathNr,:].T, decodedQualityFeatures[:]])
441
442 hpen = mat(h.penalties).reshape(len(h.penalties),1)
443 dpen = mat(d.penalties).reshape(len(d.penalties),1)
444 apen = mat(a.penalties).reshape(len(a.penalties),1)
445 features = numpy.vstack([hpen, dpen, apen, mmatrix[:], totalQualityPenalties[:]])
446
447 featureVectors[:,exampleIdx] = allWeights[:,pathNr+1]
448
449 AlignmentScores[pathNr+1] = (allWeights[:,pathNr+1].T * features)[0,0]
450
451 distinct_scores = False
452 if math.fabs(AlignmentScores[pathNr] - AlignmentScores[pathNr+1]) > 1e-5:
453 distinct_scores = True
454
455 # Check wether scalar product + loss equals viterbi score
456 if not math.fabs(newDPScores[pathNr,0] - AlignmentScores[pathNr+1]) <= 1e-5:
457 self.plog("Scalar prod. + loss not equals Viterbi output!\n")
458 pdb.set_trace()
459
460 self.plog(" scalar prod (correct) : %f\n"%AlignmentScores[0])
461 self.plog(" scalar prod (pred.) : %f %f\n"%(newDPScores[pathNr,0],AlignmentScores[pathNr+1]))
462
463 # if the pathNr-best alignment is very close to the true alignment consider it as true
464 if norm( allWeights[:,0] - allWeights[:,pathNr+1] ) < 1e-5:
465 true_map[pathNr+1] = 1
466
467 if not trueAlignmentScore <= max(AlignmentScores[1:]) + 1e-6:
468 print "suboptimal_example %d\n" %exampleIdx
469 #trueSpliceAlign, trueWeightMatch, trueWeightQuality dna_calc=\
470 #computeSpliceAlignWithQuality(dna, exons, est, original_est, quality, qualityPlifs)
471
472 #pdb.set_trace()
473 suboptimal_example += 1
474 self.plog("suboptimal_example %d\n" %exampleIdx)
475
476 # the true label sequence should not have a larger score than the maximal one WHYYYYY?
477 # this means that all n-best paths are to close to each other
478 # we have to extend the n-best search to a (n+1)-best
479 if len([elem for elem in true_map if elem == 1]) == len(true_map):
480 num_path[exampleIdx] = num_path[exampleIdx]+1
481
482 # Choose true and first false alignment for extending
483 firstFalseIdx = -1
484 for map_idx,elem in enumerate(true_map):
485 if elem == 0:
486 firstFalseIdx = map_idx
487 break
488
489 if False:
490 self.plog("Is considered as: %d\n" % true_map[1])
491
492 result_len = currentAlignment.getResultLength()
493 c_dna_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
494 c_est_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
495
496 currentAlignment.getAlignmentArrays(c_dna_array,c_est_array)
497
498 dna_array = [0.0]*result_len
499 est_array = [0.0]*result_len
500
501 for r_idx in range(result_len):
502 dna_array[r_idx] = c_dna_array[r_idx]
503 est_array[r_idx] = c_est_array[r_idx]
504
505 _newSpliceAlign = newSpliceAlign[0].flatten().tolist()[0]
506 _newEstAlign = newEstAlign[0].flatten().tolist()[0]
507
508 #line1,line2,line3 = pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array)
509 #self.plog(line1+'\n')
510 #self.plog(line2+'\n')
511 #self.plog(line3+'\n')
512
513 # if there is at least one useful false alignment add the
514 # corresponding constraints to the optimization problem
515 if firstFalseIdx != -1:
516 firstFalseWeights = allWeights[:,firstFalseIdx]
517 differenceVector = trueWeight - firstFalseWeights
518 #pdb.set_trace()
519
520 #print 'NOT ADDING ANY CONSTRAINTS'
521 const_added = solver.addConstraint(differenceVector, exampleIdx)
522
523 const_added_ctr += 1
524 #
525 # end of one example processing
526 #
527
528 # call solver every nth example //added constraint
529 if exampleIdx != 0 and exampleIdx % numConstPerRound == 0:
530 objValue,w,self.slacks = solver.solve()
531 solver_call_ctr += 1
532
533 if solver_call_ctr == 5:
534 numConstPerRound = 200
535 self.plog('numConstPerRound is now %d\n'% numConstPerRound)
536
537 if math.fabs(objValue - self.oldObjValue) <= 1e-6:
538 self.noImprovementCtr += 1
539
540 if self.noImprovementCtr == numExamples+1:
541 break
542
543 self.oldObjValue = objValue
544 print "objValue is %f" % objValue
545
546 sum_xis = 0
547 for elem in self.slacks:
548 sum_xis += elem
549
550 print 'sum of slacks is %f'% sum_xis
551 self.plog('sum of slacks is %f\n'% sum_xis)
552
553 for i in range(len(param)):
554 param[i] = w[i]
555
556 cPickle.dump(param,open('param_%d.pickle'%param_idx,'w+'))
557 param_idx += 1
558 [h,d,a,mmatrix,qualityPlifs] =\
559 set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
560
561 #
562 # end of one iteration through all examples
563 #
564
565 self.plog("suboptimal rounds %d\n" %suboptimal_example)
566
567 if self.noImprovementCtr == numExamples*2:
568 break
569
570 iteration_nr += 1
571
572 #
573 # end of optimization
574 #
575 print 'Training completed'
576
577 cPickle.dump(param,open('param_%d.pickle'%param_idx,'w+'))
578 self.logfh.close()
579
580
581 ###############################################################################
582 #
583 # End of the code needed for training
584 #
585 # Begin of code for prediction
586 #
587 ###############################################################################
588
589 def predict(self,run,prediction_set,param):
590 """
591 Performing a prediction takes...
592 """
593 self.run = run
594
595 full_working_path = os.path.join(run['alignment_dir'],run['name'])
596
597 #assert not os.path.exists(full_working_path)
598 if not os.path.exists(full_working_path):
599 os.mkdir(full_working_path)
600
601 assert os.path.exists(full_working_path)
602
603 # ATTENTION: Changing working directory
604 os.chdir(full_working_path)
605
606 self.logfh = open('_qpalma_train.log','w+')
607
608 if self.run['mode'] == 'normal':
609 self.use_quality_scores = False
610
611 elif self.run['mode'] == 'using_quality_scores':
612 self.use_quality_scores = True
613 else:
614 assert(False)
615
616 # number of prediction instances
617 self.plog('Number of prediction examples: %d\n'% len(prediction_set))
618
619 # Set the parameters such as limits penalties for the Plifs
620 [h,d,a,mmatrix,qualityPlifs] =\
621 set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
622
623 #############################################################################################
624 # Prediction
625 #############################################################################################
626 self.plog('Starting prediction...\n')
627
628 donSP = self.run['numDonSuppPoints']
629 accSP = self.run['numAccSuppPoints']
630 lengthSP = self.run['numLengthSuppPoints']
631 mmatrixSP = run['matchmatrixRows']*run['matchmatrixCols']
632 numq = self.run['numQualSuppPoints']
633 totalQualSP = self.run['totalQualSuppPoints']
634
635 totalQualityPenalties = zeros((totalQualSP,1))
636
637 problem_ctr = 0
638
639 # where we store the predictions
640 allPredictions = []
641
642 # beginning of the prediction loop
643 for example_key in prediction_set.keys():
644 print 'Current example %d' % example_key
645
646 currentSeqInfo,original_est,currentQualities = prediction_set[id]
647
648 id,chr,strand,genomicSeq_start,genomicSeq_stop =\
649 currentSeqInfo
650
651 if not chr in range(1,6):
652 continue
653
654 self.plog('Loading example nr. %d (id: %d)...\n'%(exampleIdx,int(id)))
655
656 est = original_est
657 est = unbracket_est(est)
658
659 if run['mode'] == 'normal':
660 quality = [40]*len(est)
661
662 if run['mode'] == 'using_quality_scores':
663 quality = currentQualities[0]
664
665 if not run['enable_quality_scores']:
666 quality = [40]*len(est)
667
668 current_example_predictions = []
669
670 try:
671 currentDNASeq, currentAcc, currentDon = get_seq_and_scores(chr,strand,genomicSeq_start,genomicSeq_stop,run['dna_flat_files'])
672 except:
673 problem_ctr += 1
674 continue
675
676 if not run['enable_splice_signals']:
677 for idx,elem in enumerate(currentDon):
678 if elem != -inf:
679 currentDon[idx] = 0.0
680
681 for idx,elem in enumerate(currentAcc):
682 if elem != -inf:
683 currentAcc[idx] = 0.0
684
685 current_prediction = self.calc_alignment(currentDNASeq, est,\
686 quality, currentDon, currentAcc, d, a, h, mmatrix, qualityPlifs)
687
688 current_prediction['id'] = id
689 #current_prediction['start_pos'] = up_cut
690 current_prediction['start_pos'] = genomicSeq_start
691 current_prediction['chr'] = chr
692 current_prediction['strand'] = strand
693
694 allPredictions.append(current_prediction)
695
696 # end of the prediction loop we save all predictions in a pickle file and exit
697 cPickle.dump(allPredictions,open('%s_allPredictions_%s'%(run['name'],set_flag),'w+'))
698 print 'Prediction completed'
699 print 'Problem ctr %d' % problem_ctr
700 self.logfh.close()
701
702
703 def calc_alignment(self, dna, est, quality, don_supp, acc_supp, d, a, h, mmatrix, qualityPlifs):
704 """
705 Given two sequences and the parameters we calculate on alignment
706 """
707
708 run = self.run
709 donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
710
711 dna = str(dna)
712 est = str(est)
713
714 if '-' in est:
715 self.plog('found gap\n')
716 est = est.replace('-','')
717 assert len(est) == 36
718
719 dna_len = len(dna)
720 est_len = len(est)
721
722 ps = h.convert2SWIG()
723
724 newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
725 newQualityPlifsFeatures, dna_array, est_array =\
726 self.do_alignment(dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,1,True)
727
728 mm_len = run['matchmatrixRows']*run['matchmatrixCols']
729
730 # old code removed
731 newSpliceAlign = newSpliceAlign.reshape(1,dna_len)
732 newWeightMatch = newWeightMatch.reshape(1,mm_len)
733 true_map = [0]*2
734 true_map[0] = 1
735 pathNr = 0
736
737 _newSpliceAlign = newSpliceAlign.flatten().tolist()[0]
738 _newEstAlign = newEstAlign.flatten().tolist()[0]
739
740 alignment = get_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array) #(qStart, qEnd, tStart, tEnd, num_exons, qExonSizes, qStarts, qEnds, tExonSizes, tStarts, tEnds)
741 #line1,line2,line3 = pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array)
742 #self.plog(line1+'\n')
743 #self.plog(line2+'\n')
744 #self.plog(line3+'\n')
745
746 newExons = self.calculatePredictedExons(newSpliceAlign)
747
748 current_prediction = {'predExons':newExons, 'dna':dna, 'est':est, 'DPScores':newDPScores,\
749 'alignment':alignment}
750
751 return current_prediction
752
753
754 def calculatePredictedExons(self,SpliceAlign):
755 newExons = []
756 oldElem = -1
757 SpliceAlign = SpliceAlign.flatten().tolist()[0]
758 SpliceAlign.append(-1)
759 for pos,elem in enumerate(SpliceAlign):
760 if pos == 0:
761 oldElem = -1
762 else:
763 oldElem = SpliceAlign[pos-1]
764
765 if oldElem != 0 and elem == 0: # start of exon
766 newExons.append(pos)
767
768 if oldElem == 0 and elem != 0: # end of exon
769 newExons.append(pos)
770
771 return newExons
772
773 ###########################
774 # A simple command line
775 # interface
776 ###########################
777
778 if __name__ == '__main__':
779 assert len(sys.argv) == 4
780
781 run_fn = sys.argv[1]
782 dataset_fn = sys.argv[2]
783 param_fn = sys.argv[3]
784
785 run_obj = cPickle.load(open(run_fn))
786 dataset_obj = cPickle.load(open(dataset_fn))
787
788 qpalma = QPalma()
789
790 if param_fn == 'train':
791 qpalma.train(run_obj,dataset_obj)
792 else:
793 param_obj = cPickle.load(open(param_fn))
794 qpalma.predict(run_obj,dataset_obj,param_obj)