Ejemplo n.º 1
0
    def _penta_dots(self, c, intervals=False):
        penta_notes = tuple([i['note'] for i in self.penta])

        def ival_by_idx(idx, minor):
            return ('1', 'b3', '4', '5', 'b7')[idx] if minor else ('1', '2', '3', '5', '6')[idx]

        for fret in range(0, self.frets + 1):
            for string in range(0, 6):
                note = self._interval(
                    self.tones.index(self.tuning[string]), fret)
                if note['note'] in penta_notes:
                    idx = penta_notes.index(note['note'])
                    fret_x = self.x if fret == 0 else (
                        fret - 1) * self.fret_width + float(self.fret_width/2)
                    if idx != 0:
                        styles = [style.linewidth.Thick, deco.filled(
                            [color.rgb.black])] if not intervals else [style.linewidth.Thick, deco.filled([color.rgb.white])]
                        c.stroke(path.circle(fret_x, self.y + string *
                                             self.fret_height, self.note_rad), styles)
                        if intervals:
                            tx = ival_by_idx(idx, self.ptype['minor'])
                            c.text(fret_x - self.dot_rad * (1.2 * len(tx)), self.y + string *
                                   self.fret_height - self.dot_rad, tx)

                    else:
                        # root note
                        styles = [style.linewidth.Thick, deco.filled(
                            [color.rgb.black])] if not intervals else [style.linewidth.Thick, deco.filled([color.rgb.white])]

                        c.stroke(path.circle(fret_x, self.y + string * self.fret_height,
                                             self.note_rad), [style.linewidth.Thick, deco.filled([color.rgb.red])])
                        if intervals:
                            tx = ival_by_idx(idx, self.ptype['minor'])
                            c.text(fret_x - self.dot_rad * (1.2 * len(tx)), self.y + string *
                                   self.fret_height - self.dot_rad, tx, [color.rgb.white])
Ejemplo n.º 2
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
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
Ejemplo n.º 4
0
def put_label(x, y, nr):
    r = 0.3
    label = r'\textsf{{\bfseries {}}}'.format(nr)
    if abs(x) == abs(y):
        c.fill(path.circle(x, y, r), [color.rgb.black])
        c.text(x, y, label,
               [text.halign.center, text.valign.middle, color.rgb.white])
    else:
        c.stroke(path.circle(x, y, r), [deco.filled([color.rgb.white])])
        c.text(x, y, label, [text.halign.center, text.valign.middle])
Ejemplo n.º 5
0
def draw_pie(c, radius, start, end):
    pie = path.path(path.moveto(0, 0), path.arc(0, 0, radius, start, end),
                    path.closepath())

    hue = (start + end) / (360 * 2)
    color = pyx.color.hsb(hue, 0.8, 0.8)

    c.stroke(
        pie,
        [style.linewidth(0.01),
         pyx.color.rgb(1, 1, 1),
         deco.filled([color])])
 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
Ejemplo n.º 7
0
def arrow(g,
          x_coord_init,
          y_coord_init,
          x_coord_final,
          y_coord_final,
          size,
          line_color,
          stroke_color=None,
          fill_color=None):
    """
        Function that draws an arrow in a given plot

        INPUTS:

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

                x_coord_init    (Double) x-coordinate (in plot units) at which you want the arrow
                                to start.

                y_coord_init    (Double) y-coordinate (in plot units) at which you want the arrow
                                to start.

                x_coord_final   (Double) x-coordinate (in plot units) at which you want the arrow
                                to end.

                y_coord_final   (Double) y-coordinate (in plot units) at which you want the arrow
                                to end.

		size		(int) Size of the arrow.

		line_color	(instance) Instance color that defines the color of the line of the arrow.

		stroke_color	(instance, optional) Defines the stroke color (default is same as line_color).

		fill_color	(instance, optional) Defines the color fill of the arrow (default is same as 
				line_color).

        """

    if stroke_color is None:
        stroke_color = line_color
    if fill_color is None:
        fill_color = line_color

    x0, y0 = g.pos(x_coord_init, y_coord_init)
    xf, yf = g.pos(x_coord_final, y_coord_final)
    g.stroke(pyx_path.line(x0,y0,xf,yf),\
     [pyx_style.linewidth.normal, pyx_style.linestyle.solid, line_color,\
      pyx_deco.earrow([pyx_deco.stroked([stroke_color]),\
      pyx_deco.filled([fill_color])], size=0.1)])
 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
Ejemplo n.º 9
0
def cluster_sunburst(organism, graph, method):
    c = canvas.canvas()

    core_length = 5
    recurse_sunburst(c, graph, core_length, 0, 360)
    core = path.circle(0, 0, core_length)
    c.stroke(core, [
        style.linewidth(0.1),
        pyx.color.rgb(1, 1, 1),
        deco.filled([pyx.color.rgb(1, 1, 1)])
    ])

    file_name = '{}-{}-clusters_sunburst.svg'.format(organism.org_id, method)
    with open(utils.join_path(cs.SVG_PATH, file_name), 'wb') as svg:
        c.writeSVGfile(svg)
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
Ejemplo n.º 11
0
def test_pie(radius, start, end):
    c = canvas.canvas()
    container = path.rect(-(radius + 1), -(radius + 1), 2 * (radius + 1),
                          2 * (radius + 1))

    c.stroke(container, [style.linewidth(0.001), color.rgb.red])

    pie = path.path(path.moveto(0, 0), path.arc(0, 0, radius, start, end),
                    path.closepath())

    c.stroke(pie, [
        style.linewidth(0.1),
        pyx.color.rgb(1, 1, 1),
        deco.filled([color.rgb.red])
    ])
    c.writeSVGfile("figure")
