Ejemplo n.º 1
0
x = m + 2*dw

y = 20*dr

c.text(x, y,
r"""Braiding with Fibonacci anyons
can realize universal quantum computing, so
we don't expect to be able to simulate
every instance in a reasonable amount of time.
Instead we bound the compute time, and any
instance that exceeds this bound is considered
``missing'' data:""",
[text.parbox(dw-2*m),])

y -= 18*dr
try:
    c.insert(epsfile.epsfile(x, y, "qip/fibonacci.eps", width=(dw-2*m)))
except IOError, e:
    print e


# -------------------------------------------------------------------


the_can = canvas.canvas()
the_can.insert(c, [trafo.scale(SCALE)])

the_can.writeEPSfile("poster")
the_can.writePDFfile("poster")

Ejemplo n.º 2
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)
Ejemplo n.º 3
0
#ax.annotate("B", (0,1.), xycoords=(ax.get_yaxis().get_label(), "axes fraction"), 
#             fontsize=14) 

#suptitle("Figure S%i"%sfn)
figures.append(fig)

# <codecell>

#Principles taken from http://matplotlib.1069221.n5.nabble.com/svg-in-plot-td27904.html
fig.savefig("ChildrenandTime.eps")

from pyx import canvas, epsfile 

c = canvas.canvas() 
# load both external files 
c.insert(epsfile.epsfile(0, 0, "ChildrenandTime.eps")) 
c.insert(epsfile.epsfile(4, 17, "Parent-nChild-Diagram1.eps", scale=1.4)) 
c.insert(epsfile.epsfile(13.5, 17, "Parent-nChild-Diagram2.eps", scale=1.4)) 

# save generated EPS files 
c.writeEPSfile("FigureS3") 

sfn+=1

# <codecell>

import matplotlib.image as mpimg
img=mpimg.imread('/data/alstottjd/Langley/Payout_diagram.png')

