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