Ejemplo n.º 1
0
class Test(HasTraits):
    # This should be set.
    recorder = Instance(HasTraits)

    # These should be ignored.
    _ignore = Bool(False)
    ignore_ = Bool(False)
Ejemplo n.º 2
0
class LEDDemoHandler(Handler):

    # The UIInfo object associated with the UI:
    info = Instance(UIInfo)

    # Is the demo currently running:
    running = Bool(True)

    # Is the thread still alive?
    alive = Bool(True)

    def init(self, info):
        self.info = info
        Thread(target=self._update_counter).start()

    def closed(self, info, is_ok):
        self.running = False
        while self.alive:
            sleep(.05)

    def _update_counter(self):
        while self.running:
            self.info.object.counter1 += 1
            self.info.object.counter2 += .001
            sleep(.01)
        self.alive = False
Ejemplo n.º 3
0
class BaseDataSource(HasStrictTraits):

    has_data = Bool(False)  # set True when data is loaded

    description = Str
    kind = data_source_kinds
    voxel_sizes = Tuple(Float(1.0), Float(1.0), Float(1.0))
    pixel_sizes = Tuple(Float(1.0), Float(1.0))

    tables = Dict

    is_image_stack = Bool(True)
    is_image_timeseries = Bool(False)
    is_image_stack_timeseries = Bool(False)

    @property
    def data(self):
        return _data[0]

    @data.setter
    def data(self, data):
        _data[0] = data
        self.has_data = data is not None
        if data is None:
            print '%s.data.setter: removing data' % (self.__class__.__name__)
        else:
            print '%s.data.setter: setting data' % (self.__class__.__name__)

    def _kind_changed(self):
        self.is_image_stack = self.kind == 'image_stack'
        self.is_image_timeseries = self.kind == 'image_timeseries'
        self.is_image_stack_timeseries = self.kind == 'image_stack_timeseries'
