def init_visual_elements(self): self.canvas = scene.SceneCanvas(keys='interactive', show=True) self.grid = self.canvas.central_widget.add_grid(spacing=0) self.viewbox = self.grid.add_view(row=0, col=1, camera='panzoom') # add some axes self.x_axis = scene.AxisWidget(orientation='bottom') self.x_axis.stretch = (1, 0.1) self.grid.add_widget(self.x_axis, row=1, col=1) self.x_axis.link_view(self.viewbox) self.y_axis = scene.AxisWidget(orientation='left') self.y_axis.stretch = (0.1, 1) self.grid.add_widget(self.y_axis, row=0, col=0) self.y_axis.link_view(self.viewbox) # add a line plot inside the viewbox self.line_outline = scene.Line(self._get_robot_outline(), parent=self.viewbox.scene) pathx, pathy = self.path_handler.get_path() path = np.vstack((pathx, pathy)) path = path.T self.line_path = scene.Line(path, parent=self.viewbox.scene) # auto-scale to see the whole line. self.viewbox.camera.set_range() self.t = 0 self.t_max = 10 self.d_t = 0.1 app.Canvas.__init__(self, keys='interactive')
def _plot_candle_stick(self, data): time = data["time"] open = data["open"] high = data["high"] low = data["low"] close = data["close"] width = data["time_frame"] * 0.8 bullish = close > open height = abs(open - close) center = (time, open + height * 0.5 if bullish else open - height * 0.5) rect = None if height > 0: rect = scene.Rectangle(center=center, height=height, width=width, color = "green" if bullish else "red", border_color="black", border_width=200.0) rect.interactive = True self.view.add(rect) else: line_empty_body = scene.Line(pos=np.array([[time - width*0.5, close], [time + width*0.5, close]]), color="black", width=2.0) self.view.add(line_empty_body) line_high = scene.Line(pos=np.array([[time, close if bullish else open], [time, high]]), color="black", width=2.0) line_low = scene.Line(pos=np.array([[time, open if bullish else close], [time, low]]), color="black", width=2.0) self.view.add(line_high) self.view.add(line_low) return rect if rect is not None else line_empty_body
def draw_field(self): field = scene.Rectangle(center=(0, 0), width=10, height=7, color=green, parent=self.view.scene) center_circle = scene.Ellipse(center=(0, 0), radius=1.3 / 2, color=green, border_color=white, border_width=2, parent=self.view.scene) center_line = scene.Line(pos=np.array([[0, 3.5], [0, -3.5]]), width=2, color=white, parent=self.view.scene) goals = scene.Line(pos=np.array([[-4.5, 1.3], [-4.5, -1.3], [4.5, 1.3], [4.5, -1.3]]), connect='segments', width=2, color=white, parent=self.view.scene)
def __init__(self, icurves, highlight=None, clrmap='husl', colors=None): """ :param icurves: input curve or list of curves :param clrmap: (optional) what colormap name from vispy.colormap to use :param highlight: (optional) index of a curve to highlight :param colors: (optional) use list of colors instead of colormap """ self.canvas = scene.SceneCanvas(size=(1280, 900), position=(200, 200), keys='interactive', bgcolor=bg_clr) self.grid = self.canvas.central_widget.add_grid(spacing=0) self.view = self.grid.add_view(row=0, col=1, camera='panzoom') curves = np.array(icurves) if len(curves.shape) == 1: ## Single curve curves = np.array([icurves]) nb_traces, size = curves.shape # the Line visual requires a vector of X,Y coordinates xy_curves = np.dstack((np.tile(np.arange(size), (nb_traces, 1)), curves)) # Specify which points are connected # Start by connecting each point to its successor connect = np.empty((nb_traces * size - 1, 2), np.int32) connect[:, 0] = np.arange(nb_traces * size - 1) connect[:, 1] = connect[:, 0] + 1 # Prevent vispy from drawing a line between the last point # of a curve and the first point of the next curve for i in range(size, nb_traces * size, size): connect[i - 1, 1] = i - 1 if highlight is not None: # 'husl' is horrible in this case so we switch to viridis colormap = color.get_colormap('viridis')[np.linspace(0., 1., nb_traces * size)] # cheat by predrawing a single line over the highlighted one scene.Line(pos=xy_curves[highlight], color=colormap[connect.shape[0]-1][0], parent=self.view.scene) scene.Line(pos=xy_curves, color=colormap[connect.shape[0]//2][0], parent=self.view.scene, connect=connect) else: if colors is None: colormap = color.get_colormap(clrmap)[np.linspace(0., 1., nb_traces * size)] else: colormap = color.get_colormap(clrmap)[colors] scene.Line(pos=xy_curves, color=colormap, parent=self.view.scene, connect=connect) self.x_axis = scene.AxisWidget(orientation='bottom') self.y_axis = scene.AxisWidget(orientation='left') self.x_axis.stretch = (1, 0.05) self.y_axis.stretch = (0.05, 1) self.grid.add_widget(self.x_axis, row=1, col=1) self.grid.add_widget(self.y_axis, row=0, col=0) self.x_axis.link_view(self.view) self.y_axis.link_view(self.view) self.view.camera.set_range(x=(-1, size), y=(curves.min(), curves.max())) self.canvas.show() self.canvas.app.run()
def __init__(self): # vertex positions of data to draw N = length self.pos1 = np.zeros((N, 2)) self.pos2 = np.zeros((N, 2)) self.pos1[:, 0] = np.arange(N) / samplerate self.pos2[:, 0] = np.arange(N) / samplerate # color array self.color1 = (1, 0, 0) self.color2 = (0, 1, 0) canvas = scene.SceneCanvas(keys="interactive", show=True) main_grid = canvas.central_widget.add_grid() grid = Grid(border_color="r") info = scene.widgets.ViewBox(border_color="b") info.camera = "panzoom" info.camera.rect = -1, -1, 2, 2 info.stretch = (1, 0.1) main_grid.add_widget(grid, row=0, col=0) main_grid.add_widget(info, row=1, col=0) # add some axes x_axis = scene.AxisWidget(orientation="bottom") x_axis.stretch = (1, 0.1) y_axis = scene.AxisWidget(orientation="left") y_axis.stretch = (0.1, 1) grid.add_widget(x_axis, row=1, col=1) grid.add_widget(y_axis, row=0, col=0) viewbox = grid.add_view(row=0, col=1, camera="panzoom") x_axis.link_view(viewbox) y_axis.link_view(viewbox) # add cpu information text = Text(text="TEXT", color=(1, 1, 1, 1), parent=info.scene) text.font_size = 18 self.text = text # add a line plot inside the viewbox self.line1 = scene.Line(self.pos1, self.color1, parent=viewbox.scene) self.line2 = scene.Line(self.pos2, self.color2, parent=viewbox.scene) # auto-scale to see the whole line. viewbox.camera.set_range()
def plot(mesh, show_k=False, show_v=False, show_f=False): points = mesh.points springs = mesh.springs canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 edges = springs[['p0', 'p1']].view(('i8', 2)) lines = scene.Line(pos=points, connect=edges, antialias=False, method='gl', color='green', parent=view.scene) markers = scene.Markers(pos=points, face_color='blue', symbol='o', parent=view.scene, size=0.5, scaling=True) view.camera.set_range() app.run()
def create_surface(self): N = self.n_samples_to_display color = np.ones((N, 4), dtype=np.float32) color[:, 0] = np.linspace(0, 1, N) color[:, 1] = color[::-1, 0] canvas = scene.SceneCanvas(keys='interactive', show=True) grid = canvas.central_widget.add_grid(spacing=0) self.viewbox = grid.add_view(row=0, col=1, camera='panzoom') x_axis = scene.AxisWidget(orientation='bottom') x_axis.stretch = (1, 0.1) grid.add_widget(x_axis, row=1, col=1) x_axis.link_view(self.viewbox) y_axis = scene.AxisWidget(orientation='left') y_axis.stretch = (0.1, 1) grid.add_widget(y_axis, row=0, col=0) y_axis.link_view(self.viewbox) self.setLayout(QVBoxLayout()) self.layout().addWidget(canvas.native) for i in range(0, self.n_channels): pos = np.zeros((N, 2), dtype=np.float32) pos[:, 0] = self.x_mesh[:self.n_samples_to_display] if i: pos[:, 1] = pos[:, 1] + 50*i c = scene.Line(pos, color, parent=self.viewbox.scene) self.curves.append(pos) self.lines.append(c) self.viewbox.camera.set_range()
def __init__(self, model, fn): self.model = model self.fn = fn self.roadcolors = np.empty((model.graph.roads * 2, 4), dtype=np.float32) for i in range(model.graph.roads): self.roadcolors[2 * i:2 * i + 2] = np.array([0, 1, 0, 0.4]) self.roadrots = np.zeros((model.graph.roads, 2, 2)) roadlines = np.concatenate(model.graph.locs) self.canvas = scene.SceneCanvas(show=True, size=(2500, 2500)) view = self.canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 self.lines = scene.Line(pos=roadlines, connect='segments', method='gl', parent=view.scene, color=self.roadcolors) view.camera.set_range() self.markers = scene.Markers(parent=view.scene) for i in range(model.graph.roads): cos = model.graph.locs[i, 1, 0] - model.graph.locs[i, 0, 0] sin = model.graph.locs[i, 1, 1] - model.graph.locs[i, 0, 1] self.roadrots[i] = np.array([[cos, sin], [-sin, cos] ]) / model.graph.len
def __init__(self, name, n, freq): super().__init__() layout = QHBoxLayout() self.setWindowTitle(name) color = np.ones((n, 4), dtype=np.float32) color[:, 0] = np.linspace(0, 1, n) color[:, 1] = color[::-1, 0] canvas = scene.SceneCanvas(keys='interactive', show=True) grid = canvas.central_widget.add_grid(spacing=0) self.viewbox = grid.add_view(row=0, col=1, camera='panzoom') x_axis = scene.AxisWidget(orientation='bottom') x_axis.stretch = (1, 0.1) grid.add_widget(x_axis, row=1, col=1) x_axis.link_view(self.viewbox) y_axis = scene.AxisWidget(orientation='left') y_axis.stretch = (0.1, 1) grid.add_widget(y_axis, row=0, col=0) y_axis.link_view(self.viewbox) self.pos = np.zeros((n, 2), dtype=np.float32) self.pos[:, 0] = rfftfreq(n, 1/freq) #pos[:, 0] = self.x_mesh[:self.n_samples_to_display] self.line = scene.Line(self.pos, color, parent=self.viewbox.scene) self.viewbox.camera.set_range() self.freqbar = pg.BarGraphItem(x=[1], height=0, width=0.6, brush='g') self.plot = pg.PlotWidget() self.plot.addItem(self.freqbar) self.plot.setFixedWidth(100) layout.addWidget(canvas.native) layout.addWidget(self.plot) self.setLayout(layout)
def test_picking_basic(): """Test basic picking behavior. Based on https://github.com/vispy/vispy/issues/2107. """ with TestingCanvas(size=(125, 125), show=True, title='run') as c: view = c.central_widget.add_view() view.margin = 5 # add empty space where there are no visuals view.camera = 'panzoom' x = np.linspace(0, 400, 100) y = np.linspace(0, 200, 100) line = scene.Line(np.array((x, y)).T.astype(np.float32)) line.interactive = True view.add(line) view.camera.set_range() c.render() # initial basic draw for _ in range(2): # run picking twice to make sure it is repeatable # get Visuals on a Canvas point that Line is drawn on picked_visuals = c.visuals_at((100, 25)) assert len(picked_visuals) == 2 assert any(isinstance(vis, scene.ViewBox) for vis in picked_visuals) assert any(isinstance(vis, scene.Line) for vis in picked_visuals)
def __init__(self, vispy_canvas, times, freqs, offset=None, auto_align=False): color_def = (1, 1, 1, .5) color_sel = (0, 1, 0, 1) BaseMarker.__init__(self, vispy_canvas, vispy_canvas.lines, color_def, color_sel) self.times = np.asarray(times) self.freqs = np.asarray(freqs) #note: the final, output speed curve output should be linscale and centered on 1 self.speed = np.log2(freqs) self.speed-= np.mean(self.speed) #we don't want to overwrite existing offsets loaded from files if offset is None: if not auto_align: offset = 0 else: #create the array for sampling out = np.ones((len(times), len(self.vispy_canvas.lines)), dtype=np.float32) #lerp and sample all lines, use NAN for missing parts for i, line in enumerate(self.vispy_canvas.lines): line_sampled = np.interp(times, line.times, line.speed, left = np.nan, right = np.nan) out[:, i] = line_sampled #take the mean and ignore nans mean_with_nans = np.nanmean(out, axis=1) offset = np.nanmean(mean_with_nans-self.speed) offset = 0 if np.isnan(offset) else offset self.offset = offset self.speed += offset #calculate the centers mean_times = np.mean(self.times) self.spec_center = np.array( (mean_times, np.mean(self.freqs)) ) self.speed_center = np.array( (mean_times, np.mean(self.speed)) ) #create the speed curve visualization self.speed_data = np.stack( (self.times, self.speed), axis=-1) self.visuals.append( scene.Line(pos=self.speed_data, color=color_def, method='gl') ) #create the spectral visualization #could also do a stack here; note the z coordinate! spec_data = np.stack( (self.times, self.freqs, np.ones(len(self.times), dtype=np.float32)*-2), axis=-1) self.visuals.append( scene.Line(pos=spec_data, color=color_def, method='gl') ) #the data is in Hz, so to visualize correctly, it has to be mel'ed self.visuals[1].transform = vispy_canvas.spectra[0].mel_transform self.initialize() self.vispy_canvas.master_speed.update()
def draw_curves(self, curves_, labels=None, clrmap="husl"): curves = np.array(curves_) self.shape_ = curves.shape if labels is not None: assert len(labels) == self.shape_[0] self.labels = labels else: self.labels = [f"0x{i:x}" for i in range(self.shape_[0])] if len(curves.shape) == 1: ## Single curve curves = np.array([curves]) nb_traces, size = curves.shape # the Line visual requires a vector of X,Y coordinates xy_curves = np.dstack((np.tile(np.arange(size), (nb_traces, 1)), curves)) # Specify which points are connected # Start by connecting each point to its successor connect = np.empty((nb_traces * size - 1, 2), np.int32) connect[:, 0] = np.arange(nb_traces * size - 1) connect[:, 1] = connect[:, 0] + 1 # Prevent vispy from drawing a line between the last point # of a curve and the first point of the next curve for i in range(size, nb_traces * size, size): connect[i - 1, 1] = i - 1 self.colors = np.ones((nb_traces * size, 3), dtype=np.float32) self.backup_colors = np.ones((nb_traces, 3), dtype=np.float32) R_p = np.linspace(0.4, 0.4, num=nb_traces) G_p = np.linspace(0.5, 0.3, num=nb_traces) B_p = np.linspace(0.5, 0.3, num=nb_traces) self.colors[:, 0] = np.repeat(R_p, size) self.colors[:, 1] = np.repeat(G_p, size) self.colors[:, 2] = np.repeat(B_p, size) self.backup_colors[:, 0] = R_p self.backup_colors[:, 1] = G_p self.backup_colors[:, 2] = B_p self.line = scene.Line(pos=xy_curves, color=self.colors, parent=self.view.scene, connect=connect) self.selected_lines = [] self.hl_labels = [] self.hl_colorset = cycle( color.get_colormap(clrmap)[np.linspace(0.0, 1.0, self.MAX_HL)]) self.view.camera.set_range(x=(-1, size), y=(curves.min(), curves.max()))
def __init__(self, vispy_canvas): self.vispy_canvas = vispy_canvas #create the speed curve visualization self.data = np.zeros((2, 2), dtype=np.float32) self.data[:, 0] = (0, 999) self.data[:, 1] = (0, 0) self.line_speed = scene.Line(pos=self.data, color=(0, 0, 1, .5), method='gl') self.line_speed.parent = vispy_canvas.speed_view.scene
def __init__(self, vispy_canvas, color=(1, 0, 0, .5)): self.vispy_canvas = vispy_canvas #create the speed curve visualization self.data = np.zeros((2, 2), dtype=np.float32) self.data[:, 0] = (0, 999) self.empty = np.array(self.data) self.bands = (0, 9999999) self.line_speed = scene.Line(pos=self.data, color=color, method='gl') self.line_speed.parent = self.vispy_canvas.speed_view.scene
def __init__(self, vispy_canvas, t0, t1, amplitude, omega, phase, offset): color_def = (1, 1, 1, .5) color_sel = (0, 1, 0, 1) BaseMarker.__init__(self, vispy_canvas, vispy_canvas.regs, color_def, color_sel) #the extents on which this regression operated self.t0 = t0 self.t1 = t1 #here, the reg values are most accurate self.t_center = (t0 + t1) / 2 self.speed_center = np.array((self.t_center, 0)) self.spec_center = np.array((self.t_center, 2000)) #the following is more or less duped in the tracer - resolve? speed_curve = vispy_canvas.master_speed.get_linspace() times = speed_curve[:, 0] speeds = speed_curve[:, 1] #which part to process? period = times[1] - times[0] ind_start = int(self.t0 / period) ind_stop = int(self.t1 / period) clipped_times = times[ind_start:ind_stop] #set the properties self.amplitude = amplitude self.omega = omega self.phase = phase self.offset = offset #some conventions are needed #correct the amplitude & phase so we can interpolate properly if self.amplitude < 0: self.amplitude *= -1 self.phase += np.pi #phase should be in 0 < x< 2pi #this is not completely guaranteed by this # if self.phase < 0: # self.phase += (2*np.pi) # if self.phase > 2*np.pi: # self.phase -= (2*np.pi) #self.phase = self.phase % (2*np.pi) #create the speed curve visualization self.speed_data = np.stack( (clipped_times, self.amplitude * np.sin(self.omega * clipped_times + self.phase)), axis=-1) #sine_on_hz = np.power(2, sine + np.log2(2000)) self.visuals.append( scene.Line(pos=self.speed_data, color=(0, 0, 1, .5), method='gl')) self.initialize()
def run(mesh, show_k=False, show_v=False, show_f=False, run=None, verbose=False): points = mesh.points springs = mesh.springs canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 edges = springs[['p0', 'p1']].view(('i8', 2)) lines = scene.Line(pos=points, connect=edges, antialias=False, method='gl', color='green', parent=view.scene) markers = scene.Markers(pos=points, face_color='blue', symbol='o', parent=view.scene, size=0.5, scaling=True) view.camera.set_range() def update(ev): t0 = time.time() run(mesh) t1 = time.time() if verbose: print("run: %s" % (t1 - t0, )) if mesh.points.min() == numpy.nan or mesh.points.max() == numpy.nan: return False t0 = time.time() markers.set_data(pos=mesh.points, size=0.5, scaling=True) lines.set_data(pos=mesh.points) t1 = time.time() if verbose: print("set_data: %s" % (t1 - t0, )) if run is not None: timer = app.Timer(interval=0, connect=update, start=True) app.run()
# Main input array N = 500 pos = np.zeros((N, 2), dtype=np.float32) # Create x and y points x_arr = np.arange(0,N) pos[:, 0] = x_arr #np.linspace(50., 750., N) pos[:, 1] = np.sin(x_arr) * 500;#np.arange(0,200)#.normal(size=N, scale=100, loc=400) # color array color = np.ones((N, 4), dtype=np.float32) color[:, 0] = np.linspace(0, 1, N) color[:, 1] = color[::-1, 0] canvas = scene.SceneCanvas(keys='interactive', size=(800, 800), show=True) line = scene.Line(pos, color, parent=canvas.scene) def update(ev): global pos, color, line #pos[:, 1] = np.arange(0,200)#np.random.normal(size=N, scale=100, loc=400) color = np.roll(color, 1, axis=0) line.set_data(pos=pos, color=color) timer = app.Timer() timer.connect(update) timer.start(0) if __name__ == '__main__' and sys.flags.interactive == 0: app.run()
def __init__(self, icurves, highlight=None, clrmap="husl", colors=None, parent=None, itermode=False): """ :param icurves: input curve or list of curves :param clrmap: (optional) what colormap name from vispy.colormap to use :param colors: (optional) use list of colors instead of colormap """ self.canvas = scene.SceneCanvas( size=(1280, 900), position=(200, 200), keys="interactive", bgcolor=bg_clr, parent=parent, ) self.grid = self.canvas.central_widget.add_grid(spacing=0) self.view = self.grid.add_view(row=0, col=1, camera="panzoom") curves = np.array(icurves) if len(curves.shape) == 1: ## Single curve curves = np.array([icurves]) nb_traces, size = curves.shape if not itermode: # the Line visual requires a vector of X,Y coordinates xy_curves = np.dstack((np.tile(np.arange(size), (nb_traces, 1)), curves)) # Specify which points are connected # Start by connecting each point to its successor connect = np.empty((nb_traces * size - 1, 2), np.int32) connect[:, 0] = np.arange(nb_traces * size - 1) connect[:, 1] = connect[:, 0] + 1 # Prevent vispy from drawing a line between the last point # of a curve and the first point of the next curve for i in range(size, nb_traces * size, size): connect[i - 1, 1] = i - 1 if highlight is not None: # cheat by predrawing a single line over the highlighted one scene.Line(pos=xy_curves[highlight], color=highlighted, parent=self.view.scene) scene.Line(pos=xy_curves, color=others, parent=self.view.scene, connect=connect) else: if colors is None: colormap = color.get_colormap(clrmap)[np.linspace( 0.0, 1.0, nb_traces * size)] else: colormap = color.get_colormap(clrmap)[colors] scene.Line( pos=xy_curves, color=colormap, parent=self.view.scene, connect=connect, ) else: colormap = color.get_colormap(clrmap)[np.linspace( 0., 1., nb_traces)] for i in range(nb_traces): scene.Line(pos=np.dstack((np.arange(size), curves[i]))[0], color=colormap[i], method="agg", width=2., parent=self.view.scene) self.x_axis = scene.AxisWidget(orientation="bottom", text_color=txt_clr) self.y_axis = scene.AxisWidget(orientation="left", text_color=txt_clr) self.x_axis.stretch = (1, 0.05) self.y_axis.stretch = (0.05, 1) self.grid.add_widget(self.x_axis, row=1, col=1) self.grid.add_widget(self.y_axis, row=0, col=0) self.x_axis.link_view(self.view) self.y_axis.link_view(self.view) self.view.camera.set_range(x=(-1, size), y=(curves.min(), curves.max())) self.canvas.show() if parent is None: self.canvas.app.run()
cmap = color.get_colormap('cubehelix') typ_colors = np.array([cmap.map(x)[0, :3] for x in np.linspace(0.2, 0.8, typ)]) colors[:] = typ_colors[types] # Add some RGB noise and clip colors *= 1.1 ** np.random.normal(size=colors.shape) colors = np.clip(colors, 0, 1) # Display the data canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'arcball' view.camera.aspect = 1 lines = scene.Line(pos=pos, connect=edges, antialias=False, method='gl', color=(1, 1, 1, 0.2), parent=view.scene) markers = scene.Markers(pos=pos, face_color=colors, symbol='o', parent=view.scene) view.camera.set_range() i = 1 def update(ev): global pos, edges, lines, markers, view, force, dist, i dx = np.empty((npts, npts, 2), dtype='float32') dx[:] = pos[:, np.newaxis, :] dx -= pos[np.newaxis, :, :]
def plot_elements(elements, overlay_deformed=False, sel_nodes=None, sel_elements=None, canvas={}, hold_on=False, view=None, cam={}, tmat_scaling=1, plot_tmat_ax=None, plot_nodes=False, node_labels=False, element_labels=False, element_label_settings={}, node_label_settings={}, element_settings={}, node_settings={}, sel_node_settings={}, sel_element_settings={}, sel_node_label_settings={}, sel_element_label_settings={}, tmat_settings={}, deformed_element_settings={}, title='BEEF Element plot'): el_settings = dict(color='#008800') el_settings.update(**element_settings) def_el_settings = dict(color='#ff2288') def_el_settings.update(**deformed_element_settings) elsel_settings = dict(color='#ff0055', width=3) elsel_settings.update(**sel_element_settings) elsellab_settings = dict(color='#ff0055', bold=True, italic=False, face='OpenSans', font_size=10, anchor_x='left') elsellab_settings.update(**sel_element_label_settings) ellab_settings = dict(color='#008800', bold=False, italic=False, face='OpenSans', font_size=10, anchor_x='left') ellab_settings.update(**element_label_settings) n_settings = dict(face_color='#0000ff', edge_color=None, size=4) n_settings.update(**node_settings) nlab_settings = dict(color='#0000ff', bold=False, italic=False, face='OpenSans', font_size=10, anchor_x='left') nlab_settings.update(**node_label_settings) nsel_settings = dict(face_color='#ff0000', edge_color='#ff0000', size=8) nsel_settings.update(**sel_node_settings) nsellab_settings = dict(color='#ff0000', bold=True, italic=False, face='OpenSans', font_size=10, anchor_x='left') nsellab_settings.update(**sel_node_label_settings) tmat_colors = ['#0000ff', '#00ff00', '#ff0000'] tmatax_settings = dict(arrow_size=1) tmatax_settings.update(**tmat_settings) # Node coordinates nodes = list(set([a for b in [el.nodes for el in elements] for a in b])) #flat list of unique nodes node_pos = np.vstack([node.coordinates for node in nodes]) # Selected elements if sel_elements is None: sel_elements = [] unsel_elements = [el for el in elements if el.label not in sel_elements] sel_elements = [el for el in elements if el.label in sel_elements] if view is None: view, canvas, cam = initialize_plot(canvas=canvas, cam=cam, elements=elements, title=title) else: canvas = view.canvas cam = view.camera if not hold_on: rm_visuals(view) # Establish element lines if len(unsel_elements) > 0: element_lines = [None] * len(unsel_elements) for ix, el in enumerate(unsel_elements): element_lines[ix] = np.vstack( [node.coordinates for node in el.nodes]) element_visual = scene.Line(pos=np.vstack(element_lines), connect='segments', **el_settings) view.add(element_visual) # Establish selected element lines if len(sel_elements) > 0: element_lines = [None] * len(sel_elements) for ix, el in enumerate(sel_elements): element_lines[ix] = np.vstack( [node.coordinates for node in el.nodes]) element_visual = scene.Line(pos=np.vstack(element_lines), connect='segments', **elsel_settings) view.add(element_visual) # Overlay deformed plot if if overlay_deformed: element_lines = [None] * len(elements) for ix, el in enumerate(elements): element_lines[ix] = np.vstack([node.x[:3] for node in el.nodes]) element_visual = scene.Line(pos=np.vstack(element_lines), connect='segments', **def_el_settings) view.add(element_visual) # Establish element labels if element_labels and len(unsel_elements) > 0: el_cog = [el.get_cog() for el in unsel_elements] el_labels = [str(el.label) for el in unsel_elements] element_label_visual = scene.Text(text=el_labels, pos=el_cog, **ellab_settings) view.add(element_label_visual) if len(sel_elements) > 0: el_cog = [el.get_cog() for el in sel_elements] el_labels = [str(el.label) for el in sel_elements] element_label_visual = scene.Text(text=el_labels, pos=el_cog, **elsellab_settings) view.add(element_label_visual) # Node labels if node_labels: node_labels = [str(node.label) for node in nodes] element_label_visual = scene.Text(text=node_labels, pos=node_pos, **nlab_settings) view.add(element_label_visual) # Nodes if plot_nodes: node_visual = scene.visuals.Markers(pos=node_pos, **n_settings) view.add(node_visual) if sel_nodes is not None: sel_nodes = [node for node in nodes if node.label in sel_nodes] sel_node_labels = [str(node.label) for node in sel_nodes] if len(sel_nodes) >= 1: node_pos = np.vstack([node.coordinates for node in sel_nodes]) sel_node_label_visual = scene.Text(text=sel_node_labels, pos=node_pos, **nsellab_settings) sel_node_visual = scene.visuals.Markers(pos=node_pos, **nsel_settings) view.add(sel_node_label_visual) view.add(sel_node_visual) else: print('Requested nodes to highlight not found.') # Add transformation matrices if plot_tmat_ax is not None: for ax in plot_tmat_ax: el_vecs = np.vstack( [element.tmat[ax, 0:3] for element in elements]) * tmat_scaling el_cogs = np.vstack([element.get_cog() for element in elements]) # INTERTWINE TMAT AND ELCOGS arrow_data = np.hstack([el_cogs, el_cogs + el_vecs]) tmat_visual = scene.Arrow(pos=arrow_data.reshape( [el_vecs.shape[0] * 2, 3]), color=tmat_colors[ax], arrow_color=tmat_colors[ax], connect='segments', arrows=arrow_data, **tmatax_settings) view.add(tmat_visual) canvas.show() axis = scene.visuals.XYZAxis(parent=view.scene) return canvas, view
from vispy.visuals.transforms import STTransform from vispy.ext.six import next colormaps = itertools.cycle(colormaps) # vertex positions of data to draw N = 200 pos = np.zeros((N, 2), dtype=np.float32) pos[:, 0] = np.linspace(10, 390, N) pos[:, 1] = np.random.normal(size=N, scale=20, loc=0) canvas = scene.SceneCanvas(keys='interactive', size=(400, 200), show=True) # Create a visual that updates the line with different colormaps color = next(colormaps) line = scene.Line(pos=pos, color=color, mode='gl') line.transform = STTransform(translate=[0, 140]) line.parent = canvas.central_widget text = scene.Text(color, bold=True, font_size=24, color='w', pos=(200, 40), parent=canvas.central_widget) def on_timer(event): global colormaps, line, text, pos color = next(colormaps) line.set_data(pos=pos, color=color)
grid = canvas.central_widget.add_grid(spacing=0) viewbox = grid.add_view(row=0, col=1, camera='panzoom') # add some axes x_axis = scene.AxisWidget(orientation='bottom') x_axis.stretch = (1, 0.1) grid.add_widget(x_axis, row=1, col=1) x_axis.link_view(viewbox) y_axis = scene.AxisWidget(orientation='left') y_axis.stretch = (0.1, 1) grid.add_widget(y_axis, row=0, col=0) y_axis.link_view(viewbox) # add a line plot inside the viewbox line = scene.Line(pos, color, parent=viewbox.scene) # auto-scale to see the whole line. viewbox.camera.set_range() def update(ev): global pos, color, line pos[:, 1] = np.random.normal(size=N) color = np.roll(color, 1, axis=0) line.set_data(pos=pos, color=color) timer = app.Timer() timer.connect(update) timer.start(0)
def update(self, ev=None): if self.graph_time is not None and self.graph_position is not None: # self.graph_lock.acquire() if self.graph_index.value > 1: #at least 2 elements to start graphing s = self.last_graph_index + 1 e = self.graph_index.value self.last_graph_index = e N = e - s if N < 0: #this would be due to a reset s = 0 self.last_graph_index = e self.data_pos = np.zeros((0, 2), dtype=np.float32) self.data_pos_error = np.zeros((0, 2), dtype=np.float32) self.color = np.ones((0, 4), dtype=np.float32) self.data_fan = np.zeros((0, 2), dtype=np.float32) self.data_target = np.zeros((0, 2), dtype=np.float32) N = e - s if N > 0: new_pos = np.zeros((N, 2), dtype=np.float32) new_pos_error = np.zeros((N, 2), dtype=np.float32) new_data_fan = np.zeros((N, 2), dtype=np.float32) new_data_target = np.zeros((N, 2), dtype=np.float32) new_color = np.ones((N, 4), dtype=np.float32) for i in range(N): new_pos[i, 0] = self.graph_time[s + i] new_pos[i, 1] = self.graph_position[s + i] new_pos_error[i, 0] = self.graph_time[s + i] new_pos_error[i, 1] = self.graph_error[s + i] new_data_fan[i, 0] = self.graph_time[s + i] new_data_fan[i, 1] = self.graph_fan[s + i] new_data_target[i, 0] = self.graph_time[s + i] new_data_target[i, 1] = self.graph_target[s + i] new_color[i] = [1, 0, 0, self.line_opacity] # self.graph_lock.release() self.data_pos = np.append(self.data_pos, new_pos, axis=0) self.data_pos_error = np.append(self.data_pos_error, new_pos_error, axis=0) self.color = np.append(self.color, new_color, axis=0) self.data_fan = np.append(self.data_fan, new_data_fan, axis=0) self.data_target = np.append(self.data_target, new_data_target, axis=0) auto_scrolling_lines = 500 if self.line_pos is None: self.line_pos_error = scene.Line( self.data_pos_error, [1, 1, 0, self.line_opacity], parent=self.viewbox_pos.scene) self.line_target = scene.Line( self.data_target, [0, 0, 1, self.line_opacity], parent=self.viewbox_pos.scene, width=2) self.line_fan = scene.Line( self.data_fan, [0, 1, 0, self.line_opacity], parent=self.viewbox_fan.scene, ) self.line_pos = scene.Line( self.data_pos, self.color, parent=self.viewbox_pos.scene) else: i = 0 j = self.data_pos.shape[0] if j > auto_scrolling_lines and self.auto_scale and self.auto_scroll: i = j - auto_scrolling_lines self.line_pos_error.set_data( pos=self.data_pos_error[i:j, :], color=[1, 1, 0, self.line_opacity]) self.line_target.set_data( pos=self.data_target[i:j, :], color=[0, 0, 1, self.line_opacity]) self.line_fan.set_data( pos=self.data_fan[i:j, :], color=[0, 1, 0, self.line_opacity]) self.line_pos.set_data(pos=self.data_pos[i:j, :], color=self.color[i:j, :]) if self.auto_scale == True: i = 0 j = self.data_pos.shape[0] if j > auto_scrolling_lines and self.auto_scale and self.auto_scroll: i = j - auto_scrolling_lines self.viewbox_pos.camera.set_range(x=(self.data_pos[i, 0], self.data_pos[-1, 0]), y=(-1.1, 1.1))
yaxis.width_max = 80 grid.add_widget(yaxis, row=1, col=0) xaxis = scene.AxisWidget(orientation='bottom', axis_label='X Axis', axis_font_size=12, axis_label_margin=50, tick_label_margin=5) xaxis.height_max = 80 grid.add_widget(xaxis, row=2, col=1) right_padding = grid.add_widget(row=1, col=2, row_span=1) right_padding.width_max = 50 view = grid.add_view(row=1, col=1, border_color='white') data = np.random.normal(size=(1000, 2)) data[0] = -10, -10 data[1] = 10, -10 data[2] = 10, 10 data[3] = -10, 10 data[4] = -10, -10 plot = scene.Line(data, parent=view.scene) view.camera = 'panzoom' xaxis.link_view(view) yaxis.link_view(view) if __name__ == '__main__' and sys.flags.interactive == 0: app.run()
from vispy.color import get_colormaps from vispy.visuals.transforms import STTransform colormaps = itertools.cycle(get_colormaps()) # vertex positions of data to draw N = 200 pos = np.zeros((N, 2), dtype=np.float32) pos[:, 0] = np.linspace(10, 390, N) pos[:, 1] = np.random.normal(size=N, scale=20, loc=0) canvas = scene.SceneCanvas(keys='interactive', size=(400, 200), show=True) # Create a visual that updates the line with different colormaps color = next(colormaps) line = scene.Line(pos=pos, color=color, method='gl') line.transform = STTransform(translate=[0, 140]) line.parent = canvas.central_widget text = scene.Text(color, bold=True, font_size=24, color='w', pos=(200, 40), parent=canvas.central_widget) def on_timer(event): global colormaps, line, text, pos color = next(colormaps) line.set_data(pos=pos, color=color)
df = formatData(df) df = (df - df.mean()) / df.std() df["PctStd"] = df["PCT_CHG"].rolling(4).std() df["HLStd"] = df["HL_CHG"].rolling(4).std() df["PctMean"] = df["PCT_CHG"].rolling(4).mean() df["HLMean"] = df["HL_CHG"].rolling(4).mean() df = df[5:-30] df = df[["Close", "High", "Low", "PCT_CHG", "HL_CHG", "Volume", "Date"]] df.to_csv("./test.csv") #df = df[~df.isin([np.nan, np.inf, -np.inf]).any(1)] #df.to_csv("test.csv") X_predTime = [] Y_pred = [] graph = Graph() positions = np.array(list(zip(df.index, df["High"]))) plot = scene.Line(positions, parent=graph.view.scene, antialias=True, width=4) for i in range(20): for b in range(2): data = findNextTick(df[0:-(i + 1)].copy(), b) positions2 = np.array(list(zip(data["X"], data["Y"]))) if (b == 0): plot = scene.Line(positions2, parent=graph.view.scene, antialias=True, color="red") elif (b == 1): plot = scene.Line(positions2, parent=graph.view.scene, antialias=True, color="blue") elif (b == 2):
def __init__(self, keys='interactive', size=(1024, 768), **kwargs): super().__init__(keys=keys, size=size, **kwargs) self.unfreeze() self._grid = self.central_widget.add_grid(spacing=0, border_color='k', border_width=2, margin=0) self._viewbox = self._grid.add_view(row=0, col=1, camera='panzoom', border_color='k', margin=0, border_width=2, bgcolor=(0.99, 0.99, 0.99, 1)) # add some axes self._xAxis = scene.AxisWidget(orientation='bottom', axis_label='X Axis', font_size=10, axis_color='k', tick_color='k', text_color='k', tick_label_margin=20, axis_label_margin=30) self._xAxis.stretch = (1, 0.1) self._grid.add_widget(self._xAxis, row=1, col=1) self._xAxis.link_view(self._viewbox) self._yAxis = scene.AxisWidget(orientation='left', axis_label='Y Axis', font_size=10, axis_color='k', tick_color='k', text_color='k') self._yAxis.stretch = (0.1, 1) self._grid.add_widget(self._yAxis, row=0, col=0) self._yAxis.link_view(self._viewbox) self._gridLines = scene.GridLines(color=(0, 0, 0, 1), parent=self._viewbox.scene) self._xLine = scene.Line(color='r', width=2, parent=self._viewbox.scene) self._yLine = scene.Line(color='b', width=2, parent=self._viewbox.scene) self._zLine = scene.Line(color='g', width=2, parent=self._viewbox.scene) self._gridLines.set_gl_state('translucent', cull_face=False) self._xLine.set_gl_state(depth_test=False) self._yLine.set_gl_state(depth_test=False) self._zLine.set_gl_state(depth_test=False) self._pointNum = 3000 self._timeLine = 5.0 self._xAxisLim = [0., self._timeLine] self._yAxisLim = [-1., 1.] self._xPos = np.array([ [0, 0], ], dtype=np.float32) # np.zeros((self._pointNum, 2), dtype=np.float32) self._yPos = np.array([ [0, 0], ], dtype=np.float32) self._zPos = np.array([ [0, 0], ], dtype=np.float32) self.freeze() self.show()
def __init__(self): self.reset() self.isenable = False self._vline = scene.Line()