for p in points: Xs = Geo['SC_BOT_CORNER_%s_X' % (p)] Ys = Geo['SC_BOT_CORNER_%s_Y' % (p)] xy.append([Xs, Ys]) top.append((Xs, Ys, H)) bottom.append((Xs, Ys, 0)) sideslist = [] for p in range(8): sides = (top[p], top[p + 1], bottom[p + 1], bottom[p]) #print(sides) vertsside = [sides] sideslist.append([top[p], top[p + 1], bottom[p + 1], bottom[p]]) #facecolors = [cm.jet(Histtop)] sideart = ax.add_collection3d(Poly3DCollection( vertsside, alpha=.75)) #, facecolor = colormap)) #print(ax.get_children()) vertstop = [top] vertsbot = [bottom] topart = ax.add_collection3d(Poly3DCollection(vertstop, alpha=.75)) botart = ax.add_collection3d(Poly3DCollection(vertsbot, alpha=.75)) linex = liney = linez = np.arange(-1, 2) zeros = np.zeros(len(linex)) ax.plot(linex, zeros, zeros) ax.plot(zeros, liney, zeros) ax.plot(zeros, zeros, linez) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()
def fs_plot_data(self, plot_type = 'mpl', bz_linewidth= 0.9, axis_labels = True, symmetry_labels = True, color_list = None, title_str = None): """Function for producing a plot of the Fermi surface. Will edit this to allow for custom plotting options. """ meshes = [] if plot_type == 'mpl': fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') rlattvec = self._brillouin_zone._rlattvec # specify the colour list for plotting the bands. # Below is the deafult, can be overidden by specifying 'colour' in calling function. if color_list is None: color_list = plt.cm.Set1(np.linspace(0, 1, 9)) # create a mesh for each electron band which has an isosurface at the Fermi energy. # mesh data is generated by a marching cubes algorithm when the FermiSurface object is created. for i, band in enumerate(self._fermi_surface._iso_surface, 0): verts = band[0] faces = band[1] grid = [np.array([item[0] for item in verts]), np.array([item[1] for item in verts]), np.array([item[2] for item in verts])] # reposition the vertices so that the cente of the Brill Zone is at (0,0,0) # include if want gamma at centre of plot, along with "rearrange_data method in bulk_objects" # verts -= np.array([grid[0].max()/2,grid[1].max()/2,grid[2].max()/2]) # create a mesh and add it to the plot mesh = Poly3DCollection(verts[faces], linewidths=0.1) mesh.set_facecolor(color_list[i]) mesh.set_edgecolor('lightgray') ax.add_collection3d(mesh) # add the Brillouin Zone outline to the plot corners = self._recip_cell._faces ax.add_collection3d(Line3DCollection(corners, colors='k', linewidths=bz_linewidth)) # add high-symmetry points to the plot sym_pts = self._symmetry_pts x, y, z = zip(*sym_pts[0]) # Placeholders for the high-symmetry points in cartesian coordinates x_cart, y_cart, z_cart = [], [], [] # Convert high-symmetry point coordinates into cartesian, and shift to match mesh position for i in x: if i < 0: i = np.linalg.norm([rlattvec[:,0]])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,0])*(i) x_cart.append(i) for i in y: if i < 0: i = np.linalg.norm(rlattvec[:,1])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,1])*(i) y_cart.append(i) for i in z: if i < 0: i = np.linalg.norm(rlattvec[:,2])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,2])*(i) z_cart.append(i) ax.scatter(x_cart, y_cart, z_cart, s=10, c='k') for i, txt in enumerate(sym_pts[1]): ax.text(x_cart[i],y_cart[i],z_cart[i], '%s' % (txt), size=15, zorder=1, color='k') ax.axis('off') if title_str is not None: plt.title(title_str) ax.set_xlim(0, np.linalg.norm(rlattvec[:,0])+1) ax.set_ylim(0, np.linalg.norm(rlattvec[:,1])+1) ax.set_zlim(0, np.linalg.norm(rlattvec[:,2])+1) plt.tight_layout() plt.show() elif plot_type == 'plotly': init_notebook_mode(connected=True) # plotly.tools.set_credentials_file(username='******', api_key='PiOwBRIRWKGJWIFXe1vT') rlattvec = self._recip_cell._rlattvec # Different colours # colors = [ # '#1f77b4', # muted blue # '#ff7f0e', # safety orange # '#2ca02c', # cooked asparagus green # '#d62728', # brick red # '#9467bd', # muted purple # '#8c564b', # chestnut brown # '#e377c2', # raspberry yogurt pink # '#7f7f7f', # middle gray # '#bcbd22', # curry yellow-green # '#17becf', # blue-teal # '#00FFFF' #another blue teal # '#1f77b4', # muted blue # '#ff7f0e', # safety orange # '#2ca02c', # cooked asparagus green # '#d62728', # brick red # '#9467bd', # muted purple # '#8c564b', # chestnut brown # '#e377c2', # raspberry yogurt pink # '#7f7f7f', # middle gray # '#bcbd22', # curry yellow-green # '#17becf', # blue-teal # '#00FFFF' #another blue teal # ] colors = cl.scales['11']['qual']['Set3'] # create a mesh for each electron band which has an isosurface at the Fermi energy. # mesh data is generated by a marching cubes algorithm when the FermiSurface object is created. for i, band in enumerate(self._fermi_surface._iso_surface, 0): verts = band[0] faces = band[1] grid = [np.array([np.abs(item[0]) for item in verts]), np.array([np.abs(item[1]) for item in verts]), np.array([np.abs(item[2]) for item in verts])] x, y, z = zip(*verts) I, J, K = ([triplet[c] for triplet in faces] for c in range(3)) trace = go.Mesh3d(x=x, y=y, z=z, color=colors[i], opacity = 0.9, i=I, j=J, k=K) meshes.append(trace) # add the Brillouin Zone outline to the plot corners = self._recip_cell._faces for facet in corners: x, y, z = zip(*facet) trace = go.Scatter3d(x=x, y=y, z=z, mode = 'lines', line=dict( color='black', width=3 )) meshes.append(trace) # add the high symmetry points to the plot sym_pts = self._symmetry_pts # Get text labels into Latex form labels = [] for i in sym_pts[1]: labels.append(sympy.latex(i)) x, y, z = zip(*sym_pts[0]) # Placeholders for the high-symmetry points in cartesian coordinates x_cart, y_cart, z_cart = [], [], [] # Convert high-symmetry point coordinates into cartesian, and shift to match mesh position for i in x: if i < 0: i = np.linalg.norm([rlattvec[:,0]])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,0])*(i) x_cart.append(i) for i in y: if i < 0: i = np.linalg.norm(rlattvec[:,1])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,1])*(i) y_cart.append(i) for i in z: if i < 0: i = np.linalg.norm(rlattvec[:,2])*((0.5+i)+0.5) else: i = np.linalg.norm(rlattvec[:,2])*(i) z_cart.append(i) trace = go.Scatter3d(x=x_cart, y=y_cart, z=z_cart, mode='markers+text', marker = dict(size = 5, color = 'black' ), name='Markers and Text', text = labels, textposition='bottom center' ) meshes.append(trace) # Specify plot parameters layout = go.Layout(scene = dict(xaxis=dict(title = '', showgrid=True, zeroline=True, showline=False, ticks='', showticklabels=False), yaxis=dict(title = '', showgrid=True, zeroline=True, showline=False, ticks='', showticklabels=False), zaxis=dict(title = '', showgrid=True, zeroline=True, showline=False, ticks='', showticklabels=False)), showlegend=False, title=go.layout.Title( text=title_str, xref='paper', x=0 )) plot(go.Figure(data=meshes,layout= layout), include_mathjax='cdn') else: raise ValueError( "The type you have entered is not a valid option for the plot_type parameter." "Please enter one of {'mpl', 'plotly'} for a matplotlib or plotly-type plot" " respectively. For an interactive plot 'plotly' is recommended.")
def polyplane(verts, alpha=0.5, color="green"): poly = Poly3DCollection(verts) poly.set_alpha(alpha) poly.set_facecolor(color) return poly
def plot_cam(M, sz_cam, ax=None): if ax is None: fig = plt.figure(figsize=(10, 10)) ax = fig.gca(projection='3d') # To make plot more intuitive, I've swapped the Y and Z axes ps_axes = M.new_tensor([[0, 0, 0], [2.0 * sz_cam, 0, 0], [0, 0, 0], [0, 2.0 * sz_cam, 0], [0, 0, 0], [0, 0, 2.0 * sz_cam]]) ps_text = M.new_tensor([[2.5 * sz_cam, 0, 0], [0, 2.5 * sz_cam, 0], [0, 0, 2.5 * sz_cam]]) pss_cam = [[[0, 0, 0], [sz_cam / 2, sz_cam / 2, 1.5 * sz_cam], [-sz_cam / 2, sz_cam / 2, 1.5 * sz_cam]], [[0, 0, 0], [sz_cam / 2, sz_cam / 2, 1.5 * sz_cam], [sz_cam / 2, -sz_cam / 2, 1.5 * sz_cam]], [[0, 0, 0], [sz_cam / 2, -sz_cam / 2, 1.5 * sz_cam], [-sz_cam / 2, -sz_cam / 2, 1.5 * sz_cam]], [[0, 0, 0], [-sz_cam / 2, sz_cam / 2, 1.5 * sz_cam], [-sz_cam / 2, -sz_cam / 2, 1.5 * sz_cam]], [[sz_cam / 2, sz_cam / 2, sz_cam / 2], [sz_cam / 2, sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, sz_cam / 2, sz_cam / 2]], [[sz_cam / 2, -sz_cam / 2, sz_cam / 2], [sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, sz_cam / 2]], [[sz_cam / 2, sz_cam / 2, sz_cam / 2], [sz_cam / 2, sz_cam / 2, -sz_cam / 2], [sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [sz_cam / 2, -sz_cam / 2, sz_cam / 2]], [[-sz_cam / 2, sz_cam / 2, sz_cam / 2], [-sz_cam / 2, sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, sz_cam / 2]], [[sz_cam / 2, sz_cam / 2, sz_cam / 2], [sz_cam / 2, -sz_cam / 2, sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, sz_cam / 2], [-sz_cam / 2, sz_cam / 2, sz_cam / 2]], [[sz_cam / 2, sz_cam / 2, -sz_cam / 2], [sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, -sz_cam / 2, -sz_cam / 2], [-sz_cam / 2, sz_cam / 2, -sz_cam / 2]]] # TODO: Do one face and rotate it instead pss_cam = [M.new_tensor(ps_cam) for ps_cam in pss_cam] ps_axes_root = pmm(ps_axes, M, aug=True) ax.quiver(ps_axes_root[::2, 0], ps_axes_root[::2, 2], ps_axes_root[::2, 1], ps_axes_root[1::2, 0] - ps_axes_root[::2, 0], ps_axes_root[1::2, 2] - ps_axes_root[::2, 2], ps_axes_root[1::2, 1] - ps_axes_root[::2, 1], color='r') ps_text_root = pmm(ps_text, M, aug=True) ax.text(*ps_text_root[0, [0, 2, 1]], 'x') ax.text(*ps_text_root[1, [0, 2, 1]], 'y') ax.text(*ps_text_root[2, [0, 2, 1]], 'z') pss_cam_root = [pmm(ps_cam, M, aug=True) for ps_cam in pss_cam] ax.add_collection3d( Poly3DCollection( [ps_cam_root[:, [0, 2, 1]] for ps_cam_root in pss_cam_root], facecolors='k', alpha=0.5)) return ax, torch.cat([ps_axes_root, ps_text_root] + pss_cam_root)
def show_matplotlib(self, ax=None, normal_vectors=False, scale_normal_vector=None, saveas=None, **kwargs): """Poor man's viewer with matplotlib. Parameters ---------- ax: matplotlib axis The 3d axis in which to plot the mesh. If not provided, create a new one. normal_vector: bool If True, print normal vector. scale_normal_vector: array of shape (nb_faces, ) Scale separately each of the normal vectors. saveas: str file path where to save the image Other parameters are passed to Poly3DCollection. """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection default_axis = ax is None if default_axis: fig = plt.figure() ax = fig.add_subplot(111, projection="3d") faces = [] for face in self.faces: vertices = [] for index_vertex in face: vertices.append(self.vertices[int(index_vertex), :]) faces.append(vertices) if 'facecolors' not in kwargs: kwargs['facecolors'] = (0.3, 0.3, 0.3, 0.3) if 'edgecolor' not in kwargs: kwargs['edgecolor'] = 'k' ax.add_collection3d(Poly3DCollection(faces, **kwargs)) # Plot normal vectors. if normal_vectors: if scale_normal_vector is not None: vectors = (scale_normal_vector * self.faces_normals.T).T else: vectors = self.faces_normals ax.quiver(*zip(*self.faces_centers), *zip(*vectors), length=0.2) if default_axis: ax.set_xlabel("x") ax.set_ylabel("y") xmin, xmax, ymin, ymax, zmin, zmax = self.squared_axis_aligned_bbox ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_zlim(zmin, zmax) if saveas is not None: plt.tight_layout() plt.savefig(saveas) else: plt.show()
def plot_trisurf(fig, ax, vertices, triangles, texture=None, vmin=None, vmax=None): """ Display a tri surface. Parameters ---------- fig: Figure the matplotlib figure. ax: Axes3D axis to display the surface plot. vertices: array (N, 3) the surface vertices. triangles: array (N, 3) the surface triangles. texture: array (N,), default None a texture to display on the surface. vmin: float, default None minimum value to map. vmax: float, default None maximum value to map. """ # Parameters if vmin is None: vmin = texture.min() if vmax is None: vmax = texture.max() if texture is None: texture = np.ones((len(vertices), )) # Display tri surface x, y, z = vertices[:, 0], vertices[:, 1], vertices[:, 2] norm = colors.Normalize(vmin=0, vmax=vmax, clip=False) facecolors = cm.coolwarm(norm(texture)) triangle_vertices = np.array([vertices[tri] for tri in triangles]) polygon = Poly3DCollection(triangle_vertices, facecolors=facecolors, edgecolors="black") ax.add_collection3d(polygon) ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ax.set_zlim(-1, 1) # Add colorbar m = cm.ScalarMappable(cmap=cm.coolwarm, norm=norm) m.set_array(texture) fig.colorbar(m, ax=ax, fraction=0.046, pad=0.04) # Get rid of the panes ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([])
def plot_wigner_seitz(ax, lattice, **kwargs): ws_cell = lattice.get_wigner_seitz_cell() ax.add_collection3d(Poly3DCollection(ws_cell, **kwargs))
P_re = np.hstack((P[:, i], P[:, 1].reshape(3, 1))) #Plot base and platform perimeter ax.plot(B_re[0, :], B_re[1, :], B_re[2, :], 'grey', linewidth=3) ax.plot(P_re[0, :], P_re[1, :], P_re[2, :], 'grey', linewidth=3) #Plot applied force vector (not to scale) a = 3 u = np.dot(R_p_b, appliedForceDirection_p) * a T_f = T_in - u ax.quiver(T_f[0], T_f[1], T_f[2], u[0], u[1], u[2]) #Plot base and platform polygons PolyCollections = [] PolyCollections.append( Poly3DCollection([B_re.T], facecolor='grey', lw=2, alpha=0.2)) PolyCollections.append( Poly3DCollection([P_re.T], facecolor='grey', lw=2, alpha=0.2)) ax.add_collection3d(PolyCollections[0]) ax.add_collection3d(PolyCollections[1]) #Set axis labels ax.set_title("Stewart Platform") ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.axis('square') ax.view_init(25, -15) #-----------Second subplot (XZ Plane)----------------------------
def plot(render_state, fig=None, ax=None): size = int(math.sqrt(len(render_state.top))) if fig is None or ax is None or not plt.get_fignums(): fig = plt.figure(facecolor='grey', figsize=(8, 8)) ax = fig.add_subplot(111, projection='3d', xlim=(0, size), ylim=(0, size), zlim=(0, size), xticks=[], yticks=[], zticks=[], frame_on=False) # top layer z = [size] * 4 for i, c in enumerate(render_state.top): a, b = i % size, i // size x = [a, a, a + 1, a + 1] y = [size - 1 - b, size - b, size - b, size - 1 - b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) # front layer y = [0] * 4 for i, c in enumerate(render_state.front): a, b = i % size, i // size x = [a, a, a + 1, a + 1] z = [size - 1 - b, size - b, size - b, size - 1 - b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) # right layer x = [size] * 4 for i, c in enumerate(render_state.right): a, b = i % size, i // size y = [a, a, a + 1, a + 1] z = [size - 1 - b, size - b, size - b, size - 1 - b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) # left layer x = [0] * 4 for i, c in enumerate(render_state.left): a, b = i % size, i // size y = [size - a, size - a, size - a - 1, size - a - 1] z = [size - 1 - b, size - b, size - b, size - 1 - b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) # back layer y = [size] * 4 for i, c in enumerate(render_state.back): a, b = i % size, i // size x = [size - a, size - a, size - a - 1, size - a - 1] z = [size - 1 - b, size - b, size - b, size - 1 - b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) # bottom layer z = [0] * 4 for i, c in enumerate(render_state.bottom): a, b = i % size, i // size x = [a, a, a + 1, a + 1] y = [b, b + 1, b + 1, b] verts = [list(zip(x, y, z))] ax.add_collection3d( Poly3DCollection(verts, facecolors=colors[c], edgecolors='black')) plt.show() return fig, ax
def pore_volume(points,plot=False): import numpy as np from scipy.spatial import Delaunay #points = np.random.randn(20, 3) # Random points in space #points = np.array([[0,0,0],[0,1,0],[1,0,0],[1,1,0],[0.5,0.5,3]]) # Regular Conical Pyramid - Volume = 1.0 tri = Delaunay(points) " We only want points included in the convex hull to calculate the centroid " hull_points = np.unique(tri.convex_hull) #hull_centroid = np.array([points[hull_points,0].mean(),points[hull_points,1].mean(),points[hull_points,2].mean()]) hull_centroid = centroid(points[hull_points]) # -- Make a list of faces, [(p1, p2, p3), ...]; pj = (xj, yj, zj) faces = [] # list of points making each face face_centers = [] # co-ordinates of the face centroids face_normals = [] # normal vector of the faces face_areas = [] # Area of each face hull_volume = 0.0 for ia, ib, ic in tri.convex_hull: " Points making each triangular face " faces.append(points[[ia, ib, ic]]) " Collection of co-ordinates of each point in this face " face_x = points[[ia,ib,ic]][:,0] face_y = points[[ia,ib,ic]][:,1] face_z = points[[ia,ib,ic]][:,2] " Average of each co-ordinate is the centroid of the face " face_centroid = [face_x.mean(),face_y.mean(),face_z.mean()] face_centers.append(face_centroid) face_centroid_vector = face_centroid - hull_centroid " Vectors of the sides of the face used to find normal vector and area " vab = points[ib] - points[ia] vac = points[ic] - points[ia] vbc = points[ic] - points[ib] # used later for area " As vectors are co-planar the cross-product will produce the normal vector of the face " face_normal = np.cross(vab,vac) face_unit_normal = face_normal/np.linalg.norm(face_normal) face_normals.append(face_unit_normal) " As triangles are orientated randomly in 3D we could either transform co-ordinates to align with a plane and perform 2D operations " " to work out the area or we could work out the lengths of each side and use Heron's formula which is easier" " Using Delaunay traingulation will always produce triangular faces but if dealing with other polygons co-ordinate transfer may be necessary " a = np.linalg.norm(vab) b = np.linalg.norm(vbc) c = np.linalg.norm(vac) " Semiperimeter " s = 0.5*(a+b+c) face_area = np.sqrt(s*(s-a)*(s-b)*(s-c)) face_areas.append(face_area) " Now the volume of the pyramid section defined by the 3 face points and the hull centroid can be calculated " pyramid_volume = np.abs(np.dot(face_centroid_vector,face_unit_normal)*face_area/3) " Each pyramid is summed together to calculate the total volume " hull_volume += pyramid_volume face_centers = np.asarray(face_centers) face_normals = np.asarray(face_normals) face_areas = np.asarray(face_areas) if (plot): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection fig = plt.figure() ax = fig.gca(projection='3d') r,g,b=np.random.rand(3,1) items = Poly3DCollection(faces, facecolors=[(r, g, b, 0.1)]) ax.add_collection(items) #ax.scatter(points[hull_points,0], points[hull_points,1], points[hull_points,2], 'o') ax.scatter(points[:,0], points[:,1], points[:,2], 'o') ax.scatter(hull_centroid[0],hull_centroid[1],hull_centroid[2],c='r',marker='o') #ax.scatter(face_centers[:,0], face_centers[:,1], face_centers[:,2],c='g',marker='o') plt.show() print "Pore Volume: "+str(hull_volume) return hull_volume
def plot_RGB_colourspaces_gamuts(colourspaces, reference_colourspace='CIE xyY', segments=8, show_grid=True, grid_segments=10, show_spectral_locus=False, spectral_locus_colour=None, cmfs='CIE 1931 2 Degree Standard Observer', chromatically_adapt=False, **kwargs): """ Plots given *RGB* colourspaces gamuts in given reference colourspace. Parameters ---------- colourspaces : unicode or RGB_Colourspace or array_like *RGB* colourspaces to plot the gamuts. ``colourspaces`` elements can be of any type or form supported by the :func:`colour.plotting.filter_RGB_colourspaces` definition. reference_colourspace : unicode, optional **{'CIE XYZ', 'CIE xyY', 'CIE xy', 'CIE Lab', 'CIE LCHab', 'CIE Luv', 'CIE Luv uv', 'CIE LCHuv', 'CIE UCS', 'CIE UCS uv', 'CIE UVW', 'DIN 99', 'Hunter Lab', 'Hunter Rdab', 'IPT', 'JzAzBz', 'OSA UCS', 'hdr-CIELAB', 'hdr-IPT'}**, Reference colourspace to plot the gamuts into. segments : int, optional Edge segments count for each *RGB* colourspace cubes. show_grid : bool, optional Whether to show a grid at the bottom of the *RGB* colourspace cubes. grid_segments : bool, optional Edge segments count for the grid. show_spectral_locus : bool, optional Whether to show the spectral locus. spectral_locus_colour : array_like, optional Spectral locus colour. cmfs : unicode or XYZ_ColourMatchingFunctions, optional Standard observer colour matching functions used for computing the spectral locus boundaries. ``cmfs`` can be of any type or form supported by the :func:`colour.plotting.filter_cmfs` definition. chromatically_adapt : bool, optional Whether to chromatically adapt the *RGB* colourspaces given in ``colourspaces`` to the whitepoint of the default plotting colourspace. Other Parameters ---------------- \\**kwargs : dict, optional {:func:`colour.plotting.artist`, :func:`colour.plotting.volume.nadir_grid`}, Please refer to the documentation of the previously listed definitions. face_colours : array_like, optional Face colours array such as `face_colours = (None, (0.5, 0.5, 1.0))`. edge_colours : array_like, optional Edge colours array such as `edge_colours = (None, (0.5, 0.5, 1.0))`. face_alpha : numeric, optional Face opacity value such as `face_alpha = (0.5, 1.0)`. edge_alpha : numeric, optional Edge opacity value such as `edge_alpha = (0.0, 1.0)`. Returns ------- tuple Current figure and axes. Examples -------- >>> plot_RGB_colourspaces_gamuts(['ITU-R BT.709', 'ACEScg', 'S-Gamut']) ... # doctest: +ELLIPSIS (<Figure size ... with 1 Axes>, <...Axes3DSubplot...>) .. image:: ../_static/Plotting_Plot_RGB_Colourspaces_Gamuts.png :align: center :alt: plot_RGB_colourspaces_gamuts """ colourspaces = filter_RGB_colourspaces(colourspaces).values() count_c = len(colourspaces) title = '{0} - {1} Reference Colourspace'.format( ', '.join([colourspace.name for colourspace in colourspaces]), reference_colourspace, ) settings = Structure( **{ 'face_colours': [None] * count_c, 'edge_colours': [None] * count_c, 'face_alpha': [1] * count_c, 'edge_alpha': [1] * count_c, 'title': title, }) settings.update(kwargs) figure = plt.figure() axes = figure.add_subplot(111, projection='3d') illuminant = CONSTANTS_COLOUR_STYLE.colour.colourspace.whitepoint points = zeros([4, 3]) if show_spectral_locus: cmfs = first_item(filter_cmfs(cmfs).values()) XYZ = cmfs.values points = common_colourspace_model_axis_reorder( XYZ_to_colourspace_model(XYZ, illuminant, reference_colourspace), reference_colourspace) points[np.isnan(points)] = 0 c = ((0.0, 0.0, 0.0, 0.5) if spectral_locus_colour is None else spectral_locus_colour) axes.plot( points[..., 0], points[..., 1], points[..., 2], color=c, zorder=10) axes.plot( (points[-1][0], points[0][0]), (points[-1][1], points[0][1]), (points[-1][2], points[0][2]), color=c, zorder=10) plotting_colourspace = CONSTANTS_COLOUR_STYLE.colour.colourspace quads, RGB_f, RGB_e = [], [], [] for i, colourspace in enumerate(colourspaces): if chromatically_adapt and not np.array_equal( colourspace.whitepoint, plotting_colourspace.whitepoint): colourspace = colourspace.chromatically_adapt( plotting_colourspace.whitepoint, plotting_colourspace.whitepoint_name) quads_c, RGB = RGB_identity_cube( width_segments=segments, height_segments=segments, depth_segments=segments) XYZ = RGB_to_XYZ( quads_c, colourspace.whitepoint, colourspace.whitepoint, colourspace.matrix_RGB_to_XYZ, ) quads.extend( common_colourspace_model_axis_reorder( XYZ_to_colourspace_model( XYZ, colourspace.whitepoint, reference_colourspace, ), reference_colourspace)) if settings.face_colours[i] is not None: RGB = ones(RGB.shape) * settings.face_colours[i] RGB_f.extend( np.hstack([RGB, full([RGB.shape[0], 1], settings.face_alpha[i])])) if settings.edge_colours[i] is not None: RGB = ones(RGB.shape) * settings.edge_colours[i] RGB_e.extend( np.hstack([RGB, full([RGB.shape[0], 1], settings.edge_alpha[i])])) quads = as_float_array(quads) quads[np.isnan(quads)] = 0 if quads.size != 0: for i, axis in enumerate('xyz'): min_a = min(np.min(quads[..., i]), np.min(points[..., i])) max_a = max(np.max(quads[..., i]), np.max(points[..., i])) getattr(axes, 'set_{}lim'.format(axis))((min_a, max_a)) labels = np.array( COLOURSPACE_MODELS_AXIS_LABELS[reference_colourspace])[as_int_array( common_colourspace_model_axis_reorder([0, 1, 2], reference_colourspace))] for i, axis in enumerate('xyz'): getattr(axes, 'set_{}label'.format(axis))(labels[i]) if show_grid: limits = np.array([[-1.5, 1.5], [-1.5, 1.5]]) quads_g, RGB_gf, RGB_ge = nadir_grid(limits, grid_segments, labels, axes, **settings) quads = np.vstack([quads_g, quads]) RGB_f = np.vstack([RGB_gf, RGB_f]) RGB_e = np.vstack([RGB_ge, RGB_e]) collection = Poly3DCollection(quads) collection.set_facecolors(RGB_f) collection.set_edgecolors(RGB_e) axes.add_collection3d(collection) settings.update({ 'axes': axes, 'axes_visible': False, 'camera_aspect': 'equal' }) settings.update(kwargs) return render(**settings)
print "Verts of reduced hull:" print pore_points print "Reduced Volume: "+str(pore_vol) print "Original Verts:" print vor.vertices[polygon] print "Original Volume: "+str(polygon_volume) #sys.exit("Volume of reduced hull is larger than original") print "**************************************************" writer.writerow(['Pore',i, throat_count-occluded_throat, 0.0, 0.0,pore_vol, points[i][0],points[i][1],points[i][2]]) coordination_number.append(throat_count-occluded_throat) collect_pore_vols.append(pore_vol) fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(points[:,0], points[:,1], points[:,2], 'r.') items = Poly3DCollection(faces,linewidths=1, alpha=0.2) face_colours=[(0.5, 0, 0.5, 0.05)] items.set_facecolor(face_colours) ax.add_collection(items) #ax.scatter(vor.vertices[:,0], vor.vertices[:,1], vor.vertices[:,2], 'o') ax.set_xlim(0,1) ax.set_ylim(0,1) ax.set_zlim(0,1) plt.show() dataCSV.close() " Plot histograms of pore stats" plt.figure() plt.title("Histogram of Pore Volumes") num,bins,patches = plt.hist(collect_pore_vols,bins=20,normed=1,histtype='bar',color='r')
periodicity=(True, True, True), unit_system="mks") center = np.array(ds.domain_center) dm = { 'left': np.array(ds.domain_left_edge), 'right': np.array(ds.domain_right_edge) } dm['left'] = dm['left'] + 200. * 1000 dm['right'] = dm['right'] - 200 * 1000 boxregion = ds.region(ds.domain_center, dm['left'], dm['right']) isoval = 4 surface = ds.surface(boxregion, "dvs", isoval) p3dc = Poly3DCollection(surface.triangles, linewidth=0.0) fig = plt.figure() ax = fig.gca(projection='3d') ax.add_collection(p3dc) max_extent = (surface.vertices.max(axis=1) - surface.vertices.min(axis=1)).max() centers = (surface.vertices.max(axis=1) + surface.vertices.min(axis=1)) / 2 bounds = np.zeros([3, 2]) bounds[:, 0] = centers[:] - max_extent / 2 bounds[:, 1] = centers[:] + max_extent / 2 print(bounds) ax.auto_scale_xyz(bounds[0, :], bounds[1, :], bounds[2, :]) plt.savefig('output/WUS_isosurf_synth_' + str(isoval) + '.png') plt.close('all')
def plot_contours(clf, xx, yy, zz, ww, X_Circle, X_Triangle, X_MIN, X_MAX, Y_MIN, Y_MAX, Z_MIN, Z_MAX, type=2, eps=0.1, **params): """Plot the decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object """ plt.close('all') Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel(), zz.ravel(), ww.ravel()]) Z = Z.reshape(xx.shape) # Create a figure with axes for 3D plotting fig = plt.figure() ax = fig.gca(projection='3d') # Plot the different input points using 3D scatter plotting if type == 0: Z = Z[:, 0, :, :] b1 = ax.scatter(X_Circle[:, 1], X_Circle[:, 2], X_Circle[:, 3], c='red') b2 = ax.scatter(X_Triangle[:, 1], X_Triangle[:, 2], X_Triangle[:, 3], c='green') ax.set_xlabel("Y") ax.set_ylabel("Z") ax.set_zlabel("W") elif type == 1: Z = Z[:, :, 0, :] b1 = ax.scatter(X_Circle[:, 0], X_Circle[:, 2], X_Circle[:, 3], c='red') b2 = ax.scatter(X_Triangle[:, 0], X_Triangle[:, 2], X_Triangle[:, 3], c='green') ax.set_xlabel("X") ax.set_ylabel("Z") ax.set_zlabel("W") elif type == 2: Z = Z[:, :, :, 0] b1 = ax.scatter(X_Circle[:, 0], X_Circle[:, 1], X_Circle[:, 3], c='red') b2 = ax.scatter(X_Triangle[:, 0], X_Triangle[:, 1], X_Triangle[:, 3], c='green') ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("W") elif type == 3: Z = Z[:, :, :, 0] b1 = ax.scatter(X_Circle[:, 0], X_Circle[:, 1], X_Circle[:, 2], c='red') b2 = ax.scatter(X_Triangle[:, 0], X_Triangle[:, 1], X_Triangle[:, 2], c='green') ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") # Plot the separating hyperplane by recreating the isosurface for the distance # == 0 level in the distance grid computed through the decision function of the # SVM. This is done using the marching cubes algorithm implementation from # scikit-image. try: verts, faces = measure.marching_cubes_classic(Z) # Scale and transform to actual size of the interesting volume verts = verts * \ [X_MAX - X_MIN, Y_MAX - Y_MIN, Z_MAX - Z_MIN] / SPACE_SAMPLING_POINTS verts = verts + [X_MIN + 1, Y_MIN + 1, Z_MIN + 1] # and create a mesh to display alpha = 0.5 fc = "orange" mesh = Poly3DCollection(verts[faces], alpha=alpha, linewidths=1) mesh.set_edgecolor('w') mesh.set_facecolor((0, 1, 0, alpha)) ax.add_collection3d(mesh) # Some presentation tweaks #ax.set_xlim((-5, 5)) #ax.set_ylim((-5, 5)) #ax.set_zlim((-5, 5)) filename = "image_eps_poly_n_" + str(eps) + str(type) + ".png" name_Image = os.path.join(FILEROOT, filename) ax.legend([mpatches.Patch(color='orange', alpha=0.3), b1, b2], [ "Projected hyperplane", "class of circles", "class of triangles" ], loc="lower left", prop=mpl.font_manager.FontProperties(size=11)) plt.savefig(name_Image) except BaseException as e: print('Failed to do something: ' + str(e)) plt.clf()
def estimate_position(startPos, startOrientation): start_time = datetime.datetime.now() startQuatOrientation = p.getQuaternionFromEuler(startOrientation) # boxId = p.loadURDF("/home/h3ct0r/catkin_ws_espeleo/src/espeleo_planner/espeleo_planner/urdf/espeleo2_low_poly.urdf",startPos, startQuatOrientation) # linkId = 0 boxId = p.loadURDF( "/home/h3ct0r/catkin_ws_espeleo/src/espeleo_planner/espeleo_planner/urdf/espeleo2_low_poly_prismatic.urdf", startPos, startQuatOrientation) linkId = 1 jointFrictionForce = 0 for joint in range(p.getNumJoints(boxId)): p.setJointMotorControl2(boxId, joint, p.POSITION_CONTROL, force=jointFrictionForce) #print " ------------- ", p.getNumBodies() # prevCubePos, prevCubeOrn = p.getBasePositionAndOrientation(boxId) linkStateFull = p.getLinkState(boxId, linkId) prevCubePos, prevCubeOrn = linkStateFull[4], linkStateFull[5] for i in range(1000): p.stepSimulation() #print " ------------- 0 ", p.getLinkState(boxId, 0) # print " ------------- 1 ", p.getLinkState(boxId, 1) # print " ------------- 2 ", p.getLinkState(boxId, 2) # print " ------------- 3 ", p.getLinkState(boxId, 3) # print " ------------- 4 ", p.getLinkState(boxId, 4) # print " ------------- 5 ", p.getLinkState(boxId, 5) # print " ------------- 6 ", p.getLinkState(boxId, 6) #multiplyTransforms #print "------- p.getLinkState():", p.getLinkState(boxId, 0) #print "------- p.getDynamicsInfo:", p.getDynamicsInfo(boxId, -1) #cubePos, cubeOrn = p.getBasePositionAndOrientation(boxId) linkStateFull = p.getLinkState(boxId, linkId) cubePos, cubeOrn = linkStateFull[4], linkStateFull[5] #print "cubePos:", cubePos, cubeOrn # dist = math.sqrt((cubePos[0] - prevCubePos[0])**2 + # (cubePos[1] - prevCubePos[1])**2 + # (cubePos[2] - prevCubePos[2])**2) dist = math.sqrt((cubePos[2] - prevCubePos[2])**2) # only z q0 = pyquaternion.Quaternion(cubeOrn) q1 = pyquaternion.Quaternion(prevCubeOrn) quat_dist = pyquaternion.Quaternion.absolute_distance(q0, q1) #print "dist:{:.8f}".format(dist), "quat_dist:{:.6f}".format(quat_dist) prevCubePos, prevCubeOrn = cubePos, cubeOrn if i > 10 and (dist <= 0.00001 and quat_dist <= 0.0001): print "breaking at step:", i, dist, quat_dist break #time.sleep(1./360.) # faster #time.sleep(1. / 120.) # slower time.sleep(1. / 720.) # fast # # bv = p.getBaseVelocity(boxId) # # print "base_vel:", bv # # bv = (0.0, 0.0, bv[0][2] + 0.5, bv[1][0], bv[1][1], bv[1][2]) # # p.resetBaseVelocity(boxId, bv) end_time = datetime.datetime.now() delta = end_time - start_time delta_millis = int(delta.total_seconds() * 1000) # milliseconds print "total time millis:{}".format(delta_millis) p.removeBody(boxId) print "euler from quat:", p.getEulerFromQuaternion(prevCubeOrn) print "q1.vector:", q1.vector print "q1.degrees:", q1.degrees #R = q1.rotation_matrix R = Rxyz( p.getEulerFromQuaternion(prevCubeOrn)[0], p.getEulerFromQuaternion(prevCubeOrn)[1], p.getEulerFromQuaternion(prevCubeOrn)[2]) # , order="YZX" # PLOT POLYGON print "R:", R xf = np.array([1, 0, 0]) yf = np.array([0, 1, 0]) zf = np.array([0, 0, 1]) zf_l = np.dot(R, zf) print "q1R.vector:", (zf_l[0], zf_l[1], zf_l[2]) print "pos:", prevCubePos, "orn:", prevCubeOrn dx = 0.212 # distancia entre p1 e p2 = distancia entre p2 e p3 ... dy = 0.33 # distancia entre p6 e p1 = distancia entre p4 e p3 dy_m = 0.425 # distancia entre p5 e p2 - rodas mais afastadas poly = np.array([[dx, -(dy / 2), 0], [0, -(dy_m / 2), 0], [-dx, -(dy / 2), 0], [-dx, (dy / 2), 0], [0, (dy_m / 2), 0], [dx, (dy / 2), 0]]) fig = pyplot.figure() # figsize=pyplot.figaspect(0.5)*1.1 # ax = fig.axes(projection="3d") ax = Axes3D(fig) local_poly = np.dot(poly, R.T) ax.scatter(local_poly[:, 0], local_poly[:, 1], local_poly[:, 2], zdir='z', c='b') stability_poly_tuples = list([map(list, local_poly)]) collection = Poly3DCollection(list(stability_poly_tuples), linewidths=0.5, alpha=0.7, edgecolors='blue') face_color = [0.5, 0.5, 1] # alternative: matplotlib.colors.rgb2hex([0.5, 0.5, 1]) collection.set_facecolor(face_color) ax.add_collection3d(collection) cz = np.mean(local_poly[:, 2]) # mean of z values # center = np.array([origin[0], origin[1], cz + 0.2]) xf = np.array([1, 0, 0]) yf = np.array([0, 1, 0]) zf = np.array([0, 0, 1]) xf_l = np.dot(R, xf) yf_l = np.dot(R, yf) zf_l = np.dot(R, zf) ax.quiver(0, 0, cz, zf_l[0], zf_l[1], zf_l[2], length=0.2, pivot='tail', linestyle="-", color='blue') # z def axisEqual3D(ax): extents = np.array( [getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:, 1] - extents[:, 0] centers = np.mean(extents, axis=1) maxsize = max(abs(sz)) r = maxsize / 2 for ctr, dim in zip(centers, 'xyz'): getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r) axisEqual3D(ax) # scaling = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']); # ax.auto_scale_xyz(*[[np.min(scaling), np.max(scaling)]] * 3) pyplot.show() return prevCubePos, prevCubeOrn
# Plot the different input points using 3D scatter plotting b = ax.scatter(X_train.values[:, 0], X_train.values[:, 1], X_train.values[:, 2], c='black') c = ax.scatter(X_test.values[:, 0], X_test.values[:, 1], X_test.values[:, 2], c='gold',) # Plot the separating hyperplane by recreating the isosurface for the distance # == 0 level in the distance grid computed through the decision function of the # SVM. This is done using the marching cubes algorithm implementation from # scikit-image. verts, faces = measure.marching_cubes_classic(Z, 0) # Scale and transform to actual size of the interesting volume verts = verts * \ [X_MAX - X_MIN, Y_MAX - Y_MIN, Z_MAX - Z_MIN] / SPACE_SAMPLING_POINTS verts = verts + [X_MIN, Y_MIN, Z_MIN] # and create a mesh to display mesh = Poly3DCollection(verts[faces], facecolor='orange', edgecolor='grey', alpha=0.3) ax.add_collection3d(mesh) # Some presentation tweaks ax.set_xlim((X_MIN, X_MAX)) ax.set_ylim((Y_MIN, Y_MAX)) ax.set_zlim((Z_MIN, Z_MAX)) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.legend([mpatches.Patch(color='orange', alpha=0.3), b, c], ["learned frontier", "training observations", "new abnormal observations"], loc="lower left", prop=matplotlib.font_manager.FontProperties(size=11)) ax.set_title(
def draw_original(self, instance, azim=None, elev=None, boundary=False, center_nodes=False, faces=True): """ Function used to draw a voronoi problem instance. This is the standard matplotlib visualization. You can choose if you want to draw the boundaries, center nodes and faces. Currently 22 different cells can be drawn. If you want more, extend the colors list at the beginning of this function. :param instance: The voronoi problem instance :param azim: Parameter for the view_init function of matplotlib :param elev: Parameter for the view_init function of matplotlib :param boundary: Whether to draw boundaries or not :param center_nodes: Whether to draw center nodes of the voronoi cells (subcell centers will be drawn also) :param faces: Whether to draw cell faces or not """ colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000' ] fig = plt.figure() ax = fig.add_subplot(111, projection="3d") for c_idx, cell in enumerate(instance): if boundary: # draw boundaries for v_start_idx, adj_idxs in enumerate(cell["adjacency"]): for v_end_idx in adj_idxs: line = np.append([cell["vertices"][v_start_idx]], [cell["vertices"][v_end_idx]], axis=0) ax.plot(line[:, 0], line[:, 1], line[:, 2], c="#000000", ls="-", lw=1.) if center_nodes: # draw center node assert len(instance) <= len(colors) if len(cell["original"].shape) == 1: center = np.array([cell["original"]]) else: center = cell["original"] ax.scatter(center[:, 0], center[:, 1], center[:, 2], c=colors[c_idx]) if faces: # draw faces assert len(instance) <= len(colors) for face_dict in cell["faces"]: points = np.array([[ cell["vertices"][v_idx] for v_idx in face_dict["vertices"] ]]) ax.add_collection3d( Poly3DCollection(points, alpha=.2, fc=colors[c_idx])) # axis labels ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") # set view ax.view_init(azim=azim, elev=elev) plt.show()
ax.set_ylabel("y") ax.set_zlabel("z") ax.set_xlim(0, 1.25 * 2) ax.set_ylim(0 - 0.25, 0.25) ax.set_zlim(0 - 0.25, 0.25) ### End setting up the plot ### elements = [] for index, element_points in enumerate(s4r_elements[:, 1:]): if index % 6 != 0: continue elements.append(tuple(map(tuple, points[element_points - 1, 1:]))) ax.add_collection3d(Poly3DCollection(elements)) # assembly_nodes indices [4, 15) # 4 and 14: load = -0.737 # [3, 13]: load = -1.474 ax.quiver(*np.split(assembly_nodes[4:15, 1:].T, 3), [0] * 11, [-0.737] + [-1.474] * 9 + [-0.737], [0] * 11, length=0.05, normalize=False, pivot='tip', color='red') ax.quiver(*np.split(assembly_nodes[3, 1:].T, 3), [0], [0], [-97.4], length=0.005, normalize=False, pivot='tip',
images = np.array(images) # Generate a level set about zero of two identical ellipsoids in 3D # ellip_base = ellipsoid(6, 10, 16, levelset=True) # ellip_double = np.concatenate((ellip_base[:-1, ...], # ellip_base[2:, ...]), axis=0) # Use marching cubes to obtain the surface mesh of these ellipsoids verts, faces, _, _ = measure.marching_cubes_lewiner(images, 0) # Display resulting triangular mesh using Matplotlib. This can also be done # with mayavi (see skimage.measure.marching_cubes_lewiner docstring). fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') # Fancy indexing: `verts[faces]` to generate a collection of triangles mesh = Poly3DCollection(verts[faces]) mesh.set_edgecolor('k') ax.add_collection3d(mesh) ax.set_xlabel("x-axis: a = 6 per ellipsoid") ax.set_ylabel("y-axis: b = 10") ax.set_zlabel("z-axis: c = 16") ax.set_xlim(0, 24) # a = 6 (times two for 2nd ellipsoid) ax.set_ylim(0, 20) # b = 10 ax.set_zlim(0, 32) # c = 16 plt.tight_layout() plt.show()
def plotBoardLocations(self, X, Y, R, t, n_disp_img=1e5): # Expects X, U, R, t to be lists of arrays, just like u_meas, v_meas ind_corners = [ 0, self.n_corners_x - 1, self.n_corners_x * self.n_corners_y - 1, self.n_corners_x * (self.n_corners_y - 1), ] s_cam = 0.02 d_cam = 0.05 xyz_cam = [[0, -s_cam, s_cam, s_cam, -s_cam], [0, -s_cam, -s_cam, s_cam, s_cam], [0, -d_cam, -d_cam, -d_cam, -d_cam]] ind_cam = [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1]] verts_cam = [] for i in range(len(ind_cam)): verts_cam.append([ zip([xyz_cam[0][j] for j in ind_cam[i]], [xyz_cam[1][j] for j in ind_cam[i]], [xyz_cam[2][j] for j in ind_cam[i]]) ]) fig = plt.figure('Estimated Chessboard Locations', figsize=(12, 5)) axim = fig.add_subplot(121) ax3d = fig.add_subplot(122, projection='3d') boards = [] verts = [] for p in range(self.n_chessboards): M = [] W = np.column_stack((R[p], t[p])) for i in range(4): M_tld = W.dot( np.array( [X[p][ind_corners[i]], Y[p][ind_corners[i]], 0, 1])) if np.sign(M_tld[2]) == 1: Rz = np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) M_tld = Rz.dot(M_tld) M_tld[2] *= -1 M.append(M_tld[0:3]) M = (np.array(M).T).tolist() verts.append([zip(M[0], M[1], M[2])]) boards.append(Poly3DCollection(verts[p])) for i, file in enumerate(sorted(os.listdir(self.cal_img_path))): if i < n_disp_img: img = cv2.imread(self.cal_img_path + '/' + file, 0) axim.imshow(img, cmap='gray') axim.axis('off') ax3d.clear() for j in range(len(ind_cam)): cam = Poly3DCollection(verts_cam[j]) cam.set_alpha(0.2) cam.set_color('green') ax3d.add_collection3d(cam) for p in range(self.n_chessboards): if p == i: boards[p].set_alpha(1.0) boards[p].set_color('blue') else: boards[p].set_alpha(0.1) boards[p].set_color('red') ax3d.add_collection3d(boards[p]) ax3d.text(verts[p][0][0][0], verts[p][0][0][1], verts[p][0][0][2], '{0}'.format(p + 1)) plt.show(block=False) view_max = 0.2 ax3d.set_xlim(-view_max, view_max) ax3d.set_ylim(-view_max, view_max) ax3d.set_zlim(-2 * view_max, 0) ax3d.set_xlabel('X axis') ax3d.set_ylabel('Y axis') ax3d.set_zlabel('Z axis') if i == 0: ax3d.view_init(azim=90, elev=120) plt.tight_layout() fig.canvas.set_window_title( 'Estimated Board Locations (Chessboard {0})'.format(i + 1)) plt.show(block=False) raw_input('<Hit Enter To Continue>')
def q2(cube, parallel, pyramid, tronco): # Escalas tronco = make_scale(tronco, 0.5, 0.5, 0.5) # Translaçẽs cube = make_translation(cube, 1, 1, 1) parallel = make_translation(parallel, -5, 1, 1) pyramid = make_translation(pyramid, 3, 3, 1) tronco = make_translation(tronco, -2, 3, 1) all_points = [] all_points.extend(cube.tolist()) all_points.extend(parallel.tolist()) all_points.extend(pyramid.tolist()) all_points.extend(tronco.tolist()) all_points.extend([[0, 6, 6], [0, -6, 6], [0, -6, -6], [0, 6, -6], [6, 0, 6], [-6, 0, 6], [-6, 0, -6], [6, 0, -6], [6, 6, 0], [-6, 6, 0], [-6, -6, 0], [6, -6, 0]]) points = np.array(all_points) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") # plot vertices ax.scatter3D(points[:, 0], points[:, 1], points[:, 2]) ax.add_collection3d( Poly3DCollection( get_rectangle_faces(cube), facecolors="cyan", linewidths=1, edgecolors="r", alpha=0.25, )) ax.add_collection3d( Poly3DCollection( get_triangle_faces(pyramid), facecolors="red", linewidths=1, edgecolors="r", alpha=0.25, )) ax.add_collection3d( Poly3DCollection(get_rectangle_faces(parallel), facecolors="green", linewidths=1, edgecolors="r", alpha=.25)) ax.add_collection3d( Poly3DCollection(get_rectangle_faces(tronco), facecolors="yellow", linewidths=1, edgecolors="r", alpha=.25)) ax.add_collection3d( Poly3DCollection([[[0, 6, 6], [0, -6, 6], [0, -6, -6], [0, 6, -6]], [[6, 0, 6], [-6, 0, 6], [-6, 0, -6], [6, 0, -6]], [[6, 6, 0], [-6, 6, 0], [-6, -6, 0], [6, -6, 0]]], facecolors="purple", linewidths=1, edgecolors="w", alpha=.25)) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") plt.show() return cube, parallel, pyramid, tronco
def plot_arc3d(vector1, vector2, radius=0.2, fig=None, colour='C0', vector_colors=[], vector_labels=[], arc_label="", arrow_kwargs={}): """ Plot arc between two given vectors in 3D space. """ """ Confirm correct input arguments """ assert len(vector1) == 3 assert len(vector2) == 3 """ Calculate vector between two vector end points, and the resulting spherical angles for various points along this vector. From this, derive points that lie along the arc between vector1 and vector2 """ v = [i - j for i, j in zip(vector1, vector2)] v_points_direct = [(vector2[0] + v[0] * l, vector2[1] + v[1] * l, vector2[2] + v[2] * l) for l in np.linspace(0, 1)] v_phis = [ math.atan2(v_point[1], v_point[0]) for v_point in v_points_direct ] v_thetas = [ math.acos(v_point[2] / np.linalg.norm(v_point)) for v_point in v_points_direct ] v_points_arc = [(radius * sin(theta) * cos(phi), radius * sin(theta) * sin(phi), radius * cos(theta)) for theta, phi in zip(v_thetas, v_phis)] v_points_arc.append((0, 0, 0)) if fig is None: fig = plt.figure() ax = fig.add_subplot(111, projection='3d', frame_on=True) ax.set_xlim(0, 0.8) ax.set_ylim(0, 0.8) ax.set_zlim(0, 0.8) else: ax = fig.gca() points_collection = Poly3DCollection([v_points_arc], alpha=0.4) points_collection.set_facecolor(colour) ax.add_collection3d(points_collection) if len(vector_labels) == len(vector_colors) == 2: for v, label, col, kwg in zip([vector1, vector2], vector_labels, vector_colors, arrow_kwargs): ax.annotate3D(label, v, xytext=(3, 3), textcoords='offset points', color=col) if kwg.get("mutation_scale", None) is None: kwg['mutation_scale'] = 10 ax.arrow3D(0, 0, 0, v[0], v[1], v[2], color=col, **kwg) point_id = int(len(v_points_arc) / 2) ax.annotate3D(arc_label, v_points_arc[point_id], xytext=(0, 0), textcoords='offset points', color=colour) if arc_label: legend_label = f"{arc_label} = {np.arccos(np.dot(vector1, vector2) / (np.linalg.norm(vector1)* np.linalg.norm(vector2))) / np.pi : 0.2f} $\pi$" print(legend_label) ax.plot([], [], color=colour, label=legend_label) return fig
def plot_state_city(rho, title="", figsize=None, color=None, alpha=1): """Plot the cityscape of quantum state. Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho. Args: rho (ndarray): Numpy array for state vector or density matrix. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list): A list of len=2 giving colors for real and imaginary components of matrix elements. alpha (float): Transparency value for bars Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. ValueError: When 'color' is not a list of len=2. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) num = int(np.log2(len(rho))) # get the real and imag parts of rho datareal = np.real(rho) dataimag = np.imag(rho) # get the labels column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) xpos = np.arange(0, lx, 1) # Set up a mesh of positions ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx * ly) dx = 0.5 * np.ones_like(zpos) # width of bars dy = dx.copy() dzr = datareal.flatten() dzi = dataimag.flatten() if color is None: color = ["#648fff", "#648fff"] else: if len(color) != 2: raise ValueError("'color' must be a list of len=2.") if color[0] is None: color[0] = "#648fff" if color[1] is None: color[1] = "#648fff" # set default figure size if figsize is None: figsize = (15, 5) fig = plt.figure(figsize=figsize) ax1 = fig.add_subplot(1, 2, 1, projection='3d') x = [0, max(xpos) + 0.5, max(xpos) + 0.5, 0] y = [0, 0, max(ypos) + 0.5, max(ypos) + 0.5] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0]) for idx, cur_zpos in enumerate(zpos): if dzr[idx] > 0: zorder = 2 else: zorder = 0 b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzr[idx], alpha=alpha, zorder=zorder) b1.set_facecolors(fc1[6 * idx:6 * idx + 6]) pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k', linewidths=1, zorder=1) if min(dzr) < 0 < max(dzr): ax1.add_collection3d(pc1) ax2 = fig.add_subplot(1, 2, 2, projection='3d') fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1]) for idx, cur_zpos in enumerate(zpos): if dzi[idx] > 0: zorder = 2 else: zorder = 0 b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzi[idx], alpha=alpha, zorder=zorder) b2.set_facecolors(fc2[6 * idx:6 * idx + 6]) pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k', linewidths=1, zorder=1) if min(dzi) < 0 < max(dzi): ax2.add_collection3d(pc2) ax1.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax1.set_yticks(np.arange(0.5, ly + 0.5, 1)) max_dzr = max(dzr) min_dzr = min(dzr) if max_dzr != min_dzr: ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr) + 1e-9) else: if min_dzr == 0: ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr) + 1e-9) else: ax1.axes.set_zlim3d(auto=True) ax1.zaxis.set_major_locator(MaxNLocator(5)) ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45) ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5) ax1.set_zlabel("Real[rho]", fontsize=14) for tick in ax1.zaxis.get_major_ticks(): tick.label.set_fontsize(14) ax2.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax2.set_yticks(np.arange(0.5, ly + 0.5, 1)) min_dzi = np.min(dzi) max_dzi = np.max(dzi) if min_dzi != max_dzi: eps = 0 ax2.zaxis.set_major_locator(MaxNLocator(5)) ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi) + eps) else: if min_dzi == 0: ax2.set_zticks([0]) eps = 1e-9 ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi) + eps) else: ax2.axes.set_zlim3d(auto=True) ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45) ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5) ax2.set_zlabel("Imag[rho]", fontsize=14) for tick in ax2.zaxis.get_major_ticks(): tick.label.set_fontsize(14) plt.suptitle(title, fontsize=16) plt.tight_layout() if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(fig) return fig
def plot_vehicle(vehicle, save_figure=False, plot_control_points=True, save_filename="Vehicle_Geometry"): """This plots vortex lattice panels created when Fidelity Zero Aerodynamics Routine is initialized Assumptions: None Source: None Inputs: vehicle Outputs: Plots Properties Used: N/A """ # unpack vortex distribution VD = vehicle.vortex_distribution face_color = 'grey' edge_color = 'grey' alpha_val = 0.5 # initalize figure fig = plt.figure(save_filename) fig.set_size_inches(8, 8) axes = Axes3D(fig) axes.view_init(elev=30, azim=210) n_cp = VD.n_cp for i in range(n_cp): X = [VD.XA1[i], VD.XB1[i], VD.XB2[i], VD.XA2[i]] Y = [VD.YA1[i], VD.YB1[i], VD.YB2[i], VD.YA2[i]] Z = [VD.ZA1[i], VD.ZB1[i], VD.ZB2[i], VD.ZA2[i]] verts = [list(zip(X, Y, Z))] collection = Poly3DCollection(verts) collection.set_facecolor(face_color) collection.set_edgecolor(edge_color) collection.set_alpha(alpha_val) axes.add_collection3d(collection) max_range = np.array([ VD.X.max() - VD.X.min(), VD.Y.max() - VD.Y.min(), VD.Z.max() - VD.Z.min() ]).max() / 2.0 mid_x = (VD.X.max() + VD.X.min()) * 0.5 mid_y = (VD.Y.max() + VD.Y.min()) * 0.5 mid_z = (VD.Z.max() + VD.Z.min()) * 0.5 axes.set_xlim(mid_x - max_range, mid_x + max_range) axes.set_ylim(mid_y - max_range, mid_y + max_range) axes.set_zlim(mid_z - max_range, mid_z + max_range) if plot_control_points: axes.scatter(VD.XC, VD.YC, VD.ZC, c='r', marker='o') if 'Wake' in VD: face_color = 'white' edge_color = 'blue' alpha = 0.5 num_prop = len(VD.Wake.XA1[:, 0, 0, 0]) nts = len(VD.Wake.XA1[0, :, 0, 0]) num_B = len(VD.Wake.XA1[0, 0, :, 0]) dim_R = len(VD.Wake.XA1[0, 0, 0, :]) for p_idx in range(num_prop): for t_idx in range(nts): for B_idx in range(num_B): for loc in range(dim_R): X = [ VD.Wake.XA1[p_idx, t_idx, B_idx, loc], VD.Wake.XB1[p_idx, t_idx, B_idx, loc], VD.Wake.XB2[p_idx, t_idx, B_idx, loc], VD.Wake.XA2[p_idx, t_idx, B_idx, loc] ] Y = [ VD.Wake.YA1[p_idx, t_idx, B_idx, loc], VD.Wake.YB1[p_idx, t_idx, B_idx, loc], VD.Wake.YB2[p_idx, t_idx, B_idx, loc], VD.Wake.YA2[p_idx, t_idx, B_idx, loc] ] Z = [ VD.Wake.ZA1[p_idx, t_idx, B_idx, loc], VD.Wake.ZB1[p_idx, t_idx, B_idx, loc], VD.Wake.ZB2[p_idx, t_idx, B_idx, loc], VD.Wake.ZA2[p_idx, t_idx, B_idx, loc] ] verts = [list(zip(X, Y, Z))] collection = Poly3DCollection(verts) collection.set_facecolor(face_color) collection.set_edgecolor(edge_color) collection.set_alpha(alpha) axes.add_collection3d(collection) if np.all(VD.FUS_SURF_PTS) != None: face_color = 'grey' edge_color = 'black' alpha = 1 num_fus_segs = len(VD.FUS_SURF_PTS[:, 0, 0]) tesselation = len(VD.FUS_SURF_PTS[0, :, 0]) for i_seg in range(num_fus_segs - 1): for i_tes in range(tesselation - 1): X = [ VD.FUS_SURF_PTS[i_seg, i_tes, 0], VD.FUS_SURF_PTS[i_seg, i_tes + 1, 0], VD.FUS_SURF_PTS[i_seg + 1, i_tes + 1, 0], VD.FUS_SURF_PTS[i_seg + 1, i_tes, 0] ] Y = [ VD.FUS_SURF_PTS[i_seg, i_tes, 1], VD.FUS_SURF_PTS[i_seg, i_tes + 1, 1], VD.FUS_SURF_PTS[i_seg + 1, i_tes + 1, 1], VD.FUS_SURF_PTS[i_seg + 1, i_tes, 1] ] Z = [ VD.FUS_SURF_PTS[i_seg, i_tes, 2], VD.FUS_SURF_PTS[i_seg, i_tes + 1, 2], VD.FUS_SURF_PTS[i_seg + 1, i_tes + 1, 2], VD.FUS_SURF_PTS[i_seg + 1, i_tes, 2] ] verts = [list(zip(X, Y, Z))] collection = Poly3DCollection(verts) collection.set_facecolor(face_color) collection.set_edgecolor(edge_color) collection.set_alpha(alpha) axes.add_collection3d(collection) for propulsor in vehicle.propulsors: if ('propeller' in propulsor.keys()) or ('rotor' in propulsor.keys()): try: prop = propulsor.propeller except: prop = propulsor.rotor # ------------------------------------------------------------------------ # Generate Propeller Geoemtry # ------------------------------------------------------------------------ # unpack Rt = prop.tip_radius Rh = prop.hub_radius num_B = prop.number_blades a_sec = prop.airfoil_geometry a_secl = prop.airfoil_polar_stations beta = prop.twist_distribution b = prop.chord_distribution r = prop.radius_distribution MCA = prop.mid_chord_aligment t = prop.max_thickness_distribution ta = -propulsor.thrust_angle n_points = 10 af_pts = (2 * n_points) - 1 dim = len(b) num_props = len(prop.origin) theta = np.linspace(0, 2 * np.pi, num_B + 1)[:-1] # create empty arrays for storing geometry G = Data() G.XA1 = np.zeros((dim - 1, af_pts)) G.YA1 = np.zeros_like(G.XA1) G.ZA1 = np.zeros_like(G.XA1) G.XA2 = np.zeros_like(G.XA1) G.YA2 = np.zeros_like(G.XA1) G.ZA2 = np.zeros_like(G.XA1) G.XB1 = np.zeros_like(G.XA1) G.YB1 = np.zeros_like(G.XA1) G.ZB1 = np.zeros_like(G.XA1) G.XB2 = np.zeros_like(G.XA1) G.YB2 = np.zeros_like(G.XA1) G.ZB2 = np.zeros_like(G.XA1) for n_p in range(num_props): rot = prop.rotation[n_p] a_o = 0 flip_1 = (np.pi / 2) flip_2 = (np.pi / 2) for i in range(num_B): # get airfoil coordinate geometry airfoil_data = import_airfoil_geometry(a_sec, npoints=n_points) # store points of airfoil in similar format as Vortex Points (i.e. in vertices) for j in range(dim - 1): # loop through each radial station # -------------------------------------------- # INNER SECTION # -------------------------------------------- # INNER SECTION POINTS ixpts = airfoil_data.x_coordinates[a_secl[j]] izpts = airfoil_data.y_coordinates[a_secl[j]] iba_max_t = airfoil_data.thickness_to_chord[a_secl[j]] iba_xp = rot * (-MCA[j] + ixpts * b[j] ) # x coord of airfoil iba_yp = r[j] * np.ones_like(iba_xp) # radial location iba_zp = izpts * (t[j] / iba_max_t ) # former airfoil y coord iba_matrix = np.zeros((len(iba_zp), 3)) iba_matrix[:, 0] = iba_xp iba_matrix[:, 1] = iba_yp iba_matrix[:, 2] = iba_zp # ROTATION MATRICES FOR INNER SECTION # rotation about y axis to create twist and position blade upright iba_trans_1 = [[ np.cos(rot * flip_1 - rot * beta[j]), 0, -np.sin(rot * flip_1 - rot * beta[j]) ], [0, 1, 0], [ np.sin(rot * flip_1 - rot * beta[j]), 0, np.cos(rot * flip_1 - rot * beta[j]) ]] # rotation about x axis to create azimuth locations iba_trans_2 = [ [1, 0, 0], [ 0, np.cos(theta[i] + rot * a_o + flip_2), np.sin(theta[i] + rot * a_o + flip_2) ], [ 0, np.sin(theta[i] + rot * a_o + flip_2), np.cos(theta[i] + rot * a_o + flip_2) ] ] # roation about y to orient propeller/rotor to thrust angle iba_trans_3 = [[np.cos(ta), 0, -np.sin(ta)], [0, 1, 0], [np.sin(ta), 0, np.cos(ta)]] iba_trans = np.matmul( iba_trans_3, np.matmul(iba_trans_2, iba_trans_1)) irot_mat = np.repeat(iba_trans[np.newaxis, :, :], len(iba_yp), axis=0) # -------------------------------------------- # OUTER SECTION # -------------------------------------------- # OUTER SECTION POINTS oxpts = airfoil_data.x_coordinates[a_secl[j + 1]] ozpts = airfoil_data.y_coordinates[a_secl[j + 1]] oba_max_t = airfoil_data.thickness_to_chord[a_secl[j + 1]] oba_xp = -MCA[j + 1] + oxpts * b[ j + 1] # x coord of airfoil oba_yp = r[j + 1] * np.ones_like( oba_xp) # radial location oba_zp = ozpts * (t[j + 1] / oba_max_t ) # former airfoil y coord oba_matrix = np.zeros((len(oba_zp), 3)) oba_matrix[:, 0] = oba_xp oba_matrix[:, 1] = oba_yp oba_matrix[:, 2] = oba_zp # ROTATION MATRICES FOR OUTER SECTION # rotation about y axis to create twist and position blade upright oba_trans_1 = [ [ np.cos(rot * flip_1 - rot * beta[j + 1]), 0, -np.sin(rot * flip_1 - rot * beta[j + 1]) ], [0, 1, 0], [ np.sin(rot * flip_1 - rot * beta[j + 1]), 0, np.cos(rot * flip_1 - rot * beta[j + 1]) ] ] # rotation about x axis to create azimuth locations oba_trans_2 = [ [1, 0, 0], [ 0, np.cos(theta[i] + rot * a_o + flip_2), np.sin(theta[i] + rot * a_o + flip_2) ], [ 0, np.sin(theta[i] + rot * a_o + flip_2), np.cos(theta[i] + rot * a_o + flip_2) ] ] # roation about y to orient propeller/rotor to thrust angle oba_trans_3 = [[np.cos(ta), 0, -np.sin(ta)], [0, 1, 0], [np.sin(ta), 0, np.cos(ta)]] oba_trans = np.matmul( oba_trans_3, np.matmul(oba_trans_2, oba_trans_1)) orot_mat = np.repeat(oba_trans[np.newaxis, :, :], len(oba_yp), axis=0) # --------------------------------------------------------------------------------------------- # ROTATE POINTS iba_mat = orientation_product(irot_mat, iba_matrix) oba_mat = orientation_product(orot_mat, oba_matrix) # --------------------------------------------------------------------------------------------- # store points G.XA1[j, :] = iba_mat[:-1, 0] + prop.origin[n_p][0] G.YA1[j, :] = iba_mat[:-1, 1] + prop.origin[n_p][1] G.ZA1[j, :] = iba_mat[:-1, 2] + prop.origin[n_p][2] G.XA2[j, :] = iba_mat[1:, 0] + prop.origin[n_p][0] G.YA2[j, :] = iba_mat[1:, 1] + prop.origin[n_p][1] G.ZA2[j, :] = iba_mat[1:, 2] + prop.origin[n_p][2] G.XB1[j, :] = oba_mat[:-1, 0] + prop.origin[n_p][0] G.YB1[j, :] = oba_mat[:-1, 1] + prop.origin[n_p][1] G.ZB1[j, :] = oba_mat[:-1, 2] + prop.origin[n_p][2] G.XB2[j, :] = oba_mat[1:, 0] + prop.origin[n_p][0] G.YB2[j, :] = oba_mat[1:, 1] + prop.origin[n_p][1] G.ZB2[j, :] = oba_mat[1:, 2] + prop.origin[n_p][2] # ------------------------------------------------------------------------ # Plot Propeller Blade # ------------------------------------------------------------------------ prop_face_color = 'red' prop_edge_color = 'red' prop_alpha = 1 for sec in range(dim - 1): for loc in range(af_pts): X = [ G.XA1[sec, loc], G.XB1[sec, loc], G.XB2[sec, loc], G.XA2[sec, loc] ] Y = [ G.YA1[sec, loc], G.YB1[sec, loc], G.YB2[sec, loc], G.YA2[sec, loc] ] Z = [ G.ZA1[sec, loc], G.ZB1[sec, loc], G.ZB2[sec, loc], G.ZA2[sec, loc] ] prop_verts = [list(zip(X, Y, Z))] prop_collection = Poly3DCollection(prop_verts) prop_collection.set_facecolor(prop_face_color) prop_collection.set_edgecolor(prop_edge_color) prop_collection.set_alpha(prop_alpha) axes.add_collection3d(prop_collection) plt.axis('off') plt.grid(None) return
def plot_state_city(state, title="", figsize=None, color=None, alpha=1, ax_real=None, ax_imag=None, *, rho=None): """Plot the cityscape of quantum state. Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list): A list of len=2 giving colors for real and imaginary components of matrix elements. alpha (float): Transparency value for bars ax_real (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. If this is specified without an ax_real only the imaginary component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. Returns: matplotlib.Figure: The matplotlib.Figure of the visualization if the ``ax_real`` and ``ax_imag`` kwargs are not set Raises: MissingOptionalLibraryError: Requires matplotlib. ValueError: When 'color' is not a list of len=2. VisualizationError: if input is not a valid N-qubit state. Example: .. jupyter-execute:: from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city %matplotlib inline qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix.from_instruction(qc) plot_state_city(state, color=['midnightblue', 'midnightblue'], title="New State City") """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_state_city", pip_install="pip install matplotlib", ) from matplotlib import get_backend from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") # get the real and imag parts of rho datareal = np.real(rho.data) dataimag = np.imag(rho.data) # get the labels column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) xpos = np.arange(0, lx, 1) # Set up a mesh of positions ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx * ly) dx = 0.5 * np.ones_like(zpos) # width of bars dy = dx.copy() dzr = datareal.flatten() dzi = dataimag.flatten() if color is None: color = ["#648fff", "#648fff"] else: if len(color) != 2: raise ValueError("'color' must be a list of len=2.") if color[0] is None: color[0] = "#648fff" if color[1] is None: color[1] = "#648fff" if ax_real is None and ax_imag is None: # set default figure size if figsize is None: figsize = (15, 5) fig = plt.figure(figsize=figsize) ax1 = fig.add_subplot(1, 2, 1, projection="3d") ax2 = fig.add_subplot(1, 2, 2, projection="3d") elif ax_real is not None: fig = ax_real.get_figure() ax1 = ax_real ax2 = ax_imag else: fig = ax_imag.get_figure() ax1 = None ax2 = ax_imag max_dzr = max(dzr) min_dzr = min(dzr) min_dzi = np.min(dzi) max_dzi = np.max(dzi) if ax1 is not None: fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0]) for idx, cur_zpos in enumerate(zpos): if dzr[idx] > 0: zorder = 2 else: zorder = 0 b1 = ax1.bar3d( xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzr[idx], alpha=alpha, zorder=zorder, ) b1.set_facecolors(fc1[6 * idx:6 * idx + 6]) xlim, ylim = ax1.get_xlim(), ax1.get_ylim() x = [xlim[0], xlim[1], xlim[1], xlim[0]] y = [ylim[0], ylim[0], ylim[1], ylim[1]] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] pc1 = Poly3DCollection(verts, alpha=0.15, facecolor="k", linewidths=1, zorder=1) if min(dzr) < 0 < max(dzr): ax1.add_collection3d(pc1) ax1.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax1.set_yticks(np.arange(0.5, ly + 0.5, 1)) if max_dzr != min_dzr: ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi)) else: if min_dzr == 0: ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, np.max(dzi))) else: ax1.axes.set_zlim3d(auto=True) ax1.get_autoscalez_on() ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top") ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center") ax1.set_zlabel("Re[$\\rho$]", fontsize=14) for tick in ax1.zaxis.get_major_ticks(): tick.label.set_fontsize(14) if ax2 is not None: fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1]) for idx, cur_zpos in enumerate(zpos): if dzi[idx] > 0: zorder = 2 else: zorder = 0 b2 = ax2.bar3d( xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzi[idx], alpha=alpha, zorder=zorder, ) b2.set_facecolors(fc2[6 * idx:6 * idx + 6]) xlim, ylim = ax2.get_xlim(), ax2.get_ylim() x = [xlim[0], xlim[1], xlim[1], xlim[0]] y = [ylim[0], ylim[0], ylim[1], ylim[1]] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] pc2 = Poly3DCollection(verts, alpha=0.2, facecolor="k", linewidths=1, zorder=1) if min(dzi) < 0 < max(dzi): ax2.add_collection3d(pc2) ax2.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax2.set_yticks(np.arange(0.5, ly + 0.5, 1)) if min_dzi != max_dzi: eps = 0 ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps)) else: if min_dzi == 0: ax2.set_zticks([0]) eps = 1e-9 ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps)) else: ax2.axes.set_zlim3d(auto=True) ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top") ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center") ax2.set_zlabel("Im[$\\rho$]", fontsize=14) for tick in ax2.zaxis.get_major_ticks(): tick.label.set_fontsize(14) ax2.get_autoscalez_on() fig.suptitle(title, fontsize=16) if ax_real is None and ax_imag is None: if get_backend() in [ "module://ipykernel.pylab.backend_inline", "nbAgg" ]: plt.close(fig) return fig
def draw_3D_matching_complex(M_G, fill=[], k=None, iterations=100, make_video=False, vid_elevation=10, vid_path=None): """ Draws the given matching complex in 3 dimensions, filling in any faces (e.g. triangles/tetrahedron). Uses the spring-force algorithm to determine the location of nodes. @params M_G : matching complex; iterable of 2-tuples specifying each edge in the complex fill : tuples of vertices specifying a face to be colored. For example, (1,2,3) specifies coloring in the face made by vertices 1,2,3 (and the corresponding edges between them). k : optimal distance for nodes to be in graph. Allows you to adjust how far apart nodes are in drawing iterations : number of iterations to run stochastic spring-force algorithm for make_video : makes a video spinning simplicial complex around. vid_elevation : elevation of viewpoint when making video. vid_path : filepath to save video at @returns fig : returns matplotlib figure. """ pos = nx.spring_layout(M_G, dim=3, k=k, iterations=iterations, weight="weight") fig = plt.figure() ax = fig.add_subplot('111', projection='3d') tetra_verts = [] tri_verts = [] for V in fill: verts = [tuple(pos[v]) for v in V] if len(verts) == 3: #triangle tri_verts.append(verts) elif len(verts) == 4: # tetrahedron for v1, v2, v3 in itl.combinations(verts, 3): tetra_verts.append((v1, v2, v3)) poly = Poly3DCollection(tri_verts, linewidth=1, alpha=0.2) poly.set_facecolor('g') ax.add_collection3d(poly) poly = Poly3DCollection(tetra_verts, linewidth=1, alpha=0.2) poly.set_facecolor('b') ax.add_collection3d(poly) for key in pos: point = pos[key] ax.scatter(point[0], point[1], point[2], s=120, c='r', alpha=0.4, edgecolor='k') ax.text(point[0], point[1], point[2], key, fontsize=15 ) #horizontalalignment='center', verticalalignment='center') for e in M_G.edges(): ax.plot(xs=[pos[e[0]][0], pos[e[1]][0]], ys=[pos[e[0]][1], pos[e[1]][1]], zs=[pos[e[0]][2], pos[e[1]][2]], c='k') #### make a video out of stuff if make_video: writer = manimation.writers['ffmpeg'](fps=15) fig = plt.gcf() dpi = 200 with writer.saving(fig, vid_path, dpi): # do stuff for ii in range(0, 360, 1): ax.view_init(elev=vid_elevation, azim=ii) writer.grab_frame() #### ############# plt.show() return fig
def figure2(): def swap_zy(v): return [v[0], v[2], v[1]] fig, ax = create_plot_with_grid_3d() ax.axis("off") cube_vertices = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) cube_edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)] R = get_rotation_matrix((0, 30 * (math.pi / 180), 10 * (math.pi / 180))) t = np.array([0, 0, 3]) K = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32) world_cube_vertices = [np.dot(R, v) + t for v in cube_vertices] projected_points = [v / v[2] for v in world_cube_vertices] world_cube_vertices = [swap_zy(v) for v in world_cube_vertices] projected_points = [swap_zy(v) for v in projected_points] # draw cube edges for e_a, e_b in cube_edges: draw_line(ax, world_cube_vertices[e_a], world_cube_vertices[e_b], linestyle='-', c="black", zorder=1, linewidth=1.0) # draw projection rays for world_vertex, projected_vertex in zip(world_cube_vertices, projected_points): draw_line(ax, world_vertex, projected_vertex, linestyle='--', c="gray", zorder=0, linewidth=0.4) # draw cube edges on projection for e_a, e_b in cube_edges: draw_line(ax, projected_points[e_a], projected_points[e_b], linestyle='-', c="gray", zorder=1, linewidth=0.5) # draw rays to center of projection for projected_vertex in projected_points: draw_line(ax, (0, 0, 0), projected_vertex, linestyle=':', c="gray", zorder=-1, linewidth=0.4) plane_tri = [(-2, -2, 1), (2, -2, 1), (-2, 2, 1), (2, -2, 1), (2, 2, 1), (-2, 2, 1)] plane_tri = [swap_zy(v) for v in plane_tri] tri = Poly3DCollection(plane_tri, color='gray', linewidths=0, alpha=0.3) ax.add_collection3d(tri) ax.view_init(elev=12., azim=20.) ax.figure.savefig('./assets/Figure_2.png', transparent=False, bbox_inches='tight', pad_inches=0)
def plot3d_anim(times, states, modes, ps_list, Nz_list, skip=1, filename=None): ''' make a 3d plot of the GCAS maneuver ''' full_plot = True if filename == '': # plot to the screen filename = None skip = 20 full_plot = False elif filename.endswith('.gif'): skip = 5 else: skip = 1 # plot every frame assert len(times) == len(states) start = time.time() times = times[0::skip] states = states[0::skip] modes = modes[0::skip] ps_list = ps_list[0::skip] Nz_list = Nz_list[0::skip] fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111, projection='3d') ax.view_init(30, 45) pos_xs = [pt[9] for pt in states] pos_ys = [pt[10] for pt in states] pos_zs = [pt[11] for pt in states] trail_line, = ax.plot([], [], [], color='r', lw=1) data = loadmat('f-16.mat') f16_pts = data['V'] f16_faces = data['F'] plane_polys = Poly3DCollection([], color=None if full_plot else 'k') ax.add_collection3d(plane_polys) ax.set_xlim([min(pos_xs), max(pos_xs)]) ax.set_ylim([min(pos_ys), max(pos_xs)]) ax.set_zlim([min(pos_zs), max(pos_zs)]) ax.set_xlabel('X [ft]') ax.set_ylabel('Y [ft]') ax.set_zlabel('Altitude [ft] ') frames = len(times) # text fontsize = 14 time_text = ax.text2D(0.05, 1.07, "", transform=ax.transAxes, fontsize=fontsize) mode_text = ax.text2D(0.95, 1.07, "", transform=ax.transAxes, fontsize=fontsize, horizontalalignment='right') alt_text = ax.text2D(0.05, 1.00, "", transform=ax.transAxes, fontsize=fontsize) v_text = ax.text2D(0.95, 1.00, "", transform=ax.transAxes, fontsize=fontsize, horizontalalignment='right') alpha_text = ax.text2D(0.05, 0.93, "", transform=ax.transAxes, fontsize=fontsize) beta_text = ax.text2D(0.95, 0.93, "", transform=ax.transAxes, fontsize=fontsize, horizontalalignment='right') nz_text = ax.text2D(0.05, 0.86, "", transform=ax.transAxes, fontsize=fontsize) ps_text = ax.text2D(0.95, 0.86, "", transform=ax.transAxes, fontsize=fontsize, horizontalalignment='right') ang_text = ax.text2D(0.5, 0.79, "", transform=ax.transAxes, fontsize=fontsize, horizontalalignment='center') def anim_func(frame): 'updates for the animation frame' speed = states[frame][0] alpha = states[frame][1] beta = states[frame][2] alt = states[frame][11] phi = states[frame][3] theta = states[frame][4] psi = states[frame][5] dx = states[frame][9] dy = states[frame][10] dz = states[frame][11] time_text.set_text('t = {:.2f} sec'.format(times[frame])) mode_text.set_text('Mode: {}'.format(modes[frame])) alt_text.set_text('h = {:.2f} ft'.format(alt)) v_text.set_text('V = {:.2f} ft/sec'.format(speed)) alpha_text.set_text('$\\alpha$ = {:.2f} deg'.format(rad2deg(alpha))) beta_text.set_text('$\\beta$ = {:.2f} deg'.format(rad2deg(beta))) nz_text.set_text('$N_z$ = {:.2f} g'.format(Nz_list[frame])) ps_text.set_text('$p_s$ = {:.2f} deg/sec'.format( rad2deg(ps_list[frame]))) ang_text.set_text('[$\\phi$, $\\theta$, $\\psi$] = [{:.2f}, {:.2f}, {:.2f}] deg'.format(\ rad2deg(phi), rad2deg(theta), rad2deg(psi))) # do trail trail_len = 200 // skip start_index = max(0, frame - trail_len) trail_line.set_data(pos_xs[start_index:frame], pos_ys[start_index:frame]) trail_line.set_3d_properties(pos_zs[start_index:frame]) scale = 25 pts = scale3d(f16_pts, [-scale, scale, scale]) pts = rotate3d(pts, theta, -psi, phi) size = 1000 minx = dx - size maxx = dx + size miny = dy - size maxy = dy + size minz = dz - size maxz = dz + size ax.set_xlim([minx, maxx]) ax.set_ylim([miny, maxy]) ax.set_zlim([minz, maxz]) verts = [] fc = [] count = 0 for face in f16_faces: face_pts = [] count = count + 1 if not full_plot and count % 10 != 0: continue for index in face: face_pts.append((pts[index-1][0] + dx, \ pts[index-1][1] + dy, \ pts[index-1][2] + dz)) verts.append(face_pts) fc.append('k') # draw ground if minz <= 0 and maxz >= 0: z = 0 verts.append([(minx, miny, z), (maxx, miny, z), (maxx, maxy, z), (minx, maxy, z)]) fc.append('0.8') plane_polys.set_verts(verts) plane_polys.set_facecolors(fc) return None anim_obj = animation.FuncAnimation(fig, anim_func, frames, interval=30, \ blit=False, repeat=True) if filename is not None: if filename.endswith('.gif'): print("\nSaving animation to '{}' using 'imagemagick'...".format( filename)) anim_obj.save(filename, dpi=80, writer='imagemagick') print("Finished saving to {} in {:.1f} sec".format( filename, time.time() - start)) else: fps = 50 codec = 'libx264' print("\nSaving '{}' at {:.2f} fps using ffmpeg with codec '{}'.". format(filename, fps, codec)) # if this fails do: 'sudo apt-get install ffmpeg' try: extra_args = [] if codec is not None: extra_args += ['-vcodec', str(codec)] anim_obj.save(filename, fps=fps, extra_args=extra_args) print("Finished saving to {} in {:.1f} sec".format( filename, time.time() - start)) except AttributeError: traceback.print_exc() print( "\nSaving video file failed! Is ffmpeg installed? Can you run 'ffmpeg' in the terminal?" ) else: plt.show()
def fermi3D(procar, outcar, bands, scale=1, mode='plain', st=False, **kwargs): """ This function plots 3d fermi surface list of acceptable kwargs : plotting_package nprocess face_colors arrow_colors arrow_spin atom orbital spin """ # Initilizing the arguments : if 'plotting_package' in kwargs: plotting_package = kwargs['plotting_package'] else: plotting_package = 'mayavi' if 'nprocess' in kwargs: nprocess = kwargs['nprocess'] else: nprocess = 2 if 'face_colors' in kwargs: face_colors = kwargs['face_colors'] else: face_colors = None if 'cmap' in kwargs: cmap = kwargs['cmap'] else: cmap = 'jet' if 'atoms' in kwargs: atoms = kwargs['atoms'] else: atoms = [-1] # project all atoms if 'orbitals' in kwargs: orbitals = kwargs['orbitals'] else: orbitals = [-1] if 'spin' in kwargs: spin = kwargs['spin'] else: spin = [0] if "mask_points" in kwargs: mask_points = kwargs['mask_points'] else: mask_points = 1 if "energy" in kwargs: energy = kwargs['energy'] else: energy = 0 if "transparent" in kwargs: transparent = kwargs['transparent'] else: transparent = False if "arrow_projection" in kwargs: arrow_projection = kwargs['arrow_projection'] else: arrow_projection = 2 if plotting_package == 'mayavi': try: from mayavi import mlab from tvtk.api import tvtk except: print( "You have selected mayavi as plottin package. please install mayavi or choose a different package" ) return elif plotting_package == 'plotly': try: import plotly.plotly as py import plotly.figure_factory as ff import plotly.graph_objs as go cmap = mpl.cm.get_cmap(cmap) figs = [] except: print( "You have selected plotly as plottin package. please install plotly or choose a different package" ) return elif plotting_package == 'matplotlib': try: import matplotlib.pylab as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection except: print( "You have selected matplotlib as plotting package. please install matplotlib or choose a different package" ) return elif plotting_package == 'ipyvolume': try: import ipyvolume.pylab as ipv except: print( "You have selected ipyvolume as plotting package. please install ipyvolume or choose a different package" ) return permissive = False #get fermi from outcar outcarparser = UtilsProcar() e_fermi = outcarparser.FermiOutcar(outcar) print('Fermi=', e_fermi) e_fermi += energy #get reciprocal lattice from outcar recLat = outcarparser.RecLatOutcar(outcar) #parsing the Procar file procarFile = ProcarParser() procarFile.readFile(procar, permissive) poly = get_wigner_seitz(recLat) # plot brilliouin zone if plotting_package == 'mayavi': brillouin_point = [] brillouin_faces = [] point_count = 0 for iface in poly: single_face = [] for ipoint in iface: single_face.append(point_count) brillouin_point.append(list(ipoint)) point_count += 1 brillouin_faces.append(single_face) polydata_br = tvtk.PolyData(points=brillouin_point, polys=brillouin_faces) mlab.pipeline.surface(polydata_br, representation='wireframe', color=(0, 0, 0), line_width=4, name="BRZ") elif plotting_package == 'plotly': for iface in poly: iface = np.pad(iface, ((0, 1), (0, 0)), 'wrap') x, y, z = iface[:, 0], iface[:, 1], iface[:, 2] plane = go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='black', width=4)) figs.append(plane) elif plotting_package == 'matplotlib': fig = plt.figure() ax = fig.add_subplot(111, projection='3d') brillouin_zone = Poly3DCollection(poly, facecolors=["None"] * len(poly), alpha=1, linewidth=4) brillouin_zone.set_edgecolor("k") ax.add_collection3d(brillouin_zone, zs=0, zdir='z') br_points = [] for iface in poly: for ipoint in iface: br_points.append(ipoint) br_points = np.unique(br_points, axis=0) print('Number of bands: %d' % procarFile.bandsCount) print('Number of koints %d' % procarFile.kpointsCount) print('Number of ions: %d' % procarFile.ionsCount) print('Number of orbitals: %d' % procarFile.orbitalCount) print('Number of spins: %d' % procarFile.ispin) #selecting the data data = ProcarSelect(procarFile, deepCopy=True) if bands == -1: bands = range(data.bands.shape[1]) kvector = data.kpoints kmax = np.max(kvector) kmin = np.min(kvector) if abs(kmax) != abs(kmin): print("The mesh provided is gamma center, symmetrizing data") print("For a better fermi surface, use a non-gamma centered k-mesh") data = symmetrize(data) kvector = data.kpoints kvector_red = data.kpoints.copy() kvector_cart = np.dot(kvector_red, recLat) # This section finds points that are outside of the 1st BZ and and creates those points in the 1st BZ kvector_cart, kvector_red, has_points_out = bring_pnts_to_BZ( recLat, kvector_cart, kvector_red, br_points) # has_points_out = False # getting the mesh grid in each dirrection kx_red = np.unique(kvector_red[:, 0]) ky_red = np.unique(kvector_red[:, 1]) kz_red = np.unique(kvector_red[:, 2]) # getting the lengths between kpoints in each direction klength_x = np.abs(kx_red[-1] - kx_red[-2]) klength_y = np.abs(ky_red[-1] - ky_red[-2]) klength_z = np.abs(kz_red[-1] - kz_red[-2]) klengths = [klength_x, klength_y, klength_z] # getting number of kpoints in each direction with the addition of kpoints needed to sample the 1st BZ fully (in reduced) nkx_red = kx_red.shape[0] nky_red = ky_red.shape[0] nkz_red = kz_red.shape[0] # getting numner of kpoints in each direction provided by vasp nkx_orig = np.unique(kvector[:, 0]).shape[0] nky_orig = np.unique(kvector[:, 1]).shape[0] nkz_orig = np.unique(kvector[:, 2]).shape[0] # Amount of kpoints needed to add on to fully sample 1st BZ padding_x = (nkx_red - nkx_orig) // 2 padding_y = (nky_red - nky_orig) // 2 padding_z = (nkz_red - nkz_orig) // 2 if mode == 'parametric': data.selectIspin(spin) data.selectAtoms(atoms, fortran=False) data.selectOrbital(orbitals) elif mode == 'external': if "color_file" in kwargs: rf = open(kwargs['color_file']) lines = rf.readlines() counter = 0 color_kvector = [] color_eigen = [] for iline in lines: if counter < 2: if 'band' in iline: counter += 1 continue temp = [float(x) for x in iline.split()] color_kvector.append([temp[0], temp[1], temp[2]]) counter = -1 for iline in lines: if 'band' in iline: counter += 1 iband = int(iline.split()[-1]) color_eigen.append([]) continue color_eigen[counter].append(float(iline.split()[-1])) rf.close() color_kvector = np.array(color_kvector) color_kvector_red = color_kvector.copy() color_kvector_cart = np.dot(color_kvector, recLat) if has_points_out: color_kvector_cart, color_kvector_red, temp = bring_pnts_to_BZ( recLat, color_kvector_cart, color_kvector_red, br_points) else: print( "mode selected was external, but no color_file name was provided" ) return if st: dataX = ProcarSelect(procarFile, deepCopy=True) dataY = ProcarSelect(procarFile, deepCopy=True) dataZ = ProcarSelect(procarFile, deepCopy=True) dataX.kpoints = data.kpoints dataY.kpoints = data.kpoints dataZ.kpoints = data.kpoints dataX.spd = data.spd dataY.spd = data.spd dataZ.spd = data.spd dataX.bands = data.bands dataY.bands = data.bands dataZ.bands = data.bands dataX.selectIspin([1]) dataY.selectIspin([2]) dataZ.selectIspin([3]) dataX.selectAtoms(atoms, fortran=False) dataY.selectAtoms(atoms, fortran=False) dataZ.selectAtoms(atoms, fortran=False) dataX.selectOrbital(orbitals) dataY.selectOrbital(orbitals) dataZ.selectOrbital(orbitals) ic = 0 for iband in bands: print("Plotting band %d" % iband) eigen = data.bands[:, iband] # mapping the eigen values on the mesh grid to a matrix mapped_func, kpoint_matrix = mapping_func(kvector, eigen) # adding the points from the 2nd BZ to 1st BZ to fully sample the BZ. Check np.pad("wrap") for more information mapped_func = np.pad(mapped_func, ((padding_x, padding_x), (padding_y, padding_y), (padding_z, padding_z)), 'wrap') # Fourier interpolate the mapped function E(x,y,z) surf_equation = fft_interpolate(mapped_func, scale) # after the FFT we loose the center of the BZ, using numpy roll we bring back the center of the BZ surf_equation = np.roll(surf_equation, (scale) // 2, axis=[0, 1, 2]) try: # creating the isosurface if possible verts, faces, normals, values = measure.marching_cubes_lewiner( surf_equation, e_fermi) except: print("No isosurface for this band") continue # the vertices provided are scaled and shifted to start from zero # we center them to zero, and rescale them to fit the real BZ by multiplying by the klength in each direction for ix in range(3): verts[:, ix] -= verts[:, ix].min() verts[:, ix] -= (verts[:, ix].max() - verts[:, ix].min()) / 2 verts[:, ix] *= klengths[ix] / scale # the vertices need to be transformed to reciprocal spcae from recuded space, to find the points that are # in 2nd BZ, to be removed verts = np.dot(verts, recLat) # identifying the points in 2nd BZ and removing them if has_points_out: args = [] for ivert in range(len(verts)): args.append([br_points, verts[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] # outs_bool_mat = np.zeros(shape=faces.shape,dtype=np.bool) for iface in faces: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces = np.array(new_faces) print("done removing") # At this point we have the plain Fermi surface, we can color the surface depending on the projection # We create the center of faces by averaging coordinates of corners if mode == 'parametric': character = data.spd[:, iband] centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(kvector_cart, character, centers, method="nearest") elif mode == 'external': character = np.array(color_eigen[ic]) ic += 1 centers = np.zeros(shape=(len(faces), 3)) for iface in range(len(faces)): centers[iface, 0:3] = np.average(verts[faces[iface]], axis=0) colors = interpolate.griddata(color_kvector_cart, character, centers, method="nearest") if st: projection_x = dataX.spd[:, iband] projection_y = dataY.spd[:, iband] projection_z = dataZ.spd[:, iband] verts_spin, faces_spin, normals, values = measure.marching_cubes_lewiner( mapped_func, e_fermi) for ix in range(3): verts_spin[:, ix] -= verts_spin[:, ix].min() verts_spin[:, ix] -= (verts_spin[:, ix].max() - verts_spin[:, ix].min()) / 2 verts_spin[:, ix] *= klengths[ix] verts_spin = np.dot(verts_spin, recLat) if has_points_out: args = [] for ivert in range(len(verts_spin)): args.append([br_points, verts_spin[ivert]]) p = Pool(nprocess) results = np.array(p.map(is_outside, args)) p.close() out_verts = np.arange(0, len(results))[results] new_faces = [] for iface in faces_spin: remove = False for ivert in iface: if ivert in out_verts: remove = True continue if not remove: new_faces.append(iface) faces_spin = np.array(new_faces) centers = np.zeros(shape=(len(faces_spin), 3)) for iface in range(len(faces_spin)): centers[iface, 0:3] = np.average(verts_spin[faces_spin[iface]], axis=0) colors1 = interpolate.griddata(kvector_cart, projection_x, centers, method="linear") colors2 = interpolate.griddata(kvector_cart, projection_y, centers, method="linear") colors3 = interpolate.griddata(kvector_cart, projection_z, centers, method="linear") spin_arrows = np.vstack((colors1, colors2, colors3)).T if plotting_package == 'mayavi': polydata = tvtk.PolyData(points=verts, polys=faces) if face_colors != None: mlab.pipeline.surface(polydata, representation='surface', color=face_colors[ic], opacity=1, name='band-' + str(iband)) ic += 1 else: if mode == 'plain': if not (transparent): s = mlab.pipeline.surface(polydata, representation='surface', color=(0, 0.5, 1), opacity=1, name='band-' + str(iband)) elif mode == 'parametric' or mode == 'external': polydata.cell_data.scalars = colors polydata.cell_data.scalars.name = 'celldata' mlab.pipeline.surface(polydata, vmin=0, vmax=colors.max(), colormap=cmap) cb = mlab.colorbar(orientation='vertical') if st: x, y, z = list(zip(*centers)) u, v, w = list(zip(*spin_arrows)) pnts = mlab.quiver3d(x, y, z, u, v, w, line_width=5, mode='arrow', resolution=25, reset_zoom=False, name='spin-' + str(iband), mask_points=mask_points, scalars=spin_arrows[:, arrow_projection], vmin=-1, vmax=1, colormap=cmap) pnts.glyph.color_mode = 'color_by_scalar' pnts.glyph.glyph_source.glyph_source.shaft_radius = 0.05 pnts.glyph.glyph_source.glyph_source.tip_radius = 0.1 elif plotting_package == 'plotly': if mode == 'plain': if not (transparent): x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, simplices=faces, title="band-%d" % ic) figs.append(fig['data'][0]) elif mode == 'parametric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] x, y, z = zip(*verts) fig = ff.create_trisurf(x=x, y=y, z=z, plot_edges=False, colormap=colormap, simplices=faces, show_colorbar=True, title="band-%d" % ic) figs.append(fig['data'][0]) elif plotting_package == 'matplotlib': if mode == 'plain': x, y, z = zip(*verts) ax.plot_trisurf(x, y, faces, z, linewidth=0.2, antialiased=True) elif mode == 'parametric' or mode == 'external': print( 'coloring the faces is not implemented in matplot lib, please use another plotting package.we recomend mayavi.' ) elif plotting_package == 'ipyvolume': if mode == 'plain': ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces) elif mode == 'paramteric' or mode == 'external': face_colors = cmap(colors) colormap = [ 'rgb(%i,%i,%i)' % (x[0], x[1], x[2]) for x in (face_colors * 255).round() ] ipv.figure() ipv.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], triangles=faces, color=cmap) if plotting_package == 'mayavi': mlab.colorbar(orientation='vertical') #,label_fmt='%.1f') mlab.show() elif plotting_package == 'plotly': layout = go.Layout(showlegend=False) fig = go.Figure(data=figs, layout=layout) py.iplot(fig) elif plotting_package == 'matplotlib': plt.show() elif plotting_package == 'ipyvolume': ipv.show() return
def Plot(self, filename=None, edgeColor='none'): """ Plot the optimized shape Parameters ---------- None Returns ------- None """ fig = plt.figure("Result", figsize=(12,12), clear=True) if self.fem.nDof == 2: collection = PolyCollection(self.fem.nodes[self.fem.elements], edgecolors=edgeColor) collection.set_array(self.densities) collection.set_cmap('gray_r') collection.set_clim(vmin=0, vmax=1) ax = fig.gca() ax.add_collection(collection) ax.set_xlim(self.fem.nodes[:,0].min(), self.fem.nodes[:,0].max()) ax.set_ylim(self.fem.nodes[:,1].min(), self.fem.nodes[:,1].max()) ratio = ((ax.get_ylim()[1] - ax.get_ylim()[0]) / (ax.get_xlim()[1] - ax.get_xlim()[0])) if ratio < 1: fig.set_figheight(ratio * fig.get_figwidth()) else: fig.set_figwidth(fig.get_figheight() / ratio) ax.axis('off') elif self.fem.nDof == 3: if not hasattr(self, 'facePairs'): face = np.array([0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 5, 4, 3, 2, 6, 7, 0, 4, 7, 3, 1, 5, 6, 2]).reshape(6,4) faces = np.concatenate([el[face] for el in self.fem.elements]) order = np.arange(faces.shape[0]) for i in range(faces.shape[1]): ind = np.argsort(faces[:,i], kind='stable') faces = faces[ind,:] order = order[ind] elements = np.tile(np.arange(self.fem.nElem).reshape(-1, 1), (1,6)).ravel()[order] self.facePairs = [] self.faceNodes = [] i = 0 while i < faces.shape[0] - 1: if (faces[i,:] == faces[i+1,:]).all(): self.facePairs.append([elements[i], elements[i+1]]) self.faceNodes.append(faces[i]) i += 2 else: self.facePairs.append([elements[i], self.fem.nElem]) self.faceNodes.append(faces[i]) i += 1 if i < faces.shape[0]: self.facePairs.append([elements[i], self.fem.nElem]) self.faceNodes.append(faces[i]) self.facePairs = np.array(self.facePairs) self.faceNodes = np.array(self.faceNodes) densities = np.append(self.densities, [0]) faces = np.logical_xor(densities[self.facePairs[:,0]] > self.dens_thresh, densities[self.facePairs[:,1]] > self.dens_thresh) print("Plotting %i faces" % (self.faceNodes[faces].size // 4)) collection = Poly3DCollection(self.fem.nodes[self.faceNodes[faces].reshape(-1,4)], edgecolors=edgeColor) densities = densities[self.facePairs].max(axis=1)[faces] collection.set_array(densities) # elements = self.fem.elements[self.densities > self.dens_thresh,:] # collection = Poly3DCollection(self.fem.nodes[elements[:,face].reshape(-1,4)], # edgecolors="k") # densities = np.tile(self.densities[self.densities > self.dens_thresh], (6,1)).T.ravel() # collection.set_array(densities) collection.set_cmap('gray_r') collection.set_clim(vmin=0, vmax=1) ax = fig.gca(projection='3d') ax.add_collection3d(collection) ax.set_xlim(np.min(self.fem.nodes), np.max(self.fem.nodes)) ax.set_ylim(np.min(self.fem.nodes), np.max(self.fem.nodes)) ax.set_zlim(np.min(self.fem.nodes), np.max(self.fem.nodes)) plt.draw() plt.pause(0.01) if filename: plt.tight_layout() plt.savefig(filename, bbox_inches='tight', pad_inches=0)