def put_axes(view): size = 20 domain_x = (118.34 - size / 2, 118.34 + size / 2) domain_y = (117.69 - size / 2, 117.69 + size / 2) xax = scene.Axis(pos=[[-0.5, -0.5], [0.5, -0.5]], domain=domain_x, tick_direction=(0, -1), font_size=16, axis_color='white', tick_color='white', text_color='white', parent=view) xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis(pos=[[-0.5, -0.5], [-0.5, 0.5]], domain=domain_y, tick_direction=(-1, 0), font_size=16, axis_color='white', tick_color='white', text_color='white', parent=view) yax.transform = scene.STTransform(translate=(0, 0, -0.2))
def Vispy(matrice): def normalize(x, cmin=None, cmax=None, clip=True): """Normalize an array from the range [cmin, cmax] to [0,1], with optional clipping.""" if not isinstance(x, np.ndarray): x = np.array(x) if cmin is None: cmin = x.min() if cmax is None: cmax = x.max() if cmin == cmax: return .5 * np.ones(x.shape) else: cmin, cmax = float(cmin), float(cmax) y = (x - cmin) * 1. / (cmax - cmin) if clip: y = np.clip(y, 0., 1.) return y canvas = scene.SceneCanvas(keys='interactive', bgcolor='w') view = canvas.central_widget.add_view() view.camera = scene.TurntableCamera(up='z', fov=60) matrice = (matrice + 1) * 127 # Simple surface plot example # x, y values are not specified, so assumed to be 0:50 couleurs = normalize(CMAPGRAD) couleurs = np.flip(couleurs, 0) p1 = scene.visuals.SurfacePlot(z=matrice) #couleurs[0] p1.transform = scene.transforms.MatrixTransform() p1.transform.scale([1/100, 1/100, 4/100]) p1.transform.translate([0, 0, 0]) view.add(p1) p1._update_data() # p1._update_data() # cheating. cf = scene.filters.ZColormapFilter(vs.color.Colormap(couleurs, interpolation='linear'), zrange=(matrice.max(), matrice.min())) p1.attach(cf) xax = scene.Axis(pos=[[-0.5, -0.5], [0.5, -0.5]], tick_direction=(0, -1), font_size=16, axis_color='k', tick_color='k', text_color='k', parent=view.scene) xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis(pos=[[-0.5, -0.5], [-0.5, 0.5]], tick_direction=(-1, 0), font_size=16, axis_color='k', tick_color='k', text_color='k', parent=view.scene) yax.transform = scene.STTransform(translate=(0, 0, -0.2)) # Add a 3D axis to keep us oriented axis = scene.visuals.XYZAxis(parent=view.scene) canvas.show() app.run()
def drawSome(self): self.unfreeze() # generate data # pos = np.random.normal(size=(100000, 3), scale=0.2) # # one could stop here for the data generation, the rest is just to make the # # data look more interesting. Copied over from magnify.py # centers = np.random.normal(size=(50, 3)) # indexes = np.random.normal(size=100000, loc=centers.shape[0] / 2., # scale=centers.shape[0] / 3.) # indexes = np.clip(indexes, 0, centers.shape[0] - 1).astype(int) # scales = 10 ** (np.linspace(-2, 0.5, centers.shape[0]))[indexes][:, np.newaxis] # pos *= scales # pos += centers[indexes] # # # create scatter object and fill in the data # scatter = scene.Markers() # scatter.set_data(pos, edge_color=None, face_color=(1, 1, 1, .5), size=5) # # self.view.add(scatter) self.view.camera = 'turntable' # or try 'arcball' # add a colored 3D axis for orientation ax = scene.Axis(pos=[[0, 0], [1, 0]], tick_direction=(0, -1), axis_color='r', tick_color='r', text_color='r', font_size=16, parent=self.view.scene) yax = scene.Axis(pos=[[0, 0], [0, 1]], tick_direction=(-1, 0), axis_color='g', tick_color='g', text_color='g', font_size=16, parent=self.view.scene) zax = scene.Axis(pos=[[0, 0], [-1, 0]], tick_direction=(0, -1), axis_color='b', tick_color='b', text_color='b', font_size=16, parent=self.view.scene) zax.transform = scene.transforms.MatrixTransform( ) # its acutally an inverted xaxis zax.transform.rotate(90, (0, 1, 0)) # rotate cw around yaxis zax.transform.rotate(-45, (0, 0, 1)) # tick direction towards (-1,-1) # self.gridlines = visuals.GridLines(color=Color('gray')) # self.gridlines.set_gl_state('translucent', cull_face=False) # self.view.add(self.gridlines) self.freeze()
def build_axes(self): self.unfreeze() # add a colored 3D axis for orientation ax = scene.Axis(pos=[[0, 0], [1, 0]], tick_direction=(0, -1), font_size=16, parent=self.view.scene, axis_color='black', tick_color='black', text_color='black') yax = scene.Axis(pos=[[0, 0], [0, 1]], tick_direction=(-1, 0), font_size=16, parent=self.view.scene, axis_color='black', tick_color='black', text_color='black') zax = scene.Axis(pos=[[0, 0], [-1, 0]], tick_direction=(0, -1), font_size=16, parent=self.view.scene, axis_color='black', tick_color='black', text_color='black') zax.transform = scene.transforms.MatrixTransform() # its acutally an inverted xaxis zax.transform.rotate(90, (0, 1, 0)) # rotate cw around yaxis zax.transform.rotate(-45, (0, 0, 1)) # tick direction towards (-1,-1) self.freeze()
z = gaussian_filter(z, (10, 10)) p1 = scene.visuals.SurfacePlot(z=z, color=(0.3, 0.3, 1, 1)) p1.transform = scene.transforms.MatrixTransform() p1.transform.scale([1 / 249., 1 / 249., 1 / 249.]) p1.transform.translate([-0.5, -0.5, 0]) view.add(p1) # p1._update_data() # cheating. # cf = scene.filters.ZColormapFilter('fire', zrange=(z.max(), z.min())) # p1.attach(cf) xax = scene.Axis(pos=[[-0.5, -0.5], [0.5, -0.5]], tick_direction=(0, -1), font_size=16, axis_color='k', tick_color='k', text_color='k', parent=view.scene) xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis(pos=[[-0.5, -0.5], [-0.5, 0.5]], tick_direction=(-1, 0), font_size=16, axis_color='k', tick_color='k', text_color='k', parent=view.scene) yax.transform = scene.STTransform(translate=(0, 0, -0.2)) # Add a 3D axis to keep us oriented
cnorm = zGrid / abs(np.amax(zGrid)) c = color.get_colormap("greens").map(cnorm).reshape(zGrid.shape + (-1, )) c = c.flatten().tolist() c = list( map(lambda x, y, z, w: (x, y, z, w), c[0::4], c[1::4], c[2::4], c[3::4])) p1.mesh_data.set_vertex_colors( c) # but explicitly setting vertex colors does work? p1.transform = scene.transforms.MatrixTransform() p1.transform.scale([1110000, 1110000., 1]) view.add(p1) print("ok") xax = scene.Axis(pos=[[0, 0], [1, 0]], tick_direction=(0, -1), axis_color='r', tick_color='r', text_color='r', font_size=16, parent=view.scene) yax = scene.Axis(pos=[[0, 0], [0, 1]], tick_direction=(-1, 0), axis_color='g', tick_color='g', text_color='g', font_size=16, parent=view.scene) zax = scene.Axis(pos=[[0, 0], [-1, 0]], tick_direction=(0, -1), axis_color='b', tick_color='b',
def zbow_2d_plot(self, parent, scale, color, update=False, highlight_cells=None, highlight_color=False): new_window_position = parent.pos() if parent.was_closed: parent.show() if update: options = self.h_view_2d.camera.get_state() # get scale data: scale_list = ['custom', 'default', 'linear'] if scale == 0: scale_data = self.custom_ternary.as_matrix() elif scale == 1: scale_data = self.default_ternary.as_matrix() elif scale == 2: scale_data = self.linear_ternary.as_matrix() else: scale_data = self.custom_ternary.as_matrix() # get color data:color_list = ['custom', 'default', 'cluster color', 'linear'] if color == 0: color_data = self.custom_transformed.as_matrix() elif color == 1: color_data = self.default_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 2: if self.tab_cluster_data.empty: color_data = helper.distinguishable_colors(1) else: pseudo_color = helper.distinguishable_colors(self.tab_cluster_data['id'].count()) pseudo_color[self.noise_cluster_idx] = "#646464" color_data = [None] * scale_data.shape[0] for i in range(0, scale_data.shape[0]): color_data[i] = pseudo_color[self.cluster_data_idx[i]] elif color == 3: color_data = self.linear_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 4: color_data = np.empty([self.custom_transformed.shape[0], self.custom_transformed.shape[1]]) color_data[:] = 0.8 # grey for non-highlighted cells highlight_cells = pd.Series(highlight_cells, name='bools') if highlight_color: color_data[highlight_cells, :] = [0.2, 0.2, 0.2] else: color_data[highlight_cells, :] = self.custom_transformed[['RFP', 'YFP', 'CFP']][ highlight_cells.values].as_matrix() if not update: # build your visuals scatter = scene.visuals.create_visual_node(visuals.MarkersVisual) # build canvas self.h_canvas_2d = scene.SceneCanvas(title='zbow 2D ternary plot', keys='interactive', show=True, bgcolor=Color([1, 1, 1, 1]), ) parent.setCentralWidget(self.h_canvas_2d.native) # Add a ViewBox to let the user zoom/rotate if not update: self.h_view_2d = self.h_canvas_2d.central_widget.add_view() self.h_view_2d.camera = 'panzoom' self.h_view_2d.camera.set_range(x=(-0.2, 1.2), y=(-0.2, 1.2)) # if update: # self.h_view_2d = self.h_canvas_2d.central_widget.add_view() # self.h_view_2d.camera = 'panzoom' # self.h_view_2d.camera.set_state(options) # else: # self.h_view_2d = self.h_canvas_2d.central_widget.add_view() # self.h_view_2d.camera = 'panzoom' self.h_scatter_2d = scatter(parent=self.h_view_2d.scene) # p1.set_gl_state('translucent', blend=True, depth_test=True) self.h_scatter_2d.set_gl_state('translucent', blend=True, depth_test=False) # plot 2D ternary axis bottom_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[0, 0], [1, 0]], tick_direction=(0, 1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) right_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[1, 0], [0.5, 1]], tick_direction=(-1, -1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) left_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[0, 0], [0.5, 1]], tick_direction=(1, -1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) cell_color = ColorArray(color=color_data, alpha=1) # @BUG I want to use a different alpha here, but Vispy has a bug where you can see through the main canvas with alpha self.h_scatter_2d.set_data(pos=scale_data, symbol='o', size=5, edge_width=0, face_color=cell_color) # if not update: # self.h_scatter_2d.symbol = visuals.marker_types[10] if not update: parent.move(new_window_position.x(), new_window_position.y()) parent.show()
# 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', show=True) viewbox = canvas.central_widget.add_view() # add some axes domains = np.array([x_lim, y_lim]) pos_ax = [ np.array([domains[0], [domains[1][0]] * 2]).T, np.array([[domains[0][0]] * 2, domains[1]]).T ] x_axis = scene.Axis(pos_ax[0], domains[0], (0, -1), parent=viewbox.scene) y_axis = scene.Axis(pos_ax[1], domains[1], (-1, 0), parent=viewbox.scene) viewbox.camera = 'panzoom' # set after adding axes to auto-zoom line = scene.Line(pos, color, parent=viewbox.scene) 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()
def draw_axes(self): #First, calculate positions self.position_axes() #Draw x axis self._xax=scene.Axis( pos=[[self._xlim[0], self._ylim[self._axpos[0,1]], self._zlim[self._axpos[0,2]]], [self._xlim[1], self._ylim[self._axpos[0,1]], self._zlim[self._axpos[0,2]]]], domain=self._xlim, tick_direction=(0,-1,0), major_tick_length=10*self._cam_dist, font_size=10*self._cam_dist, font_face='FreeSerif', axis_color='k', tick_color='k', text_color='k', parent=self._view.scene) self._xlabel = scene.Text("x", pos=[(self._xlim[0]+self._xlim[1])/2, self._ylim[self._axpos[0,1]]-self._label_dist, self._zlim[self._axpos[0,2]]], font_size=10*self._cam_dist, face='FreeSerif', color='k', parent=self._view.scene) #Draw y axis self._yax=scene.Axis( pos=[[self._xlim[self._axpos[1,0]], self._ylim[0], self._zlim[self._axpos[1,2]]], [self._xlim[self._axpos[1,0]], self._ylim[1], self._zlim[self._axpos[1,2]]]], domain=self._ylim, tick_direction=(1,0,0), major_tick_length=10*self._cam_dist, font_size=10*self._cam_dist, font_face='FreeSerif', axis_color='k', tick_color='k', text_color='k', parent=self._view.scene) self._ylabel = scene.Text("y", pos=[self._xlim[self._axpos[1,0]]-self._label_dist, (self._ylim[0]+self._ylim[1])/2, self._zlim[self._axpos[1,2]]], font_size=10*self._cam_dist, face='FreeSerif', color='k', parent=self._view.scene) #Draw z axis self._zax=scene.Axis( pos=[[self._xlim[self._axpos[2,0]], self._ylim[self._axpos[2,1]], self._zlim[0]], [self._xlim[self._axpos[2,0]], self._ylim[self._axpos[2,1]], self._zlim[1]]], domain=self._zlim, tick_direction=(0,-1,0), major_tick_length=10*self._cam_dist, font_face='FreeSerif', font_size=10*self._cam_dist, axis_color='k', tick_color='k', text_color='k', parent=self._view.scene) self._zlabel = scene.Text("z", pos=[self._xlim[self._axpos[2,0]], self._ylim[self._axpos[2,1]]-self._label_dist, (self._zlim[0]+self._zlim[1])/2], font_size=10*self._cam_dist, face='FreeSerif', color='k', parent=self._view.scene) self._xax._update_subvisuals() self._yax._update_subvisuals() self._zax._update_subvisuals() #Add plot to scene self._view.add(self._volume)
def main(objects, object_id, var_name=None): m = objects.where(objects == object_id, drop=True) data_source, objects_mask = object_file.split(".objects.") path, base_name = data_source.split("__") if var_name: fn = os.path.join(path, "3d_blocks", "full_domain", "{}.{}.nc".format(base_name, var_name)) if not os.path.exists(fn): fn = os.path.join(path, "masks", "{}.{}.nc".format(base_name, var_name)) da = xr.open_dataarray(fn, decode_times=False) da = da.squeeze().sel(xt=m.xt, yt=m.yt, zt=m.zt) da -= da.mean() da /= da.max() print(da.max()) else: da = m # vispy expects data as (z, y, x) da = da.transpose("zt", "yt", "xt") nz, ny, nx = da.shape fn_out = "temp_3d_block.nc" del da.xt.attrs["standard_name"] del da.yt.attrs["standard_name"] da.to_netcdf(fn_out) print("Wrote {}".format(fn_out)) # m = np.swapaxes(m, 0, 2) # x_min, x_max = m.xt.min(), m.xt.max() # y_min, y_max = m.yt.min(), m.yt.max() # xc, yc = m.xt.mean(), m.yt.mean() # Prepare canvas canvas = scene.SceneCanvas(keys="interactive", size=(1200, 800), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Set whether we are emulating a 3D texture emulate_texture = False # Create the volume visuals, only one is visible # data = np.swapaxes(m.values, 0, 1) data = da.fillna(0.0).values # np.flipud(np.rollaxis(m.values, 1)) data = (data - data.min()) / (data.max() - data.min()) volume1 = scene.visuals.Volume( data, parent=view.scene, threshold=0.5, emulate_texture=emulate_texture, method="translucent", cmap=translucent_cmap, ) # volume1.transform = scene.STTransform(translate=(0, 0, nz)) volume1.transform = scene.STTransform(translate=(-nx / 2, -ny / 2, 0)) # Create three cameras (Fly, Turntable and Arcball) fov = 60.0 cam = scene.cameras.ArcballCamera(parent=view.scene, fov=fov, name="Arcball", up="z") cam.distance = nz * 5 view.camera = cam _ = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [0.5 * nx, -0.5 * ny]], tick_direction=(0, -1), font_size=16, axis_color="r", tick_color="r", text_color="r", parent=view.scene, ) _ = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [0.5 * nx, -0.5 * ny]], tick_direction=(0, -1), font_size=16, axis_color="r", tick_color="r", text_color="r", parent=view.scene, ) # xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [-0.5 * nx, 0.5 * ny]], tick_direction=(-1, 0), font_size=16, axis_color="b", tick_color="b", text_color="b", parent=view.scene, ) yax.transform = scene.STTransform(translate=(0, 0, -0.2)) # Implement key presses @canvas.events.key_press.connect def on_key_press(event): global opaque_cmap, translucent_cmap if event.text == "1": pass elif event.text == "2": methods = ["translucent", "additive"] method = methods[(methods.index(volume1.method) + 1) % len(methods)] print("Volume render method: %s" % method) cmap = opaque_cmap if method in ["mip", "iso" ] else translucent_cmap volume1.method = method volume1.cmap = cmap elif event.text == "4": if volume1.method in ["mip", "iso"]: cmap = opaque_cmap = next(opaque_cmaps) else: cmap = translucent_cmap = next(translucent_cmaps) volume1.cmap = cmap elif event.text == "0": cam.set_range() elif event.text != "" and event.text in "[]": s = -0.025 if event.text == "[" else 0.025 volume1.threshold += s th = volume1.threshold print("Isosurface threshold: %0.3f" % th) # for testing performance # @canvas.connect # def on_draw(ev): # canvas.update() app.run()