Esempio n. 1
0
    def update_pipeline(self):
        inputs = self.inputs
        if len(inputs) == 0:
            return

        input = inputs[0].outputs[0]
        mapping = {
            "vtkStructuredGrid": tvtk.ExtractGrid,
            "vtkRectilinearGrid": tvtk.ExtractRectilinearGrid,
            "vtkImageData": tvtk.ExtractVOI,
        }

        for key, klass in mapping.iteritems():
            if input.is_a(key):
                self.filter = klass()
                break
        else:
            error("This filter does not support %s objects" % (input.__class__.__name__))
            return

        fil = self.filter
        fil.input = input
        fil.update_whole_extent()
        fil.update()
        self._set_outputs([fil.output])
        self._update_limits()
        self._update_voi()
        self._update_sample_rate()
Esempio n. 2
0
    def perform(self, event):
        """ Performs the action. """
        mv = get_imayavi(self.window)
        s = get_scene(mv)
        if s is None:
            return

        wildcard = 'All files (*.*)|*.*'
        for src in registry.sources:
            if len(src.extensions) > 0:
                if wildcard.endswith('|') or \
                   src.wildcard.startswith('|'):
                    wildcard += src.wildcard
                else:
                    wildcard += '|' + src.wildcard

        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open supported data file',
                            action='open',
                            wildcard=wildcard)
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist!" % dialog.path, parent)
                return
            # FIXME: Ask for user input if a filetype is unknown and
            # choose appropriate reader.
            src = mv.open(dialog.path)
            if src is not None:
                mv.engine.current_selection = src
Esempio n. 3
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if len(self.inputs) == 0:
            return
        input = self.inputs[0].outputs[0]
        plane = None
        if input.is_a('vtkStructuredGrid'):
            plane = tvtk.StructuredGridGeometryFilter()
        elif input.is_a('vtkStructuredPoints') or input.is_a('vtkImageData'):
            plane = tvtk.ImageDataGeometryFilter ()
        elif input.is_a('vtkRectilinearGrid'):
            plane = tvtk.RectilinearGridGeometryFilter ()
        else:
            msg = "The GridPlane component does not support the %s dataset."\
                  %(input.class_name)
            error(msg)
            raise TypeError, msg

        plane.input = input
        self.plane = plane
        self._update_limits()
        self._update_voi()
        self.outputs = [plane.output]
Esempio n. 4
0
    def _find_input(self):
        mm = self.module_manager
        if self.object is None:
            if self.object_id == -1:
                self.input = mm.source
            elif self.object_id > -1:
                obj = mm.children[self.object_id]
                if hasattr(obj, 'actor'):
                    self.set(object=obj, trait_change_notify=False)
                    self.input = obj.actor.inputs[0]
                else:
                    self.input = mm.source
        else:
            o = self.object
            if hasattr(o, 'module_manager'):
                # A module.
                if hasattr(o, 'actor'):
                    self.input = o.actor.inputs[0]
                else:
                    self.input = o.module_manager.source

        if self.input is None:
            if self.object_id == -2:
                self.input = mm.source
            else:
                error('No object to label!')
                return
Esempio n. 5
0
 def open(self, filename, scene=None):
     """Open a file given a filename if possible in either the
     current scene or the passed `scene`.
     """
     passed_scene = scene
     reader = registry.get_file_reader(filename)        
     if reader is None:
         msg = 'No suitable reader found for the file %s'%filename
         error(msg)
     else:
         src = None
         if scene is None:
             scene = self.current_scene
         if scene is None:
             scene = self.new_scene()
         try:
             sc = scene.scene
             if sc is not None:
                 sc.busy = True
             callable = reader.get_callable()
             if reader.factory is None:
                 src = callable()
                 src.initialize(filename)
             else:
                 # Factory functions are passed the filename and a
                 # reference to the engine. 
                 src = callable(filename, self)
             if src is not None:
                 self.add_source(src, passed_scene)
         finally:
             if sc is not None:
                 sc.busy = False 
         if src is not None:
             return src