Ejemplo n.º 4
0
class IView(IWorkbenchPart, IPerspectiveItem):
    """ The interface for workbench views. """

    # Is the view busy? (i.e., should the busy cursor (often an hourglass) be
    # displayed?).
    busy = Bool(False)

    # The category that the view belongs to (this can used to group views when
    # they are displayed to the user).
    category = Str('General')

    # An image used to represent the view to the user (shown in the view tab
    # and in the view chooser etc).
    image = Instance(ImageResource)

    # Whether the view is visible or not.
    visible = Bool(False)

    ###########################################################################
    # 'IView' interface.
    ###########################################################################

    def activate(self):
        """ Activate the view.

        """

    def hide(self):
        """ Hide the view.

        """

    def show(self):
        """ Show the view.
Ejemplo n.º 5
0
class RootPreferencesHelper(PreferencesHelper):

    # The preferences path for which we use.
    preferences_path = 'enthought.mayavi'

    ######################################################################
    # Our preferences.

    # Specifies if the nodes on the tree may be deleted without a
    # confirmation or not.  If True the user will be prompted before
    # the object is deleted.  If it is False then the user will not be
    # prompted.
    confirm_delete = Bool(desc='if the user is prompted before'
                          ' a node on the MayaVi tree is deleted')

    # Specifies if the splash screen is shown when mayavi starts.
    show_splash_screen = Bool(desc='if the splash screen is shown at'
                              ' startup')

    # Specifies if the adder nodes are shown on the mayavi tree view.
    show_helper_nodes = Bool(desc='if the helper (adder) nodes are shown'
                             ' on the tree view')

    # Specifies if the adder nodes are shown on the mayavi tree view.
    open_help_in_light_browser = Bool(
        desc='if the help pages are opened in a chromeless'
        ' browser window (only works with Firefox)')

    # Contrib directories to load on startup.
    contrib_packages = List(Str, desc='contrib packages to load on startup')

    # Whether or not to use IPython for the Shell.
    use_ipython = Bool(desc='use IPython for the embedded shell '
                       '(if available)')

    ########################################
    # Private traits.
    _contrib_finder = Instance(HasTraits)

    ######################################################################
    # Traits UI view.

    traits_view = View(Group(
        Item(name='confirm_delete'), Item(name='show_splash_screen'),
        Item(name='show_helper_nodes'),
        Item(name='open_help_in_light_browser'),
        Item(
            '_contrib_finder',
            show_label=False,
            editor=InstanceEditor(label='Find contributions'),
        )),
                       resizable=True)

    ######################################################################
    # Non-public interface.
    ######################################################################
    def __contrib_finder_default(self):
        from contrib_finder import ContribFinder
        return ContribFinder()
Ejemplo n.º 6
0
class Permission(HasTraits):
    """A permission is the link between an application action and the current
    user - if the user has a permission attached to the action then the user is
    allowed to perform that action."""

    #### 'Permission' interface ###############################################

    # The id of the permission.  By convention a dotted format is used for the
    # id with the id of the application being the first part.
    id = Str

    # A user friendly description of the permission.
    description = Unicode

    # Set if the current user has this permission.  This is typically used with
    # the enabled_when and visible_when traits of a TraitsUI Item object when
    # the permission instance has been placed in the TraitsUI context.
    granted = Property

    # Set if the permission should be granted automatically when bootstrapping.
    # This is normally only ever set for permissions related to user management
    # and permissions.  The user manager determines exactly what is meant by
    # "bootstrapping" but it is usually when it determines that no user or
    # permissions information has been defined.
    bootstrap = Bool(False)

    # Set if the permission has been defined by application code rather than as
    # a result of loading the policy database.
    application_defined = Bool(True)

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __init__(self, **traits):
        """Initialise the object."""

        super(Permission, self).__init__(**traits)

        # Register the permission.
        get_permissions_manager().policy_manager.register_permission(self)

    def __str__(self):
        """Return a user friendly representation."""

        s = self.description
        if not s:
            s = self.id

        return s

    ###########################################################################
    # Trait handlers.
    ###########################################################################

    def _get_granted(self):
        """Check the user has this permission."""

        return get_permissions_manager().check_permissions(self)
Ejemplo n.º 7
0
class Bool(Variable):
    """A variable wrapper for a boolean variable.
       """
    
    def __init__(self, default_value=False, iotype=None, desc=None, 
                 **metadata):

        # Put iotype in the metadata dictionary
        if iotype is not None:
            metadata['iotype'] = iotype
            
        # Put desc in the metadata dictionary
        if desc is not None:
            metadata['desc'] = desc

        self._validator = Enthought_Bool(value=default_value, **metadata)
            
        super(Bool, self).__init__(default_value=default_value, **metadata)

    def validate(self, obj, name, value):
        """ Use the Enthought trait's validate.
        """
        return self._validator.validate(obj, name, value)

    def create_editor(self):
        """ User the one in the Enthought trait.
        """
        return self._validator.create_editor()

    def get_attribute(self, name, value, trait, meta):
        """Return the attribute dictionary for this variable. This dict is
        used by the GUI to populate the edit UI. Bools need to turn
        their value into a string for compatibility.
        
        name: str
          Name of variable
          
        value: object
          The value of the variable
          
        trait: CTrait
          The variable's trait
          
        meta: dict
          Dictionary of metadata for this variable
        """
        
        attr = {}
        
        attr['name'] = name
        attr['type'] = type(value).__name__
        attr['value'] = str(value)
        
        for field in meta:
            if field not in gui_excludes:
                attr[field] = meta[field]
        
        return attr, None
Ejemplo n.º 8
0
class DerivedFoo(BaseFoo):
    """ A derived class that puts additional content in the 'foo' dynamic view.
        Note that the additional content could also have been added via a traits 
        category contribution, or even dynamic manipulation of metadata on a UI
        subelement.  The key is what the metadata represents when the view is
        *created*
    """

    knows_mother = Bool(False)
    mother_first_name = Str("My mother's first name")
    mother_last_name = Str("My mother's last name")

    knows_father = Bool(True)
    father_first_name = Str("My father's first name")
    father_last_name = Str("My father's last name")
    father_derived = Str

    ui_parents = Group(
        'knows_mother',
        'knows_father',
        label='Parents?',
        _foo_order=7,
        _foo_priority=1,
    )

    ui_mother = Group(
        'mother_first_name',
        'mother_last_name',
        label="Mother's Info",
        _foo_priority=1,
    )

    ui_father = Group(
        'father_first_name',
        'father_last_name',
        spring,
        'father_derived',
        label="Father's Info",
        _foo_order=15,
        _foo_priority=1,
        _foo_handler=FatherInfoHandler(),
    )

    def _knows_mother_changed(self, old, new):
        ui_mother = self.trait_view('ui_mother')
        if new:
            ui_mother._foo_order = 10
        elif hasattr(ui_mother, '_foo_order'):
            del ui_mother._foo_order

    def _knows_father_changed(self, old, new):
        ui_father = self.trait_view('ui_father')
        if new:
            ui_father._foo_order = 15
        elif hasattr(ui_father, '_foo_order'):
            del ui_father._foo_order
Ejemplo n.º 9
0
class _Tool(HasTraits):
    """ A tool bar tool representation of an action item. """

    #### '_Tool' interface ####################################################

    # Is the item checked?
    checked = Bool(False)

    # A controller object we delegate taking actions through (if any).
    controller = Any

    # Is the item enabled?
    enabled = Bool(True)

    # Is the item visible?
    visible = Bool(True)

    # The radio group we are part of (None if the tool is not part of such a
    # group).
    group = Any

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __init__(self, parent, tool_bar, image_cache, item, controller,
                 show_labels):
        """ Creates a new tool bar tool for an action item. """

        self.item = item
        self.tool_bar = tool_bar

        # Create an appropriate tool depending on the style of the action.
        action = self.item.action

        # If the action has an image then convert it to a bitmap (as required
        # by the toolbar).
        if action.image is not None:
            image = action.image.create_image()
            path = action.image.absolute_path
            bmp = image_cache.get_bitmap(path)

        else:
            from enthought.pyface.api import ImageResource
            image = ImageResource('foo')
            bmp = image.create_bitmap()

        self.control_id = 1
        self.control = None
        if controller is not None:
            self.controller = controller
            controller.add_to_toolbar(self)

        return
Ejemplo n.º 10
0
class tcProcess(tcGeneric):
    name = Property(String)  # overide TimeChart
    # start_ts=CArray # inherited from TimeChart
    # end_ts=CArray # inherited from TimeChart
    # values = CArray   # inherited from TimeChart
    pid = Long
    ppid = Long
    selection_time = Long(0)
    selection_pc = Float(0)
    comm = String
    cpus = CArray
    comments = []
    has_comments = Bool(True)
    show = Bool(True)
    process_type = String
    project = None

    @cached_property
    def _get_name(self):
        return "%s:%d (%s)" % (self.comm, self.pid,
                               _pretty_time(self.total_time))

    def get_comment(self, i):
        if len(self.comments) > i:
            return "%s" % (self.comments[int(i)])
        elif len(self.cpus) > i:
            return "%d" % (self.cpus[i])
        else:
            return ""

    @cached_property
    def _get_max_latency(self):
        if self.pid == 0 and self.comm.startswith("irq"):
            return 1000

    @cached_property
    def _get_max_latency_ts(self):
        if self.max_latency > 0:
            indices = np.nonzero(
                (self.end_ts - self.start_ts) > self.max_latency)[0]
            return np.array(sorted(map(lambda i: self.start_ts[i], indices)))
        return []

    @cached_property
    def _get_default_bg_color(self):
        if self.max_latency > 0 and max(self.end_ts -
                                        self.start_ts) > self.max_latency:
            return (1, .1, .1, 1)
        return colors.get_traits_color_by_name(self.process_type + "_bg")

    def _get_bg_color(self):
        if self.project != None and self in self.project.selected:
            return colors.get_traits_color_by_name("selected_bg")
        return self.default_bg_color
Ejemplo n.º 11
0
class ToolBarManager(ActionManager):
    """ A tool bar manager realizes itself in errr, a tool bar control. """

    #### 'ToolBarManager' interface ###########################################

    # The size of tool images (width, height).
    image_size = Tuple((16, 16))

    # The orientation of the toolbar.
    orientation = Enum('horizontal', 'vertical')

    # Should we display the name of each tool bar tool under its image?
    show_tool_names = Bool(True)

    # Should we display the horizontal divider?
    show_divider = Bool(True)

    #### Private interface ####################################################

    # Cache of tool images (scaled to the appropriate size).
    _image_cache = Instance(ImageCache)

    ###########################################################################
    # 'object' interface.
    ###########################################################################

    def __init__(self, *args, **traits):
        """ Creates a new tool bar manager. """

        # Base class contructor.
        super(ToolBarManager, self).__init__(*args, **traits)

        # An image cache to make sure that we only load each image used in the
        # tool bar exactly once.
        self._image_cache = ImageCache(self.image_size[0], self.image_size[1])

        return

    ###########################################################################
    # 'ToolBarManager' interface.
    ###########################################################################

    def create_tool_bar(self, parent, controller=None):
        """ Creates a tool bar. """

        # If a controller is required it can either be set as a trait on the
        # tool bar manager (the trait is part of the 'ActionManager' API), or
        # passed in here (if one is passed in here it takes precedence over the
        # trait).
        if controller is None:
            controller = self.controller

        return None
Ejemplo n.º 12
0
class IConfirmationDialog(IDialog):
    """ The interface for a dialog that prompts the user for confirmation. """

    #### 'IConfirmationDialog' interface ######################################

    # Should the cancel button be displayed?
    cancel = Bool(False)

    # The default button.
    default = Enum(NO, YES, CANCEL)

    # The image displayed with the message.  The default is toolkit specific.
    image = Instance(ImageResource)

    # The message displayed in the body of the dialog (use the inherited
    # 'title' trait to set the title of the dialog itself).
    message = Unicode

    # Some informative text to display below the main message
    informative = Unicode

    # Some additional details that can be exposed by the user
    detail = Unicode

    # The label for the 'no' button.  The default is toolkit specific.
    no_label = Unicode

    # The label for the 'yes' button.  The default is toolkit specific.
    yes_label = Unicode
Ejemplo n.º 13
0
class SetStep(HasTraits):

    _viewer = Instance(Viewer)
    _source = Instance(FileSource)
    _step_editor = RangeEditor(low_name='step_low',
                               high_name='step_high',
                               label_width=28,
                               auto_set=True,
                               mode='slider')
    step = None
    step_low = Int
    step_high = Int
    file_changed = Bool(False)

    traits_view = View(
        Item('step', defined_when='step is not None', editor=_step_editor), )

    def __source_changed(self, old, new):
        rng = self._source.get_step_range()
        self.add_trait('step', Int(0))
        self.step_low, self.step_high = [int(ii) for ii in rng]

    def _step_changed(self, old, new):
        self._source.set_step(self.step)
        self._viewer.set_source_filename(self._source.filename)

    def _file_changed_changed(self, old, new):
        if new == True:
            rng = self._source.get_step_range()
            self.step_low, self.step_high = [int(ii) for ii in rng]

        self.file_changed = False
Ejemplo n.º 14
0
class IEditor(IWorkbenchPart):
    """ The interface of a workbench editor. """

    # The optional command stack.
    command_stack = Instance('enthought.undo.api.ICommandStack')

    # Is the object that the editor is editing 'dirty' i.e., has it been
    # modified but not saved?
    dirty = Bool(False)

    # The object that the editor is editing.
    #
    # The framework sets this when the editor is created.
    obj = Any

    #### Editor Lifecycle Events ##############################################
    
    # Fired when the editor is closing.
    closing = VetoableEvent
    
    # Fired when the editor is closed.
    closed = Event

    #### Methods ##############################################################
    
    def close(self):
        """ Close the editor.
