def wait_statement(self, wtime, N=5): ''' ''' start_time = time.time() if self.debug: time.sleep(1) else: if isinstance(wtime, str): wtime = float(self._get_interpolation_value(wtime)) if wtime > N: c = Condition() c.acquire() wd = WaitDialog(wtime=wtime, condition=c, parent=self) do_later(wd.edit_traits, kind='livemodal') c.wait() c.release() do_later(wd.close) else: time.sleep(wtime) msg = 'actual wait time %0.3f s' % (time.time() - start_time) self.log_statement(msg)
def __init__(self, model=None, **metadata): """ Setup and initialize the plot. """ tui.ModelView.__init__(self, model=model, **metadata) axes = self.figure.add_subplot(111) self.lines = [] for i in range(self.model.timeseries.shape[1] - 1): line, = axes.plot([0], [1], color='mistyrose', alpha=.5) self.lines.append(line) axes.set_title('Frequency Content') axes.set_ylabel(r'Signal Strength ($\mu$V/sqrt(Hz))') axes.set_xlabel('Frequency (Hz)') axes.set_xticks([i * 10 for i in range(10)]) # multiples of 10 axes.set_xlim( 0, 65, # SAMPLE_RATE / 2, auto=False) # axes.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) # axes.set_yticks(y_ticks) # axes.set_yticklabels(y_labels) axes.set_yscale('log') self.axes = axes # l/b/r/t do_later(self.figure.tight_layout ) # optimize padding and layout after everything's set up.
def _mouse_click(self, event, trait): """ Generate a TabularEditorEvent event for a specified mouse event and editor trait name. """ x = event.GetX() row, flags = self.control.HitTest(wx.Point(x, event.GetY())) if row == wx.NOT_FOUND: if self.factory.multi_select: self.multi_selected = [] self.multi_selected_rows = [] else: self.selected = None self.selected_row = -1 else: if self.factory.multi_select and event.ShiftDown(): # Handle shift-click multi-selections because the wx.ListCtrl # does not (by design, apparently). # We must append this to the event queue because the # multi-selection will not be recorded until this event handler # finishes and lets the widget actually handle the event. do_later(self._item_selected, None) setattr( self, trait, TabularEditorEvent(editor=self, row=row, column=self._get_column(x, translate=True))) # wx should continue with additional event handlers. Skip(False) # actually means to skip looking, skip(True) means to keep looking. # This seems backwards to me... event.Skip(True)
def _file_position_changed ( self, file_position ): """ Handles the 'file_position' trait being changed. """ if file_position is not None: # Reset the current file position to None, so we are ready for a # new one: do_later( self.set, file_position = None ) viewers = self.viewers for i, viewer in enumerate( viewers ): if ((file_position.name == viewer.name) and (file_position.file_name == viewer.file_name) and (file_position.lines == viewer.lines) and (file_position.object == viewer.object)): viewer.selected_line = file_position.line if i == (len( viewers ) - 1): return del viewers[i] break else: # Create the viewer: viewer = AnFBIViewer( **file_position.get( 'name', 'file_name', 'line', 'lines', 'object' ) ) # Make sure the # of viewers doesn't exceed the maximum allowed: if len( viewers ) >= self.max_viewers: del viewers[0] # Add the new viewer to the list of viewers (which will cause it to # appear as a new notebook page): viewers.append( viewer )
def object_ok_changed ( self, info ): """ Handles the user clicking the OK button. """ if self.is_save_file and exists( self.file_name ): do_later( self._file_already_exists ) else: info.ui.dispose( True )
def _project_changed_for_model_service(self, object, name, old, new): """ Detects if an autosaved version exists for the project, and displays a dialog to confirm restoring the project from the autosaved version. """ if old is not None: self.timer = None if new is not None: # Check if an autosaved version exists and if so, display a dialog # asking if the user wishes to restore the project from the # autosaved version. # Note: An autosaved version should exist only if the app crashed # unexpectedly. Regular exiting of the workbench should cause the # autosaved version to be deleted. autosave_loc = self._get_autosave_location(new.location.strip()) if (os.path.exists(autosave_loc)): # Issue a do_later command here so as to allow time for the # project view to be updated first to reflect the current # project's state. do_later(self._restore_from_autosave, new, autosave_loc) else: self._start_timer(new) return
def _item_changed(self, item): """ Handles the 'item' trait being changed. """ if isinstance(item, HasPayload): item = item.payload if isinstance(item, TraitsNode): item = item.value if item is not None: inspectors = [] self._file_names = [] description = '' for klass in item.__class__.__mro__: module = klass.__module__.split('.') module_name = module[-1] if module_name != '__builtin__': module_name += '.py' if len(description) > 0: description += ' -> ' description += '%s[%s]' % (klass.__name__, module_name) inspector = self.inspector_for(join(*module), item) if inspector is not None: inspectors.append(inspector) self._file_names.append(inspector.file_name) self.inspectors = inspectors self.description = description do_later(self.set, item=None)
def _project_changed_for_model_service(self, object, name, old, new): """ Detects if an autosaved version exists for the project, and displays a dialog to confirm restoring the project from the autosaved version. """ if old is not None: self.timer = None if new is not None: # Check if an autosaved version exists and if so, display a dialog # asking if the user wishes to restore the project from the # autosaved version. # Note: An autosaved version should exist only if the app crashed # unexpectedly. Regular exiting of the workbench should cause the # autosaved version to be deleted. autosave_loc = self._get_autosave_location(new.location.strip()) if os.path.exists(autosave_loc): # Issue a do_later command here so as to allow time for the # project view to be updated first to reflect the current # project's state. do_later(self._restore_from_autosave, new, autosave_loc) else: self._start_timer(new) return
def _search_results_items_changed(self, event): """ Add/remove the items from the context. This should only get called when the user adds or deletes a row from the GUI. Changing the search term does not affect this. Unique names are enforced. The enforcement is done here because the variables are constructed before being put on the list so this is the first opportunity to check with the context. """ # XXX: use the undo framework for this. self.context.defer_events = True for var in event.added: var.name = self._create_unique_key(var.name) self.context[var.name] = var.value for var in event.removed: del self.context[var.name] # This may have been triggered by creating a new var with the UI, # in which case, adding the new row needs to finish before we handle # the context events. def _enable_events(context): context.defer_events = False do_later(_enable_events, self.context)
def _item_changed ( self, item ): """ Handles the 'item' trait being changed. """ if isinstance( item, HasPayload ): item = item.payload if isinstance( item, TraitsNode ): item = item.value if item is not None: inspectors = [] self._file_names = [] description = '' for klass in item.__class__.__mro__: module = klass.__module__.split( '.' ) module_name = module[-1] if module_name != '__builtin__': module_name += '.py' if len( description ) > 0: description += ' -> ' description += '%s[%s]' % ( klass.__name__, module_name ) inspector = self.inspector_for( join( *module ), item ) if inspector is not None: inspectors.append( inspector ) self._file_names.append( inspector.file_name ) self.inspectors = inspectors self.description = description do_later( self.set, item = None )
def _mouse_click(self, event, trait): """ Generate a TabularEditorEvent event for a specified mouse event and editor trait name. """ x = event.GetX() row, flags = self.control.HitTest(wx.Point(x, event.GetY())) if row == wx.NOT_FOUND: if self.factory.multi_select: self.multi_selected = [] self.multi_selected_rows = [] else: self.selected = None self.selected_row = -1 else: if self.factory.multi_select and event.ShiftDown(): # Handle shift-click multi-selections because the wx.ListCtrl # does not (by design, apparently). # We must append this to the event queue because the # multi-selection will not be recorded until this event handler # finishes and lets the widget actually handle the event. do_later(self._item_selected, None) setattr(self, trait, TabularEditorEvent( editor=self, row=row, column=self._get_column(x, translate=True) )) # wx should continue with additional event handlers. Skip(False) # actually means to skip looking, skip(True) means to keep looking. # This seems backwards to me... event.Skip(True)
def main(args=None): if args is None: args = sys.argv[1:] if '-h' in args or '--help' in args: usage() sys.exit(0) if '-v' in args: logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) args.remove('-v') kw = {} files = [] scripts = [] directory = None for arg in args: if '=' not in arg: if arg.endswith('.py'): scripts.append(arg) continue elif arg.endswith(output_formats): try: _sort_key(arg) except ValueError: print("Error: file name is not supported") print("filename format accepted is *_number.npz" " or *_number.hdf5") sys.exit(1) files.extend(glob.glob(arg)) continue elif os.path.isdir(arg): directory = arg continue else: usage() sys.exit(1) key, arg = [x.strip() for x in arg.split('=')] try: val = eval(arg, math.__dict__) # this will fail if arg is a string. except Exception: val = arg kw[key] = val sort_file_list(files) live_mode = (len(files) == 0 and directory is None) # If we set the particle arrays before the scene is activated, the arrays # are not displayed on screen so we use do_later to set the files. m = MayaviViewer(live_mode=live_mode) if files: kw['files'] = files if directory: kw['directory'] = directory do_later(m.trait_set, **kw) for script in scripts: do_later(m.run_script, script) m.configure_traits()
def _client_changed(self, old, new): if not self.live_mode: return self._clear() if new is None: return else: self.pa_names = self.client.controller.get_particle_array_names() self.particle_arrays = [ self._make_particle_array_helper(self.scene, x) for x in self.pa_names ] self.interpolator = InterpolatorView(scene=self.scene) do_later(self.update_plot) output_dir = self.client.controller.get_output_directory() config_file = os.path.join(output_dir, 'mayavi_config.py') if os.path.exists(config_file): do_later(self.run_script, config_file) else: # Turn on the legend for the first particle array. if len(self.particle_arrays) > 0: self.particle_arrays[0].trait_set(show_legend=True, show_time=True)
def _object_changed(self, object): """ Handles the 'object' trait being changed. """ if object is not None: # Reset the current object to None, so we are ready for a new one: do_later(self.set, object=None) name = title = '' if isinstance(object, HasPayload): name = object.payload_name title = object.payload_full_name object = object.payload viewers = self.viewers for i, viewer in enumerate(viewers): if object is viewer.object: if i == (len(viewers) - 1): return del viewers[i] break else: # Create the viewer: viewer = AnObjectViewer(name=name, title=title).set(object=object) # Make sure the # of viewers doesn't exceed the maximum allowed: if len(viewers) >= self.max_viewers: del viewers[0] # Add the new viewer to the list of viewers (which will cause it to # appear as a new notebook page): viewers.append(viewer)
def __init__(self, model=None, **metadata): """ Setup and initialize the plot. """ tui.ModelView.__init__(self, model=model, **metadata) axes = self.figure.add_subplot(111) self.lines = [] for i in range(self.model.timeseries.shape[1] - 1): line, = axes.plot([0], [1], color='mistyrose', alpha=.5) self.lines.append(line) axes.set_title('Frequency Content') axes.set_ylabel(r'Signal Strength ($\mu$V/sqrt(Hz))') axes.set_xlabel('Frequency (Hz)') axes.set_xticks([i * 10 for i in range(10)]) # multiples of 10 axes.set_xlim(0, 65, # SAMPLE_RATE / 2, auto=False) # axes.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) # axes.set_yticks(y_ticks) # axes.set_yticklabels(y_labels) axes.set_yscale('log') self.axes = axes # l/b/r/t do_later(self.figure.tight_layout) # optimize padding and layout after everything's set up.
def _object_changed ( self, object ): """ Handles the 'object' trait being changed. """ if object is not None: # Reset the current object to None, so we are ready for a new one: do_later( self.set, object = None ) name = title = '' if isinstance( object, HasPayload ): name = object.payload_name title = object.payload_full_name object = object.payload viewers = self.viewers for i, viewer in enumerate( viewers ): if object is viewer.object: if i == (len( viewers ) - 1): return del viewers[i] break else: # Create the viewer: viewer = AnObjectViewer( name = name, title = title ).set( object = object ) # Make sure the # of viewers doesn't exceed the maximum allowed: if len( viewers ) >= self.max_viewers: del viewers[0] # Add the new viewer to the list of viewers (which will cause it to # appear as a new notebook page): viewers.append( viewer )
def __init__(self, **traits): """ Initializes the object. """ super(ObjectDebugger, self).__init__(**traits) self.module = CBModuleFile(path=self.file_name, python_path=self.python_path, object=self.object) do_later(self.select_object)
def __init__ ( self, **traits ): """ Initializes the object. """ super( ObjectDebugger, self ).__init__( **traits ) self.module = CBModuleFile( path = self.file_name, python_path = self.python_path, object = self.object ) do_later( self.select_object )
def _profile_changed ( self, file_position ): """ Handles the 'profile' trait being changed. """ if file_position is not None: do_later( self.set, profile = None ) if file_position.class_name != '': if file_position.method_name != '': self.add_method( file_position ) else: self.add_class( file_position )
def _filter_changed(self, old_filter, new_filter): """Handles the current filter being changed.""" if not self._no_notify: if new_filter is customize_filter: do_later(self._customize_filters, old_filter) else: self._update_filtering() self.model.invalidate() self.set_selection(self.selected)
def _profile_changed(self, file_position): """ Handles the 'profile' trait being changed. """ if file_position is not None: do_later(self.set, profile=None) if file_position.class_name != '': if file_position.method_name != '': self.add_method(file_position) else: self.add_class(file_position)
def add_paths ( self, paths ): """ Adds paths to the work queue. """ paths = [ cb_path.path for cb_path in paths if cb_path.path not in self.paths ] if len( paths ) > 0: self.paths.extend( paths ) if self.lock is None: self.lock = Lock() do_later( self.start_thread ) self.init_queue( paths )
def on_auto_add_row(self): """ Handles the user modifying the current 'auto_add' mode row. """ object = self.auto_add_row object.on_trait_change(self.on_auto_add_row, remove=True) self.auto_add_row = row = self.editor.create_new_row() if row is not None: row.on_trait_change(self.on_auto_add_row, dispatch="ui") do_later(self.editor.add_row, object, len(self.get_filtered_items()) - 2)
def _size_modified(self, event): """Handles the size of the list control being changed.""" control = self.control n = control.GetColumnCount() if n == 1: dx, dy = control.GetClientSize() control.SetColumnWidth(0, dx - 1) elif n > 1: do_later(self._set_column_widths) event.Skip()
def on_auto_add_row(self): """Handles the user modifying the current 'auto_add' mode row.""" object = self.auto_add_row object.on_trait_change(self.on_auto_add_row, remove=True) self.auto_add_row = row = self.editor.create_new_row() if row is not None: row.on_trait_change(self.on_auto_add_row, dispatch="ui") do_later(self.editor.add_row, object, len(self.get_filtered_items()) - 2)
def _size_modified(self, event): """ Handles the size of the list control being changed. """ control = self.control n = control.GetColumnCount() if n == 1: dx, dy = control.GetClientSizeTuple() control.SetColumnWidth(0, dx - 1) elif n > 1: do_later(self._set_column_widths) event.Skip()
def add_paths(self, paths): """ Adds paths to the work queue. """ paths = [ cb_path.path for cb_path in paths if cb_path.path not in self.paths ] if len(paths) > 0: self.paths.extend(paths) if self.lock is None: self.lock = Lock() do_later(self.start_thread) self.init_queue(paths)
def _value_changed(self, event): """Handles the history object's 'value' trait being changed.""" if not self._dont_update: history = self.history try: self._dont_update = True self.value = history.value history.error = False except: history.error = True do_later(self.trait_set, _dont_update=False)
def _value_changed(self, value): """ Handles the history object's 'value' trait being changed. """ if not self._dont_update: history = self.history try: self._dont_update = True self.value = history.value history.error = False except: history.error = True do_later(self.set, _dont_update=False)
def main(args=None): if args is None: args = sys.argv[1:] if '-h' in args or '--help' in args: usage() sys.exit(0) if '-v' in args: logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) args.remove('-v') kw = {} files = [] scripts = [] for arg in args: if '=' not in arg: if arg.endswith('.py'): scripts.append(arg) continue elif arg.endswith(output_formats): files.extend(glob.glob(arg)) continue elif os.path.isdir(arg): _files = glob.glob(os.path.join(arg, '*.hdf5')) if len(_files) == 0: _files = glob.glob(os.path.join(arg, '*.npz')) files.extend(_files) continue else: usage() sys.exit(1) key, arg = [x.strip() for x in arg.split('=')] try: val = eval(arg, math.__dict__) # this will fail if arg is a string. except NameError: val = arg kw[key] = val sort_file_list(files) live_mode = len(files) == 0 # If we set the particle arrays before the scene is activated, the arrays # are not displayed on screen so we use do_later to set the files. m = MayaviViewer(live_mode=live_mode) do_later(m.set, files=files, **kw) for script in scripts: do_later(m.run_script, script) m.configure_traits()
def _load_history(self, restore=None, select=True): """Loads the current history list into the control.""" control = self.control control.Freeze() if restore is None: restore = control.GetValue() control.Clear() for value in self.history: control.Append(value) self._restore = True do_later(self._thaw_value, restore, select)
def _load_history(self, restore=None, select=True): """ Loads the current history list into the control. """ control = self.control control.Freeze() if restore is None: restore = control.GetValue() control.Clear() for value in self.history: control.Append(value) self._restore = True do_later(self._thaw_value, restore, select)
def warning(self, msg, decorate=True): ''' ''' if self.logger is not None: if self.use_warning_display: from src.helpers.gdisplays import gWarningDisplay if globalv.show_warnings: if not gWarningDisplay.opened and not gWarningDisplay.was_closed: do_later(gWarningDisplay.edit_traits) gWarningDisplay.add_text('{{:<{}s}} -- {{}}'.format(NAME_WIDTH).format(self.logger.name.strip(), msg)) if decorate: msg = '****** {}'.format(msg) self._log_('warning', msg)
def sync_camera(reference_figure, target_figure): """ Synchronise the camera of the target_figure on the camera of the reference_figure. """ reference_figure.scene._renderer.sync_trait('active_camera', target_figure.scene._renderer) target_figure.scene._renderer.active_camera.on_trait_change( lambda: do_later(target_figure.scene.render))
def info(self, msg, decorate=True, dolater=False, color=None): ''' ''' if self.logger is not None: if self.use_logger_display: from src.helpers.gdisplays import gLoggerDisplay if globalv.show_infos: if not gLoggerDisplay.opened and not gLoggerDisplay.was_closed: do_later(gLoggerDisplay.edit_traits) args = ('{{:<{}s}} -- {{}}'.format(NAME_WIDTH).format(self.logger.name.strip(), msg)) gLoggerDisplay.add_text(args, color=color) if decorate: msg = '====== {}'.format(msg) self._log_('info', msg)
def _calculate_indicator_positions(self, shift=None): ccm = self.camera_calibration_manager zoom = self.parent.zoom src, name = self.video_manager.snapshot(identifier=zoom) ccm.image_factory(src=src) ccm.process_image() ccm.title = name cond = Condition() ccm.cond = cond cond.acquire() do_later(ccm.edit_traits, view='snapshot_view') if shift: self.stage_controller.linear_move(*shift, block=False) cond.wait() cond.release()
def toggle_feature ( cls, event ): """ Toggles the feature on or off. """ if cls.state == 0: cls.state = 1 add_feature( cls ) for control in event.window.control.GetChildren(): window = getattr( control, 'owner', None ) if isinstance( window, DockWindow ): do_later( window.update_layout ) else: method = 'disable' cls.state = 3 - cls.state if cls.state == 1: method = 'enable' cls.instances = [ aref for aref in cls.instances if aref() is not None ] for aref in cls.instances: feature = aref() if feature is not None: getattr( feature, method )()
def __init__(self, model=None, **metadata): """ Set up and initialize the plot. """ tui.ModelView.__init__(self, model=model, **metadata) axes = self.figure.add_subplot(111) self.lines = [] y_ticks = [] y_labels = [] y_labels2 = [] for i in range(self.model.timeseries.shape[1] - 1): line, = axes.plot( self.model.timeseries[::PLOT_STEP, 0], self.model.timeseries[::PLOT_STEP, i + 1] / self.y_lim_uv + i, color='mistyrose', alpha=.75, linewidth=0.5) self.lines.append(line) y_ticks.append(i) y_labels.append('Ch %d' % (i + 1)) y_labels2.append('Mean: 0.0\nRMS: 0.0') axes.set_title('EEG Timeseries') # axes.set_ylabel('Amplitude') axes.set_xlabel('Time [s]') axes.set_xlim(0, X_WIDTH_S, auto=False) axes.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) axes.set_yticks(y_ticks) axes.set_yticklabels(y_labels) self.axes = axes # Right axes # self.axes_r = self.figure.add_subplot(1, 1, 1, sharex=axes, frameon=False) # self.axes_r.yaxis.tick_right() # self.axes_r.yaxis.set_label_position("right") # self.axes_r.set_yticks(y_ticks) # self.axes_r.tick_params(axis='y', which='both', length=0) # self.axes_r.set_yticklabels(y_labels2, {'size':8}) # self.axes_r.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) # l/b/r/t do_later(self.figure.tight_layout ) # optimize padding and layout after everything's set up.
def __init__(self, model=None, **metadata): """ Set up and initialize the plot. """ tui.ModelView.__init__(self, model=model, **metadata) axes = self.figure.add_subplot(111) self.lines = [] y_ticks = [] y_labels = [] y_labels2 = [] for i in range(self.model.timeseries.shape[1] - 1): line, = axes.plot( self.model.timeseries[::PLOT_STEP, 0], self.model.timeseries[::PLOT_STEP, i + 1] / self.y_lim_uv + i, color="mistyrose", alpha=0.75, linewidth=0.5, ) self.lines.append(line) y_ticks.append(i) y_labels.append("Ch %d" % (i + 1)) y_labels2.append("Mean: 0.0\nRMS: 0.0") axes.set_title("EEG Timeseries") # axes.set_ylabel('Amplitude') axes.set_xlabel("Time [s]") axes.set_xlim(0, X_WIDTH_S, auto=False) axes.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) axes.set_yticks(y_ticks) axes.set_yticklabels(y_labels) self.axes = axes # Right axes # self.axes_r = self.figure.add_subplot(1, 1, 1, sharex=axes, frameon=False) # self.axes_r.yaxis.tick_right() # self.axes_r.yaxis.set_label_position("right") # self.axes_r.set_yticks(y_ticks) # self.axes_r.tick_params(axis='y', which='both', length=0) # self.axes_r.set_yticklabels(y_labels2, {'size':8}) # self.axes_r.set_ylim(-1, self.model.timeseries.shape[1] - 1, auto=False) # l/b/r/t do_later(self.figure.tight_layout) # optimize padding and layout after everything's set up.
def main(args=None): if args is None: args = sys.argv[1:] if '-h' in args or '--help' in args: usage() sys.exit(0) if '-v' in args: logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) args.remove('-v') kw = {} files = [] for arg in args: if '=' not in arg: if arg.endswith('.npz'): files.extend(glob.glob(arg)) continue else: usage() sys.exit(1) key, arg = [x.strip() for x in arg.split('=')] try: val = eval(arg, math.__dict__) # this will fail if arg is a string. except NameError: val = arg kw[key] = val sort_file_list(files) # This hack to set n_files first is a dirty hack to work around issues with # setting up the UI but setting the files only after the UI is activated. # If we set the particle arrays before the scene is activated, the arrays # are not displayed on screen so we use do_later to set the files. We set # n_files to number of files so as to set the UI up correctly. m = MayaviViewer(n_files=len(files) - 1) do_later(m.set, files=files, **kw) m.configure_traits()
def _file_position_changed ( self, file_position ): """ Handles the 'file_position' trait being changed. """ if file_position is not None: do_later( self.set, file_position = None ) # Try to create a new ProfilerStats viewer: try: p_stats = ProfilerStats( owner = self, name = file_position.name, file_name = file_position.file_name ) except: return stats = self.stats # Make sure the # of stats doesn't exceed the maximum allowed: if len( stats ) >= self.max_stats: del stats[0] # Add the new stats to the list of stats (which will cause it to # appear as a new notebook page): stats.append( p_stats )
def _file_position_changed(self, file_position): """ Handles the 'file_position' trait being changed. """ if file_position is not None: do_later(self.set, file_position=None) # Try to create a new ProfilerStats viewer: try: p_stats = ProfilerStats(owner=self, name=file_position.name, file_name=file_position.file_name) except: return stats = self.stats # Make sure the # of stats doesn't exceed the maximum allowed: if len(stats) >= self.max_stats: del stats[0] # Add the new stats to the list of stats (which will cause it to # appear as a new notebook page): stats.append(p_stats)
def __plot_default(self): plot = self.plot_line() self.plot_updater.start() do_later(self.recenter_plot) return plot
#============= views =================================== def traits_view(self): v = View( Item('control', show_label=False, style='custom'), # VGroup( # Item('laser_amps', format_str = '%0.2f', style = 'readonly'), # Item('laser_temperature', format_str = '%0.2f', style = 'readonly'), # Item('laser_power', format_str = '%0.2f', style = 'readonly'), # Item('laser_voltage', format_str = '%0.2f', style = 'readonly'), # ), # handler = self.handler_klass, width=500, height=500, resizable=True ) return v if __name__ == '__main__': from src.helpers.logger_setup import logging_setup logging_setup('vue_metrix') v = VueMetrixManager() v.control.bootstrap() do_later(v.start) v.configure_traits() #============= EOF ====================================
def _window_changed(self, window): if window is not None: self.root = WXWindow(window=window) do_later(self.set, window=None)
def _item_changed ( self, item ): """ Handles the 'item' trait being changed. """ # Check to see if it is a list of File objects, which represent files # dropped onto the view from an external source (like MS Explorer): if isinstance( item, list ) and (len( item ) > 0): for an_item in item: if not isinstance( an_item, File ): break else: for an_item in item: self._item_changed( an_item ) return # Set up the default values: name = full_name = '' line = 0 lines = -1 # Extract the file name from a File object: if isinstance( item, File ): item = item.absolute_path # Handle the case of an item which contains a payload: elif isinstance( item, HasPayload ): name = item.payload_name full_name = item.payload_full_name item = item.payload # Handle the case of a file position, which has a file name and a # possible starting line and range of lines: if isinstance( item, FilePosition ): name = item.name line = item.line lines = item.lines item = item.file_name # Only create an inspector if there actually is a valid item: if item is not None: inspector = None # If it is a string value, check to see if it is a valid file name: if isinstance( item, basestring ): data = read_file( item, 'r' ) if data is not None: if name == '': name = basename( item ) full_name = item try: inspector = ObjectInspector( object = self._object_from_pickle( data ), name = name, full_name = full_name ) except: try: inspector = ObjectInspector( object = self._object_from_pickle( read_file( item ) ), name = name, full_name = full_name ) except: inspector = FileInspector( name = name, line = line, lines = lines ).set( file_name = item ) # If it is not a file, then it must just be a generic object: if inspector is None: inspector = ObjectInspector( object = item, name = name, full_name = full_name ) inspectors = self.inspectors # Make sure the # of inspectors doesn't exceed the maximum allowed: if len( inspectors ) >= self.max_inspectors: del inspectors[0] # Add the new inspector to the list of inspectors (which will # cause it to appear as a new notebook page): inspectors.append( inspector ) # Reset the current item to None, so we are ready for a new item: do_later( self.set, item = None )
def create_plot ( parent, editor ): """ Creates a data explorer plot. """ try: nmep = editor.object model = nmep.model items = nmep.plot_items if len( items ) == 0: return wx.Panel( parent, -1 ) index = nmep.plot_index if index is None: plot_index = PlotValue( arange( 0.0, len( model.model_indices ) ) ) selection_index = None else: plot_index = PlotValue( ModelData( model = model, name = index.name ) ) selection_index = PlotValue( SelectionData( model = model, name = index.name ) ) canvas = PlotCanvas( plot_type = items[0].plot_type, plot_bg_color = items[0].canvas_color ) canvas.axis_index = PlotAxis() if index is not None: canvas.axis_index.title = index.label if len( items ) == 1: canvas.axis = PlotAxis( title = items[0].label ) else: canvas.add( PlotGroup( overlay = True, position = 'top right', *[ PlotOverlay( legend_color = item.line_color, text = item.label, border_size = 0, bg_color = transparent, margin = 0, padding = 2 ) for item in items ] ) ) for item in items: canvas.add( PlotValue( ModelData( model = model ).set( name = item.name ), index = plot_index, plot_type = item.plot_type, line_weight = item.line_weight, line_color = item.line_color, fill_color = item.fill_color, outline_color = item.outline_color, size = 'small' ) ) if selection_index is not None: plot_value = PlotValue( SelectionData( model = model ).set( name = item.name ), index = selection_index, plot_type = 'scatter', size = item.selection_size, fill_color = item.selection_color ) canvas.add( plot_value ) # Set up the interactive data filters: if selection_index is not None: canvas.interaction = nmep._interaction = ia = \ NumericModelExplorerInteraction( value = plot_value ) nmep._selection_models = sms = [] ia._filters = filters = [] for item in items: sm = model.get_selection_model() sms.append( sm ) sm.model_filter = PolygonFilter( x_value = index.name, y_value = item.name ) filters.append( sm.model_filter ) ia.on_trait_change( editor.ui.handler.interaction_complete, 'points' ) if len( nmep.polygon ) > 0: do_later( ia.set_selection, nmep.polygon ) return Window( parent, component = PlotComponent( component = canvas ) ).control except: import traceback traceback.print_exc() raise
def _value_changed ( self, value ): """ Handles the 'value' being changed. """ do_later( self._close_popup )
def __plot_default(self): plot = ChacoPlot(self._plot_data) # recenter_plot() requires self._plot to be defined do_later(self.recenter_plot) return plot
def RecalcSizes ( self ): """ Layout the contents of the sizer based on the sizer's current size and position. """ horizontal = (self._orient == wx.HORIZONTAL) x, y = self.GetPosition() dx, dy = self.GetSize() x0, y0 = x, y ex = x + dx ey = y + dy mdx = mdy = sdx = sdy = i = 0 visible = True cur_max = 0 while True: try: item = self.GetItem( i ) if item is None: break i += 1 except: break idx, idy = item.CalcMin() expand = item.GetFlag() & wx.EXPAND if horizontal: if (x > x0) and ((x + idx) > ex): x = x0 y += (mdy + sdy) mdy = sdy = 0 if y >= ey: visible = False cur_max = max( idy, cur_max ) if expand: idy = cur_max if item.IsSpacer(): sdy = max( sdy, idy ) if x == x0: idx = 0 item.SetDimension( wx.Point( x, y ), wx.Size( idx, idy ) ) item.Show( visible ) x += idx mdy = max( mdy, idy ) else: if (y > y0) and ((y + idy) > ey): y = y0 x += (mdx + sdx) mdx = sdx = 0 if x >= ex: visible = False cur_max = max( idx, cur_max ) if expand: idx = cur_max if item.IsSpacer(): sdx = max( sdx, idx ) if y == y0: idy = 0 item.SetDimension( wx.Point( x, y ), wx.Size( idx, idy ) ) item.Show( visible ) y += idy mdx = max( mdx, idx ) if (not visible) and (self._needed_size is None): max_dx = max_dy = 0 if horizontal: max_dy = max( dy, y + mdy + sdy - y0 ) else: max_dx = max( dx, x + mdx + sdx - x0 ) self._needed_size = wx.Size( max_dx, max_dy ) if not self._frozen: self._do_parent( '_freeze' ) do_later( self._do_parent, '_thaw' ) else: self._needed_size = None
def _value_changed(self, value): """ Handles the 'value' being changed. """ do_later(self._close_popup)
def create_plot(parent, editor): """ Creates a data explorer plot. """ try: nmep = editor.object model = nmep.model items = nmep.plot_items if len(items) == 0: return wx.Panel(parent, -1) index = nmep.plot_index if index is None: plot_index = PlotValue(arange(0.0, len(model.model_indices))) selection_index = None else: plot_index = PlotValue(ModelData(model=model, name=index.name)) selection_index = PlotValue( SelectionData(model=model, name=index.name)) canvas = PlotCanvas(plot_type=items[0].plot_type, plot_bg_color=items[0].canvas_color) canvas.axis_index = PlotAxis() if index is not None: canvas.axis_index.title = index.label if len(items) == 1: canvas.axis = PlotAxis(title=items[0].label) else: canvas.add( PlotGroup(overlay=True, position='top right', *[ PlotOverlay(legend_color=item.line_color, text=item.label, border_size=0, bg_color=transparent, margin=0, padding=2) for item in items ])) for item in items: canvas.add( PlotValue(ModelData(model=model).set(name=item.name), index=plot_index, plot_type=item.plot_type, line_weight=item.line_weight, line_color=item.line_color, fill_color=item.fill_color, outline_color=item.outline_color, size='small')) if selection_index is not None: plot_value = PlotValue( SelectionData(model=model).set(name=item.name), index=selection_index, plot_type='scatter', size=item.selection_size, fill_color=item.selection_color) canvas.add(plot_value) # Set up the interactive data filters: if selection_index is not None: canvas.interaction = nmep._interaction = ia = \ NumericModelExplorerInteraction( value = plot_value ) nmep._selection_models = sms = [] ia._filters = filters = [] for item in items: sm = model.get_selection_model() sms.append(sm) sm.model_filter = PolygonFilter(x_value=index.name, y_value=item.name) filters.append(sm.model_filter) ia.on_trait_change(editor.ui.handler.interaction_complete, 'points') if len(nmep.polygon) > 0: do_later(ia.set_selection, nmep.polygon) return Window(parent, component=PlotComponent(component=canvas)).control except: import traceback traceback.print_exc() raise