def draw_points_lines_crs(points: torch.Tensor,
                          lines: torch.Tensor,
                          crs: torch.Tensor,
                          filename,
                          size=1,
                          lw=1,
                          clw=1,
                          pcols=None,
                          lcols=None,
                          crscols=None,
                          canvas_clip=None,
                          svg=False):
    if canvas_clip is not None:
        c = canvas.canvas([canvas.clip(path.rect(*canvas_clip))])
    else:
        c = canvas.canvas()

    draw_points_to_canvas(c, points, size, pcols)
    draw_lines_to_canvas(c, lines, lw, lcols)
    draw_crs_to_canvas(c, crs, clw, crscols)

    if svg:
        c.writeSVGfile(file=filename)
    else:
        c.writePDFfile(file=filename)
Exemple #2
0
    def draw(self, r=5):
        c = canvas.canvas()

        x_centre = r + 1
        y_centre = r + 1

        angle_diff = 2*math.pi/self.n

        def get_pos(index):
            x_pos = x_centre + math.sin(index*angle_diff)*r
            y_pos = y_centre + math.cos(index*angle_diff)*r
            return x_pos, y_pos

        # nodes
        for i in range(self.n):
            x, y = get_pos(i)
            c.stroke(path.circle(x, y, 1))
            c.text(x, y, i)

        # edges
        for i in range(self.n):
            for j in range(self.n):
                if math.isnan(self.adj_mat[i, j]):
                    continue
                x1, y1 = get_pos(i)
                x2, y2 = get_pos(j)
                x_offset = (x2 - x1)/math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
                y_offset = (y2 - y1)/math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
                arc = path.line(x1 + x_offset, y1 + y_offset, x2 - x_offset, y2 - y_offset)
                c.stroke(arc, [deco.earrow()])
                c.text((x1 + x2)/2 + x_offset, (y1 + y2)/2 + y_offset, self.adj_mat[i, j])  # moved towards the end pt

        c.writePDFfile("graph")
Exemple #3
0
def main():
    A4_lsc = document.paperformat(
        document.paperformat.A4.height, document.paperformat.A4.width)

    text.set(text.UnicodeEngine, fontname="cmss12", size=12)

    pages = []
    for i in (
        ('C', 'Am', 'C#', 'A#m'),
        ('D', 'Bm', 'D#', 'Cm'),
        ('E', 'C#m', 'F', 'Dm'),
        ('F#', 'D#m', 'G', 'Em'),
        ('G#', 'Fm', 'A', 'F#m'),
        ('A#', 'Gm', 'B', 'G#m')
    ):
        c = canvas.canvas()
        c.text(0, 32, f'{i[0]} Pentatonic Scale')
        Pentatonic(0, 26, i[0]).render(c, intervals=True)

        c.text(0, 24, f'{i[1]} Pentatonic Scale')
        Pentatonic(0, 18, i[1]).render(c, intervals=True)

        c.text(0, 16, f'{i[2]} Pentatonic Scale')
        Pentatonic(0, 10, i[2]).render(c, intervals=True)

        c.text(0, 8, f'{i[3]} Pentatonic Scale')
        Pentatonic(0, 2, i[3]).render(c, intervals=True)

        page = document.page(c, paperformat=A4_lsc, fittosize=1, margin=2)
        pages.append(page)

    doc = document.document(pages=pages)
    doc.writePDFfile("pentatonic")
Exemple #4
0
def array34(arange, hlshape=None):
    c = canvas.canvas()
    if hlshape is None:
        c.text(2, 3.3, 'shape=(3, 4)', [text.halign.center])
    else:
        c.text(2, 3.3, 'shape=%s' % repr(hlshape), [text.halign.center])
    if hlshape is not None:
        if len(hlshape) == 1:
            hlshape = (1, hlshape[0])
    if arange:
        gridcolor = color.grey(0)
    else:
        gridcolor = color.grey(0.5)
    if hlshape is None:
        arange = True
    elif (hlshape[0] in (1, 3)) and (hlshape[1] in (1, 4)):
        arange = False
    else:
        arange = None
    drawgrid(c, 4, 3, 0, gridcolor, arange=arange)
    if hlshape is not None:
        c.stroke(path.rect(0, 3, hlshape[1], -hlshape[0]),
                 [deco.filled([color.rgb(1, 0.8, 0.4)])])
        drawgrid(c, hlshape[1], hlshape[0], 3 - hlshape[0], arange=False)
    if arange is None:
        alertcolor = color.rgb(0.6, 0, 0)
        c.stroke(path.line(0, 0, 4, 3), [alertcolor, style.linewidth.Thick])
        c.stroke(path.line(0, 3, 4, 0), [alertcolor, style.linewidth.Thick])
    return c
