Пример #1
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
Пример #3
0
def color_map(alpha, nums):
    """returns a dict of which color a character maps to"""
    n = 1.0 / (len(alpha) + 5)
    mapping = {}
    init = len(alpha) * n
    for letter in alpha:
        mapping[letter] = color.rgb(init, init, init)
        init -= n
    for number in nums:
        mapping[number] = color.rgb(0.5, 0.5, 0.5)
    mapping[''] = color.rgb.red
    return mapping
Пример #4
0
def array(shape):
    baseshape = (3, 4)
    bgcolor = color.grey(0.5)
    c = canvas.canvas()
    c.text(baseshape[1] / 2, baseshape[0] + 0.3, 'shape=%s' % repr(shape),
           [text.halign.center])
    if len(shape) == 1:
        shape = (1, shape[0])
    assert len(shape) == 2
    c.stroke(path.rect(0, 0, baseshape[1], baseshape[0]), [bgcolor])
    for nx in range(1, baseshape[1]):
        c.stroke(path.line(nx, 0, nx, baseshape[0]), [bgcolor])
    for ny in range(1, baseshape[0]):
        c.stroke(path.line(0, ny, baseshape[1], ny), [bgcolor])
    if not (shape == baseshape):
        c.fill(path.rect(0, baseshape[0], shape[1], -shape[0]),
               [color.rgb(1, 0.8, 0.4)])
        if shape[0] in (1, baseshape[0]) and shape[1] in (1, baseshape[1]):
            for nx in range(baseshape[1]):
                for ny in range(baseshape[0]):
                    c.text(
                        nx + 0.5, baseshape[0] - ny - 0.5,
                        str(baseshape[1] * min(ny, shape[0] - 1) +
                            min(nx, shape[1] - 1) + 1),
                        [text.halign.center, text.valign.middle, bgcolor])
        else:
            alertcolor = color.rgb(0.6, 0, 0)
            c.stroke(path.line(0, 0, baseshape[1], baseshape[0]),
                     [alertcolor, style.linewidth.Thick])
            c.stroke(path.line(0, baseshape[0], baseshape[1], 0),
                     [alertcolor, style.linewidth.Thick])
    else:
        for nx in range(baseshape[1]):
            for ny in range(baseshape[0]):
                c.text(nx + 0.5, baseshape[0] - ny - 0.5,
                       str(baseshape[1] * ny + nx + 1),
                       [text.halign.center, text.valign.middle])
    c.stroke(path.rect(0, baseshape[0], shape[1], -shape[0]))
    for nx in range(1, shape[1]):
        c.stroke(path.line(nx, baseshape[0], nx, baseshape[0] - shape[0]))
    for ny in range(1, shape[0]):
        c.stroke(path.line(0, ny, shape[1], ny))
    if not (shape == baseshape):
        for nx in range(shape[1]):
            for ny in range(shape[0]):
                c.text(nx + 0.5, baseshape[0] - ny - 0.5,
                       str(baseshape[1] * ny + nx + 1),
                       [text.halign.center, text.valign.middle])
    return c
Пример #5
0
 def HLcolor(self, t):
     """Half-life color scheme"""
     if (type(t) != type(1.0) and type(t) != type(1)) or t == 0: return rgb(.5, .5, .5)
     if t == float("inf"): return rgb.black
     x = log(t/self.HLmin)/log(pi*self.HLmax/self.HLmin) if t else 1
     x = min(max(0,x),1)
     return hsb(0.90*x, 1, 1)
Пример #6
0
def draw_graph(graph, pts=None, name="output"):
    import pyx
    from pyx import path, deco, trafo, style, text, color, deformer
    from pyx.color import rgb, cmyk
    from pyx.color import rgbfromhexstring as rgbhex

    black = rgb(0., 0., 0.)
    blue = rgb(0., 0., 0.8)
    lred = rgb(1., 0.4, 0.4)
    red = rgb(1., 0.0, 0.0)
    white = rgb(1., 1., 1.)

    if pts is None:
        pts = pos_circ(graph)

    directed = isinstance(graph, (nx.DiGraph, nx.MultiDiGraph))

    #W = 10.
    #H = 10.

    R = 1.5
    r = 0.2

    c = pyx.canvas.canvas()

    for edge in graph.edges():
        src, tgt = edge

        x0, y0 = pts[src]
        x1, y1 = pts[tgt]

        color = black
        if edge in edge_colors:
            color = eval(edge_colors[edge])
        c.stroke(path.line(R * x0, R * y0, R * x1, R * y1), [color])

    for node in graph.nodes():
        x, y = pts[node]
        p = path.circle(R * x, R * y, r)

        color = white
        if node in node_colors:
            color = eval(node_colors[node])
        c.fill(p, [color])
        c.stroke(p, [black])

    c.writePDFfile(name)
Пример #7
0
    def draw(self, NC):
        isProton = self.Z < 0
        A,Z = self.A, abs(self.Z)

        c = rgb(1,0.5,0) if isProton else rgb(0,0.5,1)
        alpha = color.transparency(1. - self.w)
        s = [style.linewidth.THick, c, alpha, deco.earrow([deco.filled([c])], size=NC.dscale*0.3)]

        if NC.dA[0] < 0:
            x0,y0 = NC.nucCenter(A, Z, 0.3, -0.3 if isProton else 0)
            if isProton: x1,y1 = NC.nucCenter(A-1, Z-1, -0.35, 0)
            else: x1,y1 = NC.nucCenter(A-1, Z, -0.35, 0)
        else:
            x0,y0 = NC.nucCenter(A, Z, -0.3, -0.35 if isProton else 0)
            if isProton: x1,y1 = NC.nucCenter(A-1, Z-1, 0.35, 0)
            else: x1,y1 = NC.nucCenter(A-1, Z, 0.35, 0)
        NC.stroke(path.line(x0,y0,x1,y1), s)
Пример #8
0
def draw_crs_to_canvas(c, crs: torch.Tensor, lw=1, lcols=None, alpha=0.5):
    # crs [n, nc, 2]; only draw nc>1<nc-1
    if crs is None:
        return

    n, nc, _ = crs.shape

    # Premultiplied power constant for the following tj() function.
    alpha = alpha / 2

    def tj(ti, pi, pj):
        return ((pi - pj)**2).sum(dim=-1)**alpha + ti

    if lcols is not None:
        lcols = lcols.detach().cpu()

    if crs is not None:
        crs = crs.detach().cpu()

        for i in range(n):
            _lw = lw[i] if isinstance(lw, torch.Tensor) else lw
            if _lw > 1e-3:
                for j in range(nc - 4 + 1):
                    p0 = crs[i, j + 0]
                    p1 = crs[i, j + 1]
                    p2 = crs[i, j + 2]
                    p3 = crs[i, j + 3]

                    t0 = 0
                    t1 = tj(t0, p0, p1)
                    t2 = tj(t1, p1, p2)
                    t3 = tj(t2, p2, p3)

                    c1 = (t2 - t1) / (t2 - t0)
                    c2 = (t1 - t0) / (t2 - t0)
                    d1 = (t3 - t2) / (t3 - t1)
                    d2 = (t2 - t1) / (t3 - t1)

                    m1 = (t2 - t1) * (c1 * (p1 - p0) / (t1 - t0) + c2 *
                                      (p2 - p1) / (t2 - t1))
                    m2 = (t2 - t1) * (d1 * (p2 - p1) / (t2 - t1) + d2 *
                                      (p3 - p2) / (t3 - t2))

                    q0 = p1
                    q1 = p1 + m1 / 3
                    q2 = p2 - m2 / 3
                    q3 = p2

                    curve = path.curve(q0[1], -q0[0], q1[1], -q1[0], q2[1],
                                       -q2[0], q3[1], -q3[0])
                    if lcols is None:
                        c.stroke(curve,
                                 [style.linewidth(_lw), style.linecap.round])
                    else:
                        c.stroke(curve, [
                            style.linewidth(_lw), style.linecap.round,
                            color.rgb(*lcols[i])
                        ])
Пример #9
0
    def draw(self):
        """draw the text!!"""

        for layer in self.sectors:
            radius = self.sectors[layer]['radius']
            letter_radius = radius + 0.25 * self.sector_width

            prev_radian = 0
            for radian in self.sectors[layer]['letters']:
                end = False
                letter = self.sectors[layer]['letters'][radian][0]
                if len(letter) > 1:
                    end = True
                freq = self.sectors[layer]['letters'][radian][1]

                offset = False
                cur_radian = radian

                if (radian - prev_radian) * letter_radius < 0.22:
                    cur_radian = prev_radian + 0.22 / letter_radius
                    prev_radian = cur_radian
                    offset = True

                centroid_x = radius * cos(radian) + self.xo
                centroid_y = radius * sin(radian) + self.yo
                if end:
                    letter_x = radius * cos(cur_radian) + self.xo
                    letter_y = radius * sin(cur_radian) + self.yo
                else:
                    letter_x = letter_radius * cos(cur_radian) + self.xo
                    letter_y = letter_radius * sin(cur_radian) + self.yo

                # rotate the text accordingly
                transform = trafo.rotate(radian * 180 / pi)

                if cur_radian > pi / 2 and cur_radian < (3 * pi / 2):
                    transform = trafo.rotate(180 + radian * 180 / pi)

                # if this condition is true then the letter is actually the
                # whole word, it is an end sector, so display the frequency
                if len(letter) > 1:
                    letter += ' '
                    letter += str(freq)

                # the random floats are me tuning the color just right lol
                text_color = color.rgb(0, 0.0784 * 1.4, 0.156 * 1.4)
                self.canvas.text(
                    letter_x, letter_y, r"\texttt{" + letter + '}', [
                        text.halign.center, text.valign.middle, transform,
                        text.size.scriptsize, text_color
                    ])
                if offset:
                    self.canvas.stroke(
                        path.line(centroid_x, centroid_y, letter_x, letter_y),
                        [style.linewidth(0.0035), text_color])
                self.canvas.fill(path.circle(centroid_x, centroid_y, 0.0065),
                                 [text_color])
                prev_radian = cur_radian
