def getHTML(self): if not self.enabled: return '' if not self.data or not self.curves: return '<span>No data or curves found</span>' with self.lock: for i, (d, c) in enumerate(zip(self.data, self.curves)): try: # add a point "current value" at "right now" to avoid curves # not updating if the value doesn't change now = currenttime() if d[0][-1] < now - 10: self.updatevalues(i, now, d[1][-1]) c.x, c.y = self.maybeDownsamplePlotdata(d) except IndexError: # no data (yet) pass c = self.axes.getCurves() self.axes.setWindow(c.xmin, c.xmax, c.ymin, c.ymax) if os.path.isfile(self.tempfile): os.unlink(self.tempfile) gr.beginprint(self.tempfile) gr.setwsviewport(0, self.width * 0.0022, 0, self.height * 0.0022) try: self.plot.drawGR() except Exception as err: return html.escape('Error generating plot: %s' % err) finally: gr.endprint() gr.clearws() with open(self.tempfile, 'rb') as fp: imgbytes = fp.read() return ('<img src="data:image/svg+xml;base64,%s" ' 'style="width: %sex; height: %sex">' % (b64encode(imgbytes).decode(), self.width, self.height))
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))
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)
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))
def draw(mesh, x=None, y=None, z=None): gr3.clear() gr3.drawmesh(mesh, 1, (0,0,0), (0,0,1), (0,1,0), (1,1,1), (1,1,1)) gr3.drawslicemeshes(data, x=x, y=y, z=z) gr.clearws() gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.updatews()
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))
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)
def double_pendulum(theta, length, mass): gr.clearws() gr.setviewport(0, 1, 0, 1) direction = [] position = [(0, 0, 0)] for i in range(2): direction.append( (sin(theta[i]) * length[i] * 2, -cos(theta[i]) * length[i] * 2, 0)) position.append([position[-1][j] + direction[-1][j] for j in range(3)]) gr3.clear() # draw pivot point gr3.drawcylindermesh(1, (0, 0.2, 0), (0, 1, 0), (0.4, 0.4, 0.4), 0.4, 0.05) gr3.drawcylindermesh(1, (0, 0.2, 0), (0, -1, 0), (0.4, 0.4, 0.4), 0.05, 0.2) gr3.drawspheremesh(1, (0, 0, 0), (0.4, 0.4, 0.4), 0.05) # draw rods gr3.drawcylindermesh(2, position, direction, (0.6, 0.6, 0.6) * 2, (0.05, 0.05), [l * 2 for l in length]) # draw bobs gr3.drawspheremesh(2, position[1:], (1, 1, 1) * 2, [m * 0.2 for m in mass]) gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.updatews() return
def draw(self): """ Draw the figure using the renderer """ gr.clearws() renderer = RendererGR(self.figure.dpi) self.figure.draw(renderer) gr.updatews()
def draw(mesh, x=None, y=None, z=None): gr3.clear() gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1), (1, 1, 1)) gr3.drawslicemeshes(data, x=x, y=y, z=z) gr.clearws() gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.updatews()
def paintEvent(self, event): self._painter = QPainter() self._painter.begin(self) self._painter.fillRect(0, 0, self.width(), self.height(), self._bgColor) os.environ["GKSconid"] = getGKSConnectionId(self, self._painter) gr.clearws() self.draw() gr.updatews() self._painter.end()
def plot_domain(color_func, f, re=(-1, 1), im=(-1, 1), N=100, n=15): w = func_vals(f, re, im, N) domc = color_func(w, n) * 255 width, height = domc.shape[:2] domc = np.append(domc, np.ones((width, height, 1)) * 255, axis=2) domc = domc.astype(np.uint8) domc = domc.view('<i4') gr.clearws() gr.setviewport(0, 1, 0, 1) gr.drawimage(0, 1, 0, 1, width, height, domc, model=gr.MODEL_HSV) gr.updatews()
def draw(self): """ Draw the figure using the renderer """ flags = gr.inqregenflags() if not flags & gr.MPL_SUPPRESS_CLEAR: gr.clearws() self.renderer.configure() self.figure.draw(self.renderer) if not flags & gr.MPL_POSTPONE_UPDATE: gr.updatews()
def plot_domain(color_func, f, re=[-1, 1], im=[-1, 1], N=100, n=15): w = func_vals(f, re, im, N) domc = color_func(w, n) * 255 width, height = domc.shape[:2] domc = np.append(domc, np.ones((width, height, 1)) * 255, axis=2) domc = domc.astype(np.uint8) domc = domc.view("<i4") gr.clearws() gr.setviewport(0, 1, 0, 1) gr.drawimage(0, 1, 0, 1, width, height, domc, model=gr.MODEL_HSV) gr.updatews()
def _plot_img(I): global _plt if isinstance(I, basestring): width, height, data = gr.readimage(I) if width == 0 or height == 0: return else: I = np.array(I) width, height = I.shape data = np.array(1000+(1.0*I - I.min()) / I.ptp() * 255, np.int32) if _plt.kwargs['clear']: gr.clearws() if not _plt.kwargs['ax']: _set_viewport('line', _plt.kwargs['subplot']) viewport = _plt.kwargs['viewport'] vp = _plt.kwargs['vp'] if width * (viewport[3] - viewport[2]) < height * (viewport[1] - viewport[0]): w = width / height * (viewport[3] - viewport[2]) x_min = max(0.5 * (viewport[0] + viewport[1] - w), viewport[0]) x_max = min(0.5 * (viewport[0] + viewport[1] + w), viewport[1]) y_min = viewport[2] y_max = viewport[3] else: h = height / width * (viewport[1] - viewport[0]) x_min = viewport[0] x_max = viewport[1] y_min = max(0.5 * (viewport[3] + viewport[2] - h), viewport[2]) y_max = min(0.5 * (viewport[3] + viewport[2] + h), viewport[3]) if 'cmap' in _plt.kwargs: warnings.warn('The parameter "cmap" has been replaced by "colormap". The value of "cmap" will be ignored.', stacklevel=3) colormap = _plt.kwargs.get('colormap', gr.COLORMAP_VIRIDIS) if colormap is not None: gr.setcolormap(colormap) gr.selntran(0) if isinstance(I, basestring): gr.drawimage(x_min, x_max, y_min, y_max, width, height, data) else: gr.cellarray(x_min, x_max, y_min, y_max, width, height, data) if 'title' in _plt.kwargs: gr.savestate() gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP) gr.textext(0.5 * (viewport[0] + viewport[1]), vp[3], _plt.kwargs['title']) gr.restorestate() gr.selntran(1)
def _plot_img(I): global _plt if isinstance(I, basestring): width, height, data = gr.readimage(I) if width == 0 or height == 0: return else: I = np.array(I) width, height = I.shape data = np.array(1000 + (1.0 * I - I.min()) / I.ptp() * 255, np.int32) if _plt.kwargs['clear']: gr.clearws() if not _plt.kwargs['ax']: _set_viewport('line', _plt.kwargs['subplot']) viewport = _plt.kwargs['viewport'] vp = _plt.kwargs['vp'] if width * (viewport[3] - viewport[2]) < height * (viewport[1] - viewport[0]): w = width / height * (viewport[3] - viewport[2]) x_min = max(0.5 * (viewport[0] + viewport[1] - w), viewport[0]) x_max = min(0.5 * (viewport[0] + viewport[1] + w), viewport[1]) y_min = viewport[2] y_max = viewport[3] else: h = height / width * (viewport[1] - viewport[0]) x_min = viewport[0] x_max = viewport[1] y_min = max(0.5 * (viewport[3] + viewport[2] - h), viewport[2]) y_max = min(0.5 * (viewport[3] + viewport[2] + h), viewport[3]) gr.setcolormap(_plt.kwargs.get('cmap', 1)) gr.selntran(0) if isinstance(I, basestring): gr.drawimage(x_min, x_max, y_min, y_max, width, height, data) else: gr.cellarray(x_min, x_max, y_min, y_max, width, height, data) if 'title' in _plt.kwargs: gr.savestate() gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP) gr.textext(0.5 * (viewport[0] + viewport[1]), vp[3], _plt.kwargs['title']) gr.restorestate() gr.selntran(1)
def draw(self): gr.clearws() gr.setwswindow(0, self._sizex, 0, self._sizey) gr.setviewport(0, self._sizex, 0, self._sizey) if self._projection == 'perspective': gr.setperspectiveprojection(near_plane=0.1, far_plane=1000, fov=15) else: gr.setorthographicprojection(left=-60, right=60, bottom=-60, top=60, near_plane=-60, far_plane=60) gr.axes3d(10, 10, 10, 50, 50, 0, 2, 2, 2, -0.0075) self.update()
def _plot_img(I): global _plt if isinstance(I, basestring): width, height, data = gr.readimage(I) if width == 0 or height == 0: return else: I = np.array(I) width, height = I.shape data = np.array(1000+(1.0*I - I.min()) / I.ptp() * 255, np.int32) if _plt.kwargs['clear']: gr.clearws() if not _plt.kwargs['ax']: _set_viewport('line', _plt.kwargs['subplot']) viewport = _plt.kwargs['viewport'] vp = _plt.kwargs['vp'] if width * (viewport[3] - viewport[2]) < height * (viewport[1] - viewport[0]): w = width / height * (viewport[3] - viewport[2]) x_min = max(0.5 * (viewport[0] + viewport[1] - w), viewport[0]) x_max = min(0.5 * (viewport[0] + viewport[1] + w), viewport[1]) y_min = viewport[2] y_max = viewport[3] else: h = height / width * (viewport[1] - viewport[0]) x_min = viewport[0] x_max = viewport[1] y_min = max(0.5 * (viewport[3] + viewport[2] - h), viewport[2]) y_max = min(0.5 * (viewport[3] + viewport[2] + h), viewport[3]) gr.setcolormap(_plt.kwargs.get('cmap', 1)) gr.selntran(0) if isinstance(I, basestring): gr.drawimage(x_min, x_max, y_min, y_max, width, height, data) else: gr.cellarray(x_min, x_max, y_min, y_max, width, height, data) if 'title' in _plt.kwargs: gr.savestate() gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP) gr.textext(0.5 * (viewport[0] + viewport[1]), vp[3], _plt.kwargs['title']) gr.restorestate() gr.selntran(1)
def pendulum(t, theta, omega, acceleration): gr.clearws() gr.setviewport(0, 1, 0, 1) x, y = (sin(theta) * 3.0, -cos(theta) * 3.0) gr3.clear() # draw pivot point gr3.drawspheremesh(1, (0, 0, 0), (0.4, 0.4, 0.4), 0.1) # draw rod gr3.drawcylindermesh(1, (0, 0, 0), (x, y, 0), (0.6, 0.6, 0.6), 0.05, 3.0) # draw sphere gr3.drawspheremesh(1, (x, y, 0), (1, 1, 1), 0.25) # show angular velocity V = 0.3 * omega - sign(omega) * 0.15 gr3.drawcylindermesh(1, (x, y, 0), (cos(theta), sin(theta), 0), (0, 0, 1), 0.05, V) gr3.drawconemesh(1, (x + cos(theta) * V, y + sin(theta) * V, 0), (-y, x, 0), (0, 0, 1), 0.1, sign(omega) * 0.25) # show angular acceleration A = 0.3 * acceleration gr3.drawcylindermesh(1, (x, y, 0), (sin(theta), cos(theta), 0), (1, 0, 0), 0.05, A) gr3.drawconemesh(1, (x + sin(theta) * A, y + cos(theta) * A, 0), (x, -y, 0), (1, 0, 0), 0.1, 0.25) # draw GR3 objects gr3.drawimage(0, 1, 0.15, 0.85, 500, 350, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.settextfontprec(2, gr.TEXT_PRECISION_STRING) gr.setcharheight(0.024) gr.settextcolorind(1) gr.textext(0.05, 0.96, 'Damped Pendulum') gr.mathtex(0.05, 0.9, '\\omega=\\dot{\\theta}') gr.mathtex(0.05, 0.83, '\\dot{\\omega}=-\\gamma\\omega-\\frac{g}{l}sin(\\theta)') gr.setcharheight(0.020) gr.textext(0.05, 0.20, 't:%7.2f' % t) gr.textext(0.05, 0.16, '\\theta:%7.2f' % (theta / pi * 180)) gr.settextcolorind(4) gr.textext(0.05, 0.12, '\\omega:%7.2f' % omega) gr.settextcolorind(2) gr.textext(0.05, 0.08, 'y_{A}:%6.2f' % acceleration) gr.updatews() return
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
def pendulum(t, theta, omega, acceleration): gr.clearws() gr.setviewport(0, 1, 0, 1) x = [0.5, 0.5 + np.sin(theta) * 0.4] y = [0.8, 0.8 - np.cos(theta) * 0.4] # draw pivot point gr.fillarea([0.46, 0.54, 0.54, 0.46], [0.79, 0.79, 0.81, 0.81]), gr.setlinecolorind(1) gr.setlinewidth(2) gr.polyline(x, y) # draw rod gr.setmarkersize(5) gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) gr.setmarkercolorind(86) gr.polymarker([x[1]], [y[1]]) # draw bob gr.setlinecolorind(4) V = 0.05 * omega # show angular velocity gr.drawarrow(x[1], y[1], x[1] + V * np.cos(theta), y[1] + V * np.sin(theta)) gr.setlinecolorind(2) A = 0.05 * acceleration # show angular acceleration gr.drawarrow(x[1], y[1], x[1] + A * np.sin(theta), y[1] + A * np.cos(theta)) gr.settextfontprec(2, gr.TEXT_PRECISION_STRING) gr.setcharheight(0.032) gr.settextcolorind(1) gr.textext(0.05, 0.95, 'Damped Pendulum') gr.setcharheight(0.040) gr.mathtex(0.4, 0.22, '\\omega=\\dot{\\theta}') gr.mathtex(0.4, 0.1, '\\dot{\\omega}=-\\gamma\\omega-\\frac{g}{l}sin(\\theta)') gr.setcharheight(0.028) gr.textext(0.05, 0.22, 't:%7.2f' % t) gr.textext(0.05, 0.16, '\\theta:%7.2f' % (theta / np.pi * 180)) gr.settextcolorind(4) gr.textext(0.05, 0.10, '\\omega:%7.2f' % omega) gr.settextcolorind(2) gr.textext(0.05, 0.04, 'y_{A}:%6.2f' % acceleration) gr.updatews()
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()
def pendulum(t, theta, omega, acceleration): gr.clearws() gr.setviewport(0, 1, 0, 1) x = [0.5, 0.5 + sin(theta) * 0.4] y = [0.8, 0.8 - cos(theta) * 0.4] # draw pivot point gr.fillarea([0.46, 0.54, 0.54, 0.46], [0.79, 0.79, 0.81, 0.81]), gr.setlinecolorind(1) gr.setlinewidth(2) gr.polyline(x, y) # draw rod gr.setmarkersize(5) gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) gr.setmarkercolorind(86) gr.polymarker([x[1]], [y[1]]) # draw bob gr.setlinecolorind(4) V = 0.05 * omega # show angular velocity gr.drawarrow(x[1], y[1], x[1] + V*cos(theta), y[1] + V*sin(theta)) gr.setlinecolorind(2) A = 0.05 * acceleration # show angular acceleration gr.drawarrow(x[1], y[1], x[1] + A*sin(theta), y[1] + A*cos(theta)) gr.settextfontprec(2, gr.TEXT_PRECISION_STRING) gr.setcharheight(0.032) gr.settextcolorind(1) gr.textext(0.05, 0.95, 'Damped Pendulum') gr.setcharheight(0.040) gr.mathtex(0.4, 0.22, '\\omega=\\dot{\\theta}') gr.mathtex(0.4, 0.1, '\\dot{\\omega}=-\\gamma\\omega-\\frac{g}{l}sin(\\theta)') gr.setcharheight(0.028) gr.textext(0.05, 0.22, 't:%7.2f' % t) gr.textext(0.05, 0.16, '\\theta:%7.2f' % (theta / pi * 180)) gr.settextcolorind(4) gr.textext(0.05, 0.10, '\\omega:%7.2f' % omega) gr.settextcolorind(2) gr.textext(0.05, 0.04, 'y_{A}:%6.2f' % acceleration) gr.updatews()
def printDialog(self, documentName="qtgr-untitled"): printer = QPrinter(QPrinter.HighResolution) printer.setDocName(documentName) painter = QPainter() dlg = QPrintDialog(printer) if dlg.exec_() == QPrintDialog.Accepted: painter.begin(printer) os.environ["GKSconid"] = getGKSConnectionId(self, painter) # upscaling to paper size and # alignment (horizontal and vertical centering) xscale = printer.pageRect().width() / float(self.width()) yscale = printer.pageRect().height() / float(self.height()) scale = min(xscale, yscale) painter.translate( printer.paperRect().x() + printer.pageRect().width() / 2, printer.paperRect().y() + printer.pageRect().height() / 2) painter.scale(scale, scale) painter.translate(-self.width() / 2, -self.height() / 2) gr.clearws() self.draw() gr.updatews() painter.end()
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()
def printDialog(self, documentName="qtgr-untitled"): printer = QPrinter(QPrinter.HighResolution) printer.setDocName(documentName) painter = QPainter() dlg = QPrintDialog(printer) if dlg.exec_() == QPrintDialog.Accepted: painter.begin(printer) os.environ["GKSconid"] = getGKSConnectionId(self, painter) # upscaling to paper size and # alignment (horizontal and vertical centering) xscale = printer.pageRect().width() / float(self.width()) yscale = printer.pageRect().height() / float(self.height()) scale = min(xscale, yscale) painter.translate(printer.paperRect().x() + printer.pageRect().width() / 2, printer.paperRect().y() + printer.pageRect().height() / 2) painter.scale(scale, scale) painter.translate(-self.width() / 2, -self.height() / 2) gr.clearws() self.draw() gr.updatews() painter.end()
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
import gr import gr3 gr.setviewport(0, 1, 0, 1) for i in range(360): gr.clearws() gr3.clear() gr3.drawmolecule('dna.xyz', bond_delta=2, tilt=45, rotation=i) gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.settextcolorind(0) gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP) gr.text(0.5, 1, "DNA rendered using gr3.drawmolecule") gr.updatews()
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)
def display(): global window_width, window_height, rx gr3.setbackgroundcolor(1, 1, 1, 1) # set up camera gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10 * math.cos(-rx * math.pi / 2), 10 * math.sin(-rx * math.pi / 2), 0, 0, 0, 0, 0, 0, 1) gr3.drawimage(0, window_width, 0, window_height, window_width, window_height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL) glViewport(0, 0, window_width, window_height) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glColor4f(1, 0, 0, 1) x, y = 0, 0.22 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"This is a GLUT window in which GR3 renders": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) y -= 0.05 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"a scene. You can drag the mouse to rotate the": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) y -= 0.05 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"molecule or right-click to open a context menu.": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glutSwapBuffers() gr.clearws() selntran(0) gr3.setquality(4) gr3.drawimage(0, 0.5, 0.5, 1, 250, 250, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.settextcolorind(1) gr.settextfontprec(6, 0) x = list(range(5)) y = list(range(5)) nominalWindowHeight = 500.0 pointSize = (8, 9, 10, 11, 12, 14, 18, 24, 36) s = "i\\hbar\\frac{\\partial\\psi}{\\partial t} = \\frac{\\hbar^2}{2m}\\nabla^2\\psi + V(\\mathbf{r})\\psi" x = 0.9 y = 0.9 gr.settextalign(3, 3) for i in range(8): gr.setcharheight(pointSize[i] / nominalWindowHeight) gr.mathtex(x, y, s) y -= 4 * pointSize[i] / nominalWindowHeight gr.setcharheight(0.1) gr.mathtex(0.9, 0.05, "Hello World!") gr.settextcolorind(8) gr.text(0.9, 0.05, "Hello World!") gr.updatews() gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10 * math.cos(-rx * math.pi / 2), 10 * math.sin(-rx * math.pi / 2), 0, 0, 0, 0, 0, 0, 1)
def _plot_data(**kwargs): global _plt _plt.kwargs.update(kwargs) if not _plt.args: return kind = _plt.kwargs.get('kind', 'line') if _plt.kwargs['clear']: gr.clearws() if kind in ('imshow', 'isosurface'): _set_viewport(kind, _plt.kwargs['subplot']) elif not _plt.kwargs['ax']: _set_viewport(kind, _plt.kwargs['subplot']) _set_window(kind) if kind == 'polar': _draw_polar_axes() else: _draw_axes(kind) gr.setcolormap(_plt.kwargs.get('colormap', gr.COLORMAP_COOLWARM)) gr.uselinespec(" ") for x, y, z, c, spec in _plt.args: gr.savestate() if 'alpha' in _plt.kwargs: gr.settransparency(_plt.kwargs['alpha']) if kind == 'line': mask = gr.uselinespec(spec) if mask in (0, 1, 3, 4, 5): gr.polyline(x, y) if mask & 2: gr.polymarker(x, y) elif kind == 'scatter': gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) if z is not None or c is not None: if c is not None: c_min = c.min() c_ptp = c.ptp() for i in range(len(x)): if z is not None: gr.setmarkersize(z[i] / 100.0) if c is not None: c_index = 1000 + int(255 * (c[i]-c_min)/c_ptp) gr.setmarkercolorind(c_index) gr.polymarker([x[i]], [y[i]]) else: gr.polymarker(x, y) elif kind == 'stem': gr.setlinecolorind(1) gr.polyline(_plt.kwargs['window'][:2], [0, 0]) gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) gr.uselinespec(spec) for xi, yi in zip(x, y): gr.polyline([xi, xi], [0, yi]) gr.polymarker(x, y) elif kind == 'hist': y_min = _plt.kwargs['window'][2] for i in range(1, len(y)+1): gr.setfillcolorind(989) gr.setfillintstyle(gr.INTSTYLE_SOLID) gr.fillrect(x[i-1], x[i], y_min, y[i-1]) gr.setfillcolorind(1) gr.setfillintstyle(gr.INTSTYLE_HOLLOW) gr.fillrect(x[i-1], x[i], y_min, y[i-1]) elif kind == 'contour': z_min, z_max = _plt.kwargs['zrange'] gr.setspace(z_min, z_max, 0, 90) h = [z_min + i/19*(z_max-z_min) for i in range(20)] if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) gr.contour(x, y, h, z, 1000) _colorbar(0, 20) elif kind == 'contourf': z_min, z_max = _plt.kwargs['zrange'] gr.setspace(z_min, z_max, 0, 90) if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = (200, 200) if _plt.kwargs['scale'] & gr.OPTION_Z_LOG != 0: z = np.log(z) gr.surface(x, y, z, gr.OPTION_CELL_ARRAY) _colorbar() elif kind == 'hexbin': nbins = _plt.kwargs.get('nbins', 40) cntmax = gr.hexbin(x, y, nbins) if cntmax > 0: _plt.kwargs['zrange'] = (0, cntmax) _colorbar() elif kind == 'heatmap': x_min, x_max, y_min, y_max = _plt.kwargs['window'] width, height = z.shape cmap = _colormap() icmap = np.zeros(256, np.uint32) for i in range(256): r, g, b, a = cmap[i] icmap[i] = (int(r*255) << 0) + (int(g*255) << 8) + (int(b*255) << 16) + (int(a*255) << 24) z_range = np.ptp(z) if z_range > 0: data = (z - np.min(z)) / z_range * 255 else: data = np.zeros((width, height)) rgba = np.zeros((width, height), np.uint32) for x in range(width): for y in range(height): rgba[x, y] = icmap[int(data[x, y])] gr.drawimage(x_min, x_max, y_min, y_max, width, height, rgba) _colorbar() elif kind == 'wireframe': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 50, 50) gr.setfillcolorind(0) z.shape = np.prod(z.shape) gr.surface(x, y, z, gr.OPTION_FILLED_MESH) _draw_axes(kind, 2) elif kind == 'surface': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) if _plt.kwargs.get('accelerate', True): gr3.clear() gr3.surface(x, y, z, gr.OPTION_COLORED_MESH) else: gr.surface(x, y, z, gr.OPTION_COLORED_MESH) _draw_axes(kind, 2) _colorbar(0.05) elif kind == 'plot3': gr.polyline3d(x, y, z) _draw_axes(kind, 2) elif kind == 'scatter3': gr.polymarker3d(x, y, z) _draw_axes(kind, 2) elif kind == 'imshow': _plot_img(z) elif kind == 'isosurface': _plot_iso(z) elif kind == 'polar': gr.uselinespec(spec) _plot_polar(x, y) elif kind == 'trisurf': gr.trisurface(x, y, z) _draw_axes(kind, 2) _colorbar(0.05) gr.restorestate() if kind in ('line', 'scatter', 'stem') and 'labels' in _plt.kwargs: _draw_legend() if _plt.kwargs['update']: gr.updatews() if gr.isinline(): return gr.show()
def display(): global window_width, window_height, rx gr3.setbackgroundcolor(1,1,1,1) # Kamera einstellen gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10*math.cos(-rx*math.pi/2), 10*math.sin(-rx*math.pi/2), 0, 0, 0, 0, 0, 0, 1) gr3.drawimage(0, window_width, 0, window_height, window_width, window_height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL) glViewport(0,0,window_width,window_height); glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glColor4f(1,0,0,1) x, y = 0, 0.22 glRasterPos2f(x*2-1,y*2-1) for c in u"Dies ist ein GLUT-Fenster, in dem mit GR3 eine": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,ord(c)) y-=0.05 glRasterPos2f(x*2-1,y*2-1) for c in u"Szene gerendert wird. Mit der Maus kann man": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,ord(c)) y-=0.05 glRasterPos2f(x*2-1,y*2-1) for c in u"das dargestellte Molekül rotieren lassen.": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,ord(c)) y-=0.04 glRasterPos2f(x*2-1,y*2-1) for c in u"(Rechtsklick öffnet das Kontextmenü)": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12,ord(c)) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glutSwapBuffers() gr.clearws() selntran(0) gr3.setquality(4) gr3.drawimage(0, 0.5, 0.5, 1, 250, 250, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.settextcolorind(1) gr.settextfontprec(6,0) x = list(range(5)) y = list(range(5)) nominalWindowHeight = 500.0 pointSize = ( 8, 9, 10, 11, 12, 14, 18, 24, 36 ) s = "i\\hbar\\frac{\\partial\\psi}{\\partial t} = \\frac{\\hbar^2}{2m}\\nabla^2\\psi + V(\\mathbf{r})\\psi" x = 0.9 y = 0.9; gr.settextalign(3, 3) for i in range(8): gr.setcharheight(pointSize[i] / nominalWindowHeight) gr.mathtex(x, y, s) y -= 4 * pointSize[i] / nominalWindowHeight gr.setcharheight(0.1) gr.mathtex(0.9, 0.05, "Hello World!") gr.settextcolorind(8) gr.text(0.9, 0.05, "Hello World!") gr.updatews() gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10*math.cos(-rx*math.pi/2), 10*math.sin(-rx*math.pi/2), 0, 0, 0, 0, 0, 0, 1)
def display(): global window_width, window_height, rx gr3.setbackgroundcolor(1, 1, 1, 1) # Kamera einstellen gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10 * math.cos(-rx * math.pi / 2), 10 * math.sin(-rx * math.pi / 2), 0, 0, 0, 0, 0, 0, 1) gr3.drawimage(0, window_width, 0, window_height, window_width, window_height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL) glViewport(0, 0, window_width, window_height) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMatrixMode(GL_PROJECTION) glPushMatrix() glLoadIdentity() glColor4f(1, 0, 0, 1) x, y = 0, 0.22 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"Dies ist ein GLUT-Fenster, in dem mit GR3 eine": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) y -= 0.05 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"Szene gerendert wird. Mit der Maus kann man": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) y -= 0.05 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"das dargestellte Molekül rotieren lassen.": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c)) y -= 0.04 glRasterPos2f(x * 2 - 1, y * 2 - 1) for c in u"(Rechtsklick öffnet das Kontextmenü)": glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, ord(c)) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glMatrixMode(GL_MODELVIEW) glPopMatrix() glMatrixMode(GL_PROJECTION) glPopMatrix() glutSwapBuffers() gr.clearws() selntran(0) gr3.setquality(4) gr3.drawimage(0, 0.5, 0.5, 1, 250, 250, gr3.GR3_Drawable.GR3_DRAWABLE_GKS) gr.settextcolorind(1) gr.settextfontprec(6, 0) x = list(range(5)) y = list(range(5)) nominalWindowHeight = 500.0 pointSize = (8, 9, 10, 11, 12, 14, 18, 24, 36) s = "i\\hbar\\frac{\\partial\\psi}{\\partial t} = \\frac{\\hbar^2}{2m}\\nabla^2\\psi + V(\\mathbf{r})\\psi" x = 0.9 y = 0.9 gr.settextalign(3, 3) for i in range(8): gr.setcharheight(pointSize[i] / nominalWindowHeight) gr.mathtex(x, y, s) y -= 4 * pointSize[i] / nominalWindowHeight gr.setcharheight(0.1) gr.mathtex(0.9, 0.05, "Hello World!") gr.settextcolorind(8) gr.text(0.9, 0.05, "Hello World!") gr.updatews() gr3.setcameraprojectionparameters(45, 1, 200) gr3.cameralookat(10 * math.cos(-rx * math.pi / 2), 10 * math.sin(-rx * math.pi / 2), 0, 0, 0, 0, 0, 0, 1)
def _plot_data(**kwargs): global _plt _plt.kwargs.update(kwargs) if not _plt.args: return kind = _plt.kwargs.get('kind', 'line') if _plt.kwargs['clear']: gr.clearws() if kind in ('imshow', 'isosurface'): _set_viewport(kind, _plt.kwargs['subplot']) elif not _plt.kwargs['ax']: _set_viewport(kind, _plt.kwargs['subplot']) _set_window(kind) if kind == 'polar': _draw_polar_axes() else: _draw_axes(kind) if 'cmap' in _plt.kwargs: warnings.warn('The parameter "cmap" has been replaced by "colormap". The value of "cmap" will be ignored.', stacklevel=3) colormap = _plt.kwargs.get('colormap', gr.COLORMAP_VIRIDIS) if colormap is not None: gr.setcolormap(colormap) gr.uselinespec(" ") for x, y, z, c, spec in _plt.args: gr.savestate() if 'alpha' in _plt.kwargs: gr.settransparency(_plt.kwargs['alpha']) if kind == 'line': mask = gr.uselinespec(spec) if mask in (0, 1, 3, 4, 5): gr.polyline(x, y) if mask & 2: gr.polymarker(x, y) elif kind == 'scatter': gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) if z is not None or c is not None: if c is not None: c_min = c.min() c_ptp = c.ptp() for i in range(len(x)): if z is not None: gr.setmarkersize(z[i] / 100.0) if c is not None: c_index = 1000 + int(255 * (c[i]-c_min)/c_ptp) gr.setmarkercolorind(c_index) gr.polymarker([x[i]], [y[i]]) else: gr.polymarker(x, y) elif kind == 'stem': gr.setlinecolorind(1) gr.polyline(_plt.kwargs['window'][:2], [0, 0]) gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) gr.uselinespec(spec) for xi, yi in zip(x, y): gr.polyline([xi, xi], [0, yi]) gr.polymarker(x, y) elif kind == 'hist': y_min = _plt.kwargs['window'][2] for i in range(1, len(y)+1): gr.setfillcolorind(989) gr.setfillintstyle(gr.INTSTYLE_SOLID) gr.fillrect(x[i-1], x[i], y_min, y[i-1]) gr.setfillcolorind(1) gr.setfillintstyle(gr.INTSTYLE_HOLLOW) gr.fillrect(x[i-1], x[i], y_min, y[i-1]) elif kind == 'contour': z_min, z_max = _plt.kwargs['zrange'] gr.setspace(z_min, z_max, 0, 90) h = [z_min + i/19*(z_max-z_min) for i in range(20)] if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) gr.contour(x, y, h, z, 1000) _colorbar(0, 20) elif kind == 'contourf': z_min, z_max = _plt.kwargs['zrange'] gr.setspace(z_min, z_max, 0, 90) scale = _plt.kwargs['scale'] gr.setscale(scale) if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = (200, 200) gr.surface(x, y, z, gr.OPTION_CELL_ARRAY) _colorbar() elif kind == 'hexbin': nbins = _plt.kwargs.get('nbins', 40) cntmax = gr.hexbin(x, y, nbins) if cntmax > 0: _plt.kwargs['zrange'] = (0, cntmax) _colorbar() elif kind == 'heatmap': x_min, x_max, y_min, y_max = _plt.kwargs['window'] width, height = z.shape cmap = _colormap() icmap = np.zeros(256, np.uint32) for i in range(256): r, g, b, a = cmap[i] icmap[i] = (int(r*255) << 0) + (int(g*255) << 8) + (int(b*255) << 16) + (int(a*255) << 24) z_min, z_max = _plt.kwargs.get('zlim', (np.min(z), np.max(z))) if z_max < z_min: z_max, z_min = z_min, z_max if z_max > z_min: data = (z - z_min) / (z_max - z_min) * 255 else: data = np.zeros((width, height)) rgba = np.zeros((width, height), np.uint32) for x in range(width): for y in range(height): rgba[x, y] = icmap[int(data[x, y])] gr.drawimage(x_min, x_max, y_min, y_max, width, height, rgba) _colorbar() elif kind == 'wireframe': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 50, 50) gr.setfillcolorind(0) z.shape = np.prod(z.shape) gr.surface(x, y, z, gr.OPTION_FILLED_MESH) _draw_axes(kind, 2) elif kind == 'surface': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) if _plt.kwargs.get('accelerate', True): gr3.clear() gr3.surface(x, y, z, gr.OPTION_COLORED_MESH) else: gr.surface(x, y, z, gr.OPTION_COLORED_MESH) _draw_axes(kind, 2) _colorbar(0.05) elif kind == 'plot3': gr.polyline3d(x, y, z) _draw_axes(kind, 2) elif kind == 'scatter3': gr.polymarker3d(x, y, z) _draw_axes(kind, 2) elif kind == 'imshow': _plot_img(z) elif kind == 'isosurface': _plot_iso(z) elif kind == 'polar': gr.uselinespec(spec) _plot_polar(x, y) elif kind == 'trisurf': gr.trisurface(x, y, z) _draw_axes(kind, 2) _colorbar(0.05) elif kind == 'tricont': zmin, zmax = _plt.kwargs['zrange'] levels = np.linspace(zmin, zmax, 20) gr.tricontour(x, y, z, levels) gr.restorestate() if kind in ('line', 'scatter', 'stem') and 'labels' in _plt.kwargs: _draw_legend() if _plt.kwargs['update']: gr.updatews() if gr.isinline(): return gr.show()
def _plot_data(**kwargs): global _plt _plt.kwargs.update(kwargs) if not _plt.args: return kind = _plt.kwargs.get('kind', 'line') if _plt.kwargs['clear']: gr.clearws() if kind in ('imshow', 'isosurface'): _set_viewport(kind, _plt.kwargs['subplot']) elif not _plt.kwargs['ax']: _set_viewport(kind, _plt.kwargs['subplot']) _set_window(kind) _draw_axes(kind) gr.setcolormap(_plt.kwargs.get('colormap', gr.COLORMAP_COOLWARM)) gr.uselinespec(" ") for x, y, z, c, spec in _plt.args: gr.savestate() if 'alpha' in _plt.kwargs: gr.settransparency(_plt.kwargs['alpha']) if kind == 'line': mask = gr.uselinespec(spec) if mask in (0, 1, 3, 4, 5): gr.polyline(x, y) if mask & 2: gr.polymarker(x, y) elif kind == 'scatter': gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) if z is not None or c is not None: if c is not None: c_min = c.min() c_ptp = c.ptp() for i in range(len(x)): if z is not None: gr.setmarkersize(z[i] / 100.0) if c is not None: c_index = 1000 + int(255 * (c[i]-c_min)/c_ptp) gr.setmarkercolorind(c_index) gr.polymarker([x[i]], [y[i]]) else: gr.polymarker(x, y) elif kind == 'stem': gr.setlinecolorind(1) gr.polyline(_plt.kwargs['window'][:2], [0, 0]) gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE) gr.uselinespec(spec) for xi, yi in zip(x, y): gr.polyline([xi, xi], [0, yi]) gr.polymarker(x, y) elif kind == 'hist': y_min = _plt.kwargs['window'][2] for i in range(1, len(y)): gr.setfillcolorind(989) gr.setfillintstyle(gr.INTSTYLE_SOLID) gr.fillrect(x[i-1], x[i], y_min, y[i]) gr.setfillcolorind(1) gr.setfillintstyle(gr.INTSTYLE_HOLLOW) gr.fillrect(x[i-1], x[i], y_min, y[i]) elif kind == 'contour': z_min, z_max = _plt.kwargs['zrange'] gr.setspace(z_min, z_max, 0, 90) h = [z_min + i/19*(z_max-z_min) for i in range(20)] if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) gr.contour(x, y, h, z, 1000) _colorbar(0, 20) elif kind == 'contourf': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = (200, 200) if _plt.kwargs['scale'] & gr.OPTION_Z_LOG != 0: z = np.log(z) width, height = z.shape data = np.array(1000+(z-z.min()) / z.ptp() * 255, np.int32) x_min, x_max = _plt.kwargs['xrange'] y_min, y_max = _plt.kwargs['yrange'] gr.cellarray(x_min, x_max, y_max, y_min, width, height, data) _colorbar() elif kind == 'wireframe': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 50, 50) gr.setfillcolorind(0) z.shape = np.prod(z.shape) gr.surface(x, y, z, gr.OPTION_FILLED_MESH) _draw_axes(kind, 2) elif kind == 'surface': if x.shape == y.shape == z.shape: x, y, z = gr.gridit(x, y, z, 200, 200) z.shape = np.prod(z.shape) if _plt.kwargs.get('accelerate', True): gr3.surface(x, y, z, gr.OPTION_COLORED_MESH) else: gr.surface(x, y, z, gr.OPTION_COLORED_MESH) _draw_axes(kind, 2) _colorbar(0.05) elif kind == 'plot3': gr.polyline3d(x, y, z) _draw_axes(kind, 2) elif kind == 'scatter3': gr.polymarker3d(x, y, z) _draw_axes(kind, 2) elif kind == 'imshow': _plot_img(z) elif kind == 'isosurface': _plot_iso(z) gr.restorestate() if kind in ('line', 'scatter', 'stem') and 'labels' in _plt.kwargs: _draw_legend() if _plt.kwargs['update']: gr.updatews() if gr.isinline(): return gr.show()
# coding: utf8 from gr import selntran, settextfontprec, settextalign, setcharheight, clearws, setcharup, text, inqtext, fillarea, updatews from math import pi, sin, cos from numpy import linspace s = 'Using inline math $\\frac{2hc^2}{\\lambda^5} \\frac{1}{e^{\\frac{hc}{\\lambda k_B T}} - 1}$ in GR text\nmixed with raw strings ' + r'$- \frac{{\hbar ^2}}{{2m}}\frac{{\partial ^2 \psi (x,t)}}{{\partial x^2 }} + U(x)\psi (x,t) = i\hbar \frac{{\partial \psi (x,t)}}{{\partial t}}$' + '\n– with line breaks\nand UTF-8 characters (ħπ),\nand rendered using GR\'s text attributes' selntran(0) settextfontprec(232, 3) settextalign(2, 3) setcharheight(0.02) for phi in linspace(0, 2 * pi, 360): clearws() setcharup(sin(phi), cos(phi)) text(0.5, 0.5, s) tbx, tby = inqtext(0.5, 0.5, s) fillarea(tbx, tby) updatews()
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))