Пример #1
0
class Inputs(HasTraits):
    """ Object that contains the parameters that control the experiment, 
        modified by the user.
    """
    start = Int(0, label="Start", desc="Startpoint from where to plot")
    length = Int(1100, label="N/o samples.", desc="Number of datapoints to get")
    step = Int(5, label="Step", desc="Step size between the samples")
    offset = Int(50, label="Scaling", desc="Vertical distance between channels")
    preset = Enum("Oddball_eeg","20 s","10 s","1 s")
    timescale = Enum("samples","seconds","minutes","hours")
    
    linewidth = Range(0.1,2.0,0.5)
    color1 = RGBColor((0,0,0))
    color2 = RGBColor((0,0,1))
    xtickswidth = Int(1000, label="X-Ticks", desc="Horizontal distance between ticks on x-axis")

    
    show_trial_length = Bool(False, label="Show")
    trial_0 = Int(-500, label="t0", desc="Beginning of trial")
    trial_1 = Int(1000, label="t0", desc="End of trial")
    trial_alpha = Enum(0.3,0.1,0.2,0.3,0.4,0.5,0.8,1)
    #color_trial = RGBColor((0,0,1))
    
    traits_view = View(VGroup(
                       VGroup(
                            Item('preset'),
                            Item('start'),
                            Item('length'),
                            Item('step'),
                            Item('offset'),
                            Item('timescale'),
                       ),
                       VGroup(
                            Item('linewidth'),
                            Item('color1', style='custom', springy=True,resizable=False,show_label=True,label="Color 1"),
                            Item('color2', style='custom', springy=True,resizable=False,show_label=True,label="Color 2"),
                            Item('xtickswidth',label="Grid-spacing"),
                            VGroup(
                                 Item('show_trial_length'),
                                Item('trial_0'),
                                Item('trial_1'),
                                Item('trial_alpha'),
                                #Item('color_trial', style='custom', springy=True,resizable=False,show_label=True,label="Color for Trial"),
                                label="Plot trial-length around markers",
                            ),
                             label="Plot-parameters",
                        ),
                 ),
            ) 
    
    def _preset_changed(self):
        slso =  input_presets[str(self.preset)]
        if slso[0] != None:
            self.start = slso[0]
        if slso[1] != None:
            self.length = slso[1]
        if slso[2] != None:
            self.step = slso[2]
        if slso[3] != None:
            self.offset = slso[3]
Пример #2
0
class ApplyRevertDemo(HasTraits):

    # Trait definitions:
    input = Str
    stack = List
    queue = List

    # Traits view definitions:
    traits_view = View(VGroup(
        VGroup(Item('input', show_label=False),
               label='Input',
               show_border=True),
        HGroup(
            VGroup(Item('stack',
                        show_label=False,
                        height=50,
                        width=100,
                        style='readonly'),
                   label='Stack',
                   show_border=True),
            VGroup(Item('queue',
                        show_label=False,
                        height=50,
                        width=100,
                        style='readonly'),
                   label='Queue',
                   show_border=True))),
                       title='Apply/Revert example',
                       buttons=['Apply', 'Revert'],
                       kind='modal',
                       handler=ApplyRevert_Handler)
Пример #3
0
class ProbePlot(HasTraits):
    def __init__(self):
        super(Probe, self).__init__()
        x = linspace(0, self.N, self.N / self.d)
        y = linspace(0, self.N, self.N / self.d)
        xgrid, ygrid = meshgrid(x[1:], y[1:])
        z = exp(-(xgrid * xgrid + ygrid * ygrid) / 10000)
        plotdata = ArrayPlotData(imagedata=z)
        plot = Plot(plotdata)
        self.renderer = plot.img_plot("imagedata",
                                      xbounds=x,
                                      ybounds=y,
                                      colormap=bone)
        #self.renderer = plot.plot(("x", "y"), type="scatter", color="blue")[0]
        self.plot = plot

    traits_view = View(VGroup(
        HGroup(
            Item('HT',
                 label="High Tension, kV",
                 help='The microscope accelerating voltage'), spring,
            Item('wl', label="Wavelength, nm", style='readonly')),
        HGroup(spring, Item('alpha', label="Conv. Angle")),
        HGroup(VGroup(Item('noms', label="Nomenclature")),
               Item('notations[self.noms]', label='Labels')),
        HGroup(Item('plot', editor=ComponentEditor(), show_label=False))),
                       width=800,
                       height=600,
                       resizable=True,
                       title="Chaco Plot")