Exemple #5
0
 def paintcolumn(self, plotitems):
     "creates the layout of a key column"
     c = canvas.canvas()
     self.dist_pt = unit.topt(self.dist)
     self.hdist_pt = unit.topt(self.hdist)
     self.vdist_pt = unit.topt(self.vdist)
     self.symbolwidth_pt = unit.topt(self.symbolwidth)
     self.symbolheight_pt = unit.topt(self.symbolheight)
     self.symbolspace_pt = unit.topt(self.symbolspace)
     titleboxes = []
     for plotitem in plotitems:
         titlebox = c.texrunner.text_pt(
             0, 0, plotitem.title, self.defaulttextattrs + self.textattrs)
         titlebox.plotitem = plotitem
         titleboxes.append(titlebox)
     dy_pt = box.tile_pt(titleboxes, self.dist_pt, 0, -1)
     box.linealignequal_pt(titleboxes,
                           self.symbolwidth_pt + self.symbolspace_pt, 1, 0)
     y_pt = -0.5 * self.symbolheight_pt + titleboxes[0].center[1]
     for titlebox in titleboxes:
         titlebox.plotitem.key_pt(c, 0, y_pt, self.symbolwidth_pt,
                                  self.symbolheight_pt)
         y_pt -= dy_pt
     for titlebox in titleboxes:
         c.insert(titlebox)
     return c
Exemple #6
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
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
Exemple #8
0
 def try_size(self, frame_shape, file=''):
     # first we setup the block anew
     self.frame = Frame(self.dimensions, self.num_vectors, self.steps)
     first_frame_shape = self.get_first_frame_shape()
     self.frame.seed_frame(first_frame_shape)
     cross_vectors = self.get_cross_vectors()
     for vector in cross_vectors:
         self.frame.populate(vector)
     # now we try to grow our block to the right size
     if not self.frame.grow_to_size(frame_shape):
         return None
     print '--> generating linear system'
     linear_system = self.generate_linear_system()
     print '     size is %s, %s' % (len(linear_system), len(linear_system[0]))
     print '--> trying to find a solution'
     vector_solution = self.solve(linear_system)
     if vector_solution is None:
         print '--> solution not found'
         return None
     else:
         print '--> solution found'
     solution = self.normalize_solution(vector_solution)
     self.set_edge_weights(solution)
     if file:
         c = canvas.canvas()
         self.draw_edges(c)
         c.writePDFfile(file)
Exemple #9
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
Exemple #10
0
 def Draw(self, file):
     # this simply creates a canvas, draws the interior and exterior and 
     # then exports it as a PDF
     c = canvas.canvas()
     DrawBlock(self.block, c)
     DrawBlock(self.interior, c)
     c.writePDFfile(file)
Exemple #11
0
def make_stride_figure(lowerstride, upperstride=1, nrentries=6):
    c = canvas.canvas()
    ht = 0.5
    wd = 2
    dist = 0.2
    textcolor = color.hsb(0.02, 1, 0.6)
    for n in range(nrentries):
        x = n*(wd+dist)
        c.stroke(path.rect(x, 0, wd, ht))
        c.text(x+0.5*wd, 0.5*ht, str(n), [text.halign.center, text.valign.middle])

    for n in range(nrentries-1):
        x = n*(wd+dist)
        c.stroke(path.curve(x-dist/3, ht+0.5*dist,
                            x+0.3*wd, ht+3*dist,
                            x+0.7*wd, ht+3*dist,
                            x+wd+dist/3, ht+0.5*dist),
                 [deco.earrow.large])
        c.text(x+0.5*wd, ht+3.2*dist, r'\Large 8', [text.halign.center, textcolor])

    if lowerstride:
        for n in range((nrentries-1)//lowerstride):
            x = n*lowerstride*(wd+dist)
            c.stroke(path.curve(x-dist/3, -0.5*dist,
                                x+0.5*wd, -5*dist,
                                x+(lowerstride-0.5)*wd+lowerstride*dist, -5*dist,
                                x+lowerstride*wd+(lowerstride-0.7)*dist, -0.5*dist),
                     [deco.earrow.large])
            c.text(x+0.5*lowerstride*wd+dist,-5.2*dist, r'\Large %i' % (lowerstride*8),
                   [text.halign.center, text.valign.top, textcolor])
    return c
Exemple #12
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
Exemple #13
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)
Exemple #14
0
def main():
    width = 16.8
    out_fname = sys.argv[1]
    basedir = "%s/Analysis/Timing" % '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    data_fnames = {
        "HiFive-Probability":{'0':"%s/hifive_data" % basedir, '1':"%s/hifive_project" % basedir,
                '3':'%s/hifive_prob' % basedir, '4':"%s/hifive_prob_heatmap" % basedir},
        "HiFive-Binning":{'0':"%s/hifive_data" % basedir, '1':"%s/hifive_project_nodist" % basedir,
               '3':'%s/hifive_bin' % basedir, '4':"%s/hifive_bin_heatmap" % basedir},
        "HiFive-Express":{'0':"%s/hifive_data" % basedir, '1':"%s/hifive_project" % basedir,
               '3':'%s/hifive_exp' % basedir, '4':"%s/hifive_exp_heatmap" % basedir},
        "HiFive-ExpressKR":{'0':"%s/hifive_data" % basedir, '1':"%s/hifive_project_nodist" % basedir,
                 '3':'%s/hifive_expKR' % basedir, '4':"%s/hifive_expKR_heatmap" % basedir},
        "HiFive-ExpressKR w/distance":{'0':"%s/hifive_data" % basedir, '1':"%s/hifive_project" % basedir,
                     '3':'%s/hifive_expKRdist' % basedir, '4':"%s/hifive_expKRdist_heatmap" % basedir},
        "HiCPipe":{'0':"%s/bam2raw" % basedir, '1':"%s/hicpipe_data" % basedir,
                   '2':'%s/hicpipe_binning' % basedir, '3':'%s/hicpipe_norm' % basedir,
                   '4':'%s/hicpipe_heatmap' % basedir},
        "HiCLib":{'0':"%s/hiclib_mapping" % basedir, '1':'%s/hiclib_data' % basedir,
                  '3':"%s/hiclib_norm" % basedir, '4':'%s/hiclib_heatmap' % basedir},
        "HiCNorm":{'0':"%s/bam2raw" % basedir, '1':"%s/hicpipe_data" % basedir,
                   "2":"%s/hicnorm_data" % basedir, '3':'%s/hicnorm_norm' % basedir},
    }
    data = load_data(data_fnames)
    c = canvas.canvas()
    c.insert(plot_bargraph(data, width, 4.0), [trafo.translate(4.0, 0)])
    c.insert(plot_key(width * 0.3, 1.5), [trafo.translate(width * 0.75 - 1.0, 0.2)])
    c.writePDFfile(out_fname)
