def short_branches(): """ Visualization of short branches of the skeleton. """ data1_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5') data1_sk.sort() for i,j, k in zip(d[1][37:47], data1_sk[46:56], ell[1][37:47]): g = nx.read_gpickle(i) dat = tb.openFile(j) skel = np.copy(dat.root.skel) bra = np.copy(dat.root.branches) mask = np.zeros_like(skel) dat.close() length = nx.get_edge_attributes(g, 'length') number = nx.get_edge_attributes(g, 'number') num_dict = {} for m in number: for v in number[m]: num_dict.setdefault(v, []).append(m) find_br = ndimage.find_objects(bra) for l in list(length.keys()): if length[l]<0.5*k: #Criteria for b in number[l]: mask[find_br[b-1]] = bra[find_br[b-1]]==b mlab.figure(bgcolor=(1,1,1), size=(1200,1200)) mlab.contour3d(skel, colormap='hot') mlab.contour3d(mask) mlab.savefig('/backup/yuliya/vsi05/skeletons/short_bran/'+ i[42:-10] + '.png') mlab.close()
def vis_breakups(): """ This function allows to visualize break-ups as the highlighted branches in the original skeleton. """ data_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5') data_sk.sort() data_br = glob.glob('/backup/yuliya/vsi05/breakups_con_correction/dict/*.npy') data_br.sort() for i,j in zip(data_sk[27:67][::-1], data_br[19:][::-1]): d = tb.openFile(i, mode='r') bran1 = np.copy(d.root.branches) skel1 = np.copy(d.root.skel) d.close() br = np.load(j).item() mlab.figure(1, bgcolor=(1,1,1), size=(1200,1200)) surf_skel = mlab.contour3d(skel1, colormap='hot') surf_skel.actor.property.representation = 'points' surf_skel.actor.property.line_width = 2.3 mask = np.zeros_like(skel1) for k in br: sl = br[k] mask[sl] = (bran1[sl] == k) surf_mask = mlab.contour3d(mask.astype('uint8')) surf_mask.actor.property.representation = 'wireframe' surf_mask.actor.property.line_width = 5 mlab.savefig('/backup/yuliya/vsi05/breakups_con_correction/video_hot/' + i[39:-3] + '.png') mlab.close()
def view_thresholdedT(design, contrast, threshold, inequality=np.greater): """ A mayavi isosurface view of thresholded t-statistics Parameters ---------- design : {'block', 'event'} contrast : str threshold : float inequality : {np.greater, np.less}, optional """ maska = np.asarray(MASK) tmap = np.array(load_image_fiac('group', design, contrast, 't.nii')) test = inequality(tmap, threshold) tval = np.zeros(tmap.shape) tval[test] = tmap[test] # XXX make the array axes agree with mayavi2 avganata = np.array(AVGANAT) avganat_iso = mlab.contour3d(avganata * maska, opacity=0.3, contours=[3600], color=(0.8,0.8,0.8)) avganat_iso.actor.property.backface_culling = True avganat_iso.actor.property.ambient = 0.3 tval_iso = mlab.contour3d(tval * MASK, color=(0.8,0.3,0.3), contours=[threshold]) return avganat_iso, tval_iso
def visual_test1(): poly = polygon_gaussian_density(3) #s = mlab.contour3d(poly) #mlab.show() grid_dimesions = poly.shape grid_center = np.array(grid_dimesions) / 2.0 radii = np.arange(2.0, 10.0) L_max = 25 shg = SphHarmGrid(grid_dimesions, grid_center, radii, L_max) coeff = shg(poly) reconstructed_poly = shg.expand_sph_harm(coeff) print 'magnitudes' print 'real:', np.sum(np.abs(reconstructed_poly.real)), 'imag:', np.sum(np.abs(reconstructed_poly.imag)) poly /= poly.sum() rpoly = np.abs(reconstructed_poly) rpoly /= rpoly.sum() err = np.sum( np.abs(poly - rpoly) / float(np.product(grid_dimesions)) ) print "Reconstruction error:", err print 'showing model' s1 = mlab.contour3d(rpoly) mlab.show() print 'showing error' s2 = mlab.contour3d(rpoly - poly) mlab.show() return
def test3(): import numpy as np from mayavi import mlab sdf = np.load('/Users/yue/data/segment/sdf_diff_3d_1/imseg_iter_100.npz')['sdf'] mlab.contour3d(sdf[0], contours=[0]) # mlab.savefig('/Users/yue/data/segment/sdf_diff_3d_1/imseg_iter_100.png') mlab.show()
def showContour(self): """ Display real space model using contour """ mlab.contour3d(self.array, contours=8, opacity=0.3, transparent=True) mlab.outline() mlab.show()
def show_scatterer(scatterer, spacing=None): mlab = import_mayavi() if spacing == None: # if no spacing given, represent the object with 100 voxels # along each dimension spacing = [(b[1]-b[0])/100 for b in scatterer.bounds] vol = scatterer.voxelate(spacing, 0) mlab.contour3d(vol)
def plot_LAM_contours(self, readfile): if self.LAMgauss == None: print "Reading file..." self.LAMgauss = self.load_data(readfile) print "Plotting..." mlab.contour3d(self.LAMgauss, contours = 75, opacity=0.10) mlab.show()
def plotParcels(self, brain, label = None, contourVals = [], opacity = 0.5, cmap='autumn'): ''' plot an isosurface using Mayavi, almost the same as skull plotting ''' if not(label): label = self.getAutoLabel() if contourVals == []: self.isosurfacePlots[label] = mlab.contour3d(brain.parcels, opacity = opacity, colormap=cmap) else: self.isosurfacePlots[label] = mlab.contour3d(brain.parcels, opacity = opacity, contours = contourVals, colormap=cmap)
def plot(ply): ''' Plot vertices and triangles from a PlyData instance. Assumptions: `ply' has a 'vertex' element with 'x', 'y', and 'z' properties; `ply' has a 'face' element with an integral list property 'vertex_indices', all of whose elements have length 3. ''' vertex = ply['vertex'] (x, y, z) = (vertex[t] for t in ('x', 'y', 'z')) # mlab.points3d(x, y, z, color=(1, 1, 1), mode='point') if 'face' in ply: tri_idx = ply['face']['vertex_indices'] print type(tri_idx) idx_dtype = tri_idx[0].dtype print "idx_dtype" , idx_dtype triangles = numpy.fromiter(tri_idx, [('data', idx_dtype, (3,))], count=len(tri_idx))['data'] k = triangles.byteswap() # p.from_array(numpy.array([[1,2,3],[3,4,5]], dtype=numpy.float32)) p.from_array((triangles.byteswap().newbyteorder().astype('<f4'))) # p1.add_points_from_input_cloud() p1.set_input_cloud(p) fil = p.make_statistical_outlier_filter() # cloud_filtered = fil.filter() # fil = p1.make_statistical_outlier_filter() fil.set_mean_k(20) fil.set_std_dev_mul_thresh(0.1) pointx = triangles[:,0] pc_1 = pcl.PointCloud() pc_1 = p pc_2 = pcl.PointCloud() pc_2 = p kd = pcl.KdTreeFLANN(pc_1) print('pc_1:') print type(triangles) # file1 = open("values.txt",'w') # file1.write(str(triangles[:])) # mlab.mesh(x,y,z) print numpy.shape(p) print numpy.shape(z) print numpy.shape(y) print numpy.shape(x) mlab.contour3d(x, y, z, p)
def show_fitting(self, depth_image, offsets, model_transform): v, u = np.nonzero(depth_image != 0) depth = depth_image[(v,u)]/1000.0 points = np.vstack([depth*(u+offsets[0]), depth*(v+offsets[1]), depth]) model_points = np.dot(d.K_default_inv, points) model_points = np.vstack([model_points, np.ones_like(model_points[0])]) transformed_points = np.dot(inv(model_transform), model_points)[0:3,:] mlab.contour3d(self.x/self.scale[0], self.y/self.scale[1], self.z/self.scale[2], self.sdf, contours=[0.05], opacity=0.5) mlab.points3d(transformed_points[0], transformed_points[1], transformed_points[2], color=(1,0,0), mode='point') mlab.show()
def plotIsosurface(self, brain, label = None, contourVals = [], opacity = 0.1, cmap='autumn'): ''' plot an isosurface using Mayavi, almost the same as skull plotting ''' if not(label): label = self.getAutoLabel() if contourVals == []: s = mlab.contour3d(brain.iso, opacity = opacity, colormap=cmap) else: s = mlab.contour3d(brain.iso, opacity = opacity, contours = contourVals, colormap=cmap) # get the object for editing self.isosurfacePlots[label] = s
def plotBackground(self, brain, label = None, contourVals = [3000,9000], opacity = 0.1, cmap='Spectral'): ''' plot the skull using Mayavi ''' if not(label): label = self.getAutoLabel() if contourVals == []: s = mlab.contour3d(brain.background, opacity = opacity, colormap=cmap) else: s = mlab.contour3d(brain.background, opacity = opacity, contours = contourVals, colormap=cmap) # get the object for editing self.skullPlots[label] = s
def plot_volume(nifti_file,v_color=(.98,.63,.48),v_opacity=.1, fliplr=False, newfig=False): """ Render a volume from a .nii file Use fliplr option if scan has radiological orientation """ import nibabel as nib if newfig: mlab.figure(bgcolor=(1, 1, 1), size=(400, 400)) input = nib.load(nifti_file) input_d = input.get_data() d_shape = input_d.shape if fliplr: input_d = input_d[range(d_shape[0]-1,-1,-1), :, :] mlab.contour3d(input_d, color=v_color, opacity=v_opacity) # good natural color is (.98,.63,.48)
def plotSkull(self, brain, label = None, contourVals = [], opacity = 0.1, cmap='Spectral'): ''' plot the skull using Mayavi ''' if not(label): label = self.getAutoLabel() # remove old version if not(label in self.skullPlots): self.skullPlots[label].remove() if contourVals == []: self.skullPlots[label] = mlab.contour3d(brain.background, opacity = opacity, colormap=cmap) else: self.skullPlots[label] = mlab.contour3d(brain.background, opacity = opacity, contours = contourVals, colormap=cmap)
def calc(): """ The function that implements break-ups detection algorithm and write the data in a file. Input skeletons and graphs must correspond each other. """ #input graphs data_gr = glob.glob('/path/graphs_largedom/*_1.gpickle') data_gr.sort() #input skeletons data_sk = glob.glob('/path/skeletons_largedom/*.h5') data_sk.sort() for i, j, w in zip(data_gr[:-1][::-1], data_sk[:-1][::-1], data_sk[1:][::-1]): g = nx.read_gpickle(i) #We simplify the graph g1 = remove_terminal_br(g) g1 = remove_nodes(g1) #We use labeled branches arrays, skeletons, distans transfrom. All are of the same shape. d = tb.openFile(j, mode='r') bran1 = np.copy(d.root.branches1) skel1 = np.copy(d.root.skel) #this 'current' skeletons are used only for visualization. thick = np.copy(d.root.dist) d.close() #Skeletons shifted in time by one step. d = tb.openFile(w, mode='r') skel2 = np.copy(d.root.skel) d.close() b, pos = branches_map(g1, skel2, bran1, thick) #Visualization of break-ups if necessary. mlab.figure(1, bgcolor=(1,1,1), size=(1500,1500)) mlab.contour3d(skel1, colormap='hot') mask = np.zeros_like(skel1) for k in b: sl = b[k] mask[sl] = (bran1[sl] == k) mlab.contour3d(mask.astype('uint8')) np.save('/path/breakups/' + j[41:-3] + '_1.npy', b) #j[41:-3] must be replaced according to the path np.save('/path/breakups/' + j[41:-3] + '_pos.npy', pos) mlab.savefig('/path/breakups/' + j[41:-3] + '_1.png') mlab.close()
def make3dHist(data): # n, m, l = data.shape # results = np.zeros((n*l,3)) # for i in range(n): # for j in range(m): # results[i*l:(i+1)*l,j] = data[i,j,:] # H, edges = np.histogramdd(results, bins = (100,100,100)) # print H.shape # data = earthSpherify(data) mlab.contour3d(data) data = data / np.max(data) * 3.74 print "Still fine" mlab.pipeline.volume(mlab.pipeline.scalar_field(data)) mlab.show()
def plotIsosurface(self, brain, label=None, contourVals=[], opacity=0.1, cmap="autumn"): """ plot an isosurface using Mayavi, almost the same as skull plotting """ if not (label): label = self.getAutoLabel() if label in self.isosurfacePlots: self.isosurfacePlots[label].remove() if contourVals == []: self.isosurfacePlots[label] = mlab.contour3d(brain.iso, opacity=opacity, colormap=cmap) else: self.isosurfacePlots[label] = mlab.contour3d( brain.iso, opacity=opacity, contours=contourVals, colormap=cmap )
def visual_test2(): """ Compute and display expansions of sparse spherical harmonic function. """ grid_dimesions = (30, 30, 30) grid_center = np.array(grid_dimesions) / 2.0 radii = np.arange(2.0, 10.0) L_max = 25 shg = SphHarmGrid(grid_dimesions, grid_center, radii, L_max) r = 7 for ell in range(1,5): sparse = np.zeros((shg.num_radii, shg.L_max, 2 * shg.L_max + 1)) m = 1 sparse[r,ell,m] = 1.0 #sparse[3,ell,m] = 1.0 sph_harm = shg.expand_sph_harm(sparse) print 'plotting l=%d, m=%d || %s' % (ell, m, str(sph_harm.shape)) plot_grid = np.zeros_like(sph_harm.real) plot_grid[ sph_harm.real > 1e-6 ] = 1.0 plot_grid[ sph_harm.real < -1e-6 ] = -1.0 s = mlab.contour3d( plot_grid, contours=5, line_width=1.0, transparent=True ) mlab.show() return
def plot_isosurface(crystal): filename = './output/potentialfield.txt' data = np.genfromtxt(filename, delimiter='\t') size = np.round((len(data))**(1/3)) X = np.reshape(data[:,0], (size,size,size)) Y = np.reshape(data[:,1], (size,size,size)) Z = np.reshape(data[:,2], (size,size,size)) DeltaU = np.reshape(data[:,3], (size,size,size)) average = np.average(crystal.coordinates[:,0]) start = average - crystal.a end = average + crystal.a coords1 = np.array([[start, start, start]]) coords2 = np.array([[end, end, end]]) array1 = np.repeat(coords1,len(crystal.coordinates),axis=0) array2 = np.repeat(coords2,len(crystal.coordinates),axis=0) basefilter1 = np.greater(crystal.coordinates,array1) basefilter2 = np.less(crystal.coordinates,array2) basefilter = np.nonzero(np.all(basefilter1*basefilter2, axis=1)) base = crystal.coordinates[basefilter] mlab.figure(bgcolor=(1, 1, 1), fgcolor=(1, 1, 1), size=(2048,2048)) dataset = mlab.contour3d(X, Y, Z, DeltaU, contours=[3.50],color=(1,0.25,0)) scatter = mlab.points3d(base[:,0], base[:,1], base[:,2], color=(0.255,0.647,0.88), resolution=24, scale_factor=1.0, opacity=0.40) mlab.view(azimuth=17, elevation=90, distance=10, focalpoint=[average,average-0.2,average]) mlab.draw() savename = './output/3Dpotential.png' mlab.savefig(savename, size=(2048,2048)) mlab.show()
def showDsweep(): k_s_sweep = [10**(x-5) for x in range(10)] sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)] vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)] Dmsd = numpy.load(data_dir + "/D_numpy.npy") kDa = 1.660538921e-30; mass = 40.0*kDa; viscosity = 8.9e-4; diameter = 5e-9; T = 300.0; Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter); Dmsd = Dmsd/Dbase mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1), bgcolor=(0.5, 0.5, 0.5)) mlab.clf() contours = numpy.arange(0.01,2,0.2).tolist() obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1]) outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10)) axes = mlab.axes(outline, color=(.7, .7, .7), nb_labels = 5, ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), xlabel='spring stiffness', ylabel='step length', zlabel='volume ratio') mlab.colorbar(obj,title='D',nb_labels=5) mlab.show()
def vortexCylinder(): #VERTICAL STACK OF 2D FIELDS....3D FIELD """ """ from vortexCore import vortexCore2 from lambda2 import lambda2_3d gamma = 1 #strength of the vortex. Rcore = 18 #radious of the vortex core. s = 20 #size parameter of the field x*y points. h = 3 #min is 1 q = N.array([[0,0,0]]) #point where the vortex will be located [z,y,x] = N.mgrid[0:1,-s:s+1, -s:s+1] [Z,Y,X] = N.mgrid[-h:h+1,-s:s+1, -s:s+1] [W,V,U] = N.zeros_like([Z,Y,X],dtype=float) for i in range(len(Z)): #vortexCore2(X,Y,C,Rcore,gamma): [U_temp,V_temp] = vortexCore2(x[0],y[0],q,Rcore,gamma) U[i]=U_temp V[i]=V_temp L2 = lambda2_3d(X,Y,Z,U,V,W) #print L2[3] #vF=mlab.quiver3d(Z,Y,X,W,V,U) Lamda2 = mlab.contour3d(Z,Y,X,L2,transparent=True) mlab.show() return
def plotIsosurface(figure, values, variables, contour_value=0.0001, color=(0,0,1)): from mayavi import mlab x, y, z = variables if isinstance(color, str): color = {'blue': (0,0,1), 'red':(1,0,0)}[color] surf = mlab.contour3d(x,y,z,values, contours=[contour_value], color=color) return mlab
def demo(smoothed = False): from mayavi import mlab from mayavi.mlab import points3d, contour3d, plot3d random.seed(0) Nw = 15 xx, yy = randomSphereSampleMatrix(Nw = Nw, Nsamples = 50) indexX, indexY, indexZ = mgrid[0:Nw,0:Nw,0:Nw] cubeEdges = array([[0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1]]) cubeEdges *= Nw for ii in range(10): fig = mlab.gcf() #fig.scene.disable_render = True mlab.clf(fig) #from tvtk.api import tvtk #fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain() #mlab.clf() plot3d(cubeEdges[0,:], cubeEdges[1,:], cubeEdges[2,:], color=(.5,.5,.5), line_width = 0, representation = 'wireframe', opacity = 1) thisShape = xx[ii,:] if smoothed: contour3d(reshape(thisShape, (Nw,Nw,Nw)), contours=[.5], color=(1,1,1)) else: points3d(indexX.flatten()[thisShape > 0], indexY.flatten()[thisShape > 0], indexZ.flatten()[thisShape > 0], ones(sum(thisShape > 0)) * .9, color = (1,1,1), mode = 'cube', scale_factor = 1.0) mlab.view(57.15, 75.55, 50.35, (7.5, 7.5, 7.5)) # nice view filename = 'test_%02d.png' % ii mlab.savefig(filename) #, size=(800,800)) if raw_input('Saved %s, enter to continue (q to quit)...' % filename) == 'q': return
def void(i, figure, show = False): datos2 = np.copy(datos) datos2[datos!=i] = 0 contour = mlab.contour3d(datos2, contours=2) #mlab.pipeline.volume(mlab.pipeline.scalar_field(datos), vmin=0) if show: mlab.show() return contour
def scatter_contour(nodes,vals,**kwargs): pts = 100j xmin,xmax = np.min(nodes[:,0]),np.max(nodes[:,0]) ymin,ymax = np.min(nodes[:,1]),np.max(nodes[:,1]) zmin,zmax = np.min(nodes[:,2]),np.max(nodes[:,2]) x,y,z = np.mgrid[xmin:xmax:pts, ymin:ymax:pts, zmin:zmax:pts] f = griddata(nodes, vals, (x,y,z),method='linear') p = mlab.contour3d(x,y,z,f,**kwargs) mlab.colorbar(p)
def mayavi_demo2(): """ This function is a practice for the mayavi package in python """ # function x = np.linspace(-10,10,100) y = np.linspace(-10,10,100) z = x*np.sin(x)*np.sin(y) # mayavi plot mlab.figure(1,bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.contour3d(x,y,z) mlab.axes(extent=[-10,10,-10,10,-10,10], \ x_axis_visibility=False, \ y_axis_visibility=False, \ z_axis_visibility=False) mlab.move(1,0,0) mlab.show()
def plot_path(points, rock): path_rock = np.ones(rock.shape) for (x, y, z) in points: path_rock[x][y][z] = 0 @mlab.animate def anim(): f = mlab.gcf() while 1: f.scene.camera.azimuth(1) f.scene.render() yield mlab.figure(bgcolor=(1,1,1)) # Set bkg color mlab.contour3d(rock, color = (0,0,0), contours = 2, opacity = .2 + .8/rock.shape[0]) # Draw pores for 3d, changed froo .20 * 100 / self.shape[0] mlab.contour3d(path_rock) a = anim()
def topographyFrom3D( data, contour_value=None, z_range=None, ): from mayavi import mlab values, xyz = data x, y, z = xyz values = values.copy() value_max = np.max(values, axis=(0,1)) value_min = np.min(values, axis=(0,1)) valid_span = value_max.min(), value_min.max() if contour_value is None: if valid_span[0] > valid_span[1]: contour_value = valid_span[0] else: contour_value = np.exp(np.log(valid_span).mean()) if not z_range is None: take_max = value_max > contour_value take_min = value_min < contour_value arg_shift = take_max.sum() - 1 zmax = z[0, 0, arg_shift + 1] zmin = z[0, 0, arg_shift] - z_range take = z < zmin values[take] = 2*contour_value take = z > zmax values[take] = 0 surf = mlab.contour3d(x,y,z, values, contours=[contour_value]) surface_points = contourToArray(surf) x, y, z = surface_points if not z_range is None: maxi = z.max() mini = maxi - z_range take1 = z > mini take2 = z < maxi take = np.logical_and(take1, take2) surface_points = surface_points[:,take] xi = np.linspace(x.min(), x.max(), 4000) yi = np.linspace(y.min(), y.max(), 4000) x, y, z = surface_points if len(z) > 100: zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') else: zi = None zi[zi > zmax] = zmax zi[np.isnan(zi)] = (zmax + zmin)/2.0 return (xi, yi, zi), (zmin, zmax)
def surface3d(self,filename,times=2): _times = times dot_index = filename.find('.mat') _filename = filename[0:dot_index] pmat = sciMat.loadmat(_filename+'.mat') da = np.tile(pmat['ADens'],[_times,_times,_times]) db = np.tile(pmat['BDens'],[_times,_times,_times]) d = da.shape dim = (d[0]+2,d[1]+2,d[2]+2) dA = np.zeros((dim[0],dim[1],dim[2])) dB = np.zeros((dim[0],dim[1],dim[2])) dA[1:-1,1:-1,1:-1] = np.tile(pmat['ADens'],[_times,_times,_times]) dB[1:-1,1:-1,1:-1] = np.tile(pmat['BDens'],[_times,_times,_times]) sX, sY, sZ = float(pmat['sizeZ']), \ float(pmat['sizeY']), \ float(pmat['sizeX']) X = np.zeros((dim[0],dim[1],dim[2])) Y = np.zeros((dim[0],dim[1],dim[2])) Z = np.zeros((dim[0],dim[1],dim[2])) x,y,z = np.arange(0,dim[0]),np.arange(0,dim[1]),np.arange(0,dim[2]) x = sX * _times / dim[0] * x y = sY * _times / dim[1] * y z = sZ * _times / dim[2] * z for (i,j) in np.ndindex(dim[1],dim[2]): X[:,i,j] = x for (i,j) in np.ndindex(dim[0],dim[2]): Y[i,:,j] = y for (i,j) in np.ndindex(dim[0],dim[1]): Z[i,j,:] = z # mlab.engine.current_scene.scene.off_screen_rendering = True # mlab.options.offscreen = True mlab.clf() mlab.contour3d(X,Y,Z,dB,color=self.c_r,contours=self.cont) mlab.contour3d(X,Y,Z,dA,color=self.c_g,contours=self.cont) mlab.savefig(_filename+'.png')
def modb_on_surface(self, s=1, ntheta=64, nphi=64, plot=True, show=False, outxyz=None, full=False, alpha=1, mayavi=True): #first attempt will use trisurface, let's see how it looks r = np.zeros([nphi, ntheta]) z = np.zeros([nphi, ntheta]) x = np.zeros([nphi, ntheta]) y = np.zeros([nphi, ntheta]) b = np.zeros([nphi, ntheta]) if full: divval = 1 else: divval = self.nfp theta = np.linspace(0, 2 * np.pi, num=ntheta) phi = np.linspace(0, 2 * np.pi / divval, num=nphi) for phii in range(nphi): p = phi[phii] for ti in range(ntheta): th = theta[ti] r[phii, ti] = self.r_at_point(s, th, p) z[phii, ti] = self.z_at_point(s, th, p) x[phii, ti] += r[phii, ti] * np.cos(p) y[phii, ti] += r[phii, ti] * np.sin(p) b[phii, ti] = self.modb_at_point(s, th, p) my_col = cm.jet((b - np.min(b)) / (np.max(b) - np.min(b))) if plot and (not use_mayavi or not mayavi): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #my_col = cm.jet((b-np.min(b))/(np.max(b)-np.min(b))) ax.plot_surface(x, y, z, facecolors=my_col, norm=True, alpha=alpha) #set axis to equal max_range = np.array( [x.max() - x.min(), y.max() - y.min(), z.max() - z.min()]).max() / 2.0 mid_x = (x.max() + x.min()) * 0.5 mid_y = (y.max() + y.min()) * 0.5 mid_z = (z.max() + z.min()) * 0.5 ax.set_xlim(mid_x - max_range, mid_x + max_range) ax.set_ylim(mid_y - max_range, mid_y + max_range) ax.set_zlim(mid_z - max_range, mid_z + max_range) if show: plt.show() elif plot and use_mayavi and mayavi: mlab.figure(bgcolor=(1.0, 1.0, 1.0), size=(800, 600)) mlab.contour3d(x, y, z, b) if show: mlab.show() if outxyz is not None: wf = open(outxyz, 'w') for phii in range(nphi): for ti in range(ntheta): s = (str(x[phii, ti]) + '\t' + str(y[phii, ti]) + '\t' + str(z[phii, ti]) + '\n') wf.write(s) return [x, y, z, b]
rangesize=100 boxes=100j VX, VY, VZ = np.mgrid[-rangesize:rangesize:boxes, -rangesize:rangesize:boxes, -rangesize:rangesize:boxes] positions = np.vstack([VX.ravel(), VY.ravel(), VZ.ravel()]) dens = np.reshape(np.exp(kde_fit.score_samples(positions.T)), VX.shape) binsize = 2*rangesize/(boxes.imag) w = int(boxes.imag/2) #Visualize the density estimate as isosurfaces figure = mlab.figure('myfig') figure.scene.disable_render = True # Super duper trick #mlab.contour3d(VX, VY, VZ, dens, contours=[0.25*10**-5,0.5*10**-5,1*10**-5,2*10**-5,2.5*10**-5,3*10**-5], opacity=0.3, colormap = 'Blues', figure = figure) mlab.contour3d(VX, VY, VZ, dens, contours=[0.1*10**-4,0.5*10**-4,1*10**-4,1.5*10**-4,2*10**-4,2.5*10**-4], opacity=0.3, vmin=np.min(dens), vmax=np.max(dens), colormap = 'Reds', figure = figure) mlab.axes(xlabel='U (km/s)', ylabel='V (km/s)', zlabel='W (km/s)', nb_labels = 3, figure = figure) #mlab.quiver3d(x, y, z, vx, vy, vz) #mlab.axes(extent = [-650, 650, -650, 650, -650, 650], ranges = [-650, 650, -650, 650, -650, 650], nb_labels = 7, figure = figure) #mlab.points3d(vx, vy, vz, np.full(len(vx),1), scale_factor = 1, color=(1,1,1), figure = figure) mlab.points3d(vx_OD1, vy_OD1, vz_OD1, np.full(len(x_OD1),1), scale_factor = 1, color=(0,1,0), figure = figure) mlab.points3d(vx_OD2, vy_OD2, vz_OD2, np.full(len(x_OD2),1), scale_factor = 1, color=(0,0,1), figure = figure) #mlab.points3d(vx_OD3, vy_OD3, vz_OD3, np.full(len(x_OD3),1), scale_factor = 1, color=(0,0,1), figure = figure) #mlab.points3d(vx_OD4, vy_OD4, vz_OD4, np.full(len(x_OD4),1), scale_factor = 1, color=(1,1,1), figure = figure) figure.scene.disable_render = False # Super duper trick mlab.show() """ fig, axs = plt.subplots(1, 3, sharey=True, tight_layout=True)
def plotData3DContour(a): mlab.contour3d(a,contours=4, transparent=True, vmin=0.2, vmax=0.8)
z = np.append(z, df2['Center of Mass (Bounding box): Z (px)']) zmax = np.amax(z) zmin = np.amin(z) z = (z-zmin)/(zmax-zmin) values = np.array([x, y, z]) kde = stats.gaussian_kde(values) xmin, ymin, zmin = values.T.min(axis=0) xmax, ymax, zmax = values.T.max(axis=0) xi, yi, zi = np.mgrid[xmin:xmax:70j, ymin:ymax:70j, zmin:zmax:70j] coords = np.vstack([item.ravel() for item in [xi, yi, zi]]) density = kde(coords).reshape(xi.shape) print (np.amin(density), np.amax(density)) #maxid = np.where(density == np.amax(density)) #maxid = np.argmax(density) #print (coords.shape, maxid) #Characterstics of contour plot mlab.contour3d(xi, yi, zi, density, contours=20, vmin=0, vmax=15, opacity=0.4) mlab.axes() mlab.show()
data=np.random.multivariate_normal(mu,sigma,1000) values = data.T kde = stats.gaussian_kde(values) # Create a regular 3D grid with 50 points in each dimension xmin, ymin, zmin = data.min(axis=0) xmax, ymax, zmax = data.max(axis=0) xi, yi, zi = np.mgrid[xmin:xmax:50j, ymin:ymax:50j, zmin:zmax:50j] # Evaluate the KDE on a regular grid... coords = np.vstack([item.ravel() for item in [xi, yi, zi]]) density = kde(coords).reshape(xi.shape) # Visualize the density estimate as isosurfaces mlab.contour3d(xi, yi, zi, density, opacity=0.5) mlab.axes() mlab.show() # Pickling shiz import cPickle with open(r"/media/chet/hdd/seismic/NZ/clustering/nlloc_dets_Sherburn_km_mat.npy", 'rb') as f: dist_mat = cPickle.load(f) with open(r"/media/chet/hdd/seismic/NZ/clustering/nlloc_dets_Sherburn_linkage.npy", 'wb') as f: cPickle.dump(Z, f) catN = [] catS = [] for i, ev in enumerate(catalog): if ev.preferred_origin().latitude < -38.580367:
random_state=42, metric="euclidean", output_metric=torus_euclidean_grad, init="spectral", min_dist=0.15, # requires adjustment since the torus has limited space verbose=True, ).fit(X_train) mlab.clf() x, y, z = np.mgrid[-3:3:50j, -3:3:50j, -3:3:50j] # Plot a torus R = 2 r = 1 values = (R - np.sqrt(x ** 2 + y ** 2)) ** 2 + z ** 2 - r ** 2 mlab.contour3d(x, y, z, values, color=(1.0, 1.0, 1.0), contours=[0]) # torus angles -> 3D x = (R + r * np.cos(trans.embedding_[:, 0])) * np.cos(trans.embedding_[:, 1]) y = (R + r * np.cos(trans.embedding_[:, 0])) * np.sin(trans.embedding_[:, 1]) z = r * np.sin(trans.embedding_[:, 0]) pts = mlab.points3d( x, y, z, y_train, colormap="spectral", scale_mode="none", scale_factor=0.1 ) mlab.show() if "sphere" in target_spaces: # embed onto a sphere trans = umap.UMAP(
# 计算哪个小球被选取 point_id = int(picker.point_id / glyph_points.shape[0]) # int向下取整 if point_id != -1: # 如果没有小球被选取,则point_id = -1 # 找到与此红色小球相关的坐标 x, y, z = x1[point_id], y1[point_id], z1[point_id] # 将外框移到小球上 outline.bounds = (x - 0.1, x + 0.1, y - 0.1, y + 0.1, z - 0.1, z + 0.1) picker = figure.on_mouse_pick(picker_callback) mlab.title('Click on red balls') mlab.show() ''' ''' x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j] s = np.sin(x*y*z)/(x*y*z) mlab.contour3d(s) mlab.show() ''' ''' mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s), plane_orientation='x_axes', slice_index=10,) mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),plane_orientation='y_axes', slice_index=10,) mlab.outline() ''' ''' x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j] s = np.sin(x * y * z) / (x * y * z)
""" =============== Fermi surface =============== """ from mayavi import mlab from fplore import FPLORun run = FPLORun("../example_data/yrs") level_indices = run.band.bands_at_energy() energy_data = run.band.data['e'][..., level_indices] axes, grid_idx = run.band.reshape_gridded_data() data = energy_data[grid_idx] # reshape to grid mlab.figure() for i, level_idx in enumerate(level_indices): mlab.contour3d(data[..., i], contours=[0], opacity=0.4) mlab.show()
def configure_logger(): root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter( fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) root_logger.addHandler(handler) def download_array(blob: storage.Blob) -> np.ndarray: in_stream = io.BytesIO() blob.download_to_file(in_stream) in_stream.seek(0) # Read from the start of the file-like object return np.load(in_stream) if __name__ == '__main__': configure_logger() client = storage.Client(project='elvo-198322') bucket = storage.Bucket(client, name='elvos') in_blob: storage.Blob for in_blob in bucket.list_blobs(prefix='numpy/'): logging.info(f'downloading {in_blob.name}') arr = download_array(in_blob) mlab.contour3d(arr) mlab.show()
def contour3d(isovalues, colors, fid=1, atoms=None, data=None, box=None, origin=None, filename=None): mlab.figure(bgcolor=(0, 0, 0), size=(350, 350)) #mlab.clf() if filename is not None: fobj = open(filename, 'r') dt = aic.read_cube(fobj, read_data=True) atoms, origin, data = [dt[key] for key in ['atoms', 'origin', 'data']] box = atoms.cell else: assert atoms is not None assert data is not None assert box is not None if len(box.shape) == 1: _box = np.eye(3) _box[np.diag_indices_from(_box)] = box box = _box if origin is None: origin = np.zeros(3) _zs = atoms.numbers na = len(_zs) # get bonds newm = RawMol(_zs, atoms.positions) newm.connect() bonds = [ list(edge) for edge in \ np.array( list( np.where(np.triu(newm.g)>0) ) ).T ] box0 = np.zeros((3, 3)) box0[np.diag_indices_from(box0)] = np.diag(box) assert np.all(box0 == box), '#ERROR: not a cubic box?' grids = data.shape scales = np.array(data.shape) / np.diag(box) scale_av = np.mean(scales) # rescale the position of the atoms _coords = np.array([(atoms.positions[i] - origin) * scales for i in range(na)]) nzs = [] zsu = [] coords = [] for i, zi in enumerate(_zs): if zi in zsu: idx = zsu.index(zi) coords[idx] += [_coords[i]] else: zsu.append(zi) coords.append([_coords[i]]) nzu = len(zsu) objs = [] for i in range(nzu): Z = zsu[i] coords_i = coords[i] ox, oy, oz = list(map(np.array, zip(*coords_i))) ai = mlab.points3d(ox, oy, oz, scale_factor=covalent_radii[Z] * scale_av, resolution=20, color=tuple(cpk_colors[Z])) objs.append(ai) # The bounds between the atoms, we use the scalar information to give # color for bond in bonds: coords_b = _coords[bond] ox, oy, oz = list(map(np.array, zip(*coords_b))) obj = mlab.plot3d(ox, oy, oz, [1, 2], tube_radius=0.05 * scale_av, color=(0.5, 0.5, 0.5)) objs.append(obj) for i, val in enumerate(isovalues): color = dc[colors[i]] obj = mlab.contour3d(data, contours=[val], opacity=0.25, color=color) #(1,0,0)) objs.append(obj) objs.append(obj) # https://gitlab.com/chaffra/ase/blob/master/ase/visualize/mlab.py # Do some tvtk magic in order to allow for non-orthogonal unit cells: #polydata = obj.actor.actors[0].mapper.input #pts = np.array(polydata.points) - 1 # Transform the points to the unit cell: #polydata.points = np.dot(pts, box / np.array(data.shape)[:, np.newaxis]) #mlab.axes(x_axis_visibility=True) #,y_axis_visibility=True) #mlab.axes(xlabel='X', ylabel='Y', zlabel='Z') #Display axis obj = mlab.orientation_axes() objs.append(obj) return objs[0]
def plot(self, labels=False, show=True): ''' This function plots 2D and 3D models :param labels: :param show: If True, the plots are displayed at the end of this call. If False, plt.show() should be called outside this function :return: ''' if self.k == 3: import mayavi.mlab as mlab predictFig = mlab.figure(figure='predict') errorFig = mlab.figure(figure='error') if self.testfunction: truthFig = mlab.figure(figure='test') dx = 1 pts = 25j X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts] scalars = np.zeros(X.shape) errscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): errscalars[i][j][k1] = self.predicterr_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) scalars[i][j][k1] = self.predict_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) if self.testfunction: tfscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): tfplot = tfscalars[i][j][k1] = self.testfunction( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) plot = mlab.contour3d(tfscalars, contours=15, transparent=True, figure=truthFig) plot.compute_normals = False # obj = mlab.contour3d(scalars, contours=10, transparent=True) plot = mlab.contour3d(scalars, contours=15, transparent=True, figure=predictFig) plot.compute_normals = False errplt = mlab.contour3d(errscalars, contours=15, transparent=True, figure=errorFig) errplt.compute_normals = False if show: mlab.show() if self.k == 2: fig = pylab.figure(figsize=(8, 6)) samplePoints = zip(*self.X) # Create a set of data to plot plotgrid = 61 x = np.linspace(self.normRange[0][0], self.normRange[0][1], num=plotgrid) y = np.linspace(self.normRange[1][0], self.normRange[1][1], num=plotgrid) # x = np.linspace(0, 1, num=plotgrid) # y = np.linspace(0, 1, num=plotgrid) X, Y = np.meshgrid(x, y) # Predict based on the optimized results zs = np.array([ self.predict([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Z = zs.reshape(X.shape) # Z = (Z*(self.ynormRange[1]-self.ynormRange[0]))+self.ynormRange[0] #Calculate errors zse = np.array([ self.predict_var([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Ze = zse.reshape(X.shape) spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0]) ) + self.normRange[0][0] spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0]) ) + self.normRange[1][0] contour_levels = 25 ax = fig.add_subplot(222) CS = pylab.contourf(X, Y, Ze, contour_levels) pylab.colorbar() pylab.plot(spx, spy, 'ow') ax = fig.add_subplot(221) if self.testfunction: # Setup the truth function zt = self.testfunction(np.array(zip(np.ravel(X), np.ravel(Y)))) ZT = zt.reshape(X.shape) CS = pylab.contour(X, Y, ZT, contour_levels, colors='k', zorder=2) # contour_levels = np.linspace(min(zt), max(zt),50) if self.testfunction: contour_levels = CS.levels delta = np.abs(contour_levels[0] - contour_levels[1]) contour_levels = np.insert(contour_levels, 0, contour_levels[0] - delta) contour_levels = np.append(contour_levels, contour_levels[-1] + delta) CS = plt.contourf(X, Y, Z, contour_levels, zorder=1) pylab.plot(spx, spy, 'ow', zorder=3) pylab.colorbar() ax = fig.add_subplot(212, projection='3d') # fig = plt.gcf() #ax = fig.gca(projection='3d') ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4) if self.testfunction: ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3) if show: pylab.show()
import numpy as np from mayavi import mlab from scpy2.tvtk import fix_mayavi_bugs fix_mayavi_bugs() x, y, z = np.ogrid[-2:2:40j, -2:2:40j, -2:0:40j] s = 2/np.sqrt((x-1)**2 + y**2 + z**2) + 1/np.sqrt((x+1)**2 + y**2 + z**2) surface = mlab.contour3d(s, contours=4, transparent=True) surface.contour.maximum_contour = 15 surface.contour.number_of_contours = 10 surface.actor.property.opacity = 0.4 mlab.figure() mlab.pipeline.volume(mlab.pipeline.scalar_field(s)) mlab.figure() field = mlab.pipeline.scalar_field(s) mlab.pipeline.volume(field, vmin=1.5, vmax=10) cut = mlab.pipeline.scalar_cut_plane(field.children[0], plane_orientation="y_axes") cut.enable_contours = True cut.contour.number_of_contours = 40 mlab.gcf().scene.background = (0.8, 0.8, 0.8) mlab.show()
mlab.points3d(interp_coords[0], interp_coords[1], u, scale_factor=.8, color=(1, 0, 0)) mlab.show() mlab.close() if example3D is True: ''' 3D plot ''' import os os.environ['ETS_TOOLKIT'] = 'qt4' os.environ['QT_API'] = 'pyqt' from mayavi import mlab # random field instance rf = RandomField(distr_type='Gauss', lacor_arr=np.array([5.0, 4.0, 2.0]), nDgrid=[ np.linspace(0.0, 20., 20), np.linspace(0.0, 30., 30), np.linspace(0.0, 40., 40) ]) rand_field_3D = rf.random_field x, y, z = rf.nDgrid cx, cy, cz = np.mgrid[x[0]:x[-1]:complex(0, len(x)), y[0]:y[-1]:complex(0, len(y)), z[0]:z[-1]:complex(0, len(z))] mlab.contour3d(cx, cy, cz, rand_field_3D, contours=7, transparent=True) mlab.show() mlab.close()
import sdf import numpy as np import constant as const from mayavi import mlab data = sdf.read('Documents/data/2800.sdf', dict=True) var1 = data['Electric Field/Ey'].data bz = var1 k_bz = np.fft.fft(bz, axis=0) delta_k = 3.14 / const.delta_x / (const.Nx / 2) k_bz2 = k_bz * 1 k_n = [] for n in range(0, const.Nx): mi = 3e8 / 0.1e12 #limit_min ma = 3e8 / 10e12 #limit_max if 2 * 3.14 / ma > n * delta_k and n * delta_k > 2 * 3.14 / mi: k_n.append(n) k_bz2[0:k_n[0], :, :] = 0 #k_bz.argmin() k_bz2[k_n[-1]:-k_n[-1], :, :] = 0 #k_bz.argmin() k_bz2[-k_n[0]:, :, :] = 0 #k_bz.argmin() var1 = np.fft.ifft(k_bz2, axis=0).real mlab.contour3d(var1) mlab.show()
) * v / 2.0 + rho g1 = lambda rho, u, v: epsilon * (a * (1 - u) - eta(rho + 1)) g2 = lambda rho, u, v: epsilon * (b * (1 - v) - eta(rho - 1)) # Initial conditions u[0] = 0.8 v[0] = 0.8 rho[0] = -0.1 for i in range(T - 1): rho[i + 1] = rho[i] + h * f(rho[i], u[i], v[i]) u[i + 1] = u[i] + h * g1(rho[i], u[i], v[i]) v[i + 1] = v[i] + h * g2(rho[i], u[i], v[i]) time[i + 1] = time[i] + h ux, vx, rhox = np.mgrid[-1:2:50j, -1:2:50j, -1.5:1.5:50j] values = -rhox**3 - (rhox + 1.0) * ux / 2.0 - (rhox - 1.0) * vx / 2.0 + rhox mlab.contour3d(ux, vx, rhox, values, contours=[0], opacity=0.5) mlab.axes() mlab.xlabel('u') mlab.ylabel('v') mlab.zlabel('rho') mlab.plot3d(u, v, rho, tube_radius=0.02, line_width=2.0) print('Mean u: ', np.mean(u)) print('Mean v: ', np.mean(v)) plt.plot(time, u, label='u') plt.plot(time, v, label='v') plt.legend() plt.show(block=False) mlab.show()
# plot 3D isosurface (perspective view) # ######################################### grid_qx, grid_qz, grid_qy = np.mgrid[0:2 * z_pixel_FOV * voxel_size:voxel_size, 0:2 * y_pixel_FOV * voxel_size:voxel_size, 0:2 * x_pixel_FOV * voxel_size:voxel_size] extent = [ 0, 2 * z_pixel_FOV * voxel_size, 0, 2 * y_pixel_FOV * voxel_size, 0, 2 * x_pixel_FOV * voxel_size ] # in CXI convention, z is downstream, y vertical and x outboard myfig = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) mlab.contour3d(grid_qx, grid_qz, grid_qy, amp[numz // 2 - z_pixel_FOV:numz // 2 + z_pixel_FOV, numy // 2 - y_pixel_FOV:numy // 2 + y_pixel_FOV, numx // 2 - x_pixel_FOV:numx // 2 + x_pixel_FOV], contours=[threshold_isosurface], color=(0.7, 0.7, 0.7)) mlab.view( azimuth=0, elevation=50, distance=3 * field_of_view[0]) # azimut is the rotation around z axis of mayavi (x) mlab.roll(0) ax = mlab.axes(extent=extent, line_width=2.0, nb_labels=int(1 + field_of_view[0] / tick_spacing)) mlab.savefig(homedir + 'S' + str(scan) + '-perspective_labels.png', figure=myfig) ax.label_text_property.opacity = 0.0 ax.title_text_property.opacity = 0.0
def saveFigure(self, name=None): ''' Similar to plot, except that figures are saved to file :param name: the file name of the plot image ''' if self.k == 3: import mayavi.mlab as mlab mlab.options.offscreen = True predictFig = mlab.figure(figure='predict') mlab.clf(figure='predict') errorFig = mlab.figure(figure='error') mlab.clf(figure='error') if self.testfunction: truthFig = mlab.figure(figure='test') mlab.clf(figure='test') dx = 1 pts = 75j X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts] scalars = np.zeros(X.shape) errscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): errscalars[i][j][k1] = self.predicterr_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) scalars[i][j][k1] = self.predict_normalized( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) if self.testfunction: tfscalars = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): for k1 in range(X.shape[2]): tfscalars[i][j][k1] = self.testfunction( [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]]) mlab.contour3d(tfscalars, contours=15, transparent=True, figure=truthFig, compute_normals=False) # obj = mlab.contour3d(scalars, contours=10, transparent=True) pred = mlab.contour3d(scalars, contours=15, transparent=True, figure=predictFig) pred.compute_normals = False errpred = mlab.contour3d(errscalars, contours=15, transparent=True, figure=errorFig) errpred.compute_normals = False mlab.savefig('%s_prediction.wrl' % name, figure=predictFig) mlab.savefig('%s_error.wrl' % name, figure=errorFig) if self.testfunction: mlab.savefig('%s_actual.wrl' % name, figure=truthFig) mlab.close(all=True) if self.k == 2: samplePoints = list(zip(*self.X)) # Create a set of data to plot plotgrid = 61 x = np.linspace(0, 1, num=plotgrid) y = np.linspace(0, 1, num=plotgrid) X, Y = np.meshgrid(x, y) # Predict based on the optimized results zs = np.array([ self.predict_normalized([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Z = zs.reshape(X.shape) Z = ( Z * (self.ynormRange[1] - self.ynormRange[0])) + self.ynormRange[0] # Calculate errors zse = np.array([ self.predicterr_normalized([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y)) ]) Ze = zse.reshape(X.shape) if self.testfunction: # Setup the truth function zt = self.testfunction( np.array( list( zip( np.ravel((X * (self.normRange[0][1] - self.normRange[0][0])) + self.normRange[0][0]), np.ravel((Y * (self.normRange[1][1] - self.normRange[1][0])) + self.normRange[1][0]))))) ZT = zt.reshape(X.shape) # Plot real world values X = (X * (self.normRange[0][1] - self.normRange[0][0]) ) + self.normRange[0][0] Y = (Y * (self.normRange[1][1] - self.normRange[1][0]) ) + self.normRange[1][0] spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0]) ) + self.normRange[0][0] spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0]) ) + self.normRange[1][0] fig = plt.figure(figsize=(8, 6)) # contour_levels = np.linspace(min(zt), max(zt),50) contour_levels = 15 plt.plot(spx, spy, 'ow') cs = plt.colorbar() if self.testfunction: pass plt.plot(spx, spy, 'ow') cs = plt.colorbar() plt.plot(spx, spy, 'ow') ax = fig.add_subplot(212, projection='3d') ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4) if self.testfunction: ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3) if name: plt.savefig(name) else: plt.savefig('pyKrigingResult.png')
#!/usr/bin/env mayavi2 import numpy as np def V(x, y, z): """ A 3D sinusoidal lattice with a parabolic confinement. """ return np.cos(10 * x) + np.cos(10 * y) + np.cos( 10 * z) + 2 * (x**2 + y**2 + z**2) X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j] V(X, Y, Z) from mayavi import mlab mlab.contour3d(X, Y, Z, V) def gradient(f, x, y, z, d=0.01): """ Return the gradient of f in (x, y, z). """ fx = f(x + d, y, z) fx_ = f(x - d, y, z) fy = f(x, y + d, z) fy_ = f(x, y - d, z) fz = f(x, y, z + d) fz_ = f(x, y, z - d) return (fx - fx_) / (2 * d), (fy - fy_) / (2 * d), (fz - fz_) / (2 * d) Vx, Vy, Vz = gradient(V, X[50, ::3, ::3], Y[50, ::3, ::3], Z[50, ::3, ::3]) mlab.quiver3d(X[50, ::3, ::3],
with open(interpfn, 'rb') as fn: egrid = pkl.load(fn) # Plot the result if method == 'scatter': # Draw the energy as scatterplot plt.scatter3d() elif method == 'isosurfaces': print 'plotting isosurfaces...' maxe = np.max(egrid.ravel()) levels = [maxe, 0.5 * maxe, 0.25 * maxe] size = sz_from_resolution(args.resolution) print 'size = ', size fig = mlab.figure(fgcolor=(0,0,0), bgcolor=(1,1,1), size=size) mlab.contour3d(egrid, transparent=True) # , contours=levels) # exp = tvtk.GL2PSExporter(file_format='pdf', sort='bsp', compress=1) # fig.scene.save_gl2ps(fnfig + '.pdf', exp) # Sideview # mlab.view(45, 70, 100.0) mlab.savefig(fnfig + '_' + str(int(args.resolution)) + '_trans.png', magnification='auto') fig = mlab.figure(fgcolor=(0,0,0), bgcolor=(1,1,1), size=size) mlab.contour3d(egrid, transparent=False) # , contours=levels) # mlab.view(45, 70, 100.0) mlab.savefig(fnfig + '_' + str(int(args.resolution)) + '.png', magnification='auto') # size = sz_from_resolution(600) # mlab.savefig(fnfig + '_600.png', magnification='auto', size=size)
rmax = np.amax(rhof) rmin = np.amin(rhof) x = np.linspace(0., dsizex, ncel_pic, endpoint=False) y = np.linspace(0., dsizey, ncel_pic, endpoint=False) z = np.linspace(0., dsizez, ncel_pic, endpoint=False) Y, X, Z = np.meshgrid(x, y, z) ## Generate 3D contour plot of final density with Mayavi ## mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(1024, 768)) mlab.contour3d(X, Y, Z, rhof / np.mean(rhof), contours=32, opacity=.5, colormap='jet', vmax=np.amax(rhof) / np.mean(rhof), vmin=np.amin(rhof) / np.mean(rhof)) mlab.colorbar(orientation='vertical') mlab.view(azimuth=30, elevation=60, distance='auto') mlab.axes() mlab.savefig('MayaviFrames/Cyclotron3D_nc' + str(ncx) + '_nppc' + str(N_per_sparse_cell) + '_final.png', size=(640, 480)) mlab.show() plt.show()
import math cell_size = mp.Vector3(2, 2, 2) geometry = [ #mp.Block(center=mp.Vector3(0,0,0), size=cell_size, material=mp.air), mp.Ellipsoid(material=mp.metal, size=mp.Vector3(2, 0.5, 0.5), e1=mp.Vector3(1, 1, 1), e2=mp.Vector3(-1, 1, -1), e3=mp.Vector3(-2, 1, 1)) ] sim = mp.Simulation(resolution=50, cell_size=cell_size, geometry=geometry) sim.init_sim() eps_data = sim.get_epsilon() #eps_data = sim.get_array() #sim.plot3D(eps_data) #from mayavi import mlab #s = mlab.contour3d() #mlab.show() #mlab.savefig(filename='test2.png') from mayavi import mlab s = mlab.contour3d(eps_data, colormap="hsv") #mlab.show() mlab.savefig('Ellipsoid3D.pdf')
x, y = sur.ParamGrid() ax.scatter(x, y, s=2) plt.show() else: sur = Hemisphere() c = CoarseGrid(sur) g = c.grid(40, [-2, -2, -2], [2, 2, 2]) b = c.bandwidth(3., 1.) mask = c.mask(g, b) c.build_index_mappers(mask) fig = mlab.figure() scalars = np.ones_like(mask, dtype=np.int) scalars[mask] = 2. s = mlab.points3d(g[0].ravel(), g[1].ravel(), g[2].ravel(), scalars.ravel(), scale_factor=0.01, transparent=True) s = mlab.contour3d(g[0], g[1], g[2], scalars, opacity=0.7, contours=2, color=(0.2, 0.2, 0.2)) x, y, z = sur.ParamGrid() s2 = mlab.mesh(x, y, z, color=(0.2, 0.8, 0.2)) mlab.show()
def show_contour(img): from mayavi import mlab mlab.contour3d(img, colormap='gray')