Пример #4
0
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')
Пример #5
0
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())
Пример #6
0
class TitleEditorDemo(HasTraits):

    # Define the selection of titles that can be displayed:
    title = Enum('Select a new title from the drop down list below',
                 'This is the TitleEditor demonstration',
                 'Acme Widgets Sales for Each Quarter',
                 'This is Not Intended to be a Real Application')

    # A user settable version of the title:
    title_2 = Str('Type into the text field below to change this title')

    # A title driven by the result of a calculation:
    title_3 = Property(depends_on='value')

    # The number used to drive the calculation:
    value = Float

    # Define the test view:
    view = View(VGroup(
        VGroup(HGroup(
            Item('title', show_label=False, springy=True,
                 editor=TitleEditor())),
               Item('title'),
               show_border=True),
        VGroup(HGroup(
            Item('title_2',
                 show_label=False,
                 springy=True,
                 editor=TitleEditor())),
               Item('title_2', label='Title'),
               show_border=True),
        VGroup(HGroup(
            Item('title_3',
                 show_label=False,
                 springy=True,
                 editor=TitleEditor())),
               Item('value'),
               show_border=True)),
                width=0.4)

    #-- Property Implementations -----------------------------------------------

    @cached_property
    def _get_title_3(self):
        try:
            return ('The square root of %s is %s' %
                    (self.value, self.value**0.5))
        except:
            return ('The square root of %s is %si' % (self.value,
                                                      (-self.value)**0.5))
Пример #7
0
class UserPerspectiveName(HasTraits):
    """ Object with views for naming or renaming a user perspective. """

    ###########################################################################
    # 'UserPerspectiveName' interface.
    ###########################################################################

    # The name of the new user perspective.
    name = NotEmptyString

    # Should the editor area be shown in this perpsective?
    show_editor_area = Bool(True)

    # Help notes when creating a new view.
    new_help = Constant("""Note:
 - The new perspective will initially be empty.
 - Add new views to the perspective by selecting 
   them from the 'View' menu.
 - Drag the notebook tabs and splitter bars to 
   arrange the views within the perspective.""")

    #### Traits views #########################################################

    new_view = View(VGroup(
        VGroup('name', 'show_editor_area'),
        VGroup('_', Item('new_help', style='readonly'), show_labels=False)),
                    title='New User Perspective',
                    id='enthought.envisage.workbench.action.'
                    'new_user_perspective_action.UserPerspectiveName',
                    buttons=['OK', 'Cancel'],
                    kind='livemodal',
                    width=300)

    save_as_view = View('name',
                        title='Save User Perspective As',
                        id='enthought.envisage.workbench.action.'
                        'save_as_user_perspective_action.UserPerspectiveName',
                        buttons=['OK', 'Cancel'],
                        kind='livemodal',
                        width=300)

    rename_view = View('name',
                       title='Rename User Perspective',
                       id='enthought.envisage.workbench.action.'
                       'rename_user_perspective_action.UserPerspectiveName',
                       buttons=['OK', 'Cancel'],
                       kind='livemodal',
                       width=300)