Exemple #15
0
 def find(self, file=''):
     """
     This is the meat of the algorithm. It takes the frame and runs the steps outlined
     in the report. So if you've read the report this should be pretty self explanatory.
     """
     dimension = 0
     while True:
         print '--> generating linear system'
         linear_system = self.generate_linear_system()
         print '     size is %s, %s' % (len(linear_system), len(linear_system[0]))
         print '--> trying to find a solution'
         vector_solution = self.solve(linear_system)
         if vector_solution is None:
             print '--> solution not found'
             print '--> doubling along dimension %s' % dimension
             self.frame.double(dimension)
             dimension = (dimension + 1) % self.dimensions
         else:
             break
     solution = self.normalize_solution(vector_solution)
     self.set_edge_weights(solution)
     if file:
         c = canvas.canvas()
         self.draw_edges(c)
         c.writePDFfile(file)
Exemple #16
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)
def array34(arange, hlshape=None):
    c = canvas.canvas()
    if hlshape is None:
        c.text(2, 3.3, 'shape=(3, 4)', [text.halign.center])
    else:
        c.text(2, 3.3, 'shape=%s' % repr(hlshape), [text.halign.center])
    if hlshape is not None:
        if len(hlshape) == 1:
            hlshape = (1, hlshape[0])
    if arange:
        gridcolor = color.grey(0)
    else:
        gridcolor = color.grey(0.5)
    if hlshape is None:
        arange = True
    elif (hlshape[0] in (1, 3)) and (hlshape[1] in (1, 4)):
        arange = False
    else:
        arange = None
    drawgrid(c, 4, 3, 0, gridcolor, arange=arange)
    if hlshape is not None:
        c.stroke(path.rect(0, 3, hlshape[1], -hlshape[0]),
                 [deco.filled([color.rgb(1, 0.8, 0.4)])])
        drawgrid(c, hlshape[1], hlshape[0], 3-hlshape[0], arange=False)
    if arange is None:
        alertcolor = color.rgb(0.6, 0, 0)
        c.stroke(path.line(0, 0, 4, 3), [alertcolor, style.linewidth.Thick])
        c.stroke(path.line(0, 3, 4, 0), [alertcolor, style.linewidth.Thick])
    return c
