コード例 #1
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(
        os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'distance-corrected':
        '%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir,
        'raw': '%s/Analysis/hifive_mm9_ESC_expdist_correlations.txt' % basedir,
    }
    mm9_data = load_data(mm9_methods)
    width = 16.8
    spacer = 0.4
    plot_width = (width - spacer * 4) / 5
    c = canvas.canvas()
    mm9_ranges_img, mm9_ranges_height = plot_dataset_ranges(
        mm9_data, plot_width, spacer)
    mm9_ranges_img.text(0, mm9_ranges_height, 'b',
                        [text.halign.left, text.valign.top,
                         text.size(-1)])
    c.insert(mm9_ranges_img, [trafo.translate(plot_width + spacer, 0)])
    mm9_overall_img = plot_overall(mm9_data, plot_width - spacer,
                                   (mm9_ranges_height - spacer) - 0.3)
    c.text(0, mm9_ranges_height, 'a',
           [text.halign.left, text.valign.top,
            text.size(-1)])
    c.insert(mm9_overall_img, [trafo.translate(0, 0.4)])
    c.writePDFfile(out_fname)
コード例 #2
0
def plot_dataset_ranges(data, width, label):
    methods = data.keys()
    binsizes = numpy.unique(data[methods[0]]['binsize'])
    ho = 0.4
    ho2 = 0.4
    vo = 0.6
    spacer = 0.25
    plot_width = (width - ho * 2 -
                  (binsizes.shape[0] - 1) * spacer) / binsizes.shape[0] - ho2
    plot_height = plot_width
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data, binsize, plot_width, plot_width)
        c.insert(img, [
            trafo.translate((plot_width + spacer) * i + ho2 * (i + 1) + ho, vo)
        ])
    c.text(
        0, plot_height * 0.5 + vo, "Correlation",
        [text.halign.center, text.valign.top,
         text.size(-3),
         trafo.rotate(90)])
    c.text(width, plot_height * 0.5 + vo, label, [
        text.halign.center, text.valign.top,
        text.size(-3),
        trafo.rotate(-90)
    ])
    c.text((plot_width + ho2) * 2 + spacer * 1.5 + ho, 0,
           "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    return c, plot_height + vo + 0.3
コード例 #3
0
def plot_dataset_ranges(data0, data1, width):
    methods = data0.keys()
    binsizes = numpy.unique(data0[methods[0]]['binsize'])
    ho = 0.8
    ho2 = 0.25
    vo = 0.7
    vo2 = 0.4
    spacer = 0.0
    plot_width = (2 * width - ho * 2 - ho2 - spacer) / 2
    plot_height = width - vo - vo2
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data0, data1, binsize, plot_width, plot_width,
                                vo, vo2)
        c.insert(img, [
            trafo.translate(
                (plot_width + spacer + ho) * (i % 2) + ho2 + ho,
                (1 - i / 2) * (plot_height + spacer + vo + vo2) + vo)
        ])
    c.text(
        0, plot_height + 0.5 * spacer + vo + vo2, r"$r_{0K} - r_{500K}$",
        [text.halign.center, text.valign.top,
         text.size(-2),
         trafo.rotate(90)])
    c.text(plot_width + ho2 + spacer * 0.5 + ho, 0, "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.text(0, width * 2 + spacer, 'a',
           [text.halign.left, text.valign.top,
            text.size(-1)])
    return c
コード例 #4
0
def plot_dataset_ranges(data0, data1, width, height):
    binsizes = numpy.unique(data0['binsize'])
    ho = 1.1
    ho2 = 0.2
    vo = 1.0
    plot_width = (width - ho - ho2 * 3) / 4.0
    plot_height = height - vo
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        if i == 0:
            ylabel = True
        else:
            ylabel = False
        img = plot_single_range(data0, data1, binsize, plot_width, plot_height,
                                ylabel)
        c.insert(img, [trafo.translate(ho + i * (plot_width + ho2), vo - 0.3)])
    c.text(
        0, plot_height * 0.5 + vo - 0.3, r"$r_{Poisson} - r_{binomial}$",
        [text.halign.center, text.valign.top,
         text.size(-2),
         trafo.rotate(90)])
    c.text(plot_width * 2 + ho + 1.5 * ho2, 0, "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.text(0, height, 'a', [text.halign.left, text.valign.top, text.size(-1)])
    return c
コード例 #5
0
def plot_dataset_ranges(data, width, spacer):
    methods = data.keys()
    binsizes = numpy.unique(data[methods[0]]['binsize'])
    plot_width = width - 0.4
    plot_height = plot_width + 0.2
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data, binsize, plot_width, plot_height)
        c.insert(img, [
            trafo.translate(
                (plot_width + spacer) * i + 0.4, 0.4 + spacer * 0.5)
        ])
    c.text(
        0, plot_height * 0.5 + 0.2 + spacer * 0.75, "Dataset correlation",
        [text.halign.center, text.valign.top,
         text.size(-3),
         trafo.rotate(90)])
    c.text(plot_width * 2 + spacer * 1.5 + 0.4, 0.35, "Interaction range (bp)",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.fill(path.rect(0.4, 0.025, 0.2, 0.2), [color.rgb.black])
    c.text(0.7, 0.125, "HiFive-Express using raw reads",
           [text.halign.left, text.valign.middle,
            text.size(-2)])
    c.fill(path.rect(plot_width * 2 + spacer * 1.5, 0.025, 0.2, 0.2),
           [color.rgb.red])
    c.text(plot_width * 2 + spacer * 1.5 + 0.3, 0.125,
           "HiFive-Express using distance-corrected reads",
           [text.halign.left, text.valign.middle,
            text.size(-2)])
    return c, plot_height + 0.4 + spacer
コード例 #6
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        '0 pseudo-counts':'%s/Analysis/hifive_mm9_ESC_bin_correlations.txt' % basedir, 
        '1 pseudo-count':'%s/Analysis/hifive_mm9_ESC_binPC1_correlations.txt' % basedir, 
        '3 pseudo-counts':'%s/Analysis/hifive_mm9_ESC_binPC3_correlations.txt' % basedir, 
        '6 pseudo-counts':'%s/Analysis/hifive_mm9_ESC_binPC6_correlations.txt' % basedir, 
        'HiCPipe':'%s/Analysis/hicpipe_mm9_ESC_correlations.txt' % basedir, 
    }
    mm9_data = load_data(mm9_methods)
    width = 16.8
    spacer = 0.4
    overall_width = (width - spacer * 2) / 2.6
    c = canvas.canvas()
    prob_ranges_img, prob_ranges_height = plot_dataset_ranges(mm9_data, width)
    prob_ranges_img.text(0, prob_ranges_height, 'a',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(prob_ranges_img)
    overall_height = prob_ranges_height * 0.6
    hifive_overall_img = plot_overall(mm9_data, overall_width, overall_height, 'cis')
    hifive_overall_img.text(0, overall_height + 0.1, 'b',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(hifive_overall_img, [trafo.translate(0, -overall_height - spacer)])
    hifive_overall_img = plot_overall(mm9_data, overall_width, overall_height, 'trans')
    hifive_overall_img.text(0, overall_height + 0.1, 'c',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(hifive_overall_img,
             [trafo.translate(width - overall_width, -overall_height - spacer)])
    c.insert(plot_key(overall_width * 0.6 + 0.4, overall_height, mm9_data),
             [trafo.translate(overall_width + spacer + 0.6, -overall_height - spacer)])
    c.writePDFfile(out_fname)
コード例 #7
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    hic_fname1 = "%s/Data/HiC/HiFive/mm9_ESC_NcoI_prob.hcp" % basedir
    hic_fname2 = "%s/Data/HiC/HiFive/mm9_ESC_HindIII_prob.hcp" % basedir
    fivec_fnames = {
        "Prob_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_prob.fcp" % basedir,
        "Prob_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_prob.fcp" % basedir,
        "Bin_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_bin.fcp" % basedir,
        "Bin_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_bin.fcp" % basedir,
        "Exp_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_exp.fcp" % basedir,
        "Exp_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_exp.fcp" % basedir,
        "Exp-KR_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_expKR.fcp" % basedir,
        "Exp-KR_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expKR.fcp" % basedir,
    }
    hic1 = hifive.HiC(hic_fname1)
    hic2 = hifive.HiC(hic_fname2)
    hic_hm = { 'Phillips': {} }
    fc = hifive.FiveC(fivec_fnames["Prob_Phillips"])
    fragments = fc.frags['fragments'][...]
    regions = fc.frags['regions'][...]
    for i in range(fc.frags['regions'].shape[0]):
            binbounds = numpy.hstack((
                    fragments['start'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1),
                    fragments['stop'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1)))
            binbounds = binbounds[numpy.where(fc.filter[regions['start_frag'][i]:regions['stop_frag'][i]])[0], :]
            hic_hm['Phillips'][i] = dynamically_bin(hic1, hic2, regions['chromosome'][i], binbounds)
    fc = hifive.FiveC(fivec_fnames["Prob_Nora"])
    fragments = fc.frags['fragments'][...]
    regions = fc.frags['regions'][...]
    binbounds = numpy.hstack((
            fragments['start'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1),
            fragments['stop'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1)))
    binbounds = binbounds[numpy.where(fc.filter[regions['start_frag'][0]:regions['stop_frag'][0]])[0], :]
    hic_hm['Nora'] = dynamically_bin(hic1, hic2, regions['chromosome'][0], binbounds)
    dist_corr = find_correlations( hic_hm, fivec_fnames, out_fname, True )
    nodist_corr = find_correlations( hic_hm, fivec_fnames, out_fname, False )
    c = canvas.canvas()
    width = 16.8
    spacer = 0.4
    plot_width = (width - spacer * 2) / 2.5
    plot_height = plot_width
    key_width = width - (plot_width + spacer) * 2 
    phillips_img = plot_correlation_diffs(dist_corr, nodist_corr, 'Phillips', plot_width, plot_height)
    nora_img = plot_correlation_diffs(dist_corr, nodist_corr, 'Nora', plot_width, plot_height)
    key_img = plot_key(key_width, plot_height)
    c.insert(phillips_img)
    c.insert(nora_img, [trafo.translate(plot_width + spacer, 0)])
    c.insert(key_img, [trafo.translate((plot_width + spacer) * 2, 0)])
    c.text(0, plot_height, "a",
       [text.halign.left, text.valign.top, text.size(-1)])
    c.text(plot_width + spacer, plot_height, "b",
       [text.halign.left, text.valign.top, text.size(-1)])
    c.writePDFfile(out_fname)
コード例 #8
0
def plot_overall(data, width, height, name):
    vo = 0.55
    ho = 0.7
    plot_width = width - ho
    plot_height = height - vo - 0.3
    c = canvas.canvas()
    methods = data.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'trans')])
    Y = numpy.zeros((len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32)    
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'cis') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j] = data[method]['correlation'][where]
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'trans') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where]
        bar_colors.append(method_colors[method])
    Y = numpy.array(Y)
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for i in range(len(methods)):
        g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2),
               [graph.style.changebar([method_colors[methods[i]]])])
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label,
               [text.halign.center, text.valign.top, text.size(-3)])
    c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0, vo * 0.5), [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5, ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin])
    c.text(0, plot_height * 0.5 + vo, "Correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    c.text(plot_width * 0.5 + ho, height, name,
           [text.halign.center, text.valign.top, text.size(-3)])
    return c
コード例 #9
0
def plot_overall(data, width, height, int_type):
    methods = data.keys()
    methods.sort()
    vo = 0.3
    ho = 0.8
    plot_width = width - ho
    plot_height = height - vo - 0.3
    c = canvas.canvas()
    bar_colors = []
    binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == int_type)])
    Y = numpy.zeros((len(methods), binsizes.shape[0]), dtype=numpy.float32)    
    for i, method in enumerate(methods):
        for j, binsize in enumerate(binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == int_type) *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j] = data[method]['correlation'][where]
        bar_colors.append(method_colors[method])
    Y = numpy.array(Y)
    minY = numpy.amin(Y)
    maxY = numpy.amax(Y)
    spanY = maxY - minY
    minY -= spanY * 0.05
    maxY += spanY * 0.05
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter, min=minY, max=maxY),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for i in range(len(methods)):
        g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2),
               [graph.style.changebar([method_colors[methods[i]]])])
    c.insert(g, [trafo.translate(ho, vo)])
    if int_type == 'cis':
        for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb"]):
            c.text(ho + plot_width * (i + 0.5) / 4.0, vo - 0.05, "%s" % label,
                   [text.halign.center, text.valign.top, text.size(-3)])
        c.text(ho + plot_width * 0.5, height, "Cis",
               [text.halign.center, text.valign.top, text.size(-2)])
    else:
        for i, label in enumerate(["250Kb", "1Mb"]):
            c.text(ho + plot_width * (i + 0.5) / 2.0, vo - 0.05, "%s" % label,
                   [text.halign.center, text.valign.top, text.size(-3)])
        c.text(ho + plot_width * 0.5, height, "Trans",
               [text.halign.center, text.valign.top, text.size(-2)])
    c.text(0, plot_height * 0.5 + vo, "Correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    return c
コード例 #10
0
def plot_correlation_diffs(corr1, corr2, name, width, height):
    ho = 1.2
    vo = 0.4
    plot_width = width - ho
    plot_height = height - vo
    diffs = {}
    ymin = numpy.inf
    ymax = -numpy.inf
    for n in ['Phillips', 'Nora']:
        for meth in meth_names.keys():
            cname = "%s_%s" % (meth, n)
            diff = corr2[cname] - corr1[cname]
            ymin = min(ymin, diff)
            ymax = max(ymax, diff)
    for meth in meth_names.keys():
        cname = "%s_%s" % (meth, name)
        diffs[meth] = corr2[cname] - corr1[cname]
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    yspan = ymax - ymin
    c = canvas.canvas()
    g = graph.graphxy(
        width=plot_width,
        height=plot_height,
        x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)),
        y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
        x2=graph.axis.lin(parter=None, min=0, max=1),
        y2=graph.axis.lin(parter=None, min=0, max=1))
    w = plot_width / float(len(meth_names) + 1)
    y0 = -ymin / yspan * plot_height
    for i, meth in enumerate(methods):
        col = method_colors[meth]
        g.stroke(
            path.rect((i + 0.5) * w, y0, w, diffs[meth] / yspan * plot_height),
            [deco.filled([col])])
    g.stroke(path.line(0, y0, plot_width, y0),
             [style.linestyle.dotted, style.linewidth.THin])
    c.insert(g, [trafo.translate(ho, vo)])
    c.text(
        0, plot_height * 0.5 + vo, r"$r_{0K} - r_{50K}$",
        [text.halign.center, text.valign.top,
         text.size(-3),
         trafo.rotate(90)])
    c.text(plot_width * 0.5 + ho, vo * 0.5, name,
           [text.halign.center, text.valign.middle,
            text.size(-3)])
    return c
