+ added feature calculation for the labels
[qpalma.git] / python / qpalma.py
index a411ad2..4efc708 100644 (file)
@@ -11,6 +11,7 @@ import sys
 import subprocess
 import scipy.io
 import pdb
+import os.path
 
 from numpy.matlib import mat,zeros,ones,inf
 from numpy.linalg import norm
@@ -25,6 +26,7 @@ from paths_load_data_pickle import *
 from computeSpliceWeights import *
 from set_param_palma import *
 from computeSpliceAlign import *
+from computeSpliceAlignWithQuality import *
 from penalty_lookup_new import *
 from compute_donacc import *
 from TrainingParam import Param
@@ -32,6 +34,14 @@ from export_param import *
 
 import Configuration
 
+from Plif import Plf
+
+def getQualityFeatureCounts(qualityPlifs):
+   weightQuality = qualityPlifs[0].penalties
+   for currentPlif in qualityPlifs[1:]:
+      weightQuality = numpy.vstack([weightQuality, currentPlif.penalties])
+
+   return weightQuality 
 
 
 def initializeQualityScoringFunctions(numPlifs,numSuppPoints):
@@ -69,7 +79,6 @@ def initializeQualityScoringFunctions(numPlifs,numSuppPoints):
       curPlif = curPlif.convert2SWIG()
       qualityPlifs[idx] = curPlif
 
-   qualityPlifs = QPalmaDP.createPenaltyArrayFromList(qualityPlifs)
    return qualityPlifs
 
 class QPalma:
@@ -83,59 +92,11 @@ class QPalma:
       self.logfh = open('qpalma.log','w+')
       gen_file= '%s/genome.config' % self.ARGS.basedir
 
-      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')
-      self.genome_info = ginfo['genome_info']
+      ginfo_filename = 'genome_info.pickle'
+      self.genome_info = fetch_genome_info(ginfo_filename)
 
       self.plog('genome_info.basedir is %s\n'%self.genome_info.basedir)
 
-      self.C=1.0
-
-      # 'normal' means work like Palma
-      # 'using_quality_scores' means work like Palma plus using sequencing
-      # quality scores
-      self.mode = 'normal'
-      #self.mode = 'using_quality_scores'
-
-      # Here we specify the total number of parameters.
-      # When using quality scores our scoring function is defined as
-      #
-      # f: S x R x S -> R
-      # 
-      # as opposed to a usage without quality scores when we only have
-      # 
-      # f: S x S -> R 
-      #
-      self.numDonSuppPoints     = 30
-      self.numAccSuppPoints     = 30
-      self.numLengthSuppPoints  = 30 
-      if self.mode == 'normal':
-         self.sizeMMatrix          = 36
-      elif self.mode == 'using_quality_scores':
-         self.sizeMMatrix          = 728
-      else:
-         assert False, 'Wrong operation mode specified'
-
-      # this number defines the number of support points for one tuple (a,b)
-      # where 'a' comes with a quality score
-      self.numQualSuppPoints    = 10
-      self.numQualSuppPoints    = 0
-
-      self.numFeatures = self.numDonSuppPoints + self.numAccSuppPoints\
-      + self.numLengthSuppPoints + self.sizeMMatrix 
-
-      self.plog('Initializing problem...\n')
-
 
    def plog(self,string):
       self.logfh.write(string)
@@ -177,23 +138,30 @@ class QPalma:
 
       # Initialize solver 
       if not __debug__:
-         solver = SIQPSolver(self.numFeatures,self.numExamples,self.C,self.logfh)
+         self.plog('Initializing problem...\n')
+         solver = SIQPSolver(Configuration.numFeatures,Configuration.numExamples,Configuration.C,self.logfh)
 
       # stores the number of alignments done for each example (best path, second-best path etc.)
       num_path = [anzpath]*N 
       # stores the gap for each example
       gap      = [0.0]*N
 
-      qualityMatrix = zeros((self.numQualSuppPoints,1))
-
-      numPlifs = 24
-      numSuppPoints = 30
-
       #############################################################################################
       # Training
       #############################################################################################
       self.plog('Starting training...\n')
 
+      donSP       = Configuration.numDonSuppPoints
+      accSP       = Configuration.numAccSuppPoints
+      lengthSP    = Configuration.numLengthSuppPoints
+      mmatrixSP   = Configuration.sizeMMatrix
+      totalQualSP = Configuration.totalQualSuppPoints
+
+      currentPhi = zeros((Configuration.numFeatures,1))
+      totalQualityPenalties = zeros((totalQualSP,1))
+
+      #qualityMatrix = zeros((Configuration.numPlifSuppPoints*Configuration.numQualPlifs,1))
+
       iteration_nr = 0
 
       while True:
@@ -207,24 +175,28 @@ class QPalma:
             dna = Sequences[exampleIdx] 
             est = Ests[exampleIdx] 
 
+            quality = [0.0]*len(est)
+
             exons = Exons[exampleIdx] 
             # NoiseMatrix = Noises[exampleIdx] 
             don_supp = Donors[exampleIdx] 
             acc_supp = Acceptors[exampleIdx] 
 
             # Berechne die Parameter des wirklichen Alignments (but with untrained d,a,h ...)    
-            trueSpliceAlign, trueWeightMatch = computeSpliceAlign(dna, exons)
+            # trueSpliceAlign, trueWeightMatch = computeSpliceAlign(dna, exons)
+            trueSpliceAlign, trueWeightMatch, trueQualityPlifs = computeSpliceAlignWithQuality(dna, exons, quality)
             
             # Calculate the weights
             trueWeightDon, trueWeightAcc, trueWeightIntron = computeSpliceWeights(d, a, h, trueSpliceAlign, don_supp, acc_supp)
-            trueWeight = numpy.vstack([trueWeightIntron, trueWeightDon, trueWeightAcc, trueWeightMatch, qualityMatrix ])
 
-            currentPhi = zeros((self.numFeatures,1))
-            currentPhi[0:30]     = mat(d.penalties[:]).reshape(30,1)
-            currentPhi[30:60]    = mat(a.penalties[:]).reshape(30,1)
-            currentPhi[60:90]    = mat(h.penalties[:]).reshape(30,1)
-            currentPhi[90:126]   = mmatrix[:]
-            currentPhi[126:]   = qualityMatrix[:]
+            trueWeightQuality = getQualityFeatureCounts(trueQualityPlifs)
+            trueWeight = numpy.vstack([trueWeightIntron, trueWeightDon, trueWeightAcc, trueWeightMatch, trueWeightQuality])
+
+            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[:]
+            currentPhi[donSP+accSP+lengthSP+mmatrixSP:]                       = totalQualityPenalties[:]
 
             # Calculate w'phi(x,y) the total score of the alignment
             trueAlignmentScore = (trueWeight.T * currentPhi)[0,0]
@@ -232,7 +204,7 @@ class QPalma:
             # The allWeights vector is supposed to store the weight parameter
             # of the true alignment as well as the weight parameters of the
             # num_path[exampleIdx] other alignments
-            allWeights = zeros((self.numFeatures,num_path[exampleIdx]+1))
+            allWeights = zeros((Configuration.numFeatures,num_path[exampleIdx]+1))
             allWeights[:,0] = trueWeight[:,0]
 
             AlignmentScores = [0.0]*(num_path[exampleIdx]+1)
@@ -266,18 +238,18 @@ class QPalma:
             acceptor = QPalmaDP.createDoubleArrayFromList(acceptor)
 
             currentAlignment = QPalmaDP.Alignment()
-            qualityMat = QPalmaDP.createDoubleArrayFromList(qualityMatrix)
-            currentAlignment.setQualityMatrix(qualityMat,self.numQualSuppPoints)
+            #qualityMat = QPalmaDP.createDoubleArrayFromList(qualityMatrix)
+            #currentAlignment.setQualityMatrix(qualityMat,self.numQualSuppPoints)
 
-            qualityPlifs = initializeQualityScoringFunctions(numPlifs,numSuppPoints)
+            qualityPlifs = initializeQualityScoringFunctions(Configuration.numQualPlifs,Configuration.numQualSuppPoints)
 
-            # pdb.set_trace()
+            c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList(qualityPlifs)
 
             #print 'PYTHON: 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, qualityPlifs, remove_duplicate_scores, print_matrix)
+             acceptor, a_len, c_qualityPlifs, remove_duplicate_scores, print_matrix)
             #print 'PYTHON: After myalign call...'
 
             c_SpliceAlign       = QPalmaDP.createIntArrayFromList([0]*(dna_len*num_path[exampleIdx]))
@@ -285,29 +257,54 @@ class QPalma:
             c_WeightMatch       = QPalmaDP.createIntArrayFromList([0]*(mm_len*num_path[exampleIdx]))
             c_AlignmentScores   = QPalmaDP.createDoubleArrayFromList([.0]*num_path[exampleIdx])
 
