def ShowAnimation3D(self, size=15): ipv.figure() ipv.style.use("dark") x_Part = [] y_Part = [] z_Part = [] for Part in self.Parts: temp_x = Part.x temp_y = Part.y temp_z = Part.z x_Part.append(temp_x) y_Part.append(temp_y) z_Part.append(temp_z) x = combine(self.speed * 5, *x_Part) y = combine(self.speed * 5, *y_Part) z = combine(self.speed * 5, *z_Part) u = ipv.scatter(x, y, z, marker="sphere", size=10, color="green") ipv.animation_control(u, interval=100) ipv.xyzlim(-size, size) ipv.show()
def volshow_zoom_correct_scale(x_list, y_list, z_list, f, zoom_factor=0): # zoom_factor is the number of times the grid is doubled # (actually a zoom by 2 ** zoom_factor) # Assume constant spacing in each dimension dx = np.mean(np.diff(x_list)) dy = np.mean(np.diff(y_list)) dz = np.mean(np.diff(z_list)) # zoom x_grid, y_grid, z_grid = np.meshgrid(x_list, y_list, z_list, indexing='ij') new_f = double_n(f, zoom_factor) # data extent extent = ((min(x_list) - dx / 2, max(x_list) + dx / 2), (min(y_list) - dy / 2, max(y_list) + dy / 2), (min(z_list) - dz / 2, max(z_list) + dz / 2)) ipv.figure() # volshow ipv.volshow(new_f.T) # figure extent ipv.xlim(min(x_list) - dx / 2, max(x_list) + dx / 2) ipv.ylim(min(y_list) - dy / 2, max(y_list) + dy / 2) ipv.zlim(min(z_list) - dz / 2, max(z_list) + dz / 2) ipv.show()
def FCC(L_x, L_y, L_z, Color='red'): Ax = [] Ay = [] Az = [] #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells for O in range(L_x * 2 - 1): #for each layer in the y direction. for S in range(L_y * 2 - 1): #for each layer in the z direction. for A in range(L_z * 2 - 1): if (O + S + A) % 2 == 0: #the 0.5 is becasue L_xyz was multiplied by 2 Ax.append(float(O * .5)) Ay.append(float(S * .5)) Az.append(float(A * .5)) elif S % 2 == 1 and O % 2 == 1 and A % 2 == 0: Ax.append(float(O * .5)) Ay.append(float(S * .5)) Az.append(float(A * .5)) #if there should not be an atom #in theory this could be used to remove other atoms to make cubic or BCC structure #the x, y, z limits ipv.xyzlim(0, 10) #define as a function highest of L_xyz ipv.scatter(np.array(Ax), np.array(Ay), np.array(Az), marker='sphere', size=6.5, color=Color) ipv.show()
def plot_clusters(self, threshold, rcut=28, size=5.): ipv.clear() s = self.trace <= threshold xyz = self.stress_coord[s] x, y, z = xyz[:, 0], xyz[:, 1], xyz[:, 2] clustering = DBSCAN(eps=rcut, min_samples=1).fit(xyz) labels = np.unique(clustering.labels_) counts, edges = np.histogram(clustering.labels_, bins=np.arange(labels.min(), labels.max() + 1)) largest = edges[counts.argmax()] color_dict = {} for l in labels: color_dict[l] = tuple(np.random.uniform(0, 1, size=3)) color_dict[largest] = (1, 1, 1) colors = np.array([color_dict[c] for c in clustering.labels_]) color = np.array([(x - x.min()) / x.ptp(), np.ones_like(x), np.ones_like(x)]).T ipv.scatter(x, y, z, size=size, marker="sphere", color=colors) ipv.show()
def show_segmentation(voxel_segmentation, size=2.0, width=500, height=500): ipyvolume.figure(width=width, height=height) ipyvolume.view(0, 90) def get_color(label, info): if label == "stem": color = (128, 128, 128) elif label == "unknown": color = (255, 255, 255) elif 'pm_leaf_number' in info: color_map = order_color_map() color = color_map[info['pm_leaf_number']] color = tuple([int(255 * x) for x in color]) else: if label == "growing_leaf": color = (255, 0, 0) else: color = (0, 255, 0) return "rgb" + str(color) for vo in voxel_segmentation.voxel_organs: voxels_position = numpy.array( list(map(tuple, list(vo.voxels_position())))) plot_voxel(voxels_position, size=size * 1, color=get_color(vo.label, vo.info)) if ((vo.label == "mature_leaf" or vo.label == "growing_leaf") and len(vo.voxel_segments) > 0 and "pm_position_tip" in vo.info): plot_voxel(numpy.array([vo.info['pm_position_tip']]), size=size * 2, color="red", marker="sphere") plot_voxel(numpy.array([vo.info['pm_position_base']]), size=size * 2, color="blue", marker="sphere") voxels_position = numpy.array( list(voxel_segmentation.get_voxels_position())) x_min = voxels_position[:, 0].min() x_max = voxels_position[:, 0].max() y_min = voxels_position[:, 1].min() y_max = voxels_position[:, 1].max() z_min = voxels_position[:, 2].min() z_max = voxels_position[:, 2].max() xyz_max = max(x_max - x_min, y_max - y_min, z_max - z_min) ipyvolume.xlim(x_min, x_min + xyz_max) ipyvolume.ylim(y_min, y_min + xyz_max) ipyvolume.zlim(z_min, z_min + xyz_max) ipyvolume.show()
def on_select_to_plot(self, change): """Call-back function for plotting a 3D visualisaiton of the segmentation""" #if the selected file has changed, import image, segmentation and global mask and plot if change['new'] != change['old']: print('new: ' + str(change['new'])) print('old: ' + str(change['old'])) image = skimage.io.imread(self.folder_name + '/' + self.select_file_to_plot.value, plugin='tifffile') image2 = skimage.io.imread( self.folder_name + '/' + os.path.splitext(self.select_file_to_plot.value)[0] + '_label.tif', plugin='tifffile') image3 = skimage.io.imread( self.folder_name + '/' + os.path.splitext(self.select_file_to_plot.value)[0] + '_region.tif', plugin='tifffile') #create ipyvolume figure ipv.figure() volume_image = ipv.volshow(image[0, :, :, :, 1], extent=[[0, 1024], [0, 1024], [-20, 20]], level=[0.3, 0.2, 0.2], opacity=[0.2, 0, 0]) volume_seg = ipv.plot_isosurface(np.swapaxes(image2 > 0, 0, 2), level=0.5, controls=True, color='green', extent=[[0, 1024], [0, 1024], [-20, 20]]) volume_reg = ipv.volshow(image3, extent=[[0, 1024], [0, 1024], [-20, 20]], level=[0.3, 0.2, 1], opacity=[0.0, 0, 0.5]) volume_reg.brightness = 10 volume_image.brightness = 10 volume_image.opacity = 100 ipv.xyzlim(0, 1024) ipv.zlim(-500, 500) ipv.style.background_color('black') #create additional controls to show/hide segmentation color = ColorPicker(description='Segmentation color') visible = ipw.Checkbox() jslink((volume_seg, 'color'), (color, 'value')) jslink((volume_seg, 'visible'), (visible, 'value')) ipv.show() with self.out: clear_output(wait=True) display(VBox([ipv.gcc(), color, visible])) viewer = napari.Viewer(ndisplay=3) viewer.add_image(image, colormap='red') viewer.add_image(image2, colormap='green', blending='additive') viewer.add_image(image3, colormap='blue', blending='additive')
def plot_mesh(value_mesh_list, w1_mesh, w2_mesh, save, show_box, show_axes): ipv.clear() figs = [] for mesh in value_mesh_list: fig = ipv.pylab.figure() fig.camera.up = (0, 0, 1) fig.camera.position = (-2, 1, -0.5) fig.camera_control = "trackball" if not show_axes: ipv.style.box_off() else: ipv.xlabel("w1") ipv.ylabel("w2") ipv.zlabel("f_lambda") if not show_box: ipv.pylab.style.axes_off() ipv.pylab.zlim(mesh.min(), mesh.max()) ptp = (mesh - mesh.min()).ptp() col = [] for m in mesh: znorm = (m - m.min()) / (m.max() - m.min() + 1e-8) color = np.asarray([[interpolate(darker(colors_alpha[0], 1.5 * x + 0.75), darker(colors_alpha[1], 1.5 * (1 - x) + 0.75), x) for x in y] for y in znorm]) col.append(color) color = np.array(col) surf = ipv.plot_surface(w1_mesh, w2_mesh, mesh, color=color[..., :3]) ipv.animation_control(surf, interval=400) figs.append(fig) ipv.show() if save: ipv.save(f'renders/{datetime.datetime.now().strftime("%m%d-%H%M")}.html', offline=True) return figs
def volshow_with_isoplanes_and_zoom(x_list, y_list, z_list, f, zoom_factor): # zoom_factor is the number of times the grid is doubled # (actually a zoom by 2 ** zoom_factor) # Assume constant spacing in each dimension dx = np.mean(np.diff(x_list)) dy = np.mean(np.diff(y_list)) dz = np.mean(np.diff(z_list)) # zoom x_grid, y_grid, z_grid = np.meshgrid(x_list, y_list, z_list, indexing='ij') new_f = double_n(f, zoom_factor) # data extent extent = ((min(x_list) - dx / 2, max(x_list) + dx / 2), (min(y_list) - dy / 2, max(y_list) + dy / 2), (min(z_list) - dz / 2, max(z_list) + dz / 2)) ipv.figure() # isosurfaces ipv.plot_isosurface(new_f) # volshow ipv.volshow(new_f.T) ipv.show()
def browse_history(history, coords=["x", "y", "z"], start=None, stop=None, size=None, **draw_specs_kw): times = history.slice(start, stop, size) num_frames = times.size draw_specs = sheet_spec() spec_updater(draw_specs, draw_specs_kw) sheet = history.retrieve(0) ipv.clear() fig, meshes = sheet_view(sheet, coords, **draw_specs_kw) lim_inf = sheet.vert_df[sheet.coords].min().min() lim_sup = sheet.vert_df[sheet.coords].max().max() ipv.xyzlim(lim_inf, lim_sup) def set_frame(i=0): fig.animation = 0 t = times[i] meshes = _get_meshes(history.retrieve(t), coords, draw_specs) update_view(fig, meshes) ipv.show() interact(set_frame, i=(0, num_frames - 1))
def plot_3D(self, type, fname): x = self.data['XWIN'] y = self.data['YWIN'] oceta = self.data['O-Ceta'] oxi = self.data['O-Cxi'] resids = [(((oceta[i]**2) + (oxi[i]**2))**.5) for i in range(len(oceta))] if type == 'trisurf': z = resids fig = plt.figure() ax = fig.gca(projection='3d') ax.set_xlabel('XWIN') ax.set_ylabel('YWIN') ax.set_zlabel('magnitude of residual') ax.plot_trisurf(x, y, z, cmap='magma') plt.savefig(os.path.join(self.directory, fname + '.png')) plt.show() elif type == 'quiver': x = np.array(x) y = np.array(y) over = self.searchhighestresids(90) #x = [self.data['XWIN'][i] for i in over] #y = [self.data['YWIN'][i] for i in over] z = np.array(resids) u = np.array(self.data['O-Ceta']) v = np.array(self.data['O-Cxi']) w = np.array([0 for i in range(len(v))]) p3.clear() quiver = p3.quiver(x, y, z, u, v, w, size=3) #p3.savefig(os.path.join(self.directory, fname + '.png')) p3.show()
def complete(final_solution: Solution, correct_solution: Solution = None) -> None: """ Will print result in 3D world :return: Noting """ # init of plot-output #1 figure = plot.figure() axes = figure.add_subplot(111, projection='3d') for part in final_solution.partitions: color = random.choice(list_of_colors) marker = random.choice(list_of_marker) for p in part: axes.scatter(p.x, p.y, p.z, marker=marker, c=color) axes.set_xlabel("X Achse") axes.set_ylabel("Y Achse") axes.set_zlabel("Z Achse") plot.show() # init 3D view ipv.current.containers.clear() ipv.current.figures.clear() extra_figures = list() # create correct solution if correct_solution is not None: figure_correct = ipv.figure("correct") ipv.pylab.xyzlim(-1, 11) for part in correct_solution.partitions: marker = random.choice(list_of_IPYVmarker) color = random.choice(list_of_colors) ipv.scatter(*convert.partition_to_IpyVolume(part), marker=marker, color=color) extra_figures.append(figure_correct) figure_result = ipv.figure("result") container = ipv.gcc() ipv.current.container = widgets.HBox(container.children) ipv.current.containers["result"] = ipv.current.container # crate computed solution for part in final_solution.partitions: marker = random.choice(list_of_IPYVmarker) color = random.choice(list_of_colors) ipv.scatter(*convert.partition_to_IpyVolume(part), marker=marker, color=color) ipv.pylab.xyzlim(-1, 11) ipv.current.container.children = list( ipv.current.container.children) + extra_figures ipv.show() # save in a separate file ipv.save("example.html") # destroy 3D views ipv.clear()
def plot_train_test ( trainData, trainLabels, testData, testLabels, maxSamplesToPlot = 10000): minStride = 2 trainStride = trainData.shape[0] // maxSamplesToPlot if trainStride % minStride != 0: trainStride += 1 testStride = testData.shape[0] // maxSamplesToPlot if testStride % minStride != 0: testStride += 1 strideStepTrain = np.max((minStride, trainStride)) strideStepTest = np.max((minStride, testStride)) coil1TrainData = trainData[0::strideStepTrain].to_pandas().values.astype( 'float64') coil2TrainData = trainData[1::strideStepTrain].to_pandas().values.astype( 'float64') coil1TestData = testData[0::strideStepTest].to_pandas().values.astype( 'float64') coil2TestData = testData[1::strideStepTest].to_pandas().values.astype( 'float64') ipv.figure() # train data ipv.scatter(coil1TrainData[:,0], coil1TrainData[:,1], coil1TrainData[:,2], size = .25, color='lightgreen', marker='sphere') ipv.scatter(coil2TrainData[:,0], coil2TrainData[:,1], coil2TrainData[:,2], size = .25, color='purple', marker='sphere') # test data overlay on train data ipv.scatter(coil1TestData[:,0], coil1TestData[:,1], coil1TestData[:,2], size = .1, color='lightgray', marker='sphere') ipv.scatter(coil2TestData[:,0], coil2TestData[:,1], coil2TestData[:,2], size = .1, color='lightgray', marker='sphere') # test data callout offset = np.max((coil1TrainData[:,2])) * 3 ipv.scatter(coil1TestData[:,0], coil1TestData[:,1], coil1TestData[:,2] + offset, size = .25, color='lightgreen', marker='sphere') ipv.scatter(coil2TestData[:,0], coil2TestData[:,1], coil2TestData[:,2] + offset, size = .25, color='purple', marker='sphere') ipv.pylab.squarelim() ipv.show()
def viz_dimer_positions(positions, size=5, cmap_name="tab20c", color_feature_name=None): import ipyvolume as ipv # Only show visible dimers selected_dimers = positions[positions['visible'] is True] x, y, z = selected_dimers[['x', 'y', 'z']].values.astype('float').T if color_feature_name: # TODO: that code should be much simpler... cmap = matplotlib.cm.get_cmap(cmap_name) categories = selected_dimers[color_feature_name].unique() color_indices = cmap([i / len(categories) for i in categories]) color = np.zeros((len(selected_dimers[color_feature_name]), 4)) for color_index in enumerate(categories): color[selected_dimers[color_feature_name] == categories[color_index]] = color_indices[color_index] else: color = '#e4191b' ipv.figure(height=800, width=1000) ipv.scatter(x, y, z, size=size, marker='sphere', color=color) ipv.squarelim() ipv.show()
def show_colorspace(cspace: np.array, clip=True, size=0.5, marker='sphere', **kwargs) -> None: """ Visualise colorspace vector as an interactive 3D figure. Colorspace can have extra columns By default RGB channels are clipped to the range [0,1]. Extra arguments can be used to control the appearance of ipyvolume.scatter """ assert isinstance(cspace, DataFrame), "Colorspace must be a dataframe" assert all(np.isin(['R', 'G', 'B'], cspace.columns)), "Colorspace must contain RGB columns" fig = ipv.figure() if clip: ipv.scatter(cspace.loc[:, 'R'].values, cspace.loc[:, 'G'].values, cspace.loc[:, 'B'].values, color=np.clip(cspace[['R', 'G', 'B']].values, 0, 1), s=size, marker=marker, *kwargs) else: ipv.scatter(cspace.loc[:, 'R'].values, cspace.loc[:, 'G'].values, cspace.loc[:, 'B'].values, color=cspace[['R', 'G', 'B']].values, s=size, marker=marker, *kwargs) ipv.show()
def display_hidden_fluxes_sphere( self, cmap="magma", distance_transform=None, use_log=False, background_color="white", show=True, **kwargs, ): theta = self._theta[~self._selection] phi = self._phi[~self._selection] fig = self._display_sphere( self._flux_hidden, self._distance_hidden, theta=theta, phi=phi, cmap=cmap, distance_transform=distance_transform, background_color=background_color, use_log=use_log, show=show, **kwargs, ) if show: ipv.show() return fig
def data_points(buttons, drop): ipv.figure() ipv.scatter(all_pt[0], all_pt[1], all_pt[2], size=2, marker='sphere', color='red') for i in range(len(traces)): pairs = traces[i]['pairs'] ipv.plot_trisurf(all_pt[0], all_pt[1], all_pt[2], lines=pairs) if drop != None: if buttons == 'Analysis': x = pt55[in_names55[drop]][0] y = pt55[in_names55[drop]][1] z = pt55[in_names55[drop]][2] ipv.scatter(x, y, z, size=3, color='blue', marker='circle_2d') if buttons == 'Function data': x = pt58[in_names58[drop]][0] y = pt58[in_names58[drop]][1] z = pt58[in_names58[drop]][2] ipv.scatter(x, y, z, size=3, color='blue', marker='circle_2d') ipv.xlim(min(all_pt[0]) - 1, max(all_pt[0]) + 1) ipv.ylim(min(all_pt[1]) - 1, max(all_pt[1]) + 1) ipv.zlim(min(all_pt[2]) - 1, max(all_pt[2]) + 1) ipv.show()
def my_volshow_2channel(volume, view=(0, 0, 0), rotation=(0, 0, 0, 'XYZ'), perspective=None, plot_params=None, fig_width=400, fig_height=500): """Customized volume show function, with specified camera position and angle. Args: volume: multi-channnel volume data view: camera position rotation: camera angle perspective: alternatively, pre-saved camera perspective plot_params: list of key-word arguments as a dictionary for ipv.volshow """ n_channels = len(volume) if plot_params is None: plot_params = [{}] * n_channels assert len(plot_params) == n_channels ipv.pylab.figure(width=fig_width, height=fig_height) for ch in range(n_channels): ipv.volshow(volume[ch, :], **plot_params[ch]) ipv.show() # wait for plot to be generated (JavaScript) time.sleep(1) # set camera position and angle set_perspective(view=view, rotation=rotation, perspective=perspective)
def ipv_animate(particles, velocities, particleColors, particleSizes, paramRanges): nTimesteps = particles.shape[0] nParticles = particles.shape[1] # determine quiver sizes and colors veloQuiverSizes = np.zeros((nTimesteps, nParticles, 1)) for iTimestep in range(nTimesteps): veloQuiverSizes[iTimestep, :, 0] = np.linalg.norm(velocities[iTimestep, :, :], axis=1) veloQuiverSizes = np.clip(veloQuiverSizes, 0, 2) quiverColors = np.ones( (nTimesteps, nParticles, 4)) * .8 #veloQuiverSizes/3 ipv.figure() #bPlots = ipv.scatter( best[:, :, 0], best[:, :, 1], best[:, :, 2], marker = 'sphere', size=2, color = 'red' ) pPlots = ipv.scatter(particles[:, :, 0], particles[:, :, 1], particles[:, :, 2], marker='sphere', size=particleSizes, color=particleColors) #qvPlots = ipv.quiver( particles[:, :, 0], particles[:, :, 1], particles[:, :, 2], velocities[:, :, 0], velocities[:, :, 1], velocities[:, :, 2], size=veloQuiverSizes[:,:,0]*3, color=quiverColors) ipv.animation_control([pPlots], interval=600) ipv.xlim(paramRanges[0][1], paramRanges[0][2]) ipv.ylim(paramRanges[1][1], paramRanges[1][2]) ipv.zlim(paramRanges[2][1], paramRanges[2][2]) ipv.show()
def show_mesh(vertices, faces, color='green', width=500, height=500, colors=None): ipyvolume.figure(width=width, height=height) ipyvolume.view(0, 90) ipyvolume.plot_trisurf(vertices[:, 0], vertices[:, 1], vertices[:, 2], triangles=faces, color=color) x_min = vertices[:, 0].min() x_max = vertices[:, 0].max() y_min = vertices[:, 1].min() y_max = vertices[:, 1].max() z_min = vertices[:, 2].min() z_max = vertices[:, 2].max() xyz_max = max(x_max - x_min, y_max - y_min, z_max - z_min) ipyvolume.xlim(x_min, x_min + xyz_max) ipyvolume.ylim(y_min, y_min + xyz_max) ipyvolume.zlim(z_min, z_min + xyz_max) ipyvolume.show()
def viz_dimer_positions_ipv(positions, size=5, cmap_name="tab20c", color_feature_name=None): try: import ipyvolume as ipv except ImportError: mess = "YOu need to install the ipyvolume library. " mess += "Please follow the official instructions at https://github.com/maartenbreddels/ipyvolume." raise ImportError(mess) # Only show visible dimers selected_dimers = positions[positions["visible"]] x, y, z = selected_dimers[["x", "y", "z"]].values.astype("float").T if color_feature_name: # TODO: that code should be much simpler... cmap = matplotlib.cm.get_cmap(cmap_name) categories = selected_dimers[color_feature_name].unique() color_indices = cmap([i / len(categories) for i in categories]) color = np.zeros((len(selected_dimers[color_feature_name]), 4)) for color_index, _ in enumerate(categories): mask = selected_dimers[color_feature_name] == categories[ color_index] color[mask] = color_indices[color_index] else: color = "#e4191b" ipv.figure(height=800, width=1000) ipv.scatter(x, y, z, size=size, marker="sphere", color=color) ipv.squarelim() ipv.show()
def particleSimulate(num_particles, box_size, total_time, time_step, particle_radius, grav=False, save=False): print("Running simulation...") """Run the simulation and extract the x,y,z coordinates to plot the particle's path""" particle_list = initialize_particles(num_particles, box_size, time_step, grav) #Generate starting points x = np.zeros([total_time, num_particles, 1]) y = np.zeros([total_time, num_particles, 1]) z = np.zeros([total_time, num_particles, 1]) time = 0 #print(str(tot_eng(particle_list))) #Used to track the total energy of the particles while time < total_time: #Loop through iterations of particle movements #Check to see if bouncing occurs isbounce(particle_list, particle_radius, time_step) for i in range(len(particle_list)): particle_list[i].pos_update(time_step) #Update position x[time, i] = particle_list[i].pos[0] y[time, i] = particle_list[i].pos[1] z[time, i] = particle_list[i].pos[2] time += 1 if (time / total_time) * 100 % 10 == 0: print(str(time / total_time * 100) + "% complete") """Plot the results of all of the particle movements""" colors = [] for i in range(num_particles): colors.append( [np.random.random(), np.random.random(), np.random.random()]) ipv.figure() s = ipv.scatter(x, z, y, color=colors, size=7, marker="sphere") ipv.animation_control(s, interval=1) ipv.xlim(-1, box_size + 1) ipv.ylim(-1, box_size + 1) ipv.zlim(-1, box_size + 1) ipv.style.axes_off() ipv.show() if save == True: print("Saving the video of the simulation in the current directory...") ipv.save('./particle_sim.html')
def draw_tensor(tensor_img): ipv.figure() # ipv.volshow(tensor_img[...,0], level=[0.36, 0.55,1], opacity=[0.11,0.13, 0.13], level_width=0.05, data_min=0, data_max=1 ,lighting=True) ipv.volshow(tensor_img[...,0], level=[0.36, 0.17,0.36], opacity=[0.05,0.13, 0.10], level_width=0.05, data_min=0, data_max=1 ,lighting=True) ipv.view(-30, 45) ipv.show()
def brain(draw=True, show=True, fiducial=True, flat=True, inflated=True, subject='S1', interval=1000, uv=True, color=None): import ipyvolume as ipv try: import cortex except: warnings.warn("it seems pycortex is not installed, which is needed for this example") raise xlist, ylist, zlist = [], [], [] polys_list = [] def add(pts, polys): xlist.append(pts[:,0]) ylist.append(pts[:,1]) zlist.append(pts[:,2]) polys_list.append(polys) def n(x): return (x - x.min()) / x.ptp() if fiducial or color is True: pts, polys = cortex.db.get_surf('S1', 'fiducial', merge=True) x, y, z = pts.T r = n(x) g = n(y) b = n(z) if color is True: color = np.array([r,g,b]).T.copy() else: color = None if fiducial: add(pts, polys) else: if color is False: color = None if inflated: add(*cortex.db.get_surf('S1', 'inflated', merge=True, nudge=True)) u = v = None if flat or uv: pts, polys = cortex.db.get_surf('S1', 'flat', merge=True, nudge=True) x, y, z = pts.T u = n(x) v = n(y) if flat: add(pts, polys) polys_list.sort(key=lambda x: len(x)) polys = polys_list[0] if draw: if color is None: mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, u=u, v=v) else: mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, color=color, u=u, v=v) if show: if len(x) > 1: ipv.animation_control(mesh, interval=interval) ipv.squarelim() ipv.show() return mesh else: return xlist, ylist, zlist, polys
def plot_data(self, data, outPath="3-D_figure", marker='sphere', size=2, heatmap=None, inline=False, plot_type="scatter"): ipv.figure(width=400, height=500, lighting=True, controls=True) x, y, z = data[0], data[1], data[2] #TODO: marker control if heatmap == None: if plot_type == "scatter": ipv.quickscatter(x, y, z, marker=marker, size=size) #, size=10) if plot_type == "surface": ipv.plot_surface(x, y, z) else: from matplotlib import cm colormap = cm.coolwarm heatmap /= (heatmap - heatmap.min()) color = colormap(heatmap) if plot_type == "scatter": ipv.quickscatter(x, y, z, color=color[..., :3], marker=marker, size=size) #, size=10) if plot_type == "surface": ipv.plot_surface(x, y, z, color=color) #ipv.plot_surface(data[0], data[1], data[2], color="orange") #ipv.plot_wireframe(data[0], data[1], data[2], color="red") ipv.pylab.xlim(self.xlim[0], self.xlim[1]) ipv.pylab.ylim(self.ylim[0], self.ylim[1]) if self.zlim != [None, None]: ipv.pylab.zlim(self.zlim[0], self.zlim[1]) else: ipv.pylab.zlim(self.ylim[0], self.ylim[1]) #ipv.style.use(['seaborn-darkgrid', {'axes.x.color':'orange'}]) ipv.pylab.view(azimuth=-45, elevation=25, distance=5) ipv.pylab.xlabel("%s" % self.axis_labels[0]) ipv.pylab.ylabel("%s" % self.axis_labels[1]) ipv.pylab.zlabel("%s" % self.axis_labels[2]) if inline: ipv.show() else: ipv.pylab.save("%s.html" % outPath, title=r"%s" % (latex), offline=None, template_options=(('extra_script_head', ''), ('body_pre', ''), ('body_post', ''))) run_cmd('open %s.html' % (str(outPath)))
def show(): view = [0, 0, 0] ipv.xlim(view[1] - 0.5, view[1] + 0.5) ipv.ylim(view[1] - 0.5, view[1] + 0.5) ipv.zlim(view[2] - 0.5, view[2] + 0.5) #ipv.style.axes_off() #ipv.style.box_off() ipv.show()
def show_centerline(pred): pred[pred == 255] = 0 mesh = np.meshgrid(*[range(pred.shape[i]) for i in range(1, 4)], indexing='ij') cents = mesh + pred[1:] centdots = cents.transpose([1, 2, 3, 0])[pred[0] > 0] ipv.figure() ipv.scatter(centdots[:, 0], centdots[:, 1], centdots[:, 2], size=0.1) # ipv.volshow(pred[0]) ipv.show()
def NACL(L_x, L_y=None, L_z=None, ColorNa='red', ColorCl='green'): if L_y == None: L_y = L_x if L_z == None: L_z = L_x if L_x > L_y: Max = L_x else: Max = L_y if L_z > Max: Max = L_z #defined as a function highest of L_xyz #define a list of positions to append to Clx = [] Cly = [] Clz = [] Nax = [] Nay = [] Naz = [] #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells for O in range(L_x * 2 - 1): #for each layer in the y direction. for S in range(L_y * 2 - 1): #for each layer in the z direction. for A in range(L_z * 2 - 1): #if in this position there shoud be a Cl atom if (O + S + A) % 2 == 0: #the 0.5 is becasue L_xyz was multiplied by 2 Clx.append(float(O * .5)) Cly.append(float(S * .5)) Clz.append(float(A * .5)) #if there should be a Na atom elif (O + S + A) % 2 == 1: Nax.append(float(O * .5)) Nay.append(float(S * .5)) Naz.append(float(A * .5)) #if there should not be an atom #in theory this could be used to remove other atoms to make cubic or BCC structure #the x, y, z limits ipv.xyzlim(0, Max) #the color and size the Na and Cl atoms ipv.scatter(np.array(Clx), np.array(Cly), np.array(Clz), marker='sphere', size=6.5, color=ColorCl) ipv.scatter( np.array(Nax), np.array(Nay), np.array(Naz), marker='sphere', size=4, color=ColorNa, ) ipv.show()
def ipv_plot_coils ( coil1, coil2, maxSamplesToPlot = 10000): assert( type(coil1) == np.ndarray and type(coil2) == np.ndarray) maxSamplesToPlot = min( ( coil1.shape[0], maxSamplesToPlot ) ) stride = np.max((1, coil1.shape[0]//maxSamplesToPlot)) print( '\t plotting data - stride = {} '.format( stride ) ) ipv.figure() ipv.scatter( coil1[::stride,0], coil1[::stride,1], coil1[::stride,2], size = .5, marker = 'sphere', color = 'lightgreen') ipv.scatter( coil2[::stride,0], coil2[::stride,1], coil2[::stride,2], size = .5, marker = 'sphere', color = 'purple') ipv.pylab.squarelim() ipv.show()
def aniplot(folder, frame): if frame is None: frame = len( fnmatch.filter(os.listdir('/u/yali/' + folder + '/test/output'), '*.hdf5')) x = [] y = [] z = [] vx = [] vy = [] vz = [] v = [] for i in np.arange(frame): fname = str(format(i, '03d')) f = h5py.File("/u/yali/" + folder + "/test/output/snapshot_" + fname + ".hdf5", 'r') # Read-only access to the file #intE = [] #density = [] x.append(f['PartType0']['Coordinates'][:, 0]) y.append(f['PartType0']['Coordinates'][:, 1]) z.append(f['PartType0']['Coordinates'][:, 2]) #intE.append(f['Partype0']['InternalEnergy'][:]) vx.append(f['PartType0']['Velocities'][:, 0]) vy.append(f['PartType0']['Velocities'][:, 1]) vz.append(f['PartType0']['Velocities'][:, 2]) #density.append(f['PartType0']['Density'][:]) # and normalize x = np.array(x) y = np.array(y) z = np.array(z) vx = np.array(vx) vy = np.array(vy) vz = np.array(vz) v = np.array(np.sqrt(vx**2 + vy**2 + vz**2)) v -= v.min() v /= v.max() # map the normalized values to rgba colors cmap = cm.Reds colors = np.array([cmap(k) for k in v]) colors.shape # plot animation fig = ipv.figure() ipv.style.use('dark') # use just rgb colors, not rgba quiver = ipv.quiver(x, y, z, vx, vy, vz, size=5, color=colors[:, :, :3]) # create the animation widgets/slider ipv.animation_control(quiver, interval=500) ipv.show()
def show_quiver(pred, sparse=10): arrows = pred[1:].transpose([1, 2, 3, 0])[pred[0] > 0] coord = np.array(np.where(pred[0] > 0)).astype('float').transpose() ipv.figure() ipv.quiver(coord[::sparse, 0], coord[::sparse, 1], coord[::sparse, 2], arrows[::sparse, 0], arrows[::sparse, 1], arrows[::sparse, 2], size=1) ipv.show()