+ added some text and references to the documentation
[qpalma.git] / scripts / qpalma_main.py
index 4c778b0..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 together 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 pdb
-import re
 import os.path
+import pdb
+import sys
 
-from compile_dataset import getSpliceScores
+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.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.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
 
-# this two imports are needed for the load genomic resp. interval query
-# functions
-from Genefinding import *
-from genome_utils import load_genomic
+class SpliceSiteException:
+   pass
 
-from Utils import calc_stat, calc_info, pprint_alignment
 
+def getData(training_set,exampleKey,run):
+   """ This function...  """
 
-def unbracket_est(est):
-   new_est = ''
-   e = 0
+   currentSeqInfo,original_est,currentQualities,currentExons = training_set[exampleKey]
+   id,chr,strand,up_cut,down_cut = currentSeqInfo
 
-   while True:
-      if e >= len(est):
-         break
+   est = original_est
+   est = "".join(est)
+   est = est.lower()
+   est = unbracket_est(est)
+   est = est.replace('-','')
 
-      if est[e] == '[':
-         new_est += est[e+2]
-         e += 4
-      else:
-         new_est += est[e]
-         e += 1
+   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]]
 
-   return "".join(new_est).lower()
+      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
-
-      if self.run['mode'] == 'normal':
-         self.use_quality_scores = False
-
-      elif self.run['mode'] == 'using_quality_scores':
-         self.use_quality_scores = True
-      else:
-         assert(False)
+      self.seqInfo = seqInfo
 
 
    def plog(self,string):
