# Path: nanopore/mappers/abstractMapper.py
# class AbstractMapper(Target):
#     """Base class for mappers. Inherit this class to create a mapper
#     """
#     def __init__(self, readFastqFile, readType, referenceFastaFile, outputSamFile, emptyHmmFile=None):
#         Target.__init__(self)
#         self.readFastqFile = readFastqFile
#         self.referenceFastaFile = referenceFastaFile
#         self.outputSamFile = outputSamFile
#         self.readType = readType
#         self.emptyHmmFile=emptyHmmFile
#         
#     def chainSamFile(self):
#         """Converts the sam file so that there is at most one global alignment of each read
#         """ 
#         tempSamFile = os.path.join(self.getLocalTempDir(), "temp.sam")
#         system("cp %s %s" % (self.outputSamFile, tempSamFile))
#         chainSamFile(tempSamFile, self.outputSamFile, self.readFastqFile, self.referenceFastaFile)
#     
#     def realignSamFile(self, gapGamma=0.5, matchGamma=0.0, doEm=False,  useTrainedModel=False, trainedModelFile="blasr_hmm_0.txt"):
#         """Chains and then realigns the resulting global alignments.
#         """
#         tempSamFile = os.path.join(self.getGlobalTempDir(), "temp.sam")
#         if useTrainedModel and doEm:
#             raise RuntimeError("Attempting to train stock model")
#         system("cp %s %s" % (self.outputSamFile, tempSamFile))
#         if doEm:
#             hmmFile = self.emptyHmmFile
#         elif useTrainedModel:
#             hmmFile = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", trainedModelFile)
#         else:
#             hmmFile = None
#         self.addChildTargetFn(realignSamFileTargetFn, args=(tempSamFile, self.outputSamFile, 
#                                                             self.readFastqFile, self.referenceFastaFile, gapGamma, matchGamma, hmmFile, doEm))


from nanopore.mappers.abstractMapper import AbstractMapper
from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite
import os

class Last(AbstractMapper):
    def run(self, params=""):
        localReferenceFastaFile = os.path.join(self.getLocalTempDir(), "ref.fa") #Because we don't want to have any crufty files created in the local temp dir.
        indexFile = os.path.join(self.getLocalTempDir(), "my-index") #Index file
        mafFile = os.path.join(self.getLocalTempDir(), "out.maf") #MAF file
        #Hack to make last work, creating SQ line
        fH = open(self.outputSamFile, 'w')
        for name, seq in fastaRead(open(self.referenceFastaFile, 'r')):
            fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq)))
        fH.close()
        
        #Make fasta file, as last fastq seems broken
        localReadFile = os.path.join(self.getLocalTempDir(), "reads.fa") #Index file
        fH = open(localReadFile, 'w')
        for name, seq, quals in fastqRead(self.readFastqFile):
            fastaWrite(fH, name, seq)
        fH.close()
        
        system("cp %s %s" % (self.referenceFastaFile, localReferenceFastaFile)) #Copy across the ref file
        system("lastdb %s %s" % (indexFile, localReferenceFastaFile)) #Build the index
        system("lastal %s %s %s > %s" % (params, indexFile, localReadFile, mafFile)) #Build the alignment
        system("maf-convert.py sam %s >> %s" % (mafFile, self.outputSamFile)) #Now convert sam file

class LastChain(Last):

# Path: nanopore/mappers/abstractMapper.py
# class AbstractMapper(Target):
#     """Base class for mappers. Inherit this class to create a mapper
#     """
#     def __init__(self, readFastqFile, readType, referenceFastaFile, outputSamFile, emptyHmmFile=None):
#         Target.__init__(self)
#         self.readFastqFile = readFastqFile
#         self.referenceFastaFile = referenceFastaFile
#         self.outputSamFile = outputSamFile
#         self.readType = readType
#         self.emptyHmmFile=emptyHmmFile
#         
#     def chainSamFile(self):
#         """Converts the sam file so that there is at most one global alignment of each read
#         """ 
#         tempSamFile = os.path.join(self.getLocalTempDir(), "temp.sam")
#         system("cp %s %s" % (self.outputSamFile, tempSamFile))
#         chainSamFile(tempSamFile, self.outputSamFile, self.readFastqFile, self.referenceFastaFile)
#     
#     def realignSamFile(self, gapGamma=0.5, matchGamma=0.0, doEm=False,  useTrainedModel=False, trainedModelFile="blasr_hmm_0.txt"):
#         """Chains and then realigns the resulting global alignments.
#         """
#         tempSamFile = os.path.join(self.getGlobalTempDir(), "temp.sam")
#         if useTrainedModel and doEm:
#             raise RuntimeError("Attempting to train stock model")
#         system("cp %s %s" % (self.outputSamFile, tempSamFile))
#         if doEm:
#             hmmFile = self.emptyHmmFile
#         elif useTrainedModel:
#             hmmFile = os.path.join(pathToBaseNanoporeDir(), "nanopore", "mappers", trainedModelFile)
#         else:
#             hmmFile = None
#         self.addChildTargetFn(realignSamFileTargetFn, args=(tempSamFile, self.outputSamFile, 
#                                                             self.readFastqFile, self.referenceFastaFile, gapGamma, matchGamma, hmmFile, doEm))


# Path: nanopore/mappers/last.py
from nanopore.mappers.abstractMapper import AbstractMapper
from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite
import os


class Last(AbstractMapper):
    def run(self, params=""):
        localReferenceFastaFile = os.path.join(self.getLocalTempDir(), "ref.fa") #Because we don't want to have any crufty files created in the local temp dir.
        indexFile = os.path.join(self.getLocalTempDir(), "my-index") #Index file
        mafFile = os.path.join(self.getLocalTempDir(), "out.maf") #MAF file
        #Hack to make last work, creating SQ line
        fH = open(self.outputSamFile, 'w')
        for name, seq in fastaRead(open(self.referenceFastaFile, 'r')):
            fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq)))
        fH.close()
        
        #Make fasta file, as last fastq seems broken
        localReadFile = os.path.join(self.getLocalTempDir(), "reads.fa") #Index file
        fH = open(localReadFile, 'w')
        for name, seq, quals in fastqRead(self.readFastqFile):
            fastaWrite(fH, name, seq)
        fH.close()
        
        system("cp %s %s" % (self.referenceFastaFile, localReferenceFastaFile)) #Copy across the ref file
        system("lastdb %s %s" % (indexFile, localReferenceFastaFile)) #Build the index
        system("lastal %s %s %s > %s" % (params, indexFile, localReadFile, mafFile)) #Build the alignment
        system("maf-convert.py sam %s >> %s" % (mafFile, self.outputSamFile)) #Now convert sam file

class LastChain(Last):

    def run(self):