Beispiel #1
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__)
Beispiel #2
0
 def perform(self,event):
     """Perform the Save Phantom  Action """
     wildcard = 'MagicalPhantom files (*.mp)|*.mp|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title = 'Open MagicalPhantom file',
                         action = 'open',wildcard = wildcard)
     if dialog.open()==OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist"%dialog.path,parent)
             return
    
     run_manager = self.window.application.get_service('mphantom.api.RunManager')
     
     phantom = run_manager.model
     
    
     
     print dialog.path
             
     phantom.clear_phantom()
     phantom.load_phantom(dialog.path)
     
    
     
     self.window.active_perspective = self.window.perspectives[1]
Beispiel #3
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
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))
Beispiel #5
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
Beispiel #6
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))
Beispiel #7
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])
Beispiel #8
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])
     dataset = self._get_source_dataset(src)
     sc = dataset.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
Beispiel #9
0
def convert_to_poly_data(obj):
    """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 obj.is_a('vtkDataSet'):
        data = obj
    else:
        # FIXME
        data = obj.output

    if obj.is_a('vtkPolyData') or data.is_a('vtkPolyData'):
        return obj


    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:
        configure_input(fil, obj)
        fil.update()
        return fil
    else:
        error('Given object is not a VTK dataset: %s'%data.__class__.__name__)
Beispiel #10
0
    def update_pipeline(self):
        inputs = self.inputs
        if len(inputs) == 0:
            return

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

        for key, klass in mapping.items():
            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
        self.configure_connection(fil, inputs[0])
        fil.update_whole_extent()
        fil.update()
        self._set_outputs([fil])
        self._update_limits()
        self._update_voi()
        self._update_sample_rate()
Beispiel #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 any of the inputs
        sends a `pipeline_changed` event.
        """
        mm = self.module_manager
        if mm is None:
            return


        dataset = mm.source.get_output_dataset()

        ug = hasattr(tvtk, 'UnstructuredGridVolumeMapper')
        if ug:
            if not dataset.is_a('vtkImageData') \
                   and not dataset.is_a('vtkUnstructuredGrid'):
                error('Volume rendering only works with '\
                      'StructuredPoints/ImageData/UnstructuredGrid datasets')
                return
        elif not dataset.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
Beispiel #12
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
Beispiel #13
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__)
Beispiel #14
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.get_output_dataset()
        if not input.is_a('vtkUnstructuredGrid'):
            error('SliceUnstructuredGrid only works with input '\
                  'unstructured grids')
        self.implicit_plane.inputs = [mod_mgr.source]
        src = self.module_manager.source
        self.configure_connection(self.extract_geometry, src)

        # 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
Beispiel #15
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
 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
    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].get_output_dataset()
        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)

        self.configure_connection(plane, self.inputs[0])
        self.plane = plane
        self._update_limits()
        self._update_voi()
        self.outputs = [plane]
Beispiel #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])
    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()
Beispiel #20
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)]
Beispiel #21
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
Beispiel #22
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
Beispiel #23
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))
Beispiel #24
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 polydata reader based on file type
        old_reader = self.reader
        if self._reader_dict.has_key(extension):
            self.reader = self._reader_dict[extension]
        else:
            error('Invalid 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()
    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))
Beispiel #26
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
Beispiel #27
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
Beispiel #28
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
    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.get_output_dataset()
        if not input.is_a('vtkUnstructuredGrid'):
            error('SliceUnstructuredGrid only works with input '\
                  'unstructured grids')
        self.implicit_plane.inputs = [mod_mgr.source]
        src = self.module_manager.source
        self.configure_connection(self.extract_geometry, src)

        # 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
Beispiel #30
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].get_output_dataset()
        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)

        self.configure_connection(plane, self.inputs[0])
        self.plane = plane
        self._update_limits()
        self._update_voi()
        self.outputs = [plane]