Esempio n. 6
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if len(self.inputs) == 0:
            return
        input = self.inputs[0].outputs[0]
        plane = None
        if input.is_a('vtkStructuredGrid'):
            plane = tvtk.StructuredGridGeometryFilter()
        elif input.is_a('vtkStructuredPoints') or input.is_a('vtkImageData'):
            plane = tvtk.ImageDataGeometryFilter()
        elif input.is_a('vtkRectilinearGrid'):
            plane = tvtk.RectilinearGridGeometryFilter()
        else:
            msg = "The GridPlane component does not support the %s dataset."\
                  %(input.class_name)
            error(msg)
            raise TypeError, msg

        plane.input = input
        self.plane = plane
        self._update_limits()
        self._update_voi()
        self.outputs = [plane.output]
Esempio n. 7
0
 def open(self, filename, scene=None):
     """Open a file given a filename if possible in either the
     current scene or the passed `scene`.
     """
     passed_scene = scene
     reader = registry.get_file_reader(filename)
     if reader is None:
         msg = 'No suitable reader found for the file %s' % filename
         error(msg)
     else:
         src = None
         if scene is None:
             scene = self.current_scene
         if scene is None:
             scene = self.new_scene()
         try:
             sc = scene.scene
             if sc is not None:
                 sc.busy = True
             callable = reader.get_callable()
             if reader.factory is None:
                 src = callable()
                 src.initialize(filename)
             else:
                 # Factory functions are passed the filename and a
                 # reference to the engine.
                 src = callable(filename, self)
             if src is not None:
                 self.add_source(src, passed_scene)
         finally:
             if sc is not None:
                 sc.busy = False
         if src is not None:
             return src
Esempio n. 8
0
    def perform(self, event):
        """ Performs the action. """
        mv = get_imayavi(self.window)
        s = get_scene(mv)
        if s is None:
            return

        wildcard = 'All files (*.*)|*.*'
        for src in registry.sources:
            if len(src.extensions) > 0:
                if wildcard.endswith('|') or \
                   src.wildcard.startswith('|'):
                       wildcard += src.wildcard
                else:
                    wildcard += '|' + src.wildcard
                   
        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open supported data file',
                            action='open', wildcard=wildcard
                            )
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist!"%dialog.path, parent)
                return
            # FIXME: Ask for user input if a filetype is unknown and
            # choose appropriate reader.
            src = mv.open(dialog.path)
            if src is not None:
                mv.engine.current_selection = src
Esempio n. 9
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mm = self.module_manager
        if mm is None:
            return

        input = mm.source.outputs[0]

        ug = hasattr(tvtk, 'UnstructuredGridVolumeMapper')
        if ug:
            if not input.is_a('vtkImageData') \
                   and not input.is_a('vtkUnstructuredGrid'):
                error('Volume rendering only works with '\
                      'StructuredPoints/ImageData/UnstructuredGrid datasets')
                return
        elif not input.is_a('vtkImageData'):
            error('Volume rendering only works with '\
                  'StructuredPoints/ImageData datasets')
            return
    
        self._setup_mapper_types()
        self._setup_current_range()
        self._volume_mapper_type_changed(self.volume_mapper_type)
        self._update_ctf_fired()
        self.pipeline_changed = True
Esempio n. 10
0
    def _file_path_changed(self, fpath):
        value = fpath.get()
        if len(value) == 0:
            return
        # Extract the file extension
        splitname = value.strip().split('.')
        extension = splitname[-1].lower()
        # Select UnstructuredGridreader based on file type
        old_reader = self.reader
        if self._reader_dict.has_key(extension):
            self.reader = self._reader_dict[extension]
        else:
            error('Invalid file extension for file: %s' % value)
            return

        self.reader.file_name = value.strip()
        self.reader.update()
        self.reader.update_information()

        if old_reader is not None:
            old_reader.on_trait_change(self.render, remove=True)
        self.reader.on_trait_change(self.render)

        old_outputs = self.outputs
        self.outputs = [self.reader.output]

        if self.outputs == old_outputs:
            self.data_changed = True

        # Change our name on the tree view
        self.name = self._get_name()