コード例 #11
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'HiFive-Probability':'%s/Analysis/hifive_mm9_ESC_prob_correlations.txt' % basedir, 
        'HiFive-Express':'%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir, 
        'HiFive-Binning':'%s/Analysis/hifive_mm9_ESC_bin_correlations.txt' % basedir, 
    }
    dist_methods = {
        'HiFive-Probability':'%s/Analysis/hifive_mm9_ESC_probnodist_correlations.txt' % basedir, 
        'HiFive-Express':'%s/Analysis/hifive_mm9_ESC_expnodist_correlations.txt' % basedir, 
        'HiFive-Binning':'%s/Analysis/hifive_mm9_ESC_binnodist_correlations.txt' % basedir, 
    }
    mm9_data = load_data(mm9_methods)
    dist_data = load_data(dist_methods)
    width = 16.8
    spacer = 0.4
    range_width = (width - spacer) / 3.0
    c = canvas.canvas()
    mm9_ranges_img = plot_dataset_ranges(mm9_data, dist_data, range_width)
    c.insert(mm9_ranges_img)
    mm9_overall_img = plot_overall(mm9_data, dist_data, range_width, range_width)
    mm9_overall_img.text(0, range_width, 'b',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(mm9_overall_img, [trafo.translate(range_width * 2 + spacer, range_width)])
    c.insert(plot_key(range_width / 2, range_width / 2),
             [trafo.translate(range_width * 2.25 + spacer, range_width * 0.25)])
    c.writePDFfile(out_fname)
コード例 #12
0
def text_pyx(g, x_coord, y_coord, text_input, text_size = -2, color = None, rotation = 0.):
    """
    Function that draws text in a given plot
    INPUTS:
        g       (Object) A graph-type object to which you want to add the text
        x_coord     (Double) x-coordinate (in plot units) at which you want to place
                the text
        y_coord     (Double) y-coordinate (in plot units) at which you want to place
                the text
        text_input  (String) Text that you want to add.
        text_size   (int, optional) Text size of the text added to the plot. Default is -2.
        color       (instance) Color instance that defines the color that you want the 
                text to have. Default is black.
    """

    # First define the text attributes:
    textattrs = [pyx_text.size(text_size),pyx_text.halign.center, pyx_text.vshift.middlezero, trafo.rotate(rotation)]

    # Now convert plot positions to pyx's:
    x0,y0 = g.pos(x_coord, y_coord)

    # If no color is given, draw black text. If color is given, draw text with the input color:
    if color is None:
        g.text(x0,y0,text_input,textattrs)
    else:
        # First, check which was the input color palette:
        color_dict = color.color
        if len(color_dict.keys()) == 4:
            color_string = str(color_dict['c'])+','+str(color_dict['m'])+','+str(color_dict['y'])+','+str(color_dict['k'])
            color_palette = 'cmyk'
        else:
                        color_string = str(color_dict['r'])+','+str(color_dict['g'])+','+str(color_dict['b'])
                        color_palette = 'rgb'
        # Now draw the text:
        g.text(x0, y0, r"\textcolor["+color_palette+"]{"+color_string+"}{"+text_input+"}",textattrs)
コード例 #13
0
def plot_key(width, height):
    c = canvas.canvas()
    w = height / 7.0
    for i, meth in enumerate(methods):
        c.fill(path.rect(1.0, (6 - i) * w - 0.1, 0.2, 0.2), [method_colors[meth]])
        c.text(1.3, (6 - i) * w, "%s" % meth_names[meth],
               [text.halign.left, text.valign.middle, text.size(-3)])
    return c
コード例 #14
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'HiFive-Probability':'%s/Analysis/hifive_mm9_ESC_prob_correlations.txt' % basedir, 
        'HiFive-Express':'%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir, 
        'HiFive-Binning':'%s/Analysis/hifive_mm9_ESC_bin_correlations.txt' % basedir, 
        'HiCNorm':'%s/Analysis/hicnorm_mm9_ESC_correlations.txt' % basedir, 
        'HiCPipe':'%s/Analysis/hicpipe_mm9_ESC_correlations.txt' % basedir, 
        'Matrix-Balancing':'%s/Analysis/mb_mm9_ESC_correlations.txt' % basedir,
    }
    hg19_methods = {
        'HiFive-Probability':'%s/Analysis/hifive_hg19_GM12878_prob_correlations.txt' % basedir, 
        'HiFive-Express':'%s/Analysis/hifive_hg19_GM12878_exp_correlations.txt' % basedir, 
        'HiFive-Binning':'%s/Analysis/hifive_hg19_GM12878_bin_correlations.txt' % basedir, 
        'HiCNorm':'%s/Analysis/hicnorm_hg19_GM12878_correlations.txt' % basedir, 
        'HiCPipe':'%s/Analysis/hicpipe_hg19_GM12878_correlations.txt' % basedir, 
        'Matrix-Balancing':'%s/Analysis/mb_hg19_GM12878_correlations.txt' % basedir,
    }
    mm9_data = load_data(mm9_methods)
    hg19_data = load_data(hg19_methods)
    width = 16.8
    spacer = 0.4
    overall_width = (width - spacer * 2) / 2.6
    c = canvas.canvas()
    mm9_ranges_img, mm9_ranges_height = plot_dataset_ranges(mm9_data, width, "MM9 ESC")
    mm9_ranges_img.text(0, mm9_ranges_height, 'a',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(mm9_ranges_img)
    hg19_ranges_img, hg19_ranges_height = plot_dataset_ranges(hg19_data, width, "HG19 GM12878")
    hg19_ranges_img.text(0, hg19_ranges_height, 'b',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(hg19_ranges_img, [trafo.translate(0, -hg19_ranges_height - spacer)])
    overall_height = mm9_ranges_height * 0.6
    mm9_overall_img = plot_overall(mm9_data, overall_width, overall_height, "MM9 ESC")
    mm9_overall_img.text(0, overall_height + 0.1, 'c',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(mm9_overall_img, [trafo.translate(0, -hg19_ranges_height - overall_height - spacer * 2)])
    hg19_overall_img = plot_overall(hg19_data, overall_width, overall_height, "HG19 GM12878")
    hg19_overall_img.text(0, overall_height + 0.1, 'd',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(hg19_overall_img, [trafo.translate(overall_width * 1.6 + spacer * 2,
                                -hg19_ranges_height - overall_height - spacer * 2)])
    c.insert(plot_key(overall_width * 0.6 + 0.4, overall_height),
             [trafo.translate(overall_width + spacer + 0.6, -hg19_ranges_height - overall_height - spacer * 2)])
    c.writePDFfile(out_fname)
コード例 #15
0
ファイル: time_comparison.py プロジェクト: bxlab/HiFive_Paper
def plot_key(width, height):
    c = canvas.canvas()
    wstep = width / 2.0
    hstep = height / 3
    for i in range(5):
        x = wstep * (i / 3)
        y = height - (i % 3 + 0.5) * hstep
        c.fill(path.rect(x + 0.1, y - 0.15, 0.3, 0.3), [step_colors[i]])
        temp = step_names[str(i)].split(' ')
        if len(temp) > 2:
            c.text(x + 0.5, y + 0.13, ' '.join(temp[:2]),
                   [text.halign.left, text.valign.middle, text.size(-2)])
            c.text(x + 0.5, y - 0.13, temp[-1],
                   [text.halign.left, text.valign.middle, text.size(-2)])
        else:
            c.text(x + 0.5, y, step_names[str(i)],
                   [text.halign.left, text.valign.middle, text.size(-2)])
    return c
コード例 #16
0
def plot_overall(data, width, height):
    plot_width = width - 0.4
    plot_height = height - 0.4
    c = canvas.canvas()
    methods = data.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(data[methods[0]]['interaction'] == 'trans')])
    Y = numpy.zeros((len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32)    
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'cis') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j] = data[method]['correlation'][where]
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'trans') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j + cis_binsizes.shape[0]] = data[method]['correlation'][where]
        bar_colors.append(method_colors[method])
    Y = numpy.array(Y)
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for i in range(len(methods)):
        g.plot(graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]), Y[i, :]), xname=1, y=2),
               [graph.style.changebar([method_colors[methods[i]]])])
    step = plot_width / (cis_binsizes.shape[0] + trans_binsizes.shape[0])
    for i, binsize in enumerate(cis_binsizes):
        g.text(step * (0.5 + i), -0.05, "%s cis" % (str(binsize/1000) + 'Kb').replace('000Kb', 'Mb'),
               [text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45)])
    for i, binsize in enumerate(trans_binsizes):
        g.text(step * (0.5 + i + cis_binsizes.shape[0]), -0.05, "%s trans" % (str(binsize/1000) + 'Kb').replace('000Kb', 'Mb'),
               [text.halign.right, text.valign.middle, text.size(-4), trafo.rotate(45)])
    c.insert(g, [trafo.translate(0.7, 0.4)])
    c.text(0, plot_height / 2.0 + 0.4, "Dataset Correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    return c
コード例 #17
0
def plot_key(width, height):
    c = canvas.canvas()
    w = height / 7.0
    for i, meth in enumerate(methods):
        c.fill(path.rect(1.0, (6 - i) * w - 0.1, 0.2, 0.2),
               [method_colors[meth]])
        c.text(1.3, (6 - i) * w, "%s" % meth_names[meth],
               [text.halign.left, text.valign.middle,
                text.size(-3)])
    return c
コード例 #18
0
def plot_dataset_ranges(data, width):
    methods = data.keys()
    methods.sort()
    binsizes = numpy.unique(data[methods[0]]['binsize'])
    ho = 0.4
    ho2 = 0.4
    vo = 0.6
    spacer = 0.25
    plot_width = (width - ho - (binsizes.shape[0] - 1) * spacer) / binsizes.shape[0] - ho2
    plot_height = plot_width
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data, binsize, plot_width, plot_width, methods)
        c.insert(img, [trafo.translate((plot_width + spacer) * i + ho2 * (i + 1) + ho, vo)])
    c.text(0, plot_height * 0.5 + vo, "Correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    c.text((plot_width + ho2) * 2 + spacer * 1.5 + ho, 0, "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    return c, plot_height + vo + 0.3
コード例 #19
0
def plot_dataset_ranges(data, width, spacer):
    methods = data.keys()
    binsizes = numpy.unique(data[methods[0]]['binsize'])
    plot_width = width - 0.4
    plot_height = plot_width + 0.2
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data, binsize, plot_width, plot_height)
        c.insert(img, [trafo.translate((plot_width + spacer) * i + 0.4, 0.4 + spacer * 0.5)])
    c.text(0, plot_height * 0.5 + 0.2 + spacer * 0.75, "Dataset correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    c.text(plot_width * 2 + spacer * 1.5 + 0.4, 0.35, "Interaction range (bp)",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.fill(path.rect(0.4, 0.025, 0.2, 0.2), [color.rgb.black])
    c.text(0.7, 0.125, "HiFive-Express using raw reads", [text.halign.left, text.valign.middle, text.size(-2)])
    c.fill(path.rect(plot_width * 2 + spacer * 1.5, 0.025, 0.2, 0.2), [color.rgb.red])
    c.text(plot_width * 2 + spacer * 1.5 + 0.3, 0.125, "HiFive-Express using distance-corrected reads",
           [text.halign.left, text.valign.middle, text.size(-2)])
    return c, plot_height + 0.4 + spacer
コード例 #20
0
def plot_key(width, height):
    c = canvas.canvas()
    step = height / float(len(method_colors))
    for i, meth in enumerate(
        ['HiFive-Probability', 'HiFive-Express', 'HiFive-Binning']):
        c.fill(path.rect(0.2, height - step * (i + 0.5) - 0.1, 0.2, 0.2),
               [method_colors[meth]])
        c.text(0.5, height - step * (i + 0.5), meth,
               [text.halign.left, text.valign.middle,
                text.size(-2)])
    return c
コード例 #21
0
def plot_dataset_ranges(data0, data1, width, height):
    binsizes = numpy.unique(data0['binsize'])
    ho = 1.1
    ho2 = 0.2
    vo = 1.0
    plot_width = (width - ho - ho2 * 3) / 4.0
    plot_height = height - vo
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        if i == 0:
            ylabel = True
        else:
            ylabel = False
        img = plot_single_range(data0, data1, binsize, plot_width, plot_height, ylabel)
        c.insert(img, [trafo.translate(ho + i * (plot_width + ho2), vo - 0.3)])
    c.text(0, plot_height * 0.5 + vo - 0.3, r"$r_{Poisson} - r_{binomial}$",
           [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)])
    c.text(plot_width * 2 + ho + 1.5 * ho2, 0, "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.text(0, height, 'a', [text.halign.left, text.valign.top, text.size(-1)])
    return c
コード例 #22
0
ファイル: time_comparison.py プロジェクト: bxlab/HiFive_Paper
def plot_key(width, height):
    c = canvas.canvas()
    wstep = width / 2.0
    hstep = height / 3
    for i in range(5):
        x = wstep * (i / 3)
        y = height - (i % 3 + 0.5) * hstep
        c.fill(path.rect(x + 0.1, y - 0.15, 0.3, 0.3), [step_colors[i]])
        temp = step_names[str(i)].split(' ')
        if len(temp) > 2:
            c.text(x + 0.5, y + 0.13, ' '.join(temp[:2]),
                   [text.halign.left, text.valign.middle,
                    text.size(-2)])
            c.text(x + 0.5, y - 0.13, temp[-1],
                   [text.halign.left, text.valign.middle,
                    text.size(-2)])
        else:
            c.text(x + 0.5, y, step_names[str(i)],
                   [text.halign.left, text.valign.middle,
                    text.size(-2)])
    return c
コード例 #23
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'distance-corrected':'%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir, 
        'raw':'%s/Analysis/hifive_mm9_ESC_expdist_correlations.txt' % basedir, 
    }
    mm9_data = load_data(mm9_methods)
    width = 16.8  
    spacer = 0.4
    plot_width = (width - spacer * 4) / 5
    c = canvas.canvas()
    mm9_ranges_img, mm9_ranges_height = plot_dataset_ranges(mm9_data, plot_width, spacer)
    mm9_ranges_img.text(0, mm9_ranges_height, 'b',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(mm9_ranges_img, [trafo.translate(plot_width + spacer, 0)])
    mm9_overall_img = plot_overall(mm9_data, plot_width - spacer, (mm9_ranges_height - spacer) - 0.3)
    c.text(0,  mm9_ranges_height, 'a',
                        [text.halign.left, text.valign.top, text.size(-1)])
    c.insert(mm9_overall_img, [trafo.translate(0, 0.4)])
    c.writePDFfile(out_fname)
コード例 #24
0
def plot_correlation_diffs(corr1, corr2, name, width, height):
    ho = 1.2
    vo = 0.4
    plot_width = width - ho
    plot_height = height - vo
    diffs = {}
    ymin = numpy.inf
    ymax = -numpy.inf
    for n in ['Phillips', 'Nora']:
        for meth in meth_names.keys():
            cname = "%s_%s" % (meth, n)
            diff = corr2[cname] - corr1[cname]
            ymin = min(ymin, diff)
            ymax = max(ymax, diff)
    for meth in meth_names.keys():
        cname = "%s_%s" % (meth, name)
        diffs[meth] = corr2[cname] - corr1[cname]
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    yspan = ymax - ymin
    c = canvas.canvas()
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    w = plot_width / float(len(meth_names) + 1)
    y0 = -ymin / yspan * plot_height
    for i, meth in enumerate(methods):
        col = method_colors[meth]
        g.stroke( path.rect((i + 0.5) * w, y0, w, diffs[meth] / yspan * plot_height), [deco.filled([col])])
    g.stroke( path.line(0, y0, plot_width, y0), [style.linestyle.dotted, style.linewidth.THin])
    c.insert(g, [trafo.translate(ho, vo)])
    c.text(0, plot_height * 0.5 + vo, r"$r_{0K} - r_{50K}$",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    c.text(plot_width * 0.5 + ho, vo * 0.5, name,
           [text.halign.center, text.valign.middle, text.size(-3)])
    return c
コード例 #25
0
ファイル: draw.py プロジェクト: nespinoza/pyx-utils
def text(g, x_coord, y_coord, text_input, text_size=-2, color=None):
    """
 	Function that draws text in a given plot

	INPUTS:

		g		(Object) A graph-type object to which you want to add the text

		x_coord		(Double) x-coordinate (in plot units) at which you want to place
				the text

		y_coord		(Double) y-coordinate (in plot units) at which you want to place
				the text

		text_input	(String) Text that you want to add.

		text_size	(int, optional) Text size of the text added to the plot. Default is -2.

		color		(instance) Color instance that defines the color that you want the 
				text to have. Default is black.
	"""

    # First define the text attributes:
    textattrs = [
        pyx_text.size(text_size), pyx_text.halign.center,
        pyx_text.vshift.middlezero
    ]

    # Now convert plot positions to pyx's:
    x0, y0 = g.pos(x_coord, y_coord)

    # If no color is given, draw black text. If color is given, draw text with the input color:
    if color is None:
        g.text(x0, y0, text_input, textattrs)
    else:
        # First, check which was the input color palette:
        color_dict = color.color
        if len(color_dict.keys()) == 4:
            color_string = str(color_dict['c']) + ',' + str(
                color_dict['m']) + ',' + str(color_dict['y']) + ',' + str(
                    color_dict['k'])
            color_palette = 'cmyk'
        else:
            color_string = str(color_dict['r']) + ',' + str(
                color_dict['g']) + ',' + str(color_dict['b'])
            color_palette = 'rgb'
        # Now draw the text:
        g.text(
            x0, y0, r"\textcolor[" + color_palette + "]{" + color_string +
            "}{" + text_input + "}", textattrs)
コード例 #26
0
def plot_single_range(data, binsize, width, height):
    plot_width = width
    plot_height = height
    c = canvas.canvas()
    xmax = 0.0
    methods = data.keys()
    methods.sort()
    for method in methods:
        where = numpy.where((data[method]['binsize'] == binsize) *
                            (data[method]['interaction'] == 'cis') *
                            (data[method]['range'] > 0))
        if where[0].shape[0] > 0:
            xmax = max(xmax, numpy.amax(data[method]['range'][where]))
            X = data[method]['range'][where]
    X = numpy.r_[0, X]
    X[0] = X[1]**2.0 / X[2]
    xmin = X[0]
    g = graph.graphxy(width=plot_width,
                      height=plot_height,
                      x=graph.axis.log(painter=painter, min=X[0], max=xmax),
                      y=graph.axis.lin(painter=painter),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for x in X[1:-1]:
        pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width)
        g.stroke(path.line(pos, 0, pos, plot_height),
                 [style.linestyle.dotted, style.linewidth.THin])

    X = (X[1:]**0.5) * (X[:-1]**0.5)
    for method in methods:
        where = numpy.where((data[method]['binsize'] == binsize) *
                            (data[method]['interaction'] == 'cis') *
                            (data[method]['range'] > 0))
        if where[0].shape[0] > 0:
            Y = data[method]['correlation'][where]
            g.plot(graph.data.points(zip(X, Y), x=1, y=2), [
                graph.style.line(
                    lineattrs=[method_colors[method], style.linewidth.Thick])
            ])
    if binsize / 1000000 > 0:
        binstring = "%iMb" % (binsize / 1000000)
    elif binsize / 1000 > 0:
        binstring = "%iKb" % (binsize / 1000)
    else:
        binstring = str(binsize)
    g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring),
           [text.halign.center, text.valign.top,
            text.size(-2)])
    c.insert(g)
    return c
