rule RNAseQC:
    """
    RNA-SeQC is a java program which computes a series of quality control metrics for RNA-seq data.
    The input can be one or more BAM files. The output consists of HTML reports and tab delimited files of metrics data.
    This program can be valuable for comparing sequencing quality across different samples or experiments to evaluate
    different experimental parameters. It can also be run on individual samples as a means of quality control before
    continuing with downstream analysis.

    RNA-SeQC is built on the GATK as well as the Picard API.

    Required input:
        - __RNAseQC__input_bam : a set of BAM files (sorted and indexed with reOrderSam)

    Required output:
        - __RNAseQC__output: directory where output files are written
        - __RNAseQC__conf: an automated configuration file build in this rule and give to RNA-seQC
        - __RNAseQC__figure: a house-made plot of transcrit-associated reads (also avalaible in multiQC)

    Other requirements:
        -  __RNAseQC__logs

    Required configuration:
        .. code-block:: yaml

            RNAseQC:
                 do: no
                 gtf_file: path to a GTF file
                 BWArRNA_file: path to the fasta file with ribosomale sequences
                 options: Any option recognized by RNAseQC tool


    References:
        http://archive.broadinstitute.org/cancer/cga/rnaseqc_run
    """



    input :
        __RNAseQC__input_bam
    log :
        __RNAseQC__logs
    output:
        dir = __RNAseQC__output,
        sample_index = __RNAseQC__conf,
        png = __RNAseQC__figure
    params:
        genome = config['genome']['fasta_file'],
        gtf = config['RNAseQC']['gtf_file'],
        rRNA = config['RNAseQC']['BWArRNA_file'],
        kwargs = config['RNAseQC']['options']

    run:
        import pandas as pd
        import matplotlib.pyplot as pl
        pl.style.use('ggplot')
        from re import split

        #create the sample index
        data = [(split(r'.[ATCG]{6,7,8}\_.*',file)[0], file, 'NA') for file in input]
        df = pd.DataFrame(data, columns=['Sample ID','Bam File','Notes'])
        df.to_csv(output.sample_index, sep="\t",index=False)

        #run RNAseQC
        shell("rna-seqc -o {output.dir}  -r {params.genome}  -s {output.sample_index} -t {params.gtf}  -BWArRNA {params.rRNA} {params.kwargs} 2> {log}")

        if os.path.isfile(os.path.join(output.dir,'metrics.tsv')):
            df = pd.DataFrame.from_csv(os.path.join(output.dir,'metrics.tsv'), header = 0, sep="\t")
            #plot results
            if sum(df['rRNA rate']) == 0 :
                frames = [df['rRNA rate'] ,df['Exonic Rate'], df['Intronic Rate'], df['Intergenic Rate']]
            else :
                frames = [df['rRNA rate'], df['Exonic Rate'] - df['rRNA rate'], df['Intronic Rate'],
                     df['Intergenic Rate']]
        res = pd.concat(frames, axis=1)
        ##légender correctement
        res.plot(kind='bar', stacked=True)
        pl.ylim([0,1])
        #pl.legend(('rRNA rate', 'Exonic Rate', 'Intronic Rate', 'Intergenic Rate'), loc='lower center',
        #           bbox_to_anchor=(0.5, +1.00), fancybox=True, shadow=True, ncol=4)
        pl.legend(('rRNA rate', 'Exonic Rate', 'Intronic Rate', 'Intergenic Rate'), loc='best')
        pl.tight_layout()
        pl.savefig(output.png)