Esempio n. 11
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if len(self.inputs) == 0:
            return
        input = self.inputs[0].outputs[0]
        plane = None
        if input.is_a('vtkStructuredGrid'):
            plane = tvtk.StructuredGridGeometryFilter()
        elif input.is_a('vtkStructuredPoints') or input.is_a('vtkImageData'):
            plane = tvtk.ImageDataGeometryFilter ()
        elif input.is_a('vtkRectilinearGrid'):
            plane = tvtk.RectilinearGridGeometryFilter ()
        else:
            msg = "The GridPlane component does not support the %s dataset."\
                  %(input.class_name)
            error(msg)
            raise TypeError, msg

        plane.input = input
        self.plane = plane
        self.outputs = [plane.output]
        self._update_limits()
        self._update_extents()
        # If the data is 2D make sure that we default to the
        # appropriate axis.
        extents = list(_get_extent(input))
        diff = [y-x for x, y in zip(extents[::2], extents[1::2])]
        if diff.count(0) > 0:
            self.axis = ['x', 'y', 'z'][diff.index(0)]
Esempio n. 12
0
def find_file_data_type(file_name):
    "Parses the named file to see what type of data there is."
    r = tvtk.XMLFileReadTester(file_name=file_name)
    if r.test_read_file():
        return r.file_data_type
    else:
        error("File %s is not a valid VTK XML file!"%(file_name))
Esempio n. 13
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if len(self.inputs) == 0:
            return
        input = self.inputs[0].outputs[0]
        plane = None
        if input.is_a('vtkStructuredGrid'):
            plane = tvtk.StructuredGridGeometryFilter()
        elif input.is_a('vtkStructuredPoints') or input.is_a('vtkImageData'):
            plane = tvtk.ImageDataGeometryFilter()
        elif input.is_a('vtkRectilinearGrid'):
            plane = tvtk.RectilinearGridGeometryFilter()
        else:
            msg = "The GridPlane component does not support the %s dataset."\
                  %(input.class_name)
            error(msg)
            raise TypeError, msg

        plane.input = input
        self.plane = plane
        self.outputs = [plane.output]
        self._update_limits()
        self._update_extents()
        # If the data is 2D make sure that we default to the
        # appropriate axis.
        extents = list(_get_extent(input))
        diff = [y - x for x, y in zip(extents[::2], extents[1::2])]
        if diff.count(0) > 0:
            self.axis = ['x', 'y', 'z'][diff.index(0)]
Esempio n. 14
0
    def _find_input(self):
        mm = self.module_manager
        if self.object is None:
            if self.object_id == -1:
                self.input = mm.source
            elif self.object_id > -1:
                obj = mm.children[self.object_id]
                if hasattr(obj, 'actor'):
                    self.set(object=obj, trait_change_notify=False)
                    self.input = obj.actor.inputs[0]
                else:
                    self.input = mm.source
        else:
            o = self.object
            if hasattr(o, 'module_manager'):
                # A module.
                if hasattr(o, 'actor'):
                    self.input = o.actor.inputs[0]
                else:
                    self.input = o.module_manager.source

        if self.input is None:
            if self.object_id == -2:
                self.input = mm.source
            else:
                error('No object to label!')
                return
Esempio n. 15
0
def convert_to_poly_data(data):
    """Given a VTK dataset object, this returns the data as PolyData.
    This is primarily used to convert the data suitably for filters
    that only work for PolyData.
    """
    if data.is_a('vtkPolyData'):
        return data

    conv = {'vtkStructuredPoints': tvtk.ImageDataGeometryFilter,
            'vtkImageData': tvtk.ImageDataGeometryFilter,
            'vtkRectilinearGrid': tvtk.RectilinearGridGeometryFilter,
            'vtkStructuredGrid': tvtk.StructuredGridGeometryFilter,
            'vtkUnstructuredGrid':tvtk.GeometryFilter}

    fil = None
    for name, fil_class in conv.items():
        if data.is_a(name):
            fil = fil_class()
            break
        
    if fil is not None:
        fil.input = data
        return fil.output
    else:
        error('Given object is not a VTK dataset: %s'%data.__class__.__name__)
