Beispiel #1
0
    def _glyph_source_changed(self, value):
        if self._updating == True:
            return

        gd = self.glyph_dict
        value_cls = camel2enthought(value.__class__.__name__)
        if value not in gd.values():
            gd[value_cls] = value

        # Now change the glyph's source trait.
        self._updating = True
        recorder = self.recorder
        if recorder is not None:
            name = recorder.get_script_id(self)
            lhs = '%s.glyph_source' % name
            rhs = '%s.glyph_dict[%r]' % (name, value_cls)
            recorder.record('%s = %s' % (lhs, rhs))

        name = value.__class__.__name__
        if name == 'GlyphSource2D':
            self.outputs = [value.output]
        else:
            self._trfm.input = value.output
            self.outputs = [self._trfm.output]
        value.on_trait_change(self.render)
        self._updating = False

        # Now update the glyph position since the transformation might
        # be different.
        self._glyph_position_changed(self.glyph_position)
Beispiel #2
0
def _make_functions(namespace):
    """Make the functions for adding modules and add them to the
    namespace automatically.
    """
    # Ignore these since they are already provided.
    ignore = ['axes', 'text', 'orientation_axes']
    for mod in registry.modules:
        func_name = camel2enthought(mod.id)
        class_name = mod.id
        if func_name.endswith('_module'):
            func_name = func_name[:-7]
            class_name = class_name[:-6]
        class_name = class_name + 'Factory'

        # Don't create any that are already defined or ignored.
        if class_name in namespace or func_name in ignore:
            continue

        # The class to wrap.
        klass = new.classobj(class_name, 
                             (_AutomaticModuleFactory,),
                             {'__doc__': mod.help,}
                             )
        klass._metadata = mod
        # The mlab helper function.
        func = make_function(klass)

        # Inject class/function into the namespace and __all__.
        namespace[class_name] = klass
        namespace[func_name] = func
        __all__.append(func_name)
Beispiel #3
0
def _make_functions(namespace):
    """Make the functions for adding filters and add them to the
    namespace automatically.
    """
    for fil in registry.filters:
        func_name = camel2enthought(fil.id)
        class_name = fil.id
        if func_name.endswith('_filter'):
            func_name = func_name[:-7]
            class_name = class_name[:-6]
        class_name = class_name + 'Factory'

        # Don't create any that are already defined.
        if class_name in namespace:
            continue

        # The class to wrap.
        klass = new.classobj(class_name, 
                             (_AutomaticFilterFactory,),
                             {'__doc__': fil.help,}
                             )
        klass._metadata = fil

        # The mlab helper function.
        func = make_function(klass)

        # Inject class/function into the namespace and __all__.
        namespace[class_name] = klass
        namespace[func_name] = func
        __all__.append(func_name)
Beispiel #4
0
    def _glyph_source_changed(self, value):
        if self._updating == True:
            return

        gd = self.glyph_dict
        value_cls = camel2enthought(value.__class__.__name__)
        if value not in gd.values():
            gd[value_cls] = value

        # Now change the glyph's source trait.
        self._updating = True
        recorder = self.recorder
        if recorder is not None:
            name = recorder.get_script_id(self)
            lhs = '%s.glyph_source'%name
            rhs = '%s.glyph_dict[%r]'%(name, value_cls)
            recorder.record('%s = %s'%(lhs, rhs))

        name = value.__class__.__name__
        if name == 'GlyphSource2D':       
            self.outputs = [value.output]
        else:
            self._trfm.input = value.output
            self.outputs = [self._trfm.output]
        value.on_trait_change(self.render)
        self._updating = False            

        # Now update the glyph position since the transformation might
        # be different.        
        self._glyph_position_changed(self.glyph_position)
Beispiel #5
0
def _make_functions(namespace):
    """Make the functions for adding filters and add them to the
    namespace automatically.
    """
    for fil in registry.filters:
        func_name = camel2enthought(fil.id)
        class_name = fil.id
        if func_name.endswith('_filter'):
            func_name = func_name[:-7]
            class_name = class_name[:-6]
        class_name = class_name + 'Factory'

        # Don't create any that are already defined.
        if class_name in namespace:
            continue

        # The class to wrap.
        klass = new.classobj(class_name, (_AutomaticFilterFactory, ), {
            '__doc__': fil.help,
        })
        klass._metadata = fil

        # The mlab helper function.
        func = make_function(klass)

        # Inject class/function into the namespace and __all__.
        namespace[class_name] = klass
        namespace[func_name] = func
        __all__.append(func_name)
