+ added some text and references to the documentation
[qpalma.git] / scripts / qpalma_main.py
index 99da8a0..e70e6d2 100644 (file)
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
-###########################################################
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
 #
-# The QPalma project aims at extending the Palma project 
-# to be able to use Solexa reads toegether with their 
-# quality scores.
-# 
-# This file represents the conversion of the main matlab 
-# training loop for Palma to python.
-# 
-# Author: Fabio De Bona
-# 
-###########################################################
+# Written (W) 2008 Fabio De Bona
+# Copyright (C) 2008 Max-Planck-Society
 
-import sys
+import array
 import cPickle
-import subprocess
-import scipy.io
-import pdb
 import os.path
+import pdb
+import sys
+
+from qpalma.sequence_utils import SeqSpliceInfo,DataAccessWrapper,unbracket_seq
 
 import numpy
 from numpy.matlib import mat,zeros,ones,inf
 from numpy.linalg import norm
 
+#from qpalma.SIQP_CPX import SIQPSolver
+#from qpalma.SIQP_CVXOPT import SIQPSolver
+
 import QPalmaDP
 import qpalma
-from qpalma.SIQP_CPX import SIQPSolver
-from qpalma.DataProc import *
-from qpalma.generateEvaluationData import *
 from qpalma.computeSpliceWeights import *
 from qpalma.set_param_palma import *
 from qpalma.computeSpliceAlignWithQuality import *
-from qpalma.penalty_lookup_new import *
-from qpalma.compute_donacc import *
-from qpalma.export_param import *
 from qpalma.TrainingParam import Param
-from qpalma.Plif import Plf
+from qpalma.Plif import Plf,compute_donacc
 
-from qpalma.tools.splicesites import getDonAccScores
-from qpalma.Configuration import *
+from Utils import pprint_alignment, get_alignment
 
-from compile_dataset import compile_d
+class SpliceSiteException:
+   pass
 
-import palma.palma_utils as pu
-from palma.output_formating import print_results
 
-class para:
-   pass
+def getData(training_set,exampleKey,run):
+   """ This function...  """
+
+   currentSeqInfo,original_est,currentQualities,currentExons = training_set[exampleKey]
+   id,chr,strand,up_cut,down_cut = currentSeqInfo
+
+   est = original_est
+   est = "".join(est)
+   est = est.lower()
+   est = unbracket_est(est)
+   est = est.replace('-','')
+
+   assert len(est) == run['read_size'], pdb.set_trace()
+   est_len = len(est)
+
+   #original_est = OriginalEsts[exampleIdx]
+   original_est = "".join(original_est)
+   original_est = original_est.lower()
+
+   dna_flat_files =  '/fml/ag-raetsch/share/projects/genomes/A_thaliana_best/genome/'
+   dna, acc_supp, don_supp = get_seq_and_scores(chr,strand,up_cut,down_cut,dna_flat_files)
+
+   #currentDNASeq, currentAcc, currentDon = seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop)
+
+   original_exons = currentExons
+   exons = original_exons - (up_cut-1)
+   exons[0,0] -= 1
+   exons[1,0] -= 1
+
+   if exons.shape == (2,2):
+      fetched_dna_subseq = dna[exons[0,0]:exons[0,1]] + dna[exons[1,0]:exons[1,1]]
+     
+      donor_elem = dna[exons[0,1]:exons[0,1]+2]
+      acceptor_elem = dna[exons[1,0]-2:exons[1,0]]
+
+      if not ( donor_elem == 'gt' or donor_elem == 'gc' ):
+         print 'invalid donor in example %d'% exampleKey
+         raise SpliceSiteException
+
+      if not ( acceptor_elem == 'ag' ):
+         print 'invalid acceptor in example %d'% exampleKey
+         raise SpliceSiteException
+
+      assert len(fetched_dna_subseq) == len(est), pdb.set_trace()
+
+   return dna,est,acc_supp,don_supp,exons,original_est,currentQualities
+
 
 class QPalma:
    """
-   A training method for the QPalma project
+   This class wraps the training and prediction functions for 
+   the alignment.
    """
    
-   def __init__(self,run):
+   def __init__(self,run,seqInfo,dmode=False):
       self.ARGS = Param()
-
+      self.qpalma_debug_mode = dmode
       self.run = run
+      self.seqInfo = seqInfo
 
-      #data_filename = self.run['dataset_filename']
-      #Sequences, Acceptors, Donors, Exons, Ests, OriginalEsts, Qualities, SplitPos = paths_load_data(data_filename,'training',None,self.ARGS)
 
-      # Load the whole dataset 
-      if self.run['mode'] == 'normal':
-         self.use_quality_scores = False
+   def plog(self,string):
+      self.logfh.write(string)
+      self.logfh.flush()
 
-      elif self.run['mode'] == 'using_quality_scores':
-         self.use_quality_scores = True
+
+   def do_alignment(self,dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,current_num_path,prediction_mode):
+      """
+      Given the needed input this method calls the QPalma C module which
+      calculates a dynamic programming in order to obtain an alignment
+      """
+
+      dna_len = len(dna)
+      est_len = len(est)
+
+      prb = QPalmaDP.createDoubleArrayFromList(quality)
+      chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
+
+      matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
+      mm_len = self.run['matchmatrixRows']*self.run['matchmatrixCols']
+
+      d_len = len(donor)
+      donor = QPalmaDP.createDoubleArrayFromList(donor)
+      a_len = len(acceptor)
+      acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
+
+      # Create the alignment object representing the interface to the C/C++ code.
+      currentAlignment = QPalmaDP.Alignment(self.run['numQualPlifs'],self.run['numQualSuppPoints'], self.use_quality_scores)
+      c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList([elem.convert2SWIG() for elem in qualityPlifs])
+      # calculates SpliceAlign, EstAlign, weightMatch, Gesamtscores, dnaest
+      currentAlignment.myalign( current_num_path, dna, dna_len,\
+       est, est_len, prb, chastity, ps, matchmatrix, mm_len, donor, d_len,\
+       acceptor, a_len, c_qualityPlifs, self.run['remove_duplicate_scores'],\
+       self.run['print_matrix'] )
+
+      if prediction_mode:
+         # part that is only needed for prediction
+         result_len = currentAlignment.getResultLength()
+         dna_array,est_array = currentAlignment.getAlignmentArraysNew()
       else:
-         assert(False)
+         dna_array = None
+         est_array = None
 
-      #self.Sequences   = Sequences
-      #self.Exons       = Exons
-      #self.Ests        = Ests
-      #self.OriginalEsts= OriginalEsts
-      #self.Qualities   = Qualities
-      #self.SplitPos    = SplitPos
-      #self.Donors      = Donors
-      #self.Acceptors   = Acceptors
+      newSpliceAlign, newEstAlign, newWeightMatch, newDPScores, newQualityPlifsFeatures =\
+      currentAlignment.getAlignmentResultsNew()
 
-      #calc_info(self.Acceptors,self.Donors,self.Exons,self.Qualities)
-      #print 'leaving constructor...'
+      return newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
+      newQualityPlifsFeatures, dna_array, est_array
 
-   def plog(self,string):
-      self.logfh.write(string)
-      self.logfh.flush()
 