def find_file_data_type(file_name):
    "Parses the named file to see what type of data there is."
    r = tvtk.XMLFileReadTester(file_name=file_name)
    if r.test_read_file():
        return r.file_data_type
    else:
        error("File %s is not a valid VTK XML file!" % (file_name))
Esempio n. 17
0
def convert_to_poly_data(data):
    """Given a VTK dataset object, this returns the data as PolyData.
    This is primarily used to convert the data suitably for filters
    that only work for PolyData.
    """
    if data.is_a('vtkPolyData'):
        return data

    conv = {
        'vtkStructuredPoints': tvtk.ImageDataGeometryFilter,
        'vtkImageData': tvtk.ImageDataGeometryFilter,
        'vtkRectilinearGrid': tvtk.RectilinearGridGeometryFilter,
        'vtkStructuredGrid': tvtk.StructuredGridGeometryFilter,
        'vtkUnstructuredGrid': tvtk.GeometryFilter
    }

    fil = None
    for name, fil_class in conv.items():
        if data.is_a(name):
            fil = fil_class()
            break

    if fil is not None:
        fil.input = data
        return fil.output
    else:
        error('Given object is not a VTK dataset: %s' %
              data.__class__.__name__)
Esempio n. 18
0
    def update_pipeline(self):
        # Do nothing if there is no input.
        inputs = self.inputs
        if len(inputs) == 0:
            return

        inp = inputs[0].outputs[0]
        if inp.is_a('vtkImageData') or inp.is_a('vtkRectilinearGrid'):
            error('Transformation not supported for '\
                  'ImageData/StructuredPoints/RectilinearGrid')
            return

        # Set the input for the widget and place it if this hasn't
        # been done before.
        w = self.widget
        w.input = inp
        if self._first:
            w.place_widget()
            self._first = False

        # By default we set the input to the first output of the first
        # input.
        fil = self.filter
        fil.input = inp
        fil.transform = self._transform
        fil.update()
        self._set_outputs([fil.output])
Esempio n. 19
0
    def update_pipeline(self):
        # Do nothing if there is no input.
        inputs = self.inputs
        if len(inputs) == 0:
            return

        inp = inputs[0].outputs[0]
        if inp.is_a('vtkImageData') or inp.is_a('vtkRectilinearGrid'):
            error('Transformation not supported for '\
                  'ImageData/StructuredPoints/RectilinearGrid')
            return
        
        # Set the input for the widget and place it if this hasn't
        # been done before.
        w = self.widget
        w.input = inp
        if self._first:
            w.place_widget()
            self._first = False
        
        # By default we set the input to the first output of the first
        # input.
        fil = self.filter
        fil.input = inp
        fil.transform = self._transform
        fil.update()
        self._set_outputs([fil.output])
Esempio n. 20
0
    def update_pipeline(self):
        inputs = self.inputs
        if len(inputs) == 0:
            return

        input = inputs[0].outputs[0]
        mapping = {
            'vtkStructuredGrid': tvtk.ExtractGrid,
            'vtkRectilinearGrid': tvtk.ExtractRectilinearGrid,
            'vtkImageData': tvtk.ExtractVOI
        }

        for key, klass in mapping.iteritems():
            if input.is_a(key):
                self.filter = klass()
                break
        else:
            error('This filter does not support %s objects'%\
                  (input.__class__.__name__))
            return

        fil = self.filter
        fil.input = input
        fil.update_whole_extent()
        fil.update()
        self._set_outputs([fil.output])
        self._update_limits()
        self._update_voi()
        self._update_sample_rate()
Esempio n. 21
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. 22
0
    def _file_path_changed(self, fpath):
        value = fpath.get()
        if len(value) == 0:
            return
        # Extract the file extension
        splitname = value.strip().split('.')
        extension = splitname[-1].lower()
        # Select UnstructuredGridreader based on file type
        old_reader = self.reader
        if self._reader_dict.has_key(extension):
            self.reader = self._reader_dict[extension]
        else:
            error('Invalid file extension for file: %s'%value)
            return

        self.reader.file_name = value.strip()
        self.reader.update()
        self.reader.update_information()
        
        if old_reader is not None:
            old_reader.on_trait_change(self.render, remove=True)
        self.reader.on_trait_change(self.render)
        
        old_outputs = self.outputs
        self.outputs = [self.reader.output]
        
        if self.outputs == old_outputs:
            self.data_changed = True

        # Change our name on the tree view
        self.name = self._get_name()