Beispiel #6
0
def _make_functions(namespace):
    """Make the automatic functions and add them to the namespace."""
    for src in registry.sources:
        if len(src.extensions) == 0:
            func_name = camel2enthought(src.id)
            if func_name.endswith('_source'):
                func_name = func_name[:-7]
            func = lambda metadata=src: _create_data_source(metadata)
            func.__doc__ = src.help
            func.__name__ = func_name
            # Inject function into the namespace and __all__.
            namespace[func_name] = func
            __all__.append(func_name)
Beispiel #7
0
 def __set_pure_state__(self, state):
     if 'glyph_dict' in state:
         # Set their state.
         set_state(self, state, first=['glyph_dict'], ignore=['*'])
         ignore = ['glyph_dict']
     else:
         # Set the dict state using the persisted list.
         gd = self.glyph_dict
         gl = self.glyph_list
         handle_children_state(gl, state.glyph_list)
         for g, gs in zip(gl, state.glyph_list):
             name = camel2enthought(g.__class__.__name__)
             if name not in gd:
                 gd[name] = g
             # Set the glyph source's state.
             set_state(g, gs)
         ignore = ['glyph_list']
     g_name = state.glyph_source.__metadata__['class_name']
     name = camel2enthought(g_name)
     # Set the correct glyph_source.
     self.glyph_source = self.glyph_dict[name]
     set_state(self, state, ignore=ignore)
Beispiel #8
0
 def __set_pure_state__(self, state):
     if 'glyph_dict' in state:
         # Set their state.
         set_state(self, state, first=['glyph_dict'], ignore=['*'])
         ignore = ['glyph_dict']
     else:
         # Set the dict state using the persisted list.
         gd = self.glyph_dict
         gl = self.glyph_list
         handle_children_state(gl, state.glyph_list)
         for g, gs in zip(gl, state.glyph_list):
             name = camel2enthought(g.__class__.__name__)
             if name not in gd:
                 gd[name] = g
             # Set the glyph source's state.
             set_state(g, gs)
         ignore = ['glyph_list']
     g_name = state.glyph_source.__metadata__['class_name']
     name = camel2enthought(g_name)
     # Set the correct glyph_source.
     self.glyph_source = self.glyph_dict[name]
     set_state(self, state, ignore=ignore)
Beispiel #9
0
 def test_camel2enthought(self):
     """Test CamelCase to Enthought style name conversion."""
     v_name = ['GetFooBar', 'GetOBBTree', 'XMLDataReader',
               'GetFooXML', 'HTMLIsSGML', '_SetMe', '_XYZTest',
               'Actor2D', 'Actor3D', 'Actor6D', 'PLOT3DReader',
               'Actor61Dimension', 'GL2PSExporter',
               'Volume16Reader']
     t_name = ['get_foo_bar', 'get_obb_tree', 'xml_data_reader',
               'get_foo_xml', 'html_is_sgml', '_set_me',
               '_xyz_test', 'actor2d', 'actor3d', 'actor6_d',
               'plot3d_reader', 'actor61_dimension',
               'gl2ps_exporter', 'volume16_reader']
     for i, vn in enumerate(v_name):
         tn = camel2enthought(vn)
         self.assertEqual(tn, t_name[i])
Beispiel #10
0
 def test_camel2enthought(self):
     """Test CamelCase to Enthought style name conversion."""
     v_name = [
         'GetFooBar', 'GetOBBTree', 'XMLDataReader', 'GetFooXML',
         'HTMLIsSGML', '_SetMe', '_XYZTest', 'Actor2D', 'Actor3D',
         'Actor6D', 'PLOT3DReader', 'Actor61Dimension', 'GL2PSExporter',
         'Volume16Reader'
     ]
     t_name = [
         'get_foo_bar', 'get_obb_tree', 'xml_data_reader', 'get_foo_xml',
         'html_is_sgml', '_set_me', '_xyz_test', 'actor2d', 'actor3d',
         'actor6_d', 'plot3d_reader', 'actor61_dimension', 'gl2ps_exporter',
         'volume16_reader'
     ]
     for i, vn in enumerate(v_name):
         tn = camel2enthought(vn)
         self.assertEqual(tn, t_name[i])