@@ -95,7 +109,6 @@ class QPalma:
       Given the needed input this method calls the QPalma C module which
       calculates a dynamic programming in order to obtain an alignment
       """
-      run = self.run
 
       dna_len = len(dna)
       est_len = len(est)
@@ -104,7 +117,7 @@ class QPalma:
       chastity = QPalmaDP.createDoubleArrayFromList([.0]*est_len)
 
       matchmatrix = QPalmaDP.createDoubleArrayFromList(mmatrix.flatten().tolist()[0])
-      mm_len = run['matchmatrixRows']*run['matchmatrixCols']
+      mm_len = self.run['matchmatrixRows']*self.run['matchmatrixCols']
 
       d_len = len(donor)
       donor = QPalmaDP.createDoubleArrayFromList(donor)
@@ -112,104 +125,47 @@ class QPalma:
       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)
+      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, remove_duplicate_scores,
-       print_matrix)
-
-      c_SpliceAlign       = QPalmaDP.createIntArrayFromList([0]*(dna_len*current_num_path))
-      c_EstAlign          = QPalmaDP.createIntArrayFromList([0]*(est_len*current_num_path))
-      c_WeightMatch       = QPalmaDP.createIntArrayFromList([0]*(mm_len*current_num_path))
-      c_DPScores   = QPalmaDP.createDoubleArrayFromList([.0]*current_num_path)
-
-      c_qualityPlifsFeatures = QPalmaDP.createDoubleArrayFromList([.0]*(run['totalQualSuppPoints']*current_num_path))
+       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()
-         c_dna_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-         c_est_array = QPalmaDP.createIntArrayFromList([0]*(result_len))
-
-         currentAlignment.getAlignmentArrays(c_dna_array,c_est_array)
-
-         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()
       else:
          dna_array = None
          est_array = None
 
-      currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign,\
-      c_WeightMatch, c_DPScores, c_qualityPlifsFeatures)
-
-      #print 'After calling getAlignmentResults...'
-
-      newSpliceAlign = zeros((current_num_path*dna_len,1))
-      newEstAlign    = zeros((est_len*current_num_path,1))
-      newWeightMatch = zeros((current_num_path*mm_len,1))
-      newDPScores    = zeros((current_num_path,1))
-      newQualityPlifsFeatures = zeros((run['totalQualSuppPoints']*current_num_path,1))
-
-      for i in range(dna_len*current_num_path):
-         newSpliceAlign[i] = c_SpliceAlign[i]
-
-      for i in range(est_len*current_num_path):
-         newEstAlign[i] = c_EstAlign[i]
-
-      for i in range(mm_len*current_num_path):
-         newWeightMatch[i] = c_WeightMatch[i]
-
-      for i in range(current_num_path):
-         newDPScores[i] = c_DPScores[i]
-
-      if self.use_quality_scores:
-         for i in range(run['totalQualSuppPoints']*current_num_path):
-            newQualityPlifsFeatures[i] = c_qualityPlifsFeatures[i]
-
-      del c_SpliceAlign
-      del c_EstAlign
-      del c_WeightMatch
-      del c_DPScores
-      del c_qualityPlifsFeatures
-      del currentAlignment
+      newSpliceAlign, newEstAlign, newWeightMatch, newDPScores, newQualityPlifsFeatures =\
+      currentAlignment.getAlignmentResultsNew()
 
       return newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
       newQualityPlifsFeatures, dna_array, est_array
 
 
-   def train(self):
-      run = self.run
-
-      full_working_path = os.path.join(run['experiment_path'],run['name'])
+   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)
-      os.mkdir(full_working_path)
+      #assert not os.path.exists(full_working_path)
+      if 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)
 
-      cPickle.dump(run,open('run_object.pickle','w+'))
-
       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))
-
-      data_filename = self.run['dataset_filename']
-
-      SeqInfo, Exons, OriginalEsts, Qualities,\
-      AlternativeSequences = paths_load_data(data_filename,'training',None,self.ARGS)
+      self.plog("%s\n"%str(self.run))
 
-      # Load the whole dataset 
       if self.run['mode'] == 'normal':
          self.use_quality_scores = False
 
@@ -218,68 +174,59 @@ class QPalma:
       else:
          assert(False)
 
-      self.SeqInfo     = SeqInfo
-      self.Exons       = Exons
-      self.OriginalEsts= OriginalEsts
-      self.Qualities   = Qualities
 
-      #calc_info(self.Exons,self.Qualities)
+   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)
 
-      beg = run['training_begin']
-      end = run['training_end']
+      solver.enforceMonotonicity(lengthSP,lengthSP+donSP)
+      solver.enforceMonotonicity(lengthSP+donSP,lengthSP+donSP+accSP)
 
-      SeqInfo     = SeqInfo[beg:end]
-      Exons       = Exons[beg:end]
-      OriginalEsts= OriginalEsts[beg:end]
-      Qualities   = Qualities[beg:end]
+      return solver
 
-      # number of training instances
-      N = numExamples = len(SeqInfo) 
-      assert len(Exons) == N and len(OriginalEsts) == N and len(Qualities) == N,\
-      'The Exons,Acc,Don,.. arrays are of different lengths'
 
+   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))
@@ -292,50 +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
-
-            currentSeqInfo = SeqInfo[exampleIdx]
-            chr,strand,up_cut,down_cut = currentSeqInfo 
-
-            est = OriginalEsts[exampleIdx] 
-            est = "".join(est)
-            est = est.lower()
-            est = unbracket_est(est)
-            est = est.replace('-','')
-
-            original_est = OriginalEsts[exampleIdx] 
-            original_est = "".join(original_est)
-            original_est = original_est.lower()
-
-            est_len = len(est)
+         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_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)
             dna_len = len(dna)
 
-            #don_supp = don_supp[1:] + [-inf] 
-            #acc_supp = acc_supp[1:] + [-inf]
-
-            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][0]
-
-            if not run['enable_quality_scores']:
-               quality = [40]*len(est)
-
-            exons = Exons[exampleIdx] 
-            exons -= up_cut
+            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):
@@ -353,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)
@@ -386,45 +313,20 @@ class QPalma:
             # 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()
 
-            _newSpliceAlign, _newEstAlign, _newWeightMatch, _newDPScores,\
-            _newQualityPlifsFeatures, unneeded1, unneeded2 =\
+            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']
 
-            # old code removed
-
-            newSpliceAlign = _newSpliceAlign
-            newEstAlign    = _newEstAlign
-            newWeightMatch = _newWeightMatch
-            newDPScores    = _newDPScores
-            newQualityPlifsFeatures = _newQualityPlifsFeatures
-
             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.
@@ -432,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
@@ -447,6 +348,8 @@ class QPalma:
                apen = mat(a.penalties).reshape(len(a.penalties),1)
                features = numpy.vstack([hpen, dpen, apen, mmatrix[:], totalQualityPenalties[:]])
 
+               featureVectors[:,exampleIdx] = allWeights[:,pathNr+1]
+
                AlignmentScores[pathNr+1] = (allWeights[:,pathNr+1].T * features)[0,0]
 
                distinct_scores = False
@@ -490,27 +393,13 @@ 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)
-
-                  dna_array = [0.0]*result_len
-                  est_array = [0.0]*result_len
+                  #result_len = currentAlignment.getResultLength()
 
-                  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
                if firstFalseIdx != -1:
@@ -520,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:
@@ -555,82 +443,85 @@ class QPalma:
                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)
+
 
-      cPickle.dump(param,open('param_%d.pickle'%param_idx,'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 evaluate(self,param_filename):
-      run = self.run
-      beg = run['prediction_begin']
-      end = run['prediction_end']
+   def init_prediction(self,dataset_fn,prediction_keys,param_fn,set_name):
+      """
+      Performing a prediction takes...
+      """
+      self.set_name = set_name
 
-      data_filename = self.run['dataset_filename']
-      Sequences, Acceptors, Donors, Exons, Ests, OriginalEsts, Qualities,\
-      UpCut, StartPos, AlternativeSequences=\
-      paths_load_data(data_filename,'training',None,self.ARGS)
+      #full_working_path = os.path.join(run['alignment_dir'],run['name'])
+      full_working_path = self.run['result_dir']
 
-      self.Sequences   = Sequences
-      self.Exons       = Exons
-      self.Ests        = Ests
-      self.OriginalEsts= OriginalEsts
-      self.Qualities   = Qualities
-      self.Donors      = Donors
-      self.Acceptors   = Acceptors
-      self.UpCut       = UpCut
-      self.StartPos    = StartPos
+      print 'full_working_path is %s' % full_working_path 
 
-      self.AlternativeSequences = AlternativeSequences
+      #assert not os.path.exists(full_working_path)
+      if not os.path.exists(full_working_path):
+         os.mkdir(full_working_path)
 
-      #calc_info(self.Acceptors,self.Donors,self.Exons,self.Qualities)
-      #print 'leaving constructor...'
+      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
-      self.plog('##### Prediction on the training set #####\n')
+      self.logfh = open('_qpalma_predict_%s.log'%set_name,'w+')
 
-      self.predict(param_filename,0,beg,'TRAIN')
-      
-      # predict on test set
-      self.plog('##### Prediction on the test set #####\n')
-      self.predict(param_filename,beg,end,'TEST')
+      # 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.plog('##### Finished prediction #####\n')
-      self.logfh.close()
+      # Load parameter vector to predict with
+      param = cPickle.load(open(param_fn))
 
-   def predict(self,param_filename,beg,end,set_flag):
-      """
-      Performing a prediction takes...
+      self.predict(prediction_set,param)
 
