def test_text(self): """ Test the text module. """ data = np.random.random((3, 3, 3)) src = mlab.pipeline.scalar_field(data) # Some smoke testing mlab.text(0.1, 0.9, 'foo') mlab.text(3, 3, 'foo', z=3) mlab.title('foo') # Check that specifying 2D positions larger than 1 raises an # error self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
def plot_3d(lats,lons,depth,vs,runlat,runlon,vtkname='rayleigh_c_u.vtk', annotate_depth=False,coastline=False,annotate_lat=True,annotate_lon=True): """ plot 3d results using mayavi """ if coastline: plot_canada_map() sgrid = get_tvtk_grid(lats,lons,depth,vs) d = mlab.pipeline.add_dataset(sgrid) #sf = mlab.pipeline.surface(d) #gx = mlab.pipeline.grid_plane(d) #gx.grid_plane.axis = 'x' gy = mlab.pipeline.grid_plane(d) gy.grid_plane.axis = 'x' gy.module_manager.scalar_lut_manager.show_scalar_bar = True gy.module_manager.scalar_lut_manager.lut_mode = 'jet' gy.module_manager.scalar_lut_manager.data_range = np.array([ 2. , 4.8]) gy.module_manager.scalar_lut_manager.scalar_bar_representation.maximum_size = np.array([100000, 100000]) gy.module_manager.scalar_lut_manager.scalar_bar_representation.minimum_size = np.array([1, 1]) gy.module_manager.scalar_lut_manager.scalar_bar_representation.position2 = np.array([ 0.08796009, 0.56264591]) gy.module_manager.scalar_lut_manager.scalar_bar_representation.position = np.array([ 0.03396896, 0.39182879]) gy.actor.mapper.progress = 1.0 gy.actor.mapper.scalar_range = np.array([ 0., 1.]) gy.actor.mapper.scalar_visibility = True gy.actor.property.representation = 'surface' gy.grid_plane.position = 6 #gz = mlab.pipeline.grid_plane(d) #gz.grid_plane.axis = 'z' if annotate_lat: for lat in runlat: x,y,z = convert_pt(lat,-58.,10.) txt = mlab.text3d(x,y,z,'%d'%(lat),color=(0,0,0),line_width=10.0) txt.scale = [20,20,20] if annotate_lon: for lon in runlon[1::]: x,y,z = convert_pt(49.,lon,10.) txt = mlab.text3d(x,y,z,'%d'%(lon),color=(0,0,0),line_width=10.0) txt.scale = [20,20,20] if annotate_depth: for dp in [-10,-40,-80,-120]: x,y,z = convert_pt(49,-68.,dp) txt = mlab.text3d(x,y,z,'%d km'%(dp),color=(0,0,0),line_width=10.0) txt.scale = [20,20,20] ### Include 3D screenshot in matplotlib #arr = mlab.screenshot() #import pylab as pl #pl.imshow(arr) #pl.show() mlab.text(0.76,0.86,'49N',width=0.1) mlab.show()
def show_variable_timecourse(self, var, time_point, start_value, end_value): """Show an animation of all the section that have the recorded variable among time""" # Getting the new scalar new_scalar = self.get_var_data(var, time_point) d = self.dataset.point_data.get_array('diameter') if len(d) != len(new_scalar): message = "ERROR! MISMATCH on the Vector Length. \ If you assign the new vectors it will not work \ Diameter length: %s New Scalar length: %s var: %s" % ( len(d), len(new_scalar), var) logger.error(message) # ReEnable the rendering self.mayavi.visualization.scene.disable_render = True self.redraw_color(new_scalar, var) if not self.colorbar: self.colorbar = mlab.colorbar(orientation='vertical') self.timelabel = mlab.text(0.05, 0.05, str(time_point), width=0.05) self.colorbar.data_range = [start_value, end_value] time = self.manager.groups['t'][time_point] self.timelabel.text = str(round(time, 3)) self.mayavi.visualization.scene.disable_render = False
if False: from enthought.mayavi import mlab fig1 = mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(800,800)) #mlab.points3d(ph_a, th_a, r_a, s_a,opacity=0.1,scale_factor=3)#, color=(0,0,1)) mlab.points3d(ph_r, th_r, r_r, s_r,opacity=0.3,scale_factor=2)#, color=(1,0,0)) mlab.axes(ranges=[0.0, 90.0, 0.0, 90.0, 3.0, 9.0]) #mlab.orientation_axes() mlab.xlabel("phi") mlab.ylabel("theta") mlab.zlabel("centroid\ndistance") #mlab.colorbar(nb_labels=2,nb_colors=2,label_fmt='') mlab.colorbar() #mlab.text(0.1,0.1,"attraction",color=(0,0,1),width=0.1) #mlab.text(0.8,0.1,"repulsion",color=(1,0,0),width=0.1) mlab.text(0.1,0.8,"%s-%s (n=%i; x=%i); (%s)"%(res1,res2,ndata,countNone,pdblistfile),width=0.8) mlab.title("Free Energy (%s,%s)"%(res1,res2),size=0.3,height=0.7,figure=fig1) viewdist = 120 elevation = 60 # angle or 'rotate' azimuth = 180+45 # angle or 'rotate' mlab.view(distance=viewdist,elevation=elevation, azimuth=azimuth) mlab.savefig(pdblistfile+"_%s_%s_r_theta_phi.png"%(res1,res2)) mlab.show() #sys.exit() ############## for i in xrange(len(bins[0])): tmp = []
# value. We want to reposition this value to 0, so as to put it in the # center of our extents. cat1 -= 0.5 cat2 -= 0.5 cat3 -= 0.5 cat1_extent = (-14,-6, -4,4, 0,5) surf_cat1 = mlab.surf(x-10, y, cat1, colormap='Spectral', warp_scale=5, extent=cat1_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat1, color=(.7, .7, .7)) mlab.axes(surf_cat1, color=(.7, .7, .7), extent=cat1_extent, ranges=(0,1, 0,1, 0,1), xlabel='', ylabel='', zlabel='Probability', x_axis_visibility=False, z_axis_visibility=False) mlab.text(-18, -4, '1 photon', z=-4, width=0.13) cat2_extent = (-4,4, -4,4, 0,5) surf_cat2 = mlab.surf(x, y, cat2, colormap='Spectral', warp_scale=5, extent=cat2_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat2, color=(0.7, .7, .7), extent=cat2_extent) mlab.text(-4, -3, '2 photons', z=-4, width=0.14) cat3_extent = (6,14, -4,4, 0,5) surf_cat3 = mlab.surf(x+10, y, cat3, colormap='Spectral', warp_scale=5, extent=cat3_extent, vmin=-0.5, vmax=0.5) mlab.outline(surf_cat3, color=(.7, .7, .7), extent=cat3_extent) mlab.text(6, -2.5, '3 photons', z=-4, width=0.14)
def make_side_view(self, axis_name): scene = getattr(self, 'scene_%s' % axis_name) scene.scene.parallel_projection = True ipw_3d = getattr(self, 'ipw_3d_%s' % axis_name) # We create the image_plane_widgets in the side view using a # VTK dataset pointing to the data on the corresponding # image_plane_widget in the 3D view (it is returned by # ipw_3d._get_reslice_output()) side_src = ipw_3d.ipw._get_reslice_output() ipw = mlab.pipeline.image_plane_widget( side_src, plane_orientation='z_axes', vmin=self.data.min(), vmax=self.data.max(), figure=scene.mayavi_scene, name='Cut view %s' % axis_name, ) setattr(self, 'ipw_%s' % axis_name, ipw) # Extract the spacing of the side_src to convert coordinates # into indices spacing = side_src.spacing # Make left-clicking create a crosshair ipw.ipw.left_button_action = 0 x, y, z = self.position cursor = mlab.points3d(x, y, z, mode='axes', color=(0, 0, 0), scale_factor=2*max(self.data.shape), figure=scene.mayavi_scene, name='Cursor view %s' % axis_name, ) self.cursors[axis_name] = cursor # Add a callback on the image plane widget interaction to # move the others this_axis_number = self._axis_names[axis_name] def move_view(obj, evt): # Disable rendering on all scene position = list(obj.GetCurrentCursorPosition()*spacing)[:2] position.insert(this_axis_number, self.position[this_axis_number]) # We need to special case y, as the view has been rotated. if axis_name is 'y': position = position[::-1] self.position = position ipw.ipw.add_observer('InteractionEvent', move_view) ipw.ipw.add_observer('StartInteractionEvent', move_view) # Center the image plane widget ipw.ipw.slice_position = 0.5*self.data.shape[ self._axis_names[axis_name]] # 2D interaction: only pan and zoom scene.scene.interactor.interactor_style = \ tvtk.InteractorStyleImage() scene.scene.background = (0, 0, 0) # Some text: mlab.text(0.01, 0.8, axis_name, width=0.08) # Choose a view that makes sens views = dict(x=(0, 0), y=(90, 180), z=(0, 0)) mlab.view(views[axis_name][0], views[axis_name][1], focalpoint=0.5*np.array(self.data.shape), figure=scene.mayavi_scene) scene.scene.camera.parallel_scale = 0.52*np.mean(self.data.shape)
points.mlab_source.dataset.lines = connections points.mlab_source.update() # To represent the lines, we use the surface module. Using a wireframe # representation allows to control the line-width. mlab.pipeline.surface(points, color=(1, 1, 1), representation='wireframe', line_width=4, name='Connections') ############################################################################### # Display city names for city, index in cities.iteritems(): label = mlab.text(x[index], y[index], city, z=z[index], width=0.016 * len(city), name=city) label.property.shadow = True ############################################################################### # Display continents outline, using the VTK Builtin surface 'Earth' from enthought.mayavi.sources.builtin_surface import BuiltinSurface continents_src = BuiltinSurface(source='earth', name='Continents') # The on_ratio of the Earth source controls the level of detail of the # continents outline. continents_src.data_source.on_ratio = 2 continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0)) ############################################################################### # Display a semi-transparent sphere, for the surface of the Earth
# -*- coding: utf-8 -*- from enthought.mayavi import mlab from tvtk_rectilineargrid import r from figure_imagedata import plot_cell if __name__ == "__main__": mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.clf() mlab.pipeline.surface(mlab.pipeline.extract_edges(r), color=(0, 0, 0)) mlab.pipeline.glyph(r, mode='sphere', scale_factor=0.5, scale_mode='none') plot_cell(r.get_cell(1)) mlab.text(0.01, 0.9, "get_cell(1)", width=0.25) axes = mlab.orientation_axes() mlab.show()
opacity=1, colormap='Blues', name='[O III]-2') surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\ opacity=0.1,colormap='autumn', name='Hbeta') surf6 = mlab.points3d((stars[:,0]-size_x/2)*0.5*astopc,(stars[:,1]-size_y/2.)*0.5*astopc,stars[:,0]*0.0,stars[:,2]*0.5*astopc*2,color=(0,0,0), scale_factor=1, name = 'Stars') # Now to make it look decent ... ax = mlab.axes(extent=[-10,10,-12,12,-7,7],nb_labels=5) ax.axes.fly_mode = 'outer_edges' ax.title_text_property.font_size = 10 ax.title_text_property.font_family = 'courier' ax.label_text_property.font_family = 'courier' # And a bit of references if anyone is interested ... mlab.text(0.05,0.95,'Oxygen-rich ejecta in SNR N132D. Vogt & Dopita, Ap&SS, 311, 521 (2011); Vogt & Shingles, Ap&SS (2013), submitted.',width=0.75) mlab.text(0.05,0.05,'*****@*****.**',width=0.25) # Label the axes ... ax.axes.x_label = 'X (Dec.) [pc]' ax.axes.y_label = 'Y (R.A.) [pc]' ax.axes.z_label = 'Z [pc]' mlab.show() # Define the view point - useful to make a movie (not build here) ... mlab.view(90,0,60) # Save it all ... #mlab.savefig('Vogt+Shingles_test.wrl') #mlab.savefig('Vogt+Shingles_test.eps') #mlab.savefig('Vogt+Shingles_test.png')
connections = np.array(connections) # We add lines between the points that we have previously created by # directly modifying the VTK dataset. points.mlab_source.dataset.lines = connections points.mlab_source.update() # To represent the lines, we use the surface module. Using a wireframe # representation allows to control the line-width. mlab.pipeline.surface(points, color=(1, 1, 1), representation='wireframe', line_width=4, name='Connections') ############################################################################### # Display city names for city, index in cities.iteritems(): label = mlab.text(x[index], y[index], city, z=z[index], width=0.016*len(city), name=city) label.property.shadow = True ############################################################################### # Display continents outline, using the VTK Builtin surface 'Earth' from enthought.mayavi.sources.builtin_surface import BuiltinSurface continents_src = BuiltinSurface(source='earth', name='Continents') # The on_ratio of the Earth source controls the level of detail of the # continents outline. continents_src.data_source.on_ratio = 2 continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0)) ############################################################################### # Display a semi-transparent sphere, for the surface of the Earth # We use a sphere Glyph, throught the points3d mlab function, rather than
# -*- coding: utf-8 -*- from enthought.mayavi import mlab from tvtk_rectilineargrid import r from figure_imagedata import plot_cell if __name__ == "__main__": mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) mlab.clf() mlab.pipeline.surface(mlab.pipeline.extract_edges(r), color=(0, 0, 0)) mlab.pipeline.glyph(r, mode='sphere', scale_factor=0.5, scale_mode='none') plot_cell(r.get_cell(1)) mlab.text(0.01, 0.9, "get_cell(1)", width=0.25) axes = mlab.orientation_axes( ) mlab.show()
def visualize_graph(self): """ Visualize the graph with the 3D view """ from enthought.mayavi import mlab from enthought.tvtk.api import tvtk # precondition for the graph visualization if self.scene3d is None: self.scene3d = self._create3DScene() # alias for currently used scene fig = self.scene3d # get source object srcobj = self.datasourcemanager.get_sourceobject() # create node source ##### self.nodesrc = mlab.pipeline.scalar_scatter(srcobj.positions[:,0], srcobj.positions[:,1], srcobj.positions[:,2],\ figure = fig, name = 'Node Source') # adding scalar data arrays # create a sequence array to map the node ids to color from numpy import array ar = array(range(1,len(srcobj.nodeids)+1)) self.nodesrc.mlab_source.dataset.point_data.add_array(ar) self.nodesrc.mlab_source.dataset.point_data.get_array(0).name = 'nodeids' self.nodesrc.mlab_source.dataset.point_data.add_array(srcobj.selected_nodes) self.nodesrc.mlab_source.dataset.point_data.get_array(1).name = 'selected_nodes' # setting the active attributes actsel1 = mlab.pipeline.set_active_attribute(self.nodesrc, point_scalars='nodeids', \ name="Colored Nodes") actsel2 = mlab.pipeline.set_active_attribute(self.nodesrc, point_scalars='selected_nodes', \ name="Selected Nodes") # create glyphs self.nodes = mlab.pipeline.glyph(actsel1, scale_factor=3.0, scale_mode='none',\ name = 'Nodes', mode='cube') self.nodes.glyph.color_mode = 'color_by_scalar' # FIXME: # interpolate setting to true makes the color mapping wrong on linux # otherwise on windows, if not set to true, the cubes stay dark (why?) from sys import platform if 'win32' in platform: self.nodes.actor.mapper.interpolate_scalars_before_mapping = True # if there exists a colormap, use it l = self.nodes.glyph.module.module_manager.scalar_lut_manager.lut # number of colors has to be greater equal to 2 if not len(srcobj.nodeids) < 2: l.number_of_colors = len(srcobj.nodeids) l.build() # getting colors from source object l.table = srcobj.colors # create glyphs for selected nodes self.nodes_selected = mlab.pipeline.glyph(actsel2, scale_mode = 'scalar', \ opacity = 0.2, scale_factor = 7.0, \ name = 'Nodes', color = (0.92, 0.98, 0.27)) self.nodes_selected.glyph.color_mode = 'no_coloring' self.nodes_selected.glyph.glyph.clamping = False self.nodes_selected.glyph.glyph_source.glyph_source.phi_resolution = 12 self.nodes_selected.glyph.glyph_source.glyph_source.theta_resolution = 12 self.nodes_selected.actor.mapper.interpolate_scalars_before_mapping = True # should I load the node labels? # this is too slow for many nodes if preference_manager.cviewerui.labelload: for index, label in enumerate(srcobj.labels): tmplabel = mlab.text(srcobj.positions[index,0], srcobj.positions[index,1], \ label, z=srcobj.positions[index,2], \ width=0.010*len(label), \ color = (1,1,1), name='Node Label ' + label) tmplabel.property.shadow = True # split up what was achieved before by quiver3d # add a vector_scatter data source with scalars self.vectorsrc = mlab.pipeline.vector_scatter(srcobj.start_positions[0], srcobj.start_positions[1], srcobj.start_positions[2], srcobj.vectors[0], srcobj.vectors[1], srcobj.vectors[2], name = 'Connectivity Source', figure = fig) lastkey = '' # add all the scalars we have (from the srcobj scalarsdict) # this should be an ordered dict! for key, value in srcobj.scalarsdict.items(): da = tvtk.DoubleArray(name=str(key)) da.from_array(srcobj.scalarsdict[key]) self.vectorsrc.mlab_source.dataset.point_data.add_array(da) self.vectorsrc.mlab_source.dataset.point_data.scalars = da.to_array() self.vectorsrc.mlab_source.dataset.point_data.scalars.name = str(key) lastkey = str(key) # this is the winning time-consuming line, and can be ommited in further mayavi releases self.vectorsrc.outputs[0].update() # add a set active attribute filter to select the scalars self.attract = mlab.pipeline.set_active_attribute(self.vectorsrc, point_scalars=lastkey, \ name="Set Edge Attribute") self.thres = mlab.pipeline.threshold(self.attract, name="Thresholding") # to prevent vtkLookupTable: Bad table range self.thres.filter_type = 'cells' #self.thres.threshold_filter.all_scalars = False if srcobj.directed: self.vectors = mlab.pipeline.vectors(self.thres,\ colormap='OrRd', figure=fig, name='Connections', mode='arrow', scale_factor=1, resolution=20, scale_mode = 'vector') self.vectors.glyph.glyph_source.glyph_source.shaft_radius = 0.015 self.vectors.glyph.glyph_source.glyph_source.shaft_resolution = 20 self.vectors.glyph.glyph_source.glyph_source.tip_radius = 0.04 self.vectors.glyph.glyph_source.glyph_source.tip_length = 0.15 self.vectors.glyph.glyph_source.glyph_source.tip_resolution = 20 self.vectors.glyph.color_mode = 'color_by_scalar' self.vectors.glyph.glyph.clamping = False else: # then create a .vectors filter to display self.vectors = mlab.pipeline.vectors(self.thres,\ colormap='OrRd', #mode='cylinder', figure=fig, name='Connections', #scale_factor=1, #resolution=20, # make the opacity of the actor depend on the scalar. #transparent=True, scale_mode = 'vector') self.vectors.glyph.glyph_source.glyph_source.glyph_type = 'dash' # vectors.glyph.glyph_source.glyph_source.radius = 0.01 self.vectors.glyph.color_mode = 'color_by_scalar' self.vectors.glyph.glyph.clamping = False
def make_side_view(self, axis_name): scene = getattr(self, 'scene_%s' % axis_name) scene.scene.parallel_projection = True ipw_3d = getattr(self, 'ipw_3d_%s' % axis_name) # We create the image_plane_widgets in the side view using a # VTK dataset pointing to the data on the corresponding # image_plane_widget in the 3D view (it is returned by # ipw_3d._get_reslice_output()) ipw = mlab.pipeline.image_plane_widget( ipw_3d.ipw._get_reslice_output(), plane_orientation='z_axes', vmin=self.data.min(), vmax=self.data.max(), figure=scene.mayavi_scene, name='Cut view %s' % axis_name, ) setattr(self, 'ipw_%s' % axis_name, ipw) # Make left-clicking create a crosshair ipw.ipw.left_button_action = 0 x, y, z = self.position cursor = mlab.points3d(x, y, z, mode='axes', color=(0, 0, 0), scale_factor=2*max(self.data.shape), figure=scene.mayavi_scene, name='Cursor view %s' % axis_name, ) self.cursors[axis_name] = cursor # Add a callback on the image plane widget interaction to # move the others this_axis_number = self._axis_names[axis_name] def move_view(obj, evt): # Disable rendering on all scene position = list(obj.GetCurrentCursorPosition())[:2] position.insert(this_axis_number, self.position[this_axis_number]) # We need to special case y, as the view has been rotated. if axis_name is 'y': position = position[::-1] self.position = position ipw.ipw.add_observer('InteractionEvent', move_view) ipw.ipw.add_observer('StartInteractionEvent', move_view) # Center the image plane widget ipw.ipw.slice_position = 0.5*self.data.shape[ self._axis_names[axis_name]] # 2D interaction: only pan and zoom scene.scene.interactor.interactor_style = \ tvtk.InteractorStyleImage() scene.scene.background = (0, 0, 0) # Some text: mlab.text(0.01, 0.8, axis_name, width=0.08) # Choose a view that makes sens views = dict(x=(0, 0), y=(90, 180), z=(0, 0)) #mlab.view(*views[axis_name],figure=scene.mayavi_scene) #focalpoint=0.5*np.array(self.data.shape), scene.scene.camera.parallel_scale = 0.52*np.mean(self.data.shape)
theta = arcsin(vlen(planenormal) / k_photon / 2) ########################################## #angle between diffraction plane and surface theta1 = arccos(vlen(planenormal * array([0, 0, 1])) / vlen(planenormal)) phi1 = arctan(planenormal[1] / planenormal[0]) textwidth = 0.005 ####################### # the surface x, y = mgrid[-100:101, -100:101] / 100 * a z = x - x mlab.mesh(x, y, z, opacity=0.5) text = 'film surface' mlab.text(1.1 * a, 0, 'film surface', z=0, width=len(text) * textwidth) at.plot3d(text='(0,0,0)') mlab.quiver3d([0], [0], [0], [0], [0], [1], mode='2ddash', color=(0, 0, 1), scale_mode="none", scale_factor=6) text = 'surface normal' mlab.text(0, 0, text, z=1.1 * c, width=len(text) * textwidth) ########################## # the diffraction plane plane_kx = planenormal[0] / planenormal[2] plane_ky = planenormal[1] / planenormal[2]
# Non-broadcasting version of the cube calculation ################################################################################ new_fig(size=(500, 300)) options['opacity'] = 1 x, y, z = np.mgrid[0:4, 0:4, 0:4] pts_x = mlab.points3d(x-5, y, z, 2*z, **options) pts_y = mlab.points3d(x-10, y, z, 2*y, **options) pts_z = mlab.points3d(x-15, y, z, 2*x, **options) r = 2*np.sqrt(x**2 + y**2 + z**2) pts = mlab.points3d(r, **options) mlab.text(-14.5, -1, 'x', z=-3, width=0.06) mlab.text(-9.2, -1, 'y', z=-3, width=0.06) mlab.text(-4, -1, 'z', z=-3, width=0.05) mlab.text(1.5, -1, 'r', z=-3, width=0.035) mlab.view(-96, 46, 22, (-6.25, 1.1, 1.1)) mlab.savefig('3d_radius_non_broadcasting.jpg') ################################################################################ # Broadcasting operations that happen in this cube ################################################################################ x, y, z = np.mgrid[0:4, 0:4, 0:4] mlab.outline(pts_x, color=(0.5, 0.5, 0.5)) pts_x.remove()
def generate_mayavi_line_plot(self, srcid_sciclasses_list, use_linfit_segments=False, enable_mayavi2_interactive_gui=False): """ Generate a Mayavi mlab 3D plot which summarizes iterative classification of a TUTOR source over the number of epochs used/added. """ # TODO: I would like to plot each sci class a different color # - I should have each science class re-use a single number/color # - I should label which science class by color, as Y axis labels # TODO: I will need to insert a 0 point onto arrays (for s[0]?) if enable_mayavi2_interactive_gui: from enthought.mayavi.scripts import mayavi2 mayavi2.standalone(globals()) from enthought.mayavi import mlab # scalar cut plane plotting module stuff: import enthought.mayavi from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane epoch_ids = [0] # x class_groups = [0] # y probs = [0] # z styles = [0] # numbers used for coloring & glyph sizes used_final_classes = [] i_srcid = 0 for final_class in self.pars['interested_sci_classes']: if not finalclass_ordered_dict.has_key(final_class): continue # skip this science class since nothing to plot else: used_final_classes.append(final_class) srcid_sciclasses_list = finalclass_ordered_dict[final_class] for src_id,sci_classes in srcid_sciclasses_list: print 'src_id:', src_id, '\t', final_class sci_classes.generate_linearfit_endpoints_segments() i = 0 for class_name,class_dict in sci_classes.class_dict.iteritems(): class_style = self.sciclass_style_dict[class_name] if use_linfit_segments: for segment_dict in class_dict['linfit_segments']: epoch_ids.extend([segment_dict['epoch_ids'][0]]) class_groups.extend([i_srcid]) probs.extend([0]) styles.extend([0]) epoch_ids.extend(segment_dict['epoch_ids']) class_groups.extend([i_srcid]*len(segment_dict['epoch_ids'])) probs.extend(segment_dict['probs']) styles.extend([class_style]*len(segment_dict['epoch_ids'])) epoch_ids.extend([segment_dict['epoch_ids'][-1]]) class_groups.extend([i_srcid]) probs.extend([0]) styles.extend([0]) else: epoch_ids.extend([class_dict['epoch_ids'][0]]) class_groups.extend([i_srcid]) probs.extend([0]) styles.extend([0]) epoch_ids.extend(class_dict['epoch_ids']) class_groups.extend([i_srcid]*len(class_dict['epoch_ids'])) probs.extend(class_dict['probs']) styles.extend([class_style]*len(class_dict['epoch_ids'])) epoch_ids.extend([class_dict['epoch_ids'][-1]]) class_groups.extend([i_srcid]) probs.extend([0]) styles.extend([0]) i += 1 i_srcid += 3 # Y spacing between srcids within a science-class i_srcid += 20 # Y spacing between science-class groups mlab.plot3d(numpy.array(epoch_ids), numpy.array(class_groups), numpy.array(probs)*100.0, numpy.array(styles), colormap="Paired", tube_radius=1) # extent=[0,600, # 0,i_srcid, # 15, 110]) mlab.axes(xlabel='N of epochs', ylabel='science class', zlabel='% Prob.')#, # DEBUG/UPGRADE: These seem to trigger some bug about Actor methods: # extent=[0,600, # 0,i_srcid, # -10, 110]) title_str = "num_srcids=%d probability_cut=%0.2lf factor_threshold=%0.2lf bin_size=%d poly_order=%d" % (\ self.pars['num_srcids_to_retrieve_plot'], self.pars['sciclass_probability_cut'], self.pars['polyfit_factor_threshold'], self.pars['polyfit_bin_size'], self.pars['polyfit_poly_order']) ##### TITLE: # The 'z' is a flag in Mayavi2 v3.1.0 documentation: #mlab.text(0.01, 0.97, title_str, width=1.0, name='title', z=0.0) mlab.text(0.01, 0.97, title_str, width=1.0, name='title') ##### SCIENCE CLASS LABELS: # TODO: Eventually I would like the class labels to be colored and # placed on the y axis, but this requires: # 1) later mayavi version to allow 3D text positioning # 2) ability to match text color to the line color-map. if 1: used_final_classes.reverse() y = 0.95 for class_name in used_final_classes: class_str = "%2d %s" %(len(finalclass_ordered_dict[class_name]), class_name) mlab.text(0.85, y, class_str, width=0.095*(len(class_str)/20.0)) y -= 0.018 ##### Add a x-axis plane (I can't figure out code to make it opaque) if 0: cp = ScalarCutPlane() mayavi.add_module(cp) cp.implicit_plane._hideshow() # this un-displays the plane cp.implicit_plane.normal = 0,0,1 cp.implicit_plane.origin = 150,168,15 #cp.implicit_plane.position= 0.15 # feature not available yet print '##### cp:' cp.print_traits() print '##### cp.implicit_plane:' cp.implicit_plane.print_traits() print '##### cp.implicit_plane._HideShowAction:' cp.implicit_plane._HideShowAction.print_traits() ##### Camera position: if enable_mayavi2_interactive_gui: camera_distance = 600 else: camera_distance = 1200 enthought.mayavi.tools.camera.view(azimuth=50, elevation=70, # 0:looking down to -z distance=camera_distance, focalpoint=(100,(i_srcid*0.4),50)) #enthought.mayavi.mlab.show_pipeline() # this introspecive feature is not available in current mayavi version. #####If no Mayavi2 GUI, we allow user to resize image before saving file if not enable_mayavi2_interactive_gui: print 'Please resize window & Press a Key.' import curses stdscr = curses.initscr() while 1: c = stdscr.getch() break curses.endwin() ##### Save figure: img_fpath ="/tmp/%s%s.png" %(title_str.replace('=','').replace(' ','_'), self.pars['save_plot_image_suffix']) if os.path.exists(img_fpath): os.system('rm ' + img_fpath) mlab.savefig(img_fpath)#, size=(500,500))#, dpi=200) #size flag doesn't do anything print "Saved:", img_fpath
# ... and a sphere at the same location. mlab.quiver3d([my_x], [my_y - sphere_size / 4.], [my_z], [0], [1], [0], scalars=[1], scale_factor=sphere_size / 2., scale_mode='scalar', mode='sphere', line_width=lw * 0.75, name=gal, color=gals[gal]['col']) # Finally, add the galaxy name as 3D text. #mlab.text3d(my_x,my_y,my_z,'HCG91'+gal[-1],scale=20,color = (0,0,0)) mlab.text(my_x, my_y, 'HCG91' + gal[-1], color=(0, 0, 0), z=my_z, width=0.1) # Next, add peculiar HII regions of interest inside HCG 91c # (See Vogt+, MNRAS (2015) for details) # First, compute their coordinates coords_91c = [[ ratodeg(gals['hcg91c']['ra']), dectodeg(gals['hcg91c']['dec']), 0, 0 ]] coords_91c_plot = (np.array(coords_91c) - np.array([ramean, decmean, 0, 0])) * 3600. coords_91c_plot[0][0] *= np.cos(np.radians(decmin))
# ... and a sphere at the same location. mlab.quiver3d([my_x], [my_y - sphere_size/4.], [my_z], [0],[1],[0], scalars = [1], scale_factor = sphere_size/2., scale_mode = 'scalar', mode = 'sphere', line_width = lw*0.75, name = gal, color=gals[gal]['col']) # Finally, add the galaxy name as 3D text. #mlab.text3d(my_x,my_y,my_z,'HCG91'+gal[-1],scale=20,color = (0,0,0)) mlab.text(my_x,my_y,'HCG91'+gal[-1],color=(0,0,0),z=my_z,width=0.1) # Next, add peculiar HII regions of interest inside HCG 91c # (See Vogt+, MNRAS (2015) for details) # First, compute their coordinates coords_91c = [[ratodeg(gals['hcg91c']['ra']), dectodeg(gals['hcg91c']['dec']),0,0]] coords_91c_plot = (np.array(coords_91c)-np.array([ramean,decmean,0,0]))*3600. coords_91c_plot[0][0] *= np.cos(np.radians(decmin)) cube_size = 5 hx1 = coords_91c_plot[0][0] - 3.2 hx2 = coords_91c_plot[0][0] - 7.0 hx3 = coords_91c_plot[0][0] - 10.5
stars[:, 2] * 0.5 * astopc * 2, color=(0, 0, 0), scale_factor=1, name='Stars') # Now to make it look decent ... ax = mlab.axes(extent=[-10, 10, -12, 12, -7, 7], nb_labels=5) ax.axes.fly_mode = 'outer_edges' ax.title_text_property.font_size = 10 ax.title_text_property.font_family = 'courier' ax.label_text_property.font_family = 'courier' # And a bit of references if anyone is interested ... mlab.text( 0.05, 0.95, 'Oxygen-rich ejecta in SNR N132D. Vogt & Dopita, Ap&SS, 311, 521 (2011); Vogt & Shingles, Ap&SS (2013), submitted.', width=0.75) mlab.text(0.05, 0.05, '*****@*****.**', width=0.25) # Label the axes ... ax.axes.x_label = 'X (Dec.) [pc]' ax.axes.y_label = 'Y (R.A.) [pc]' ax.axes.z_label = 'Z [pc]' mlab.show() # Define the view point - useful to make a movie (not build here) ... mlab.view(90, 0, 60) # Save it all ... #mlab.savefig('Vogt+Shingles_test.wrl') #mlab.savefig('Vogt+Shingles_test.eps')
theta = arcsin(vlen(planenormal)/k_photon/2); ########################################## #angle between diffraction plane and surface theta1 = arccos(vlen(planenormal*array([0,0,1]))/vlen(planenormal)); phi1 = arctan(planenormal[1]/planenormal[0]); textwidth=0.005; ####################### # the surface x,y=mgrid[-100:101,-100:101]/100*a; z=x-x; mlab.mesh(x,y,z,opacity=0.5); text='film surface' mlab.text(1.1*a,0,'film surface',z=0,width=len(text)*textwidth) at.plot3d(text='(0,0,0)'); mlab.quiver3d([0],[0],[0],[0],[0],[1],mode='2ddash',color=(0,0,1),scale_mode="none",scale_factor=6); text='surface normal' mlab.text(0,0,text,z=1.1*c,width=len(text)*textwidth) ########################## # the diffraction plane plane_kx=planenormal[0]/planenormal[2]; plane_ky=planenormal[1]/planenormal[2]; z=-plane_kx*x-plane_ky*y; planenormal=planenormal/vlen(planenormal)*6; mlab.mesh(x,y,z,opacity=0.5);