コード例 #1
0
    def draw_image(self):
        w, h = (self.w, self.h)
        clearws()
        setwindow(0, self.w, 0, self.h)
        setviewport(0, 1, 0, 1)

        setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = triangulate(data, \
          (1.0/64, 1.0/64, 1.0/128), (-0.5, -0.5, -0.5), self.isolevel)
        mesh = createmesh(len(vertices)*3, vertices, normals, \
          ones(vertices.shape))
        drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1),
                 (1, 1, 1))
        center = spherical_to_cartesian(-2, pi * self.y / self.h + pi / 2,
                                        pi * self.x / self.w)
        up = spherical_to_cartesian(1, pi * self.y / self.h + pi,
                                    pi * self.x / self.w)
        cameralookat(center[0], center[1], -0.25 + center[2], 0, 0, -0.25,
                     up[0], up[1], up[2])
        drawimage(0, self.w, 0, self.h, \
          self.w, self.h, GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        clear()
        deletemesh(c_int(mesh.value))
コード例 #2
0
 def draw_path(self, gc, path, transform, rgbFace=None):
     path = transform.transform_path(path)
     points = path.vertices
     codes = path.codes
     bbox = gc.get_clip_rectangle()
     if bbox is not None and not np.any(np.isnan(bbox.bounds)):
         x, y, w, h = bbox.bounds
         clrt = np.array([x, x + w, y, y + h])
     else:
         clrt = np.array([0, self.width, 0, self.height])
     gr.setviewport(*clrt / self.size)
     gr.setwindow(*clrt)
     if rgbFace is not None and len(points) > 2:
         color = gr.inqcolorfromrgb(rgbFace[0], rgbFace[1], rgbFace[2])
         gr.settransparency(rgbFace[3])
         gr.setcolorrep(color, rgbFace[0], rgbFace[1], rgbFace[2])
         gr.setfillintstyle(gr.INTSTYLE_SOLID)
         gr.setfillcolorind(color)
         gr.drawpath(points, codes, fill=True)
     lw = gc.get_linewidth()
     if lw != 0:
         rgba = gc.get_rgb()[:4]
         color = gr.inqcolorfromrgb(rgba[0], rgba[1], rgba[2])
         gr.settransparency(rgba[3])
         gr.setcolorrep(color, rgba[0], rgba[1], rgba[2])
         if isinstance(gc._linestyle, str):
             gr.setlinetype(linetype[gc._linestyle])
         gr.setlinewidth(lw)
         gr.setlinecolorind(color)
         gr.drawpath(points, codes, fill=False)
コード例 #3
0
    def draw(self, clear=None, update=None):
        # obsolete kwargs clear, update (unused) just kept for compatibility
        GRWidget.draw(self, clear, update)
        gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        gr.setwswindow(0, self.sizex, 0, self.sizey)

        for plot in self._lstPlot:
            plot.sizex, plot.sizey = self.sizex, self.sizey
            plot.drawGR()
            # logDomainCheck
            logXinDomain = plot.logXinDomain()
            logYinDomain = plot.logYinDomain()
            if logXinDomain != self._logXinDomain:
                self._logXinDomain = logXinDomain
                self.logXinDomain.emit(self._logXinDomain)
            if logYinDomain != self._logYinDomain:
                self._logYinDomain = logYinDomain
                self.logYinDomain.emit(self._logYinDomain)

        if self._pickEvent:
            event = self._pickEvent
            gr.setviewport(*event.viewport)
            wcPoint = event.getWC(event.viewport)
            window = gr.inqwindow()
            gr.setwindow(*event.getWindow())
            gr.setmarkertype(gr.MARKERTYPE_PLUS)
            gr.polymarker([wcPoint.x], [wcPoint.y])
            gr.setwindow(*window)
コード例 #4
0
    def draw(self, clear=False, update=True):
        if clear:
            gr.clearws()
        gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        gr.setwswindow(0, self.sizex, 0, self.sizey)

        for plot in self._lstPlot:
            plot.sizex, plot.sizey = self.sizex, self.sizey
            plot.drawGR()
            # logDomainCheck
            logXinDomain = plot.logXinDomain()
            logYinDomain = plot.logYinDomain()
            if logXinDomain != self._logXinDomain:
                self._logXinDomain = logXinDomain
                self.logXinDomain.emit(self._logXinDomain)
            if logYinDomain != self._logYinDomain:
                self._logYinDomain = logYinDomain
                self.logYinDomain.emit(self._logYinDomain)

        if self._pickEvent:
            event = self._pickEvent
            wcPoint = event.getWC(event.viewport)
            window = gr.inqwindow()
            gr.setwindow(*event.getWindow())
            gr.setmarkertype(gr.MARKERTYPE_PLUS)
            gr.polymarker([wcPoint.x], [wcPoint.y])
            gr.setwindow(*window)
コード例 #5
0
ファイル: __init__.py プロジェクト: EmDash00/python-gr
    def draw(self, clear=None, update=None):
        # obsolete kwargs clear, update (unused) just kept for compatibility
        GRWidget.draw(self, clear, update)
        gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        gr.setwswindow(0, self.sizex, 0, self.sizey)

        for plot in self._lstPlot:
            plot.sizex, plot.sizey = self.sizex, self.sizey
            plot.drawGR()
            # logDomainCheck
            logXinDomain = plot.logXinDomain()
            logYinDomain = plot.logYinDomain()
            if logXinDomain != self._logXinDomain:
                self._logXinDomain = logXinDomain
                self.logXinDomain.emit(self._logXinDomain)
            if logYinDomain != self._logYinDomain:
                self._logYinDomain = logYinDomain
                self.logYinDomain.emit(self._logYinDomain)

        if self._pickEvent:
            event = self._pickEvent
            gr.setviewport(*event.viewportscaled)
            wcPoint = event.getWC(event.viewport)
            window = gr.inqwindow()
            gr.setwindow(*event.getWindow())
            gr.setmarkertype(gr.MARKERTYPE_PLUS)
            gr.polymarker([wcPoint.x], [wcPoint.y])
            gr.setwindow(*window)
コード例 #6
0
    def draw_image(self):
        if not self.needs_refresh:
            return
        self.needs_refresh = False
        w, h = (self.w, self.h)
        clearws()
        setwindow(0, self.w, 0, self.h)
        setviewport(0, 1, 0, 1)

        setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = triangulate(data, \
          (1.0/64, 1.0/64, 1.0/128), (-0.5, -0.5, -0.5), self.isolevel)
        mesh = createmesh(len(vertices)*3, vertices, normals, \
          ones(vertices.shape))
        drawmesh(mesh, 1, (0,0,0), (0,0,1), (0,1,0), (1,1,1), (1,1,1))
        center = spherical_to_cartesian(-2, pi*self.y/self.h+pi/2, pi*self.x/self.w)
        up = spherical_to_cartesian(1, pi*self.y/self.h+pi, pi*self.x/self.w)
        cameralookat(center[0], center[1], -0.25+center[2], 0, 0, -0.25, up[0], up[1], up[2])
        drawimage(0, self.w, 0, self.h, \
          self.w, self.h, GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        clear()
        deletemesh(c_int(mesh.value))
コード例 #7
0
    def expose(self, widget, event):

        cr = widget.window.cairo_create()

        environ["GKS_WSTYPE"] = "142"
        pc = PyCairoContext.from_address(id(cr))
        environ['GKSconid'] = "%lu" % pc.ctx

        cr.move_to(15, 15)
        cr.set_font_size(14)
        cr.show_text("Contour Plot using Gtk ...")

        seed(0)
        xd = uniform(-2, 2, 100)
        yd = uniform(-2, 2, 100)
        zd = xd * np.exp(-xd**2 - yd**2)

        gr.setviewport(0.15, 0.95, 0.1, 0.9)
        gr.setwindow(-2, 2, -2, 2)
        gr.setspace(-0.5, 0.5, 0, 90)
        gr.setmarkersize(1)
        gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
        gr.setcharheight(0.024)
        gr.settextalign(2, 0)
        gr.settextfontprec(3, 0)

        x, y, z = gr.gridit(xd, yd, zd, 200, 200)
        h = np.linspace(-0.5, 0.5, 20)
        gr.surface(x, y, z, 5)
        gr.contour(x, y, h, z, 0)
        gr.polymarker(xd, yd)
        gr.axes(0.25, 0.25, -2, -2, 2, 2, 0.01)

        gr.updatews()
コード例 #8
0
ファイル: __init__.py プロジェクト: faroit/gr
    def draw(self, clear=False, update=True):
        if clear:
            gr.clearws()
        gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        gr.setwswindow(0, self.sizex, 0, self.sizey)

        for plot in self._lstPlot:
            plot.sizex, plot.sizey = self.sizex, self.sizey
            plot.drawGR()
            # logDomainCheck
            logXinDomain = plot.logXinDomain()
            logYinDomain = plot.logYinDomain()
            if logXinDomain != self._logXinDomain:
                self._logXinDomain = logXinDomain
                self.logXinDomain.emit(self._logXinDomain)
            if logYinDomain != self._logYinDomain:
                self._logYinDomain = logYinDomain
                self.logYinDomain.emit(self._logYinDomain)

        if self._pickEvent:
            event = self._pickEvent
            gr.setviewport(*event.viewport)
            wcPoint = event.getWC(event.viewport)
            window = gr.inqwindow()
            gr.setwindow(*event.getWindow())
            gr.setmarkertype(gr.MARKERTYPE_PLUS)
            gr.polymarker([wcPoint.x], [wcPoint.y])
            gr.setwindow(*window)
コード例 #9
0
ファイル: wx_ex.py プロジェクト: kaigaox/gr
    def draw(self, event):
        self.bm = wx.EmptyBitmap(self.GetSizeTuple()[0], self.GetSizeTuple()[1])
        dc = wx.MemoryDC(self.bm)
        
        os.environ['GKSconid'] = "%x!%x" % (get_address(repr(self)), get_address(repr(dc)))
        
        dc.SetBackground(wx.WHITE_BRUSH)
        dc.Clear()
        
        dc.DrawText("Surface Plot using wxWidgets ...", 15, 15)
        
        x = range(1, 481)
        y = range(1, 481)
        w, h, d = gr.readimage(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         'surf.png'))
        z = map(lambda x: x & 0xff, d)

        gr.setviewport(0, 1, 0, 1)
        gr.setwindow(1, 480, 1, 480)
        gr.setspace(1, 1000, 30, 80)
        gr.setcolormap(3)
        gr.surface(x, y, z, 6)
        gr.contour(x, y, range(1), z, 0)
        gr.updatews()
        
        self.Refresh()
        event.Skip()
コード例 #10
0
    def draw_image(self):
        if not self.needs_refresh:
            return
        self.needs_refresh = False
        gr.clearws()
        gr.setwindow(0, self.w, 0, self.h)
        gr.setviewport(0, 1, 0, 1)

        gr3.setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = gr3.triangulate(data,
                                            (1.0 / 64, 1.0 / 64, 1.0 / 128),
                                            (-0.5, -0.5, -0.5), self.isolevel)
        mesh = gr3.createmesh(
            len(vertices) * 3, vertices, normals, np.ones(vertices.shape))
        gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1),
                     (1, 1, 1))
        center = spherical_to_cartesian(-2,
                                        np.pi * self.y / self.h + np.pi / 2,
                                        np.pi * self.x / self.w)
        up = spherical_to_cartesian(1, np.pi * self.y / self.h + np.pi,
                                    np.pi * self.x / self.w)
        gr3.cameralookat(center[0], center[1], -0.25 + center[2], 0, 0, -0.25,
                         up[0], up[1], up[2])
        gr3.drawimage(0, self.w, 0, self.h, self.w, self.h,
                      gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            gr3.export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        gr3.clear()
        gr3.deletemesh(c_int(mesh.value))
コード例 #11
0
ファイル: backend_gr.py プロジェクト: Juanlu001/gr
 def draw_path(self, gc, path, transform, rgbFace=None):
     path = transform.transform_path(path)
     points = path.vertices
     codes = path.codes
     bbox = gc.get_clip_rectangle()
     if bbox is not None:
         x, y, w, h = bbox.bounds
         clrt = np.array([x, x + w, y, y + h])
     else:
         clrt = np.array([0, self.width, 0, self.height])
     gr.setviewport(*clrt / self.size)
     gr.setwindow(*clrt)
     if rgbFace is not None and len(points) > 2:
         color = gr.inqcolorfromrgb(rgbFace[0], rgbFace[1], rgbFace[2])
         gr.settransparency(rgbFace[3])
         gr.setcolorrep(color, rgbFace[0], rgbFace[1], rgbFace[2])
         gr.setfillintstyle(gr.INTSTYLE_SOLID)
         gr.setfillcolorind(color)
         gr.drawpath(points, codes, fill=True)
     lw = gc.get_linewidth()
     if lw != 0:
         rgba = gc.get_rgb()[:4]
         color = gr.inqcolorfromrgb(rgba[0], rgba[1], rgba[2])
         gr.settransparency(rgba[3])
         gr.setcolorrep(color, rgba[0], rgba[1], rgba[2])
         if isinstance(gc._linestyle, str):
             gr.setlinetype(linetype[gc._linestyle])
         gr.setlinewidth(lw)
         gr.setlinecolorind(color)
         gr.drawpath(points, codes, fill=False)
コード例 #12
0
 def __init__(self, dpi):
     self.dpi = dpi
     self.width = 640.0 * dpi / 80
     self.height = 480.0 * dpi / 80
     mwidth, mheight, width, height = gr.inqdspsize()
     if (width / (mwidth / 0.0256) < 200):
         mwidth *= self.width / width
         gr.setwsviewport(0, mwidth, 0, mwidth * 0.75)
     else:
         gr.setwsviewport(0, 0.192, 0, 0.144)
     gr.setwswindow(0, 1, 0, 0.75)
     gr.setviewport(0, 1, 0, 0.75)
     gr.setwindow(0, self.width, 0, self.height)
     self.mathtext_parser = MathTextParser('agg')
     self.texmanager = TexManager()
コード例 #13
0
 def configure(self):
     aspect_ratio = self.width / self.height
     if aspect_ratio > 1:
         rect = np.array([0, 1, 0, 1.0 / aspect_ratio])
         self.size = self.width
     else:
         rect = np.array([0, aspect_ratio, 0, 1])
         self.size = self.height
     mwidth, mheight, width, height = gr.inqdspsize()
     if width / (mwidth / 0.0256) < 200:
         mwidth *= self.width / width
         gr.setwsviewport(*rect * mwidth)
     else:
         gr.setwsviewport(*rect * 0.192)
     gr.setwswindow(*rect)
     gr.setviewport(*rect)
     gr.setwindow(0, self.width, 0, self.height)
コード例 #14
0
ファイル: backend_gr.py プロジェクト: Juanlu001/gr
 def configure(self):
     aspect_ratio = self.width / self.height
     if aspect_ratio > 1:
         rect = np.array([0, 1, 0, 1.0 / aspect_ratio])
         self.size = self.width
     else:
         rect = np.array([0, aspect_ratio, 0, 1])
         self.size = self.height
     mwidth, mheight, width, height = gr.inqdspsize()
     if width / (mwidth / 0.0256) < 200:
         mwidth *= self.width / width
         gr.setwsviewport(*rect * mwidth)
     else:
         gr.setwsviewport(*rect * 0.192)
     gr.setwswindow(*rect)
     gr.setviewport(*rect)
     gr.setwindow(0, self.width, 0, self.height)
コード例 #15
0
ファイル: histogram_widget.py プロジェクト: sciapp/pyMolDyn
    def draw(self, wsviewport=None):
        if self.xvalues is not None and self.widths is not None:
            maxidx = np.argmax(self.xvalues)
            rangex = (self.xvalues.min(),
                      self.xvalues[maxidx] + self.widths[maxidx])
        else:
            rangex = (0.0, 100.0)
        if self.yvalues is not None:
            rangey = gr.adjustrange(0.0, self.yvalues.max())
        else:
            rangey = (0.0, 8.0)

        if wsviewport is None:
            gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        else:
            gr.setwsviewport(*wsviewport)
        gr.setwswindow(0, self.sizex, 0, self.sizey)
        gr.setviewport(0.075 * self.sizex, 0.95 * self.sizex,
                       0.075 * self.sizey, 0.95 * self.sizey)
        gr.setwindow(rangex[0], rangex[1], rangey[0], rangey[1])
        gr.setcharheight(0.012)

        gr.setfillintstyle(1)
        gr.setfillcolorind(0)
        gr.fillrect(rangex[0], rangex[1], rangey[0], rangey[1])

        if self.xvalues is not None and self.yvalues is not None \
                and self.widths is not None:
            gr.setfillintstyle(1)
            gr.setfillcolorind(2)
            for i in range(self.xvalues.size):
                gr.fillrect(self.xvalues[i],
                            self.xvalues[i] + self.widths[i] * 0.8,
                            0.0, self.yvalues[i])
        else:
            gr.text(0.45 * self.sizex, 0.5 * self.sizey, "no data")

        gr.setlinecolorind(1)
        xtick = floor(0.02 * (rangex[1] - rangey[0]) * 100.0) / 100.0
        ytick = floor(0.04 * (rangey[1] - rangey[0]) * 50.0) / 50.0
        gr.axes(xtick, ytick, rangex[0], rangey[0], 10, 5, 0.0075)
        gr.axes(xtick, ytick, rangex[1], rangey[1], -10, -5, -0.0075)

        if self.title is not None:
            gr.text(0.8 * self.sizex, 0.9 * self.sizey, self.title)
コード例 #16
0
ファイル: histogram_widget.py プロジェクト: sciapp/pyMolDyn
    def draw(self, wsviewport=None):
        if self.xvalues is not None and self.widths is not None:
            maxidx = np.argmax(self.xvalues)
            rangex = (self.xvalues.min(),
                      self.xvalues[maxidx] + self.widths[maxidx])
        else:
            rangex = (0.0, 100.0)
        if self.yvalues is not None:
            rangey = gr.adjustrange(0.0, self.yvalues.max())
        else:
            rangey = (0.0, 8.0)

        if wsviewport is None:
            gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        else:
            gr.setwsviewport(*wsviewport)
        gr.setwswindow(0, self.sizex, 0, self.sizey)
        gr.setviewport(0.075 * self.sizex, 0.95 * self.sizex,
                       0.075 * self.sizey, 0.95 * self.sizey)
        gr.setwindow(rangex[0], rangex[1], rangey[0], rangey[1])
        gr.setcharheight(0.012)

        gr.setfillintstyle(1)
        gr.setfillcolorind(0)
        gr.fillrect(rangex[0], rangex[1], rangey[0], rangey[1])

        if self.xvalues is not None and self.yvalues is not None \
                and self.widths is not None:
            gr.setfillintstyle(1)
            gr.setfillcolorind(2)
            for i in range(self.xvalues.size):
                gr.fillrect(self.xvalues[i],
                            self.xvalues[i] + self.widths[i] * 0.8,
                            0.0, self.yvalues[i])
        else:
            gr.text(0.45 * self.sizex, 0.5 * self.sizey, "no data")

        gr.setlinecolorind(1)
        xtick = floor(0.02 * (rangex[1] - rangey[0]) * 100.0) / 100.0
        ytick = floor(0.04 * (rangey[1] - rangey[0]) * 50.0) / 50.0
        gr.axes(xtick, ytick, rangex[0], rangey[0], 10, 5, 0.0075)
        gr.axes(xtick, ytick, rangex[1], rangey[1], -10, -5, -0.0075)

        if self.title is not None:
            gr.text(0.8 * self.sizex, 0.9 * self.sizey, self.title)
コード例 #17
0
ファイル: pygrwidgetqt5_ex.py プロジェクト: jheinen/gr
    def draw(self):
        if not self._draw_graphics:
            return

        x = range(0, 128)
        y = range(0, 128)
        z = readfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "kws.dat"), separator="$")
        zrange = max(z) - min(z)
        h = [min(z) + i * 0.025 * zrange for i in range(0, 40)]

        gr.setviewport(0.075, 0.95, 0.075, 0.95)
        gr.setwindow(1, 128, 1, 128)
        gr.setspace(min(z), max(z), 0, 90)
        gr.setcharheight(0.018)
        gr.setcolormap(-3)
        gr.surface(x, y, z, 5)
        gr.contour(x, y, h, z, -1)
        gr.axes(5, 5, 1, 1, 2, 2, 0.0075)