-      """
 
-      run = self.run
+   def predict(self,prediction_set,param):
+      """
+      This method...
+      """
 
       if self.run['mode'] == 'normal':
          self.use_quality_scores = False
@@ -640,118 +531,46 @@ 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]
-      UpCut       = self.UpCut[beg:end]
-      StartPos    = self.StartPos[beg:end]
-
-      AlternativeSequences = self.AlternativeSequences[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'
-      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
+      # 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)
+      set_param_palma(param,self.ARGS.train_with_intronlengthinformation,self.run)
 
-      #############################################################################################
-      # Prediction
-      #############################################################################################
-      self.plog('Starting prediction...\n')
+      if not self.qpalma_debug_mode:
+         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']
-
-      totalQualityPenalties = zeros((totalQualSP,1))
+      self.problem_ctr = 0
 
       # where we store the predictions
       allPredictions = []
 
-      # beginning of the prediction loop
-      for exampleIdx in range(numExamples):
-         self.plog('Loading example nr. %d...\n'%exampleIdx)
-
-         dna = Sequences[exampleIdx] 
-         est = Ests[exampleIdx] 
-
-         new_est = unbracket_est(est)
-
+      # we take the first quality vector of the tuple of quality vectors
+      quality_index = 0
 
-         exons = Exons[exampleIdx]
-
-         current_up_cut = UpCut[exampleIdx]
-
-         current_start_pos = StartPos[exampleIdx]
-
-         currentAlternatives = AlternativeSequences[exampleIdx]
-
-         #est = est.replace('-','')
-         #original_est = OriginalEsts[exampleIdx] 
-         #original_est = "".join(original_est)
-         #original_est = original_est.lower()
-         #currentSplitPos = SplitPos[exampleIdx]
-
-         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)
-
-         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
+      # 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]:
 
-            for idx,elem in enumerate(acc_supp):
-               if elem != -inf:
-                  acc_supp[idx] = 0.0
+            currentSeqInfo,read,currentQualities = example
 
-         current_example_predictions = []
+            id,chromo,strand,genomicSeq_start,genomicSeq_stop =\
+            currentSeqInfo 
 
-         # first make a prediction on the dna fragment which comes from the ground truth                  
-         current_prediction = self.calc_alignment(dna, est, exons, quality, don_supp, acc_supp, d, a, h, mmatrix, qualityPlifs)
-         current_prediction['exampleIdx'] = exampleIdx
-         current_prediction['start_pos']  = current_start_pos
-         current_prediction['label'] = True
+            if not self.qpalma_debug_mode:
+               self.plog('Loading example id: %d...\n'% int(id))
 
-         current_example_predictions.append(current_prediction)
+            if self.run['enable_quality_scores']:
+               quality = currentQualities[quality_index]
+            else:
+               quality = [40]*len(read)
 
-         # then make predictions for all dna fragments that where occurring in
-         # the vmatch results
-         for alternative_alignment in currentAlternatives:
-            chr, strand, genomicSeq_start, genomicSeq_stop, currentLabel = alternative_alignment
-            currentDNASeq, currentAcc, currentDon = get_seq_and_scores(chr,strand,genomicSeq_start,genomicSeq_stop,run['dna_flat_files'])
+            try:
+               currentDNASeq, currentAcc, currentDon = self.seqInfo.get_seq_and_scores(chromo,strand,genomicSeq_start,genomicSeq_stop)
+            except:
+               self.problem_ctr += 1
+               continue
 
-            if not run['enable_splice_signals']:
+            if not self.run['enable_splice_signals']:
                for idx,elem in enumerate(currentDon):
                   if elem != -inf:
                      currentDon[idx] = 0.0
@@ -760,77 +579,72 @@ class QPalma:
                   if elem != -inf:
                      currentAcc[idx] = 0.0
 
-            current_prediction = self.calc_alignment(currentDNASeq, est, exons,\
+            current_prediction = self.calc_alignment(currentDNASeq, read,\
             quality, currentDon, currentAcc, d, a, h, mmatrix, qualityPlifs)
-            current_prediction['exampleIdx'] = exampleIdx
-            current_prediction['start_pos'] = current_start_pos
-            current_prediction['alternative_start_pos'] = genomicSeq_start
-            current_prediction['label'] = currentLabel
 
-            current_example_predictions.append(current_prediction)
+            current_prediction['id']         = id
+            current_prediction['chr']        = chromo
+            current_prediction['strand']     = strand
+            current_prediction['start_pos']  = genomicSeq_start
+
+            allPredictions.append(current_prediction)
+
+      if not self.qpalma_debug_mode:
+         self.FinalizePrediction(allPredictions)
+      else:
+         return allPredictions
 
-         allPredictions.append(current_example_predictions)
 
-      # end of the prediction loop we save all predictions in a pickle file and exit
-      cPickle.dump(allPredictions,open('%s_allPredictions_%s'%(run['name'],set_flag),'w+'))
-      print 'Prediction completed'
+   def FinalizePrediction(self,allPredictions):
+      """ End of the prediction loop we save all predictions in a pickle file and exit """
 
+      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)
 
-   def calc_alignment(self, dna, est, exons, quality, don_supp, acc_supp, d, a, h, mmatrix, qualityPlifs):
+
+   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
       """
 
       run = self.run
