예제 #1
0
def main(args=None):
    args = process_args(args)

    if not args.plotFile and not args.outRawCounts and not args.outQualityMetrics:
        sys.stderr.write("\nAt least one of --plotFile, --outRawCounts or --outQualityMetrics is required.\n")
        sys.exit(1)

    cr = sumR.SumCoveragePerBin(
        args.bamfiles,
        args.binSize,
        args.numberOfSamples,
        blackListFileName=args.blackListFileName,
        numberOfProcessors=args.numberOfProcessors,
        verbose=args.verbose,
        region=args.region,
        extendReads=args.extendReads,
        minMappingQuality=args.minMappingQuality,
        ignoreDuplicates=args.ignoreDuplicates,
        center_read=args.centerReads,
        samFlag_include=args.samFlagInclude,
        samFlag_exclude=args.samFlagExclude,
        minFragmentLength=args.minFragmentLength,
        maxFragmentLength=args.maxFragmentLength)

    num_reads_per_bin = cr.run()
    if num_reads_per_bin.sum() == 0:
        import sys
        sys.stderr.write(
            "\nNo reads were found in {} regions sampled. Check that the\n"
            "min mapping quality is not overly high and that the \n"
            "chromosome names between bam files are consistant.\n"
            "\n".format(num_reads_per_bin.shape[0]))
        exit(1)

    if args.skipZeros:
        num_reads_per_bin = countR.remove_row_of_zeros(num_reads_per_bin)

    total = len(num_reads_per_bin[:, 0])
    x = np.arange(total).astype('float') / total  # normalize from 0 to 1

    if args.plotFile is not None:
        i = 0
        # matplotlib won't iterate through line styles by itself
        pyplot_line_styles = sum([7 * ["-"], 7 * ["--"], 7 * ["-."], 7 * [":"]], [])
        plotly_colors = ["#d73027", "#fc8d59", "#f33090", "#e0f3f8", "#91bfdb", "#4575b4"]
        plotly_line_styles = sum([6 * ["solid"], 6 * ["dot"], 6 * ["dash"], 6 * ["longdash"], 6 * ["dashdot"], 6 * ["longdashdot"]], [])
        data = []
        for i, reads in enumerate(num_reads_per_bin.T):
            count = np.cumsum(np.sort(reads))
            count = count / count[-1]  # to normalize y from 0 to 1
            if args.plotFileFormat == 'plotly':
                trace = go.Scatter(x=x, y=count, mode='lines', name=args.labels[i])
                trace['line'].update(dash=plotly_line_styles[i % 36], color=plotly_colors[i % 6])
                data.append(trace)
            else:
                j = i % 35
                plt.plot(x, count, label=args.labels[i], linestyle=pyplot_line_styles[j])
                plt.xlabel('rank')
                plt.ylabel('fraction w.r.t. bin with highest coverage')
        # set the plotFileFormat explicitly to None to trigger the
        # format from the file-extension
        if not args.plotFileFormat:
            args.plotFileFormat = None

        if args.plotFileFormat == 'plotly':
            fig = go.Figure()
            fig['data'] = data
            fig['layout'].update(title=args.plotTitle)
            fig['layout']['xaxis1'].update(title="rank")
            fig['layout']['yaxis1'].update(title="fraction w.r.t bin with highest coverage")
            py.plot(fig, filename=args.plotFile, auto_open=False)
        else:
            plt.legend(loc='upper left')
            plt.suptitle(args.plotTitle)
            plt.savefig(args.plotFile, bbox_inches=0, format=args.plotFileFormat)
            plt.close()

    if args.outRawCounts is not None:
        of = open(args.outRawCounts, "w")
        of.write("#plotFingerprint --outRawCounts\n")
        of.write("'" + "'\t'".join(args.labels) + "'\n")
        fmt = "\t".join(np.repeat('%d', num_reads_per_bin.shape[1])) + "\n"
        for row in num_reads_per_bin:
            of.write(fmt % tuple(row))
        of.close()

    if args.outQualityMetrics is not None:
        of = open(args.outQualityMetrics, "w")
        of.write("Sample\tAUC\tSynthetic AUC\tX-intercept\tSynthetic X-intercept\tElbow Point\tSynthetic Elbow Point")
        if args.JSDsample:
            of.write("\tJS Distance\tSynthetic JS Distance\t% genome enriched\tdiff. enrichment\tCHANCE divergence")
        else:
            of.write("\tSynthetic JS Distance")
        of.write("\n")
        line = np.arange(num_reads_per_bin.shape[0]) / float(num_reads_per_bin.shape[0] - 1)
        for idx, reads in enumerate(num_reads_per_bin.T):
            counts = np.cumsum(np.sort(reads))
            counts = counts / float(counts[-1])
            AUC = np.sum(counts) / float(len(counts))
            XInt = (np.argmax(counts > 0) + 1) / float(counts.shape[0])
            elbow = (np.argmax(line - counts) + 1) / float(counts.shape[0])
            expected = getExpected(np.mean(reads))  # A tuple of expected (AUC, XInt, elbow)
            of.write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}".format(args.labels[idx], AUC, expected[0], XInt, expected[1], elbow, expected[2]))
            if args.JSDsample:
                JSD = getJSD(args, idx, num_reads_per_bin)
                syntheticJSD = getSyntheticJSD(num_reads_per_bin[:, idx])
                CHANCE = getCHANCE(args, idx, num_reads_per_bin)
                of.write("\t{0}\t{1}\t{2}\t{3}\t{4}".format(JSD, syntheticJSD, CHANCE[0], CHANCE[1], CHANCE[2]))
            else:
                syntheticJSD = getSyntheticJSD(num_reads_per_bin[:, idx])
                of.write("\t{0}".format(syntheticJSD))
            of.write("\n")
        of.close()
