Example #1
0
    def draw_sector(self, end):
        """draw the sector"""
        segment = path.path(
            path.arc(self.xo, self.yo, self.inner_r, self.start_angle,
                     self.end_angle),
            path.arcn(self.xo, self.yo, self.sector_width + self.inner_r,
                      self.end_angle, self.start_angle), path.closepath())
        self.shape_canvas.fill(segment, [self.sector_color])

        # draw a delimiting line between sectors
        line_color = color.gray(0.15)
        if end and (self.end_angle - self.start_angle) < 0.25:
            line_color = color.rgb.red

        r = self.inner_r + self.sector_width
        start_radians = self.start_angle * pi / 180.0
        end_radians = self.end_angle * pi / 180.0
        x0 = self.inner_r * cos(start_radians) + self.xo
        y0 = self.inner_r * sin(start_radians) + self.yo
        x1 = r * cos(start_radians) + self.xo
        y1 = r * sin(start_radians) + self.yo

        self.shape_canvas.stroke(path.line(x0, y0, x1, y1),
                                 [style.linewidth(0.01), line_color])

        x0 = self.inner_r * cos(end_radians) + self.xo
        y0 = self.inner_r * sin(end_radians) + self.yo
        x1 = r * cos(end_radians) + self.xo
        y1 = r * sin(end_radians) + self.yo

        self.shape_canvas.stroke(path.line(x0, y0, x1, y1),
                                 [style.linewidth(0.01), line_color])
Example #2
0
def draw_page(c, file, sensori, sensorj, nci, ncj, matrix):
    """
    Generates the contingency table for the peaks

    :param c:
    :param file:
    :param sensori:
    :param sensorj:
    :param nci:
    :param ncj:
    :return:
    """

    for i in range(nci):
        im = Image.open(resultpath+'/icons/'+"%s%s.cl%d.png"%(file, sensori, i+1))
        image_bw = bitmap.image(im.size[0], im.size[1], im.mode, im.tostring())
        bitmap_bw = bitmap.bitmap(0, i+1, image_bw, height=0.8)
        c.insert(bitmap_bw)
    for i in range(ncj):
        im = Image.open(resultpath+'/icons/'+"%s%s.cl%d.png"%(file, sensorj, i+1))
        image_bw = bitmap.image(im.size[0], im.size[1], im.mode, im.tostring())
        bitmap_bw = bitmap.bitmap(i+1, 0, image_bw, height=0.8)
        c.insert(bitmap_bw)

    grad = np.zeros(matrix.shape)
    for i in range(matrix.shape[0]):
        grad[i] = matrix[i]/np.sum(matrix[i])

    for i in range(nci):
        for j in range(ncj):
            p = path.rect(i+1, j+1, 1, 1)
            c.stroke(p, [deco.filled([gray(1-grad[i, j])])])
            c.text(i+1, j+1, str(int(matrix[i,j])), [text.size(-1), rgb.blue])
    c.text(-1, (nci/2)+1, sensori, [text.size(-1)])
    c.text((ncj/2)+1, -1, sensorj, [text.size(-1)])
    # Margings for better printing
    c.text(-1.5, (nci/2)+1, " ", [text.size(-1)])
    c.text(nci+2, (nci/2)+1, " ", [text.size(-1)])
    c.text((ncj/2)+1, -1.5, " ", [text.size(-1)])
    c.text((ncj/2)+1, ncj+2,  " ", [text.size(-1)])
Example #3
0
def draw_page(c, file, sensori, sensorj, nci, ncj, matrix):
    """
    Generates the contingency table for the peaks

    :param c:
    :param file:
    :param sensori:
    :param sensorj:
    :param nci:
    :param ncj:
    :return:
    """

    for i in range(nci):
        im = Image.open(datainfo.dpath + '/' + datainfo.name +'/Results/icons/' + "%s%s.cl%d.png"%(file, sensori, i+1))
        image_bw = bitmap.image(im.size[0], im.size[1], im.mode, im.tostring())
        bitmap_bw = bitmap.bitmap(0, i+1, image_bw, height=0.8)
        c.insert(bitmap_bw)
    for i in range(ncj):
        im = Image.open(datainfo.dpath + '/' + datainfo.name +'/Results/icons/' + "%s%s.cl%d.png"%(file, sensorj, i+1))
        image_bw = bitmap.image(im.size[0], im.size[1], im.mode, im.tostring())
        bitmap_bw = bitmap.bitmap(i+1, 0, image_bw, height=0.8)
        c.insert(bitmap_bw)

    grad = np.zeros(matrix.shape)
    for i in range(matrix.shape[0]):
        grad[i] = matrix[i]/np.sum(matrix[i])

    for i in range(nci):
        for j in range(ncj):
            p = path.rect(i+1, j+1, 1, 1)
            c.stroke(p, [deco.filled([gray(1-grad[i, j])])])
            c.text(i+1, j+1, str(int(matrix[i,j])), [text.size(-1), rgb.blue])
    c.text(-1, (nci/2)+1, sensori, [text.size(-1)])
    c.text((ncj/2)+1, -1, sensorj, [text.size(-1)])
    # Margings for better printing
    c.text(-1.5, (nci/2)+1, " ", [text.size(-1)])
    c.text(nci+2, (nci/2)+1, " ", [text.size(-1)])
    c.text((ncj/2)+1, -1.5, " ", [text.size(-1)])
    c.text((ncj/2)+1, ncj+2,  " ", [text.size(-1)])
Example #4
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")
Example #5
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)
Example #6
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)
Example #7
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)