Beispiel #11
0
def process_cmd_line(app, opts, args):
    """ Processes the passed command line arguments.

    Input Arguments:
      app -- A Mayavi application instance.

      opts -- The list of options returned by getopt.

      args -- The remaining arguments returned by getopt.
    """    

    from enthought.mayavi.core.common import error, exception
    from enthought.tvtk.common import camel2enthought

    sources = _get_non_file_sources()
    script = app.script
    last_obj = None

    # Start a new scene by default if there is none currently and none
    # was specified at the start of the command line arguments.
    if script.engine.current_scene is None:
        new_scene = False
        if len(opts) == 0:
            if len(args) == 0:
                new_scene = True
        elif (opts[0][0] not in ('-n', '--new-scene', '-z',
                                 '--visualization', '--viz',
                                 '-x', '--exec')):
            new_scene = True
        if new_scene:            
            last_obj = script.new_scene()
        
    for o, a in opts:
        if o in ('-d', '--data'):
            base, ext = splitext(a)
            if exists(a):
                last_obj = script.open(a)
            elif a in sources:
                md = sources[a]
                src = md.get_callable()()
                script.add_source(src)
                last_obj = src
            else:
                error("File/Source %s does not exist!"%a)
                return

        if o in ('-m', '--module'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx+1:]
            else:
                modname = 'enthought.mayavi.modules.%s'%camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                m = getattr(mod, classname)()
                if classname == 'Labels':
                    m.object = script.engine.current_object
                script.add_module(m)
                last_obj = m

        if o in ('-f', '--filter'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx+1:]
            else:
                if a[:12] == 'UserDefined:':
                    modname = 'enthought.mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from enthought.tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'enthought.mayavi.filters.%s'%camel2enthought(a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                klass = getattr(mod, classname)
                if classname != 'UserDefined':
                    f = klass()
                else:
                    if extra is not None:
                        f = klass(filter=extra)
                    else:
                        f = klass()
                    f.setup_filter()
                script.add_filter(f)
                last_obj = f
Beispiel #12
0
    def get_children(self, obj):
        """Returns the child objects of a particular tvtk object in a
        dictionary, the keys are the trait names.  This is used to
        generate the tree in the browser."""

        vtk_obj = tvtk.to_vtk(obj)
        methods = self._get_methods(vtk_obj)

        kids = {}
        def _add_kid(key, x):
            if x is None:
                kids[key] = None
            else:
                if type(x) in (type([]), type(())):
                    x1 = [i for i in x if isinstance(i, TVTKBase)]
                    if x1:
                        kids[key] = x1
                elif isinstance(x, TVTKBase):
                    if hasattr(x, '__iter__'):
                        # Don't add iterable objects that contain non
                        # acceptable nodes
                        if len(list(x)) and isinstance(list(x)[0], TVTKBase):
                            kids[key] = x
                    else:
                        kids[key] = x

        for method in methods:
            attr = camel2enthought(method[0])
            if hasattr(obj, attr):
                _add_kid(attr, getattr(obj, attr))

        # Check for sources and inputs.
        if hasattr(obj, 'number_of_sources'):
            srcs = [obj.get_source(i) \
                    for i in range(obj.number_of_sources)]
            _add_kid('source', srcs)
        elif hasattr(obj, 'source'):
            _add_kid('source', obj.source)

        if hasattr(obj, 'get_input'):
            inputs = []
            if hasattr(obj, 'number_of_input_ports'):
                if obj.number_of_input_ports:
                    # Sometimes not all the inputs can be retrieved using
                    # 'get_input', as they may be sources (for instance
                    # the ProbeFilter). 
                    inputs = list()
                    for i in range(obj.number_of_input_ports):
                        try:
                            inputs.append(obj.get_input(i))
                        except TypeError:
                            pass
                    if not inputs:
                        inputs = [obj.get_input()]
            else:
                inputs = [obj.get_input(i) \
                          for i in range(obj.number_of_inputs)]
            _add_kid('input', inputs)
        elif hasattr(obj, 'input'):
            _add_kid('input', obj.input)

        if hasattr(obj, 'producer_port'):
            _add_kid('producer_port', obj.producer_port)

        return kids