Ejemplo n.º 12
0
unit.set(xscale=1.2, wscale=1.5)

frontplane = canvas.canvas()
backplane = canvas.canvas()
xcells = 4
ycells = 3
xshift = 0.8
yshift = 1.2
dist = 0.2
myred = color.rgb(0.8, 0, 0)
mygreen = color.rgb(0, 0.6, 0)
myblue = color.rgb(0, 0, 0.8)
for c, start in ((frontplane, 0), (backplane, xcells * ycells)):
    c.stroke(
        path.rect(0, 0, 4, 3),
        [deco.filled([color.grey(1), color.transparency(0.2)])])
    for x in range(1, xcells):
        c.stroke(path.line(x, 0, x, ycells))
    for y in range(1, ycells):
        c.stroke(path.line(0, y, xcells, y))
    for entry in range(xcells * ycells):
        x = entry % 4
        y = ycells - entry // 4
        c.text(x + 0.5, y - 0.5, str(start + entry),
               [text.halign.center, text.valign.middle])
c = canvas.canvas()
c.insert(backplane, [trafo.translate(xshift, yshift)])
for x, y in product((0, xcells), (0, ycells)):
    c.stroke(path.line(x, y, x + xshift, y + yshift))
c.insert(frontplane)
dx = -dist * yshift / sqrt(xshift**2 + yshift**2)
Ejemplo n.º 13
0
from math import exp, expm1
from pyx import color, deco, graph, style, text, unit

text.set(text.LatexEngine)
mypainter = graph.axis.painter.regular(innerticklength=None,
                                       outerticklength=graph.axis.painter.ticklength.normal)
g = graph.graphxy(width=8,
                  x=graph.axis.log(title="$x$",
                                   painter=mypainter),
                  y=graph.axis.lin(title=r"$f(x)-1$",
                                   min=-1.1e-6,
                                   max=1.1e-6,
                                   painter=mypainter,
                                   parter=graph.axis.parter.lin(tickdists=[1e-6])),
                  key=graph.key.key(pos="tr")
                 )
g.plot(graph.data.function("y(x)=(exp(x)-1)/x-1", min=1e-10, max=1e-6,
                           title=r"\textsf{\big(exp(x)-1\big)/x}"),
       [graph.style.symbol(symbol=graph.style.symbol.circle,
                           size=0.15*unit.v_cm,
                           symbolattrs=[deco.filled([color.rgb(0.2, 0.2, 1)]),
                                        deco.stroked([color.grey(1)])])])
g.plot(graph.data.function("y(x)=expm1(x)/x-1", min=1e-10, max=1e-6,
                           title=r"\textsf{expm1(x)/x}",
                           context={"expm1": expm1}),
       [graph.style.line([color.rgb(1, 0.5, 0), style.linewidth.Thick])])
g.writeGSfile("expm1.png", resolution=300)
Ejemplo n.º 14
0
utf8markercolor = color.rgb(1.0, 0.7, 0)
codecolor = color.rgb(0.7, 1, 0)

codepoint = 0x00E9
bits = 16

codepointbinary = [(codepoint & 2**n)/2**n for n in range(bits)]
codepointbinary.reverse()

size = 0.4
x0 = 0
y0 = 3
dy = 0.07
c.fill(path.rect(x0, y0, 5*size, size),
       [markercolor, deco.stroked([markercolor])])
c.stroke(path.rect(x0+5*size, y0, 5*size, size), [deco.filled([codecolor])])
c.stroke(path.rect(x0+10*size, y0, 6*size, size), [deco.filled([codecolor])])
for n in range(len(codepointbinary)):
    c.text(x0+(n+0.5)*size, y0+dy, r"\sffamily %i" % codepointbinary[n],
           [text.halign.center])

p = path.path(path.moveto(0.2*size, size+0.03),
              path.lineto(0.2*size, size+0.07),
              path.lineto(3.8*size, size+0.07),
              path.lineto(3.8*size, size+0.03))