コード例 #27
0
def plot_dataset_ranges(data0, data1, width):
    methods = data0.keys()
    binsizes = numpy.unique(data0[methods[0]]['binsize'])
    ho = 0.8
    ho2 = 0.25
    vo = 0.7
    vo2 = 0.4
    spacer = 0.0
    plot_width = (2 * width - ho * 2 - ho2 - spacer) / 2
    plot_height = width - vo - vo2
    c = canvas.canvas()
    for i, binsize in enumerate(binsizes):
        img = plot_single_range(data0, data1, binsize, plot_width, plot_width, vo, vo2)
        c.insert(img, [trafo.translate((plot_width + spacer + ho) * (i % 2) + ho2 + ho,
                                        (1 - i /
                                         2) * (plot_height + spacer + vo + vo2) + vo)])
    c.text(0, plot_height + 0.5 * spacer + vo + vo2, r"$r_{0K} - r_{500K}$",
           [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)])
    c.text(plot_width + ho2 + spacer * 0.5 + ho, 0, "Interaction Range (bp)",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.text(0, width * 2 + spacer, 'a',
                        [text.halign.left, text.valign.top, text.size(-1)])
    return c
コード例 #28
0
 def draw(self):
     p = path.path(path.moveto(*self.corners[0]),
                   path.lineto(*self.corners[1]),
                   path.lineto(*self.corners[2]),
                   path.lineto(*self.corners[3]),
                   path.closepath())
     fillcolor = color.hsb(2/3*(1-(self.counter-1)/(self.nsquares-1)), 0.2, 1)
     self.c.stroke(p, [deco.filled([fillcolor])])
     x, y = 0.5*(self.corners[0]+self.corners[2])
     s = int(np.sum(np.abs(self.corners[1]-self.corners[0])))
     self.c.text(x, y, str(s),
                 [text.halign.center, text.valign.middle,
                  text.size(min(s, 5))])
     self.counter = self.counter+1
コード例 #29
0
 def draw(self):
     p = path.path(path.moveto(*self.corners[0]),
                   path.lineto(*self.corners[1]),
                   path.lineto(*self.corners[2]),
                   path.lineto(*self.corners[3]), path.closepath())
     fillcolor = color.hsb(
         2 / 3 * (1 - (self.counter - 1) / (self.nsquares - 1)), 0.2, 1)
     self.c.stroke(p, [deco.filled([fillcolor])])
     x, y = 0.5 * (self.corners[0] + self.corners[2])
     s = int(np.sum(np.abs(self.corners[1] - self.corners[0])))
     self.c.text(
         x, y, str(s),
         [text.halign.center, text.valign.middle,
          text.size(min(s, 5))])
     self.counter = self.counter + 1
コード例 #30
0
def plot_single_range(data, binsize, width, height):
    plot_width = width
    plot_height = height
    c = canvas.canvas()
    xmax = 0.0
    methods = data.keys()
    methods.sort()
    for method in methods:
        where = numpy.where((data[method]['binsize'] == binsize) *
                            (data[method]['interaction'] == 'cis') *
                            (data[method]['range'] > 0))
        if where[0].shape[0] > 0:
            xmax = max(xmax, numpy.amax(data[method]['range'][where]))
            X = data[method]['range'][where]
    X = numpy.r_[0, X]
    X[0] = X[1] ** 2.0 / X[2]
    xmin = X[0]
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.log(painter=painter, min=X[0], max=xmax),
                      y=graph.axis.lin(painter=painter),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for x in X[1:-1]:
        pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width)
        g.stroke(path.line(pos, 0, pos, plot_height), [style.linestyle.dotted, style.linewidth.THin])

    X = (X[1:] ** 0.5) * (X[:-1] ** 0.5)
    for method in methods:
        where = numpy.where((data[method]['binsize'] == binsize) *
                            (data[method]['interaction'] == 'cis') *
                            (data[method]['range'] > 0))
        if where[0].shape[0] > 0:
            Y = data[method]['correlation'][where]
            g.plot(graph.data.points(zip(X, Y), x=1, y=2),
                   [graph.style.line(lineattrs=[method_colors[method], style.linewidth.Thick])])
    if binsize / 1000000 > 0:
        binstring = "%iMb" % (binsize / 1000000)
    elif binsize / 1000 > 0:
        binstring = "%iKb" % (binsize / 1000)
    else:
        binstring = str(binsize)
    g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring),
           [text.halign.center, text.valign.top, text.size(-2)])
    c.insert(g)
    return c
コード例 #31
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(
        os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'HiFive-Probability':
        '%s/Analysis/hifive_mm9_ESC_prob_correlations.txt' % basedir,
        'HiFive-Express':
        '%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir,
        'HiFive-Binning':
        '%s/Analysis/hifive_mm9_ESC_bin_correlations.txt' % basedir,
    }
    dist_methods = {
        'HiFive-Probability':
        '%s/Analysis/hifive_mm9_ESC_probnodist_correlations.txt' % basedir,
        'HiFive-Express':
        '%s/Analysis/hifive_mm9_ESC_expnodist_correlations.txt' % basedir,
        'HiFive-Binning':
        '%s/Analysis/hifive_mm9_ESC_binnodist_correlations.txt' % basedir,
    }
    mm9_data = load_data(mm9_methods)
    dist_data = load_data(dist_methods)
    width = 16.8
    spacer = 0.4
    range_width = (width - spacer) / 3.0
    c = canvas.canvas()
    mm9_ranges_img = plot_dataset_ranges(mm9_data, dist_data, range_width)
    c.insert(mm9_ranges_img)
    mm9_overall_img = plot_overall(mm9_data, dist_data, range_width,
                                   range_width)
    mm9_overall_img.text(0, range_width, 'b',
                         [text.halign.left, text.valign.top,
                          text.size(-1)])
    c.insert(mm9_overall_img,
             [trafo.translate(range_width * 2 + spacer, range_width)])
    c.insert(
        plot_key(range_width / 2, range_width / 2),
        [trafo.translate(range_width * 2.25 + spacer, range_width * 0.25)])
    c.writePDFfile(out_fname)
コード例 #32
0
def plot_key(width, height, data):
    methods = data.keys()
    methods.sort()
    c = canvas.canvas()
    step = height / float(len(method_colors))
    for i, meth in enumerate(methods):
        c.fill(path.rect(0.2, height - step * (i + 0.5) - 0.1, 0.2, 0.2),
               [method_colors[meth]])
        c.text(0.5, height - step * (i + 0.5), meth, [text.halign.left, text.valign.middle, text.size(-2)])
    return c
コード例 #33
0
def plot_overall(data0, data1, width, height):
    vo = 0.55
    ho = 1.1
    plot_width = width - ho
    plot_height = height - vo
    c = canvas.canvas()
    methods = data0.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where(data0[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where(data0[methods[0]]['interaction'] == 'trans')])
    ymin = numpy.inf
    ymax = -numpy.inf
    Y = numpy.zeros((len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32)    
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data0[method]['binsize'] == binsize) *
                                (data0[method]['interaction'] == 'cis') *
                                (data0[method]['range'] < 0))
            where1 = numpy.where((data1[method]['binsize'] == binsize) *
                                 (data1[method]['interaction'] == 'cis') *
                                 (data1[method]['range'] < 0))
            if where[0].shape[0] > 0:
                Y[i, j] = (data1[method]['correlation'][where1] - data0[method]['correlation'][where])
                ymin = min(ymin, Y[i, j])
                ymax = max(ymax, Y[i, j])
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data0[method]['binsize'] == binsize) *
                                (data0[method]['interaction'] == 'trans') *
                                (data0[method]['range'] < 0))
            where1 = numpy.where((data1[method]['binsize'] == binsize) *
                                 (data1[method]['interaction'] == 'trans') *
                                 (data1[method]['range'] < 0))
            if where[0].shape[0] > 0:
                Y[i, j + cis_binsizes.shape[0]] = (data1[method]['correlation'][where1] -
                                                              data0[method]['correlation'][where])
                ymin = min(ymin, Y[i, j + cis_binsizes.shape[0]])
                ymax = max(ymax, Y[i, j + cis_binsizes.shape[0]])
        bar_colors.append(method_colors[method])
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    Y = numpy.array(Y)
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    y0 = plot_height * (-ymin) / (ymax - ymin)
    g.stroke(path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    w0 = plot_width / Y.shape[1]
    w1 = w0 / (len(methods) + 0.5)
    for i in range(len(methods)):
        for j in range(Y.shape[1]):
            x = j * w0 + (i + 0.25) * w1
            y = plot_height * (Y[i, j] - ymin) / (ymax - ymin)
            g.stroke( path.rect(x, y0, w1, y - y0), [deco.filled([method_colors[methods[i]]])])
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label,
               [text.halign.center, text.valign.top, text.size(-3)])
    c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0, vo * 0.5), [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5, ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin])
    c.text(0, plot_height * 0.5 + vo, r"$r_{0K} - r_{500K}$",
           [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)])
    return c