Beispiel #31
0
    def _update_reader_output(self):
        r = self.reader
        r.update()

        if r.error_code != 0:
            try:
                self.reader.i_blanking = True
            except AttributeError:
                pass
            else:
                r.update()

        # Try reading file.
        if r.error_code != 0:
            # No output so the file might be an ASCII file.
            try:
                # Turn off IBlanking.
                r.trait_set(i_blanking=False, binary_file=False)
            except AttributeError:
                pass
            else:
                r.update()

        # Try again this time as ascii and with blanking.
        if r.error_code != 0:
            # No output so the file might be an ASCII file.
            try:
                # Turn on IBlanking.
                r.i_blanking = True
            except AttributeError:
                pass
            else:
                r.update()

        # If there still is an error, ask the user.
        if r.error_code != 0:
            r.edit_traits(kind='livemodal')
            r.update()

        # If there still is an error, ask the user to retry.
        if r.error_code != 0:
            msg = 'Unable to read file properly. '\
                  'Please check the settings of the reader '\
                  'on the UI and press the "Update Reader" button '\
                  'when done and try again!'
            error(msg)
            return

        # Now setup the outputs by resetting self.outputs.  Changing
        # the outputs automatically fires a pipeline_changed event.
        self.outputs = [r]

        # Fire data_changed just in case the outputs are not
        # really changed.  This can happen if the dataset is of
        # the same type as before.
        self.data_changed = True

        # Change our name on the tree view
        self.name = self._get_name()
Beispiel #32
0
    def _update_reader_output(self):
        r = self.reader
        r.update()

        if r.error_code != 0:
            try:
                self.reader.i_blanking = True
            except AttributeError:
                pass
            else:
                r.update()

        # Try reading file.
        if r.error_code != 0:
            # No output so the file might be an ASCII file.
            try:
                # Turn off IBlanking.
                r.trait_set(i_blanking=False, binary_file=False)
            except AttributeError:
                pass
            else:
                r.update()

        # Try again this time as ascii and with blanking.
        if r.error_code != 0:
            # No output so the file might be an ASCII file.
            try:
                # Turn on IBlanking.
                r.i_blanking = True
            except AttributeError:
                pass
            else:
                r.update()

        # If there still is an error, ask the user.
        if r.error_code != 0:
            r.edit_traits(kind='livemodal')
            r.update()

        # If there still is an error, ask the user to retry.
        if r.error_code != 0:
            msg = 'Unable to read file properly. '\
                  'Please check the settings of the reader '\
                  'on the UI and press the "Update Reader" button '\
                  'when done and try again!'
            error(msg)
            return

        # Now setup the outputs by resetting self.outputs.  Changing
        # the outputs automatically fires a pipeline_changed event.
        self.outputs = [r]

        # Fire data_changed just in case the outputs are not
        # really changed.  This can happen if the dataset is of
        # the same type as before.
        self.data_changed = True

        # Change our name on the tree view
        self.name = self._get_name()
Beispiel #33
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.get_output_dataset(), fname)
     else:
         error('Object has no outputs to save!')
 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.get_output_dataset(), fname)
     else:
         error('Object has no outputs to save!')
Beispiel #35
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
 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
Beispiel #37
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))
Beispiel #38
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.")
 def show_engine(self):
     """ Open the engine view corresponding to the engine of the
         scene.
     """
     from mayavi.core.registry import registry
     from 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)
Beispiel #40
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.')
Beispiel #41
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.')
    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))
    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)
Beispiel #44
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)
Beispiel #45
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])
     dsh = DataSetHelper(src.outputs[0])
     name, rng = dsh.get_range('scalars', 'point')
     if name is None:
         error('Cannot contour: No scalars in input data!')
         rng = (0.0, 1.0)
     if rng != self._current_range:
         self.trait_set(_data_min=rng[0], _data_max=rng[1],
                        trait_change_notify=False)
         self._clip_contours(rng)
         self._current_range = rng
 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])
     dsh = DataSetHelper(src.outputs[0])
     name, rng = dsh.get_range('scalars', 'point')
     if name is None:
         error('Cannot contour: No scalars in input data!')
         rng = (0.0, 1.0)
     if rng != self._current_range:
         self.trait_set(_data_min=rng[0],
                        _data_max=rng[1],
                        trait_change_notify=False)
         self._clip_contours(rng)
         self._current_range = rng