-
       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)
-
-      dna = str(dna)
-      est = str(est)
-      dna_len = len(dna)
-      est_len = len(est)
+      if '-' in read:
+         self.plog('found gap\n')
+         read = read.replace('-','')
+         assert len(read) == Conf.read_size
 
       ps = h.convert2SWIG()
 
-      __newSpliceAlign, __newEstAlign, __newWeightMatch, __newDPScores,\
-      __newQualityPlifsFeatures, __dna_array, __est_array =\
-      self.do_alignment(dna,est,quality,mmatrix,donor,acceptor,ps,qualityPlifs,1,True)
+      newSpliceAlign, newEstAlign, newWeightMatch, newDPScores,\
+      newQualityPlifsFeatures, dna_array, read_array =\
+      self.do_alignment(dna,read,quality,mmatrix,donor,acceptor,ps,qualityPlifs,1,True)
 
       mm_len = run['matchmatrixRows']*run['matchmatrixCols']
 
-      # old code removed
-
-      newSpliceAlign = __newSpliceAlign
-      newEstAlign    = __newEstAlign
-      newWeightMatch = __newWeightMatch
-      newDPScores    = __newDPScores
-      newQualityPlifsFeatures = __newQualityPlifsFeatures
-      dna_array = __dna_array
-      est_array = __est_array
-
-      newSpliceAlign = newSpliceAlign.reshape(1,dna_len)
-      newWeightMatch = newWeightMatch.reshape(1,mm_len)
-      true_map = [0]*2
+      true_map    = [0]*2
       true_map[0] = 1