Пример #8
0
class InternetExplorerDemo ( HasTraits ):
    
    # A URL to display:
    url = Str( 'http://' )
    
    # The list of web pages being browsed:
    pages = List( WebPage )

    # The view to display:
    view = View(
        VGroup( 
            Item( 'url',
                  label  = 'Location',
                  editor = TextEditor( auto_set = False, enter_set = True )
            )
        ),
        Item( 'pages',
              show_label = False,
              style      = 'custom',
              editor     = ListEditor( use_notebook = True,
                                       deletable    = True,
                                       dock_style   = 'tab',
                                       export       = 'DockWindowShell',
                                       page_name    = '.title' )
        )
    )    
    
    # Event handlers:
    def _url_changed ( self, url ):
        self.pages.append( WebPage( url = url.strip() ) )
Пример #9
0
class EventTableManager(HasTraits):
    """ Manage the EventTables used for the display. 
    Also controls where new marks are saved to.
    """
    evt_filenames = List(EventTableListEntry)
    evts = List(Instance(eegpy.EventTable))

    view = View(
        VGroup(
            Group(
                Item(
                    'evt_filenames',
                    editor=tabular_editor,
                    show_label=False,
                ),
                label="EventTables",
            ), ), )

    def append(self, et_fn):
        for etle in self.evt_filenames:
            if etle.fn == et_fn:
                return False
        self.evt_filenames.append(EventTableListEntry(fn=et_fn))
        #self.evt_filenames.sort(cmp=lambda x,y: cmp(x.short_fn,y.short_fn))
        self.evts.append(eegpy.EventTable(str(et_fn)))

    def get_marks(self, start, stop):
        rv = []
        for et in self.evts:
            for k in et.keys():
                for t in et[k]:
                    if t >= start and t <= stop:
                        rv.append((k, t))
        return rv
Пример #10
0
class Employee(HasTraits):

    # Define the traits:
    name = Str
    dept = Str
    email = Str

    # Define the view:
    view = View(
        VGroup(
            VGroup(
                Item('name',
                     show_label=False,
                     editor=ImageEditor(image=ImageResource(
                         'info', search_path=search_path)))),
            VGroup(Item('name'), Item('dept'), Item('email'))))
Пример #11
0
class FileTreeDemo ( HasTraits ):
    
    # The path to the file tree root:
    root_path = Directory( entries = 10 ) 
    
    # The root of the file tree:
    root = Property
    
    # The traits view to display:
    view = View(
        VGroup(
            Item( 'root_path' ),
            Item( 'root', 
                  editor = TreeEditor( editable = False, auto_open = 1 )
            ),
            show_labels = False
        ),
        width     = 0.33,
        height    = 0.50,
        resizable = True
    )
    
    #-- Traits Default Value Methods -------------------------------------------
    
    def _root_path_default ( self ):
        return getcwd()
    
    #-- Property Implementations -----------------------------------------------
    
    @property_depends_on( 'root_path' )
    def _get_root ( self ):
        return File( path = self.root_path )
Пример #12
0
class Converter ( HasStrictTraits ):
    
    # Trait definitions:
    input_amount  = CFloat( 12.0,    desc = "the input quantity" )
    input_units   = Units( 'inches', desc = "the input quantity's units" )
    output_amount = Property( depends_on = [ 'input_amount', 'input_units',
                                             'output_units' ],
                              desc = "the output quantity" ) 
    output_units  = Units( 'feet',   desc = "the output quantity's units" )

    # User interface views:
    traits_view = View( 
        VGroup( 
            HGroup( 
                Item( 'input_amount', springy = True ),
                Item( 'input_units', show_label = False ),
                label       = 'Input',
                show_border = True
            ),
            HGroup(
                Item( 'output_amount', style = 'readonly', springy = True ),
                Item( 'output_units',  show_label = False ),
                label       = 'Output',
                show_border = True
            ),
            help = ViewHelp
        ),
        title   = 'Units Converter',
        buttons = [ 'Undo', 'OK', 'Help' ]
    )
    
    # Property implementations
    def _get_output_amount ( self ):
        return ((self.input_amount * self.input_units_) / self.output_units_)
