class TitleEditorDemo(HasTraits): # Define the selection of titles that can be displayed: title = Enum('Select a new title from the drop down list below', 'This is the TitleEditor demonstration', 'Acme Widgets Sales for Each Quarter', 'This is Not Intended to be a Real Application') # A user settable version of the title: title_2 = Str('Type into the text field below to change this title') # A title driven by the result of a calculation: title_3 = Property(depends_on='value') # The number used to drive the calculation: value = Float() # Define the test view: view = View(VGroup( VGroup(HGroup( Item('title', show_label=False, springy=True, editor=TitleEditor())), Item('title'), show_border=True), VGroup(HGroup( Item('title_2', show_label=False, springy=True, editor=TitleEditor())), Item('title_2', label='Title'), show_border=True), VGroup(HGroup( Item('title_3', show_label=False, springy=True, editor=TitleEditor())), Item('value'), show_border=True)), width=0.4) #-- Property Implementations --------------------------------------------- @cached_property def _get_title_3(self): try: return ('The square root of %s is %s' % (self.value, self.value**0.5)) except: return ('The square root of %s is %si' % (self.value, (-self.value)**0.5))
class ParticleArrayHelper(HasTraits): """ This class manages a particle array and sets up the necessary plotting related information for it. """ # The particle array we manage. particle_array = Instance(ParticleArray) # The name of the particle array. name = Str # Current time. time = Float(0.0) # The active scalar to view. scalar = Str('rho', desc='name of the active scalar to view') # The mlab scalar plot for this particle array. plot = Instance(PipelineBase) # The mlab vectors plot for this particle array. plot_vectors = Instance(PipelineBase) # List of available scalars in the particle array. scalar_list = List(Str) scene = Instance(MlabSceneModel) # Sync'd trait with the scalar lut manager. show_legend = Bool(False, desc='if the scalar legend is to be displayed') # Show all scalars. list_all_scalars = Bool(False, desc='if all scalars should be listed') # Sync'd trait with the dataset to turn on/off visibility. visible = Bool(True, desc='if the particle array is to be displayed') # Show the time of the simulation on screen. show_time = Bool(False, desc='if the current time is displayed') # Edit the scalars. edit_scalars = Button('More options ...') # Show vectors. show_vectors = Bool(False, desc='if vectors should be displayed') vectors = Str('u, v, w', enter_set=True, auto_set=False, desc='the vectors to display') mask_on_ratio = Int(3, desc='mask one in specified points') scale_factor = Float(1.0, desc='scale factor for vectors', enter_set=True, auto_set=False) edit_vectors = Button('More options ...') # Private attribute to store the Text module. _text = Instance(PipelineBase) # Extra scalars to show. These will be added and saved to the data if # needed. extra_scalars = List(Str) # Set to True when the particle array is updated with a new property say. updated = Event ######################################## # View related code. view = View( Item(name='name', show_label=False, editor=TitleEditor()), Group(Group( Group( Item(name='visible'), Item(name='show_legend'), Item(name='scalar', editor=EnumEditor(name='scalar_list')), Item(name='list_all_scalars'), Item(name='show_time'), columns=2, ), Item(name='edit_scalars', show_label=False), label='Scalars', ), Group( Item(name='show_vectors'), Item(name='vectors'), Item(name='mask_on_ratio'), Item(name='scale_factor'), Item(name='edit_vectors', show_label=False), label='Vectors', ), layout='tabbed')) ####### Private protocol ############################################ def _add_vmag(self, pa): if 'vmag' not in pa.properties: if 'vmag2' in pa.output_property_arrays: vmag = numpy.sqrt(pa.vmag2) else: vmag = numpy.sqrt(pa.u**2 + pa.v**2 + pa.w**2) pa.add_property(name='vmag', data=vmag) if len(pa.output_property_arrays) > 0: # We do not call add_output_arrays when the default is empty # as if it is empty, all arrays are saved anyway. However, # adding just vmag in this case will mean that when the # particle array is saved it will only save vmag! This is # not what we want, hence we add vmag *only* if the # output_property_arrays is non-zero length. pa.add_output_arrays(['vmag']) self.updated = True def _get_scalar(self, pa, scalar): """Return the requested scalar from the given particle array. """ if scalar in self.extra_scalars: method_name = '_add_' + scalar method = getattr(self, method_name) method(pa) return getattr(pa, scalar) ####### Traits handlers ############################################# def _edit_scalars_fired(self): self.plot.edit_traits() def _edit_vectors_fired(self): self.plot_vectors.edit_traits() def _particle_array_changed(self, pa): self.name = pa.name self._list_all_scalars_changed(self.list_all_scalars) # Update the plot. x, y, z = pa.x, pa.y, pa.z s = self._get_scalar(pa, self.scalar) p = self.plot mlab = self.scene.mlab if p is None: src = mlab.pipeline.scalar_scatter(x, y, z, s) p = mlab.pipeline.glyph(src, mode='point', scale_mode='none') p.actor.property.point_size = 3 scm = p.module_manager.scalar_lut_manager scm.set(show_legend=self.show_legend, use_default_name=False, data_name=self.scalar) self.sync_trait('visible', p, mutual=True) self.sync_trait('show_legend', scm, mutual=True) #set_arrays(p.mlab_source.m_data, pa) self.plot = p else: if len(x) == len(p.mlab_source.x): p.mlab_source.set(x=x, y=y, z=z, scalars=s) else: p.mlab_source.reset(x=x, y=y, z=z, scalars=s) if self.plot_vectors: self._vectors_changed(self.vectors) # Setup the time. self._show_time_changed(self.show_time) def _scalar_changed(self, value): p = self.plot if p is not None: p.mlab_source.scalars = self._get_scalar(self.particle_array, value) p.module_manager.scalar_lut_manager.data_name = value def _list_all_scalars_changed(self, list_all_scalars): pa = self.particle_array if list_all_scalars: sc_list = pa.properties.keys() self.scalar_list = sorted(set(sc_list + self.extra_scalars)) else: if len(pa.output_property_arrays) > 0: self.scalar_list = sorted( set(pa.output_property_arrays + self.extra_scalars)) else: sc_list = pa.properties.keys() self.scalar_list = sorted(set(sc_list + self.extra_scalars)) def _show_time_changed(self, value): txt = self._text mlab = self.scene.mlab if value: if txt is not None: txt.visible = True elif self.plot is not None: mlab.get_engine().current_object = self.plot txt = mlab.text(0.01, 0.01, 'Time = 0.0', width=0.35) self._text = txt self._time_changed(self.time) else: if txt is not None: txt.visible = False def _vectors_changed(self, value): pa = self.particle_array comps = [x.strip() for x in value.split(',')] if len(comps) == 3: try: vec = [getattr(pa, x) for x in comps] except AttributeError: pass else: self.plot.mlab_source.set(vectors=numpy.c_[vec[0], vec[1], vec[2]]) def _show_vectors_changed(self, value): pv = self.plot_vectors if pv is not None: pv.visible = value else: self._vectors_changed(self.vectors) pv = self.scene.mlab.pipeline.vectors( self.plot.mlab_source.m_data, mask_points=self.mask_on_ratio, scale_factor=self.scale_factor) self.plot_vectors = pv def _mask_on_ratio_changed(self, value): pv = self.plot_vectors if pv is not None: pv.glyph.mask_points.on_ratio = value def _scale_factor_changed(self, value): pv = self.plot_vectors if pv is not None: pv.glyph.glyph.scale_factor = value def _time_changed(self, value): txt = self._text if txt is not None: txt.text = 'Time = %.3e' % (value) def _extra_scalars_default(self): return ['vmag']
class ModifyGraph(HasTraits): #visualization items scene = Instance(MlabSceneModel, ()) plot = Instance(PipelineBase) #control items Glyph_size=Range(low=.1, high=5.0, value=1) Tube_radius=Range(low=.1, high=5.0, value=1) Bound_size=Range(low=.1, high=5.0, value=1) Forground_color=Enum('Black','White','Red', 'Green', 'Blue', 'Yellow') Glyph_color=Enum('Black','White','Red', 'Green', 'Blue', 'Yellow') Tube_color=Enum('Black','White','Red', 'Green', 'Blue', 'Yellow') #edit items current_node=String() nodes_list=List(editor=ListEditor()) reset_nodes=Button(label='Reset') connect_nodes=Button(label='Add branch') remove_node=Button(label='Remove') save=Button(label='Save graph') #others colors={'Black':(0,0,0),'White':(1,1,1),'Red':(1,0,0), 'Green':(0,1,0), 'Blue':(0,0,1), 'Yellow':(1,1,0)} def __init__(self, G_, **traits): HasTraits.__init__(self, **traits) # Visualization self.G_=G_ self.G=None self.engine=None self.scn=None self.pipeline=None self.tube=None self.surface=None self.glyph=None self.glyph_points=None # points needed to render one glyph self.outline=None self.x, self.y, self.z= None, None, None self.node_id=None self.data=None self.nodes=None self.edges=None #parameters self.bound=3 self.bending_factor=40 self.connect_step=.1 self.n_new_nodes=0 ################## #Fuctions on scene ################## def clearScene(self): mlab.clf() mlab.close(self.scene) def update_selection(self): self.current_node=self.node_id self.nodes_list=self.nodes_list.append(self.node_id) def update_picker_opt(self): b=self.bound self.outline.outline_mode = 'full' self.outline.bounds = (self.x-b, self.x+b, self.y-b, self.y+b, self.z-b, self.z+b) def update_picker(self): if self.x and self.y and self.z: pass else: self.x, self.y, self.z= self.nodes[0] b=self.bound if self.outline: self.outline.bounds = (self.x-b, self.x+b, self.y-b, self.y+b, self.z-b, self.z+b) else: self.outline = mlab.outline(line_width=3, color=(0,0,0)) self.outline.outline_mode = 'full' self.outline.bounds = (self.x-b, self.x+b, self.y-b, self.y+b, self.z-b, self.z+b) self.update_selection() def update_data(self): self.nodes.reset() all_pos=[self.G.node[i]['pos'] for i in self.G.GetNodes()] self.nodes.from_array(all_pos) self.edges.reset() self.edges.from_array(np.array(self.G.edges())) self.pipeline.update() #################### # Functions on graph #################### def get_bezier(self, pnts): try: import bezier as bz except: print('To run this function, \'bezier\' sould be installed.') return #to well-bended curve v1=(pnts[1]-pnts[0])/np.linalg.norm(pnts[1]-pnts[0]) v2=(pnts[2]-pnts[3])/np.linalg.norm(pnts[2]-pnts[3]) pnts[1]=pnts[1]+self.bending_factor*v1 pnts[2]=pnts[2]+self.bending_factor*v2 x=pnts[:,0].tolist(); y=pnts[:,1].tolist(); z=pnts[:,2].tolist(); nodes = np.asfortranarray([x,y,z]) curve = bz.Curve(nodes, degree=2) stp=self.connect_step steps=np.arange(0+stp, 1-stp, stp) new_pnts=[] for i in steps: new_pnts.append(np.ravel(curve.evaluate(i))) return np.array(new_pnts) def add_branch4(self): #new_nodes pos=np.array([ self.G.node[i]['pos'] for i in list(self.nodes_list) ]) new_pos=self.get_bezier(pos) self.n_new_nodes=np.shape(new_pos)[0] new_nodes=range(len(self.nodes), len(self.nodes)+ self.n_new_nodes) #new_connections srt=self.nodes_list[1] end=self.nodes_list[-2] new_con=[[new_nodes[i], new_nodes[i+1]] for i in range(len(new_nodes)-1)] new_con.append([srt,new_nodes[0]]) new_con.append([new_nodes[-1],end]) #add nodes self.G.add_nodes_from(new_nodes) for idx, i in enumerate(new_nodes): self.G.node[i]['pos']=new_pos[idx] #add connectinos self.G.add_edges_from(new_con) #update visualization self.update_data() def add_branch2(self): #add connectinos self.G.add_edge(self.nodes_list[0], self.nodes_list[1]) #update visualization self.update_data() def add_branch(self): if len(self.nodes_list)==4: self.add_branch4() if len(self.nodes_list)==2: self.add_branch2() def rm_node(self): self.G.remove_node(self.node_id) self.G=fixG(self.G) self.update_data() def init_graph(self): if not self.G: self.G=self.G_.copy() # control call backes def _Glyph_size_changed(self): self.glyph.glyph.glyph_source.glyph_source.radius = self.Glyph_size # control call backes def _Bound_size_changed(self): self.bound = self.Bound_size self.update_picker_opt() def _Glyph_color_changed(self): self.glyph.actor.property.color=self.colors[self.Glyph_color] def _Tube_radius_changed(self): self.tube.filter.radius=self.Tube_radius def _Tube_color_changed(self): self.surface.actor.property.color=self.colors[self.Tube_color] # edit call backs def _reset_nodes_fired(self): self.nodes_list=[] def _connect_nodes_fired(self): self.add_branch() def _save_fired(self): dlg = FileDialog(action='save as') if dlg.open() == OK: if dlg.filename: #os.mkdir(dlg.filename) nx.write_pajek(self.G, dlg.directory+'/'+dlg.filename+'.pajek') def _remove_node_fired(self): self.rm_node() @on_trait_change('scene.activated') def update_plot(self): if self.plot is None: visG(self.G_, radius=.1, color=(0,0,1), gylph_r=1, gylph_c=(0,1,0)) self.init_graph() self.scene.scene.background = (1.0, 1.0, 1.0) self.engine=mlab.get_engine() self.scn=self.engine.scenes[1] self.pipeline=self.scn.children[0] self.tube=self.scn.children[0].children[1] self.surface=self.scn.children[0].children[1].children[0].children[0] self.glyph=self.scn.children[0].children[0].children[0] self.glyph_points = self.glyph.glyph.glyph_source.glyph_source.output.points.to_array() self.data=self.glyph.mlab_source.dataset self.nodes=self.data.points self.edges=self.data.lines self.figure=mlab.gcf(engine=self.engine) def picker_callback(picker): """ Picker callback: this get called when on pick events. """ if picker.actor in self.glyph.actor.actors: self.node_id = picker.point_id/self.glyph_points.shape[0] if self.node_id != -1: self.x, self.y, self.z = self.nodes[self.node_id] self.update_picker() self.picker = self.figure.on_mouse_pick(picker_callback) self.picker.tolerance = 0.01 self.update_picker() else: pass ############## # control tool ############## control_group= Group( Group( Item('Glyph_size'), Item('Glyph_color'), orientation='horizontal', layout='normal' ), Group( Item('Tube_radius'), Item('Tube_color'), orientation='horizontal', layout='normal' ), Group( Item('Bound_size'), orientation='horizontal', layout='normal' ), label='Control', layout='normal') ########### # edit tool ########### editing_group= Group( Group( Item('current_node', label='Current node', editor=TitleEditor()), Item('remove_node', show_label=False)), Group( Item('reset_nodes', show_label=False), Item('nodes_list', style='readonly', label='Selected nodes'), Item('connect_nodes', show_label=False), orientation='horizontal' ), Group('_', Item('save', show_label=False),'_'), label='Edit', orientation='vertical', layout='split',show_border = True, ) # The layout of the dialog created view = View( Group( Group(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=600, width=400, show_label=False)), Group(control_group, editing_group, layout='tabbed'), layout='split'), resizable=True, title = 'Nodes selection' )
class LiveSearch(HasTraits): # The currenty root directory being searched: root = Directory(getcwd(), entries=10) # Should sub directories be included in the search: recursive = Bool(True) # The file types to include in the search: file_type = Enum('Python', 'C', 'C++', 'Java', 'Ruby') # The current search string: search = Str() # Is the search case sensitive? case_sensitive = Bool(False) # The live search table filter: filter = Property # Instance( TableFilter ) # The current list of source files being searched: source_files = Property # List( SourceFile ) # The currently selected source file: selected = Any # Instance( SourceFile ) # The contents of the currently selected source file: selected_contents = Property # List( Str ) # The currently selected match: selected_match = Int() # The text line corresponding to the selected match: selected_line = Property # Int # The full name of the currently selected source file: selected_full_name = Property # File # The list of marked lines for the currently selected file: mark_lines = Property # List( Int ) # Summary of current number of files and matches: summary = Property # Str #-- Traits UI Views ------------------------------------------------------ view = View( VGroup( HGroup( Item('root', id='root', label='Path', width=0.5 ), Item('recursive'), Item('file_type', label='Type'), Item('search', id='search', width=0.5, editor=HistoryEditor(auto_set=True) ), Item('case_sensitive') ), VSplit( VGroup( Item('summary', editor=TitleEditor() ), Item('source_files', id='source_files', editor=table_editor ), dock='horizontal', show_labels=False ), VGroup( HGroup( Item('selected_full_name', editor=TitleEditor(), springy=True ), Item('selected_full_name', editor=DNDEditor(), tooltip='Drag this file' ), show_labels=False ), Item('selected_contents', style='readonly', editor=CodeEditor(mark_lines='mark_lines', line='selected_line', selected_line='selected_line') ), dock='horizontal', show_labels=False ), id='splitter' ) ), title='Live File Search', id='enthought.examples.demo.Advanced.' 'Table_editor_with_live_search_and_cell_editor.LiveSearch', width=0.75, height=0.67, resizable=True ) #-- Property Implementations --------------------------------------------- @property_depends_on('search, case_sensitive') def _get_filter(self): if len(self.search) == 0: return lambda x: True return lambda x: len(x.matches) > 0 @property_depends_on('root, recursive, file_type') def _get_source_files(self): root = self.root if root == '': root = getcwd() file_types = FileTypes[self.file_type] if self.recursive: result = [] for dir_path, dir_names, file_names in walk(root): for file_name in file_names: if splitext(file_name)[1] in file_types: result.append(SourceFile( live_search=self, full_name=join(dir_path, file_name))) return result return [SourceFile(live_search=self, full_name=join(root, file_name)) for file_name in listdir(root) if splitext(file_name)[1] in file_types] @property_depends_on('selected') def _get_selected_contents(self): if self.selected is None: return '' return ''.join(self.selected.contents) @property_depends_on('selected') def _get_mark_lines(self): if self.selected is None: return [] return [int(match.split(':', 1)[0]) for match in self.selected.matches] @property_depends_on('selected, selected_match') def _get_selected_line(self): selected = self.selected if (selected is None) or (len(selected.matches) == 0): return 1 return int(selected.matches[self.selected_match - 1 ].split(':', 1)[0]) @property_depends_on('selected') def _get_selected_full_name(self): if self.selected is None: return '' return self.selected.full_name @property_depends_on('source_files, search, case_sensitive') def _get_summary(self): source_files = self.source_files search = self.search if search == '': return 'A total of %d files.' % len(source_files) files = 0 matches = 0 for source_file in source_files: n = len(source_file.matches) if n > 0: files += 1 matches += n return 'A total of %d files with %d files containing %d matches.' % ( len(source_files), files, matches) #-- Traits Event Handlers ------------------------------------------------ def _selected_changed(self): self.selected_match = 1 def _source_files_changed(self): if len(self.source_files) > 0: self.selected = self.source_files[0] else: self.selected = None
class DataSourceWizardView(DataSourceWizard): #---------------------------------------------------------------------- # Private traits #---------------------------------------------------------------------- _top_label = Str('Describe your data') _info_text = Str('Array size do not match') _array_label = Str('Available arrays') _data_type_text = Str("What does your data represents?") _lines_text = Str("Connect the points with lines") _scalar_data_text = Str("Array giving the value of the scalars") _optional_scalar_data_text = Str("Associate scalars with the data points") _connectivity_text = Str("Array giving the triangles") _vector_data_text = Str("Associate vector components") _position_text = Property(depends_on="position_type_") _position_text_dict = { 'explicit': 'Coordinnates of the data points:', 'orthogonal grid': 'Position of the layers along each axis:', } def _get__position_text(self): return self._position_text_dict.get(self.position_type_, "") _shown_help_text = Str _data_sources_wrappers = Property(depends_on='data_sources') def _get__data_sources_wrappers(self): return [ ArrayColumnWrapper(name=name, shape=repr(self.data_sources[name].shape)) for name in self._data_sources_names ] # A traits pointing to the object, to play well with traitsUI _self = Instance(DataSourceWizard) _suitable_traits_view = Property(depends_on="data_type_") def _get__suitable_traits_view(self): return "_%s_data_view" % self.data_type_ ui = Any(False) _preview_button = Button(label='Preview structure') def __preview_button_fired(self): if self.ui: self.build_data_source() self.preview() _ok_button = Button(label='OK') def __ok_button_fired(self): if self.ui: self.ui.dispose() self.build_data_source() _cancel_button = Button(label='Cancel') def __cancel_button_fired(self): if self.ui: self.ui.dispose() _is_ok = Bool _is_not_ok = Bool def _anytrait_changed(self): """ Validates if the OK button is enabled. """ if self.ui: self._is_ok = self.check_arrays() self._is_not_ok = not self._is_ok _preview_window = Instance(PreviewWindow, ()) _info_image = Instance(ImageResource, ImageLibrary.image_resource('@std:alert16', )) #---------------------------------------------------------------------- # TraitsUI views #---------------------------------------------------------------------- _coordinates_group = \ HGroup( Item('position_x', label='x', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('position_y', label='y', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('position_z', label='z', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), ) _position_group = \ Group( Item('position_type'), Group( Item('_position_text', style='readonly', resizable=False, show_label=False), _coordinates_group, visible_when='not position_type_=="image data"', ), Group( Item('grid_shape_source_', label='Grid shape', editor=EnumEditor( name='_grid_shape_source_labels', invalid='_is_not_ok')), HGroup( spring, Item('grid_shape', style='custom', editor=ArrayEditor(width=-60), show_label=False), enabled_when='grid_shape_source==""', ), visible_when='position_type_=="image data"', ), label='Position of the data points', show_border=True, show_labels=False, ), _connectivity_group = \ Group( HGroup( Item('_connectivity_text', style='readonly', resizable=False), spring, Item('connectivity_triangles', editor=EnumEditor(name='_data_sources_names'), show_label=False, ), show_labels=False, ), label='Connectivity information', show_border=True, show_labels=False, enabled_when='position_type_=="explicit"', ), _scalar_data_group = \ Group( Item('_scalar_data_text', style='readonly', resizable=False, show_label=False), HGroup( spring, Item('scalar_data', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), show_labels=False, ), label='Scalar value', show_border=True, show_labels=False, ) _optional_scalar_data_group = \ Group( HGroup( 'has_scalar_data', Item('_optional_scalar_data_text', resizable=False, style='readonly'), show_labels=False, ), Item('_scalar_data_text', style='readonly', resizable=False, enabled_when='has_scalar_data', show_label=False), HGroup( spring, Item('scalar_data', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok'), enabled_when='has_scalar_data'), show_labels=False, ), label='Scalar data', show_border=True, show_labels=False, ), _vector_data_group = \ VGroup( HGroup( Item('vector_u', label='u', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_v', label='v', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_w', label='w', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), ), label='Vector data', show_border=True, ), _optional_vector_data_group = \ VGroup( HGroup( Item('has_vector_data', show_label=False), Item('_vector_data_text', style='readonly', resizable=False, show_label=False), ), HGroup( Item('vector_u', label='u', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_v', label='v', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_w', label='w', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), enabled_when='has_vector_data', ), label='Vector data', show_border=True, ), _array_view = \ View( Item('_array_label', editor=TitleEditor(), show_label=False), Group( Item('_data_sources_wrappers', editor=TabularEditor( adapter = ArrayColumnAdapter(), ), ), show_border=True, show_labels=False )) _questions_view = View( Item('_top_label', editor=TitleEditor(), show_label=False), HGroup( Item('_data_type_text', style='readonly', resizable=False), spring, 'data_type', spring, show_border=True, show_labels=False, ), HGroup( Item( '_self', style='custom', editor=InstanceEditor(view_name='_suitable_traits_view'), ), Group( # FIXME: Giving up on context sensitive help # because of lack of time. #Group( # Item('_shown_help_text', editor=HTMLEditor(), # width=300, # label='Help', # ), # show_labels=False, # label='Help', #), #Group( Item('_preview_button', enabled_when='_is_ok'), Item('_preview_window', style='custom', label='Preview structure'), show_labels=False, #label='Preview structure', #), #layout='tabbed', #dock='tab', ), show_labels=False, show_border=True, ), ) _point_data_view = \ View(Group( Group(_coordinates_group, label='Position of the data points', show_border=True, ), HGroup( 'lines', Item('_lines_text', style='readonly', resizable=False), label='Lines', show_labels=False, show_border=True, ), _optional_scalar_data_group, _optional_vector_data_group, # XXX: hack to have more vertical space Label('\n'), Label('\n'), Label('\n'), )) _surface_data_view = \ View(Group( _position_group, _connectivity_group, _optional_scalar_data_group, _optional_vector_data_group, )) _vector_data_view = \ View(Group( _vector_data_group, _position_group, _optional_scalar_data_group, )) _volumetric_data_view = \ View(Group( _scalar_data_group, _position_group, _optional_vector_data_group, )) _wizard_view = View( Group( HGroup( Item( '_self', style='custom', show_label=False, editor=InstanceEditor(view='_array_view'), width=0.17, ), '_', Item( '_self', style='custom', show_label=False, editor=InstanceEditor(view='_questions_view'), ), ), HGroup( Item('_info_image', editor=ImageEditor(), visible_when="_is_not_ok"), Item('_info_text', style='readonly', resizable=False, visible_when="_is_not_ok"), spring, '_cancel_button', Item('_ok_button', enabled_when='_is_ok'), show_labels=False, ), ), title='Import arrays', resizable=True, ) #---------------------------------------------------------------------- # Public interface #---------------------------------------------------------------------- def __init__(self, **traits): DataSourceFactory.__init__(self, **traits) self._self = self def view_wizard(self): """ Pops up the view of the wizard, and keeps the reference it to be able to close it. """ # FIXME: Workaround for traits bug in enabled_when self.position_type_ self.data_type_ self._suitable_traits_view self.grid_shape_source self._is_ok self.ui = self.edit_traits(view='_wizard_view') def preview(self): """ Display a preview of the data structure in the preview window. """ self._preview_window.clear() self._preview_window.add_source(self.data_source) data = lambda name: self.data_sources[name] g = Glyph() g.glyph.glyph_source.glyph_source = \ g.glyph.glyph_source.glyph_list[0] g.glyph.scale_mode = 'data_scaling_off' if not (self.has_vector_data or self.data_type_ == 'vector'): g.glyph.glyph_source.glyph_source.glyph_type = 'cross' g.actor.property.representation = 'points' g.actor.property.point_size = 3. self._preview_window.add_module(g) if not self.data_type_ in ('point', 'vector') or self.lines: s = Surface() s.actor.property.opacity = 0.3 self._preview_window.add_module(s) if not self.data_type_ == 'point': self._preview_window.add_filter(ExtractEdges()) s = Surface() s.actor.property.opacity = 0.2 self._preview_window.add_module(s)
class Lab(ASection): """ Defines a lab, which is a section of a tutorial with only Python code. This type of section might typically follow a lecture which introduced the code being worked on in the lab. """ # The set-up code (if any) for the lab: setup = Instance(CodeItem) # The list of code items for the lab: snippets = List(CodeItem) # The list of visible code items for the lab: visible_snippets = Property(depends_on='visible', cached=True) # The currently selected snippet: snippet = Instance(CodeItem) # Should normally hidden code items be shown? visible = Bool(False) # The dictionary containing the items from the Python code execution: values = Dict # The run Python code button: run = Button(image=ImageResource('run'), height_padding=1) # User error message: message = Str # The output produced while the program is running: output = Str # The current demo pane (if any): demo = Instance(DemoPane, ()) view = View(VSplit( VGroup( Item('visible_snippets', style='custom', show_label=False, editor=snippet_editor), HGroup( Item('run', style='custom', show_label=False, tooltip='Run the Python code'), '_', Item('message', springy=True, show_label=False, editor=TitleEditor()), '_', Item('visible', label='View hidden sections'), ), ), Tabbed( Item( 'values', id='values_1', label='Shell', editor=ShellEditor(share=True), dock='tab', export='DockWindowShell', ), Item( 'values', id='values_2', editor=ValueEditor(), dock='tab', export='DockWindowShell', ), Item( 'output', style='readonly', editor=CodeEditor(show_line_numbers=False, selected_color=0xFFFFFF), dock='tab', export='DockWindowShell', ), Item( 'demo', id='demo', style='custom', resizable=True, dock='tab', export='DockWindowShell', ), show_labels=False, ), id='splitter', ), id='enthought.tutor.lab', handler=LabHandler) def _run_changed(self): """ Runs the current set of snippet code. """ self.run_code() @cached_property def _get_visible_snippets(self): """ Returns the list of code items that are currently visible. """ if self.visible: return self.snippets return [snippet for snippet in self.snippets if (not snippet.hidden)] def run_code(self): """ Runs all of the code snippets associated with the section. """ # Reconstruct the lab code from the current set of code snippets: start_line = 1 module = '' for snippet in self.snippets: snippet.start_line = start_line module = '%s\n\n%s' % (module, snippet.content) start_line += (snippet.content.count('\n') + 2) # Reset any syntax error and message log values: self.message = self.output = '' # Redirect standard out and error to the message log: stdout, stderr = sys.stdout, sys.stderr sys.stdout = sys.stderr = StdOut(self) try: try: # Get the execution context dictionary: values = self.values # Clear out any special variables defined by the last run: for name in ('demo', 'popup'): if isinstance(values.get(name), HasTraits): del values[name] # Execute the current lab code: exec module[2:] in values, values # fixme: Hack trying to update the Traits UI view of the dict. self.values = {} self.values = values # Handle a 'demo' value being defined: demo = values.get('demo') if not isinstance(demo, HasTraits): demo = NoDemo() self.demo.demo = demo # Handle a 'popup' value being defined: popup = values.get('popup') if isinstance(popup, HasTraits): popup.edit_traits(kind='livemodal') except SyntaxError, excp: # Convert the line number of the syntax error from one in the # composite module to one in the appropriate code snippet: line = excp.lineno if line is not None: snippet = self.snippets[0] for s in self.snippets: if s.start_line > line: break snippet = s line -= (snippet.start_line - 1) # Highlight the line in error: snippet.selected_line = line # Select the correct code snippet: self.snippet = snippet # Display the syntax error message: self.message = '%s in column %s of line %s' % ( excp.msg.capitalize(), excp.offset, line) else: # Display the syntax error message without line # info: self.message = excp.msg.capitalize() except: import traceback traceback.print_exc() finally:
class Lesson(Lab): """ Defines a lesson, which is a section of a tutorial with both descriptive information and associated Python code. """ # The list of descriptive items for the lesson: descriptions = List(ATutorialItem) view = View( HSplit( Item( 'descriptions', label='Lesson', style='custom', show_label=False, dock='horizontal', editor=list_editor, ), VSplit( VGroup( Item( 'visible_snippets', style='custom', show_label=False, editor=snippet_editor, ), HGroup( Item( 'run', style='custom', show_label=False, tooltip='Run the Python code', ), '_', Item( 'message', springy=True, show_label=False, editor=TitleEditor(), ), '_', Item( 'visible', label='View hidden sections', ), ), label='Lab', dock='horizontal', ), Tabbed( Item( 'values', id='values_1', label='Shell', editor=ShellEditor(share=True), dock='tab', export='DockWindowShell', ), Item( 'values', id='values_2', editor=ValueEditor(), dock='tab', export='DockWindowShell', ), Item( 'output', style='readonly', editor=CodeEditor(show_line_numbers=False, selected_color=0xFFFFFF), dock='tab', export='DockWindowShell', ), Item( 'demo', id='demo', style='custom', resizable=True, dock='tab', export='DockWindowShell', ), show_labels=False, ), label='Lab', dock='horizontal', ), id='splitter', ), id='enthought.tutor.lesson', handler=LabHandler, )
class Tutor(HasPrivateTraits): """ The main tutorial class which manages the presentation and navigation of the entire tutorial. """ # The path to the files distributed with the tutor: home = Directory # The path to the root of the tutorial tree: path = Directory # The root of the tutorial lesson tree: root = Instance(ASection) # The current section of the tutorial being displayed: section = Instance(ASection) # The next section: next_section = Property(depends_on='section', cached=True) # The previous section: previous_section = Property(depends_on='section', cached=True) # The previous section button: previous = Button(image=ImageResource('previous'), height_padding=1) # The next section button: next = Button(image=ImageResource('next'), height_padding=1) # The parent section button: parent = Button(image=ImageResource('parent'), height_padding=1) # The reload tutor button: reload = Button(image=ImageResource('reload'), height_padding=1) # The title of the current session: title = Property(depends_on='section') view = View( VGroup( HGroup( Item( 'previous', style='custom', enabled_when='previous_section is not None', tooltip='Go to previous section', ), Item( 'parent', style='custom', enabled_when='(section is not None) and ' '(section.parent is not None)', tooltip='Go up one level', ), Item( 'next', style='custom', enabled_when='next_section is not None', tooltip='Go to next section', ), '_', Item( 'title', springy=True, editor=TitleEditor(), ), '_', Item( 'reload', style='custom', tooltip='Reload the tutorial', ), show_labels=False, ), '_', HSplit( Item( 'root', label='Table of Contents', editor=tree_editor, dock='horizontal', export='DockWindowShell', ), Item( 'section', id='section', label='Current Lesson', style='custom', resizable=True, dock='horizontal', ), id='splitter', show_labels=False, )), title='Python Tutor', id='dmorrill.tutor.tutor:1.0', buttons=NoButtons, resizable=True, width=0.8, height=0.8, ) def _path_changed(self, path): """ Handles the tutorial root path being changed. """ self.init_tutor() def _next_changed(self): """ Displays the next tutorial section. """ self.section = self.next_section def _previous_changed(self): """ Displays the previous tutorial section. """ self.section = self.previous_section def _parent_changed(self): """ Displays the parent of the current tutorial section. """ self.section = self.section.parent def _reload_changed(self): """ Reloads the tutor from the original path specified. """ self.init_tutor() @cached_property def _get_next_section(self): """ Returns the next section of the tutorial. """ next = None section = self.section if len(section.subsections) > 0: next = section.subsections[0] else: parent = section.parent while parent is not None: index = parent.subsections.index(section) if index < (len(parent.subsections) - 1): next = parent.subsections[index + 1] break parent, section = parent.parent, parent return next @cached_property def _get_previous_section(self): """ Returns the previous section of the tutorial. """ previous = None section = self.section parent = section.parent if parent is not None: index = parent.subsections.index(section) if index > 0: previous = parent.subsections[index - 1] while len(previous.subsections) > 0: previous = previous.subsections[-1] else: previous = parent return previous def _get_title(self): """ Returns the title of the current section. """ section = self.section if section is None: return '' return ('%s: %s' % (section.__class__.__name__, section.title)) def init_tutor(self): """ Initials the tutor by creating the root section from the specified path. """ path = self.path title = title_for(os.path.splitext(os.path.basename(path))[0]) section = SectionFactory(title=title).trait_set(path=path).section if section is not None: self.section = self.root = section
class FileSieve ( HasPrivateTraits ): # The name of the plugin: name = Str( 'File Sieve' ) # The persistence id for this object: id = Str( 'etsdevtools.developer.tools.file_sieve.state', save_state_id = True ) # The path specifying the files to be listed: path = Directory( save_state = True, connect = 'to: path to sieve' ) # Base path (in normalized form): base_path = Str # Extension to match on: ext = Str # The list of files containing in the specified path: files = List( File ) # The list of currently selected files: selected = List( File ) # The list of selected file names: selected_files = Property( depends_on = 'selected', connect = 'from: selected file names' ) # The filter used to 'sieve' the list of files: filter = Instance( FileFilter, () ) # Select all listed files button: select_all = Button( 'Select All' ) # The indices of the table items currently passing the table filter: filtered_indices = List( Int ) # The list of filtered file names: filtered_files = Property( depends_on = 'filtered_indices', connect = 'from: filtered file names' ) # The total number of files being displayed: num_files = Property( depends_on = 'filtered_indices' ) # The total size of all filtered files: size = Property( depends_on = 'filtered_indices' ) # Should subdirectories of the path be included? recursive = Bool( True ) # The current file worker thread object we are using: worker = Instance( FileWorker ) #-- Traits View Definitions ------------------------------------------------ view = View( VSplit( Item( 'path', id = 'path', editor = DirectoryEditor( entries = 10 ), dock = 'vertical' ), HGroup( Item( 'filter', show_label = False, style = 'custom' ), # '_', # Item( 'recursive' ), spring, '_', Item( 'num_files', label = 'Files', style = 'readonly', format_func = commatize, width = -40 ), '_', Item( 'size', style = 'readonly', format_func = commatize, width = -70 ), '_', Item( 'select_all', show_label = False, enabled_when = 'len( files ) > 0' ), dock = 'vertical' ), VGroup( HGroup( Item( 'base_path', label = 'Path', editor = TitleEditor(), springy = True ), '_', Item( 'ext', editor = TitleEditor() ) ), Item( 'files', id = 'files', editor = files_table_editor ), dock = 'horizontal', show_labels = False ), id = 'splitter', ), title = 'File Sieve', id = 'etsdevtools.developer.tools.file_sieve.FileSieve', width = 0.6, height = 0.7, resizable = True, handler = FileSieveHandler ) #-- Property Implementations ----------------------------------------------- def _get_num_files ( self ): return len( self.filtered_indices ) @cached_property def _get_size ( self ): files = self.files return reduce( lambda l, r: l + files[r].size, self.filtered_indices, 0L ) @cached_property def _get_selected_files ( self ): return [ file.path for file in self.selected ] @cached_property def _get_filtered_files ( self ): files = self.files return [ files[i].path for i in self.filtered_indices ] #-- Event Handlers --------------------------------------------------------- def _path_changed ( self, path ): """ Handles the 'path' trait being changed. """ # Make sure the path has been normalized: path = abspath( path ) # Determine the correct starting directory and optional file extension # to match on: ext = '' if not isdir( path ): path, name = split( path ) if not isdir( path ): del self.files[:] return root, ext = splitext( name ) self.base_path = path self.ext = ext if self.worker is not None: self.worker.abort = True self.worker = FileWorker( sieve = self, ext = ext ).set( path = path ) def _select_all_changed ( self ): """ Handles the 'Select All' button being pressed. """ files = self.files self.selected = [ files[i] for i in self.filtered_indices ] def _recursive_changed ( self, recursive ): """ Handles the 'recursive' trait being changed.
class LiveSearch ( HasTraits ): """ Searches for files in operating system. Adapted heavily from traits examples.""" #THIS DICTSTRINGLIST CAN BE OVERWRITTEN AT ANY TIME AND THE PROGRAM WILL NOT FAULTER, MEANING CUSTOM FILE SEARCHES ARE POSSIBLE ValidTypes =DictStrList({ # 'Python': [ '.py' ], 'Sopra': [ '.nk'], 'XNK': [ '.txt', '.dat' ], #CAN EDIT MODULE WHICH CONTROLS THIS TO ADD "ANY" OPTION, OR MAYBE FILTER = NONE OPTION 'XNK_csv': ['.csv'] # 'Java': [ '.java' ], # 'Ruby': [ '.rb' ] }) #A list of the keys in ValidTypes, basically a list of searchable types 'Python' vs. 'Java' types_list=Property(List, depends_on='ValidTypes') # Enumerated list of the above list (Allows user to select based on types_name) type_range = Enum(values='types_list') # The currenty root directory being searched: root = Directory( getcwd(), entries = 10 ) # Should sub directories be included in the search: recursive = Bool( False ) # The current search string: search = Str() # Is the search case sensitive? case_sensitive = Bool( False ) # The live search table filter: filter = Property # Instance( TableFilter ) # The current list of source files being searched: source_files = Property # List( SourceFile ) # The current list of items which are deposited for return by the user my_files = List # The currently selected source file: selected = Any # Instance( SourceFile ) # The currently selected stored file: selected_file=Any# Instance( SourceFile) # The currently selected match: selected_match = Int # source_summary of current number of files and matches: source_summary = Property # Str # selected_summary of current number of selected files and matches: selected_summary = Property # Str # Button to add files from source list to return list Add=Button AddAll=Button RemoveAll=Button Remove=Button #-- Traits UI Views -------------------------------------------------------- view = View( VGroup( HGroup( Item( 'root', #Directory id = 'root', label = 'Path', width = 0.5 ), Item( 'recursive' ), Item( 'type_range', label = 'Type' ), #HERE IS FILE TYPE # COMMENTED OUT STRING SEARCH, DONT DELETE THIS LETS ME SEARCH FILES # MUST ALSO UNCOMMENT 2 METHODS AT END OF FILE # Item( 'search', # id = 'search', # width = 0.5, # label = 'Search for infile string', # editor = HistoryEditor( auto_set = True ) # ), # Item( 'case_sensitive' ) ), VSplit( VGroup( HGroup( VGroup( Item( 'source_summary', editor = TitleEditor(), show_label=False ), Item( 'source_files', id = 'source_files', editor = source_editor, show_label=False), HGroup( Item('Add', label='Deposit Selected', show_label=False), Item('AddAll', label='Deposit All', show_label=False) ) ), VGroup( Item( 'selected_summary', editor = TitleEditor(), show_label=False ), Item( 'my_files', editor=file_editor, show_label=False), HGroup( Item('Remove', label='Remove Selected', show_label=False, enabled_when='len(my_files) > 0'), Item('RemoveAll', label='Remove All Stored', show_label=False, enabled_when='len(my_files) > 0') ) ), ), ), dock = 'horizontal', show_labels = False ), ), title = 'Live File Search', id = 'File Search Mod', width = 0.75, height = 0.67, resizable = True, buttons=OKCancelButtons #Why don't these work on small button operations ) # Button Events # ------------- def _Add_fired(self): for afile in self.selected: if afile not in self.my_files: self.my_files.append(afile) def _AddAll_fired(self): """ Add all files in a directory possibly. Can add a lot of files, so instead of appending one by one, add them all at once to avoid over-triggering event handlers in modeltree_v2.py, which will update a dictionary every single time something in here changes. """ new = [] for afile in self.source_files: if afile not in self.my_files: new.append(afile) self.my_files.extend(new) def _Remove_fired(self): for afile in self.selected_file: #Since multi rows, this is a list, even when selected on object self.my_files.remove(afile) #Selected_file is the variable for all selections on file table def _RemoveAll_fired(self): self.my_files=[] #-- Property Implementations ----------------------------------------------- def _get_types_list(self): return self.ValidTypes.keys() @property_depends_on( 'search, case_sensitive' ) def _get_filter ( self ): if len( self.search ) == 0: return lambda x: True return lambda x: len( x.matches ) > 0 @property_depends_on( 'root, recursive, type_range' ) def _get_source_files ( self ): """FIND THE SOURCE FILES populates with a list of source_files""" root = self.root if root == '': root = getcwd() valid_extensions = self.ValidTypes[ self.type_range ] #TYPE_RANGES=EXTENSIONS. type_range=filenames if self.recursive: result = [] for dir_path, dir_names, file_names in walk( root ): for file_name in file_names: extension=splitext(file_name)[1] if extension in valid_extensions: result.append( SourceFile( live_search = self, full_name = join( dir_path, file_name ), file_ext = extension) #File class set automatically ) return result return [ SourceFile( live_search = self, full_name = join( root, file_name ) ) for file_name in listdir( root ) if splitext( file_name )[1] in valid_extensions ] @property_depends_on( 'source_files, search, case_sensitive' ) def _get_source_summary ( self ): source_files = self.source_files search = self.search if search == '': return 'A total of %d files found.' % len( source_files ) @property_depends_on('my_files') def _get_selected_summary ( self ): return 'A total of %d files have been selected.' %(len(self.my_files) ) #-- Traits Event Handlers -------------------------------------------------- def _selected_changed ( self ): self.selected_match = 1 def _source_files_changed ( self ): if len( self.source_files ) > 0: self.selected = self.source_files[0] else: self.selected = None
class TTitle ( Item ): show_label = Constant( False ) editor = TitleEditor()
point (a 3-vector). """ p1 = numpy.asarray(p1).reshape(-1,1) p2 = numpy.asarray(p2).reshape(-1,1) max_length = ((p1-p2)**2).sum(axis=0)[0] nearest = self.intersect(p1, p2, max_length)[0] return nearest['length'], nearest['cell'], nearest['point'] def update_complete(self): pass OrientationEditor = RangeEditor(low=-180.0, high=180.0, mode='slider') Traceable.uigroup = VGroup( Item('name', editor=TitleEditor(), springy=False, show_label=False), Item('display'), VGroup( Item('orientation', editor=OrientationEditor), Item('elevation', editor=OrientationEditor), Item('rotation', editor=OrientationEditor), ), HGroup(Item('centre', show_label=False, editor=VectorEditor, springy=True), show_border=True, label="Centre"), HGroup( VGroup(