class RemapDemo(HasTraits): surf_func = Str() func_list = List([ "np.sqrt(8- x**2 - y**2)", "np.sin(6*np.sqrt(x**2+y**2))", "np.sin(6*x)", "np.sin(6*y)", "np.sin(np.sqrt(x**2+y**2))/np.sqrt(x**2+y**2)", ]) range = Range(1.0, 100.0) view_height = Range(1.0, 50.0, 10.0) grid = Bool(True) view = View(Item("surf_func", label="曲面函数", editor=EnumEditor(name="func_list", auto_set=False, evaluate=lambda x: x)), Item("range", label="曲面范围"), Item("view_height", label="视点高度"), Item("grid", label="显示网格"), title="Remap Demo控制面板") def __init__(self, *args, **kwargs): super(RemapDemo, self).__init__(*args, **kwargs) self.img = cv.imread("lena.jpg") self.size = self.img.size() self.w, self.h = self.size.width, self.size.height self.dstimg = cv.Mat() self.map1 = cv.Mat(self.size, cv.CV_32FC1) self.map2 = cv.Mat(self.size, cv.CV_32FC1) self.gridimg = self.make_grid_img() self.on_trait_change(self.redraw, "surf_func,range,view_height,grid") def redraw(self): def func(x, y): return eval(self.surf_func, globals(), locals()) try: self.map1[:], self.map2[:] = make_surf_map(func, self.range, self.w, self.h, self.view_height) except SyntaxError: return if self.grid: img = self.gridimg else: img = self.img cv.remap(img, self.dstimg, self.map1, self.map2, cv.INTER_LINEAR) cv.imshow("Remap Demo", self.dstimg) def make_grid_img(self): img = self.img.clone() for i in range(0, self.w, 30): cv.line(img, cv.Point(i, 0), cv.Point(i, self.h), cv.CV_RGB(0, 0, 0), 1) for i in range(0, self.h, 30): cv.line(img, cv.Point(0, i), cv.Point(self.w, i), cv.CV_RGB(0, 0, 0), 1) return img
class CCSliders(HasTraits): odorname = Str odorconc = Float cc_orn = Range(-3.0, 4.0, 1.0) cc_nrm = Range(-3.0, 4.0, 1.0) cc_cen = Range(-3.0, 4.0, 1.0) view = View(Item('odorname'), Item('odorconc'), Item('cc_orn'), Item('cc_nrm'), Item('cc_cen')) def __init__(self, odorname): self.edit_traits() self.odorname = odorname def __set_conc(self, conc, layer): self.odorconc = conc dw() bulb.show_odor(self.odorname, conc, layer) up() def _cc_orn_changed(self): self.__set_conc(10**self.cc_orn, 0) def _cc_nrm_changed(self): self.__set_conc(10**self.cc_nrm, 1) def _cc_cen_changed(self): self.__set_conc(10**self.cc_cen, 2)
class Equalizer(HasTraits): freq = Range(10.0, SAMPLING_RATE / 2, 1000) Q = Range(0.1, 10.0, 1.0) gain = Range(-24.0, 24.0, 0) a = List(Float, [1.0, 0.0, 0.0]) b = List(Float, [1.0, 0.0, 0.0]) h = Array(dtype=np.complex, transient=True) def __init__(self): super(Equalizer, self).__init__() self.design_parameter() @on_trait_change("freq,Q,gain") def design_parameter(self): '''设计系数并计算频率响应''' try: self.b, self.a = design_equalizer(self.freq, self.Q, self.gain, SAMPLING_RATE) except: self.b, self.a = [1.0, 0.0, 0.0], [1.0, 0.0, 0.0] self.h = myfreqz(self.b, self.a, W) def export_parameters(self, f): '''输出滤波器系数为C语言数组''' tmp = self.b[0], self.b[1], self.b[2], self.a[1], self.a[ 2], self.freq, self.Q, self.gain f.write("{%s,%s,%s,%s,%s}, // %s,%s,%s\n" % tmp)
class Visualization(HasTraits): alpha = Range(0.0, 4.0, 1.0 / 4) beta = Range(0.0, 4.0, 1.0 / 4) scene = Instance(MlabSceneModel, ()) def __init__(self): # Do not forget to call the parent's __init__ HasTraits.__init__(self) x, y, z, = tens_fld(1, 1, 1, self.beta, self.alpha) self.plot = self.scene.mlab.mesh(x, y, z, colormap='copper', representation='surface') @on_trait_change('beta,alpha') def update_plot(self): x, y, z, = tens_fld(1, 1, 1, self.beta, self.alpha) self.plot.mlab_source.set(x=x, y=y, z=z) # the layout of the dialog created view = View( Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=750, width=750, show_label=False), HGroup( '_', 'beta', 'alpha', ), )
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 Visualization(HasTraits): meridonal = Range(1, 30, 6) transverse = Range(0, 30, 11) scene = Instance(MlabSceneModel, ()) def __init__(self): HasTraits.__init__(self) x, y, z, t = curve(self.meridonal, self.transverse) self.plot = self.scene.mlab.plot3d(x, y, x, t, colormap='Spectral') @on_trait_change('meridonal,transverse') def update_plot(self): x, y, z, t = curve(self.meridonal, self.transverse) self.plot.mlab_source.set(x=x, y=y, z=z, scalars=t) #layout of the dialog view = View( Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=False), HGroup( '_', 'meridonal', 'transverse', ), )
class ScrubberDemo(HasTraits): # Define some sample ranges and values: simple_integer = Range(0, 100) rollover_float = Range(-10.0, 10.0) bordered_unbounded = Float themed_dynamic_low = Range(high=-0.01, value=-10.0) themed_dynamic_high = Range(low=0.01, value=10.0) themed_dynamic_value = Range('themed_dynamic_low', 'themed_dynamic_high', 0.0) # Define the demo view: view = View(HGroup( VGroup(Item('simple_integer', editor=ScrubberEditor()), Item('rollover_float', editor=ScrubberEditor(hover_color=0xFFFFFF, active_color=0xA0CD9E)), Item('bordered_unbounded', editor=ScrubberEditor(hover_color=0xFFFFFF, active_color=0xA0CD9E, border_color=0x808080)), TItem('themed_dynamic_low'), TItem('themed_dynamic_high'), TItem('themed_dynamic_value'), show_border=True, label='Scrubber Editors'), VGroup(Item('simple_integer'), Item('rollover_float'), Item('bordered_unbounded'), Item('themed_dynamic_low'), Item('themed_dynamic_high'), Item('themed_dynamic_value'), show_border=True, label='Default Editors'), spring), title='Scrubber Editor Demo')
class Instance(HasTraits): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- integer_text = Int(1) enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 5) boolean = Bool(True) view = View('integer_text', 'enumeration', 'float_range', 'int_range', 'boolean')
class DoublePendulumGUI(HasTraits): pendulum = Instance(DoublePendulum) m1 = Range(1.0, 10.0, 2.0) m2 = Range(1.0, 10.0, 2.0) l1 = Range(1.0, 10.0, 2.0) l2 = Range(1.0, 10.0, 2.0) positions = Tuple index = Int(0) timer = Instance(Timer) graph = Instance(DoublePendulumComponent) animation = Bool(True) view = View(HGroup( VGroup( Item("m1"), Item("m2"), Item("l1"), Item("l2"), ), Item("graph", editor=ComponentEditor(), show_label=False), ), width=600, height=400, title="双摆演示", resizable=True) def __init__(self): self.pendulum = DoublePendulum(self.m1, self.m2, self.l1, self.l2) self.pendulum.init_status[:] = 1.0, 2.0, 0, 0 self.graph = DoublePendulumComponent() self.graph.gui = self self.timer = Timer(10, self.on_timer) def on_timer(self, *args): if len(self.positions) == 0 or self.index == len(self.positions[0]): self.pendulum.m1 = self.m1 self.pendulum.m2 = self.m2 self.pendulum.l1 = self.l1 self.pendulum.l2 = self.l2 if self.animation: self.positions = double_pendulum_odeint( self.pendulum, 0, 0.5, 0.02) else: self.positions = double_pendulum_odeint( self.pendulum, 0, 0.00001, 0.00001) self.index = 0 self.graph.p = tuple(array[self.index] for array in self.positions) self.index += 1 self.graph.request_redraw()
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 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()
class Person(HasTraits): """ Demo class for demonstrating dynamic interface restructuring. """ first_name = Str last_name = Str age = Range(0, 120) misc = Instance(Spec) # Interface for attributes that are always visible in interface: gen_group = Group(Item(name='first_name'), Item(name='last_name'), Item(name='age'), label='General Info', show_border=True) # Interface for attributes that depend on the value of 'age': spec_group = Group(Group(Item(name='misc', style='custom'), show_labels=False), label='Additional Info', show_border=True) # A simple View is enough as long as the right handler is specified: view = View(Group(gen_group, spec_group), title='Personal Information', buttons=['OK'], resizable=True, handler=PersonHandler())
def __init__(self, vmin, vmax, vdefault, **traits): HasTraits.__init__(self, **traits) self.vmin = vmin self.vmax = vmax trait = Range(float(vmin), float(vmax), value=vdefault) self.add_trait("coord", trait) self.coord = vdefault
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 ChildSpec(Spec): """ Trait list for children (assigned to 'misc' for a Person when age < 18). """ legal_guardian = Str school = Str grade = Range(1, 12) traits_view = View('legal_guardian', 'school', 'grade')
class Adult(HasTraits): first_name = Str last_name = Str age = Range(21, 99) registered_voter = Bool traits_view = View(Item(name='first_name'), Item(name='last_name'), Item(name='age'), Item(name='registered_voter'))
class GaussianFilter(BaseFilter): sigma = Range(0., 100, 0.) def process(self, image): if self.sigma != 0.: print('processing gaussian') image = nd.gaussian_filter(image, self.sigma, **self.kw) return image
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 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())
class Person(HasTraits): # General traits: first_name = Str last_name = Str age = Range(0, 120) # Traits for children only: legal_guardian = Str school = Str grade = Range(1, 12) # Traits for adults only: marital_status = Enum('single', 'married', 'divorced', 'widowed') registered_voter = Bool(False) military_service = Bool(False) # Interface for attributes that are always visible in interface: gen_group = Group(Item(name='first_name'), Item(name='last_name'), Item(name='age'), label='General Info', show_border=True) # Interface for attributes of Persons under 18: child_group = Group(Item(name='legal_guardian'), Item(name='school'), Item(name='grade'), label='Additional Info', show_border=True, visible_when='age < 18') # Interface for attributes of Persons 18 and over: adult_group = Group(Item(name='marital_status'), Item(name='registered_voter'), Item(name='military_service'), label='Additional Info', show_border=True, visible_when='age >= 18') # A simple View is sufficient, since the Group definitions do all the work: view = View(Group(gen_group, child_group, adult_group), title='Personal Information', resizable=True, buttons=['OK'])
class MyModel(HasTraits): n_meridional = Range( 0, 30, 6, ) #mode='spinner') n_longitudinal = Range( 0, 30, 11, ) #mode='spinner') scene = Instance(MlabSceneModel, ()) plot = Instance(PipelineBase) # When the scene is activated, or when the parameters are changed, we # update the plot. @on_trait_change('n_meridional,n_longitudinal,scene.activated') def update_plot(self): x, y, z, t = curve(self.n_meridional, self.n_longitudinal) if self.plot is None: self.plot = self.scene.mlab.plot3d(x, y, z, t, tube_radius=0.025, colormap='Spectral') else: self.plot.mlab_source.set(x=x, y=y, z=z, scalars=t) # The layout of the dialog created view = View( Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=False), Group( '_', 'n_meridional', 'n_longitudinal', ), resizable=True, )
class System(HasTraits): # The mass of the system: mass = Range(0.0, 100.0) # The velocity of the system: velocity = Range(0.0, 100.0) # The kinetic energy of the system: kinetic_energy = Property(Float) # The current error status of the system: error = Property( Bool, sync_to_view='mass.invalid, velocity.invalid, status.invalid') # The current status of the system: status = Property(Str) view = View( VGroup( VGroup(Item('mass'), Item('velocity'), Item('kinetic_energy', style='readonly', format_str='%.0f'), label='System', show_border=True), VGroup(Item('status', style='readonly', show_label=False), label='Status', show_border=True), )) @property_depends_on('mass, velocity') def _get_kinetic_energy(self): return (self.mass * self.velocity * self.velocity) / 2.0 @property_depends_on('kinetic_energy') def _get_error(self): return (self.kinetic_energy > 50000.0) @property_depends_on('error') def _get_status(self): if self.error: return 'The kinetic energy of the system is too high.' return ''
class Star(HasTraits): x = Float y = Float r = Float theta = Float n = Range(3, 10) s = Float c = Tuple def polygon(self): return star_polygon(self.x, self.y, self.r, self.theta, self.n, self.s)
def __init__(self, default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, **metadata): # Range trait didn't seem to handle "None" correctly when passed on # the command line. if default_value is None: if low is None and high is None: default_value = 0 elif low is None: default_value = high else: default_value = low if low is None: low = -maxint if high is None: high = maxint if not isinstance(default_value, int): raise ValueError("Default value for an Int must be an integer.") if not isinstance(low, int): raise ValueError("Lower bound for an Int must be an integer.") if not isinstance(high, int): raise ValueError("Upper bound for an Int must be an integer.") if low > high: raise ValueError("Lower bound is greater than upper bound.") if default_value > high or default_value < low: raise ValueError("Default value is outside of bounds [%s, %s]." % (str(low), str(high))) # 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 self._validator = Range(value=default_value, low=low, high=high, exclude_low=exclude_low, exclude_high=exclude_high, **metadata) # Add low and high to the trait's dictionary so they can be accessed metadata['low'] = low metadata['high'] = high metadata['exclude_low'] = exclude_low metadata['exclude_high'] = exclude_high super(Int, self).__init__(default_value=default_value, **metadata)
class ToolkitEditorFactory(EditorFactory): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- cols = Range(1, 20) # Number of columns to use when displayed as a grid values = List # List of possible checklist values (either a list # of strings, or a list of 2-element sequences: # ( value, label )) #--------------------------------------------------------------------------- # Performs any initialization needed after all constructor traits have # been set: #--------------------------------------------------------------------------- def init(self, handler=None): """ Performs any initialization needed after all constructor traits have been set. """ values = self.values if isinstance(values[0], basestring): values = [(x, x.capitalize()) for x in values] self._values = [x[0] for x in values] self._names = [x[1] for x in values] #--------------------------------------------------------------------------- # 'Editor' factory methods: #--------------------------------------------------------------------------- def simple_editor(self, ui, object, name, description, parent): return SimpleEditor(parent, factory=self, ui=ui, object=object, name=name, description=description) def custom_editor(self, ui, object, name, description, parent): return CustomEditor(parent, factory=self, ui=ui, object=object, name=name, description=description) def text_editor(self, ui, object, name, description, parent): return TextEditor(parent, factory=self, ui=ui, object=object, name=name, description=description)
class WithLargeIntRange(HasTraits): r = Range(0, 1000) r_copied_on_change = Str _changed_handler_calls = Int def _r_changed(self, old, new): self._changed_handler_calls += 1 self.r_copied_on_change = str(self.r) if self.r > 100: self.r = 0
class WithFloatRange(HasTraits): r = Range(0.0, 100.0) r_copied_on_change = Str _changed_handler_calls = Int def _r_changed(self, old, new): self._changed_handler_calls += 1 self.r_copied_on_change = str(self.r) if (self.r % 10) > 0: self.r += 10-(self.r % 10)
class ExtentDialog(HasTraits): """ A dialog to graphical adjust the extents of a filter. """ # Data extents data_x_min = Float data_x_max = Float data_y_min = Float data_y_max = Float data_z_min = Float data_z_max = Float x_min = Range('data_x_min', 'data_x_max', 'data_x_min') x_max = Range('data_x_min', 'data_x_max', 'data_x_max') y_min = Range('data_y_min', 'data_y_max', 'data_y_min') y_max = Range('data_y_min', 'data_y_max', 'data_y_max') z_min = Range('data_z_min', 'data_z_max', 'data_z_min') z_max = Range('data_z_min', 'data_z_max', 'data_z_max') filter = Instance(HasTraits, allow_none=False) @on_trait_change('x_min,x_max,y_min,y_max,z_min,z_max') def update_extent(self): if (self.filter is not None and self.x_min < self.x_max and self.y_min < self.y_max and self.z_min < self.z_max ): self.filter.extent = (self.x_min, self.x_max, self.y_min, self.y_max, self.z_min, self.z_max) view = View('x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max', title='Edit extent', resizable=True)
class Pen(HasTraits): """ Store pen traits. """ # Stroke colour. color = Color("black", desc="stroke colour") # Fill colour. fill_color = Color("black", desc="fill colour") # Stroke width in points. line_width = Range(low=1, high=8, value=1, desc="stroke width in points") # Text font. font = Font #("14 point Arial")
class MeanShiftDemo(HasTraits): spatial_radius = Range(1, 40, 20) color_radius = Range(1, 100, 40) max_level = Range(1, 4, 2) do_button = Button("计算") view = View(Item("spatial_radius", label="空间半径"), Item("color_radius", label="颜色半径"), Item("max_level", label="最大层数"), Item("do_button", show_label=False), title="Mean Shift Demo控制面板") def __init__(self, *args, **kwargs): super(MeanShiftDemo, self).__init__(*args, **kwargs) self.img = cv.imread("fruits.jpg") self.img2 = self.img.clone() self.on_trait_change(self.redraw, "do_button") self.redraw() def redraw(self): cv.pyrMeanShiftFiltering(self.img, self.img2, self.spatial_radius, self.color_radius, self.max_level) cv.imshow("Mean Shift Demo", self.img2)
def __init__(self, eval=None, label='Value', trait=None, min=0.0, max=1.0, initial=None, **traits): HasTraits.__init__(self, **traits) if trait is None: if min > max: min, max = max, min if initial is None: initial = min elif not (min <= initial <= max): initial = [min, max][ abs(initial - min) > abs(initial - max)] trait = Range(min, max, value = initial) self.add_trait(label, trait)
class Int(Variable): """A variable wrapper for an integer valid within a specified range of values. """ def __init__(self, default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, **metadata): # Range trait didn't seem to handle "None" correctly when passed on # the command line. if default_value is None: if low is None and high is None: default_value = 0 elif low is None: default_value = high else: default_value = low if low is None: low = -maxint if high is None: high = maxint if not isinstance(default_value, int): raise ValueError("Default value for an Int must be an integer.") if not isinstance(low, int): raise ValueError("Lower bound for an Int must be an integer.") if not isinstance(high, int): raise ValueError("Upper bound for an Int must be an integer.") if low > high: raise ValueError("Lower bound is greater than upper bound.") if default_value > high or default_value < low: raise ValueError("Default value is outside of bounds [%s, %s]." % (str(low), str(high))) # 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 self._validator = Range(value=default_value, low=low, high=high, exclude_low=exclude_low, exclude_high=exclude_high, **metadata) # Add low and high to the trait's dictionary so they can be accessed metadata['low'] = low metadata['high'] = high metadata['exclude_low'] = exclude_low metadata['exclude_high'] = exclude_high super(Int, self).__init__(default_value=default_value, **metadata) def validate(self, obj, name, value): """ Validates that a specified value is valid for this trait.""" try: return self._validator.validate(obj, name, value) except Exception: self.error(obj, name, value) def error(self, obj, name, value): """Returns a descriptive error string.""" # pylint: disable-msg=E1101 right = left = '=' if self.exclude_high is True: right = '' if self.exclude_low is True: left = '' if self.low is None and self.high is None: info = "an int" elif self.low is not None and self.high is not None: info = "%s <%s an integer <%s %s"% (self.low, left, right, self.high) elif self.low is not None: info = "a float with a value >%s %s"% (left, self.low) else: # self.high is not None info = "a float with a value <%s %s"% (right, self.high) vtype = type( value ) msg = "Variable '%s' must be %s, but a value of %s %s was specified." % \ (name, info, value, vtype) obj.raise_exception(msg, ValueError)
class Float(Variable): """A Variable wrapper for floating point number valid within a specified range of values. """ def __init__(self, default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, units=None, **metadata): # Determine defalt_value if unspecified if default_value is None: if low is None and high is None: default_value = 0.0 elif low is None: default_value = high else: default_value = low else: if not isinstance(default_value, float): if isinstance(default_value, int): default_value = float(default_value) else: raise ValueError("Default value should be a float.") # excludes must be saved locally because we override error() self.exclude_low = exclude_low self.exclude_high = exclude_high # 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 units in the metadata dictionary if units is not None: metadata['units'] = units # The Range trait must be used if High or Low is set if low is None and high is None: self._validator = TraitFloat(default_value, **metadata) else: if low is None: low = -float_info.max else: low = float(low) if high is None: high = float_info.max else: high = float(high) if low > high: raise ValueError("Lower bound is greater than upper bound.") if default_value > high or default_value < low: raise ValueError("Default value is outside of bounds [%s, %s]." % (str(low), str(high))) # Range can be float or int, so we need to force these to be float. default_value = float(default_value) self._validator = Range(low=low, high=high, value=default_value, exclude_low=exclude_low, exclude_high=exclude_high, **metadata) # If there are units, test them by creating a physical quantity if 'units' in metadata: try: pq = PhysicalQuantity(0., metadata['units']) except: raise ValueError("Units of '%s' are invalid" % metadata['units']) # Add low and high to the trait's dictionary so they can be accessed metadata['low'] = low metadata['high'] = high super(Float, self).__init__(default_value=default_value, **metadata) def validate(self, obj, name, value): """ Validates that a specified value is valid for this trait. Units are converted as needed. """ # pylint: disable-msg=E1101 # If both source and target have units, we need to process differently if isinstance(value, AttrWrapper): if self.units: valunits = value.metadata.get('units') if valunits and isinstance(valunits, basestring) and self.units != valunits: return self._validate_with_metadata(obj, name, value.value, valunits) value = value.value elif isinstance(value, UncertainDistribution): value = value.getvalue() try: return self._validator.validate(obj, name, value) except Exception: self.error(obj, name, value) def error(self, obj, name, value): """Returns a descriptive error string.""" # pylint: disable-msg=E1101 if self.low is None and self.high is None: if self.units: info = "a float having units compatible with '%s'" % self.units else: info = "a float" elif self.low is not None and self.high is not None: right = ']' left = '[' if self.exclude_high is True: right = ')' if self.exclude_low is True: left = '(' info = "a float in the range %s%s, %s%s"% \ (left,self.low,self.high,right) elif self.low is not None: info = "a float with a value > %s"% self.low else: # self.high is not None info = "a float with a value < %s"% self.high vtype = type( value ) msg = "Variable '%s' must be %s, but a value of %s %s was specified." % \ (name, info, value, vtype) try: obj.raise_exception(msg, ValueError) except AttributeError: raise ValueError(msg) def get_val_wrapper(self, value, index=None): """Return a UnitsAttrWrapper object. Its value attribute will be filled in by the caller. """ if index is not None: raise ValueError("Float does not support indexing") # pylint: disable-msg=E1101 if self.units is None: return value return UnitsAttrWrapper(value, units=self.units) def _validate_with_metadata(self, obj, name, value, src_units): """Perform validation and unit conversion using metadata from the source trait. """ # pylint: disable-msg=E1101 dst_units = self.units if isinstance(value, UncertainDistribution): value = value.getvalue() # FIXME: The try blocks testing whether the unit is bogus or undefined # are generally redundant because that test is done at creation. HOWEVER # you might have a case where it wasn't tested because it's technically # not a float. NPSS wrapper may be such a case. A test needs to be # constructed to test these lines. # Note: benchmarking showed that this check does speed things up -- KTM if src_units == dst_units: try: return self._validator.validate(obj, name, value) except Exception: self.error(obj, name, value) try: pq = PhysicalQuantity(value, src_units) except NameError: raise NameError("while setting value of %s: undefined unit '%s'" % (src_units, name)) try: pq.convert_to_unit(dst_units) except NameError: raise NameError("undefined unit '%s' for variable '%s'" % (dst_units, name)) except TypeError: msg = "%s: units '%s' are incompatible " % (name, src_units) + \ "with assigning units of '%s'" % (dst_units) raise TypeError(msg) try: return self._validator.validate(obj, name, pq.value) except Exception: self.error(obj, name, pq.value)
def __init__(self, default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, units=None, **metadata): # Determine defalt_value if unspecified if default_value is None: if low is None and high is None: default_value = 0.0 elif low is None: default_value = high else: default_value = low else: if not isinstance(default_value, float): if isinstance(default_value, int): default_value = float(default_value) else: raise ValueError("Default value should be a float.") # excludes must be saved locally because we override error() self.exclude_low = exclude_low self.exclude_high = exclude_high # 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 units in the metadata dictionary if units is not None: metadata['units'] = units # The Range trait must be used if High or Low is set if low is None and high is None: self._validator = TraitFloat(default_value, **metadata) else: if low is None: low = -float_info.max else: low = float(low) if high is None: high = float_info.max else: high = float(high) if low > high: raise ValueError("Lower bound is greater than upper bound.") if default_value > high or default_value < low: raise ValueError("Default value is outside of bounds [%s, %s]." % (str(low), str(high))) # Range can be float or int, so we need to force these to be float. default_value = float(default_value) self._validator = Range(low=low, high=high, value=default_value, exclude_low=exclude_low, exclude_high=exclude_high, **metadata) # If there are units, test them by creating a physical quantity if 'units' in metadata: try: pq = PhysicalQuantity(0., metadata['units']) except: raise ValueError("Units of '%s' are invalid" % metadata['units']) # Add low and high to the trait's dictionary so they can be accessed metadata['low'] = low metadata['high'] = high super(Float, self).__init__(default_value=default_value, **metadata)