def plot_subgraph_old(vertices, edges, vertex_properties, subgraph_no): _, subgraph_edges = get_subgraph(edges, subgraph_no) begin_verts = vertices[subgraph_edges[:, 0], :] end_verts = vertices[subgraph_edges[:, 1], :] vector_components = end_verts - begin_verts distances = np.sqrt(np.sum(np.square(end_verts - begin_verts), axis=1)) vertex_mask = np.isin(np.arange(vertices.shape[0]), subgraph_edges) mlab.points3d(vertices[vertex_mask, 0], vertices[vertex_mask, 1], vertices[vertex_mask, 2], vertex_properties[vertex_mask, 1], scale_mode='scalar', scale_factor=1, opacity=0.1) mlab.quiver3d(begin_verts[:, 0], begin_verts[:, 1], begin_verts[:, 2], vector_components[:, 0], vector_components[:, 1], vector_components[:, 2], scalars=distances, mode="2ddash", opacity=1., scale_mode="scalar", scale_factor=1, color=(1, 1, 1))
def showPath(self): px, py, pz, dirx,diry,dirz = [],[],[],[],[],[] print self.path print len(self.z) for node in self.path: px.append(node[0]) py.append(node[1]) pz.append(self.z[node[0]][node[1]]) dirx.append(cos(radians(node[2]))) diry.append(sin(radians(node[2]))) dirz.append(0) px = np.array(px) py = np.array(py) pz = np.array(pz) dirx = np.array(dirx) diry = np.array(diry) dirz = np.array(dirz) mlab.quiver3d(self.x,self.y,self.z,self.gx,self.gy,self.Gt,color=(1,0,0),scale_factor=1) mlab.quiver3d(px,py,pz,dirx,diry,dirz,color=(0,0,0),scale_factor=1) mlab.surf(self.x, self.y, self.z, representation='wireframe') mlab.show()
def surface_orientation(surface, normals="triangles", name=None): """ """ fig = mlab.figure(figure=name, fgcolor=(0.5, 0.5, 0.5)) surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0], surface.vertices[:, 1], surface.vertices[:, 2], surface.triangles, color=(0.7, 0.67, 0.67), figure=fig) if normals == "triangles": surf_orient = mlab.quiver3d(surface.triangle_centres[:, 0], surface.triangle_centres[:, 1], surface.triangle_centres[:, 2], surface.triangle_normals[:, 0], surface.triangle_normals[:, 1], surface.triangle_normals[:, 2]) elif normals == "vertices": surf_orient = mlab.quiver3d(surface.vertices[:, 0], surface.vertices[:, 1], surface.vertices[:, 2], surface.vertex_normals[:, 0], surface.vertex_normals[:, 1], surface.vertex_normals[:, 2]) else: LOG.error("normals must be either 'triangles' or 'vertices'") return (surf_mesh, surf_orient)
def render(self, colour='r', line_width=2, marker_style='2darrow', marker_resolution=8, marker_size=None, step=None, alpha=1.0): from mayavi import mlab marker_size = _parse_marker_size(marker_size, self.points) colour = _parse_colour(colour) mlab.quiver3d(self.points[:, 0], self.points[:, 1], self.points[:, 2], self.vectors[:, 0], self.vectors[:, 1], self.vectors[:, 2], figure=self.figure, color=colour, mask_points=step, line_width=line_width, mode=marker_style, resolution=marker_resolution, opacity=alpha, scale_factor=marker_size) return self
def draw_path(self, path): points, vectors, processes = [], [], [] for k in range(1, len(path)): points.append(path[k][0]) vectors.append(path[k - 1][0] - path[k][0]) processes.append(path[k][2]) points, vectors = np.array(points), np.array(vectors) processes = np.array(processes) pnts, vctrs = points[processes], vectors[processes] mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=(0.3, 0.5, 0.7), mode='2ddash', scale_factor=1, line_width=5.0) #mode='2ddash', 'arrow', 'cylinder' pnts = points[np.bitwise_not(processes)] vctrs = vectors[np.bitwise_not(processes)] mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=(0.8, 0.6, 0.2), mode='2ddash', scale_factor=1, line_width=2.0)
def test_surface_normals(plot=False, skip_asserts=False, write_reference=False): "Test the surface normals of a horseshoe mesh" sim = openmodes.Simulation() mesh = sim.load_mesh(osp.join(mesh_dir, 'horseshoe_rect.msh')) part = sim.place_part(mesh) basis = sim.basis_container[part] r, rho = basis.integration_points(mesh.nodes, triangle_centres) normals = mesh.surface_normals r = r.reshape((-1, 3)) if write_reference: write_2d_real(osp.join(reference_dir, 'surface_r.txt'), r) write_2d_real(osp.join(reference_dir, 'surface_normals.txt'), normals) r_ref = read_2d_real(osp.join(reference_dir, 'surface_r.txt')) normals_ref = read_2d_real(osp.join(reference_dir, 'surface_normals.txt')) if not skip_asserts: assert_allclose(r, r_ref) assert_allclose(normals, normals_ref) if plot: from mayavi import mlab mlab.figure() mlab.quiver3d(r[:, 0], r[:, 1], r[:, 2], normals[:, 0], normals[:, 1], normals[:, 2], mode='cone') mlab.view(distance='auto') mlab.show()
def render(self, scale_factor=1.0, text_scale=1.0, **kwargs): import mayavi.mlab as mlab # disabling the rendering greatly speeds up this for loop self.figure.scene.disable_render = True positions = [] for label in self.lmark_group: p = self.lmark_group[label] for i, p in enumerate(p.points): positions.append(p) l = '%s_%d' % (label, i) # TODO: This is due to a bug in mayavi that won't allow # rendering text to an empty figure mlab.points3d(p[0], p[1], p[2], scale_factor=scale_factor) mlab.text3d(p[0], p[1], p[2], l, figure=self.figure, scale=text_scale) positions = np.array(positions) os = np.zeros_like(positions) os[:, 2] = 1 mlab.quiver3d(positions[:, 0], positions[:, 1], positions[:, 2], os[:, 0], os[:, 1], os[:, 2], figure=self.figure) self.figure.scene.disable_render = False # Ensure everything fits inside the camera viewport mlab.get_engine().current_scene.scene.reset_zoom() return self
def plot_points_norms_3d(positions: np.ndarray, normals: np.ndarray, num_points: int = 5000, size: Tuple[int, int] = None): """ 3D Quiver of points with given normal vectors """ import mayavi.mlab as mlab if size is None: size = (768, 768) mlab.figure(bgcolor=(1, 1, 1), size=size) skip_rate = max(1, positions.shape[0] // num_points) mlab.points3d( positions[::skip_rate, 0], positions[::skip_rate, 1], positions[::skip_rate, 2], color=(31/255.0, 119/255.0, 180/255.0), scale_factor=1e-3) mlab.quiver3d( positions[::skip_rate, 0], positions[::skip_rate, 1], positions[::skip_rate, 2], normals[::skip_rate, 0], normals[::skip_rate, 1], normals[::skip_rate, 2], color=(0, 0, 0), scale_factor=1e-3) bounding_box_size = np.linalg.norm(np.max(positions, 0)-np.min(positions, 0), ord=2) mlab.view(azimuth=15.0, elevation=150.0, distance=1.5*0.8*bounding_box_size, focalpoint=np.mean(positions, 0) * np.array([1., 2/2.2, 1.0]), roll=0) mlab.show()
def quiver_gradient(self): """ Plot the gradient vector in current window. This requires to cast the contravariant vector components into Cartesian components first. """ TV = VectorTensorProductSpace(self.T) du = project(grad(self.u_hat), TV).backward( uniform=True).real # Contravariant components (real part) b = self.T.coors.b ui, vi = self.T.local_mesh(broadcast=True, uniform=True) b1 = np.array(sp.lambdify(psi, b[0])(ui, vi)) b2 = sp.lambdify(psi, b[1])(ui, vi) b2[2] = np.zeros(ui.shape) # b2[2] is 0, so need to broadcast b2 = np.array(b2) df = du[0] * b1 + du[1] * b2 # Cartesian components df = np.concatenate([df, df[:, :, 0][:, :, None]], axis=2) # wrap periodic X = self.T.local_curvilinear_mesh(uniform=True) X[0] = np.hstack([X[0], X[0][:, 0][:, None]]) X[1] = np.hstack([X[1], X[1][:, 0][:, None]]) X[2] = np.hstack([X[2], X[2][:, 0][:, None]]) x, y, z = X mlab.quiver3d(x[::2, ::2], y[::2, ::2], z[::2, ::2], df[0, ::2, ::2], df[1, ::2, ::2], df[2, ::2, ::2], color=(0, 0, 0), scale_factor=5, mode='2darrow') show()
def plot_channel(self,fn_hist,fn_corrvec,fn_arrows): list_channel = self.list_channel import matplotlib.pyplot as plt # plot vecs plt.figure() #vecs = np.array((3,len(list_channel))) for i in range(3): vecs = [chan.vec[i] for chan in list_channel] plt.hist(vecs,bins=100) plt.savefig(fn_hist) # plot corr vecs plt.figure() v0 = [chan.vec[0] for chan in list_channel] v1 = [chan.vec[1] for chan in list_channel] v2 = [chan.vec[2] for chan in list_channel] plt.plot(v0,v1,"o") plt.plot(v0,v2,"o") plt.plot(v1,v2,"o") plt.savefig(fn_corrvec) # cluster import matplotlib.pyplot as plt import mayavi.mlab as mlab #from mlab import quiver3d mlab.options.backend = 'envisage' # one way to save visualization #f = mlab.figure() mlab.figure() x = [np.zeros(v.shape) for v in v0] mlab.quiver3d(x,x,x,v0,v1,v2) mlab.savefig(fn_arrows)
def plot_pos_ori(pos, ori, color=(0., 0., 0.)): mlab.points3d(pos[:, 0], pos[:, 1], pos[:, 2], scale_factor=0.005, color=color) mlab.quiver3d(pos[:, 0], pos[:, 1], pos[:, 2], ori[:, 0], ori[:, 1], ori[:, 2], scale_factor=0.03, color=color)
def showPc(s, figm=None, showNormals=False, algo='sobel', color=(1, 0, 0)): import mayavi.mlab as mlab s.getPc() if figm is None: figm = mlab.figure(bgcolor=(1, 1, 1)) mlab.points3d(s.pc[s.mask, 0], s.pc[s.mask, 1], s.pc[s.mask, 2], s.gray[s.mask], colormap='gray', scale_factor=0.01, figure=figm, mode='point', mask_points=1) if showNormals: s.getNormals(algo) mlab.quiver3d(s.pc[s.mask, 0], s.pc[s.mask, 1], s.pc[s.mask, 2], s.n[s.mask, 0], s.n[s.mask, 1], s.n[s.mask, 2], figure=figm, mode='2darrow', line_width=1.0, color=color, scale_factor=0.1, mask_points=50) return figm
def plotvfonsph3D(theta_rad, phi_rad, E_th, E_ph, freq=0.0, vcoord='sph', projection='equirectangular'): PLOT3DTYPE = "quiver" (x, y, z) = sph2crtISO(theta_rad, phi_rad) from mayavi import mlab mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) mlab.clf() if PLOT3DTYPE == "MESH_RADIAL" : r_Et = numpy.abs(E_th) r_Etmx = numpy.amax(r_Et) mlab.mesh(r_Et*(x)-1*r_Etmx, r_Et*y, r_Et*z, scalars=r_Et) r_Ep = numpy.abs(E_ph) r_Epmx = numpy.amax(r_Ep) mlab.mesh(r_Ep*(x)+1*r_Epmx , r_Ep*y, r_Ep*z, scalars=r_Ep) elif PLOT3DTYPE == "quiver": ##Implement quiver plot s2cmat = getSph2CartTransfMatT(numpy.array([x,y,z])) E_r = numpy.zeros(E_th.shape) E_fldsph = numpy.rollaxis(numpy.array([E_r, E_ph, E_th]), 0, 3)[...,numpy.newaxis] E_fldcrt = numpy.rollaxis(numpy.matmul(s2cmat, E_fldsph).squeeze(), 2, 0) #print E_fldcrt.shape mlab.quiver3d(x+1.5, y, z, numpy.real(E_fldcrt[0]), numpy.real(E_fldcrt[1]), numpy.real(E_fldcrt[2])) mlab.quiver3d(x-1.5, y, z, numpy.imag(E_fldcrt[0]), numpy.imag(E_fldcrt[1]), numpy.imag(E_fldcrt[2])) mlab.show()
def __init__(self, system): """Constructor. **Arguments** :system: instance of espressomd.System """ self.system = system # objects drawn self.points = mlab.quiver3d([],[],[], [],[],[], scalars=[], mode="sphere", scale_factor=1, name="Particles") self.points.glyph.color_mode = 'color_by_scalar' self.points.glyph.glyph_source.glyph_source.center = [0, 0, 0] self.box = mlab.outline(extent=(0,0,0,0,0,0), color=(1,1,1), name="Box") self.arrows = mlab.quiver3d([],[],[], [],[],[], scalars=[], mode="2ddash", scale_factor=1, name="Bonds") self.arrows.glyph.color_mode = 'color_by_scalar' # state self.data = None self.last_N = 1 self.last_Nbonds = 1 self.last_boxl = [0,0,0] self.running = False self.last_T = None # GUI window self.gui = GUI() self.timers = [Timer(100, self._draw)]
def plot_pca(pcd, n_neighborhood, point, eigenvectors, eigen_values): fig1 = mlab.figure(bgcolor=(1, 1, 1)) mean_nn = pyreg.functions.get_mean_nn_distance(pcd) pcd_pts = mlab.points3d(pcd.points[:, 0], pcd.points[:, 1], pcd.points[:, 2], color=(0, 0, 1), mode="sphere", figure=fig1, scale_factor=0.25 * mean_nn) neighbors = mlab.points3d(n_neighborhood[:, 0], n_neighborhood[:, 1], n_neighborhood[:, 2], color=(1, 0, 0), mode="sphere", figure=fig1, scale_factor=0.5 * mean_nn) pt = mlab.points3d(point[:, 0], point[:, 1], point[:, 2], color=(0, 0, 0), mode="sphere", figure=fig1, scale_factor=1 * mean_nn) eigenvector1 = mlab.quiver3d(point[:, 0], point[:, 1], point[:, 2], eigenvectors[0, 0], eigenvectors[0, 1], eigenvectors[0, 2], mode="arrow", color=(0, 0, 0), figure=fig1, scale_factor=3 * mean_nn) eigenvector2 = mlab.quiver3d(point[:, 0], point[:, 1], point[:, 2], eigenvectors[1, 0], eigenvectors[1, 1], eigenvectors[1, 2], mode="arrow", color=(0, 1, 0), figure=fig1, scale_factor=3 * mean_nn) eigenvector3 = mlab.quiver3d(point[:, 0], point[:, 1], point[:, 2], eigenvectors[2, 0], eigenvectors[2, 1], eigenvectors[2, 2], mode="arrow", color=(0, 1, 0), figure=fig1, scale_factor=3 * mean_nn) return
def test_quiver3d(): x, y, z = numpy.mgrid[-2:3, -2:3, -2:3] r = numpy.sqrt(x ** 2 + y ** 2 + z ** 4) u = y * numpy.sin(r) / (r + 0.001) v = -x * numpy.sin(r) / (r + 0.001) w = numpy.zeros_like(z) mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=1) mlab.show()
def show_vector_in_mayavi(self, fld, do_show=True, **kwargs): c = self.points from mayavi import mlab mlab.quiver3d(c[0], c[1], c[2], fld[0], fld[1], fld[2], **kwargs) if do_show: mlab.show()
def vector_field(x, y, z, u, v, w, name, constant_color): figure = mlab.figure( name, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1) ) mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=1, figure=figure, color=constant_color)
def plot_normals(self): mayalab.quiver3d(self.vertices[:, 0], self.vertices[:, 1], self.vertices[:, 2], self.vnormals[:, 0], self.vnormals[:, 1], self.vnormals[:, 2], mode='arrow')
def draw_vec(origin, dir, color=(0, 0, 0)): mlab.quiver3d(origin[0], origin[1], origin[2], dir[0], dir[1], dir[2], color=color)
def plot_pc_with_normal(pcs, pcs_n): mayalab.quiver3d(pcs[:, 0], pcs[:, 1], pcs[:, 2], pcs_n[:, 0], pcs_n[:, 1], pcs_n[:, 2], mode='arrow')
def viz_vector_field(position, velocity, vscale=3, scale_factor=7, volumeimg=None, thresh=10, sampling=1, vsampling=1, cmap=None, opacity=None): from mayavi import mlab from skimage import measure from skimage.morphology import binary_dilation, ball import numpy as np if volumeimg is not None: """ Cut the isovolume and restrict display to the thresholded volume of the velocity field. """ mask = volumeimg > thresh mask = binary_dilation(mask, ball(3)) n_z, n_y, n_x = mask.shape pos_int = position.astype(np.int) select_coords = mask[pos_int[:, 2], pos_int[:, 1], pos_int[:, 0]] # restrict the visualization. position = position[select_coords == 1] velocity = velocity[select_coords == 1] verts, faces, _, vals = measure.marching_cubes_lewiner( volumeimg, thresh, spacing=(1, 1, 1), step_size=sampling) world_centre = np.mean(verts, axis=0) # compute the world centre coords. mlab.triangular_mesh(verts[:, 0] - world_centre[0], verts[:, 1] - world_centre[1], verts[:, 2] - world_centre[2], faces, scalars=vals, colormap=cmap, opacity=opacity) else: world_centre = np.mean(position, axis=0) mlab.quiver3d(position[::vsampling, 2] - world_centre[0], position[::vsampling, 1] - world_centre[1], position[::vsampling, 0] - world_centre[2], vscale * velocity[::vsampling, 2], vscale * velocity[::vsampling, 1], vscale * velocity[::sampling, 0], scale_factor=scale_factor, transparent=False) mlab.show() return []
def draw_frame(self, pose, scale=10, label=''): R, t = pose scale = self.scale * scale clr = [RED, GREEN, BLUE] vecs = R[:, 0], R[:, 1], R[:, 2] for k in range(3): mlab.quiver3d(t[0], t[1], t[2], vecs[k][0], vecs[k][1], vecs[k][2], color=clr[k], mode='arrow', scale_factor=scale) mlab.text3d(t[0], t[1], t[2], label, scale=scale/5)
def draw_ground_coords_path_3D(dynamicstuple, solution, figure, actual_capture_point=None, multiplier=10, colorbar=False, predicted_capture_point_color=(1, 1, 0), actual_capture_point_color=(0, 1, 0)): from mayavi import mlab from driftmodel.graphics import lines (turn_1, straight_1, turn_2, straight_2, turn_3, straight_3) = dynamicstuple (x2d, y2d, t, s, arrow_indices, capture_index) = build_spatial_path(dynamicstuple, solution, solution.fish.water_velocity) path = solution.path # reaction_point = path.capture_point # commented 2 lines here replaced by the one below, not deleting until double-checking # predicted_capture_point = solution.to_3D(reaction_point + (solution.fish.water_velocity * (turn_1.duration + straight_1.duration), 0)) predicted_capture_point = solution.predicted_capture_point_3D_groundcoords() x1 = [] y1 = [] z1 = [] x2 = [] y2 = [] z2 = [] arrx = [] arry = [] arrz = [] arru = [] arrv = [] arrw = [] prevsol = [] def ar(x): return multiplier * np.array(x) # multiplier here for difference in units between maneuver model and data (I use 10 to convert modeled cm -> measured mm) cmap = 'RdYlBu' # other options: RdYlBu, cool, spectral max_colorbar_speed = 60.0 cnorm = colors.Normalize(vmin=0.0, vmax=max_colorbar_speed) # scale factor for colors stays in cm/s so the colorbar does too for i in range(len(x2d)): sol = solution.to_3D(np.array((x2d[i], y2d[i]))) if i > 0: x1.append(prevsol[0]) y1.append(prevsol[1]) z1.append(prevsol[2]) x2.append(sol[0]) y2.append(sol[1]) z2.append(sol[2]) if i in arrow_indices: dirvec = ((sol - prevsol) / np.linalg.norm(sol - prevsol)) * 0.01 * solution.fish.fork_length arrx = np.array((prevsol[0])) arry = np.array((prevsol[1])) arrz = np.array((prevsol[2])) arru = np.array((dirvec[0])) arrv = np.array((dirvec[1])) arrw = np.array((dirvec[2])) conecolor = plt.get_cmap(cmap)(cnorm(s[i]))[:3] mlab.quiver3d(ar(arrx), ar(arry), ar(arrz), ar(arru), ar(arrv), ar(arrw), figure=figure, line_width=1, mode='cone', color=conecolor, scale_factor=4.0) prevsol = sol # Note I tried reversing the colormap so blue = slow and red = fast, but then it shows the slow spots as fast and vice versa; this is the only way to not mess that up, it seems. mlab.points3d(ar((predicted_capture_point[0])), ar((predicted_capture_point[1])), ar((predicted_capture_point[2])), figure=figure, color=predicted_capture_point_color, scale_factor=5.0) # previously used 5, going to 10 for grayling demo if actual_capture_point is not None: mlab.points3d(np.array((actual_capture_point[0])), np.array((actual_capture_point[1])), np.array((actual_capture_point[2])), figure=figure, color=actual_capture_point_color, scale_factor=5.0) mlab.plot3d(np.array((multiplier * predicted_capture_point[0], actual_capture_point[0])), np.array((multiplier * predicted_capture_point[1], actual_capture_point[1])), np.array((multiplier * predicted_capture_point[2], actual_capture_point[2])), figure=figure, color=(1, 1, 1), tube_radius=0.7, opacity=0.5) lines(ar(x1), ar(y1), ar(z1), ar(x2), ar(y2), ar(z2), s1=np.array(s[:(len(x2d) - 1)]), figure=figure, line_width=2, colormap='RdYlBu', vmin=0, vmax=max_colorbar_speed, reverse_colormap=False, colorbar=False)
def drawVector(origin, vector, scale=1, color=(1, 0, 0)): mlab.quiver3d(origin[0], origin[1], origin[2], vector[0], vector[1], vector[2], scale_factor=scale, color=color)
def arrow(direction, point): mlab.quiver3d( point[0], point[1], point[2], direction[0], direction[1], direction[2], )
def drawVector(origin,vector,scale=1,color=(1,0,0)): mlab.quiver3d( origin[0], origin[1], origin[2], vector[0], vector[1], vector[2], scale_factor=scale, color=color)
def spatial_tensors(pts0, tensors, cb_title=''): n_pts = len(pts0) x0, y0, z0 = pts0.T u, v, w = tensors.T mlab.figure() mlab.quiver3d(x0, y0, z0, u, v, w, mode="sphere", scale_mode='vector', scale_factor=10, colormap='viridis') mlab.colorbar(title=cb_title, orientation='vertical') mlab.show()
def draw_tools(self, points, frames, scale=10): scale = self.scale * scale vectors = [] for frame in frames: vectors.append(frame[:, 2]) vectors = np.array(vectors) points = points - scale * vectors mlab.quiver3d(points[:, 0], points[:, 1], points[:, 2], vectors[:, 0], vectors[:, 1], vectors[:, 2], color=(0, 0, 1), mode='arrow', scale_factor=scale)
def plot(self, color=None, facevec=None): from mayavi import mlab q = self.vertices.mean(axis=0) * 0 x, y, z = (self.vertices + q / 4).T mlab.triangular_mesh(x, y, z, self.faces, scalars=color) # mlab.triangular_mesh(x, y, z, t, color=(0, 0, 0), representation='wireframe') if facevec is not None: centroids = self.face_centroids() mlab.quiver3d(*np.concatenate([centroids, facevec], axis=1).T) mlab.show()
def test15(self): from numpy import mgrid, sqrt, sin, zeros_like x, y, z = mgrid[-0:3:0.6, -0:3:0.6, 0:3:0.3] r = sqrt(x**2 + y**2 + z**4) u = y * sin(r) / (r + 0.001) v = -x * sin(r) / (r + 0.001) w = zeros_like(r) mlab.quiver3d(x, y, z, u, v, w) mlab.colorbar() mlab.show()
def plot_sample_points(self): self.s_pc, self.s_pc_n = self.sample_points(1000, with_normal=True)[0:2] mayalab.quiver3d(self.s_pc[:, 0], self.s_pc[:, 1], self.s_pc[:, 2], self.s_pc_n[:, 0], self.s_pc_n[:, 1], self.s_pc_n[:, 2], mode='arrow')
def draw_gravVector(M, x1, y1, z1): global fx, fy, fz x0, y0, z0 = 0, 0, 0 r = dist(x0, y0, z0, x1, y1, z1) G = 1 f_g = (G*M)/r vec(x1, y1, z1, x0, y0, z0) vecNorm = vectorMag(ux, uy, uz) fx, fy, fz = f_g*(ux/vecNorm), f_g*(uy/vecNorm), f_g*(uz/vecNorm) mlab.quiver3d(x1, y1, z1, fx, fy, fz, color = (0, 1, 0), line_width = 1, scale_factor= .000000001)
def make_quiver(l, v, mode='arrow', opacity=0.9, scale=1): opacity = l['x'].shape[0] * [opacity] mlab.quiver3d(l['x'], l['y'], l['z'], v['x'], v['y'], v['z'], mode=mode, scale_factor=scale, transparent=True)
def show_quiver(arr, vct, scale=1., color=None): m, v = arr.T, vct.T mlab.quiver3d(m[0], m[1], m[2], v[0], v[1], v[2], line_width=1, scale_factor=scale, color=color)
def _PlotQuiver(self, Phi, Theta, Figure, Origin, Coord, Vector, Scalar, Label=''): FlatCoord = [1.01*Coord[i].flatten() + Origin[i] for i in range(3)] A = Scalar.flatten() A /= np.max(abs(A)) Vector = A * Vector mlab.quiver3d(*FlatCoord, *Vector, color=(0,0,0), scale_factor=0.25, scale_mode = 'vector', figure=Figure) mlab.text3d(x = Origin[0], y = Origin[1], z = Origin[2]+3.5, text = Label, line_width = 0.1, figure = Figure, scale = 0.25, color = (0,0,0))
def show_arrow(self, point, direction, color='lb', scale_factor=.03): color_f = self.get_color(color) mlab.quiver3d(point[0], point[1], point[2], direction[0], direction[1], direction[2], scale_factor=scale_factor, line_width=0.05, color=color_f, mode='arrow')
def show_vectorfield(S, U, V, W): print "Show Vectors" mins = S.min() ptps = S.ptp() mlab.quiver3d(U, V, W, scalars=S, scale_mode="scalar", vmin=mins + 0.2 * ptps, vmax=mins + 0.8 * ptps) print "done."
def VectorPlot3D(res, varName): if ((not mlabLoaded)): print("The mayavi is not installed!") return x = res['X'].transpose(1, 0, 2) y = res['Y'].transpose(1, 0, 2) z = res['Z'].transpose(1, 0, 2) varX = res[varName[0]].transpose(1, 0, 2) varY = res[varName[1]].transpose(1, 0, 2) varZ = res[varName[2]].transpose(1, 0, 2) mlab.quiver3d(x, y, z, varX, varY, varZ) mlab.show()
def e_vector(q, pos, x_grid, y_grid, z_grid, x_field, y_field, z_field): fig = mplt.figure() # draw sphere for point charge for charge, location in zip(q, pos): sphere(charge, location) # draw vector field X, Y, Z = np.meshgrid(x_grid, y_grid, z_grid, indexing='ij') mplt.quiver3d(X, Y, Z, x_field, y_field, z_field) # set view to x-axis coming out of screen fig.scene.x_plus_view() mplt.axes() mplt.show()
def render(self, **kwargs): from mayavi import mlab # Only get every nth vector. 1 means get every vector. mask_points = kwargs.get('mask_points', 1) mlab.quiver3d(self.points[:, 0], self.points[:, 1], self.points[:, 2], self.vectors[:, 0], self.vectors[:, 1], self.vectors[:, 2], mask_points=mask_points, figure=self.figure) return self
def visualize(self, obj, arrow_len=0.01, line_width=20.0): """ Display point grasp as arrows on the contact points of the mesh """ contacts_found, contacts = self.close_fingers(obj) if contacts_found: c1_world = contacts[0].point c2_world = contacts[1].point v = c2_world - c1_world v = arrow_len * v / np.linalg.norm(v) mv.quiver3d(c1_world[0] - v[0], c1_world[1] - v[1], c1_world[2] - v[2], v[0], v[1], v[2], scale_factor=1.0, mode='arrow', line_width=line_width) mv.quiver3d(c2_world[0] + v[0], c2_world[1] + v[1], c2_world[2] + v[2], -v[0], -v[1], -v[2], scale_factor=1.0, mode='arrow', line_width=line_width)
def showPc(s,figm=None,showNormals=False,algo='sobel',color=(1,0,0)): s.getPc() if figm is None: figm = mlab.figure(bgcolor=(1,1,1)) mlab.points3d(s.pc[s.mask,0],s.pc[s.mask,1],s.pc[s.mask,2], s.gray[s.mask],colormap='gray',scale_factor=0.01, figure=figm,mode='point',mask_points=1) if showNormals: s.getNormals(algo) mlab.quiver3d(s.pc[s.mask,0],s.pc[s.mask,1],s.pc[s.mask,2], s.n[s.mask,0],s.n[s.mask,1],s.n[s.mask,2], figure=figm, mode='2darrow',line_width=1.0, color=color, scale_factor=0.1,mask_points=50) return figm
def draw_path(self, path, color=(0.7, 0.5, 0.3)): points, vectors, processes = [], [], [] for k in range(len(path)-1): points.append(path[k][0]) vectors.append(path[k+1][0] - path[k][0]) processes.append(path[k][2]) points, vectors = np.array(points), np.array(vectors) processes = np.array(processes) pnts, vctrs = points[processes], vectors[processes] mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=color, mode='2ddash', scale_factor=1, line_width=5.0) mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=color, mode='arrow', scale_factor=3, scale_mode='scalar', line_width=5.0) pnts = points[np.bitwise_not(processes)] vctrs = vectors[np.bitwise_not(processes)] mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=(0.6, 0.6, 0.6), mode='2ddash', scale_factor=1, line_width=2.0) mlab.quiver3d(pnts[:, 0], pnts[:, 1], pnts[:, 2], vctrs[:, 0], vctrs[:, 1], vctrs[:, 2], color=(0.6, 0.6, 0.6), mode='arrow', scale_factor=2, scale_mode='scalar', line_width=2.0)
def _plot_axes(lattice, color=(1, 0, 0)): lat = np.transpose([x/np.linalg.norm(x) for x in lattice.T]) mlab.quiver3d([0, 0, 0], [0, 0, 0], [0, 0, 0], lat[0], lat[1], lat[2], color=color, line_width=3, scale_factor=1) for c, v in zip(('a','b','c'), (lat * 1.3).T): mlab.text3d(v[0]+0.15, v[1], v[2], c, color=color, scale=0.3)
def draw_frames(self, points, frames, scale=10): scale = self.scale * scale clr = [RED, GREEN, BLUE] vectors = [[], [], []] for frame in frames: vectors[0].append(frame[:, 0]) vectors[1].append(frame[:, 1]) vectors[2].append(frame[:, 2]) vectors[0] = np.array(vectors[0]) vectors[1] = np.array(vectors[1]) vectors[2] = np.array(vectors[2]) for k in range(3): mlab.quiver3d(points[:, 0], points[:, 1], points[:, 2], vectors[k][:, 0], vectors[k][:, 1], vectors[k][:, 2], color=clr[k], mode='arrow', scale_factor=scale)
def drawReferenceFrameFromDCM(pos,dcm,size): # check Visual.Mframe ############################################################################### # draw x, y z axes # quiver = [x,y,z, u,v,w] v1 = np.dot(dcm,np.array([1,0,0])) v2 = np.dot(dcm,np.array([0,1,0])) v3 = np.dot(dcm,np.array([0,0,1])) pos = pos.tolist() a = mlab.quiver3d(pos[0], pos[1], pos[2], v1[0], v1[1], v1[2], scale_factor=size, color=(1,0,0), mask_points=5) b = mlab.quiver3d(pos[0], pos[1], pos[2], v2[0], v2[1], v2[2], scale_factor=size, color=(0,1,0), mask_points=5) c = mlab.quiver3d(pos[0], pos[1], pos[2], v3[0], v3[1], v3[2], scale_factor=size, color=(0,0,1), mask_points=5) return [a,b,c]
def draw(self): x = np.linspace(self._base_square_x[0], self._base_square_x[1],self._Nl) y = np.linspace(self._base_square_y[0], self._base_square_y[1],self._Nw) x,y = np.meshgrid(x,y) z = 0.0*x for trans in self._transforms: p = np.concatenate((x[:,:,None], y[:,:,None], z[:,:,None]), axis=-1) p = trans(p) pflat = np.reshape(p,(-1,3)) x,y,z = pflat[:,0],pflat[:,1],pflat[:,2] value = self._f(pflat,*self._f_args,**self._f_kwargs) u,v,w = value[:,0],value[:,1],value[:,2] m = mlab.quiver3d(x,y,z,u,v,w,mode='arrow',color=(0.4,0.4,0.4)) mlab.draw() if self._plots is None: self._plots = (m,trans), else: self._plots += (m,trans),
def graph_plot(x, y, z, start_idx, end_idx, edge_scalars=None, **kwargs): """ Show the graph edges using Mayavi Parameters ----------- x: ndarray x coordinates of the points y: ndarray y coordinates of the points z: ndarray z coordinates of the points edge_scalars: ndarray, optional optional data to give the color of the edges. kwargs: extra keyword arguments are passed to quiver3d. """ vec = mlab.quiver3d( x[start_idx], y[start_idx], z[start_idx], x[end_idx] - x[start_idx], y[end_idx] - y[start_idx], z[end_idx] - z[start_idx], scalars=edge_scalars, mode="2ddash", scale_factor=1, **kwargs ) if edge_scalars is not None: vec.glyph.color_mode = "color_by_scalar" return vec
def build(mp): air_cells = filter(lambda cell: cell.tag == str2tag["Air"] and numpy.any(cell.wind.potential > 0), mp.cells) size = len(air_cells) xs = numpy.zeros(size) ys = numpy.zeros(size) zs = numpy.zeros(size) us = numpy.zeros(size) vs = numpy.zeros(size) ws = numpy.zeros(size) for index, cell in enumerate(air_cells): coord = cell.coord xs[index] = coord[0] ys[index] = coord[1] zs[index] = coord[2] + 0.5 wind = cell.wind.potential # wind = cell.wind.calc_wind() us[index] = wind[0] vs[index] = wind[1] ws[index] = wind[2] # us[index] = potential.wv_x # vs[index] = potential.wv_y # ws[index] = potential.wv_z return mb.quiver3d(xs, ys, zs, us, vs, ws, line_width=0.5, scale_mode="vector", mode="2darrow")
def draw(self,**kwargs): x = np.linspace(self._base_square_x[0] + 0.5*(self._base_square_x[1]-self._base_square_x[0])/self._Nl, self._base_square_x[1] - 0.5*(self._base_square_x[1]-self._base_square_x[0])/self._Nl, self._Nl) y = np.linspace(self._base_square_y[0] + 0.5*(self._base_square_y[1]-self._base_square_y[0])/self._Nw, self._base_square_y[1] - 0.5*(self._base_square_y[1]-self._base_square_y[0])/self._Nw, self._Nw) x,y = np.meshgrid(x,y) z = 0.0*x for trans in self._transforms: p = np.concatenate((x[:,:,None], y[:,:,None], z[:,:,None]), axis=-1) p = trans(p) pflat = np.reshape(p,(-1,3)) x,y,z = pflat[:,0],pflat[:,1],pflat[:,2] value = self._f(pflat,*self._f_args,**self._f_kwargs) u,v,w = value[:,0],value[:,1],value[:,2] m = mlab.quiver3d(x,y,z,u,v,w,mode='arrow',color=(1.0,1.0,1.0),scale_factor=self.scale_units, resolution=20,**kwargs) mlab.draw() if self._plots is None: self._plots = (m,trans), else: self._plots += (m,trans), return [i[0] for i in self._plots]
def show_correspondence(verts1, tris1, verts2, tris2, ij, points=5, show_spheres=True, scalars=None, colormap='gist_rainbow', blend_factor=0.9, compute_blend_weights=compute_fake_weights, color_only_correspondences=1, color_no_correspondence=(0,0,0), offset_factor=(1.5, 0., 0.), block=True, ): mlab.figure(bgcolor=(1,1,1)) # select sparse points to visualize if type(points) is int: i_sel = [0] geo = GeodesicDistanceComputation(verts1, tris1) for n in xrange(points-1): d = geo(ij[i_sel,0])[ij[:,0]] i_sel.append(d.argmax()) else: i_sel = points #i_sel = np.random.randint(0, len(ij), 10) ij_sel = np.column_stack((ij[i_sel,0], ij[i_sel, 1])) # color per marker - value between 0 and 1 which is passed through a color map later on color = np.linspace(0, 1, len(ij_sel)) # prepare visualization offset = verts2.ptp(axis=0) * offset_factor#(verts2[:,0].ptp() * offset_factor, 0, 0) p1 = verts1[ij_sel[:,0]] p2 = verts2[ij_sel[:,1]] + offset v = p2 - p1 # visualize! # correspondence arrows quiv = mlab.quiver3d(p1[:,0], p1[:,1], p1[:,2], v[:,0], v[:,1], v[:,2], scale_factor=1, line_width=2, mode='2ddash', scale_mode='vector', scalars=color, colormap=colormap) quiv.glyph.color_mode = 'color_by_scalar' # show sparse points as spheres if show_spheres: h = veclen(verts1[tris1[:,0]] - verts1[tris1[:,1]]).mean() * 2 mlab.points3d(p1[:,0], p1[:,1], p1[:,2], color, scale_mode='none', scale_factor=h, colormap=colormap, resolution=32) mlab.points3d(p2[:,0], p2[:,1], p2[:,2], color, scale_mode='none', scale_factor=h, colormap=colormap, resolution=32) # make colors for the meshes if scalars is None: H = compute_blend_weights(verts1, tris1, ij_sel[:,0]) # interpolate colors lut = quiv.module_manager.scalar_lut_manager.lut.table.to_array() lut_colors_rgb = lut[(color * (lut.shape[0]-1)).astype(np.int), :3].astype(np.float) scalars = ((1 - blend_factor) * lut_colors_rgb[H.argmax(axis=1)] + \ blend_factor * (H[:,:,np.newaxis] * lut_colors_rgb[np.newaxis,:,:]).sum(1)) scalars = np.uint8(scalars) if color_only_correspondences: scalars_filtered = np.zeros((len(verts1), 3)) scalars_filtered[:] = np.array(color_no_correspondence)[np.newaxis] * 255 scalars_filtered[ij[:,0]] = scalars[ij[:,0]] scalars = scalars_filtered scalars2 = np.zeros((len(verts2), 3)) scalars2[:] = np.array(color_no_correspondence)[np.newaxis] * 255 scalars2[ij[:,1]] = scalars[ij[:,0]] # show meshes vismesh(verts1, tris1, scalars=scalars) vismesh(verts2 + offset, tris2, scalars=scalars2) if block: mlab.show()
def build(candidate, fig): can_list = candidate.leaks size = len(can_list) xs = numpy.empty(size, dtype=int) ys = numpy.empty(size, dtype=int) zs = numpy.empty(size, dtype=int) us = numpy.empty(size) vs = numpy.empty(size) ws = numpy.empty(size) for index, can in enumerate(can_list): loc = can.coord infor_gain = can.conc print "information gain =", [loc[0], loc[1], loc[2]], "->", infor_gain xs[index] = loc[0] ys[index] = loc[1] zs[index] = loc[2] us[index] = infor_gain vs[index] = infor_gain ws[index] = 0 if fig is None: fig = mb.quiver3d(xs, ys, zs, us, vs, ws, scale_mode="vector", mode="2dthick_cross", colormap="cool") else: fig.mlab_source.reset(x=xs, y=ys, z=zs, u=us, v=vs, w=ws) return fig
def build(dect, hyps, fig): pair_list = map(lambda leak: (leak.coord, sum([_loc_vector_calculator(leak.coord, len(hyps))(hyp) for hyp in hyps]) / len( hyps) if len(hyps) > 0 else 1), dect.leaks) size = len(pair_list) xs = numpy.empty(size, dtype=int) ys = numpy.empty(size, dtype=int) zs = numpy.empty(size, dtype=int) us = numpy.empty(size) vs = numpy.empty(size) ws = numpy.empty(size) for index, pair in enumerate(pair_list): loc, vec = pair xs[index], ys[index], zs[index] = loc us[index], vs[index], ws[index] = vec # print loc, vec if not fig is None: fig.glyph.color_mode = 'color_by_scalar' fig = mb.quiver3d(xs, ys, zs, us, vs, ws, line_width=2.0, scale_factor=4.0, mode="2dthick_arrow", colormap="Spectral") # print fig return fig
def draw_coordinate_system_axes(fig, coordinate_system, offset=0.0, scale=1.0, draw_labels=True): points, lengths = coordinate_system_arrows(coordinate_system, offset=offset, scale=scale) mlab.figure(fig, bgcolor=fig.scene.background) arrows = mlab.quiver3d( points[:, 0], points[:, 1], points[:, 2], lengths[0, :], lengths[1, :], lengths[2, :], scalars=np.array([3, 2, 1]), mode="arrow", ) arrows.glyph.color_mode = "color_by_scalar" arrows.glyph.glyph.scale_factor = scale data = arrows.parent.parent data.name = coordinate_system.name glyph_scale = arrows.glyph.glyph.scale_factor * 1.1 # label_col = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] labels = [] if draw_labels: for i in range(3): labels.append( mlab.text( points[i, 0] + glyph_scale * coordinate_system.basis[i, 0], points[i, 1] + glyph_scale * coordinate_system.basis[i, 1], coordinate_system.labels[i], z=points[i, 2] + glyph_scale * coordinate_system.basis[i, 2], # color=label_col[i], width=0.1 * scale, ) ) return arrows, labels