Ejemplo n.º 15
0
class IHelpDoc(Interface):
    """ The interface for help docs.
    
    A help doc is defined by a UI label, a filename, and a viewer program.
    """
    
    # The UI label for the help doc, which appears in menus or dialogs.
    label = Str
    
    # The path to the document, which can be full, or relative to the Python 
    # installation directory (sys.prefix).
    filename = File
    
    # Is this a url?
    url = Bool(False)
    
    # The program to use to view the document. 'browser' means the platform 
    # default web browser. Otherwise, it is a command to run, which may be
    # in the program search path of the current environment, or an absolute
    # path to a program.
    viewer = Either('browser', Str)
    
    # The unique ID of the preferences node that contains the other values for
    # this object
    preferences_path = Str
    
Ejemplo n.º 16
0
class HelpDoc(PreferencesHelper):
    """ The implementation for help docs.
    
    A help doc is defined by a UI label, a filename, and a viewer program.
    """
    implements(IHelpDoc)

    #### IHelpDoc interface / Preferences ######################################

    # NOTE: This class inherits preferences_path from PreferencesHelper.

    # The UI label for the help doc, which appears in menus or dialogs.
    label = Str

    # The path to the document, which can be full, or relative to the Python
    # installation directory (sys.prefix).
    filename = File

    # Is this a url?
    url = Bool(False)

    # The program to use to view the document. 'browser' means the platform
    # default web browser. Otherwise, it is a command to run, which may be
    # in the program search path of the current environment, or an absolute
    # path to a program.
    viewer = Either('browser', Str)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