Esempio n. 23
0
 def _choose_filter(self):
     chooser = TVTKFilterChooser()
     chooser.edit_traits(kind='livemodal')
     obj = chooser.object
     if obj is None:
         error('Invalid filter chosen!  Try again!')
     return obj
Esempio n. 24
0
 def save_output(self, fname):
     """Save our output (by default the first of our outputs) to the
     specified filename as a VTK file.  Both old style and new style
     XML files are supported.
     """
     if len(self.outputs) > 0:
         write_data(self.outputs[0], fname)
     else:
         error('Object has no outputs to save!')
Esempio n. 25
0
 def setup_filter(self):
     """Setup the filter if none has been set or check it if it
     already has been."""
     obj = self.filter
     if not self._check_object(obj):
         if obj is not None:
             cname = obj.__class__.__name__
             error('Invalid filter %s chosen!  Try again!'%cname)
         obj = self._choose_filter()
         self.filter = obj
Esempio n. 26
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. 27
0
def open_help_index():
    """ Open the mayavi user manual index in a browser. 
    """
    # If the HTML_DIR was found, bring up the documentation in a
    # web browser.  Otherwise, bring up an error message.
    if HTML_DIR:
        auto_close_message("Opening help in web browser...")
        browser_open(join(HTML_DIR, 'index.html'))
    else:
        error("Could not find the user guide in your installation " \
            "or the source tree.")
Esempio n. 28
0
def open_help_index():
    """ Open the mayavi user manual index in a browser. 
    """
    # If the HTML_DIR was found, bring up the documentation in a
    # web browser.  Otherwise, bring up an error message.
    if HTML_DIR:
        auto_close_message("Opening help in web browser...")
        browser_open(join(HTML_DIR, 'index.html'))
    else:
        error("Could not find the user guide in your installation " \
            "or the source tree.")
Esempio n. 29
0
 def show_engine(self):
     """ Open the engine view corresponding to the engine of the
         scene.
     """
     from enthought.mayavi.core.registry import registry
     from enthought.mayavi.core.ui.engine_rich_view import EngineRichView
     try:
         engine = registry.find_scene_engine(self)
     except TypeError:
         error('This scene is not managed by Mayavi')
     return EngineRichView(engine=engine).scene_editing_view(scene=self)
Esempio n. 30
0
    def show_engine(self):
        """ Open the engine view corresponding to the engine of the
            scene.
        """
        from enthought.mayavi.core.registry import registry
        from enthought.mayavi.core.ui.engine_rich_view import EngineRichView

        try:
            engine = registry.find_scene_engine(self)
        except TypeError:
            error("This scene is not managed by Mayavi")
        return EngineRichView(engine=engine).scene_editing_view(scene=self)
Esempio n. 31
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. 32
0
 def add_filter(self, fil, obj=None):
     """Adds a filter to the pipeline at an appropriate point. Adds it 
     to the selected object, or to an object passed as the 
     kwarg `obj`.
     """
     passed_obj = obj
     if obj is None:
         obj = self.current_object
     if not isinstance(obj, Base):
         msg = 'No valid current object, '\
               'please select an active object.'
         error(msg)
         return
     if (obj is not None) and (not isinstance(obj, Scene)):
         if obj.running:
             obj.add_child(fil)
             self.current_object = fil
         else:
             msg = 'Current object is not active, '\
                   'please select an active object.'
             error(msg)
     else:
         if obj is None:
             error('Please create a VTK scene and open some data first.')
         else:
             error('No data: cannot use a Filter/Module/ModuleManager.')
