class Player(HasStrictTraits): # Trait definitions: name = Str at_bats = Int strike_outs = Int(event='affects_average') singles = Int(event='affects_average') doubles = Int(event='affects_average') triples = Int(event='affects_average') home_runs = Int(event='affects_average') walks = Int average = Property(Float) def _get_average(self): """ Computes the player's batting average from the current statistics. """ if self.at_bats == 0: return 0.0 return float(self.singles + self.doubles + self.triples + self.home_runs) / self.at_bats def _affects_average_changed(self): """ Handles an event that affects the player's batting average. """ self.at_bats += 1
class CallbackTester(HasTraits): num_callbacks = Int(0) some_trait = Int() _underscore = Int() def _callback(self, obj, name, old, new): self.num_callbacks += 1 self.nested = MyHasTraits() self.nested.mht2 = MyHasTraits2()
class PupilTools(HasTraits): wavelength = Float(700) #NA = Float(1.49) sizeX = Int(61) sizeZ = Int(61) zSpacing = Float(50) view = View( Item('wavelength'), #Item('NA'), Item('zSpacing'), Item('sizeZ'), Item('sizeX'), buttons=[OKButton]) def __init__(self, dsviewer): self.dsviewer = dsviewer self.do = dsviewer.do self.image = dsviewer.image dsviewer.AddMenuItem('Processing', "Generate PSF from pupil", self.OnPSFFromPupil) def OnPSFFromPupil(self, event): import numpy as np #import pylab from PYME.PSFGen import fourierHNA from PYME.DSView.image import ImageStack from PYME.DSView import ViewIm3D self.configure_traits(kind='modal') z_ = np.arange(self.sizeZ) * float(self.zSpacing) z_ -= z_.mean() ps = fourierHNA.PsfFromPupil( self.image.data[:, :], z_, self.image.mdh['voxelsize.x'] * 1e3, self.wavelength) #, shape = [self.sizeX, self.sizeX]) ps = ps / ps[:, :, self.sizeZ / 2].sum() im = ImageStack(ps, titleStub='Generated PSF') im.mdh.copyEntriesFrom(self.image.mdh) im.mdh['Parent'] = self.image.filename #im.mdh['Processing.CropROI'] = roi mode = 'psf' dv = ViewIm3D(im, mode=mode, glCanvas=self.dsviewer.glCanvas, parent=wx.GetTopLevelParent(self.dsviewer))
class OutputSystemViewer(HasTraits): num_outputs = Property(Int(1), depends_on='runoutput.eigenmodes') @cached_property def _get_num_outputs(self): ret = len(self.runoutput.eigenmodes) #print 'num_outputs', ret return ret run_number = Int(1) #Range(low=1, high='num_outputs') runoutput = Instance(RunOutput) modes = Property(List(EigenMode), depends_on='runoutput.eigenmodes,run_number') @cached_property def _get_modes(self): return self.runoutput.eigenmodes[self.run_number - 1] modes_array = Property(Array(numpy.complex), depends_on='modes') @cached_property def _get_modes_array(self): ret = numpy.empty((len(self.modes), 13), dtype='complex') for i, mode in enumerate(self.modes): ret[i, 0] = mode.eigenvalue #.real #ret[i,1] = mode.eigenvalue.imag ret[i, 1:] = mode.eigenvector #print mode.eigenvector return ret matrix = Property(Instance(EigenMatrix), depends_on='runoutput.eigenmatrix,run_number') @cached_property def _get_matrix(self): #print len(self.runoutput.eigenmatrix) return self.runoutput.eigenmatrix[self.run_number - 1] view = View(Item('run_number', editor=RangeEditor(mode='spinner')), Group( Item('modes_array', editor=TabularEditor(adapter=ModesAdapter(), operations=[], editable=False), show_label=False), Item('object.matrix.matrix', editor=TabularEditor(adapter=EigenMatrixAdapter(), operations=[], editable=False), show_label=False)), resizable=True)
class MyHasTraits(HasTraits): explicit_int = Int explicit_int_def = Int(7) explicit_property = MyProp() inst = Instance(MyClass) impval_ = Int(1) _ = MyProp() def __init__(self, *args, **kwargs): super(MyHasTraits, self).__init__(*args, **kwargs) self.inst = MyClass()
def test_reset_traits(self): mht = MyHasTraits() mht.implicit_property = 999 mht.impval1 = 999 mht.explicit_int_def = 999 mht.explicit_int = 999 mht.explicit_property = 999 mht.inst = MyClass() mht.inst.val = 999 mht.add_trait('added_int_def', Int(42)) mht.added_int_def = 999 mht.add_trait('added_int', Int()) mht.added_int = 999 self.assertEqual(mht.implicit_property, 999) self.assertEqual(mht.impval1, 999) self.assertEqual(mht.explicit_int_def, 999) self.assertEqual(mht.explicit_int, 999) self.assertEqual(mht.added_int, 999) self.assertEqual(mht.added_int_def, 999) self.assertEqual(mht.explicit_property, 999) self.assertEqual(mht.inst.val, 999) unresetable = mht.reset_traits() # failed to reset the explicit property self.assertEqual(unresetable, ['explicit_property']) # implicit property traits are not reset self.assertEqual(mht.implicit_property, 999) # implicit value traits are reset self.assertEqual(mht.impval1, 1) # dynamically added traits are reset, because after # their values have been set, they show up in trait_names() # which is what reset_traits() calls to get the list # of traits (if not explicitly specified) self.assertEqual(mht.added_int_def, 42) self.assertEqual(mht.added_int, 0) # other traits are reset self.assertEqual(mht.explicit_int_def, 7) self.assertEqual(mht.explicit_int, 0) # instance trait is reset to None self.assertEqual(mht.inst, None) # even if explicitly specified, implicit property traits are not reset unresetable = mht.reset_traits(traits=['implicit_property']) self.assertEqual(unresetable, ['implicit_property']) self.assertEqual(mht.implicit_property, 999)
class Plot_i(HasTraits): plot = Instance(Plot) color = ColorTrait('blue') marker = marker_trait marker_size = Int(4) line_width = Int(4) traits_view = View(Group(Tabbed(Group( \ Group(Item('color', label="Color"), \ Item('marker', label="Marker"), \ orientation = 'vertical'), \ Group( \ Item('marker_size', label= "Size"), \ Item('line_width', label = 'Linewidth'), \ orientation = 'vertical'), \ dock = 'tab', orientation = 'vertical')), \ Item('plot', editor=ComponentEditor(), show_label=False), orientation = 'horizontal'), \ width=800, height=600, resizable=True, title="Chaco Plot") def __init__(self,X,Y): super(Plot_i, self).__init__() self.load_data(X,Y) self.start() def load_data(self,X,Y) : self.X = X self.Y = Y plotdata = ArrayPlotData(x = X, y = Y) plot = Plot(plotdata) self.renderer_line = plot.plot(('x','y'),type = 'line', color = "blue")[0] self.renderer_scat = plot.plot(('x','y'),type = 'scatter', color = "blue")[0] self.plot = plot def start(self): self.configure_traits() def _color_changed(self): self.renderer_line.color = self.color self.renderer_scat.color = self.color def _marker_changed(self): self.renderer_scat.marker = self.marker def _marker_size_changed(self): self.renderer_scat.marker_size = self.marker_size def _line_width_changed(self): self.renderer_line.line_width = self.line_width
class NewModelSelector(HasTraits): modelnames = List selectedname = Str('No Model') modelargnum = Int(2) selectedmodelclass = Property isvarargmodel = Property(depends_on='modelnames') traits_view = View(Item('selectedname',label='Model Name:',editor=EnumEditor(name='modelnames')), Item('modelargnum',label='Extra Parameters:',enabled_when='isvarargmodel'), buttons=['OK','Cancel']) def __init__(self,include_models=None,exclude_models=None,**traits): super(NewModelSelector,self).__init__(**traits) self.modelnames = list_models(include_models,exclude_models,FunctionModel1D) self.modelnames.insert(0,'No Model') self.modelnames.sort() def _get_selectedmodelclass(self): n = self.selectedname if n == 'No Model': return None else: return get_model_class(n) def _get_isvarargmodel(self): cls = self.selectedmodelclass if cls is None: return False else: return cls.isVarnumModel()
class MetadataTest(HasTraits): i = Int(99, myinfo="test my info") s = Str("test", label=u"字符串") # NumPy的数组 a = Array # 元素为Int的列表 list = List(Int)
class FrameInfo(HasTraits): """This holds information about each frame. This is to be used in :class:`Video` """ #: frame index index = Range(low='_low', high='_high') #: frame time time = Property(depends_on='index,fps', editor=RangeEditor(is_float=True, low_name='object._low_', high_name='duration')) #: duration of the movie duration = Float(1.) #: frame rate fps = Float(1.) #: number of frames n_frames = Long(1) view = View('index', 'time') _low = Int(0) _high = Property(depends_on='n_frames') _low_ = Float(0) def _get_time(self): return self.index / self.fps def _set_time(self, value): value = int(round(self.fps * value + 0.5)) if value > self.n_frames - 1: value = self.n_frames - 1 self.index = value def _get__high(self): return self.n_frames - 1
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 Trace(PolyLine): x = Instance(Expression) y = Instance(Expression) z = Instance(Expression) #point = Instance(Expression) length = Int(0) traits_view = View( Item(name='length', label='Frame'), Item(name='x', style='custom'), Item(name='y', style='custom'), Item(name='z', style='custom'), #Item(name = 'points', style = 'custom'), Item(name='properties', editor=InstanceEditor(), label='Render properties'), title='Line properties') def __init__(self, *args, **kwargs): PolyLine.__init__(self, *args, **kwargs) def update(self): x = self.x.get_array(first=-self.length) y = self.y.get_array(first=-self.length) z = self.z.get_array(first=-self.length) self.points = array([x, y, z]).T #self.points = self.point.get_array(first=-self.length) #array([x,y,z]).T #print self.point.get_array(first=-self.length).shape super(Trace, self).update()
class Demo(HasTraits): count = Int(0) button = Button("Click Me") view = View(Item("button"), Item("count")) def _button_fired(self): self.count += 1
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 ISplashScreen(IWindow): """ The interface for a splash screen. """ #### 'ISplashScreen' interface ############################################ # The image to display on the splash screen. image = Instance(ImageResource, ImageResource('splash')) # If log messages are to be displayed then this is the logging level. See # the Python documentation for the 'logging' module for more details. log_level = Int(logging.DEBUG) # Should the splash screen display log messages in the splash text? show_log_messages = Bool(True) # Optional text to display on top of the splash image. text = Unicode # The text color. # FIXME v3: When TraitsUI supports PyQt then change this to 'Color', # (unless that needs the toolkit to be selected too soon, in which case it # may need to stay as Any - or Str?) #text_color = WxColor('black') text_color = Any # The text font. # FIXME v3: When TraitsUI supports PyQt then change this back to # 'Font(None)' with the actual default being toolkit specific. #text_font = Font(None) text_font = Any # The x, y location where the text will be drawn. # FIXME v3: Remove this. text_location = Tuple(5, 5)
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 RegularPolygon(Polygon): center = Tuple(Float, Float) sides = Int(6) radius = Float(1.0) theta = Float(0.) # orientation in radians sequence = 'rectangles' def __init__(self): self._update_vertices() def _sides_changed(self, old, new): self._update_verts() def _theta_changed(self, old, new): self._update_verts() def _radius_changed(self, old, new): self._update_verts() def _update_verts(self): theta = 2 * npy.pi / self.sides * npy.arange(self.sides) + self.theta x, y = self.center xy = npy.zeros((self.sides, 2)) xy[:, 0] = x + self.radius * npy.cos(theta) xy[:, 1] = y + self.radius * npy.sin(theta) self.vertices = xy
class PupilGenerator(HasTraits): wavelength = Float(700) NA = Float(1.49) n = Float(1.51) pupilSizeX = Int(61) pixelSize = Float(70) pupils = List(_pupils) aberations = List(ZernikeMode, value=[ZernikeMode(i) for i in range(25)]) basePupil = Instance(Pupil, _getDefaultPupil) pupil = None view = View(Item( 'basePupil', label='Pupil source', editor=InstanceEditor(name='pupils', editable=True), ), Item('_'), Item('wavelength'), Item('n'), Item('NA'), Item('pupilSizeX'), Item('pixelSize'), Item('_'), Item('aberations'), buttons=[OKButton]) def GetPupil(self): u, v, R, pupil = self.basePupil.GeneratePupil(self.pixelSize, self.pupilSizeX, self.wavelength, self.NA, self.n)
class ParafoilWizard(HasTraits): span = Float(7.5) chord = Float(3.75) number_of_cells = Int(9) anhedral_angle = Float(40) sectiondata = Instance(SectionData, SectionAFILEData(filename=os.path.join(src_dir, 'testcase', 'avl_case', 'clarky.dat'))) #le_cut = Range(0.0,1.0,0.0, desc='leading edge cut position') inlet_height = Range(0.0, 0.5, 0.1, desc='the height of the inlet cut') cut_angle = Range(90., 180., 135, desc='leading edge cut angle with the positive x axis') def get_surface(self): num_sections = (self.number_of_cells + 1) // 2 anhedral_angle_r = self.anhedral_angle * numpy.pi / 180 r = self.span / 2.0 / numpy.sin(anhedral_angle_r) sections = [] y = numpy.linspace(self.number_of_cells % 2, self.number_of_cells, num_sections) / self.number_of_cells sectiondata = SectionAIRFOILData.get_clipped_section_data(self.sectiondata, self.inlet_height, self.cut_angle) filename = 'parafoil.dat' filename = os.path.abspath(filename) sectiondata.write_airfoil_file(filename, 'parafoil') if self.number_of_cells%2==1: le = numpy.zeros((3,)) sectionafile = SectionAFILEData(filename=filename) sections.append(Section(leading_edge=le, chord=self.chord, type=sectionafile.type, data=sectionafile)) for i, theta in enumerate(anhedral_angle_r * y): le = numpy.array([0, r * numpy.sin(theta), r * (numpy.cos(theta) - 1)]) sectionafile = SectionAFILEData(filename=filename) sections.append(Section(leading_edge=le, chord=self.chord, type=sectionafile.type, data=sectionafile)) surface = Surface(name='Parafoil', yduplicate=0, sections=sections) return surface traits_view = View('span','chord','number_of_cells','anhedral_angle', Item('object.sectiondata.filename',label='section data file'), 'inlet_height','cut_angle')
class LocatedPerson(Person): street = Str city = Str state = Str zip = Int(78663) extra = Group('street', 'city', 'state', 'zip')
class Baz(HasTraits): _enthought_pickle_version = Int(3) b3 = Bool(False) f3 = Float(3) i3 = Int(3) s3 = Str('baz') def __setstate__(self, state): logger.debug('Running Baz\'s original __setstate__') if state['_enthought_pickle_version'] < 3: info = [('b2', 'b3'), ('f2', 'f3'), ('i2', 'i3'), ('s2', 's3')] for old, new in info: if old in state: state[new] = state[old] del state[old] state['_enthought_pickle_version'] = 3 self.__dict__.update(state)
class Counter(HasTraits): value = Int() add_one = Button() def _add_one_fired(self): self.value += 1 view = View('value', Item('add_one', show_label=False))
class CameraPosition(HasTraits): position = CArray(shape=(3, ), dtype='float64') focal_point = CArray(shape=(3, ), dtype='float64') view_up = CArray(shape=(3, ), dtype='float64') clipping_range = CArray(shape=(2, ), dtype='float64') distance = Float num_steps = Int(10) orientation_wxyz = CArray(shape=(4, ), dtype='float64')
class AcmeUI(HasTraits): """ The Acme UI class! """ # The traits that we want to initialize from preferences. bgcolor = Str('blue') width = Int(50) ratio = Float(1.0) visible = Bool(True)
class AcmeUI(HasTraits): """ The Acme UI class! """ # The traits that we want to initialize from preferences. bgcolor = Str('red') width = Int(60) ratio = Float(2.0) visible = Bool(False)
class TextEditorDemo ( HasTraits ): """ This class specifies the details of the TextEditor demo. """ # Define a trait for each of three variants string_trait = Str( "sample string" ) int_trait = Int( 1 ) password = Password # TextEditor display without multi-line capability (for various traits): text_int_group = Group( Item('int_trait', style='simple', label='Simple'), Item('_'), Item('int_trait', style='custom', label='Custom'), Item('_'), Item('int_trait', style='text', label='Text'), Item('_'), Item('int_trait', style='readonly', label='ReadOnly'), label='Integer' ) # TextEditor display with multi-line capability (for various traits): text_str_group = Group( Item('string_trait', style='simple', label='Simple'), Item('_'), Item('string_trait', style='custom', label='Custom'), Item('_'), Item('string_trait', style='text', label='Text'), Item('_'), Item('string_trait', style='readonly', label='ReadOnly'), label='String' ) # TextEditor display with secret typing capability (for Password traits): text_pass_group = Group( Item('password', style='simple', label='Simple'), Item('_'), Item('password', style='custom', label='Custom'), Item('_'), Item('password', style='text', label='Text'), Item('_'), Item('password', style='readonly', label='ReadOnly'), label='Password' ) # The view includes one group per data type. These will be displayed # on separate tabbed panels. view1 = View(text_int_group, text_str_group, text_pass_group, title = 'TextEditor', buttons = ['OK'])
class IvyDriver(IODriver): """ Ivy input driver. """ _use_thread = False _ivy_id = Int(0) name = Str('Ivy Driver') ivy_agent_name = Str('Plot-o-matic') ivy_bus = Str('') ivy_ready_msg = Str('READY') ivy_regex = Str('(.*)') view = View(Item('ivy_agent_name', label='Agent name', editor=TextEditor(enter_set=True, auto_set=False)), Item('ivy_bus', label='Ivy bus', editor=TextEditor(enter_set=True, auto_set=False)), Item('ivy_regex', label='Regex', editor=TextEditor(enter_set=True, auto_set=False)), Item('ivy_ready_msg', label='Ready message', editor=TextEditor(enter_set=True, auto_set=False)), title='Ivy input driver') def open(self): IvyInit(self.ivy_agent_name, self.ivy_ready_msg) logging.getLogger('Ivy').setLevel(logging.ERROR) IvyStart(self.ivy_bus) self._ivy_id = IvyBindMsg(self.on_ivy_msg, self.ivy_regex) def close(self): IvyUnBindMsg(self._ivy_id) IvyStop() def reopen(self): self.close() self.open() def _ivy_agent_name_changed(self): self.reopen() def _ivy_bus_changed(self): self.reopen() def _ivy_ready_msg_changed(self): self.reopen() def _ivy_regex_changed(self): self.reopen() def on_ivy_msg(self, agent, *larg): if larg[0] != self.ivy_ready_msg: self.pass_data(larg[0])
class ZernikeMode(HasTraits): num = Int(0) coeff = Float(0) name = Property() def _get_name(self): return zernike.NameByNumber[self.num] def __init__(self, num): self.num = num
def __source_changed(self, old, new): steps = self._source.steps if len(steps): self.add_trait('step', Int(0)) self.step_low, self.step_high = steps[0], steps[-1] times = self._source.times if len(times): self.add_trait('time', Float(0.0)) self.time_low, self.time_high = times[0], times[-1]