-   def train(self):
-      run = self.run
+   def init_train(self,training_set):
+      full_working_path = os.path.join(self.run['alignment_dir'],self.run['name'])
+
+      #assert not os.path.exists(full_working_path)
+      if not os.path.exists(full_working_path):
+         os.mkdir(full_working_path)
 
-      full_working_path = os.path.join(run['experiment_path'],run['name'])
-      assert not os.path.exists(full_working_path)
-      os.mkdir(full_working_path)
       assert os.path.exists(full_working_path)
 
       # ATTENTION: Changing working directory
       os.chdir(full_working_path)
 
       self.logfh = open('_qpalma_train.log','w+')
+      cPickle.dump(self.run,open('run_obj.pickle','w+'))
 
       self.plog("Settings are:\n")
-      self.plog("%s\n"%str(run))
+      self.plog("%s\n"%str(self.run))
 
-      data_filename = self.run['dataset_filename']
-      Sequences, Acceptors, Donors, Exons, Ests, OriginalEsts, Qualities, SplitPos = paths_load_data(data_filename,'training',None,self.ARGS)
-
-      # Load the whole dataset 
       if self.run['mode'] == 'normal':
          self.use_quality_scores = False
 
@@ -116,74 +174,59 @@ class QPalma:
       else:
          assert(False)
 
-      self.Sequences   = Sequences
-      self.Exons       = Exons
-      self.Ests        = Ests
-      self.OriginalEsts= OriginalEsts
-      self.Qualities   = Qualities
-      self.SplitPos    = SplitPos
-      self.Donors      = Donors
-      self.Acceptors   = Acceptors
-
-      calc_info(self.Acceptors,self.Donors,self.Exons,self.Qualities)
-
-      beg = run['training_begin']
-      end = run['training_end']
-
-      Sequences   = Sequences[beg:end]
-      Exons       = Exons[beg:end]
-      Ests        = Ests[beg:end]
-      OriginalEsts= OriginalEsts[beg:end]
-      Qualities   = Qualities[beg:end]
-      Acceptors   = Acceptors[beg:end]
-      Donors      = Donors[beg:end]
-
-      # number of training instances
-      N = numExamples = len(Sequences) 
-      assert len(Exons) == N and len(Ests) == N\
-      and len(Qualities) == N and len(Acceptors) == N\
-      and len(Donors) == N, 'The Exons,Acc,Don,.. arrays are of different lengths'
+
+   def setUpSolver(self):
+      # Initialize solver 
+      self.plog('Initializing problem...\n')
+      
+      try:
+         solver = SIQPSolver(run['numFeatures'],numExamples,run['C'],self.logfh,run)
+      except:
+         self.plog('Got no license. Telling queue to reschedule job...\n')
+         sys.exit(99)
+
+      solver.enforceMonotonicity(lengthSP,lengthSP+donSP)
+      solver.enforceMonotonicity(lengthSP+donSP,lengthSP+donSP+accSP)
+
+      return solver
+
+
+   def train(self,training_set):
+      numExamples = len(training_set)
       self.plog('Number of training examples: %d\n'% numExamples)
 
       self.noImprovementCtr = 0
       self.oldObjValue = 1e8
 
-      iteration_steps         = run['iter_steps']
-      remove_duplicate_scores = run['remove_duplicate_scores']
-      print_matrix            = run['print_matrix']
-      anzpath                 = run['anzpath']
+      iteration_steps         = self.run['iter_steps']
+      remove_duplicate_scores = self.run['remove_duplicate_scores']
+      print_matrix            = self.run['print_matrix']
+      anzpath                 = self.run['anzpath']
 
-      # Initialize parameter vector  / param = numpy.matlib.rand(126,1)
-      param = Conf.fixedParam[:run['numFeatures']]
+      # Initialize parameter vector
+      param = numpy.matlib.rand(run['numFeatures'],1)
    
-      lengthSP    = run['numLengthSuppPoints']
-      donSP       = run['numDonSuppPoints']
-      accSP       = run['numAccSuppPoints']
-      mmatrixSP   = run['matchmatrixRows']*run['matchmatrixCols']
-      numq        = run['numQualSuppPoints']
-      totalQualSP = run['totalQualSuppPoints']
+      lengthSP    = self.run['numLengthSuppPoints']
+      donSP       = self.run['numDonSuppPoints']
+      accSP       = self.run['numAccSuppPoints']
+      mmatrixSP   = self.run['matchmatrixRows']*run['matchmatrixCols']
+      numq        = self.run['numQualSuppPoints']
+      totalQualSP = self.run['totalQualSuppPoints']
 
       # no intron length model
-      if not run['enable_intron_length']:
+      if not self.run['enable_intron_length']:
          param[:lengthSP] *= 0.0
 
       # Set the parameters such as limits penalties for the Plifs
-      [h,d,a,mmatrix,qualityPlifs] = set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
+      [h,d,a,mmatrix,qualityPlifs] = set_param_palma(param,self.ARGS.train_with_intronlengthinformation,self.run)
 
-      # Initialize solver 
-      self.plog('Initializing problem...\n')
-      solver = SIQPSolver(run['numFeatures'],numExamples,run['C'],self.logfh,run)
-      #solver.enforceMonotonicity(lengthSP,lengthSP+donSP)
-      #solver.enforceMonotonicity(lengthSP+donSP,lengthSP+donSP+accSP)
+      solver = self.setUpSolver()
 
       # stores the number of alignments done for each example (best path, second-best path etc.)
       num_path = [anzpath]*numExamples
+
       # stores the gap for each example
       gap      = [0.0]*numExamples
-      #############################################################################################
-      # Training
-      #############################################################################################
-      self.plog('Starting training...\n')
 
       currentPhi = zeros((run['numFeatures'],1))
       totalQualityPenalties = zeros((totalQualSP,1))
@@ -196,41 +239,28 @@ class QPalma:
       param_idx = 0
       const_added_ctr = 0
 
+      featureVectors = zeros((run['numFeatures'],numExamples))
+
+      self.plog('Starting training...\n')
       # the main training loop
       while True:
          if iteration_nr == iteration_steps:
             break
 
-         for exampleIdx in range(numExamples):
-            if (exampleIdx%100) == 0:
-               print 'Current example nr %d' % exampleIdx
-
-            dna = Sequences[exampleIdx] 
-            est = Ests[exampleIdx] 
-            est = "".join(est)
-            est = est.lower()
-            est = est.replace('-','')
-            original_est = OriginalEsts[exampleIdx] 
-            original_est = "".join(original_est)
-            original_est = original_est.lower()
+         for exampleIdx,example_key in enumerate(training_set.keys()):
+            print 'Current example %d' % example_key
+            try:
+               dna,est,acc_supp,don_supp,exons,original_est,currentQualities =\
+               getData(training_set,example_key,run)
+            except SpliceSiteException:
+               continue
 
             dna_len = len(dna)
-            est_len = len(est)
 
-            assert len(est) == run['read_size'], pdb.set_trace()
-
-            if run['mode'] == 'normal':
-               quality = [40]*len(est)
-
-            if run['mode'] == 'using_quality_scores':
-               quality = Qualities[exampleIdx]
-
-            if not run['enable_quality_scores']:
-               quality = [40]*len(est)
-
-            exons = Exons[exampleIdx] 
-            don_supp = Donors[exampleIdx] 
-            acc_supp = Acceptors[exampleIdx] 
+            if run['enable_quality_scores']:
+               quality = currentQualities[quality_index]
+            else:
+               quality = [40]*len(read)
 
             if not run['enable_splice_signals']:
                for idx,elem in enumerate(don_supp):
