Exemple #1
0
class Person(HasTraits):
    implements(IName)

    first_name = Str( 'John' )
    last_name  = Str( 'Doe' )

    # Implementation of the 'IName' interface:
    def get_name ( self ):
        """ Returns the name of an object. """
        return ('%s %s' % ( self.first_name, self.last_name ))
Exemple #2
0
class CVolumeTreeNode(TreeNode):

    # The object that contains the container ;^)
    parent = Any

    # the network associated with this node
    node_for = [CVolume]

    # a default icons
    # Name of group item icon
    icon_group = Str('volume.png')
    # Name of leaf item icon
    icon_item = Str('volume.png')
    # Name of opened group item icon
    icon_open = Str('volume.png')

    # labels
    label = 'dname'

    ###
    # Private Traits

    # activate / deactivate logic
    # if the node is activated, this means that there exists a
    # corresponding RenderManager instance

    _VolumeVisualizer = Instance(
        Action,
        kw={
            'name': 'Volume Slicer',
            'action': 'object.vol_vis',
            'tooltip': 'Invokes a simple Volume Slicer by Gael Varoquaux.',
            'enabled_when': 'object.loaded == True'
        },
    )

    # the menu shown after right-click
    menu = Instance(Menu, transient=True)

    def get_children(self, object):
        """ Get the object's children. """
        pass

    ######################################################################
    # Non-public interface
    ######################################################################

    def _menu_default(self):
        """ Standard menus for network nodes """

        menu_actions = [
            Separator(),
        ]

        return Menu(*menu_actions)
class CSurfaceTreeNode(TreeNode):

    # The object that contains the container ;^)
    parent = Any

    # the network associated with this node
    node_for = [CSurface]

    # a default icons
    # Name of group item icon
    icon_group = Str('surface.png')
    # Name of leaf item icon
    icon_item = Str('surface.png')
    # Name of opened group item icon
    icon_open = Str('surface.png')

    # labels
    label = 'dname'

    ###
    # Private Traits

    # activate / deactivate logic
    # if the node is activated, this means that there exists a
    # corresponding RenderManager instance

    _ShowName = Instance(
        Action,
        kw={
            'name': 'Show name',
            'action': 'object.show_name',
            'tooltip': 'Shows the network name'
        },
    )

    # the menu shown after right-click
    menu = Instance(Menu, transient=True)

    def get_children(self, object):
        # this works!
        return object.children

    ######################################################################
    # Non-public interface
    ######################################################################

    def _menu_default(self):
        """ Standard menus for network nodes """

        menu_actions = [Separator()]

        return Menu(*menu_actions)

    def __init__(self, **traits):
        super(CSurfaceTreeNode, self).__init__(**traits)
Exemple #4
0
class FilterAdderNode(ListAdderNode):
    """ Tree node that presents a view to the user to add filters.
    """
    # String to be shown in the TreeEditor.
    label = Str('Add a processing filter')

    # The icon of the displayed objects
    icon_name = Str('filter.ico')

    # A reference to the registry, to generate this list.
    items_list_source = registry.filters
class CScriptTreeNode(TreeNode):

    # The object that contains the container ;^)
    parent = Any

    # the network associated with this node
    node_for = [CScript]

    # a default icons
    # Name of group item icon
    icon_group = Str('script.png')
    # Name of leaf item icon
    icon_item = Str('script.png')
    # Name of opened group item icon
    icon_open = Str('script.png')

    # labels
    label = 'dname'

    ###
    # Private Traits

    # activate / deactivate logic
    # if the node is activated, this means that there exists a
    # corresponding RenderManager instance

    _OpenFile = Instance(
        Action,
        kw={
            'name': 'Open File in Editor',
            'action': 'object.open_file',
            'tooltip': 'Open the file in editor'
        },
    )

    # the menu shown after right-click
    menu = Instance(Menu, transient=True)

    def get_children(self, object):
        """ Get the object's children. """
        pass

    ######################################################################
    # Non-public interface
    ######################################################################

    def _menu_default(self):
        """ Standard menus for network nodes """

        menu_actions = [Separator(), \
                        self._OpenFile]

        return Menu(*menu_actions)
Exemple #6
0
class aboutBox(HasTraits):
    program = Str("pytimechart: linux traces exploration and visualization")
    author = Str("Pierre Tardy <*****@*****.**>")
    version = Str(__version__)
    doc = Button(__doc__)
    traits_view = View(Item("program", show_label=False, style="readonly"),
                       Item("author", style="readonly"),
                       Item("version", style="readonly"),
                       Item("doc"),
                       width=500,
                       title="about")

    def _doc_changed(self, ign):
        browse_doc()