Пример #10
0
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
Пример #11
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
Пример #12
0
def get(color):
    if isinstance(color, basestring):
        if color.startswith('#'):
            r = int(color[1:3], 16)
            g = int(color[3:5], 16)
            b = int(color[5:7], 16)
            color = rgb(r=r/255.0, g=g/255.0, b=b/255.0)
        else:
            color = getattr(cmyk, color, cmyk.Black)
    return color
Пример #13
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])
Пример #14
0
def get(color):
    if isinstance(color, basestring):
        if color.startswith('#'):
            r = int(color[1:3], 16)
            g = int(color[3:5], 16)
            b = int(color[5:7], 16)
            color = rgb(r=r / 255.0, g=g / 255.0, b=b / 255.0)
        else:
            color = getattr(cmyk, color, cmyk.Black)
    return color
Пример #15
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])
Пример #16
0
def choose_color(nsym):
    """
    selects the  RBG colors from a range with maximum nsym colors
    :param mx:
    :return:
    """
    lcols = []
    for i in np.arange(380, 750, 370.0 / nsym):
        r, g, b = wavelength_to_rgb(i)
        lcols.append(rgb(r, g, b))
    return lcols[0:nsym]
Пример #17
0
    def get_rgb(self, name_in):
        if isinstance(name_in, color.rgb):
            return name_in

        name=name_in.lower()
        rgb=_rgbdict.get(name,None)
        if rgb is None:
            raise ValueError("bad color name: '%s'" % name_in)

        r=rgb[0]/255.0
        g=rgb[1]/255.0
        b=rgb[2]/255.0
        return color.rgb(r=r, g=g, b=b)
Пример #18
0
 def fill(self, path, clr):
     """
     Draws the given path as a closed shape
     
     :param path: The path to draw
     :type path:  ``path``
     
     :param clr: The color to draw
     :type clr:  3d ``tuple``
     """
     from pyx import color
     pclr = color.rgb(clr[0], clr[1], clr[2])
     self._canvas.fill(path, [pclr, self._offset()])
     self._mark = True
Пример #19
0
def draw_points_to_canvas(c, points: torch.Tensor, size=1, pcols=None):
    if pcols is not None:
        pcols = pcols.detach().cpu()

    if points is not None:
        points = points.detach().cpu()
        for i in range(points.shape[0]):
            _size = size[i] if isinstance(size, torch.Tensor) else size
            if _size > 0:
                if pcols is None:
                    c.fill(path.circle(points[i, 1], -points[i, 0], _size))
                else:
                    c.fill(path.circle(points[i, 1], -points[i, 0], _size),
                           [color.rgb(*pcols[i])])
Пример #20
0
 def stroke(self, path, clr):
     """
     Draws the given path and color as a line.
     
     :param path: The path to draw
     :type path:  ``path``
     
     :param clr: The color to draw
     :type clr:  3d ``tuple``
     """
     from pyx import color
     pclr = color.rgb(clr[0], clr[1], clr[2])
     self._canvas.stroke(path, [pclr, self._offset()])
     self._mark = True
Пример #21
0
def winding(n,
            radius,
            angle=60,
            windingnumber=False,
            endpointcolor=color.rgb(0.6, 0.2, 0),
            pathcolor=color.rgb(0.4, 0.3, 0.8)):
    c = canvas.canvas()
    ticklen = 0.1
    c.stroke(path.circle(0, 0, radius), [style.linewidth.Thin])
    tick = path.line((1 - ticklen) * radius, 0, (1 + ticklen) * radius, 0)
    c.stroke(tick, [endpointcolor, style.linewidth.Thick])
    c.stroke(tick, [trafo.rotate(angle), endpointcolor, style.linewidth.Thick])
    tick_outer = (1 + ticklen) * radius
    for _angle, label in ((0, r'$\phi_\text{i}$'), (radians(angle),
                                                    r'$\phi_\text{f}$')):
        c.text((tick_outer + 0.3) * cos(_angle),
               (tick_outer + 0.3) * sin(_angle), label,
               [text.halign.center, text.valign.middle, endpointcolor])
    if windingnumber:
        c.text(0, -radius - 0.3, '$n={}$'.format(n),
               [text.halign.center, text.valign.top])
    c.stroke(spiral(radius, angle, n), [pathcolor, style.linewidth.Thick])
    return c
Пример #22
0
    def draw(self, NC):
        """Draw to NucCanvas"""
        isPositron = self.Z < 0
        A,Z = self.A,abs(self.Z)

        if isPositron:
            x0,y0 = NC.nucCenter(A, Z-0.5)
            c = rgb(1,0,1)
        else:
            x0,y0 = NC.nucCenter(A, Z+0.5)
            c = rgb.blue

        alpha = color.transparency(1. - self.w)
        p0 = NC.nucCenter(A, Z)
        pZ = NC.nucCenter(A, Z - (1 if isPositron else -1))
        thz = atan2(pZ[0]-p0[0], pZ[1]-p0[1]) * 180/pi
        NC.fill(self.btri, [c, alpha, trafo.scale(NC.dscale), trafo.rotate(thz), trafo.translate(x0,y0)])
Пример #23
0
def make_moon_key(canv, chart) :
    large_moon_rad = 0.16
    small_moon_rad = 0.12
    x = 0.0
    y = -1.8
    canv.fill(path.rect(x, y, chart.width, 1.0), 
            [color.rgb(0.0, 0.0, 0.0)])
    for i in range(8) :
        X = 1.0-(i+1.0)/9.0
        canv.fill(waning_moon(X, small_moon_rad, x+(i+4.0)/4.0, -1.3),
                    [style.linejoin.bevel,mooncolorlight])
    canv.text(x+1.8, -1.1,
              r'{\footnotesize\sffamily Küçülen Ay}',
              [text.halign.center,text.valign.baseline,mooncolorlight])
    canv.text(x+1.8, -1.7,
              r"{\scriptsize\sffamily (Ay'ın doğuş zamanları)}",
              [text.halign.center,text.valign.baseline,mooncolorlight])
    for i in range(8) :
        X = (i+1.0)/9.0
        canv.fill(waxing_moon(X, small_moon_rad, x+(i+4.0)/4.0+3.0, -1.3),
                    [style.linejoin.bevel,mooncolordark])
    canv.text(x+1.8+3.0, -1.1,
              r'{\footnotesize\sffamily Büyüyen Ay}',
              [text.halign.center,text.valign.baseline,mooncolordark])
    canv.text(x+1.8+3.0, -1.7,
              r"{\scriptsize\sffamily (Ay'ın batış zamanları)}",
              [text.halign.center,text.valign.baseline,mooncolordark])
    # new moon, first quarter
    # full moon,  last quarter
    canv.stroke(path.circle(x+8.5,-1.1,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolordark])])
    canv.text(x+8.25, -1.2, r'{\footnotesize\sffamily Yeni ay}',
            [text.halign.right,text.valign.baseline, mooncolordark])
    canv.stroke(first_quarter_moon(large_moon_rad, x+8.9,-1.1),[mooncolordark,pyx.deco.filled([mooncolordark])])
    canv.text(x+9.25, -1.2, r'{\footnotesize\sffamily İlk dördün}',
            [text.halign.left,text.valign.baseline, mooncolordark])
    canv.stroke(path.circle(x+8.5,-1.5,large_moon_rad),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+8.25, -1.6, r'{\footnotesize\sffamily Dolunay}',
            [text.halign.right,text.valign.baseline, mooncolorlight])
    canv.stroke(last_quarter_moon(large_moon_rad, x+8.9,-1.5),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+9.25, -1.6, r'{\footnotesize\sffamily Son dördün}',
            [text.halign.left,text.valign.baseline, mooncolorlight])
Пример #24
0
def draw_lines_to_canvas(c, lines: torch.Tensor, lw=1, lcols=None):
    if lcols is not None:
        lcols = lcols.detach().cpu()

    if lines is not None:
        lines = lines.detach().cpu()
        for i in range(lines.shape[0]):
            _lw = lw[i] if isinstance(lw, torch.Tensor) else lw
            if _lw > 0:
                if lcols is None:
                    c.stroke(
                        path.line(lines[i, 0, 1], -lines[i, 0, 0],
                                  lines[i, 1, 1], -lines[i, 1, 0]),
                        [style.linewidth(_lw), style.linecap.round])
                else:
                    c.stroke(
                        path.line(lines[i, 0, 1], -lines[i, 0, 0],
                                  lines[i, 1, 1], -lines[i, 1, 0]),
                        [
                            style.linewidth(_lw), style.linecap.round,
                            color.rgb(*lcols[i])
                        ])
