Exemplo n.º 1
0
def corner(nx, ny, z, facecolor, edgecolor, trans, xdir, ydir):
    if xdir:
        p = path.path(path.moveto(*projector(nx, z, ny)),
                      path.lineto(*projector(nx - 1, z, ny)),
                      path.lineto(*projector(nx - 1, z + 1, ny)),
                      path.lineto(*projector(nx, z + 1, ny)), path.closepath())
        c.fill(p, [facecolor, color.transparency(trans)])
    if ydir:
        p = path.path(path.moveto(*projector(nx, z, ny)),
                      path.lineto(*projector(nx, z, ny + 1)),
                      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])
Exemplo n.º 2
0
def server(r, servercolor=color.rgb(0.5, 0.5, 0.8), transparency=0):
    c = canvas.canvas()
    c.fill(path.circle(0, 0, r), [
        servercolor,
        color.transparency(transparency),
        trafo.scale(1, 0.5).translated(0, 0.5 * r)
    ])
    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,
        color.transparency(transparency),
        trafo.scale(1, 0.5).translated(0, 0.5 * r - 0.08 * r)
    ])
    return c
Exemplo n.º 3
0
def timeslice(x, y, transparency=0.0, label="", W=3):
    dopath(
        [(-1.1, y0), (-0.1, y1), (W + 0.2, y1), (W - 0.8, y0)],
        fill=[shade, color.transparency(0.3)],
        extra=[trafo.translate(x, y)],
        closepath=True,
    )
    if label:
        c.text(W + 0.2, 0.0, label, west + [trafo.translate(x, y)])
def corner(nx, ny, z, facecolor, edgecolor, trans, xdir, ydir):
    if xdir:
        p = path.path(path.moveto(*projector(nx, z, ny)),
                      path.lineto(*projector(nx-1, z, ny)),
                      path.lineto(*projector(nx-1, z+1, ny)),
                      path.lineto(*projector(nx, z+1, ny)),
                      path.closepath())
        c.fill(p, [facecolor, color.transparency(trans)])
    if ydir:
        p = path.path(path.moveto(*projector(nx, z, ny)),
                      path.lineto(*projector(nx, z, ny+1)),
                      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])
Exemplo n.º 5
0
def loop(x0, y0, r1, theta0, theta1, tpy):
    t = Turtle(x0, y0, theta0)
    #theta = 0.55*pi
    theta = theta1
    r2 = 2*r1*sin(theta - 0.5*pi)
    t.penup().fwd(0.1*r1).pendown()
    t.fwd(0.9*r1).right(theta).fwd(r2).right(theta).fwd(0.9*r1) 
    t.stroke([deco.earrow(), 
        deformer.smoothed(4.0), style.linewidth.Thick,
        color.transparency(tpy), tr])
Exemplo n.º 6
0
def frontplane(z, nxmax, mymax, facecolor, edgecolor, trans):
    p = path.path(path.moveto(*projector(0, z, 0)),
                  path.lineto(*projector(nxmax, z, 0)),
                  path.lineto(*projector(nxmax, z, nymax)),
                  path.lineto(*projector(0, z, nymax)), path.closepath())
    c.fill(p, [facecolor, color.transparency(trans)])
    c.stroke(p, [edgecolor])
    for nx in range(1, nxmax):
        x0, y0 = projector(nx, z, 0)
        x1, y1 = projector(nx, z, nymax)
        c.stroke(path.line(x0, y0, x1, y1), [edgecolor])
    for ny in range(1, nymax):
        x0, y0 = projector(0, z, ny)
        x1, y1 = projector(nxmax, z, ny)
        c.stroke(path.line(x0, y0, x1, y1), [edgecolor])
def frontplane(z, nxmax, mymax, facecolor, edgecolor, trans):
    p = path.path(path.moveto(*projector(0, z, 0)),
                  path.lineto(*projector(nxmax, z, 0)),
                  path.lineto(*projector(nxmax, z, nymax)),
                  path.lineto(*projector(0, z, nymax)),
                  path.closepath())
    c.fill(p, [facecolor, color.transparency(trans)])
    c.stroke(p, [edgecolor])
    for nx in range(1, nxmax):
        x0, y0 = projector(nx, z, 0)
        x1, y1 = projector(nx, z, nymax)
        c.stroke(path.line(x0, y0, x1, y1), [edgecolor])
    for ny in range(1, nymax):
        x0, y0 = projector(0, z, ny)
        x1, y1 = projector(nxmax, z, ny)
        c.stroke(path.line(x0, y0, x1, y1), [edgecolor])