for n in range(bits//4):
    c.stroke(p, [trafo.translate(4*n*size, y0)])
    c.text((4*n+2)*size, size+0.14+y0, r"\sffamily %X" %
           (codepoint >> (bits//4-n-1)*4 & 0x0f),
           [text.halign.center])
Ejemplo n.º 15
0
def draw_square(x, y, kante):
    c.stroke(path.rect(x, y, kante, kante),
             [style.linewidth.thick, deco.filled([color.grey(1)])])
Ejemplo n.º 16
0
def pyxColor(string):
    """
    :param string: RGB color name like 'ffffff'
    :return: pyx color.

    >>> assert pyxColor('ffffff')
    """
    assert len(string) == 6
    colorTuple = tuple(
        int('0x' + c, 16) for c in [string[i:i + 2] for i in range(0, 6, 2)])
    return color.rgb(*[i / 255.0 for i in colorTuple])


if __name__ == '__main__':  # pragma: no cover
    if not pyx:
        sys.exit(1)
    asset_resolver = AssetResolver()
    for icon in ICONS:
        c = canvas.canvas()
        c.draw(shapes[icon.name[0]], [
            deco.stroked([linewidth]),
            deco.filled([pyxColor(icon.name[1:])])
        ])
        stream = c.pipeGS("pngalpha",
                          resolution=20,
                          bbox=bbox.bbox(0, 0, 40, 40))
        with open(asset_resolver.resolve(icon.asset_spec).abspath(),
                  'wb') as fp:
            fp.write(stream.read())
    sys.exit(0)
Ejemplo n.º 17
0
    def doplot(self,
               d,
               xlabel=None,
               xlog=False,
               ymin=-0.0029,
               ymax=0.0029,
               xmin=None,
               xmax=None,
               nocorr=False,
               fitlines=False,
               **kw):
        """
        plot the results

        parameters
        ----------
        d: dict
            result of running something like process_run or process_flist
        **kw:
            extra plotting keywords
        """
        import pyxtools
        from pyx import graph, deco, style
        from pyx.graph import axis

        if xlabel is None:
            xlabel = 'x'

        xdensity = kw.get('xdensity', 1.5)
        ydensity = kw.get('ydensity', 1.5)

        red = pyxtools.colors('red')
        blue = pyxtools.colors('blue')

        xvals = self._extract_xvals(d)

        if nocorr:
            sh = d['shear_nocorr']['shear']
            sherr = d['shear_nocorr']['shear_err']
        else:
            sh = d['shear']['shear']
            sherr = d['shear']['shear_err']

        if xlog:
            xcls = axis.log
        else:
            xcls = axis.lin

        xaxis = xcls(
            title=xlabel,
            density=xdensity,
            min=xmin,
            max=xmax,
        )
        yaxis = axis.lin(
            title=r"$\langle g \rangle$",
            density=ydensity,
            min=ymin,
            max=ymax,
        )

        key = graph.key.key(pos='bl')
        g = graph.graphxy(
            width=8,
            ratio=1.2,
            key=key,
            x=xaxis,
            y=yaxis,
        )

        c = graph.data.function(
            "y(x)=0",
            title=None,
            min=xvals[0],
            max=xvals[-1],
        )

        g.plot(c)

        g1values = graph.data.values(
            x=list(xvals),
            y=list(sh[:, 0]),
            dy=list(sherr[:, 0]),
            title=r'$g_1$',
        )
        g2values = graph.data.values(
            x=list(xvals),
            y=list(sh[:, 1]),
            dy=list(sherr[:, 1]),
            title=r'$g_2$',
        )

        symbol1 = graph.style.symbol(
            symbol=graph.style.symbol.circle,
            symbolattrs=[red, deco.filled([red])],
            size=0.1,
        )
        symbol2 = graph.style.symbol(
            symbol=graph.style.symbol.triangle,
            symbolattrs=[blue, deco.filled([blue])],
            size=0.1,
        )

        g.plot(g1values, [symbol1, graph.style.errorbar(errorbarattrs=[red])])
        g.plot(g2values, [symbol2, graph.style.errorbar(errorbarattrs=[blue])])

        use_errors = True
        if fitlines and not use_errors:
            res1 = fitline(xvals, sh[:, 0])
            res2 = fitline(xvals, sh[:, 1])

            fmt = '(%(slope).3g +/- %(slope_err).3g) x + (%(offset).3g +/- %(offset_err).3g)'
            print("line1: " + fmt % res1)
            print("line2: " + fmt % res2)

            if self.element is not None:
                tit1 = r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % (
                    res1['slope'], self.element + 1, res1['offset'])
                tit2 = r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % (
                    res2['slope'], self.element + 1, res2['offset'])
            else:
                tit1 = r'$g_1=%.2g ~x + %.2g$' % (res1['slope'],
                                                  res1['offset'])
                tit2 = r'$g_2=%.2g ~x + %.2g$' % (res1['slope'],
                                                  res1['offset'])

            c1 = graph.data.function(
                "y(x)=%g*x + %g" % tuple((res1['slope'], res1['offset'])),
                title=tit1,
                min=xvals[0],
                max=xvals[-1],
            )
            c2 = graph.data.function(
                "y(x)=%g*x + %g" % tuple((res2['slope'], res2['offset'])),
                title=tit2,
                min=xvals[0],
                max=xvals[-1],
            )

            styles1 = [
                graph.style.line([red, style.linestyle.solid]),
            ]
            styles2 = [
                graph.style.line([blue, style.linestyle.dashed]),
            ]

            g.plot(c1, styles1)
            g.plot(c2, styles2)

        if fitlines and use_errors:
            # old code
            import fitting
            l1 = fitting.fit_line(xvals, sh[:, 0], yerr=sherr[:, 0])
            l2 = fitting.fit_line(xvals, sh[:, 1], yerr=sherr[:, 1])
            res1 = l1.get_result()
            res2 = l2.get_result()

            pars1, err1 = res1['pars'], res1['perr']
            pars2, err2 = res2['pars'], res2['perr']

            fmt = '(%.3g +/- %.3g) x + (%.3g +/- %.3g)'
            print("line1: " + fmt % (pars1[0], err1[0], pars1[1], err1[1]))
            print("line2: " + fmt % (pars2[0], err2[0], pars2[1], err2[1]))

            if self.element is not None:
                tit1 = r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % (
                    pars1[0], self.element + 1, pars1[1])
                tit2 = r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % (
                    pars2[0], self.element + 1, pars2[1])
            else:
                tit1 = r'$g_1=%.2g ~x + %.2g$' % (pars1[0], pars1[1])
                tit2 = r'$g_2=%.2g ~x + %.2g$' % (pars2[0], pars2[1])
            c1 = graph.data.function(
                "y(x)=%g*x + %g" % tuple(pars1),
                title=tit1,
                min=xvals[0],
                max=xvals[-1],
            )
            c2 = graph.data.function(
                "y(x)=%g*x + %g" % tuple(pars2),
                title=tit2,
                min=xvals[0],
                max=xvals[-1],
            )

            styles1 = [
                graph.style.line([red, style.linestyle.solid]),
            ]
            styles2 = [
                graph.style.line([blue, style.linestyle.dashed]),
            ]

            g.plot(c1, styles1)
            g.plot(c2, styles2)

        if 'file' in kw:
            print("writing:", kw['file'])
            pyxtools.write(g, kw['file'], dpi=200)

        if fitlines and 'fitfile' in kw:
            print("writing:", kw['fitfile'])
            with open(kw['fitfile'], 'w') as fobj:
                fobj.write(repr(l1))
                fobj.write('\n')
                fobj.write(repr(l2))
                fobj.write('\n')

        return g
Ejemplo n.º 18
0
    return cwrite


text.set(text.LatexRunner)
text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}')
c = canvas.canvas()

wd = 6.9
ht = 3.5
gitlabfgcolor = color.grey(0.4)
gitlabbgcolor = color.grey(0.97)
maintainercolor = color.hsb(0.7, 1, 0.5)
usercolor = color.hsb(0.05, 1, 0.5)
c.stroke(path.rect(0, 0, wd, ht), [
    deformer.smoothed(0.1), gitlabfgcolor, style.linewidth.Thick,
    deco.filled([gitlabbgcolor])
])

clabel = canvas.canvas()
labeltext = text.text(0, 0, r'\textsf{\bfseries Gitlab}', [color.grey(1)])
extrawd = 0.15
labelbox = labeltext.bbox().enlarged(extrawd)
clabel.fill(labelbox.path(), [gitlabfgcolor, deformer.smoothed(0.1)])
clabel.insert(labeltext)
c.insert(clabel, [trafo.translate(extrawd, ht + extrawd)])

c.text(wd + 0.4, ht - 0.5, r'\footnotesize\textsf{read/write permissions}')
c.insert(read(1, usercolor), [trafo.translate(wd + 0.7, ht - 0.9)])
c.insert(write(1, usercolor), [trafo.translate(wd + 1.05, ht - 0.9)])
c.text(wd + 1.5, ht - 1.0, r'\footnotesize\textsf{user}', [usercolor])
c.insert(write(1, maintainercolor), [trafo.translate(wd + 1.05, ht - 1.3)])
from pyx import canvas, color, deco, path, text, unit

text.set(text.LatexRunner)
text.preamble(
    r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{nicefrac}')
unit.set(xscale=1.4, wscale=1.2)

c = canvas.canvas()
r = 0.05
for n in range(1, 5):
    c.stroke(path.circle(n, 0, r))
    c.stroke(path.circle(-n, 0, r))
c.stroke(path.circle(0, 0, r), [deco.filled([color.grey(0)])])
dx = 0.1
dy = 0.3
c.stroke(path.curve(dx, dx, dy, dy, 1 - dy, dy, 1 - dx, dx), [deco.earrow])
c.text(0.5, dy + 0.1, '+1', [text.halign.center])
c.stroke(path.curve(-dx, dx, -dy, dy, -1 + dy, dy, -1 + dx, dx), [deco.earrow])
c.text(-0.5, dy + 0.1, '-1', [text.halign.center])
c.writePDFfile()
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
Ejemplo n.º 21
0
pathsegments = [path.path(path.moveto(qi, 0),
                          path.lineto(qf, 0)),
                path.path(path.moveto(qf, 0),
                          path.lineto(width-radius, 0),
                          path.arc(width-radius, radius, radius, -90, 90),
                          path.lineto(qf, 2*radius)),
                path.path(path.moveto(qf, 0),
                          path.lineto(qi, 0)),
                path.path(path.moveto(qi, 0),
                          path.lineto(radius, 0),
                          path.arcn(radius, radius, radius, 270, 90),
                          path.lineto(qi, 2*radius))]
anzahl_segmente = (1, 2, 2, 3)
ypos = 0.5*dy
for n in range(1, ntraj+1):
    offset = 0
    if n % 2 == 0:
        offset = -1
    nsegmente = anzahl_segmente[(n-1) % 4] + (n-1)//4*4
    for nsegment in range(1, nsegmente+1):
        yshift = (-offset+nsegment-1)//2*2*radius
        c.stroke(pathsegments[(offset+nsegment-1) % 4],
                 [trafo.translate(0, ypos+yshift),
                  linecolor, style.linewidth.Thick])
    c.stroke(path.circle(qi, ypos, 0.06),
             [style.linewidth.thick, linecolor, deco.filled([color.grey(1)])])
    c.stroke(path.circle(qf, ypos+n//2*2*radius, 0.06),
             [style.linewidth.thick, linecolor, deco.filled([color.grey(1)])])
    ypos = ypos + dy + (n//2)*2*radius
c.writePDFfile()
Ejemplo n.º 22
0
xmin = -2
xmax = 1
width = npts
ymin = -1.5
ymax = 1.5
height = npts
niter = 2000

cnvs = canvas.canvas()
unit.set(wscale=0.8)
cellheight = 0.17

for nr, ndiv in enumerate((2, 4, 8, 16, 32)):
    nrproc, start, ende, data = mandelbrot(xmin, xmax, width, ymin, ymax, height,
                      npts, ndiv, niter)
    offset = -(nrproc+1.2)*cellheight*nr
    cnvs.text(-0.2, offset+2*cellheight, "$n=%s$" % ndiv**2,
              [text.halign.right, text.valign.middle])
    cnvs.stroke(path.line(0, -0.2*cellheight+offset, 0,
        (nrproc+0.2)*cellheight+offset))
    cnvs.stroke(path.line(ende-start, -0.2*cellheight+offset, ende-start,
        (nrproc+0.2)*cellheight+offset))
    for d in data:
        colours = color.hsb(0.667*d[0]/(nrproc-1), 1, 0.3)
        colourf = color.hsb(0.667*d[0]/(nrproc-1), 0.2, 1)
        cnvs.stroke(path.rect(d[1], d[0]*cellheight+offset, (d[2]-d[1]), 0.8*cellheight),
                [colours, deco.filled([colourf])])

cnvs.writePDFfile()
cnvs.writeGSfile(device="png16m", resolution=600)
Ejemplo n.º 23
0
def draw_square(x, y, kante):
    c.stroke(path.rect(x, y, kante, kante),
             [style.linewidth.thick,
              deco.filled([color.grey(1)])])
from pyx import canvas, color, deco, path, text, unit

text.set(text.LatexRunner)
text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{nicefrac}')
unit.set(xscale=1.4, wscale=1.2)

c = canvas.canvas()
r = 0.05
for n in range(1, 5):
    c.stroke(path.circle(n, 0, r))
    c.stroke(path.circle(-n, 0, r))
c.stroke(path.circle(0, 0, r), [deco.filled([color.grey(0)])])
dx = 0.1
dy = 0.3
c.stroke(path.curve(dx, dx, dy, dy, 1-dy, dy, 1-dx, dx), [deco.earrow])
c.text(0.5, dy+0.1, '+1', [text.halign.center])
c.stroke(path.curve(-dx, dx, -dy, dy, -1+dy, dy, -1+dx, dx), [deco.earrow])
c.text(-0.5, dy+0.1, '-1', [text.halign.center])
c.writePDFfile()
Ejemplo n.º 25
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)
Ejemplo n.º 26
0
def pyxColor(string):
    """Return a pyxColor instance.

    :param string: RGB color name like 'ffffff'
    :return: pyx color.

    >>> assert pyxColor('ffffff')
    """
    assert len(string) == 6
    colorTuple = tuple(
        int('0x' + c, 16) for c in [string[i:i + 2] for i in range(0, 6, 2)])
    return color.rgb(*[i / 255.0 for i in colorTuple])


if __name__ == '__main__':  # pragma: no cover
    out = sys.argv[1]
    if not pyx:
        sys.exit(1)
    for icon in set(d['Color'] for d in reader('../cobl-data/cldf/languages.csv', dicts=True)):
        assert len(icon) == 6
        c = canvas.canvas()
        c.draw(
            path.circle(20, 20, 13.6),
            [deco.stroked([linewidth]), deco.filled([pyxColor(icon)])])
        stream = c.pipeGS("pngalpha", resolution=20, bbox=bbox.bbox(0, 0, 40, 40))
        with open(os.path.join(out, 'c{0}.png'.format(icon)), 'wb') as fp:
            fp.write(stream.read())
    sys.exit(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
Ejemplo n.º 28
0
from pyx import color, deco, graph, style, unit

unit.set(xscale=1.3)

g = graph.graphxy(width=8,
                  x=graph.axis.linear(title="$x$"),
                  y=graph.axis.linear(title="$y$"))
g.plot(graph.data.file("pyx1.dat", x=1, y=2), [
    graph.style.line([style.linestyle.dashed,
                      color.rgb(0, 0, 1)]),
    graph.style.symbol(graph.style.symbol.circle,
                       size=0.1,
                       symbolattrs=[
                           deco.filled([color.rgb.red]),
                           deco.stroked([color.grey(0)])
                       ])
])
g.writePDFfile()
g.writeGSfile(device="png16m", resolution=800)
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
Ejemplo n.º 30
0
    def doplot(self, d, xlabel=None, xlog=False,
               ymin=-0.0029, ymax=0.0029,
               xmin=None,xmax=None,
               nocorr=False,
               fitlines=False,
               **kw):
        """
        plot the results

        parameters
        ----------
        d: dict
            result of running something like process_run or process_flist
        **kw:
            extra plotting keywords
        """
        import pyxtools
        from pyx import graph, deco, style
        from pyx.graph import axis

        if xlabel is None:
            xlabel='x'

        xdensity=kw.get('xdensity',1.5)
        ydensity=kw.get('ydensity',1.5)

        red=pyxtools.colors('red')
        blue=pyxtools.colors('blue')

        xvals=self._extract_xvals(d)

        if nocorr:
            sh=d['shear_nocorr']['shear']
            sherr=d['shear_nocorr']['shear_err']
        else:
            sh=d['shear']['shear']
            sherr=d['shear']['shear_err']


        if xlog:
            xcls=axis.log
        else:
            xcls=axis.lin

        xaxis=xcls(
            title=xlabel,
            density=xdensity,
            min=xmin,
            max=xmax,
        )
        yaxis=axis.lin(
            title=r"$\langle g \rangle$",
            density=ydensity,
            min=ymin,
            max=ymax,
        )

        key=graph.key.key(pos='bl')
        g = graph.graphxy(
            width=8,
            ratio=1.2,
            key=key,
            x=xaxis,
            y=yaxis,
        )

        c=graph.data.function(
            "y(x)=0",
            title=None,
            min=xvals[0], max=xvals[-1],
        )

        g.plot(c)

        g1values=graph.data.values(
            x=list(xvals),
            y=list(sh[:,0]),
            dy=list(sherr[:,0]),
            title=r'$g_1$',
        )
        g2values=graph.data.values(
            x=list(xvals),
            y=list(sh[:,1]),
            dy=list(sherr[:,1]),
            title=r'$g_2$',
        )

        symbol1=graph.style.symbol(
            symbol=graph.style.symbol.circle,
            symbolattrs=[red,deco.filled([red])],
            size=0.1,
        )
        symbol2=graph.style.symbol(
            symbol=graph.style.symbol.triangle,
            symbolattrs=[blue,deco.filled([blue])],
            size=0.1,
        )

        g.plot(g1values,[symbol1, graph.style.errorbar(errorbarattrs=[red])])
        g.plot(g2values,[symbol2, graph.style.errorbar(errorbarattrs=[blue])])

        use_errors=True
        if fitlines and not use_errors:
            res1=fitline(xvals,sh[:,0])
            res2=fitline(xvals,sh[:,1])


            fmt='(%(slope).3g +/- %(slope_err).3g) x + (%(offset).3g +/- %(offset_err).3g)'
            print("line1: "+fmt % res1)
            print("line2: "+fmt % res2)

            if self.element is not None:
                tit1=r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % (res1['slope'],self.element+1,res1['offset'])
                tit2=r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % (res2['slope'],self.element+1,res2['offset'])
            else:
                tit1=r'$g_1=%.2g ~x + %.2g$' % (res1['slope'],res1['offset'])
                tit2=r'$g_2=%.2g ~x + %.2g$' % (res1['slope'],res1['offset'])

            c1=graph.data.function(
                "y(x)=%g*x + %g" % tuple( (res1['slope'], res1['offset'])),
                title=tit1,
                min=xvals[0], max=xvals[-1],
            )
            c2=graph.data.function(
                "y(x)=%g*x + %g" % tuple( (res2['slope'], res2['offset'])),
                title=tit2,
                min=xvals[0], max=xvals[-1],
            )

            styles1=[
                graph.style.line([red, style.linestyle.solid]),
            ]
            styles2=[
                graph.style.line([blue, style.linestyle.dashed]),
            ]

            g.plot(c1,styles1)
            g.plot(c2,styles2)

        if fitlines and use_errors:
            # old code
            import fitting
            l1=fitting.fit_line(xvals,sh[:,0],yerr=sherr[:,0])
            l2=fitting.fit_line(xvals,sh[:,1],yerr=sherr[:,1])
            res1=l1.get_result()
            res2=l2.get_result()

            pars1,err1=res1['pars'],res1['perr']
            pars2,err2=res2['pars'],res2['perr']

            fmt='(%.3g +/- %.3g) x + (%.3g +/- %.3g)'
            print("line1: "+fmt % (pars1[0],err1[0],pars1[1],err1[1]))
            print("line2: "+fmt % (pars2[0],err2[0],pars2[1],err2[1]))

            if self.element is not None:
                tit1=r'$g_1=%.2g ~g^{psf}_%d + %.2g$' % (pars1[0],self.element+1,pars1[1])
                tit2=r'$g_2=%.2g ~g^{psf}_%d + %.2g$' % (pars2[0],self.element+1,pars2[1])
            else:
                tit1=r'$g_1=%.2g ~x + %.2g$' % (pars1[0],pars1[1])
                tit2=r'$g_2=%.2g ~x + %.2g$' % (pars2[0],pars2[1])
            c1=graph.data.function(
                "y(x)=%g*x + %g" % tuple(pars1),
                title=tit1,
                min=xvals[0], max=xvals[-1],
            )
            c2=graph.data.function(
                "y(x)=%g*x + %g" % tuple(pars2),
                title=tit2,
                min=xvals[0], max=xvals[-1],
            )

            styles1=[
                graph.style.line([red, style.linestyle.solid]),
            ]
            styles2=[
                graph.style.line([blue, style.linestyle.dashed]),
            ]

            g.plot(c1,styles1)
            g.plot(c2,styles2)


        if 'file' in kw:
            print("writing:",kw['file'])
            pyxtools.write(g, kw['file'], dpi=200)

        if fitlines and 'fitfile' in kw:
            print("writing:",kw['fitfile'])
            with open(kw['fitfile'],'w') as fobj:
                fobj.write(repr(l1))
                fobj.write('\n')
                fobj.write(repr(l2))
                fobj.write('\n')

        return g
Ejemplo n.º 31
0
    "f": polygon((2, 36), (38, 36), (20, 5)),  # inverted pyramid
    "d": polygon((20, 2), (38, 20), (20, 38), (2, 20)),  # diamond
}


def pyxColor(string):
    """
    :param string: RGB color name like 'ffffff'
    :return: pyx color.

    >>> assert pyxColor('ffffff')
    """
    assert len(string) == 6
    colorTuple = tuple(int('0x' + c, 16) for c in [string[i:i+2] for i in range(0, 6, 2)])
    return color.rgb(*[i / 255.0 for i in colorTuple])


if __name__ == '__main__':  # pragma: no cover
    if not pyx:
        sys.exit(1)
    asset_resolver = AssetResolver()
    for icon in ICONS:
        c = canvas.canvas()
        c.draw(
            shapes[icon.name[0]],
            [deco.stroked([linewidth]), deco.filled([pyxColor(icon.name[1:])])])
        stream = c.pipeGS("pngalpha", resolution=20, bbox=bbox.bbox(0, 0, 40, 40))
        with open(asset_resolver.resolve(icon.asset_spec).abspath(), 'wb') as fp:
            fp.write(stream.read())
    sys.exit(0)
Ejemplo n.º 32
0
basename = os.path.splitext(sys.argv[0])[0]

text.set(text.LatexRunner)
text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}')
c = canvas.canvas()

wd = 6.9
ht = 3.5
githubfgcolor = color.grey(0.4)
githubbgcolor = color.grey(0.97)
maintainercolor = color.hsb(0.7, 1, 0.5)
usercolor = color.hsb(0.05, 1, 0.5)
c.stroke(path.rect(0, 0, wd, ht), [deformer.smoothed(0.1),
                                   githubfgcolor,
                                   style.linewidth.Thick,
                                   deco.filled([githubbgcolor])])

clabel = canvas.canvas()
labeltext = text.text(0, 0, r'\textsf{\bfseries Github}', [color.grey(1)])
extrawd = 0.15
labelbox = labeltext.bbox().enlarged(extrawd)
clabel.fill(labelbox.path(), [githubfgcolor, deformer.smoothed(0.1)])
clabel.insert(labeltext)
c.insert(clabel, [trafo.translate(extrawd, ht+extrawd)])

c.text(wd+0.4, ht-0.5, r'\footnotesize\textsf{read/write permissions}')
c.insert(read(1, usercolor), [trafo.translate(wd+0.7, ht-0.9)])
c.insert(write(1, usercolor), [trafo.translate(wd+1.05, ht-0.9)])
c.text(wd+1.5, ht-1.0, r'\footnotesize\textsf{user}', [usercolor])
c.insert(write(1, maintainercolor), [trafo.translate(wd+1.05, ht-1.3)])
c.insert(read(1, maintainercolor), [trafo.translate(wd+0.7, ht-1.3)])
Ejemplo n.º 33
0
from pyx import color, deco, graph, style

with open('numba_parallel.dat') as fh:
    t_cpu = float(fh.readline().rstrip('\n').split()[1])
    t_parallel = [(1, t_cpu)]
    for _ in range(7):
        elems = fh.readline().rstrip('\n').split()
        t_parallel.append((int(elems[0]), float(elems[1])))
t_parallel = [(n, t_cpu / t) for n, t in t_parallel]

g = graph.graphxy(width=8,
                  x=graph.axis.linear(min=1, max=8, title="number of threads"),
                  y=graph.axis.linear(title="acceleration"))
g.plot(graph.data.points(t_parallel, x=1, y=2), [
    graph.style.line([]),
    graph.style.symbol(symbol=graph.style.symbol.circle,
                       size=0.1,
                       symbolattrs=[deco.filled([color.grey(1)])])
])
g.writePDFfile()
g.writeGSfile(device="png16m", resolution=600)
Ejemplo n.º 34
0
    def visualize(self, namespace='', comp_idx=-1, reduce_type='max'):

        # Breadth-first traversal.

        seen_cells = set()
        cell_order = []

        from queue import SimpleQueue
        queue = SimpleQueue()
        queue.put((self, 0))

        n_levels = 1
        levels = {}
        level_sizes = {}

        while not queue.empty():
            node, depth = queue.get()

            if depth + 1 > n_levels:
                n_levels = depth + 1

            if depth not in levels:
                levels[depth] = {}
            for si in node.sample_idx:
                if si not in levels[depth]:
                    levels[depth][si] = []
                levels[depth][si].append(node.viz_value[comp_idx])

            if depth not in level_sizes:
                level_sizes[depth] = 0
            level_sizes[depth] += 1.

            if len(node.children) == 0:
                [
                    cell_order.append(si) for si in node.sample_idx
                    if si not in seen_cells
                ]
                seen_cells.update(node.sample_idx)

            else:
                for child in node.children:
                    queue.put((child, depth + 1))

        # Draw the pyramid.
        from pyx import canvas, path, style, deco, color

        c = canvas.canvas()

        unit = 20.
        height = unit * np.sqrt(3) / 2.

        level_height = height / n_levels
        curr_height = height

        grad = color.lineargradient_rgb(color.rgb.white, color.rgb.red)

        for level in range(n_levels):
            top_width = height - curr_height
            bottom_width = height - curr_height + level_height

            n_in_level = len(levels[level])
            assert (n_in_level == len(self.sample_idx) == len(cell_order))

            x_top = (unit / 2.) - (top_width / 2.)
            x_top_curr = x_top
            x_top_inc = top_width / n_in_level

            x_bottom = (unit / 2.) - (bottom_width / 2.)
            x_bottom_curr = x_bottom
            x_bottom_inc = bottom_width / n_in_level

            if reduce_type == 'mean':
                reduce_fn = np.mean
            elif reduce_type == 'median':
                reduce_fn = np.median
            elif reduce_type == 'max':
                reduce_fn = np.max
            elif reduce_type == 'min':
                reduce_fn = np.min
            else:
                raise ValueError(
                    'Invalid reduce function {}'.format(reduce_type))

            curr_node = reduce_fn(levels[level][cell_order[0]])

            for sidx in cell_order:

                if reduce_fn(levels[level][sidx]) != curr_node:

                    brick = path.path(
                        path.moveto(x_top, curr_height),
                        path.lineto(x_top_curr, curr_height),
                        path.lineto(x_bottom_curr, curr_height - level_height),
                        path.lineto(x_bottom, curr_height - level_height),
                        path.closepath(),
                    )
                    c.stroke(brick, [
                        style.linewidth(1e-3),
                        deco.filled([grad.getcolor(curr_node)])
                    ])

                    curr_node = reduce_fn(levels[level][sidx])
                    x_top = x_top_curr
                    x_bottom = x_bottom_curr

                x_top_curr += x_top_inc
                x_bottom_curr += x_bottom_inc

            brick = path.path(
                path.moveto(x_top, curr_height),
                path.lineto(x_top_curr, curr_height),
                path.lineto(x_bottom_curr, curr_height - level_height),
                path.lineto(x_bottom, curr_height - level_height),
                path.closepath(),
            )
            c.stroke(brick, [
                style.linewidth(1e-3),
                deco.filled([grad.getcolor(curr_node)])
            ])

            curr_height -= level_height

        c.writeSVGfile('pyramid{}_{}_{}_{}_{}'.format(namespace,
                                                      self.dag_method,
                                                      self.decomp_method,
                                                      reduce_type, comp_idx))
text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
unit.set(xscale=1.6, wscale=1.5)

frontplane = canvas.canvas()
backplane = canvas.canvas()
xcells = 4
ycells = 3
xshift = 0.8
yshift = 1.2
dist = 0.2
myred = color.rgb(0.8, 0, 0)
mygreen = color.rgb(0, 0.6, 0)
myblue = color.rgb(0, 0, 0.8)
for c, start in ((frontplane, 0), (backplane, xcells*ycells)):
    c.stroke(path.rect(0, 0, 4, 3),
             [deco.filled([color.grey(1), color.transparency(0.2)])])
    for x in range(1, xcells):
        c.stroke(path.line(x, 0, x, ycells))
    for y in range(1, ycells):
        c.stroke(path.line(0, y, xcells, y))
    for entry in range(xcells*ycells):
        x = entry % 4
        y = ycells - entry // 4
        c.text(x+0.5, y-0.5, str(start+entry),
               [text.halign.center, text.valign.middle])
c = canvas.canvas()
c.insert(backplane, [trafo.translate(xshift, yshift)])
for x, y in product((0, xcells), (0, ycells)):
    c.stroke(path.line(x, y, x+xshift, y+yshift))
c.insert(frontplane)
dx = -dist*yshift/sqrt(xshift**2+yshift**2)
Ejemplo n.º 36
0
                  \usepackage{newtxsf}''')
unit.set(vscale=1.2, wscale=1.3, xscale=1.3)
c = canvas.canvas()
c.fill(path.rect(0, 0, -0.3, height-0.3), [color.grey(0.5)])
c.stroke(path.line(-0.5*width, 0, 0.5*width, 0), [deco.earrow])
c.text(0.5*width+0.1, 0, '$q$', [text.valign.middle])
c.stroke(path.line(0, 0, 0, height), [deco.earrow])
c.text(0.2, height, '$t$', [text.valign.top])
c.stroke(path.path(path.moveto(qi, 0),
                   path.curveto(qi, 0.5, qi+0.2, 1.3, qi+0.8, 1.6),
                   path.curveto(qi+1.4, 1.9, qf+0.7, 3, qf, t)),
         [style.linewidth.thick, linecolor1])
c.stroke(path.path(path.moveto(qi, 0),
                   path.curveto(0.5*qi, 0.5, -2.5, 1.3, 0, 1.6)),
         [style.linewidth.thick, linecolor2])
p = path.path(path.moveto(0, 1.6),
              path.curveto(2.5, 1.9, 3, 3, qf, t))
c.stroke(p, [style.linewidth.thick, linecolor2])
c.stroke(p, [style.linewidth.thick, style.linestyle.dashed,
             linecolor2, trafo.mirror(90)])
ypos = 0
for q, label in ((qi, r'$q_\text{i}$'),
                 (qf, r'$q_\text{f}$'),
                 (-qf, r'$-q_\text{f}$')):
    c.stroke(path.line(q, 0.1, q, -0.1))
    c.text(q, -0.5, label, [text.halign.center])
    c.stroke(path.circle(q, ypos, 0.06),
             [deco.filled([color.grey(1)])])
    ypos = t
c.writePDFfile()
Ejemplo n.º 37
0
codecolor = color.rgb(0.7, 1, 0)

codepoint = 0x00221E
bits = 24

codepointbinary = [(codepoint & 2**n) / 2**n for n in range(bits)]
codepointbinary.reverse()

size = 0.4
x0 = 0
y0 = 3
dy = 0.07
c.fill(path.rect(x0, y0, 8 * size, size),
       [markercolor, deco.stroked([markercolor])])
c.stroke(path.rect(x0 + 8 * size, y0, 4 * size, size),
         [deco.filled([codecolor])])
c.stroke(path.rect(x0 + 12 * size, y0, 6 * size, size),
         [deco.filled([codecolor])])
c.stroke(path.rect(x0 + 18 * size, y0, 6 * size, size),
         [deco.filled([codecolor])])
for n in range(len(codepointbinary)):
    c.text(x0 + (n + 0.5) * size, y0 + dy,
           r"\sffamily %i" % codepointbinary[n], [text.halign.center])

p = path.path(path.moveto(0.2 * size, size + 0.03),
              path.lineto(0.2 * size, size + 0.07),
              path.lineto(3.8 * size, size + 0.07),
              path.lineto(3.8 * size, size + 0.03))
for n in range(bits // 4):
    c.stroke(p, [trafo.translate(4 * n * size, y0)])
    c.text((4 * n + 2) * size, size + 0.14 + y0,
Ejemplo n.º 38
0
from pyx import color, deco, graph, style, unit

unit.set(xscale=1.3)

g = graph.graphxy(width=8,
                  x=graph.axis.linear(title="$x$"),
                  y=graph.axis.linear(title="$y$"))
g.plot(graph.data.file("pyx1.dat", x=1, y=2),
       [graph.style.line([style.linestyle.dashed, color.rgb(0, 0, 1)]),
        graph.style.symbol(graph.style.symbol.circle, size=0.1,
                           symbolattrs=[deco.filled([color.rgb.red]),
                                        deco.stroked([color.grey(0)])])])
g.writePDFfile()
g.writeGSfile(device="png16m", resolution=800)