Exemple #18
0
def guide_layer(holes):
    guide_size = 1.2

    # Get guide fiber information
    iguide = np.nonzero(np.array(holes['holetype']) == b'GUIDE')[0]
    guide_xfocal = np.array(holes['xfocal'])[iguide]
    guide_yfocal = np.array(holes['yfocal'])[iguide]
    guidenum = np.array(holes['iguide'])[iguide]

    # Set up object to print
    clippath = path.circle(0., 0., interior_radius)
    clipobject = canvas.clip(clippath)
    interior = canvas.canvas([clipobject])

    for indx in range(len(guide_xfocal)):
        interior.stroke(
            path.rect((guide_yfocal[indx] / 10.) - guide_size * 0.5,
                      (guide_xfocal[indx] / 10.) - guide_size * 0.5,
                      guide_size, guide_size),
            [style.linewidth.THick, color.cmyk.Black])
        interior.text(
            (guide_yfocal[indx] / 10.) + guide_size * 0.66,
            (guide_xfocal[indx] / 10.),
            r"\font\myfont=cmr10 at 35pt {\myfont " + str(guidenum[indx]) +
            "}", [text.halign.boxleft, text.valign.middle, text.size.Huge])

    return interior
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)
Exemple #20
0
def make_picture_for_two_vertices():
    c = canvas.canvas()
    c.stroke(path.rect(0, 0, 12, 1))
    c.stroke(path.rect(1, 0, 1, 1), [style.linewidth.THICK])
    c.stroke(path.rect(5, 0, 1, 1), [style.linewidth.THICK])
    c.stroke(path.rect(7, 0, 1, 1), [style.linewidth.THICK])
    c.stroke(path.rect(10, 0, 1, 1), [style.linewidth.THICK])
    c.stroke(path.line(-0.5, 0.5, -0.5, 6), [deco.earrow(size=0.2)])
    c.stroke(path.line(1.5, 0.5, 1.5, 5), [deco.earrow(size=0.2)])
    c.stroke(path.line(5.5, 0.5, 5.5, 4), [deco.earrow(size=0.2)])
    c.stroke(path.line(7.5, 0.5, 7.5, 3), [deco.earrow(size=0.2)])
    c.stroke(path.line(10.5, 0.5, 10.5, 2), [deco.earrow(size=0.2)])
    c.stroke(path.line(12.5, 0.5, 12.5, 1), [deco.earrow(size=0.2)])
    c.stroke(path.line(5.5, 4, 8, 4), [style.linewidth.THIN])
    c.stroke(path.line(7, 3, 8, 3), [style.linewidth.THIN])
    c.text(7.5, 3.5, r"$\delta_i = l_i - l_{i + 1}$", [text.halign.boxcenter, text.valign.middle])
    c.stroke(path.line(6, 0, 6, -1), [style.linewidth.THIN])
    c.stroke(path.line(7, 0, 7, -1), [style.linewidth.THIN])
    c.text(6.5, -0.4, r"$d_i$", [text.halign.boxcenter, text.valign.middle])
    c.text(-0.5, 3, r"$l_0 = 1.0$", [text.halign.boxleft])
    c.text(5.5, 2.5, r"$l_i$", [text.halign.boxright])
    c.text(7.5, 2, r"$l_{i+1}$", [text.halign.boxleft])
    c.text(12.5, 1.1, r"$l_{E+1} = 0.0$", [text.halign.boxcenter])

    c.writePDFfile("test_picture.pdf")
Exemple #21
0
    def processPS(self, file, writer, context, registry, bbox):
        if writer.mesh_as_bitmap:
            from pyx import bitmap, canvas
            from PIL import Image
            c = canvas.canvas()
            c.insert(self)
            i = Image.open(c.pipeGS("pngalpha", resolution=writer.mesh_as_bitmap_resolution))
            i.load()
            b = bitmap.bitmap_pt(self.bbox().llx_pt, self.bbox().lly_pt, i)
            # we slightly shift the bitmap to re-center it, as the bitmap might contain some additional border
            # unfortunately we need to construct another bitmap instance for that ...
            b = bitmap.bitmap_pt(self.bbox().llx_pt + 0.5*(self.bbox().width_pt()-b.bbox().width_pt()),
                                 self.bbox().lly_pt + 0.5*(self.bbox().height_pt()-b.bbox().height_pt()), i)
            b.processPS(file, writer, context, registry, bbox)
        else:
            thisbbox = self.bbox()
            bbox += thisbbox
            file.write("""<< /ShadingType 4
/ColorSpace %s
/BitsPerCoordinate 24
/BitsPerComponent 8
/BitsPerFlag 8
/Decode [%f %f %f %f %s]
/DataSource currentfile /ASCIIHexDecode filter /FlateDecode filter
>> shfill\n""" % (self.elements[0].nodes[0].value.colorspacestring(),
                  thisbbox.llx_pt, thisbbox.urx_pt, thisbbox.lly_pt, thisbbox.ury_pt,
                  " ".join(["0 1" for value in self.elements[0].nodes[0].value.to8bitbytes()])))
            file.write_bytes(binascii.b2a_hex(zlib.compress(self.data(thisbbox))))
            file.write(">\n")
Exemple #22
0
    def signature(self, deg_max=6, padded=False, has_border=False):
        """ For a visualization of glyphs, lay out in a 2D grid PNG file. """
        self.scale()
        sig = canvas.canvas([trafo.rotate(90), trafo.mirror(0)])
        scale = 1.5
        if padded or has_border:
            sig_margin = 0.2
            x = (deg_max + 1) * scale + (1.5 * sig_margin)
            border_path = path.path(path.moveto(0, 0), path.lineto(0, x),
                                    path.lineto(x, x), path.lineto(x, 0),
                                    path.closepath())
            if padded:
                border_color = color.cmyk.White
            if has_border:
                border_color = color.cmyk.Gray
            sig.stroke(border_path, [
                border_color,
                trafo.translate(-sig_margin * 2, -sig_margin * 2),
                style.linewidth(.025)
            ])

        for index in self.glist:
            if len(index) > 2:
                c = degree_glyph(index[0], index[1], index[2],
                                 (self.mincount, self.maxcount))
            else:
                c = degree_glyph(index[0], index[1], 1,
                                 (self.mincount, self.maxcount))
            sig.insert(c,
                       [trafo.translate(index[0] * scale, (index[1]) * scale)
                        ])  # text writing requires full latex
        return sig