コード例 #34
0
def plot_single_range(data0, data1, binsize, width, height, ylabel):
    plot_width = width
    plot_height = height
    c = canvas.canvas()
    xmax = 0.0
    where = numpy.where((data0['binsize'] == binsize) *
                        (data0['interaction'] == 'cis') *
                        (data0['range'] >= 0))
    if where[0].shape[0] > 0:
        xmax = max(xmax, numpy.amax(data0['range'][where]))
        X = data0['range'][where]
    X = numpy.r_[0, X]
    X[0] = X[1] ** 2.0 / X[2]
    xmin = X[0]
    ymin = numpy.inf
    ymax = -numpy.inf
    binsizes = numpy.unique(data0['binsize'])
    for b in binsizes:
        where = numpy.where((data0['binsize'] == b) *
                            (data0['interaction'] == 'cis') *
                            (data0['range'] >= 0))
        where1 = numpy.where((data1['binsize'] == b) *
                             (data1['interaction'] == 'cis') *
                             (data1['range'] >= 0))
        if where[0].shape[0] > 0:
            Y = (data1['correlation'][where1] -
                             data0['correlation'][where] )
            ymin = min(ymin, numpy.amin(Y))
            ymax = max(ymax, numpy.amax(Y))
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    if ylabel:
        yaxis = graph.axis.lin(painter=painter, min=ymin, max=ymax)
    else:
        yaxis = graph.axis.lin(painter=None, min=ymin, max=ymax)
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.log(painter=painter, min=X[0], max=xmax),
                      y=yaxis,
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    g.stroke( path.line(0, 0, 0, plot_height) )
    for x in X[1:-1]:
        pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width)
        g.stroke(path.line(pos, 0, pos, plot_height), [style.linestyle.dotted, style.linewidth.THin])
    X = (X[1:] ** 0.5) * (X[:-1] ** 0.5)
    where = numpy.where((data0['binsize'] == binsize) *
                        (data0['interaction'] == 'cis') *
                        (data0['range'] > 0))
    where1 = numpy.where((data1['binsize'] == binsize) *
                         (data1['interaction'] == 'cis') *
                         (data1['range'] > 0))
    if where[0].shape[0] > 0:
        Y = ( data1['correlation'][where1] - data0['correlation'][where] )
        g.plot(graph.data.points(zip(X, Y), x=1, y=2),
               [graph.style.line(lineattrs=[style.linewidth.Thick])])
    g.stroke(path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    if binsize / 1000000 > 0:
        binstring = "%iMb" % (binsize / 1000000)
    elif binsize / 1000 > 0:
        binstring = "%iKb" % (binsize / 1000)
    else:
        binstring = str(binsize)
    g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring),
           [text.halign.center, text.valign.top, text.size(-2)])
    c.insert(g)
    return c
コード例 #35
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(
        os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    mm9_methods = {
        'HiFive-Probability':
        '%s/Analysis/hifive_mm9_ESC_prob_correlations.txt' % basedir,
        'HiFive-Express':
        '%s/Analysis/hifive_mm9_ESC_exp_correlations.txt' % basedir,
        'HiFive-Binning':
        '%s/Analysis/hifive_mm9_ESC_bin_correlations.txt' % basedir,
        'HiCNorm': '%s/Analysis/hicnorm_mm9_ESC_correlations.txt' % basedir,
        'HiCPipe': '%s/Analysis/hicpipe_mm9_ESC_correlations.txt' % basedir,
        'Matrix-Balancing':
        '%s/Analysis/mb_mm9_ESC_correlations.txt' % basedir,
    }
    hg19_methods = {
        'HiFive-Probability':
        '%s/Analysis/hifive_hg19_GM12878_prob_correlations.txt' % basedir,
        'HiFive-Express':
        '%s/Analysis/hifive_hg19_GM12878_exp_correlations.txt' % basedir,
        'HiFive-Binning':
        '%s/Analysis/hifive_hg19_GM12878_bin_correlations.txt' % basedir,
        'HiCNorm':
        '%s/Analysis/hicnorm_hg19_GM12878_correlations.txt' % basedir,
        'HiCPipe':
        '%s/Analysis/hicpipe_hg19_GM12878_correlations.txt' % basedir,
        'Matrix-Balancing':
        '%s/Analysis/mb_hg19_GM12878_correlations.txt' % basedir,
    }
    mm9_data = load_data(mm9_methods)
    hg19_data = load_data(hg19_methods)
    width = 16.8
    spacer = 0.4
    overall_width = (width - spacer * 2) / 2.6
    c = canvas.canvas()
    mm9_ranges_img, mm9_ranges_height = plot_dataset_ranges(
        mm9_data, width, "MM9 ESC")
    mm9_ranges_img.text(0, mm9_ranges_height, 'a',
                        [text.halign.left, text.valign.top,
                         text.size(-1)])
    c.insert(mm9_ranges_img)
    hg19_ranges_img, hg19_ranges_height = plot_dataset_ranges(
        hg19_data, width, "HG19 GM12878")
    hg19_ranges_img.text(0, hg19_ranges_height, 'b',
                         [text.halign.left, text.valign.top,
                          text.size(-1)])
    c.insert(hg19_ranges_img,
             [trafo.translate(0, -hg19_ranges_height - spacer)])
    overall_height = mm9_ranges_height * 0.6
    mm9_overall_img = plot_overall(mm9_data, overall_width, overall_height,
                                   "MM9 ESC")
    mm9_overall_img.text(0, overall_height + 0.1, 'c',
                         [text.halign.left, text.valign.top,
                          text.size(-1)])
    c.insert(mm9_overall_img, [
        trafo.translate(0, -hg19_ranges_height - overall_height - spacer * 2)
    ])
    hg19_overall_img = plot_overall(hg19_data, overall_width, overall_height,
                                    "HG19 GM12878")
    hg19_overall_img.text(0, overall_height + 0.1, 'd',
                          [text.halign.left, text.valign.top,
                           text.size(-1)])
    c.insert(hg19_overall_img, [
        trafo.translate(overall_width * 1.6 + spacer * 2,
                        -hg19_ranges_height - overall_height - spacer * 2)
    ])
    c.insert(plot_key(overall_width * 0.6 + 0.4, overall_height), [
        trafo.translate(overall_width + spacer + 0.6,
                        -hg19_ranges_height - overall_height - spacer * 2)
    ])
    c.writePDFfile(out_fname)
コード例 #36
0
def plot_key(width, height):
    c = canvas.canvas()
    step = height / float(len(method_colors))
    for i, meth in enumerate(['HiFive-Probability', 'HiFive-Express', 'HiFive-Binning',
                              'HiCNorm', 'HiCPipe', 'Matrix-Balancing']):
        c.fill(path.rect(0.2, height - step * (i + 0.5) - 0.1, 0.2, 0.2),
               [method_colors[meth]])
        c.text(0.5, height - step * (i + 0.5), meth, [text.halign.left, text.valign.middle, text.size(-2)])
    return c
コード例 #37
0
def plot_memory(data, width, height):
    plot_width = width - 4.0
    plot_height = height - 0.8
    left_width = plot_width * 0.6
    right_width = plot_width * 0.2
    prob = data['HiFive-Probability']['3']
    norm = data['HiCNorm']['3']
    prob_min = prob - right_width * 2.2e4 / left_width * 0.7
    prob_max = prob + right_width * 2.2e4 / left_width * 0.3
    norm_min = norm - right_width * 2.2e4 / left_width * 0.6
    norm_max = norm + right_width * 2.2e4 / left_width * 0.4
    c1 = canvas.canvas()
    g1 = graph.graphxy(width=left_width, height=plot_height,
                      y=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), min=0, max=2.2e4),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(painter=None, min=0, max=1))
    c1.insert(g1, [trafo.translate(0, 0)])
    g2 = graph.graphxy(width=right_width, height=plot_height,
                      y=graph.axis.lin(painter=None, min=0, max=1),
                      x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), min=prob_min, max=prob_max),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(painter=None, min=0, max=1))
    c1.insert(g2, [trafo.translate(left_width, 0)])
    g3 = graph.graphxy(width=right_width, height=plot_height,
                      y=graph.axis.lin(painter=None, min=0, max=1),
                      x=graph.axis.lin(painter=painter, texter=graph.axis.texter.exponential(mantissaexp=r"{{%s}e%s}", nomantissaexp=r"{e%s}"), parter=graph.axis.parter.linear(tickdists=[5000]), min=norm_min, max=norm_max),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    c1.insert(g3, [trafo.translate(left_width + right_width, 0)])
    split = canvas.canvas()
    split.fill(path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2), path.lineto(.15, 0.2),
               path.lineto(-0.05, -0.2), path.closepath()), [color.cmyk.White])
    split.stroke(path.line(-0.15, -0.2, 0.05, 0.2))
    split.stroke(path.line(-0.05, -0.2, 0.15, 0.2))
    c1.insert(split, [trafo.translate(left_width, 0)])
    c1.insert(split, [trafo.translate(left_width, plot_height)])
    c1.insert(split, [trafo.translate(left_width + right_width, 0)])
    c1.insert(split, [trafo.translate(left_width + right_width, plot_height)])
    methods = ['HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning', 'HiFive-Express',
               'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance']
    hstep = plot_height / len(methods)
    substep = hstep / 6.0
    scale = left_width / 2.2e4
    for i, meth in enumerate(methods[::-1]):
        for j in range(5):
            if str(j) not in data[meth]:
                continue
            if meth not in ['HiCNorm', 'HiFive-Probability'] or j != 3:
                c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, data[meth][str(j)] * scale, substep),
                       [step_colors[j]])
            elif meth == 'HiCNorm':
                c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, left_width + right_width * 1.7, substep),
                       [step_colors[j]])
                c1.insert(split, [trafo.translate(left_width, hstep * i + (5 - j) * substep)])
                c1.insert(split, [trafo.translate(left_width + right_width, hstep * i + (5 - j) * substep)])
            else:
                c1.fill(path.rect(0, hstep * i + (4.5 - j) * substep, left_width + right_width * 0.6, substep),
                       [step_colors[j]])
                c1.insert(split, [trafo.translate(left_width, hstep * i + (5 - j) * substep)])
    c = canvas.canvas()
    c.insert(c1, [trafo.translate(4.0, 0.8)])
    for i, meth in enumerate(methods):
        c.text(3.9, height - plot_height / len(methods) * (i + 0.5), meth,
               [text.halign.right, text.valign.middle, text.size(-2)])
    c.text(4.0 + plot_width / 2, 0, "Maximum RAM usage (resident set size, Mbytes)",
           [text.halign.center, text.valign.bottom, text.size(-2)])
    return c
コード例 #38
0
def plot_overall(data, width, height, name):
    vo = 0.55
    ho = 0.7
    plot_width = width - ho
    plot_height = height - vo - 0.3
    c = canvas.canvas()
    methods = data.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(
        data[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(
        data[methods[0]]['interaction'] == 'trans')])
    Y = numpy.zeros(
        (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]),
        dtype=numpy.float32)
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'cis') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j] = data[method]['correlation'][where]
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'trans') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j +
                  cis_binsizes.shape[0]] = data[method]['correlation'][where]
        bar_colors.append(method_colors[method])
    Y = numpy.array(Y)
    g = graph.graphxy(
        width=plot_width,
        height=plot_height,
        x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
        y=graph.axis.lin(painter=painter),
        x2=graph.axis.lin(parter=None, min=0, max=1),
        y2=graph.axis.lin(parter=None, min=0, max=1))
    for i in range(len(methods)):
        g.plot(
            graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]),
                                  Y[i, :]),
                              xname=1,
                              y=2),
            [graph.style.changebar([method_colors[methods[i]]])])
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb",
                               "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label,
               [text.halign.center, text.valign.top,
                text.size(-3)])
    c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(
        path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0,
                  vo * 0.5), [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(
        path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5,
                  ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin])
    c.text(
        0, plot_height * 0.5 + vo, "Correlation",
        [text.halign.center, text.valign.top,
         text.size(-3),
         trafo.rotate(90)])
    c.text(plot_width * 0.5 + ho, height, name,
           [text.halign.center, text.valign.top,
            text.size(-3)])
    return c
コード例 #39
0
circle = path.circle
line = path.line

# TODO: configs
BLACK = color.rgb.black
RED = color.rgb.red
GREEN = color.rgb.green

POINT_RADIUS = 4
POINT_STD_COLOR = BLACK
POINT_LABEL_DEFAULT_OFFSET = (10, 10)

LINE_DEF_COLOR = BLACK
LINE_DEF_WIDTH = 2

TEXT_DEFAULT_STYLE = [text.halign.center, text.size(5), BLACK]


class point:
    def __init__(self, x, y, name=None):
        self.x = x
        self.y = y

        self.name = name

    def get_xy(self):
        return (self.x, self.y)

    def mark(self, canv, r=POINT_RADIUS, color=POINT_STD_COLOR):
        circle = path.circle(self.x, self.y, r)
        style = [color]