Exemplo n.º 8
0
c.insert(c_m1)
c.insert(c_m2, [trafo.translate(c_m1.bbox().width() + 0.1, 0)])
end = c_m1.bbox().right() + c_m2.bbox().width() + 0.1
dist2 = 0.6
c.insert(c_m3, [trafo.translate(end + dist2 - c_m3.bbox().left(), 0)])
ycenter = 0.5 * (c_m1.bbox().top() + c_m1.bbox().bottom())
for dy in (-0.05, 0.05):
    c.stroke(
        path.line(end + 0.15, ycenter + dy, end + dist2 - 0.15, ycenter + dy))

c_tot = canvas.canvas()
for y in range(4):
    c_tot.insert(c, [trafo.translate(0, 1.5 * y)])

dx = 0.2
colorprops = [color.rgb(0.8, 0.2, 0), color.transparency(0.2)]
arrowprops = [deco.earrow] + colorprops
for lineno, (ny, nx) in enumerate(product((0, 1), repeat=2)):
    yoff = 1.5 * (3 - lineno) + 0.17
    c_tot.stroke(path.line(-dx, yoff - 0.5 * ny, 0.5 + dx, yoff - 0.5 * ny),
                 arrowprops)
    xoff = c_m1.bbox().width() + 0.1 + 0.5 * nx
    c_tot.stroke(path.line(xoff, yoff + 0.2, xoff, yoff - 0.7), arrowprops)
    wd = 0.6
    ht = 0.5
    xoff = end + dist2 - c_m3.bbox().left() + 0.7 * nx
    c_tot.stroke(
        path.rect(xoff - 0.5 * wd, yoff - 0.5 * ny - 0.5 * ht, wd, ht),
        colorprops)
