# 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/analyses/utils.py
# def normaliseQualValues(inputFastqFile, outputFastqFile):
#     """Makes a fastq with valid qual values
#     """
#     fileHandle = open(outputFastqFile, 'w')
#     for name, seq, quals in fastqRead(open(inputFastqFile, 'r')):
#         if quals == None:
#             quals = [33] * len(seq)
#         fastqWrite(fileHandle, name, seq, quals)
#     fileHandle.close()
#     return outputFastqFile


from nanopore.mappers.abstractMapper import AbstractMapper
from sonLib.bioio import system, fastaRead
from nanopore.analyses.utils import normaliseQualValues
import pysam
import os

class Lastz(AbstractMapper):
    def run(self, args=""):
        tempFastqFile = os.path.join(self.getLocalTempDir(), "temp.fastq")
        normaliseQualValues(self.readFastqFile, tempFastqFile)
        system("lastz %s[multiple] %s %s --format=sam > %s" % (self.referenceFastaFile, tempFastqFile, args, self.outputSamFile))
        try:
            pysam.Samfile(self.outputSamFile, "r" ).close()
        except ValueError:
            #Hack to make lastz work, creating SQ lines when no alignments are found
            fH = open(self.outputSamFile, 'a')
            for name, seq in fastaRead(open(self.referenceFastaFile, 'r')):
                fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq)))
            fH.close()
        
class LastzChain(Lastz):
    def run(self):
        Lastz.run(self)
        self.chainSamFile()
        
class LastzRealign(Lastz):
    def run(self):

# 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/analyses/utils.py
# def normaliseQualValues(inputFastqFile, outputFastqFile):
#     """Makes a fastq with valid qual values
#     """
#     fileHandle = open(outputFastqFile, 'w')
#     for name, seq, quals in fastqRead(open(inputFastqFile, 'r')):
#         if quals == None:
#             quals = [33] * len(seq)
#         fastqWrite(fileHandle, name, seq, quals)
#     fileHandle.close()
#     return outputFastqFile


# Path: nanopore/mappers/lastz.py
from nanopore.mappers.abstractMapper import AbstractMapper
from sonLib.bioio import system, fastaRead
from nanopore.analyses.utils import normaliseQualValues
import pysam
import os


class Lastz(AbstractMapper):
    def run(self, args=""):
        tempFastqFile = os.path.join(self.getLocalTempDir(), "temp.fastq")
        normaliseQualValues(self.readFastqFile, tempFastqFile)
        system("lastz %s[multiple] %s %s --format=sam > %s" % (self.referenceFastaFile, tempFastqFile, args, self.outputSamFile))
        try:
            pysam.Samfile(self.outputSamFile, "r" ).close()
        except ValueError:
            #Hack to make lastz work, creating SQ lines when no alignments are found
            fH = open(self.outputSamFile, 'a')
            for name, seq in fastaRead(open(self.referenceFastaFile, 'r')):
                fH.write("@SQ\tSN:%s\tLN:%s\n" % (name.split()[0], len(seq)))
            fH.close()
        
class LastzChain(Lastz):
    def run(self):
        Lastz.run(self)
        self.chainSamFile()
        
class LastzRealign(Lastz):
    def run(self):

        Lastz.run(self)