def __init__(self, *args, **kargs): ArtGL.__init__(self, **kargs) self.do_stencil_test = True self._gl_offset = kargs.pop('gl_offset', (0, 0, 0.)) self._gl_3dpath = kargs.pop('gl_3dpath', None) self._gl_facecolor = kargs.pop('gl_facecolor', None) self._gl_edgecolor = kargs.pop('gl_edgecolor', None) self._gl_solid_facecolor = kargs.pop('gl_solid_facecolor', None) self._gl_solid_edgecolor = kargs.pop('gl_solid_edgecolor', None) self._gl_shade = kargs.pop('gl_shade', 'smooth') self._gl_lighting = kargs.pop('gl_lighting', True) self._gl_facecolordata = kargs.pop('facecolordata', None) self._gl_voffset = kargs.pop('view_offset', (0,0,0,0.)) self._gl_array_idx = kargs.pop('array_idx', None) self._gl_use_pointfill = kargs.pop('use_pointfill', False) self._cz = None self._gl_cz = None self._update_ec = True self._update_fc = True self._update_v = True self._update_i = True self._update_a = True Poly3DCollection.__init__(self, *args, **kargs)
def update_scalarmappable(self): if self._gl_solid_facecolor is not None: f = cc.to_rgba(self._gl_solid_facecolor) self._gl_facecolor = np.tile(f, (len(self._gl_3dpath[2]),1)) else: if self._gl_cz: if self._gl_facecolordata is not None: self._gl_facecolor = self.to_rgba(self._gl_facecolordata) elif self._gl_shade =='flat': if self._gl_cz: z = [np.mean(self._gl_3dpath[2][idx]) for idx in self._gl_3dpath[4]] else: z = [np.mean(self._gl_cz[idx]) for idx in self._gl_3dpath[4]] z = np.array(z) self._gl_facecolor = self.to_rgba(z) else: if self._gl_cz is None: self._gl_facecolor = self.to_rgba(self._gl_3dpath[2]) else: self._gl_facecolor = self.to_rgba(self._gl_cz) if self._alpha is not None: if self._gl_facecolor.ndim == 3: self._gl_facecolor[:, :,-1]=self._alpha else: self._gl_facecolor[:,-1]=self._alpha if self._gl_solid_edgecolor is not None: f = cc.to_rgba(self._gl_solid_edgecolor) self._gl_edgecolor = np.tile(f, (len(self._gl_3dpath[2]),1)) else: if self._gl_shade == False: z = [np.mean(self._gl_3dpath[2][idx]) for idx in self._gl_3dpath[4]] z = np.array(z) self._gl_edgecolor = self.to_rgba(z) else: self._gl_edgecolor = self.to_rgba(self._gl_3dpath[2]) if self._alpha is not None: if self._gl_edgecolor.ndim == 3: self._gl_edgecolor[:, :,-1]=self._alpha else: self._gl_edgecolor[:,-1]=self._alpha Poly3DCollection.update_scalarmappable(self)
def polyplane(verts, alpha=0.1, color="green"): poly = Poly3DCollection(verts) poly.set_alpha(alpha) poly.set_facecolor(color) return poly
def animate(ii): removePlt() #ii=1 if ii<18: dec = 90 inc = 0. + ii*5. elif ii < 36: dec = 270. inc = 90. - (ii-18)*5. elif ii < 54: dec = 270. inc = 0.+ (ii-36)*5. else: dec = 90 inc = 90. - (ii-54)*5. ax1.axis('equal') block_xyz = np.asarray([[-.2, -.2, .2, .2, 0], [-.25, -.25, -.25, -.25, 0.5], [-.2, .2, .2, -.2, 0]])*10. block_xyz[1][:] -=20. # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec)) # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot, # np.r_[p.xc, p.yc, p.zc]) R = Utils.rotationMatrix(inc, dec) xyz = R.dot(block_xyz).T xyz[:,2] -= depth + dz/2. #print xyz # Face 1 ax1.add_collection3d(Poly3DCollection([zip(xyz[:4, 0], xyz[:4, 1], xyz[:4, 2])], facecolors='b')) ax1.add_collection3d(Poly3DCollection([zip(xyz[[1, 2, 4], 0], xyz[[1, 2, 4], 1], xyz[[1, 2, 4], 2])], facecolors='b')) ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 1, 4], 0], xyz[[0, 1, 4], 1], xyz[[0, 1, 4], 2])], facecolors='b')) ax1.add_collection3d(Poly3DCollection([zip(xyz[[2, 3, 4], 0], xyz[[2, 3, 4], 1], xyz[[2, 3, 4], 2])], facecolors='b')) ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 3, 4], 0], xyz[[0, 3, 4], 1], xyz[[0, 3, 4], 2])], facecolors='b')) ax1.w_yaxis.set_ticklabels('') ax1.w_yaxis.set_label_text('') ax1.w_zaxis.set_ticklabels('') ax1.w_zaxis.set_label_text('') # block_xyz[1][:] +=20. # # rot = Utils.mkvc(Utils.dipazm_2_xyz(pinc, pdec)) # # # xyz = Utils.rotatePointsFromNormals(block_xyz.T, np.r_[0., 1., 0.], rot, # # np.r_[p.xc, p.yc, p.zc]) # # R = Utils.rotationMatrix(rinc, rdec) # # xyz = R.dot(block_xyz).T # xyz[:,2] -= depth + dz/2. # # #print xyz # # Face 1 # ax1.add_collection3d(Poly3DCollection([zip(xyz[:4, 0], # xyz[:4, 1], # xyz[:4, 2])], facecolors='y')) # # ax1.add_collection3d(Poly3DCollection([zip(xyz[[1, 2, 4], 0], # xyz[[1, 2, 4], 1], # xyz[[1, 2, 4], 2])], facecolors='y')) # # ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 1, 4], 0], # xyz[[0, 1, 4], 1], # xyz[[0, 1, 4], 2])], facecolors='y')) # # ax1.add_collection3d(Poly3DCollection([zip(xyz[[2, 3, 4], 0], # xyz[[2, 3, 4], 1], # xyz[[2, 3, 4], 2])], facecolors='y')) # # ax1.add_collection3d(Poly3DCollection([zip(xyz[[0, 3, 4], 0], # xyz[[0, 3, 4], 1], # xyz[[0, 3, 4], 2])], facecolors='y')) MAG.plotObj3D(p, rx_h, View_elev, View_azim, npts2D, xylim, profile="X", fig= fig, axs = ax1, plotSurvey=False) # Create problem prob = PFlocal.problem() prob.prism = p prob.survey = srvy prob.Bdec, prob.Binc, prob.Bigrf = dec, inc, Bigrf prob.Q, prob.rinc, prob.rdec = Q, rinc, rdec prob.uType, prob.mType = comp, 'total' prob.susc = susc # Compute fields from prism b_ind, b_rem = prob.fields() if irt == 'total': out = b_ind + b_rem elif irt == 'induced': out = b_ind else: out = b_rem #out = plogMagSurvey2D(prob, susc, Einc, Edec, Bigrf, x1, y1, x2, y2, comp, irt, Q, rinc, rdec, fig=fig, axs1=ax2, axs2=ax3) #dat = axs1.contourf(X,Y, np.reshape(out, (X.shape)).T global im1 im1 = ax1.contourf(X,Y,np.reshape(out, (X.shape)).T,20,zdir='z',offset=rx_h+5., clim=clim, vmin=clim[0],vmax=clim[1], cmap = 'RdBu_r') ax5 = fig.add_axes([pos.x0 , pos.y0+0.25, pos.height*0.02, pos.height*0.4]) cb = plt.colorbar(im1,cax=ax5, orientation="vertical", ax = ax1, ticks=np.linspace(im1.vmin,im1.vmax, 4), format="${%.0f}$") cb.set_label("$B^{TMI}\;(nT)$",size=12) cb.ax.yaxis.set_ticks_position('left') cb.ax.yaxis.set_label_position('left') global im5 im5 = ax1.text(0,0,-60,'$B_0, I: ' + str(inc) + '^\circ, D: ' + str(dec) + '^\circ$', horizontalalignment='center') H0 = (Bigrf,inc,dec) actv = np.ones(mesh.nC)==1 # Create active map to go from reduce space to full actvMap = Maps.InjectActiveCells(mesh, actv, -100) nC = len(actv) # Create a MAGsurvey rxLoc = np.c_[Utils.mkvc(X), Utils.mkvc(Y), Utils.mkvc(Z)] rxLoc = PF.BaseMag.RxObs(rxLoc) srcField = PF.BaseMag.SrcField([rxLoc],param = H0) survey = PF.BaseMag.LinearSurvey(srcField) # We can now create a susceptibility model and generate data # Lets start with a simple block in half-space # model = np.zeros((mesh.nCx,mesh.nCy,mesh.nCz)) # model[(midx-2):(midx+2),(midy-2):(midy+2),-6:-2] = 0.02 # model = mkvc(model) # model = model[actv] # Create active map to go from reduce set to full actvMap = Maps.InjectActiveCells(mesh, actv, -100) # Creat reduced identity map idenMap = Maps.IdentityMap(nP = nC) # Create the forward model operator probinv = PF.Magnetics.MagneticIntegral(mesh, mapping = idenMap, actInd = actv) # Pair the survey and problem survey.pair(probinv) # Compute linear forward operator and compute some data # d = probinv.fields(model) # Plot the model # m_true = actvMap * model # m_true[m_true==-100] = np.nan #plt.figure() #ax = plt.subplot(212) #mesh.plotSlice(m_true, ax = ax, normal = 'Y', ind=midy, grid=True, clim = (0., model.max()/3.), pcolorOpts={'cmap':'viridis'}) #plt.title('A simple block model.') #plt.xlabel('x'); plt.ylabel('z') #plt.gca().set_aspect('equal', adjustable='box') # We can now generate data data = out + np.random.randn(len(out)) # We add some random Gaussian noise (1nT) wd = np.ones(len(data))*1. # Assign flat uncertainties # Create distance weights from our linera forward operator wr = np.sum(probinv.G**2.,axis=0)**0.5 wr = ( wr/np.max(wr) ) #survey.makeSyntheticData(data, std=0.01) survey.dobs= data survey.std = wd survey.mtrue = model # Create a regularization reg = Regularization.Sparse(mesh, indActive=actv, mapping=idenMap) reg.cell_weights = wr dmis = DataMisfit.l2_DataMisfit(survey) dmis.Wd = 1/wd # Add directives to the inversion opt = Optimization.ProjectedGNCG(maxIter=100 ,lower=0.,upper=1., maxIterLS = 20, maxIterCG= 10, tolCG = 1e-3) invProb = InvProblem.BaseInvProblem(dmis, reg, opt) betaest = Directives.BetaEstimate_ByEig() # Here is where the norms are applied # Use pick a treshold parameter empirically based on the distribution of model # parameters (run last cell to see the histogram before and after IRLS) IRLS = Directives.Update_IRLS( norms=([2,2,2,2]), eps=(2e-3,2e-3), f_min_change = 1e-3, minGNiter=3,beta_tol=1e-2) update_Jacobi = Directives.Update_lin_PreCond() inv = Inversion.BaseInversion(invProb, directiveList=[IRLS,betaest,update_Jacobi]) m0 = np.ones(nC)*1e-4 mrec = inv.run(m0) # Here is the recovered susceptibility model ypanel = midx zpanel = -4 m_l2 = actvMap * reg.l2model m_l2[m_l2==-100] = np.nan m_lp = actvMap * mrec m_lp[m_lp==-100] = np.nan # m_true = actvMap * model # m_true[m_true==-100] = np.nan #Plot L2 model #global im2 xx, zz = mesh.gridCC[:,0].reshape(mesh.vnC, order="F"), mesh.gridCC[:,2].reshape(mesh.vnC, order="F") yy = mesh.gridCC[:,1].reshape(mesh.vnC, order="F") temp = m_lp.reshape(mesh.vnC, order='F') ptemp = temp[:,:,indz].T #ptemp = ma.array(ptemp ,mask=np.isnan(ptemp)) global im2 im2 = ax2.contourf(xx[:,:,indz].T,yy[:,:,indz].T,ptemp,20, vmin = vmin, vmax= vmax, clim=[vmin,vmax]) ax2.plot(([mesh.vectorCCx[0],mesh.vectorCCx[-1]]),([mesh.vectorCCy[indy],mesh.vectorCCy[indy]]),color='w') ax2.set_aspect('equal') ax2.xaxis.set_visible(False) ax2.set_xlim(-60,60) ax2.set_ylim(-60,60) ax2.set_title('Induced Model') ax2.set_ylabel('Northing (m)',size=14) ptemp = temp[:,indy,:].T global im3 im3 = ax3.contourf(xx[:,indy,:].T,zz[:,indy,:].T,ptemp,20, vmin = vmin, vmax= vmax, clim=[vmin,vmax]) ax3.set_aspect('equal') ax3.set_xlim(-60,60) ax3.set_ylim(-60,0) ax3.set_title('EW Section') ax3.set_xlabel('Easting (m)',size=14) ax3.set_ylabel('Elevation (m)',size=14) ax4 = fig.add_axes([pos.x0 + 0.75, pos.y0+0.25, pos.height*0.02, pos.height*0.4]) cb = plt.colorbar(im3,cax=ax4, orientation="vertical", ax = ax1, ticks=np.linspace(im3.vmin,im3.vmax, 4), format="${%.3f}$") cb.set_label("Susceptibility (SI)",size=12)
def show_fermi_surf(self, cell='bz', plot='mpl', savefig='fs.png', cmap='Spectral'): ''' Plotting the Fermi surface within the BZ using matplotlib. ''' try: from skimage.measure import marching_cubes_lewiner as marching_cubes except ImportError: try: from skimage.measure import marching_cubes except ImportError: raise ImportError("scikit-image not installed.\n" "Please install with it with `conda install scikit-image` or `pip install scikit-image`") bcell = self.atoms.get_reciprocal_cell() b1, b2, b3 = np.linalg.norm(bcell, axis=1) if cell == 'bz': # the vertices, rigdges and facets of the BZ p, l, f = get_brillouin_zone_3d(bcell) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # https://docs.scipy.org/doc/scipy/reference/tutorial/spatial.html#voronoi-diagrams # cKDTree is implemented in cython, which is MUCH MUCH FASTER than KDTree #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from scipy.spatial import cKDTree px, py, pz = np.tensordot( self.atoms.get_reciprocal_cell(), np.mgrid[-1:2, -1:2, -1:2], axes=[0, 0] ) points = np.c_[px.ravel(), py.ravel(), pz.ravel()] tree = cKDTree(points) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Gamma point belong to the first BZ. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! gamma_region_id = tree.query([0, 0, 0])[1] else: # the vertices, rigdges and facets of the primitive cell p, l, f = get_primitive_cell_3d(bcell) if plot.lower() == 'mpl': ############################################################ # Plot the Fermi surface using matplotlib ############################################################ import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection ############################################################ fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot(111, projection='3d') # ax.set_aspect('equal') ############################################################ basis_vector_clrs = ['r', 'g', 'b'] basis_vector_labs = ['x', 'y', 'z'] for ii in range(3): ax.plot([0, bcell[ii, 0]], [0, bcell[ii, 1]], [0, bcell[ii, 2]], color=basis_vector_clrs[ii], lw=1.5) ax.text(bcell[ii, 0], bcell[ii, 1], bcell[ii, 2], basis_vector_labs[ii]) ############################################################ # Plot the Fermi Surface. # Marching-cubes algorithm is used to find out the isosurface. ############################################################ for ispin in range(self.nspin): for ii in range(len(self.fermi_xbands[ispin])): # the band energies in the uc [0, 1] b3d = self.fermi_ebands3d_uc[ispin][ii] if cell == 'bz': # expand the band energies to double uc, [-1, 1] b3d_2uc = np.tile(b3d, (2, 2, 2)) nx, ny, nz = b3d_2uc.shape # https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.marching_cubes_lewiner verts, faces, normals, values = marching_cubes(b3d_2uc, level=self.efermi, spacing=( 2*b1/nx, 2*b2/ny, 2*b3/nz) ) verts_cart = np.dot( verts / np.array([b1, b2, b3]) - np.ones(3), bcell ) # the region id of the vertices verts_region_id = tree.query(verts_cart)[1] # whether the k-points are in BZ? verts_in_bz = (verts_region_id == gamma_region_id) # find out the triangles with all vertices inside BZ verts_cart_fs = verts_cart[faces][ np.alltrue(verts_in_bz[faces], axis=1) ] else: nx, ny, nz = b3d.shape # make band energies periodic in primitive cell # b3d = np.tile(b3d, (2,2,2))[:nx+1, :ny+1, :nz+1] b3d = np.pad(b3d, (0,1), mode='wrap') # mayby a little faster? # https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.marching_cubes_lewiner verts, faces, normals, values = marching_cubes(b3d, level=self.efermi, spacing=( b1/nx, b2/ny, b3/nz) ) verts_cart_fs = np.dot( verts / np.array([b1, b2, b3]), bcell )[faces] cc = np.linalg.norm(np.sum(verts_cart_fs, axis=1), axis=1) nn = mpl.colors.Normalize(vmin=cc.min(), vmax=cc.max()) art = Poly3DCollection(verts_cart_fs, facecolor='r', alpha=0.8, color=mpl.cm.get_cmap(cmap)(nn(cc))) # art.set_edgecolor('k') ax.add_collection3d(art) ############################################################ # Plot the Brillouin Zone ############################################################ # The BZ outlines for xx in l: ax.plot(xx[:, 0], xx[:, 1], xx[:, 2], color='k', lw=1.0) # art = Poly3DCollection(f, facecolor='k', alpha=0.1) # ax.add_collection3d(art) ############################################################ if cell == 'bz': ax.set_xlim(-b1, b1) ax.set_ylim(-b2, b2) ax.set_zlim(-b3, b3) else: ax.set_xlim(0, b1) ax.set_ylim(0, b2) ax.set_zlim(0, b3) ax.set_title('Fermi Energy: {:.4f} eV'.format(self.efermi), fontsize='small') # plt.tight_layout() plt.savefig(savefig, dpi=480) plt.show() ############################################################ elif plot.lower() == 'mayavi': from mayavi import mlab # from tvtk.tools import visual fig = mlab.figure(size=(800, 800)) # visual.set_viewer(fig) # for b in bcell: # x, y, z = b # ar1 = visual.Arrow(x=y, y=y, z=z) # arrow_length = np.linalg.norm(b) # ar1.actor.scale=[arrow_length, arrow_length, arrow_length] # ar1.pos = ar1.pos/arrow_length # ar1.axis = [x, y, z] ############################################################ # Plot the Brillouin Zone ############################################################ bz_line_width = b1 / 200 # The BZ outlines for xx in l: mlab.plot3d(xx[:, 0], xx[:, 1], xx[:, 2], tube_radius=bz_line_width, color=(0, 0, 0)) ############################################################ # Plot the Fermi Surface. # Marching-cubes algorithm is used to find out the isosurface. ############################################################ for ispin in range(self.nspin): for ii in range(len(self.fermi_xbands[ispin])): # the band energies in the uc [0, 1] b3d = self.fermi_ebands3d_uc[ispin][ii] if cell == 'bz': # expand the band energies to double uc, [-1, 1] b3d_2uc = np.tile(b3d, (2, 2, 2)) nx, ny, nz = b3d_2uc.shape # https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.marching_cubes_lewiner verts, faces, normals, values = marching_cubes(b3d_2uc, level=self.efermi, spacing=( 2*b1/nx, 2*b2/ny, 2*b3/nz) ) verts_cart = np.dot( verts / np.array([b1, b2, b3]) - np.ones(3), bcell ) # the region id of the vertices verts_region_id = tree.query(verts_cart)[1] # whether the k-points are in BZ? verts_in_bz = (verts_region_id == gamma_region_id) # find out the triangles with all vertices inside BZ faces_in_fs = faces[np.all(verts_in_bz[faces], axis=1)] # keeps the vertices on the Fermi surface and remove all # the other vertices vertices_old_id = np.unique(faces_in_fs) vertices_new_id = range(vertices_old_id.size) old_new_map = dict(np.c_[vertices_old_id, vertices_new_id]) verts_cart = verts_cart[vertices_old_id] faces_in_fs = [[old_new_map[v] for v in f] for f in faces_in_fs] else: nx, ny, nz = b3d.shape # make band energies periodic in primitive cell # b3d = np.tile(b3d, (2,2,2))[:nx+1, :ny+1, :nz+1] b3d = np.pad(b3d, (0,1), mode='wrap') # mayby a little faster? # https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.marching_cubes_lewiner verts, faces_in_fs, normals, values = marching_cubes(b3d, level=self.efermi, spacing=( b1/nx, b2/ny, b3/nz) ) verts_cart = np.dot( verts / np.array([b1, b2, b3]), bcell ) # cc = np.linalg.norm(np.sum(verts_cart[faces_in_fs], axis=1), axis=1) # kk = np.linalg.norm(verts_cart, axis=1) # print(cc.min(), cc.max()) # print(kk.min(), kk.max()) mlab.triangular_mesh(verts_cart[:,0], verts_cart[:,1], verts_cart[:,2], faces_in_fs, colormap='rainbow', opacity=1.0, scalars=np.linalg.norm(verts_cart, axis=1), # vmin=cc.min(), vmax=cc.max() ) mlab.orientation_axes() mlab.savefig(savefig) mlab.show() else: raise ValueError("Plotting method should be 'mpl' or 'mayavi'!")
def isosurface_timestep(data, timestep, isovalue, name, dpi=30, frame=9, dx=40, dy=40, dz=10, D=400): import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection from matplotlib import animation from skimage import measure nx, ny, nz, nt = shape(data) if not os.path.exists(name + '_' + str(timestep)): os.makedirs(name + '_' + str(timestep)) fig = plt.figure(figsize=(30, 30 * 2.5)) ax = fig.add_subplot(111, projection='3d', facecolor='w', label='Inline label') angle = 0 while (angle <= 360): percent = np.str(np.round(angle / 360 * 100)) + "%" print('{}\r'.format(percent), end="") nameg = name + ' Time:' + str(timestep) + ' Angle:' + str(angle) vol = data[:, :, :, timestep] verts, faces, _, _ = measure.marching_cubes_lewiner(vol, isovalue, spacing=(dx, dy, dz)) mesh = Poly3DCollection(verts[faces]) mesh.set_edgecolor('k') ax.add_collection3d(mesh) ax.view_init(15, angle) ax.set_xlabel("X/D", fontsize=50, labelpad=40) ax.set_ylabel("Y/D", fontsize=50, labelpad=40) ax.set_zlabel("Z/D", fontsize=50, labelpad=100) # Title: namel = len(nameg) namexpos = 0.5 - 0.01 * namel ax.text2D(namexpos, 0.85, nameg, transform=ax.transAxes, fontsize=65) ticnum = 11 ticnumz = 14 xaxis = [] for x in range(np.int(-(ticnum - 1) / 2), np.int((ticnum + 1) / 2)): xaxis.append(((nx - 1) * dx / (ticnum - 1) * x) / D) yaxis = [] for y in range(np.int(-(ticnum - 1) / 2), np.int((ticnum - 1) / 2)): yaxis.append(((ny - 1) * dy / (ticnum - 1) * y) / D) zaxis = [] for z in range(0, np.int((ticnumz + 1))): zaxis.append(z * (dz * nz / ticnumz) / D) ax.set_xticks(np.linspace(0, nx * dx, ticnum)) ax.set_yticks(np.linspace(0, ny * dy, ticnum)) ax.set_xticklabels(xaxis) ax.set_yticklabels(yaxis) ax.invert_yaxis() ax.set_zticks(np.linspace(0, nz * dz, ticnumz + 1)) ax.set_zticklabels(zaxis) ax.tick_params(axis='both', which='major', labelsize=30) plt.tight_layout() filename = name + '_T' + str(timestep) + '/' + name + '_t' + str( angle) + '.png' bbox = fig.bbox_inches.from_bounds(1, 9, 28, 58) plt.savefig(name + '_(' + str(timestep) + ')/' + name + ' ' + str(angle) + '.png', bbox_inches=bbox, dpi=dpi) plt.cla() angle = angle + frame
def plotObj3D(prism, survey, View_dip, View_azm, View_lim, fig=None, axs=None, title=None): """ Plot the prism in 3D """ x1, x2 = prism.xn[0] - prism.xc, prism.xn[1] - prism.xc y1, y2 = prism.yn[0] - prism.yc, prism.yn[1] - prism.yc z1, z2 = prism.zn[0] - prism.zc, prism.zn[1] - prism.zc pinc, pdec = prism.pinc, prism.pdec rxLoc = survey.srcField.rxList[0].locs if fig is None: fig = plt.figure(figsize=(7, 7)) if axs is None: axs = fig.add_subplot(111, projection="3d") if title is not None: axs.set_title(title) # plt.rcParams.update({'font.size': 13}) cntr = [prism.x0, prism.y0] axs.set_xlim3d(-View_lim + cntr[0], View_lim + cntr[0]) axs.set_ylim3d(-View_lim + cntr[1], View_lim + cntr[1]) axs.set_zlim3d(rxLoc[:, 2].max() * 1.1 - View_lim * 2, rxLoc[:, 2].max() * 1.1) # Create a rectangular prism, rotate and plot block_xyz = np.asarray([ [x1, x1, x2, x2, x1, x1, x2, x2], [y1, y2, y2, y1, y1, y2, y2, y1], [z1, z1, z1, z1, z2, z2, z2, z2], ]) R = MagUtils.rotationMatrix(pinc, pdec) xyz = R.dot(block_xyz).T # Offset the prism to true coordinate offx = prism.xc offy = prism.yc offz = prism.zc # print xyz # Face 1 axs.add_collection3d( Poly3DCollection([ list(zip(xyz[:4, 0] + offx, xyz[:4, 1] + offy, xyz[:4, 2] + offz)) ])) # Face 2 axs.add_collection3d( Poly3DCollection( [ list( zip(xyz[4:, 0] + offx, xyz[4:, 1] + offy, xyz[4:, 2] + offz)) ], facecolors="w", )) # Face 3 axs.add_collection3d( Poly3DCollection([ list( zip( xyz[[0, 1, 5, 4], 0] + offx, xyz[[0, 1, 5, 4], 1] + offy, xyz[[0, 1, 5, 4], 2] + offz, )) ])) # Face 4 axs.add_collection3d( Poly3DCollection([ list( zip( xyz[[3, 2, 6, 7], 0] + offx, xyz[[3, 2, 6, 7], 1] + offy, xyz[[3, 2, 6, 7], 2] + offz, )) ])) # Face 5 axs.add_collection3d( Poly3DCollection([ list( zip( xyz[[0, 4, 7, 3], 0] + offx, xyz[[0, 4, 7, 3], 1] + offy, xyz[[0, 4, 7, 3], 2] + offz, )) ])) # Face 6 axs.add_collection3d( Poly3DCollection([ list( zip( xyz[[1, 5, 6, 2], 0] + offx, xyz[[1, 5, 6, 2], 1] + offy, xyz[[1, 5, 6, 2], 2] + offz, )) ])) axs.set_xlabel("East (Y; m)") axs.set_ylabel("North (X; m)") axs.set_zlabel("Depth (Z; m)") axs.scatter(rxLoc[:, 0], rxLoc[:, 1], zs=rxLoc[:, 2], s=1, alpha=0.5) axs.view_init(View_dip, View_azm) plt.show() return True
def display_model(self, model_info, model_faces=None, with_joints=False, batch_idx=0, plot=False, fig=None, savepath=None): """ Displays mesh batch_idx in batch of model_info, model_info as returned by generate_random_model """ if plot: assert fig is not None else: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') verts, joints = model_info['verts'][batch_idx], model_info['joints'][ batch_idx] if model_faces is None: ax.scatter(verts[:, 0], verts[:, 1], verts[:, 2], alpha=0.2) else: mesh = Poly3DCollection(verts[model_faces], alpha=0.2) #[model_faces] face_color = (141 / 255, 184 / 255, 226 / 255) edge_color = (50 / 255, 50 / 255, 50 / 255) mesh.set_edgecolor(edge_color) mesh.set_facecolor(face_color) ax.add_collection3d(mesh) if with_joints: self.draw_skeleton(joints, ax=ax) #ax.set_xlabel('X') #ax.set_ylabel('Y') #ax.set_zlabel('Z') ax.set_xlim(-0.7, 0.7) ax.set_ylim(-0.7, 0.7) ax.set_zlim(-0.7, 0.7) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) #ax.get_xaxis().set_ticklabels([]) #ax.get_yaxis().set_ticklabels([]) #ax.set_zticklabels([]) ax.view_init(azim=-90, elev=100) #for camera #ax.view_init(azim=-90, elev=10) fig.subplots_adjust(left=0, right=1, bottom=0, top=1) if savepath: print('Saving figure at {}.'.format(savepath)) plt.savefig(savepath, bbox_inches='tight', pad_inches=0) fig.canvas.draw() if plot: return fig w, h = fig.canvas.get_width_height() image = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8') image = image.reshape([w, h, 3]) plt.close() return image
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 plotws(b1, b2, b3): from pylab import figure, show from mpl_toolkits.mplot3d.art3d import Poly3DCollection #draw a vector from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) faces_data, points3d = get_BZ(b1, b2, b3) import json #print(json.dumps(faces_data)) faces_coords = faces_data['faces'] faces_count = defaultdict(int) for face in faces_coords: faces_count[len(face)] += 1 for num_sides in sorted(faces_count.keys()): print("{} faces: {}".format(num_sides, faces_count[num_sides])) fig = figure() ax = fig.add_subplot(111, projection='3d') ax.add_collection3d( Poly3DCollection(faces_coords, linewidth=1, alpha=0.9, edgecolor="k", facecolor="#ccccff")) #draw origin ax.scatter([0], [0], [0], color="g", s=100) axes_length = 1 # Add axes ax.add_artist( Arrow3D((0, axes_length), (0, 0), (0, 0), mutation_scale=20, lw=2, arrowstyle="-|>", color="k")) ax.add_artist( Arrow3D((0, 0), (0, axes_length), (0, 0), mutation_scale=20, lw=2, arrowstyle="-|>", color="k")) ax.add_artist( Arrow3D((0, 0), (0, 0), (0, axes_length), mutation_scale=20, lw=2, arrowstyle="-|>", color="k")) ax.text(axes_length, 0, 0, 'ex', (1, 0, 0)) ax.text(0, axes_length, 0, 'ey', (1, 0, 0)) ax.text(0, 0, axes_length, 'ez', (1, 0, 0)) # three primitive vectors ax.add_artist( Arrow3D((0, b1[0]), (0, b1[1]), (0, b1[2]), mutation_scale=21, lw=1, arrowstyle="-|>", color="r")) ax.add_artist( Arrow3D((0, b2[0]), (0, b2[1]), (0, b2[2]), mutation_scale=21, lw=1, arrowstyle="-|>", color="r")) ax.add_artist( Arrow3D((0, b3[0]), (0, b3[1]), (0, b3[2]), mutation_scale=21, lw=1, arrowstyle="-|>", color="r")) ax.text(b1[0], b1[1], b1[2], 'qlat1', (1, 0, 0)) ax.text(b2[0], b2[1], b2[2], 'qlat2', (1, 0, 0)) ax.text(b3[0], b3[1], b3[2], 'qlat3', (1, 0, 0)) ## import sys, re iii = '' eee = '' x = [''] * 3 y = [''] * 3 n = '' symlfile = 'syml.' + sys.argv[1] sfile = open(symlfile, 'r').read().split('\n') # look for nline # print ('sfile=',sfile) i = 0 for iline in sfile: i = i + 1 ilr = re.split('\s+', iline) n = int(ilr[0]) if (n == 0): break nline = i - 1 #print( 'nline=',nline) for iline in sfile: i = i + 1 #print(i,iline) ilr = re.split('\s+', iline) n = int(ilr[0]) if (n == 0): break x = [float(ilr[i]) for i in range(1, 4)] y = [float(ilr[i]) for i in range(4, 7)] iii = ilr[7] eee = ilr[8] #print( n,x[0:3],y[0:3],iii,eee) ax.add_artist( Arrow3D((x[0], y[0]), (x[1], y[1]), (x[2], y[2]), mutation_scale=11, lw=1, arrowstyle="-|>", color="g")) ax.text(x[0], x[1], x[2], iii, (1, 0, 0)) ax.text(y[0], y[1], y[2], eee, (1, 0, 0)) # # # all face vectors. # for ix in faces_data['triangles_vertices']: #points3d: # vvv=ix # #print(vvv) # #ax.plot((vvv[0],), (vvv[1],), (vvv[2],), "o", color="#ff0000", ms=8, mew=0.5) # ax.add_artist(Arrow3D((0,vvv[0]),(0,vvv[1]),(0,vvv[2]), # mutation_scale=1, lw=.5, arrowstyle="-", color="g")) ## Reset limits # ax.set_xlim(-1,1) # ax.set_ylim(-1,1) # ax.set_zlim(-1,1) ax.axis('off') # ax.view_init(elev=0, azim=60) ax.view_init(elev=0, azim=0) ax.set_aspect('equal') ax.autoscale(True, axis='both') show()
fig = plt.figure() ax = Axes3D(fig) for roi in ROIs: # Concat all vertices x = roi[0]; x = (x - xmin)*dx y = roi[1]; y = (-y + ymin)*dx z = roi[2]; z = -z + zmin z = np.ones(x.shape) * z verts = [list(zip(x,y,z))] # Plot polygons poly = Poly3DCollection(verts) poly.set_color(None) poly.set_edgecolor('b') ax.add_collection3d(poly) # Use scatter plot to plot vertices ax.scatter(x,y,z,c='r') ax.set_xlim(-7.5, 20) ax.set_ylim(-20, 7.5) ax.set_zlim(-14,1) ax.set_xlabel('X') ax.set_ylabel('Y') plt.show()
def print_pore(geom, pores, fig=None, axis_bounds=None): r""" Print all throats around a given pore or list of pores accepted as [1,2,3,...,n] e.g geom.print_pore([34,65,99]) Original vertices plus offset vertices used to create faces and then printed in 3D To print all pores (n) pore_range = np.arange(0,n-1,1) geom.print_pore(pore_range) """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection return_fig = False if len(pores) > 0: net_pores = geom.map_pores(geom._net, pores) centroids = geom["pore.centroid"][pores] #centroids2 = self["pore.com"][pores] #for i,pore in enumerate(pores): # centroids[i]=self["pore.centroid"][pore] #coords = self._net["pore.coords"][net_pores] net_throats = geom._net.find_neighbor_throats(pores=net_pores) #for net_throat in net_throats: # try: # throats.append(geom['throat.map'].tolist().index(net_throat)) # except ValueError: # " Throat not in this geometry " throats = geom._net.map_throats(geom, net_throats, return_mapping=True)["target"] "Can't create volume from one throat" if len(throats) >= 1: verts = geom['throat.vertices'][throats] normals = geom['throat.normal'][throats] " Get verts in hull order " ordered_verts = [] for i in range(len(verts)): vert_2D = tr.rotate_and_chop(verts[i], normals[i], [0, 0, 1]) hull = ConvexHull(vert_2D, qhull_options='QJ Pp') ordered_verts.append(verts[i][hull.vertices]) offsets = geom['throat.offset_vertices'][throats] ordered_offs = [] for i in range(len(offsets)): offs_2D = tr.rotate_and_chop(offsets[i], normals[i], [0, 0, 1]) offs_hull = ConvexHull(offs_2D, qhull_options='QJ Pp') ordered_offs.append(offsets[i][offs_hull.vertices]) "Get domain extents for setting axis " if axis_bounds is None: [xmin, xmax, ymin, ymax, zmin, zmax] = vertex_dimension(geom._net, pores, parm='minmax') else: [xmin, xmax, ymin, ymax, zmin, zmax] = axis_bounds if fig is None: fig = plt.figure() else: return_fig == True ax = fig.gca(projection='3d') outer_items = Poly3DCollection(ordered_verts, linewidths=1, alpha=0.2, zsort='min') outer_face_colours = [(1, 0, 0, 0.01)] outer_items.set_facecolor(outer_face_colours) ax.add_collection(outer_items) inner_items = Poly3DCollection(ordered_offs, linewidths=1, alpha=0.2, zsort='min') inner_face_colours = [(0, 0, 1, 0.01)] inner_items.set_facecolor(inner_face_colours) ax.add_collection(inner_items) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.set_zlim(zmin, zmax) #ax.scatter(coords[:,0],coords[:,1],coords[:,2]) ax.scatter(centroids[:, 0], centroids[:, 1], centroids[:, 2], c='y') #ax.scatter(centroids2[:,0],centroids2[:,1],centroids2[:,2],c='g') plt.show() else: print_throat(throats) else: print("Please provide pore indices") if return_fig == True: return fig
def display_hand_matplot( mano_blob, faces, ax=None, alpha=0.2, cam_view=False, batch_idx=0, show=True, ): """ Displays hand batch_idx in batch of hand_info, hand_info as returned by generate_random_hand """ from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection if ax is None: fig = plt.figure() ax = fig.add_subplot(111, projection="3d") verts, joints = mano_blob.verts[batch_idx], mano_blob.joints[batch_idx] mesh = Poly3DCollection(verts[faces], alpha=alpha) face_color = (141 / 255, 184 / 255, 226 / 255) edge_color = (50 / 255, 50 / 255, 50 / 255) mesh.set_edgecolor(edge_color) mesh.set_facecolor(face_color) ax.add_collection3d(mesh) # region: joint color >>>>>>> ax.scatter(joints[0, 0], joints[0, 1], joints[0, 2], s=42, color="c", marker="p") ax.scatter(joints[1, 0], joints[1, 1], joints[1, 2], color="y", marker="s") ax.scatter(joints[2, 0], joints[2, 1], joints[2, 2], color="y", marker="^") ax.scatter(joints[3, 0], joints[3, 1], joints[3, 2], color="y", marker="o") ax.scatter(joints[4, 0], joints[4, 1], joints[4, 2], color="y", marker="*") ax.scatter(joints[5, 0], joints[5, 1], joints[5, 2], color="r", marker="s") ax.scatter(joints[6, 0], joints[6, 1], joints[6, 2], color="r", marker="^") ax.scatter(joints[7, 0], joints[7, 1], joints[7, 2], color="r", marker="o") ax.scatter(joints[8, 0], joints[8, 1], joints[8, 2], color="r", marker="*") ax.scatter(joints[9, 0], joints[9, 1], joints[9, 2], color="b", marker="s") ax.scatter(joints[10, 0], joints[10, 1], joints[10, 2], color="b", marker="^") ax.scatter(joints[11, 0], joints[11, 1], joints[11, 2], color="b", marker="o") ax.scatter(joints[12, 0], joints[12, 1], joints[12, 2], color="b", marker="*") ax.scatter(joints[13, 0], joints[13, 1], joints[13, 2], color="g", marker="s") ax.scatter(joints[14, 0], joints[14, 1], joints[14, 2], color="g", marker="^") ax.scatter(joints[15, 0], joints[15, 1], joints[15, 2], color="g", marker="o") ax.scatter(joints[16, 0], joints[16, 1], joints[16, 2], color="g", marker="*") ax.scatter(joints[17, 0], joints[17, 1], joints[17, 2], color="m", marker="s") ax.scatter(joints[18, 0], joints[18, 1], joints[18, 2], color="m", marker="^") ax.scatter(joints[19, 0], joints[19, 1], joints[19, 2], color="m", marker="o") ax.scatter(joints[20, 0], joints[20, 1], joints[20, 2], color="m", marker="*") # endregion <<<<<<<<<< if cam_view: ax.view_init(azim=-90.0, elev=-90.0) cam_equal_aspect_3d(ax, verts.numpy()) if show: plt.show()
(z_max - z_min) / size]) offsetAOM = np.array([x_min, y_min, z_min]) #Detuining freq scale = np.array([ 2 * (x_max - x_min) / (size - 1), 2 * (y_max - y_min) / (size - 1), (z_max - z_min) / (size - 1) ]) offset = np.array([2 * x_min - 180, 2 * y_min - 180, z_min]) # Fancy indexing: `verts[faces]` to generate a collection of triangles params = scale * verts[faces] + offset paramsAOM = scaleAOM * verts[faces] + offsetAOM mesh = Poly3DCollection(params) mesh.set_edgecolor('k') mesh.set_linewidth(0.1) ax.add_collection3d(mesh) ax.set_xlabel(gp.fields[indexes[0][0]]) ax.set_ylabel(gp.fields[indexes[0][1]]) ax.set_zlabel(gp.fields[indexes[0][2]]) ax.set_xlim(x_min * 2 - 180, x_max * 2 - 180) ax.set_ylim(y_min * 2 - 180, y_max * 2 - 180) ax.set_zlim(z_min, z_max) fname = '3dContuour' pl.savefig(fname + '.eps', bbox_inches='tight') pl.savefig(fname + '.png', bbox_inches='tight')
x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, color='y', alpha=0.1) # plot generator points ax.plot(points[:, 0], points[:, 1], points[:, 2], 'b.') # plot Voronoi vertices ax.plot(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2], 'g.') # indicate Voronoi regions (as Euclidean polygons) for region in sv.regions: random_color = colors.rgb2hex(np.random.rand(3)) polygon = Poly3DCollection([sv.vertices[region]], alpha=1.0) polygon.set_color(random_color) ax.add_collection3d(polygon) plt.show()
def do_3d_projection(self, renderer): # if not hasattr(renderer, 'use_gl'): if hasattr(renderer, '_gl_renderer'): return Poly3DCollection.do_3d_projection(self,renderer)
#loop over them, see Matlab code # for each tri on that face, two loops f = int(sphere_tuples[0][0]) s = int(sphere_tuples[0][1]) t = int(sphere_tuples[0][2]) #quiz: don't use append def extractPoints(data): points = [] for v in data.vertices: q=[None]*3 #preallocation for i in range(3): q[i]=v['point'][i].real points.append(q) return points points = extractPoints(sphere_data) # here (T grows through the loop) T = [] T=[[points[f],points[s],points[t]]] ax.add_collection3d(Poly3DCollection(T)) 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 image_plot(pairs, img, name, depth_only): skeleton = [] fig1 = plt.figure(figsize=(6, 8)) #### image plot ################ ax = fig1.add_subplot(2, 1, 1) iters2 = 0 for t in pairs.keys(): if pairs[t][-1] == -1: continue ### only perform for keypoints more than joints ## for very close part, the wrong association can have large disparity diffference depth = pairs[t][-1][1] sca_c = 'b' dist = pairs[t][-1][0] kp = pairs[t][0].reshape(1, -1)[0] sks = np.array(COCO_PERSON_SKELETON) - 1 x = kp[0::3] y = kp[1::3] v = kp[2::3] for sk in sks: if np.all(v[sk] > 0): plt.plot(x[sk], y[sk], linewidth=0.3, color='r') plt.plot(x[v > 0], y[v > 0], 'o', markersize=2.5, markerfacecolor=sca_c, markeredgecolor='k', markeredgewidth=0.5) plt.plot(x[v > 1], y[v > 1], 'o', markersize=2.5, markerfacecolor=sca_c, markeredgecolor='k', markeredgewidth=0.5) if depth[depth > 0].var() > 200: continue if round(dist, 1) < 12: plt.text(np.mean(x[x > 0]) - 10, y[y > 0].min() + 5 * (iters2 - 3), round(dist, 1), c='w', fontsize=10, weight="bold", bbox=dict(facecolor='black', alpha=0.5, boxstyle='round')) else: plt.text(np.mean(x[x > 0]) - 10, y[y > 0].min() + 5 * (iters2 - 3), round(dist, 1), c='w', fontsize=6, weight="bold", bbox=dict(facecolor='black', alpha=0.5, boxstyle='round')) iters2 += 1 ax.set_title('left stereo image') ax.imshow(img) #### skeleton plot ################## if not depth_only: ax = fig1.add_subplot(2, 1, 2, projection='3d') ax.set_zlabel('y') ax.set_ylabel('x') ax.set_xlabel('depth') ax.set_title('3D Pose') ax.set_ylim3d(0, img.shape[1]) ax.set_zlim3d(0, img.shape[0]) ax.set_xlim3d(0, 40) nums = [] iters = 0 for t in pairs.keys(): if pairs[t][-1] == -1: continue value = pairs[t][0] value[:, 2] = pairs[t][-1][1] Z = np.copy(value) if len(Z[:, 2][Z[:, 2] > 0]) < 5: continue dist = pairs[t][-1][0] if dist[dist > 0].var() > 200: nums.append(iters) iters += 1 continue Z[:, 2][abs(Z[:, 2] - np.median(Z[:, 2][Z[:, 2] > 0])) > 5] = 0 Z1 = np.copy(Z[Z[:, 2] != 0]) Z1[:, 2][Z1[:, 2] - np.median(Z1[:, 2][Z1[:, 2] > 0]) > 5] = 0 if len(Z1) == 0: nums.append(iters) for i in COCO_PERSON_SKELETON: a, b = i if Z[a - 1, 2] == 0 or Z[b - 1, 2] == 0: continue else: skeleton.append([[Z[a - 1][2], Z[a - 1][0], Z[a - 1][1]], [Z[b - 1][2], Z[b - 1][0], Z[b - 1][1]]]) iters += 1 # plot sides ax.add_collection3d( Poly3DCollection(skeleton, edgecolors='r', alpha=.25)) ax.scatter(Z1[:, 2], Z1[:, 0], Z1[:, 1], c='b') # rotate the axes and update for angle in range(0, 360): ax.view_init(210, angle) plt.savefig(name.split('.')[0] + '_result.png') fig1.canvas.draw()
def plot_power_density_stl(P, title='Power Density [$W/mm^2$]', elev=30, azim=30, alpha=0.8, bbox_inches='tight', transparent=True, ofile=None, colorbar=True): pmax = max([p[1] for p in P]) pmin = min([p[1] for p in P]) m = cm.ScalarMappable(cm.viridis) #m.set_array([p[1]/pmax for p in P]) xmax = ymax = zmax = -99999 xmin = ymin = zmin = +99999 for p in P: xmax = max([xmax, p[0][0][0], p[0][1][0], p[0][2][0]]) xmin = min([xmin, p[0][0][0], p[0][1][0], p[0][2][0]]) zmax = max([zmax, p[0][0][1], p[0][1][1], p[0][2][1]]) zmin = min([zmin, p[0][0][1], p[0][1][1], p[0][2][1]]) ymax = max([ymax, p[0][0][2], p[0][1][2], p[0][2][2]]) ymin = min([ymin, p[0][0][2], p[0][1][2], p[0][2][2]]) fig = plt.figure() ax = Axes3D(fig) for p in P: pp = copy.deepcopy(p) pp[0][0][1] = p[0][0][2] pp[0][0][2] = p[0][0][1] pp[0][1][1] = p[0][1][2] pp[0][1][2] = p[0][1][1] pp[0][2][1] = p[0][2][2] pp[0][2][2] = p[0][2][1] triangle = Poly3DCollection([pp[0]], alpha=alpha, edgecolors='b', linewidths=0.05) triangle.set_facecolor(m.to_rgba(pp[1] / pmax)) #triangle.set_facecolor([1, 1-p[1]/pmax, 1-p[1]/pmax]) ax.add_collection3d(triangle) #ax.view_init(elev=elev, azim=azim) plt.title(title) ax.invert_xaxis() ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) ax.set_zlim([zmin, zmax]) ax.set_xlabel('X [m]') ax.set_ylabel('Z [m]') ax.set_zlabel('Y [m]') if colorbar is True: sm = plt.cm.ScalarMappable(cmap=cm.viridis, norm=plt.Normalize(vmin=pmin, vmax=pmax)) sm._A = [] plt.colorbar(sm, format='%.0e') if ofile is not None: plt.savefig(ofile, bbox_inches=bbox_inches, transparent=transparent) plt.show() return
#celda.vor_gal_id(cv[2]) # vol_void = [] for i in range(len(cv)): celda.vor_gal_id(cv[i]) vol_void.append(celda.vol) vol_V = sum(vol_void) r_void = np.cbrt(3. / 4. / np.pi * vol_V) # f = plt.figure(figsize=(8, 6)) ax = f.add_subplot(111, projection='3d') points = celda.vor_tess.points[cv] bg = celda.vor_tess.points ax.plot(points[:, 0], points[:, 1], points[:, 2], 'r+') ax.plot(bg[:, 0], bg[:, 1], bg[:, 2], 'k.', ms=1.) for i in range(len(cv)): celda.vor_gal_id(cv[i]) faces = celda.faces for j in range(len(faces)): poli = Poly3DCollection([faces[j]]) poli.set_edgecolor('black') poli.set_facecolor('red') ax.add_collection(poli) plt.show() def test_nearest_gal_neigh(): for i in range(len(dim2.gals_zobov)): assert i == dim2.nearest_gal_neigh(dim2.gals_zobov[i], coordinates='com')
def isosurface(data, isovalue, name, dpi=30, frame=5, angleH=15, angleV=60, dx=40, dy=40, dz=10, D=400): import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection from matplotlib import animation from skimage import measure if not os.path.exists(name): os.makedirs(name) nx, ny, nz, nt = shape(data) t = 0 fig = plt.figure(figsize=(30, 30 * 2.5)) ax = fig.add_subplot(111, projection='3d', facecolor='w', label='Inline label') while (t < nt): percent = np.str(np.round(t / nt * 100)) + "%" print('{}\r'.format(percent), end="") title_name = name + ' Time:' + str(t) fr = 0 vol = data[:, :, :, t] datamax = vol.max() datamin = vol.min() while (isovalue >= datamax or isovalue <= datamin): t = t + 1 fr = fr + 1 if (fr == frame): fr = 0 vol = data[:, :, :, t] datamax = vol.max() datamin = vol.min() verts, faces, _, _ = measure.marching_cubes_lewiner(vol, isovalue, spacing=(dx, dy, dz)) mesh = Poly3DCollection(verts[faces]) mesh.set_edgecolor('k') ax.add_collection3d(mesh) ax.view_init(angleH, angleV) ax.set_xlabel("X/D", fontsize=50, labelpad=40) ax.set_ylabel("Y/D", fontsize=50, labelpad=40) ax.set_zlabel("Z/D", fontsize=50, labelpad=100) # Title: namel = len(title_name) namexpos = 0.5 - 0.01 * namel ax.text2D(namexpos, 0.85, title_name, transform=ax.transAxes, fontsize=65) ticnum = 11 ticnumz = 14 xaxis = [] for x in range(np.int(-(ticnum - 1) / 2), np.int((ticnum + 1) / 2)): xaxis.append(((nx - 1) * dx / (ticnum - 1) * x) / D) yaxis = [] for y in range(np.int(-(ticnum - 1) / 2), np.int((ticnum - 1) / 2)): yaxis.append(((ny - 1) * dy / (ticnum - 1) * y) / D) zaxis = [] for z in range(0, np.int((ticnumz + 1))): zaxis.append(z * (dz * nz / ticnumz) / D) ax.set_xticks(np.linspace(0, nx * dx, ticnum)) ax.set_yticks(np.linspace(0, ny * dy, ticnum)) ax.set_xticklabels(xaxis) ax.set_yticklabels(yaxis) ax.invert_yaxis() ax.set_zticks(np.linspace(0, nz * dz, ticnumz + 1)) ax.set_zticklabels(zaxis) ax.tick_params(axis='both', which='major', labelsize=30) plt.tight_layout() bbox = fig.bbox_inches.from_bounds(1, 9, 28, 58) if (t < 10): picname = '00' + str(t) if (t >= 10 and t < 100): picname = '0' + str(t) if (t >= 100): picname = str(t) filename = name + '/' + picname + '.png' plt.savefig(filename, bbox_inches=bbox, dpi=dpi) plt.cla() if (fr == 0): fr = frame else: fr = frame - fr t = t + fr print('Done.')
def print3d_discrete_xy(varx, vary): fxy_inner = varx + vary + 'inner_joint.out' fxy_skewed_inner = varx + vary + 'skinner_joint.out' fxy_skewed_outer = varx + vary + 'skouter_joint.out' fx_outer2 = varx + 'outer.out' fy_outer2 = vary + 'outer.out' fx_inner = varx + 'inner.out' fy_inner = vary + 'inner.out' if (path.isfile(fx_outer2) and path.isfile(fy_outer2)): #fig, ax = plt.subplots(figsize=(width_in_inches, height_in_inches), dpi=dots_per_inch) fig = plt.figure() # ax = fig.add_subplot(1, 1, 1, projection='3d') ax = fig.add_subplot( 111, projection='3d' ) #ax = fig.gca(projection='3d') ##Axes3D(fig) #fig.gca(projection='3d') plt.grid(True, which="both", linestyle='--') # rectangles if (not path.isfile(fxy_skewed_outer)): with open(fx_outer2, 'r') as x_outer2, open(fy_outer2, 'r') as y_outer2: linesx_outer2 = x_outer2.readlines() t1_outer = [float(line.split()[0]) for line in linesx_outer2] xmin_outer2 = [ float(line.split()[1]) for line in linesx_outer2 ] xmax_outer2 = [ float(line.split()[2]) for line in linesx_outer2 ] linesy_outer2 = y_outer2.readlines() ymin_outer2 = [ float(line.split()[1]) for line in linesy_outer2 ] ymax_outer2 = [ float(line.split()[2]) for line in linesy_outer2 ] for t1, xo1, xo2, yo1, yo2 in zip(t1_outer, xmin_outer2, xmax_outer2, ymin_outer2, ymax_outer2): Z = np.array([[xo1, t1, yo1], [xo2, t1, yo1], [xo2, t1, yo2], [xo1, t1, yo2]]) ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2]) verts = [[Z[0], Z[1], Z[2], Z[3]]] ax.add_collection3d( Poly3DCollection(verts, facecolors='g', linewidths=2, edgecolors='g', label='maximal inner-approximation', alpha=.1)) if (path.isfile(fxy_inner) and os.stat(fxy_inner).st_size != 0): with open(fxy_inner, 'r') as xy_inner: linesxy_inner = xy_inner.readlines() t1_inner = [float(line.split()[0]) for line in linesxy_inner] xmin_inner = [float(line.split()[1]) for line in linesxy_inner] xmax_inner = [float(line.split()[2]) for line in linesxy_inner] ymin_inner = [float(line.split()[3]) for line in linesxy_inner] ymax_inner = [float(line.split()[4]) for line in linesxy_inner] for t1, xi1, xi2, yi1, yi2 in zip(t1_inner, xmin_inner, xmax_inner, ymin_inner, ymax_inner): Z = np.array([[xi1, t1, yi1], [xi2, t1, yi1], [xi2, t1, yi2], [xi1, t1, yi2]]) ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2]) verts = [[Z[0], Z[1], Z[2], Z[3]]] ax.add_collection3d( Poly3DCollection(verts, facecolors='orange', linewidths=2, linestyle='--', edgecolors='b', label='maximal inner-approximation', alpha=.3)) # skew box if (path.isfile(fxy_skewed_outer)): with open(fxy_skewed_outer, 'r') as xy_skewed_outer: linesxy_skewed_outer = xy_skewed_outer.readlines() t1_outer = [ float(line.split()[0]) for line in linesxy_skewed_outer ] x1_outer = [ float(line.split()[1]) for line in linesxy_skewed_outer ] y1_outer = [ float(line.split()[2]) for line in linesxy_skewed_outer ] x2_outer = [ float(line.split()[3]) for line in linesxy_skewed_outer ] y2_outer = [ float(line.split()[4]) for line in linesxy_skewed_outer ] x3_outer = [ float(line.split()[5]) for line in linesxy_skewed_outer ] y3_outer = [ float(line.split()[6]) for line in linesxy_skewed_outer ] x4_outer = [ float(line.split()[7]) for line in linesxy_skewed_outer ] y4_outer = [ float(line.split()[8]) for line in linesxy_skewed_outer ] patches = [] for t1, xi1, yi1, xi2, yi2, xi3, yi3, xi4, yi4 in zip( t1_outer, x1_outer, y1_outer, x2_outer, y2_outer, x3_outer, y3_outer, x4_outer, y4_outer): Z = np.array([[xi1, t1, yi1], [xi2, t1, yi2], [xi3, t1, yi3], [xi4, t1, yi4]]) # plot vertices ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2]) # list of sides' polygons of figure verts = [[Z[0], Z[1], Z[2], Z[3]]] ax.add_collection3d( Poly3DCollection(verts, facecolors='g', linewidths=2, edgecolors='g', label='maximal inner-approximation', alpha=.1)) if (path.isfile(fxy_skewed_inner)): with open(fxy_skewed_inner, 'r') as xy_skewed_inner: linesxy_skewed_inner = xy_skewed_inner.readlines() t1_inner = [ float(line.split()[0]) for line in linesxy_skewed_outer ] x1_inner = [ float(line.split()[1]) for line in linesxy_skewed_inner ] y1_inner = [ float(line.split()[2]) for line in linesxy_skewed_inner ] x2_inner = [ float(line.split()[3]) for line in linesxy_skewed_inner ] y2_inner = [ float(line.split()[4]) for line in linesxy_skewed_inner ] x3_inner = [ float(line.split()[5]) for line in linesxy_skewed_inner ] y3_inner = [ float(line.split()[6]) for line in linesxy_skewed_inner ] x4_inner = [ float(line.split()[7]) for line in linesxy_skewed_inner ] y4_inner = [ float(line.split()[8]) for line in linesxy_skewed_inner ] for t1, xi1, yi1, xi2, yi2, xi3, yi3, xi4, yi4 in zip( t1_inner, x1_inner, y1_inner, x2_inner, y2_inner, x3_inner, y3_inner, x4_inner, y4_inner): Z = np.array([[xi1, t1, yi1], [xi2, t1, yi2], [xi3, t1, yi3], [xi4, t1, yi4]]) # plot vertices ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2]) # list of sides' polygons of figure verts = [[Z[0], Z[1], Z[2], Z[3]]] ax.add_collection3d( Poly3DCollection(verts, facecolors='orange', linewidths=2, linestyle='--', edgecolors='b', label='maximal inner-approximation', alpha=.3)) if (path.isfile('xi.out')): with open('xi.out', 'r') as xi: lines_xi = xi.readlines() t = [float(line.split()[0]) for line in lines_xi] z1 = [float(line.split()[1]) for line in lines_xi] z2 = [float(line.split()[2]) for line in lines_xi] # ax.scatter3D(z1,t,z2,c='purple',alpha=1.,s=1.,label='estimated reachable states') ax.autoscale() ax.set_xlabel(varx, fontsize="x-large") ax.set_zlabel(vary, fontsize="x-large") ax.set_ylabel('step', fontsize="x-large") ax.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax.zaxis.set_major_locator(mticker.MaxNLocator(5)) # ax.set_zlim3d(0, 25) # plt.legend(fontsize="x-large",loc='center') # plt.legend(fontsize="x-large",loc='lower right') f_output = varx + vary + 'time' plt.savefig(f_output) plt.show() plt.close()
print xn,yn #custom draw surface poly3d = np.zeros((xn*(yn-1), 4, 3)) for yk in range(yn-1): for xk in range(xn): itr = yk*xn+xk if xk==xn-1: poly3d[itr,:,:] = [[X[xk, yk] , Y[xk, yk] , W[xk, yk] ], [X[0, yk] , Y[0, yk] , W[0, yk] ], [X[0, yk+1] , Y[0, yk+1] , W[0, yk+1] ], [X[xk, yk+1] , Y[xk, yk+1] , W[xk, yk+1]]] else: poly3d[itr,:,:] = [[X[xk, yk] , Y[xk, yk] , W[xk, yk] ], [X[xk+1, yk] , Y[xk+1, yk] , W[xk+1, yk] ], [X[xk+1, yk+1] , Y[xk+1, yk+1] , W[xk+1, yk+1]], [X[xk, yk+1] , Y[xk, yk+1] , W[xk, yk+1] ]] plt.xlim(-2.1,2.1) plt.ylim(-2.1,2.1) ax.add_collection3d(Poly3DCollection(poly3d, facecolors='#77dd77', linewidths=1,alpha=.5)) ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=.2)) #ax.plot_surface(X, Y, W, rstride=1, cstride=1, cmap=cm.jet) #ax.plot_wireframe(X, Y, W, rstride=5, cstride=5) #ax.contourf(X, Y, W, zdir='z', offset=-1, cmap=cm.coolwarm) plt.show()
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel(), zz.ravel()]) Z = Z.reshape(xx.shape) plt.title("Novelty Detection") ax = plt.gca(projection='3d') b1 = ax.scatter(X_train[:, 0], X_train[:, 1], X_train[:, 2], c='white') b2 = ax.scatter(X_test[:, 0], X_test[:, 1], X_test[:, 2], c='green') c = ax.scatter(X_outliers[:, 0], X_outliers[:, 1], X_outliers[:, 2], c='red') verts, faces = measure.marching_cubes(Z, 0) 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] mesh = Poly3DCollection(verts[faces], facecolor='orange', edgecolor='gray', alpha=0.3) ax.add_collection3d(mesh) ax.set_xlim((-10, 10)) ax.set_ylim((-10, 10)) ax.set_zlim((-10, 10)) ax.axis('tight') ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.legend([mpatches.Patch(color='orange', alpha=0.3), b1, b2, c], [ "learned frontier", "training observations", "new regular observations", "new abnormal observations" ],
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' print("{}/{}".format(frame, frames)) 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])) colorMap = {GcasAutopilot.STATE_START:'red', GcasAutopilot.STATE_ROLL: 'blue', \ GcasAutopilot.STATE_PULL:'green', GcasAutopilot.STATE_DONE:'magenta'} mode = modes[frame] col = colorMap[mode] mode_text.set_color(col) mode_text.set_text('Mode: {}'.format(mode)) 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 = 60 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 createPics(tracks): fontfile = os.path.join(os.path.dirname(__file__), 'Fonts/FreeSans.ttf') randFilename = random.randrange(0, 100001, 2) #PIL_images_dir = os.path.join(os.path.dirname(__file__) , 'tmp/') profile_filename = 'tmp/profile' + str(randFilename) # serialize tracks track = [] for t in tracks: track.extend(t) """ # set scales: maxDist=track[len(track)-1]['dist'] minEle=track[0]['ele'] maxEle=track[0]['ele'] for t in track: if t['ele'] !=0: # discontinuities if t['ele'] < minEle: minEle=t['ele'] if t['ele'] > maxEle: maxEle=t['ele'] # Set format maxDistValue=" %.1fkm" % maxDist minEleValue=" %.fm" % minEle maxEleValue=" %.fm" % maxEle minLat=track[0]['lat'] maxLat=track[0]['lat'] for t in track: if t['ele'] !=0: # discontinuities if t['lat'] < minLat: minLat=t['lat'] if t['lat'] > maxLat: maxLat=t['lat'] minLon=track[0]['lon'] maxLon=track[0]['lon'] for t in track: if t['ele'] !=0: # discontinuities if t['lon'] < minLon: minLon=t['lon'] if t['lon'] > maxLon: maxLon=t['lon'] # Set markers near the track fourth #~ markers=[] #~ for i in range(1, len(track)): #~ if track[i-1]['dist'] < maxDist/4 and track[i]['dist'] > maxDist/4: #~ markers.append(track[i]) #~ if track[i-1]['dist'] < maxDist/2 and track[i]['dist'] > maxDist/2: #~ markers.append(track[i]) #~ if track[i-1]['dist'] < maxDist*3/4 and track[i]['dist'] > maxDist*3/4: #~ markers.append(track[i]) # Set the route points points=[] for t in tracks: points.append(t[-1]) points=points[:-1] # Provide a reasonable scale for flat tracks if (maxEle - minEle) < 50: maxEle = (maxEle + minEle)/2 + 25 minEle = (maxEle + minEle)/2 - 25 #--------------------------------------------- #------- draw the elevation profile ---------- #--------------------------------------------- # All sizes are *2 then we downsample for aliasing sans=ImageFont.truetype(fontfile,10*2) #sans=ImageFont.truetype('FreeSans.ttf',10*2) # XX width=250*2 height=120*2 margin=15 marginLeft=sans.getsize(str(maxEleValue))[0] marginBottom=sans.getsize(str(maxDistValue))[1] plotHeight=height-2*margin-marginBottom plotWidth=width-2*margin-marginLeft im = Image.new('RGB',(width,height),'#FFFFFF') draw = ImageDraw.Draw(im) #Draw plot # draw elevation grid (20m) for i in range(int(minEle/20), int(maxEle/20)+1): if i*20 > minEle and i*20< maxEle: x1=margin+marginLeft y =height-marginBottom-(i*20-minEle)/(maxEle-minEle)*plotHeight x2=width-margin draw.line((x1,y,x2,y),fill='#BBBBBB',width=1) # draw profile for i in range(1, len(track)): x1=margin+marginLeft+track[i-1]['dist']/maxDist*plotWidth y1=height-marginBottom-(track[i-1]['ele']-minEle)/(maxEle-minEle)*plotHeight x2=margin+marginLeft+track[i]['dist']/maxDist*plotWidth y2=height-marginBottom-(track[i]['ele']-minEle)/(maxEle-minEle)*plotHeight if track[i]['ele'] == 0 or track[i-1]['ele'] == 0: # discontinuities draw.line((x1,y1,x2,y2),fill='#606060',width=1) else: draw.line((x1,y1,x2,y2),fill='#808080',width=3) # Draw point at start, end r = 15 x1=margin+marginLeft+track[0]['dist']/maxDist*plotWidth y1=height-marginBottom-(track[0]['ele']-minEle)/(maxEle-minEle)*plotHeight x2=margin+marginLeft+track[len(track)-1]['dist']/maxDist*plotWidth y2=height-marginBottom-(track[len(track)-1]['ele']-minEle)/(maxEle-minEle)*plotHeight draw.ellipse((x1-r/2,y1-r/2,x1+r/2,y1+r/2), fill='#AAAAAA', outline='#000000') draw.ellipse((x2-r/2,y2-r/2,x2+r/2,y2+r/2), fill='#000000') # Draw points on route points r = 8 for point in points: x1=margin+marginLeft+point['dist']/maxDist*plotWidth y1=height-marginBottom-(point['ele']-minEle)/(maxEle-minEle)*plotHeight draw.ellipse((x1-r/2,y1-r/2,x1+r/2,y1+r/2), fill='#FFFFFF', outline='#000000') # draw a white rectangle under the scales: x = 0 y = height-marginBottom +2 draw.rectangle((x,y,width,height),\ fill='#EEEEEE', outline='#EEEEEE') draw.rectangle((0,0,marginLeft,height),\ fill='#EEEEEE', outline='#EEEEEE') # Draw scales: #~ draw.text((margin+marginLeft,height-marginBottom),'0',fill='#000000',font=sans) #~ draw.text((width-sans.getsize(str(maxDistValue))[0],\ #~ height-marginBottom),str(maxDistValue),fill='#000000',font=sans) draw.text((2,height-marginBottom - sans.getsize('1')[1]/2),minEleValue,fill='#000000',font=sans) draw.text((2,\ height-marginBottom-plotHeight - sans.getsize('1')[1]/2),maxEleValue,fill='#000000',font=sans) #Draw markers #~ for m in markers: #~ mDist=" %.1fkm" % m['dist'] #~ x=margin+marginLeft+m['dist']/maxDist*plotWidth\ #~ -sans.getsize(str(m['dist']))[0]/2 #~ y=height-marginBottom #~ draw.text((x,y),mDist,fill='#000000',font=sans) del draw resolution=(int(width/2),int(height/2)) im = im.resize(resolution,Image.ANTIALIAS) outname=PIL_images_dir + profile_filename im.save(outname, "PNG") """ lats = [] lons = [] eles = [] dists = [] for t in tracks: lats.append(t['lat']) lons.append(t['lon']) eles.append(t['ele']) dists.append(t['dist']) #~ plt.plot(lons,lats) #~ plt.show() #~ fig = plt.figure() #~ ax = fig.gca(projection='3d') #~ ax.fill(lons,lats,eles,'r') #~ plt.show() #~ exit(0) xs = lons ys = lats zs = eles ls = dists ### 3D plot # Code to convert data in 3D polygons v = [] h = min(zs) for k in range(0, len(xs) - 1): x = [xs[k], xs[k + 1], xs[k + 1], xs[k]] y = [ys[k], ys[k + 1], ys[k + 1], ys[k]] z = [zs[k], zs[k + 1], h, h] v.append(zip(x, y, z)) poly3dCollection = Poly3DCollection(v, facecolors=(0.4, 0.4, 0.4, 0.5), edgecolors='none') dpi = 100 width = 200 height = 150 # Code to plot the 3D polygons plt.rcParams['axes.labelsize'] = 1 fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) #~ ax = Axes3D(fig) ax = fig.gca(projection='3d') ax.add_collection3d(poly3dCollection) ax.set_xlim([min(xs), max(xs)]) ax.set_ylim([min(ys), max(ys)]) ax.set_zlim([min(zs), max(zs)]) #~ ax.set_axis_off() # 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)) # Get rid of the ticks ax.zaxis._axinfo['tick']['inward_factor'] = 0 ax.zaxis._axinfo['tick']['outward_factor'] = 0.2 ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([int(min(zs)), int(max(zs))]) ax.set_zticks([]) zed = [tick.label.set_fontsize(7) for tick in ax.zaxis.get_major_ticks()] plt.tight_layout(pad=0.1) fig.savefig(profile_filename + '-3d.png', dpi=dpi) #plt.show() ### Way plot fig, ax = plt.subplots() fig.set_size_inches(width / dpi, height / dpi, forward=True) fig.set_dpi(dpi) ax.set_xticks([]) ax.set_yticks([]) plt.axis('off') ax.plot(xs, ys, alpha=0.6, linewidth=3, color='r') ax.set_xlim([ min(xs) - (max(xs) - min(xs)) / 10, max(xs) + (max(xs) - min(xs)) / 10 ]) ax.set_ylim([ min(ys) - (max(ys) - min(ys)) / 10, max(ys) + (max(ys) - min(ys)) / 10 ]) l = sqrt((max(xs) - min(xs))**2 + ((max(ys) - min(ys))**2)) / 10 a = math.atan(1 / (xs[1] - xs[0]) * (ys[1] - ys[0])) y2 = ys[0] + math.sin(a) * l x2 = xs[0] + math.cos(a) * l arrow = dict(facecolor=(0.1, 0.1, 0.1), edgecolor=(0.1, 0.1, 0.1), headwidth=6, frac=0.3, width=2) plt.annotate(s='', xy=(x2, y2), xytext=(xs[0], ys[0]), arrowprops=arrow) plt.tight_layout(pad=0.1) fig.savefig(profile_filename + '-2d.png', dpi=dpi) #~ plt.show() ### profileplot fig, ax = plt.subplots() fig.set_size_inches(width / dpi, height / dpi, forward=True) fig.set_dpi(dpi) ax.set_xticks([]) #~ ax.set_yticks([]) #~ plt.axis('off') ax.spines['bottom'].set_color((1.0, 1.0, 1.0, 0.5)) ax.spines['top'].set_color((1.0, 1.0, 1.0, 0)) ax.spines['left'].set_color((1.0, 1.0, 1.0, 0)) ax.spines['right'].set_color((1.0, 1.0, 1.0, 0)) ax.tick_params(axis='y', colors=(0, 0, 0, 0.7)) ax.plot(ls, zs, alpha=0.6, linewidth=1, color=(0.5, 0.5, 0.5)) ax.fill_between(ls, min(zs), zs, facecolor=(0, 0, 0, 0.3), interpolate=True) ax.set_yticks([int(min(zs)), int(max(zs))]) zed = [tick.label.set_fontsize(7) for tick in ax.yaxis.get_major_ticks()] plt.tight_layout(pad=0.1) fig.savefig(profile_filename + '-ele.png', dpi=dpi) return profile_filename
def show_3d_survey_geometry(self, elev, azim, show_block=False): X1, X2 = -250.0, 250.0 Y1, Y2 = -250.0, 250.0 Z1, Z2 = -400.0, 0.0 def polyplane(verts, alpha=0.1, color="green"): poly = Poly3DCollection(verts) poly.set_alpha(alpha) poly.set_facecolor(color) return poly z1 = -100.0 x = np.r_[X1, X2, X2, X1, X1] y = np.ones(5) * 0.0 z = np.r_[Z1, Z1, Z2, Z2, Z1] verts = [list(zip(x, y, z))] polyplane(verts, color="green") x = np.r_[X1, X2, X2, X1, X1] y = np.r_[Y1, Y1, Y2, Y2, Y1] z = np.ones(5) * 0.0 verts = [list(zip(x, y, z))] polyplane(verts, color="grey") x = np.r_[X1, X2, X2, X1, X1] y = np.r_[Y1, Y1, Y2, Y2, Y1] z = np.ones(5) * z1 verts = [list(zip(x, y, z))] polyplane(verts, color="grey") fig = plt.figure(figsize=(8, 8)) ax = fig.gca(projection="3d") ax.plot3D(np.r_[-200, 200], np.r_[0, 0], np.r_[1, 1] * 0.0, "r-", lw=3) ax.plot3D( self.mesh.gridCC[:, 0], self.mesh.gridCC[:, 1], np.zeros_like(self.mesh.gridCC[:, 0]), "k.", ) ax.legend(("Tx", "Rx"), loc=1) if show_block: xc, yc, zc = 0, 0, 0 x1, x2 = -40, 40 y1, y2 = -40, 40 z1, z2 = -160, -80 x = np.r_[x1, x2, x2, x1, x1] y = np.ones(5) * 0.0 z = np.r_[z1, z1, z2, z2, z1] ax.plot3D(x, y, z, "k--") x = np.r_[x1, x2, x2, x1, x1] y = np.r_[y1, y1, y2, y2, y1] z = np.ones(5) * (z1 + z2) / 2.0 ax.plot3D(x, y, z, "k--") block_xyz = np.asarray([ [x1, x1, x2, x2, x1, x1, x2, x2], [y1, y2, y2, y1, y1, y2, y2, y1], [z1, z1, z1, z1, z2, z2, z2, z2], ]) xyz = block_xyz.T # Face 1 ax.add_collection3d( Poly3DCollection( [ list( zip(xyz[:4, 0] + xc, xyz[:4, 1] + yc, xyz[:4, 2] + zc)) ], facecolors="k", alpha=0.5, )) # Face 2 ax.add_collection3d( Poly3DCollection( [ list( zip(xyz[4:, 0] + xc, xyz[4:, 1] + yc, xyz[4:, 2] + zc)) ], facecolors="k", alpha=0.5, )) # Face 3 ax.add_collection3d( Poly3DCollection( [ list( zip( xyz[[0, 1, 5, 4], 0] + xc, xyz[[0, 1, 5, 4], 1] + yc, xyz[[0, 1, 5, 4], 2] + zc, )) ], facecolors="k", alpha=0.5, )) # Face 4 ax.add_collection3d( Poly3DCollection( [ list( zip( xyz[[3, 2, 6, 7], 0] + xc, xyz[[3, 2, 6, 7], 1] + yc, xyz[[3, 2, 6, 7], 2] + zc, )) ], facecolors="k", alpha=0.5, )) # Face 5 ax.add_collection3d( Poly3DCollection( [ list( zip( xyz[[0, 4, 7, 3], 0] + xc, xyz[[0, 4, 7, 3], 1] + yc, xyz[[0, 4, 7, 3], 2] + zc, )) ], facecolors="k", alpha=0.5, )) # Face 6 ax.add_collection3d( Poly3DCollection( [ list( zip( xyz[[1, 5, 6, 2], 0] + xc, xyz[[1, 5, 6, 2], 1] + yc, xyz[[1, 5, 6, 2], 2] + zc, )) ], facecolors="k", alpha=0.5, )) ax.set_xlim(X1, X2) ax.set_ylim(Y1, Y2) ax.set_zlim(Z1, Z2) ax.set_xlabel("X (m)") ax.set_ylabel("Y (m)") ax.set_zlabel("Depth (m)") # ax.set_aspect("equal") ax.view_init(elev=elev, azim=azim) plt.show()
# list of faces faces = [[Z[0], Z[1], Z[2], Z[3]], [Z[4], Z[5], Z[6], Z[7]], [Z[0], Z[1], Z[5], Z[4]], [Z[2], Z[3], Z[7], Z[6]], [Z[1], Z[2], Z[6], Z[5]], [Z[4], Z[7], Z[3], Z[0]]] # Plot the cube in 3D from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.add_collection3d( Poly3DCollection(faces, facecolors='cyan', linewidths=1, edgecolors='r', alpha=.75)) ax.scatter(Z[:, 0], Z[:, 1], Z[:, 2]) ax.set_xlim(0, 11), ax.set_ylim(0, 11), ax.set_zlim(0, 11) ax.set_aspect('equal') # uniform scale axes #Use the same method from before to project the 3D points to 2D pts2d = None # TODO: your code here K = np.array([[800, 0, 320], [0, 800, 240], [0, 0, 1]], dtype=np.float32) pts2d = cv2.projectPoints(np.float32(Z), rvec=(0, 0, 0), tvec=(0, 0, 0), cameraMatrix=K, distCoeffs=None)[0]
def ShowDeformation(t=0): I = np.eye(3) F = I + (DeformationGradient - I) * t Y1 = F.dot(X1) Y2 = F.dot(X2) Y3 = F.dot(X3) Y4 = F.dot(X4) P1 = np.array([X1[0][0], X1[1][0], X1[2][0]]) P2 = np.array([X2[0][0], X2[1][0], X2[2][0]]) P3 = np.array([X3[0][0], X3[1][0], X3[2][0]]) P4 = np.array([X4[0][0], X4[1][0], X4[2][0]]) # vertices of a pyramid Vertices = np.array([P1, P2, P3, P4]) Center1 = Vertices.sum(axis=0) / 4 Vectors1 = Vertices - Center1 plt.cla() Axis.scatter3D(Vertices[:, 0], Vertices[:, 1], Vertices[:, 2], facecolor="blue") # generate list of sides' polygons of our pyramid Faces = [[Vertices[0], Vertices[1], Vertices[2]], [Vertices[0], Vertices[1], Vertices[3]], [Vertices[0], Vertices[2], Vertices[3]], [Vertices[1], Vertices[2], Vertices[3]]] # plot sides Axis.add_collection3d( Poly3DCollection(Faces, facecolors='blue', linewidths=1, edgecolors='blue', alpha=.25)) P1 = np.array([Y1[0][0], Y1[1][0], Y1[2][0]]) P2 = np.array([Y2[0][0], Y2[1][0], Y2[2][0]]) P3 = np.array([Y3[0][0], Y3[1][0], Y3[2][0]]) P4 = np.array([Y4[0][0], Y4[1][0], Y4[2][0]]) # vertices of a pyramid Vertices = np.array([P1, P2, P3, P4]) Center2 = Vertices.sum(axis=0) / 4 Vectors2 = Vertices - Center2 Axis.scatter3D(Vertices[:, 0], Vertices[:, 1], Vertices[:, 2], facecolor="red") # generate list of sides' polygons of our pyramid Faces = [[Vertices[0], Vertices[1], Vertices[2]], [Vertices[0], Vertices[1], Vertices[3]], [Vertices[0], Vertices[2], Vertices[3]], [Vertices[1], Vertices[2], Vertices[3]]] # plot sides Axis.add_collection3d( Poly3DCollection(Faces, facecolors='red', linewidths=1, edgecolors='red', alpha=.25)) # add displacement arrows Axis.quiver(X1[0][0], X1[1][0], X1[2][0], Y1[0][0] - X1[0][0], Y1[1][0] - X1[1][0], Y1[2][0] - X1[2][0], color=(0, 0, 0), linewidth=2) Axis.quiver(X2[0][0], X2[1][0], X2[2][0], Y2[0][0] - X2[0][0], Y2[1][0] - X2[1][0], Y2[2][0] - X2[2][0], color=(0, 0, 0), linewidth=2) Axis.quiver(X3[0][0], X3[1][0], X3[2][0], Y3[0][0] - X3[0][0], Y3[1][0] - X3[1][0], Y3[2][0] - X3[2][0], color=(0, 0, 0), linewidth=2) Axis.quiver(X4[0][0], X4[1][0], X4[2][0], Y4[0][0] - X4[0][0], Y4[1][0] - X4[1][0], Y4[2][0] - X4[2][0], color=(0, 0, 0), linewidth=2) # make the panes transparent Axis.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) Axis.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) Axis.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # make the grid lines transparent Axis.xaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) Axis.yaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) Axis.zaxis._axinfo["grid"]['color'] = (1, 1, 1, 0) # modify ticks # Axis.set_xticks([-1, 0, 1]) # Axis.set_yticks([-1, 0, 1]) # Axis.set_zticks([-1, 0, 1]) # set limits Center = (Center1 + Center2) / 2 Vertices1 = Vectors1 + Center1 Vertices2 = Vectors2 + Center2 Vectors1 = Vertices1 - Center Vectors2 = Vertices2 - Center Max = max(np.abs(Vectors1).max(), np.abs(Vectors2).max()) Axis.set_xlim(Center[0] - Max, Center[0] + Max) Axis.set_ylim(Center[1] - Max, Center[1] + Max) Axis.set_zlim(Center[2] - Max, Center[2] + Max) # set axes labels Axis.xaxis.set_rotate_label(False) # disable automatic rotation Axis.yaxis.set_rotate_label(False) # disable automatic rotation Axis.zaxis.set_rotate_label(False) # disable automatic rotation Axis.set_xlabel('e$_1$', rotation=0) Axis.set_ylabel('e$_2$', rotation=0) Axis.set_zlabel('e$_3$', rotation=0) plt.show() return
l_plane = 1.5 c1 = normal + l_plane * default_x_axis + l_plane * default_y_axis c2 = normal + l_plane * default_x_axis - l_plane * default_y_axis c3 = normal - l_plane * default_x_axis - l_plane * default_y_axis c4 = normal - l_plane * default_x_axis + l_plane * default_y_axis x = np.array([c1[0], c2[0], c3[0], c4[0]]) y = np.array([c1[1], c2[1], c3[1], c4[1]]) z = np.array([c1[2], c2[2], c3[2], c4[2]]) verts = [list(zip(x, y, z))] # xx, yy = np.meshgrid(xx, yy) pc = Poly3DCollection(verts, facecolors='C0', alpha=0.5, linewidths=1) pc.set_alpha(0.5) pc.set_facecolor('C0') ax.add_collection3d(pc) palette = sns.color_palette() # plot the axes lines l = 3 ax.plot([0, l], [0, 0], [0, 0], color=palette[0], linewidth=3) ax.plot([0, 0], [0, l], [0, 0], color=palette[1], linewidth=3) ax.plot([0, 0], [0, 0], [0, l], color=palette[2], linewidth=3) ax.plot([-l, 0], [0, 0], [0, 0], color=palette[0], linestyle=':', linewidth=3) ax.plot([0, 0], [-l, 0], [0, 0], color=palette[1], linestyle=':', linewidth=3) ax.plot([0, 0], [0, 0], [-l, 0], color=palette[2], linestyle=':', linewidth=3)
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [0,1,1,0] y = [0,0,1,1] z = [0,1,0,1] verts = [zip(x, y,z)] ax.add_collection3d(Poly3DCollection(verts)) plt.show()
def PlotCell(self, d1, d2, d3, d4, d5, d6, dat, faces, l1, l2, l3, l4, l5, l6, l7, l8, labels, n1, n2, n3, n4, n5, n6, xyz, show=False): from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d from matplotlib.lines import Line2D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt fig = plt.figure(figsize=(10, 10), dpi=90) ax = fig.add_subplot(111, projection='3d') ax.plot([l1[0], l4[0]], [l1[1], l4[1]], [l1[2], l4[2]], 'k-') ax.plot([l4[0], l3[0]], [l4[1], l3[1]], [l4[2], l3[2]], 'k*-.') ax.plot([l3[0], l2[0]], [l3[1], l2[1]], [l3[2], l2[2]], 'k-') ax.plot([l2[0], l1[0]], [l2[1], l1[1]], [l2[2], l1[2]], 'k*-.') ax.plot([l5[0], l8[0]], [l5[1], l8[1]], [l5[2], l8[2]], 'k-') ax.plot([l8[0], l7[0]], [l8[1], l7[1]], [l8[2], l7[2]], 'k*-.') ax.plot([l7[0], l6[0]], [l7[1], l6[1]], [l7[2], l6[2]], 'k-') ax.plot([l6[0], l5[0]], [l6[1], l5[1]], [l6[2], l5[2]], 'k*-.') ax.plot([l1[0], l5[0]], [l1[1], l5[1]], [l1[2], l5[2]], 'k-') ax.plot([l2[0], l6[0]], [l2[1], l6[1]], [l2[2], l6[2]], 'k--') ax.plot([l4[0], l8[0]], [l4[1], l8[1]], [l4[2], l8[2]], 'k-') ax.plot([l3[0], l7[0]], [l3[1], l7[1]], [l3[2], l7[2]], 'k-') ax.scatter(l1[0], l1[1], l1[2], c='r', s=25) ax.scatter(l2[0], l2[1], l2[2], c='g', s=25) ax.scatter(l3[0], l3[1], l3[2], c='y') ax.scatter(l4[0], l4[1], l4[2], c='b') ax.scatter(l5[0], l5[1], l5[2], c='k') ax.scatter(l6[0], l6[1], l6[2], c='k') ax.scatter(l7[0], l7[1], l7[2], c='k') ax.scatter(l8[0], l8[1], l8[2], c='k') ax.scatter(xyz[0], xyz[1], xyz[2], c='y', s=25) ax.set_xlabel("X-Axis") ax.set_ylabel("Y-Axis") ax.set_zlabel("Z-Axis") # ================================================== # Verification Plotting only between double lines. ln1x = [l1[0], xyz[0]] ln1y = [l1[1], xyz[1]] ln1z = [l1[2], xyz[2]] ax.plot(ln1x, ln1y, ln1z, 'k-') ln7x = [l7[0], xyz[0]] ln7y = [l7[1], xyz[1]] ln7z = [l7[2], xyz[2]] ax.plot(ln7x, ln7y, ln7z, 'b-') # =================================================== # ================================================================================= # Verification plotting ONLY between double lines # # # print ("d1: {}".format(d1)) # print ("d2: {}".format(d2)) # print ("d3: {}".format(d3)) # print ("d4: {}".format(d4)) # print ("d5: {}".format(d5)) # print ("d6: {}".format(d6)) dn1 = n1 * d1 dn2 = n2 * d2 dn3 = n3 * d3 dn4 = n4 * d4 dn5 = n5 * d5 dn6 = n6 * d6 ax.scatter((xyz + dn1)[0], (xyz + dn1)[1], (xyz + dn1)[2], c='r', marker='*') ax.scatter((xyz + dn2)[0], (xyz + dn2)[1], (xyz + dn2)[2], c='r', marker=">") ax.scatter((xyz + dn3)[0], (xyz + dn3)[1], (xyz + dn3)[2], c='b', marker="*") ax.scatter((xyz + dn4)[0], (xyz + dn4)[1], (xyz + dn4)[2], c='b', marker="<") ax.scatter((xyz + dn5)[0], (xyz + dn5)[1], (xyz + dn5)[2], c='r', marker="^") ax.scatter((xyz + dn6)[0], (xyz + dn6)[1], (xyz + dn6)[2], c='b', marker="v") # print ("V1: {}".format(v1)) # print ("V2: {}".format(v2)) fcolors = ['r', 'g', 'b', 'y', 'k', 'w'] count = 0 face_plots = [] face_legends = [] for face in faces: x, y, z = np.hsplit(face, 3) x = x.flatten() y = y.flatten() z = z.flatten() verts = [zip(x, y, z)] ax.add_collection3d(Poly3DCollection(verts, alpha=0.5, color=fcolors[count])) face_plots.append(Line2D([0], [0], linestyle="none", marker="s", alpha=0.5, markersize=10, markerfacecolor=fcolors[count])) face_legends.append("Face {}".format(count + 1)) count += 1 ax.legend(face_plots, face_legends, numpoints=1, loc='best') # print("Requested Point: {}".format(xyz)) # print("Labels: {}".format(labels)) # print("Locations: {}".format(dat)) # print("Length of Labels: {}".format(len(labels))) for a in range(len(labels)): x, y, z = dat[a] lab = ax.text(x, y, z, " p{}".format(str(a + 1)), size=10, zorder=1, color='r') # plt.figtext(0.02, 0.01, "Face Distances from point {}:\n1: {}\n2: {}\n3: {}\n4: {}\n5: {}\n6: {}".format(xyz, d1, d2, d3, d4, d5, d6), size=10, zorder=1, color='k') # ================================================================================= fig.savefig("points/point_{}.pdf".format(xyz)) if show: plt.show() plt.close(fig)