コード例 #18
0
def pendulum(theta, length, mass):
    l = length[0] + length[1]
    gr.clearws()
    gr.setviewport(0, 1, 0, 1)
    gr.setwindow(-l, l, -l, l)
    gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
    gr.setmarkercolorind(86)
    pivot = [0, 0.775]  # draw pivot point
    gr.fillarea([-0.2, 0.2, 0.2, -0.2], [0.75, 0.75, 0.8, 0.8])
    for i in range(2):
        x = [pivot[0], pivot[0] + sin(theta[i]) * length[i]]
        y = [pivot[1], pivot[1] - cos(theta[i]) * length[i]]
        gr.polyline(x, y)  # draw rod
        gr.setmarkersize(3 * mass[i])
        gr.polymarker([x[1]], [y[1]])  # draw bob
        pivot = [x[1], y[1]]
    gr.updatews()
    return
コード例 #19
0
ファイル: double_pendulum.py プロジェクト: albertocabello/gr
def pendulum(theta, length, mass):
    l = length[0] + length[1]
    gr.clearws()
    gr.setviewport(0, 1, 0, 1)
    gr.setwindow(-l, l, -l, l)
    gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
    gr.setmarkercolorind(86)
    pivot = [0, 0.775]                         # draw pivot point
    gr.fillarea([-0.2, 0.2, 0.2, -0.2], [0.75, 0.75, 0.8, 0.8])
    for i in range(2):
        x = [pivot[0], pivot[0] + sin(theta[i]) * length[i]]
        y = [pivot[1], pivot[1] - cos(theta[i]) * length[i]]
        gr.polyline(x, y)                   # draw rod
        gr.setmarkersize(3 * mass[i])
        gr.polymarker([x[1]], [y[1]])       # draw bob
        pivot = [x[1], y[1]]
    gr.updatews()
    return