예제 #2
0
def main(args=None):
    args = process_args(args)

    if not args.plotFile and not args.outRawCounts and not args.outQualityMetrics:
        sys.stderr.write(
            "\nAt least one of --plotFile, --outRawCounts or --outQualityMetrics is required.\n"
        )
        sys.exit(1)

    cr = sumR.SumCoveragePerBin(args.bamfiles,
                                args.binSize,
                                args.numberOfSamples,
                                blackListFileName=args.blackListFileName,
                                numberOfProcessors=args.numberOfProcessors,
                                verbose=args.verbose,
                                region=args.region,
                                extendReads=args.extendReads,
                                minMappingQuality=args.minMappingQuality,
                                ignoreDuplicates=args.ignoreDuplicates,
                                center_read=args.centerReads,
                                samFlag_include=args.samFlagInclude,
                                samFlag_exclude=args.samFlagExclude,
                                minFragmentLength=args.minFragmentLength,
                                maxFragmentLength=args.maxFragmentLength)

    num_reads_per_bin = cr.run()
    if num_reads_per_bin.sum() == 0:
        import sys
        sys.stderr.write(
            "\nNo reads were found in {} regions sampled. Check that the\n"
            "min mapping quality is not overly high and that the \n"
            "chromosome names between bam files are consistant.\n"
            "\n".format(num_reads_per_bin.shape[0]))
        exit(1)

    if args.skipZeros:
        num_reads_per_bin = countR.remove_row_of_zeros(num_reads_per_bin)

    total = len(num_reads_per_bin[:, 0])
    x = np.arange(total).astype('float') / total  # normalize from 0 to 1

    if args.plotFile:
        i = 0
        # matplotlib won't iterate through line styles by itself
        pyplot_line_styles = sum(
            [7 * ["-"], 7 * ["--"], 7 * ["-."], 7 * [":"]], [])
        for i, reads in enumerate(num_reads_per_bin.T):
            count = np.cumsum(np.sort(reads))
            count = count / count[-1]  # to normalize y from 0 to 1
            j = i % 35
            plt.plot(x,
                     count,
                     label=args.labels[i],
                     linestyle=pyplot_line_styles[j])
            plt.xlabel('rank')
            plt.ylabel('fraction w.r.t. bin with highest coverage')
        plt.legend(loc='upper left')
        plt.suptitle(args.plotTitle)
        # set the plotFileFormat explicitly to None to trigger the
        # format from the file-extension
        if not args.plotFileFormat:
            args.plotFileFormat = None

        plt.savefig(args.plotFile.name,
                    bbox_inches=0,
                    format=args.plotFileFormat)
        plt.close()

    if args.outRawCounts:
        args.outRawCounts.write("'" + "'\t'".join(args.labels) + "'\n")
        fmt = "\t".join(np.repeat('%d', num_reads_per_bin.shape[1])) + "\n"
        for row in num_reads_per_bin:
            args.outRawCounts.write(fmt % tuple(row))
        args.outRawCounts.close()

    if args.outQualityMetrics:
        args.outQualityMetrics.write(
            "Sample\tAUC\tSynthetic AUC\tX-intercept\tSynthetic X-intercept\tElbow Point\tSynthetic Elbow Point"
        )
        if args.JSDsample:
            args.outQualityMetrics.write(
                "\tJS Distance\tSynthetic JS Distance\t% genome enriched\tdiff. enrichment\tCHANCE divergence"
            )
        args.outQualityMetrics.write("\n")
        line = np.arange(
            num_reads_per_bin.shape[0]) / float(num_reads_per_bin.shape[0] - 1)
        for idx, reads in enumerate(num_reads_per_bin.T):
            counts = np.cumsum(np.sort(reads))
            counts = counts / float(counts[-1])
            AUC = np.sum(counts) / float(len(counts))
            XInt = (np.argmax(counts > 0) + 1) / float(counts.shape[0])
            elbow = (np.argmax(line - counts) + 1) / float(counts.shape[0])
            expected = getExpected(
                np.mean(reads))  # A tuple of expected (AUC, XInt, elbow)
            args.outQualityMetrics.write(
                "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}".format(
                    args.labels[idx], AUC, expected[0], XInt, expected[1],
                    elbow, expected[2]))
            if args.JSDsample:
                JSD = getJSD(args, idx, num_reads_per_bin)
                syntheticJSD = getSyntheticJSD(num_reads_per_bin[:, idx])
                CHANCE = getCHANCE(args, idx, num_reads_per_bin)
                args.outQualityMetrics.write(
                    "\t{0}\t{1}\t{2}\t{3}\t{4}".format(JSD, syntheticJSD,
                                                       CHANCE[0], CHANCE[1],
                                                       CHANCE[2]))
            args.outQualityMetrics.write("\n")
        args.outQualityMetrics.close()