Exemple #23
0
 def see_frame(self, file):
     for edge in self.frame.coordinate_vectors:
         edge.weight = edge.pin
     for edge in self.frame.cross_vectors:
         edge.weight = edge.pin
     c = canvas.canvas()
     self.draw_edges(c)
     c.writePDFfile(file)
 def __init__(self, nsquares):
     self.nsquares = nsquares
     self.corners = deque([np.array([0, 0]), np.array([1, 0]),
                           np.array([1, 1]), np.array([0, 1])])
     self.counter = 1
     self.initialize_pyx()
     self.c = canvas.canvas()
     self.draw()
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
Exemple #26
0
 def paint(self, plotitems):
     "creates the layout of the key"
     columndist_pt = unit.topt(self.columndist)
     c = canvas.canvas()
     itemspercolumn = (len(plotitems) + self.columns - 1) // self.columns
     x_pt = 0
     while plotitems:
         subc = self.paintcolumn(plotitems[:itemspercolumn])
         c.insert(subc, [trafo.translate_pt(x_pt, 0)])
         x_pt += unit.topt(subc.bbox().width()) + columndist_pt
         del plotitems[:itemspercolumn]
     if self.keyattrs is not None:
         newc = canvas.canvas()
         newc.draw(c.bbox().enlarged(self.border).path(), self.keyattrs)
         newc.insert(c)
         c = newc
     return c
Exemple #27
0
 def paint(self, plotitems):
     "creates the layout of the key"
     columndist_pt = unit.topt(self.columndist)
     c = canvas.canvas()
     itemspercolumn = (len(plotitems) + self.columns - 1) // self.columns
     x_pt = 0
     while plotitems:
         subc = self.paintcolumn(plotitems[:itemspercolumn])
         c.insert(subc, [trafo.translate_pt(x_pt, 0)])
         x_pt += unit.topt(subc.bbox().width()) + columndist_pt
         del plotitems[:itemspercolumn]
     if self.keyattrs is not None:
         newc = canvas.canvas()
         newc.draw(c.bbox().enlarged(self.border).path(), self.keyattrs)
         newc.insert(c)
         c = newc
     return c
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
Exemple #29
0
def backup():
    inFolder = Path(args.input)

    memTar = BytesIO()
    tar = tarfile.open(fileobj=memTar, mode="x")
    for itm in inFolder.iterdir():
        tar.add(itm.resolve(), arcname=itm.relative_to(inFolder))

    tar.close()

    content = memTar.getvalue()
    memTar.close()

    content = compress(content)
    b85Content = b85encode(content).decode("UTF-8")

    pdf = document()
    pdfPage = None

    counter = 0
    while b85Content:
        b85Content = str(counter) + ">" + b85Content
        chunk, b85Content = maxSplit(b85Content)
        if b85Content is None:
            chunk = chunk[:chunk.index(">")] + "<" + chunk[
                chunk.index(">") + 1:]  #Signal last chunk

        print("Generating QRCode for chunk " + str(counter) + ", " +
              (str(len(b85Content)) if b85Content else "0") +
              " bytes remaining")
        qrCode = QRencode(chunk)

        #Used for debugging
        if args.plainChunk:
            f = open("chunk" + str(counter) + ".chunk", "w")
            f.write(chunk)
            f.close

        if counter % 6 == 0:
            pdfPage = page(canvas(), paperformat=paperformat.A4, centered=0)
            pdf.append(pdfPage)

        pdfPage.canvas.insert(
            bitmap(**pdfImagePlacement(counter), image=qrCode.convert("LA")))

        if args.makeBmp:
            qrCode.save("chunk" + str(counter) + ".bmp")

        counter += 1

    print("Writing to pdf...")
    outFile = Path(args.output)
    if (outFile.suffix == ".pdf"):
        pdf.writePDFfile(args.output)
    else:
        pdf.writePDFfile(args.output + ".pdf")

    print("Done")
Exemple #30
0
def make_dirs_plot(filename, dirs_dict, other=None):
    plot_canvas = canvas.canvas()
    plot_canvas.stroke(path.circle(0, 0, 10))
    for sample_name in dirs_dict.keys():
        if other is None:
            dirs_dict[sample_name].plot(plot_canvas)
        else:
            dirs_dict[sample_name].plot(plot_canvas, other=other[sample_name])
    plot_canvas.writePDFfile(filename)
def client(clientcolor=color.rgb(0.8, 0.5, 0.5)):
    c = canvas.canvas()
    r = 0.3
    c.fill(path.circle(0, 0, r), [clientcolor])
    r = 0.5
    p = path.path(path.moveto(-r, 0), path.curveto(-r, r, r, r, r, 0),
                  path.closepath())
    c.fill(p, [clientcolor, trafo.translate(0, -1.3 * r)])
    return c
