Esempio n. 1
0
 def add_source(self, src, scene=None):
     """Adds a given source to the MayaVi pipeline.
     """
     try:
         self.engine.add_source(src, scene=scene)
     except:
         exception()
Esempio n. 2
0
def run_script(mayavi, script_name):
    """Execfiles a given script.  The name `mayavi` is bound to the
    mayavi script instance just like in the embedded interpreter.
    `script_name` is the name of the script to execute.

    Note that this function uses `execfile`. You should be careful
    when using this.

    It returns `False` if everything was OK and `True` if not.
    """
    from mayavi.core.common import exception

    g = sys.modules['__main__'].__dict__
    if 'mayavi' not in g:
        g['mayavi'] = mayavi
        g['engine'] = mayavi.engine
    g['__file__'] = script_name
    error = False
    # Do execfile
    try:
        # If we don't pass globals twice we get NameErrors and nope,
        # using exec open(script_name).read() does not fix it.
        exec(compile(open(script_name).read(), script_name, 'exec'), g, g)
    except Exception as msg:
        exception(str(msg))
        error = True

    return error
Esempio n. 3
0
 def load_visualization(self, fname):
     """Given a file/file name this loads the visualization.
     """
     try:
         self.engine.load_visualization(fname)
     except:
         exception()
Esempio n. 4
0
def run_script(mayavi, script_name):
    """Execfiles a given script.  The name `mayavi` is bound to the
    mayavi script instance just like in the embedded interpreter.
    `script_name` is the name of the script to execute.

    Note that this function uses `execfile`. You should be careful
    when using this.

    It returns `False` if everything was OK and `True` if not.
    """
    from mayavi.core.common import exception

    g = sys.modules['__main__'].__dict__
    if 'mayavi' not in g:
        g['mayavi'] = mayavi
        g['engine'] = mayavi.engine
    g['__file__'] = script_name
    error = False
    # Do execfile
    try:
        # If we don't pass globals twice we get NameErrors and nope,
        # using exec open(script_name).read() does not fix it.
        exec(compile(open(script_name).read(), script_name, 'exec'), g, g)
    except Exception as msg:
        exception(str(msg))
        error = True

    return error
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open Python file',
                            action='open',
                            wildcard=wildcard)
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist" % dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine
            g['__file__'] = dialog.path
            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                exec(compile(open(dialog.path).read(), dialog.path, 'exec'), g,
                     g)
            except Exception as msg:
                exception(str(msg))
Esempio n. 6
0
 def open(self, filename):
     """Open a data file if possible.
     """
     try:
         return self.engine.open(filename)
     except:
         exception()
Esempio n. 7
0
 def add_source(self, src, scene=None):
     """Adds a given source to the MayaVi pipeline.
     """
     try:
         self.engine.add_source(src, scene=scene)
     except:
         exception()
Esempio n. 8
0
 def load_visualization(self, fname):
     """Given a file/file name this loads the visualization.
     """
     try:
         self.engine.load_visualization(fname)
     except:
         exception()
Esempio n. 9
0
 def open(self, filename):
     """Open a data file if possible.
     """
     try:
         return self.engine.open(filename)
     except:
         exception()
Esempio n. 10
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open Python file',
                            action='open', wildcard=wildcard
                            )
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist"%dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine
            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                execfile(dialog.path, g, g)
            except Exception, msg:
                exception(str(msg))
