def _plot_polar(theta, rho): global _plt window = _plt.kwargs['window'] r_min, r_max = window[2:] rho = (rho - r_min) / (r_max - r_min) x = rho * np.cos(theta) y = rho * np.sin(theta) gr.polyline(x, y)
def draw_vehicle_ellipse(x, P): ell = covariance_ellipse(x[0:2], P[0:2, 0:2], n_sigma=2) gr.settransparency(0.8) gr.setlinewidth(2) # gr.setlinecolorind(983) gr.polyline(ell[0, :], ell[1, :]) gr.setlinewidth(1) gr.settransparency(1.0)
def draw_vehicle(x): """Draw the vehicle CM as a circle. Draw a line for the vehicle heading. x = [x, y, phi] """ gr.setmarkertype(gr.MARKERTYPE_CIRCLE) gr.setmarkersize(2) gr.setmarkercolorind(1) # black gr.polymarker([x[0]], [x[1]]) xh = [x[0], x[0] + 5 * np.cos(x[2])] yh = [x[1], x[1] + 5 * np.sin(x[2])] gr.polyline(xh, yh)
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 drawGR(self): if self.linetype is not None and self.x: # preserve old values lcolor = gr.inqlinecolorind() gr.setlinewidth(2) gr.setlinecolorind(self.linecolor) for xi, yi in zip(self.x, self.y): gr.polyline([xi, xi], [0, yi]) # restore old values gr.setlinecolorind(lcolor) gr.setlinewidth(1)
def drawGR(self): lwidth = gr.inqlinewidth() gr.setlinewidth(0.) PlotAxes.drawGR(self) if self.drawxylines: xmin, xmax, ymin, ymax = self.getWindow() linecolor = gr.inqlinecolorind() gr.setlinecolorind(self.xylinecolor) for xpos in self.xlines: gr.polyline([xpos, xpos], [ymin, ymax]) for ypos in self.ylines: gr.polyline([xmin, xmax], [ypos, ypos]) gr.setlinecolorind(linecolor) gr.setlinewidth(lwidth)
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 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 _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()
def _draw_polar_axes(): global _plt viewport = _plt.kwargs['viewport'] diag = ((viewport[1]-viewport[0])**2 + (viewport[3]-viewport[2])**2)**0.5 charheight = max(0.018 * diag, 0.012) window = _plt.kwargs['window'] r_min, r_max = window[2], window[3] gr.savestate() gr.setcharheight(charheight) gr.setlinetype(gr.LINETYPE_SOLID) tick = 0.5 * gr.tick(r_min, r_max) n = int(round((r_max - r_min) / tick + 0.5)) for i in range(n+1): r = i / n if i % 2 == 0: gr.setlinecolorind(88) if i > 0: gr.drawarc(-r, r, -r, r, 0, 359) gr.settextalign(gr.TEXT_HALIGN_LEFT, gr.TEXT_VALIGN_HALF) x, y = gr.wctondc(0.05, r) gr.text(x, y, "%g" % (r_min + i * tick)) else: gr.setlinecolorind(90) gr.drawarc(-r, r, -r, r, 0, 359) for alpha in range(0, 360, 45): sinf = np.sin(np.radians(alpha+90)) cosf = np.cos(np.radians(alpha+90)) gr.polyline([sinf, 0], [cosf, 0]) gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_HALF) x, y = gr.wctondc(1.1 * sinf, 1.1 * cosf) gr.textext(x, y, "%d^o" % alpha) gr.restorestate()
def draw(self, wsviewport=None): if self.xvalues is not None: rangex = (self.xvalues.min(), self.xvalues.max()) else: rangex = (0, 10) if self.yvalues is not None: rangey = gr.adjustrange(self.yvalues.min(), self.yvalues.max()) else: rangey = (0, 4) if wsviewport is None: gr.setwsviewport(0, self.mwidth, 0, self.mheight) else: gr.setwsviewport(*wsviewport) gr.setwswindow(0, self.sizex, 0, self.sizey) gr.setviewport(0.075 * self.sizex, 0.95 * self.sizex, 0.075 * self.sizey, 0.95 * self.sizey) gr.setwindow(rangex[0], rangex[1], rangey[0], rangey[1]) gr.setcharheight(0.012) gr.setfillintstyle(1) gr.setfillcolorind(0) gr.fillrect(rangex[0], rangex[1], rangey[0], rangey[1]) if self.xvalues is not None and self.yvalues is not None: gr.setlinecolorind(2) gr.polyline(self.xvalues, self.yvalues) else: gr.text(0.4 * self.sizex, 0.5 * self.sizey, "no elements selected") gr.setlinecolorind(1) gr.axes(0.2, 0.2, rangex[0], rangey[0], 5, 5, 0.0075) gr.axes(0.2, 0.2, rangex[1], rangey[1], -5, -5, -0.0075) if self.title is not None: gr.text(0.8 * self.sizex, 0.9 * self.sizey, self.title)
wf = wave.open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Monty_Python.wav'), 'rb') pa = pyaudio.PyAudio() stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) gr.setwindow(0, SAMPLES, -30000, 30000) gr.setviewport(0.05, 0.95, 0.05, 0.95) gr.setlinecolorind(218) gr.setfillintstyle(1) gr.setfillcolorind(208) data = wf.readframes(SAMPLES) while data != '' and len(data) == SAMPLES * wf.getsampwidth(): stream.write(data) amplitudes = numpy.fromstring(data, dtype=numpy.short) power = abs(scipy.fftpack.fft(amplitudes / 512.0))[:SAMPLES / 2:2] - 30000 gr.clearws() gr.fillrect(0, SAMPLES, -30000, 30000) gr.grid(40, 1200, 0, 0, 5, 5) gr.polyline(range(SAMPLES)[0::4], amplitudes[0::4]) gr.polyline(range(SAMPLES)[0::4], power) gr.updatews() data = wf.readframes(SAMPLES)
import gr SAMPLES = 2048 wf = wave.open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Monty_Python.wav'), 'rb') pa = pyaudio.PyAudio() stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) gr.setwindow(0, SAMPLES, -30000, 30000) gr.setviewport(0.05, 0.95, 0.05, 0.95) gr.setlinecolorind(218) gr.setfillintstyle(1) gr.setfillcolorind(208) data = wf.readframes(SAMPLES) while data != '' and len(data) == SAMPLES * wf.getsampwidth(): stream.write(data) amplitudes = numpy.fromstring(data, dtype=numpy.short) power = abs(numpy.fft.fft(amplitudes / 512.0))[:SAMPLES/2:2] - 30000 gr.clearws() gr.fillrect(0, SAMPLES, -30000, 30000) gr.grid(40, 1200, 0, 0, 5, 5) gr.polyline(range(SAMPLES)[0::4], amplitudes[0::4]) gr.polyline(range(SAMPLES)[0::4], power) gr.updatews() data = wf.readframes(SAMPLES)
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) gr.setcharheight(0.020) gr.text(0.15, 0.965, '100Hz') gr.text(0.47, 0.965, '1kHz') gr.text(0.79, 0.965, '10kHz') gr.setlinecolorind(4) gr.polyline(f[1:], power[1:]) for p in peakind: if power[p] > 10: gr.setlinewidth(2) gr.setlinecolorind(2) xe, ye = parabolic(f[p], power, p) print(xe, ye) gr.polyline([xe] * 2, [0, ye]) gr.updatews()
def drawGR(self): if self.visible: color = gr.inqlinecolorind() gr.setlinecolorind(GRCOLORS['white']) gr.polyline(self.x, self.y) gr.setlinecolorind(color)
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))
from __future__ import print_function from __future__ import unicode_literals import sys import os import numpy as np import gr sys.path.insert(0, os.path.abspath('../src')) from statistics.rdf import Kernels x = np.linspace(-1.25, 1.25, 500) for name in dir(Kernels): if name.startswith('_') or name == 'bandwidth': continue kernel = getattr(Kernels, name) y = kernel(x) gr.beginprint(name.lower()+'.svg') gr.clearws() gr.setwsviewport(0, 0.1, 0, 0.06) gr.setviewport(0, 1, 0, 1) gr.setwindow(-1.25, 1.25, -0.25, 1.25) gr.grid(0.1, 0.1, 0, 0, 5, 5) gr.axes(0.1, 0.1, 0, 0, 5, 5, -0.01) gr.setlinewidth(2) gr.setlinecolorind(2) gr.polyline(x, y) gr.setlinecolorind(1) gr.setlinewidth(1) gr.updatews() gr.endprint()
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) gr.setcharheight(0.020) gr.text(0.15, 0.965, '100Hz') gr.text(0.47, 0.965, '1kHz') gr.text(0.79, 0.965, '10kHz') gr.setlinecolorind(4) gr.polyline(f[1:], power[1:]) for p in peakind: if power[p] > 10: gr.setlinewidth(2) gr.setlinecolorind(2) xe, ye = parabolic(f[p], power, p) print(xe, ye) gr.polyline([xe] * 2, [0, ye]) gr.updatews()
gr.setregenflags(gr.MPL_POSTPONE_UPDATE) for t in range(100): plt.cla() fig = plt.subplot(133) fig.xaxis.set_ticks([-100, 0, 100]) fig.yaxis.set_ticks([]) plt.ylim([0, 1000]) plt.hist(angles[t], 20, normed=0, facecolor='g', alpha=0.5) plt.show() gr.setviewport(0, 0.7, 0, 0.7) gr.setwindow(0.1, 0.9, 0.05, 0.85) mogli.draw(molecules[t], bonds_param=1.15, camera=((60, 0, 0), (0, 0, 0), (0, 1, 0))) gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_HALF) gr.text(0.35, 0.7, '700K (%.1f ps) # of bonds: %d' % (t / 10.0, len(angles[t]))) lens.append(len(angles[t])) if t > 0: gr.setwindow(0, 10, 3500, 5000) gr.setviewport(0.1, 0.6, 0.05, 0.1) gr.axes(1, 0, 0, 3500, 2, 0, 0.005) gr.polyline(np.arange(t + 1) / 10.0, lens) gr.updatews()
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()
wf = wave.open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Monty_Python.wav'), 'rb') pa = pyaudio.PyAudio() stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) gr.setwindow(0, SAMPLES, -30000, 30000) gr.setviewport(0.05, 0.95, 0.05, 0.95) gr.setlinecolorind(218) gr.setfillintstyle(1) gr.setfillcolorind(208) data = wf.readframes(SAMPLES) while data != '' and len(data) == SAMPLES * wf.getsampwidth(): stream.write(data) amplitudes = np.frombuffer(data, dtype=np.short) power = abs(np.fft.fft(amplitudes / 512.0))[:SAMPLES // 2:2] - 30000 gr.clearws() gr.fillrect(0, SAMPLES, -30000, 30000) gr.grid(40, 1200, 0, 0, 5, 5) gr.polyline(np.arange(0, SAMPLES, 4), amplitudes[0::4]) gr.polyline(np.arange(0, SAMPLES, 4), power) gr.updatews() data = wf.readframes(SAMPLES)
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) 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 draw_observation_lines(x, observations): for (r, b) in observations: x1, x2 = x[0], x[0] + r * np.cos(b + x[2]) y1, y2 = x[1], x[1] + r * np.sin(b + x[2]) gr.polyline([x1, x2], [y1, y2])
# fig = plt.Fig() # ax_left = fig[0, 0] # ax_right = fig[0, 1] # ax_left._configure_2d() # ax_left.title.text = 'Current Clamp Recording' # ax_left.ylabel.text = 'Membrane Potential (mV)' # ax_left.xlabel.text = 'Time (ms)' selected = None # cmap = get_colormap('hsl', value=0.5) # colors = cmap.map(np.linspace(0.1, 0.9, df.shape[0])) # colors = cmap.map(np.linspace(0.1, 0.9, CYCLE)) # ax_right.histogram(df.iloc[:,3]) # df2 = df.copy() df = df.groupby("cycle_no") gr.clearws() for i, (group_name, data) in enumerate(df): color_id = i - int(i / 256) * 256 gr.setlinecolorind(int(color_id)) gr.polyline(data["cycle_cnt"].tolist(), data["val"].tolist()) gr.updatews() """ or for i, (group_name, data) in enumerate(df): gr.pygr.oplot((data["cycle_cnt"], data["val"])) """