Beispiel #47
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.trait_set(default_data_name=slm.default_data_name,
                     default_data_range=slm.default_data_range)

        # Set the current range.
        dataset = mm.source.get_output_dataset()
        dsh = DataSetHelper(dataset)
        name, rng = dsh.get_range('scalars', 'point')
        if name is None:
            error('No scalars in input data!')
            rng = (0, 255)

        if self.current_range != rng:
            self.current_range = rng
Beispiel #48
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.trait_set(default_data_name=slm.default_data_name,
                     default_data_range=slm.default_data_range)

        # Set the current range.
        dataset = mm.source.get_output_dataset()
        dsh = DataSetHelper(dataset)
        name, rng = dsh.get_range('scalars', 'point')
        if name is None:
            error('No scalars in input data!')
            rng = (0, 255)

        if self.current_range != rng:
            self.current_range = rng
Beispiel #49
0
 def _setup_mapper_types(self):
     """Sets up the mapper based on input data types.
     """
     dataset = self.module_manager.source.get_output_dataset()
     if dataset.is_a('vtkMultiBlockDataSet'):
         if 'MultiBlockVolumeMapper' in self._available_mapper_types:
             self._mapper_types = ['MultiBlockVolumeMapper']
     elif dataset.is_a('vtkUniformGridAMR'):
         if 'AMRVolumeMapper' not in self._available_mapper_types:
             self._mapper_types = ['AMRVolumeMapper']
     elif dataset.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:
         mapper_types = self._get_image_data_volume_mappers()
         if dataset.point_data.scalars.data_type not in \
            [vtkConstants.VTK_UNSIGNED_CHAR,
             vtkConstants.VTK_UNSIGNED_SHORT]:
             if 'FixedPointVolumeRayCastMapper' \
                    in self._available_mapper_types:
                 mapper_types.append('FixedPointVolumeRayCastMapper')
             elif len(mapper_types) == 0:
                 error('Available volume mappers only work with '
                       'unsigned_char or unsigned_short datatypes')
         else:
             check = [
                 'FixedPointVolumeRayCastMapper', 'VolumeProMapper',
                 'TextureMapper2D', 'RayCastMapper', 'TextureMapper3D'
             ]
             for mapper in check:
                 if mapper in self._available_mapper_types:
                     mapper_types.append(mapper)
         self._mapper_types = mapper_types
Beispiel #50
0
 def _setup_mapper_types(self):
     """Sets up the mapper based on input data types.
     """
     dataset = self.module_manager.source.get_output_dataset()
     if dataset.is_a('vtkMultiBlockDataSet'):
         if 'MultiBlockVolumeMapper' in self._available_mapper_types:
             self._mapper_types = ['MultiBlockVolumeMapper']
     elif dataset.is_a('vtkUniformGridAMR'):
         if 'AMRVolumeMapper' not in self._available_mapper_types:
             self._mapper_types = ['AMRVolumeMapper']
     elif dataset.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:
         mapper_types = self._get_image_data_volume_mappers()
         if dataset.point_data.scalars.data_type not in \
            [vtkConstants.VTK_UNSIGNED_CHAR,
             vtkConstants.VTK_UNSIGNED_SHORT]:
             if 'FixedPointVolumeRayCastMapper' \
                    in self._available_mapper_types:
                 mapper_types.append('FixedPointVolumeRayCastMapper')
             elif len(mapper_types) == 0:
                 error('Available volume mappers only work with '
                       'unsigned_char or unsigned_short datatypes')
         else:
             check = ['FixedPointVolumeRayCastMapper',
                      'VolumeProMapper', 'TextureMapper2D', 'RayCastMapper',
                      'TextureMapper3D'
                      ]
             for mapper in check:
                 if mapper in self._available_mapper_types:
                     mapper_types.append(mapper)
         self._mapper_types = mapper_types
Beispiel #51
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)
Beispiel #52
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.
        dataset = mm.source.get_output_dataset()
        sc = dataset.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
Beispiel #53
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
Beispiel #54
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."""
        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
Beispiel #55
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 as 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()
Beispiel #56
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()