Пример #25
0
def make_moon_key2_eng(canv, chart, y) :
    x = 0.0
    canv.fill(path.rect(x, y, chart.width, 1.0), 
            [color.rgb(0.0, 0.0, 0.0)])
    for i in range(8) :
        X = 1.0-(i+1.0)/9.0
        canv.fill(waning_moon(X, 0.08, x+(i+4.0)/4.0, y+0.5),
                    [style.linejoin.bevel,mooncolorlight])
    canv.text(x+1.8, y+0.7,
              r'{\footnotesize\sffamily Waning Moon}',
              [text.halign.center,text.valign.baseline,mooncolorlight])
    canv.text(x+1.8, y+0.2,
              r"{\scriptsize\sffamily (Moon rising)}",
              [text.halign.center,text.valign.baseline,mooncolorlight])
    for i in range(8) :
        X = (i+1.0)/9.0
        canv.fill(waxing_moon(X, 0.08, x+(i+4.0)/4.0+3.0, y+0.5),
                    [style.linejoin.bevel,mooncolordark])
    canv.text(x+1.8+3.0, y+0.7,
              r'{\footnotesize\sffamily Waxing Moon}',
              [text.halign.center,text.valign.baseline,mooncolordark])
    canv.text(x+1.8+3.0, y+0.2,
              r"{\scriptsize\sffamily (Moon setting)}",
              [text.halign.center,text.valign.baseline,mooncolordark])
    # new moon, first quarter
    # full moon,  last quarter
    canv.stroke(path.circle(x+8.5,y+0.75,.12),[mooncolorlight,pyx.deco.filled([mooncolordark])])
    canv.text(x+8.25, y+0.65, r'{\footnotesize\sffamily New Moon}',
            [text.halign.right,text.valign.baseline, mooncolordark])
    canv.stroke(first_quarter_moon(0.12, x+8.9,y+0.75),[mooncolordark,pyx.deco.filled([mooncolordark])])
    canv.text(x+9.25, y+0.65, r'{\footnotesize\sffamily First Quarter}',
            [text.halign.left,text.valign.baseline, mooncolordark])
    canv.stroke(path.circle(x+8.5,y+0.35,.12),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+8.25, y+0.25, r'{\footnotesize\sffamily Full Moon}',
            [text.halign.right,text.valign.baseline, mooncolorlight])
    canv.stroke(last_quarter_moon(0.12, x+8.9,y+0.35),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+9.25, y+0.25, r'{\footnotesize\sffamily Last Quarter}',
            [text.halign.left,text.valign.baseline, mooncolorlight])
Пример #26
0
def make_moon_key2(canv, chart, y) :
    x = 0.0
    canv.fill(path.rect(x, y, chart.width-1.0, 1.0), 
            [color.rgb(0.0, 0.0, 0.0)])
    for i in range(8) :
        X = 1.0-(i+1.0)/9.0
        canv.fill(waning_moon(X, 0.08, x+(i+4.0)/4.0, y+0.5),
                    [style.linejoin.bevel,mooncolorlight])
    canv.text(x+1.8, y+0.7,
              r'{\footnotesize\sffamily Küçülen Ay}',
              [text.halign.center,text.valign.baseline,mooncolorlight])
    canv.text(x+1.8, y+0.2,
              r"{\scriptsize\sffamily (Ay'ın doğuş zamanları)}",
              [text.halign.center,text.valign.baseline,mooncolorlight])
    for i in range(8) :
        X = (i+1.0)/9.0
        canv.fill(waxing_moon(X, 0.08, x+(i+4.0)/4.0+3.0, y+0.5),
                    [style.linejoin.bevel,mooncolordark])
    canv.text(x+1.8+3.0, y+0.7,
              r'{\footnotesize\sffamily Büyüyen Ay}',
              [text.halign.center,text.valign.baseline,mooncolordark])
    canv.text(x+1.8+3.0, y+0.2,
              r"{\scriptsize\sffamily (Ay'ın batış zamanları)}",
              [text.halign.center,text.valign.baseline,mooncolordark])
    # new moon, first quarter
    # full moon,  last quarter
    canv.stroke(path.circle(x+8.5,y+0.7,.12),[mooncolorlight,pyx.deco.filled([mooncolordark])])
    canv.text(x+8.25, y+0.6, r'{\footnotesize\sffamily Yeni Ay}',
            [text.halign.right,text.valign.baseline, mooncolordark])
    canv.stroke(first_quarter_moon(0.12, x+8.9,y+0.7),[mooncolordark,pyx.deco.filled([mooncolordark])])
    canv.text(x+9.25, y+0.6, r'{\footnotesize\sffamily İlk Dördün}',
            [text.halign.left,text.valign.baseline, mooncolordark])
    canv.stroke(path.circle(x+8.5,y+0.3,.12),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+8.25, y+0.2, r'{\footnotesize\sffamily Dolunay}',
            [text.halign.right,text.valign.baseline, mooncolorlight])
    canv.stroke(last_quarter_moon(0.12, x+8.9,y+0.3),[mooncolorlight,pyx.deco.filled([mooncolorlight])])
    canv.text(x+9.25, y+0.2, r'{\footnotesize\sffamily Son Dördün}',
            [text.halign.left,text.valign.baseline, mooncolorlight])
        inner_offset = framefactor*boxsize
    p = (path.rect(x+outer_offset, y+outer_offset,
                   w-2*outer_offset, h-2*outer_offset)
         + path.rect(x+inner_offset, y+inner_offset,
                     w-2*inner_offset, h-2*inner_offset).reversed()
         )
    c.fill(p, [framecolor])


ncols = 6
nrows = ncols
boxsize = 1
angle = radians(40)
reducedboxsize = 0.65*boxsize

ex1color = color.rgb(0, 0.5, 0)
ex2color = color.rgb(0, 0, 0.7)
ex3color = color.rgb(0.7, 0, 0)

text.set(text.LatexRunner)
preamble = r'''\usepackage[T1]{fontenc}
               \usepackage{bera}
               \renewcommand*\familydefault{\ttdefault}
               \usepackage{color}'''
for nr, elem in enumerate((ex1color, ex2color, ex3color)):
    preamble = preamble+r'\definecolor{{ex{}color}}{{rgb}}{{{}, {}, {}}}'.format(
                  nr+1, elem.r, elem.g, elem.b)
text.preamble(preamble)
unit.set(xscale=1.2)

c = canvas.canvas()
Пример #28
0
from pyx import canvas, color, deco, path, text, trafo, unit