class IWizardController(Interface):
    """ The interface for all pyface wizard controllers. """

    #### 'IWizardController' interface ########################################

    # The pages under the control of this controller.
    pages = List(IWizardPage)

    # The current page.
    current_page = Instance(IWizardPage)

    # Set if the wizard complete.
    complete = Bool(False)

    ###########################################################################
    # 'IWizardController' interface.
    ###########################################################################

    def get_first_page(self):
        """ Returns the first page in the model. """

    def get_next_page(self, page):
        """ Returns the next page. """

    def get_previous_page(self, page):
        """ Returns the previous page. """

    def is_first_page(self, page):
        """ Is the page the first page? """

    def is_last_page(self, page):
        """ Is the page the last page? """

    def dispose_pages(self):
        """ Dispose all the pages. """
Ejemplo n.º 19
0
class IUser(Interface):
    """The interface implemented by a user (or principal)."""

    # The user's name, ie. how they identified themselves to the permissions
    # policy.  It is only valid if the authenticated trait is True.
    name = Unicode

    # This is set if the user has been authenticated, ie. the name trait is
    # valid.
    authenticated = Bool(False)

    # An optional description of the user (eg. their full name).  The exact
    # meaning is defined by the user manager.
    description = Unicode

    # This allows application defined, user specific data to be persisted in
    # the user database.  An application (or plugin) should save the data as a
    # single value in the dictionary keyed on the application's (or plugin's)
    # unique id.  The data will be saved in the user database whenever it is
    # changed, and will be read from the user database whenever the user is
    # authenticated.
    blob = Dict

    def __str__(self):
        """Return a user friendly representation of the user."""