@@ -248,11 +278,13 @@ class QPalma:
                quality, qualityPlifs,run)
             else:
                trueSpliceAlign, trueWeightMatch, trueWeightQuality = computeSpliceAlignWithQuality(dna, exons)
-            
+
             dna_calc = dna_calc.replace('-','')
 
+            #print 'right before computeSpliceWeights exampleIdx %d' % exampleIdx
             # Calculate the weights
-            trueWeightDon, trueWeightAcc, trueWeightIntron = computeSpliceWeights(d, a, h, trueSpliceAlign, don_supp, acc_supp)
+            trueWeightDon, trueWeightAcc, trueWeightIntron =\
+            computeSpliceWeights(d, a, h, trueSpliceAlign, don_supp, acc_supp)
             trueWeight = numpy.vstack([trueWeightIntron, trueWeightDon, trueWeightAcc, trueWeightMatch, trueWeightQuality])
 
             currentPhi[0:lengthSP]                                            = mat(h.penalties[:]).reshape(lengthSP,1)
@@ -275,107 +307,26 @@ class QPalma:
 
             AlignmentScores = [0.0]*(num_path[exampleIdx]+1)
             AlignmentScores[0] = trueAlignmentScore
+
             ################## Calculate wrong alignment(s) ######################
             # Compute donor, acceptor with penalty_lookup_new
             # returns two double lists
             donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
 
-            #myalign wants the acceptor site on the g of the ag
-            acceptor = acceptor[1:]
-            acceptor.append(-inf)
-
-            # check that splice site scores are at dna positions as expected by
-            # the dynamic programming component
-
-            #for d_pos in [pos for pos,elem in enumerate(donor) if elem != -inf]:
-            #   assert dna[d_pos] == 'g' and (dna[d_pos+1] == 'c'\
-            #   or dna[d_pos+1] == 't'), pdb.set_trace()
-            #    
-            #for a_pos in [pos for pos,elem in enumerate(acceptor) if elem != -inf]:
-            #   assert dna[a_pos-1] == 'a' and dna[a_pos] == 'g', pdb.set_trace()
-
             ps = h.convert2SWIG()
 
-            prb = QPalmaDP.createDoubleArrayFromList(quality)
-            chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
-
-            matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
+            newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
+            newQualityPlifsFeatures, unneeded1, unneeded2 =\
+            self.do_alignment(dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,num_path[exampleIdx],False)
             mm_len = run['matchmatrixRows']*run['matchmatrixCols']
 
-            d_len = len(donor)
-            donor = QPalmaDP.createDoubleArrayFromList(donor)
-            a_len = len(acceptor)
-            acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
-
-            # Create the alignment object representing the interface to the C/C++ code.
-            currentAlignment = QPalmaDP.Alignment(run['numQualPlifs'],run['numQualSuppPoints'], self.use_quality_scores)
-            c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList([elem.convert2SWIG() for elem in qualityPlifs])
-            #print 'Calling myalign...'
-            # calculates SpliceAlign, EstAlign, weightMatch, Gesamtscores, dnaest
-            currentAlignment.myalign( num_path[exampleIdx], dna, dna_len,\
-             est, est_len, prb, chastity, ps, matchmatrix, mm_len, donor, d_len,\
-             acceptor, a_len, c_qualityPlifs, remove_duplicate_scores,
-             print_matrix)
-
-            c_SpliceAlign       = QPalmaDP.createIntArrayFromList([0]*(dna_len*num_path[exampleIdx]))
-            c_EstAlign          = QPalmaDP.createIntArrayFromList([0]*(est_len*num_path[exampleIdx]))
-            c_WeightMatch       = QPalmaDP.createIntArrayFromList([0]*(mm_len*num_path[exampleIdx]))
-            c_DPScores   = QPalmaDP.createDoubleArrayFromList([.0]*num_path[exampleIdx])
-
-            c_qualityPlifsFeatures = QPalmaDP.createDoubleArrayFromList([.0]*(run['totalQualSuppPoints']*num_path[exampleIdx]))
-
-            currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign,\
-            c_WeightMatch, c_DPScores, c_qualityPlifsFeatures)
-
-            #print 'After calling getAlignmentResults...'
-
-            newSpliceAlign = zeros((num_path[exampleIdx]*dna_len,1))
-            newEstAlign    = zeros((est_len*num_path[exampleIdx],1))
-            newWeightMatch = zeros((num_path[exampleIdx]*mm_len,1))
-            newDPScores    = zeros((num_path[exampleIdx],1))
-            newQualityPlifsFeatures = zeros((run['totalQualSuppPoints']*num_path[exampleIdx],1))
-
-            #print 'newSpliceAlign'
-            for i in range(dna_len*num_path[exampleIdx]):
-               newSpliceAlign[i] = c_SpliceAlign[i]
-            #   print '%f' % (spliceAlign[i])
-
-            #print 'newEstAlign'
-            for i in range(est_len*num_path[exampleIdx]):
-               newEstAlign[i] = c_EstAlign[i]
-            #   print '%f' % (spliceAlign[i])
-
-            #print 'weightMatch'
-            for i in range(mm_len*num_path[exampleIdx]):
-               newWeightMatch[i] = c_WeightMatch[i]
-            #   print '%f' % (weightMatch[i])
-
-            #print 'ViterbiScores'
-            for i in range(num_path[exampleIdx]):
-               newDPScores[i] = c_DPScores[i]
-
-            if self.use_quality_scores:
-               for i in range(run['totalQualSuppPoints']*num_path[exampleIdx]):
-                  newQualityPlifsFeatures[i] = c_qualityPlifsFeatures[i]
-
-            #  equals palma up to here
-
-            #print "Calling destructors"
-            del c_SpliceAlign
-            del c_EstAlign
-            del c_WeightMatch
-            del c_DPScores
-            del c_qualityPlifsFeatures
-            #del currentAlignment
-
             newSpliceAlign = newSpliceAlign.reshape(num_path[exampleIdx],dna_len)
             newWeightMatch = newWeightMatch.reshape(num_path[exampleIdx],mm_len)
 
             newQualityPlifsFeatures = newQualityPlifsFeatures.reshape(num_path[exampleIdx],run['totalQualSuppPoints'])
-            # Calculate weights of the respective alignments Note that we are
-            # calculating n-best alignments without hamming loss, so we
-            # have to keep track which of the n-best alignments correspond to
-            # the true one in order not to incorporate a true alignment in the
+            # Calculate weights of the respective alignments. Note that we are calculating n-best alignments without 
+            # hamming loss, so we have to keep track which of the n-best alignments correspond to the true one in order 
+            # not to incorporate a true alignment in the
             # constraints. To keep track of the true and false alignments we
             # define an array true_map with a boolean indicating the
             # equivalence to the true alignment for each decoded alignment.
@@ -383,11 +334,10 @@ class QPalma:
             true_map[0] = 1
 
             for pathNr in range(num_path[exampleIdx]):
-               #print 'decodedWeights' 
                weightDon, weightAcc, weightIntron = computeSpliceWeights(d, a,\
                h, newSpliceAlign[pathNr,:].flatten().tolist()[0], don_supp,\
                acc_supp)