コード例 #40
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    hic_phillips_fname1 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_NcoI_Phillips.hch" % basedir
    hic_phillips_fname2 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_HindIII_Phillips.hch" % basedir
    hic_nora_fname1 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_NcoI_Nora.hch" % basedir
    hic_nora_fname2 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_HindIII_Nora.hch" % basedir
    hic_phillips1 = h5py.File(hic_phillips_fname1, 'r')
    hic_phillips2 = h5py.File(hic_phillips_fname2, 'r')
    hic_nora1 = h5py.File(hic_nora_fname1, 'r')
    hic_nora2 = h5py.File(hic_nora_fname2, 'r')
    hm_phillips = {}
    hm_nora = {}
    for key in hic_phillips1.keys():
        if key.count('unbinned_counts') == 0:
            continue
        region = int(key.split('.')[0])
        hm_phillips[region] = dynamically_bin(hic_phillips1, hic_phillips2, region)
    for key in hic_nora1.keys():
        if key.count('unbinned_counts') == 0:
            continue
        region = int(key.split('.')[0])
        hm_nora[region] = dynamically_bin(hic_nora1, hic_nora2, region)

    fivec_fnames = {
        "Prob_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_probnodist.fcp" % basedir,
        "Prob_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_probnodist.fcp" % basedir,
        "Bin_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_binnodist.fcp" % basedir,
        "Bin_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_binnodist.fcp" % basedir,
        "Exp_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_expnodist.fcp" % basedir,
        "Exp_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expnodist.fcp" % basedir,
        "Exp-KR_Phillips":"%s/Data/FiveC/HiFive/Phillips_ESC_expKRnodist.fcp" % basedir,
        "Exp-KR_Nora":"%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expKRnodist.fcp" % basedir,
    }
    data = {}
    imgs = {}
    ratio1 = 0
    ratio2 = 0
    for meth in ['Prob', 'Bin', 'Exp', 'Exp-KR']:
        fc = hifive.FiveC(fivec_fnames["%s_Phillips" % meth])
        fragments = fc.frags['fragments'][...]
        regions = fc.frags['regions'][...]
        counts = numpy.zeros(0, dtype=numpy.float64)
        expected = numpy.zeros(0, dtype=numpy.float64)
        hic_counts = numpy.zeros(0, dtype=numpy.float64)
        hic_expected = numpy.zeros(0, dtype=numpy.float64)
        skipped = []
        for i in range(fc.frags['regions'].shape[0]):
            temp = fc.cis_heatmap(i, datatype='fragment', arraytype='compact', binsize=0, skipfiltered=True)
            if temp is None:
                skipped.append(i)
                continue
            counts = numpy.hstack((counts, temp[:, :, 0].ravel()))
            expected = numpy.hstack((expected, temp[:, :, 1].ravel()))
            if i == 6:
                ratio1 = temp.shape[1] / float(temp.shape[0])
                imgs["%s_Phillips" % meth] = hifive.plotting.plot_full_array(temp, symmetricscaling=False)
            if meth == 'Prob':
                temp1 = numpy.zeros((temp.shape[0], temp.shape[1]), dtype=numpy.float32)
                temp1[numpy.where(temp[:, :, 0] > 0.0)] = 1
                if i == 6:
                    imgs["Raw_Phillips"] = hifive.plotting.plot_full_array(
                            numpy.dstack((temp[:, :, 0], temp1)), symmetricscaling=False)
                binbounds = numpy.hstack((
                    fragments['start'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1),
                    fragments['stop'][regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1)))
                valid = numpy.where(fc.filter[regions['start_frag'][i]:regions['stop_frag'][i]])[0]
                binbounds = binbounds[valid, :]
                temp = hm_phillips[i]
                strands = fragments['strand'][regions['start_frag'][i]:regions['stop_frag'][i]][valid]
                temp = temp[numpy.where(strands == 0)[0], :, :][:, numpy.where(strands == 1)[0], :]
                hic_counts = numpy.hstack((hic_counts, temp[:, :, 0].ravel()))
                hic_expected = numpy.hstack((hic_expected, temp[:, :, 1].ravel()))
                if i == 6:
                    imgs["HiC_Phillips"] = hifive.plotting.plot_full_array(temp, symmetricscaling=False)
        if meth == 'Prob':
            data["Raw_Phillips"] = numpy.copy(counts)
            where = numpy.where(hic_expected > 0.0)[0]
            hic_counts[where] /= hic_expected[where]
            data["HiC_Phillips"] = numpy.copy(hic_counts)
        where = numpy.where(expected > 0.0)[0]
        counts[where] /= expected[where] 
        data["%s_Phillips" % meth] = numpy.copy(counts)
        fc = hifive.FiveC(fivec_fnames["%s_Nora" % meth])
        temp = fc.cis_heatmap(0, datatype='fragment', arraytype='compact', binsize=0, skipfiltered=True)
        ratio2 = temp.shape[1] / float(temp.shape[0])
        imgs["%s_Nora" % meth] = hifive.plotting.plot_full_array(temp, symmetricscaling=False)
        counts = temp[:, :, 0].ravel()
        expected = temp[:, :, 1].ravel()
        if meth == 'Prob':
            temp1 = numpy.zeros((temp.shape[0], temp.shape[1]), dtype=numpy.float32)
            temp1[numpy.where(temp[:, :, 0] > 0.0)] = 1
            imgs["Raw_Nora"] = hifive.plotting.plot_full_array(
                            numpy.dstack((temp[:, :, 0], temp1)), symmetricscaling=False)
            data["Raw_Nora"] = numpy.copy(counts)
            fragments = fc.frags['fragments'][...]
            regions = fc.frags['regions'][...]
            binbounds = numpy.hstack((
                    fragments['start'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1),
                    fragments['stop'][regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1)))
            binbounds = binbounds[numpy.where(fc.filter[regions['start_frag'][0]:regions['stop_frag'][0]])[0], :]
            temp = hm_nora[0]
            strands = fragments['strand'][regions['start_frag'][0]:regions['stop_frag'][0]]
            temp = temp[numpy.where(strands==0)[0], :, :][:, numpy.where(strands == 1)[0], :]
            imgs["HiC_Nora"] = hifive.plotting.plot_full_array(temp, symmetricscaling=False)
            hic_counts = temp[:, :, 0].ravel()
            hic_expected = temp[:, :, 1].ravel()
            where = numpy.where(hic_expected > 0.0)[0]
            hic_counts[where] /= hic_expected[where]
            data["HiC_Nora"] = numpy.copy(hic_counts)
        where = numpy.where(expected > 0.0)[0]
        counts[where] /= expected[where] 
        data["%s_Nora" % meth] = numpy.copy(counts)
    correlations = {}
    output = open(out_fname.replace('pdf', 'txt'), 'w')
    print >> output, "Method\tPhillips\tNora"
    for meth in methods:
        temp = [meth]
        for name in ["Phillips", "Nora"]:
            valid = numpy.where((data["%s_%s" % (meth, name)] > 0.0) * (data["HiC_%s" % name] > 0.0))
            correlations["%s_%s" % (meth, name)] = numpy.corrcoef(numpy.log(data["%s_%s" % (meth, name)][valid]),
                                                              numpy.log(data["HiC_%s" % name][valid]))[0, 1]
            temp.append(str(correlations["%s_%s" % (meth, name)]))
        print >> output, '\t'.join(temp)
    output.close()
    width = 16.8
    spacer = 0.3
    c = canvas.canvas()
    plot_width = (width - spacer * 3.0 - 0.4) / 4.0
    for i, meth in enumerate(["Raw", "Prob", "HiC"]):
        meth_names = {"Raw":"Raw", "Prob":"HiFive", "HiC":"HiC"}
        c.text(plot_width * (i + 1.5) + spacer * (i + 1), (ratio1 + ratio2) * plot_width + spacer + 0.1,
               "%s" % meth_names[meth], [text.halign.center, text.valign.bottom, text.size(-2)])
        c.insert(bitmap.bitmap(0, 0, imgs["%s_Phillips" % meth], width=plot_width),
                 [trafo.translate((i + 1) * (plot_width + spacer), plot_width * ratio2 + spacer)])
        c.insert(bitmap.bitmap(0, 0, imgs["%s_Nora" % meth], width=plot_width),
                 [trafo.translate((i + 1) * (plot_width + spacer), 0)])
    g = graph.graphxy(width=plot_width - 0.8, height=plot_width * ratio1,
                      x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    for i, meth in enumerate(methods):
        Y = numpy.zeros(2, dtype=numpy.float32)
        col = method_colors[meth]
        for j, name in enumerate(["Phillips", "Nora"]):
            Y[j] = correlations["%s_%s" % (meth, name)]
        g.plot(graph.data.points(zip(zip(range(Y.shape[0]), [i] * Y.shape[0]), Y), xname=1, y=2),
               [graph.style.changebar([col])])
    g.text(-0.8, plot_width * ratio1 * 0.5, "Correlation",
           [text.halign.center, text.valign.top, text.size(-3), trafo.rotate(90)])
    g.text((plot_width - 0.8) * 0.25, -0.1, "Phillips",
           [text.halign.center, text.valign.top, text.size(-3)])
    g.text((plot_width - 0.8) * 0.75, -0.1, "Nora",
           [text.halign.center, text.valign.top, text.size(-3)])
    c.insert(g, [trafo.translate(0.8, plot_width * ratio2 + spacer)])
    c.text(width, (ratio1 + ratio2 * 0.5) * plot_width + spacer, "Phillips",
           [text.halign.center, text.valign.top, trafo.rotate(-90), text.size(-2)])
    c.text(width, ratio1 * 0.5 * plot_width, "Nora",
           [text.halign.center, text.valign.top, trafo.rotate(-90), text.size(-2)])
    meth_names = {"Raw":"Raw", "Prob":"HiFive-Probability", "Exp":"HiFive-Express", "Bin":"HiFive-Binning",
                  "Exp-KR":"HiFive-ExpressKR", "Exp-KR-dist":"HiFive-ExpressKR-dist"}
    for i, meth in enumerate(methods):
        c.fill(path.rect(1.0, plot_width * ratio1 - 1.0 - i * 0.5, 0.2, 0.2), [method_colors[meth]])
        c.text(1.3, plot_width * ratio1 - 0.9 - i * 0.5, "%s" % meth_names[meth],
               [text.halign.left, text.valign.middle, text.size(-3)])
    c.writePDFfile(out_fname)
コード例 #41
0
def plot_overall(data, width, height):
    plot_width = width - 0.4
    plot_height = height - 0.4
    c = canvas.canvas()
    methods = data.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(
        data[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data[methods[0]]['binsize'][numpy.where(
        data[methods[0]]['interaction'] == 'trans')])
    Y = numpy.zeros(
        (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]),
        dtype=numpy.float32)
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'cis') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j] = data[method]['correlation'][where]
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data[method]['binsize'] == binsize) *
                                (data[method]['interaction'] == 'trans') *
                                (data[method]['range'] == 0))
            if where[0].shape[0] > 0:
                Y[i, j +
                  cis_binsizes.shape[0]] = data[method]['correlation'][where]
        bar_colors.append(method_colors[method])
    Y = numpy.array(Y)
    g = graph.graphxy(
        width=plot_width,
        height=plot_height,
        x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
        y=graph.axis.lin(painter=painter),
        x2=graph.axis.lin(parter=None, min=0, max=1),
        y2=graph.axis.lin(parter=None, min=0, max=1))
    for i in range(len(methods)):
        g.plot(
            graph.data.points(zip(zip(range(Y.shape[1]), [i] * Y.shape[1]),
                                  Y[i, :]),
                              xname=1,
                              y=2),
            [graph.style.changebar([method_colors[methods[i]]])])
    step = plot_width / (cis_binsizes.shape[0] + trans_binsizes.shape[0])
    for i, binsize in enumerate(cis_binsizes):
        g.text(step * (0.5 + i), -0.05,
               "%s cis" % (str(binsize / 1000) + 'Kb').replace('000Kb', 'Mb'),
               [
                   text.halign.right, text.valign.middle,
                   text.size(-4),
                   trafo.rotate(45)
               ])
    for i, binsize in enumerate(trans_binsizes):
        g.text(
            step * (0.5 + i + cis_binsizes.shape[0]), -0.05,
            "%s trans" % (str(binsize / 1000) + 'Kb').replace('000Kb', 'Mb'), [
                text.halign.right, text.valign.middle,
                text.size(-4),
                trafo.rotate(45)
            ])
    c.insert(g, [trafo.translate(0.7, 0.4)])
    c.text(
        0, plot_height / 2.0 + 0.4, "Dataset Correlation",
        [text.halign.center, text.valign.top,
         text.size(-3),
         trafo.rotate(90)])
    return c
コード例 #42
0
ファイル: time_comparison.py プロジェクト: bxlab/HiFive_Paper
def plot_bargraph(data, width, height):
    methods = ['HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning', 'HiFive-Express',
               'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance']
    ho = 4.0
    left_width = (width - ho) * 0.45
    mid_width1 = (width - ho) * 0.3
    mid_width2 = (width - ho) * 0.125
    right_width = (width - ho) * 0.125
    bar_height = height / len(methods) - 0.1
    data_totals = {}
    ranges = numpy.zeros((4, 2), dtype=numpy.float32)
    for meth in data:
        data_totals[meth] = find_total(data[meth])
        if meth == 'HiCPipe':
            ranges[1, 1] = data_totals[meth]
        elif meth == 'HiCNorm':
            ranges[2, 1] = data_totals[meth]
        elif meth == 'HiFive-Probability':
            ranges[3, 1] = data_totals[meth]
        else:
            ranges[0, 1] = max(ranges[0, 1], data_totals[meth])
    ranges /= 60.0
    ranges[0, 1] = 28.0
    ranges[1, 0] = ranges[1, 1] - ranges[0, 1] / 0.45 * 0.3 * 0.9
    ranges[1, 1] = ranges[1, 1] + ranges[0, 1] / 0.45 * 0.3 * 0.1
    ranges[2, 0] = ranges[2, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[2, 1] = ranges[2, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[3, 0] = ranges[3, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[3, 1] = ranges[3, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5
    c = canvas.canvas()
    g1 = graph.graphxy(width=left_width, height=height,
                       x=graph.axis.lin(painter=painter, min=0, max=ranges[0, 1]),
                       x2=graph.axis.lin(parter=None, min=0, max=ranges[0, 1]),
                       y=graph.axis.lin(parter=None, min=0, max=1),
                       y2=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g1)
    g2 = graph.graphxy(width=mid_width1, height=height,
                       x=graph.axis.lin(painter=painter, min=ranges[1, 0], max=ranges[1, 1]),
                       x2=graph.axis.lin(parter=None, min=ranges[1, 0], max=ranges[1, 1]),
                       y2=graph.axis.lin(painter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g2, [trafo.translate(left_width, 0)])
    g3 = graph.graphxy(width=mid_width2, height=height,
                       x=graph.axis.lin(painter=painter, min=ranges[2, 0], max=ranges[2, 1]),
                       x2=graph.axis.lin(parter=None, min=ranges[2, 0], max=ranges[2, 1]),
                       y2=graph.axis.lin(painter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g3, [trafo.translate(left_width + mid_width1, 0)])
    g4 = graph.graphxy(width=right_width, height=height,
                       x=graph.axis.lin(painter=painter, min=ranges[3, 0], max=ranges[3, 1]),
                       x2=graph.axis.lin(parter=None, min=ranges[3, 0], max=ranges[3, 1]),
                       y2=graph.axis.lin(parter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g4, [trafo.translate(left_width + mid_width1 + mid_width2, 0)])
    split = canvas.canvas()
    split.fill(path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2), path.lineto(.15, 0.2),
               path.lineto(-0.05, -0.2), path.closepath()), [color.cmyk.White])
    split.stroke(path.line(-0.15, -0.2, 0.05, 0.2))
    split.stroke(path.line(-0.05, -0.2, 0.15, 0.2))
    c.insert(split, [trafo.translate(left_width, 0)])
    c.insert(split, [trafo.translate(left_width, height)])
    c.insert(split, [trafo.translate(left_width + mid_width1, 0)])
    c.insert(split, [trafo.translate(left_width + mid_width1, height)])
    c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, 0)])
    c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, height)])
    for i, meth in enumerate(methods):
        c.insert(plot_bar(data[meth], ranges, bar_height, left_width / ranges[0, 1], split),
                 [trafo.translate(0, height - 0.05 - bar_height * (i + 1) - i * 0.1)])
        c.text(-0.1, height * (len(methods) - i - 0.5) / len(methods), meth,
               [text.halign.right, text.valign.middle, text.size(-2)])
    c.text((width - ho) / 2.0, -0.35, "Runtime (minutes)",
           [text.halign.center, text.valign.top, text.size(-2)])
    return c