c_tot.writePDFfile()
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
    def plot_scores(self,
                    fname,
                    binsize=10000,
                    show_lads=False,
                    show_dips=False,
                    show_means=False,
                    show_partitions=False):
        """Plot a PDF of score data with optional indicators of partitions, "
        partition means, LADs, and DIPs."""
        # Make sure that the PYX module is available
        try:
            from pyx import canvas, path, document, color, text, style
        except ImportError:
            self.logger.warn("The package pyx must be installed to plot data")
            return None
        # Make sure desired data is present
        if self.focus != 'binned':
            if (self.data is None or numpy.nanmin(self.data['score']) == 0):
                self.logger.warn("Requested data is not available for "
                                 "plotting")
                return None
        elif (self.binned is None or numpy.nanmin(self.binned['score']) == 0):
            self.logger.warn("Requested binned data is not available for "
                             "plotting")
            return None
        self.logger.info("Plotting data")
        # Determine which data to use
        if self.focus == 'binned':
            data = self.binned
            chr_indices = self.bin_indices
        else:
            data = self.data
            chr_indices = self.chr_indices
        # Plot each chromosome on its own page
        pages = []
        for i in range(self.chroms.shape[0]):
            valid = numpy.where(
                numpy.logical_not(
                    numpy.isnan(
                        data['score'][chr_indices[i]:chr_indices[i + 1]])))[0]
            valid += chr_indices[i]
            # Skip chromosomes without valid data
            if valid.shape[0] == 0:
                continue
            mids = (data['coords'][valid, 0] + data['coords'][valid, 1]) // 2
            if binsize > 0:
                # Bin data to the resolution requested
                start = (mids[0] // binsize) * binsize
                stop = (mids[-1] // binsize + 1) * binsize
                indices = (mids - start) // binsize
                counts = numpy.bincount(indices)
                Ys = numpy.bincount(
                    indices, weights=data['score'][valid]) / numpy.maximum(
                        1, counts)
                mids = (start + numpy.arange(
                    (stop - start) // binsize) * binsize + binsize / 2)
                valid = numpy.where(counts > 0)[0]
                Ys = Ys[valid]
                mids = mids[valid]
                coords = numpy.zeros((Ys.shape[0], 2), dtype=numpy.float64)
                coords[:, 0] = start + valid * binsize
                coords[:, 1] = start + valid * binsize + binsize
            else:
                Ys = data['score'][valid]
                start = data['coords'][valid, 0]
                stop = data['coords'][valid[-1], 1]
                coords = data['coords'][valid, :].astype(numpy.float64)
            c = canvas.canvas()
            width = (stop - start) / 5000000.
            height = 5.
            maxscore = numpy.amax(numpy.abs(Ys))
            if show_means and self.partitions is not None:
                where = numpy.where(self.partitions['chr'] == i)[0]
                maxscore = max(
                    maxscore,
                    numpy.amax(numpy.abs(self.partitions['score'][where])))
            Ys /= maxscore
            Ys *= height * 0.5
            Xs = (mids - start) / float(stop - start) * width
            coords -= start
            coords /= (stop - start)
            coords *= width
            lpath = path.path(path.moveto(0, 0))
            for j in range(valid.shape[0]):
                if j == 0 or valid[j] - valid[j - 1] > 1:
                    lpath.append(path.lineto(coords[j, 0], 0))
                lpath.append(path.lineto(Xs[j], Ys[j]))
                if j == Xs.shape[0] - 1 or valid[j + 1] - valid[j] > 1:
                    lpath.append(path.lineto(coords[j, 1], 0))
            lpath.append(path.lineto(width, 0))
            lpath.append(path.closepath())

            # add lads if requests and already determined
            if show_lads and self.LADs is not None:
                where = numpy.where(self.LADs['chr'] == i)[0]
                if where.shape[0] == 0:
                    continue
                for j in where:
                    X0 = ((self.LADs['coords'][j, 0] - start) /
                          float(stop - start) * width)
                    X1 = ((self.LADs['coords'][j, 1] - start) /
                          float(stop - start) * width)
                    c.fill(path.rect(X0, -height / 2, X1 - X0, height),
                           [color.gray(0.85)])

            # add dips if requests and already determined
            if show_dips and self.DIPs is not None:
                print(self.DIPs.shape)
                where = numpy.where(self.DIPs['chr'] == i)[0]
                if where.shape[0] == 0:
                    continue
                for j in where:
                    X0 = ((self.DIPs['coords'][j, 0] - start) /
                          float(stop - start) * width)
                    X1 = ((self.DIPs['coords'][j, 1] - start) /
                          float(stop - start) * width)
                    c.fill(path.rect(X0, -height / 2, X1 - X0, height),
                           [color.rgb.red])

            # add signal track
            c.fill(lpath)
            c.stroke(path.line(0, -height / 2, width, -height / 2))

            # add partition mean line if requested and already determined
            if show_means and self.partitions is not None:
                where = numpy.where(self.partitions['chr'] == i)[0]
                coords = ((self.partitions['coords'][where, :] - start) /
                          float(stop - start) * width)
                Ys = ((self.partitions['score'][where] / maxscore) * height *
                      0.5)
                lpath = path.path(path.moveto(0, 0))
                for j in range(Ys.shape[0]):
                    if j == 0 or coords[j, 0] != coords[j - 1, 1]:
                        lpath.append(path.lineto(coords[j, 0], 0))
                    lpath.append(path.lineto(coords[j, 0], Ys[j]))
                    lpath.append(path.lineto(coords[j, 1], Ys[j]))
                    if (j == Ys.shape[0] - 1
                            or coords[j, 1] != coords[j + 1, 0]):
                        lpath.append(path.lineto(coords[j, 1], 0))
                lpath.append(path.lineto(width, 0))
                c.stroke(lpath, [
                    color.rgb.blue, style.linewidth.THIN,
                    color.transparency(0.5)
                ])

            # add partition lines if requested and already determined
            if show_partitions and self.partitions is not None:
                where = numpy.where(self.partitions['chr'] == i)[0]
                coords = ((self.partitions['coords'][where, :] - start) /
                          float(stop - start) * width)
                for j in range(coords.shape[0] - 1):
                    c.stroke(
                        path.line(coords[j, 1], -height * 0.5, coords[j, 1],
                                  height * 0.5), [style.linewidth.THin])
                    if coords[j, 1] != coords[j + 1, 0]:
                        c.stroke(
                            path.line(coords[j + 1, 0], -height * 0.5,
                                      coords[j + 1, 0], height * 0.5),
                            [style.linewidth.THin])

            # add coordinates
            for j in range(int(numpy.ceil(start / 10000000.)),
                           int(numpy.floor(stop / 10000000.) + 1)):
                X = (j * 10000000. - start) / (stop - start) * width
                c.stroke(path.line(X, -height / 2, X, -height / 2 - 0.2))
                c.text(X, -height / 2 - 0.25, "%i Mb" % (j * 10),
                       [text.halign.center, text.valign.top])
            c.text(width * 0.5, -height / 2 - 0.6,
                   "%s" % self.chroms[i].replace('_', ' '),
                   [text.halign.center, text.valign.top])
            pages.append(document.page(c))
        doc = document.document(pages)
        doc.writePDFfile(fname)
Exemplo n.º 12
0
def dorect(x, y, W=2, H=0.6):
    dopath([(x-1.1, y-H), (x-0.1, y+H), (x+W+.2, y+H), (x+W-0.8, y-H)],
        fill=[shade, color.transparency(0.3)],
        closepath=True)
Exemplo n.º 13
0
from pyx import canvas, color, deformer, path, text, trafo, unit

text.set(text.LatexRunner)
text.preamble(r'''\usepackage[scaled=0.85,lining]{FiraMono}
                  \usepackage[utf8]{inputenc}''')
pistring = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852'
char_per_line = 25
pistring = ' '.join(
    [pistring[n * char_per_line:(n + 1) * char_per_line] for n in range(10)])
unit.set(xscale=1.45)

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)])
c.fill(p, [color.grey(0.9)])
c.text(0, 0, r'\noindent\texttt{{{}}}'.format(pistring),
       [text.valign.bottom, text.parbox(5)])
c.text(0.5 * w, 0.5 * h, r'\Huge $\pi$', [
    text.halign.center, text.valign.middle,
    color.hsb(0.66, 0.8, 1),
    color.transparency(0.2),
    trafo.scale(5.8)
])

c.writePDFfile()
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)
c_m2 = matrix_22(m2)
m3 = np.dot(m1, m2)
c_m3 = matrix_22(m3, dx=0.7)
c.insert(c_m1)
c.insert(c_m2, [trafo.translate(c_m1.bbox().width()+0.1, 0)])
end  = c_m1.bbox().right()+c_m2.bbox().width()+0.1
dist2 = 0.6
c.insert(c_m3, [trafo.translate(end+dist2-c_m3.bbox().left(), 0)])
ycenter = 0.5*(c_m1.bbox().top()+c_m1.bbox().bottom())
for dy in (-0.05, 0.05):
    c.stroke(path.line(end+0.15, ycenter+dy,
                       end+dist2-0.15, ycenter+dy))