-
+              
                decodedQualityFeatures = zeros((run['totalQualSuppPoints'],1))
                decodedQualityFeatures = newQualityPlifsFeatures[pathNr,:].T
                # Gewichte in restliche Zeilen der Matrix speichern
@@ -398,7 +348,7 @@ class QPalma:
                apen = mat(a.penalties).reshape(len(a.penalties),1)
                features = numpy.vstack([hpen, dpen, apen, mmatrix[:], totalQualityPenalties[:]])
 
-               #pdb.set_trace()
+               featureVectors[:,exampleIdx] = allWeights[:,pathNr+1]
 
                AlignmentScores[pathNr+1] = (allWeights[:,pathNr+1].T * features)[0,0]
 
@@ -406,8 +356,6 @@ class QPalma:
                if math.fabs(AlignmentScores[pathNr] - AlignmentScores[pathNr+1]) > 1e-5:
                   distinct_scores = True
 
-               #pdb.set_trace()
-               
                # Check wether scalar product + loss equals viterbi score
                if not math.fabs(newDPScores[pathNr,0] - AlignmentScores[pathNr+1]) <= 1e-5:
                   self.plog("Scalar prod. + loss not equals Viterbi output!\n")
@@ -416,13 +364,10 @@ class QPalma:
                self.plog(" scalar prod (correct) : %f\n"%AlignmentScores[0])
                self.plog(" scalar prod (pred.) : %f %f\n"%(newDPScores[pathNr,0],AlignmentScores[pathNr+1]))
 
-               #pdb.set_trace()
-
                # if the pathNr-best alignment is very close to the true alignment consider it as true
                if norm( allWeights[:,0] - allWeights[:,pathNr+1] ) < 1e-5:
                   true_map[pathNr+1] = 1
 
-
                if not trueAlignmentScore <= max(AlignmentScores[1:]) + 1e-6:
                   print "suboptimal_example %d\n" %exampleIdx
                   #trueSpliceAlign, trueWeightMatch, trueWeightQuality dna_calc=\
@@ -432,7 +377,6 @@ class QPalma:
                   suboptimal_example += 1
                   self.plog("suboptimal_example %d\n" %exampleIdx)
 
-
                # the true label sequence should not have a larger score than the maximal one WHYYYYY?
                # this means that all n-best paths are to close to each other 
                # we have to extend the n-best search to a (n+1)-best
@@ -449,25 +393,12 @@ class QPalma:
                if False:
                   self.plog("Is considered as: %d\n" % true_map[1])
 
-                  result_len = currentAlignment.getResultLength()
-                  c_dna_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-                  c_est_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-
-                  currentAlignment.getAlignmentArrays(c_dna_array,c_est_array)
+                  #result_len = currentAlignment.getResultLength()
 
-                  dna_array = [0.0]*result_len
-                  est_array = [0.0]*result_len
-
-                  for r_idx in range(result_len):
-                     dna_array[r_idx] = c_dna_array[r_idx]
-                     est_array[r_idx] = c_est_array[r_idx]
+                  dna_array,est_array = currentAlignment.getAlignmentArraysNew()
 
                   _newSpliceAlign = newSpliceAlign[0].flatten().tolist()[0]
                   _newEstAlign = newEstAlign[0].flatten().tolist()[0]
-                  line1,line2,line3 = pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array)
-                  self.plog(line1+'\n')
-                  self.plog(line2+'\n')
-                  self.plog(line3+'\n')
 
                # if there is at least one useful false alignment add the
                # corresponding constraints to the optimization problem
@@ -478,9 +409,8 @@ class QPalma:
 
                   const_added = solver.addConstraint(differenceVector, exampleIdx)
                   const_added_ctr += 1
-               #
+
                # end of one example processing 
-               #
 
             # call solver every nth example //added constraint
             if exampleIdx != 0 and exampleIdx % numConstPerRound == 0:
@@ -510,87 +440,88 @@ class QPalma:
                for i in range(len(param)):
                   param[i] = w[i]
 
-               #pdb.set_trace()
-
                cPickle.dump(param,open('param_%d.pickle'%param_idx,'w+'))
                param_idx += 1
                [h,d,a,mmatrix,qualityPlifs] =\
-               set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
+               set_param_palma(param,self.ARGS.train_with_intronlengthinformation,self.run)
 
-         #
-         # end of one iteration through all examples
-         #
+         ##############################################
+         # end of one iteration through all examples  #
+         ##############################################
 
          self.plog("suboptimal rounds %d\n" %suboptimal_example)
 
          if self.noImprovementCtr == numExamples*2:
-            break
+            FinalizeTraining(param,'param_%d.pickle'%param_idx)
 
          iteration_nr += 1
 
       #
       # end of optimization 
       #  
-      print 'Training completed'
+      FinalizeTraining(param,'param_%d.pickle'%param_idx)
 
-      pa = para()
-      pa.h = h
-      pa.d = d
-      pa.a = a
-      pa.mmatrix = mmatrix
-      pa.qualityPlifs = qualityPlifs
 
-      cPickle.dump(param,open('param_%d.pickle'%param_idx,'w+'))
-      #cPickle.dump(pa,open('elegans.param','w+'))
+   def FinalizeTraining(self,vector,name):
+      self.plog("Training completed")
+      cPickle.dump(param,open(name,'w+'))
       self.logfh.close()
+      sys.exit(0)
+   
 
 ###############################################################################
 #
 # End of the code needed for training 
-# 
-#
-#
-#
 #
 # Begin of code for prediction
 #
-#
 ###############################################################################
 
+   def init_prediction(self,dataset_fn,prediction_keys,param_fn,set_name):
+      """
+      Performing a prediction takes...
+      """
+      self.set_name = set_name
 
-   def evaluate(self,param_filename,dataset):
-      run = self.run
+      #full_working_path = os.path.join(run['alignment_dir'],run['name'])
+      full_working_path = self.run['result_dir']
 
-      data = dataset
-      self.Sequences   = data['Sequences']
-      self.Acceptors   = data['Acceptors']
-      self.Donors      = data['Donors']
-      self.Exons       = data['Exons']
-      self.Ests        = data['Ests']
-      self.OriginalEsts= data['OriginalEsts']
-      self.Qualities   = data['Qualities']
-      self.SplitPositions = data['SplitPositions']
+      print 'full_working_path is %s' % full_working_path 
 
-      self.FReads = data['FReads']
+      #assert not os.path.exists(full_working_path)
+      if not os.path.exists(full_working_path):
+         os.mkdir(full_working_path)
 
-      beg = run['prediction_begin']
-      end = run['prediction_end']
+      assert os.path.exists(full_working_path)
 
-      self.logfh = open('_qpalma_predict.log','w+')
+      # ATTENTION: Changing working directory
+      os.chdir(full_working_path)
 
-      # predict on training set
-      print '##### Prediction on the training set #####'
-      #self.predict(param_filename,0,beg)
-      
-      # predict on test set
-      print '##### Prediction on the test set #####'
-      self.predict(param_filename,beg,end)
+      self.logfh = open('_qpalma_predict_%s.log'%set_name,'w+')
+
+      # number of prediction instances
+      self.plog('Number of prediction examples: %d\n'% len(prediction_keys))
+
+      # load dataset and fetch instances that shall be predicted
+      dataset = cPickle.load(open(dataset_fn))
+
+      prediction_set = {}
+      for key in prediction_keys:
+         prediction_set[key] = dataset[key]
+
+      # we do not need the full dataset anymore
+      del dataset
    