Exemple #32
0
def server(r, servercolor=color.rgb(0.5, 0.5, 0.8)):
    c = canvas.canvas()
    c.fill(path.circle(0, 0, r), [servercolor, trafo.scale(1, 0.5)])
    h = 2 * r
    p = path.path(path.moveto(-r, 0), path.lineto(-r, -h),
                  path.arc(0, -h, r, 180, 0), path.lineto(r, 0),
                  path.arcn(0, 0, r, 0, 180), path.closepath())
    c.fill(p, [servercolor, trafo.scale(1, 0.5).translated(0, -0.08 * r)])
    return c
Exemple #33
0
def repo(label, colorfg, colorbg):
    crepo = canvas.canvas()
    labeltext = text.text(0, 0, r'\textsf{{{}}}'.format(label),
                          [colorfg])
    extrawd = 0.15
    labelbox = labeltext.bbox().enlarged(extrawd)
    crepo.fill(labelbox.path(), [colorbg, deformer.smoothed(0.05),
                                  deco.stroked([colorfg])])
    crepo.insert(labeltext)
    return crepo
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
def read(size, color):
    size = size * 0.25
    cread = canvas.canvas()
    cread.fill(path.circle(0, 0, 0.35), [color, trafo.scale(size)])
    p = path.path(path.moveto(0.8, 0),
                  path.curveto(0.2, 0.5, -0.2, 0.5, -0.8, 0),
                  path.curveto(-0.2, -0.5, 0.2, -0.5, 0.8, 0),
                  path.closepath())
    cread.stroke(p, [color, style.linewidth.thick, trafo.scale(size)])
    return cread
Exemple #36
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
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)
Exemple #38
0
    def processPDF(self, file, writer, context, registry, bbox):
        if writer.mesh_as_bitmap:
            from pyx import bitmap, canvas
            import Image
            c = canvas.canvas()
            c.insert(self)
            fd, fname = tempfile.mkstemp()
            f = os.fdopen(fd, "wb")
            f.close()
            c.pipeGS(fname,
                     device="pngalpha",
                     resolution=writer.mesh_as_bitmap_resolution)
            i = Image.open(fname)
            os.unlink(fname)
            b = bitmap.bitmap_pt(self.bbox().llx_pt, self.bbox().lly_pt, i)
            # we slightly shift the bitmap to re-center it, as the bitmap might contain some additional border
            # unfortunately we need to construct another bitmap instance for that ...
            b = bitmap.bitmap_pt(
                self.bbox().llx_pt + 0.5 *
                (self.bbox().width_pt() - b.bbox().width_pt()),
                self.bbox().lly_pt + 0.5 *
                (self.bbox().height_pt() - b.bbox().height_pt()), i)
            b.processPDF(file, writer, context, registry, bbox)
        else:
            thisbbox = self.bbox()
            bbox += thisbbox
            d = self.data(thisbbox)
            if writer.compress:
                filter = "/Filter /FlateDecode\n"
                d = zlib.compress(d)
            else:
                filter = ""
            name = "shading-%s" % id(self)
            shading = PDFGenericResource(
                "shading", name, """<<
/ShadingType 4
/ColorSpace %s
/BitsPerCoordinate 24
/BitsPerComponent 8
/BitsPerFlag 8
/Decode [%f %f %f %f %s]
/Length %i
%s>>
stream
%s
endstream\n""" % (self.elements[0].nodes[0].value.colorspacestring(),
                  thisbbox.llx_pt, thisbbox.urx_pt, thisbbox.lly_pt,
                  thisbbox.ury_pt, " ".join([
                      "0 1" for value in
                      self.elements[0].nodes[0].value.to8bitstring()
                  ]), len(d), filter, d))
            registry.add(shading)
            registry.addresource("Shading", name, shading)
            file.write("/%s sh\n" % name)
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
Exemple #40
0
def main():
    # set up the line tracing function
    tracer = sunburst.Trace(
        os.path.dirname(os.path.abspath(sunburst.__file__)),
        sunburst.generate_diagrams, sunburst.stop_trace)
    sys.settrace(tracer.trace)
    # where is the sunburst directory?
    path = os.path.dirname(os.path.abspath(sunburst.__file__))
    # instantiate canvases
    shape_canvas = canvas.canvas()
    text_canvas = canvas.canvas()
    # read in settings
    settings = yaml.load(open('config.yaml', 'r'))
    # list of diagrams to create
    data = [('test', (0, 0), ('raw', )),
            ('test2', (settings['output']['xdelta'], 0), ('trace',
                                                          tracer.lines))]
    sunburst.generate_diagrams(data, shape_canvas, text_canvas, settings, path)
    sunburst.output(settings['output']['name'], shape_canvas, text_canvas)
    print(tracer.traced)
Exemple #41
0
def build_canvas():
    cnv = canvas.canvas()
    cnv.stroke(make_line(w), [deco.earrow()])
    text_at(cnv, w / 2. - (.5, 0), r'$\vec{w}$')
    cnv.stroke(make_line(v), [deco.earrow()])
    text_at(cnv, v / 2. - (0, .5), r'$\vec{v}$')
    cnv.stroke(make_line(w, c * v), [deco.earrow(), rgb.red])
    text_at(cnv, w - (w - c * v) / 2 + (.1, .1), r'$\vec{w} - c \vec{v}$')
    cnv.stroke(make_line(c * v), [deco.earrow(), ls.dashed, rgb.blue])
    text_at(cnv, c * v / 1.5 - (0, .5), r'$c \vec{v}$')
    cnv.stroke(make_line(v * -1.5, v * 3), [ls.dotted])
    return cnv