Beispiel #13
0
    def get_children(self, obj):
        """Returns the child objects of a particular tvtk object in a
        dictionary, the keys are the trait names.  This is used to
        generate the tree in the browser."""

        vtk_obj = tvtk.to_vtk(obj)
        methods = self._get_methods(vtk_obj)

        kids = {}

        def _add_kid(key, x):
            if x is None:
                kids[key] = None
            else:
                if type(x) in (type([]), type(())):
                    x1 = [i for i in x if isinstance(i, TVTKBase)]
                    if x1:
                        kids[key] = x1
                elif isinstance(x, TVTKBase):
                    if hasattr(x, '__iter__'):
                        # Don't add iterable objects that contain non
                        # acceptable nodes
                        if len(list(x)) and isinstance(list(x)[0], TVTKBase):
                            kids[key] = x
                    else:
                        kids[key] = x

        for method in methods:
            attr = camel2enthought(method[0])
            if hasattr(obj, attr):
                _add_kid(attr, getattr(obj, attr))

        # Check for sources and inputs.
        if hasattr(obj, 'number_of_sources'):
            srcs = [obj.get_source(i) \
                    for i in range(obj.number_of_sources)]
            _add_kid('source', srcs)
        elif hasattr(obj, 'source'):
            _add_kid('source', obj.source)

        if hasattr(obj, 'get_input'):
            inputs = []
            if hasattr(obj, 'number_of_input_ports'):
                if obj.number_of_input_ports:
                    # Sometimes not all the inputs can be retrieved using
                    # 'get_input', as they may be sources (for instance
                    # the ProbeFilter).
                    inputs = list()
                    for i in range(obj.number_of_input_ports):
                        try:
                            inputs.append(obj.get_input(i))
                        except TypeError:
                            pass
                    if not inputs:
                        inputs = [obj.get_input()]
            else:
                inputs = [obj.get_input(i) \
                          for i in range(obj.number_of_inputs)]
            _add_kid('input', inputs)
        elif hasattr(obj, 'input'):
            _add_kid('input', obj.input)

        if hasattr(obj, 'producer_port'):
            _add_kid('producer_port', obj.producer_port)

        return kids
Beispiel #14
0
def process_cmd_line(app, opts, args):
    """ Processes the passed command line arguments.

    Input Arguments:
      app -- A Mayavi application instance.

      opts -- The list of options returned by getopt.

      args -- The remaining arguments returned by getopt.
    """

    from enthought.mayavi.core.common import error, exception
    from enthought.tvtk.common import camel2enthought

    sources = _get_non_file_sources()
    script = app.script
    last_obj = None

    # Start a new scene by default if there is none currently and none
    # was specified at the start of the command line arguments.
    if script.engine.current_scene is None:
        new_scene = False
        if len(opts) == 0:
            if len(args) == 0:
                new_scene = True
        elif (opts[0][0] not in ('-n', '--new-scene', '-z', '--visualization',
                                 '--viz', '-x', '--exec')):
            new_scene = True
        if new_scene:
            last_obj = script.new_scene()

    for o, a in opts:
        if o in ('-d', '--data'):
            base, ext = splitext(a)
            if exists(a):
                last_obj = script.open(a)
            elif a in sources:
                md = sources[a]
                src = md.get_callable()()
                script.add_source(src)
                last_obj = src
            else:
                error("File/Source %s does not exist!" % a)
                return

        if o in ('-m', '--module'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx + 1:]
            else:
                modname = 'enthought.mayavi.modules.%s' % camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                m = getattr(mod, classname)()
                if classname == 'Labels':
                    m.object = script.engine.current_object
                script.add_module(m)
                last_obj = m

        if o in ('-f', '--filter'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx + 1:]
            else:
                if a[:12] == 'UserDefined:':
                    modname = 'enthought.mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from enthought.tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'enthought.mayavi.filters.%s' % camel2enthought(
                        a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                klass = getattr(mod, classname)
                if classname != 'UserDefined':
                    f = klass()
                else:
                    if extra is not None:
                        f = klass(filter=extra)
                    else:
                        f = klass()
                    f.setup_filter()
                script.add_filter(f)
                last_obj = f