コード例 #20
0
ファイル: pygrwidgetqt5_ex.py プロジェクト: directorscut82/gr
    def draw(self):
        if not self._draw_graphics:
            return

        x = range(0, 128)
        y = range(0, 128)
        z = readfile(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  "kws.dat"), separator='$')
        zrange = max(z) - min(z)
        h = [min(z) + i * 0.025 * zrange for i in range(0, 40)]

        gr.setviewport(0.075, 0.95, 0.075, 0.95)
        gr.setwindow(1, 128, 1, 128)
        gr.setspace(min(z), max(z), 0, 90)
        gr.setcharheight(0.018)
        gr.setcolormap(-3)
        gr.surface(x, y, z, 5)
        gr.contour(x, y, h, z, -1)
        gr.axes(5, 5, 1, 1, 2, 2, 0.0075)
コード例 #21
0
ファイル: video_output.py プロジェクト: sciapp/pyMolDyn
    def write(self, image, device_pixel_ratio=1):
        height, width = image.shape[:2]
        gr.clearws()
        if width > height:
            xmax = 1.0
            ymax = 1.0*height/width
        else:
            xmax = 1.0*width/height
            ymax = 1.0

        metric_width, metric_height, pixel_width, pixel_height = gr.inqdspsize()
        meter_per_horizontal_pixel = metric_width/pixel_width
        meter_per_vertical_pixel = metric_height/pixel_height
        gr.setwsviewport(0, meter_per_horizontal_pixel*width*device_pixel_ratio, 0,
                         meter_per_vertical_pixel*height*device_pixel_ratio)
        gr.setwswindow(0, xmax, 0, ymax)
        gr.setviewport(0, xmax, 0, ymax)
        gr.setwindow(0, xmax, 0, ymax)
        gr.drawimage(0, xmax, 0, ymax, width*device_pixel_ratio, height*device_pixel_ratio, image.view('uint32'))
        gr.updatews()