def draw_points(points: torch.Tensor, filename, size=1, svg=False):
    c = canvas.canvas()

    points = points.detach().cpu()

    for i in range(points.shape[0]):
        c.fill(path.circle(points[i, 1], -points[i, 0], size))

    if svg:
        c.writeSVGfile(file=filename)
    else:
        c.writePDFfile(file=filename)
Exemple #43
0
 def axisatv(self, axis, v):
     if axis.positioner.fixtickdirection[0]:
         # it is a y-axis
         t = trafo.translate_pt(self.xpos_pt + v*self.width_pt - axis.positioner.x1_pt, 0)
     else:
         # it is an x-axis
         t = trafo.translate_pt(0, self.ypos_pt + v*self.height_pt - axis.positioner.y1_pt)
     c = canvas.canvas()
     for layer, subcanvas in axis.canvas.layers.items():
         c.layer(layer).insert(subcanvas, [t])
     assert len(axis.canvas.layers) == len(axis.canvas.items), str(axis.canvas.items)
     axis.canvas = c
Exemple #44
0
def checkone(knots, refpoints):  # <<<
    print(myprint(knots))
    mp_make_choices(knots, epsilon)
    print(myprint(knots))

    c = canvas.canvas()
    c.stroke(mypath(knots), [deco.shownormpath(), deco.earrow.normal])
    c.writePDFfile(bboxenlarge=unit.t_cm)
    c.writeEPSfile(bboxenlarge=unit.t_cm)
    c.writeSVGfile(bboxenlarge=unit.t_cm)

    check(knots, refpoints)
Exemple #45
0
def checkone(knots, refpoints): # <<<
    print(myprint(knots))
    mp_make_choices(knots, epsilon)
    print(myprint(knots))

    c = canvas.canvas()
    c.stroke(mypath(knots), [deco.shownormpath(), deco.earrow.normal])
    c.writePDFfile(bboxenlarge=unit.t_cm)
    c.writeEPSfile(bboxenlarge=unit.t_cm)
    c.writeSVGfile(bboxenlarge=unit.t_cm)

    check(knots, refpoints)
 def __init__(self, nsquares):
     self.nsquares = nsquares
     self.corners = deque([
         np.array([0, 0]),
         np.array([1, 0]),
         np.array([1, 1]),
         np.array([0, 1])
     ])
     self.counter = 1
     self.initialize_pyx()
     self.c = canvas.canvas()
     self.draw()
Exemple #47
0
def checkall(): # <<<
    c = None
    for knots, refpoints in [curve1(), curve2(), curve3(),
                             curve4(-90), curve4(0), curve4(70), curve5(),
                             curve6a(), curve6b(), curve6c(), curve7(),
                             curve8a(), curve8b(), curve9(), curve10()]:
        #print myprint(knots)
        mp_make_choices(knots, epsilon)
        #print myprint(knots)

        cc = canvas.canvas()
        cc.stroke(mypath(knots), [deco.shownormpath(), deco.earrow.normal])
        if c is None:
            c = canvas.canvas()
            c.insert(cc)
        else:
            c.insert(cc, [trafo.translate(0, c.bbox().bottom() - cc.bbox().top()-0.5)])

        check(knots, refpoints)
    c.writePDFfile()
    c.writeEPSfile()
    c.writeSVGfile()
def write(size, color):
    size = size * 0.3
    cwrite = canvas.canvas()
    p = path.path(path.moveto(-0.2, 0.8), path.lineto(0.2, 0.8),
                  path.lineto(0.2, 0), path.lineto(0, -0.2),
                  path.lineto(-0.2, 0), path.lineto(-0.2, 0.8),
                  path.closepath(), path.moveto(0, 0.8), path.lineto(0, 0.05),
                  path.moveto(-0.2, 0), path.arcn(-0.1, 0, 0.1, 180, 20),
                  path.arcn(0.1, 0, 0.1, 160, 0))
    cwrite.stroke(
        p, [color,
            trafo.scale(size).rotated(-30).translated(0, -0.4 * size)])
    return cwrite
Exemple #49
0
 def processSVG(self, xml, writer, context, registry, bbox):
     from pyx import bitmap, canvas
     from PIL import Image
     c = canvas.canvas()
     c.insert(self)
     i = Image.open(c.pipeGS("pngalpha", resolution=writer.mesh_as_bitmap_resolution))
     i.load()
     b = bitmap.bitmap_pt(self.bbox().llx_pt, self.bbox().lly_pt, i)
     # we slightly shift the bitmap to re-center it, as the bitmap might contain some additional border
     # unfortunately we need to construct another bitmap instance for that ...
     b = bitmap.bitmap_pt(self.bbox().llx_pt + 0.5*(self.bbox().width_pt()-b.bbox().width_pt()),
                          self.bbox().lly_pt + 0.5*(self.bbox().height_pt()-b.bbox().height_pt()), i)
     b.processSVG(xml, writer, context, registry, bbox)
