class MultiSelect ( HasPrivateTraits ): choices = List( Str ) selected = List( Str ) view = View( HGroup( Item( 'choices', show_label = False, editor = TabularEditor( show_titles = False, selected = 'selected', editable = False, multi_select = True, adapter = MultiSelectAdapter() ) ), Item( 'selected', show_label = False, editor = TabularEditor( show_titles = False, editable = False, adapter = MultiSelectAdapter() ) ) ) )
class NBSNetworkParameter(HasTraits): choices1 = List(Str) selected1 = List(Str) choices2 = List(Str) selected2 = List(Str) view = View( HGroup( Group(HGroup( Item('choices1', show_label=False, editor=TabularEditor(show_titles=False, selected='selected1', editable=False, multi_select=True, adapter=MultiSelectAdapter())), Item('selected1', show_label=False, editor=TabularEditor(show_titles=False, editable=False, adapter=MultiSelectAdapter())), ), label="First group"), Group(HGroup( Item('choices2', show_label=False, editor=TabularEditor(show_titles=False, selected='selected2', editable=False, multi_select=True, adapter=MultiSelectAdapter())), Item('selected2', show_label=False, editor=TabularEditor(show_titles=False, editable=False, adapter=MultiSelectAdapter())), ), label="Second group"), ), title='Select networks', width=0.5, height=0.5, buttons=['OK'], resizable=True, ) def __init__(self, cfile, **traits): super(NBSNetworkParameter, self).__init__(**traits) li = [] for cobj in cfile.connectome_network: li.append(cobj.obj.name) self.choices1 = li self.choices2 = li
class OutputSystemViewer(HasTraits): num_outputs = Property(Int(1), depends_on='runoutput.eigenmodes') @cached_property def _get_num_outputs(self): ret = len(self.runoutput.eigenmodes) #print 'num_outputs', ret return ret run_number = Int(1) #Range(low=1, high='num_outputs') runoutput = Instance(RunOutput) modes = Property(List(EigenMode), depends_on='runoutput.eigenmodes,run_number') @cached_property def _get_modes(self): return self.runoutput.eigenmodes[self.run_number - 1] modes_array = Property(Array(numpy.complex), depends_on='modes') @cached_property def _get_modes_array(self): ret = numpy.empty((len(self.modes), 13), dtype='complex') for i, mode in enumerate(self.modes): ret[i, 0] = mode.eigenvalue #.real #ret[i,1] = mode.eigenvalue.imag ret[i, 1:] = mode.eigenvector #print mode.eigenvector return ret matrix = Property(Instance(EigenMatrix), depends_on='runoutput.eigenmatrix,run_number') @cached_property def _get_matrix(self): #print len(self.runoutput.eigenmatrix) return self.runoutput.eigenmatrix[self.run_number - 1] view = View(Item('run_number', editor=RangeEditor(mode='spinner')), Group( Item('modes_array', editor=TabularEditor(adapter=ModesAdapter(), operations=[], editable=False), show_label=False), Item('object.matrix.matrix', editor=TabularEditor(adapter=EigenMatrixAdapter(), operations=[], editable=False), show_label=False)), resizable=True)
class _StringListEditor(UIEditor): # Indicate that the editor is scrollable/resizable: scrollable = True # The list of available editor choices: choices = List(Str) # The list of currently selected items: selected = List(Str) # The traits UI view used by the editor: view = View(Item('choices', show_label=False, editor=TabularEditor(show_titles=False, selected='selected', editable=False, multi_select=True, adapter=MultiSelectAdapter())), id='string_list_editor', resizable=True) def init_ui(self, parent): self.sync_value(self.factory.choices, 'choices', 'from', is_list=True) self.selected = self.value return self.edit_traits(parent=parent, kind='subpanel') @on_trait_change(' selected') def _selected_modified(self): self.value = self.selected
class Company(HasTraits): employees = List(Employee) employee = Instance(Employee) increase = Float give_raise = Button('Give raise') view = View(Item('employees', show_label=False, editor=TabularEditor(adapter=EmployeeAdapter(), selected='employee', auto_update=True)), HGroup( spring, Item('increase'), Item('give_raise', show_label=False, enabled_when='employee is not None')), title='Auto Update Tabular Editor demo', height=0.25, width=0.30, resizable=True) def _give_raise_changed(self): self.employee.salary += self.increase self.employee = None
def _tabular_editor_default(self): class ArrayAdapter(TabularAdapter): columns = [(n, i) for i, n in enumerate(self.model.names)] font = 'Courier 10' alignment = 'right' format = '%s' return TabularEditor(adapter=ArrayAdapter())
class ShowArray ( HasTraits ): data = Array view = View( Item( 'data', show_label = False, style = 'readonly', editor = TabularEditor( adapter = ArrayAdapter() ) ), title = 'Array Viewer', width = 0.3, height = 0.8, resizable = True )
class OutputVariablesViewer(HasTraits): runoutput = Instance(RunOutput) save_data = Button('') def _save_data_fired(self): filename = get_file_from_user() if filename: f = open(filename, 'w') self.runoutput.save_variables(f) f.close() view = View(Item('save_data', show_label=False), Item('object.runoutput.variable_values', editor=TabularEditor(adapter=OutputVariablesAdapter(), operations=[], editable=False), show_label=False), resizable=True)
MarriedPerson_spouse_text = Property Person_spouse_text = Constant( '' ) def _get_MarriedPerson_age_image ( self ): if self.item.age < 18: return 'red_flag' return None def _get_MarriedPerson_spouse_text ( self ): return self.item.partner.name #--[Tabular Editor Definition]-------------------------------------------------- tabular_editor = TabularEditor( adapter = ReportAdapter(), operations = [ 'move' ], images = [ ImageResource( 'red_flag', search_path = search_path ) ], ) #--[Report Class]--------------------------------------------------------------- class Report ( HasTraits ): people = List( Person ) view = View( Group( Item( 'people', id = 'table', editor = tabular_editor ), show_labels = False, ), title = 'Tabular Editor Demo',
class Demo(HasTraits): plot = Instance(Component) fileName = "clusters.cpickle" case = List(UncertaintyValue) cases = {} defaultCase = [] # Attributes to use for the plot view. size = (400, 1600) traits_view = View(Group( Group(Item('plot', editor=ComponentEditor(size=size), show_label=False), orientation="vertical", show_border=True, scrollable=True), Group(Item('case', editor=TabularEditor(adapter=CaseAdapter(can_edit=False)), show_label=False), orientation="vertical", show_border=True), layout='split', orientation='horizontal'), title='Interactive Lines', resizable=True) def setFileName(self, newName): self.fileName = newName def _update_case(self, name): if name: self.case = self.cases.get(name) else: self.case = self.defaultCase def _plot_default(self): #load the data to visualize. # it is a list of data in the 'results' format, each belonging to a cluster - gonenc resultsList = cPickle.load(open(self.fileName, 'r')) #get the names of the outcomes to display outcome = [] for entry in resultsList: a = entry[0][1].keys() outcome.append(a[0]) # outcome = resultsList[0][0][1].keys() # pop the time axis from the list of outcomes # outcome.pop(outcome.index('TIME')) x = resultsList[0][0][1]['TIME'] # the list and number of features (clustering related) stored regarding each run features = resultsList[0][0][0][0].keys() noFeatures = len(features) # Iterate over each cluster to prepare the cases corresponding to indivisdual runs in # each cluster plot. Each case is labeled as, e.g., y1-2 (3rd run in the 2nd cluster) - gonenc for c, results in enumerate(resultsList): for j, aCase in enumerate(results): aCase = [ UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items() ] self.cases['y' + str(c) + '-' + str(j)] = aCase # for j, aCase in enumerate(results): # aCase = [UncertaintyValue(name="blaat", value=aCase[0][0])] # self.cases['y'+str(j)] = aCase #make an empty case for default. #if you have multiple datafields associated with a run, iterate over #the keys of a dictionary of a case, instead of over lenght(2) case = [] for i in range(noFeatures): case.append(UncertaintyValue(name='Default', value='None')) self.case = case self.defaultCase = case # Create some x-y data series to plot pds = [] # enumerate over the results of all clusters for c, results in enumerate(resultsList): pd = ArrayPlotData(index=x) for j in range(len(results)): data = np.array(results[j][1].get(outcome[c])) print "y" + str(c) + '-' + str(j) pd.set_data("y" + str(c) + '-' + str(j), data) pds.append(pd) # Create a container and add our plots container = GridContainer(bgcolor="lightgray", use_backbuffer=True, shape=(len(resultsList), 1)) #plot data tools = [] for c, results in enumerate(resultsList): pd1 = pds[c] # Create some line plots of some of the data plot = Plot(pd1, title='Cluster ' + str(c), border_visible=True, border_width=1) plot.legend.visible = False #plot the results for i in range(len(results)): plotvalue = "y" + str(c) + '-' + str(i) print plotvalue color = colors[i % len(colors)] plot.plot(("index", plotvalue), name=plotvalue, color=color) #make sure that the time axis runs in the right direction for value in plot.plots.values(): for entry in value: entry.index.sort_order = 'ascending' # Attach the selector tools to the plot selectorTool1 = LineSelectorTool(component=plot) plot.tools.append(selectorTool1) tools.append(selectorTool1) # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) container.add(plot) #make sure the selector tools knows the main screen for tool in tools: tool._demo = self return container
print "Save to ASCII" pass @on_trait_change("active_row") def go_to(self): print "Going to mark", self.markers[ self.active_row].name, "at", self.markers[self.active_row].t traits_view = View( Group( VGroup( Item("record_mark", show_label=True, label="Record marks:"), Item("name_new", show_label=True, label="Name for new marks:"), ), Item( 'markers', id='table', editor=TabularEditor( adapter=MarkerlistAdapter(), operations=['delete'], multi_select=True, activated="goto_marker", activated_row="active_row", dclicked="goto_marker", editable=False #images = [ ImageResource( 'red_flag', search_path = search_path ) ] )), show_labels=False), toolbar=toolbar, )
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)
index_image = Property def _get_index_text(self): return str(self.row) def _get_index_image(self): x, y, z = self.item if sqrt((x - 0.5)**2 + (y - 0.5)**2 + (z - 0.5)**2) <= 0.25: return 'red_flag' return None #--[Tabular Editor Definition]-------------------------------------------------- tabular_editor = TabularEditor( adapter=ArrayAdapter(), images=[ImageResource('red_flag', search_path=search_path)]) #--[ShowArray Class]------------------------------------------------------------ class ShowArray(HasTraits): data = Array view = View(Item('data', editor=tabular_editor, show_label=False), title='Array Viewer', width=0.3, height=0.8, resizable=True, buttons=NoButtons)
Person_spouse_text = Constant('') def _get_MarriedPerson_age_image(self): if self.item.age < 18: return '@icons:red_ball' return None def _get_MarriedPerson_spouse_text(self): return self.item.partner.name #-- Tabular Editor Definition -------------------------------------------------- tabular_editor = TabularEditor( adapter=ReportAdapter(), operations=['move'], ) #-- Report Class Definition ---------------------------------------------------- class Report(HasTraits): people = List(Person) view = View(Group(Item('people', id='table', editor=tabular_editor), show_labels=False), title='Tabular Editor Demo', id='enthought.traits.ui.demo.Applications.tabular_editor_demo', width=0.60, height=0.75,
big_width = Float( 18 ) big_image = Property def _get_big_image ( self ): size = self.item.size if size > 65536: return 'red_ball' return ( None, 'blue_ball' )[ size > 16384 ] #--[Tabular Editor Definition]-------------------------------------------------- tabular_editor = TabularEditor( editable = False, selected = 'file_info', adapter = FileInfoAdapter(), operations = [], images = [ ImageResource( 'blue_ball', search_path = search_path ), ImageResource( 'red_ball', search_path = search_path ) ] ) #--[PythonBrowser Class]-------------------------------------------------------- class PythonBrowser ( HasPrivateTraits ): dir = Directory files = List( FileInfo ) file_info = Instance( FileInfo ) code = Code view = View( HSplit(
class Variables(HasTraits): vars_pool = {} vars_list = List() vars_table_list = List( ) # a list version of vars_pool maintained for the TabularEditor vars_table_list_update_time = Float(0) sample_number = Int(0) sample_count = Int(0) max_samples = Int(20000) start_time = time.time() add_var_event = Event() expressions = List() vars_table_update = Bool(True) clear_button = Button('Clear') view = View(HSplit( Item(name='clear_button', show_label=False), Item(name='max_samples', label='Max samples'), Item(name='sample_count', label='Samples'), Item(name='vars_table_update', label='Update variables view')), Item(name='vars_table_list', editor=TabularEditor(adapter=VariableTableAdapter(), editable=False, dclicked="add_var_event"), resizable=True, show_label=False), title='Variable view', resizable=True, width=.7, height=.2) def new_expression(self, expr): new_expression = Expression(self, expr) self.expressions.append(new_expression) return new_expression def update_variables(self, data_dict): """ Receive a dict of variables from a decoder and integrate them into our global variable pool. """ self.sample_number += 1 # We update into a new dict rather than vars_pool due to pythons pass by reference # behaviour, we need a fresh object to put on our array new_vars_pool = {} new_vars_pool.update(self.vars_pool) new_vars_pool.update(data_dict) new_vars_pool.update({ 'sample_num': self.sample_number, 'system_time': time.time(), 'time': time.time() - self.start_time }) if '' in new_vars_pool: del new_vars_pool[''] # weed out undesirables self.vars_list.append(new_vars_pool) self.update_vars_list() def update_vars_list(self): self.vars_pool = self.vars_list[-1] if time.time() - self.vars_table_list_update_time > 0.2: self.vars_table_list_update_time = time.time() self.update_vars_table() self.sample_count = len(self.vars_list) if self.sample_count > self.max_samples: self.vars_list = self.vars_list[-self.max_samples:] self.sample_count = self.max_samples @on_trait_change('clear_button') def clear(self): """ Clear all recorded data. """ self.sample_number = 0 self.vars_list = [{}] self.update_vars_list() self.update_vars_table() self.start_time = time.time() for expression in self.expressions: expression.clear_cache() def save_data_set(self, filename): fp = open(filename, 'wb') pickle.dump(self.vars_list, fp, True) fp.close() def open_data_set(self, filename): fp = open(filename, 'rb') self.vars_list = pickle.load(fp) fp.close() self.update_vars_list() self.update_vars_table() self.sample_number = self.sample_count # spoof start time so that we start where we left off self.start_time = time.time() - self.vars_list[-1]['time'] def update_vars_table(self): if self.vars_table_update: vars_list_unsorted = [ (name, repr(val)) for (name, val) in list(self.vars_pool.iteritems()) ] self.vars_table_list = sorted(vars_list_unsorted, key=(lambda x: x[0].lower())) def test_expr(self, expr): is_ok = (True, '') try: eval(expr, expression_context, self.vars_pool) except Exception as e: is_ok = (False, repr(e)) return is_ok def _eval_expr(self, expr, vars_pool=None): """ Returns the value of a python expression evaluated with the variables in the pool in scope. Used internally by Expression. Users should use Expression instead as it has caching etc. """ if vars_pool == None: vars_pool = self.vars_pool try: data = eval(expr, expression_context, vars_pool) except: data = None return data def bound_array(self, first, last): if first < 0: first += self.sample_number if first < 0: first = 0 if last and last < 0: last += self.sample_number if last == None: last = self.sample_number return (first, last) def _get_array(self, expr, first=0, last=None): """ Returns an array of tuples containing the all the values of an the supplied expression and the sample numbers and times corresponding to these values. Used internally by Expression, users should use Expression directly as it has caching etc. """ first, last = self.bound_array(first, last) vars_list_offset = self.sample_number - self.sample_count if expr in self.vars_pool: data = [ vs.get(expr) for vs in self.vars_list[first - vars_list_offset:last - vars_list_offset] ] else: data = [ self._eval_expr(expr, vs) for vs in self.vars_list[first - vars_list_offset:last - vars_list_offset] ] data = [0.0 if d is None else d for d in data] data_array = numpy.array(data) return data_array
class LoggerView(TraitsUIView): """ The Workbench View showing the list of log items. """ id = Str('enthought.logger.plugin.view.logger_view.LoggerView') name = Str('Logger') service = Instance(LoggerService) log_records = List(Instance(logging.LogRecord)) formatted_records = Property(Str, depends_on='log_records') activated = Instance(logging.LogRecord) activated_text = Property(Str, depends_on='activated') reset_button = Button("Reset Logs") show_button = Button("Complete Text Log") copy_button = Button("Copy Log to Clipboard") code_editor = CodeEditor(lexer='null', show_line_numbers=False) log_records_editor = TabularEditor(adapter=LogRecordAdapter(), editable=False, activated='activated') trait_view = View( Group(Item('log_records', editor=log_records_editor), Group(Item('reset_button'), spring, Item('show_button'), Item('copy_button'), orientation='horizontal', show_labels=False), show_labels=False)) ########################################################################### # LogQueueHandler view interface ########################################################################### def update(self, force=False): """ Update 'log_records' if our handler has new records or 'force' is set. """ service = self.service if service.handler.has_new_records() or force: self.log_records = [ rec for rec in service.handler.get() if rec.levelno >= service.preferences.level_ ] ########################################################################### # Private interface ########################################################################### @on_trait_change('service.preferences.level_') def _update_log_records(self): self.service.handler._view = self self.update(force=True) def _reset_button_fired(self): self.service.handler.reset() self.log_records = [] def _show_button_fired(self): self.edit_traits(view=View(Item('formatted_records', editor=self.code_editor, style='readonly', show_label=False), width=800, height=600, resizable=True, buttons=['OK'], title='Complete Text Log')) def _copy_button_fired(self): clipboard.text_data = self.formatted_records @cached_property def _get_formatted_records(self): return '\n'.join([ self.service.handler.formatter.format(record) for record in self.log_records ]) def _activated_changed(self): if self.activated is None: return msg = self.activated.getMessage() if self.service.preferences.enable_agent: dialog = QualityAgentView(msg=msg, service=self.service) dialog.open() else: self.edit_traits(view=View(Item('activated_text', editor=self.code_editor, style='readonly', show_label=False), width=800, height=600, resizable=True, buttons=['OK'], title='Log Message Detail')) @cached_property def _get_activated_text(self): if self.activated is None: return '' else: return self.activated.getMessage()
print self.fn self.short_fn = os.path.split(self.fn)[1] self.et = eegpy.EventTable(str(self.fn)) self.marker_count = len(self.et.get_all_events()) class EventTableAdapter(TabularAdapter): columns = [('Filename', 'short_fn'), ('# of events', 'marker_count')] font = 'Courier 10' tabular_editor = TabularEditor( adapter=EventTableAdapter(), operations=[], #'delete' ], multi_select=True, #images = [ ImageResource( 'red_flag', search_path = search_path ) ] ) class EventTableManager(HasTraits): """ Manage the EventTables used for the display. Also controls where new marks are saved to. """ evt_filenames = List(EventTableListEntry) evts = List(Instance(eegpy.EventTable)) view = View( VGroup( Group( Item(
class Demo(HasTraits): plot = Instance(Component) fileName = "default.txt" case = List(UncertaintyValue) cases = {} defaultCase = [] # Attributes to use for the plot view. size = (400, 250) traits_view = View(Group( Group(Item('plot', editor=ComponentEditor(size=size), show_label=False), orientation="vertical", show_border=True), Group(Item('case', editor=TabularEditor(adapter=CaseAdapter(can_edit=False)), show_label=False), orientation="vertical", show_border=True), layout='split', orientation='horizontal'), title='Interactive Lines', resizable=True) def setFileName(self, newName): self.fileName = newName def _update_case(self, name): if name: self.case = self.cases.get(name) else: self.case = self.defaultCase def _plot_default(self): results = cPickle.load(open(self.fileName, 'r')) outcomes = results[0][1].keys() outcomes.pop(outcomes.index('TIME')) x = results[0][1]['TIME'] for j, aCase in enumerate(results): aCase = [ UncertaintyValue(name=key, value=value) for key, value in aCase[0][0].items() ] self.cases['y' + str(j)] = aCase uncertainties = results[0][0][0] uncertaintynames = uncertainties.keys() uncertaintyvalues = [] for key in uncertainties.keys(): uncertaintyvalues.append(uncertainties[key]) case = [] for i in range(len(uncertainties)): case.append( UncertaintyValue(name=str(uncertaintynames[i]), value="")) #haydaa self.case = case self.defaultCase = case # Create some x-y data series to plot pds = [] for i, outcome in enumerate(outcomes): pd = ArrayPlotData(index=x) for j in range(len(results)): pd.set_data("y" + str(j), results[j][1].get(outcome)) pds.append(pd) # Create a container and add our plots container = GridContainer(bgcolor="lightgray", use_backbuffer=True, shape=(1, 1)) #plot data tools = [] for j in range(len(outcomes)): pd1 = pds[j] # Create some line plots of some of the data plot = Plot(pd1, title=outcomes[j], border_visible=True, border_width=1) plot.legend.visible = False for i in range(len(results)): plotvalue = "y" + str(i) color = colors[i % len(colors)] plot.plot(("index", plotvalue), name=plotvalue, color=color) for value in plot.plots.values(): for entry in value: entry.index.sort_order = 'ascending' # Attach the selector tools to the plot selectorTool1 = LineSelectorTool(component=plot) plot.tools.append(selectorTool1) tools.append(selectorTool1) # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) container.add(plot) #make sure the selector tools know each other for tool in tools: tool._demo = self return container