Ejemplo n.º 20
0
class LoggerPreferences(PreferencesHelper):
    """ The persistent service exposing the Logger plugin's API.
    """

    #### Preferences ###########################################################

    # The log levels
    level = Trait(
        'Info',
        {
            'Debug': logging.DEBUG,
            'Info': logging.INFO,
            'Warning': logging.WARNING,
            'Error': logging.ERROR,
            'Critical': logging.CRITICAL,
        },
        is_str=True,
    )

    enable_agent = Bool(False)
    smtp_server = Str()
    to_address = Str()
    from_address = Str()

    # The path to the preferences node that contains the preferences.
    preferences_path = Str('enthought.logger')
Ejemplo n.º 21
0
    def render_fields(self):
        #construct traits for each parameter and place in the class dictionary
        params = self.model.get_params()
        class_dict = {}
        #construct default view
        elements = []
        elements.extend([Label("Parameter"), Label("Error"), Label("Fixed?")])
        for param in params:
            pname = param.name
            class_dict["entry_" + pname] = Float(
                param.value)  #get the initial value
            class_dict["err_" + pname] = Float(
                param.error)  #get the initial value
            class_dict["fixed_" + pname] = Bool(
                param.fixed)  #determine if fixed or not
            elements.append(
                Item("entry_" + pname,
                     format_str="%0.4g",
                     show_label=True,
                     label=pname))
            elements.append(
                Item("err_" + pname,
                     format_str="+/- %0.2g",
                     show_label=False,
                     style='readonly'))
            elements.append(Item("fixed_" + pname, show_label=False))

        kwargs = {'columns': 3}
        class_dict['traits_view'] = View(VGrid(*elements, **kwargs))
        self.fields_class = new.classobj('Fields', (HasTraits, ), class_dict)
        self.fields = self.fields_class()