Exemple #50
0
 def processPDF(self, file, writer, context, registry, bbox):
     warnings.warn("EPS file is included as a bitmap created using pipeGS")
     from pyx import bitmap, canvas
     import Image
     c = canvas.canvas()
     c.insert(self)
     i = Image.open(c.pipeGS(device="pngalpha", resolution=600, seekable=True))
     i.load()
     b = bitmap.bitmap_pt(self.bbox().llx_pt, self.bbox().lly_pt, i)
     # we slightly shift the bitmap to re-center it, as the bitmap might contain some additional border
     # unfortunately we need to construct another bitmap instance for that ...
     b = bitmap.bitmap_pt(self.bbox().llx_pt + 0.5*(self.bbox().width_pt()-b.bbox().width_pt()),
                          self.bbox().lly_pt + 0.5*(self.bbox().height_pt()-b.bbox().height_pt()), i)
     b.processPDF(file, writer, context, registry, bbox)
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
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
Exemple #53
0
    def processPDF(self, file, writer, context, registry, bbox):
        if writer.mesh_as_bitmap:
            from pyx import bitmap, canvas
            import Image
            c = canvas.canvas()
            c.insert(self)
            fd, fname = tempfile.mkstemp()
            f = os.fdopen(fd, "wb")
            f.close()
            c.pipeGS(fname, device="pngalpha", resolution=writer.mesh_as_bitmap_resolution)
            i = Image.open(fname)
            os.unlink(fname)
            b = bitmap.bitmap_pt(self.bbox().llx_pt, self.bbox().lly_pt, i)
            # we slightly shift the bitmap to re-center it, as the bitmap might contain some additional border
            # unfortunately we need to construct another bitmap instance for that ...
            b = bitmap.bitmap_pt(self.bbox().llx_pt + 0.5*(self.bbox().width_pt()-b.bbox().width_pt()),
                                 self.bbox().lly_pt + 0.5*(self.bbox().height_pt()-b.bbox().height_pt()), i)
            b.processPDF(file, writer, context, registry, bbox)
        else:
            thisbbox = self.bbox()
            bbox += thisbbox
            d = self.data(thisbbox)
            if writer.compress:
                filter = "/Filter /FlateDecode\n"
                d = zlib.compress(d)
            else:
                filter = ""
            name = "shading-%s" % id(self)
            shading = PDFGenericResource("shading", name, """<<
/ShadingType 4
/ColorSpace %s
/BitsPerCoordinate 24
/BitsPerComponent 8
/BitsPerFlag 8
/Decode [%f %f %f %f %s]
/Length %i
%s>>
stream
%s
endstream\n""" % (self.elements[0].nodes[0].value.colorspacestring(),
                  thisbbox.llx_pt, thisbbox.urx_pt, thisbbox.lly_pt, thisbbox.ury_pt,
                  " ".join(["0 1" for value in self.elements[0].nodes[0].value.to8bitstring()]),
                  len(d), filter, d))
            registry.add(shading)
            registry.addresource("Shading", name, shading)
            file.write("/%s sh\n" % name)
def main():
    out_fname = sys.argv[1]
    basedir = '/'.join(os.path.dirname(os.path.realpath(__file__)).split('/')[:-2])
    bin_file = '%s/Analysis/hifive_mm9_ESC_prob_correlations.txt' % basedir
    pois_file = '%s/Analysis/hifive_mm9_ESC_probpois_correlations.txt' % basedir
    bin_data = load_data(bin_file)
    pois_data = load_data(pois_file)
    width = 16.8
    spacer = 0.4
    range_width = (width - spacer) / 5.0
    range_height = range_width * 1.4
    c = canvas.canvas()
    ranges_img = plot_dataset_ranges(bin_data, pois_data, range_width * 4, range_height)
    c.insert(ranges_img)
    overall_img = plot_overall(bin_data, pois_data, range_width, range_height)
    c.insert(overall_img, [trafo.translate(range_width * 4 + spacer, 0)])
    c.writePDFfile(out_fname)
def matrix_22(m, dx=0.5, dy=0.5, pd=0.1, pdx=0.1, pdy=0.3):
    c = canvas.canvas()
    for nx in range(2):
        for ny in range(2):
            c.text(nx*dx, -ny*dy, str(m[ny, nx]), [text.halign.center])
    box = c.bbox()
    xoff = box.left()-pd
    c.stroke(path.curve(xoff, box.top()+pd,
                        xoff-pdx, box.top()-pdy,
                        xoff-pdx, box.bottom()+pdy,
                        xoff, box.bottom()-pd))
    xoff = box.right()+pd
    c.stroke(path.curve(xoff, box.top()+pd,
                        xoff+pdx, box.top()-pdy,
                        xoff+pdx, box.bottom()+pdy,
                        xoff, box.bottom()-pd))
    return c
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)
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