Пример #13
0
class SpringDemo(HasTraits):

    ignore = Button('Ignore')

    view = View(VGroup(
        HGroup(button,
               spring,
               button,
               show_border=True,
               label='Left and right justified'),
        HGroup(button,
               button,
               spring,
               button,
               button,
               spring,
               button,
               button,
               show_border=True,
               label='Left, center and right justified'),
        HGroup(spring,
               button,
               button,
               show_border=True,
               label='Right justified'),
        HGroup(button,
               button,
               show_border=True,
               label='Left justified (no springs)'),
    ),
                title='Spring Demo',
                buttons=['OK'])
Пример #14
0
class LineCountInfo(MFileDialogModel):
    """ Defines a file dialog extension that displays the number of text lines
        in the currently selected file.
    """

    # The number of text lines in the currently selected file:
    lines = Property(depends_on='file_name')

    #-- Traits View Definitions ------------------------------------------------

    view = View(
        VGroup(Item('lines', style='readonly'),
               label='Line Count Info',
               show_border=True))

    #-- Property Implementations -----------------------------------------------

    @cached_property
    def _get_lines(self):
        try:
            if getsize(self.file_name) > 10000000:
                return 'File too big...'

            fh = file(self.file_name, 'rb')
            data = fh.read()
            fh.close()
        except:
            return ''

        if (data.find('\x00') >= 0) or (data.find('\xFF') >= 0):
            return 'File contains binary data...'

        return ('%s lines' % commatize(len(data.splitlines())))
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()
Пример #16
0
 def default_traits_view(self):
     '''
     Generates the view from the param items.
     '''
     #rf_param_items = [ Item( 'model.' + name, format_str = '%g' ) for name in self.model.param_keys ]
     plot_param_items = [
         Item('max_x', label='max x value'),
         Item('n_points', label='No of plot points')
     ]
     control_items = [
         Item('show', show_label=False),
         Item('clear', show_label=False),
     ]
     view = View(
         HSplit(
             VGroup(
                 Item('@resp_func', show_label=False),  #*rf_param_items,
                 label='Function Parameters',
                 id='stats.spirrid_bak.rf_model_view.rf_params',
                 scrollable=True),
             VGroup(*plot_param_items,
                    label='Plot Parameters',
                    id='stats.spirrid_bak.rf_model_view.plot_params'),
             VGroup(
                 Item('model.comment', show_label=False, style='readonly'),
                 label='Comment',
                 id='stats.spirrid_bak.rf_model_view.comment',
                 scrollable=True,
             ),
             VGroup(HGroup(*control_items),
                    Item('figure',
                         editor=MPLFigureEditor(),
                         resizable=True,
                         show_label=False),
                    label='Plot',
                    id='stats.spirrid_bak.rf_model_view.plot'),
             dock='tab',
             id='stats.spirrid_bak.rf_model_view.split'),
         kind='modal',
         resizable=True,
         dock='tab',
         buttons=[OKButton],
         id='stats.spirrid_bak.rf_model_view')
     return view
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]
Пример #18
0
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 ''
Пример #19
0
class MyViewController(Controller):
    """ Define a combined controller/view class that validates that 
        MyModel.name is consistent with the 'allow_empty_string' flag. 
    """

    # When False, the model.name trait is not allowed to be empty:
    allow_empty_string = Bool

    # Last attempted value of model.name to be set by user:
    last_name = Str

    # Define the view associated with this controller:
    view = View(
        VGroup(
            HGroup(Item('name', springy=True), '10',
                   Item('controller.allow_empty_string', label='Allow Empty')),

            # Add an empty vertical group so the above items don't end up
            # centered vertically:
            VGroup()),
        resizable=True)

    #-- Handler Interface ------------------------------------------------------

    def name_setattr(self, info, object, name, value):
        """ Validate the request to change the named trait on object to the
            specified value.  Vaildation errors raise TraitError.
        """
        self.last_name = value
        if (not self.allow_empty_string) and (value.strip() == ''):
            raise TraitError('Empty string not allowed.')

        return super(MyViewController, self).setattr(info, object, name, value)

    #-- Event handlers ---------------------------------------------------------

    def controller_allow_empty_string_changed(self, info):
        """ 'allow_empty_string' has changed, check the name trait to ensure
            that it is consistent with the current setting.
        """
        if (not self.allow_empty_string) and (self.model.name == ''):
            self.model.name = '?'
        else:
            self.model.name = self.last_name
