def newSurface(self): processes = self.plotter.getProcesses() if not self._cv_dlg: self._cv_dlg = daeChooseVariable(daeChooseVariable.plot3D) self._cv_dlg.updateProcessesList(processes) self._cv_dlg.setWindowTitle('Choose variable for 3D plot') if self._cv_dlg.exec_() != QtWidgets.QDialog.Accepted: return False variable, domainIndexes, domainPoints, xAxisLabel, yAxisLabel, zAxisLabel, xPoints, yPoints, zPoints, currentTime = self._cv_dlg.getPlot3DData( ) xPoints = numpy.array(xPoints) yPoints = numpy.array(yPoints) xmax = numpy.max(xPoints) ymax = numpy.max(yPoints) zmax = numpy.max(zPoints) xmin = numpy.min(xPoints) ymin = numpy.min(yPoints) zmin = numpy.min(zPoints) warp = 'auto' #if((xmax == xmin) or (ymax == ymin) or (zmax == zmin)): # warp = 'auto' #else: # warp = math.sqrt( (xmax-xmin)*(ymax-ymin) ) / (zmax-zmin) # colormap='gist_earth', 'RdBu' stype = 'surface' mlab.figure() if (stype == 'surface'): #print "warp=", warp #print "[xmin, xmax, ymin, ymax, zmin, zmax]=", [xmin, xmax, ymin, ymax, zmin, zmax] mlab.surf(xPoints, yPoints, zPoints, warp_scale=warp, representation='surface') mlab.colorbar(orientation='vertical') #mlab.title('polar mesh') #mlab.outline() mlab.axes(ranges=[xmin, xmax, ymin, ymax, zmin, zmax], nb_labels=3) mlab.xlabel(xAxisLabel) mlab.ylabel(yAxisLabel) mlab.zlabel(zAxisLabel) elif (stype == 'map'): mlab.imshow(zPoints) mlab.colorbar(orientation='vertical') #mlab.title('polar mesh') #mlab.outline() mlab.axes(ranges=[xmin, xmax, ymin, ymax], nb_labels=3) mlab.xlabel(xAxisLabel) mlab.ylabel(yAxisLabel) mlab.zlabel(zAxisLabel) mlab.show()
def main(): #set some values to be used later sh_order = 6 verts, edges, efaces = create_unit_sphere(4) #read_data from disk data, fa, bvec, bval, voxel_size = sample_hardi_data() data_slice = data[32:76, 32:76, 26:27] fa_slice = fa[32:76, 32:76, 26] #normalize data by dividing by b0, this is needed so we can take log later norm_data = normalize_data(data_slice, bval, min_signal=1) #create an instance of the model model_instance = MonoExpOpdfModel(sh_order, bval, bvec, .006) model_instance.set_sampling_points(verts, edges) #use the model it fit the data opdfs_sampled_at_verts = model_instance.evaluate(norm_data) opdfs_sph_harm_coef = model_instance.fit_data(norm_data) #display the opdf blobs using mayavi faces = edges[efaces, 0] show_blobs(opdfs_sampled_at_verts, verts, faces) mlab.imshow(fa_slice, colormap='gray', interpolate=False) mlab.show()
def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi="s"): """Plot the mask. """ try: import enthought.mayavi.mlab as ml mayavi = True print "using mayavi" except: import pylab as pl mayavi = False print "using matplotlib" if self.maskfile is None: print "error: plotmask: get mask file first:" print ">>> m = Mask()" print ">>> m.getmask('fname')" print "then you can do:" print ">>> m.plotmask(region='left/right/bottom/top', resolution=20)" sys.exit() m_mask = self.m_mask x_mask = self.x_mask y_mask = self.y_mask if region is not None: left, right, bottom, top = str.split(region, "/") left, bottom = self.mapll(left, bottom, slat=slat, slon=slon, hemi=hemi) right, top = self.mapll(right, top, slat=slat, slon=slon, hemi=hemi) jmin, = np.where(x_mask == np.rint(left)) jmax, = np.where(x_mask == np.rint(right)) imin, = np.where(y_mask == np.rint(bottom)) imax, = np.where(y_mask == np.rint(top)) # x_mask = x_mask[jmin:jmax+1:resolution] # y_mask = y_mask[imin:imax+1:resolution] m_mask = m_mask[imin : imax + 1 : resolution, jmin : jmax + 1 : resolution] else: # x_mask = x_mask[::resolution] # y_mask = y_mask[::resolution] m_mask = m_mask[::resolution, ::resolution] print "plotting mask ..." if mayavi: ml.figure() ml.imshow(m_mask) ml.show() else: pl.figure() pl.imshow(m_mask, origin="lower", interpolation="nearest") pl.show() print "done!"
def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi='s'): """Plot the mask. """ try: import enthought.mayavi.mlab as ml mayavi = True print 'using mayavi' except: import pylab as pl mayavi = False print 'using matplotlib' if self.maskfile is None: print 'error: plotmask: get mask file first:' print '>>> m = Mask()' print ">>> m.getmask('fname')" print 'then you can do:' print ">>> m.plotmask(region='left/right/bottom/top', resolution=20)" sys.exit() m_mask = self.m_mask x_mask = self.x_mask y_mask = self.y_mask if region is not None: left, right, bottom, top = str.split(region, '/') left, bottom = self.mapll(left, bottom, slat=slat, slon=slon, hemi=hemi) right, top = self.mapll(right, top, slat=slat, slon=slon, hemi=hemi) jmin, = np.where(x_mask == np.rint(left)) jmax, = np.where(x_mask == np.rint(right)) imin, = np.where(y_mask == np.rint(bottom)) imax, = np.where(y_mask == np.rint(top)) #x_mask = x_mask[jmin:jmax+1:resolution] #y_mask = y_mask[imin:imax+1:resolution] m_mask = m_mask[imin:imax+1:resolution, jmin:jmax+1:resolution] else: #x_mask = x_mask[::resolution] #y_mask = y_mask[::resolution] m_mask = m_mask[::resolution,::resolution] print 'plotting mask ...' if mayavi: ml.figure() ml.imshow(m_mask) ml.show() else: pl.figure() pl.imshow(m_mask, origin='lower', interpolation='nearest') pl.show() print 'done!'
def show_blobs(blobs, v, faces,fa_slice=None,colormap='jet'): """Mayavi gets really slow when triangular_mesh is called too many times so this function stacks blobs and calls triangular_mesh once """ print blobs.shape xcen = blobs.shape[0]/2. ycen = blobs.shape[1]/2. zcen = blobs.shape[2]/2. faces = np.asarray(faces, 'int') xx = [] yy = [] zz = [] count = 0 ff = [] mm = [] for ii in xrange(blobs.shape[0]): for jj in xrange(blobs.shape[1]): for kk in xrange(blobs.shape[2]): m = blobs[ii,jj,kk] #m /= (2.2*m.max()) #m /= (2.2*abs(m).max()) #m /= (2.2*1.) #m[m<.4*abs(m).max()]=0 x, y, z = v.T*m/2.2 x += ii - xcen y += jj - ycen z += kk - zcen ff.append(count+faces) count += len(x) xx.append(x) yy.append(y) zz.append(z) mm.append(m) ff = np.concatenate(ff) xx = np.concatenate(xx) yy = np.concatenate(yy) zz = np.concatenate(zz) mm = np.concatenate(mm) mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap) if fa_slice!=None: mlab.imshow(fa_slice, colormap='gray', interpolate=False) mlab.colorbar() mlab.show()
################################################################################ # Plot the data from enthought.mayavi import mlab # A first plot in 3D fig = mlab.figure(1) mlab.clf() mesh = mlab.mesh(x, y, z, scalars=s) cursor3d = mlab.points3d(0.0, 0.0, 0.0, mode="axes", color=(0, 0, 0), scale_factor=0.5) mlab.title("Click on the ball") # A second plot, flat fig2d = mlab.figure(2) mlab.clf() im = mlab.imshow(s) cursor = mlab.points3d(0, 0, 0, mode="2dthick_cross", color=(0, 0, 0), scale_factor=10) mlab.view(90, 0) ################################################################################ # Some logic to select 'mesh' and the data index when picking. def picker_callback(picker_obj): picked = picker_obj.actors if mesh.actor.actor._vtk_obj in [o._vtk_obj for o in picked]: # m.mlab_source.points is the points array underlying the vtk # dataset. GetPointId return the index in this array. x_, y_ = np.lib.index_tricks.unravel_index(picker_obj.point_id, s.shape) print "Data indices: %i, %i" % (x_, y_) n_x, n_y = s.shape
def show_odfs(odfs, vertices_faces, image=None, colormap='jet', scale=2.2, norm=True, radial_scale=True): """ Display a grid of ODFs. Parameters ---------- odfs : (X, Y, Z, M) ndarray A 3-D arrangement of orientation distribution functions (ODFs). At each ``(x, y, z)`` position, it contains the the values of the corresponding ODF evaluated on the M vertices. vertices_faces : str or tuple of (vertices, faces) A named sphere from `dipy.data.get_sphere`, or a combination of `(vertices, faces)`. image : (X, Y) ndarray Background image (e.g., fractional anisotropy) do display behind the ODFs. colormap : str Color mapping. scale : float Increasing the scale spaces ODFs further apart. norm : bool Whether or not to normalize each individual ODF (divide by its maximum absolute value). radial_scale : bool Whether or not to change the radial shape of the ODF according to its scalar value. If set to False, the ODF is displayed as a sphere. Notes ----- Mayavi gets really slow when `triangular_mesh` is called too many times, so this function stacks ODF data and calls `triangular_mesh` once. Examples -------- >>> from dipy.data import get_sphere >>> verts, faces = get_sphere('symmetric724') >>> angle = np.linspace(0, 2*np.pi, len(verts)) >>> odf1 = np.sin(angle) >>> odf2 = np.cos(angle) >>> odf3 = odf1**2 * odf2 >>> odf4 = odf1 + odf2**2 >>> odfs = [[[odf1, odf2], ... [odf3, odf4]]] >>> show_odfs(odfs, (verts, faces), scale=5) """ vertices, faces = sphere_vf_from(vertices_faces) odfs = np.asarray(odfs) if odfs.ndim != 4: raise ValueError("ODFs must by an (X,Y,Z,M) array. " + "Has shape " + str(odfs.shape)) grid_shape = np.array(odfs.shape[:3]) faces = np.asarray(faces, dtype=int) xx, yy, zz, ff, mm = [], [], [], [], [] count = 0 for ijk in np.ndindex(*grid_shape): m = odfs[ijk] if norm: m /= abs(m).max() if radial_scale: xyz = vertices.T * m else: xyz = vertices.T.copy() xyz += scale * (ijk - grid_shape / 2.)[:, None] x, y, z = xyz ff.append(count + faces) xx.append(x) yy.append(y) zz.append(z) mm.append(m) count += len(x) ff, xx, yy, zz, mm = (np.concatenate(arrs) for arrs in (ff, xx, yy, zz, mm)) mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap) if image is not None: mlab.imshow(image, colormap='gray', interpolate=False) mlab.colorbar() mlab.show()
def show_odfs(odfs, vertices_faces, image=None, colormap='jet', scale=2.2, norm=True, radial_scale=True): """ Display a grid of ODFs. Parameters ---------- odfs : (X, Y, Z, M) ndarray A 3-D arrangement of orientation distribution functions (ODFs). At each ``(x, y, z)`` position, it contains the the values of the corresponding ODF evaluated on the M vertices. vertices_faces : str or tuple of (vertices, faces) A named sphere from `dipy.data.get_sphere`, or a combination of `(vertices, faces)`. image : (X, Y) ndarray Background image (e.g., fractional anisotropy) do display behind the ODFs. colormap : str Color mapping. scale : float Increasing the scale spaces ODFs further apart. norm : bool Whether or not to normalize each individual ODF (divide by its maximum absolute value). radial_scale : bool Whether or not to change the radial shape of the ODF according to its scalar value. If set to False, the ODF is displayed as a sphere. Notes ----- Mayavi gets really slow when `triangular_mesh` is called too many times, so this function stacks ODF data and calls `triangular_mesh` once. Examples -------- >>> from dipy.data import get_sphere >>> verts, faces = get_sphere('symmetric724') >>> angle = np.linspace(0, 2*np.pi, len(verts)) >>> odf1 = np.sin(angle) >>> odf2 = np.cos(angle) >>> odf3 = odf1**2 * odf2 >>> odf4 = odf1 + odf2**2 >>> odfs = [[[odf1, odf2], ... [odf3, odf4]]] >>> show_odfs(odfs, (verts, faces), scale=5) """ vertices, faces = sphere_vf_from(vertices_faces) odfs = np.asarray(odfs) if odfs.ndim != 4: raise ValueError("ODFs must by an (X,Y,Z,M) array. " + "Has shape " + str(odfs.shape)) grid_shape = np.array(odfs.shape[:3]) faces = np.asarray(faces, dtype=int) xx, yy, zz, ff, mm = [], [], [], [], [] count = 0 for ijk in np.ndindex(*grid_shape): m = odfs[ijk] if norm: m /= abs(m).max() if radial_scale: xyz = vertices.T * m else: xyz = vertices.T.copy() xyz += scale * (ijk - grid_shape / 2.)[:, None] x, y, z = xyz ff.append(count + faces) xx.append(x) yy.append(y) zz.append(z) mm.append(m) count += len(x) ff, xx, yy, zz, mm = (np.concatenate(arrs) for arrs in (ff, xx, yy, zz, mm)) mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap) if image is not None: mlab.imshow(image, colormap='gray', interpolate=False) mlab.colorbar() mlab.show()
matrix=assembleMatrix(mToB,kernel,quadRule=quadrule) identity=assembleIdentity(mToB,quadrule) rhs=projRhs(mToB,[lambda t,x,normals: -numpy.exp(1j*k*x[1])],quadrule) coeffs=numpy.linalg.solve(.5*identity+matrix,rhs) gx,gy=numpy.mgrid[-2:4:200j,-2:2:200j] points=numpy.array([gx.ravel(),gy.ravel()]) res=evaluate(points,mToB,kernel,quadrule,coeffs) res=res.reshape(200,200) res+=numpy.exp(1j*k*gy) from enthought.mayavi import mlab mlab.imshow(gx,gy,numpy.real(res),vmin=-1,vmax=1) mlab.axes() mlab.view(0,0) mlab.show() print "Finished"
# Plot the data from enthought.mayavi import mlab # A first plot in 3D fig = mlab.figure(1) mlab.clf() mesh = mlab.mesh(x, y, z, scalars=s) cursor3d = mlab.points3d(0., 0., 0., mode='axes', color=(0, 0, 0), scale_factor=0.5) mlab.title('Click on the ball') # A second plot, flat fig2d = mlab.figure(2) mlab.clf() im = mlab.imshow(s) cursor = mlab.points3d(0, 0, 0, mode='2dthick_cross', color=(0, 0, 0), scale_factor=10) mlab.view(90, 0) ################################################################################ # Some logic to select 'mesh' and the data index when picking. def picker_callback(picker_obj): picked = picker_obj.actors if mesh.actor.actor._vtk_obj in [o._vtk_obj for o in picked]: # m.mlab_source.points is the points array underlying the vtk # dataset. GetPointId return the index in this array. x_, y_ = np.lib.index_tricks.unravel_index(picker_obj.point_id, s.shape)
# -*- coding: utf-8 -*- import numpy as np from enthought.mayavi import mlab x, y = np.ogrid[-2:2:20j, -2:2:20j] z = x * np.exp(-x**2 - y**2) mlab.figure(1) pl = mlab.imshow(x, y, z) mlab.figure(2) pl = mlab.contour_surf(x, y, z, contours=20) mlab.show()
# -*- coding: utf-8 -*- import numpy as np from enthought.mayavi import mlab x, y = np.ogrid[-2:2:20j, -2:2:20j] z = x * np.exp( - x**2 - y**2) mlab.figure(1) pl = mlab.imshow(x, y, z) mlab.figure(2) pl = mlab.contour_surf(x, y, z, contours=20) mlab.show()
""" Script to generate the preview images for the mayavi2 LUTs. Requires ImageMagick. """ import os from enthought.mayavi import mlab from enthought.mayavi.core.lut_manager import lut_mode_list, lut_image_dir import numpy as np # Create some data X = np.arange(0, 255) X = X * np.ones((200, 1)) mlab.clf() image = mlab.imshow(X.T) mlab.view(0, 0, 118) # Make a preview for each possible lut for lut in lut_mode_list(): filebasename = os.path.join(lut_image_dir, lut.lower()) if not lut == 'file': image.module_manager.scalar_lut_manager.lut_mode = lut mlab.savefig(filebasename + '.png', size=(80, 20)) #os.system('convert %s.png %s.gif &' %(filebasename, filebasename)) os.system('montage -geometry -0-0 -label "%s" %s.png %s.gif &' % (lut, filebasename, filebasename))
""" Script to generate the preview images for the mayavi2 LUTs. Requires ImageMagick. """ import os from enthought.mayavi import mlab from enthought.mayavi.core.lut_manager import lut_mode_list, lut_image_dir import numpy as np # Create some data X = np.arange(0, 255) X = X * np.ones((200, 1)) mlab.clf() image = mlab.imshow(X.T) mlab.view(0, 0, 118) # Make a preview for each possible lut for lut in lut_mode_list(): filebasename = os.path.join(lut_image_dir, lut.lower()) if not lut == 'file': image.module_manager.scalar_lut_manager.lut_mode = lut mlab.savefig(filebasename + '.png', size=(80, 20)) #os.system('convert %s.png %s.gif &' %(filebasename, filebasename)) os.system('montage -geometry -0-0 -label "%s" %s.png %s.gif &' % (lut, filebasename, filebasename) )