Esempio n. 11
0
 def save_visualization(self, fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     try:
         self.engine.save_visualization(fname)
     except:
         exception()
Esempio n. 12
0
 def add_filter(self, fil, obj=None):
     """Adds a given filter to the MayaVi pipeline. Adds it to the selected
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_filter(fil, obj=obj)
     except:
         exception()
Esempio n. 13
0
 def add_module(self, mod, obj=None):
     """Adds a given module to the MayaVi pipeline. Adds it to the selected
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_module(mod, obj=obj)
     except:
         exception()
Esempio n. 14
0
 def save_visualization(self, fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     try:
         self.engine.save_visualization(fname)
     except:
         exception()
Esempio n. 15
0
 def add_filter(self, fil, obj=None):
     """Adds a given filter to the MayaVi pipeline. Adds it to the selected
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_filter(fil, obj=obj)
     except:
         exception()
Esempio n. 16
0
 def add_module(self, mod, obj=None):
     """Adds a given module to the MayaVi pipeline. Adds it to the selected
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_module(mod, obj=obj)
     except:
         exception()
Esempio n. 17
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control

        # path from preference manager
        pref_script_path = preference_manager.cviewerui.scriptpath

        if pref_script_path == '':
            # store executed script path in preferences
            dialog = FileDialog(
                parent=parent,
                title='Open Python file',
                action='open',
                wildcard=wildcard,
            )
        else:
            dialog = FileDialog(
                parent=parent,
                title='Open Python file',
                action='open',
                wildcard=wildcard,
                default_directory=pref_script_path,
            )

        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist" % dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine

            if 'cfile' not in g:
                # load cfile reference into gloabl name space
                cfile = self.window.application.get_service(
                    'cviewer.plugins.cff2.cfile.CFile')
                g['cfile'] = cfile

            # always store last executed path in preferences
            # but this only gets definitely stored when one open the preference manager
            preference_manager.cviewerui.scriptpath = dirname(dialog.path)

            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                execfile(dialog.path, g, g)
            except Exception, msg:
                exception(str(msg))
Esempio n. 18
0
 def _handle_children(self, removed, added):
     for obj in removed:
         obj.stop()
     for obj in added:
         obj.trait_set(scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Esempio n. 19
0
 def _handle_children(self, removed, added):
     for obj in removed:
         obj.stop()
     for obj in added:
         obj.set(scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Esempio n. 20
0
 def _handle_children(self, removed, added):
     # Stop all the old children.
     for obj in removed:
         obj.stop()
     # Setup and start the new ones.
     for obj in added:
         obj.set(module_manager=self, scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Esempio n. 21
0
 def _handle_children(self, removed, added):
     # Stop all the old children.
     for obj in removed:
         obj.stop()
     # Setup and start the new ones.
     for obj in added:
         obj.trait_set(module_manager=self, scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Esempio n. 22
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = "Python files (*.py)|*.py"
        parent = self.window.control

        # path from preference manager
        pref_script_path = preference_manager.cviewerui.scriptpath

        if pref_script_path == "":
            # store executed script path in preferences
            dialog = FileDialog(parent=parent, title="Open Python file", action="open", wildcard=wildcard)
        else:
            dialog = FileDialog(
                parent=parent,
                title="Open Python file",
                action="open",
                wildcard=wildcard,
                default_directory=pref_script_path,
            )

        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist" % dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules["__main__"].__dict__
            if "mayavi" not in g:
                mv = get_imayavi(self.window)
                g["mayavi"] = mv
                g["engine"] = mv.engine

            if "cfile" not in g:
                # load cfile reference into gloabl name space
                cfile = self.window.application.get_service("cviewer.plugins.cff2.cfile.CFile")
                g["cfile"] = cfile

            # always store last executed path in preferences
            # but this only gets definitely stored when one open the preference manager
            preference_manager.cviewerui.scriptpath = dirname(dialog.path)

            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                execfile(dialog.path, g, g)
            except Exception, msg:
                exception(str(msg))
Esempio n. 23
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.
        """
        # Do nothing if we are already running.
        if self.running:
            return

        # Start all our children.
        for obj in self.children:
            try:
                obj.start()
            except:
                exception()

        # Call parent method to set the running state.
        super(Source, self).start()
Esempio n. 24
0
    def _handle_children(self, removed, added):
        # Stop all the removed children.
        for obj in removed:
            obj.stop()

        # Process the new objects.
        for obj in added:
            obj.trait_set(scene=self.scene, parent=self)
            if isinstance(obj, ModuleManager):
                obj.source = self
            elif is_filter(obj):
                obj.inputs.append(self)
            if self.running:
                try:
                    obj.start()
                except:
                    exception()
Esempio n. 25
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.
        """
        # Do nothing if we are already running.
        if self.running:
            return

        # Start all our children.
        for obj in self.children:
            try:
                obj.start()
            except:
                exception()

        # Call parent method to set the running state.
        super(Source, self).start()
Esempio n. 26
0
    def _handle_children(self, removed, added):
        # Stop all the removed children.
        for obj in removed:
            obj.stop()

        # Process the new objects.
        for obj in added:
            obj.trait_set(scene=self.scene, parent=self)
            if isinstance(obj, ModuleManager):
                obj.source = self
            elif is_filter(obj):
                obj.inputs.append(self)
            if self.running:
                try:
                    obj.start()
                except:
                    exception()
Esempio n. 27
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.  Note that when start is invoked, all the other
        information for the pipeline should be already set.
        """
        if self.running:
            return

        # Setup event handlers.
        self._setup_event_handlers()

        # Setup the pipeline.
        self.update_pipeline()

        # Start the components.
        try:
            for component in self.components:
                component.start()
        except:
            exception()

        # Call parent method to set the running state.
        super(Module, self).start()
Esempio n. 28
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.  Note that when start is invoked, all the other
        information for the pipeline should be already set.
        """
        if self.running:
            return

        # Setup event handlers.
        self._setup_event_handlers()

        # Setup the pipeline.
        self.update_pipeline()

        # Start the components.
        try:
            for component in self.components:
                component.start()
        except:
            exception()

        # Call parent method to set the running state.
        super(Module, self).start()
Esempio n. 29
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 mayavi.core.common import error, exception
    from 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 = 'mayavi.modules.%s' % camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError as 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 = 'mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'mayavi.filters.%s' % camel2enthought(a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError as 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

        if o in ('-M', '--module-mgr'):
            from mayavi.core.module_manager \
                 import ModuleManager
            mm = ModuleManager()
            script.add_filter(mm)
            last_obj = mm

        if o in ('-n', '--new-scene'):
            script.new_scene()
            e = script.engine
            s = e.scenes[-1]
            e.trait_set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec'):
            err = run_script(script, a)
            if err:  # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec(stmt, locals(), globals())
            except Exception as msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext(arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err:  # stop processing arguments.
                return
        else:
            script.open(arg)
Esempio n. 30
0
            e = script.engine
            s = e.scenes[-1]
            e.set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec' ):
            err = run_script(script, a)
            if err: # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec stmt in locals(), globals()
            except Exception, msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext (arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err: # stop processing arguments.
                return
        else:
            script.open(arg)
Esempio n. 31
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 mayavi.core.common import error, exception
    from 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 = 'mayavi.modules.%s'%camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError as 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 = 'mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'mayavi.filters.%s'%camel2enthought(a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError as 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

        if o in ('-M', '--module-mgr'):
            from mayavi.core.module_manager \
                 import ModuleManager
            mm = ModuleManager()
            script.add_filter(mm)
            last_obj = mm

        if o in ('-n', '--new-scene'):
            script.new_scene()
            e = script.engine
            s = e.scenes[-1]
            e.set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec' ):
            err = run_script(script, a)
            if err: # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec(stmt, locals(), globals())
            except Exception as msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext (arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err: # stop processing arguments.
                return
        else:
            script.open(arg)
Esempio n. 32
0
            e = script.engine
            s = e.scenes[-1]
            e.set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec'):
            err = run_script(script, a)
            if err:  # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec stmt in locals(), globals()
            except Exception, msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext(arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err:  # stop processing arguments.
                return
        else:
            script.open(arg)