Exemple #7
0
class ExDesignSpec(HasTraits):
    ''' Specification of the experiment design.

    Defines the parameters varied in the experiment design.
    The parameters can be read from the file included in the design.
    '''

    factors = []
    data_converters = {0: fcomma2fdot,
                       1: fcomma2fdot}

    design_file = Str('exdesign_num.csv')
    data_dir = Str('data')
    data_file_name = " '%s %dnm %d.TRA' % (self.embedding, self.torque, self.rep_number ) "
Exemple #8
0
class SubgraphTreeNode(BaseGraphTreeNode):
    """ Defines a tree node for Subgraph.
    """

    # Name to use for a new instance.
    name = Str( "Subgraph" )

    # List of object classes and/or interfaces that the node applies to.
    node_for = [ Subgraph ]

    # Name of group item icon.
    icon_group = Str( "subgraph" )

    # Name of opened group item icon.
    icon_open = Str( "subgraph" )
Exemple #9
0
class ClusterTreeNode(BaseGraphTreeNode):
    """ Defines a tree node for Cluster.
    """

    # Name to use for a new instance.
    name = Str( "Cluster" )

    # List of object classes and/or interfaces that the node applies to.
    node_for = [ Cluster ]

    # Name of group item icon.
    icon_group = Str( "cluster" )

    # Name of opened group item icon.
    icon_open = Str( "cluster" )
class Foo(HasTraits):
    s = Str('foo')
    t = Str('foo.t')

    def _s_changed(self, name, old, new):
        print 'Foo._s_changed( %s, %s, %s, %s)' % (self, name, old, new)
        global foo_s_handler_self
        foo_s_handler_self = self
        return

    def _t_changed(self, name, old, new):
        print 'Foo._t_changed( %s, %s, %s, %s)' % (self, name, old, new)
        global foo_t_handler_self
        foo_t_handler_self = self
        return
Exemple #11
0
class Demo(HasName):
    x = Int
    y = Int
    z = Int(monitor=1)  # 有元数据属性monitor的Int
    inner = Instance(Inner)
    alist = List(Int)
    test1 = Str()
    test2 = Str()

    def _inner_default(self):
        return Inner(name="inner1")

    @on_trait_change("x,y,inner.[x,y],test+,+monitor,alist[]")
    def event(self, obj, name, old, new):
        print((obj, name, old, new))
Exemple #12
0
class ProjPlotSpec(VMPlotSpec):
    weight_field = Str("None")
    none_field_list = Property(depends_on='field_list')

    @cached_property
    def _get_none_field_list(self):
        return ["None"] + self.field_list
Exemple #13
0
class DisplayShape(HasTraits):
    """
    A display-able shape. This class wraps AIS.AIS_Shape.
    
    Instances of this class are the root shape objects in the model
    and are the things we actually visualise.
    
    We could add visualisation traits to this object
    """
    name = Str("an AIS shape")
    input = Input

    _input = List

    ais_shape = Instance(AIS.AIS_Shape)

    render = Event

    def _input_changed(self, name, vold, vnew):
        if vold is not None:
            vold.on_trait_change(self.on_modified, "modified", remove=True)
        vnew.on_trait_change(self.on_modified, "modified")
        self._input = [vnew]

    def on_modified(self, vnew):
        if vnew is True:
            shape = self.input.shape
            self.ais_shape.Set(shape)
            self.render = True

    def _ais_shape_default(self):
        return AIS.AIS_Shape(self.input.shape)
class Employee(HasTraits):
    name = Str('<unknown>')
    title = Str
    phone = Regex(regex=r'\d\d\d-\d\d\d\d')

    def default_title(self):
        self.title = 'Senior Engineer'
Exemple #15
0
class MetadataTest(HasTraits):
    i = Int(99, myinfo="test my info")
    s = Str("test", label=u"字符串")
    # NumPy的数组
    a = Array
    # 元素为Int的列表
    list = List(Int)
Exemple #16
0
class ModuleAdderNode(ListAdderNode):
    """ Tree node that presents a view to the user to add modules.
    """
    # String to be shown in the TreeEditor.
    label = Str('Add a visualization module')

    # The icon of the displayed objects
    icon_name = Str('module.ico')

    # A reference to the registry, to generate this list.
    items_list_source = registry.modules

    def _object_changed(self, value):
        if value is not None:
            value.menu_helper._build_filter_actions()
        ListAdderNode._object_changed(self, value)