Ejemplo n.º 22
0
class IWizard(IDialog):
    """ The interface for all pyface wizards. """

    #### 'IWizard' interface ##################################################

    # The pages in the wizard.
    pages = List(IWizardPage)

    # The wizard controller provides the pages displayed in the wizard, and
    # determines when the wizard is complete etc.
    controller = Instance(IWizardController)

    # Should the 'Cancel' button be displayed?
    show_cancel = Bool(True)

    #### 'IWindow' interface ##################################################

    # The dialog title.
    title = Unicode('Wizard')

    ###########################################################################
    # 'IWizard' interface.
    ###########################################################################

    def next(self):
        """ Advance to the next page in the wizard. """

    def previous(self):
        """ Return to the previous page in the wizard. """
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
class Parameter(HasTraits):
    """Defines parameter for FitFunction

    >>> p = Parameter(name = 'a', value = 10.)
    >>> p.name
    'a'
    >>> p.value
    10.0
    """
    #: parameter name
    name = Str()
    #: actual value
    value = Float(1.)
    #: a string representation of value
    value_str = Property(depends_on='value')
    #: sigma of fitted parameter
    sigma = Float(0.)
    #: a string representation of sigma
    sigma_str = Property(depends_on='sigma')
    #: whether it is treated as a constant
    is_constant = Bool(False)

    def _is_constant_changed(self, value):
        if value == True:
            self.sigma = 0.

    def _get_sigma_str(self):
        return ' +/- %f ' % self.sigma

    def _get_value_str(self):
        return ' %f ' % self.value
Ejemplo n.º 25
0
class CViewerUIPreferencesPage(PreferencesPage):
    """ The preferences page for the Connectome Viewer UI Plugin. """

    #### 'PreferencesPage' interface ##########################################

    # The page's category (e.g. 'General/Appearance'). The empty string means
    # that this is a top-level page.
    category = ''

    # The page name (this is what is shown in the preferences dialog.
    name = 'Connectome Viewer'

    # The path to the preference node that contains the preferences.
    preferences_path = 'cviewer.plugins.ui'

    #### Preferences ##########################################################

    # Load labels automatically
    labelload = Bool(desc='if to load and show all node labels in the 3D View')

    # Use IPython in Shell
    useipython = Bool(desc='if to use IPython as default Shell')

    # Default path to load cff files
    cffpath = Directory(desc='the default path to open Connectome files from')

    # default path for scripts
    scriptpath = Directory(
        desc='the default path to find executable Python scripts')

    # Path to Trackvis
    trackvispath = Directory(
        desc='the path where the TrackVis executables reside')

    # show the ConnectomeViewer splash screen
    show_splash_screen = Bool(
        desc='if the Connectome Viewer splashscreen is shown on startup')

    #### Traits UI views ######################################################
    trait_view = View(Group(
        Item('show_splash_screen', label='Show Splash Screen:'),
        Item('labelload', label='Load All Node Labels:'),
        Item('useipython', label='Use IPython:'),
        Item('cffpath', label='Connectome File Path:'),
        Item('scriptpath', label='Python Script Path:'),
        Item('trackvispath', label='TrackVis Executable Path:')),
                      resizable=True)
