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 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 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 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 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 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 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 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 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 PlotSkeleton(seg_name, plot_type='node', out_res=(30, 48, 48)): print('Read skeletons') skeletons = ReadSkeletons(seg_name, skeleton_algorithm='thinning', downsample_resolution=out_res, read_edges=True) print('Plot skeletons') node_list = skeletons[1].get_nodes() nodes = np.stack(node_list).astype(float) junction_idx = skeletons[1].get_junctions() junctions = nodes[junction_idx, :] ends = skeletons[1].get_ends() jns_ends = np.vstack([junctions, ends]) IX, IY, IZ = 2, 1, 0 ipv.figure() if plot_type == 'nodes': nodes = ipv.scatter(nodes[:,IX], nodes[:,IY], nodes[:,IZ], \ size=0.5, marker='sphere', color='blue') elif plot_type == 'edges': edges = skeletons[1].get_edges().astype(float) for e1, e2 in edges: if not ((e1[IX] == e2[IX]) and (e1[IY] == e2[IY]) and (e1[IZ] == e2[IZ])): ipv.plot([e1[IX], e2[IX]], [e1[IY], e2[IY]], [e1[IZ], e2[IZ]], \ color='blue') jns = ipv.scatter(jns_ends[:,IX], jns_ends[:,IY], jns_ends[:,IZ], \ size=0.85, marker='sphere', color='red') ipv.pylab.style.axes_off() ipv.pylab.style.box_off() ipv.save(seg_name + '_skel.html')
def test_view(): ipv.figure() az0, el0, r0 = ipv.view() ipv.view(azimuth=az0 + 42) az, el, r = ipv.view() assert az == pytest.approx(az0 + 42) assert el == el0 assert r == r0 ipv.view(elevation=el0 + 42) az, el, r = ipv.view() assert az == pytest.approx(az0 + 42) assert el == pytest.approx(el0 + 42) assert r == r0 ipv.view(distance=r0 + 42) az, el, r = ipv.view() assert az == pytest.approx(az0 + 42) assert el == pytest.approx(el0 + 42) assert r == pytest.approx(r0 + 42) ipv.view(42, 42, 42) az, el, r = ipv.view() assert az == pytest.approx(42) assert el == pytest.approx(42) assert r == pytest.approx(42)
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 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 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 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 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 test_movie(): fractions = [] def f(fig, i, fraction): fractions.append(fraction) ipv.figure() with shim_savefig(): ipv.movie(function=f, frames=2) assert fractions == [0, 0.5]
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 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 ipv_plot_data(data, colorStack='purple', holdOnFlag=False, markerSize=.25): if not holdOnFlag: ipv.figure( width=600, height=600 ) # create a new figure by default, otherwise append to existing ipv.scatter(data[:, 0], data[:, 1], data[:, 2], size=markerSize, marker='sphere', color=colorStack) if not holdOnFlag: ipv.show()
def SaveMeshAsHTML(cell_dir, stl_id, mesh_dir='./'): in_mesh = GetMesh(cell_dir, stl_id) IX, IY, IZ = 2, 1, 0 x, y, z = in_mesh.vertices[:,IX].astype(float), \ in_mesh.vertices[:,IY].astype(float), \ in_mesh.vertices[:,IZ].astype(float) triangles = in_mesh.faces ipv.figure() mesh = ipv.plot_trisurf(x, y, z, triangles=triangles, color='skyblue') ipv.pylab.style.axes_off() ipv.pylab.style.box_off() ipv.save(os.path.join(mesh_dir, 'mesh' + str(stl_id) + '.html'))
def __enter__(self): """Set this figure as the current in the pylab API. Example: >>> f1 = ipv.figure(1) >>> f2 = ipv.figure(2) >>> with f1: >>> ipv.scatter(x, y, z) >>> assert ipv.gcf() is f2 """ self._previous_figure = ipv.gcf() ipv.figure(self)
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()
def initalize_hpo(nTimesteps, nParticles, nWorkers, paramRanges, nParameters=3, plotFlag=True): accuracies = np.zeros((nTimesteps, nParticles)) bestParticleIndex = {} globalBestParticleParams = np.zeros((nTimesteps, 1, nParameters)) particles = np.zeros((nTimesteps, nParticles, nParameters)) velocities = np.zeros((nTimesteps, nParticles, nParameters)) particleBoostingRounds = np.zeros((nTimesteps, nParticles)) # initial velocity is one velocities[0, :, :] = np.ones((nParticles, nParameters)) * .25 # randomly initialize particle colors particleColors = np.random.uniform(size=(1, nParticles, 3)) # best initialized to middle [ fictional particle ] -- is this necessary bestParticleIndex[0] = -1 # grid initialize particles x = np.linspace(paramRanges[0][1], paramRanges[0][2], nWorkers) y = np.linspace(paramRanges[1][1], paramRanges[1][2], nWorkers) z = np.linspace(paramRanges[2][1], paramRanges[2][2], nWorkers) xx, yy, zz = np.meshgrid(x, y, z, indexing='xy') xS = xx.reshape(1, -1)[0] yS = yy.reshape(1, -1)[0] zS = zz.reshape(1, -1)[0] # clip middle particles particles[0, :, 0] = np.hstack([xS[-nWorkers**2:], xS[:nWorkers**2]]) particles[0, :, 1] = np.hstack([yS[-nWorkers**2:], yS[:nWorkers**2]]) particles[0, :, 2] = np.hstack([zS[-nWorkers**2:], zS[:nWorkers**2]]) if plotFlag: ipv.figure() ipv.scatter(particles[0, :, 0], particles[0, :, 1], particles[0, :, 2], marker='sphere', color=particleColors) 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() return particles, velocities, accuracies, bestParticleIndex, globalBestParticleParams, particleBoostingRounds, particleColors
def show_syntehtic_plant(vertices, faces, meta_data=None, size=0.5, color='green', width=500, height=500): ipyvolume.figure(width=width, height=height) ipyvolume.view(0, 90) ipyvolume.plot_trisurf(vertices[:, 0], vertices[:, 1], vertices[:, 2], triangles=faces, color=color) voxels_position = vertices if meta_data is not None: ranks = meta_data['leaf_order'] polylines = { n: list(map(numpy.array, list(zip(*meta_data['leaf_polylines'][i])))) for i, n in enumerate(ranks) } voxels = set() for leaf_order in polylines: x, y, z, r = polylines[leaf_order] polyline = numpy.array(list(zip(x, y, z))) * 10 - \ numpy.array([0, 0, 750]) plot_voxel(polyline, size=size, color="red") voxels = voxels.union(set(map(tuple, list(polyline)))) voxels = voxels.union(set(map(tuple, list(voxels_position)))) voxels_position = numpy.array(list(voxels), dtype=numpy.int) 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 test_style(): f = ipv.figure() ipv.style.use('nobox') assert f.style['box']['visible'] == False ipv.style.use(['nobox', {'box': {'visible': True}}]) assert f.style['box']['visible'] == True ipv.style.use({'box': {'visible': False}}) assert f.style['box']['visible'] == False ipv.style.use({'axes': {'visible': False}}) assert f.style['axes']['visible'] == False ipv.style.axes_off() assert f.style['axes']['visible'] == False ipv.style.axes_on() assert f.style['axes']['visible'] == True ipv.style.box_off() assert f.style['box']['visible'] == False ipv.style.box_on() assert f.style['box']['visible'] == True ipv.style.set_style_light() assert f.style['background-color'] == 'white' ipv.style.box_off() assert f.style['box']['visible'] == False assert f.style['background-color'] == 'white' # keep old style settings
def test_context(): f1 = ipv.figure(1) f2 = ipv.figure(2) f3 = ipv.figure(2) assert ipv.gcf() is f3 with f2: assert ipv.gcf() is f2 assert ipv.gcf() is f3 # test nested with f2: assert ipv.gcf() is f2 with f1: assert ipv.gcf() is f1 assert ipv.gcf() is f2 assert ipv.gcf() is f3
def test_view(): fig = ipv.figure() az0, el0, r0 = ipv.view() ipv.view(azimuth=az0 + 42) az, el, r = ipv.view() assert az == az0 + 42 assert el == el0 assert r == r0 ipv.view(elevation=el0 + 42) az, el, r = ipv.view() assert az == az0 + 42 assert el == el0 + 42 assert r == r0 ipv.view(distance=r0 + 42) az, el, r = ipv.view() assert az == az0 + 42 assert el == el0 + 42 assert r == r0 + 42 ipv.view(42, 42, 42) az, el, r = ipv.view() assert az == 42 assert el == 42 assert r == 42
def test_context(): f1 = ipv.figure(1) f2 = ipv.figure(2) f3 = ipv.figure(2) assert ipv.gcf() is f3 with f2: # pylint: disable=not-context-manager assert ipv.gcf() is f2 assert ipv.gcf() is f3 # test nested with f2: # pylint: disable=not-context-manager assert ipv.gcf() is f2 with f1: # pylint: disable=not-context-manager assert ipv.gcf() is f1 assert ipv.gcf() is f2 assert ipv.gcf() is f3