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()
def printDialog(self, documentName="qtgr-untitled"): printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setDocName(documentName) painter = QtGui.QPainter() dlg = QtGui.QPrintDialog(printer) if dlg.exec_() == QtGui.QPrintDialog.Accepted: painter.begin(printer) os.environ["GKSconid"] = "%x!%x" % (sip.unwrapinstance(self), sip.unwrapinstance(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); self.draw(True) gr.updatews() painter.end()
def paintEvent(self, ev): self.painter = QtGui.QPainter() self.painter.begin(self) os.environ['GKSconid'] = "%x!%x" % (sip.unwrapinstance(self), sip.unwrapinstance(self.painter)) gr.updatews() self.painter.end()
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()
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 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 paintEvent(self, event): self._painter = QtGui.QPainter() self._painter.begin(self) self._painter.fillRect(0, 0, self.width(), self.height(), self._bgColor) os.environ["GKSconid"] = getGKSConnectionId(self, self._painter) self.draw(self._clear, self._update) gr.updatews() self._painter.end()
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, ev): self.painter.begin(self) if have_pyside: environ['GKSconid'] = "%x!%x" % ( int(shiboken.getCppPointer(self)[0]), int(shiboken.getCppPointer(self.painter)[0])) else: environ["GKSconid"] = "%x!%x" % (unwrapinstance(self), unwrapinstance(self.painter)) 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 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 draw( x, x_extents=(-100, 100), y_extents=(-100, 100), landmarks=None, observations=None, particles=None, weights=None, ellipses=None, fig=None, ): """Draw vehicle state x = [x, y, theta] on the map.""" xmin, xmax = x_extents ymin, ymax = y_extents tick_spacing = (xmax - xmin) / 20 if fig is not None: print("saving", draw.i) gr.beginprint("{}_{:03d}.pdf".format(fig, draw.i)) init_plot_window(xmin, xmax, ymin, ymax) draw_vehicle(x) if landmarks is not None: draw_landmarks(landmarks) if observations is not None: draw_observation_lines(x, observations) if particles is not None: draw_particles(particles, weights=weights) if ellipses is not None: for i, ell in enumerate(ellipses): draw_ellipse(ell, alpha=(0.1)) draw_axes(tick_spacing, xmin, ymin) gr.updatews() if fig is not None: gr.endprint() draw.i += 1 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 = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setDocName(documentName) painter = QtGui.QPainter() dlg = QtGui.QPrintDialog(printer) if dlg.exec_() == QtGui.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) self.draw(True) gr.updatews() painter.end()
def draw(x, x_extents=(-100, 100), y_extents=(-100, 100), landmarks=None, observations=None, particles=None, weights=None, fig=None): """Draw vehicle state x = [x, y, theta] on the map.""" xmin, xmax = x_extents ymin, ymax = y_extents tick_spacing = (xmax - xmin) / 20 if fig is not None: print('saving', draw.i) gr.beginprint('{}_{}.pdf'.format(fig, draw.i)) init_plot_window(xmin, xmax, ymin, ymax) draw_vehicle(x) # draw_vehicle_ellipse(x, np.eye(3)) # this works; not needed yet if landmarks is not None: draw_landmarks(landmarks) if observations is not None: draw_observation_lines(x, observations) if particles is not None: draw_particles(particles, weights=weights) draw_axes(tick_spacing, xmin, ymin) gr.updatews() if fig is not None: gr.endprint() draw.i += 1 return
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 _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) # 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 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) _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()
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 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))
# 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()