コード例 #43
0
def plot_single_range(data0, data1, binsize, width, height, ylabel):
    plot_width = width
    plot_height = height
    c = canvas.canvas()
    xmax = 0.0
    where = numpy.where(
        (data0['binsize'] == binsize) * (data0['interaction'] == 'cis') *
        (data0['range'] >= 0))
    if where[0].shape[0] > 0:
        xmax = max(xmax, numpy.amax(data0['range'][where]))
        X = data0['range'][where]
    X = numpy.r_[0, X]
    X[0] = X[1]**2.0 / X[2]
    xmin = X[0]
    ymin = numpy.inf
    ymax = -numpy.inf
    binsizes = numpy.unique(data0['binsize'])
    for b in binsizes:
        where = numpy.where(
            (data0['binsize'] == b) * (data0['interaction'] == 'cis') *
            (data0['range'] >= 0))
        where1 = numpy.where(
            (data1['binsize'] == b) * (data1['interaction'] == 'cis') *
            (data1['range'] >= 0))
        if where[0].shape[0] > 0:
            Y = (data1['correlation'][where1] - data0['correlation'][where])
            ymin = min(ymin, numpy.amin(Y))
            ymax = max(ymax, numpy.amax(Y))
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    if ylabel:
        yaxis = graph.axis.lin(painter=painter, min=ymin, max=ymax)
    else:
        yaxis = graph.axis.lin(painter=None, min=ymin, max=ymax)
    g = graph.graphxy(width=plot_width,
                      height=plot_height,
                      x=graph.axis.log(painter=painter, min=X[0], max=xmax),
                      y=yaxis,
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    g.stroke(path.line(0, 0, 0, plot_height))
    for x in X[1:-1]:
        pos = ((log(x) - log(xmin)) / (log(xmax) - log(xmin)) * plot_width)
        g.stroke(path.line(pos, 0, pos, plot_height),
                 [style.linestyle.dotted, style.linewidth.THin])
    X = (X[1:]**0.5) * (X[:-1]**0.5)
    where = numpy.where((data0['binsize'] == binsize) *
                        (data0['interaction'] == 'cis') * (data0['range'] > 0))
    where1 = numpy.where(
        (data1['binsize'] == binsize) * (data1['interaction'] == 'cis') *
        (data1['range'] > 0))
    if where[0].shape[0] > 0:
        Y = (data1['correlation'][where1] - data0['correlation'][where])
        g.plot(graph.data.points(zip(X, Y), x=1, y=2),
               [graph.style.line(lineattrs=[style.linewidth.Thick])])
    g.stroke(
        path.line(0,
                  plot_height * (-ymin) / (ymax - ymin), plot_width,
                  plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    if binsize / 1000000 > 0:
        binstring = "%iMb" % (binsize / 1000000)
    elif binsize / 1000 > 0:
        binstring = "%iKb" % (binsize / 1000)
    else:
        binstring = str(binsize)
    g.text(plot_width / 2, plot_height + 0.3, "%s binning" % (binstring),
           [text.halign.center, text.valign.top,
            text.size(-2)])
    c.insert(g)
    return c
コード例 #44
0
def plot_overall(data0, data1, width, height):
    vo = 1.15
    ho = 1.15
    plot_width = width - ho
    plot_height = height - vo
    c = canvas.canvas()
    cis_binsizes = numpy.unique(
        data0['binsize'][numpy.where(data0['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(
        data0['binsize'][numpy.where(data0['interaction'] == 'trans')])
    ymin = numpy.inf
    ymax = -numpy.inf
    Y = numpy.zeros((cis_binsizes.shape[0] + trans_binsizes.shape[0]),
                    dtype=numpy.float32)
    for j, binsize in enumerate(cis_binsizes):
        where = numpy.where(
            (data0['binsize'] == binsize) * (data0['interaction'] == 'cis') *
            (data0['range'] < 0))
        where1 = numpy.where(
            (data1['binsize'] == binsize) * (data1['interaction'] == 'cis') *
            (data1['range'] < 0))
        if where[0].shape[0] > 0:
            Y[j] = (data1['correlation'][where1] - data0['correlation'][where])
            ymin = min(ymin, Y[j])
            ymax = max(ymax, Y[j])
    for j, binsize in enumerate(trans_binsizes):
        where = numpy.where(
            (data0['binsize'] == binsize) * (data0['interaction'] == 'trans') *
            (data0['range'] < 0))
        where1 = numpy.where(
            (data1['binsize'] == binsize) * (data1['interaction'] == 'trans') *
            (data1['range'] < 0))
        if where[0].shape[0] > 0:
            Y[j + cis_binsizes.shape[0]] = (data1['correlation'][where1] -
                                            data0['correlation'][where])
            ymin = min(ymin, Y[j + cis_binsizes.shape[0]])
            ymax = max(ymax, Y[j + cis_binsizes.shape[0]])
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    Y = numpy.array(Y)
    g = graph.graphxy(
        width=plot_width,
        height=plot_height,
        x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)),
        y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
        x2=graph.axis.lin(parter=None, min=0, max=1),
        y2=graph.axis.lin(parter=None, min=0, max=1))
    y0 = plot_height * (-ymin) / (ymax - ymin)
    g.stroke(
        path.line(0,
                  plot_height * (-ymin) / (ymax - ymin), plot_width,
                  plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    w0 = plot_width / Y.shape[0]
    w1 = w0 / 1.5
    for j in range(Y.shape[0]):
        x = j * w0 + 0.25 * w1
        y = plot_height * (Y[j] - ymin) / (ymax - ymin)
        g.fill(path.rect(x, y0, w1, y - y0))
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb",
                               "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label, [
            text.halign.right, text.valign.middle,
            text.size(-3),
            trafo.rotate(90)
        ])
    c.text(ho + plot_width * 2.0 / 6.0, 0, "cis",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(path.line(ho + 0.2, 0.3, ho - 0.2 + plot_width * 4.0 / 6.0, 0.3),
             [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0, "trans",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(
        path.line(ho + 0.2 + plot_width * 4.0 / 6.0, 0.3,
                  ho - 0.2 + plot_width, 0.3), [style.linewidth.THin])
    c.text(
        0, plot_height * 0.5 + vo, r"$r_{Poisson} - r_{binomial}$",
        [text.halign.center, text.valign.top,
         text.size(-2),
         trafo.rotate(90)])
    c.text(0, height, 'b', [text.halign.left, text.valign.top, text.size(-1)])
    return c
コード例 #45
0
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(
        os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    hic_fname1 = "%s/Data/HiC/HiFive/mm9_ESC_NcoI_prob.hcp" % basedir
    hic_fname2 = "%s/Data/HiC/HiFive/mm9_ESC_HindIII_prob.hcp" % basedir
    fivec_fnames = {
        "Prob_Phillips":
        "%s/Data/FiveC/HiFive/Phillips_ESC_prob.fcp" % basedir,
        "Prob_Nora":
        "%s/Data/FiveC/HiFive/Nora_ESC_male_E14_prob.fcp" % basedir,
        "Bin_Phillips":
        "%s/Data/FiveC/HiFive/Phillips_ESC_bin.fcp" % basedir,
        "Bin_Nora":
        "%s/Data/FiveC/HiFive/Nora_ESC_male_E14_bin.fcp" % basedir,
        "Exp_Phillips":
        "%s/Data/FiveC/HiFive/Phillips_ESC_exp.fcp" % basedir,
        "Exp_Nora":
        "%s/Data/FiveC/HiFive/Nora_ESC_male_E14_exp.fcp" % basedir,
        "Exp-KR_Phillips":
        "%s/Data/FiveC/HiFive/Phillips_ESC_expKR.fcp" % basedir,
        "Exp-KR_Nora":
        "%s/Data/FiveC/HiFive/Nora_ESC_male_E14_expKR.fcp" % basedir,
    }
    hic1 = hifive.HiC(hic_fname1)
    hic2 = hifive.HiC(hic_fname2)
    hic_hm = {'Phillips': {}}
    fc = hifive.FiveC(fivec_fnames["Prob_Phillips"])
    fragments = fc.frags['fragments'][...]
    regions = fc.frags['regions'][...]
    for i in range(fc.frags['regions'].shape[0]):
        binbounds = numpy.hstack(
            (fragments['start']
             [regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1, 1),
             fragments['stop']
             [regions['start_frag'][i]:regions['stop_frag'][i]].reshape(-1,
                                                                        1)))
        binbounds = binbounds[numpy.where(
            fc.filter[regions['start_frag'][i]:regions['stop_frag'][i]])[0], :]
        hic_hm['Phillips'][i] = dynamically_bin(hic1, hic2,
                                                regions['chromosome'][i],
                                                binbounds)
    fc = hifive.FiveC(fivec_fnames["Prob_Nora"])
    fragments = fc.frags['fragments'][...]
    regions = fc.frags['regions'][...]
    binbounds = numpy.hstack(
        (fragments['start']
         [regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1),
         fragments['stop']
         [regions['start_frag'][0]:regions['stop_frag'][0]].reshape(-1, 1)))
    binbounds = binbounds[numpy.where(
        fc.filter[regions['start_frag'][0]:regions['stop_frag'][0]])[0], :]
    hic_hm['Nora'] = dynamically_bin(hic1, hic2, regions['chromosome'][0],
                                     binbounds)
    dist_corr = find_correlations(hic_hm, fivec_fnames, out_fname, True)
    nodist_corr = find_correlations(hic_hm, fivec_fnames, out_fname, False)
    c = canvas.canvas()
    width = 16.8
    spacer = 0.4
    plot_width = (width - spacer * 2) / 2.5
    plot_height = plot_width
    key_width = width - (plot_width + spacer) * 2
    phillips_img = plot_correlation_diffs(dist_corr, nodist_corr, 'Phillips',
                                          plot_width, plot_height)
    nora_img = plot_correlation_diffs(dist_corr, nodist_corr, 'Nora',
                                      plot_width, plot_height)
    key_img = plot_key(key_width, plot_height)
    c.insert(phillips_img)
    c.insert(nora_img, [trafo.translate(plot_width + spacer, 0)])
    c.insert(key_img, [trafo.translate((plot_width + spacer) * 2, 0)])
    c.text(0, plot_height, "a",
           [text.halign.left, text.valign.top,
            text.size(-1)])
    c.text(plot_width + spacer, plot_height, "b",
           [text.halign.left, text.valign.top,
            text.size(-1)])
    c.writePDFfile(out_fname)
コード例 #46
0
ファイル: time_comparison.py プロジェクト: bxlab/HiFive_Paper
import sys
import os
from glob import glob
from math import floor

import numpy
from pyx import canvas, text, path, graph, color, trafo, unit, attr, deco, style, bitmap

unit.set(defaultunit="cm")
text.set(mode="latex")
text.preamble(r"\usepackage{times}")
text.preamble(r"\usepackage{sansmath}")
text.preamble(r"\sansmath")
text.preamble(r"\renewcommand*\familydefault{\sfdefault}")
painter = graph.axis.painter.regular(labeldist=0.1,
                                     labelattrs=[text.size(-3)],
                                     titleattrs=[text.size(-3)])
painter2 = graph.axis.painter.regular(labelattrs=None)

step_colors = {
    0: color.cmyk.MidnightBlue,
    1: color.cmyk.Mahogany,
    2: color.cmyk.CadetBlue,
    3: color.cmyk.Dandelion,
    4: color.cmyk.OliveGreen,
}

step_names = {
    '0': 'Loading data',
    '1': 'Filtering and preprocessing',
    '2': 'Binning',
コード例 #47
0
def plot_overall(data0, data1, width, height):
    vo = 0.55
    ho = 1.1
    plot_width = width - ho
    plot_height = height - vo
    c = canvas.canvas()
    methods = data0.keys()
    methods.sort()
    bar_colors = []
    cis_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where(
        data0[methods[0]]['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data0[methods[0]]['binsize'][numpy.where(
        data0[methods[0]]['interaction'] == 'trans')])
    ymin = numpy.inf
    ymax = -numpy.inf
    Y = numpy.zeros(
        (len(methods), cis_binsizes.shape[0] + trans_binsizes.shape[0]),
        dtype=numpy.float32)
    for i, method in enumerate(methods):
        for j, binsize in enumerate(cis_binsizes):
            where = numpy.where((data0[method]['binsize'] == binsize) *
                                (data0[method]['interaction'] == 'cis') *
                                (data0[method]['range'] < 0))
            where1 = numpy.where((data1[method]['binsize'] == binsize) *
                                 (data1[method]['interaction'] == 'cis') *
                                 (data1[method]['range'] < 0))
            if where[0].shape[0] > 0:
                Y[i, j] = (data1[method]['correlation'][where1] -
                           data0[method]['correlation'][where])
                ymin = min(ymin, Y[i, j])
                ymax = max(ymax, Y[i, j])
        for j, binsize in enumerate(trans_binsizes):
            where = numpy.where((data0[method]['binsize'] == binsize) *
                                (data0[method]['interaction'] == 'trans') *
                                (data0[method]['range'] < 0))
            where1 = numpy.where((data1[method]['binsize'] == binsize) *
                                 (data1[method]['interaction'] == 'trans') *
                                 (data1[method]['range'] < 0))
            if where[0].shape[0] > 0:
                Y[i, j + cis_binsizes.shape[0]] = (
                    data1[method]['correlation'][where1] -
                    data0[method]['correlation'][where])
                ymin = min(ymin, Y[i, j + cis_binsizes.shape[0]])
                ymax = max(ymax, Y[i, j + cis_binsizes.shape[0]])
        bar_colors.append(method_colors[method])
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    Y = numpy.array(Y)
    g = graph.graphxy(
        width=plot_width,
        height=plot_height,
        x=graph.axis.nestedbar(painter=graph.axis.painter.bar(nameattrs=None)),
        y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
        x2=graph.axis.lin(parter=None, min=0, max=1),
        y2=graph.axis.lin(parter=None, min=0, max=1))
    y0 = plot_height * (-ymin) / (ymax - ymin)
    g.stroke(
        path.line(0,
                  plot_height * (-ymin) / (ymax - ymin), plot_width,
                  plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    w0 = plot_width / Y.shape[1]
    w1 = w0 / (len(methods) + 0.5)
    for i in range(len(methods)):
        for j in range(Y.shape[1]):
            x = j * w0 + (i + 0.25) * w1
            y = plot_height * (Y[i, j] - ymin) / (ymax - ymin)
            g.stroke(path.rect(x, y0, w1, y - y0),
                     [deco.filled([method_colors[methods[i]]])])
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb",
                               "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label,
               [text.halign.center, text.valign.top,
                text.size(-3)])
    c.text(ho + plot_width * 2.0 / 6.0, 0.05, "cis",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(
        path.line(ho + 0.2, vo * 0.5, ho - 0.2 + plot_width * 4.0 / 6.0,
                  vo * 0.5), [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0.05, "trans",
           [text.halign.center, text.valign.bottom,
            text.size(-3)])
    c.stroke(
        path.line(ho + 0.2 + plot_width * 4.0 / 6.0, vo * 0.5,
                  ho - 0.2 + plot_width, vo * 0.5), [style.linewidth.THin])
    c.text(
        0, plot_height * 0.5 + vo, r"$r_{0K} - r_{500K}$",
        [text.halign.center, text.valign.top,
         text.size(-2),
         trafo.rotate(90)])
    return c
コード例 #48
0
ファイル: time_comparison.py プロジェクト: bxlab/HiFive_Paper
def plot_bargraph(data, width, height):
    methods = [
        'HiCLib', 'HiCPipe', 'HiCNorm', 'HiFive-Probability', 'HiFive-Binning',
        'HiFive-Express', 'HiFive-ExpressKR', 'HiFive-ExpressKR w/distance'
    ]
    ho = 4.0
    left_width = (width - ho) * 0.45
    mid_width1 = (width - ho) * 0.3
    mid_width2 = (width - ho) * 0.125
    right_width = (width - ho) * 0.125
    bar_height = height / len(methods) - 0.1
    data_totals = {}
    ranges = numpy.zeros((4, 2), dtype=numpy.float32)
    for meth in data:
        data_totals[meth] = find_total(data[meth])
        if meth == 'HiCPipe':
            ranges[1, 1] = data_totals[meth]
        elif meth == 'HiCNorm':
            ranges[2, 1] = data_totals[meth]
        elif meth == 'HiFive-Probability':
            ranges[3, 1] = data_totals[meth]
        else:
            ranges[0, 1] = max(ranges[0, 1], data_totals[meth])
    ranges /= 60.0
    ranges[0, 1] = 28.0
    ranges[1, 0] = ranges[1, 1] - ranges[0, 1] / 0.45 * 0.3 * 0.9
    ranges[1, 1] = ranges[1, 1] + ranges[0, 1] / 0.45 * 0.3 * 0.1
    ranges[2, 0] = ranges[2, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[2, 1] = ranges[2, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[3, 0] = ranges[3, 1] - ranges[0, 1] / 0.45 * 0.125 * 0.5
    ranges[3, 1] = ranges[3, 1] + ranges[0, 1] / 0.45 * 0.125 * 0.5
    c = canvas.canvas()
    g1 = graph.graphxy(width=left_width,
                       height=height,
                       x=graph.axis.lin(painter=painter,
                                        min=0,
                                        max=ranges[0, 1]),
                       x2=graph.axis.lin(parter=None, min=0, max=ranges[0, 1]),
                       y=graph.axis.lin(parter=None, min=0, max=1),
                       y2=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g1)
    g2 = graph.graphxy(width=mid_width1,
                       height=height,
                       x=graph.axis.lin(painter=painter,
                                        min=ranges[1, 0],
                                        max=ranges[1, 1]),
                       x2=graph.axis.lin(parter=None,
                                         min=ranges[1, 0],
                                         max=ranges[1, 1]),
                       y2=graph.axis.lin(painter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g2, [trafo.translate(left_width, 0)])
    g3 = graph.graphxy(width=mid_width2,
                       height=height,
                       x=graph.axis.lin(painter=painter,
                                        min=ranges[2, 0],
                                        max=ranges[2, 1]),
                       x2=graph.axis.lin(parter=None,
                                         min=ranges[2, 0],
                                         max=ranges[2, 1]),
                       y2=graph.axis.lin(painter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g3, [trafo.translate(left_width + mid_width1, 0)])
    g4 = graph.graphxy(width=right_width,
                       height=height,
                       x=graph.axis.lin(painter=painter,
                                        min=ranges[3, 0],
                                        max=ranges[3, 1]),
                       x2=graph.axis.lin(parter=None,
                                         min=ranges[3, 0],
                                         max=ranges[3, 1]),
                       y2=graph.axis.lin(parter=None, min=0, max=1),
                       y=graph.axis.lin(painter=None, min=0, max=1))
    c.insert(g4, [trafo.translate(left_width + mid_width1 + mid_width2, 0)])
    split = canvas.canvas()
    split.fill(
        path.path(path.moveto(-0.15, -0.2), path.lineto(0.05, 0.2),
                  path.lineto(.15, 0.2), path.lineto(-0.05, -0.2),
                  path.closepath()), [color.cmyk.White])
    split.stroke(path.line(-0.15, -0.2, 0.05, 0.2))
    split.stroke(path.line(-0.05, -0.2, 0.15, 0.2))
    c.insert(split, [trafo.translate(left_width, 0)])
    c.insert(split, [trafo.translate(left_width, height)])
    c.insert(split, [trafo.translate(left_width + mid_width1, 0)])
    c.insert(split, [trafo.translate(left_width + mid_width1, height)])
    c.insert(split, [trafo.translate(left_width + mid_width1 + mid_width2, 0)])
    c.insert(split,
             [trafo.translate(left_width + mid_width1 + mid_width2, height)])
    for i, meth in enumerate(methods):
        c.insert(
            plot_bar(data[meth], ranges, bar_height, left_width / ranges[0, 1],
                     split),
            [
                trafo.translate(0, height - 0.05 - bar_height *
                                (i + 1) - i * 0.1)
            ])
        c.text(-0.1,
               height * (len(methods) - i - 0.5) / len(methods), meth,
               [text.halign.right, text.valign.middle,
                text.size(-2)])
    c.text((width - ho) / 2.0, -0.35, "Runtime (minutes)",
           [text.halign.center, text.valign.top,
            text.size(-2)])
    return c
コード例 #49
0
                                       ('file 2', (0, 1, 2, 3, 5)),
                                       ('file 3', (1, 4, 5)))):
    nr_revisions = max(nr_revisions, max(versions))
    hue = hueoff+nr/3
    cf.text(0, -nr*dy, name, [color.hsb(hue, 1, 0.5), text.valign.middle])
    for nver, (v1, v2) in enumerate(zip(versions[:-1], versions[1:])):
        y = -(nr+0.4)*dy
        lv = len(versions)-1
        xll = v1*dx+versionoff+0.1
        yll = y
        width = (v2-v1)*dx-0.2
        height = 0.8*dy
        cf.fill(path.rect(xll, yll, width, height),
                [color.hsb(hue, 1-(lv-1-nver)/(lv-1)*0.7, 0.6)])
        cf.text(xll+0.5*width, yll+0.5*height, gethashstring(),
                [text.size(-4), text.halign.center, text.valign.middle, color.grey(1)])
for n in range(nr_revisions):
    xcenter = (n+0.5)*dx+versionoff
    y = 0.5
    cf.text(xcenter, y, gethashstring(), [text.size(-4), text.halign.center])
    if n:
        yshift = 0.1
        cf.stroke(path.line(xcenter-0.33*dx, y+yshift, xcenter-0.67*dx, y+yshift),
                  [deco.earrow])
cf.stroke(path.rect(3*dx+versionoff, -2.6*dy, dx, 2.6*dy+1.0),
              [style.linewidth.THIck, deformer.smoothed(0.3)])
    
c.insert(cf, [trafo.translate(4.5, 1)])

c.writePDFfile()
コード例 #50
0
import os

import numpy
from pyx import canvas, text, path, graph, color, trafo, unit, attr, deco, style, bitmap
import h5py

import hifive


unit.set(defaultunit="cm")
text.set(mode="latex")
text.preamble(r"\usepackage{times}")
text.preamble(r"\usepackage{sansmath}")
text.preamble(r"\sansmath")
text.preamble(r"\renewcommand*\familydefault{\sfdefault}")
painter = graph.axis.painter.regular( labeldist=0.1, labelattrs=[text.size(-3)], titleattrs=[text.size(-3)] )

methods = ['Raw', 'Prob', 'Exp', 'Bin', 'Exp-KR']
method_colors = {
        'Prob':color.cmyk.Black,
        'Exp':color.cmyk.CadetBlue,
        'Bin':color.cmyk.MidnightBlue, 
        'Raw':color.cmyk.Dandelion,
        'Exp-KR':color.cmyk.Mahogany,
}


def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    hic_phillips_fname1 = "%s/Data/HiC/HiCPipe/HM/mm9_ESC_NcoI_Phillips.hch" % basedir
コード例 #51
0
def draw_continent_circle(con,
                          name="",
                          draw_upper_landscape=True,
                          draw_lower_landscape=False,
                          draw_upper_green=True,
                          draw_lower_purple=False,
                          draw_train_tracks=False,
                          draw_foliation=True,
                          foliation_style_old=False,
                          foliation_style_split=False,
                          foliation_style_cusp_leaves=True,
                          foliation_style_boundary_leaves=True,
                          shade_triangles=False,
                          draw_fund_domain=False,
                          fund_dom_tets=None,
                          draw_fund_domain_edges=False,
                          draw_tetrahedron_rectangles=[]):

    global_scale_up = 10.0
    edge_thickness = 0.02
    track_thickness = 0.02
    leaf_thickness = 0.03
    edge_colours = {
        True: color.rgb(0.9, 0.3, 0),
        False: color.rgb(0, 0.3, 0.9)
    }
    green = color.rgb(0.0, 0.5, 0.0)
    purple = color.rgb(0.5, 0.0, 0.5)

    scl = trafo.trafo(matrix=((global_scale_up, 0), (0, global_scale_up)),
                      vector=(0, 0))
    canv = canvas.canvas()
    canv.stroke(path.circle(0, 0, global_scale_up), [style.linewidth(0.02)])

    n = len(con.coast)
    for v in con.coast:
        i = v.coastal_index
        t = 2 * pi * float(i) / float(n)
        v.circle_pos = complex(cos(t), sin(t))
        vert_pos = v.circle_pos * 1.01 * global_scale_up
        canv.text(vert_pos.real,
                  vert_pos.imag,
                  "$" + str(con.vertices.index(v)) + "$",
                  textattrs=[
                      text.size(-4), text.halign.left, text.valign.middle,
                      trafo.rotate(
                          (180 / pi) * atan2(vert_pos.imag, vert_pos.real))
                  ])

        # vert_pos2 = v.circle_pos * 1.2 * global_scale_up
        # p = path.path(path.moveto(vert_pos.real, vert_pos.imag), path.lineto(vert_pos2.real, vert_pos2.imag))
        # canv.stroke(p, [deco.curvedtext("$"+str(con.vertices.index(v))+"$")])

    ### highlight vertices of tetrahedra in a fundamental domain
    if draw_fund_domain:
        if fund_dom_tets == None:
            fund_dom_tets = get_fund_domain_tetrahedra(con)
        for con_tet in fund_dom_tets:
            if type(
                    con_tet
            ) == continent_tetrahedron:  ### could be an integer if we didnt find this tet
                if draw_fund_domain_edges:
                    for e in con_tet.edges():
                        col = edge_colours[e.is_red]
                        u, v = e.vertices
                        p = make_arc(u.circle_pos, v.circle_pos)
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(edge_thickness),
                            style.linecap.round, col
                        ])

        update_fund_dom_tet_nums(con, fund_dom_tets)
        for v in [v for v in con.coast if v.fund_dom_tet_nums != []]:
            vert_pos = v.circle_pos * 1.03 * global_scale_up
            canv.text(vert_pos.real,
                      vert_pos.imag,
                      "$" + str(v.fund_dom_tet_nums) + "$",
                      textattrs=[
                          text.size(-4), text.halign.left, text.valign.middle,
                          trafo.rotate(
                              (180 / pi) * atan2(vert_pos.imag, vert_pos.real))
                      ])

    # lower_colours = {True: color.rgb(0.5,0.3,0), False: color.rgb(0,0.3,0.5)}
    # upper_colours = {True: color.rgb(0.9,0.3,0), False: color.rgb(0,0.3,0.9)}

    landscape_edges = [con.lower_landscape_edges, con.upper_landscape_edges]

    # colours = [lower_colours, upper_colours]

    upper_tris = con.upper_landscape_triangles
    lower_tris = con.lower_landscape_triangles
    boundary_tris = [lower_tris, upper_tris]

    if shade_triangles:
        u, v, w = con.triangle_path[0].vertices
        p = make_arc(u.circle_pos, v.circle_pos)
        q = make_arc(v.circle_pos, w.circle_pos)
        r = make_arc(w.circle_pos, u.circle_pos)
        p.append(q[1])
        p.append(r[1])  ### remove extraneous moveto commands
        p = p.transformed(scl)
        canv.stroke(
            p, [deco.filled([color.transparency(0.8)]),
                style.linewidth(0)])
        u, v, w = con.triangle_path[-1].vertices
        p = make_arc(u.circle_pos, v.circle_pos)
        q = make_arc(v.circle_pos, w.circle_pos)
        r = make_arc(w.circle_pos, u.circle_pos)
        p.append(q[1])
        p.append(r[1])  ### remove extraneous moveto commands
        p = p.transformed(scl)
        canv.stroke(
            p, [deco.filled([color.transparency(0.8)]),
                style.linewidth(0)])
        # for triangle in con.triangle_path:
        #     u,v,w = triangle.vertices
        #     p = make_arc(u.circle_pos, v.circle_pos)
        #     q = make_arc(v.circle_pos, w.circle_pos)
        #     r = make_arc(w.circle_pos, u.circle_pos)
        #     p.append(q[1])
        #     p.append(r[1])  ### remove extraneous moveto commands
        #     p = p.transformed(scl)
        #     canv.stroke(p, [deco.filled([color.transparency(0.8)]), style.linewidth(0)])

    to_do = []
    if draw_lower_landscape:
        to_do.append(0)
    if draw_upper_landscape:
        to_do.append(1)
    for i in to_do:
        for e in landscape_edges[i]:
            col = edge_colours[e.is_red]
            transp = []
            if i == 0:
                transp = [color.transparency(0.75)]
            u, v = e.vertices
            p = make_arc(u.circle_pos, v.circle_pos)
            p = p.transformed(scl)
            canv.stroke(
                p,
                [style.linewidth(edge_thickness), style.linecap.round, col] +
                transp)
        for tri in boundary_tris[i]:
            center = incenter(tri.vertices[0].circle_pos,
                              tri.vertices[1].circle_pos,
                              tri.vertices[2].circle_pos)
            # canv.fill(path.circle(global_scale_up*center[0], global_scale_up*center[1], 0.1))
            canv.text(global_scale_up * center[0],
                      global_scale_up * center[1],
                      "$" + str(tri.index) + "$",
                      textattrs=[
                          text.size(-2), text.halign.center, text.valign.middle
                      ] + transp)

    ### train tracks...

    purple_train_routes = [
    ]  ### pairs of coastal edges corresponding to a train route
    green_train_routes = []
    if draw_lower_purple:
        if draw_train_tracks:
            for tri in lower_tris:
                midpts = []
                is_reds = []
                for e in tri.edges:
                    is_reds.append(e.is_red)
                    u, v = e.vertices
                    p, midpt = make_arc(u.circle_pos,
                                        v.circle_pos,
                                        return_midpt=True)
                    midpts.append(midpt)
                for i in range(3):
                    if (is_reds[i] == is_reds[(i + 1) % 3]) or (
                            not is_reds[i] and is_reds[(i + 1) % 3]):
                        p = make_arc(midpts[i], midpts[(i + 1) % 3])
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(track_thickness),
                            style.linecap.round, purple
                        ])
        if draw_foliation:
            for edge in con.lower_landscape_edges:
                leaf_end_edges = []
                if edge.is_coastal():
                    if not edge.is_coastal_sink(upper=False):
                        leaf_end_edges.append(edge)
                        for tri in edge.boundary_triangles:
                            if not tri.is_upper:
                                last_tri = con.flow(tri)[0]
                                last_edge = last_tri.edges[
                                    last_tri.downriver_index()]
                                leaf_end_edges.append(last_edge)
                else:
                    if edge.is_watershed():
                        for tri in edge.boundary_triangles:
                            last_tri = con.flow(tri)[0]
                            last_edge = last_tri.edges[
                                last_tri.downriver_index()]
                            leaf_end_edges.append(last_edge)
                if len(leaf_end_edges) == 2:
                    purple_train_routes.append(leaf_end_edges)
                    if foliation_style_old:
                        leaf_ends = []
                        for e in leaf_end_edges:
                            endpts = e.vertices
                            _, midpt = make_arc(endpts[0].circle_pos,
                                                endpts[1].circle_pos,
                                                return_midpt=True)
                            leaf_ends.append(midpt)
                        p = make_arc(leaf_ends[0], leaf_ends[1])
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, purple
                        ])

    if draw_upper_green:
        if draw_train_tracks:
            for tri in upper_tris:
                midpts = []
                is_reds = []
                for e in tri.edges:
                    is_reds.append(e.is_red)
                    u, v = e.vertices
                    p, midpt = make_arc(u.circle_pos,
                                        v.circle_pos,
                                        return_midpt=True)
                    midpts.append(midpt)
                for i in range(3):
                    if (is_reds[i] == is_reds[(i + 1) % 3]) or (
                            is_reds[i] and not is_reds[(i + 1) % 3]):
                        p = make_arc(midpts[i], midpts[(i + 1) % 3])
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(track_thickness),
                            style.linecap.round, green
                        ])
        if draw_foliation:
            for edge in con.upper_landscape_edges:
                leaf_end_edges = []
                if edge.is_coastal():
                    if not edge.is_coastal_sink(upper=True):
                        leaf_end_edges.append(edge)
                        for tri in edge.boundary_triangles:
                            if tri.is_upper:
                                last_tri = con.flow(tri)[0]
                                last_edge = last_tri.edges[
                                    last_tri.downriver_index()]
                                leaf_end_edges.append(last_edge)
                else:
                    if edge.is_watershed():
                        for tri in edge.boundary_triangles:
                            last_tri = con.flow(tri)[0]
                            last_edge = last_tri.edges[
                                last_tri.downriver_index()]
                            leaf_end_edges.append(last_edge)
                if len(leaf_end_edges) == 2:
                    green_train_routes.append(leaf_end_edges)
                    if foliation_style_old:
                        leaf_ends = []
                        for e in leaf_end_edges:
                            endpts = e.vertices
                            _, midpt = make_arc(endpts[0].circle_pos,
                                                endpts[1].circle_pos,
                                                return_midpt=True)
                            leaf_ends.append(midpt)
                        p = make_arc(leaf_ends[0], leaf_ends[1])
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, green
                        ])

    if draw_foliation and (foliation_style_split or foliation_style_cusp_leaves
                           or foliation_style_boundary_leaves):
        for e in con.coastal_edges:
            e.purple_ends = []
            e.green_ends = []
        for e1, e2 in purple_train_routes:
            e1.purple_ends.append(e2)
            e2.purple_ends.append(e1)
        for e1, e2 in green_train_routes:
            e1.green_ends.append(e2)
            e2.green_ends.append(e1)
        for i, e in enumerate(con.coastal_edges):
            rotated_coastal_edges = con.coastal_edges[
                i:] + con.coastal_edges[:i]
            e.purple_ends.sort(
                key=lambda e_other: rotated_coastal_edges.index(e_other),
                reverse=True)
            e.green_ends.sort(
                key=lambda e_other: rotated_coastal_edges.index(e_other),
                reverse=True)
            if e.is_red:
                e.ends = e.green_ends + e.purple_ends
            else:
                e.ends = e.purple_ends + e.green_ends
        if foliation_style_split:
            for e1, e2 in purple_train_routes:
                p1 = end_pos(e2, e1)
                p2 = end_pos(e1, e2)
                p = make_arc(p1, p2)
                p = p.transformed(scl)
                canv.stroke(p, [
                    style.linewidth(leaf_thickness), style.linecap.round,
                    purple
                ])
            for e1, e2 in green_train_routes:
                p1 = end_pos(e2, e1)
                p2 = end_pos(e1, e2)
                p = make_arc(p1, p2)
                p = p.transformed(scl)
                canv.stroke(p, [
                    style.linewidth(leaf_thickness), style.linecap.round, green
                ])
        if foliation_style_cusp_leaves or foliation_style_boundary_leaves:
            for i, c in enumerate(con.coast):
                c.purple_thorn_end_positions = []  ### complex numbers
                c.purple_thorn_ends = [
                ]  ### [coastal arc, position along that arc]
                e = con.coastal_edges[i]
                e1 = e.purple_ends[0]
                while True:
                    index = e1.purple_ends.index(e)
                    if index == len(e1.purple_ends) - 1:
                        break
                    else:
                        c.purple_thorn_end_positions.append(
                            end_pos(e, e1, offset=0.5))
                        c.purple_thorn_ends.append((e1, e1.ends.index(e)))
                        e, e1 = e1, e1.purple_ends[index + 1]

                if foliation_style_boundary_leaves:
                    e_before = con.coastal_edges[(i - 1) % len(con.coast)]
                    e_after = con.coastal_edges[i]
                    first_pos = end_pos(e_after.purple_ends[0],
                                        e_after,
                                        offset=-0.25)
                    last_pos = end_pos(e_before.purple_ends[-1],
                                       e_before,
                                       offset=0.25)
                    c.purple_thorn_end_positions = [
                        first_pos
                    ] + c.purple_thorn_end_positions + [last_pos]
                    arcs = []
                    for i in range(len(c.purple_thorn_end_positions) - 1):
                        arcs.append(
                            make_arc(c.purple_thorn_end_positions[i],
                                     c.purple_thorn_end_positions[i + 1]))
                    for p in arcs:
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, purple
                        ])

                if foliation_style_cusp_leaves:
                    for thorn_end in c.purple_thorn_ends:
                        thorn_end_pos = end_pos2(thorn_end)
                        p = make_arc(c.circle_pos, thorn_end_pos)
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, purple
                        ])

            for i, c in enumerate(con.coast):
                c.green_thorn_end_positions = []  ### complex numbers
                c.green_thorn_ends = [
                ]  ### [coastal arc, position along that arc]
                e = con.coastal_edges[i]
                e1 = e.green_ends[0]
                while True:
                    index = e1.green_ends.index(e)
                    if index == len(e1.green_ends) - 1:
                        break
                    else:
                        c.green_thorn_end_positions.append(
                            end_pos(e, e1, offset=0.5))
                        c.green_thorn_ends.append((e1, e1.ends.index(e)))
                        e, e1 = e1, e1.green_ends[index + 1]
                if foliation_style_boundary_leaves:
                    e_before = con.coastal_edges[(i - 1) % len(con.coast)]
                    e_after = con.coastal_edges[i]
                    first_pos = end_pos(e_after.green_ends[0],
                                        e_after,
                                        offset=-0.25)
                    last_pos = end_pos(e_before.green_ends[-1],
                                       e_before,
                                       offset=0.25)
                    c.green_thorn_end_positions = [
                        first_pos
                    ] + green_thorn_end_positions + [last_pos]
                    arcs = []
                    for i in range(len(c.green_thorn_end_positions) - 1):
                        arcs.append(
                            make_arc(c.green_thorn_end_positions[i],
                                     c.green_thorn_end_positions[i + 1]))
                    for p in arcs:
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, green
                        ])

                if foliation_style_cusp_leaves:
                    for thorn_end in c.green_thorn_ends:
                        thorn_end_pos = end_pos2(thorn_end)
                        p = make_arc(c.circle_pos, thorn_end_pos)
                        p = p.transformed(scl)
                        canv.stroke(p, [
                            style.linewidth(leaf_thickness),
                            style.linecap.round, green
                        ])

            for tet in draw_tetrahedron_rectangles:
                purple_sides = tet_purple_rectangle_sides(
                    tet, actually_do_green=False)
                green_sides = tet_purple_rectangle_sides(
                    tet, actually_do_green=True)
                for side in purple_sides:
                    for cusp_leaf in side:
                        if cusp_leaf != None:
                            v, thorn_end = cusp_leaf
                            thorn_end_pos = end_pos2(thorn_end)
                            p = make_arc(v.circle_pos, thorn_end_pos)
                            p = p.transformed(scl)
                            canv.stroke(p, [
                                style.linewidth(2 * leaf_thickness),
                                style.linecap.round, purple
                            ])
                for side in green_sides:
                    for cusp_leaf in side:
                        if cusp_leaf != None:
                            v, thorn_end = cusp_leaf
                            thorn_end_pos = end_pos2(thorn_end)
                            p = make_arc(v.circle_pos, thorn_end_pos)
                            p = p.transformed(scl)
                            canv.stroke(p, [
                                style.linewidth(2 * leaf_thickness),
                                style.linecap.round, green
                            ])

    output_filename = 'Images/CircleContinent/' + name + '.pdf'
    canv.writePDFfile(output_filename)