Exemple #17
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.
Exemple #18
0
class Frame(HasTraits):
    parent = This
    T = Instance(Expression)
    name = Str("")
    variables = DelegatesTo('parent')

    traits_view = View(Item(name='name'),
                       Item(name='parent',
                            label='Base',
                            editor=InstanceEditor(label="Frame")),
                       Item(name='T', label='Matrix4x4', style='custom'),
                       title='Frame properties')

    def evalT(self):
        if self.T.get_curr_value() != None and self.parent.evalT() != None:
            return self.parent.evalT() * self.T.get_curr_value()
        else:
            return None

    def __init__(self, parent, T, name=""):
        self.name = name
        self.parent = parent
        if isinstance(T, Expression):
            self.T = T
        else:
            self.T = self.variables.new_expression(T)
Exemple #19
0
class LabelMapping(HasTraits):

    label_trait = Str("name")

    diagram_label = Instance(HasTraits)

    node_mapping = Instance(HasTraits)
Exemple #20
0
class NewModelSelector(HasTraits):
    modelnames = List
    selectedname = Str('No Model')
    modelargnum = Int(2)
    selectedmodelclass = Property
    isvarargmodel = Property(depends_on='modelnames')

    traits_view = View(Item('selectedname',label='Model Name:',editor=EnumEditor(name='modelnames')),
                       Item('modelargnum',label='Extra Parameters:',enabled_when='isvarargmodel'),
                       buttons=['OK','Cancel'])

    def __init__(self,include_models=None,exclude_models=None,**traits):
        super(NewModelSelector,self).__init__(**traits)

        self.modelnames = list_models(include_models,exclude_models,FunctionModel1D)
        self.modelnames.insert(0,'No Model')
        self.modelnames.sort()

    def _get_selectedmodelclass(self):
        n = self.selectedname
        if n == 'No Model':
            return None
        else:
            return get_model_class(n)

    def _get_isvarargmodel(self):
        cls = self.selectedmodelclass

        if cls is None:
            return False
        else:
            return cls.isVarnumModel()
class JobySimDecoder(DataDecoder):
  """
      Decodes lines of text formatted using a simple format.
  """
  name = Str('JobySim Decoder')
  
  view = View(
    title='JobySim decoder'
  )
  
  _sub_re = re.compile('\W+')
  _names = List()

  def decode(self, data):
    """
        Decodes input from the Joby Simulator.
    """
    if data[0] == '#':
      # list of names
      self._names = [self._sub_re.sub('_', name) for name in data[1:].split('!')]
      print "JobySimDecoder got names:", self._names
      return None

    vals = map(eval, data.split('!'))
    d = dict(zip(self._names, vals))
    return d
Exemple #22
0
class TVTKClass(TreeNodeObject):
    children = List()
    name = Str("node")
    doc = Code   
    Classes = {}
    
    def __init__(self, **traits):
        super(TVTKClass, self).__init__(**traits)
        TVTKClass.Classes[self.name] = self
    
    def _get_children(self):
        try:
            subclass_names = SubClasses[self.name]["subclass"]
            subclass_names.sort()
            return [TVTKClass(name=t) for t in subclass_names]
        except:
            return []
    
    def _name_changed(self):
        #self.doc = get_tvtk_class_doc(getattr(tvtk, self.name))
        self.doc = SubClasses[self.name]["doc"]
        self.children = self._get_children()
        
    def tno_get_children(self, node):
        return self.children
class LcmDecoder(DataDecoder):
    """
      Decodes lines of text formatted using a simple format.
  """
    name = Str('LCM Decoder')

    view = View(title='LCM Decoder')

    _sub_re = re.compile('\W+')
    _names = List()

    def decode(self, data):
        """
        Decodes input from LCM messages.
    """
        #    if data[0] == '#':
        #      # list of names
        #      self._names = [self._sub_re.sub('_', name) for name in data[1:].split('!')]
        #      print "JobySimDecoder got names:", self._names
        #      return None
        #
        #    vals = map(eval, data.split('!'))
        #    d = dict(zip(self._names, vals))
        #    return d

        #    print data
        return data
Exemple #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
Exemple #25
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
Exemple #26
0
class WebPage ( HasTraits ):

    # The URL to display:
    url = Str( 'http://code.enthought.com' )
    
    # The page title:
    title = Str
    
    # The page status:
    status = Str
    
    # The browser navigation buttons:
    back    = Button( '<--' )
    forward = Button( '-->' )
    home    = Button( 'Home' )
    stop    = Button( 'Stop' )
    refresh = Button( 'Refresh' )
    search  = Button( 'Search' )

    # The view to display:
    view = View(
        HGroup( 'back', 'forward', 'home', 'stop', 'refresh', 'search', '_',
                Item( 'status', style = 'readonly' ),
                show_labels = False
        ),
        Item( 'url',
              show_label = False,
              editor     = IEHTMLEditor( 
                               home    = 'home',    back   = 'back', 
                               forward = 'forward', stop   = 'stop', 
                               refresh = 'refresh', search = 'search',
                               title   = 'title',   status = 'status' )
        )
    )