Пример #20
0
Файл: traits.py Проект: ghorn/Eg
class Model(HasTraits):
	a = Code("print 'hello'")
	b = Button("click me")
 
	traits_view = View(HSplit(
	VGroup(
	Tabbed(
	Item('a'),
	Item('a'),
	Item('a')),
	Item('b')),
	VSplit(
	VGroup('b','b','b'),
	HGroup('a', show_border=True,
	label="traits is great")),
	dock="horizontal"
	),
	resizable=True,
	id="my.test.program.id")
Пример #21
0
class Shape(HasTraits):
    shape_type = Enum("rectangle", "circle")
    editable = Bool
    x, y, w, h, r = [Int] * 5

    view = View(VGroup(
        HGroup(Item("shape_type"), Item("editable")),
        VGroup(Item("x"),
               Item("y"),
               Item("w"),
               Item("h"),
               visible_when="shape_type=='rectangle'",
               enabled_when="editable"),
        VGroup(Item("x"),
               Item("y"),
               Item("r"),
               visible_when="shape_type=='circle'",
               enabled_when="editable"),
    ),
                resizable=True)
class Circle(Shape):
    center = Instance(Point, ())
    r = Int

    view = View(VGroup(
        Item("center", style="custom"),
        Item("r"),
    ))

    @on_trait_change("r")
    def set_info(self):
        self.info = "area:%f" % (pi * self.r**2)
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 MyDemo(HasTraits):
    scene = Instance(SceneModel, ())

    source = Instance(tvtk.ParametricFunctionSource, ())

    func_name = Enum([c.__name__ for c in source_types])

    func = Property(depends_on="func_name")

    traits_view = View(HSplit(
        VGroup(
            Item("func_name", show_label=False),
            Tabbed(
                Item("func",
                     style="custom",
                     editor=InstanceEditor(),
                     show_label=False),
                Item("source", style="custom", show_label=False))),
        Item("scene", style="custom", show_label=False, editor=SceneEditor())),
                       resizable=True,
                       width=700,
                       height=600)

    def __init__(self, *args, **kwds):
        super(MyDemo, self).__init__(*args, **kwds)
        self._make_pipeline()

    def _get_func(self):
        return sources[self.func_name]

    def _make_pipeline(self):
        self.func.on_trait_change(self.on_change, "anytrait")
        src = self.source
        src.on_trait_change(self.on_change, "anytrait")
        src.parametric_function = self.func
        map = tvtk.PolyDataMapper(input_connection=src.output_port)
        act = tvtk.Actor(mapper=map)
        self.scene.add_actor(act)
        self.src = src

    def _func_changed(self, old_func, this_func):
        if old_func is not None:
            old_func.on_trait_change(self.on_change, "anytrait", remove=True)
        this_func.on_trait_change(self.on_change, "anytrait")
        self.src.parametric_function = this_func
        self.scene.render()

    def on_change(self):
        self.scene.render()
Пример #25
0
class Factors(HasTraits):

    # The maximum number to include in the table:
    max_n = Range(1, 1000, 20, mode='slider')

    # The list of Factor objects:
    factors = Property(List)

    # The view of the list of Factor objects:
    view = View(VGroup(
        VGroup(Item('max_n'),
               show_labels=False,
               show_border=True,
               label='Maximum Number'),
        VGroup(Item('factors', show_label=False,
                    editor=factors_table_editor), )),
                title='List of numbers and their factors',
                width=0.2,
                height=0.4,
                resizable=True)

    @property_depends_on('max_n')
    def _get_factors(self):
        return [Factor(n=i + 1) for i in xrange(self.max_n)]
