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_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 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_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 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 plot_geometry(self, plot_e_r=True, plot_e_phi=True, plot_e_theta=True, plot_bezier=True, bezier_order=3): """Generates 3D ipyvolume plot """ fig = ipv.figure() scatter = ipv.scatter(self.center[:, 0], self.center[:, 1], self.center[:, 2], color='#ff0000', size=5) if plot_e_r: self._my_ipv_vectorplot(np.repeat(self.center, len(self.points), axis=0), self.e_r, length=1, N=1000, size=0.2, color='#00ff00') if plot_e_theta: self._my_ipv_vectorplot(self.points, self.e_theta, length=0.05, N=100, size=0.2, color='#ff0000') if plot_e_phi: self._my_ipv_vectorplot(self.points, self.e_phi, length=0.05, N=100, size=0.2, color='#ff0000') if plot_bezier: assert 1 <= bezier_order <= 3 p = self._arrange_bezier_points(self.bezier_points, order=bezier_order) self._plot_bezier_curves(p, N=100, size=0.5, color='#ff00ff') scatter = ipv.scatter(self.points[:, 0], self.points[:, 1], self.points[:, 2], color='#0000bb', size=1) ipv.xlim(0, 1) ipv.ylim(0, 1) ipv.zlim(0, 1) return fig
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 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 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 show_voxel_grid(voxel_grid, color='green', size=2, width=500, height=500): ipyvolume.figure(width=width, height=height, controls=True, lighting=True) plot_voxel(voxel_grid.voxels_position, size=size, color=color) x_min = voxel_grid.voxels_position[:, 0].min() x_max = voxel_grid.voxels_position[:, 0].max() y_min = voxel_grid.voxels_position[:, 1].min() y_max = voxel_grid.voxels_position[:, 1].max() z_min = voxel_grid.voxels_position[:, 2].min() z_max = voxel_grid.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.view(0, 90) ipyvolume.show()
def __init__(self, df: pd.DataFrame): self.figure = ipv.figure(animation=0., animation_exponent=0, width=800, height=800) #self.figure.camera_control = 'orbit' self.lpp = lpp = 1 x_min = np.min([-lpp, df['x0'].min()]) x_max = np.max([lpp, df['x0'].max()]) y_min = np.min([-lpp, df['y0'].min()]) y_max = np.max([lpp, df['y0'].max()]) z_min = np.min([-lpp, df['z0'].min()]) z_max = np.max([lpp, df['z0'].max()]) ipv.xlim(x_min, x_max) ipv.ylim(y_min, y_max) ipv.zlim(z_min, x_max) ipv.style.box_off() self.track = ipv.pylab.plot(df['x0'].values, df['y0'].values, df['z0'].values) self.load_ship_geometry() self.port = ipv.plot_mesh(self.X, self.Y_port, self.Z, wireframe=False) self.stbd = ipv.plot_mesh(self.X, self.Y_starboard, self.Z, wireframe=False) ipv.pylab.view(azimuth=180, elevation=60, distance=1) ipv.show() self.df = df min = df.index[0] max = df.index[-1] step = (max - min) / 100 self.ui = widgets.interact(self.update, t=widgets.FloatSlider(value=0, min=min, max=max, step=step))
def set_axes_lims(points, axeslim='auto', aspect_ratio_preserve=True): x = points[:, 0] y = points[:, 1] z = points[:, 2] if axeslim == 'auto': if aspect_ratio_preserve: bounds = np.array([(v.min(), v.max()) for v in [x, y, z]]).T widths = bounds[1] - bounds[0] max_width = widths.max() pads = (max_width - widths) / 2 pads = np.vstack([-pads, pads]) axeslim = (bounds + pads).T ipv.xlim(axeslim[0][0], axeslim[0][1]) ipv.ylim(axeslim[1][0], axeslim[1][1]) ipv.zlim(axeslim[2][0], axeslim[2][1]) else: ipv.xlim(x.min(), x.max()) ipv.ylim(y.min(), y.max()) ipv.zlim(z.min(), z.max()) else: ipv.xlim(-axeslim, axeslim) ipv.ylim(-axeslim, axeslim) ipv.zlim(-axeslim, axeslim)
def show_skeleton(voxel_skeleton, size=2, with_voxel=True, voxels_color='green', polyline_color='red', width=500, height=500): ipyvolume.figure(width=width, height=height) ipyvolume.view(0, 90) if with_voxel: voxels_position = voxel_skeleton.voxels_position() plot_voxel(voxels_position, size=size / 2, color=voxels_color) voxels_position = voxel_skeleton.voxels_position_polyline() plot_voxel(voxels_position, size=size, color=polyline_color) for vs in voxel_skeleton.segments: for color, index in [("blue", 0), ("red", -1)]: plot_voxel(numpy.array([vs.polyline[index]]), size=size * 2, marker="sphere", color=color) 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 hpo_animate(particles, particleSizes, particleColors, paramRanges, nTimesteps=1): nParticles = particles.shape[1] colorStack = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .9 colorStackLines = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .5 for iTimestep in range(nTimesteps): colorStack[iTimestep, :, 0:3] = numpy.matlib.repmat(particleColors[0, :, :], nTimesteps, 1) colorStackLines[iTimestep, :, 0:3] = numpy.matlib.repmat(particleColors[0, :, :], nTimesteps, 1) colorStackLines[iTimestep, :, 3] = .6 # alpha ipv.figure() pplot = ipv.scatter(particles[0:nTimesteps, :, 0], particles[0:nTimesteps, :, 1], particles[0:nTimesteps, :, 2], marker='sphere', size=particleSizes, color=colorStack[:, :, :]) for iParticle in range(nParticles): plines = ipv.plot(particles[0:nTimesteps, iParticle, 0], particles[0:nTimesteps, iParticle, 1], particles[0:nTimesteps, iParticle, 2], color=colorStackLines[:, iParticle, :]) ipv.animation_control([pplot], interval=600) ipv.xlim(paramRanges[0][1] - .5, paramRanges[0][2] + .5) ipv.ylim(paramRanges[1][1] - .1, paramRanges[1][2] + .1) ipv.zlim(paramRanges[2][1] - .1, paramRanges[2][2] + .1) ipv.show()
def graph_skeleton_and_mesh(main_mesh_verts=[], main_mesh_faces=[], unique_skeleton_verts_final=[], edges_final=[], edge_coordinates=[], other_meshes=[], other_meshes_colors=[], main_mesh_face_coloring=[], buffer=0, axis_box_off=True, html_path=""): """ Graph the final result: """ ipv.figure(figsize=(15, 15)) if (len(unique_skeleton_verts_final) > 0 and len(edges_final) > 0) or (len(edge_coordinates) > 0): if (len(edge_coordinates) > 0): unique_skeleton_verts_final, edges_final = convert_skeleton_to_nodes_edges( edge_coordinates) mesh2 = ipv.plot_trisurf(unique_skeleton_verts_final[:, 0], unique_skeleton_verts_final[:, 1], unique_skeleton_verts_final[:, 2], lines=edges_final, color='blue') mesh2.color = [0, 0., 1, 1] mesh2.material.transparent = True if len(main_mesh_verts) > 0 and len(main_mesh_faces) > 0: main_mesh = trimesh.Trimesh(vertices=main_mesh_verts, faces=main_mesh_faces) mesh3 = ipv.plot_trisurf(main_mesh.vertices[:, 0], main_mesh.vertices[:, 1], main_mesh.vertices[:, 2], triangles=main_mesh.faces) mesh3.color = [0., 1., 0., 0.2] mesh3.material.transparent = True volume_max = np.max(main_mesh.vertices, axis=0) volume_min = np.min(main_mesh.vertices, axis=0) ranges = volume_max - volume_min index = [0, 1, 2] max_index = np.argmax(ranges) min_limits = [0, 0, 0] max_limits = [0, 0, 0] for i in index: if i == max_index: min_limits[i] = volume_min[i] - buffer max_limits[i] = volume_max[i] + buffer continue else: difference = ranges[max_index] - ranges[i] min_limits[i] = volume_min[i] - difference / 2 - buffer max_limits[i] = volume_max[i] + difference / 2 + buffer #ipv.xyzlim(-2, 2) ipv.xlim(min_limits[0], max_limits[0]) ipv.ylim(min_limits[1], max_limits[1]) ipv.zlim(min_limits[2], max_limits[2]) for curr_mesh, curr_color in zip(other_meshes, other_meshes_colors): plot_ipv_mesh(curr_mesh, color=curr_color) #will go through and color the faces of the main mesh if any sent for face_array, face_color in main_mesh_face_coloring: curr_mesh = main_mesh.submesh([face_array], append=True) plot_ipv_mesh(curr_mesh, face_color) ipv.style.set_style_light() if axis_box_off: ipv.style.axes_off() ipv.style.box_off() else: ipv.style.axes_on() ipv.style.box_on() ipv.show() if html_path != "": print(f"printing to html : {html_path}") ipv.pylab.save(html_path)
def viz_swarm(swarm, paramLabels=False): swarmDF, particleHistory = viz_prep(swarm) particleHistoryCopy = copy.deepcopy(particleHistory) nParticles = swarm.nParticles nAnimationFrames = list( swarmDF['nEvals'])[0] # max( sortedBarHeightsDF['nEvals'] ) particleXYZ = np.zeros((nAnimationFrames, nParticles, 3)) lastKnownLocation = {} # TODO: bestIterationNTrees # particleSizes[ iFrame, iParticle ] = particleHistoryCopy[iParticle]['bestIterationNTrees'].pop(0).copy() for iFrame in range(nAnimationFrames): for iParticle in range(nParticles): if iParticle in particleHistoryCopy.keys(): # particle exists in the particleHistory and it has parameters for the current frame if len(particleHistoryCopy[iParticle]): particleXYZ[iFrame, iParticle, :] = particleHistoryCopy[ iParticle].pop(0).copy() lastKnownLocation[iParticle] = particleXYZ[ iFrame, iParticle, :].copy() else: # particle exists but it's params have all been popped off -- use its last known location if iParticle in lastKnownLocation.keys(): particleXYZ[iFrame, iParticle, :] = lastKnownLocation[ iParticle].copy() else: # particle does not exist in the particleHistory if iParticle in lastKnownLocation.keys(): # particle has no params in current frame, attempting to use last known location particleXYZ[ iFrame, iParticle, :] = lastKnownLocation[iParticle].copy() else: print('particle never ran should we even display it') assert (False) # using initial params #particleXYZ[iFrame, iParticle, : ] = initialParticleParams[iParticle].copy() #lastKnownLocation[iParticle] = particleXYZ[iFrame, iParticle, : ].copy() ipvFig = ipv.figure(width=ipvPlotWidth, height=ipvPlotHeight) scatterPlots = ipv.scatter(particleXYZ[:, :, 0], particleXYZ[:, :, 1], particleXYZ[:, :, 2], marker='sphere', size=5, color=swarm.particleColorStack) xyzLabelsButton = widgets.Button(description="x, y, z labels") paramNamesLabelsButton = widgets.Button(description="parameter labels") ipv.animation_control([scatterPlots], interval=400) ipv.xlim(swarm.paramRanges[0][1] - .5, swarm.paramRanges[0][2] + .5) ipv.ylim(swarm.paramRanges[1][1] - .1, swarm.paramRanges[1][2] + .1) ipv.zlim(swarm.paramRanges[2][1] - .1, swarm.paramRanges[2][2] + .1) container = ipv.gcc() container.layout.align_items = 'center' comboBox = append_label_buttons(swarm, ipvFig, container) display(comboBox)
def initialize_particle_swarm(nTimesteps, nParticles, paramRanges, nParameters=3, randomSeed=None, plotFlag=True): if randomSeed is not None: np.random.seed(randomSeed) 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)) * .15 # 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 nDivisions = int(np.sqrt(nParticles)) # grid initialize particles x = np.linspace(paramRanges[0][1], paramRanges[0][2], nDivisions) y = np.linspace(paramRanges[1][1], paramRanges[1][2], nDivisions) z = np.linspace(paramRanges[2][1], paramRanges[2][2], nDivisions) xx, yy, zz = np.meshgrid(x, y, z, indexing='xy') xyz = np.dstack( [xx.reshape(1, -1)[0], yy.reshape(1, -1)[0], zz.reshape(1, -1)[0]])[0] # only retain particles along parameter boundaries boundaryPointIndexes = [] for iPoint in range(xyz.shape[0]): if ( xyz[iPoint,0] == paramRanges[0][1] or xyz[iPoint,0] == paramRanges[0][2]) or \ ( xyz[iPoint,1] == paramRanges[1][1] or xyz[iPoint,1] == paramRanges[1][2]) or \ ( xyz[iPoint,2] == paramRanges[2][1] or xyz[iPoint,2] == paramRanges[2][2]): boundaryPointIndexes += [iPoint] else: pass stepSize = np.max((1, len(boundaryPointIndexes) // nParticles)) # randomly select nParticles from the boundary points boundaryPoints = np.random.permutation(boundaryPointIndexes)[0:nParticles] # clip middle particles particles[0, :, 0] = xyz[boundaryPoints, 0] particles[0, :, 1] = xyz[boundaryPoints, 1] particles[0, :, 2] = xyz[boundaryPoints, 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 reset_zoom(*ignore): with self.figure: if self.last_shape is not None: ipv.xlim(0, self.last_shape[0]) ipv.ylim(0, self.last_shape[1]) ipv.zlim(0, self.last_shape[2])
def scatter_normals( points, normals, labels=None, labels_gt=None, with_normals_errors_only=False, width=800, height=600, cmap=cm.RdBu, cmap_normals=cm.cool, aspect_ratio_preserve=True, axeslim='auto', reorder_colors=True, point_size_value=0.2, vector_size_value=1.0, title=None, ): assert len(points) == len( normals), "Length incorrect. These are not normals of points, may be." points = points.astype(np.float32) normals = normals.astype(np.float32) x = points[:, 0] y = points[:, 1] z = points[:, 2] u = normals[:, 0] v = normals[:, 1] w = normals[:, 2] if labels is None: labels = np.ones(shape=len(points), dtype=np.int) # draw ipv.figure(width=width, height=height) if axeslim == 'auto': if aspect_ratio_preserve: bounds = np.array([(v.min(), v.max()) for v in [x, y, z]]).T widths = bounds[1] - bounds[0] max_width = widths.max() pads = (max_width - widths) / 2 pads = np.vstack([-pads, pads]) axeslim = (bounds + pads).T ipv.xlim(axeslim[0][0], axeslim[0][1]) ipv.ylim(axeslim[1][0], axeslim[1][1]) ipv.zlim(axeslim[2][0], axeslim[2][1]) else: ipv.xlim(x.min(), x.max()) ipv.ylim(y.min(), y.max()) ipv.zlim(z.min(), z.max()) else: ipv.xlim(-axeslim, axeslim) ipv.ylim(-axeslim, axeslim) ipv.zlim(-axeslim, axeslim) # calc point colors colors_seg = cmap(np.linspace(0, 1, labels.max() + 1)) if reorder_colors: colors_seg = reorder_contrast(colors_seg) colors = np.array([colors_seg[label - 1][:3] for label in labels]) sc = ipv.scatter(x, y, z, size=point_size_value, marker="sphere", color=colors) colors_seg = cmap_normals(np.linspace(0, 1, labels.max() + 1)) if reorder_colors: colors_seg = reorder_contrast(colors_seg) colors_normals = np.array([colors_seg[label - 1][:3] for label in labels]) if labels_gt is None: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) else: if not with_normals_errors_only: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) # accuracy assert len(labels_gt) == len(labels) accuracy = (labels_gt == labels).sum() / len(labels) print("Accuracy: {}".format(accuracy)) # draw errors points_error = points[(labels_gt != labels)] x = points_error[:, 0] y = points_error[:, 1] z = points_error[:, 2] # normals with errors normals_error = normals[(labels_gt != labels)] u = normals_error[:, 0] v = normals_error[:, 1] w = normals_error[:, 2] sc2 = ipv.scatter(x, y, z, size=point_size_value, marker="sphere", color='red') point_size2 = FloatSlider(min=0, max=2, step=0.02, description='Error point size') jslink((sc2, 'size'), (point_size2, 'value')) if with_normals_errors_only: quiver = ipv.quiver(x, y, z, u, v, w, size=vector_size_value, marker="arrow", color=colors_normals) point_size = FloatSlider(min=0, max=2, step=0.1, description='Point size') vector_size = FloatSlider(min=0, max=5, step=0.1, description='Vector size') jslink((sc, 'size'), (point_size, 'value')) jslink((quiver, 'size'), (vector_size, 'value')) if labels_gt is not None: widget_list = [ipv.gcc(), point_size, point_size2, vector_size] else: widget_list = [ipv.gcc(), point_size, vector_size] if title is not None: widget_list = [Label(title)] + widget_list return display_widgets(widget_list)