class ThresholdFactory(PipeFactory): """Applies the Threshold mayavi filter to the given VTK object.""" _target = Instance(filters.Threshold, ()) filter_type = Enum('cells', 'points', adapts='filter_type', help="If threshold is put on cells or points") low = Trait(None, None, CFloat, help="The lower threshold") def _low_changed(self): if self.low == None: pass else: self._target.lower_threshold = self.low up = Trait(None, None, CFloat, help="The upper threshold") def _up_changed(self): if self.up == None: pass else: self._target.upper_threshold = self.up
class Widget(HasTraits): part1 = Trait(Part) part2 = Trait(Part) cost = Float(0.0) def __init__(self): self.part1 = Part() self.part2 = Part() self.part1.on_trait_change(self.update_cost, 'cost') self.part2.on_trait_change(self.update_cost, 'cost') def update_cost(self): self.cost = self.part1.cost + self.part2.cost
class MTraitsNamespace: DPI = Float(72.) Alpha = traits.Range(0., 1., 0.) Affine = Trait(Affine()) AntiAliased = traits.true Color = Trait('black', ColorHandler()) DPI = Float(72.) Interval = Array('d', (2, ), npy.array([0.0, 1.0], npy.float_)) LineStyle = Trait('-', '--', '-.', ':', 'steps', None) LineWidth = Float(1.0) Marker = Trait(None, '.', ',', 'o', '^', 'v', '<', '>', 's', '+', 'x', 'd', 'D', '|', '_', 'h', 'H', 'p', '1', '2', '3', '4') MarkerSize = Float(6) Visible = traits.true
def get_all_traits(self): """ 2012.2.21 this function determines the set of possible keys in kwargs. add two keywords, x_scale, y_scale. Returns all the traits of class, and the classes in the pipeline. """ #call the parental one first. traits = Pipeline.get_all_traits(self) traits['x_scale'] = Trait(0.9, desc='The scale of the glyph on the x-axis, ' 'in units of the distance between nearest points') traits['y_scale'] = Trait(0.9, desc='The scale of the glyph on the y-axis, ' 'in units of the distance between nearest points') return traits
class LoggerPreferences(PreferencesHelper): """ The persistent service exposing the Logger plugin's API. """ #### Preferences ########################################################### # The log levels level = Trait( 'Info', { 'Debug': logging.DEBUG, 'Info': logging.INFO, 'Warning': logging.WARNING, 'Error': logging.ERROR, 'Critical': logging.CRITICAL, }, is_str=True, ) enable_agent = Bool(False) smtp_server = Str() to_address = Str() from_address = Str() # The path to the preferences node that contains the preferences. preferences_path = Str('enthought.logger')
class ImageEnumEditorDemo ( HasTraits ): """ Defines the ImageEnumEditor demo class. """ # Define a trait to view: image_from_list = Trait( editor = ImageEnumEditor( values = image_list, prefix = '@icons:', suffix = '_origin', cols = 4, klass = Dummy ), *image_list ) # Items are used to define the demo display, one Item per editor style: img_group = Group( Item( 'image_from_list', style = 'simple', label = 'Simple' ), Item( '_' ), Item( 'image_from_list', style = 'custom', label = 'Custom' ), Item( '_' ), Item( 'image_from_list', style = 'text', label = 'Text' ), Item( '_' ), Item( 'image_from_list', style = 'readonly', label = 'ReadOnly' ) ) # Demo view: view = View( img_group, title = 'ImageEnumEditor', buttons = [ 'OK' ], resizable = True )
class Axes(AxesLikeModuleFactory): """ Creates axes for the current (or given) object.""" xlabel = String(None, adapts='axes.x_label', help='the label of the x axis') ylabel = String(None, adapts='axes.y_label', help='the label of the y axis') zlabel = String(None, adapts='axes.z_label', help='the label of the z axis') nb_labels = Range(0, 50, 2, adapts='axes.number_of_labels', desc='The number of labels along each direction') ranges = Trait( None, None, CArray(shape=(6, )), help="""[xmin, xmax, ymin, ymax, zmin, zmax] Ranges of the labels displayed on the axes. Default is the object's extents.""", ) x_axis_visibility = true( adapts='axes.x_axis_visibility', help="Whether or not the x axis is visible (boolean)") y_axis_visibility = true( adapts='axes.y_axis_visibility', help="Whether or not the y axis is visible (boolean)") z_axis_visibility = true( adapts='axes.z_axis_visibility', help="Whether or not the z axis is visible (boolean)") _target = Instance(modules.Axes, ()) def _extent_changed(self): """ Code to modify the extents for """ axes = self._target axes.axes.use_data_bounds = False axes.axes.bounds = self.extent if self.ranges is None: axes.axes.ranges = \ axes.module_manager.source.outputs[0].bounds def _ranges_changed(self): if self.ranges is not None: self._target.axes.ranges = self.ranges self._target.axes.use_ranges = True
class Text(ModuleFactory): """ Adds a text on the figure. **Function signature**:: text(x, y, text, ...) x, and y are the position of the origin of the text. If no z keyword argument is given, x and y are the 2D projection of the figure, they belong to [0, 1]. If a z keyword argument is given, the text is positionned in 3D, in figure coordinnates. """ width = Trait(None, None, CFloat, adapts='width', help="""width of the text.""") z = Trait(None, None, CFloat, help="""Optional z position. When specified, the text is positioned in 3D""") _target = Instance(modules.Text, ()) opacity = CFloat(1, adapts="property.opacity", help="""The opacity of the text.""") def __init__(self, x, y, text, **kwargs): """ Override init as for different positional arguments.""" if 'z' in kwargs and kwargs['z'] is not None: self._target.z_position = kwargs['z'] self._target.position_in_3d = True elif not (x < 1. and x > 0. and y > 0. and y < 1.): raise ValueError('Text positions should be in [0, 1] if no z' 'position is given') super(Text, self).__init__(None, **kwargs) self._target.text = text self._target.x_position = x self._target.y_position = y
class TestEnumEditor(HasTraits): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- value = Trait(1, enum, range, editor=EnumEditor(values=values, evaluate=int))
def __init__(self, parent, id): self.Window = wx.Frame.__init__(self, parent, id, 'fMRI Player', size=(800, 500)) self.pnl1 = wx.Panel(self, -1) self.pnl1.SetBackgroundColour(wx.BLACK) self.pnl2 = wx.Panel(self, -1) self.pnl3 = wx.Panel(self, -1) self.pnl4 = wx.Panel(self, -1) self.pnl4.SetBackgroundColour(wx.BLACK) self.nb = wx.Notebook(self, -1) self.timer = wx.Timer(self, -1) self.colormap = Any self.colorcube = Any self.num_figs = 10 self.Data = 0 self.numPC = 100 # number of principal components self.numANOVA_voxels = 100 # number of ANOVA analysis voxels self.pcInd = 0 self.principalComponent = [] self.volume_on = False self.previous_vol = 0 self.best_voxels_ind = [] self.portNum = 9001 self.osc = sn.osc_send(self.portNum) self.TR = 2 #The sample period self.Fs = 1.0 / self.TR #The sample frequency self.Fs = 44100 #The sample frequency self.cmap = Trait(gmt_drywet, Callable) #gmt_drywet,jet self.Voxel = num.zeros(self.num_figs) self.FFTVoxel = num.zeros(self.num_figs) self.frqs = num.zeros(self.num_figs) self.fftPeaks = num.zeros(self.num_figs) self.maxtab = num.zeros(shape=(self.num_figs, 2)) self.path = '../data/exp1-1/' self.restTime = 30 # Pause time in seconds self.verbalCueTime = 8 # Verbal cue time in seconds self.taskTime = 30 # task's time in seconds self.numTaskEpochs = 6 # Number of task epochs pro run self.numRuns = 2 # Number of runs pro subject and experiment self.numTasks = 3 # Number of tasks to attend to self.init_panel() self.init_data() self.init_experiment() self.update_panel() self.update_voxel_data() self.updateOSC() self.draw_plot()
class PickedData(HasTraits): """This class stores the picked data.""" # Was there a valid picked point? valid = Trait(false_bool_trait, desc='specifies the validity of the pick event') # Id of picked point (-1 implies none was picked) point_id = Long(-1, desc='the picked point ID') # Id of picked cell (-1 implies none was picked) cell_id = Long(-1, desc='the picked cell ID') # World pick -- this has no ID. world_pick = Trait(false_bool_trait, desc='specifies if the pick is a world pick.') # Coordinate of picked point. coordinate = Array('d', (3, ), labels=['x', 'y', 'z'], cols=3, desc='the coordinate of the picked point') # The picked data -- usually a tvtk.PointData or tvtk.CellData of # the object picked. The user can use this data and extract any # necessary values. data = Any
class Instance(HasTraits): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- integer_text = Int(1) enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 5) boolean = true view = View('integer_text', 'enumeration', 'float_range', 'int_range', 'boolean')
class CompoundEditorDemo(HasTraits): """ This class specifies the details of the CompoundEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. compound_trait = Trait(1, Range(1, 6), 'a', 'b', 'c', 'd', 'e', 'f') # Display specification (one Item per editor style) comp_group = Group( Item('compound_trait', style='simple', label='Simple'), Item('_'), Item('compound_trait', style='custom', label='Custom'), Item('_'), Item('compound_trait', style='text', label='Text'), Item('_'), Item('compound_trait', style='readonly', label='ReadOnly')) # Demo view view1 = View(comp_group, title='CompoundEditor', buttons=['OK'])
class InstanceEditorDemo(HasTraits): """ This class specifies the details of the InstanceEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. sample_instance = Trait(SampleClass()) # Items are used to define the demo display - one item per # editor style inst_group = Group( Item('sample_instance', style='simple', label='Simple'), Item('_'), Item('sample_instance', style='custom', label='Custom'), Item('_'), Item('sample_instance', style='text', label='Text'), Item('_'), Item('sample_instance', style='readonly', label='ReadOnly')) # Demo View view1 = View(inst_group, title='InstanceEditor', buttons=['OK'])
class FloodFillDemo(HasTraits): lo_diff = Array(np.float, (1, 4)) hi_diff = Array(np.float, (1, 4)) plot = Instance(Plot) point = Tuple((0, 0)) option = Trait(u"以邻点为标准-4联通", Options) view = View(VGroup( VGroup(Item("lo_diff", label=u"负方向范围"), Item("hi_diff", label=u"正方向范围"), Item("option", label=u"算法标志")), Item("plot", editor=ComponentEditor(), show_label=False), ), title=u"FloodFill Demo控制面板", width=500, height=450, resizable=True) def __init__(self, *args, **kwargs): self.lo_diff.fill(5) self.hi_diff.fill(5) self.img = cv.imread("lena.jpg") self.data = ArrayPlotData(img=self.img[:, :, ::-1]) w = self.img.size().width h = self.img.size().height self.plot = Plot(self.data, padding=10, aspect_ratio=float(w) / h) self.plot.x_axis.visible = False self.plot.y_axis.visible = False self.imgplot = self.plot.img_plot("img", origin="top left")[0] self.imgplot.interpolation = "nearest" self.imgplot.overlays.append( PointPicker(application=self, component=self.imgplot)) self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option") def redraw(self): img = self.img.clone() cv.floodFill(img, cv.Point(*self.point), cv.Scalar(255, 0, 0, 255), loDiff=cv.asScalar(self.lo_diff[0]), upDiff=cv.asScalar(self.hi_diff[0]), flags=self.option_) self.data["img"] = img[:, :, ::-1]
class CompoundEditorDemo(HasTraits): """ Defines the main CompoundEditor demo class. """ # Define a compund trait to view: compound_trait = Trait(1, Range(1, 6), 'a', 'b', 'c', 'd', 'e', 'f') # Display specification (one Item per editor style): comp_group = Group( Item('compound_trait', style='simple', label='Simple'), Item('_'), Item('compound_trait', style='custom', label='Custom'), Item('_'), Item('compound_trait', style='text', label='Text'), Item('_'), Item('compound_trait', style='readonly', label='ReadOnly')) # Demo view: view = View(comp_group, title='CompoundEditor', buttons=['OK'], resizable=True)
class Plot3d(Pipeline): """ Draws lines between points. **Function signatures**:: plot3d(x, y, z, ...) plot3d(x, y, z, s, ...) x, y, z and s are numpy arrays or lists of the same shape. x, y and z give the positions of the successive points of the line. s is an optional scalar value associated with each point.""" tube_radius = Trait(0.025, CFloat, None, adapts='filter.radius', help="""radius of the tubes used to represent the lines, If None, simple lines are used. """) _source_function = Callable(line_source) _pipeline = [ StripperFactory, TubeFactory, SurfaceFactory, ] def __call_internal__(self, *args, **kwargs): """ Override the call to be able to choose whether to apply filters. """ self.source = self._source_function(*args, **kwargs) kwargs.pop('name', None) self.store_kwargs(kwargs) # Copy the pipeline so as not to modify it for the next call self.pipeline = self._pipeline[:] if self.kwargs['tube_radius'] == None: self.pipeline.remove(TubeFactory) self.pipeline.remove(StripperFactory) return self.build_pipeline()
class TrimCase(HasTraits): # Instance(RunCase) runcase = Any() type = Trait('horizontal flight', {'horizontal flight':'c1', 'looping flight':'c2'}) parameters = Dict(String, Instance(Parameter)) parameter_view = List(Parameter, []) traits_view = View(Group(Item('type')), Group(Item('parameter_view', editor=Parameter.editor, show_label=False), label='Parameters'), Item(), # so that groups are not tabbed kind='livemodal', buttons=['OK'] ) #@on_trait_change('type,parameters.value') def update_parameters_from_avl(self): #print 'in update_parameters_from_avl' avl = self.runcase.avl avl.sendline('oper') avl.expect(AVL.patterns['/oper']) avl.sendline(self.type_) avl.expect(AVL.patterns['/oper/m']) constraint_lines = [line.strip() for line in avl.before.splitlines()] i1 = constraint_lines.index('=================================================') constraint_lines = constraint_lines[i1:] #print constraint_lines groups = [re.search(RunCase.patterns['parameter'], line) for line in constraint_lines] params = {} for group in groups: if group is not None: group = group.groupdict() pattern = group['pattern'] name = pattern unit = group.get('unit', '') unit = unit if unit is not None else '' params[name] = Parameter(name=name, pattern=pattern, cmd=group['cmd'], unit=unit, value=float(group['val'])) AVL.goto_state(avl) self.parameters = params self.parameter_view = sorted(params.values(), key=lambda x:x.name.upper()) return self
class ImageEnumEditorDemo(HasTraits): """ This class specifies the details of the ImageEnumEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. image_from_list = Trait(editor=ImageEnumEditor(values=image_list, prefix='@icons:', suffix='_origin', cols=4, klass=Dummy), *image_list) # Items are used to define the demo display - one Item per # editor style img_group = Group( Item('image_from_list', style='simple', label='Simple'), Item('_'), Item('image_from_list', style='custom', label='Custom'), Item('_'), Item('image_from_list', style='text', label='Text'), Item('_'), Item('image_from_list', style='readonly', label='ReadOnly')) #Demo view view1 = View(img_group, title='ImageEnumEditor', buttons=['OK'])
class RunOptionsConfig(HasTraits): runcase = Instance(RunCase) constraint_config = Property(List(ConstraintConfig), depends_on='runcase.constraints[]') @cached_property def _get_constraint_config(self): constraints = sorted(self.runcase.constraints.values(), key=lambda x: x.name.upper()) return [ConstraintConfig(constraint=c) for c in constraints] x_range_min = Float(0) x_range_max = Float(1) x_num_pts = Int(2) x_range_type = Trait('Linear', { 'Linear': numpy.linspace, 'Log': numpy.logspace }) x = Property(Array(numpy.float), depends_on='x_range_min,x_range_max,x_num_pts,x_range_type') @cached_property def _get_x(self): return self.x_range_type_(self.x_range_min, self.x_range_max, self.x_num_pts) traits_view = View( HGroup( Include('custom_group'), Group(Item('constraint_config', editor=ConstraintConfig.editor, show_label=False), label='Constraints')), Group(HGroup(Item('x_range_min', label='From'), Item('x_range_max', label='To'), Item('x_num_pts', label='Points'), Item('x_range_type', label='Spacing')), label='Variable x'), Item())
class Artist(HasTraits): zorder = Float(1.0) alpha = mtraits.Alpha() visible = mtraits.Visible() adata = Instance(Affine, ()) # the data affine aview = Instance(Affine, ()) # the view affine affine = Instance(Affine, ()) # the product of the data and view affine renderer = Trait(None, Renderer) # every artist defines a string which is the name of the attr that # containers should put it into when added. Eg, an Axes is an # Aritst container, and when you place a Line in to an Axes, the # Axes will store a reference to it in the sequence ax.lines where # Line.sequence = 'lines' sequence = 'artists' def __init__(self): self.artistid = artistID() # track affine as the product of the view and the data affines # -- this should be a property, but I had trouble making a # property on my custom class affine so this is a workaround def product(ignore): # modify in place self.affine.follow((self.aview * self.adata).vec6) product(None) # force an affine product updated self.adata.on_trait_change(product, 'vec6') self.aview.on_trait_change(product, 'vec6') def _get_affine(self): return self.aview * self.adata def draw(self): pass
from item \ import Item from include \ import Include from ui_traits \ import SequenceTypes, container_delegate #------------------------------------------------------------------------------- # Trait definitions: #------------------------------------------------------------------------------- # Group orientation trait Orientation = Trait( 'vertical', TraitPrefixList( 'vertical', 'horizontal' ) ) # Group layout trait Layout = Trait( 'normal', TraitPrefixList( 'normal', 'split', 'tabbed', 'flow' ) ) # Delegate trait to the object being "shadowed" ShadowDelegate = Delegate( 'shadow' ) # Amount of padding to add around item Padding = Range( 0, 15, desc = 'amount of padding to add around each item' ) #------------------------------------------------------------------------------- # 'Group' class: #-------------------------------------------------------------------------------
class Polygon(HasTraits): line_color = Trait(wx.wxColour(0, 0, 0), editor=ColorEditor())
class EmployedPerson(LocatedPerson): employer = Trait(Employer(company='Enthought, Inc.', boss='eric')) extra = Group('employer', '<extra>')
class ExtraPerson(Person): sex = Trait('Male', 'Female') eye_color = Color extra = Group('sex', 'eye_color')
class tcPlot(BarPlot): """custom plot to draw the timechart probably not very 'chacotic' We draw the chart as a whole """ # The text of the axis title. title = Trait('', Str, Unicode) #May want to add PlotLabel option # The font of the title. title_font = KivaFont('modern 9') # The font of the title. title_font_large = KivaFont('modern 15') # The font of the title. title_font_huge = KivaFont('modern 20') # The spacing between the axis line and the title title_spacing = Trait('auto', 'auto', Float) # The color of the title. title_color = ColorTrait("black") not_on_screen = List on_screen = List options = TimeChartOptions() range_tools = RangeSelectionTools() redraw_timer = None def invalidate(self): self.invalidate_draw() self.request_redraw() def immediate_invalidate(self): self.invalidate_draw() self.request_redraw_delayed() def request_redraw_delayed(self): self.redraw_timer.Stop() BarPlot.request_redraw(self) def request_redraw(self): if self.redraw_timer == None: self.redraw_timer = timer.Timer(30, self.request_redraw_delayed) self.redraw_timer.Start() def auto_zoom_y(self): if self.value_range.high != self.max_y + 1 or self.value_range.low != self.min_y: self.value_range.high = self.max_y + 1 self.value_range.low = self.min_y self.invalidate_draw() self.request_redraw() def _gather_timechart_points(self, start_ts, end_ts, y, step): low_i = searchsorted(end_ts, self.index_mapper.range.low) high_i = searchsorted(start_ts, self.index_mapper.range.high) if low_i == high_i: return array([]) start_ts = start_ts[low_i:high_i] end_ts = end_ts[low_i:high_i] points = column_stack( (start_ts, end_ts, zeros(high_i - low_i) + (y + step), ones(high_i - low_i) + (y - step), array(range(low_i, high_i)))) return points def _draw_label(self, gc, label, text, x, y): label.text = text l_w, l_h = label.get_width_height(gc) offset = array((x, y - l_h / 2)) gc.translate_ctm(*offset) label.draw(gc) gc.translate_ctm(*(-offset)) return l_w, l_h def _draw_timechart(self, gc, tc, label, base_y): bar_middle_y = self.first_bar_y + (base_y + .5) * self.bar_height points = self._gather_timechart_points(tc.start_ts, tc.end_ts, base_y, .2) overview = None if self.options.use_overview: if points.size > 500: overview = tc.get_overview_ts(self.overview_threshold) points = self._gather_timechart_points(overview[0], overview[1], base_y, .2) if self.options.remove_pids_not_on_screen and points.size == 0: return 0 if bar_middle_y + self.bar_height < self.y or bar_middle_y - self.bar_height > self.y + self.height: return 1 #quickly decide we are not on the screen self._draw_bg(gc, base_y, tc.bg_color) # we are too short in height, dont display all the labels if self.last_label >= bar_middle_y: # draw label l_w, l_h = self._draw_label(gc, label, tc.name, self.x, bar_middle_y) self.last_label = bar_middle_y - 8 else: l_w, l_h = 0, 0 if points.size != 0: # draw the middle line from end of label to end of screen if l_w != 0: # we did not draw label because too short on space gc.set_alpha(0.2) gc.move_to(self.x + l_w, bar_middle_y) gc.line_to(self.x + self.width, bar_middle_y) gc.draw_path() gc.set_alpha(0.5) # map the bars start and stop locations into screen space lower_left_pts = self.map_screen(points[:, (0, 2)]) upper_right_pts = self.map_screen(points[:, (1, 3)]) bounds = upper_right_pts - lower_left_pts if overview: # critical path, we only draw unicolor rects #calculate the mean color #print points.size gc.set_fill_color(get_aggcolor_by_id(get_color_id("overview"))) gc.set_alpha(.9) rects = column_stack((lower_left_pts, bounds)) gc.rects(rects) gc.draw_path() else: # lets display them more nicely rects = column_stack((lower_left_pts, bounds, points[:, (4)])) last_t = -1 gc.save_state() for x, y, sx, sy, i in rects: t = tc.types[i] if last_t != t: # only draw when we change color. agg will then simplify the path # note that a path only can only have one color in agg. gc.draw_path() gc.set_fill_color(get_aggcolor_by_id(int(t))) last_t = t gc.rect(x, y, sx, sy) # draw last path gc.draw_path() if tc.has_comments: for x, y, sx, sy, i in rects: if sx < 8: # not worth calculatig text size continue label.text = tc.get_comment(i) l_w, l_h = label.get_width_height(gc) if l_w < sx: offset = array( (x, y + self.bar_height * .6 / 2 - l_h / 2)) gc.translate_ctm(*offset) label.draw(gc) gc.translate_ctm(*(-offset)) if tc.max_latency > 0: # emphase events where max_latency is reached ts = tc.max_latency_ts if ts.size > 0: points = self._gather_timechart_points(ts, ts, base_y, 0) if points.size > 0: # map the bars start and stop locations into screen space gc.set_alpha(1) lower_left_pts = self.map_screen(points[:, (0, 2)]) upper_right_pts = self.map_screen(points[:, (1, 3)]) bounds = upper_right_pts - lower_left_pts rects = column_stack((lower_left_pts, bounds)) gc.rects(rects) gc.draw_path() return 1 def _draw_freqchart(self, gc, tc, label, y): self._draw_bg(gc, y, tc.bg_color) low_i = searchsorted(tc.start_ts, self.index_mapper.range.low) high_i = searchsorted(tc.start_ts, self.index_mapper.range.high) if low_i > 0: low_i -= 1 if high_i < len(tc.start_ts): high_i += 1 if low_i >= high_i - 1: return array([]) start_ts = tc.start_ts[low_i:high_i - 1] end_ts = tc.start_ts[low_i + 1:high_i] values = (tc.types[low_i:high_i - 1] / (float(tc.max_types))) + y starts = column_stack((start_ts, values)) ends = column_stack((end_ts, values)) starts = self.map_screen(starts) ends = self.map_screen(ends) gc.begin_path() gc.line_set(starts, ends) gc.stroke_path() for i in xrange(len(starts)): x1, y1 = starts[i] x2, y2 = ends[i] sx = x2 - x1 if sx > 8: label.text = str(tc.types[low_i + i]) l_w, l_h = label.get_width_height(gc) if l_w < sx: if x1 < 0: x1 = 0 offset = array((x1, y1)) gc.translate_ctm(*offset) label.draw(gc) gc.translate_ctm(*(-offset)) def _draw_wake_ups(self, gc, processes_y): low_i = searchsorted(self.proj.wake_events['time'], self.index_mapper.range.low) high_i = searchsorted(self.proj.wake_events['time'], self.index_mapper.range.high) gc.set_stroke_color((0, 0, 0, .6)) for i in xrange(low_i, high_i): waker, wakee, ts = self.proj.wake_events[i] if processes_y.has_key(wakee) and processes_y.has_key(waker): y1 = processes_y[wakee] y2 = processes_y[waker] x, y = self.map_screen(array((ts, y1))) gc.move_to(x, y) y2 = processes_y[waker] x, y = self.map_screen(array((ts, y2))) gc.line_to(x, y) x, y = self.map_screen(array((ts, (y1 + y2) / 2))) if y1 > y2: y += 5 dy = -5 else: y -= 5 dy = +5 gc.move_to(x, y) gc.line_to(x - 3, y + dy) gc.move_to(x, y) gc.line_to(x + 3, y + dy) gc.draw_path() def _draw_bg(self, gc, y, color): gc.set_alpha(1) gc.set_line_width(0) gc.set_fill_color(color) this_bar_y = self.map_screen(array((0, y)))[1] gc.rect(self.x, this_bar_y, self.width, self.bar_height) gc.draw_path() gc.set_line_width(self.line_width) gc.set_alpha(0.5) def _draw_plot(self, gc, view_bounds=None, mode="normal"): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_antialias(1) gc.set_stroke_color(self.line_color_) gc.set_line_width(self.line_width) self.first_bar_y = self.map_screen(array((0, 0)))[1] self.last_label = self.height + self.y self.bar_height = self.map_screen(array((0, 1)))[1] - self.first_bar_y self.max_y = y = self.proj.num_cpu * 2 + self.proj.num_process - 1 if self.bar_height > 15: font = self.title_font_large else: font = self.title_font label = Label(text="", font=font, color=self.title_color, rotate_angle=0) # we unmap four pixels on screen, and find the nearest greater power of two # this by rounding the log2, and then exponentiate again # as the overview data is cached, this avoids using too much memory four_pixels = self.index_mapper.map_data(array((0, 4))) self.overview_threshold = 1 << int( log(1 + int(four_pixels[1] - four_pixels[0]), 2)) for i in xrange(len(self.proj.c_states)): tc = self.proj.c_states[i] if self.options.show_c_states: self._draw_timechart(gc, tc, label, y) y -= 1 tc = self.proj.p_states[i] if self.options.show_p_states: self._draw_freqchart(gc, tc, label, y) y -= 1 processes_y = {0xffffffffffffffffL: y + 1} not_on_screen = [] on_screen = [] for tc in self.proj.processes: if tc.show == False: continue processes_y[(tc.comm, tc.pid)] = y + .5 if self._draw_timechart( gc, tc, label, y) or not self.options.remove_pids_not_on_screen: y -= 1 on_screen.append(tc) else: not_on_screen.append(tc) self.not_on_screen = not_on_screen self.on_screen = on_screen if self.options.show_wake_events: self._draw_wake_ups(gc, processes_y) message = "" if self.proj.filename == "dummy": message = "please load a trace file in the 'file' menu" elif len(self.proj.processes) == 0: message = "no processes??! is your trace empty?" if message: label.text = message label.font = self.title_font_huge gc.translate_ctm(100, (self.y + self.height) / 2) label.draw(gc) gc.restore_state() self.min_y = y if self.options.auto_zoom_y: self.options.auto_zoom_timer.Start() def _on_hide_others(self): for i in self.not_on_screen: i.show = False self.invalidate_draw() self.request_redraw() def _on_hide_onscreen(self): for i in self.on_screen: i.show = False self.invalidate_draw() self.request_redraw()
# Imports: #------------------------------------------------------------------------------- import tk import wx.wizard as wz from ui_panel import fill_panel_for_group from editor import Editor from enthought.traits.api import Trait, Str #------------------------------------------------------------------------------- # Trait definitions: #------------------------------------------------------------------------------- # Only allow 'None' or a string value: none_str_trait = Trait('', None, str) #------------------------------------------------------------------------------- # Creates a wizard-based Tkinter user interface for a specified UI object: #------------------------------------------------------------------------------- def ui_wizard(ui, parent): # Create the copy of the 'context' we will need while editing: context = ui.context ui._context = context new_context = {} for name, value in context.items(): new_context[name] = value.clone_traits() ui.context = new_context
class Person(HasTraits): first_name = Str last_name = Str age = Int gender = Trait(None, 'M', 'F') name_view = View('first_name', 'last_name')
class CustomBarChart(Pipeline): """ 2012.2.21 custom version of BarChart. It has two more keyword arguments, x_scale, y_scale, which is in charge of the lateral_scale in the X and Y direction. Plots vertical glyphs (like bars) scaled vertical, to do histogram-like plots. This functions accepts a wide variety of inputs, with positions given in 2-D or in 3-D. **Function signatures**:: barchart(s, ...) barchart(x, y, s, ...) barchart(x, y, f, ...) barchart(x, y, z, s, ...) barchart(x, y, z, f, ...) If only one positional argument is passed, it can be a 1-D, 2-D, or 3-D array giving the length of the vectors. The positions of the data points are deducted from the indices of array, and an uniformly-spaced data set is created. If 3 positional arguments (x, y, s) are passed the last one must be an array s, or a callable, f, that returns an array. x and y give the 2D coordinates of positions corresponding to the s values. If 4 positional arguments (x, y, z, s) are passed, the 3 first are arrays giving the 3D coordinates of the data points, and the last one is an array s, or a callable, f, that returns an array giving the data value. """ _source_function = Callable(vertical_vectors_source) _pipeline = [VectorsFactory, ] mode = Trait('cube', bar_mode_dict, desc='The glyph used to represent the bars.') lateral_scale = CFloat(0.9, desc='The lateral scale of the glyph, ' 'in units of the distance between nearest points') def __call__(self, *args, **kwargs): """ Override the call to be able to scale automaticaly the axis. """ g = Pipeline.__call__(self, *args, **kwargs) gs = g.glyph.glyph_source # Use a cube source for glyphs. if not 'mode' in kwargs: gs.glyph_source = gs.glyph_list[-1] # Position the glyph tail on the point. gs.glyph_position = 'tail' gs.glyph_source.center = (0.0, 0.0, 0.5) g.glyph.glyph.orient = False if not 'color' in kwargs: g.glyph.color_mode = 'color_by_scalar' if not 'scale_mode' in kwargs: g.glyph.scale_mode = 'scale_by_vector_components' g.glyph.glyph.clamping = False x, y, z = g.mlab_source.x, g.mlab_source.y, g.mlab_source.z scale_factor = g.glyph.glyph.scale_factor* \ tools._min_axis_distance(x, y, z) x_scale = kwargs.pop('x_scale', self.lateral_scale) y_scale = kwargs.pop('y_scale', self.lateral_scale) try: g.glyph.glyph_source.glyph_source.y_length = \ y_scale/(scale_factor) g.glyph.glyph_source.glyph_source.x_length = \ x_scale/(scale_factor) except TraitError: " Not all types of glyphs have controlable y_length and x_length" return g def get_all_traits(self): """ 2012.2.21 this function determines the set of possible keys in kwargs. add two keywords, x_scale, y_scale. Returns all the traits of class, and the classes in the pipeline. """ #call the parental one first. traits = Pipeline.get_all_traits(self) traits['x_scale'] = Trait(0.9, desc='The scale of the glyph on the x-axis, ' 'in units of the distance between nearest points') traits['y_scale'] = Trait(0.9, desc='The scale of the glyph on the y-axis, ' 'in units of the distance between nearest points') return traits
class B(HasTraits): v = Trait(1, TraitEvenInteger())