コード例 #22
0
def _colorbar(off=0.0, colors=256):
    global _plt
    gr.savestate()
    viewport = _plt.kwargs['viewport']
    zmin, zmax = _plt.kwargs['zrange']
    gr.setwindow(0, 1, zmin, zmax)
    gr.setviewport(viewport[1] + 0.02 + off, viewport[1] + 0.05 + off,
                   viewport[2], viewport[3])

    l = [1000+int(255*i/(colors-1)) for i in range(colors)]

    gr.cellarray(0, 1, zmax, zmin, 1, colors, l)
    diag = ((viewport[1] - viewport[0])**2 + (viewport[3] - viewport[2])**2)**0.5
    charheight = max(0.016 * diag, 0.012)
    gr.setcharheight(charheight)
    if _plt.kwargs['scale'] & gr.OPTION_Z_LOG:
        gr.setscale(gr.OPTION_Y_LOG)
        gr.axes(0, 2, 1, zmin, 0, 1, 0.005)
    else:
        ztick = 0.5 * gr.tick(zmin, zmax)
        gr.axes(0, ztick, 1, zmin, 0, 1, 0.005)
    gr.restorestate()
コード例 #23
0
ファイル: mlab.py プロジェクト: j-fu/gr
def _colorbar(off=0.0, colors=256):
    global _plt
    gr.savestate()
    viewport = _plt.kwargs['viewport']
    zmin, zmax = _plt.kwargs['zrange']
    gr.setwindow(0, 1, zmin, zmax)
    gr.setviewport(viewport[1] + 0.02 + off, viewport[1] + 0.05 + off,
                   viewport[2], viewport[3])

    l = [1000+int(255*i/(colors-1)) for i in range(colors)]

    gr.cellarray(0, 1, zmax, zmin, 1, colors, l)
    diag = ((viewport[1] - viewport[0])**2 + (viewport[3] - viewport[2])**2)**0.5
    charheight = max(0.016 * diag, 0.012)
    gr.setcharheight(charheight)
    if _plt.kwargs['scale'] & gr.OPTION_Z_LOG:
        gr.setscale(gr.OPTION_Y_LOG)
        gr.axes(0, 2, 1, zmin, 0, 1, 0.005)
    else:
        ztick = 0.5 * gr.tick(zmin, zmax)
        gr.axes(0, ztick, 1, zmin, 0, 1, 0.005)
    gr.restorestate()
コード例 #24
0
    def draw(self, wsviewport=None):
        if self.xvalues is not None:
            rangex = (self.xvalues.min(), self.xvalues.max())
        else:
            rangex = (0, 10)
        if self.yvalues is not None:
            rangey = gr.adjustrange(self.yvalues.min(), self.yvalues.max())
        else:
            rangey = (0, 4)

        if wsviewport is None:
            gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        else:
            gr.setwsviewport(*wsviewport)
        gr.setwswindow(0, self.sizex, 0, self.sizey)
        gr.setviewport(0.075 * self.sizex, 0.95 * self.sizex,
                       0.075 * self.sizey, 0.95 * self.sizey)
        gr.setwindow(rangex[0], rangex[1], rangey[0], rangey[1])
        gr.setcharheight(0.012)

        gr.setfillintstyle(1)
        gr.setfillcolorind(0)
        gr.fillrect(rangex[0], rangex[1], rangey[0], rangey[1])

        if self.xvalues is not None and self.yvalues is not None:
            gr.setlinecolorind(2)
            gr.polyline(self.xvalues, self.yvalues)
        else:
            gr.text(0.4 * self.sizex, 0.5 * self.sizey, "no elements selected")

        gr.setlinecolorind(1)
        gr.axes(0.2, 0.2, rangex[0], rangey[0], 5, 5, 0.0075)
        gr.axes(0.2, 0.2, rangex[1], rangey[1], -5, -5, -0.0075)

        if self.title is not None:
            gr.text(0.8 * self.sizex, 0.9 * self.sizey, self.title)
コード例 #25
0
ファイル: video_output.py プロジェクト: sciapp/pyMolDyn
    def write(self, image, device_pixel_ratio=1):
        height, width = image.shape[:2]
        gr.clearws()
        if width > height:
            xmax = 1.0
            ymax = 1.0 * height / width
        else:
            xmax = 1.0 * width / height
            ymax = 1.0

        metric_width, metric_height, pixel_width, pixel_height = gr.inqdspsize()
        meter_per_horizontal_pixel = metric_width / pixel_width
        meter_per_vertical_pixel = metric_height / pixel_height
        gr.setwsviewport(
            0,
            meter_per_horizontal_pixel * width * device_pixel_ratio,
            0,
            meter_per_vertical_pixel * height * device_pixel_ratio,
        )
        gr.setwswindow(0, xmax, 0, ymax)
        gr.setviewport(0, xmax, 0, ymax)
        gr.setwindow(0, xmax, 0, ymax)
        gr.drawimage(0, xmax, 0, ymax, width * device_pixel_ratio, height * device_pixel_ratio, image.view("uint32"))
        gr.updatews()
コード例 #26
0
ファイル: pdf_widget.py プロジェクト: sciapp/pyMolDyn
    def draw(self, wsviewport=None):
        if self.xvalues is not None:
            rangex = (self.xvalues.min(), self.xvalues.max())
        else:
            rangex = (0, 10)
        if self.yvalues is not None:
            rangey = gr.adjustrange(self.yvalues.min(), self.yvalues.max())
        else:
            rangey = (0, 4)

        if wsviewport is None:
            gr.setwsviewport(0, self.mwidth, 0, self.mheight)
        else:
            gr.setwsviewport(*wsviewport)
        gr.setwswindow(0, self.sizex, 0, self.sizey)
        gr.setviewport(0.075 * self.sizex, 0.95 * self.sizex,
                       0.075 * self.sizey, 0.95 * self.sizey)
        gr.setwindow(rangex[0], rangex[1], rangey[0], rangey[1])
        gr.setcharheight(0.012)

        gr.setfillintstyle(1)
        gr.setfillcolorind(0)
        gr.fillrect(rangex[0], rangex[1], rangey[0], rangey[1])

        if self.xvalues is not None and self.yvalues is not None:
            gr.setlinecolorind(2)
            gr.polyline(self.xvalues, self.yvalues)
        else:
            gr.text(0.4 * self.sizex, 0.5 * self.sizey, "no elements selected")

        gr.setlinecolorind(1)
        gr.axes(0.2, 0.2, rangex[0], rangey[0], 5, 5, 0.0075)
        gr.axes(0.2, 0.2, rangex[1], rangey[1], -5, -5, -0.0075)

        if self.title is not None:
            gr.text(0.8 * self.sizex, 0.9 * self.sizey, self.title)
コード例 #27
0
ファイル: spectrum.py プロジェクト: j-fu/gr
    if mic is None:
        pa = pyaudio.PyAudio()
        mic = pa.open(format=pyaudio.paInt16, channels=1, rate=FS,
                      input=True, frames_per_buffer=SAMPLES)
    amplitudes = numpy.fromstring(mic.read(SAMPLES), dtype=numpy.short)
    return abs(numpy.fft.fft(amplitudes / 32768.0))[:SAMPLES/2]