-      self.logfh.close()
-      #pdb.set_trace()
+      # Load parameter vector to predict with
+      param = cPickle.load(open(param_fn))
 
-   def predict(self,param_filename,beg,end):
-      run = self.run
+      self.predict(prediction_set,param)
+
+
+   def predict(self,prediction_set,param):
+      """
+      This method...
+      """
 
       if self.run['mode'] == 'normal':
          self.use_quality_scores = False
@@ -600,424 +531,127 @@ class QPalma:
       else:
          assert(False)
 
-      Sequences   = self.Sequences[beg:end]
-      Exons       = self.Exons[beg:end]
-      Ests        = self.Ests[beg:end]
-      OriginalEsts        = self.OriginalEsts[beg:end]
-      Qualities   = self.Qualities[beg:end]
-      Acceptors   = self.Acceptors[beg:end]
-      Donors      = self.Donors[beg:end]
-      SplitPos    = self.SplitPositions[beg:end]
-
-      FReads   = self.FReads[beg:end]
-
-      print 'STARTING PREDICTION'
-
-      # number of training instances
-      N = numExamples = len(Sequences) 
-      assert len(Exons) == N and len(Ests) == N\
-      and len(Qualities) == N and len(Acceptors) == N\
-      and len(Donors) == N, 'The Exons,Acc,Don,.. arrays are of different lengths'
-      self.plog('Number of training examples: %d\n'% numExamples)
-
-      self.noImprovementCtr = 0
-      self.oldObjValue = 1e8
-
-      remove_duplicate_scores = self.run['remove_duplicate_scores']
-      print_matrix            = self.run['print_matrix']
-      anzpath                 = self.run['anzpath']
-
-      param = cPickle.load(open(param_filename))
-
-      # Set the parameters such as limits penalties for the Plifs
-      #pdb.set_trace()
+      # Set the parameters such as limits/penalties for the Plifs
       [h,d,a,mmatrix,qualityPlifs] =\
-      set_param_palma(param,self.ARGS.train_with_intronlengthinformation,run)
-
-      #############################################################################################
-      # Prediction
-      #############################################################################################
-      self.plog('Starting prediction...\n')
-
-      donSP       = self.run['numDonSuppPoints']
-      accSP       = self.run['numAccSuppPoints']
-      lengthSP    = self.run['numLengthSuppPoints']
-      mmatrixSP   = run['matchmatrixRows']*run['matchmatrixCols']
-      numq        = self.run['numQualSuppPoints']
-      totalQualSP = self.run['totalQualSuppPoints']
+      set_param_palma(param,self.ARGS.train_with_intronlengthinformation,self.run)
 
-      currentPhi = zeros((self.run['numFeatures'],1))
-      totalQualityPenalties = zeros((totalQualSP,1))
-
-      exon1Begin = []
-      exon1End = []
-      exon2Begin = []
-      exon2End = []
-      allWrongExons = []
+      if not self.qpalma_debug_mode:
+         self.plog('Starting prediction...\n')
 
-      allRealCorrectSplitPos = []
-      allRealWrongSplitPos = []
+      self.problem_ctr = 0
 
+      # where we store the predictions
       allPredictions = []
 
-      for exampleIdx in range(numExamples):
-         dna = Sequences[exampleIdx] 
-         est = Ests[exampleIdx] 
-
-         fRead = FReads[exampleIdx]
-         est = fRead['seq']
-
-         new_est = ''
-         e = 0
-         while True:
-            if not e < len(est):
-               break
-
-            if est[e] == '[':
-               new_est += est[e+2]
-               e += 4
-            else:
-               new_est += est[e]
-               e += 1
-
-         #pdb.set_trace()
-         est = new_est
-         #pdb.set_trace()
-
-         print exampleIdx
-
-         est = "".join(est)
-         est = est.lower()
-         est = est.replace('-','')
-         #original_est = OriginalEsts[exampleIdx] 
-         #original_est = "".join(original_est)
-         #original_est = original_est.lower()
-
-         original_est = est
-
-         currentSplitPos = SplitPos[exampleIdx]
-
-
-         #import re
-         #num_hits = len(re.findall('\[',original_est[:currentSplitPos]))
-
-         #if num_hits == 0:
-         #   currentRealSplitPos = currentSplitPos
-         #else:
-         #   currentRealSplitPos = currentSplitPos - (num_hits*3)
-         currentRealSplitPos = 0
-
-         #assert 0 < currentRealSplitPos < 36, pdb.set_trace()
-         currentRealRestPos  = 36 - currentRealSplitPos 
-         #assert 0 < currentRealRestPos < 36, pdb.set_trace()
-
-         if self.run['mode'] == 'normal':
-            quality = [40]*len(est)
-
-         if self.run['mode'] == 'using_quality_scores':
-            quality = Qualities[exampleIdx]
-
-         if not run['enable_quality_scores']:
-            quality = [40]*len(est)
-
-         quality = fRead['prb']
-
-         exons = zeros((2,2))
-         
-         exons[0,0] = fRead['p_start']-fRead['p_start']
-         exons[0,1] = fRead['exon_stop']-fRead['p_start']
-         exons[1,0] = fRead['exon_start']-fRead['p_start']
-         exons[1,1] = fRead['p_stop']-fRead['p_start']
-
-         don_supp = Donors[exampleIdx] 
-         acc_supp = Acceptors[exampleIdx] 
-
-         if not run['enable_splice_signals']:
-
-            for idx,elem in enumerate(don_supp):
-               if elem != -inf:
-                  don_supp[idx] = 0.0
+      # we take the first quality vector of the tuple of quality vectors
+      quality_index = 0
 
-            for idx,elem in enumerate(acc_supp):
-               if elem != -inf:
-                  acc_supp[idx] = 0.0
+      # beginning of the prediction loop
+      for example_key in prediction_set.keys():
+         print 'Current example %d' % example_key
+         for example in prediction_set[example_key]:
 
-         currentPhi[0:donSP]                                               = mat(d.penalties[:]).reshape(donSP,1)
-         currentPhi[donSP:donSP+accSP]                                     = mat(a.penalties[:]).reshape(accSP,1)
-         currentPhi[donSP+accSP:donSP+accSP+lengthSP]                      = mat(h.penalties[:]).reshape(lengthSP,1)
-         currentPhi[donSP+accSP+lengthSP:donSP+accSP+lengthSP+mmatrixSP]   = mmatrix[:]
+            currentSeqInfo,read,currentQualities = example
 
-         ################## Calculate wrong alignment(s) ######################
+            id,chromo,strand,genomicSeq_start,genomicSeq_stop =\
+            currentSeqInfo 
 
-         # Compute donor, acceptor with penalty_lookup_new
-         # returns two double lists
-         donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
+            if not self.qpalma_debug_mode:
+               self.plog('Loading example id: %d...\n'% int(id))
 