-            currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign, c_WeightMatch, c_AlignmentScores)
-            del currentAlignment
+            emptyPlif = Plf(30)
+            emptyPlif = emptyPlif.convert2SWIG()
+            c_qualityPlifs = QPalmaDP.createPenaltyArrayFromList([emptyPlif]*(Configuration.numQualPlifs*num_path[exampleIdx]))
+
+            currentAlignment.getAlignmentResults(c_SpliceAlign, c_EstAlign,\
+            c_WeightMatch, c_AlignmentScores, c_qualityPlifs)
 
             newSpliceAlign = zeros((num_path[exampleIdx]*dna_len,1))
+            newEstAlign = zeros((est_len*num_path[exampleIdx],1))
             newWeightMatch = zeros((num_path[exampleIdx]*mm_len,1))
+            newQualityPlifs = [None]*num_path[exampleIdx]*Configuration.numQualPlifs
 
-            print 'spliceAlign'
+            #print 'newSpliceAlign'
             for i in range(dna_len*num_path[exampleIdx]):
                newSpliceAlign[i] = c_SpliceAlign[i]
             #   print '%f' % (spliceAlign[i])
 
-            print 'weightMatch'
+            #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 'AlignmentScores'
             for i in range(num_path[exampleIdx]):
                AlignmentScores[i+1] = c_AlignmentScores[i]
 
+            #print 'newQualityPlifs'
+            for i in range(num_path[exampleIdx]*Configuration.numQualPlifs):
+               newQualityPlifs[i] = QPalmaDP.penaltyArray_getitem(c_qualityPlifs, i)
+
+            #print "Calling destructors"
+
+            del c_SpliceAlign
+            del c_EstAlign
+            del c_WeightMatch
+            del c_AlignmentScores
+            del c_qualityPlifs
+            del currentAlignment
+
             newSpliceAlign = newSpliceAlign.reshape(num_path[exampleIdx],dna_len)
             newWeightMatch = newWeightMatch.reshape(num_path[exampleIdx],mm_len)
             # Calculate weights of the respective alignments Note that we are
-            # calculating n-best alignments without any hamming loss, so we
+            # 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
@@ -318,25 +315,36 @@ class QPalma:
             path_loss = [0]*(num_path[exampleIdx]+1)
 
             for pathNr in range(num_path[exampleIdx]):
-               #dna_numbers = dnaest{1,pathNr}
-               #est_numbers = dnaest{2,pathNr}
 
                weightDon, weightAcc, weightIntron = computeSpliceWeights(d, a, h, newSpliceAlign[pathNr,:].flatten().tolist()[0], don_supp, acc_supp)
 
+               decodedQualityFeatures = zeros((Configuration.totalQualSuppPoints,1))
+               qidx = 0
+
+               for currentPlif in newQualityPlifs[Configuration.numQualPlifs*pathNr:Configuration.numQualPlifs*(pathNr+1)]:
+                  for tidx in range(currentPlif.len):
+                     #elem = currentPlif.penalties[tidx]
+                     elem = QPalmaDP.doubleFArray_getitem(currentPlif.penalties, tidx)
+                     #print '%f ' % elem, 
+                     print qidx
+                     decodedQualityFeatures[qidx] = elem
+                     qidx += 1
+                  #print
+
                # sum up positionwise loss between alignments
                for alignPosIdx in range(len(newSpliceAlign[pathNr,:])):
                   if newSpliceAlign[pathNr,alignPosIdx] != trueSpliceAlign[alignPosIdx]:
                      path_loss[pathNr+1] += 1
 
                # Gewichte in restliche Zeilen der Matrix speichern
-               wp = numpy.vstack([weightIntron, weightDon, weightAcc, newWeightMatch[pathNr,:].T, qualityMatrix ])
+               wp = numpy.vstack([weightIntron, weightDon, weightAcc, newWeightMatch[pathNr,:].T, decodedQualityFeatures])
                allWeights[:,pathNr+1] = wp
 
                hpen = mat(h.penalties).reshape(len(h.penalties),1)
                dpen = mat(d.penalties).reshape(len(d.penalties),1)
                apen = mat(a.penalties).reshape(len(a.penalties),1)
 
-               features = numpy.vstack([hpen , dpen , apen , mmatrix[:]])
+               features = numpy.vstack([hpen , dpen , apen , mmatrix[:], zeros((Configuration.totalQualSuppPoints,1))])
                AlignmentScores[pathNr+1] = (allWeights[:,pathNr+1].T * features)[0,0]
 
                # Check wether scalar product + loss equals viterbi score
@@ -403,6 +411,26 @@ class QPalma:
       self.logfh.close()
       print 'Training completed'
 
+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))
+
 if __name__ == '__main__':
    qpalma = QPalma()
    qpalma.run()