# Path: nanopore/analyses/abstractAnalysis.py
# class AbstractAnalysis(Target):
#     """Base class to for analysis targets. Inherit this class to create an analysis.
#     """
#     def __init__(self, readFastqFile, readType, referenceFastaFile, samFile, outputDir):
#         Target.__init__(self)
#         self.readFastqFile = readFastqFile
#         self.referenceFastaFile = referenceFastaFile
#         self.samFile = samFile
#         self.outputDir = outputDir
#         self.readType = readType
#         print(str(self.samFile))
#         
#     def run(self):
#         """Base method that does some logging
#         """
#         logger.info("This analysis target has read fastq file: %s, reference fasta file: %s, sam file: %s and will output to the directory: %s" % \
#                     (self.readFastqFile, self.referenceFastaFile, self.samFile, self.outputDir))
#         
#     def finish(self):
#         """Method called when a analysis has finished successfully to indicate that it should not be repeated.
#         """
#         open(os.path.join(self.outputDir, "DONE"), 'w').close()
# 
#     @staticmethod
#     def reset(outputDir):
#         if AbstractAnalysis.isFinished(outputDir):
#             os.remove(os.path.join(outputDir, "DONE"))
#     
#     @staticmethod
#     def isFinished(outputDir):
#         return os.path.exists(os.path.join(outputDir, "DONE"))
#     
#     @staticmethod
#     def formatRatio(numerator, denominator):
#         if denominator == 0:
#             return float("nan")
#         return float(numerator)/denominator
# 
# Path: nanopore/analyses/utils.py
# def samToBamFile(samInputFile, bamOutputFile):
#     """Converts a sam file to a bam file (sorted)
#     """
#     samfile = pysam.Samfile(samInputFile, "r" )
#     bamfile = pysam.Samfile(bamOutputFile, "wb", template=samfile)
#     for line in samfile:
#         bamfile.write(line)
# 
#     samfile.close()
#     bamfile.close()
# 
# def samIterator(sam):
#     """Creates an iterator over the aligned reads in a sam file, filtering out
#     any reads that have no reference alignment.
#     """
#     for aR in sam:
#         if aR.rname != -1:
#             yield aR


from nanopore.analyses.abstractAnalysis import AbstractAnalysis
from sonLib.bioio import system
from nanopore.analyses.utils import samToBamFile, samIterator
import os
import pysam

class QualiMap(AbstractAnalysis):
    def run(self):
        AbstractAnalysis.run(self) #Call base method to do some logging
        emptyQual = False
        for entry in samIterator(pysam.Samfile(self.samFile, "r")):
            if entry.qual is None:
                emptyQual = True
        if emptyQual is False:
            localBamFile = os.path.join(self.getLocalTempDir(), "mapping.bam")
            localSortedBamFile = os.path.join(self.getLocalTempDir(), "mapping.sorted")
            samToBamFile(self.samFile, localBamFile)
            pysam.sort(localBamFile, localSortedBamFile)

# Path: nanopore/analyses/abstractAnalysis.py
# class AbstractAnalysis(Target):
#     """Base class to for analysis targets. Inherit this class to create an analysis.
#     """
#     def __init__(self, readFastqFile, readType, referenceFastaFile, samFile, outputDir):
#         Target.__init__(self)
#         self.readFastqFile = readFastqFile
#         self.referenceFastaFile = referenceFastaFile
#         self.samFile = samFile
#         self.outputDir = outputDir
#         self.readType = readType
#         print(str(self.samFile))
#         
#     def run(self):
#         """Base method that does some logging
#         """
#         logger.info("This analysis target has read fastq file: %s, reference fasta file: %s, sam file: %s and will output to the directory: %s" % \
#                     (self.readFastqFile, self.referenceFastaFile, self.samFile, self.outputDir))
#         
#     def finish(self):
#         """Method called when a analysis has finished successfully to indicate that it should not be repeated.
#         """
#         open(os.path.join(self.outputDir, "DONE"), 'w').close()
# 
#     @staticmethod
#     def reset(outputDir):
#         if AbstractAnalysis.isFinished(outputDir):
#             os.remove(os.path.join(outputDir, "DONE"))
#     
#     @staticmethod
#     def isFinished(outputDir):
#         return os.path.exists(os.path.join(outputDir, "DONE"))
#     
#     @staticmethod
#     def formatRatio(numerator, denominator):
#         if denominator == 0:
#             return float("nan")
#         return float(numerator)/denominator
# 
# Path: nanopore/analyses/utils.py
# def samToBamFile(samInputFile, bamOutputFile):
#     """Converts a sam file to a bam file (sorted)
#     """
#     samfile = pysam.Samfile(samInputFile, "r" )
#     bamfile = pysam.Samfile(bamOutputFile, "wb", template=samfile)
#     for line in samfile:
#         bamfile.write(line)
# 
#     samfile.close()
#     bamfile.close()
# 
# def samIterator(sam):
#     """Creates an iterator over the aligned reads in a sam file, filtering out
#     any reads that have no reference alignment.
#     """
#     for aR in sam:
#         if aR.rname != -1:
#             yield aR


# Path: nanopore/analyses/qualimap.py
from nanopore.analyses.abstractAnalysis import AbstractAnalysis
from sonLib.bioio import system
from nanopore.analyses.utils import samToBamFile, samIterator
import os
import pysam


class QualiMap(AbstractAnalysis):
    def run(self):
        AbstractAnalysis.run(self) #Call base method to do some logging
        emptyQual = False
        for entry in samIterator(pysam.Samfile(self.samFile, "r")):
            if entry.qual is None:
                emptyQual = True
        if emptyQual is False:
            localBamFile = os.path.join(self.getLocalTempDir(), "mapping.bam")
            localSortedBamFile = os.path.join(self.getLocalTempDir(), "mapping.sorted")
            samToBamFile(self.samFile, localBamFile)
            pysam.sort(localBamFile, localSortedBamFile)

            system("qualimap bamqc -bam %s -outdir %s" % (localSortedBamFile + ".bam", self.outputDir))