-         #myalign wants the acceptor site on the g of the ag
-         acceptor = acceptor[1:]
-         acceptor.append(-inf)
-
-         dna = str(dna)
-         est = str(est)
-         dna_len = len(dna)
-         est_len = len(est)
-
-         ps = h.convert2SWIG()
-
-         prb = QPalmaDP.createDoubleArrayFromList(quality)
-         chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
-
-         matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
-         mm_len = run['matchmatrixRows']*run['matchmatrixCols']
-
-         d_len = len(donor)
-         donor = QPalmaDP.createDoubleArrayFromList(donor)
-         a_len = len(acceptor)
-         acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
-
-         # Create the alignment object representing the interface to the C/C++ code.
-         currentAlignment = QPalmaDP.Alignment(run['numQualPlifs'],run['numQualSuppPoints'], self.use_quality_scores)
-
-         c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList([elem.convert2SWIG() for elem in qualityPlifs])
-
-         # calculates SpliceAlign, EstAlign, weightMatch, Gesamtscores, dnaest
-         currentAlignment.myalign(1, dna, dna_len,\
-          est, est_len, prb, chastity, ps, matchmatrix, mm_len, donor, d_len,\
-          acceptor, a_len, c_qualityPlifs, remove_duplicate_scores,
-          print_matrix)
-
-         c_SpliceAlign  = QPalmaDP.createIntArrayFromList([0]*(dna_len*1))
-         c_EstAlign     = QPalmaDP.createIntArrayFromList([0]*(est_len*1))
-         c_WeightMatch  = QPalmaDP.createIntArrayFromList([0]*(mm_len*1))
-         c_DPScores     = QPalmaDP.createDoubleArrayFromList([.0]*1)
-
-         result_len = currentAlignment.getResultLength()
-         c_dna_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-         c_est_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-
-         currentAlignment.getAlignmentArrays(c_dna_array,c_est_array)
-
-         c_qualityPlifsFeatures = QPalmaDP.createDoubleArrayFromList([.0]*(self.run['totalQualSuppPoints']))
-
-         currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign,\
-         c_WeightMatch, c_DPScores, c_qualityPlifsFeatures)
-
-         newSpliceAlign = zeros((dna_len,1))
-         newEstAlign    = zeros((est_len,1))
-         newWeightMatch = zeros((mm_len,1))
-         newQualityPlifsFeatures = zeros((self.run['totalQualSuppPoints'],1))
-
-         for i in range(dna_len):
-            newSpliceAlign[i] = c_SpliceAlign[i]
-
-         for i in range(est_len):
-            newEstAlign[i] = c_EstAlign[i]
-
-         for i in range(mm_len):
-            newWeightMatch[i] = c_WeightMatch[i]
-
-         newDPScores = c_DPScores[0]
-
-         for i in range(run['totalQualSuppPoints']):
-            newQualityPlifsFeatures[i] = c_qualityPlifsFeatures[i]
-
-         del c_SpliceAlign
-         del c_EstAlign
-         del c_WeightMatch
-         del c_DPScores
-         del c_qualityPlifsFeatures
-         del currentAlignment
-
-         newSpliceAlign = newSpliceAlign.reshape(1,dna_len)
-         newWeightMatch = newWeightMatch.reshape(1,mm_len)
-         true_map = [0]*2
-         true_map[0] = 1
-         pathNr = 0
-
-         dna_array = [0.0]*result_len
-         est_array = [0.0]*result_len
-
-         for r_idx in range(result_len):
-            dna_array[r_idx] = c_dna_array[r_idx]
-            est_array[r_idx] = c_est_array[r_idx]
-
-         _newSpliceAlign = newSpliceAlign.flatten().tolist()[0]
-         _newEstAlign = newEstAlign.flatten().tolist()[0]
+            if self.run['enable_quality_scores']:
+               quality = currentQualities[quality_index]
+            else:
+               quality = [40]*len(read)
 
-         line1,line2,line3 = pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array)
-         self.plog(line1+'\n')
-         self.plog(line2+'\n')
-         self.plog(line3+'\n')
+            try:
+               currentDNASeq, currentAcc, currentDon = self.seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop)
+            except:
+               self.problem_ctr += 1
+               continue
 
-         e1_b_off,e1_e_off,e2_b_off,e2_e_off,newExons = self.evaluateExample(dna,est,exons,newSpliceAlign,newEstAlign,currentSplitPos,exampleIdx)
+            if not self.run['enable_splice_signals']:
+               for idx,elem in enumerate(currentDon):
+                  if elem != -inf:
+                     currentDon[idx] = 0.0
 
-         one_prediction = {'e1_b_off':e1_b_off,'e1_e_off':e1_e_off,
-         'e2_b_off':e2_b_off ,'e2_e_off':e2_e_off,\
-         'predExons':newExons, 'trueExons':exons,\
-         'dna':dna, 'est':est, 'exampleIdx':exampleIdx,\
-         'realRestPos':currentRealRestPos,\
-         'DPScores':newDPScores,
-         'fRead':fRead
-         }
+               for idx,elem in enumerate(currentAcc):
+                  if elem != -inf:
+                     currentAcc[idx] = 0.0
 
-         allPredictions.append(one_prediction)
+            current_prediction = self.calc_alignment(currentDNASeq, read,\
+            quality, currentDon, currentAcc, d, a, h, mmatrix, qualityPlifs)
 
-         if e1_b_off != None:
-            exon1Begin.append(e1_b_off)
-            exon1End.append(e1_e_off)
-            exon2Begin.append(e2_b_off)
-            exon2End.append(e2_e_off)
-            allRealCorrectSplitPos.append(currentRealRestPos)
-         else:
-            allWrongExons.append((newExons,exons))
-            allRealWrongSplitPos.append(currentRealRestPos)
+            current_prediction['id']         = id
+            current_prediction['chr']        = chromo
+            current_prediction['strand']     = strand
+            current_prediction['start_pos']  = genomicSeq_start
 
-         logfile = self.logfh
+            allPredictions.append(current_prediction)
 
-         if e1_b_off == 0 and e1_e_off == 0 and e2_b_off == 0 and e2_e_off == 0:
-            print >> logfile, 'example %d correct' % exampleIdx
-         else:
-            print >> logfile, 'example %d wrong' % exampleIdx
+      if not self.qpalma_debug_mode:
+         self.FinalizePrediction(allPredictions)
+      else:
+         return allPredictions
 
-      e1Begin_pos,e1Begin_neg,e1End_pos,e1End_neg,mean_e1Begin_neg,mean_e1End_neg = self.evaluatePositions(exon1Begin,exon1End)
-      e2Begin_pos,e2Begin_neg,e2End_pos,e2End_neg,mean_e2Begin_neg,mean_e2End_neg = self.evaluatePositions(exon2Begin,exon2End)
 
-      correct_rest2error = {}
-      off_rest2error = {}
-      wrong_rest2error = {}
+   def FinalizePrediction(self,allPredictions):
+      """ End of the prediction loop we save all predictions in a pickle file and exit """
 
-      for e_idx in range(len(exon1Begin)):
-         e1b = exon1Begin[e_idx]
-         e1e = exon1End[e_idx]
+      cPickle.dump(allPredictions,open('%s.predictions.pickle'%(self.set_name),'w+'))
+      self.plog('Prediction completed\n')
+      mes =  'Problem ctr %d' % self.problem_ctr
+      self.plog(mes+'\n')
+      self.logfh.close()
+      sys.exit(0)
 
-         e2b = exon2Begin[e_idx]
-         e2e = exon2End[e_idx]
 
-         current_elem = allRealCorrectSplitPos[e_idx]
+   def calc_alignment(self, dna, read, quality, don_supp, acc_supp, d, a, h, mmatrix, qualityPlifs):
+      """
+      Given two sequences and the parameters we calculate on alignment
+      """
 