def parabolic(x, f, i):
    xe = 1/2. * (f[i-1] - f[i+1]) / (f[i-1] - 2 * f[i] + f[i+1]) + x
    ye = f[i] - 1/4. * (f[i-1] - f[i+1]) * (xe - x)
    return xe, ye

f = [FS/float(SAMPLES)*t for t in range(0, SAMPLES//2)]

gr.setviewport(0.1, 0.95, 0.1, 0.95)
gr.setwindow(50, 25000, 0, 100)
gr.setscale(1)

start = time.time()

while time.time() - start < 10:
    try:
        power = get_spectrum()
        peakind = signal.find_peaks_cwt(power, numpy.array([5]))
    except (IOError):
        continue

    gr.clearws()
    gr.setlinewidth(1)
    gr.setlinecolorind(1)
    gr.grid(1, 5, 50, 0, 1, 2)
コード例 #28
0
ファイル: audio_ex.py プロジェクト: albertocabello/gr
Play an audio file and display signal and power spectrum in realtime
"""

import os, wave, pyaudio
import numpy
import gr

SAMPLES = 2048

wf = wave.open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'Monty_Python.wav'), 'rb')
pa = pyaudio.PyAudio()
stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                 channels=wf.getnchannels(), rate=wf.getframerate(), output=True)
 
gr.setwindow(0, SAMPLES, -30000, 30000)
gr.setviewport(0.05, 0.95, 0.05, 0.95)
gr.setlinecolorind(218)
gr.setfillintstyle(1)
gr.setfillcolorind(208)

data = wf.readframes(SAMPLES)
while data != '' and len(data) == SAMPLES * wf.getsampwidth():
    stream.write(data)
    amplitudes = numpy.fromstring(data, dtype=numpy.short)
    power = abs(numpy.fft.fft(amplitudes / 512.0))[:SAMPLES/2:2] - 30000

    gr.clearws()
    gr.fillrect(0, SAMPLES, -30000, 30000)
    gr.grid(40, 1200, 0, 0, 5, 5)
    gr.polyline(range(SAMPLES)[0::4], amplitudes[0::4])
コード例 #29
0
def main():
    ymin, ymax = 0.0, 5.0
    timestep = 0.03
    kp, ki, kd = 0.5, 8.0, 0.001

    pid = PIDController(kp,
                        ki,
                        kd, (ymax - ymin) / 2,
                        timestep,
                        min_output=0,
                        max_output=1.0)

    plant = EmaFilter(alpha=0.7)

    init_plot_window(0, 1, 0, 1)

    queue_size = 100
    t = deque(maxlen=queue_size)
    y1 = deque(maxlen=queue_size)
    y2 = deque(maxlen=queue_size)

    counter = 0
    target = 0.0
    t0 = time()

    while True:
        start = time()
        if counter % 100 == 0:
            target = np.random.randint(low=1, high=5)
            pid.setpoint = target / ymax  # Normalize to lie inside [0, 1]

        # Simulation of measured input
        plant_value = plant.ema(pid.output * (ymax - ymin))

        pid.update(plant_value / (ymax - ymin), time())

        t.append(time() - t0)
        y1.append(target)
        y2.append(pid.output * (ymax - ymin))

        if counter > 0:
            xmin, xmax = t[0], t[-1]
            # ymin, ymax = min(min(y1), min(y2)), max(max(y1), max(y2))
            gr.clearws()
            gr.setwindow(xmin, xmax, ymin, ymax)

            # Target
            gr.setlinewidth(2)
            linecolor(0, 0, 1.0)
            gr.polyline(t, y1)

            # Controller value
            gr.setlinewidth(2)
            linecolor(1.0, 0, 0)
            gr.polyline(t, y2)

            gr.setlinewidth(1)
            linecolor(0, 0, 0)
            draw_axes(1.0, 5.0 / 10, xmin, ymin, x_major=2, y_major=2)
            gr.updatews()
        counter += 1
        sleep(max(timestep - (time() - start), 0.0))
コード例 #30
0
x = [-2 + i * 0.5 for i in range(0, 29)]
y = [-7 + i * 0.5 for i in range(0, 29)]
z = list(range(0, 841))

for i in range(0, 29):
    for j in range(0, 29):
        r1 = math.sqrt((x[j] - 5)**2 + y[i]**2)
        r2 = math.sqrt((x[j] + 5)**2 + y[i]**2)
        z[i * 29 - 1 +
          j] = (math.exp(math.cos(r1)) + math.exp(math.cos(r2)) - 0.9) * 25

gr.setcharheight(24.0 / 500)
gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP)
gr.textext(0.5, 0.9, "Surface Example")
(tbx, tby) = gr.inqtextext(0.5, 0.9, "Surface Example")
gr.fillarea(tbx, tby)

gr.setwindow(-2, 12, -7, 7)
gr.setspace(-80, 200, 45, 70)

gr.setcharheight(14.0 / 500)
gr.axes3d(1, 0, 20, -2, -7, -80, 2, 0, 2, -0.01)
gr.axes3d(0, 1, 0, 12, -7, -80, 0, 2, 0, 0.01)
gr.titles3d("X-Axis", "Y-Axis", "Z-Axis")

gr.surface(x, y, z, 3)
gr.surface(x, y, z, 1)

gr.updatews()
コード例 #31
0
ファイル: mandel_gr3.py プロジェクト: albertocabello/gr
    output = calc_fractal(q, min_x, max_x, min_y, max_y, width, height, iters)

    return output


if getenv('PYOPENCL_CTX') == None:
    environ['PYOPENCL_CTX'] = '0'

x = -0.9223327810370947027656057193752719757635
y = 0.3102598350874576432708737495917724836010

f = 0.5
for i in range(200):
    start = timer()
    pixels = create_fractal(x-f, x+f, y-f, y+f, 500, 500, 400)
    dt = timer() - start

    print("Mandelbrot created in %f s" % dt)

    gr.clearws()
    gr.setviewport(0, 1, 0, 1)
    gr.setcolormap(113)
    z = np.resize(pixels, (500, 500))
    gr.setwindow(0, 500, 0, 500)
    gr.setspace(0, 600, 30, 80)
    gr3.surface(range(500), range(500), z, 3)
    gr.updatews()

    f *= 0.9
コード例 #32
0
ファイル: spectrum3.py プロジェクト: albertocabello/gr
    return abs(np.fft.fft(amplitudes / 32768.0))[:SAMPLES/2]

spectrum = np.zeros((256, 256), dtype=float)
t = -255
dt = float(SAMPLES) / FS
df = FS / float(SAMPLES) / 2 / 2

start = time.time()

while time.time() - start < 10:
    try:
        power = get_spectrum()
    except (IOError):
        continue

    gr.clearws()
    spectrum[:, 255] = power[:256]
    spectrum = np.roll(spectrum, 1)
    gr.setcolormap(-113)
    gr.setviewport(0.05, 0.95, 0.1, 1)
    gr.setwindow(t * dt, (t + 255) * dt, 0, df)
    gr.setscale(gr.OPTION_FLIP_X)
    gr.setspace(0, 200, 30, 80)
    gr3.surface((t + np.arange(256)) * dt, np.linspace(0, df, 256), spectrum, 4)
    gr.setscale(0)
    gr.axes3d(0.2, 0.2, 0, (t + 255) * dt, 0, 0, 5, 5, 0, -0.01)
    gr.titles3d('t [s]', 'f [kHz]', '')
    gr.updatews()

    t += 1
コード例 #33
0
from __future__ import print_function
from __future__ import unicode_literals

import sys
import os
import numpy as np
import gr

sys.path.insert(0, os.path.abspath('../src'))
from statistics.rdf import Kernels

x = np.linspace(-1.25, 1.25, 500)
for name in dir(Kernels):
    if name.startswith('_') or name == 'bandwidth':
        continue
    kernel = getattr(Kernels, name)
    y = kernel(x)
    gr.beginprint(name.lower()+'.svg')
    gr.clearws()
    gr.setwsviewport(0, 0.1, 0, 0.06)
    gr.setviewport(0, 1, 0, 1)
    gr.setwindow(-1.25, 1.25, -0.25, 1.25)
    gr.grid(0.1, 0.1, 0, 0, 5, 5)
    gr.axes(0.1, 0.1, 0, 0, 5, 5, -0.01)
    gr.setlinewidth(2)
    gr.setlinecolorind(2)
    gr.polyline(x, y)
    gr.setlinecolorind(1)
    gr.setlinewidth(1)
    gr.updatews()
    gr.endprint()
コード例 #34
0
lens = []

gr.setregenflags(gr.MPL_POSTPONE_UPDATE)

for t in range(100):

    plt.cla()
    fig = plt.subplot(133)
    fig.xaxis.set_ticks([-100, 0, 100])
    fig.yaxis.set_ticks([])
    plt.ylim([0, 1000])
    plt.hist(angles[t], 20, normed=0, facecolor='g', alpha=0.5)
    plt.show()

    gr.setviewport(0, 0.7, 0, 0.7)
    gr.setwindow(0.1, 0.9, 0.05, 0.85)
    mogli.draw(molecules[t],
               bonds_param=1.15,
               camera=((60, 0, 0), (0, 0, 0), (0, 1, 0)))

    gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_HALF)
    gr.text(0.35, 0.7,
            '700K (%.1f ps)  # of bonds: %d' % (t / 10.0, len(angles[t])))
    lens.append(len(angles[t]))
    if t > 0:
        gr.setwindow(0, 10, 3500, 5000)
        gr.setviewport(0.1, 0.6, 0.05, 0.1)
        gr.axes(1, 0, 0, 3500, 2, 0, 0.005)
        gr.polyline(np.arange(t + 1) / 10.0, lens)

    gr.updatews()
コード例 #35
0
ファイル: audio_ex.py プロジェクト: faroit/gr
import numpy
import gr
import scipy.fftpack

SAMPLES = 2048

wf = wave.open(
    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                 'Monty_Python.wav'), 'rb')
pa = pyaudio.PyAudio()
stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                 channels=wf.getnchannels(),
                 rate=wf.getframerate(),
                 output=True)

gr.setwindow(0, SAMPLES, -30000, 30000)
gr.setviewport(0.05, 0.95, 0.05, 0.95)
gr.setlinecolorind(218)
gr.setfillintstyle(1)
gr.setfillcolorind(208)

data = wf.readframes(SAMPLES)
while data != '' and len(data) == SAMPLES * wf.getsampwidth():
    stream.write(data)
    amplitudes = numpy.fromstring(data, dtype=numpy.short)
    power = abs(scipy.fftpack.fft(amplitudes / 512.0))[:SAMPLES / 2:2] - 30000

    gr.clearws()
    gr.fillrect(0, SAMPLES, -30000, 30000)
    gr.grid(40, 1200, 0, 0, 5, 5)
    gr.polyline(range(SAMPLES)[0::4], amplitudes[0::4])
コード例 #36
0
ファイル: mandel_gr3.py プロジェクト: cfelder/python-gr
    q = np.zeros(width * height).astype(np.complex128)

    output = calc_fractal(q, min_x, max_x, min_y, max_y, width, height, iters)

    return output


os.environ['PYOPENCL_CTX'] = os.environ.get('PYOPENCL_CTX', '0')

x = -0.9223327810370947027656057193752719757635
y = 0.3102598350874576432708737495917724836010

f = 0.5
for i in range(200):
    start = timer()
    pixels = create_fractal(x - f, x + f, y - f, y + f, 500, 500, 400)
    dt = timer() - start

    print("Mandelbrot created in %f s" % dt)

    gr.clearws()
    gr.setviewport(0, 1, 0, 1)
    gr.setcolormap(113)
    z = np.resize(pixels, (500, 500))
    gr.setwindow(0, 500, 0, 500)
    gr.setspace(0, 600, 30, 80)
    gr3.surface(range(500), range(500), z, 3)
    gr.updatews()

    f *= 0.9
コード例 #37
0
ファイル: main.py プロジェクト: li012589/xyzFile2Animation
if args.output is not None:
    os.environ["GKS_VIDEO_OPTS"] = "2000x2000"
    os.environ["GKS_WSTYPE"] = args.output[-3:]
    os.environ["GKS_FILEPATH"] = args.output

if args.filename.endswith('.xyz'):
    molecules = mogli.read(args.filename)
elif args.filename.endswith('.npz'):
    fixs = np.array([args.fixx,args.fixy,args.fixz])
    molecules = mogli.load(args.filename,args.name,args.smile,args.scaling,fixs)

    if args.fix_bond:
        bonds_method = 'fix_bond'
        bonds_param = args.smile
    else:
        bonds_method = 'radii'
        bonds_param = args.bond


for t in range(args.batch):
    print(str(t)+" of "+str(args.batch))
    gr.clearws()
    gr.setviewport(0, 0.7, 0, 0.7)
    gr.setwindow(0.1, 0.9, 0.05, 0.85)
    #mogli.draw(molecules[t], bonds_param=args.bond, camera=((12, 0, 12),(0, 0, 0),(0, 1, 0)))
    mogli.draw(molecules[t], width=500, height=500, bonds_method=bonds_method,bonds_param=bonds_param, camera=((args.camera_distance, 0, args.camera_distance),(0, 0, 0),(0, 1, 0)))
    #mogli.draw(molecules[t], bonds_method=bonds_method,bonds_param=bonds_param, camera=((12, 0, 12),(0, 0, 0),(0, 1, 0)))

    gr.updatews()
コード例 #38
0
ファイル: mlab.py プロジェクト: j-fu/gr
def _set_window(kind):
    global _plt
    scale = 0
    scale |= gr.OPTION_X_LOG if _plt.kwargs.get('xlog', False) else 0
    scale |= gr.OPTION_Y_LOG if _plt.kwargs.get('ylog', False) else 0
    scale |= gr.OPTION_Z_LOG if _plt.kwargs.get('zlog', False) else 0
    scale |= gr.OPTION_FLIP_X if _plt.kwargs.get('xflip', False) else 0
    scale |= gr.OPTION_FLIP_Y if _plt.kwargs.get('yflip', False) else 0
    scale |= gr.OPTION_FLIP_Z if _plt.kwargs.get('zflip', False) else 0

    _minmax()
    if kind in ('wireframe', 'surface', 'plot3', 'scatter3'):
        major_count = 2
    else:
        major_count = 5

    x_min, x_max = _plt.kwargs['xrange']
    if not scale & gr.OPTION_X_LOG:
        x_min, x_max = gr.adjustlimits(x_min, x_max)
        x_major_count = major_count
        x_tick = gr.tick(x_min, x_max) / x_major_count
    else:
        x_tick = x_major_count = 1
    if not scale & gr.OPTION_FLIP_X:
        xorg = (x_min, x_max)
    else:
        xorg = (x_max, x_min)
    _plt.kwargs['xaxis'] = x_tick, xorg, x_major_count

    y_min, y_max = _plt.kwargs['yrange']
    if kind in ('hist', 'stem') and 'ylim' not in _plt.kwargs:
        y_min = 0
    if not scale & gr.OPTION_Y_LOG:
        y_min, y_max = gr.adjustlimits(y_min, y_max)
        y_major_count = major_count
        y_tick = gr.tick(y_min, y_max) / y_major_count
    else:
        y_tick = y_major_count = 1
    if not scale & gr.OPTION_FLIP_Y:
        yorg = (y_min, y_max)
    else:
        yorg = (y_max, y_min)
    _plt.kwargs['yaxis'] = y_tick, yorg, y_major_count

    _plt.kwargs['window'] = (x_min, x_max, y_min, y_max)
    gr.setwindow(x_min, x_max, y_min, y_max)

    if kind in ('wireframe', 'surface', 'plot3', 'scatter3'):
        z_min, z_max = _plt.kwargs['zrange']
        if not scale & gr.OPTION_Z_LOG:
            z_min, z_max = gr.adjustlimits(z_min, z_max)
            z_major_count = major_count
            z_tick = gr.tick(z_min, z_max) / z_major_count
        else:
            z_tick = z_major_count = 1
        if not scale & gr.OPTION_FLIP_Z:
            zorg = (z_min, z_max)
        else:
            zorg = (z_max, z_min)
        _plt.kwargs['zaxis'] = z_tick, zorg, z_major_count

        rotation = _plt.kwargs.get('rotation', 40)
        tilt = _plt.kwargs.get('tilt', 70)
        gr.setspace(z_min, z_max, rotation, tilt)

    _plt.kwargs['scale'] = scale
    gr.setscale(scale)
コード例 #39
0
                      input=True,
                      frames_per_buffer=SAMPLES)
    amplitudes = np.frombuffer(mic.read(SAMPLES), dtype=np.short)
    return abs(np.fft.fft(amplitudes / 32768.0))[:SAMPLES // 2]


def parabolic(x, f, i):
    xe = 1 / 2. * (f[i - 1] - f[i + 1]) / (f[i - 1] - 2 * f[i] + f[i + 1]) + x
    ye = f[i] - 1 / 4. * (f[i - 1] - f[i + 1]) * (xe - x)
    return xe, ye


f = [FS / float(SAMPLES) * t for t in range(0, SAMPLES // 2)]

gr.setviewport(0.1, 0.95, 0.1, 0.95)
gr.setwindow(50, 25000, 0, 100)
gr.setscale(1)

start = time.time()

while time.time() - start < 10:
    try:
        power = get_spectrum()
        peakind = signal.find_peaks_cwt(power, np.array([5]))
    except (IOError):
        continue

    gr.clearws()
    gr.setlinewidth(1)
    gr.setlinecolorind(1)
    gr.grid(1, 5, 50, 0, 1, 2)
コード例 #40
0
from gr.pygr import Plot, PlotAxes, PlotCurve, Text

tx, ty = 0, -20
x = [-3.3 + t * .1 for t in range(66)]
y = [t**5 - 13 * t**3 + 36 * t for t in x]
txtfmt = "Text drawn on\n(%g, %g) with\nhalign left, valign top"

plt = Plot((.1, .95, .1, .88))
plt.title = "Text on Axes Example"
plt.subTitle = "Show usage of gr.pygr.Text"
plt.xlabel = "x"
plt.ylabel = "y"

curve = PlotCurve(x, y, legend="foo bar")
axes = PlotAxes(plt.viewport).addCurves(curve)
axes.setWindow(-4.0, 4.0, -60.0, 40.0)
text = Text(tx, -ty, txtfmt % (tx, -ty), axes, .02)
plt.addAxes(axes)
text2 = Text(tx, ty, txtfmt % (tx, ty), axes, .02)
tbx, tby = text2.getBoundingBox()

plt.drawGR()
text.drawGR()
text2.drawGR()

# set viewport and window accordingly to draw in NDC space
gr.setviewport(0, axes.sizex, 0, axes.sizey)
gr.setwindow(0, axes.sizex, 0, axes.sizey)
gr.fillarea(tbx, tby)
gr.updatews()
コード例 #41
0
ファイル: audio_ex3.py プロジェクト: albertocabello/gr
stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                 channels=wf.getnchannels(), rate=wf.getframerate(), output=True)

spectrum = np.zeros((256, 64), dtype=float)
t = -63
dt = float(SAMPLES) / FS
df = FS / float(SAMPLES) / 2 / 2

data = wf.readframes(SAMPLES)
while data != '' and len(data) == SAMPLES * wf.getsampwidth():
    stream.write(data)
    amplitudes = np.fromstring(data, dtype=np.short)
    power = abs(np.fft.fft(amplitudes / 32768.0))[:SAMPLES/2]

    gr.clearws()
    spectrum[:, 63] = power[:256]
    spectrum = np.roll(spectrum, 1)
    gr.setcolormap(-113)
    gr.setviewport(0.05, 0.95, 0.1, 1)
    gr.setwindow(t * dt, (t + 63) * dt, 0, df)
    gr.setscale(gr.OPTION_FLIP_X)
    gr.setspace(0, 256, 30, 80)
    gr3.surface((t + np.arange(64)) * dt, np.linspace(0, df, 256), spectrum, 4)
    gr.setscale(0)
    gr.axes3d(0.2, 0.2, 0, (t + 63) * dt, 0, 0, 5, 5, 0, -0.01)
    gr.titles3d('t [s]', 'f [kHz]', '')
    gr.updatews()

    data = wf.readframes(SAMPLES)
    t += 1
コード例 #42
0
ファイル: griddata.py プロジェクト: vleo/gr
#!/usr/bin/env python
"""
Create a contour plot of irregular distributed data
"""

from numpy.random import uniform, seed
import numpy as np
import gr

seed(0)
xd = uniform(-2, 2, 100)
yd = uniform(-2, 2, 100)
zd = xd * np.exp(-xd ** 2 - yd ** 2)

gr.setviewport(0.1, 0.95, 0.1, 0.95)
gr.setwindow(-2, 2, -2, 2)
gr.setspace(-0.5, 0.5, 0, 90)
gr.setmarkersize(1)
gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
gr.setcharheight(0.024)
gr.settextalign(2, 0)
gr.settextfontprec(3, 0)

x, y, z = gr.gridit(xd, yd, zd, 200, 200)
h = np.linspace(-0.5, 0.5, 20)
gr.surface(x, y, z, 5)
gr.contour(x, y, h, z, 0)
gr.polymarker(xd, yd)
gr.axes(0.25, 0.25, -2, -2, 2, 2, 0.01)

gr.updatews()
コード例 #43
0
#!/usr/bin/env python
"""
Create a contour plot of irregular distributed data
"""

import numpy as np
import gr

np.random.seed(0)
xd = np.random.uniform(-2, 2, 100)
yd = np.random.uniform(-2, 2, 100)
zd = xd * np.exp(-xd**2 - yd**2)

gr.setviewport(0.1, 0.95, 0.1, 0.95)
gr.setwindow(-2, 2, -2, 2)
gr.setspace(-0.5, 0.5, 0, 90)
gr.setmarkersize(1)
gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
gr.setcharheight(0.024)
gr.settextalign(2, 0)
gr.settextfontprec(3, 0)

x, y, z = gr.gridit(xd, yd, zd, 200, 200)
h = np.linspace(-0.5, 0.5, 20)
gr.surface(x, y, z, 5)
gr.contour(x, y, h, z, 0)
gr.polymarker(xd, yd)
gr.axes(0.25, 0.25, -2, -2, 2, 2, 0.01)

gr.updatews()
コード例 #44
0
ファイル: textonaxes.py プロジェクト: vleo/gr
from gr.pygr import Plot, PlotAxes, PlotCurve, Text

if __name__ == "__main__":
    tx, ty = 0, -20
    x = [-3.3 + t * 0.1 for t in range(66)]
    y = [t ** 5 - 13 * t ** 3 + 36 * t for t in x]
    txtfmt = "Text drawn on\n(%g, %g) with\nhalign left, valign top"

    plt = Plot((0.1, 0.95, 0.1, 0.88))
    plt.title = "Text on Axes Example"
    plt.subTitle = "Show usage of gr.pygr.Text"
    plt.xlabel = "x"
    plt.ylabel = "y"

    curve = PlotCurve(x, y, legend="foo bar")
    axes = PlotAxes(plt.viewport).addCurves(curve)
    axes.setWindow(-4.0, 4.0, -60.0, 40.0)
    text = Text(tx, -ty, txtfmt % (tx, -ty), axes, 0.02)
    plt.addAxes(axes)
    text2 = Text(tx, ty, txtfmt % (tx, ty), axes, 0.02)
    tbx, tby = text2.getBoundingBox()

    plt.drawGR()
    text.drawGR()
    text2.drawGR()

    # set viewport and window accordingly to draw in NDC space
    gr.setviewport(0, axes.sizex, 0, axes.sizey)
    gr.setwindow(0, axes.sizex, 0, axes.sizey)
    gr.fillarea(tbx, tby)
コード例 #45
0
ファイル: audio_ex3.py プロジェクト: EmDash00/python-gr
                 rate=wf.getframerate(),
                 output=True)

spectrum = np.zeros((256, 64), dtype=float)
t = -63
dt = float(SAMPLES) / FS
df = FS / float(SAMPLES) / 2 / 2

data = wf.readframes(SAMPLES)
while data != '' and len(data) == SAMPLES * wf.getsampwidth():
    stream.write(data)
    amplitudes = np.frombuffer(data, dtype=np.short)
    power = abs(np.fft.fft(amplitudes / 32768.0))[:SAMPLES // 2]

    gr.clearws()
    spectrum[:, 63] = power[:256]
    spectrum = np.roll(spectrum, 1)
    gr.setcolormap(-113)
    gr.setviewport(0.05, 0.95, 0.1, 1)
    gr.setwindow(t * dt, (t + 63) * dt, 0, df)
    gr.setscale(gr.OPTION_FLIP_X)
    gr.setspace(0, 256, 30, 80)
    gr3.surface((t + np.arange(64)) * dt, np.linspace(0, df, 256), spectrum, 4)
    gr.setscale(0)
    gr.axes3d(0.2, 0.2, 0, (t + 63) * dt, 0, 0, 5, 5, 0, -0.01)
    gr.titles3d('t [s]', 'f [kHz]', '')
    gr.updatews()

    data = wf.readframes(SAMPLES)
    t += 1
コード例 #46
0
def init_plot_window(xmin, xmax, ymin, ymax):
    gr.clearws()
    gr.setwsviewport(0.0, 0.25, 0.0, 0.25)  # Desktop window extents in meters
    gr.setviewport(0.15, 0.95, 0.15, 0.95)
    gr.setwindow(xmin, xmax, ymin, ymax)
コード例 #47
0
def _set_window(kind):
    global _plt
    scale = 0
    if kind != 'polar':
        scale |= gr.OPTION_X_LOG if _plt.kwargs.get('xlog', False) else 0
        scale |= gr.OPTION_Y_LOG if _plt.kwargs.get('ylog', False) else 0
        scale |= gr.OPTION_Z_LOG if _plt.kwargs.get('zlog', False) else 0
        scale |= gr.OPTION_FLIP_X if _plt.kwargs.get('xflip', False) else 0
        scale |= gr.OPTION_FLIP_Y if _plt.kwargs.get('yflip', False) else 0
        scale |= gr.OPTION_FLIP_Z if _plt.kwargs.get('zflip', False) else 0

    _minmax()
    if kind in ('wireframe', 'surface', 'plot3', 'scatter3', 'polar', 'trisurf'):
        major_count = 2
    else:
        major_count = 5

    x_min, x_max = _plt.kwargs['xrange']
    if not scale & gr.OPTION_X_LOG:
        x_min, x_max = gr.adjustlimits(x_min, x_max)
        x_major_count = major_count
        x_tick = gr.tick(x_min, x_max) / x_major_count
    else:
        x_tick = x_major_count = 1
    if not scale & gr.OPTION_FLIP_X:
        xorg = (x_min, x_max)
    else:
        xorg = (x_max, x_min)
    _plt.kwargs['xaxis'] = x_tick, xorg, x_major_count

    y_min, y_max = _plt.kwargs['yrange']
    if kind in ('hist', 'stem') and 'ylim' not in _plt.kwargs:
        y_min = 0
    if not scale & gr.OPTION_Y_LOG:
        y_min, y_max = gr.adjustlimits(y_min, y_max)
        y_major_count = major_count
        y_tick = gr.tick(y_min, y_max) / y_major_count
    else:
        y_tick = y_major_count = 1
    if not scale & gr.OPTION_FLIP_Y:
        yorg = (y_min, y_max)
    else:
        yorg = (y_max, y_min)
    _plt.kwargs['yaxis'] = y_tick, yorg, y_major_count

    _plt.kwargs['window'] = (x_min, x_max, y_min, y_max)
    if kind == 'polar':
        gr.setwindow(-1, 1, -1, 1)
    else:
        gr.setwindow(x_min, x_max, y_min, y_max)

    if kind in ('wireframe', 'surface', 'plot3', 'scatter3', 'trisurf'):
        z_min, z_max = _plt.kwargs['zrange']
        if not scale & gr.OPTION_Z_LOG:
            z_min, z_max = gr.adjustlimits(z_min, z_max)
            z_major_count = major_count
            z_tick = gr.tick(z_min, z_max) / z_major_count
        else:
            z_tick = z_major_count = 1
        if not scale & gr.OPTION_FLIP_Z:
            zorg = (z_min, z_max)
        else:
            zorg = (z_max, z_min)
        _plt.kwargs['zaxis'] = z_tick, zorg, z_major_count

        rotation = _plt.kwargs.get('rotation', 40)
        tilt = _plt.kwargs.get('tilt', 70)
        gr.setspace(z_min, z_max, rotation, tilt)

    _plt.kwargs['scale'] = scale
    gr.setscale(scale)
コード例 #48
0
ファイル: spectrum3.py プロジェクト: cfelder/python-gr
spectrum = np.zeros((256, 256), dtype=float)
t = -255
dt = float(SAMPLES) / FS
df = FS / float(SAMPLES) / 2 / 2

start = time.time()

while time.time() - start < 10:
    try:
        power = get_spectrum()
    except (IOError):
        continue

    gr.clearws()
    spectrum[:, 255] = power[:256]
    spectrum = np.roll(spectrum, 1)
    gr.setcolormap(-113)
    gr.setviewport(0.05, 0.95, 0.1, 1)
    gr.setwindow(t * dt, (t + 255) * dt, 0, df)
    gr.setscale(gr.OPTION_FLIP_X)
    gr.setspace(0, 200, 30, 80)
    gr3.surface((t + np.arange(256)) * dt, np.linspace(0, df, 256), spectrum,
                4)
    gr.setscale(0)
    gr.axes3d(0.2, 0.2, 0, (t + 255) * dt, 0, 0, 5, 5, 0, -0.01)
    gr.titles3d('t [s]', 'f [kHz]', '')
    gr.updatews()

    t += 1
コード例 #49
0
CYCLE = 1000
N_PAR_CYCLE = 1000
n = CYCLE * N_PAR_CYCLE

df = pd.DataFrame({
    "idx": np.arange(1, n + 1),
    "cycle_no": np.repeat(range(1, CYCLE + 1), N_PAR_CYCLE),
    "cycle_cnt": np.tile(np.arange(1, N_PAR_CYCLE + 1), CYCLE),
    "val": randn(n) + np.repeat(range(CYCLE), N_PAR_CYCLE)
})

import gr
from gr.pygr import Plot, PlotAxes, PlotContour, PlotCurve

gr.setwindow(-2, 1000, -2, 1000)
gr.setviewport(0.05, 0.95, 0.05, 0.95)
gr.setfillintstyle(1)
gr.setfillcolorind(208)

# create figure with plot
# fig = plt.Fig()
# ax_left = fig[0, 0]
# ax_right = fig[0, 1]
# ax_left._configure_2d()
# ax_left.title.text = 'Current Clamp Recording'
# ax_left.ylabel.text = 'Membrane Potential (mV)'
# ax_left.xlabel.text = 'Time (ms)'
selected = None

# cmap = get_colormap('hsl', value=0.5)