def mouseEvent(self, type, target, event): """transform QMouseEvent to MouseEvent""" btn_mask = MouseEvent.NO_BUTTON mod_mask = MouseEvent.NO_MODIFIER if event.buttons() & QtCore.Qt.LeftButton: btn_mask |= MouseEvent.LEFT_BUTTON if event.buttons() & QtCore.Qt.RightButton: btn_mask |= MouseEvent.RIGHT_BUTTON # special case: store last btn_mask in MouseEvent of type MOUSE_RELEASE # to indicate which button has been released. if (type == MouseEvent.MOUSE_RELEASE and btn_mask == MouseEvent.NO_BUTTON): btn_mask = self._last_btn_mask if event.modifiers() & QtCore.Qt.ShiftModifier: mod_mask |= MouseEvent.SHIFT_MODIFIER if event.modifiers() & QtCore.Qt.ControlModifier: mod_mask |= MouseEvent.CONTROL_MODIFIER if event.modifiers() & QtCore.Qt.AltModifier: mod_mask |= MouseEvent.ALT_MODIFIER if event.modifiers() & QtCore.Qt.MetaModifier: mod_mask |= MouseEvent.META_MODIFIER if event.modifiers() & QtCore.Qt.KeypadModifier: mod_mask |= MouseEvent.KEYPAD_MODIFIER if event.modifiers() & QtCore.Qt.GroupSwitchModifier: mod_mask |= MouseEvent.GROUP_SWITCH_MODIFIER # In order to support multiple plots in one widget # it is necessary to set the window in respect to the current # `PlotAxes` below the cursor. Otherwise the window will be determined # using the internal state machine of ``gr``. coords = DeviceCoordConverter(target.dwidth, target.dheight) coords.setDC(event.x(), event.y()) plots = target._getPlotsForPoint(coords.getNDC()) window, scale = None, None if plots and len(plots) == 1: # unambitious plot axes = plots[0].getAxes(0) # use first `PlotAxes` if axes: window = axes.getWindow() scale = axes.scale gr.setscale(axes.scale) mEvent = MouseEvent(type, target.dwidth, target.dheight, event.x(), event.y(), btn_mask, mod_mask, window=window, scale=scale) # special case: # save last btn_mask for handling in MouseEvent.MOUSE_RELEASE self._last_btn_mask = btn_mask return mEvent
def _draw_legend(): global _plt viewport = _plt.kwargs['viewport'] num_labels = len(_plt.kwargs['labels']) location = _plt.kwargs.get('location', 1) gr.savestate() gr.selntran(0) gr.setscale(0) w = 0 for label in _plt.kwargs['labels']: tbx, tby = gr.inqtextext(0, 0, label) w = max(w, tbx[2]) num_lines = len(_plt.args) h = (num_lines + 1) * 0.03 if location in (8, 9, 10): px = 0.5 * (viewport[0] + viewport[1] - w) elif location in (2, 3, 6): px = viewport[0] + 0.11 else: px = viewport[1] - 0.05 - w if location in (5, 6, 7, 10): py = 0.5 * (viewport[2] + viewport[3] + h) - 0.03 elif location in (3, 4, 8): py = viewport[2] + h else: py = viewport[3] - 0.06 gr.setfillintstyle(gr.INTSTYLE_SOLID) gr.setfillcolorind(0) gr.fillrect(px - 0.08, px + w + 0.02, py + 0.03, py - 0.03 * num_lines) gr.setlinetype(gr.LINETYPE_SOLID) gr.setlinecolorind(1) gr.setlinewidth(1) gr.drawrect(px - 0.08, px + w + 0.02, py + 0.03, py - 0.03 * num_lines) i = 0 gr.uselinespec(" ") for (x, y, z, c, spec) in _plt.args: gr.savestate() mask = gr.uselinespec(spec) if mask in (0, 1, 3, 4, 5): gr.polyline([px - 0.07, px - 0.01], [py, py]) if mask & 2: gr.polymarker([px - 0.06, px - 0.02], [py, py]) gr.restorestate() gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_HALF) if i < num_labels: gr.textext(px, py, _plt.kwargs['labels'][i]) i += 1 py -= 0.03 gr.selntran(1) gr.restorestate()
def mouseEvent(self, type, target, event): """transform QMouseEvent to MouseEvent""" btn_mask = MouseEvent.NO_BUTTON mod_mask = MouseEvent.NO_MODIFIER if event.buttons() & QtCore.Qt.LeftButton: btn_mask |= MouseEvent.LEFT_BUTTON if event.buttons() & QtCore.Qt.RightButton: btn_mask |= MouseEvent.RIGHT_BUTTON # special case: store last btn_mask in MouseEvent of type MOUSE_RELEASE # to indicate which button has been released. if (type == MouseEvent.MOUSE_RELEASE and btn_mask == MouseEvent.NO_BUTTON): btn_mask = self._last_btn_mask if event.modifiers() & QtCore.Qt.ShiftModifier: mod_mask |= MouseEvent.SHIFT_MODIFIER if event.modifiers() & QtCore.Qt.ControlModifier: mod_mask |= MouseEvent.CONTROL_MODIFIER if event.modifiers() & QtCore.Qt.AltModifier: mod_mask |= MouseEvent.ALT_MODIFIER if event.modifiers() & QtCore.Qt.MetaModifier: mod_mask |= MouseEvent.META_MODIFIER if event.modifiers() & QtCore.Qt.KeypadModifier: mod_mask |= MouseEvent.KEYPAD_MODIFIER if event.modifiers() & QtCore.Qt.GroupSwitchModifier: mod_mask |= MouseEvent.GROUP_SWITCH_MODIFIER # In order to support multiple plots in one widget # it is necessary to set the window in respect to the current # `PlotAxes` below the cursor. Otherwise the window will be determined # using the internal state machine of ``gr``. coords = DeviceCoordConverter(target.dwidth, target.dheight) coords.setDC(event.x(), event.y()) plots = target._getPlotsForPoint(coords.getNDC()) window = None if plots and len(plots) == 1: # unambitious plot axes = plots[0].getAxes(0) # use first `PlotAxes` if axes: window = axes.getWindow() gr.setscale(axes.scale) mEvent = MouseEvent(type, target.dwidth, target.dheight, event.x(), event.y(), btn_mask, mod_mask, window=window) # special case: # save last btn_mask for handling in MouseEvent.MOUSE_RELEASE self._last_btn_mask = btn_mask return mEvent
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()
def _draw_legend(): global _plt viewport = _plt.kwargs['viewport'] num_labels = len(_plt.kwargs['labels']) gr.savestate() gr.selntran(0) gr.setscale(0) w = 0 for label in _plt.kwargs['labels']: tbx, tby = gr.inqtextext(0, 0, label) w = max(w, tbx[2]) px = viewport[1] - 0.05 - w py = viewport[3] - 0.06 gr.setfillintstyle(gr.INTSTYLE_SOLID) gr.setfillcolorind(0) gr.fillrect(px - 0.08, px + w + 0.02, py + 0.03, py - 0.03 * num_labels) gr.setlinetype(1) gr.setlinecolorind(1) gr.setlinewidth(1) gr.drawrect(px - 0.08, px + w + 0.02, py + 0.03, py - 0.03 * num_labels) i = 0 gr.uselinespec(" ") for (x, y, z, c, spec) in _plt.args: gr.savestate() mask = gr.uselinespec(spec) if mask in (0, 1, 3, 4, 5): gr.polyline([px - 0.07, px - 0.01], [py, py]) if mask & 2: gr.polymarker([px - 0.06, px - 0.02], [py, py]) gr.restorestate() gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_HALF) if i < num_labels: gr.textext(px, py, _plt.kwargs['labels'][i]) i += 1 py -= 0.03 gr.selntran(1) gr.restorestate()
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
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
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)
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) gr.axes(1, 5, 50, 0, 1, 2, -0.008)
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 _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)
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) gr.axes(1, 5, 50, 0, 1, 2, -0.008)