class DrawLineComponent(Component): line_width = Enum(1, 2, 3, 4, 5, 6, 7) line_color = Color((0, 0, 0)) lines = List(Line) event_state = Enum("normal", "line") def _draw_overlay(self, gc, view_bounds=None, mode="normal"): gc.save_state() for line in self.lines: gc.set_line_width(line.width) gc.set_stroke_color(line.color) gc.move_to(line.x0, line.y0) gc.line_to(line.x1, line.y1) gc.draw_path() gc.restore_state() def normal_left_down(self, event): self.lines.append( Line(x0=event.x, y0=event.y, x1=event.x, y1=event.y, width=self.line_width, color=convert_color(self.line_color))) self.event_state = "line" self.request_redraw() def line_mouse_move(self, event): self.lines[-1].set(x1=event.x, y1=event.y) self.request_redraw() def line_left_up(self, event): self.event_state = "normal"
def __init__(self, cfile, **traits): super(MatrixEdgeNetworkParameter, self).__init__(**traits) self.netw = {} for cobj in cfile.connectome_network: if cobj.loaded: if isinstance(cobj, CNetwork): # add more info a = cobj.obj.data.edges_iter(data=True) u, v, dn = a.next() lab = [] for k in dn.keys(): if not k in lab: lab.append(k) if len(lab) == 0: lab = ["None"] self.netw[cobj.name] = {'name': cobj.obj.name, 'lab': lab} if len(self.netw) == 0: self.netw["None"] = {'name': "None", 'lab': "None"} self.add_trait('graph', Enum(self.netw.keys())) firstk = self.netw.keys()[0] self.add_trait('edge_label', Enum(self.netw[firstk]['lab']))
def _graph_changed(self, value): self.remove_trait("node_position") self.remove_trait("edge_value") self.remove_trait("node_label") self.add_trait('node_position', Enum(self.netw[value]['pos'])) # fixme: does not update the edge value (e.g. when none) self.add_trait('edge_value', Enum(self.netw[value]['ev'])) self.add_trait('node_label', Enum(self.netw[value]['lab']))
def __init__(self, cfile, **traits): super(NetworkParameter, self).__init__(**traits) self.netw = {} for cobj in cfile.connectome_network: if cobj.loaded: if isinstance(cobj, CNetwork): # add more info a = cobj.obj.data.nodes_iter(data=True) n, dn = a.next() npos = [] lab = [] for k in dn.keys(): if 'position' in k or 'pos' in k or 'location' in k: npos.append(k) if 'name' in k or 'label' in k: lab.append(k) if len(npos) == 0: npos = ["None"] if len(lab) == 0: lab = ["None"] a = cobj.obj.data.edges_iter(data=True) if len(cobj.obj.data.edges()) == 0: ev = ["None"] else: e1, e2, de = a.next() ev = [] for k in de.keys(): if isinstance(de[k], float) or isinstance( de[k], int): ev.append(k) if len(ev) == 0: ev = ["None"] self.netw[cobj.name] = { 'name': cobj.obj.name, 'ev': ev, 'pos': npos, 'lab': lab } if len(self.netw) == 0: self.netw["None"] = { 'name': "None", 'ev': "None", 'pos': "None", 'lab': "None" } self.add_trait('graph', Enum(self.netw.keys())) firstk = self.netw.keys()[0] self.add_trait('node_position', Enum(self.netw[firstk]['pos'])) self.add_trait('edge_value', Enum(self.netw[firstk]['ev'])) self.add_trait('node_label', Enum(self.netw[firstk]['lab']))
class SOKKIARecord(HasTraits): """Single or multiline record in a SOKKIA text fieldbook.""" record_type = Enum('Fbk Settings', 'JOB', 'SCALE', 'INSTR', 'RED', 'BKB', 'TARGET', 'STN', 'OBS', 'POS') point_id = Int dc = Enum(None, 'NM', 'KI', 'TP', 'F1', 'F2') north_horizontal = AngleDMS east_vertical = AngleDMS elevation_distance = Float code = String
class MixedStyles(HasTraits): first_name = Str last_name = Str department = Enum("Business", "Research", "Admin") position_type = Enum("Full-Time", "Part-Time", "Contract") traits_view = View(Group( Item(name='first_name'), Item(name='last_name'), Group(Item(name='department'), Item(name='position_type', style='custom'), style='simple')), title='Mixed Styles', style='readonly')
class IFileDialog(IDialog): """ The interface for a dialog that allows the user to open/save files etc. """ #### 'IFileDialog' interface ############################################## # The 'action' that the user is peforming on the directory. action = Enum('open', 'save as') # The default directory. default_directory = Unicode # The default filename. default_filename = Unicode # The default path (directory and filename) of the chosen file. This is # only used when the *default_directory* and *default_filename* are not set # and is equivalent to setting both. default_path = Unicode # The directory containing the chosen file. directory = Unicode # The name of the chosen file. filename = Unicode # The path (directory and filename) of the chosen file. path = Unicode # The wildcard used to restrict the set of files. wildcard = Unicode # The index of the selected wildcard. wildcard_index = Int(0)
class Person(HasTraits): """ Demo class for demonstrating enabling/disabling of trait editors """ first_name = Str last_name = Str age = Range(0, 120) marital_status = Enum('single', 'married', 'divorced', 'widowed') registered_voter = Bool legal_guardian = Str # Interface for attributes that are always enabled: gen_group = Group(Item(name='first_name'), Item(name='last_name'), Item(name='age'), label='General Info', show_border=True) # Interface for adult-only attributes: adult_group = Group(Item(name='marital_status'), Item(name='registered_voter'), enabled_when='age >= 18', label='Adults', show_border=True) # Interface for child-only attribute: child_group = Group(Item(name='legal_guardian', enabled_when='age < 18'), label='Minors', show_border=True) # The view specification is simple, as the group specs have done the work: view = View(Group(gen_group, adult_group, child_group), resizable=True, buttons=['OK'])
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 DataFitterPanel(DataFitter): """Fitter panel object, for data fitting with gui for fit function selection >>> import numpy >>> x = numpy.linspace(0,100) >>> y = numpy.linspace(0,100) + numpy.random.randn(50) >>> data = FitData(x = x, y = y) >>> t = DataFitter(data = data) >>> p,c = t.fit() """ category = Enum(list(CATEGORIES.keys())) function_names = Property(List(Str), depends_on='category') function_name = Str description = DelegatesTo('function') view = View(Group('category', Item(name='function_name', editor=EnumEditor(name='function_names'), id='function_name_edit'), Item('description', style='custom'), label='Fit Function'), data_fitter_group, resizable=False) def _function_name_changed(self, name): self.function.function = getattr(CATEGORIES[self.category], name) def _get_function_names(self): function_names = CATEGORIES[self.category].FUNCTIONS self.function_name = function_names[0] return function_names
class Person ( HasStrictTraits ): """ Defines some sample data to display in the TableEditor. """ name = Str age = Int gender = Enum( 'Male', 'Female' )
class Label(HasTraits): """The Label class implements the data model for a label.""" #### 'Label' interface #################################################### # The name. name = Unicode # The size in points. size = Int(18) # The style. style = Enum('normal', 'bold', 'italic') ########################################################################### # 'Label' interface. ########################################################################### def increment_size(self, by): """Increment the current font size.""" self.size += by def decrement_size(self, by): """Decrement the current font size.""" self.size -= by
class SurfaceParameter(HasTraits): engine = Enum("Mayavi", ["Mayavi"]) view = View(Item('engine', label="Use Engine"), Item('pointset', label="Pointset"), Item('faces', label="Faces"), Item('labels', label="labels"), id='cviewer.plugins.codeoracle.surfaceparameter', buttons=['OK'], resizable=True, title="Create surface ...") def __init__(self, cfile, **traits): super(SurfaceParameter, self).__init__(**traits) self.pointset_da = {} self.faces_da = {} self.labels_da = {} for cobj in cfile.connectome_surface: if cobj.loaded: # check darrays # if correct intent, add to list for i, cdobj in enumerate(cobj.darrays): if cdobj.data.intent == 1008: self.pointset_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } #pointset.append(cdobj) if cdobj.data.intent == 1009: self.faces_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } #faces.append(cdobj.dname) if cdobj.data.intent == 1002: self.labels_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } if len(self.pointset_da) == 0: self.pointset_da["None"] = {'name': "None"} if len(self.faces_da) == 0: self.faces_da["None"] = {'name': "None"} if len(self.labels_da) == 0: self.labels_da["None"] = {'name': "None"} # assert labels and pointset dimension are the same self.add_trait('pointset', Enum(self.pointset_da.keys())) self.add_trait('faces', Enum(self.faces_da.keys())) self.add_trait('labels', Enum(self.labels_da.keys()))
class MorphologyDemo(HasTraits): structing_element = Array(shape=(3, 3), dtype=np.uint8) process_type = Enum("dilate", "erode", "MORPH_OPEN", "MORPH_CLOSE", "MORPH_GRADIENT", "MORPH_TOPHAT", "MORPH_BLACKHAT") iter = Int(1) view = View(Item("structing_element", label=u"结构元素"), Item("process_type", label=u"处理类型"), Item("iter", label=u"迭代次数"), title=u"Morphology Demo控制面板") def __init__(self, *args, **kwargs): super(MorphologyDemo, self).__init__(*args, **kwargs) self.structing_element = np.ones((3, 3), dtype=np.uint8) self.img = cv.imread("lena.jpg") self.on_trait_change(self.redraw, "structing_element,process_type,iter") self.redraw() def redraw(self): img2 = cv.Mat() element = cv.asMat(self.structing_element, force_single_channel=True) if self.process_type.startswith("MORPH_"): type = getattr(cv, self.process_type) cv.morphologyEx(self.img, img2, type, element, iterations=self.iter) else: func = getattr(cv, self.process_type) func(self.img, img2, element, iterations=self.iter) cv.imshow("Morphology Demo", img2)
class NBSMoreParameter(HasTraits): THRES = Float(3) K = Int(10) TAIL = Enum('left', ['left', 'equal', 'right']) view = View(Item('first_edge_value', label="Edge value for first group"), Item('second_edge_value', label="Edge value for second group"), Item('THRES', label="Threshold"), Item('K', label="# Interations"), Item('TAIL', label="Tail"), buttons=['OK'], resizable=True, title="More parameters") def __init__(self, cfile, selected_network1, selected_network2, **traits): super(NBSMoreParameter, self).__init__(**traits) for cobj in cfile.connectome_network: if cobj.name == selected_network1: cnet1 = cobj break # get edge parameters edval1 = cnet1._get_edge_values() for cobj in cfile.connectome_network: if cobj.name == selected_network2: cnet2 = cobj break # get edge parameters edval2 = cnet2._get_edge_values() self.add_trait('first_edge_value', Enum(edval1)) self.add_trait('second_edge_value', Enum(edval2))
class ShapeSelector(HasTraits): select = Enum(*[cls.__name__ for cls in Shape.__subclasses__()]) shape = Instance(Shape) view = View(VGroup( Item("select", show_label=False), VSplit(Item("shape", style="custom", editor=InstanceEditor(view="view")), Item("shape", style="custom", editor=InstanceEditor(view="view_info")), show_labels=False)), width=350, height=300, resizable=True) def __init__(self, **traits): super(ShapeSelector, self).__init__(**traits) self._select_changed() def _select_changed(self): klass = [ c for c in Shape.__subclasses__() if c.__name__ == self.select ][0] self.shape = klass()
class Bear(HasTraits): name = Str color = RGBColor("gold") weight = Float location = Array() favorite_food = Enum("Honey", "Turkey", "PaloAltian", default="Honey") datadir = Directory("./")
class IConfirmationDialog(IDialog): """ The interface for a dialog that prompts the user for confirmation. """ #### 'IConfirmationDialog' interface ###################################### # Should the cancel button be displayed? cancel = Bool(False) # The default button. default = Enum(NO, YES, CANCEL) # The image displayed with the message. The default is toolkit specific. image = Instance(ImageResource) # The message displayed in the body of the dialog (use the inherited # 'title' trait to set the title of the dialog itself). message = Unicode # Some informative text to display below the main message informative = Unicode # Some additional details that can be exposed by the user detail = Unicode # The label for the 'no' button. The default is toolkit specific. no_label = Unicode # The label for the 'yes' button. The default is toolkit specific. yes_label = Unicode
class CirclePainter(AbstractOverlay): """用半径为r的圆绘制鼠标轨迹,并调用InPaintDemo的fill_circle() 在其mask图像上绘制选区。当鼠标松开时,调用InPaintDemo的inpaint() 进行inpaint图像处理。 """ x = Float(-1) # 当前圆心X轴坐标 y = Float(-1) # 当前圆心Y轴坐标 r = Range(2.0, 20.0, 10.0) # 圆形半径(数据坐标系) event_state = Enum("normal", "drawing") track = List() # 储存鼠标轨迹 updated = Event() def clear_track(self): self.track = [] self.request_redraw() def fill_circle(self, event): self.x = event.x self.y = event.y plot = self.component x = plot.x_mapper.map_data(event.x) y = plot.y_mapper.map_data(event.y) self.track.append((self.x, self.y, x, y)) self.request_redraw() def normal_mouse_move(self, event): self.x = event.x self.y = event.y self.request_redraw() def normal_left_down(self, event): self.event_state = "drawing" self.fill_circle(event) def drawing_mouse_move(self, event): self.fill_circle(event) def drawing_left_up(self, event): self.event_state = "normal" self.updated = True def normal_mouse_leave(self, event): self.x, self.y = -1, -1 self.request_redraw() def overlay(self, component, gc, view_bounds=None, mode="normal"): plot = self.component r = plot.x_mapper.map_screen(self.r) gc.save_state() if self.x > 0 and self.y > 0: gc.set_stroke_color((1, 1, 1)) gc.arc(self.x, self.y, r, 0.0, 2 * np.pi) gc.stroke_path() gc.set_fill_color((1, 1, 1)) for x, y, _, _ in self.track: gc.arc(x, y, r, 0.0, 2 * np.pi) gc.fill_path() gc.restore_state()
def __init__(self, cfile, **traits): super(SurfaceParameter, self).__init__(**traits) self.pointset_da = {} self.faces_da = {} self.labels_da = {} for cobj in cfile.connectome_surface: if cobj.loaded: # check darrays # if correct intent, add to list for i, cdobj in enumerate(cobj.darrays): if cdobj.data.intent == 1008: self.pointset_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } #pointset.append(cdobj) if cdobj.data.intent == 1009: self.faces_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } #faces.append(cdobj.dname) if cdobj.data.intent == 1002: self.labels_da[cobj.name + ' / ' + cdobj.dname + ' (%s)' % str(i)] = { 'name': cobj.obj.name, 'da_idx': i } if len(self.pointset_da) == 0: self.pointset_da["None"] = {'name': "None"} if len(self.faces_da) == 0: self.faces_da["None"] = {'name': "None"} if len(self.labels_da) == 0: self.labels_da["None"] = {'name': "None"} # assert labels and pointset dimension are the same self.add_trait('pointset', Enum(self.pointset_da.keys())) self.add_trait('faces', Enum(self.faces_da.keys())) self.add_trait('labels', Enum(self.labels_da.keys()))
class ExtractVectorComponents(FilterBase): """ This wraps the TVTK ExtractVectorComponents filter and allows one to select any of the three components of an input vector data attribute.""" # The version of this class. Used for persistence. __version__ = 0 # The actual TVTK filter that this class manages. filter = Instance(tvtk.ExtractVectorComponents, args=(), allow_none=False) # The Vector Component to be extracted component = Enum('x-component', 'y-component', 'z-component', desc='component of the vector to be extracted') input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['vectors']) output_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['any']) view = View(Group(Item(name='component')), resizable=True ) ###################################################################### # `Filter` interface. ###################################################################### def update_pipeline(self): # Do nothing if there is no input. inputs = self.inputs if len(inputs) == 0: return fil = self.filter fil.input = inputs[0].outputs[0] fil.update() self._component_changed(self.component) ###################################################################### # Non-public interface. ###################################################################### def _component_changed(self, value): # Obtain output from the TVTK ExtractVectorComponents filter # corresponding to the selected vector component if len(self.inputs) == 0: return if value == 'x-component': self._set_outputs([self.filter.vx_component]) elif value == 'y-component': self._set_outputs([self.filter.vy_component]) elif value == 'z-component': self._set_outputs([self.filter.vz_component]) self.render()
class Hotel(HasPrivateTraits): # The season of the year: season = Enum('Winter', 'Spring', 'Summer', 'Fall') # The current cost of heating fuel (in dollars/gallon): fuel_cost = Range(2.00, 10.00, 4.00) # The current minimum temparature allowed by the hotel: min_temperature = Property(depends_on='season, fuel_cost') # The guests currently staying at the hotel: guests = List # ( Instance( 'Guest' ) ) # Add a new guest to the hotel: add_guest = Button('Add Guest') # The view of the hotel: view = View(VGroup( HGroup(Item('season'), '20', Item('fuel_cost', width=300), spring, Item('add_guest', show_label=False), show_border=True, label='Hotel Information'), VGroup(Item('guests', style='custom', editor=ListEditor(use_notebook=True, deletable=True, dock_style='tab', page_name='.name')), show_labels=False, show_border=True, label='Guests')), title='The Belmont Hotel Dashboard', width=0.6, height=0.2, resizable=True) # Property implementations: @cached_property def _get_min_temperature(self): return ({ 'Winter': 32, 'Spring': 40, 'Summer': 45, 'Fall': 40 }[self.season] + min(int(60.00 / self.fuel_cost), 15)) # Event handlers: @on_trait_change('guests[]') def _guests_modified(self, removed, added): for guest in added: guest.hotel = self def _add_guest_changed(self): self.guests.append(Guest())
def __init__(self, default_value=None, values=(), iotype=None, aliases=(), desc=None, **metadata): # Allow some variant constructors (no default, no index) if not values: if default_value is None: raise ValueError("Enum must contain at least one value.") else: values = default_value if isinstance(values, (tuple, list)): default_value = values[0] else: if default_value is None: default_value = values[0] # We need tuples or a list for the index if not isinstance(values, (tuple, list)): values = (values,) if aliases: if not isinstance(aliases, (tuple, list)): aliases = (aliases,) if len(aliases) != len(values): raise ValueError("Length of aliases does not match " + \ "length of values.") if default_value not in values: raise ValueError("Default value not in values.") self._validator = TraitEnum(default_value, values, **metadata) # Put iotype in the metadata dictionary if iotype is not None: metadata['iotype'] = iotype # Put desc in the metadata dictionary if desc is not None: metadata['desc'] = desc # Put values in the metadata dictionary if values: metadata['values'] = values # We also need to store the values in a dict, to get around # a weak typechecking (i.e., enum of [1,2,3] can be 1.0) self.valuedict = {} for val in values: self.valuedict[val] = val # Put aliases in the metadata dictionary if aliases: metadata['aliases'] = aliases super(Enum, self).__init__(default_value=default_value, **metadata)
class PerspectiveItem(HasTraits): """ An item in a Perspective contents list. """ implements(IPerspectiveItem) # The Id of the view to display in the perspective. id = Str # The position of the view relative to the item specified in the # 'relative_to' trait. # # 'top' puts the view above the 'relative_to' item. # 'bottom' puts the view below the 'relative_to' item. # 'left' puts the view to the left of the 'relative_to' item. # 'right' puts the view to the right of the 'relative_to' item. # 'with' puts the view in the same region as the 'relative_to' item. # # If the position is specified as 'with' you must specify a 'relative_to' # item other than the editor area (i.e., you cannot position a view 'with' # the editor area). position = Enum('left', 'top', 'bottom', 'right', 'with') # The Id of the view to position relative to. If this is not specified # (or if no view exists with this Id) then the view will be placed relative # to the editor area. relative_to = Str # The width of the item (as a fraction of the window width). # # e.g. 0.5 == half the window width. # # Note that this is treated as a suggestion, and it may not be possible # for the workbench to allocate the space requested. width = Float(-1) # The height of the item (as a fraction of the window height). # # e.g. 0.5 == half the window height. # # Note that this is treated as a suggestion, and it may not be possible # for the workbench to allocate the space requested. height = Float(-1) # The style of the dock control created. style_hint = Enum('tab', 'vertical', 'horizontal', 'fixed')
class MayaviMlabPreferencesPage(PreferencesPage): """ Preferences page for Mayavi. """ #### 'PreferencesPage' interface ########################################## # The page's category (e.g. 'General/Appearance'). The empty string means # that this is a top-level page. category = 'Mayavi' # The page's help identifier (optional). If a help Id *is* provided then # there will be a 'Help' button shown on the preference page. help_id = '' # The page name (this is what is shown in the preferences dialog. name = 'Mlab' # The path to the preferences node that contains the preferences. preferences_path = 'enthought.mayavi.mlab' #### Preferences ########################################################## # The mlab backend to use. backend = Enum('auto', 'envisage', 'simple', 'test', desc='the mlab backend to use') # The background color of the renderer. background_color = Tuple(Range(0., 1.), Range(0., 1.), Range(0., 1.), editor=RGBColorEditor, desc='the background color of the scene') # The foreground color of the renderer. foreground_color = Tuple(Range(0., 1.), Range(0., 1.), Range(0., 1.), editor=RGBColorEditor, desc='the foreground color of the scene') # Offscreen rendering. offscreen = Bool(desc='if mlab should use offscreen rendering' ' (no window will show up in this case)') ###################################################################### # Traits UI view. traits_view = View(Group( Item('backend'), Item('background_color'), Item('foreground_color'), Item('offscreen'), ), resizable=True)
def __init__(self, cfile, selected_network1, selected_network2, **traits): super(NBSMoreParameter, self).__init__(**traits) for cobj in cfile.connectome_network: if cobj.name == selected_network1: cnet1 = cobj break # get edge parameters edval1 = cnet1._get_edge_values() for cobj in cfile.connectome_network: if cobj.name == selected_network2: cnet2 = cobj break # get edge parameters edval2 = cnet2._get_edge_values() self.add_trait('first_edge_value', Enum(edval1)) self.add_trait('second_edge_value', Enum(edval2))
class AdultSpec(Spec): """ Trait list for adults (assigned to 'misc' for a Person when age >= 18). """ marital_status = Enum('single', 'married', 'divorced', 'widowed') registered_voter = Bool military_service = Bool traits_view = View('marital_status', 'registered_voter', 'military_service')
class Facet(Sphere): """Facet class creates Facet from triangle list, follows the usual VTK pipeline and creates a Facet actor, which is passed to the show_actor() function as an argument. """ ##################################################################### # Traits definitions coords = List(value=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], 0.0, 0.0, 1.0], desc='the vertex list') indices = List(value=[[0, 1, 2]], desc='the triangle index list') color = vtk_color_trait((1.0, 1.0, 1.0)) representation = Enum('s', 'w', 'p') visibility = Bool(True) viewer = Any polydata = Instance(tvtk.PolyData, ()) property = Instance(tvtk.Property) actor = Instance(tvtk.Actor, ()) # tvtk Actor, for the usual pipeline architecture. ###################################################################### # User interface view traits_view = View( Group(Item(name='coords', style='simple', label='Vertices'), Item(name='indices', label='Triangle indices'), Item(name='color'), Item(name='visibility'), Item(name='representation'), label='Facet Properties', show_border=True)) def __init__(self, **traits): self.property = self.actor.property HasTraits.__init__(self, **traits) self._create_points(self.coords, self.indices) self._color_changed(self.color) self._visibility_changed(self.visibility) normals = tvtk.PolyDataNormals(input=self.polydata) m = tvtk.PolyDataMapper( input=normals.output) # the usual vtk pipleine countinuation self.actor.mapper = m self.property = self.actor.property self.property.representation = self.representation show_actor(self.actor) # passing the actors function for rendering self.viewer = get_viewer() # getting the ivtk viewer self.property.on_trait_change(self.viewer.scene.render) self.actor.on_trait_change(self.viewer.scene.render) ###################################################################### # Non-public methods, Event handlers def _create_points(self, c, i): self.polydata = tvtk.PolyData(points=numpy.array(c), polys=numpy.array(i)) self.points = c return self.points, self.polydata.polys
class Employee(HasTraits): name = Str age = Int gender = Enum('Male', 'Female') phone = Regex(value='000-0000', regex='\d\d\d[-]\d\d\d\d') traits_view = View('name', 'age', 'phone', title='Create new employee', width=0.18, buttons=['OK', 'Cancel'])
class ToolBarManager(ActionManager): """ A tool bar manager realizes itself in errr, a tool bar control. """ #### 'ToolBarManager' interface ########################################### # The size of tool images (width, height). image_size = Tuple((16, 16)) # The orientation of the toolbar. orientation = Enum('horizontal', 'vertical') # Should we display the name of each tool bar tool under its image? show_tool_names = Bool(True) # Should we display the horizontal divider? show_divider = Bool(True) #### Private interface #################################################### # Cache of tool images (scaled to the appropriate size). _image_cache = Instance(ImageCache) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, *args, **traits): """ Creates a new tool bar manager. """ # Base class contructor. super(ToolBarManager, self).__init__(*args, **traits) # An image cache to make sure that we only load each image used in the # tool bar exactly once. self._image_cache = ImageCache(self.image_size[0], self.image_size[1]) return ########################################################################### # 'ToolBarManager' interface. ########################################################################### def create_tool_bar(self, parent, controller=None): """ Creates a tool bar. """ # If a controller is required it can either be set as a trait on the # tool bar manager (the trait is part of the 'ActionManager' API), or # passed in here (if one is passed in here it takes precedence over the # trait). if controller is None: controller = self.controller return None
def switchDimensions(self, updateScale=True): """Update the selector when the region's dimensions change.""" dimensions = self.getDimensions() for i, dimension in enumerate(dimensions): if not updateScale and i == 0: continue indexName = 'index%d' % i oldIndex = int(getattr(self, indexName)) setattr(self, indexName + '_enum', Enum(*[str(d) for d in range(dimension)])) index = min(oldIndex, dimension - 1) setattr(self, indexName, str(index))
class Enum(Variable): """A variable wrapper for an enumeration, which is a variable that can assume one value from a set of specified values. """ def __init__(self, default_value=None, values=(), iotype=None, aliases=(), desc=None, **metadata): # Allow some variant constructors (no default, no index) if not values: if default_value is None: raise ValueError("Enum must contain at least one value.") else: values = default_value if isinstance(values, (tuple, list)): default_value = values[0] else: if default_value is None: default_value = values[0] # We need tuples or a list for the index if not isinstance(values, (tuple, list)): values = (values,) if aliases: if not isinstance(aliases, (tuple, list)): aliases = (aliases,) if len(aliases) != len(values): raise ValueError("Length of aliases does not match " + \ "length of values.") if default_value not in values: raise ValueError("Default value not in values.") self._validator = TraitEnum(default_value, values, **metadata) # Put iotype in the metadata dictionary if iotype is not None: metadata['iotype'] = iotype # Put desc in the metadata dictionary if desc is not None: metadata['desc'] = desc # Put values in the metadata dictionary if values: metadata['values'] = values # We also need to store the values in a dict, to get around # a weak typechecking (i.e., enum of [1,2,3] can be 1.0) self.valuedict = {} for val in values: self.valuedict[val] = val # Put aliases in the metadata dictionary if aliases: metadata['aliases'] = aliases super(Enum, self).__init__(default_value=default_value, **metadata) def validate(self, obj, name, value): """ Validates that a specified value is valid for this trait.""" try: val = self._validator.validate(obj, name, value) except Exception: self.error(obj, name, value) # if someone uses a float to set an int-valued Enum, we want it to # be an int. Enthought's Enum allows a float value, unfortunately. return self.valuedict[val] def error(self, obj, name, value): """Returns a general error string for Enum.""" # pylint: disable-msg=E1101 vtype = type( value ) if value not in self.values: info = str(self.values) msg = "Variable '%s' must be in %s, " % (name, info) + \ "but a value of %s %s was specified." % (value, vtype) else: msg = "Unknown error while setting trait '%s';" % (name) +\ "a value of %s %s was specified." % (value, vtype) try: obj.raise_exception(msg, ValueError) except AttributeError: raise ValueError(msg)