Esempio n. 33
0
 def add_filter(self, fil, obj=None):
     """Adds a filter to the pipeline at an appropriate point. Adds it 
     to the selected object, or to an object passed as the 
     kwarg `obj`.
     """
     passed_obj = obj
     if obj is None:
         obj = self.current_object
     if not isinstance(obj, Base):
         msg = 'No valid current object, '\
               'please select an active object.'
         error(msg)
         return
     if (obj is not None) and (not isinstance(obj, Scene)):
         if obj.running:
             obj.add_child(fil)
             self.current_object = fil
         else:
             msg = 'Current object is not active, '\
                   'please select an active object.'
             error(msg)
     else:
         if obj is None:
             error('Please create a VTK scene and open some data first.')
         else:
             error('No data: cannot use a Filter/Module/ModuleManager.')
Esempio n. 34
0
 def perform(self, event):
     """ Performs the action. """
     wildcard = 'MayaVi2 files (*.mv2)|*.mv2|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open MayaVi2 file',
                         action='open', wildcard=wildcard
                         )
     if dialog.open() == OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist"%dialog.path, parent)
             return
         
         mv = get_imayavi(self.window)
         mv.load_visualization(dialog.path)
Esempio n. 35
0
 def perform(self):
     """ Performs the action. """
     wildcard = 'HDF files (*.h5)|*.h5|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open CitcomS H5 file',
                         action='open',
                         wildcard=wildcard)
     if dialog.open() == OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist!" % dialog.path, parent)
             return
         from enthought.mayavi.plugins.CitcomS_hdf_file_reader import CitcomSHDFFileReader
         r = CitcomSHDFFileReader()
         r.initialize(dialog.path)
         mv = get_imayavi(self.window)
         mv.add_source(r)
Esempio n. 36
0
 def perform(self):
     """ Performs the action. """
     wildcard = 'HDF5 timestep files (*.*.h5)|*.*.h5|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open CitcomS HDF5 timestep file',
                         action='open', wildcard=wildcard
                         )
     if dialog.open() == OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist!" % dialog.path, parent)
             return
         from citcoms_plugins.plugins.CitcomS_hdf_file_reader import CitcomSHDFFileReader
         r = CitcomSHDFFileReader()
         r.initialize(dialog.path)
         mv = get_imayavi(self.window)
         mv.add_source(r)
Esempio n. 37
0
 def perform(self):
     """ Performs the action. """
     wildcard = 'HDF5 files (*.h5)|*.h5|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open CitcomS HDF5 file',
                         action='open',
                         wildcard=wildcard)
     if dialog.open() == OK:
         if isfile(dialog.path):
             from citcoms_display.plugins.HDF5FileReader import HDF5FileReader
             r = HDF5FileReader()
             r.initialize(dialog.path)
             mv = get_imayavi(self.window)
             mv.add_source(r)
         else:
             error("File '%s' does not exist!" % dialog.path, parent)
     return
Esempio n. 38
0
 def perform(self):
     """Performs the action. """
     wildcard = 'VTK files (*.vtk)|*.vtk|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open CitcomS VTK file',
                         action='open',
                         wildcard=wildcard)
     if dialog.open() == OK:
         if isfile(dialog):
             from citcoms_display.plugins.VTKFileReader import VTKFileReader
             r = VTKFileReader()
             r.initialize(dialog.path)
             mv = get_imayavi(self.window)
             mv.add_source(r)
         else:
             error("File '%s' does not exist!" % dialog.path, parent)
     return
Esempio n. 39
0
    def _setup_current_range(self):
        mm = self.module_manager
        # Set the default name and range for our lut.
        lm = self.lut_manager
        slm = mm.scalar_lut_manager 
        lm.set(default_data_name=slm.default_data_name,
               default_data_range=slm.default_data_range)
        
        # Set the current range.
        input = mm.source.outputs[0]
        sc = input.point_data.scalars
        if sc is not None:
            rng = sc.range
        else:
            error('No scalars in input data!')
            rng = (0, 255)

        if self.current_range != rng:
            self.current_range = rng
Esempio n. 40
0
 def load_lut_from_file(self, file_name):
     lut_list = []
     if len(file_name) > 0:
         try:
             f = open(file_name, 'r')
         except IOError:
             msg = "Cannot open Lookup Table file: %s\n"%file_name
             error(msg)
         else:
             f.close()
             try:
                 lut_list = parse_lut_file(file_name)
             except IOError, err_msg:
                 msg = "Sorry could not parse LUT file: %s\n"%file_name
                 msg += err_msg
                 error(msg)
             else:
                 if self.reverse_lut:
                     lut_list.reverse()
                 self.lut = set_lut(self.lut, lut_list)
                 self.render()