Exemple #27
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() ) )
class CheckListTest ( Handler ):
    
    #---------------------------------------------------------------------------
    #  Trait definitions:  
    #---------------------------------------------------------------------------
    
    value       = List( editor = CheckListEditor( name = 'values', cols = 5 ) )
    values      = List( Str )
    values_text = Str( 'red orange yellow green blue indigo violet' )
    
    #---------------------------------------------------------------------------
    #  Traits view definitions:  
    #---------------------------------------------------------------------------
        
    simple_view = View( 'value',  'values_text@' )
    custom_view = View( 'value@', 'values_text@' )
                        
    #---------------------------------------------------------------------------
    #  'Initializes the object:  
    #---------------------------------------------------------------------------
                               
    def __init__ ( self, **traits ):
        super( CheckListTest, self ).__init__( **traits )
        self._values_text_changed()
    
    #---------------------------------------------------------------------------
    #  Event handlers:  
    #---------------------------------------------------------------------------
        
    def _values_text_changed ( self ):
        self.values = self.values_text.split()
Exemple #29
0
class RegexDecoder(DataDecoder):
    """
      Decodes arbitrary text using regex.
  """
    name = Str('Regex Decoder')
    view = View(
        Item(name='regex',
             label='Regex',
             editor=TextEditor(enter_set=True, auto_set=False)),
        Item(
            label=
            "Each subgroup in the regex is \nassigned to a variable \nin the list in order."
        ),
        Item(name='variable_names',
             label='Group names',
             editor=TextEditor(enter_set=True, auto_set=False)),
        Item(label="(comma separated, use '_' to ignore a subgroup)"),
        title='Regex decoder')
    regex = Str()
    variable_names = Str()

    def decode(self, data):
        """
        Decode CSV input data then assign variables based on a CSV format list
        list of names, using an '_' to ignore a field.
    """
        re_result = ''
        try:
            re_result = re.search(self.regex, data)
        except:
            return None

        if not re_result:
            return None

        re_groups = re_result.groups()
        var_names = self.variable_names.split(',')

        if len(re_groups) == len(var_names):
            data_dict = {}
            for n, var in enumerate(var_names):
                if var != '_':
                    try:
                        data_dict[var] = float(re_groups[n])
                    except:
                        data_dict[var] = re_groups[n]
            return data_dict
Exemple #30
0
class DataAttributes(HasTraits):
    """A simple helper class used to store some attributes of an input
    data object."""

    # The version of this class.  Used for persistence.
    __version__ = 0

    # The name of the input data array.
    name = Str('')

    # The range of the data array.
    range = List

    def _get_np_arr(self, arr):
        data_array = arr.to_array()
        data_has_nan = numpy.isnan(data_array).any()
        return data_array, data_has_nan

    def compute_scalar(self, data, mode='point'):
        """Compute the scalar range from given VTK data array.  Mode
        can be 'point' or 'cell'."""
        if data is not None:
            if data.name is None or len(data.name) == 0:
                data.name = mode + '_scalars'
            self.name = data.name
            data_array, data_has_nan = self._get_np_arr(data)
            if data_has_nan:
                self.range = [
                    float(numpy.nanmin(data_array)),
                    float(numpy.nanmax(data_array))
                ]
            else:
                self.range = list(data.range)

    def compute_vector(self, data, mode='point'):
        """Compute the vector range from given VTK data array.  Mode
        can be 'point' or 'cell'."""
        if data is not None:
            if data.name is None or len(data.name) == 0:
                data.name = mode + '_vectors'
            self.name = data.name
            data_array, data_has_nan = self._get_np_arr(data)
            if data_has_nan:
                d_mag = numpy.sqrt((data_array * data_array).sum(axis=1))
                self.range = [
                    float(numpy.nanmin(d_mag)),
                    float(numpy.nanmax(d_mag))
                ]
            else:
                self.range = [0.0, data.max_norm]

    def config_lut(self, lut_mgr):
        """Set the attributes of the LUTManager."""
        rng = [0.0, 1.0]
        if len(self.range) > 0:
            rng = self.range

        lut_mgr.default_data_range = list(rng)
        lut_mgr.default_data_name = self.name