コード例 #52
0
ファイル: poster.py プロジェクト: punkdit/fibonacci
def cross(x, y, r=0.1):
    c.stroke(path.line(x-r, y, x+r, y))
    c.stroke(path.line(x, y-r, x, y+r))

cross(0.1, 0.1)
cross(w-0.1, 0.1)
cross(0.1, h-0.1)
cross(w-0.1, h-0.1)


y = h-2*dr

c.text(w/2, y,
    r"{\huge Error Correction in a Fibonacci Fusion Code}",
    [text.halign.boxcenter, text.valign.top, text.size(1)])

y -= 2*dr
c.text(w/2, y,
    r"{\large Simon Burton$^1$, Courtney G. Brell$^{1,2}$, Steven T. Flammia$^1$}",
    [text.halign.boxcenter, text.valign.top])

#c.text(w/2, y,
#    r"{\large Simon Burton{\tiny(1)}, Courtney G. Brell\(1,2\), Steven T. Flammia{(1)}}",
#    [text.halign.boxcenter, text.valign.top])

y -= dr
c.text(w/2, y,
    r"{\it $^1$ Centre for Engineered Quantum Systems, School of Physics, The University of Sydney, Sydney, Australia}",
    [text.halign.boxcenter, text.valign.top])
コード例 #53
0
def plot_overall(data0, data1, width, height):
    vo = 1.15
    ho = 1.15
    plot_width = width - ho
    plot_height = height - vo
    c = canvas.canvas()
    cis_binsizes = numpy.unique(data0['binsize'][numpy.where(data0['interaction'] == 'cis')])
    trans_binsizes = numpy.unique(data0['binsize'][numpy.where(data0['interaction'] == 'trans')])
    ymin = numpy.inf
    ymax = -numpy.inf
    Y = numpy.zeros((cis_binsizes.shape[0] + trans_binsizes.shape[0]), dtype=numpy.float32)    
    for j, binsize in enumerate(cis_binsizes):
        where = numpy.where((data0['binsize'] == binsize) *
                            (data0['interaction'] == 'cis') *
                            (data0['range'] < 0))
        where1 = numpy.where((data1['binsize'] == binsize) *
                             (data1['interaction'] == 'cis') *
                             (data1['range'] < 0))
        if where[0].shape[0] > 0:
            Y[j] = (data1['correlation'][where1] - data0['correlation'][where])
            ymin = min(ymin, Y[j])
            ymax = max(ymax, Y[j])
    for j, binsize in enumerate(trans_binsizes):
        where = numpy.where((data0['binsize'] == binsize) *
                            (data0['interaction'] == 'trans') *
                            (data0['range'] < 0))
        where1 = numpy.where((data1['binsize'] == binsize) *
                             (data1['interaction'] == 'trans') *
                             (data1['range'] < 0))
        if where[0].shape[0] > 0:
            Y[j + cis_binsizes.shape[0]] = (data1['correlation'][where1] - data0['correlation'][where])
            ymin = min(ymin, Y[j + cis_binsizes.shape[0]])
            ymax = max(ymax, Y[j + cis_binsizes.shape[0]])
    yspan = ymax - ymin
    ymin -= yspan * 0.05
    ymax += yspan * 0.05
    Y = numpy.array(Y)
    g = graph.graphxy(width=plot_width, height=plot_height,
                      x=graph.axis.bar(painter=graph.axis.painter.bar(nameattrs=None)),
                      y=graph.axis.lin(painter=painter, min=ymin, max=ymax),
                      x2=graph.axis.lin(parter=None, min=0, max=1),
                      y2=graph.axis.lin(parter=None, min=0, max=1))
    y0 = plot_height * (-ymin) / (ymax - ymin)
    g.stroke(path.line(0, plot_height * (-ymin) / (ymax - ymin), plot_width, plot_height * (-ymin) / (ymax - ymin)),
        [style.linestyle.dotted, style.linewidth.THin])
    w0 = plot_width / Y.shape[0]
    w1 = w0 / 1.5
    for j in range(Y.shape[0]):
        x = j * w0 + 0.25 * w1
        y = plot_height * (Y[j] - ymin) / (ymax - ymin)
        g.fill( path.rect(x, y0, w1, y - y0) )
    c.insert(g, [trafo.translate(ho, vo)])
    for i, label in enumerate(["10Kb", "50Kb", "250Kb", "1Mb", "250Kb", "1Mb"]):
        c.text(ho + plot_width * (i + 0.5) / 6.0, vo - 0.05, "%s" % label,
               [text.halign.right, text.valign.middle, text.size(-3), trafo.rotate(90)])
    c.text(ho + plot_width * 2.0 / 6.0, 0, "cis",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2, 0.3, ho - 0.2 + plot_width * 4.0 / 6.0, 0.3), [style.linewidth.THin])
    c.text(ho + plot_width * 5.0 / 6.0, 0, "trans",
           [text.halign.center, text.valign.bottom, text.size(-3)])
    c.stroke(path.line(ho + 0.2 + plot_width * 4.0 / 6.0, 0.3, ho - 0.2 + plot_width, 0.3), [style.linewidth.THin])
    c.text(0, plot_height * 0.5 + vo, r"$r_{Poisson} - r_{binomial}$",
           [text.halign.center, text.valign.top, text.size(-2), trafo.rotate(90)])
    c.text(0, height, 'b', [text.halign.left, text.valign.top, text.size(-1)])
    return c