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