def default_traits_view(self): """The default traits view of the Engine View. """ view = View(HSplit( Item('engine', id='mayavi.engine_rich_view.pipeline_view', springy=True, resizable=True, editor=self.tree_editor, dock='tab', label='Pipeline'), Item('engine', id='mayavi.engine_rich_view.current_selection', editor=InstanceEditor( view='current_selection_view'), springy=True, resizable=True, style='custom'), show_labels=False, id='mayavi.engine_rich_view_group', ), id='enthought.mayavi.engine_rich_view', help=False, resizable=True, undo=False, revert=False, ok=False, cancel=False, title='Mayavi pipeline', icon=self.icon, toolbar=self.toolbar, handler=EngineRichViewHandler) return view
class Nirvana(HasTraits): xcontrol = Instance(XControl) csetting = Instance(XSetting) figure = Instance(Figure) # 控制绘图控件的Figure对象 view = View( HSplit( # Item("figure", editor=MPLFigureEditor(), show_label=False,width=0.85), Group( Item('xcontrol',style='custom',show_label=False), Item('csetting',style='custom',show_label=False), show_labels = False, # 组中的所有控件都不显示标签 layout = 'tabbed', ), show_labels = False # 组中的所有控件都不显示标签 ), resizable=True, height=0.95, width=0.99, buttons=[OKButton,] ) def _figure_default(self): figure = Figure() figure.add_axes([0.05, 0.04, 0.9, 0.92]) return figure def _xcontrol_default(self): return XControl(figure=self.figure) def _csetting_default(self): cs = XSetting(figure=self.figure) cs.generate_candidate([base_infos,index_infos,custom_infos]) return cs
class EvapoRate(HasTraits): " Bring up the whole mess" er_plots = Instance(ER_plot_component) er_state = Instance(ER_State) plots_view = View(HSplit( Item('er_plots', style='custom', show_label=False, width=0.7), Item('er_state', style='custom', show_label=False, label='State'), ), resizable=True, height=0.7, width=0.6, x=0.1, y=0.1, title='EvapoRate HR@KIT2012-18 (git-version)') traits_view = View( Item('er_state', style='custom', show_label=False), resizable=True, x=-0.01, y=0.05, #height=0.7, width=0.6, title='EvapoRate HR@KIT2012-18 (git-version)') def _er_plots_default(self): er_plots = ER_plot_component(data=self.data) self.data.er_plots = er_plots return er_plots def _er_state_default(self): er_state = ER_State(data=self.data) self.data.er_state = er_state return er_state
def default_traits_view(self): view = View( HSplit( VSplit( Item("object_class", editor=self.tree_editor, show_label=False, visible_when="object.show_tree"), Group( Item("search", label="搜索"), Item("search_result_str", show_label=False, editor=ListStrEditor(editable=False, selected_index="search_result_index")), label="Search"), ), Item("current_document", style="custom", show_label=False, editor=CodeEditor(lexer="null", search="top", line = "current_line", mark_lines="mark_lines", mark_color=0xff7777)), id = "tvtkdoc.hsplit" ), width = 700, height = 500, resizable = True, title = "TVTK文档浏览器", id = "tvtkdoc", handler = TVTKDocumentHandler(), ) return view
def traits_view(self): """ Default traits view for this class. """ help_action = Action(name='Info', action='preferences_help') buttons = ['OK', 'Cancel'] if self.show_apply: buttons = ['Apply'] + buttons if self.show_help: buttons = [help_action] + buttons # A tree editor for preferences nodes. tree_editor = TreeEditor(nodes=[ TreeNode( node_for=[PreferencesNode], auto_open=False, children='children', label='name', rename=False, copy=False, delete=False, insert=False, menu=None, ), ], on_select=self._selection_changed, editable=False, hide_root=True, selected='selected_node', show_icons=False) view = View( HSplit( Item( name='root', editor=tree_editor, show_label=False, width=250, ), Item( name='selected_page', #editor = WidgetEditor(), show_label=False, width=450, style='custom', ), ), buttons=buttons, handler=PreferencesManagerHandler(model=self), resizable=True, title='Preferences', width=.3, height=.3, kind='modal') self.selected_page = self.pages[0] return view
class ListDemo(HasTraits): items = List(Str) view = View(HSplit(Item("items", style="custom", show_label=False), Item("items", style="custom", editor=CheckListEditor(values=filter_types, cols=4)), Item("items", editor=SetEditor(values=filter_types)), show_labels=False), resizable=True, width=600, title=u"简单列表编辑器演示")
class ComponentViewer(HasTraits): """ A viewer of components for testing purposes """ # The component being viewed component = Instance(Component) # The canvas to which the component is added canvas = Instance(Canvas) # A view into a subsection of the canvas viewport = Instance(Viewport) # Default view traits_view = View(HSplit( Group(Item("viewport", editor=ComponentEditor(), show_label=False)), Group(Item(name="component", style="custom", show_label=False), scrollable=True)), resizable=True, id="canvas_viewer", width=.6, height=.4, title="Viewer") def _canvas_default(self): """ Trait initialiser """ canvas = Canvas(draw_axes=True, bgcolor="honeydew") return canvas def _viewport_default(self): """ Trait initialiser """ viewport = Viewport(component=self.canvas, enable_zoom=True) viewport.tools.append(ViewportPanTool(viewport)) return viewport def _component_changed(self, old, new): """ Handles the component being changed. """ canvas = self.canvas if old is not None: canvas.remove(old) if new is not None: canvas.add(new) def _anytrait_changed_for_component(self, new): """ Handles redrawing of the canvas. """ self.canvas.request_redraw()
class MyDemo(HasTraits): scene = Instance(SceneModel, ()) source = Instance(tvtk.ParametricFunctionSource, ()) func_name = Enum([c.__name__ for c in source_types]) func = Property(depends_on="func_name") traits_view = View(HSplit( VGroup( Item("func_name", show_label=False), Tabbed( Item("func", style="custom", editor=InstanceEditor(), show_label=False), Item("source", style="custom", show_label=False))), Item("scene", style="custom", show_label=False, editor=SceneEditor())), resizable=True, width=700, height=600) def __init__(self, *args, **kwds): super(MyDemo, self).__init__(*args, **kwds) self._make_pipeline() def _get_func(self): return sources[self.func_name] def _make_pipeline(self): self.func.on_trait_change(self.on_change, "anytrait") src = self.source src.on_trait_change(self.on_change, "anytrait") src.parametric_function = self.func map = tvtk.PolyDataMapper(input_connection=src.output_port) act = tvtk.Actor(mapper=map) self.scene.add_actor(act) self.src = src def _func_changed(self, old_func, this_func): if old_func is not None: old_func.on_trait_change(self.on_change, "anytrait", remove=True) this_func.on_trait_change(self.on_change, "anytrait") self.src.parametric_function = this_func self.scene.render() def on_change(self): self.scene.render()
class ActorView(HasTraits): cube = Instance(tvtk.CubeSource, ()) scene = Instance(SceneModel) traits_view = View(HSplit( Item("scene", style="custom", editor=SceneEditor(), show_label=False), Item("cube", style="custom", show_label=False)), resizable=True, width=700, height=600) def _scene_default(self): cube = self.cube map = tvtk.PolyDataMapper(input=cube.output) act = tvtk.Actor(mapper=map) scene = SceneModel() scene.add_actor(act) return scene
def default_traits_view(self): ''' Generates the view from the param items. ''' #rf_param_items = [ Item( 'model.' + name, format_str = '%g' ) for name in self.model.param_keys ] plot_param_items = [ Item('max_x', label='max x value'), Item('n_points', label='No of plot points') ] control_items = [ Item('show', show_label=False), Item('clear', show_label=False), ] view = View( HSplit( VGroup( Item('@resp_func', show_label=False), #*rf_param_items, label='Function Parameters', id='stats.spirrid_bak.rf_model_view.rf_params', scrollable=True), VGroup(*plot_param_items, label='Plot Parameters', id='stats.spirrid_bak.rf_model_view.plot_params'), VGroup( Item('model.comment', show_label=False, style='readonly'), label='Comment', id='stats.spirrid_bak.rf_model_view.comment', scrollable=True, ), VGroup(HGroup(*control_items), Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), label='Plot', id='stats.spirrid_bak.rf_model_view.plot'), dock='tab', id='stats.spirrid_bak.rf_model_view.split'), kind='modal', resizable=True, dock='tab', buttons=[OKButton], id='stats.spirrid_bak.rf_model_view') return view
class Model(HasTraits): a = Code("print 'hello'") b = Button("click me") traits_view = View(HSplit( VGroup( Tabbed( Item('a'), Item('a'), Item('a')), Item('b')), VSplit( VGroup('b','b','b'), HGroup('a', show_border=True, label="traits is great")), dock="horizontal" ), resizable=True, id="my.test.program.id")
class bcsr_gui(HasTraits): n_rows = Long(0) n_cols = Long(0) n_mem = Float(0) n_bs = Long(0) rows = Array cols = Array values = Array #matrix = Instance (tt) view = View(Group(Item('n_rows', style='readonly', label='Number of rows'), Item('n_cols', style='readonly', label='Number of columns'), Item('n_bs', style='readonly', label='Block size'), Item('n_mem', style='readonly', label='Total allocated memory (MB)'), HSplit( Item('rows', show_label=False, style='readonly', editor=ArrayViewEditor(titles=['rows_ptr'], format='%d', font='Arial 8')), Item('cols', show_label=False, style='readonly', editor=ArrayViewEditor(titles=['cols_ind'], format='%d', font='Arial 8')), Item('values', show_label=False, style='readonly', editor=ArrayViewEditor(titles=['values'], format='%lf', font='Arial 8'))), label='Matrix properties:', show_border=True), title='Block CSR matrix viewer', width=0.5, height=0.5, resizable=True)
class OCCModel(HasTraits): shapes = List shape_list = Instance(ShapeList) traits_view=View(HSplit( Item('shape_list', editor=occ_tree, show_label=False, width=-300), Item('shape_list', editor=CustomEditor(MakeCanvas), show_label=False, resizable=True), id="occ.traits.test_feature_model_layout", dock="fixed" ), resizable=True, width=1000, height=800, id="occ.traits.test_feature_model" ) def _shapes_changed(self, vnew): self.shape_list = ShapeList(shapes=vnew)
class PythonBrowser ( HasPrivateTraits ): dir = Directory files = List( FileInfo ) file_info = Instance( FileInfo ) code = Code view = View( HSplit( Item( 'dir', style = 'custom' ), VSplit( Item( 'files', editor = tabular_editor ), Item( 'code', style = 'readonly' ), show_labels = False ), show_labels = False ), resizable = True, width = 0.75, height = 0.75 ) #-- Event Handlers --------------------------------------------------------- def _dir_changed ( self, dir ): self.files = [ FileInfo( file_name = join( dir, name ) ) for name in listdir( dir ) if ((splitext( name )[1] == '.py') and isfile( join( dir, name ) )) ] def _file_info_changed ( self, file_info ): fh = None try: fh = open( file_info.file_name, 'rb' ) self.code = fh.read() except: pass if fh is not None: fh.close()
class EqualizerDesigner(HasTraits): '''均衡器设计器的主界面''' equalizers = Instance(Equalizers) # 保存绘图数据的对象 plot_data = Instance(AbstractPlotData) # 绘制波形图的容器 container = Instance(Component) plot_gain = Instance(Component) plot_phase = Instance(Component) save_button = Button("Save") load_button = Button("Load") export_button = Button("Export") view = View(VGroup( HGroup(Item("load_button"), Item("save_button"), Item("export_button"), show_labels=False), HSplit( VGroup( Item("equalizers", style="custom", show_label=False), show_border=True, ), Item("container", editor=ComponentEditor(size=(800, 300)), show_label=False), )), resizable=True, width=800, height=500, title="Equalizer Designer") def _create_plot(self, data, name, type="line"): p = Plot(self.plot_data) p.plot(data, name=name, title=name, type=type) p.tools.append(PanTool(p)) zoom = ZoomTool(component=p, tool_mode="box", always_on=False) p.overlays.append(zoom) p.title = name p.index_scale = "log" return p def __init__(self): super(EqualizerDesigner, self).__init__() self.plot_data = ArrayPlotData(f=FREQS, gain=[], phase=[]) self.plot_gain = self._create_plot(("f", "gain"), "Gain(dB)") self.plot_phase = self._create_plot(("f", "phase"), "Phase(degree)") self.container = VPlotContainer() self.container.add(self.plot_phase) self.container.add(self.plot_gain) self.plot_gain.padding_bottom = 20 self.plot_phase.padding_top = 20 def _equalizers_default(self): return Equalizers() @on_trait_change("equalizers.h") def redraw(self): gain = 20 * np.log10(np.abs(self.equalizers.h)) phase = np.angle(self.equalizers.h, deg=1) self.plot_data.set_data("gain", gain) self.plot_data.set_data("phase", phase) def _save_button_fired(self): dialog = FileDialog(action="save as", wildcard='EQ files (*.eq)|*.eq') result = dialog.open() if result == OK: f = file(dialog.path, "wb") pickle.dump(self.equalizers, f) f.close() def _load_button_fired(self): dialog = FileDialog(action="open", wildcard='EQ files (*.eq)|*.eq') result = dialog.open() if result == OK: f = file(dialog.path, "rb") self.equalizers = pickle.load(f) f.close() def _export_button_fired(self): dialog = FileDialog(action="save as", wildcard='c files (*.c)|*.c') result = dialog.open() if result == OK: self.equalizers.export(dialog.path)
class RespFuncView(ModelView): def __init__(self, **kw): super(RespFuncView, self).__init__(**kw) self._redraw() self.on_trait_change(self._redraw, 'model.values') model = Instance(RespFunc) def _model_default(self): return RespFunc() figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') figure.add_axes([0.08, 0.13, 0.85, 0.74]) return figure data_changed = Event(True) count = Int def _redraw(self): self.count += 1 print('redraw', self.count) # data post-processing # xdata, ydata = self.model.values if self.model.approach.plot.yvalues == 'forces': ylabel = 'pull-out force [N]' else: ydata = ydata / self.model.approach.Af ylabel = 'pull-out stress [N/m2]' title = self.model.boundary.type.BC if title[0] == 'd': xlabel = 'crack opening [m]' else: xlabel = 'displacement [m]' figure = self.figure axes = figure.axes[0] axes.clear() axes.plot(xdata, ydata, color='blue', linewidth=2, linestyle='solid') axes.set_xlabel(xlabel, weight='semibold') axes.set_ylabel(ylabel, weight='semibold') axes.set_title( title, \ size='large', color='black', \ weight='bold', position=( .5, 1.03 ) ) axes.set_axis_bgcolor(color='white') axes.ticklabel_format(scilimits=(-3., 4.)) axes.grid(color='gray', linestyle='--', linewidth=0.1, alpha=0.4) self.data_changed = True plot_button = Button('Plot pull-out') def _plot_button_fired(self): self._redraw() traits_view = View( HSplit( VGroup( Item('@model.boundary', show_label=False), Item('@model.approach', show_label=False), id='rf.model', dock='tab', label='pull-out model', ), VGroup( Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), #Item('plot_button', show_label = False), label='plot sheet', id='rf.figure_window', dock='tab', ), id='rf.viewmodel.hsplit', ), title='Response Function', id='rf.viewmodel', dock='tab', kind='live', resizable=True, height=0.8, width=0.8, buttons=[OKButton]) def open(self, uiinfo): file_name = open_file(filter=['*.pst'], extensions=[FileInfo(), TextInfo()]) if file_name == '': return file = open(file_name, 'r') self.model = pickle.load(file) file.close() def save(self, uiinfo): file_name = save_file(filter=['*.pst'], extensions=[FileInfo(), TextInfo()]) if file_name == '': return print('writing into', file_name) file = open(file_name, 'w') pickle.dump(self.model, file) file.close()
class CSModelView(ModelView): model = Instance(ClampSetup) def _model_default(self): return ClampSetup() figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') figure.add_axes([0.08, 0.13, 0.85, 0.74]) return figure data_changed = Event @on_trait_change('model.+modified') def refresh(self): figure = self.figure axes = figure.gca() axes.clear() cs = self.model xu, u, xe, e = cs.get_values() axes.set_xlabel('position on yarn', weight='semibold') axes.set_axis_bgcolor(color='white') axes.ticklabel_format(scilimits=(-3., 4.)) axes.grid(color='gray', linestyle='--', linewidth=0.5, alpha=0.7) if cs.switch == 'strains': axes.plot(xe, e, lw=2, color='blue') axes.set_ylabel('strains [-]', weight='semibold') axes.plot(array([cs.l1, cs.l1]), array([0, max(e)]), lw=2, color='red', linestyle='dashed') axes.plot(array([cs.l1 + cs.L, cs.l1 + cs.L]), array([0, max(e)]), lw=2, color='red', linestyle='dashed') axes.text(cs.l1 + cs.L / 2, max(e) * 0.95, 'clamp', size='large', ha='center') axes.text(cs.l1 + cs.L + cs.lt / 2, max(e) * 0.95, 'tested length', size='large', ha='center') elif cs.switch == 'displacement': axes.plot(xu, u, lw=2, color='blue') axes.set_ylabel('displacement [m]', weight='semibold') axes.plot(array([cs.l1, cs.l1]), array([0, max(u)]), lw=2, color='red', linestyle='dashed') axes.plot(array([cs.l1 + cs.L, cs.l1 + cs.L]), array([0, max(u)]), lw=2, color='red', linestyle='dashed') axes.text(cs.l1 + cs.L / 2, max(u) * 0.95, 'clamp', size='large', ha='center') axes.text(cs.l1 + cs.L + cs.lt / 2, max(u) * 0.95, 'tested length', size='large', ha='center') else: print 'NOT YET IMPLEMENTED' # axes.plot(xslip, yslip, lw = 2, color = 'blue') # axes.set_ylabel('slip in clamp [m]', weight = 'semibold') # axes.set_xlabel('position in clamp [mm]', weight = 'semibold') self.data_changed = True traits_view = View(HSplit( VGroup( Item('model@', show_label=False, resizable=True), label='Material parameters', id='cs.viewmodel.model', dock='tab', ), VSplit( VGroup( Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), label='yarn displacement', id='cs.viewmodel.plot_window', dock='tab', ), id='cs.viewmodel.right', ), id='cs.viewmodel.splitter', ), title='tested yarn', id='cs.viewmodel', dock='tab', resizable=True, buttons=[OKButton], height=0.8, width=0.8)
class MayaviViewer(HasTraits): """ This class represents a Mayavi based viewer for the particles. They are queried from a running solver. """ particle_arrays = List(Instance(ParticleArrayHelper), []) pa_names = List(Str, []) client = Instance(MultiprocessingClient) host = Str('localhost', desc='machine to connect to') port = Int(8800, desc='port to use to connect to solver') authkey = Password('pysph', desc='authorization key') host_changed = Bool(True) scene = Instance(MlabSceneModel, ()) controller = Property() ######################################## # Timer traits. timer = Instance(Timer) interval = Range(2, 20.0, 5.0, desc='frequency in seconds with which plot is updated') ######################################## # Solver info/control. current_time = Float(0.0, desc='the current time in the simulation') iteration = Int(0, desc='the current iteration number') pause_solver = Bool(False, desc='if the solver should be paused') ######################################## # The layout of the dialog created view = View(HSplit( Group( Group( Item(name='host'), Item(name='port'), Item(name='authkey'), label='Connection', ), Group( Item(name='current_time'), Item(name='iteration'), Item(name='pause_solver'), Item(name='interval'), label='Solver', ), Group( Item(name='particle_arrays', style='custom', show_label=False, editor=ListEditor(use_notebook=True, deletable=False, page_name='.name'))), ), Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=480, width=500, show_label=False), ), resizable=True, title='Mayavi Particle Viewer') ###################################################################### # `MayaviViewer` interface. ###################################################################### @on_trait_change('scene.activated') def start_timer(self): # Just accessing the timer will start it. t = self.timer if not t.IsRunning(): t.Start(int(self.interval * 1000)) @on_trait_change('scene.activated') def update_plot(self): # do not update if solver is paused if self.pause_solver: return controller = self.controller if controller is None: return self.current_time = controller.get_t() for idx, name in enumerate(self.pa_names): pa = controller.get_named_particle_array(name) self.particle_arrays[idx].particle_array = pa ###################################################################### # Private interface. ###################################################################### @on_trait_change('host,port,authkey') def _mark_reconnect(self): self.host_changed = True def _get_controller(self): ''' get the controller, also sets the iteration count ''' reconnect = self.host_changed if not reconnect: try: c = self.client.controller self.iteration = c.get_count() except Exception as e: logger.info( 'Error: no connection or connection closed: reconnecting') reconnect = True self.client = None if reconnect: self.host_changed = False try: if MultiprocessingClient.is_available((self.host, self.port)): self.client = MultiprocessingClient(address=(self.host, self.port), authkey=self.authkey) else: return None except Exception as e: logger.info('Could not connect: check if solver is running') return None c = self.client.controller self.iteration = c.get_count() return self.client.controller def _client_changed(self, old, new): if self.client is None: return else: self.pa_names = self.client.controller.get_particle_array_names() self.scene.mayavi_scene.children[:] = [] self.particle_arrays = [ ParticleArrayHelper(scene=self.scene, name=x) for x in self.pa_names ] # Turn on the legend for the first particle array. if len(self.particle_arrays) > 0: self.particle_arrays[0].show_legend = True def _timer_event(self): # catch all Exceptions else timer will stop try: self.update_plot() except Exception as e: logger.info('Exception: %s caught in timer_event' % e) def _interval_changed(self, value): t = self.timer if t is None: return if t.IsRunning(): t.Stop() t.Start(int(value * 1000)) def _timer_default(self): return Timer(int(self.interval * 1000), self._timer_event) def _pause_solver_changed(self, value): c = self.client.controller if value: c.pause_on_next() else: c.cont()
class tcWindow(HasTraits): project = tcProject plot = tcPlot def __init__(self, project): self.project = project self.plot = create_timechart_container(project) self.plot_range_tools = self.plot.range_tools self.plot_range_tools.on_trait_change(self._selection_time_changed, "time") self.trait_view().title = self.get_title() def get_title(self): if self.project.filename == "dummy": return "PyTimechart: Please Open a File" return "PyTimechart:" + self.project.filename # Create an action that exits the application. status = Str("Welcome to PyTimechart") traits_view = View( HSplit( VSplit( Item('project', show_label=False, editor=InstanceEditor(view='process_view'), style='custom', width=150), # Item('plot_range_tools', show_label = False, editor=InstanceEditor(view = 'selection_view'), style='custom',width=150,height=100) ), Item('plot', show_label=False, editor=ComponentEditor()), ), toolbar=ToolBar(*_create_toolbar_actions(), image_size=(24, 24), show_tool_names=False), menubar=MenuBar(*_create_menubar_actions()), statusbar=[ StatusItem(name='status'), ], resizable=True, width=1280, height=1024, handler=tcActionHandler()) def _on_open_trace_file(self): if open_file(None) and self.project.filename == "dummy": self._ui.dispose() def _on_view_properties(self): self.plot.options.edit_traits() def _on_exit(self, n=None): self.close() sys.exit(0) def close(self, n=None): pass def _on_about(self): aboutBox().edit_traits() def _on_doc(self): browse_doc() def _selection_time_changed(self): self.status = "selection time:%s" % (self.plot_range_tools.time)
class PointSelectionDemo(HasTraits): color = Enum(Colors.keys()) green_selection = List() red_selection = List() plot = Instance(Plot) data = Instance(ArrayPlotData) traits_view = View(HSplit( Item('plot', editor=ComponentEditor(), show_label=False), VGroup( Item("color", show_label=False, style="custom"), Heading(u"绿色选择点"), Item("green_selection", show_label=False, style="readonly"), Heading(u"红色选择点"), Item("red_selection", show_label=False, style="readonly"), )), width=800, height=400, resizable=True, title=u"数据点选择演示") def __init__(self, **traits): super(PointSelectionDemo, self).__init__(**traits) x = np.random.rand(100) y = np.random.rand(100) data = ArrayPlotData(x=x, y=y) plot = Plot(data, padding=25) self.scatter = scatter = plot.plot(("x", "y"), type="scatter", marker_size=4)[0] self.select_tools = {} for i, c in enumerate(Colors.keys()): hover_name = "hover_%s" % c selection_name = "selections_%s" % c self.select_tools[c] = ScatterInspector( scatter, hover_metadata_name=hover_name, selection_metadata_name=selection_name) scatter.overlays.append( ScatterInspectorOverlay( scatter, hover_metadata_name=hover_name, selection_metadata_name=selection_name, hover_color="transparent", hover_outline_color=c, hover_marker_size=6, hover_line_width=1, selection_color=Colors[c], )) scatter.active_tool = self.select_tools[self.color] scatter.index.on_trait_change(self.selection_changed, 'metadata_changed') self.plot = plot self.data = data def _color_changed(self): self.scatter.active_tool = self.select_tools[self.color] def selection_changed(self): x = self.scatter.index.get_data() y = self.scatter.value.get_data() metadata = self.scatter.index.metadata selection = metadata.get("selections_green", []) self.green_selection = [ "%d, (%f, %f)" % (s, x[s], y[s]) for s in selection ] selection = metadata.get("selections_red", []) self.red_selection = [ "%d, (%f, %f)" % (s, x[s], y[s]) for s in selection ]
class Graph(HasTraits): """ 绘图组件,包括左边的数据选择控件和右边的绘图控件 """ name = Str # 绘图名,显示在标签页标题和绘图标题中 data_source = Instance(DataSource) # 保存数据的数据源 figure = Instance(Figure) # 控制绘图控件的Figure对象 selected_xaxis = Str # X轴所用的数据名 selected_items = List # Y轴所用的数据列表 clear_button = Button(u"清除") # 快速清除Y轴的所有选择的数据 view = View( HSplit( # HSplit分为左右两个区域,中间有可调节宽度比例的调节手柄 # 左边为一个组 VGroup( Item("name"), # 绘图名编辑框 Item("clear_button"), # 清除按钮 Heading(u"X轴数据"), # 静态文本 # X轴选择器,用EnumEditor编辑器,即ComboBox控件,控件中的候选数据从 # data_source的names属性得到 Item("selected_xaxis", editor= EnumEditor(name="object.data_source.names", format_str=u"%s")), Heading(u"Y轴数据"), # 静态文本 # Y轴选择器,由于Y轴可以多选,因此用CheckBox列表编辑,按两列显示 Item("selected_items", style="custom", editor=CheckListEditor(name="object.data_source.names", cols=2, format_str=u"%s")), show_border = True, # 显示组的边框 scrollable = True, # 组中的控件过多时,采用滚动条 show_labels = False # 组中的所有控件都不显示标签 ), # 右边绘图控件 Item("figure", editor=MPLFigureEditor(), show_label=False, width=600) ) ) def _name_changed(self): """ 当绘图名发生变化时,更新绘图的标题 """ axe = self.figure.axes[0] axe.set_title(self.name) self.figure.canvas.draw() def _clear_button_fired(self): """ 清除按钮的事件处理 """ self.selected_items = [] self.update() def _figure_default(self): """ figure属性的缺省值,直接创建一个Figure对象 """ figure = Figure() figure.add_axes([0.1, 0.1, 0.85, 0.80]) #添加绘图区域,四周留有边距 return figure def _selected_items_changed(self): """ Y轴数据选择更新 """ self.update() def _selected_xaxis_changed(self): """ X轴数据选择更新 """ self.update() def update(self): """ 重新绘制所有的曲线 """ axe = self.figure.axes[0] axe.clear() try: xdata = self.data_source.data[self.selected_xaxis] except: return for field in self.selected_items: axe.plot(xdata, self.data_source.data[field], label=field) axe.set_xlabel(self.selected_xaxis) axe.set_title(self.name) axe.legend() self.figure.canvas.draw()
class PlotOMatic(HasTraits): io_driver_list = Instance(IODriverList) variables = Instance(Variables) viewers = Instance(Viewers) selected_viewer = Instance(Viewer) handler = PlotOMaticHandler() viewer_node = TreeNode(node_for=[Viewer], auto_open=True, label='name', menu=Menu(handler.remove_viewer_action), icon_path='icons/', icon_item='plot.png') tree_editor = TreeEditor(nodes=[ TreeNode( node_for=[IODriverList], auto_open=True, children='io_drivers', label='=Input Drivers', menu=Menu(handler.refresh_tree_action, handler.add_io_driver_actions_menu), view=View(), ), TreeNode(node_for=[IODriver], auto_open=True, children='_decoders', label='name', add=[DataDecoder], menu=Menu(handler.remove_io_driver_action, handler.refresh_tree_action, handler.add_decoder_actions_menu), icon_path='icons/', icon_open='input.png', icon_group='input.png'), TreeNode(node_for=[DataDecoder], auto_open=True, children='', label='name', menu=Menu(handler.refresh_tree_action, handler.remove_decoder_action), icon_path='icons/', icon_item='decoder.png'), TreeNode(node_for=[IODriverList], auto_open=True, children='viewers', label='=Viewers', menu=Menu(handler.refresh_tree_action, handler.add_viewer_actions_menu), view=View()), viewer_node ], hide_root=True, orientation='vertical') view = View(HSplit( Item(name='io_driver_list', editor=tree_editor, resizable=True, show_label=False, width=.32), VSplit( Item(name='selected_viewer', style='custom', resizable=True, show_label=False, editor=InstanceEditor(view='view')), Item(name='variables', show_label=False, style='custom', height=.3))), menubar=MenuBar(handler.file_menu, handler.data_menu), title='Plot-o-matic', resizable=True, width=1000, height=600, handler=PlotOMaticHandler()) def __init__(self, **kwargs): HasTraits.__init__(self, **kwargs) self.viewer_node.on_select = self.click_viewer def click_viewer(self, viewer): self.selected_viewer = viewer self.viewers.select_viewer(viewer) def start(self): self.io_driver_list.start_all() self.viewers.start() def stop(self): self.viewers.stop() self.io_driver_list.stop_all() def get_config(self): config = {} config['io_drivers'] = self.io_driver_list.get_config() config['viewers'] = self.viewers.get_config() return config def set_config(self, config): if 'io_drivers' in config: self.io_driver_list.set_config(config['io_drivers']) if 'viewers' in config: self.viewers.set_config(config['viewers']) self.variables.clear()
class ImageSelections(HasTraits): analysis = Instance(MultiSelections, transient=True) figure = Instance(Figure, transient=True) data = Array def _analysis_default(self): return MultiSelections() def _figure_default(self): def selection_callback(pos1, pos2): if pos1 == pos2: self.analysis.selection.set_from_corners(pos1) else: self.analysis.selection.set_from_corners(pos1, pos2) figure = Figure(process_selection=selection_callback) return figure @on_trait_change('data') def image_show(self): self.figure.update_image(self.data) @on_trait_change('analysis.updated') def show_selection2(self): def plot(selection, color, index): s = selection x, y = list( map(lambda *args: args, s.top_left, s.top_right, s.bottom_right, s.bottom_left, s.top_left)) self.figure.plot_data(x, y, str(index), color) for i in range(len(self.analysis.selections) + 1): self.figure.del_plot(str(i)) # self.figure.del_plot('all') for index, selection in enumerate(self.analysis.selections): if self.analysis.index == index: color = 'red' else: color = 'black' plot(selection, color, index) view = View( HSplit( Item('figure', style='custom', width=0.5), Group(Item('analysis', style="custom", resizable=True, width=0.5, show_label=False), scrollable=True), show_labels=False, ), width=1200, height=800, resizable=True, # statusbar = [ StatusItem( name = 'error')], # title = 'Image selector' )
class FieldExplorer(HasTraits): scene = Instance(SceneModel, ()) wire = Instance(WireLoop) interact = Bool(False) ipl = Instance(tvtk.PlaneWidget, (), { 'resolution': 50, 'normal': [1., 0., 0.] }) #plane_src = Instance(tvtk.PlaneSource, ()) calc_B = Instance(tvtk.ProgrammableFilter, ()) glyph = Instance(tvtk.Glyph3D, (), {'scale_factor': 0.02}) scale_factor = DelegatesTo("glyph") lm = Instance(LUTManager, ()) traits_view = View(HSplit( Item("scene", style="custom", editor=SceneEditor(), show_label=False), VGroup(Item("wire", style="custom", show_label=False), Item("interact"), Item("scale_factor"), Item("lm")), ), resizable=True, width=700, height=600) def _interact_changed(self, i): self.ipl.interactor = self.scene.interactor self.ipl.place_widget() if i: self.ipl.on() else: self.ipl.off() def make_probe(self): src = self.ipl.poly_data_algorithm map = tvtk.PolyDataMapper(lookup_table=self.lm.lut) act = tvtk.Actor(mapper=map) calc_B = self.calc_B calc_B.input = src.output def execute(): print "calc fields!" output = calc_B.poly_data_output points = output.points.to_array().astype('d') nodes = self.wire.nodes.astype('d') vectors = calc_wire_B_field(nodes, points, self.wire.radius) output.point_data.vectors = vectors mag = np.sqrt((vectors**2).sum(axis=1)) map.scalar_range = (mag.min(), mag.max()) calc_B.set_execute_method(execute) cone = tvtk.ConeSource(height=0.05, radius=0.01, resolution=15) cone.update() glyph = self.glyph glyph.input_connection = calc_B.output_port glyph.source = cone.output glyph.scale_mode = 'scale_by_vector' glyph.color_mode = 'color_by_vector' map.input_connection = glyph.output_port self.scene.add_actor(act) def on_update(self): self.calc_B.modified() self.scene.render() def _wire_changed(self, anew): anew.on_trait_change(self.on_update, "update") self.scene.add_actor(anew.actor)
class TriangleWave(HasTraits): # 指定三角波的最窄和最宽范围,由于Range类型不能将常数和Traits属性名混用 # 所以定义这两个值不变的Trait属性 low = Float(0.02) hi = Float(1.0) # 三角波形的宽度 wave_width = Range("low", "hi", 0.5) # 三角波的顶点C的x轴坐标 length_c = Range("low", "wave_width", 0.5) # 三角波的定点的y轴坐标 height_c = Float(1.0) # FFT计算所使用的取样点数,这里用一个Enum类型的属性以供用户从列表中选择 fftsize = Enum([(2**x) for x in range(6, 12)]) # FFT频谱图的x轴上限值 fft_graph_up_limit = Range(0, 400, 20) # 用于显示FFT的结果 peak_list = Str # 采用多少个频率合成三角波 N = Range(1, 40, 4) # 保存绘图数据的对象 plot_data = Instance(AbstractPlotData) # 绘制波形图的容器 plot_wave = Instance(Component) # 绘制FFT频谱图的容器 plot_fft = Instance(Component) # 包括两个绘图的容器 container = Instance(Component) # 设置用户界面的视图, 注意一定要指定窗口的大小,这样绘图容器才能正常初始化 view = View(HSplit( VSplit( VGroup(Item("wave_width", editor=scrubber, label="波形宽度"), Item("length_c", editor=scrubber, label="最高点x坐标"), Item("height_c", editor=scrubber, label="最高点y坐标"), Item("fft_graph_up_limit", editor=scrubber, label="频谱图范围"), Item("fftsize", label="FFT点数"), Item("N", label="合成波频率数")), Item("peak_list", style="custom", show_label=False, width=100, height=250)), VGroup(Item("container", editor=ComponentEditor(size=(600, 300)), show_label=False), orientation="vertical")), resizable=True, width=800, height=600, title="三角波FFT演示") # 创建绘图的辅助函数,创建波形图和频谱图有很多类似的地方,因此单独用一个函数以 # 减少重复代码 def _create_plot(self, data, name, type="line"): p = Plot(self.plot_data) p.plot(data, name=name, title=name, type=type) p.tools.append(PanTool(p)) zoom = ZoomTool(component=p, tool_mode="box", always_on=False) p.overlays.append(zoom) p.title = name return p def __init__(self): # 首先需要调用父类的初始化函数 super(TriangleWave, self).__init__() # 创建绘图数据集,暂时没有数据因此都赋值为空,只是创建几个名字,以供Plot引用 self.plot_data = ArrayPlotData(x=[], y=[], f=[], p=[], x2=[], y2=[]) # 创建一个垂直排列的绘图容器,它将频谱图和波形图上下排列 self.container = VPlotContainer() # 创建波形图,波形图绘制两条曲线: 原始波形(x,y)和合成波形(x2,y2) self.plot_wave = self._create_plot(("x", "y"), "Triangle Wave") self.plot_wave.plot(("x2", "y2"), color="red") # 创建频谱图,使用数据集中的f和p self.plot_fft = self._create_plot(("f", "p"), "FFT", type="scatter") # 将两个绘图容器添加到垂直容器中 self.container.add(self.plot_wave) self.container.add(self.plot_fft) # 设置 self.plot_wave.x_axis.title = "Samples" self.plot_fft.x_axis.title = "Frequency pins" self.plot_fft.y_axis.title = "(dB)" # 改变fftsize为1024,因为Enum的默认缺省值为枚举列表中的第一个值 self.fftsize = 1024 # FFT频谱图的x轴上限值的改变事件处理函数,将最新的值赋值给频谱图的响应属性 def _fft_graph_up_limit_changed(self): self.plot_fft.x_axis.mapper.range.high = self.fft_graph_up_limit def _N_changed(self): self.plot_sin_combine() # 多个trait属性的改变事件处理函数相同时,可以用@on_trait_change指定 @on_trait_change("wave_width, length_c, height_c, fftsize") def update_plot(self): # 计算三角波 global y_data x_data = np.arange(0, 1.0, 1.0 / self.fftsize) func = self.triangle_func() # 将func函数的返回值强制转换成float64 y_data = np.cast["float64"](func(x_data)) # 计算频谱 fft_parameters = np.fft.fft(y_data) / len(y_data) # 计算各个频率的振幅 fft_data = np.clip( 20 * np.log10(np.abs(fft_parameters))[:self.fftsize / 2 + 1], -120, 120) # 将计算的结果写进数据集 self.plot_data.set_data("x", np.arange(0, self.fftsize)) # x坐标为取样点 self.plot_data.set_data("y", y_data) self.plot_data.set_data("f", np.arange(0, len(fft_data))) # x坐标为频率编号 self.plot_data.set_data("p", fft_data) # 合成波的x坐标为取样点,显示2个周期 self.plot_data.set_data("x2", np.arange(0, 2 * self.fftsize)) # 更新频谱图x轴上限 self._fft_graph_up_limit_changed() # 将振幅大于-80dB的频率输出 peak_index = (fft_data > -80) peak_value = fft_data[peak_index][:20] result = [] for f, v in zip(np.flatnonzero(peak_index), peak_value): result.append("%s : %s" % (f, v)) self.peak_list = "\n".join(result) # 保存现在的fft计算结果,并计算正弦合成波 self.fft_parameters = fft_parameters self.plot_sin_combine() # 计算正弦合成波,计算2个周期 def plot_sin_combine(self): index, data = fft_combine(self.fft_parameters, self.N, 2) self.plot_data.set_data("y2", data) # 返回一个ufunc计算指定参数的三角波 def triangle_func(self): c = self.wave_width c0 = self.length_c hc = self.height_c def trifunc(x): x = x - int(x) # 三角波的周期为1,因此只取x坐标的小数部分进行计算 if x >= c: r = 0.0 elif x < c0: r = x / c0 * hc else: r = (c - x) / (c - c0) * hc return r # 用trifunc函数创建一个ufunc函数,可以直接对数组进行计算, 不过通过此函数 # 计算得到的是一个Object数组,需要进行类型转换 return np.frompyfunc(trifunc, 1, 1)
class FitGUI(ModelView): """ Implements a Model-View style controller and default view that provides a matplolib graphical representation of an ImpedanceAnalysis model. """ text_display = Str params_gui = Instance(ParameterSetGUI) fit_button = Button() plot = Instance(IPlot) has_fit = Bool(False) pick_mode = Int(0) view = View( HSplit( VGroup( Item( 'text_display', style='custom', show_label=False, #springy = True, height=0.50, width=0.20, ), # VGrid( # Item('model.selection_low_index', width=0.05,), # Item('model.selection_high_index', width=0.05,), Item( 'params_gui', show_label=False, style='custom', springy=True, #height=0.30, width=0.20, ), Item( 'fit_button', label="Run Fit", show_label=False, #style='custom', #springy = True, #height=0.30, width=0.20, ), # columns = 1, # ), ), Item( 'plot', #editor = MPLFigureEditor(), #this editor will automatically find and connect the _handle_onpick method for handling matplotlib's object picking events style='custom', show_label=False, height=0.80, width=0.60, ), ), height=0.80, width=0.80, resizable=True, ) #-------------------------------------------------------------------------- def run_fit(self): self.model.fit() self.has_fit = True new_params = self.model.params self.params_gui.model = new_params self.params_gui.render_fields() #FIXME - to use a gentler field update self._print(self.model.fit_log, loc='front') self.update_plot() # def _plot_default(self): # return SimpleFunctionPlot() @on_trait_change('model') def update_all(self): self.params_gui = ParameterSetGUI(self.model.params) self._clear_display() self.update_plot() @on_trait_change('plot') def setup_onpick_handler(self): self.plot.register_onpick_handler(self._handle_onpick) def update_plot(self): self.plot.clear() Xs = [] Ys = [] #get all the data X_data, Y_data, W_data = self.model.get_data() Xs.append(X_data) Ys.append(Y_data) #get the data selection X_sel, Y_sel, W_sel = self.model.get_selection() Xs.append(X_sel) Ys.append(Y_sel) if self.has_fit: X_fit, Y_fit = self.model.interpolate(density=10) Xs.append(X_fit) Ys.append(Y_fit) self.plot.render(Xs, Ys, fmts=['b.', 'kx', 'r-'], pickable=[0]) self.plot.redraw() def _fit_button_fired(self): self.run_fit() #-------------------------------------------------------------------------- def _handle_onpick(self, event): "handles a data point pick event depending on the mode" #extract information from the event line = event.artist ind = event.ind[ 0] #the selected data index as first (nearest) in the group X = line.get_xdata() Y = line.get_ydata() x = X[ind] y = Y[ind] pick_mode = self.pick_mode print event.__dict__ if pick_mode == 0: self._print("\nlow point selected at index: %s (%e, %e)" % (ind, x, y), loc='front') self.model.selection_low_index = ind self.model.selection_high_index = Undefined self.pick_mode = 1 time.sleep(0.1) elif pick_mode == 1: self._print("\nhigh point selected at index: %s (%e, %e)" % (ind, x, y), loc='front') self.model.selection_high_index = ind if self.model.selection_low_index != self.model.selection_high_index: self.run_fit() self.pick_mode = 0 #-------------------------------------------------------------------------- def _clear_display(self): self.text_display = "" def _print(self, text, indent="\t", level=0, newline='\n', loc='front'): text = str(text) if level >= 1: #reformat the text to indent it text_lines = text.split(newline) space = indent * level text_lines = ["%s%s" % (space, line) for line in text_lines] text = newline.join(text_lines) if loc == 'end': self.text_display += text + newline elif loc == 'front': self.text_display = text + newline + self.text_display else: raise ValueError, "'loc' must be 'front' or 'end'"
class Images(HasTraits): """Main class for image point selections """ filenames = Instance(Filenames, ()) analysis = Instance(RectangleSelections, transient=True) filters = List(Instance(BaseFilter)) figure = Instance(Figure, transient=True) data = Array def _filters_default(self): return [Rotate(), GaussianFilter()] def _analysis_default(self): return RectangleSelections() def _figure_default(self): def selection_callback(pos1, pos2): try: if pos1 == pos2: self.analysis.selection.set_from_points(pos1) else: self.analysis.selection.set_from_points(pos1, pos2) except: pass figure = Figure(process_selection=selection_callback) return figure @on_trait_change('filenames.selected') def open_image(self): data = imread(self.filenames.selected) for f in self.filters: data = f.process(data) self.data = data @on_trait_change('data,analysis.updated') def image_show(self): try: self.figure.plot_image(self.data) except: pass @on_trait_change('analysis.updated') def show_selection2(self): def plot(selection, color, index): s = selection x, y = list( map(lambda *args: args, s.top_left, s.top_right, s.bottom_right, s.bottom_left, s.top_left)) self.figure.plot_data(x, y, str(index), color) for i in range(len(self.analysis.selections) + 1): self.figure.del_plot(str(i)) for index, selection in enumerate(self.analysis.selections): if self.analysis.index == index: color = 'red' else: color = 'black' try: plot(selection, color, index) except: pass view = View( VSplit(HSplit(Item('figure', style='custom', width=0.6, height=0.7), Group(Item('analysis', style="custom", resizable=True, width=0.4, height=0.7, show_label=False), scrollable=True), show_labels=False), HSplit( Group( Item('filenames', style='custom', show_label=False, height=0.3)), Item('filters@', id='notebook', show_label=False, editor=ListEditor(use_notebook=True, deletable=False, selected='selected', export='DockWindowShell', page_name='.name_'))), show_labels=False), width=1000, height=800, resizable=True, )
class ImageTimeseriesViewer(BaseDataViewer): plots = Dict plotdata = Instance(ArrayPlotData) image = Any time_index = Int time_points = Int time = Any traits_view = View( Tabbed( HSplit( VGroup( Item('plot', editor=ComponentEditor(), show_label=False, resizable=True, label='View'), Item("time_index", style='custom', editor=RangeEditor(low=0, high_name='time_points')), Item("time", style='readonly'), ), Item('tasks', style='custom', show_label=False, label='Tasks'), ), Item('results', style='custom', show_label=False, label='Results'), ), ) def _time_points_default(self): return self.data.shape[0] - 1 def _time_index_default(self): return 0 def _time_default(self): return self.get_data_time(0, 0) def _plotdata_default(self): data = self.get_data_slice(0, 0) plotdata = ArrayPlotData() plotdata.set_data('xy', data) return plotdata def _time_index_changed(self): self.select_xy_slice(self.time_index) def select_xy_slice(self, t): data = self.get_data_slice(t, 0) self.time = self.get_data_time(t, 0) self.plotdata.set_data('xy', data) self.image.invalidate_and_redraw() def reset(self): pass def redraw(self): self.image.invalidate_and_redraw() def get_plot(self): pixel_sizes = self.data_source.pixel_sizes shape = self.data.shape[1:] m = min(pixel_sizes) s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)] plot_sizes = dict(xy=(s[1], s[0])) plot = Plot( self.plotdata, padding=30, fixed_preferred_size=plot_sizes['xy'], ) image = plot.img_plot('xy', colormap=bone)[0] image.overlays.append(ZoomTool(image)) image.tools.append(PanTool(image, drag_button='right')) imgtool = ImageInspectorTool(image) image.tools.append(imgtool) overlay = ImageInspectorOverlay(component=image, bgcolor='white', image_inspector=imgtool) image.overlays.append(overlay) self.image = image self.plots = dict(xy=image) return plot
# -*- coding: utf-8 -*-
class MainWindow(HasTraits): parameter_file_collections = Instance(ParameterFileCollectionList) parameter_files = Instance(ParameterFileCollection) plot_frame_tabs = List(Instance(DataObject)) open_parameterfile = Button shell = PythonValue def _shell_default(self): return globals() notebook_editor = ListEditor(editor=InstanceEditor(editable=True), use_notebook=True) traits_view = View( VSplit( HSplit( VGroup( Item( 'parameter_file_collections', width=120.0, height=500.0, show_label=False, editor=TreeEditor( editable=False, nodes=[ TreeNode( node_for=[ParameterFileCollectionList], children='parameter_file_collections', label="=Data Collections"), TreeNode(node_for=[ParameterFileCollection], children='parameter_files', label="name", view=View()), TreeNode(node_for=[ParameterFile], children='data_objects', label="name", menu=Menu( Action(name='Slice', action='object.do_slice'), Action(name='Project', action='object.do_proj'), Action(name='VTK', action='object.do_vtk')), view=View()), TreeNode(node_for=[DataObject], children='', label="name"), ], show_icons=False), ), Item('open_parameterfile', show_label=False)), Item('plot_frame_tabs', style='custom', editor=notebook_editor, show_label=False, height=500.0, width=500.0), ), HGroup( #Item('shell', editor=ShellEditor(share=True), #show_label=False, height=120.0), ), ), resizable=True, width=800.0, height=660.0, title="reason v2 [prototype]") def _open_parameterfile_fired(self): print "OPENING" def _parameter_file_collections_default(self): return ParameterFileCollectionList()