c_tot = canvas.canvas()
for y in range(4):
    c_tot.insert(c, [trafo.translate(0, 1.5*y)])

dx = 0.2
colorprops = [color.rgb(0.8, 0.2, 0), color.transparency(0.2)]
arrowprops = [deco.earrow]+colorprops
for lineno, (ny, nx) in enumerate(product((0, 1), repeat=2)):
    yoff = 1.5*(3-lineno)+0.17
    c_tot.stroke(path.line(-dx, yoff-0.5*ny, 0.5+dx, yoff-0.5*ny), arrowprops)
    xoff = c_m1.bbox().width()+0.1+0.5*nx
    c_tot.stroke(path.line(xoff, yoff+0.2, xoff, yoff-0.7), arrowprops)
    wd = 0.55
    ht = 0.45
    xoff = end+dist2-c_m3.bbox().left()+0.7*nx
    c_tot.stroke(path.rect(xoff-0.5*wd, yoff-0.5*ny-0.5*ht, wd, ht), colorprops)
c_tot.writePDFfile()
Exemplo n.º 16
0
pyplot.plot(t, )
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")
Exemplo n.º 17
0
	   [pyx.trafo.scale(0.7), pyx.trafo.rotate(ang)] + mycolor)


#####
#
# 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],
Exemplo n.º 18
0
        cval = c[nx * nlen + mx, ny * nlen + my]
        data.append((cval.real, cval.imag, partialdata[mx, my]))
    procdict[(nx, ny)] = procid
procids = set(procdict.values())
colors = [
    color.hsb(n / (len(procids) - 1) * 0.67, 1, 1) for n in range(len(procids))
]
proccolors = dict(zip(procids, colors))

text.set(text.LatexRunner)
text.preamble(r'\usepackage{arev}\usepackage[T1]{fontenc}')
g = graph.graphxy(width=8,
                  height=8,
                  x=graph.axis.lin(title=r'$\mathrm{Re}(c)$'),
                  y=graph.axis.lin(title=r'$\mathrm{Im}(c)$'))
g.plot(graph.data.points(data, x=1, y=2, color=3),
       [graph.style.density(keygraph=None)])

dx = (xmax - xmin) / n
dy = (ymax - ymin) / n
for k, v in procdict.items():
    nx, ny = k
    tilecolor = proccolors[v]
    xll, yll = g.pos(xmin + dx * nx, ymin + dy * ny)
    xur, yur = g.pos(xmin + dx * (nx + 1), ymin + dy * (ny + 1))
    g.fill(path.rect(xll, yll, xur - xll, yur - yll),
           [deco.stroked([color.grey(0)]), tilecolor,
            color.transparency(0.5)])
g.writePDFfile()
# convert to PNG with Gimp to keep transparency