def _plot_max_Value( self ): X = self.X_hf[:, 0] Y = self.Y_hf[:, 0] Z = self.Z_hf[:, 0] plot_col = getattr( self, self.plot_column )[:, 0] scale = 1 / max( plot_col ) # if self.plot_column == 'n_tex': # plot_col = where( plot_col < 0, 0, plot_col ) mlab.figure( figure = "SFB532Demo", bgcolor = ( 1.0, 1.0, 1.0 ), fgcolor = ( 0.0, 0.0, 0.0 ) ) mlab.points3d( X, Y, ( -1.0 ) * Z, plot_col, # colormap = "gist_rainbow", # colormap = "Reds", colormap = "copper", mode = "cube", scale_factor = scale ) mlab.outline() mlab.scalarbar( title = self.plot_column, orientation = 'vertical' ) mlab.show
def main(argv): if ( len(argv) != 1 ): print ("Usage: python visualizeField.py <datafile.json>") return # Read input file try: infile = open( argv[0], 'r' ) except: print ("Error when opening file %s"%(argv[0])) return data = json.load( infile ) infile.close() y = np.array( data["points"]["y"] ) z = np.array( data["points"]["z"] ) x = np.zeros( len(y) ) Ex = np.array( data["field"]["x"] ) pts = mlab.points3d( y, z, x, Ex, scale_mode="scalar", scale_factor=0.0, mode="point") mesh = mlab.pipeline.delaunay2d( pts ) surf = mlab.pipeline.surface( mesh ) fname = "Figures/fieldyzPlane.png" mlab.view(0.0,0.0,1.0, (0.0,0.0,0.0)) mlab.scalarbar() mlab.xlabel( "y" ) mlab.ylabel( "z" ) mlab.show()
def show_lung(event): if not button4.get_status()[0]: tmp_3d = pred_st_tmp.copy() threshold = slider1.val tmp_3d[tmp_3d < threshold] = 0 tmp_3d[tmp_3d >= threshold] = 1 mlab.clf() mlab.contour3d(tmp_3d, colormap = 'hot', opacity = 1.0, vmin = 0, vmax = 1) if button1.get_status()[0]: mlab.contour3d(mask, colormap = 'Greys', opacity = 0.1, vmin = 0, vmax = 150) elif button4.get_status()[0]: pred_class = pred_VGG(im_ct, pred_st, res, VGG_model_path) pred_class = zoom(pred_class.copy(), zoom = zoom_fac, order = 0) mlab.clf() print(np.unique(pred_class)[1:]) for i in np.unique(pred_class): if i == 0: continue tmp = pred_class.copy() tmp[pred_class != i] = 0 mlab.contour3d(tmp, colormap = 'OrRd', color = tuple(colors[int(round((9/5)*i)),:]), vmin = 1, vmax = 5) mlab.scalarbar(orientation = 'vertical', nb_labels = 9, label_fmt='%.1f') if button1.get_status()[0]: mlab.contour3d(mask, colormap = 'Greys', opacity = 0.1, vmin = 0, vmax = 150) mlab.orientation_axes(xlabel = 'z', ylabel = 'y', zlabel = 'x')
def _plot_max_Value(self): X = self.X_hf[:, 0] Y = self.Y_hf[:, 0] Z = self.Z_hf[:, 0] plot_col = getattr(self, self.plot_column)[:, 0] scale = 1 / max(plot_col) # if self.plot_column == 'n_tex': # plot_col = where( plot_col < 0, 0, plot_col ) mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d( X, Y, (-1.0) * Z, plot_col, # colormap = "gist_rainbow", # colormap = "Reds", colormap="copper", mode="cube", scale_factor=scale) mlab.outline() mlab.scalarbar(title=self.plot_column, orientation='vertical') mlab.show
def plot_diff_grid(occupancies_3d, observation_certainties_3d, epsilon=1e-5, title_prefix="", fig_offset=None, show=True): x, y, z = get_xyz_grids(occupancies_3d, scale=0.1) s = occupancies_3d fig = create_mlab_figure(fig=fig_offset) fig_offset = fig_offset + 1 if fig_offset is not None else None mask = np.abs(s) > epsilon # print(np.max(np.abs(s))) # print(np.min(np.abs(s[mask]))) plot3d_with_mask(x, y, z, s, mask, fig=fig) mlab.title(title_prefix + "Occupancy") mlab.scalarbar() s = observation_certainties_3d fig = create_mlab_figure(fig=fig_offset) fig_offset = fig_offset + 1 if fig_offset is not None else None mask = np.abs(s) > epsilon # print(np.max(np.abs(s))) # print(np.min(np.abs(s[mask]))) plot3d_with_mask(x, y, z, s, mask, fig=fig) mlab.title(title_prefix + "Observation count") mlab.scalarbar() if show: mlab.show() return fig_offset
def plot(view="iso"): redis = Redis() px, py, pz = (redis.get('x'), redis.get('y'), redis.get('z')) if None in (px, py, pz): raise UntrainedException("You must train first!") x, y, z = (pickle.loads(px), pickle.loads(py), pickle.loads(pz)) fig = mlab.figure(size=(800, 600)) # these options could help on certain platforms # mlab.options.offscreen = True # fig.scene.off_screen_rendering = True # Define the points in 3D space # including color code based on Z coordinate. mlab.points3d(x, y, z, y) xlabel = "day of week" ylabel = "# logins" zlabel = "hour" mlab.axes(xlabel=xlabel, ylabel=ylabel, zlabel=zlabel, ranges=[0, 6, min(y), max(y), 0, 23]) mlab.scalarbar(title=ylabel, nb_labels=10, orientation='vertical') mlab.orientation_axes(xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) views = {"xp": fig.scene.x_plus_view, "xm": fig.scene.x_minus_view, "yp": fig.scene.y_plus_view, "ym": fig.scene.y_minus_view, "zp": fig.scene.z_plus_view, "zm": fig.scene.z_minus_view, "iso": fig.scene.isometric_view } try: views[view]() except KeyError as e: raise PlotException("Invalid view option: %s" % view) # can't save directly to stringIO, so have to go through a file fig.scene.save_png('fig.png') # mayavi doesn't seem to play well with celery on some platforms and # doesn't shut down properly - probably because it's in a background thread # on centos, celery just throws a WorkerLostError after a couple of requests. # fig.remove() # fig.parent.close_scene(fig) # this doesn't work on centos: # mlab.close() with open('fig.png', 'rb') as f: buf = f.read() return buf
def prepare_plot(x, y, z): """funkcija priprema pozadintki plot tj f(x,y) sa svim oznakama""" fun_plot = pipe.array2d_source(x, y, z) fun_plot.add_module(mlab.axes(nb_labels=9, color=(0, 0, 0))) warp = pipe.warp_scalar(fun_plot) normals = pipe.poly_data_normals(warp) surf = pipe.surface(normals) mlab.scalarbar(orientation='vertical', title="f(x,y)") return fun_plot
def render_classes_planar(self, volume, title): """Create 3 movable plane cuts on a 3d volume """ mlab.figure(size=(800, 800)) s = volume self.create_plane_cut(s, plane_orientation='x_axes') self.create_plane_cut(s, plane_orientation='y_axes') self.create_plane_cut(s, plane_orientation='z_axes') mlab.outline() mlab_label(mlab.xlabel, text=self.dfcn.easting_col) mlab_label(mlab.ylabel, text=self.dfcn.northing_col) mlab_label(mlab.zlabel, text='mAHD') mlab.scalarbar(nb_labels=self.nb_labels()) mlab_title(title)
def plot_grid(occupancies_3d, observation_certainties_3d): import visualize_data import visualization import mayavi.mlab as mlab x, y, z = visualize_data.get_xyz_grids(occupancies_3d, scale=0.1) s = occupancies_3d fig = visualize_data.create_mlab_figure() visualize_data.plot3d_with_threshold(x, y, z, s, low_thres=0.2, fig=fig) mlab.title("Occupancy") mlab.scalarbar() s = occupancies_3d fig = visualize_data.create_mlab_figure() visualize_data.plot3d_with_threshold(x, y, z, s, fig=fig) mlab.title("Occupancy") mlab.scalarbar() s = observation_certainties_3d fig = visualize_data.create_mlab_figure() visualize_data.plot3d_with_threshold(x, y, z, s, high_thres=0.5, fig=fig) mlab.title("Observation count") mlab.scalarbar() s = observation_certainties_3d fig = visualize_data.create_mlab_figure() visualize_data.plot3d_with_threshold(x, y, z, s, fig=fig) mlab.title("Observation count2") mlab.scalarbar() mlab.show()
def sphere_el(self): """ Visualising the magnetic field and using as a sphere as a volume element to analyse the field and its magnetic field lines """ R = float(self.slR.get()) I = float(self.slI.get()) mew0 = 4*np.pi * 10.**-7 #μ0 constant #Generating the 3D space x, y, z = [i.astype(np.float32) for i in np.ogrid[-20:20:200j, -20:20:200j, -20:20:200j]] r = np.sqrt(x ** 2 + y ** 2) x_trans = x / r #cos(a) y_trans = y / r #sin(a) E = special.ellipe((4*R*r)/((R+r)**2 + z**2)) #special ellipse E K = special.ellipk((4*R*r)/((R+r)**2 + z**2)) #special ellipse K Bz = (I)/ (2*np.pi*np.sqrt((R+r)**2 + z**2)) * (K + E * (R**2 - r**2 - z**2)/((R-r)**2 + z**2)) #When r=0 there is a ZeroDivisionError for Br try: Br = (I/(2*np.pi * r))*(z/(np.sqrt((R+r)**2 + z**2)))*(-K + E*((R**2 + r**2 + z**2)/((R-r)**2 + z**2))) except ZeroDivisionError: Br = 0 #When the current I equals 0 there is no magnetic field if I==0: return msg.showwarning('WARNING:','When I=0, \n There is no magnetic field generated') else: mlab.close(all=True) Bx, By = x_trans * Br, y_trans * Br fig = mlab.figure(1, size=(500, 500), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) field = mlab.pipeline.vector_field(Bx, By, Bz) magnitude = mlab.pipeline.extract_vector_norm(field) contours = mlab.pipeline.iso_surface(magnitude, contours=[0.001,0.8, 3.8, 4.0 ], transparent=True, opacity=0.6, colormap='YlGnBu', vmin=0, vmax=0.5) field_lines = mlab.pipeline.streamline(magnitude, seedtype='sphere', integration_direction='both', transparent=True, opacity=0.3, colormap='jet', vmin=0, vmax=0.5) field_lines.stream_tracer.maximum_propagation = 150. field_lines.seed.widget.radius = 5.5 mlab.view(azimuth=42, elevation=73, distance=104) mlab.title('Visualisation of the magnetic field\n generated by a current loop') sc = mlab.scalarbar(field_lines,title='Field Strength [T]', orientation='vertical', nb_labels=4) sc.scalar_bar_representation.position2 = np.array([ 0.1, 0.8]) sc.scalar_bar_representation.position = np.array([ 0.88374749, 0.14342105]) del x,y,z,r,E,K,Br,Bx,By,Bz
def scalarbar(*args, **kwargs): """Wraps mayavi.mlab.scalarbar and adjusts cmap if you so choose""" cmap = kwargs.pop("cmap", False) kwargs, cmap_kwargs = _extract_cmap_kwargs(kwargs) cmap_kwargs.pop("cmap") ret = mlab.scalarbar(*args, **kwargs) apply_cmap(ret, cmap=cmap, **cmap_kwargs) return ret
def _plot_fired(self): plot_col = getattr(self, self.plot_column)[:, 0] mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) gd = self.ls_table.geo_data sd = self.ls_table.state_data if self.plot_column == "n_tex": plot_col = where(plot_col < 0, 0, plot_col) r = self.ls_table.reader r.plot_col(mlab, plot_col, gd, state_data=sd, warp_factor=self.warp_factor) mlab.scalarbar(title=self.plot_column, orientation="vertical") mlab.show
def classify(event): if button4.get_status()[0]: pred_class = pred_VGG(im_ct, pred_st, res, VGG_model_path) pred_class = zoom(pred_class.copy(), zoom = zoom_fac, order = 0) mlab.clf() print(np.unique(pred_class)[1:]) for i in np.unique(pred_class): if i == 0: continue tmp = pred_class.copy() tmp[pred_class != i] = 0 mlab.contour3d(tmp, colormap = 'OrRd', color = tuple(colors[int(round((9/5)*i)),:]), vmin = 1, vmax = 5) mlab.scalarbar(orientation = 'vertical', nb_labels = 9, label_fmt='%.1f') if button1.get_status()[0]: mlab.contour3d(mask, colormap = 'Greys', opacity = 0.1, vmin = 0, vmax = 150) mlab.orientation_axes(xlabel = 'z', ylabel = 'y', zlabel = 'x') elif not button4.get_status()[0]: # re-plot without classify tmp_thr = pred_st[int(slider2.val)].copy() tmp_3d = pred_st_tmp.copy() threshold = slider1.val tmp_thr[tmp_thr < threshold] = 0 tmp_thr[tmp_thr >= threshold] = 1 tmp_3d[tmp_3d < threshold] = 0 tmp_3d[tmp_3d >= threshold] = 1 mlab.clf() mlab.contour3d(tmp_3d, colormap = 'hot', opacity = 1.0, vmin = 0, vmax = 1) if button1.get_status()[0]: mlab.contour3d(mask, colormap = 'Greys', opacity = 0.1, vmin = 0, vmax = 150) ax.clear() ax.imshow(im_ct[int(slider2.val), :, :], cmap = 'gray') #ax.imshow(tmp_thr, cmap = 'inferno', vmin = 0, vmax = 1, alpha = 0.3) ax.imshow(tmp_thr, cmap = 'gnuplot', vmin = 0, vmax = 2, alpha = 0.3) ax.set_axis_off() f.suptitle('slice '+str(slider2.val)) f.canvas.draw_idle()
def _plot_fired(self): plot_col = getattr(self, self.plot_column)[:, 0] mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) gd = self.ls_table.geo_data sd = self.ls_table.state_data if self.plot_column == 'n_tex': plot_col = where(plot_col < 0, 0, plot_col) r = self.ls_table.reader r.plot_col(mlab, plot_col, gd, state_data=sd, warp_factor=self.warp_factor) mlab.scalarbar(title=self.plot_column, orientation='vertical') mlab.show
def render_proba_class(self, prob_volume, title): """Create 3 movable plane cuts on a 3d volume of probabilities (probability of classification) Args: prob_volume (3D array): gridded probability of a lithology title (str): title """ mlab.figure(size=(800, 800)) # s = np.flip(np.flip(test,axis=2), axis=0) s = prob_volume colormap = 'magma' self.create_plane_cut(s, plane_orientation='x_axes', colormap=colormap) self.create_plane_cut(s, plane_orientation='y_axes', colormap=colormap) self.create_plane_cut(s, plane_orientation='z_axes', colormap=colormap) mlab.outline() mlab_label(mlab.xlabel, text=self.dfcn.easting_col) mlab_label(mlab.ylabel, text=self.dfcn.northing_col) mlab_label(mlab.zlabel, text='mAHD') mlab_title(title) mlab.scalarbar(nb_labels=11)
def _plot_fired(self): plot_col = getattr(self, self.plot_column).flatten() if self.plot_column == 'n_tex': plot_col = np.where(plot_col < 0, 0, plot_col) mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) gd = self.ls_table.geo_data sd = self.ls_table.state_data r = self.ls_table.reader # use plotting function defined by the specific LCCTableReader # extract global coordinates ('X','Y','Z') from 'geo_data' and # global displacements ('ux_elem','uy_elem','uz_elem') from 'state_data' # if this information is available (distinguished by the specific Reader) r.plot_col(mlab, plot_col, gd, state_data=sd, warp_factor=self.warp_factor) mlab.scalarbar(title=self.plot_column, orientation='vertical') mlab.show
def _plot_fired(self): plot_col = getattr(self, self.plot_column).flatten() if self.plot_column == 'n_tex': plot_col = where(plot_col < 0, 0, plot_col) mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) gd = self.ls_table.geo_data sd = self.ls_table.state_data r = self.ls_table.reader # use plotting function defined by the specific LCCTableReader # extract global coordinates ('X','Y','Z') from 'geo_data' and # global displacements ('ux_elem','uy_elem','uz_elem') from 'state_data' # if this information is available (distinguished by the specific Reader) r.plot_col(mlab, plot_col, gd, state_data=sd, warp_factor=self.warp_factor) mlab.scalarbar(title=self.plot_column, orientation='vertical') mlab.show
def add_data(self, array, min=None, max=None, colormap="blue-red"): """Display data from a numpy array on the surface. Parameters ---------- array : numpy array data array (nvtx vector) min : float min value in colormap (uses real min if None) max : float max value in colormap (uses real max if None) colormap : str name of Mayavi colormap to use """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab self._f.scene.disable_render = True view = mlab.view() # Possibly remove old data if hasattr(self, "data"): self.data["surface"].remove() self.data["colorbar"].remove() if min is None: min = array.min() if max is None: max = array.max() # Set up the visualization pipeline mesh = mlab.pipeline.triangular_mesh_source(self._geo.x, self._geo.y, self._geo.z, self._geo.faces, scalars=array) surf = mlab.pipeline.surface(mesh, colormap=colormap, vmin=min, vmax=max) # Get the colorbar bar = mlab.scalarbar(surf) bar.scalar_bar_representation.position2 = .8, 0.09 # Fil in the data dict self.data = dict(surface=surf, colorbar=bar) mlab.view(*view) self._f.scene.disable_render = False
def Scatter3d_Mayavi(xs, ys, zs, weights=None, weight_label=None, xlabel='x', ylabel='y', zlabel='z', axes=True, **points3d_kw): from mayavi import mlab # XXX error when max() returns zero def normalize(vs): a = vs.min() b = vs.max() if a != b: vs = vs / float(b - a) return vs xs = normalize(xs) ys = normalize(ys) zs = normalize(zs) if 'scale_mode' not in points3d_kw: points3d_kw['scale_mode'] = 'none' if 'scale_factor' not in points3d_kw: points3d_kw['scale_factor'] = .03 if weights is None: mlab.points3d(xs, ys, zs, **points3d_kw) else: mlab.points3d(xs, ys, zs, weights, **points3d_kw) if weight_label: mlab.scalarbar(title=weight_label) if axes: extent = 1.2 scale = 0.05 tube_radius = 0.01 color = (1,1,1) # white mlab.plot3d([0,extent], [0,0], [0,0], tube_radius=tube_radius, color=color) mlab.plot3d([0,0], [0,extent], [0,0], tube_radius=tube_radius, color=color) mlab.plot3d([0,0], [0,0], [0,extent], tube_radius=tube_radius, color=color) if xlabel: mlab.text3d(extent, 0, 0, xlabel, scale=scale, color=color) if ylabel: mlab.text3d(0, extent, 0, ylabel, scale=scale, color=color) if zlabel: mlab.text3d(0, 0, extent, zlabel, scale=scale, color=color)
def plot(cls, F, geomdim, domain=[[0, 1]], resolution=1 / 50, vectorized=True, style="-", opacity=1.0, with_scalar_bar=False): try: F[0] except: F = (F,) domain = (domain,) try: N = len(F) except: N = 1 if len(domain) != N: domain = domain * N for i, f, dom in zip(range(len(F)), F, domain): p = cls.get_points(geomdim, dom, resolution) if vectorized: if geomdim == 1: x = p[0] elif geomdim == 2: # x = np.vstack((p[0].flatten(), p[1].flatten())).T x = np.array([[tx, ty] for tx, ty in zip(p[0].flatten(), p[1].flatten())]) y = f(x) else: if geomdim == 1: y = np.array([ f(p[0][i]) for i in range(len(p[0])) ]) elif geomdim == 2: y = np.array([ f(np.array((tx, ty))) for tx, ty in zip(p[0].flatten(), p[1].flatten())]) if geomdim == 2: N, M = p[0].shape y = y.reshape(p[0].shape) if i == 0: fig = mlab.figure(bgcolor=(0.75, 0.75, 0.75), size=(800, 600)) cls.plot_data(geomdim, p, y, style=style, opacity=opacity) if geomdim == 2: mlab.axes(color=(0, 0, 0), line_width=2, nb_labels=3) if with_scalar_bar: mlab.scalarbar(orientation='vertical') mlab.show()
def scene_style(objs: dict, **kwargs) -> None: sc = mlab.scalarbar( objs["streamlines"], title="Field\nStrength [T]", orientation="vertical", nb_labels=4, ) # horizontal and vertical position from left->right, bottom->top sc.scalar_bar_representation.position = np.array([0.85, 0.1]) # width and height of colourbar sc.scalar_bar_representation.position2 = np.array([0.1, 0.8]) # The title of colourbar does not scale so we need to manually set it sc.scalar_bar.unconstrained_font_size = True sc.title_text_property.font_size = 20 sc.label_text_property.font_size = 20 ax = mlab.axes() mlab.view(azimuth=42, elevation=73)
def plot_grid(occupancies_3d, observation_certainties_3d, title_prefix="", fig_offset=None, show=True): x, y, z = get_xyz_grids(occupancies_3d, scale=0.1) s = occupancies_3d fig = create_mlab_figure(fig=fig_offset) fig_offset = fig_offset + 1 if fig_offset is not None else None plot3d_with_threshold(x, y, z, s, low_thres=0.51, fig=fig) mlab.title(title_prefix + "Occupied") mlab.scalarbar() # s = occupancies_3d # fig = create_mlab_figure() # plot3d_with_threshold(x, y, z, s, fig=fig) # mlab.title("Occupancy") # mlab.scalarbar() # fig = create_mlab_figure() contour3d(x, y, z, occupancies_3d, contours=[0.6], opacity=0.7, fig=fig) s = occupancies_3d fig = create_mlab_figure(fig=fig_offset) fig_offset = fig_offset + 1 if fig_offset is not None else None mask = np.logical_and(s <= 0.49, observation_certainties_3d < 1.0) mask = np.logical_and(mask, observation_certainties_3d > 0.0) plot3d_with_mask(x, y, z, s, mask, fig=fig) mlab.title(title_prefix + "Free") mlab.scalarbar() s = observation_certainties_3d fig = create_mlab_figure(fig=fig_offset) fig_offset = fig_offset + 1 if fig_offset is not None else None mask = np.logical_and(s >= 0.01, observation_certainties_3d <= 0.9) plot3d_with_mask(x, y, z, s, mask, fig=fig) mlab.title(title_prefix + "Observation count") mlab.scalarbar() # s = observation_certainties_3d # fig = create_mlab_figure() # plot3d_with_threshold(x, y, z, s, fig=fig) # mlab.title("Observation count2") # mlab.scalarbar() if show: mlab.show() return fig_offset
def postprocessing(self): import mayavi, vtk, os from mayavi import mlab mlab.init_notebook() from mayavi.sources.vtk_xml_file_reader import VTKXMLFileReader from mayavi.sources.vrml_importer import VRMLImporter from mayavi.modules.outline import Outline from mayavi.modules.streamline import Streamline from mayavi.modules.iso_surface import IsoSurface from mayavi.sources.vtk_file_reader import VTKFileReader print('Mayavi {}, {}, DISPLAY {}'.format(mayavi.__version__, vtk.vtkVersion.GetVTKSourceVersion(), os.environ['DISPLAY'])) # fetch the results fname='Composition_00010000.vtk' oc_proj_base = self.wJobPath.value.strip(' /') oc=DavProxy() oc.set_token() oc.get(oc_proj_base + '/OP/VTK/'+fname, './' + fname) # run mlab pipeline mlab.clf() # clear figure r = VTKFileReader() r.initialize(fname) r.point_scalars_name = 'TotalComposition_Li' scp=mlab.pipeline.scalar_cut_plane(r, view_controls=False,plane_orientation='y_axes') scpx=mlab.pipeline.scalar_cut_plane(r, view_controls=False,plane_orientation='x_axes') mlab.pipeline.outline(r) col_cp=mlab.scalarbar(scp, title='C(Li)', orientation='vertical') return mlab.gcf() # plot
def __init__(self, scalar_data, geo, min, max, sign): """ """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab if scalar_data.min() >= 0: sign = "pos" elif scalar_data.max() <= 0: sign = "neg" self.sign = sign # Get data with a range that will make sense for automatic thresholding if sign == "neg": range_data = np.abs(scalar_data[np.where(scalar_data < 0)]) elif sign == "pos": range_data = scalar_data[np.where(scalar_data > 0)] else: range_data = np.abs(scalar_data) if min is None: try: min = config.getfloat("overlay", "min_thresh") except ValueError: min_str = config.get("overlay", "min_thresh") if min_str == "robust_min": min = stats.scoreatpercentile(range_data, 2) elif min_str == "actual_min": min = range_data.min() else: min = 2.0 warn("The 'min_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is %s. " "I'm setting the overlay min to the config default of 2" % min) if max is None: try: max = config.getfloat("overlay", "max_thresh") except ValueError: max_str = config.get("overlay", "max_thresh") if max_str == "robust_max": max = stats.scoreatpercentile(range_data, 98) elif max_str == "actual_max": max = range_data.max() else: max = stats.scoreatpercentile(range_data, 98) warn("The 'max_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is %s. " "I'm setting the overlay min to the config default " "of robust_max" % max) # Clean up range_data since we don't need it and it might be big del range_data # Byte swap inplace; due to mayavi bug mlab_data = scalar_data.copy() if scalar_data.dtype.byteorder == '>': mlab_data.byteswap(True) if sign in ["abs", "pos"]: pos_mesh = mlab.pipeline.triangular_mesh_source(geo.x, geo.y, geo.z, geo.faces, scalars=mlab_data) # Figure out the correct threshold to avoid TraitErrors # This seems like not the cleanest way to do this pos_data = scalar_data[np.where(scalar_data > 0)] try: pos_max = pos_data.max() except ValueError: pos_max = 0 if pos_max < min: thresh_low = pos_max else: thresh_low = min pos_thresh = mlab.pipeline.threshold(pos_mesh, low=thresh_low) pos_surf = mlab.pipeline.surface(pos_thresh, colormap="YlOrRd", vmin=min, vmax=max) pos_bar = mlab.scalarbar(pos_surf) pos_bar.reverse_lut = True self.pos = pos_surf self.pos_bar = pos_bar if sign in ["abs", "neg"]: neg_mesh = mlab.pipeline.triangular_mesh_source(geo.x, geo.y, geo.z, geo.faces, scalars=mlab_data) # Figure out the correct threshold to avoid TraitErrors # This seems even less clean due to negative convolutedness neg_data = scalar_data[np.where(scalar_data < 0)] try: neg_min = neg_data.min() except ValueError: neg_min = 0 if neg_min > -min: thresh_up = neg_min else: thresh_up = -min neg_thresh = mlab.pipeline.threshold(neg_mesh, up=thresh_up) neg_surf = mlab.pipeline.surface(neg_thresh, colormap="PuBu", vmin=-max, vmax=-min) neg_bar = mlab.scalarbar(neg_surf) self.neg = neg_surf self.neg_bar = neg_bar self.__format_colorbar()
con_val = np.array(con_val) # Show the connections as tubes between sensors vmax = np.max(con_val) vmin = np.min(con_val) for val, nodes in zip(con_val, con_nodes): x1, y1, z1 = sens_loc[nodes[0]] x2, y2, z2 = sens_loc[nodes[1]] points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val], vmin=vmin, vmax=vmax, tube_radius=0.001, colormap='RdBu') points.module_manager.scalar_lut_manager.reverse_lut = True mlab.scalarbar(points, title='Phase Lag Index (PLI)', nb_labels=4) # Add the sensor names for the connections shown nodes_shown = list(set([n[0] for n in con_nodes] + [n[1] for n in con_nodes])) for node in nodes_shown: x, y, z = sens_loc[node] mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005, color=(0, 0, 0)) view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2])) mlab.view(*view)
zspin3d[:, :, k] = all_latt[H_ind, T_ind, :, :, slice_show[k], 2] pts = mlab.quiver3d(Xs, Ys, Zs, xspin3d, yspin3d, zspin3d, mode="cone", resolution=50, scale_factor=2, scalars=zspin3d, opacity=1, vmin=-1, vmax=1) pts.glyph.color_mode = 'color_by_scalar' cbar = mlab.scalarbar(pts, title=r"Mz", orientation="vertical") pts.module_manager.scalar_lut_manager.lut_mode = "RdBu" pts.module_manager.scalar_lut_manager.label_text_property.color = (0.0, 0.0, 0.0) pts.module_manager.scalar_lut_manager.title_text_property.color = (0.0, 0.0, 0.0) ## Isosurfaces surf_skip = 0 Xs, Ys, Zs = np.mgrid[surf_skip:l_size - surf_skip, surf_skip:l_size - surf_skip, 0:l_size] full_xspin3d = all_latt[H_ind, T_ind, surf_skip:l_size - surf_skip, surf_skip:l_size - surf_skip, 0:l_size, 0] full_yspin3d = all_latt[H_ind, T_ind, surf_skip:l_size - surf_skip,
# print np.array(d[1][1]) ,all(np.array(d[1][1])==0) # trace=[] # for j in range(0,len(d[1][1]),depth_num): # trace.append(data[i-1][1][1][j]-init_trace[j]) # temp_diff.append(trace) # time.append(mdates.date2num(d[0])) #ax = fig.gca(projection='3d') x,y=np.meshgrid(depth,time) a=mlab.surf(temp_diff,warp_scale='auto') mlab.scalarbar(a, title='scale', orientation=None, nb_labels=None, nb_colors=None, label_fmt=None) a.actor.actor.scale = (3.0, 1.0, 10.0) #ax.plot_surface(x,y, temp_diff, cmap=colormap, rstride=1, cstride=1, alpha=1,linewidth=0, antialiased=False) #cset = ax.contour(x,y, temp_diff, zdir='z', offset=-5, cmap=cm.coolwarm) #cset = ax.contour(x,y, temp_diff, zdir='x', offset=-100, cmap=cm.coolwarm) #cset = ax.contour(x,y, temp_diff, zdir='y', offset=time[-1]+1.0, cmap=cm.coolwarm) #date_format = mdates.DateFormatter('%Y-%m-%d %H:%M:%S') #ax.yaxis_date() #ax.yaxis.set_major_formatter(date_format) #ax.set_xlabel('Depth, m') #ax.set_zlabel('Temperature difference, degC') #ax.view_init(elev=60., azim=275) #plt.show()
con_nodes.append((i, j)) con_val.append(con[i, j]) con_val = np.array(con_val) # Show the connections as tubes between sensors vmax = np.max(con_val) vmin = np.min(con_val) for val, nodes in zip(con_val, con_nodes): x1, y1, z1 = sens_loc[nodes[0]] x2, y2, z2 = sens_loc[nodes[1]] points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val], vmin=vmin, vmax=vmax, tube_radius=0.001, colormap='RdBu') points.module_manager.scalar_lut_manager.reverse_lut = True mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4) # Add the sensor names for the connections shown nodes_shown = list(set([n[0] for n in con_nodes] + [n[1] for n in con_nodes])) for node in nodes_shown: x, y, z = sens_loc[node] mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005, color=(0, 0, 0)) view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2])) mlab.view(*view)
def add_morphometry(self, measure, grayscale=False): """Add a morphometry overlay to the image. Parameters ---------- measure : {'area' | 'curv' | 'jacobian_white' | 'sulc' | 'thickness'} which measure to load grayscale : bool whether to load the overlay with a grayscale colormap """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab # Find the source data surf_dir = pjoin(os.environ['SUBJECTS_DIR'], self.subject_id, 'surf') morph_file = pjoin(surf_dir, '.'.join([self.hemi, measure])) if not os.path.exists(morph_file): raise ValueError( 'Could not find %s in subject directory' % morph_file) # Preset colormaps cmap_dict = dict(area="pink", curv="RdBu", jacobian_white="pink", sulc="RdBu", thickness="pink") self._f.scene.disable_render = True # Maybe get rid of an old overlay if hasattr(self, "morphometry"): self.morphometry['surface'].remove() self.morphometry['colorbar'].visible = False # Save the inital view view = mlab.view() # Read in the morphometric data morph_data = io.read_morph_data(morph_file) # Get a cortex mask for robust range self._geo.load_label("cortex") ctx_idx = self._geo.labels["cortex"] # Get the display range if measure == "thickness": min, max = 1, 4 else: min, max = stats.describe(morph_data[ctx_idx])[1] # Set up the Mayavi pipeline if morph_data.dtype.byteorder == '>': morph_data.byteswap(True) # byte swap inplace; due to mayavi bug mesh = mlab.pipeline.triangular_mesh_source(self._geo.x, self._geo.y, self._geo.z, self._geo.faces, scalars=morph_data) if grayscale: colormap = "gray" else: colormap = cmap_dict[measure] surf = mlab.pipeline.surface(mesh, colormap=colormap, vmin=min, vmax=max, name=measure) # Get the colorbar bar = mlab.scalarbar(surf) bar.scalar_bar_representation.position2 = .8, 0.09 # Fil in the morphometry dict self.morphometry = dict(surface=surf, colorbar=bar, measure=measure) mlab.view(*view) self._f.scene.disable_render = False
def plot_morphology(morphology, plot_3d=None, show_compartments=False, show_diameter=False, colors=('darkblue', 'darkred'), values=None, value_norm=(None, None), value_colormap='hot', value_colorbar=True, value_unit=None, axes=None): ''' Plot a given `~brian2.spatialneuron.morphology.Morphology` in 2D or 3D. Parameters ---------- morphology : `~brian2.spatialneuron.morphology.Morphology` The morphology to plot plot_3d : bool, optional Whether to plot the morphology in 3D or in 2D. If not set (the default) a morphology where all z values are 0 is plotted in 2D, otherwise it is plot in 3D. show_compartments : bool, optional Whether to plot a dot at the center of each compartment. Defaults to ``False``. show_diameter : bool, optional Whether to plot the compartments with the diameter given in the morphology. Defaults to ``False``. colors : sequence of color specifications A list of colors that is cycled through for each new section. Can be any color specification that matplotlib understands (e.g. a string such as ``'darkblue'`` or a tuple such as `(0, 0.7, 0)`. values : ~brian2.units.fundamentalunits.Quantity, optional Values to fill compartment patches with a color that corresponds to their given value. value_norm : tuple or callable, optional Normalization function to scale the displayed values. Can be a tuple of a minimum and a maximum value (where either of them can be ``None`` to denote taking the minimum/maximum from the data) or a function that takes a value and returns the scaled value (e.g. as returned by `.matplotlib.colors.PowerNorm`). For a tuple of values, will use `.matplotlib.colors.Normalize```(vmin, vmax, clip=True)``` with the given ``(vmin, vmax)`` values. value_colormap : str or matplotlib.colors.Colormap, optional Desired colormap for plots. Either the name of a standard colormap or a `.matplotlib.colors.Colormap` instance. Defaults to ``'hot'``. Note that this uses ``matplotlib`` color maps even for 3D plots with Mayavi. value_colorbar : bool or dict, optional Whether to add a colorbar for the ``values``. Defaults to ``True``, but will be ignored if no ``values`` are provided. Can also be a dictionary with the keyword arguments for matplotlib's `~.matplotlib.figure.Figure.colorbar` method (2D plot), or for Mayavi's `~.mayavi.mlab.scalarbar` method (3D plot). value_unit : `Unit`, optional A `Unit` to rescale the values for display in the colorbar. Does not have any visible effect if no colorbar is used. If not specified, will try to determine the "best unit" to itself. axes : `~matplotlib.axes.Axes` or `~mayavi.core.api.Scene`, optional A matplotlib `~matplotlib.axes.Axes` (for 2D plots) or mayavi `~mayavi.core.api.Scene` ( for 3D plots) instance, where the plot will be added. Returns ------- axes : `~matplotlib.axes.Axes` or `~mayavi.core.api.Scene` The `~matplotlib.axes.Axes` or `~mayavi.core.api.Scene` instance that was used for plotting. This object allows to modify the plot further, e.g. by setting the plotted range, the axis labels, the plot title, etc. ''' # Avoid circular import issues from brian2tools.plotting.base import (_setup_axes_matplotlib, _setup_axes_mayavi) if plot_3d is None: # Decide whether to use 2d or 3d plotting based on the coordinates flat_morphology = FlatMorphology(morphology) plot_3d = any(np.abs(flat_morphology.z) > 1e-12) if values is not None: if hasattr(values, 'name'): value_varname = values.name else: value_varname = 'values' if value_unit is not None: if not isinstance(value_unit, Unit): raise TypeError(f'\'value_unit\' has to be a unit but is' f'\'{type(value_unit)}\'.') fail_for_dimension_mismatch(value_unit, values, 'The \'value_unit\' arguments needs ' 'to have the same dimensions as ' 'the \'values\'.') else: if have_same_dimensions(values, DIMENSIONLESS): value_unit = 1. else: value_unit = values[:].get_best_unit() orig_values = values values = values/value_unit if isinstance(value_norm, tuple): if not len(value_norm) == 2: raise TypeError('Need a (vmin, vmax) tuple for the value ' 'normalization, but got a tuple of length ' f'{len(value_norm)}.') vmin, vmax = value_norm if vmin is not None: err_msg = ('The minimum value in \'value_norm\' needs to ' 'have the same units as \'values\'.') fail_for_dimension_mismatch(vmin, orig_values, error_message=err_msg) vmin /= value_unit if vmax is not None: err_msg = ('The maximum value in \'value_norm\' needs to ' 'have the same units as \'values\'.') fail_for_dimension_mismatch(vmax, orig_values, error_message=err_msg) vmax /= value_unit if plot_3d: value_norm = (vmin, vmax) else: value_norm = Normalize(vmin=vmin, vmax=vmax, clip=True) value_norm.autoscale_None(values) elif plot_3d: raise TypeError('3d plots only support normalizations given by ' 'a (min, max) tuple.') value_colormap = plt.get_cmap(value_colormap) if plot_3d: try: import mayavi.mlab as mayavi except ImportError: raise ImportError('3D plotting needs the mayavi library') axes = _setup_axes_mayavi(axes) axes.scene.disable_render = True surf = _plot_morphology3D(morphology, axes, colors=colors, values=values, value_norm=value_norm, value_colormap=value_colormap, show_diameters=show_diameter, show_compartments=show_compartments) if values is not None and value_colorbar: if not isinstance(value_colorbar, Mapping): value_colorbar = {} if not have_same_dimensions(value_unit, DIMENSIONLESS): unit_str = f' ({value_unit!s})' else: unit_str = '' if value_varname: value_colorbar['title'] = f'{value_varname}{unit_str}' cb = mayavi.scalarbar(surf, **value_colorbar) # Make text dark gray cb.title_text_property.color = (0.1, 0.1, 0.1) cb.label_text_property.color = (0.1, 0.1, 0.1) axes.scene.disable_render = False else: axes = _setup_axes_matplotlib(axes) _plot_morphology2D(morphology, axes, colors, values, value_norm, value_colormap, show_compartments=show_compartments, show_diameter=show_diameter) axes.set_xlabel('x (um)') axes.set_ylabel('y (um)') axes.set_aspect('equal') if values is not None and value_colorbar: divider = make_axes_locatable(axes) cax = divider.append_axes("right", size="5%", pad=0.1) mappable = ScalarMappable(norm=value_norm, cmap=value_colormap) mappable.set_array([]) fig = axes.get_figure() if not isinstance(value_colorbar, Mapping): value_colorbar = {} if not have_same_dimensions(value_unit, DIMENSIONLESS): unit_str = f' ({value_unit!s})' else: unit_str = '' if value_varname: value_colorbar['label'] = f'{value_varname}{unit_str}' fig.colorbar(mappable, cax=cax, **value_colorbar) return axes
def geoVortex(L2, PosF, VelF): """ function that takes the L2 field, seeds it, and calculates an aproximate circulation ---Inputs--- L2 - the lambda2 array L2Vec - the lambda2 eigenvector array PosF - Position field ---Output--- --- C.Losada de la Lastra 2015 """ from lambda2 import L2min, cropL2min from seeding import seed_time from circulationVortex import circulationPoint, circulationFieldUpdate, hasPointCirculation X, Y, Z = PosF fig1 = mlab.figure(1, size=(1000, 500), fgcolor=(1, 1, 1),\ bgcolor=(0.5, 0.5, 0.5)) #Lambda2Surf = mlab.contour3d(Z,Y,X,L2,figure=fig1,contours=3,transparent=True) # Lambda2Legend = mlab.scalarbar(object=Lambda2Surf, title='Lambda_2',\ # orientation='vertical', nb_labels=None, nb_colors=None, label_fmt=None) print('displayed L2 isosurface') ##---1---## L2 min points #L2min(PosF,L2) dataL2min = L2min(PosF, L2) ##---2---## Crop L2min points #cropL2min(dataL2min,PosF,method='negData') #L2minData_crop = cropL2min(dataL2min,PosF,method='auto') L2minData_crop = cropL2min(dataL2min, PosF, method='negData') print('obtained and croped L2min data') seedsL2min_l2 = L2minData_crop[0] seedsL2min_p = L2minData_crop[1] seedsL2min_ijk = L2minData_crop[2] ##---3---## Eval in time L2min seeds seedsL2min_paths_time = [] seedsL2min_vels_time = [] seedsL2min_circ = [] seedsL2min_swirlVects = [] for i in range(len(seedsL2min_p)): p0 = seedsL2min_p[i] ijk = seedsL2min_ijk[i] t = 4 seed_pi2 = 0 while seed_pi2 == 0: #seed_time(p0,ijk,PosF,VelF,t) path_s, vel_s = seed_time(p0, ijk, PosF, VelF, t) #findProbeAng(path) #crit2pi(thetas) pi2 = crit2pi(findProbeAng(path_s)) if pi2 == True: seed_pi2 = 1 seedsL2min_paths_time.append(path_s) seedsL2min_vels_time.append(vel_s) #circulationPoint(vel_seed_time) seedsL2min_circ.append(circulationPoint(vel_s)) #averageNormal(path) seedsL2min_swirlVects.append(averageNormal(path_s)) #plot in MAYAVI mlab.plot3d(path_s[2], path_s[1], path_s[0], figure=fig1) else: t += 1 ##--4--## Circulation of seedsL2min into circulation field CircF0 = N.zeros_like(X, dtype=float) #circulationFieldUpdate(pnts,pnts_ijk,pnts_circ,pnts_vect_swirl,CircF,PosF,L2) pnts = seedsL2min_p pnts_ijk = seedsL2min_ijk pnts_circ = seedsL2min_circ pnts_vect_swirl = seedsL2min_swirlVects CircF = circulationFieldUpdate(pnts, pnts_ijk, pnts_circ, pnts_vect_swirl, CircF0, PosF, L2) # Vmin = CircField = mlab.contour3d(Z, Y, X, CircF, contours=11, vmin=min(CircF.flatten()), vmax=-min(CircF.flatten())) CircFieldLegend = mlab.scalarbar(object=CircField, title='Circulation',\ orientation='vertical', nb_labels=5, nb_colors=None, label_fmt=None) return CircF
u=numpy.zeros((N,N), dtype=float) v=numpy.zeros((N,N), dtype=float) u_y=numpy.zeros((N,N), dtype=float) v_x=numpy.zeros((N,N), dtype=float) omega=numpy.zeros((N,N), dtype=float) # Initial conditions for i in range(len(x)): for j in range(len(y)): u[i][j]=numpy.sin(2*math.pi*x[i])*numpy.cos(2*math.pi*y[j]) v[i][j]=-numpy.cos(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) u_y[i][j]=-2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) v_x[i][j]=2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j]) omega[i][j]=v_x[i][j]-u_y[i][j] src = mlab.imshow(xx,yy,omega,colormap='jet') mlab.scalarbar(object=src) mlab.xlabel('x',object=src) mlab.ylabel('y',object=src) # Wavenumber k_x = 2*math.pi*numpy.array([complex(0,1)*n for n in range(0,N/2) \ + [0] + range(-N/2+1,0)]) k_y=k_x kx=numpy.zeros((N,N), dtype=complex) ky=numpy.zeros((N,N), dtype=complex) kxx=numpy.zeros((N,N), dtype=complex) kyy=numpy.zeros((N,N), dtype=complex) for i in xrange(N):
pot=numpy.zeros((Nx,Ny), dtype=float) u=numpy.zeros((Nx,Ny), dtype=complex) una=numpy.zeros((Nx,Ny), dtype=complex) unb=numpy.zeros((Nx,Ny), dtype=complex) v=numpy.zeros((Nx,Ny), dtype=complex) vna=numpy.zeros((Nx,Ny), dtype=complex) vnb=numpy.zeros((Nx,Ny), dtype=complex) mass=numpy.zeros((Nx,Ny), dtype=complex) test=numpy.zeros((numplots-1),dtype=float) tdata=numpy.zeros((numplots-1), dtype=float) u=numpy.exp(-(xx**2 + yy**2 )) v=numpy.fft.fftn(u) usquared=abs(u)**2 src = mlab.surf(xx,yy,usquared,colormap='YlGnBu',warp_scale='auto') mlab.scalarbar() mlab.xlabel('x',object=src) mlab.ylabel('y',object=src) mlab.zlabel('abs(u)^2',object=src) # initial mass usquared=abs(u)**2 mass=numpy.fft.fftn(usquared) ma=numpy.real(mass[0,0]) print(ma) maO=ma t=0.0 tdata[0]=t plotnum=0 #solve pde and plot results for nt in xrange(numplots-1):
else: trace=[] for x,t in enumerate(d[1][1]): trace.append(t-temp_init[x]) time.append(mdates.date2num(d[0])-init_time) temp.append(trace) print np.array(temp).shape,np.array(time).shape,np.array(depth).shape x,y=np.meshgrid(time,depth) print x.shape,y.shape fig = mlab.figure(size=(1000,800)) myplot=mlab.surf(x.T,y.T,np.flipud(temp),extent = [0,1,0,1,0,0.3]) cb=mlab.scalarbar(myplot, title='Temperature', orientation='vertical', nb_labels=None, nb_colors=None, label_fmt='%.1f') ax=mlab.axes(xlabel='time,days',ylabel='depth,mMD',nb_labels=5,x_axis_visibility=True,y_axis_visibility=False,z_axis_visibility=True,\ ranges = [np.amax(np.array(time)),np.amin(np.array(time)),np.amin(np.array(depth)), np.amax(np.array(depth)),np.amin(np.array(temp)), np.amax(np.array(temp))]) ax.axes.label_format = '%.1f' ax.axes.font_factor=0.7 mlab.show()
X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] plot_col = n_tex_max_max[:, 0] # if n_tex is negative plot 0 instead: # plot_col = where(plot_col < 0, 0, plot_col) mlab.figure(figure="SFB532Demo", bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, (-1.0) * Z, plot_col, colormap="YlOrBr", mode="cube", scale_factor=0.10) mlab.scalarbar(title='n_tex (all LCs)', orientation='vertical') mlab.show() # print 'lc_arr', lct.lc_arr # print 'lc_list[0].sr_arr.shape[0]', lct.lc_list[0].sr_arr.shape[0] # print 'lc_arr.shape', lct.lc_arr.shape # print 'combi_arr', lct.combi_arr # print 'combi_arr.shape', lct.combi_arr.shape # print 'lcc_arr', lct.lcc_arr
def __init__(self, subject_id, hemi, surf, curv=True, title=None, config_opts={}): """Initialize a Brain object with Freesurfer-specific data. Parameters ---------- subject_id : str subject name in Freesurfer subjects dir hemi : str hemisphere id (ie 'lh' or 'rh') surf : geometry name freesurfer surface mesh name (ie 'white', 'inflated', etc.) curv : boolean if true, loads curv file and displays binary curvature (default: True) title : str title for the mayavi figure config_opts : dict options to override visual options in config file """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab # Set the identifying info self.subject_id = subject_id self.hemi = hemi if self.hemi == 'lh': self.viewdict = lh_viewdict elif self.hemi == 'rh': self.viewdict = rh_viewdict self.surf = surf # Initialize an mlab figure bg_color_code, size = self.__get_scene_properties(config_opts) if title is None: title = subject_id self._f = mlab.figure(title, bgcolor=bg_color_code, size=size) mlab.clf() self._f.scene.disable_render = True # Initialize a Surface object as the geometry self._geo = Surface(subject_id, hemi, surf) # Load in the geometry and (maybe) curvature self._geo.load_geometry() if curv: self._geo.load_curvature() curv_data = self._geo.bin_curv meshargs = dict(scalars=curv_data) else: curv_data = None meshargs = dict() # mlab pipeline mesh for geomtery self._geo_mesh = mlab.pipeline.triangular_mesh_source( self._geo.x, self._geo.y, self._geo.z, self._geo.faces, **meshargs) # mlab surface for the geometry if curv: colormap, vmin, vmax, reverse = self.__get_geo_colors(config_opts) self._geo_surf = mlab.pipeline.surface(self._geo_mesh, colormap=colormap, vmin=vmin, vmax=vmax) if reverse: curv_bar = mlab.scalarbar(self._geo_surf) curv_bar.reverse_lut = True curv_bar.visible = False else: self._geo_surf = mlab.pipeline.surface(self._geo_mesh, color=(.5, .5, .5)) # Initialize the overlay and label dictionaries self.overlays = dict() self.labels = dict() self.foci = dict() # Bring up the lateral view self.show_view(config.get("visual", "default_view")) # Turn disable render off so that it displays self._f.scene.disable_render = False
def plot_assess_value(self, title=None, add_assess_values_from_file=None, save_assess_values_to_file=None): '''plot the assess value for all loading case combinations ''' #---------------------------------------- # script to get the maximum values of 'assess_value' # at all given coordinate points for all possible loading # case combinations: #---------------------------------------- # get the list of all loading case combinations: # lcc_list = self.lcc_list #---------------------------------------------- # run trough all loading case combinations: #---------------------------------------------- assess_value_list = [] for lcc in lcc_list: # get the ls_table object and retrieve its 'ls_class' # (= LSTable_ULS-object) # ls_class = lcc.ls_table.ls_class # get 'assess_name'-column array # assess_name = ls_class.assess_name if assess_name == 'max_eta_nm_tot': assess_value = getattr(ls_class, 'eta_nm_tot') if assess_name == 'max_n_tex': assess_value = getattr(ls_class, 'n_tex') if assess_name == 'max_eta_tot': assess_value = getattr(ls_class, 'eta_tot') # n_tex = ls_class.n_tex_up # n_tex = ls_class.n_tex_lo assess_value_list.append(assess_value) # stack the list to an array in order to use ndmax-function # assess_value_arr = hstack(assess_value_list) print 'assess_value_arr.shape', assess_value_arr.shape #---------------------------------------------- # get the overall maximum values: #---------------------------------------------- assess_value_max = ndmax(assess_value_arr, axis=1)[:, None] #---------------------------------------------- # plot #---------------------------------------------- # X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] if self.reader_type == 'RFEM': Z *= -1.0 plot_col = assess_value_max[:, 0] # save assess values to file in order to superpose them later # if save_assess_values_to_file != None: print 'assess_values saved to file %s' % ( save_assess_values_to_file) assess_value_arr = plot_col np.savetxt(save_assess_values_to_file, assess_value_arr) # add read in saved assess values to be superposed with currently read in assess values # if add_assess_values_from_file != None: print 'superpose assess_value_arr with values read in from file %s' % ( add_assess_values_from_file) assess_value_arr = np.loadtxt(add_assess_values_from_file) plot_col += assess_value_arr # # if n_tex is negative plot 0 instead: # # # plot_col = where(plot_col < 0, 0, plot_col) mlab.figure(figure=title, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, Z, plot_col, colormap="YlOrBr", mode="cube", scale_mode='none', scale_factor=0.10) mlab.scalarbar(title=assess_name + ' (all LCs)', orientation='vertical') mlab.show()
def add_contour_overlay(self, filepath, min=None, max=None, n_contours=7, line_width=1.5): """Add a topographic contour overlay. Note: This visualization will look best when using the "low_contrast" cortical curvature colorscheme. Parameters ---------- filepath : str path to the overlay file (must be readable by Nibabel, or .mgh) min : float threshold for overlay display max : float saturation point for overlay display n_contours : int number of contours to use in the display line_width : float width of contour lines """ try: from mayavi import mlab except ImportError: from enthought.mayavi import mlab # Read the scalar data scalar_data = io.read_scalar_data(filepath) #TODO find a better place for this; duplicates code in Overlay object if min is None: try: min = config.getfloat("overlay", "min_thresh") except ValueError: min_str = config.get("overlay", "min_thresh") if min_str == "robust_min": min = stats.scoreatpercentile(scalar_data, 2) elif min_str == "actual_min": min = scalar_data.min() else: min = 2.0 warn("The 'min_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is %s. " "I'm setting the overlay min to the config default of 2" % min) if max is None: try: max = config.getfloat("overlay", "max_thresh") except ValueError: max_str = config.get("overlay", "max_thresh") if max_str == "robust_max": max = stats.scoreatpercentile(scalar_data, 98) elif max_str == "actual_max": max = scalar_data.max() else: max = stats.scoreatpercentile(scalar_data, 98) warn("The 'max_thresh' value in your config value must be " "a float, 'robust_min', or 'actual_min', but it is %s. " "I'm setting the overlay min to the config default " "of robust_max" % max) # Prep the viz self._f.scene.disable_render = True view = mlab.view() # Maybe get rid of an old overlay if hasattr(self, "contour"): self.contour['surface'].remove() self.contour['colorbar'].visible = False # Deal with Mayavi bug if scalar_data.dtype.byteorder == '>': scalar_data.byteswap(True) # Set up the pipeline mesh = mlab.pipeline.triangular_mesh_source(self._geo.x, self._geo.y, self._geo.z, self._geo.faces, scalars=scalar_data) thresh = mlab.pipeline.threshold(mesh, low=min) surf = mlab.pipeline.contour_surface(thresh, contours=n_contours, line_width=line_width) # Set the colorbar and range correctly bar = mlab.scalarbar(surf) bar.data_range = min, max bar.scalar_bar_representation.position2 = .8, 0.09 # Set up a dict attribute with pointers at important things self.contour = dict(surface=surf, colorbar=bar) # Show the new overlay mlab.view(*view) self._f.scene.disable_render = False
def update_scene(self): Mayavi_Scene.fig1 = mlab.figure(1, bgcolor=(.5, .5, .5)) self.scene.mlab.clf(figure=Mayavi_Scene.fig1) pyDir = os.path.dirname( os.path.realpath(__file__)) #python file location starDir = os.path.join(pyDir, 'STARs') starPaths = [] i = 0 for root, dirs, files in os.walk(starDir): for file in sorted(files): if not file.startswith('.'): #ignore hidden files if file.endswith(".star"): starPaths.append(os.path.join(root, file)) i += 1 starRot = [] #phi-values starTilt = [] #theta-values for z in starPaths: starFile = [] with open(z, 'r') as values: for i in range(0, 19): #skip header next(values) starReader = csv.reader(values, delimiter='\t') for lines in starReader: starFile.append(lines) values.close() # grab list of rot and tilt from each star file independently: for i in range(np.shape(starFile)[0]): starRot.append(starFile[i][0]) starTilt.append(starFile[i][1]) def sphere2cart(theta, phi): r = 100 x = r * np.sin(phi) * np.cos(theta) y = r * np.sin(phi) * np.sin(theta) z = r * np.cos(phi) return x, y, z starRotTilt = np.column_stack((starRot, starTilt)) if 0: #sanity-check print(starRotTilt[0]) print(starRotTilt[-1]) index = [] cartX = [] cartY = [] cartZ = [] idx = 1 for i in starRotTilt: x, y, z = sphere2cart( float(i[0]) * np.pi / 180, float(i[1]) * np.pi / 180) index.append(idx) cartX.append(x) cartY.append(y) cartZ.append(z) idx += 1 # save angles to file (e.g., for rendering figures in external programs): if 1: if os.path.exists('cartXYZ.txt'): os.remove('cartXYZ.txt') cartXYZ = np.column_stack((index, cartX, cartY, cartZ)) np.savetxt('cartXYZ.txt', cartXYZ, delimiter='\t', fmt='%1.6i %1.3f %1.3f %1.3f') # calculate S2-surface densities: if 0: print('Calculating densities...') values = np.array([cartX, cartY, cartZ]) kde = stats.gaussian_kde(values) cartD = kde(values) #density cartD /= cartD.max() #relative density, max=1 mayavi_plot = mlab.points3d(cartX, cartY, cartZ, cartD, scale_mode='none', mode='axes', scale_factor=.5, figure=Mayavi_Scene.fig1) mayavi_cbar = mlab.scalarbar(title='Relative\nDensity\n', orientation='vertical', \ nb_labels=3, label_fmt='%.1f') else: mayavi_plot = mlab.points3d(cartX, cartY, cartZ, scale_mode='none', mode='axes', scale_factor=.5, figure=Mayavi_Scene.fig1) mayavi_plot.actor.property.color = (0.0, 1.0, 1.0)
pot = numpy.zeros((Nx, Ny), dtype=float) u = numpy.zeros((Nx, Ny), dtype=complex) una = numpy.zeros((Nx, Ny), dtype=complex) unb = numpy.zeros((Nx, Ny), dtype=complex) v = numpy.zeros((Nx, Ny), dtype=complex) vna = numpy.zeros((Nx, Ny), dtype=complex) vnb = numpy.zeros((Nx, Ny), dtype=complex) mass = numpy.zeros((Nx, Ny), dtype=complex) test = numpy.zeros((numplots - 1), dtype=float) tdata = numpy.zeros((numplots - 1), dtype=float) u = numpy.exp(-(xx**2 + yy**2)) v = numpy.fft.fftn(u) usquared = abs(u)**2 src = mlab.surf(xx, yy, usquared, colormap='YlGnBu', warp_scale='auto') mlab.scalarbar() mlab.xlabel('x', object=src) mlab.ylabel('y', object=src) mlab.zlabel('abs(u)^2', object=src) # initial mass usquared = abs(u)**2 mass = numpy.fft.fftn(usquared) ma = numpy.real(mass[0, 0]) print(ma) maO = ma t = 0.0 tdata[0] = t plotnum = 0 #solve pde and plot results for nt in xrange(numplots - 1):
def show_triangular_mesh(x, y, z, triangles, scalars, vmin=None, vmax=None, colormap='jet', lut=None, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 350), azimuth=-48, elevation=142, distance=422, focalpoint=(33, -17, 16), roll=-84, cbar_orientation=None, cbar_position=None, cbar_position2=None, cbar_label_fmt=None, cbar_num=0, mode='show', **kwargs): """ Parameters: ---------- x[ndarray]: 1-D array with shape as (n_vtx) y[ndarray]: 1-D array with shape as (n_vtx) z[ndarray]: 1-D array with shape as (n_vtx) triangles[seq]: a list of triplets (or an array) list the vertices in each triangle scalars[ndarray]: 1-D or 2-D array if 1-D array, its shape is (n_vtx,). if 2-D array, its shape is (N, n_vtx), where N is the number of overlays. Overlays with larger row numbers will cover on the overlays with smaller row numbers. Vertices with the smallest scalar will be set transparent except for the bottom overlay. vmin[float|list]: the minimal scalar to display If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. vmax[float|list]: the maximal scalar to display If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. colormap[str|list]: the color map method If is list, one-by-one corresponding to the rows of scalars. Else, applied to all overlays. lut[ndarray|list]: lookup table of color with shape as (n_color, 4) If is not None, ignore 'colormap' bgcolor[seq]: the rgb color of background. fgcolor[seq]: the rgb color of foreground. size[seq]: size of figure (width x height) azimuth[float]: elevation[float]: distance[float]: focalpoint[seq]: roll[float]: cbar_orientation[str]: the orientation of colorbar cbar_position[seq]: position of bottom-left corner cbar_position2[seq]: distance from the bottom-left corner cbar_label_fmt[str]: string format of labels of the colorbar cbar_num[int]: show colorbar of the cbar_num overlay If is 0, no colorbar will be displayed. If is 1, show the first overlay's colorbar, i.e. the bottom overlay. mode[str]: show or return If is 'show', just show the figure. If is 'return', return screen shot and close the figure. Else, regard as the output path of the figure. kwargs: reference to doc of mlab.triangular_mesh Return: ------ img[ndarray]: """ # transform x, y, z x = np.asarray(x) y = np.asarray(y) z = np.asarray(z) assert x.ndim == 1 and y.ndim == 1 and z.ndim == 1 assert x.shape == y.shape and y.shape == z.shape # transform scalars if scalars.ndim == 1: scalars = scalars[None, :] elif scalars.ndim != 2: raise ValueError('Unsupported dimension number of scalars:', scalars.ndim) assert scalars.shape[1] == x.shape[0] n_overlay = scalars.shape[0] # transform vmin if not isinstance(vmin, list): vmin = [vmin] * n_overlay else: assert len(vmin) == n_overlay # transform vmax if not isinstance(vmax, list): vmax = [vmax] * n_overlay else: assert len(vmax) == n_overlay # transform colormap if not isinstance(colormap, list): colormap = [colormap] * n_overlay else: assert len(colormap) == n_overlay # transform LUT if not isinstance(lut, list): lut = [lut] * n_overlay else: assert len(lut) == n_overlay fig = mlab.figure(bgcolor=bgcolor, fgcolor=fgcolor, size=size) for idx, data in enumerate(zip(scalars, vmin, vmax, colormap, lut), 1): s, vi, va, cm, lut_i = data if vi is None: vi = np.min(s) if va is None: va = np.max(s) surf = mlab.triangular_mesh(x, y, z, triangles, scalars=s, figure=fig, vmin=vi, vmax=va, colormap=cm, **kwargs) # fix the color of the smallest scalar if lut_i is None: lut_i = np.array(surf.module_manager.scalar_lut_manager.lut.table) if idx == 1: lut_i[0, :3] = 127.5 else: lut_i[0, 3] = 0 surf.module_manager.scalar_lut_manager.lut.table = lut_i if idx == cbar_num: # create color bar cbar = mlab.scalarbar(surf, orientation=cbar_orientation, label_fmt=cbar_label_fmt, nb_labels=5) cbar.scalar_bar_representation.position = cbar_position cbar.scalar_bar_representation.position2 = cbar_position2 # adjust camera mlab.view(azimuth, elevation, distance, focalpoint, figure=fig) mlab.roll(roll, figure=fig) if mode == 'return': # may have some bugs img = mlab.screenshot(fig) mlab.close(fig) return img elif mode == 'show': mlab.show() else: # regard as output filename mlab.savefig(mode, figure=fig) mlab.close(fig)
def make_3d_plot(ds, figname, fields = ['thermal_pressure','plasma_beta', 'mag_field_x','mag_field_y','mag_field_z'], figxy = [500,550], view = (-45., 90., 20., np.array([0,0,3.75])), seeds = np.array([[0,0,1]]), offscreen = False ): """Make a 3D rendition of the atmosphere including volume filling, iso surfaces and field lines. ds: gdf data set figname: string with path of file to save image fields: list of strings indicating the fields to be plotted first volume filling, second iso surfaces, third:fifth vector field """ from mayavi import mlab from pysac.plot.mayavi_seed_streamlines import SeedStreamline # # extract field labels for plot variables # vector_field = 'magnetic field' # if 'velocity' in fields[-1]: # vector_field = 'velocity field' # if 'current' in fields[-1]: # vector_field = 'electric current' # if 'vort' in fields[-1]: # vector_field = 'vorticity' # mlab.options.offscreen = True if offscreen: #mlab.engine.current_scene.scene.off_screen_rendering = True mlab.options.offscreen = True scene = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5),size=figxy) x,y,z = np.mgrid[ ds.domain_left_edge[0].in_units('Mm'): ds.domain_right_edge[0].in_units('Mm'): 1j*ds.domain_dimensions[0], ds.domain_left_edge[1].in_units('Mm'): ds.domain_right_edge[1].in_units('Mm'): 1j*ds.domain_dimensions[1], ds.domain_left_edge[2].in_units('Mm'): ds.domain_right_edge[2].in_units('Mm'): 1j*ds.domain_dimensions[2] ] fill = np.array(ds.index.grids[0][fields[0]]) surf = np.array(ds.index.grids[0][fields[1]]) vec1 = np.array(ds.index.grids[0][fields[2]]) vec2 = np.array(ds.index.grids[0][fields[3]]) vec3 = np.array(ds.index.grids[0][fields[4]]) volfill = mlab.pipeline.scalar_field(x,y,z, fill, name=fields[0]) isosurf = mlab.pipeline.scalar_field(x,y,z, surf, name=fields[1]) # # Set up projection outline to 2D analogue plot # o1 = mlab.outline() # o1.manual_bounds = True # o1.bounds = [x.min(),x.max(),y.min(),y.max(),z.min(),z.max()] # o1.actor.property.line_width = 3 # o1.actor.property.color = (0.5,0.5,0.5) # o1.actor.property.line_stipple_pattern = 0x0FF00 # Generate isosurfaces iso = mlab.pipeline.iso_surface(isosurf) iso.contour.auto_contours = False iso.module_manager.scalar_lut_manager.lut_mode = 'PiYG' iso.module_manager.scalar_lut_manager.lut.scale = 'log10' iso.module_manager.scalar_lut_manager.reverse_lut = True iso.contour.contours = [1e-2,1e-1,1,100,10000] iso.module_manager.scalar_lut_manager.data_range = [1e-3,1e3] iso.actor.property.opacity = 0.4 # Plot the flow of trajectories with suitable parameters. # vfield = mlab.flow(x, y, z, vec1, vec2, vec3, # line_width=1, colormap='winter', seed_scale=2., # #seedtype='plane', # seed_visible=False, opacity=0.9) vecfield = mlab.pipeline.vector_field(x, y, z, vec1, vec2, vec3, name=fields[-1][:-3]) vecmag = mlab.pipeline.extract_vector_norm(vecfield, name="Field line Normals") field_lines = SeedStreamline(seed_points = np.array(seeds)) vecmag.add_child(field_lines) # vfield.seed.widget.enabled = False field_lines.module_manager.scalar_lut_manager.lut_mode = 'winter' field_lines.module_manager.scalar_lut_manager.reverse_lut = False field_lines.module_manager.scalar_lut_manager.lut.scale = 'log10' field_lines.stream_tracer.integration_direction = 'both' # field_lines.stream_tracer.maximum_propagation = 150 # field_lines.streamline_type = 'tube' ## field_lines.ribbon_filter.vary_width = True ## field_lines.ribbon_filter.width_factor = 0.01 # field_lines.tube_filter.radius_factor = 0.1 # field_lines.tube_filter.vary_radius = True # field_lines.tube_filter.number_of_sides = 3 ## field_lines.streamline_type = 'tube' # generate rear and lower background surfaces cut = mlab.pipeline.scalar_cut_plane(volfill) cut.implicit_plane.normal = [1,0,0] cut.implicit_plane.origin = [x.min()*0.999,0,0] cut.actor.property.lighting = False cut.implicit_plane.widget.enabled = False cut.actor.property.opacity = 1.0 cut2 = mlab.pipeline.scalar_cut_plane(volfill) cut2.implicit_plane.origin = [0,y.max()*0.999,0] cut2.implicit_plane.normal = [0,1,0] cut2.actor.property.lighting = False cut2.implicit_plane.widget.enabled = False cut2.actor.property.opacity = 1.0 cut3 = mlab.pipeline.scalar_cut_plane(volfill) cut3.implicit_plane.origin = [0,0,z.min()+.0001] cut3.implicit_plane.normal = [0,0,1] cut3.parent.scalar_lut_manager.lut_mode = 'YlOrBr' cut3.actor.property.lighting = False cut3.parent.scalar_lut_manager.lut.scale = 'log10' cut3.implicit_plane.widget.enabled = False cut3.parent.scalar_lut_manager.reverse_lut=False cut3.actor.property.opacity = 1.0 #Draw the axes and axis labels o = mlab.outline() o.manual_bounds = True o.bounds = [x.min(),x.max(),y.min(),y.max(),z.min(),z.max()] o.actor.property.line_width = 3 o.actor.property.color = (0.5,0.5,0.5) o.actor.property.line_stipple_pattern = 0x0FF00 mlab.axes(x_axis_visibility=True, y_axis_visibility=True, z_axis_visibility=False, zlabel=" Height\n [Mm] ", xlabel="Width\n [Mm]", ylabel="Width\n [Mm]", nb_labels=3, extent=[x.min(),x.max(),y.min(),y.max(),z.min(),z.max()]) #Define the camera projection for the 3D image mlab.view(view[0],view[1],view[2],view[3]) # mlab.view(-45.0, 90.0, 20.0, # np.array([0, 0, 3.7500000e+00])) #Add colorbars to left (volume fill) and right (isosurfaces) unit_str0 = str(ds.index.grids[0][fields[0]].units) if str(ds.index.grids[0][fields[0]].units) == 'dimensionless': unit_str0 = '' label0 = str.replace(fields[0]+'_'+unit_str0, '_','\n') # label0 = str.replace(fields[0], '_','\n') cbar0=mlab.scalarbar(object=cut, title=label0, orientation='vertical', nb_labels=None, nb_colors=None, label_fmt=None) cbar0.scalar_bar_representation.position = [0.80, 0.15] cbar0.scalar_bar_representation.position2 = [0.10, 0.80] unit_str1 = str(ds.index.grids[0][fields[1]].units) if str(ds.index.grids[0][fields[1]].units) == 'dimensionless': unit_str1 = '' label1 = str.replace(fields[1]+'_'+unit_str1, '_','\n') # label1 = str.replace(fields[1], '_','\n') cbar1 = mlab.scalarbar(object=iso, title=label1, orientation='vertical', nb_labels=None, nb_colors=None, label_fmt=None) cbar1.scalar_bar_representation.position = [0.05, 0.15] cbar1.scalar_bar_representation.position2 = [0.10, 0.80] mlab.savefig(figname) mlab.close()
def plot_assess_value(self, assess_name, scale_factor=0.1, scale_mode='none', azimuth=None, elevation=None, distance=None, focalpoint=None, title=None, save_fig_to_file=None, add_assess_values_from_file=None, save_assess_values_to_file=None): '''plot-3d the assess value for all loading case combinations as structure plot with color legend options: - plot options for mlab - save figure with specified name within "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png" - superpose data values, i.e. from imposed loads and temperature loads ''' print '################### plotting assess_value ##################' #---------------------------------------- # script to get the maximum values of 'assess_value' # at all given coordinate points for all possible loading # case combinations: #---------------------------------------- # get the list of all loading case combinations: # lcc_list = self.lcc_list #---------------------------------------------- # run trough all loading case combinations: #---------------------------------------------- assess_value_list = [] for lcc in lcc_list: # get the ls_table object and retrieve its 'ls_class' # (= LSTable_ULS-object) # ls_class = lcc.ls_table.ls_class # get 'assess_name'-column array assess_value = getattr(ls_class, assess_name) assess_value_list.append(assess_value) # stack the list to an array in order to use ndmax-function # assess_value_arr = np.hstack(assess_value_list) print 'assess_value_arr.shape', assess_value_arr.shape #---------------------------------------------- # get the overall maximum values: #---------------------------------------------- assess_value_max = np.max(assess_value_arr, axis=1)[:, None] #---------------------------------------------- # plot #---------------------------------------------- # X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] plot_col = assess_value_max[:, 0] # save assess values to file in order to superpose them later # if save_assess_values_to_file != None: simdata_dir = os.path.join(simdb.simdata_dir, 'lcc_table') # check if directory exist otherwise create # if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) filename = os.path.join(simdata_dir, save_assess_values_to_file) assess_value_arr = plot_col np.savetxt(filename, assess_value_arr) print 'assess_values saved to file %s' % (filename) # add read in saved assess values to be superposed with currently read in assess values # if add_assess_values_from_file != None: simdata_dir = os.path.join(simdb.simdata_dir, 'lcc_table') # check if directory exist otherwise create # if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) filename = os.path.join(simdata_dir, add_assess_values_from_file) assess_value_arr = np.loadtxt(filename) plot_col += assess_value_arr print 'superpose assess_value_arr with values read in from file %s' % (filename) # # if n_tex is negative plot 0 instead: # # # plot_col = where(plot_col < 0, 0, plot_col) mlab.figure(figure=title, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, Z, plot_col, colormap="YlOrBr", mode="cube", scale_mode=scale_mode, scale_factor=scale_factor) mlab.scalarbar(title=assess_name + ' (all LCs)', orientation='vertical') mlab.view(azimuth=azimuth, elevation=elevation, distance=distance, focalpoint=focalpoint) if save_fig_to_file != None: simdata_dir = os.path.join(simdb.simdata_dir, 'lcc_table') # check if directory exist otherwise create # if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) img_dir = os.path.join(simdata_dir, 'output_images') # check if directory exist otherwise create # if os.path.isdir(img_dir) == False: os.makedirs(img_dir) filename = os.path.join(img_dir, save_fig_to_file + '.png') mlab.savefig(filename) # , format='png') print 'figure saved to file %s' % (filename) mlab.show()
def plot_n_tex(self, title=None): '''plot number of textile reinforcement 'n_tex' for all loading case combinations ''' #---------------------------------------- # script to get the maximum number of reinforcement ('n_tex') # at all given coordinate points for all possible loading # case combinations: #---------------------------------------- # set option to "True" for surrounding # evaluation of necessary layers "n_tex" # needed for all loading cases # get the list of all loading case combinations: # lcc_list = self.lcc_list #---------------------------------------------- # run trough all loading case combinations: #---------------------------------------------- n_tex_list = [] for lcc in lcc_list: # get the ls_table object and retrieve its 'ls_class' # (= LSTable_ULS-object) # ls_class = lcc.ls_table.ls_class # get 'n_tex'-column array # n_tex = ls_class.n_tex # n_tex = ls_class.n_tex_up # n_tex = ls_class.n_tex_lo n_tex_list.append(n_tex) # stack the list to an array in order to use ndmax-function # n_tex_arr = hstack(n_tex_list) #---------------------------------------------- # get the overall maximum values: #---------------------------------------------- n_tex_max = ndmax(n_tex_arr, axis=1)[:, None] #---------------------------------------------- # plot #---------------------------------------------- # X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] plot_col = n_tex_max[:, 0] # if n_tex is negative plot 0 instead: # plot_col = where(plot_col < 0, 0, plot_col) mlab.figure(figure=title, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, (-1.0) * Z, plot_col, colormap="YlOrBr", mode="cube", scale_mode='none', scale_factor=0.10) mlab.scalarbar(title='n_tex (all LCs)', orientation='vertical') mlab.show()
def slicing(data, xlabel = '', ylabel = '', zlabel = '', title = ''): ''' Description This function generates a Mayavi scene that shows cut planes along the x, y and z axes of a data cube. This is an interactive scene, and so the cut planes can be moved through the cube, and the entire cube can be rotated. Required Input data: A three dimensional numpy array. Each entry of the array must contain a scalar value. xlabel: A string specifying a label for the x axis of the data cube. ylabel: A string specifying a label for the y axis of the data cube. zlabel: A string specifying a label for the z axis of the data cube. title: A string specifying the title for the visualisation. Output This function returns 1 if it runs to completion. An interactive Mayavi scene is produced by the function, allowing slices through a three dimensional data cube to be viewed. ''' # Create a new Mayavi scene to visualise slicing the data cube scene = mlab.figure(size = (800,700)) # Run a widget that allows you to visualise three dimensional data sets # This creates a slice along the x axis that can be interactively varied mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data),\ plane_orientation='x_axes', slice_index=0) # This creates a slice along the y axis that can be interactively varied, # on the same image as the x axis slice mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data),\ plane_orientation='y_axes', slice_index=0) # This creates a slice along the z axis that can be interactively varied, # on the same image as the x and y axis slices mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data), plane_orientation='z_axes', slice_index=0) # Add axes to the visualisation of the image cube, and label the x, y and # z axes mlab.axes(xlabel = xlabel, ylabel = ylabel, zlabel = zlabel) # Add a title to the visualisation of the image cube mlab.title(title, height = 1.0) # Make the outline of the image cube appear mlab.outline() # Make a colourbar for the data mlab.scalarbar(orientation = 'vertical') # Add a little symbol to show the orientation of the data mlab.orientation_axes() # Allow interaction with the produced visualisation mlab.show() # Once the interactive 3D view has been created, return 0 return 1
def plot_n_tex(self, title=None): '''plot number of textile reinforcement 'n_tex' for all loading case combinations ''' #---------------------------------------- # script to get the maximum number of reinforcement ('n_tex') # at all given coordinate points for all possible loading # case combinations: #---------------------------------------- # set option to "True" for surrounding # evaluation of necessary layers "n_tex" # needed for all loading cases # get the list of all loading case combinations: # lcc_list = self.lcc_list #---------------------------------------------- # run trough all loading case combinations: #---------------------------------------------- n_tex_list = [] for lcc in lcc_list: # get the ls_table object and retrieve its 'ls_class' # (= LSTable_ULS-object) # ls_class = lcc.ls_table.ls_class # get 'n_tex'-column array # n_tex = ls_class.n_tex # n_tex = ls_class.n_tex_up # n_tex = ls_class.n_tex_lo n_tex_list.append(n_tex) # stack the list to an array in order to use np.max-function # n_tex_arr = np.hstack(n_tex_list) #---------------------------------------------- # get the overall maximum values: #---------------------------------------------- n_tex_max = np.max(n_tex_arr, axis=1)[:, None] #---------------------------------------------- # plot #---------------------------------------------- # X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] plot_col = n_tex_max[:, 0] # if n_tex is negative plot 0 instead: # plot_col = np.where(plot_col < 0, 0, plot_col) mlab.figure(figure=title, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, (-1.0) * Z, plot_col, colormap="YlOrBr", mode="cube", scale_mode='none', scale_factor=0.10) mlab.scalarbar(title='n_tex (all LCs)', orientation='vertical') mlab.show()
def slicing(data, xlabel='', ylabel='', zlabel='', title=''): ''' Description This function generates a Mayavi scene that shows cut planes along the x, y and z axes of a data cube. This is an interactive scene, and so the cut planes can be moved through the cube, and the entire cube can be rotated. Required Input data: A three dimensional numpy array. Each entry of the array must contain a scalar value. xlabel: A string specifying a label for the x axis of the data cube. ylabel: A string specifying a label for the y axis of the data cube. zlabel: A string specifying a label for the z axis of the data cube. title: A string specifying the title for the visualisation. Output This function returns 1 if it runs to completion. An interactive Mayavi scene is produced by the function, allowing slices through a three dimensional data cube to be viewed. ''' # Create a new Mayavi scene to visualise slicing the data cube scene = mlab.figure(size=(800, 700)) # Run a widget that allows you to visualise three dimensional data sets # This creates a slice along the x axis that can be interactively varied mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data),\ plane_orientation='x_axes', slice_index=0) # This creates a slice along the y axis that can be interactively varied, # on the same image as the x axis slice mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data),\ plane_orientation='y_axes', slice_index=0) # This creates a slice along the z axis that can be interactively varied, # on the same image as the x and y axis slices mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data), plane_orientation='z_axes', slice_index=0) # Add axes to the visualisation of the image cube, and label the x, y and # z axes mlab.axes(xlabel=xlabel, ylabel=ylabel, zlabel=zlabel) # Add a title to the visualisation of the image cube mlab.title(title, height=1.0) # Make the outline of the image cube appear mlab.outline() # Make a colourbar for the data mlab.scalarbar(orientation='vertical') # Add a little symbol to show the orientation of the data mlab.orientation_axes() # Allow interaction with the produced visualisation mlab.show() # Once the interactive 3D view has been created, return 0 return 1
def plot_assess_value(self, title=None, add_assess_values_from_file=None, save_assess_values_to_file=None): '''plot-3d the assess value for all loading case combinations as structure plot with color legend ''' print '################### plotting assess_value ##################' #---------------------------------------- # script to get the maximum values of 'assess_value' # at all given coordinate points for all possible loading # case combinations: #---------------------------------------- # get the list of all loading case combinations: # lcc_list = self.lcc_list #---------------------------------------------- # run trough all loading case combinations: #---------------------------------------------- assess_value_list = [] for lcc in lcc_list: # get the ls_table object and retrieve its 'ls_class' # (= LSTable_ULS-object) # ls_class = lcc.ls_table.ls_class # get 'assess_name'-column array # assess_name = ls_class.assess_name if assess_name == 'max_eta_nm_tot': assess_value = getattr(ls_class, 'eta_nm_tot') # get only the components resulting from normal forces... # # assess_value = getattr(ls_class, 'eta_n_tot') # get only the components resulting from bending moments... # # assess_value = getattr(ls_class, 'eta_m_tot') if assess_name == 'max_n_tex': assess_value = getattr(ls_class, 'n_tex') if assess_name == 'max_eta_tot': assess_value = getattr(ls_class, 'eta_tot') # n_tex = ls_class.n_tex_up # n_tex = ls_class.n_tex_lo assess_value_list.append(assess_value) # stack the list to an array in order to use np.max-function # assess_value_arr = np.hstack(assess_value_list) print 'assess_value_arr.shape', assess_value_arr.shape #---------------------------------------------- # get the overall maximum values: #---------------------------------------------- assess_value_max = np.max(assess_value_arr, axis=1)[:, None] #---------------------------------------------- # plot #---------------------------------------------- # X = lcc_list[0].ls_table.X[:, 0] Y = lcc_list[0].ls_table.Y[:, 0] Z = lcc_list[0].ls_table.Z[:, 0] if self.reader_type == 'RFEM': Z *= -1.0 plot_col = assess_value_max[:, 0] # save assess values to file in order to superpose them later # if save_assess_values_to_file != None: print 'assess_values saved to file %s' % (save_assess_values_to_file) assess_value_arr = plot_col np.savetxt(save_assess_values_to_file, assess_value_arr) # add read in saved assess values to be superposed with currently read in assess values # if add_assess_values_from_file != None: print 'superpose assess_value_arr with values read in from file %s' % (add_assess_values_from_file) assess_value_arr = np.loadtxt(add_assess_values_from_file) plot_col += assess_value_arr # if n_tex is negative plot 0 instead: # # # plot_col = np.where(plot_col < 0, 0, plot_col) mlab.figure(figure=title, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0)) mlab.points3d(X, Y, Z, plot_col, colormap="YlOrBr", mode="cube", scale_mode='none', scale_factor=0.10) mlab.scalarbar( title=assess_name + ' (all LCs)', orientation='vertical') mlab.show()
def figlbl(figh=None): figh.scene.anti_aliasing_frames = 0 mlab.outline(figure=figh) # box around data axes mlab.orientation_axes(figure=figh) mlab.scalarbar() mlab.axes(figure=figh, xlabel="x (km)", ylabel="y (km)", zlabel="z (km)")
for j in range(len(y)): u[i][j] = numpy.sin(2 * math.pi * x[i]) * numpy.cos(2 * math.pi * y[j]) v[i][j] = -numpy.cos(2 * math.pi * x[i]) * numpy.sin( 2 * math.pi * y[j]) u_y[i][j] = -2 * math.pi * numpy.sin(2 * math.pi * x[i]) * numpy.sin( 2 * math.pi * y[j]) v_x[i][j] = 2 * math.pi * numpy.sin(2 * math.pi * x[i]) * numpy.sin( 2 * math.pi * y[j]) omega[i][j] = v_x[i][j] - u_y[i][j] theta[i][j] = numpy.exp(-2.0 * ((4 * math.pi * (x[i] - 0.3))**2 + (4 * math.pi * (y[j] - 0.3))**2)) alpha[i][j] = numpy.sin(4 * math.pi * x[i]) * numpy.cos( 6 * math.pi * y[j]) src = mlab.imshow(xx, yy, theta, colormap='jet') mlab.scalarbar(object=src) mlab.xlabel('x', object=src) mlab.ylabel('y', object=src) # Wavenumber k_x = 2*math.pi*numpy.array([complex(0,1)*n for n in range(0,N/2) \ + [0] + range(-N/2+1,0)]) k_y = k_x kx = numpy.zeros((N, N), dtype=complex) ky = numpy.zeros((N, N), dtype=complex) kxx = numpy.zeros((N, N), dtype=complex) kyy = numpy.zeros((N, N), dtype=complex) for i in xrange(N): for j in xrange(N):
surfargs = dict(colormap=colormap, vmin=vmin, vmax=vmax) # 获取坐标信息 x = coords[:, 0] y = coords[:, 1] z = coords[:, 2] geo_mesh = mayavi.mlab.pipeline.triangular_mesh_source(x, y, z, faces, **meshargs) # 返回一个二维网格 # 再根据顶点法向量调整成surface? # add surface normals geo_mesh.data.point_data.normals = vtx_normals geo_mesh.data.cell_data.normals = None # cell_data是指什么? geo_surf = mayavi.mlab.pipeline.surface(geo_mesh, figure=figure, reset_zoom=True, **surfargs) if reverse: curv_bar = mlab.scalarbar(geo_surf) # get the scalar color map from geo_surf curv_bar.reverse_lut = True # reverse the lut curv_bar.visible = False # add_overlay # -------------------------------------------------------------------------------- # 例子中说lh.sig.nii.gz中存的是激活数据,所以我猜sig是signal的意思 signal_path = os.path.join("/nfs/j3/userhome/chenxiayu/workingdir/examples/example_data", "lh.sig.nii.gz") sign, name = "abs", "sig" # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # read_scalar_data try: # try loading the nii.gz file scalar_data = nibabel.load(signal_path).get_data() # (numpy ndarray: 163842*1*1) scalar_data = numpy.ravel(scalar_data, order='F') # (shape: (163842,)) convert to one dimension
y = np.arange(0, len(ef[0]), 1) z = np.arange(0, len(ef[0]), 1) Xe, Ye, Ze = np.meshgrid(xx, y, z, indexing='ij') norm = o.dimension**3 print(norm) ef = ef / norm m.figure() m.quiver3d(Xe, Ye, Ze, ef[0], ef[1], ef[2], colormap='gnuplot') m.title('E-field/potential - vector/scalar') m.vectorbar() m.axes(ranges=[0, n, 0, n, 0, n]) m.figure() a = m.contour3d(X, Y, Z, o.potential / norm) m.scalarbar() m.axes(ranges=[0, n, 0, n, 0, n]) m.show() d_values = [] p_values = [] half = int(n / 2) for i in range(n): for j in range(n): for k in range(n): distance = np.sqrt(((i - half)**2) + ((j - half)**2) + ((k - half)**2)) d_values.append(np.log(distance)) pot = o.potential[i, j, k] p_values.append(np.log(pot))
u_x,u_y,u_z = u_x[:N],u_y[:N],u_z[:N] e_xx,e_yy,e_zz = e_xx[:N],e_yy[:N],e_zz[:N] e_xy,e_xz,e_yz = e_xy[:N],e_xz[:N],e_yz[:N] s_xx,s_yy,s_zz = s_xx[:N],s_yy[:N],s_zz[:N] s_xy,s_xz,s_yz = s_xy[:N],s_xz[:N],s_yz[:N] cmap = cm.viridis # Plot this component of the stress tensor stress = s_zz stress_label = 'vertical stress' fig = mlab.figure(bgcolor=(0.9,0.9,0.9),fgcolor=(0.0,0.0,0.0),size=(600, 600)) # turn second invariant into structured data dat = make_scalar_field(nodes,stress,bnd_vert=vert,bnd_smp=smp) # plot the top surface simplices mlab.triangular_mesh(vert[:,0],vert[:,1],vert[:,2]+1e-2,smp[10:],opacity=1.0,colormap='gist_earth',vmin=-1.0,vmax=0.25) # plot the bottom simplices mlab.triangular_mesh(vert[:,0],vert[:,1],vert[:,2],smp[:2],color=(0.0,0.0,0.0),opacity=0.5) p = mlab.pipeline.iso_surface(dat,opacity=0.5,contours=7) mlab.quiver3d(nodes[:,0],nodes[:,1],nodes[:,2],u_x,u_y,u_z,mode='arrow',color=(0.2,0.2,0.2),scale_factor=1.0) # set colormap to cmap colors = cmap(np.linspace(0.0,1.0,256))*255 p.module_manager.scalar_lut_manager.lut.table = colors # add colorbar cbar = mlab.scalarbar(p,title=stress_label) cbar.number_of_labels = 5 cbar.title_text_property.bold = False cbar.title_text_property.italic = False cbar.label_text_property.bold = False cbar.label_text_property.italic = False mlab.show()
def drawGraph(self, colormap='jet', mapping=None, surfaceOnly=False): """ """ self.figure = mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(1200, 900)) self.gcf = mlab.gcf() # mlab.clf() self.figure.scene.disable_render = True self.crds = {} print("root information:",self.root_wcrd, self.root) # create drawables for bifurcations and endpoints self.narray = np.zeros((len(self.nodes), 3), dtype=np.float32) nodeSize = np.zeros((len(self.nodes),)) labels = [] for i in range(self.narray.shape[0]): n = self.nodes[i] self.narray[i, :] = n[1]['wcrd'] dg = self.og.degree(n[0]) if(dg == 1): tmp = (self.narray[i, 0], self.narray[i, 1], self.narray[i, 2]) nodeSize[i] = 1 if tuple(map(int, tmp)) != self.root_wcrd else 1.5 labels.append((n[0], tmp)) else: nodeSize[i] = 0.5 # # create random mapping if mapping is None: mapping = {} for e in self.edges: clr = random.randint(0, 1) mapping[(e[0], e[1])] = clr # now draw self.lines = {} surface = None self.surfaces = None x = np.array([0, 0]) y = np.array([0, 0]) z = np.array([0, 0]) s = np.array([0, 4]) for e in self.edges: try: mp = e[2]["mappedPoints"] x = np.concatenate((x, mp[::4, 0])) y = np.concatenate((y, mp[::4, 1])) z = np.concatenate((z, mp[::4, 2])) clr = mapping[(e[0], e[1])] # clr_t = clr, clr, clr s = np.concatenate((s, np.linspace(clr, clr, len(mp[::4, 0])))) #print "%s->%s mapping=%s"%(e[0],e[1],clr) if surface is None: surface = e[2]['mappedPoints'] else: try: surface = np.concatenate((surface, mp), axis=0) except ValueError: pass sp = e[2]['d0'] if(sp): if not surfaceOnly: self.lines[(e[0], e[1])] = mlab.plot3d(sp[0], sp[1], sp[2], color=(0, 0, 0), # color=clrt, tube_radius=.3) except KeyError as error: print("KeyError", error) except IndexError as error: print("IndexError", error) self.surfaces = mlab.points3d(x, y, z, s, # colormap="Greys", colormap="jet", scale_mode='none', scale_factor=.4, opacity=0.5) if not surfaceOnly: self.npts = mlab.points3d(self.narray[:, 0], self.narray[:, 1], self.narray[:, 2], nodeSize, colormap="jet", scale_factor=4.0) x = surface[::1, 0] y = surface[::1, 1] z = surface[::1, 2] minx = min(x) maxx = max(x) miny = min(y) maxy = max(y) minz = min(z) maxz = max(z) X, Y, Z = np.mgrid[minx:maxx:100j, miny:maxy:100j, minz:maxz:100j] # Visualize the points3d clr = (1, 0, 0) # Labels and legends if(self.showAxes): mlab.xlabel("x") mlab.ylabel("y") mlab.xlabel("z") mlab.title(self.title, size=.5, height=.90) for label in labels: l = label[1] fl = tuple(map(int, l)) if fl == self.root_wcrd: mlab.text(l[0], l[1], repr(label[0]) + " (root)", z=l[2], width=.2, color=(0, 0, 0)) else: mlab.text(l[0], l[1], repr(label[0]), z=l[2], width=.15, color=(0, 0, 0)) #adjust lut transparency lut = self.surfaces.module_manager.scalar_lut_manager.lut.table.to_array() lut[:, -1] = np.linspace(110, 110, 256) self.surfaces.module_manager.scalar_lut_manager.lut.table = lut # add scale bar if self.surfaces is not None: mlab.scalarbar(title="scale", orientation='vertical', nb_labels=5) self.figure.scene.disable_render = False mlab.view(0, 180, 400, roll=180) #saveFileName = os.path.join(os.path.expanduser("~"), "desktop", self.title + ".png") #mlab.savefig(saveFileName) #mlab.close() mlab.show()