Esempio n. 41
0
 def load_lut_from_file(self, file_name):
     lut_list = []
     if len(file_name) > 0:
         try:
             f = open(file_name, 'r')
         except IOError:
             msg = "Cannot open Lookup Table file: %s\n" % file_name
             error(msg)
         else:
             f.close()
             try:
                 lut_list = parse_lut_file(file_name)
             except IOError, err_msg:
                 msg = "Sorry could not parse LUT file: %s\n" % file_name
                 msg += err_msg
                 error(msg)
             else:
                 if self.reverse_lut:
                     lut_list.reverse()
                 self.lut = set_lut(self.lut, lut_list)
                 self.render()
Esempio n. 42
0
    def add_source(self, src, scene=None):
        """Adds a source to the pipeline. Uses the current scene unless a
        scene is given in the scene keyword argument."""
        passed_scene = scene
        if scene is not None:
            tvtk_scene = scene.scene
            for sc in self.scenes:
                if sc.scene == tvtk_scene:
                    scene = sc
                    break
            else:
                error('This scene is not managed by mayavi')
                return
        else:
            scene = self.current_scene

        # Create a new scene if none is available.
        if scene is None:
            self.new_scene()
            scene = self.current_scene
        scene.add_child(src)
        self.current_object = src
Esempio n. 43
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mod_mgr = self.module_manager
        if mod_mgr is None:
            return

        # Data is available, so set the input for the IPW.
        input = mod_mgr.source.outputs[0]
        if not (input.is_a('vtkStructuredPoints') \
                or input.is_a('vtkImageData')):
            msg = 'ImagePlaneWidget only supports structured points or '\
                  'image data.'
            error(msg)
            raise TypeError, msg

        self.ipw.input = input
        self.setup_lut()
Esempio n. 44
0
    def add_source(self, src, scene=None):
        """Adds a source to the pipeline. Uses the current scene unless a
        scene is given in the scene keyword argument."""
        passed_scene = scene
        if scene is not None:
            tvtk_scene = scene.scene
            for sc in self.scenes:
                if sc.scene == tvtk_scene:
                    scene = sc
                    break
            else:
                error('This scene is not managed by mayavi')
                return
        else:
            scene = self.current_scene

        # Create a new scene if none is available.
        if scene is None:
            self.new_scene()
            scene = self.current_scene
        scene.add_child(src)
        self.current_object = src
Esempio n. 45
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mod_mgr = self.module_manager
        if mod_mgr is None:
            return

        # Data is available, so set the input for the IPW.
        input = mod_mgr.source.outputs[0]
        if not (input.is_a('vtkStructuredPoints') \
                or input.is_a('vtkImageData')):
            msg = 'ImagePlaneWidget only supports structured points or '\
                  'image data.'
            error(msg)
            raise TypeError, msg
            
        self.ipw.input = input
        self.setup_lut()
Esempio n. 46
0
    def open_file_action(self):
        wildcard = 'All files (*.*)|*.*'
        for src in registry.sources:
            if len(src.extensions) > 0:
                if wildcard.endswith('|') or \
                   src.wildcard.startswith('|'):
                       wildcard += src.wildcard
                else:
                    wildcard += '|' + src.wildcard

        dialog = FileDialog(parent=None,
                            title='Open supported data file',
                            action='open', wildcard=wildcard
                            )
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist!"%dialog.path)
                return
            # FIXME: Ask for user input if a filetype is unknown and
            # choose appropriate reader.
            object = self.object
            engine = get_engine(object)
            engine.open(dialog.path, object)
Esempio n. 47
0
 def _update_ranges(self):
     # Here we get the module's source since the input of this
     # component may not in general represent the entire object.
     if not self.auto_update_range:
         return
     src = get_module_source(self.inputs[0])
     sc = src.outputs[0].point_data.scalars
     if sc is not None:
         sc_array = sc.to_array()
         has_nan = numpy.isnan(sc_array).any()
         if has_nan:
             rng = (float(numpy.nanmin(sc_array)),
                    float(numpy.nanmax(sc_array)))
         else:
             rng = sc.range
     else:
         error('Cannot contour: No scalars in input data!')
         rng = (0.0, 1.0)
     if rng != self._current_range:
         self.set(_data_min=rng[0], _data_max=rng[1],
                  trait_change_notify=False)
         self._clip_contours(rng)
         self._current_range = rng
