def default_OTF(x1, x2): """Creates a default opacity transfer function. """ maxs = max(x1, x2) mins = min(x1, x2) otf = PiecewiseFunction() otf.add_point(mins, 0.0) otf.add_point(maxs, 0.2) return otf
def _vmin_changed(self): vmin = self.vmin vmax = self.vmax range_min, range_max = self._target.current_range if vmin is None: vmin = range_min if vmax is None: vmax = range_max # Change the opacity function from tvtk.util.ctf import PiecewiseFunction, save_ctfs otf = PiecewiseFunction() if range_min < vmin: otf.add_point(range_min, 0.) if range_max > vmax: otf.add_point(range_max, 0.2) otf.add_point(vmin, 0.) otf.add_point(vmax, 0.2) self._target._otf = otf self._target._volume_property.set_scalar_opacity(otf) if self.color is None and not self.__ctf_rescaled and \ ( (self.vmin is not None) or (self.vmax is not None) ): # FIXME: We don't use 'rescale_ctfs' because it screws up the nodes. def _rescale_value(x): nx = (x - range_min)/(range_max - range_min) return vmin + nx*(vmax - vmin) # The range of the existing ctf can vary. scale_min, scale_max = self._target._ctf.range def _rescale_node(x): nx = (x - scale_min)/(scale_max - scale_min) return range_min + nx*(range_max - range_min) if hasattr(self._target._ctf, 'nodes'): rgb = list() for value in self._target._ctf.nodes: r, g, b = \ self._target._ctf.get_color(value) rgb.append((_rescale_node(value), r, g, b)) else: rgb = save_ctfs(self._target.volume_property)['rgb'] from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() try: ctf.range = (range_min, range_max) except Exception: # VTK versions < 5.2 don't seem to need this. pass rgb.sort() v = rgb[0] ctf.add_rgb_point(range_min, v[1], v[2], v[3]) for v in rgb: ctf.add_rgb_point(_rescale_value(v[0]), v[1], v[2], v[3]) ctf.add_rgb_point(range_max, v[1], v[2], v[3]) self._target._ctf = ctf self._target._volume_property.set_color(ctf) self.__ctf_rescaled = True self._target.update_ctf = True
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]): # Get data from calculation files with jasp(directory) as calc: atoms = calc.get_atoms() x, y, z, cd = calc.get_charge_density() mlab.figure(bgcolor=(0,0,0), size=(640,480)) # Draw atoms if DrawAtoms == True: for atom in atoms: mlab.points3d(atom.x, atom.y, atom.z, scale_factor=vdw_radii[atom.number]/10., resolution=16, color=tuple(cpk_colors[atom.number]), scale_mode='none') # Draw unit cell if DrawCell == True: a1, a2, a3 = atoms.get_cell() origin = [0,0,0] cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1+a2], [a1, a1+a3], [a2, a2+a1], [a2, a2+a3], [a3, a1+a3], [a3, a2+a3], [a1+a2, a1+a2+a3], [a2+a3, a1+a2+a3], [a1+a3, a1+a3+a2]] # contains all points on the box for p1, p2 in cell_matrix: mlab.plot3d([p1[0], p2[0]], # x-coords of box [p1[1], p2[1]], # y-coords [p1[2], p2[2]]) # z-coords # Plot the charge density src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data vmin = cd.min() #find minimum and maximum value of CD data vmax = cd.max() vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data # Set opacity transfer function from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density vol._otf=otf vol._volume_property.set_scalar_opacity(otf) #Show a legend mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f') mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle mlab.show() if save_file != None: mlab.savefig(save_file)
def ImproveFilterDisplay(): # Changing the ctf: from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() ctf.range = [-1, 1] # Add points to CTF # Note : ctf.add_rgb_point(value, r, g, b) r, g, b are float numbers in [0,1] ctf.add_rgb_point(-1, 0, 0, 1) ctf.add_rgb_point(-0.7, 0, 0, 1) ctf.add_rgb_point(0, 0, 1, 0) ctf.add_rgb_point(0.7, 1, 0, 0) ctf.add_rgb_point(1, 1, 0, 0) # Changing the otf: from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() # Add points to OTF # Note : otf.add_point(value, opacity) -> opacity is a float number in [0,1] otf.add_point(-1, 0.005) otf.add_point(0, 0.01) otf.add_point(0.6, 0.1) otf.add_point(1, 1) return ctf, otf
def mk_otf(vlim, orange): ''' Create an opacity transfer function. Arguments: vlim -- data limits orange -- list of (fraction,opacity) pairs ''' orange[:] = [(i[0] * (vlim[1] - vlim[0]) + vlim[0], i[1]) for i in orange] otf = PiecewiseFunction() for i in orange: otf.add_point(*i) return otf
def plot_bleeds3d(data, template): from mayavi import mlab import datetime from tvtk.util.ctf import PiecewiseFunction, ColorTransferFunction string = str((datetime.datetime.now()).strftime("%d%m%Y_%H%M%S")) otf = PiecewiseFunction() otf.add_point( 0.1, 0.0 ) #opacity values for the boundary elements of the brain...For opaque objects, opacity = 1.0 otf.add_point(5, 0.1) otf.add_point(100, 0.25) ctf = ColorTransferFunction() ctf.add_rgb_point(0, 0, 0, 0) ctf.add_rgb_point(1000, 0.6, 1, 1) #3d plotting mlab.figure(bgcolor=(0, 0, 0), size=(400, 400)) src = mlab.pipeline.scalar_field(template) #voi = mlab.pipeline.extract_grid(src) vol = mlab.pipeline.volume(src) vol._otf = otf vol._volume_property.set_gradient_opacity(otf) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True src1 = mlab.pipeline.scalar_field(data) voi1 = mlab.pipeline.extract_grid(src1) mlab.pipeline.iso_surface(voi1, color=(1, 0, 0)) mlab.show()
def otf_type(vlim, otftype): '''Create the opacity transfer function based on options to this script.''' from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() def otf_mkr(pts, otf): map(lambda i: otf.add_point(*i), pts) return otf def mid_pt(r, m, b=0.001, e=1.0): return [(vlim[0], b), (vlim[0] + (vlim[1] - vlim[0]) * r, m), (vlim[1], e)] vs = { '0': (0.85, 0.06), '1': (0.90, 0.06), '2': (0.90, 0.08), '3': (0.90, 0.10), '4': (0.99, 0.20), 'solid': (0.01, 0.7, 0.0) } if (otftype == 'new'): r = [(vlim[0], 0.0), (vlim[0] + (vlim[1] - vlim[0]) * 0.999, 0.7), (vlim[1], 0.0)] return otf_mkr(r, otf) return otf_mkr(mid_pt(*vs[otftype]), otf)
def _set_cutoff(volume, cutoff): range_min, range_max = volume.current_range otf = PiecewiseFunction() otf.add_point(range_min, 0.0) otf.add_point(range_max, 0.2) volume._otf = otf volume.volume_property.set_scalar_opacity(otf) ctf = ColorTransferFunction() ctf.range = volume.current_range ctf.add_rgb_point(range_min, 1.0, 0.275, 0.0) ctf.add_rgb_point(range_max, 1.0, 0.275, 0.0) volume._ctf = ctf volume.volume_property.set_color(ctf) set_lut(volume.lut_manager.lut, volume.volume_property)
def make_volume_prop(mins=255, maxs=355): """Make a volume property for the testing.""" table = tvtk.VolumeProperty() ctf = ColorTransferFunction() ds = (maxs - mins) / 4.0 try: ctf.range = (mins, maxs) except Exception: # VTK versions < 5.2 don't seem to need this. pass ctf.add_rgb_point(mins, 0.00, 0.0, 1.00) ctf.add_rgb_point(mins + ds, 0.25, 0.5, 0.75) ctf.add_rgb_point(mins + 2 * ds, 0.50, 1.0, 0.50) ctf.add_rgb_point(mins + 3 * ds, 0.75, 0.5, 0.25) ctf.add_rgb_point(maxs, 1.00, 0.0, 0.00) otf = PiecewiseFunction() otf.add_point(mins, 0.0) otf.add_point(maxs, 0.2) table.set_color(ctf) table.set_scalar_opacity(otf) return table, ctf, otf
def make_volume_prop(mins=255, maxs=355): """Make a volume property for the testing.""" table = tvtk.VolumeProperty() ctf = ColorTransferFunction() ds = (maxs-mins)/4.0 try: ctf.range = (mins, maxs) except Exception: # VTK versions < 5.2 don't seem to need this. pass ctf.add_rgb_point(mins, 0.00, 0.0, 1.00) ctf.add_rgb_point(mins+ds, 0.25, 0.5, 0.75) ctf.add_rgb_point(mins+2*ds, 0.50, 1.0, 0.50) ctf.add_rgb_point(mins+3*ds, 0.75, 0.5, 0.25) ctf.add_rgb_point(maxs, 1.00, 0.0, 0.00) otf = PiecewiseFunction() otf.add_point(mins, 0.0) otf.add_point(maxs, 0.2) table.set_color(ctf) table.set_scalar_opacity(otf) return table, ctf, otf
def NewColorMap(h): ctf = ColorTransferFunction() otf = PiecewiseFunction() ctf.remove_all_points() otf.remove_all_points() ctf.add_rgb_point(0, 1, 1, 1) otf.add_point(0, 0) for i in range(128): q = (i + 1.0) / 128.0 ctf.add_rgb_point(-q, 1 - q * q, 1 - q * q, 1) # -1 --> blue, 0 --> white, 1-->red ctf.add_rgb_point(q, 1, 1 - q * q, 1 - q * q) otf.add_point(-q, 0.5 * q) otf.add_point(q, 0.5 * q) ctf.range = [-1, 1] h._volume_property.set_color(ctf) h._ctf = ctf h.update_ctf = True h._otf = otf h._volume_property.set_scalar_opacity(otf)
def plot_volume(x, y, z, s, logplot=False, **kwargs): if (logplot): maxval = log(abs(s).max()) minval = maxval - logrange logs = log(abs(s)) logs = where(logs > minval, logs - minval, 0) logs /= logs.max() src = mlab.pipeline.scalar_field(x, y, z, logs) else: maxval = abs(s).max() src = mlab.pipeline.scalar_field(x, y, z, abs(s) / maxval) vol = mlab.pipeline.volume(src) ctf = ColorTransferFunction() ctf.range = [0, 1] otf = PiecewiseFunction() otf.add_point((0, 0)) otf.add_point((1, 1)) otf.range = [0, 1] vol.otf = otf vol.volume_property.set_scalar_opacity(otf) return vol
def generate_data_mayavi(self): """Shows how you can generate data using mayavi instead of mlab.""" #from mayavi.sources.api import ParametricSurface x, y, z = ogrid[-10:10:20j, -10:10:20j, -10:10:20j] s = sin(x*y*z)/(x*y*z) e = self.scene.engine self.src = ArraySource() self.src.scalar_data = s e.add_source(self.src) self.v = Volume() #change opacity values from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(0, 0) otf.add_point(0.6*255, 0) otf.add_point(0.8*255,1) self.v._otf = otf self.v.volume_property.set_scalar_opacity(otf) e.add_module(self.v) cp = ScalarCutPlane() e.add_module(cp)
def plot_3d(index, data): if not contour_toggle_3d: grid = mlab.pipeline.scalar_field(data) vol = mlab.pipeline.volume(grid, vmin=1e-06) # Change the opacity to something more reasonable otf = PiecewiseFunction() otf.add_point(0.0, 0.0) otf.add_point(0.315, 0.3) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) else: mlab.contour3d(data, transparent=True) mlab.axes() mlab.title(" ".join([field, "mcs = %d" % (index * output_frequency)]), size=1, opacity=0.8) mlab.colorbar(orientation="vertical") mlab.show() return
def volume(sim, qty='rho', width=None, resolution=200, color=(1.0,1.0,1.0),vmin=None,vmax=None, dynamic_range=4.0,log=True, create_figure=True): """Create a volume rendering of the given simulation using mayavi. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (None): The width of the cube to generate, centered on the origin *resolution* (200): The number of elements along each side of the cube *color* (white): The color of the volume rendering. The value of each voxel is used to set the opacity. *vmin* (None): The value for zero opacity (calculated using dynamic_range if None) *vmax* (None): The value for full opacity (calculated from the maximum value in the region if None) *dynamic_range*: The dynamic range to use if vmin and vmax are not specified *log* (True): log-scale the image before passing to mayavi *create_figure* (True): create a new mayavi figure before rendering """ import mayavi from mayavi import mlab from tvtk.util.ctf import PiecewiseFunction, ColorTransferFunction if create_figure: fig = mlab.figure(size=(500,500),bgcolor=(0,0,0)) grid_data = sph.to_3d_grid(sim,qty=qty,nx=resolution, x2=None if width is None else width/2) if log: grid_data = np.log10(grid_data) if vmin is None: vmin = grid_data.max()-dynamic_range if vmax is None: vmax = grid_data.max() else: if vmin is None: vmin = np.min(grid_data) if vmax is None: vmax = np.max(grid_data) grid_data[grid_data<vmin]=vmin grid_data[grid_data>vmax]=vmax otf = PiecewiseFunction() otf.add_point(vmin,0.0) otf.add_point(vmax,1.0) sf = mayavi.tools.pipeline.scalar_field(grid_data) V = mlab.pipeline.volume(sf,color=color,vmin=vmin,vmax=vmax) V.trait_get('volume_mapper')['volume_mapper'].blend_mode = 'maximum_intensity' if color is None: ctf = ColorTransferFunction() ctf.add_rgb_point(vmin,107./255,124./255,132./255) ctf.add_rgb_point(vmin+(vmax-vmin)*0.8,200./255,178./255,164./255) ctf.add_rgb_point(vmin+(vmax-vmin)*0.9,1.0,210./255,149./255) ctf.add_rgb_point(vmax,1.0,222./255,141./255) print vmin,vmax V._volume_property.set_color(ctf) V._ctf = ctf V.update_ctf = True V._otf = otf V._volume_property.set_scalar_opacity(otf) return V
def td(ty,t,E,rho,sigma,wdir): D = pp.pload(t,w_dir=wdir) if ty == 'flux': for k in range(D.rho.shape[2]): for j in range(D.rho.shape[1]): for i in range(D.rho.shape[0]): # if (i-D.rho.shape[0]/2)**2+(j-D.rho.shape[1]/2)**2+(k-D.rho.shape[2]/2)**2 > 30**2: # D.rho[k,j,i] = rho if D.rho[k,j,i] > 10: D.rho[k,j,i] = rho flux = D.rho*(D.bx1**2+D.bx2**2+D.bx3**2)**1.25*(D.vx1**2+D.vx2**2+D.vx3**2)**0 flux = (flux-np.mean(flux))*1+np.mean(flux)*1 flux = flux.sum(axis=0) flux = nd.gaussian_filter(flux,sigma=(sigma,sigma),order=0) fig = plt.figure(figsize=(7,6)) ax = fig.add_subplot(111) neg = ax.imshow(np.log10(flux).T,origin='lower',extent=[D.x2[0],D.x2[-1],D.x3[0],D.x3[-1]]) levels = np.arange(-5.5, -4, 0.5) plt.contour(np.log10(flux).T, levels, origin='lower', linewidths=2, extent=[D.x1[0],D.x1[-1],D.x2[0],D.x2[-1]]) cbar = fig.colorbar(neg,ax=ax) cbar.set_label(r'log(S)') ax.set_xlabel('l offset (pc)') ax.set_ylabel('b offset (pc)') ax.set_title(r't='+str(t)+r'$\ \mathregular{\rho}$='+str(rho)+' E='+str(E)) fig.subplots_adjust(top=0.9,bottom=0.1,left=0.11,right=0.97) fig.savefig('t'+str(t)+'_density'+str(rho)+'_E'+str(E)+'.eps') fig.clear() ax = fig.add_subplot(111) ax.plot((np.rot90(np.eye(len(flux)))*flux.T).sum(axis=0)) ax.set_xlim(0,256) fig.savefig('change.eps') elif ty == 'rho': # t = 850 fig = plt.figure(figsize=(7,6)) ax = fig.add_subplot(111) neg = ax.imshow(np.log10(D.rho[:,:,128]).T,origin='lower',extent=[D.x2[0],D.x2[-1],D.x3[0],D.x3[-1]]) cbar = fig.colorbar(neg,ax=ax) cbar.set_label(r'log($\mathregular{\rho/cm^{-3}}$)') ax.set_xlabel('x offset (pc)') ax.set_ylabel('y offset (pc)') ax.set_title(r't='+str(t)+r'$\ \mathregular{\rho}$='+str(rho)+' E='+str(E)) fig.subplots_adjust(top=0.9,bottom=0.1,left=0.11,right=0.97) T = pp.Tools() newdims = 2*(20,) Xmesh, Ymesh = np.meshgrid(D.x2.T,D.x3.T) xcong = T.congrid(Xmesh,newdims,method='linear') ycong = T.congrid(Ymesh,newdims,method='linear') velxcong = T.congrid(D.bx1[:,:,128].T,newdims,method='linear') velycong = T.congrid(D.bx2[:,:,128].T,newdims,method='linear') plt.gca().quiver(xcong, ycong, velxcong, velycong,color='w') plt.show() fig.savefig('rho-t='+str(t)+'_density='+str(rho)+'_E='+str(E)+'.eps') # Only to be saved as either .png or .jpg # close() else: print(D.x1.shape) # arr = np.meshgrid(D.x1,D.x2,D.x3) # mlab.points3d(arr[0][0:256:8,0:256:8,0:256:8], arr[1][0:256:8,0:256:8,0:256:8], arr[2][0:256:8,0:256:8,0:256:8], D.rho[0:256:8,0:256:8,0:256:8]) vol = mlab.pipeline.volume(mlab.pipeline.scalar_field(np.log10(D.prs*D.rho))) ctf = ColorTransferFunction() ctf.add_hsv_point(-8, 0.8, 1, 1) ctf.add_hsv_point(-6.5, 0.45, 1, 1) ctf.add_hsv_point(-5.4, 0.15, 1, 1) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True otf = PiecewiseFunction() otf.add_point(-8, 0) otf.add_point(-5.7, 0.082) otf.add_point(-5.4, 0.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf)
def volume_red_blue(scalar_field, scalar_data): minr = scalar_data.min() maxr = scalar_data.max() #Volume for high pressure rvmin1 = minr + 0.5 * (maxr - minr) rvmax1 = minr + 1. * (maxr - minr) rvol1 = mlab.pipeline.volume(scalar_field, vmin=rvmin1, vmax=rvmax1) # Changing the ctf: from tvtk.util.ctf import ColorTransferFunction ctf1 = ColorTransferFunction() ctf1.add_rgb_point(rvmin1, 1., 1., 0.5) ctf1.add_rgb_point(rvmin1 + 0.4 * (rvmax1 - rvmin1), 1, 0.3, 0.1) ctf1.add_rgb_point(rvmax1, 1., 0., 0.) # ... rvol1._volume_property.set_color(ctf1) rvol1._ctf = ctf1 rvol1.update_ctf = True #Changing the opacity of the volume vol1 ## Changing the otf: from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(rvmin1, 0) otf.add_point(rvmin1 + (rvmax1 - rvmin1) * 0.2, 0.012) otf.add_point(rvmin1 + (rvmax1 - rvmin1) * 0.5, 0.05) otf.add_point(rvmax1, 0.15) ##vol1._otf = otf rvol1._volume_property.set_scalar_opacity(otf) # exempt volume from shading and improve overall look by increasing opacity rvol1.volume_property.shade = False rvol1.volume_property.scalar_opacity_unit_distance = 2.0 #Volume for low pressure rvmin2 = minr + 0. * (maxr - minr) rvmax2 = minr + 0.5 * (maxr - minr) rvol2 = mlab.pipeline.volume(scalar_field, vmin=rvmin2, vmax=rvmax2) # Changing the ctf: ctf2 = ColorTransferFunction() ctf2.add_rgb_point(rvmin2, 0., 0.5, 1.) ctf2.add_rgb_point(rvmin2 + 0.6 * (rvmax2 - rvmin2), 0.1, 0.7, 1.) ctf2.add_rgb_point(rvmax2, 0.5, 1., 1.) # ... rvol2._volume_property.set_color(ctf2) rvol2._ctf = ctf2 rvol2.update_ctf = True #Changing the opacity of the volume vol2 ## Changing the otf: otf = PiecewiseFunction() otf.add_point(rvmax2, 0) otf.add_point(rvmax2 - (rvmax2 - rvmin2) * 0.2, 0.012) otf.add_point(rvmax2 - (rvmax2 - rvmin2) * 0.5, 0.05) otf.add_point(rvmin2, 0.15) ##vol1._otf = otf rvol2._volume_property.set_scalar_opacity(otf) # exempt volume from shading and improve overall look by increasing opacity rvol2.volume_property.shade = False rvol2.volume_property.scalar_opacity_unit_distance = 2.0
def _vmin_changed(self): vmin = self.vmin vmax = self.vmax range_min, range_max = self._target.current_range if vmin is None: vmin = range_min if vmax is None: vmax = range_max # Change the opacity function from tvtk.util.ctf import PiecewiseFunction, save_ctfs otf = PiecewiseFunction() if range_min < vmin: otf.add_point(range_min, 0.) if range_max > vmax: otf.add_point(range_max, 0.2) otf.add_point(vmin, 0.) otf.add_point(vmax, 0.2) self._target._otf = otf self._target._volume_property.set_scalar_opacity(otf) if self.color is None and \ ((self.vmin is not None) or (self.vmax is not None)): # FIXME: We don't use 'rescale_ctfs' because it screws up the # nodes, this is because, the values are actually scaled between # the specified vmin/vmax and NOT the full range of values # specified in the CTF or in the volume object. if self.__last_vrange: last_min, last_max = self.__last_vrange else: last_min, last_max = range_min, range_max def _rescale_value(x): nx = (x - last_min) / (last_max - last_min) return vmin + nx * (vmax - vmin) # For some reason on older versions of VTK (< 8.1 at least), # The range trait is not updated correctly when the rgb points # are added, this causes problems so we explicitly update them. self._target._ctf.update_traits() scale_min, scale_max = self._target._ctf.range def _rescale_node(x): nx = (x - scale_min) / (scale_max - scale_min) return range_min + nx * (range_max - range_min) if hasattr(self._target._ctf, 'nodes'): rgb = list() for value in self._target._ctf.nodes: r, g, b = \ self._target._ctf.get_color(value) rgb.append((_rescale_node(value), r, g, b)) else: rgb = save_ctfs(self._target.volume_property)['rgb'] from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() try: ctf.range = (range_min, range_max) except Exception: # VTK versions < 5.2 don't seem to need this. pass rgb.sort() v = rgb[0] ctf.add_rgb_point(range_min, v[1], v[2], v[3]) for v in rgb: ctf.add_rgb_point(_rescale_value(v[0]), v[1], v[2], v[3]) ctf.add_rgb_point(range_max, v[1], v[2], v[3]) self._target._ctf = ctf self._target._volume_property.set_color(ctf) self.__last_vrange = vmin, vmax self._target.update_ctf = True
histA = r2m.Hist2D(A) histA = np.array(histA.content) histA = np.clip(histA, 290, 330) histA = histA[150:850, 150:850] f = TFile("CIRSHead.root") HU = f.Get("hu") print HU.GetNbinsX(), HU.GetNbinsY(), HU.GetNbinsZ() n = [HU.GetNbinsX(), HU.GetNbinsY(), HU.GetNbinsZ()] n2 = (n[0] + 2) * (n[1] + 2) * (n[2] + 2) d = HU.GetArray() d.SetSize(n2) ctf = ColorTransferFunction() ctf.add_rgb_point(0.5, 1, 1, 1) # r, g, and b are float # between 0 and 1 otf = PiecewiseFunction() otf.add_point(-110, 0.0) otf.add_point(-105, 1.0) otf.add_point(128, 1.0) #D = np.array(d).reshape(282,258,258) D = np.array(d).reshape(280 + 2, 512 + 2, 512 + 2) #D = D[80:270,37:210,64:193] X, Y, Z = np.where(D) mlab.figure(bgcolor=(0, 0, 0), size=(400, 400)) vol = mlab.pipeline.volume(mlab.pipeline.scalar_field(D, opacity=1.0), vmin=-60, vmax=128) vol.actors.position = [0, -100, 0] vol._volume_property.set_color(ctf)
def td(ty, t, E, rho, sigma, wdir): D = pp.pload(t, w_dir=wdir) if ty == 'flux': for k in range(D.rho.shape[2]): for j in range(D.rho.shape[1]): for i in range(D.rho.shape[0]): # if (i-D.rho.shape[0]/2)**2+(j-D.rho.shape[1]/2)**2+(k-D.rho.shape[2]/2)**2 > 30**2: # D.rho[k,j,i] = rho if D.rho[k, j, i] > 10: D.rho[k, j, i] = rho flux = D.rho * (D.bx1**2 + D.bx2**2 + D.bx3**2)**1.25 * (D.vx1**2 + D.vx2**2 + D.vx3**2)**0 flux = (flux - np.mean(flux)) * 1 + np.mean(flux) * 1 flux = flux.sum(axis=0) flux = nd.gaussian_filter(flux, sigma=(sigma, sigma), order=0) fig = plt.figure(figsize=(7, 6)) ax = fig.add_subplot(111) neg = ax.imshow(np.log10(flux).T, origin='lower', extent=[D.x2[0], D.x2[-1], D.x3[0], D.x3[-1]]) levels = np.arange(-5.5, -4, 0.5) plt.contour(np.log10(flux).T, levels, origin='lower', linewidths=2, extent=[D.x1[0], D.x1[-1], D.x2[0], D.x2[-1]]) cbar = fig.colorbar(neg, ax=ax) cbar.set_label(r'log(S)') ax.set_xlabel('l offset (pc)') ax.set_ylabel('b offset (pc)') ax.set_title(r't=' + str(t) + r'$\ \mathregular{\rho}$=' + str(rho) + ' E=' + str(E)) fig.subplots_adjust(top=0.9, bottom=0.1, left=0.11, right=0.97) fig.savefig('t' + str(t) + '_density' + str(rho) + '_E' + str(E) + '.eps') fig.clear() ax = fig.add_subplot(111) ax.plot((np.rot90(np.eye(len(flux))) * flux.T).sum(axis=0)) ax.set_xlim(0, 256) fig.savefig('change.eps') elif ty == 'rho': # t = 850 fig = plt.figure(figsize=(7, 6)) ax = fig.add_subplot(111) neg = ax.imshow(np.log10(D.rho[:, :, 128]).T, origin='lower', extent=[D.x2[0], D.x2[-1], D.x3[0], D.x3[-1]]) cbar = fig.colorbar(neg, ax=ax) cbar.set_label(r'log($\mathregular{\rho/cm^{-3}}$)') ax.set_xlabel('x offset (pc)') ax.set_ylabel('y offset (pc)') ax.set_title(r't=' + str(t) + r'$\ \mathregular{\rho}$=' + str(rho) + ' E=' + str(E)) fig.subplots_adjust(top=0.9, bottom=0.1, left=0.11, right=0.97) T = pp.Tools() newdims = 2 * (20, ) Xmesh, Ymesh = np.meshgrid(D.x2.T, D.x3.T) xcong = T.congrid(Xmesh, newdims, method='linear') ycong = T.congrid(Ymesh, newdims, method='linear') velxcong = T.congrid(D.bx1[:, :, 128].T, newdims, method='linear') velycong = T.congrid(D.bx2[:, :, 128].T, newdims, method='linear') plt.gca().quiver(xcong, ycong, velxcong, velycong, color='w') plt.show() fig.savefig('rho-t=' + str(t) + '_density=' + str(rho) + '_E=' + str(E) + '.eps') # Only to be saved as either .png or .jpg # close() else: print(D.x1.shape) # arr = np.meshgrid(D.x1,D.x2,D.x3) # mlab.points3d(arr[0][0:256:8,0:256:8,0:256:8], arr[1][0:256:8,0:256:8,0:256:8], arr[2][0:256:8,0:256:8,0:256:8], D.rho[0:256:8,0:256:8,0:256:8]) vol = mlab.pipeline.volume( mlab.pipeline.scalar_field(np.log10(D.prs * D.rho))) ctf = ColorTransferFunction() ctf.add_hsv_point(-8, 0.8, 1, 1) ctf.add_hsv_point(-6.5, 0.45, 1, 1) ctf.add_hsv_point(-5.4, 0.15, 1, 1) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True otf = PiecewiseFunction() otf.add_point(-8, 0) otf.add_point(-5.7, 0.082) otf.add_point(-5.4, 0.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf)
def potential3d(self, mode='', export_figure=True): """ Creates a 3D interactive ESP potential plot. :param mode: mode of the plot: '', 'iso_surface', 'contour' :param export_figure: boolean, whether to save an image or not :raises: ValueError when the visualization mode is invalid """ from mayavi import mlab potential = self.electron_potential if mode == '': grid = mlab.pipeline.scalar_field(potential) min = potential.min() negative_steps = np.percentile(potential[potential < 0], [2.0, 3.0, 7.5]) positive_steps = np.percentile(potential[potential > 0], [92.5, 97.0, 98.0]) max = potential.max() vol = mlab.pipeline.volume(grid, vmin=min, vmax=max) from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() ctf.add_rgb_point(min, 1, 0.3, 0.3) # numbers are r,g,b in [0;1] ctf.add_rgb_point(negative_steps[1], 1, 0.3, 0.3) ctf.add_rgb_point(negative_steps[2], 1, 1, 1) ctf.add_rgb_point(positive_steps[0], 1, 1, 1) ctf.add_rgb_point(positive_steps[1], 0.3, 0.3, 1) ctf.add_rgb_point(max, 0.3, 0.3, 1) ctf.range = np.asarray([min, max]) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True # Changing the otf: from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(min, 1.0) otf.add_point(negative_steps[1], 1.0) otf.add_point(negative_steps[2], 0.0) otf.add_point(positive_steps[0], 0.0) otf.add_point(positive_steps[1], 1.0) otf.add_point(max, 1.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) mlab.axes() elif mode == 'iso_surface': source = mlab.pipeline.scalar_field(potential) clip = mlab.pipeline.data_set_clipper(source) mlab.pipeline.iso_surface(clip) elif mode == 'contour': n = self.electron_potential.shape[0] range = 100 x, y, z = np.mgrid[-range / 2:range / 2:complex(n), -range / 2:range / 2:complex(n), -range / 2:range / 2:complex(n)] mlab.contour3d(x, y, z, self.electron_potential, contours=10, opacity=0.5) else: log.error("The visualisation mode of the electrostatic potential" " can be one of ['', 'iso_surface', 'contour']") raise ValueError if export_figure: mlab.savefig(filename=os.path.join( self.figures_dir, '{0}_elstpot3d.png'.format( self.molecule_name))) mlab.show()
def volume_red_blue(scalar_field, scalar_data): minr = scalar_data.min() maxr = scalar_data.max() # max and mins rvmin_pos = minr + 0.5 * (maxr - minr) rvmax_pos = minr + 1. * (maxr - minr) rvmin_neg = minr + 0. * (maxr - minr) rvmax_neg = minr + 0.5 * (maxr - minr) rvol = mlab.pipeline.volume(scalar_field, vmin=rvmin_neg, vmax=rvmax_pos) # Changing the ctf: from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() ctf.add_rgb_point(rvmin_pos, 1., 1., 0.5) ctf.add_rgb_point(rvmin_pos + 0.4 * (rvmax_pos - rvmin_pos), 1, 0.3, 0.1) ctf.add_rgb_point(rvmax_pos, 1., 0., 0.) ctf.add_rgb_point(rvmin_neg, 0., 0.5, 1.) ctf.add_rgb_point(rvmin_neg + 0.6 * (rvmax_neg - rvmin_neg), 0.1, 0.7, 1.) ctf.add_rgb_point(rvmax_neg, 0.5, 1., 1.) rvol._volume_property.set_color(ctf) rvol._ctf = ctf rvol.update_ctf = True #Changing the opacity of the volume vol ## Changing the otf: from tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(rvmin_pos, 0) otf.add_point(rvmin_pos + (rvmax_pos - rvmin_pos) * 0.2, 0.012) otf.add_point(rvmin_pos + (rvmax_pos - rvmin_pos) * 0.5, 0.05) otf.add_point(rvmax_pos, 0.15) otf.add_point(rvmax_neg, 0) otf.add_point(rvmax_neg - (rvmax_neg - rvmin_neg) * 0.2, 0.012) otf.add_point(rvmax_neg - (rvmax_neg - rvmin_neg) * 0.5, 0.05) otf.add_point(rvmin_neg, 0.15) ##vol1._otf = otf rvol._volume_property.set_scalar_opacity(otf) # exempt volume from shading and improve overall look by increasing opacity rvol.volume_property.shade = False rvol.volume_property.scalar_opacity_unit_distance = 2.0
# data = np.array(f['t'+str(i)]) # mlab.contour3d(data, contours=10, transparent=True) # mlab.savefig(filename='fig'+str(i)+'.png') ctf = ColorTransferFunction() # ctf.add_rgb_point(0, 0, 0, 1) # ctf.add_rgb_point(200, 0, 0, 1) # ctf.add_rgb_point(499, 1, 0, 0) # ctf.add_rgb_point(501, 1, 0, 0) ctf.add_rgb_point(1, 1, 0, 0) # Changing the otf: otf = PiecewiseFunction() # otf.add_point(502, 1) for i in range(101): otf.add_point(i/100.0, (np.sqrt(i/100.0))) otf2 = PiecewiseFunction() for i in range(101): otf.add_point(i/100, np.sqrt(np.sqrt(np.sqrt(np.sqrt(i/100))))) for i in range(len(f.keys())): mlab.figure(size=(800,799),bgcolor = (1,1,1)) x,y,z=np.mgrid[0:100,0:100,0:99] data=np.array(f[f.keys()[i]]) #scattered wave # data2=np.array(f_p[f_p.keys()[i]]) #plane wave # data[:,:,:]=0 m=np.amax(data) # m=0.5;
def volume_render(self, min_depth, max_depth, is_bronchioles_mode, is_no_contrast_mode, is_advanced_mode): if min_depth >= max_depth: MainController.display_message_box(QMessageBox.Warning, "Error", "Minimal depth must be less then maximal depth.") return if self._model._images_directory == '': MainController.display_message_box(QMessageBox.Warning, "Error", "Load images first.") return if is_advanced_mode: mlab.options.backend = 'envisage' else: mlab.options.backend = 'auto' mlab.figure('Volume render') images = np.zeros(shape=(len(self._model._images), 512, 512), dtype="float32") for index in range(0, len(self._model.images)): img = image.load_img(os.path.join(self._model._images_directory, self._model.images[index].name), target_size=(512, 512), color_mode='grayscale') images[index] = img s = images[:, min_depth:max_depth, :] s = s[:, :, ::-1] vol = mlab.pipeline.volume(mlab.pipeline.scalar_field(s)) otf = PiecewiseFunction() if is_bronchioles_mode and not is_no_contrast_mode: otf.add_point(0, 0.0) otf.add_point(99, 0.0) otf.add_point(100, 0.1) otf.add_point(190, 0.1) otf.add_point(191, 0.0) otf.add_point(255, 0) elif not is_no_contrast_mode: otf.add_point(0, 0.0) otf.add_point(139, 0.0) otf.add_point(140, 0.1) otf.add_point(200, 0.1) otf.add_point(255, 1) elif is_bronchioles_mode: otf.add_point(0, 0.0) otf.add_point(1, 0.2) otf.add_point(30, 0.2) otf.add_point(30, 0.0) otf.add_point(255, 0.0) else: otf.add_point(0, 0.0) otf.add_point(1, 0.1) otf.add_point(50, 1.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) mlab.show()
import numpy as np import h5py from mayavi import mlab from tvtk.util.ctf import ColorTransferFunction from tvtk.util.ctf import PiecewiseFunction filename = 'Ezdata2.h5' f = h5py.File(filename, 'r') filename = 'Ezdata.h5' f_p = h5py.File(filename, 'r') #just plane wave ctf = ColorTransferFunction() ctf.add_rgb_point(1, 1, 0, 0) # ctf.add_rgb_point(1, 0, 0, 1) # Changing the otf: otf = PiecewiseFunction() # for i in range(101): # otf.add_point(i/100, np.sqrt(np.sqrt(i/100))) # otf2 = PiecewiseFunction() for i in range(101): otf.add_point(i / 100.0, (i / 100.0)**(0.7)) for i in [30, 65, 85]: mlab.figure(size=(800, 799), bgcolor=(1, 1, 1)) x, y, z = np.mgrid[0:99, 0:99, 0:100] data = np.array(f[f.keys()[i]]) #scattered wave data2 = np.array(f_p[f_p.keys()[i]]) #plane wave data2[:, :, :] = 0 # data2=np.abs(data2-data) # m=np.amax(data) m = np.amax(data)
def volume(sim, qty='rho', width=None, resolution=200, color=(1.0, 1.0, 1.0), vmin=None, vmax=None, dynamic_range=4.0, log=True, create_figure=True): """Create a volume rendering of the given simulation using mayavi. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (None): The width of the cube to generate, centered on the origin *resolution* (200): The number of elements along each side of the cube *color* (white): The color of the volume rendering. The value of each voxel is used to set the opacity. *vmin* (None): The value for zero opacity (calculated using dynamic_range if None) *vmax* (None): The value for full opacity (calculated from the maximum value in the region if None) *dynamic_range*: The dynamic range to use if vmin and vmax are not specified *log* (True): log-scale the image before passing to mayavi *create_figure* (True): create a new mayavi figure before rendering """ import mayavi from mayavi import mlab from tvtk.util.ctf import PiecewiseFunction, ColorTransferFunction if create_figure: fig = mlab.figure(size=(500, 500), bgcolor=(0, 0, 0)) grid_data = sph.to_3d_grid(sim, qty=qty, nx=resolution, x2=None if width is None else width / 2) if log: grid_data = np.log10(grid_data) if vmin is None: vmin = grid_data.max() - dynamic_range if vmax is None: vmax = grid_data.max() else: if vmin is None: vmin = np.min(grid_data) if vmax is None: vmax = np.max(grid_data) grid_data[grid_data < vmin] = vmin grid_data[grid_data > vmax] = vmax otf = PiecewiseFunction() otf.add_point(vmin, 0.0) otf.add_point(vmax, 1.0) sf = mayavi.tools.pipeline.scalar_field(grid_data) V = mlab.pipeline.volume(sf, color=color, vmin=vmin, vmax=vmax) V.trait_get( 'volume_mapper')['volume_mapper'].blend_mode = 'maximum_intensity' if color is None: ctf = ColorTransferFunction() ctf.add_rgb_point(vmin, 107. / 255, 124. / 255, 132. / 255) ctf.add_rgb_point(vmin + (vmax - vmin) * 0.8, 200. / 255, 178. / 255, 164. / 255) ctf.add_rgb_point(vmin + (vmax - vmin) * 0.9, 1.0, 210. / 255, 149. / 255) ctf.add_rgb_point(vmax, 1.0, 222. / 255, 141. / 255) print vmin, vmax V._volume_property.set_color(ctf) V._ctf = ctf V.update_ctf = True V._otf = otf V._volume_property.set_scalar_opacity(otf) return V
def set_opacity_transfer(vol, density, opacity): otf = PiecewiseFunction() otf.add_point(0, 0) otf.add_point(density, opacity) vol._otf = otf vol._volume_property.set_scalar_opacity(otf)
surf_bar_label.x_position = 0.93 # Add GBand volume render vol = mlab.pipeline.volume(gband) vol.volume.mapper.blend_mode = 'maximum_intensity' #vol.volume.mapper.number_of_threads = 16 # Make a decent ctf and otf ctf = ColorTransferFunction() ctf.range = [0.1, 1] ctf.add_rgb_point(1, 1., 1, 0.01) ctf.add_rgb_point(0.85, 1., 0.8, 0.) ctf.add_rgb_point(0.6, 0.9, 0.3, 0.) ctf.add_rgb_point(0.4, 0.8, 0.0, 0.) ctf.add_rgb_point(0., 0.01, 0., 0.) otf = PiecewiseFunction() otf.add_point(1., 1.) otf.add_point(0.6, 0.9) otf.add_point(0.2, 0.) otf.add_point(0., 0.) vol._volume_property.set_color(ctf) vol._ctf = ctf vol._otf = otf vol._volume_property.set_scalar_opacity(otf) vol.update_ctf = True # Add The axes axes, outline = mpf.add_axes(np.array(zip(ds.domain_left_edge,ds.domain_right_edge)).flatten()/1e8, obj=bfield) axes.axes.property.color = text_color axes._title_text_property.color = text_color
import pyvoxsurf from mayavi import mlab volume1 = pyvoxsurf.voxelize_stl("model.stl", 200, [], "Robust") print(volume1.shape) # Visualize voxelized model from tvtk.util.ctf import PiecewiseFunction mlab.figure(size=(800, 800)) vol = mlab.pipeline.volume(mlab.pipeline.scalar_field(volume1)) mlab.title("Voxelized model", height=0.9, size=0.5) mlab.orientation_axes() otf = PiecewiseFunction() otf.add_point(0, 0) otf.add_point(0.001, 1) otf.add_point(1, 1) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) mlab.show() import pyvoxsurf import trimesh import numpy as np from mayavi import mlab mesh = trimesh.load("model.stl") # Load stl file # Find the max and min coordinates of the mesh to form a bounding box mesh_min_corner = [ np.min(mesh.vertices[:, 0]),