fig = plt.figure()
imgplot = plt.imshow(img)
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def plot(logn, logt, opsn, opst, pages, graphs, no_clean, debug):

    fname = str(datetime.now()).replace(' ', '_')

    plt.rc('font', family='Input Mono')
    cwd = sys.path[0]

    try:
        os.mkdir(cwd + '/../tmp')
        if debug > 0:
            err.log('../tmp/ directory created for temporary storage.')
    except FileExistsError:
        if debug > 0:
            err.log(
                '../tmp/ directory exists; using it for temporary storage.')

    new_logn = []
    new_logt = []
    new_pairs = set()
    for i, t in enumerate(logt):
        p = (t, logn[i])
        if p not in new_pairs:
            new_logn.append(logn[i])
            new_logt.append(t)

    logn = new_logn
    logt = new_logt

    xmax = int(max(logn))
    xmin = int(min(logn))
    ymax = int(max(logt))
    ymin = int(min(logt))
    xrng = max(xmax - xmin, 0)
    yrng = max(ymax - ymin, 0)

    roots = {}
    t_counts = np.zeros(yrng + 1)
    n_counts = np.zeros(xrng + 1)
    t_pairs = set()
    n_pairs = set()

    ylist = range(ymin, ymax + 1)
    xlist = range(xmin, xmax + 1)

    xticker_base = 1.0
    if xrng > ticker.MultipleLocator.MAXTICKS - 50:
        xticker_base = xrng / ticker.MultipleLocator.MAXTICKS * 1.5

    yticker_base = 1.0
    if yrng > ticker.MultipleLocator.MAXTICKS - 50:
        yticker_base = yrng / ticker.MultipleLocator.MAXTICKS * 1.5

    yloc = ticker.MultipleLocator(base=yticker_base)
    xloc = ticker.MultipleLocator(base=xticker_base)

    fig = plt.figure(figsize=(10, 10))

    fontP = FontProperties()
    fontP.set_size('small')

    gs = gridspec.GridSpec(2, 2)

    kx = dict(aspect='auto')

    ax_main = plt.subplot(gs[1, 0], **kx)
    ax_count = plt.subplot(gs[1, 1], **kx)
    ax_vcount = plt.subplot(gs[0, 0], **kx)
    ax_none = plt.subplot(gs[0, 1], **kx)
    ax_small = plt.axes([0.73, 0.11, 0.17, 0.17])
    ax_main.yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    ax_main.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    ax_count.yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    ax_count.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    ax_vcount.yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    ax_vcount.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    plt.xticks([])
    plt.yticks([])
    ax_small.yaxis.set_minor_locator(yloc)
    ax_small.yaxis.grid(True, which='minor', color=colors.h_light_gray)
    ax_small.set_axisbelow(True)

    gs.update(wspace=0.00, hspace=-0.00)

    log_marker = 'x'
    if len(opst) > 50:
        if debug > 1:
            err.log('Input size is ' + str(len(opst)) + ', using marker \'o\'')
        log_marker = 'o'
    elif debug > 1:
        err.log('Input size is ' + str(len(opst)) + ', using marker \'x\'')

    if pages:
        partial_logn = []
        partial_logt = []
        partial_opst = []
        partial_opsn = []
        last_logt_i = 0
        logt_i = 0

        for i in range(0, len(opst)):
            if debug > 1:
                err.log("Generating data plot number " + str(i))

            partial_opst = [opst[i]]
            partial_opsn = [opsn[i]]
            op_t = opst[i]

            last_logt_i = logt_i + 1
            roots = {}
            while logt_i + 1 < len(logt) and logt[logt_i + 1] <= op_t:
                logt_i += 1
                roots[logt[last_logt_i]] = logn[last_logt_i]

            partial_logn = []
            partial_logt = []
            for j in range(last_logt_i, logt_i + 1):
                partial_logt.append(logt[j])
                partial_logn.append(logn[j])

            if debug > 1:
                err.log("Starting plot generation")

            add_plot(fname, cwd, fig, partial_logn, partial_logt, partial_opsn,
                     partial_opst, t_counts, n_counts, t_pairs, n_pairs,
                     log_marker, xloc, yloc, ax_main, ax_count, ax_vcount,
                     ax_none, ax_small, xmax, xmin, ymax, ymin, xrng, yrng,
                     xlist, ylist, roots, graphs, i, debug)
            if len(graphs) > 0:
                del graphs[0]
    else:
        for i, t in enumerate(logt):
            if t not in roots.keys():
                roots[t] = logn[i]

        add_plot(fname, cwd, fig, logn, logt, opsn, opst, t_counts, n_counts,
                 t_pairs, n_pairs, log_marker, xloc, yloc, ax_main, ax_count,
                 ax_vcount, ax_none, ax_small, xmax, xmin, ymax, ymin, xrng,
                 yrng, xlist, ylist, roots, graphs, 0, debug)

    plt.close()
    page_list = []
    page_size = document.paperformat(200, 200)

    num_plots = 1
    if pages:
        num_plots = len(opsn)

    for i in range(0, num_plots):

        if debug > 0:
            err.log("Concatenating PS pages for plot #" + str(i))

        plots_name = cwd + '/../tmp/' + fname + '_' + str(i) + '.eps'
        tree_name = cwd + '/../tmp/' + fname + '_' + str(i) + '.gv.eps'

        got_tree = True
        try:
            tree_file = open(tree_name, 'r')
            tree_w = 0
            tree_h = 0
            for line in tree_file:
                if line.startswith("%%BoundingBox:"):
                    bbline = line.split()
                    tree_w = bbline[3]
                    tree_h = bbline[4]
                    if debug > 1:
                        err.log(
                            "In EPS #{} got height: {} and width {} from line {}"
                            .format(i, tree_h, tree_w, line.replace('\n', '')))
                    break
            else:
                err.err(
                    "BoundingBox line not found in EPS file for tree diagram.")
            tree_file.close()
        except:
            got_tree = False

        c = canvas.canvas()
        plots_file = epsfile.epsfile(0, 0, plots_name, height=160, width=160)

        c.insert(plots_file)

        if got_tree:
            if tree_w > tree_h:
                tree_file = epsfile.epsfile(120,
                                            120,
                                            tree_name,
                                            align='cc',
                                            width=70)
            else:
                tree_file = epsfile.epsfile(120,
                                            120,
                                            tree_name,
                                            align='cc',
                                            height=70)

            c.insert(tree_file)

        p = document.page(c,
                          fittosize=True,
                          centered=True,
                          paperformat=page_size)
        if no_clean:
            c.writeEPSfile(cwd + '/../tmp/' + fname + '_' + str(i) +
                           '.zipped.eps')

        page_list.append(p)

    d = document.document(page_list)
    out_name = cwd + '/../outputs/' + fname + '.ps'
    if debug > 0:
        err.log("Saving final output " + out_name)
    d.writePSfile(out_name)

    if not no_clean:
        for tmpf in os.listdir(cwd + '/../tmp/'):
            os.remove(cwd + '/../tmp/' + tmpf)

        os.rmdir(cwd + '/../tmp/')