Пример #26
0
 def default_traits_view(self):
     view = View(
         VGroup(
             HGroup(
                 Item("current_map", label=u"颜色映射", editor=EnumEditor(name="object.color_maps")),
                 Item("reverse_map", label=u"反转颜色"),
                 Item("position", label=u"位置", style="readonly"),
             ),
             Item("plot", show_label=False, editor=ComponentEditor()),
         ),
         resizable = True,
         width = 550, height = 300,
         title = u"Mandelbrot观察器"
     )
     return view
Пример #27
0
class CSVGrapher(HasTraits):
    """
    主界面包括绘图列表,数据源,文件选择器和添加绘图按钮
    """
    graph_list = List(Instance(Graph)) # 绘图列表
    data_source = Instance(DataSource) # 数据源
    csv_file_name = File(filter=[u"*.csv"]) # 文件选择
    add_graph_button = Button(u"添加绘图") # 添加绘图按钮

    view = View(
        # 整个窗口分为上下两个部分
        VGroup(
            # 上部分横向放置控件,因此用HGroup
            HGroup(
                # 文件选择控件
                Item("csv_file_name", label=u"选择CSV文件", width=400),
                # 添加绘图按钮
                Item("add_graph_button", show_label=False)
            ),
            # 下部分是绘图列表,采用ListEditor编辑器显示
            Item("graph_list", style="custom", show_label=False, 
                 editor=ListEditor(
                     use_notebook=True, # 是用多标签页格式显示
                     deletable=True, # 可以删除标签页
                     dock_style="tab", # 标签dock样式
                     page_name=".name") # 标题页的文本使用Graph对象的name属性
                )
        ),
        resizable = True,
        height = 0.8,
        width = 0.8,
        title = u"CSV数据绘图器"
    )

    def _csv_file_name_changed(self):
        """
        打开新文件时的处理,根据文件创建一个DataSource
        """
        self.data_source = DataSource()
        self.data_source.load_csv(self.csv_file_name)
        del self.graph_list[:]

    def _add_graph_button_changed(self):
        """
        添加绘图按钮的事件处理
        """
        if self.data_source != None:
            self.graph_list.append( Graph(data_source = self.data_source) )
Пример #28
0
 def default_traits_view(self):
     view = View(HGroup(
         VGroup('renormalized',
                Item('data_fig', style='custom', show_label=False),
                'cr_fig', 'corr_fig'),
         Item('usable_data',
              style='custom',
              show_label=False,
              editor=CheckListEditor(values=list(
                  map(str, self.possible_usable_data)),
                                     cols=1)),
     ),
                 height=800,
                 width=800,
                 handler=DLS_DataHandler)
     return view
Пример #29
0
class Doc(HasTraits):
    filename = File
    TDocStd = Instance(TDocStd.TDocStd_Document)
    root_label = Instance(Label)

    traits_view = View(VGroup(Item("filename")),
                       Item("root_label", editor=tree_ed, show_label=False))

    def _TDocStd_changed(self, new_doc):
        root_label = new_doc.Main().Root()
        label = Label(TDF_Label=root_label)
        self.root_label = label
        print "root label entry", label.entry
        h_u = TNaming.Handle_TNaming_UsedShapes()
        gid = h_u.GetObject().getid()
        if root_label.FindAttribute(gid, h_u):
            print "got used shapes"
class Triangle(Shape):
    a = Instance(Point, ())
    b = Instance(Point, ())
    c = Instance(Point, ())

    view = View(
        VGroup(
            Item("a", style="custom"),
            Item("b", style="custom"),
            Item("c", style="custom"),
        ))

    @on_trait_change("a.[x,y],b.[x,y],c.[x,y]")
    def set_info(self):
        a, b, c = self.a, self.b, self.c
        l1 = ((a.x - b.x)**2 + (a.y - b.y)**2)**0.5
        l2 = ((c.x - b.x)**2 + (c.y - b.y)**2)**0.5
        l3 = ((a.x - c.x)**2 + (a.y - c.y)**2)**0.5
        self.info = "edge length: %f, %f, %f" % (l1, l2, l3)