text.set(text.LatexRunner)
color0 = color.rgb(0.8, 0, 0)
color1 = color.rgb(0, 0, 0.8)
text.preamble(
    r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{color}')
text.preamble(r'\definecolor{axis0}{rgb}{%s, %s, %s}' %
              (color0.r, color0.g, color0.b))
text.preamble(r'\definecolor{axis1}{rgb}{%s, %s, %s}' %
              (color1.r, color1.g, color1.b))
unit.set(xscale=1.6, wscale=1.5)

dx = 2
dy = 0.8
c = canvas.canvas()
for nx in range(3):
    for ny in range(3):
        c.text(nx * dx, -ny * dy,
               r'a[\textcolor{axis0}{%s}, \textcolor{axis1}{%s}]' % (ny, nx),
               [text.halign.center])
box = c.bbox()
pd = 0.1
xoff = box.left() - pd
pdx = 0.2
pdy = 0.5
c.stroke(
    path.curve(xoff,
               box.top() + pd, xoff - pdx,
               box.top() - pdy, xoff - pdx,
Пример #29
0
    c.stroke(path.line(x0, y0, x1, y1), [edgecolor])

projector = graph.graphxyz.central(60, -60, 25).point

unit.set(wscale=1.5, xscale=1.7)
text.set(text.LatexRunner, texenc='utf8')
text.preamble(r'''\usepackage[utf8x]{inputenc}
                  \usepackage{qswiss}''')
c = canvas.canvas()
nxmax = 7
nymax = 5
trans = 0.4

xoff = 5
yoff = 1
edgecolors = (color.rgb(0, 0, 0.8),
              color.rgb(0, 0.6, 0),
              color.rgb(0.8, 0, 0))
w = 0.3
facecolors = (color.rgb(w, w, 1),
              color.rgb(w, 1, w),
              color.rgb(1, w, w))
for nplane, (edgecolor, facecolor) in enumerate(zip(edgecolors, facecolors)):
    zoff = 1.04*(2-nplane)
    frontplane(xoff, yoff, zoff+1, nxmax, nymax, facecolor, edgecolor, trans)
    for nx in range(nxmax, -1, -1):
        for ny in range(nymax+1):
            corner(xoff+nx, yoff+ny, zoff, facecolor, edgecolor, trans,
                   nx != 0, ny != nymax)
    frontplane(xoff, yoff, zoff, nxmax, nymax, facecolor, edgecolor, trans)
x0, _ = projector(xoff+0.5*nxmax, 0, yoff)
Пример #30
0
text.set(cls=text.LatexRunner)
#text.set(docopt="12pt")
text.preamble(r"\usepackage{amsmath,amsfonts,amssymb}")
#text.preamble(r"\LARGE") #??

north = [text.halign.boxcenter, text.valign.top]
northeast = [text.halign.boxright, text.valign.top]
northwest = [text.halign.boxleft, text.valign.top]
south = [text.halign.boxcenter, text.valign.bottom]
southeast = [text.halign.boxright, text.valign.bottom]
southwest = [text.halign.boxleft, text.valign.bottom]
east = [text.halign.boxright, text.valign.middle]
west = [text.halign.boxleft, text.valign.middle]
center = [text.halign.boxcenter, text.valign.middle]

black = rgb(0., 0., 0.)
blue = rgb(0.1, 0.1, 0.9)
red = lred = rgb(1.0, 0.1, 0.1)
orange = rgbhex("F36B08")
green = rgb(0.0, 0.6, 0.0)
white = rgb(1., 1., 1.)
#shade = rgb(0.75, 0.55, 0)
grey = rgb(0.85, 0.85, 0.85)
darkgrey = rgb(0.65, 0.65, 0.65)
yellow = rgb(1., 1., 0.)

shade0 = rgbhex("c5e16f")
shade1 = rgbhex("a8d18a")
shade2 = rgbhex("539699")
shade3 = rgbhex("788696")
#shade4 = rgbhex("f1646c")  # hot pink. :P
Пример #31
0
from pyx import canvas, color, deco, path, style, text, unit

boxwidth = 3
height = 4
qi = 0.2*boxwidth
qf = 0.7*boxwidth
linecolor1 = color.rgb(0.8, 0, 0)
linecolor2 = color.rgb(0, 0, 0.8)

text.set(engine=text.LatexEngine)
text.preamble(r'''\usepackage[sfdefault,scaled=.85]{FiraSans}
                  \usepackage{newtxsf}''')
unit.set(vscale=1.2, wscale=1.3, xscale=1.5)
c = canvas.canvas()
c.fill(path.rect(0, 0, boxwidth, height), [color.rgb(0.92, 1, 0.92)])
for n in range(-1, 4):
    c.stroke(path.line(n*boxwidth, 0, n*boxwidth, height),
             [style.linewidth.THick, color.grey(0.4)])
poslinestyle = (style.linestyle.dashed, style.linewidth.Thick)
for n in range(-1, 2):
    q = qf + 2*n*boxwidth
    c.stroke(path.line(q, 0, q, height), [*poslinestyle, linecolor1])
    c.stroke(path.line(q, height+1.1, q, height+1.5), [style.linewidth.thick])
for n in range(-1, 2):
    q = -qf + (2*n+2)*boxwidth
    c.stroke(path.line(q, 0, q, height), [*poslinestyle, linecolor2])
    c.stroke(path.line(q, height+0.1, q, height+0.5), [style.linewidth.thick])
for n in range(0, 2):
    c.stroke(path.line(-qf+2*n*boxwidth, height+0.3,
                       -qf+2*(n+1)*boxwidth, height+0.3),
             [style.linewidth.thick, deco.barrow, deco.earrow])
Пример #32
0
    c.stroke(path.rect(x, y, kante, kante), [style.linewidth.thick])


text.set(text.LatexRunner)
text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}')
unit.set(xscale=0.85, wscale=1.2)
c = canvas.canvas()

kante = 1
dist = 0.15
punkte = 1
nrboxes = 3
nrpoints = 3

ldist = 0.05
boxcolor = color.rgb(1, 0.7, 0.4)
c.fill(path.rect(-0.3 * dist, -0.2, 7 * kante + 6.6 * dist, kante + 0.4),
       [boxcolor])
for n in range(nrboxes):
    x = n * (kante + dist)
    draw_square(x, 0, kante)
    c.text(x + ldist * kante, (1 - ldist) * kante, n, [text.valign.top])
    nstr = ""
    if n > 0: nstr = "%+i" % n
    c.text(x + (1 - 0.5 * ldist) * kante, ldist * kante, '-N' + nstr,
           [text.halign.right])
    x = (n + nrboxes) * (kante + dist) + dist + punkte
    draw_square(x, 0, kante)
    c.text(x + ldist * kante, (1 - ldist) * kante, 'N' + str(n - 3),
           [text.valign.top])
    c.text(x + (1 - 0.5 * ldist) * kante, ldist * kante, str(n - 3),
Пример #33
0
#
#    You should have received a copy of the GNU General Public License
#    along with this program (probably in a file named COPYING).
#    If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, print_function

from math import floor, fmod, fabs, atan2, atan, asin, sqrt, sin, cos
import datetime, calendar, ephem, pytz, pyx
from datetime import timedelta as TD
from pyx import path, canvas, color, style, text, graph
from scipy import optimize

from almanac_utils import *

mooncolorlight = color.rgb(0.6235294,0.6823529,0.827451)
mooncolordark = color.rgb(0.3450980,0.3764706,0.458823)

def S_of_R(R) :
    return (R*R*asin(1.0/R) - 1.0*sqrt(R*R-1.0))/ (PI)

def R_of_S(S) :
    def func(x) :
        return S_of_R(x)-S
    return optimize.bisect(func, 1.0000001, 100.0)

def first_quarter_moon(r, cx, cy) :
    p = path.path(path.moveto(cx, cy))
    p.append(path.arc(cx, cy, r, -90, 90))
    p.append(path.closepath())
    return p
Пример #34
0
def draw_graph(graph, vec, pts=None, name="output"):
    import pyx
    from pyx import path, deco, trafo, style, text, color, deformer
    from pyx.color import rgb, cmyk
    from pyx.color import rgbfromhexstring as rgbhex

    black = rgb(0., 0., 0.)
    blue = rgb(0., 0., 0.8)
    lred = rgb(1., 0.4, 0.4)
    red = rgb(1., 0.0, 0.0)
    green = rgb(0., 1.0, 0.0)
    lgreen = rgb(0.4, 1.0, 0.4)
    dgreen = rgb(0.0, 0.4, 0.0)
    white = rgb(1., 1., 1.)

    if pts is None:
        pts = pos_circ(graph)

    directed = isinstance(graph, (nx.DiGraph, nx.MultiDiGraph))

    #W = 10.
    #H = 10.

    R = 1.5
    r = 0.2

    c = pyx.canvas.canvas()

    for edge in graph.edges():
        src, tgt = edge

        x0, y0 = pts[src]
        x1, y1 = pts[tgt]

        color = black
        c.stroke(path.line(R * x0, R * y0, R * x1, R * y1), [color])

    for node in graph.nodes():
        x, y = pts[node]

        val = vec[node]
        assert int(val) == val

        #p = path.circle(R*x, R*y, 0.2)
        #c.fill(p, [white])

        p = path.circle(R * x, R * y, 0.10)
        c.fill(p, [black])

        if val > 0:
            color = dgreen
        elif val < 0:
            color = red
            val = -val
        else:
            continue

        for i in range(val):
            p = path.circle(R * x, R * y, (i + 2) * 0.15)
            c.stroke(p, [color, style.linewidth.THick])

    c.writePDFfile(name)
Пример #35
0
from pyx import canvas, color, deco, path, text, trafo

text.set(text.LatexRunner)
c = canvas.canvas()

markercolor = color.rgb(0.7, 0.5, 1.0)
utf8markercolor = color.rgb(1.0, 0.7, 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])
from math import atan2, pi, sqrt

from pyx import canvas, color, deco, path, text, trafo, unit

text.set(text.LatexRunner)
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()
Пример #37
0
 def draw(self, NC):
     x,y = NC.nucCenter(self.A, self.Z)
     NC.stroke(path.circle(x, y, 0.37*NC.dscale), [style.linewidth.THICk, rgb(1,1,0), color.transparency(1. - self.w)])
Пример #38
0
def make_alm_bg(bclc, begin_day_datetime, no_days, chart, obs, sun, sun_set, sun_rise) :
    ''' bclc: background clipped canvas'''
    # make a gradient of dark blue to black in the bg
    daycolor = color.rgb(0,82/255.0,137/255.0)
    nightcolor = color.rgb(0,0,0)
    DNcolgrad = color.lineargradient(daycolor,nightcolor)

    # First try: Drawing thick lines, does not really work.
    #for i in range(41) :
    #    horangle = 18.0*i/40
    #    obs.horizon = '-%d' % (horangle)
    #    eve_twi_grad = []
    #    mor_twi_grad = []
    #    for doy in range(no_days) :
    #        obs.date = begin_day + doy
    #        eve_twi_grad.append(obs.next_setting(sun))
    #        mor_twi_grad.append(obs.next_rising(sun))
    #    eve_twi_gradp = event_to_path(eve_twi_grad, chart)
    #    mor_twi_gradp = event_to_path(mor_twi_grad, chart)
    #    clc.stroke(eve_twi_gradp,[style.linewidth(0.24),DNcolgrad.getcolor(i/40.0)])
    #    clc.stroke(mor_twi_gradp,[style.linewidth(0.24),DNcolgrad.getcolor(i/40.0)])

    ## Second try: using rectangles for each day. Leads to a very big file
    ## and artifacts on screen, especially with antialiasing, hopefully fine
    ## when printed.
    #def draw_LR_colgrad_rect(canv, LLx, LLy, W, H, colgrad, n) :
    #    ''' Draw a rectangle consisting of n sub rectangles, each selecting its
    #        color from the given color gradient.'''
    #    for i in range(n) :
    #        llx = (i+0.0)/n * W + LLx
    #        lly = LLy
    #        # XXX multiplication by 1.02 below is to make sure that
    #        # XXX sub-rectangles overlap
    #        w = 1.0/n * W * 1.02
    #        h = H
    #        canv.fill(path.rect(llx, lly, w, h), [colgrad.getcolor((i+0.0)/n)])
    #
    #day_thickness = chart.height/no_days
    #for doy in range(no_days) :
    #    # XXX w/o the little addition of 0.2*ephem.hour below, we would have
    #    # XXX small empty triangular regions.
    #    SS = to_chart_coord(sun_set[doy]-0.2*ephem.hour, chart)
    #    ET = to_chart_coord(eve_twilight[doy], chart)
    #    MT = to_chart_coord(mor_twilight[doy], chart)
    #    SR = to_chart_coord(sun_rise[doy]+0.2*ephem.hour, chart)
    ## evening twilight to darkness
    #    LLx = SS[0]
    #    LLy = SS[1] - day_thickness/2.0
    #    W = ET[0] - SS[0]
    #    H = day_thickness
    #    draw_LR_colgrad_rect(clc, LLx, LLy, W, H, DNcolgrad, 18)
    ## darkness to morning twilight
    #    LLx = SR[0]
    #    W = MT[0] - SR[0] # XXX note: negative width
    #    draw_LR_colgrad_rect(clc, LLx, LLy, W, H, DNcolgrad, 18)

    ## Darkness between twilights
    #rev_eve_twilight = eve_twilight[:]
    #rev_eve_twilight.reverse()
    #darknesspath = event_to_path_no_check(rev_eve_twilight[:] + mor_twilight[:], chart)
    #darknesspath.append(path.closepath())
    #clc.stroke(darknesspath, [nightcolor])
    #clc.fill(darknesspath, [nightcolor])

    # Third try: Per Alp Akoğlu's request let's try to this right.
    # This way it will also be more general and easier to adapt to higher
    # latitudes where twilight never ends on some days of the year.

    gdata = []
    for doy in range(0, no_days, 10) :
        for tt in range(16*6+1) : # for 16 hours, every 10 minutes
            sun_tt = chart.ULcorn + doy + tt*ephem.minute*10
            x, y = to_chart_coord(sun_tt, chart)
            obs.date = sun_tt
            sun.compute(obs)
            z = sun.alt/ephem.degrees('-18:00:00')
            if z>1 : z=1
            if z<0 : z=0
            z = z*z # this makes the twilight more prominent
            gdata.append([x, y, z])

    # XXX I found the magic numbers below by trial error
    g = graph.graphxyz(size=1, xpos=11, ypos=16.73, xscale=12, yscale=18.31,
            projector=graph.graphxyz.parallel(-90, 90),
            x=graph.axis.linear(min=-1, max=chart.width+1, painter=None),
            #y=graph.axis.linear(min=-1, max=chart.height+1, painter=None),
            z=graph.axis.linear(min=-1, max=2, painter=None))
    g.plot(graph.data.points(gdata, x=1, y=2, z=3, color=3),
           [graph.style.surface(gradient=DNcolgrad,
                                gridcolor=None,
                                backcolor=color.rgb.black)])
    bclc.insert(g)
Пример #39
0
                   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


text.set(text.LatexRunner)
color0 = color.rgb(0.8, 0, 0)
color1 = color.rgb(0, 0, 0.8)
text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}')
text.preamble(r'\usepackage{color}')
text.preamble(r'\definecolor{axis0}{rgb}{%s, %s, %s}' %
              (color0.r, color0.g, color0.b))
text.preamble(r'\definecolor{axis1}{rgb}{%s, %s, %s}' %
              (color1.r, color1.g, color1.b))
unit.set(xscale=1.2, wscale=1.5)

c = canvas.canvas()
m1 = np.arange(4).reshape(2, 2)
c_m1 = matrix_22(m1)
m2 = np.arange(4, 8).reshape(2, 2)
c_m2 = matrix_22(m2)
m3 = np.dot(m1, m2)
from pyx import canvas, color, deco, path, style, text, unit

def draw_square(x, y, kante):
    c.stroke(path.rect(x, y, kante, kante), [style.linewidth.thick, deco.filled([color.grey(1)])])

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

kante = 1
dist = 0.2
nrboxes = 8

boxcolor = color.rgb(1, 0.7, 0.4)
c.fill(path.rect(-0.3*dist, -0.2, 5*kante+4.6*dist, kante+0.4), [boxcolor])
c.fill(path.rect(-0.3*dist+5*(kante+dist), -0.2, 3*kante+2.6*dist, kante+0.4), [boxcolor])

for n in range(nrboxes):
    x = n*(kante+dist)
    draw_square(x, 0, kante)
    c.text(x+0.5*kante, 0.5*kante, str(n), [text.halign.center, text.valign.middle])

for n in range(nrboxes+1):
    x = n*(kante+dist)
    c.stroke(path.line(x-0.5*dist, -0.5, x-0.5*dist, -0.1), [deco.earrow])
    c.text(x-0.5*dist, -0.7, str(n), [text.halign.center, text.valign.top])

c.text(2.5*kante+2*dist, kante+0.4, "a[0:5]", [text.halign.center])
c.text(6.5*kante+6*dist, kante+0.4, "a[5:8]", [text.halign.center])
Пример #41
0
from pyx import canvas, color, deco, path, text, trafo, unit

text.set(text.LatexRunner)
color0 = color.rgb(0.8, 0, 0)
color1 = color.rgb(0, 0, 0.8)
text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{color}')
text.preamble(r'\definecolor{axis0}{rgb}{%s, %s, %s}' % (color0.r, color0.g, color0.b))
text.preamble(r'\definecolor{axis1}{rgb}{%s, %s, %s}' % (color1.r, color1.g, color1.b))
unit.set(xscale=1.6, wscale=1.5)

dx = 2
dy = 0.8
c = canvas.canvas()
for nx in range(3):
    for ny in range(3):
        c.text(nx*dx, -ny*dy,
               r'a[\textcolor{axis0}{%s}, \textcolor{axis1}{%s}]' % (ny, nx),
               [text.halign.center])
box = c.bbox()
pd = 0.1
xoff = box.left()-pd
pdx = 0.2
pdy = 0.5
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,
Пример #42
0
from pyx import canvas, color, text

text.set(text.LatexRunner)
c = canvas.canvas()
t = text.text(0, 0, r"\sffamily\bfseries ?")
tblarge = t.bbox().enlarged(0.1)
c.fill(tblarge.path(), [color.rgb(0.8, 0.5, 0)])
c.insert(t, [color.grey(1)])

c.writePDFfile()
c.writeGSfile(device="png16m", resolution=600)
Пример #43
0
    def special(self, s, fontmap):
        x =  self.pos[_POS_H] * self.pyxconv
        y = -self.pos[_POS_V] * self.pyxconv
        if self.debug:
            self.debugfile.write("%d: xxx '%s'\n" % (self.filepos, s))
        if not s.startswith("PyX:"):
            logger.warning("ignoring special '%s'" % s)
            return

        # it is in general not safe to continue using the currently active font because
        # the specials may involve some gsave/grestore operations
        self.flushtext(fontmap)

        command, args = s[4:].split()[0], s[4:].split()[1:]
        if command == "color_begin":
            if args[0] == "cmyk":
                c = color.cmyk(float(args[1]), float(args[2]), float(args[3]), float(args[4]))
            elif args[0] == "gray":
                c = color.gray(float(args[1]))
            elif args[0] == "hsb":
                c = color.hsb(float(args[1]), float(args[2]), float(args[3]))
            elif args[0] == "rgb":
                c = color.rgb(float(args[1]), float(args[2]), float(args[3]))
            elif args[0] == "RGB":
                c = color.rgb(int(args[1])/255.0, int(args[2])/255.0, int(args[3])/255.0)
            elif args[0] == "texnamed":
                try:
                    c = getattr(color.cmyk, args[1])
                except AttributeError:
                    raise RuntimeError("unknown TeX color '%s', aborting" % args[1])
            elif args[0] == "pyxcolor":
                # pyx.color.cmyk.PineGreen or
                # pyx.color.cmyk(0,0,0,0.0)
                pat = re.compile(r"(pyx\.)?(color\.)?(?P<model>(cmyk)|(rgb)|(grey)|(gray)|(hsb))[\.]?(?P<arg>.*)")
                sd = pat.match(" ".join(args[1:]))
                if sd:
                    sd = sd.groupdict()
                    if sd["arg"][0] == "(":
                        numpat = re.compile(r"[+-]?((\d+\.\d*)|(\d*\.\d+)|(\d+))([eE][+-]\d+)?")
                        arg = tuple([float(x[0]) for x in numpat.findall(sd["arg"])])
                        try:
                            c = getattr(color, sd["model"])(*arg)
                        except TypeError or AttributeError:
                            raise RuntimeError("cannot access PyX color '%s' in TeX, aborting" % " ".join(args[1:]))
                    else:
                        try:
                            c = getattr(getattr(color, sd["model"]), sd["arg"])
                        except AttributeError:
                            raise RuntimeError("cannot access PyX color '%s' in TeX, aborting" % " ".join(args[1:]))
                else:
                    raise RuntimeError("cannot access PyX color '%s' in TeX, aborting" % " ".join(args[1:]))
            else:
                raise RuntimeError("color model '%s' cannot be handled by PyX, aborting" % args[0])

            self.beginsubpage([c])
        elif command == "color_end":
            self.endsubpage()
        elif command == "rotate_begin":
            self.beginsubpage([trafo.rotate_pt(float(args[0]), x, y)])
        elif command == "rotate_end":
            self.endsubpage()
        elif command == "scale_begin":
            self.beginsubpage([trafo.scale_pt(float(args[0]), float(args[1]), x, y)])
        elif command == "scale_end":
            self.endsubpage()
        elif command == "epsinclude":
            # parse arguments
            argdict = {}
            for arg in args:
                name, value = arg.split("=")
                argdict[name] = value

            # construct kwargs for epsfile constructor
            epskwargs = {}
            epskwargs["filename"] = argdict["file"]
            epskwargs["bbox"] = bbox.bbox_pt(float(argdict["llx"]), float(argdict["lly"]),
                                           float(argdict["urx"]), float(argdict["ury"]))
            if "width" in argdict:
                epskwargs["width"] = float(argdict["width"]) * unit.t_pt
            if "height" in argdict:
                epskwargs["height"] = float(argdict["height"]) * unit.t_pt
            if "clip" in argdict:
               epskwargs["clip"] = int(argdict["clip"])
            self.actpage.insert(epsfile.epsfile(x * unit.t_pt, y * unit.t_pt, **epskwargs))
        elif command == "marker":
            if len(args) != 1:
                raise RuntimeError("marker contains spaces")
            for c in args[0]:
                if c not in string.ascii_letters + string.digits + "@":
                    raise RuntimeError("marker contains invalid characters")
            if args[0] in self.actpage.markers:
                raise RuntimeError("marker name occurred several times")
            self.actpage.markers[args[0]] = x * unit.t_pt, y * unit.t_pt
        else:
            raise RuntimeError("unknown PyX special '%s', aborting" % command)
Пример #44
0
    return ce


c = canvas.canvas()
dx = 0.3
h = 4
w = 6.5
p = path.rect(-dx, -dx, w + 2 * dx, h + 2 * dx)
p = deformer.smoothed(0.5).deform(p)
c.fill(p, [color.grey(0.5), trafo.translate(0.05, -0.05)])

c1 = canvas.canvas([canvas.clip(p)])
c1.fill(p, [color.grey(0.9)])

r = 1
brown1 = color.rgb(148 / 255, 77 / 255, 48 / 255)
brown2 = color.rgb(193 / 255, 91 / 255, 49 / 255)
red1 = color.rgb(200 / 255, 0, 0)
red2 = color.rgb(220 / 255, 0.5, 0.5)
flame = color.rgb(248 / 255, 212 / 255, 27 / 255)
c2 = canvas.canvas()
c2.insert(ellipse(r, 0.5, brown1))
c2.fill(path.rect(-r, 0, 2 * r, 0.5 * r), [brown1])
c2.insert(ellipse(r, 0.5, brown2), [trafo.translate(0, 0.5 * r)])
c2.insert(ellipse(0.2 * r, 0.5, red1), [trafo.translate(0, 0.5 * r)])
c2.fill(path.rect(-0.2 * r, 0.5 * r, 0.4 * r, r), [red1])
c2.insert(ellipse(0.2 * r, 0.5, red2), [trafo.translate(0, 1.5 * r)])
c2.stroke(path.line(0, 1.5 * r, 0, 1.5 * r + 0.2), [style.linewidth.Thick])
c2a = canvas.canvas()
c2a.fill(
    path.path(path.moveto(0, 0), path.curveto(-0.1, -0.2, -0.3, -0.6, 0, -0.6),
Пример #45
0
axislen = 3

text.set(engine=text.LatexEngine)
text.preamble(r'''\usepackage[sfdefault,scaled=.85]{FiraSans}
                  \usepackage{newtxsf}
                  \usepackage{nicefrac}''')
unit.set(vscale=1.2, wscale=1.3, xscale=1.3)
c = canvas.canvas()
c.stroke(path.line(-0.2*axislen, 0, axislen, 0), [deco.earrow])
c.text(axislen+0.1, 0, 'Re($x$)', [text.valign.middle])
c.stroke(path.line(0, -0.2*axislen, 0, axislen), [deco.earrow])
c.text(0.2, axislen, 'Im($x$)', [text.valign.top])
r = 0.85*axislen
p = path.path(path.moveto(0, 0),
              path.lineto(r, 0),
              path.arc(0, 0, r, 0, 45),
              path.lineto(0, 0),
              path.closepath())
pathcolor = color.rgb(0.2, 0, 0.8)
c.stroke(p, [style.linewidth.thick, style.linejoin.round, pathcolor])
c.stroke(path.line(0, 0, 0.53*axislen, 0), [deco.earrow, pathcolor])
c.stroke(path.path(path.arc(0, 0, r, 0, 23)), [deco.earrow, pathcolor])
c.stroke(path.path(path.moveto(r/sqrt(2), r/sqrt(2)),
                   path.lineto(0.48*r/sqrt(2), 0.48*r/sqrt(2))),
         [deco.earrow, pathcolor])
c.text(0.33, 0.11, r'\footnotesize$\nicefrac{\pi}{4}$', [pathcolor])
c.stroke(path.path(path.arc(0, 0, 0.82, 0, 45)),
         [style.linewidth.thin, pathcolor])

c.writePDFfile()
    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


text.set(text.LatexRunner)
color0 = color.rgb(0.8, 0, 0)
color1 = color.rgb(0, 0, 0.8)
text.preamble(r'\usepackage[sfdefault,scaled=.85,lining]{FiraSans}\usepackage{newtxsf}')
text.preamble(r'\usepackage{color}')
text.preamble(r'\definecolor{axis0}{rgb}{%s, %s, %s}' % (color0.r, color0.g, color0.b))
text.preamble(r'\definecolor{axis1}{rgb}{%s, %s, %s}' % (color1.r, color1.g, color1.b))
unit.set(xscale=1.5, wscale=1.5)

c = canvas.canvas()
m1 = np.arange(4).reshape(2, 2)
c_m1 = matrix_22(m1)
m2 = np.arange(4, 8).reshape(2, 2)
c_m2 = matrix_22(m2)
m3 = np.dot(m1, m2)
c_m3 = matrix_22(m3, dx=0.7)
c.insert(c_m1)
Пример #47
0
pyplot.show()
quit()

from pyx import canvas, graph, text, color, style, trafo, unit
from pyx.graph import axis, key

text.set(mode="latex")
text.preamble(r"\usepackage{txfonts}")
figwidth = 12
gkey = key.key(pos=None, hpos=0.05, vpos=0.8)
xaxis = axis.linear(title=r"Time, \(t\)")
yaxis = axis.linear(title="Signal", min=-5, max=17)
g = graph.graphxy(width=figwidth, x=xaxis, y=yaxis, key=gkey)
plotdata = [graph.data.values(x=t, y=signal+offset, title=label) for label, signal, offset in (r"\(A(t) = \mathrm{square}(2\pi t/T)\)", A, 2.5), (r"\(B(t) = \mathrm{sawtooth}(\phi + 2 \pi t/T)\)", B, -2.5)]
linestyles = [style.linestyle.solid, style.linejoin.round, style.linewidth.Thick, color.gradient.Rainbow, color.transparency(0.5)]
plotstyles = [graph.style.line(linestyles)]
g.plot(plotdata, plotstyles)
g.plot(graph.data.values(x=t, y=listX, title="Blah"), plotstyles)
g.text(10*unit.x_pt, 0.56*figwidth, r"\textbf{Cross correlation of noisy anharmonic signals}")
g.text(10*unit.x_pt, 0.33*figwidth, "Phase shift: input \(\phi = %.2f \,\pi\), recovered \(\phi = %.2f \,\pi\)" % (phase_shift/pi, recovered_phase_shift/pi))
xxaxis = axis.linear(title=r"Time Lag, \(\Delta t\)", min=-1.5, max=1.5)
yyaxis = axis.linear(title=r"\(A(t) \star B(t)\)")
gg = graph.graphxy(width=0.2*figwidth, x=xxaxis, y=yyaxis)
plotstyles = [graph.style.line(linestyles + [color.rgb(0.2,0.5,0.2)])]
#gg.plot(graph.data.values(x=dt, y=xcorr), plotstyles)
gg.plot(graph.data.values(x=dt, y=xcorr, title="Blah"), plotstyles)
gg.stroke(gg.xgridpath(recovered_time_shift), [style.linewidth.THIck, color.gray(0.5), color.transparency(0.7)])
ggtrafos = [trafo.translate(0.75*figwidth, 0.45*figwidth)]
g.insert(gg, ggtrafos)
g.writePDFfile("so-xcorr-pyx")
                      path.lineto(*projector(nx, z+1, ny+1)),
                      path.lineto(*projector(nx, z+1, ny)),
                      path.closepath())
        c.fill(p, [facecolor, color.transparency(trans)])
    x0, y0 = projector(nx, z, ny)
    x1, y1 = projector(nx, z+1, ny)
    c.stroke(path.line(x0, y0, x1, y1), [edgecolor])

projector = graph.graphxyz.central(60, -50, 25).point

unit.set(wscale=1.5)
c = canvas.canvas()
nxmax = 7
nymax = 5
trans = 0.4
edgecolors = (color.rgb(0, 0, 0.8),
              color.rgb(0, 0.6, 0),
              color.rgb(0.8, 0, 0))
w = 0.3
facecolors = (color.rgb(w, w, 1),
              color.rgb(w, 1, w),
              color.rgb(1, w, w))
for nplane, (edgecolor, facecolor) in enumerate(zip(edgecolors, facecolors)):
    zoff = 1.04*(2-nplane)
    frontplane(zoff+1, nxmax, nymax, facecolor, edgecolor, trans)
    for nx in range(nxmax, -1, -1):
        for ny in range(nymax+1):
            corner(nx, ny, zoff, facecolor, edgecolor, trans,
                   nx != 0, ny != nymax)
    frontplane(zoff, nxmax, nymax, facecolor, edgecolor, trans)
    x0, y0 = projector(nxmax, zoff+1, nymax)
Пример #49
0
def slepc(Gx, Gz, Hx, Hz, Rx, Rz, Pxt, Qx, Pz, Tx, **kw):

    name = argv.get("name", "ex3.tmp.c")
    print("slepc: name=%s"%name)

    r = len(Rx)
    n = 2**r
    assert (r<40), "ugh"

    #code = Code("body.h")
    code = Code()

    code.append("#define DIMS (%d)"%n)

    code.append("static void matmult(PetscScalar *py, const PetscScalar *px, long nx)")
    code.begin()
    code.append("assert(DIMS == %d);"%n)
    code.append("assert(nx == %d);"%n)
    code.append("memset(py, 0, sizeof(PetscScalar)*nx);")

    offset = argv.get("offset", None)

    mz = len(Gz)
    t = None
    #excite = argv.excite
    #if excite is None:
    excite = kw.get("excite") or argv.excite

    if excite is not None:
        print("excite:", excite)
        if type(excite) is tuple:
            t = Tx[excite[0]]
            for i in range(1, len(excite)):
                t = (t + Tx[excite[i]])%2
        else:
            assert type(excite) in (int, int)
            t = Tx[excite]
        print("t:", shortstr(t))
        Gzt = dot2(Gz, t)
        print("Gzt:", shortstr(Gzt))

    weights = kw.get("weights")
    if weights is not None:
        assert len(weights)==len(Gx)

    RR = dot2(Gz, Rx.transpose())

    PxtQx = dot2(Pxt, Qx)
    gxs = [getnum(dot2(gx, PxtQx)) for gx in Gx]
    gxs.sort()
    uniq_gxs = list(set(gxs))
    uniq_gxs.sort()

    code.append("long v;")
    code.append("int k;")
    code.append("struct timeval t0, t1;")
    code.append("gettimeofday(&t0, NULL);")
    code.append("for(v=0; v<%d; v++)"%n)
    code.begin()
    code.append("double pxv = px[v];")
    if n >= 128:
        code.append(r'if((v+1) %% %d == 0)' % (n//128))
        code.begin()
        code.append("gettimeofday(&t1, NULL);")
        code.append("long delta = t1.tv_sec-t0.tv_sec;")
        code.append("if(delta>1)")
        code.append('{printf("[%lds]", delta);fflush(stdout);}')
        code.append('t0 = t1;')
        code.end()
    code.append("k = 0;")
    for i, row in enumerate(RR):
        if t is not None and Gzt[i]==1:
            code.append("k += (countbits_fast(v&%s)+1) %% 2;" % getnum(row))
        else:
            code.append("k += countbits_fast(v&%s) %% 2;" % getnum(row))
    cutoff = argv.cutoff
    if cutoff is not None:
        code.append("if(k>%d) continue; // <-------- continue" % cutoff)
    else:
        code.append("if(k>cutoff) continue; // <-------- continue")
    code.append("py[v] += pxv * (%d - 2*k);" % mz)

    if weights is None:
        for gx in uniq_gxs:
            s = '+'.join(['pxv']*gxs.count(gx))
            code.append("py[v^%s] += %s;" % (gx, s))
    else:
        gxs = [getnum(dot2(gx, PxtQx)) for gx in Gx]
        for i, gx in enumerate(gxs):
            code.append("py[v^%s] += %s*pxv;" % (gx, weights[i]))

    code.end()
    code.end()

    if name is None:
        return

    s = code.output()

    src = open("ex3.c").read()
    match = '\n#include "body.h"\n'
    assert match in src
    src = src.replace(match, s)
    assert name and name.endswith(".c")
    f = open(name, 'w')
    tag = hash(src)
    print(("hash(src):", tag))
    f.write(src)
    f.close()

    import socket
    host = socket.gethostname()
    if host == "bucket":
        cmd = "gcc MATCH.c -O3 -o MATCH -I/home/simon/local/petsc/arch-linux2-c-debug/include -I/home/simon/local/petsc/include/petsc/mpiuni -I/home/simon/local/petsc/include -I/home/simon/local/slepc-3.7.1/include -I/home/simon/local/slepc-3.7.1/arch-linux2-c-debug/include/ -L/home/simon/local/petsc/arch-linux2-c-debug/lib -L/home/simon/local/slepc-3.7.1/arch-linux2-c-debug/lib -lpetsc -lslepc"
    elif host == "hero":
        cmd = "gcc MATCH.c -O3 -o MATCH -I/usr/include/openmpi -I/usr/include/petsc -I/usr/include/slepc -lpetsc -lslepc -lmpi"
    else:
        cmd = "gcc -O3 MATCH.c -I/suphys/sburton/include/ -o MATCH -lpetsc -L$PETSC_DIR/$PETSC_ARCH/lib -L$SLEPC_DIR/$PETSC_ARCH/lib -lslepc"

    cmd = cmd.replace("MATCH.c", name)
    stem = name[:-2]
    cmd = cmd.replace("MATCH", stem)

    rval = os.system(cmd)
    assert rval == 0
    #print("exec:", hash(open(stem).read()))

    nev = argv.get("nev", 1)
    cmd = "./%s -eps_nev %d -eps_ncv %d -eps_largest_real" 

    if argv.plot:
        cmd += " -eps_view_vectors binary:evec.bin "

    cmd = cmd%(stem, nev, max(2*nev, 4))
    eps_tol = argv.get("eps_tol", 1e-4)
    if eps_tol is not None:
        cmd += " -eps_tol %s "%eps_tol

    #cmd += " -eps_type arnoldi -info -eps_monitor -eps_tol 1e-3"
    print(cmd)
    #rval = os.system(cmd)
    #assert rval == 0
    f = os.popen(cmd)
    s = f.read()
    #print(s)
    lines = s.split('\n')
    vals = []
    for line in lines:
        line = line.strip()
        flds = line.split()
        #print("parse", flds)
        try:
            a, b = flds
            a = float(a)
            b = float(b)
            vals.append(a)
        except:
            pass

    if not argv.plot:
        print(("vals:", vals))
        return vals

    assert argv.plot.endswith(".pdf")

    s = open("evec.bin").read()
    sz = 8*2**r

    if len(s)==sz+8:
        s = s[8:]
    elif len(s)==sz+16:
        s = s[16:]
    #elif len(s)==2*(sz+16): # got two vectors
    #    s = s[16:16+sz] # pick the first vector
    elif len(s)%(sz+16) == 0:
        count = len(s)/(sz+16)
#        s = s[16:16+sz] # pick the first vector
        ev_idx = argv.get("ev_idx", 0)
        s = s[16+ev_idx*(16+sz):(ev_idx+1)*(16+sz)]
    else:
        assert 0, "sz=%d but s=%s"%(sz, len(s))

    vec0 = numpy.fromstring(s, dtype=">d")
    assert len(vec0)==2**r

    assert excite is None

    print("graphing...")
    gz, n = Gz.shape
    xdata = []
    lookup = {}
    GzRxt = dot2(Gz, Rx.transpose())
    for i, v in enumerate(genidx((2,)*r)):
        v = array2(v)
        lookup[v.tobytes()] = i
        syndrome = dot2(GzRxt, v)
        value = gz - 2*syndrome.sum()
        xdata.append(value)

    pdata = {}
    ndata = {}
    my = 20. # mul y
    EPSILON = argv.get("EPSILON", 1e-6)

    def yfunc(y):
        y = log2(abs(y))
        y = int(round(my*y))
        return y

    for i in range(len(vec0)):
        x = xdata[i] # integer
        y = vec0[i]
        if abs(y) < EPSILON:
            continue
        if y > 0.:
            y = yfunc(y)
            pdata[x, y] = pdata.get((x, y), 0) + 1
        else:
            y = yfunc(y)
            ndata[x, y] = ndata.get((x, y), 0) + 1

    from pyx import graph, canvas, path, trafo, color, deco, text
    
    north = [text.halign.boxcenter, text.valign.top]
    northeast = [text.halign.boxright, text.valign.top]
    northwest = [text.halign.boxleft, text.valign.top]
    south = [text.halign.boxcenter, text.valign.bottom]
    southeast = [text.halign.boxright, text.valign.bottom]
    southwest = [text.halign.boxleft, text.valign.bottom]
    east = [text.halign.boxright, text.valign.middle]
    west = [text.halign.boxleft, text.valign.middle]
    center = [text.halign.boxcenter, text.valign.middle]
    
    c = canvas.canvas()
    sx = 0.4
    sy = 1.4
    tr = trafo.scale(sx, sy)

    green = color.rgb(0.2,0.6,0.2)
    brown = color.rgb(0.8,0.2,0.2)
    grey = color.rgb(0.4,0.4,0.4)
    lgrey = color.rgb(0.8,0.8,0.8)

    W = 2*gz
    H = log2(EPSILON)
    dy = 0.5 * 1.2/my

    X0 = -gz
    Y0 = 0.

    def showp(gx, radius):
        v = dot2(gx, PxtQx)
        syndrome = dot2(GzRxt, v)
        x = gz - 2*syndrome.sum()
        i = lookup[v.tobytes()]
        #print syndrome, syndrome.sum(), vec0[i]
        y = (1./my)*yfunc(vec0[i]) + 0.5*dy
        #y = 0.5*dy + log2(abs(vec0[i]))
        c.fill(path.circle(-x*sx, y*sy, radius), [lgrey])

    showp(zeros2(n), 0.8)
    for gx in Gx:
        showp(gx, 0.4)

    for gx0 in Gx:
      for gx1 in Gx:
        gx = (gx0+gx1)%2
        if gx.sum()==0:
            continue
        showp(gx, 0.2)

    for i in range(0, gz+1):
        x, y = X0+2*i, Y0
        c.stroke(path.line(x, y, x, y+H), [tr, grey])
        if i%2 == 0:
            c.text(x*sx, y*sy + 0.2, "%d"%i, south)

    c.stroke(path.line(X0, Y0, X0+1.0*W+3.5, Y0), [tr, deco.earrow(size=0.5)])
    c.stroke(path.line(X0, Y0, X0, Y0+1.0*H-0.5), [tr, deco.earrow(size=0.5)])

    y = 1.0
    i = 0
    while y > EPSILON:

        x = X0*sx
        y1 = sy*(1./my)*yfunc(y)
        c.stroke(path.line(x, y1, x-0.1, y1))

        c.text(x-0.3, y1, "%d"%i, east)

        y /= 2.
        i -= 1

    R = 0.15
    for key, value in list(pdata.items()):
        x, y = key
        y = y/my
        x = -x
        value = 1 + math.log(value)
        r = R*value
        #c.stroke(path.circle(x, y, r))
        #c.stroke(path.line(x, y, x+r, y), [brown, tr])
        c.fill(path.rect(x, y, r, dy), [brown, tr])

    for key, value in list(ndata.items()):
        x, y = key
        y = y/my
        x = -x
        value = 1 + math.log(value)
        r = R*value
        #c.stroke(path.circle(x, y, r))
        #c.stroke(path.line(x-r, y, x, y), [green, tr])
        c.fill(path.rect(x-r, y, r, dy), [green, tr])

    c.writePDFfile(argv.plot)


    if 0:
        print("graph..")
    
        g = graph.graphxy(
            width=16,
            x=graph.axis.linear(reverse=True),
            y=graph.axis.linear())
            #y=graph.axis.log(min=0.8*vec0.min(), max=1.2*vec0.max()))
    
        g.plot(graph.data.values(x=xdata, y=ydata))
        g.writePDFfile(argv.plot)
Пример #50
0
nx = int(w / unit.tocm(textwidth))
xoff = 0.5 * (w - 1.2 * textwidth * nx + 0.2 * textwidth)
for n, p in enumerate(primetimes):
    s = formattime(p)
    x = xoff + (n % nx) * 1.2 * textwidth
    y = 1.03 * h - (n // nx) * textheight * 1.4
    c2.text(x, y, s, [color.hsb(0.67, 0.4, 0.8)])
c.insert(c2)

r1 = 0.95 * h / 2
r2 = 0.8 * h / 2
for n in range(12):
    x = sin(radians(n * 30))
    y = cos(radians(n * 30))
    c.stroke(
        path.line(w / 2 + r1 * x, h / 2 + r1 * y, w / 2 + r2 * x,
                  h / 2 + r2 * y), [style.linewidth.THICk])
x = sin(radians(70))
y = cos(radians(70))
c.stroke(
    path.line(w / 2 - 0.1 * x, h / 2 - 0.1 * y, w / 2 + r1 * x,
              h / 2 + r1 * y),
    [style.linewidth.THICk, color.rgb(0.7, 0, 0)])
x = sin(radians(320))
y = cos(radians(320))
c.stroke(
    path.line(w / 2 - 0.1 * x, h / 2 - 0.1 * y, w / 2 + 0.6 * r1 * x,
              h / 2 + 0.6 * r1 * y),
    [style.linewidth.THICk, color.rgb(0.7, 0, 0)])
c.writeGSfile(device="png16m", resolution=300)
Пример #51
0
from qupy.condmat.models import build_model
from qupy.smap import SMap
from qupy.argv import argv

try:
    from pyx import canvas, path, deco, trafo, style, text, color, deformer
    from pyx.color import rgb

    if 0:
        text.set(mode="latex")
        text.set(docopt="12pt")
        text.preamble(r"\usepackage{amsmath,amsfonts,amssymb}")

        text.preamble(r"\def\ket #1{|#1\rangle}")

    black = rgb(0., 0., 0.)
    blue = rgb(0., 0., 0.8)
    lred = rgb(1., 0.4, 0.4)
    white = rgb(1., 1., 1.)
    grey = rgb(0.75, 0.75, 0.75)
    shade = grey
    shade0 = rgb(0.75, 0.75, 0.75)
    shade1 = rgb(0.80, 0.80, 0.80)
    shade2 = rgb(0.85, 0.85, 0.85)

    light_shade = rgb(0.85, 0.65, 0.1)
    light_shade = rgb(0.9, 0.75, 0.4)

    north = [text.halign.boxcenter, text.valign.top]
    northeast = [text.halign.boxright, text.valign.top]
    northwest = [text.halign.boxleft, text.valign.top]
Пример #52
0
    def special(self, s, fontmap):
        x = self.pos[_POS_H] * self.pyxconv
        y = -self.pos[_POS_V] * self.pyxconv
        if self.debug:
            self.debugfile.write("%d: xxx '%s'\n" % (self.filepos, s))
        if not s.startswith("PyX:"):
            logger.warning("ignoring special '%s'" % s)
            return

        # it is in general not safe to continue using the currently active font because
        # the specials may involve some gsave/grestore operations
        self.flushtext(fontmap)

        command, args = s[4:].split()[0], s[4:].split()[1:]
        if command == "color_begin":
            if args[0] == "cmyk":
                c = color.cmyk(float(args[1]), float(args[2]), float(args[3]),
                               float(args[4]))
            elif args[0] == "gray":
                c = color.gray(float(args[1]))
            elif args[0] == "hsb":
                c = color.hsb(float(args[1]), float(args[2]), float(args[3]))
            elif args[0] == "rgb":
                c = color.rgb(float(args[1]), float(args[2]), float(args[3]))
            elif args[0] == "RGB":
                c = color.rgb(
                    int(args[1]) / 255.0,
                    int(args[2]) / 255.0,
                    int(args[3]) / 255.0)
            elif args[0] == "texnamed":
                try:
                    c = getattr(color.cmyk, args[1])
                except AttributeError:
                    raise RuntimeError("unknown TeX color '%s', aborting" %
                                       args[1])
            elif args[0] == "pyxcolor":
                # pyx.color.cmyk.PineGreen or
                # pyx.color.cmyk(0,0,0,0.0)
                pat = re.compile(
                    r"(pyx\.)?(color\.)?(?P<model>(cmyk)|(rgb)|(grey)|(gray)|(hsb))[\.]?(?P<arg>.*)"
                )
                sd = pat.match(" ".join(args[1:]))
                if sd:
                    sd = sd.groupdict()
                    if sd["arg"][0] == "(":
                        numpat = re.compile(
                            r"[+-]?((\d+\.\d*)|(\d*\.\d+)|(\d+))([eE][+-]\d+)?"
                        )
                        arg = tuple(
                            [float(x[0]) for x in numpat.findall(sd["arg"])])
                        try:
                            c = getattr(color, sd["model"])(*arg)
                        except TypeError or AttributeError:
                            raise RuntimeError(
                                "cannot access PyX color '%s' in TeX, aborting"
                                % " ".join(args[1:]))
                    else:
                        try:
                            c = getattr(getattr(color, sd["model"]), sd["arg"])
                        except AttributeError:
                            raise RuntimeError(
                                "cannot access PyX color '%s' in TeX, aborting"
                                % " ".join(args[1:]))
                else:
                    raise RuntimeError(
                        "cannot access PyX color '%s' in TeX, aborting" %
                        " ".join(args[1:]))
            else:
                raise RuntimeError(
                    "color model '%s' cannot be handled by PyX, aborting" %
                    args[0])

            self.beginsubpage([c])
        elif command == "color_end":
            self.endsubpage()
        elif command == "rotate_begin":
            self.beginsubpage([trafo.rotate_pt(float(args[0]), x, y)])
        elif command == "rotate_end":
            self.endsubpage()
        elif command == "scale_begin":
            self.beginsubpage(
                [trafo.scale_pt(float(args[0]), float(args[1]), x, y)])
        elif command == "scale_end":
            self.endsubpage()
        elif command == "epsinclude":
            # parse arguments
            argdict = {}
            for arg in args:
                name, value = arg.split("=")
                argdict[name] = value

            # construct kwargs for epsfile constructor
            epskwargs = {}
            epskwargs["filename"] = argdict["file"]
            epskwargs["bbox"] = bbox.bbox_pt(float(argdict["llx"]),
                                             float(argdict["lly"]),
                                             float(argdict["urx"]),
                                             float(argdict["ury"]))
            if "width" in argdict:
                epskwargs["width"] = float(argdict["width"]) * unit.t_pt
            if "height" in argdict:
                epskwargs["height"] = float(argdict["height"]) * unit.t_pt
            if "clip" in argdict:
                epskwargs["clip"] = int(argdict["clip"])
            self.actpage.insert(
                epsfile.epsfile(x * unit.t_pt, y * unit.t_pt, **epskwargs))
        elif command == "marker":
            if len(args) != 1:
                raise RuntimeError("marker contains spaces")
            for c in args[0]:
                if c not in string.ascii_letters + string.digits + "@":
                    raise RuntimeError("marker contains invalid characters")
            if args[0] in self.actpage.markers:
                raise RuntimeError("marker name occurred several times")
            self.actpage.markers[args[0]] = x * unit.t_pt, y * unit.t_pt
        else:
            raise RuntimeError("unknown PyX special '%s', aborting" % command)
Пример #53
0

#####
#
# New part 12 Apr 2009 - a multitude of lines on the thermodynamics graphs
# Modified 11 May 2009 for turbulence runs
#
#####
if varstring.startswith("not implemented yet - 24 May 2010"):
# if varstring.startswith("n-T"):
    from pyx.style import linestyle, linewidth
    from pyx.color import transparency, rgb
    from pyx.graph.style import line
    from pyx.graph import data
    line.defaultlineattrs += [linewidth.thick, transparency(0.5)]
    myred = rgb(0.5, 0.0, 0.0)
    mygreen = rgb(0.0, 0.5, 0.0)
    myblue = rgb(0.0, 0.0, 0.5)
#     # Free-fall time < 1.e5 years
#     g.plot(data.function("x(y) = 5.31"), [line([linestyle.dashed])])
#     # Plot contours of Jeans instability
#     for MJeans in (0.0, 1.0):
#	g.plot(data.function("y(x) = 0.491 + 0.6667*MJeans + 0.333*(x-3.0)",
#			     context=locals()),
#	       [line([linestyle.solid, linewidth.Thick])])
    # Plot contours of equilibrium T
    execdir = os.path.dirname(sys.argv[0])
    for col, Av, D in [
	[myblue, 0.0, 0.2],
	[mygreen, 3.0, 0.2],
	[myred, 30.0, 0.2],
Пример #54
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)