-         if e1b == 0 and e1e == 0 and e2b == 0 and e2e == 0:
-            try:
-               correct_rest2error[current_elem] += 1
-            except:
-               correct_rest2error[current_elem] = 1
-         
-         if not (e1b == 0 and e1e == 0 and e2b == 0 and e2e == 0):
-            try:
-               off_rest2error[current_elem] += 1
-            except:
-               off_rest2error[current_elem] = 1
+      run = self.run
+      donor, acceptor = compute_donacc(don_supp, acc_supp, d, a)
 
+      if '-' in read:
+         self.plog('found gap\n')
+         read = read.replace('-','')
+         assert len(read) == Conf.read_size
 
-      for e_idx in range(len(allWrongExons)):
+      ps = h.convert2SWIG()
 
-         current_elem = allRealWrongSplitPos[e_idx]
+      newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
+      newQualityPlifsFeatures, dna_array, read_array =\
+      self.do_alignment(dna,read,quality,mmatrix,donor,acceptor,ps,qualityPlifs,1,True)
 
-         try:
-            wrong_rest2error[current_elem] += 1
-         except:
-            wrong_rest2error[current_elem] = 1
+      mm_len = run['matchmatrixRows']*run['matchmatrixCols']
 
-      all_pos_correct = 0
-      for idx in range(len(exon1Begin)):
-         if exon1Begin[idx] == 0 and exon1End[idx] == 0\
-         and exon2Begin[idx] == 0 and exon2End[idx] == 0:
-            all_pos_correct += 1
+      true_map    = [0]*2
+      true_map[0] = 1
+      pathNr      = 0
 
-      logfile = self.logfh
-      print >> logfile, 'Total num. of examples: %d' % numExamples
-      print >> logfile, 'Number of total correct examples: %d' % all_pos_correct
-      print >> logfile, 'Correct positions:\t\t%d\t%d\t%d\t%d' % (len(e1Begin_pos),len(e1End_pos),len(e2Begin_pos),len(e2End_pos))
-      print >> logfile, 'Incorrect positions:\t\t%d\t%d\t%d\t%d' % (len(e1Begin_neg),len(e1End_neg),len(e2Begin_neg),len(e2End_neg))
-      print >> logfile, 'Mean of pos. offset:\t\t%.2f\t%.2f\t%.2f\t%.2f' % (mean_e1Begin_neg,mean_e1End_neg,mean_e2Begin_neg,mean_e2End_neg)
+      _newSpliceAlign   = array.array('B',newSpliceAlign)
+      _newEstAlign      = array.array('B',newEstAlign)
+       
+      #(qStart, qEnd, tStart, tEnd, num_exons, qExonSizes, qStarts, qEnds, tExonSizes, tStarts, tEnds)
+      alignment = get_alignment(_newSpliceAlign,_newEstAlign, dna_array, read_array) 
 
-      print 'Total num. of examples: %d' % numExamples
-      print 'Number of total correct examples: %d' % all_pos_correct
-      print 'Correct positions:\t\t%d\t%d\t%d\t%d' % (len(e1Begin_pos),len(e1End_pos),len(e2Begin_pos),len(e2End_pos))
-      print 'Incorrect positions:\t\t%d\t%d\t%d\t%d' % (len(e1Begin_neg),len(e1End_neg),len(e2Begin_neg),len(e2End_neg))
-      print 'Mean of pos. offset:\t\t%.2f\t%.2f\t%.2f\t%.2f' % (mean_e1Begin_neg,mean_e1End_neg,mean_e2Begin_neg,mean_e2End_neg)
-   
-      #print 'total correct'
-      #print correct_rest2error
+      dna_array   = array.array('B',dna_array)
+      read_array  = array.array('B',read_array)
 
-      #import pylab
-      #
-      #y_values = []
-      #for overlap in range(36):
-      #   result = 0
-      #   try:
-      #      cv = off_rest2error[overlap]
-      #   except:
-      #      cv = 0
-
-      #   result += cv
-
-      #   try:
-      #      cv = wrong_rest2error[overlap]
-      #   except:
-      #      cv = 0
-
-      #   result += cv
-
-      #   y_values.append(result/(1.0*numExamples))
-
-      #pylab.bar(range(36),y_values,width=0.2,align='center')
-      #pylab.xticks( numpy.arange(0,36,1) )
-      #pylab.savefig('%s_error_vs_overlap.eps'%run['name'])
-      #pylab.clf()
-      #raw_input()
-      cPickle.dump(allPredictions,open('%s_allPredictions'%run['name'],'w+'))
-
-      #print 'some positions off'
-      #print off_rest2error
-      #import pylab
-      #pylab.bar(off_rest2error.keys(),off_rest2error.values(),width=0.2,align='center')
-      ##pylab.show()
-      #pylab.xticks( numpy.arange(0,max(off_rest2error.keys())+1,1) )
-      #pylab.savefig('%s_offset.eps'%run['name'])
-      #pylab.clf()
-      ##raw_input()
-
-      #print 'total wrong'
-      #print wrong_rest2error
-      #import pylab
-      #pylab.bar(wrong_rest2error.keys(),wrong_rest2error.values(),width=0.2,align='center')
-      #pylab.xticks( numpy.arange(0,max(wrong_rest2error.keys())+1,1) )
-      #pylab.savefig('%s_wrong.eps'%run['name'])
-      #pylab.clf()
-
-      print 'Prediction completed'
-
-   def evaluatePositions(self,eBegin,eEnd):
-
-      eBegin_pos = [elem for elem in eBegin if elem == 0]
-      eBegin_neg = [elem for elem in eBegin if elem != 0]
-      eEnd_pos = [elem for elem in eEnd if elem == 0]
-      eEnd_neg = [elem for elem in eEnd if elem != 0]
-
-      mean_eBegin_neg = 0
-      for idx in range(len(eBegin_neg)):
-         mean_eBegin_neg += eBegin_neg[idx]
-         
-      try:
-         mean_eBegin_neg /= 1.0*len(eBegin_neg)
-      except:
-         mean_eBegin_neg = -1
+      newExons = self.calculatePredictedExons(newSpliceAlign)
 
-      mean_eEnd_neg = 0
-      for idx in range(len(eEnd_neg)):
-         mean_eEnd_neg += eEnd_neg[idx]
+      current_prediction = {'predExons':newExons, 'dna':dna, 'read':read, 'DPScores':newDPScores,\
+      'alignment':alignment,'spliceAlign':_newSpliceAlign,'estAlign':_newEstAlign,\
+      'dna_array':dna_array, 'read_array':read_array }
 
-      try:
-         mean_eEnd_neg /= 1.0*len(eEnd_neg)
-      except:
-         mean_eEnd_neg = -1
+      return current_prediction
 
-      return eBegin_pos,eBegin_neg,eEnd_pos,eEnd_neg,mean_eBegin_neg,mean_eEnd_neg
 
-   def evaluateExample(self,dna,est,exons,SpliceAlign,newEstAlign,spos,exampleIdx):
+   def calculatePredictedExons(self,SpliceAlign):
       newExons = []
       oldElem = -1
-      SpliceAlign = SpliceAlign.flatten().tolist()[0]
       SpliceAlign.append(-1)
       for pos,elem in enumerate(SpliceAlign):
          if pos == 0:
@@ -1031,192 +665,4 @@ class QPalma:
          if oldElem == 0 and elem != 0: # end of exon
             newExons.append(pos)
 
-      e1_b_off,e1_e_off,e2_b_off,e2_e_off = 0,0,0,0
-
-      self.plog(("Example %d"%exampleIdx) + str(exons) + " "+  str(newExons) + "\n")
-      #self.plog(("SpliceAlign " + str(SpliceAlign)+ "\n"))
-      self.plog(("read: " + str(est)+ "\n"))
-
-      if len(newExons) == 4:
-         e1_begin,e1_end = newExons[0],newExons[1]
-         e2_begin,e2_end = newExons[2],newExons[3]
-      else:
-         return None,None,None,None,newExons
-
-      e1_b_off = int(math.fabs(e1_begin - exons[0,0]))
-      e1_e_off = int(math.fabs(e1_end - exons[0,1]))
-
-      e2_b_off = int(math.fabs(e2_begin - exons[1,0]))
-      e2_e_off = int(math.fabs(e2_end - exons[1,1]))
-
-      return e1_b_off,e1_e_off,e2_b_off,e2_e_off,newExons
-
-def fetch_genome_info(ginfo_filename):
-   if not os.path.exists(ginfo_filename):
-      cmd = ['']*4
-      cmd[0] = 'addpath /fml/ag-raetsch/home/fabio/svn/tools/utils'
-      cmd[1] = 'addpath /fml/ag-raetsch/home/fabio/svn/tools/genomes'
-      cmd[2] = 'genome_info = init_genome(\'%s\')' % gen_file
-      cmd[3] = 'save genome_info.mat genome_info'  
-      full_cmd = "matlab -nojvm -nodisplay -r \"%s; %s; %s; %s; exit\"" % (cmd[0],cmd[1],cmd[2],cmd[3])
-
-      obj = subprocess.Popen(full_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
-      out,err = obj.communicate()
-      assert err == '', 'An error occured!\n%s'%err
-
-      ginfo = scipy.io.loadmat('genome_info.mat')
-      cPickle.dump(self.genome_info,open(ginfo_filename,'w+'))
-      return ginfo['genome_info']
-
-   else:
-      return cPickle.load(open(ginfo_filename))
-
-
-
-def calcStat(Acceptor,Donor,Exons):
-   maxAcc = -100
-   minAcc = 100
-   maxDon = -100
-   minDon = 100
-
-   acc_vec_pos = []
-   acc_vec_neg = []
-   don_vec_pos = []
-   don_vec_neg = []
-
-   for jdx in range(len(Acceptors)):
-      currentExons = Exons[jdx]
-      currentAcceptor = Acceptors[jdx]
-      currentAcceptor = currentAcceptor[1:]
-      currentAcceptor.append(-inf)
-      currentDonor = Donors[jdx]
-
-      for idx,elem in enumerate(currentAcceptor):
-         if idx == (int(currentExons[1,0])-1): # acceptor site
-            acc_vec_pos.append(elem)
-         else:
-            acc_vec_neg.append(elem)
-
-      for idx,elem in enumerate(currentDonor):
-         if idx == (int(currentExons[0,1])): # donor site
-            don_vec_pos.append(elem)
-         else:
-            don_vec_neg.append(elem)
-
-   acc_pos = [elem for elem in acc_vec_pos if elem != -inf]
-   acc_neg = [elem for elem in acc_vec_neg if elem != -inf]
-   don_pos = [elem for elem in don_vec_pos if elem != -inf]
-   don_neg = [elem for elem in don_vec_neg if elem != -inf]
-
-   #pdb.set_trace()
-
-   for idx in range(len(Sequences)):
-      acc = [elem for elem in Acceptors[idx] if elem != -inf]
-      maxAcc = max(max(acc),maxAcc)
-      minAcc = min(min(acc),minAcc)
-
-      don = [elem for elem in Donors[idx] if elem != -inf]
-      maxDon = max(max(don),maxDon)
-      minDon = min(min(don),minDon)
-
-def pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array):
-   (qStart, qEnd, tStart, tEnd, num_exons, qExonSizes, qStarts, qEnds, tExonSizes, tStarts, tEnds) =\
-         pu.get_splice_info(_newSpliceAlign,_newEstAlign)
-
-   t_strand = '+'
-   translation = '-ACGTN_'    #how aligned est and dna sequence is displayed
-                              #(gap_char, 5 nucleotides, intron_char) 
-   comparison_char = '| '     #first: match_char, second: intron_char
-
-   (exon_length, identity, ssQuality, exonQuality, comparison, qIDX, tIDX) =\
-             pu.comp_identity(dna_array, est_array, t_strand, qStart, tStart, translation, comparison_char)
-
-   first_identity = None
-   last_identity = None 
-   for i in range(len(comparison)):
-    if comparison[i] == '|' and first_identity is None: 
-      first_identity = i 
-    if comparison[-i] == '|' and last_identity is None: 
-      last_identity = len(comparison) - i - 1
-
-   try:
-      for idx in range(len(dna_array)):
-         dna_array[idx] = translation[int(dna_array[idx])]
-         est_array[idx] = translation[int(est_array[idx])]
-   except:
-      pdb.set_trace()
-
-   line1 = "".join(dna_array)
-   line2 = comparison
-   line3 = "".join(est_array)
-
-   return line1,line2,line3
-
-def calc_info(acc,don,exons,qualities):
-   min_score = 100
-   max_score = -100
-
-   for elem in acc:
-      for score in elem:
-         if score != -inf:
-            min_score = min(min_score,score)
-            max_score = max(max_score,score)
-
-   print 'Acceptors max/min: %f / %f' % (max_score,min_score)
-
-   min_score = 100
-   max_score = -100
-
-   for elem in don:
-      for score in elem:
-         if score != -inf:
-            min_score = min(min_score,score)
-            max_score = max(max_score,score)
-
-   print 'Donor max/min: %f / %f' % (max_score,min_score)
-
-   min_score = 10000
-   max_score = 0
-   mean_intron_len = 0
-
-   for elem in exons:
-      intron_len = int(elem[1,0] - elem[0,1])
-      mean_intron_len += intron_len
-      min_score = min(min_score,intron_len)
-      max_score = max(max_score,intron_len)
-
-   mean_intron_len /= 1.0*len(exons)
-   print 'Intron length max/min: %d / %d mean length %f' % (max_score,min_score,mean_intron_len)
-
-   min_score = 10000
-   max_score = 0
-   mean_quality = 0
-
-   for qVec in qualities:
-      for elem in qVec:
-         min_score = min(min_score,elem)
-         max_score = max(max_score,elem)
-
-   print 'Quality values max/min: %d / %d mean' % (max_score,min_score)
-
-
-###########################
-# A simple command line 
-# interface
-###########################
-
-if __name__ == '__main__':
-   qpalma = QPalma()
-
-   mode = sys.argv[1]
-
-   if len(sys.argv) == 2 and mode == 'train':
-      qpalma.train()
-
-   elif len(sys.argv) == 3 and mode == 'predict':
-      param_filename = sys.argv[2]
-      assert os.path.exists(param_filename)
-      qpalma.evaluate(param_filename)
-   else:
-      print 'You have to choose between training or prediction mode:'
-      print 'python qpalma. py (train|predict) <param_file>' 
+      return newExons