-      pathNr = 0
+      pathNr      = 0
 
-      _newSpliceAlign = newSpliceAlign.flatten().tolist()[0]
-      _newEstAlign = newEstAlign.flatten().tolist()[0]
+      _newSpliceAlign   = array.array('B',newSpliceAlign)
+      _newEstAlign      = array.array('B',newEstAlign)
        
-      if False:
-         line1,line2,line3 = pprint_alignment(_newSpliceAlign,_newEstAlign, dna_array, est_array)
-         self.plog(line1+'\n')
-         self.plog(line2+'\n')
-         self.plog(line3+'\n')
+      #(qStart, qEnd, tStart, tEnd, num_exons, qExonSizes, qStarts, qEnds, tExonSizes, tStarts, tEnds)
+      alignment = get_alignment(_newSpliceAlign,_newEstAlign, dna_array, read_array) 
+
+      dna_array   = array.array('B',dna_array)
+      read_array  = array.array('B',read_array)
 
       newExons = self.calculatePredictedExons(newSpliceAlign)
 
-      current_prediction = {'predExons':newExons, 'trueExons':exons,\
-      'dna':dna, 'est':est, 'DPScores':newDPScores}
+      current_prediction = {'predExons':newExons, 'dna':dna, 'read':read, 'DPScores':newDPScores,\
+      'alignment':alignment,'spliceAlign':_newSpliceAlign,'estAlign':_newEstAlign,\
+      'dna_array':dna_array, 'read_array':read_array }
 
       return current_prediction
 
@@ -838,7 +652,6 @@ class QPalma:
    def calculatePredictedExons(self,SpliceAlign):
       newExons = []
       oldElem = -1
-      SpliceAlign = SpliceAlign.flatten().tolist()[0]
       SpliceAlign.append(-1)
       for pos,elem in enumerate(SpliceAlign):
          if pos == 0:
@@ -853,57 +666,3 @@ class QPalma:
             newExons.append(pos)
 
       return newExons
-
-
-def get_seq_and_scores(chr,strand,genomicSeq_start,genomicSeq_stop,dna_flat_files):
-   """
-   This function expects an interval, chromosome and strand information and
-   returns then the genomic sequence of this interval and the associated scores.
-   """
-
-   chrom         = 'chr%d' % chr
-   genomicSeq = load_genomic(chrom,strand,genomicSeq_start-1,genomicSeq_stop,dna_flat_files,one_based=False)
-   genomicSeq = genomicSeq.lower()
-
-   # check the obtained dna sequence
-   assert genomicSeq != '', 'load_genomic returned empty sequence!'
-   #for elem in genomicSeq:
-   #   if not elem in alphabet:
-   
-   no_base = re.compile('[^acgt]')
-   genomicSeq = no_base.sub('n',genomicSeq)
-
-   intervalBegin  = genomicSeq_start-100
-   intervalEnd    = genomicSeq_stop+100
-   currentDNASeq  = genomicSeq
-   seq_pos_offset = genomicSeq_start
-
-   currentAcc, currentDon = getSpliceScores(chr,strand,intervalBegin,intervalEnd,currentDNASeq,seq_pos_offset)
-
-   return currentDNASeq, currentAcc, currentDon
-
-
-###########################
-# A simple command line 
-# interface
-###########################
-
-if __name__ == '__main__':
-   mode = sys.argv[1]
-   run_obj_fn = sys.argv[2]
-
-   run_obj = cPickle.load(open(run_obj_fn))
-
-   qpalma = QPalma(run_obj)
-
-
-   if len(sys.argv) == 3 and mode == 'train':
-      qpalma.train()
-
-   elif len(sys.argv) == 4 and mode == 'predict':
-      param_filename = sys.argv[3]
-      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>'