
rule pacbio_quality:
    """Pacbio quality control

    Required input:
        - __pacbio_quality__input : the input BAM file 

    Required output:
        - __pacbio_quality__output_summary : summary_{sample}.json

    In addition to a summary file with basic statistics, this
    rules creates 5 images with basic histograms about the read
    lengths, the GC content, the ZMW information, the SNR of the
    A,C,G,T nucleotides, and a 2D histogram of GC versus read length

    References:
        `sequana.pacbio <http://sequana.readthedocs.io/en/master/references.html#sequana.pacbio.BAMPacbio>`_

    """
    input: __pacbio_quality__input
    output:
        read_len   = "hist_read_len_{sample}.png",
        GC_content = "GC_content_{sample}.png",
        ZMW        = "ZMW_passes_{sample}.png",
        SNR        = "SNR_{sample}.png",
        GC_vs_len  = "GC_vs_len_{sample}.png",
        summary    = __pacbio_quality__output_summary

    run:
        ########## labels for plots
        short_name = input[0].replace(".bam","").split("/")[-1]
        bam_pacbio = pacbio.BAMPacbio(input[0])

        ########## Read length
        # individual histograms
        bam_pacbio.hist_len(label=short_name)
        pylab.title("Read length")
        pylab.legend()
        pylab.savefig(output.read_len)

        ########## GC content
        # individual histograms
        bam_pacbio.hist_GC(label=short_name)
        pylab.title("GC content")
        pylab.legend()
        pylab.savefig(output.GC_content)

        ########## ZMW passes
        # individual histograms
        bam_pacbio.hist_ZMW_subreads(label=short_name)
        pylab.title("ZMW passes")
        pylab.legend()
        pylab.savefig(output.ZMW)

        ########## SNR
        # individual histograms
        bam_pacbio.hist_snr()
        pylab.title("SNR %s" %short_name)
        pylab.savefig(output.SNR)

        # plot GC versus read length
        bam_pacbio.plot_GC_read_len()
        pylab.savefig(output.GC_vs_len)

        summary = bam_pacbio.summary()
        with open(output.summary, "w") as fh:
            summary.update(
                {"images": 
                    {"hist_read_length": output.read_len,
                    "hist_gc_content": output.GC_content,
                    "hist_snr": output.SNR,
                    "gc_vs_length": output.GC_vs_len,
                    "hist_zmw": output.ZMW}
                })
            sample_name = output.summary[8:].rstrip(".json") 
            summary.update({'sample': sample_name})
            json.dump(summary, fh, indent=True, sort_keys=True)
        pylab.close()