Ejemplo n.º 26
0
class IWizardPage(Interface):
    """ The interface for a page in a wizard. """

    #### 'IWizardPage' interface ##############################################

    # The unique Id of the page within the wizard.
    id = Str
    
    # The Id of the next page.
    next_id = Str

    # Set if this is the last page of the wizard.  It can be ignored for
    # simple linear wizards.
    last_page = Bool(False)
    
    # Is the page complete (i.e. should the 'Next' button be enabled)?
    complete = Bool(False)

    # The page heading.
    heading = Unicode
    
    # The page sub-heading.
    subheading = Unicode

    # The size of the page.
    size = Tuple
    
    ###########################################################################
    # 'IWizardPage' interface.
    ###########################################################################

    def create_page(self, parent):
        """ Creates the wizard page. """

    def dispose_page(self):
        """ Disposes the wizard page.

        Subclasses are expected to override this method if they need to
        dispose of the contents of a page.
        """

    ###########################################################################
    # Protected 'IWizardPage' interface.
    ###########################################################################

    def _create_page_content(self, parent):
        """ Creates the actual page content. """
Ejemplo n.º 27
0
        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)
Ejemplo n.º 28
0
        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)
Ejemplo n.º 29
0
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'])
Ejemplo n.º 30
0
class Surf(LUTBase):
    # Disables/enables scalar visibility.
    scalar_visibility = Bool(True, desc='show scalar visibility')

    # Color of the mesh.
    color = vtk_color_trait((0.5, 1.0, 0.5))

    def __init__(self, x, y, z, scalars=None, **traits):
        """
        Parameters
        ----------

        - x : array
          A list of x coordinate values formed using numpy.mgrid.
        - y : array
          A list of y coordinate values formed using numpy.mgrid.
        - z : array
          A list of z coordinate values formed using numpy.mgrid.
        - scalars : array (optional)
          Scalars to associate with the points.          
        """
        super(Surf, self).__init__(**traits)
        triangles, points = make_triangles_points(x, y, z, scalars)
        self.pd = make_triangle_polydata(triangles, points, scalars)

        mapper = tvtk.PolyDataMapper(input=self.pd,
                                     lookup_table=self.lut,
                                     scalar_visibility=self.scalar_visibility)
        if scalars is not None:
            rs = numpy.ravel(scalars)
            dr = min(rs), max(rs)
            mapper.scalar_range = dr
            self.lut.table_range = dr

        actor = _make_actor(mapper=mapper)
        actor.property.set(color=self.color)
        self.actors.append(actor)

    def _scalar_visibility_changed(self, val):
        if self.actors:
            mapper = self.actors[0].mapper
            mapper.scalar_visibility = val
        self.render()

    def _surface_changed(self, val):
        if self.actors:
            representation = 'w'
            if val:
                representation = 's'
            self.actors[0].property.representation = representation
        self.render()

    def _color_changed(self, val):
        if self.actors:
            self.actors[0].property.color = val
        self.render()
Ejemplo n.º 31
0
    def __init__(self, default_value=False, iotype=None, desc=None, 
                 **metadata):

        # Put iotype in the metadata dictionary
        if iotype is not None:
            metadata['iotype'] = iotype
            
        # Put desc in the metadata dictionary
        if desc is not None:
            metadata['desc'] = desc

        self._validator = Enthought_Bool(value=default_value, **metadata)
            
        super(Bool, self).__init__(default_value=default_value, **metadata)