# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
#     """ returns a filename with the suffix replaced
#     with a new suffix
#     exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
#     dirname = os.path.dirname(filename)
#     filename = os.path.basename(filename)
#     fsplit = filename.split(delim)[:-1]
#     fsplit.append(suffix)
#     return os.path.join(dirname, delim.join(fsplit))
# 
# def which(program):
#     """ returns the path to an executable"""
# 
#     def is_exe(fpath):
#         return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# 
#     fpath, fname = os.path.split(program)
#     if fpath:
#         if is_exe(program):
#             return program
#     else:
#         for path in os.environ["PATH"].split(os.pathsep):
#             exe_file = os.path.join(path, program)
#             if is_exe(exe_file):
#                 return exe_file
# 
#     return None
# 
# def remove_suffix(filename):
#     filename, extension = os.path.splitext(filename)
#     return filename
# 
# def append_stem(filename, word, delim="."):
#     """ returns a filename with word appended to the stem
#     example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
#     dirname = os.path.dirname(filename)
#     filename = os.path.basename(filename)
#     fsplit = filename.split(delim)
#     fsplit.insert(len(fsplit) - 1, word)
#     return os.path.join(dirname, delim.join(fsplit))
# 
# def prepare_ref_file(ref, config):
#     """Get a reference file, either by URL or locally.
#     Lifted from Brad Chapman
#     """
#     url = ref.get("url", None)
#     if url:
#         ref_file = _download_ref(url, config["dir"]["ref"])
#     else:
#         ref_file = ref.get("file", None)
#     assert ref_file is not None and os.path.exists(ref_file), ref_file
#     return ref_file
# 
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
#     """Abstract class for generating Latex reports. Inherit from this
#     and implement template and generate_report"""
#     __metaclass__ = abc.ABCMeta
# 
#     @abc.abstractproperty
#     def template(self):
#         return
# 
#     @abc.abstractmethod
#     def generate_report(self, *args, **kwargs):
#         """Generate the Latex output using the template"""
#         return
# 
# def safe_latex(to_fix):
#     """Escape characters that make LaTeX unhappy.
#     Lifted from Brad Chapman (bcbio)
#     """
#     chars = ["%", "_", "&", "#"]
#     for char in chars:
#         to_fix = to_fix.replace(char, "\\%s" % char)
#     return to_fix
# 
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
#     """
#     Wrapper around a stage for use with the pipeline manager. Subclasses should
#     implement their own __init__ in addition to calling the super
#     __init__. __init__ should parse the appropriate information from the config
#     dict and save it in the objects state. __call__ should be implemented as a
#     pure function with no closures.
# 
#     """
# 
#     stage = "abstract"
# 
#     def __init__(self, config):
#         self.config = config
#         self._validate_config()
# 
#     def _start_message(self, in_file, **kwargs):
#         if kwargs:
#             logger.info("Starting %s on %s with arguments %s." % (self.stage,
#                                                                   in_file,
#                                                                   kwargs))
#         else:
#             logger.info("Starting %s on %s." % (self.stage, in_file))
# 
#     def _end_message(self, in_file):
#         logger.info("%s complete on %s." % (self.stage, in_file))
# 
#     def _check_run(self, in_file):
#         if not file_exists(in_file):
#             raise IOError("%s not found." % (in_file))
# 
#     def __call__(self, in_file):
#         pass
# 
#     def _validate_config(self):
#         if "stage" not in self.config:
#             raise ValueError('Could not find "stage" in the config file.')


import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
                        prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do
                final_graphs.append((final_f, caption, size))
        return final_graphs


class RseqcReport(LatexReport):

    CAPTIONS = {"RPKM_saturation.pdf": "",
                "coverage.geneBodyCoverage.pdf": "",
                "clipping.pdf": "",
                "coverage.pdf": "",
                "junction_saturation.pdf": "",
                "splice_events.pdf": ""}

    def __init__(self):
        pass

    def template(self):
        return self._template

    def _add_captions(self, figures):
        new_figures = []
        for figure in figures:
            filename = os.path.basename(figure[0])
            caption = self.CAPTIONS.get(filename, "")
            new_figures.append((figure[0], caption, figure[2]))
        return new_figures

    def clean_figures(self, figures):
        new_figures = []
        for figure in figures:

# Path: bipy/utils.py
# def replace_suffix(filename, suffix, delim="."):
#     """ returns a filename with the suffix replaced
#     with a new suffix
#     exampoe: /path/to/test.run.sam -> /path/to/test.run.fa"""
#     dirname = os.path.dirname(filename)
#     filename = os.path.basename(filename)
#     fsplit = filename.split(delim)[:-1]
#     fsplit.append(suffix)
#     return os.path.join(dirname, delim.join(fsplit))
# 
# def which(program):
#     """ returns the path to an executable"""
# 
#     def is_exe(fpath):
#         return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# 
#     fpath, fname = os.path.split(program)
#     if fpath:
#         if is_exe(program):
#             return program
#     else:
#         for path in os.environ["PATH"].split(os.pathsep):
#             exe_file = os.path.join(path, program)
#             if is_exe(exe_file):
#                 return exe_file
# 
#     return None
# 
# def remove_suffix(filename):
#     filename, extension = os.path.splitext(filename)
#     return filename
# 
# def append_stem(filename, word, delim="."):
#     """ returns a filename with word appended to the stem
#     example: /path/to/test.run.sam -> /path/to/test.run.sorted.sam """
#     dirname = os.path.dirname(filename)
#     filename = os.path.basename(filename)
#     fsplit = filename.split(delim)
#     fsplit.insert(len(fsplit) - 1, word)
#     return os.path.join(dirname, delim.join(fsplit))
# 
# def prepare_ref_file(ref, config):
#     """Get a reference file, either by URL or locally.
#     Lifted from Brad Chapman
#     """
#     url = ref.get("url", None)
#     if url:
#         ref_file = _download_ref(url, config["dir"]["ref"])
#     else:
#         ref_file = ref.get("file", None)
#     assert ref_file is not None and os.path.exists(ref_file), ref_file
#     return ref_file
# 
# Path: bipy/toolbox/reporting.py
# class LatexReport(object):
#     """Abstract class for generating Latex reports. Inherit from this
#     and implement template and generate_report"""
#     __metaclass__ = abc.ABCMeta
# 
#     @abc.abstractproperty
#     def template(self):
#         return
# 
#     @abc.abstractmethod
#     def generate_report(self, *args, **kwargs):
#         """Generate the Latex output using the template"""
#         return
# 
# def safe_latex(to_fix):
#     """Escape characters that make LaTeX unhappy.
#     Lifted from Brad Chapman (bcbio)
#     """
#     chars = ["%", "_", "&", "#"]
#     for char in chars:
#         to_fix = to_fix.replace(char, "\\%s" % char)
#     return to_fix
# 
# Path: bipy/pipeline/stages.py
# class AbstractStage(object):
#     """
#     Wrapper around a stage for use with the pipeline manager. Subclasses should
#     implement their own __init__ in addition to calling the super
#     __init__. __init__ should parse the appropriate information from the config
#     dict and save it in the objects state. __call__ should be implemented as a
#     pure function with no closures.
# 
#     """
# 
#     stage = "abstract"
# 
#     def __init__(self, config):
#         self.config = config
#         self._validate_config()
# 
#     def _start_message(self, in_file, **kwargs):
#         if kwargs:
#             logger.info("Starting %s on %s with arguments %s." % (self.stage,
#                                                                   in_file,
#                                                                   kwargs))
#         else:
#             logger.info("Starting %s on %s." % (self.stage, in_file))
# 
#     def _end_message(self, in_file):
#         logger.info("%s complete on %s." % (self.stage, in_file))
# 
#     def _check_run(self, in_file):
#         if not file_exists(in_file):
#             raise IOError("%s not found." % (in_file))
# 
#     def __call__(self, in_file):
#         pass
# 
#     def _validate_config(self):
#         if "stage" not in self.config:
#             raise ValueError('Could not find "stage" in the config file.')


# Path: bipy/toolbox/rseqc.py
import os
import sh
import glob
import pandas as pd
from bipy.utils import (replace_suffix, which, remove_suffix, append_stem,
                        prepare_ref_file)
from bcbio.utils import file_exists, safe_makedir, add_full_path
from math import sqrt
from mako.template import Template
from bipy.toolbox.reporting import LatexReport, safe_latex
from bcbio.distributed.transaction import file_transaction
from bipy.pipeline.stages import AbstractStage
from bcbio.broad import BroadRunner, picardrun
from bcbio.log import logger
from bcbio.provenance import do

                final_graphs.append((final_f, caption, size))
        return final_graphs


class RseqcReport(LatexReport):

    CAPTIONS = {"RPKM_saturation.pdf": "",
                "coverage.geneBodyCoverage.pdf": "",
                "clipping.pdf": "",
                "coverage.pdf": "",
                "junction_saturation.pdf": "",
                "splice_events.pdf": ""}

    def __init__(self):
        pass

    def template(self):
        return self._template

    def _add_captions(self, figures):
        new_figures = []
        for figure in figures:
            filename = os.path.basename(figure[0])
            caption = self.CAPTIONS.get(filename, "")
            new_figures.append((figure[0], caption, figure[2]))
        return new_figures

    def clean_figures(self, figures):
        new_figures = []
        for figure in figures:

            filename = safe_latex(figure[0])