Esempio n. 48
0
 def _update_ranges(self):
     # Here we get the module's source since the input of this
     # component may not in general represent the entire object.
     if not self.auto_update_range:
         return
     src = get_module_source(self.inputs[0])
     sc = src.outputs[0].point_data.scalars
     if sc is not None:
         sc_array = sc.to_array()
         has_nan = numpy.isnan(sc_array).any()
         if has_nan:
             rng = (float(numpy.nanmin(sc_array)),
                    float(numpy.nanmax(sc_array)))
         else:
             rng = sc.range
     else:
         error('Cannot contour: No scalars in input data!')
         rng = (0.0, 1.0)
     if rng != self._current_range:
         self.set(_data_min=rng[0],
                  _data_max=rng[1],
                  trait_change_notify=False)
         self._clip_contours(rng)
         self._current_range = rng
Esempio n. 49
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mod_mgr = self.module_manager
        if mod_mgr is None:
            return

        # Data is available, so set the input for the grid plane.
        input = mod_mgr.source.outputs[0]
        if not input.is_a('vtkUnstructuredGrid'):
            error('SliceUnstructuredGrid only works with input '\
                  'unstructured grids')
        self.implicit_plane.inputs = [mod_mgr.source]
        self.extract_geometry.input = self.module_manager.source.outputs[0]

        # Set the LUT for the mapper.
        self.actor.set_lut(self.module_manager.scalar_lut_manager.lut)

        # Now flush the pipeline
        self.pipeline_changed = True
Esempio n. 50
0
 def _setup_mapper_types(self):
     """Sets up the mapper based on input data types.
     """
     input = self.module_manager.source.outputs[0]
     if input.is_a('vtkUnstructuredGrid'):
         if hasattr(tvtk, 'UnstructuredGridVolumeMapper'):
             check = ['UnstructuredGridVolumeZSweepMapper',
                      'UnstructuredGridVolumeRayCastMapper',
                      ]
             mapper_types = []
             for mapper in check:
                 if mapper in self._available_mapper_types:
                     mapper_types.append(mapper)
             if len(mapper_types) == 0:
                 mapper_types = ['']
             self._mapper_types = mapper_types
             return
     else:
         if input.point_data.scalars.data_type not in \
            [vtkConstants.VTK_UNSIGNED_CHAR,
             vtkConstants.VTK_UNSIGNED_SHORT]:
             if 'FixedPointVolumeRayCastMapper' \
                    in self._available_mapper_types:
                 self._mapper_types = ['FixedPointVolumeRayCastMapper']
             else:
                 error('Available volume mappers only work with \
                 unsigned_char or unsigned_short datatypes')
         else:
             mapper_types = ['TextureMapper2D', 'RayCastMapper']
             check = ['FixedPointVolumeRayCastMapper',
                      'VolumeProMapper'
                      ]
             for mapper in check:
                 if mapper in self._available_mapper_types:
                     mapper_types.append(mapper)
             self._mapper_types = mapper_types
Esempio n. 51
0
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when any of the inputs
        sends a `pipeline_changed` event.
        """
        mod_mgr = self.module_manager
        if mod_mgr is None:
            return

        # Data is available, so set the input for the grid plane.
        input = mod_mgr.source.outputs[0]
        if not input.is_a('vtkUnstructuredGrid'):
            error('SliceUnstructuredGrid only works with input '\
                  'unstructured grids')
        self.implicit_plane.inputs = [mod_mgr.source]
        self.extract_geometry.input = self.module_manager.source.outputs[0]

        # Set the LUT for the mapper.
        self.actor.set_lut(self.module_manager.scalar_lut_manager.lut)
        
        # Now flush the pipeline
        self.pipeline_changed = True
Esempio n. 52
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