Example #1
0
 def render(self):
     """Invokes render on the scene, this in turn invokes Render on
     the VTK pipeline.
     """
     s = self.scene
     if s is not None:
         s.render()
     elif self.running:
         # If there is no scene and we are running, we flush the
         # pipeline manually by calling update.
         for actor in self.actors:
             if hasattr(actor, 'mapper'):
                 m = actor.mapper
                 if m is not None:
                     if tvtk_common.is_old_pipeline():
                         m.update()
                     else:
                         m.update(0)
         if tvtk_common.is_old_pipeline():
             for widget in self.widgets:
                 if hasattr(widget, 'input'):
                     input = widget.input
                     if input is not None:
                         input.update()
     if hasattr(self, 'components'):
         for component in self.components:
                 component.render()
Example #2
0
        def surf_fill2(vertices, polys, mat, shape):
            from tvtk.common import is_old_pipeline
            voxverts = nibabel.affines.apply_affine(numpy.linalg.inv(mat), vertices)

            pd = tvtk.PolyData(points=voxverts, polys=polys)

            if is_old_pipeline():
                whiteimg = tvtk.ImageData(dimensions = shape, scalar_type = 'unsigned_char')
            else:
                whiteimg = tvtk.ImageData(dimensions = shape)
            whiteimg.point_data.scalars = numpy.ones(numpy.prod(shape), dtype=numpy.uint8)

            pdtis = tvtk.PolyDataToImageStencil()
            if is_old_pipeline():
                pdtis.input = pd
            else:
                pdtis.set_input_data(pd)
                                                                             
            pdtis.output_whole_extent = whiteimg.extent
            pdtis.update()

            imgstenc = tvtk.ImageStencil()
            if is_old_pipeline():
                imgstenc.input = whiteimg
                imgstenc.stencil = pdtis.output
            else:
                imgstenc.set_input_data(whiteimg)
            imgstenc.set_stencil_data(pdtis.output)
            imgstenc.background_value = 0
            imgstenc.update()

            data = imgstenc.output.point_data.scalars.to_array().reshape(shape[::-1]).transpose(2,1,0)
            return data
Example #3
0
 def render(self):
     """Invokes render on the scene, this in turn invokes Render on
     the VTK pipeline.
     """
     s = self.scene
     if s is not None:
         s.render()
     elif self.running:
         # If there is no scene and we are running, we flush the
         # pipeline manually by calling update.
         for actor in self.actors:
             if hasattr(actor, 'mapper'):
                 m = actor.mapper
                 if m is not None:
                     if tvtk_common.is_old_pipeline():
                         m.update()
                     else:
                         m.update(0)
         if tvtk_common.is_old_pipeline():
             for widget in self.widgets:
                 if hasattr(widget, 'input'):
                     input = widget.input
                     if input is not None:
                         input.update()
     if hasattr(self, 'components'):
         for component in self.components:
             component.render()
Example #4
0
def _poly_data_to_volume(data, voxel_size, margins):
    """
    Render the given, closed <tvtk.PolyData> into an image volume and return it
    as a Numpy array.
    """
    # Following [*] for the necessary steps.
    #
    # References
    # [*] http://www.paraview.org/Wiki/VTK/Examples/Cxx/PolyData/PolyDataToImageData (20150710)

    # Calculate the necessary number of voxels, extent, and origin
    bounds = np.array(data.bounds)
    n_vox = np.ceil(
        (bounds[1::2] - bounds[0::2] + np.sum(margins.reshape(2, 3), axis=0)) /
        voxel_size).astype(np.int)

    extent = [0, n_vox[0] - 1, 0, n_vox[1] - 1, 0, n_vox[2] - 1]
    origin = bounds[0::2] - margins[:3] + 0.5 * voxel_size

    # Create the image volume
    volume = tvtk.ImageData(spacing=voxel_size,
                            dimensions=n_vox,
                            extent=extent,
                            origin=origin)
    if is_old_pipeline():
        volume.scalar_type = "unsigned_char"
    voxel_data = (np.ones(n_vox, dtype=np.uint8) * 100).ravel()
    volume.point_data.scalars = voxel_data
    if is_old_pipeline():
        volume.update()

    # Actual transformation from polygon to image data
    voxelizer = tvtk.PolyDataToImageStencil(output_origin=origin,
                                            output_spacing=voxel_size,
                                            output_whole_extent=volume.extent,
                                            tolerance=0.0)
    configure_input(voxelizer, data)
    voxelizer.update()

    # Draw the result to a new image, extract Numpy array and return
    painter = tvtk.ImageStencil(reverse_stencil=False, background_value=0)
    configure_input(painter, volume)
    if is_old_pipeline():
        painter.stencil = voxelizer.output
    else:
        painter.set_stencil_connection(voxelizer.output_port)
    painter.update()
    voxel_data = painter.output.point_data.scalars.to_array().reshape(
        n_vox[::-1])
    voxel_data = np.transpose(voxel_data, [2, 1, 0])
    return voxel_data
Example #5
0
    def _scalar_data_changed(self, data):
        img_data = self.image_data
        if data is None:
            img_data.point_data.scalars = None
            self.data_changed = True
            return
        dims = list(data.shape)
        if len(dims) == 2:
            dims.append(1)

        # set the dimension indices
        dim0, dim1, dim2 = self.dimensions_order

        img_data.origin = tuple(self.origin)
        img_data.dimensions = tuple(dims)
        img_data.extent = 0, dims[dim0] - 1, 0, dims[dim1] - 1, 0, dims[
            dim2] - 1
        if VTK_MAJOR_VERSION <= 7:
            if is_old_pipeline():
                img_data.update_extent = 0, dims[dim0] - 1, 0, dims[
                    dim1] - 1, 0, dims[dim2] - 1
            else:
                update_extent = [
                    0, dims[dim0] - 1, 0, dims[dim1] - 1, 0, dims[dim2] - 1
                ]
                self.change_information_filter.set_update_extent(update_extent)
        if self.transpose_input_array:
            img_data.point_data.scalars = numpy.ravel(numpy.transpose(data))
        else:
            img_data.point_data.scalars = numpy.ravel(data)
        img_data.point_data.scalars.name = self.scalar_name
        # This is very important and if not done can lead to a segfault!
        typecode = data.dtype
        if is_old_pipeline():
            img_data.scalar_type = array_handler.get_vtk_array_type(typecode)
            img_data.update()  # This sets up the extents correctly.
        else:
            filter_out_info = self.change_information_filter.get_output_information(
                0)
            img_data.set_point_data_active_scalar_info(
                filter_out_info, array_handler.get_vtk_array_type(typecode),
                -1)
            img_data.modified()
        img_data.update_traits()
        self.change_information_filter.update()

        # Now flush the mayavi pipeline.
        self.data_changed = True
Example #6
0
 def __deepcopy__(self, memo):
     """Method used by copy.deepcopy().  This also uses the
     state_pickler to work correctly.
     """
     # Create a new instance.
     new = self.__class__()
     # If we have a saved state, use it for the new instance.  If
     # not, get our state and save that.
     saved_state = self._saved_state
     if len(saved_state) == 0:
         state = state_pickler.get_state(self)
         #FIXME: This is for streamline seed point widget position which
         #does not get serialized correctly
         if not is_old_pipeline():
             try:
                 st = state.children[0].children[4]
                 l_pos = st.seed.widget.position
                 st.seed.widget.position = [pos.item() for pos in l_pos]
             except (IndexError, AttributeError):
                 pass
         saved_state = pickle.dumps(state)
     new._saved_state = saved_state
     # In the unlikely case that a new instance is running, load
     # the saved state.
     if new.running:
         new._load_saved_state()
     return new
Example #7
0
 def _update_probe(self):
     pd = self.probe_data
     dims = self.dimensions
     spacing = self.spacing
     extent = (0, dims[0] -1, 0, dims[1] -1, 0, dims[2] -1)
     if tvtk_common.is_old_pipeline():
         pd.set(extent=extent,
                update_extent=extent,
                whole_extent=extent,
                dimensions=dims,
                spacing=spacing)
     else:
         pd.set(extent=extent,
                dimensions=dims,
                spacing=spacing)
     pd.modified()
     fil = self.filter
     w = fil.global_warning_display
     fil.global_warning_display = False
     fil.remove_all_inputs()
     self.configure_input_data(fil, pd)
     fil.update_whole_extent()
     fil.update()
     self._rescale_scalars_changed(self.rescale_scalars)
     fil.global_warning_display = w
     self.data_changed = True
Example #8
0
    def test_change(self):
        s = self.scene
        src = s.children[0]
        ot = src.children[0].children[0]
        src.source = 'gaussian'

        # Check with the default properties of gaussian image to verify
        # that the source has actually changed
        self.assertEqual(src.source, 'gaussian')
        self.assertEqual(numpy.allclose(src.data_source.center, (0., 0., 0.)),
                         True)
        self.assertEqual(src.data_source.maximum, 1.0)
        self.assertEqual(src.data_source.standard_deviation, 100)

        # Check the scalar ranges
        self.assertEqual(
            numpy.allclose(src.outputs[0].output.point_data.scalars.range,
                           (0.00149, 1.0),
                           atol=1.01e-03), True)

        src.data_source.maximum = 2.0
        src.data_source.standard_deviation = 15
        if not is_old_pipeline():
            src.data_source.update()
        self.check()
    def _set_data_name(self, data_type, attr_type, value):
        if value is None:
            return

        dataset = self.data
        if len(value) == 0:
            # If the value is empty then we deactivate that attribute.
            d = getattr(dataset, attr_type + '_data')
            method = getattr(d, 'set_active_%s' % data_type)
            method(None)
            self.data_changed = True
            return

        aa = self._assign_attribute
        data = None
        if attr_type == 'point':
            data = dataset.point_data
        elif attr_type == 'cell':
            data = dataset.cell_data
        method = getattr(data, 'set_active_%s' % data_type)
        method(value)
        aa.assign(value, data_type.upper(), attr_type.upper() + '_DATA')
        if data_type == 'scalars' and dataset.is_a('vtkImageData'):
            # Set the scalar_type for image data, if not you can either
            # get garbage rendered or worse.
            s = getattr(dataset, attr_type + '_data').scalars
            r = s.range
            if is_old_pipeline():
                dataset.scalar_type = s.data_type
                aa.output.scalar_type = s.data_type
        aa.update()
        # Fire an event, so the changes propagate.
        self.data_changed = True
Example #10
0
    def setUp(self):

        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        # e = Engine()
        e.start()
        s = e.new_scene()

        image_data = BuiltinImage()
        e.add_source(image_data)

        outline = Outline()
        e.add_module(outline)

        surface = Surface()
        e.add_module(surface)

        image_data.data_source.radius = array([80.0, 80.0, 80.0])
        image_data.data_source.center = array([150.0, 150.0, 0.0])
        image_data.data_source.whole_extent = array([10, 245, 10, 245, 0, 0])
        if is_old_pipeline():
            image_data.data_source.update_whole_extent()
        else:
            image_data.data_source.set_update_extent_to_whole_extent()

        self.e = e
        self.scene = e.current_scene

        return
Example #11
0
    def setUp(self):

        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        s=e.new_scene()

        image_data = BuiltinImage()
        e.add_source(image_data)

        outline = Outline()
        e.add_module(outline)

        surface = Surface()
        e.add_module(surface)

        image_data.data_source.radius = array([ 80.,  80.,  80.])
        image_data.data_source.center = array([ 150.,  150.,    0.])
        image_data.data_source.whole_extent = array([ 10, 245,  10, 245,   0,   0])
        if is_old_pipeline():
            image_data.data_source.update_whole_extent()
        else:
            image_data.data_source.set_update_extent_to_whole_extent()

        self.e=e
        self.scene = e.current_scene

        return
Example #12
0
    def _set_data_name(self, data_type, attr_type, value):
        if value is None:
            return

        dataset = self.data
        if len(value) == 0:
            # If the value is empty then we deactivate that attribute.
            d = getattr(dataset, attr_type + '_data')
            method = getattr(d, 'set_active_%s'%data_type)
            method(None)
            self.data_changed = True
            return

        aa = self._assign_attribute
        data = None
        if attr_type == 'point':
            data = dataset.point_data
        elif attr_type == 'cell':
            data = dataset.cell_data
        method = getattr(data, 'set_active_%s'%data_type)
        method(value)
        aa.assign(value, data_type.upper(), attr_type.upper() +'_DATA')
        if data_type == 'scalars' and dataset.is_a('vtkImageData'):
            # Set the scalar_type for image data, if not you can either
            # get garbage rendered or worse.
            s = getattr(dataset, attr_type + '_data').scalars
            r = s.range
            if is_old_pipeline():
                dataset.scalar_type = s.data_type
                aa.output.scalar_type = s.data_type
        aa.update()
        # Fire an event, so the changes propagate.
        self.data_changed = True
    def _setup_probe_data(self, reset=False):
        pd = self.probe_data
        input = self.inputs[0].get_output_dataset()
        if input.is_a('vtkImageData'):
            self.allow_changes = False
            self.trait_set(spacing=input.spacing, dimensions=input.dimensions)
            pd.trait_set(origin=input.origin,
                         dimensions=input.dimensions,
                         spacing=input.spacing)
            pd.update()
        elif reset:
            self.allow_changes = True
            b = numpy.array(input.bounds)
            pd.origin = b[::2]
            l = b[1::2] - b[::2]
            tot_len = sum(l)
            npnt = pow(input.number_of_points, 1. / 3.) + 0.5
            fac = 3.0 * npnt / tot_len
            dims = (l * fac).astype(int) + 1
            extent = (0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
            if tvtk_common.is_old_pipeline():
                pd.trait_set(extent=extent,
                             update_extent=extent,
                             whole_extent=extent,
                             dimensions=dims)
            else:
                pd.trait_set(extent=extent, dimensions=dims)

            max_dim = dims.max()
            dims = (dims - 1).clip(min=1, max=max_dim + 1)
            l = l.clip(min=1e-3, max=l.max() + 1.0)
            pd.spacing = l / dims
            self._event_handled = True
            self.trait_set(spacing=pd.spacing, dimensions=pd.dimensions)
            self._event_handled = False
Example #14
0
 def save_visualization(self, file_or_fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     # Save the state of VTK's global warning display.
     o = vtk.vtkObject
     w = o.GetGlobalWarningDisplay()
     o.SetGlobalWarningDisplay(0) # Turn it off.
     try:
         #FIXME: This is for streamline seed point widget position which
         #does not get serialized correctly
         if is_old_pipeline():
             state_pickler.dump(self, file_or_fname)
         else:
             state = state_pickler.get_state(self)
             st = state.scenes[0].children[0].children[0].children[4]
             l_pos = st.seed.widget.position
             st.seed.widget.position = [pos.item() for pos in l_pos]
             saved_state = state_pickler.dumps(state)
             file_or_fname.write(saved_state)
     except (IndexError, AttributeError):
         state_pickler.dump(self, file_or_fname)
     finally:
         # Reset the warning state.
         o.SetGlobalWarningDisplay(w)
Example #15
0
 def save_visualization(self, file_or_fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     # Save the state of VTK's global warning display.
     o = vtk.vtkObject
     w = o.GetGlobalWarningDisplay()
     o.SetGlobalWarningDisplay(0) # Turn it off.
     try:
         #FIXME: This is for streamline seed point widget position which
         #does not get serialized correctly
         if is_old_pipeline():
             state_pickler.dump(self, file_or_fname)
         else:
             state = state_pickler.get_state(self)
             st = state.scenes[0].children[0].children[0].children[4]
             l_pos = st.seed.widget.position
             st.seed.widget.position = [pos.item() for pos in l_pos]
             saved_state = state_pickler.dumps(state)
             file_or_fname.write(saved_state)
     except (IndexError, AttributeError):
         state_pickler.dump(self, file_or_fname)
     finally:
         # Reset the warning state.
         o.SetGlobalWarningDisplay(w)
Example #16
0
 def __deepcopy__(self, memo):
     """Method used by copy.deepcopy().  This also uses the
     state_pickler to work correctly.
     """
     # Create a new instance.
     new = self.__class__()
     # If we have a saved state, use it for the new instance.  If
     # not, get our state and save that.
     saved_state = self._saved_state
     if len(saved_state) == 0:
         state = state_pickler.get_state(self)
         # FIXME: This is for streamline seed point widget position which
         # does not get serialized correctly
         if not is_old_pipeline():
             try:
                 st = state.children[0].children[4]
                 l_pos = st.seed.widget.position
                 st.seed.widget.position = [pos.item() for pos in l_pos]
             except (IndexError, AttributeError):
                 pass
         saved_state = cPickle.dumps(state)
     new._saved_state = saved_state
     # In the unlikely case that a new instance is running, load
     # the saved state.
     if new.running:
         new._load_saved_state()
     return new
    def test_ipw(self):
        """Test the image plane widget."""
        arr1, arr2, arr3 = self.first, self.second, self.third
        ipw = self.ipw.ipw

        scalars = ipw.input.point_data.scalars

        r = scalars.range
        expect = min(arr1), max(arr1)
        self.assertEqual(r, expect)
        o = self.src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 10)
        self.assertEqual(st, 'float')

        self.src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        self.assertEqual(r, expect)
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 11)
        self.assertEqual(st, 'double')

        self.src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        self.assertEqual(r, expect)
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 10)
        self.assertEqual(st, 'float')
    def test_ipw(self):
        """Test the image plane widget."""
        arr1, arr2, arr3 = self.first, self.second, self.third
        ipw = self.ipw.ipw
        
        scalars = ipw.input.point_data.scalars

        r = scalars.range
        expect = min(arr1), max(arr1)
        self.assertEqual(r, expect)
        o = self.src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 10)
        self.assertEqual(st, 'float')

        self.src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        self.assertEqual(r, expect)
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 11)
        self.assertEqual(st, 'double')

        self.src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        self.assertEqual(r, expect)
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
        else:
            st = ipw.input.scalar_type_as_string
        self.assertEqual(scalars.data_type, 10)
        self.assertEqual(st, 'float')
Example #19
0
    def _scalar_data_changed(self, data):
        img_data = self.image_data
        if data is None:
            img_data.point_data.scalars = None
            self.data_changed = True
            return
        dims = list(data.shape)
        if len(dims) == 2:
            dims.append(1)

        # set the dimension indices
        dim0, dim1, dim2 = self.dimensions_order

        img_data.origin = tuple(self.origin)
        img_data.dimensions = tuple(dims)
        img_data.extent = 0, dims[dim0]-1, 0, dims[dim1]-1, 0, dims[dim2]-1
        if VTK_MAJOR_VERSION <= 7:
            if is_old_pipeline():
                img_data.update_extent = 0, dims[dim0]-1, 0, dims[dim1]-1, 0, dims[dim2]-1
            else:
                update_extent = [0, dims[dim0]-1, 0, dims[dim1]-1, 0, dims[dim2]-1]
                self.change_information_filter.set_update_extent(update_extent)
        if self.transpose_input_array:
            img_data.point_data.scalars = np.ravel(np.transpose(data))
        else:
            img_data.point_data.scalars = np.ravel(data)
        img_data.point_data.scalars.name = self.scalar_name
        # This is very important and if not done can lead to a segfault!
        typecode = data.dtype
        if is_old_pipeline():
            img_data.scalar_type = get_vtk_array_type(typecode)
            img_data.update() # This sets up the extents correctly.
        else:
            filter_out_info = self.change_information_filter.get_output_information(0)
            img_data.set_point_data_active_scalar_info(filter_out_info,
                                                       get_vtk_array_type(typecode), -1)
            img_data.modified()
        img_data.update_traits()
        self.change_information_filter.update()

        # Now flush the mayavi pipeline.
        self.data_changed = True
Example #20
0
 def _manual_bounds_changed(self):
     if self.manual_bounds:
         if is_old_pipeline():
             self.outline_filter.input = self.outline_source.output
         else:
             self.outline_filter.input_connection = self.outline_source.output_port
     else:
         # Set the input of the filter.
         mm = self.module_manager
         self.configure_connection(self.outline_filter, mm.source)
     self.render()
Example #21
0
 def _update_limits(self):
     if is_old_pipeline():
         extents = self.filter.input.whole_extent
     else:
         extents = self.filter.get_update_extent()
     self._x_low, self._x_high = extents[:2]
     self._y_low, self._y_high = extents[2:4]
     self._z_low, self._z_high = extents[4:]
     self._x_s_high = max(1, self._x_high)
     self._y_s_high = max(1, self._y_high)
     self._z_s_high = max(1, self._z_high)
Example #22
0
 def _manual_bounds_changed(self):
     if self.manual_bounds:
         if is_old_pipeline():
             self.outline_filter.input = self.outline_source.output
         else:
             self.outline_filter.input_connection = self.outline_source.output_port
     else:
         # Set the input of the filter.
         mm = self.module_manager
         self.configure_connection(self.outline_filter, mm.source)
     self.render()
    def _vector_data_changed(self, data):
        img_data = self.image_data
        if data is None:
            img_data.point_data.vectors = None
            self.data_changed = True
            return
        dims = list(data.shape)
        if len(dims) == 3:
            dims.insert(2, 1)
            data = np.reshape(data, dims)

        img_data.origin = tuple(self.origin)
        img_data.dimensions = tuple(dims[:-1])
        img_data.extent = 0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1
        if VTK_MAJOR_VERSION <= 7:
            if is_old_pipeline():
                img_data.update_extent = 0, dims[0] - 1, 0, dims[
                    1] - 1, 0, dims[2] - 1
            else:
                self.change_information_filter.update_information()
                update_extent = [
                    0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1
                ]
                self.change_information_filter.set_update_extent(update_extent)
        sz = np.size(data)
        if self.transpose_input_array:
            data_t = np.transpose(data, (2, 1, 0, 3))
        else:
            data_t = data
        img_data.point_data.vectors = np.reshape(data_t, (sz // 3, 3))
        img_data.point_data.vectors.name = self.vector_name
        if is_old_pipeline():
            img_data.update()  # This sets up the extents correctly.
        else:
            img_data.modified()
        img_data.update_traits()
        self.change_information_filter.update()

        # Now flush the mayavi pipeline.
        self.data_changed = True
    def setUp(self):
        """Initial setting up of test fixture, automatically called by
        TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        s=e.new_scene()
        self.e=e
        self.s=s

        ############################################################
        # Create a new scene and set up the visualization.

        #Make the grid
        grid = self.make_grid4scatter()
        e.add_source(grid)

        eg = ExtractGrid()
        e.add_filter(eg)

        nb_ticks = 6

        eg.x_ratio = eg.y_ratio = eg.z_ratio = 100/(nb_ticks-1)/2

        gpx = GridPlane()
        e.add_module(gpx)
        gpx.grid_plane.axis = 'x'

        gpy = GridPlane()
        e.add_module(gpy)
        gpy.grid_plane.axis = 'y'

        gpz = GridPlane()
        e.add_module(gpz)
        gpz.grid_plane.axis = 'z'

        #Add the scatter
        d = VTKDataSource()
        d.data = self.make_scatter()
        e.add_source(d)
        if is_old_pipeline():
            a = Axes()
            e.add_module(a)
            a.axes.number_of_labels = nb_ticks

        self.eg = eg
        self.gpx = gpx
        self.gpy = gpy
        self.gpz = gpz
        self.scene = e.current_scene
        return
    def setUp(self):
        """Initial setting up of test fixture, automatically called by
        TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        s = e.new_scene()
        self.e = e
        self.s = s

        ############################################################
        # Create a new scene and set up the visualization.

        #Make the grid
        grid = self.make_grid4scatter()
        e.add_source(grid)

        eg = ExtractGrid()
        e.add_filter(eg)

        nb_ticks = 6

        eg.x_ratio = eg.y_ratio = eg.z_ratio = 100 / (nb_ticks - 1) / 2

        gpx = GridPlane()
        e.add_module(gpx)
        gpx.grid_plane.axis = 'x'

        gpy = GridPlane()
        e.add_module(gpy)
        gpy.grid_plane.axis = 'y'

        gpz = GridPlane()
        e.add_module(gpz)
        gpz.grid_plane.axis = 'z'

        #Add the scatter
        d = VTKDataSource()
        d.data = self.make_scatter()
        e.add_source(d)
        if is_old_pipeline():
            a = Axes()
            e.add_module(a)
            a.axes.number_of_labels = nb_ticks

        self.eg = eg
        self.gpx = gpx
        self.gpy = gpy
        self.gpz = gpz
        self.scene = e.current_scene
        return
Example #26
0
    def __reader_dict_default(self):
        """Default value for reader dict."""
        if is_old_pipeline():
            rd = {'inp':tvtk.AVSucdReader(),
                 'neu':tvtk.GAMBITReader(),
                 'exii':tvtk.ExodusReader()
                }
        else:
            rd = {'inp':tvtk.AVSucdReader(),
                 'neu':tvtk.GAMBITReader(),
                 'ex2':tvtk.ExodusIIReader()
                }

        return rd
Example #27
0
    def __reader_dict_default(self):
        """Default value for reader dict."""
        if is_old_pipeline():
            rd = {'inp':tvtk.AVSucdReader(),
                 'neu':tvtk.GAMBITReader(),
                 'exii':tvtk.ExodusReader()
                }
        else:
            rd = {'inp':tvtk.AVSucdReader(),
                 'neu':tvtk.GAMBITReader(),
                 'ex2':tvtk.ExodusIIReader()
                }

        return rd
Example #28
0
    def _vector_data_changed(self, data):
        img_data = self.image_data
        if data is None:
            img_data.point_data.vectors = None
            self.data_changed = True
            return
        dims = list(data.shape)
        if len(dims) == 3:
            dims.insert(2, 1)
            data = np.reshape(data, dims)

        img_data.origin = tuple(self.origin)
        img_data.dimensions = tuple(dims[:-1])
        img_data.extent = 0, dims[0]-1, 0, dims[1]-1, 0, dims[2]-1
        if VTK_MAJOR_VERSION <= 7:
            if is_old_pipeline():
                img_data.update_extent = 0, dims[0]-1, 0, dims[1]-1, 0, dims[2]-1
            else:
                self.change_information_filter.update_information()
                update_extent = [0, dims[0]-1, 0, dims[1]-1, 0, dims[2]-1]
                self.change_information_filter.set_update_extent(update_extent)
        sz = np.size(data)
        if self.transpose_input_array:
            data_t = np.transpose(data, (2, 1, 0, 3))
        else:
            data_t = data
        img_data.point_data.vectors = np.reshape(data_t, (sz//3, 3))
        img_data.point_data.vectors.name = self.vector_name
        if is_old_pipeline():
            img_data.update() # This sets up the extents correctly.
        else:
            img_data.modified()
        img_data.update_traits()
        self.change_information_filter.update()

        # Now flush the mayavi pipeline.
        self.data_changed = True
Example #29
0
def _apply_mask(volume_data, mask_data):
    """ Mask out a portion of the data.
    """
    mask_image_data = _image_data_from_array(mask_data, volume_data.spacing)
    masker = tvtk.ImageMask()
    if is_old_pipeline():
        masker.set_image_input(volume_data)
        masker.set_mask_input(mask_image_data)
    else:
        masker.set_image_input_data(volume_data)
        masker.set_mask_input_data(mask_image_data)
    masker.update()
    result = masker.output
    result.point_data.scalars.name = POINT_DATA_SCALARS_NAME
    return masker.output
 def make_grid4scatter(self):
     src = VTKDataSource()
     xmin, xmax, dx = 100, 200, 2
     nx = int((xmax-xmin)/dx)+1
     ymin, ymax, dy = 100, 200, 2
     ny = int((ymax-ymin)/dy)+1
     zmin, zmax, dz = 100, 200, 2
     nz  = int((zmax-zmin)/dz)+1
     image_data = tvtk.ImageData(origin=(xmin, ymin, zmin),
                                 spacing=(dx, dy, dz),
                                 extent=(0, nx-1, 0, ny-1, 0, nz-1))
     if is_old_pipeline():
         image_data.whole_extent = image_data.extent
     src.data = image_data
     return src
Example #31
0
def _apply_mask(volume_data, mask_data):
    """ Mask out a portion of the data.
    """
    mask_image_data = _image_data_from_array(mask_data, volume_data.spacing)
    masker = tvtk.ImageMask()
    if is_old_pipeline():
        masker.set_image_input(volume_data)
        masker.set_mask_input(mask_image_data)
    else:
        masker.set_image_input_data(volume_data)
        masker.set_mask_input_data(mask_image_data)
    masker.update()
    result = masker.output
    result.point_data.scalars.name = POINT_DATA_SCALARS_NAME
    return masker.output
 def make_grid4scatter(self):
     src = VTKDataSource()
     xmin, xmax, dx = 100, 200, 2
     nx = int((xmax - xmin) / dx) + 1
     ymin, ymax, dy = 100, 200, 2
     ny = int((ymax - ymin) / dy) + 1
     zmin, zmax, dz = 100, 200, 2
     nz = int((zmax - zmin) / dz) + 1
     image_data = tvtk.ImageData(origin=(xmin, ymin, zmin),
                                 spacing=(dx, dy, dz),
                                 extent=(0, nx - 1, 0, ny - 1, 0, nz - 1))
     if is_old_pipeline():
         image_data.whole_extent = image_data.extent
     src.data = image_data
     return src
Example #33
0
    def _update_data(self):
        if self.data is None:
            return
        pnt_attr, cell_attr = get_all_attributes(self.data)

        pd = self.data.point_data
        scalars = pd.scalars
        if self.data.is_a('vtkImageData') and scalars is not None:
            # For some reason getting the range of the scalars flushes
            # the data through to prevent some really strange errors
            # when using an ImagePlaneWidget.
            r = scalars.range
            if is_old_pipeline():
                self._assign_attribute.output.scalar_type = scalars.data_type
                self.data.scalar_type = scalars.data_type

        def _setup_data_traits(obj, attributes, d_type):
            """Given the object, the dict of the attributes from the
            `get_all_attributes` function and the data type
            (point/cell) data this will setup the object and the data.
            """
            attrs = ['scalars', 'vectors', 'tensors']
            aa = obj._assign_attribute
            data = getattr(obj.data, '%s_data' % d_type)
            for attr in attrs:
                values = attributes[attr]
                values.append('')
                setattr(obj, '_%s_%s_list' % (d_type, attr), values)
                if len(values) > 1:
                    default = getattr(obj, '%s_%s_name' % (d_type, attr))
                    if obj._first and len(default) == 0:
                        default = values[0]
                    getattr(data, 'set_active_%s' % attr)(default)
                    aa.assign(default, attr.upper(), d_type.upper() + '_DATA')
                    aa.update()
                    kw = {
                        '%s_%s_name' % (d_type, attr): default,
                        'trait_change_notify': False
                    }
                    obj.set(**kw)

        _setup_data_traits(self, pnt_attr, 'point')
        _setup_data_traits(self, cell_attr, 'cell')
        if self._first:
            self._first = False
        # Propagate the data changed event.
        self.data_changed = True
Example #34
0
    def _update_data(self):
        if self.data is None:
            return
        pnt_attr, cell_attr = get_all_attributes(self.data)

        pd = self.data.point_data
        scalars = pd.scalars
        if self.data.is_a('vtkImageData') and scalars is not None:
            # For some reason getting the range of the scalars flushes
            # the data through to prevent some really strange errors
            # when using an ImagePlaneWidget.
            r = scalars.range
            if is_old_pipeline():
                self._assign_attribute.output.scalar_type = scalars.data_type
                self.data.scalar_type = scalars.data_type

        def _setup_data_traits(obj, attributes, d_type):
            """Given the object, the dict of the attributes from the
            `get_all_attributes` function and the data type
            (point/cell) data this will setup the object and the data.
            """
            attrs = ['scalars', 'vectors', 'tensors']
            aa = obj._assign_attribute
            data = getattr(obj.data, '%s_data'%d_type)
            for attr in attrs:
                values = attributes[attr]
                values.append('')
                setattr(obj, '_%s_%s_list'%(d_type, attr), values)
                if len(values) > 1:
                    default = getattr(obj, '%s_%s_name'%(d_type, attr))
                    if obj._first and len(default) == 0:
                        default = values[0]
                    getattr(data, 'set_active_%s'%attr)(default)
                    aa.assign(default, attr.upper(),
                              d_type.upper() +'_DATA')
                    aa.update()
                    kw = {'%s_%s_name'%(d_type, attr): default,
                          'trait_change_notify': False}
                    obj.set(**kw)

        _setup_data_traits(self, pnt_attr, 'point')
        _setup_data_traits(self, cell_attr, 'cell')
        if self._first:
            self._first = False
        # Propagate the data changed event.
        self.data_changed = True
    def _update(self):
        """Updates the traits for the fields that are available in the
        input data.
        """
        if len(self.inputs) == 0 or len(self.inputs[0].outputs) == 0:
            return

        input = self.inputs[0].get_output_object()
        if self._first and is_old_pipeline():
            # Force all attributes to be defined and computed
            input.update()
        pnt_attr, cell_attr = get_all_attributes(input)

        self._setup_data_traits(cell_attr, 'cell')
        self._setup_data_traits(pnt_attr, 'point')
        if self._first:
            self._first = False
Example #36
0
    def _update_limits(self):
        if is_old_pipeline():
            extents = self.filter.input.whole_extent
        else:
            extents = self.filter.get_update_extent()

        if (extents[0] > extents[1] or extents[2] > extents[3]
                or extents[4] > extents[5]):
            dims = self.inputs[0].get_output_dataset().dimensions
            e = extents
            extents = [e[0], dims[0] - 1, e[2], dims[1] - 1, e[4], dims[2] - 1]

        self._x_low, self._x_high = extents[:2]
        self._y_low, self._y_high = extents[2:4]
        self._z_low, self._z_high = extents[4:]
        self._x_s_high = max(1, self._x_high)
        self._y_s_high = max(1, self._y_high)
        self._z_s_high = max(1, self._z_high)
Example #37
0
    def update_data(self):
        """Override this method to do what is necessary when upstream
        data changes.

        This method is invoked (automatically) when any of the inputs
        sends a `data_changed` event.
        """
        # Invoke render to update any changes.
        if not is_old_pipeline():
            from mayavi.modules.outline import Outline
            from mayavi.components.glyph import Glyph
            #FIXME: A bad hack, but without these checks results in seg fault
            input = self.inputs[0]
            if isinstance(input, Outline) or isinstance(input, Glyph):
                self.mapper.update(0)
            else:
                self.mapper.update()
        self.render()
Example #38
0
    def update_data(self):
        """Override this method to do what is necessary when upstream
        data changes.

        This method is invoked (automatically) when any of the inputs
        sends a `data_changed` event.
        """
        # Invoke render to update any changes.
        if not is_old_pipeline():
            from mayavi.modules.outline import Outline
            from mayavi.components.glyph import Glyph
            #FIXME: A bad hack, but without these checks results in seg fault
            input = self.inputs[0]
            if isinstance(input, Outline) or isinstance(input, Glyph):
                self.mapper.update(0)
            else:
                self.mapper.update()
        self.render()
    def _update_vtk_dataset_content(self):
        vtk_dataset = self.data

        if vtk_dataset is None:
            return

        pnt_attr, cell_attr = get_all_attributes(vtk_dataset)

        scalars = vtk_dataset.point_data.scalars
        if vtk_dataset.is_a('vtkImageData') and scalars is not None:
            # For some reason getting the range of the scalars flushes
            # the data through to prevent some really strange errors
            # when using an ImagePlaneWidget.
            if is_old_pipeline():
                self._assign_attribute.output.scalar_type = scalars.data_type
                vtk_dataset.scalar_type = scalars.data_type

        self._update_vtk_pipeline_for_data('point', pnt_attr)
        self._update_vtk_pipeline_for_data('cell', cell_attr)
Example #40
0
    def _update_limits(self):
        if is_old_pipeline():
            extents = self.filter.input.whole_extent
        elif VTK_MAJOR_VERSION <= 7:
            extents = self.filter.get_update_extent()
        else:
            extents = self.filter.input.extent

        if (extents[0]>extents[1] or extents[2]>extents[3] or
                extents[4]>extents[5]):
            dims = self.inputs[0].get_output_dataset().dimensions
            e = extents
            extents = [e[0], dims[0]-1, e[2], dims[1] -1, e[4], dims[2] -1]

        self._x_low, self._x_high = extents[:2]
        self._y_low, self._y_high = extents[2:4]
        self._z_low, self._z_high = extents[4:]
        self._x_s_high = max(1, self._x_high)
        self._y_s_high = max(1, self._y_high)
        self._z_s_high = max(1, self._z_high)
Example #41
0
    def test_change(self):
        s = self.scene
        src = s.children[0]
        ot = src.children[0].children[0]
        src.source = "gaussian"

        # Check with the default properties of gaussian image to verify
        # that the source has actually changed
        self.assertEqual(src.source, "gaussian")
        self.assertEqual(numpy.allclose(src.data_source.center, (0.0, 0.0, 0.0)), True)
        self.assertEqual(src.data_source.maximum, 1.0)
        self.assertEqual(src.data_source.standard_deviation, 100)

        # Check the scalar ranges
        self.assertEqual(numpy.allclose(src.outputs[0].point_data.scalars.range, (0.00149, 1.0), atol=1.01e-03), True)

        src.data_source.maximum = 2.0
        src.data_source.standard_deviation = 15
        if not is_old_pipeline():
            src.data_source.update()
        self.check()
Example #42
0
def image_from_array(ary):
    """ Create a VTK image object that references the data in ary.
        The array is either 2D or 3D with.  The last dimension
        is always the number of channels.  It is only tested
        with 3 (RGB) or 4 (RGBA) channel images.

        Note: This works no matter what the ary type is (accept
        probably complex...).  uint8 gives results that make since
        to me.  Int32 and Float types give colors that I am not
        so sure about.  Need to look into this...
    """

    sz = ary.shape
    dims = len(sz)
    # create the vtk image data
    img = tvtk.ImageData()

    if dims == 2:
        # 1D array of pixels.
        img.whole_extent = (0, sz[0] - 1, 0, 0, 0, 0)
        img.dimensions = sz[0], 1, 1
        img.point_data.scalars = ary

    elif dims == 3:
        # 2D array of pixels.
        if is_old_pipeline():
            img.whole_extent = (0, sz[0] - 1, 0, sz[1] - 1, 0, 0)
        else:
            img.extent = (0, sz[0] - 1, 0, sz[1] - 1, 0, 0)
        img.dimensions = sz[0], sz[1], 1

        # create a 2d view of the array
        ary_2d = ary[:]
        ary_2d.shape = sz[0] * sz[1], sz[2]
        img.point_data.scalars = ary_2d

    else:
        raise ValueError("ary must be 3 dimensional.")

    return img
Example #43
0
def image_from_array(ary):
    """ Create a VTK image object that references the data in ary.
        The array is either 2D or 3D with.  The last dimension
        is always the number of channels.  It is only tested
        with 3 (RGB) or 4 (RGBA) channel images.

        Note: This works no matter what the ary type is (accept
        probably complex...).  uint8 gives results that make since
        to me.  Int32 and Float types give colors that I am not
        so sure about.  Need to look into this...
    """

    sz = ary.shape
    dims = len(sz)
    # create the vtk image data
    img = tvtk.ImageData()

    if dims == 2:
        # 1D array of pixels.
        img.whole_extent = (0, sz[0]-1, 0, 0, 0, 0)
        img.dimensions = sz[0], 1, 1
        img.point_data.scalars = ary

    elif dims == 3:
        # 2D array of pixels.
        if is_old_pipeline():
            img.whole_extent = (0, sz[0]-1, 0, sz[1]-1, 0, 0)
        else:
            img.extent = (0, sz[0]-1, 0, sz[1]-1, 0, 0)
        img.dimensions = sz[0], sz[1], 1

        # create a 2d view of the array
        ary_2d = ary[:]
        ary_2d.shape = sz[0]*sz[1],sz[2]
        img.point_data.scalars = ary_2d

    else:
        raise ValueError, "ary must be 3 dimensional."

    return img
Example #44
0
    def _setup_probe_data(self, reset=False):
        pd = self.probe_data
        input = self.inputs[0].get_output_dataset()
        if input.is_a('vtkImageData'):
            self.allow_changes = False
            self.set(spacing=input.spacing,
                     dimensions=input.dimensions)
            pd.set(origin=input.origin,
                   dimensions=input.dimensions,
                   spacing=input.spacing)
            pd.update()
        elif reset:
            self.allow_changes = True
            b = numpy.array(input.bounds)
            pd.origin = b[::2]
            l = b[1::2] - b[::2]
            tot_len = sum(l)
            npnt = pow(input.number_of_points, 1./3.) + 0.5
            fac = 3.0*npnt/tot_len
            dims = (l*fac).astype(int) + 1
            extent = (0, dims[0] -1, 0, dims[1] -1, 0, dims[2] -1)
            if tvtk_common.is_old_pipeline():
                pd.set(extent=extent,
                       update_extent=extent,
                       whole_extent=extent,
                       dimensions=dims)
            else:
                pd.set(extent=extent,
                       dimensions=dims)

            max_dim = dims.max()
            dims = (dims-1).clip(min=1, max=max_dim+1)
            l = l.clip(min=1e-3, max=l.max()+1.0)
            pd.spacing = l/dims
            self._event_handled = True
            self.set(spacing = pd.spacing,
                     dimensions=pd.dimensions)
            self._event_handled = False
    def setUp(self):
        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1 + float(n)) / 10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0 * (0.5 - random.random(27))
        arr3 = arr3.astype('f')

        if is_old_pipeline():
            p = tvtk.ImageData(dimensions=[3, 3, 3],
                               spacing=[1, 1, 1],
                               scalar_type='int')
        else:
            p = tvtk.ImageData(dimensions=[3, 3, 3], spacing=[1, 1, 1])
        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name = 'second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name = 'third'
        self.img = p
        self.first = arr1
        self.second = arr2
        self.third = arr3

        # Setup the mayavi pipeline.
        e = NullEngine()
        e.start()
        e.new_scene()
        self.e = e

        src = VTKDataSource(data=p)
        e.add_source(src)
        self.src = src
        ipw = ImagePlaneWidget()
        e.add_module(ipw)
        self.ipw = ipw
    def setUp(self):
        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1+float(n))/10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0*(0.5 - random.random(27))
        arr3 = arr3.astype('f')

        if is_old_pipeline():
            p = tvtk.ImageData(dimensions=[3,3,3],spacing=[1,1,1],
                               scalar_type='int')
        else:
            p = tvtk.ImageData(dimensions=[3,3,3],spacing=[1,1,1])
        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name='second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name='third'
        self.img = p
        self.first = arr1
        self.second = arr2
        self.third = arr3

        # Setup the mayavi pipeline.
        e = NullEngine()
        e.start()
        e.new_scene()
        self.e = e

        src = VTKDataSource(data=p)
        e.add_source(src)
        self.src = src
        ipw = ImagePlaneWidget()
        e.add_module(ipw)
        self.ipw = ipw
 def _update_probe(self):
     pd = self.probe_data
     dims = self.dimensions
     spacing = self.spacing
     extent = (0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
     if tvtk_common.is_old_pipeline():
         pd.trait_set(extent=extent,
                      update_extent=extent,
                      whole_extent=extent,
                      dimensions=dims,
                      spacing=spacing)
     else:
         pd.trait_set(extent=extent, dimensions=dims, spacing=spacing)
     pd.modified()
     fil = self.filter
     w = fil.global_warning_display
     fil.global_warning_display = False
     fil.remove_all_inputs()
     self.configure_input_data(fil, pd)
     fil.update_whole_extent()
     fil.update()
     self._rescale_scalars_changed(self.rescale_scalars)
     fil.global_warning_display = w
     self.data_changed = True
# Author: Suyog Dutt Jain <*****@*****.**>
# Copyright (c) 2009,  Enthought, Inc.
# License: BSD Style.

# Standard library imports.
import unittest

# Local imports.
from common import get_example_data

# Enthought library imports
from tvtk.common import is_old_pipeline
from mayavi.sources.unstructured_grid_reader import UnstructuredGridReader
from mayavi.tests.data_reader_test_base import DataReaderTestBase

old_pipeline = is_old_pipeline()

class TestAVSUCDReader(DataReaderTestBase):

    def setup_reader(self):

        """"Setup the reader in here.  This is called after the engine
        has been created and started.  The engine is available as
        self.e.  This method is called by setUp().
        """
        # Read a AVSUCD data file.
        r = UnstructuredGridReader()
        r.initialize(get_example_data('cellsnd.ascii.inp'))
        self.e.add_source(r)
        self.bounds =(-2.0, 2.0, -2.0, 2.0, 0.0, 0.0)
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from mayavi.modules.api import ImagePlaneWidget

        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1+float(n))/10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0*(0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3,3,3], spacing=[1,1,1])
        if is_old_pipeline():
            p.scalar_type = 'int'

        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name='second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name='third'
        if is_old_pipeline():
            p.update()

        # Make the pipeline.
        self.new_scene()
        src = VTKDataSource(data=p)
        script.add_source(src)
        ipw = ImagePlaneWidget()
        script.add_module(ipw)

        # Test.
        ipw = ipw.ipw
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr1), max(arr1)
        assert r == expect
        o = src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'

        src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 11
            assert st == 'double'

        src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'
Example #50
0
 def _color_changed(self, val):
     if is_old_pipeline():
         self.source.color = val
     else:
         self.source.set_color(val)
     self.glyph.set_color(val)
Example #51
0
 def render(self):
     if not is_old_pipeline():
         self.outline_filter.update()
     super(Outline, self).render()
Example #52
0
# Author: Suyog Dutt Jain <*****@*****.**>
# Copyright (c) 2009,  Enthought, Inc.
# License: BSD Style.

# Standard library imports.
import unittest

# Local imports.
from common import get_example_data

# Enthought library imports
from tvtk.common import is_old_pipeline
from mayavi.sources.unstructured_grid_reader import UnstructuredGridReader
from mayavi.tests.data_reader_test_base import DataReaderTestBase

old_pipeline = is_old_pipeline()


class TestAVSUCDReader(DataReaderTestBase):
    def setup_reader(self):
        """"Setup the reader in here.  This is called after the engine
        has been created and started.  The engine is available as
        self.e.  This method is called by setUp().
        """
        # Read a AVSUCD data file.
        r = UnstructuredGridReader()
        r.initialize(get_example_data('cellsnd.ascii.inp'))
        self.e.add_source(r)
        self.bounds = (-2.0, 2.0, -2.0, 2.0, 0.0, 0.0)

    def test_avsucd_data_reader(self):
Example #53
0
def vtk2array(vtk_array):
    """Converts a VTK data array to a numpy array.

    Given a subclass of vtkDataArray, this function returns an
    appropriate numpy array containing the same data.  The function
    is very efficient since it uses the VTK imaging pipeline to
    convert the data.  If a sufficiently new version of VTK (5.2) is
    installed then it actually uses the buffer interface to return a
    view of the VTK array in the returned numpy array.

    Parameters
    ----------

    - vtk_array : `vtkDataArray`

      The VTK data array to be converted.

    """
    typ = vtk_array.GetDataType()
    assert typ in get_vtk_to_numeric_typemap().keys(), \
           "Unsupported array type %s"%typ

    shape = vtk_array.GetNumberOfTuples(), \
            vtk_array.GetNumberOfComponents()
    if shape[0] == 0:
        dtype = get_numeric_array_type(typ)
        return numpy.array([], dtype)

    # First check if this array already has a numpy array cached,
    # if it does and the array size has not been changed, reshape
    # that and return it.
    if vtk_array in _array_cache:
        arr = _array_cache.get(vtk_array)
        if shape[1] == 1:
            shape = (shape[0], )
        if arr.size == numpy.prod(shape):
            arr = numpy.reshape(arr, shape)
            return arr

    # If VTK's new numpy support is available, use the buffer interface.
    if numpy_support is not None and typ != vtkConstants.VTK_BIT:
        dtype = get_numeric_array_type(typ)
        result = numpy.frombuffer(vtk_array, dtype=dtype)
        if shape[1] == 1:
            shape = (shape[0], )
        result.shape = shape
        return result

    # Setup an imaging pipeline to export the array.
    img_data = vtk.vtkImageData()
    img_data.SetDimensions(shape[0], 1, 1)
    if typ == vtkConstants.VTK_BIT:
        iarr = vtk.vtkCharArray()
        iarr.DeepCopy(vtk_array)
        img_data.GetPointData().SetScalars(iarr)
    elif typ == vtkConstants.VTK_ID_TYPE:
        # Needed since VTK_ID_TYPE does not work with VTK 4.5.
        iarr = vtk.vtkLongArray()
        iarr.SetNumberOfTuples(vtk_array.GetNumberOfTuples())
        nc = vtk_array.GetNumberOfComponents()
        iarr.SetNumberOfComponents(nc)
        for i in range(nc):
            iarr.CopyComponent(i, vtk_array, i)
        img_data.GetPointData().SetScalars(iarr)
    else:
        img_data.GetPointData().SetScalars(vtk_array)

    if is_old_pipeline():
        img_data.SetNumberOfScalarComponents(shape[1])
        if typ == vtkConstants.VTK_ID_TYPE:
            # Hack necessary because vtkImageData can't handle VTK_ID_TYPE.
            img_data.SetScalarType(vtkConstants.VTK_LONG)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            img_data.SetScalarType(vtkConstants.VTK_CHAR)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            img_data.SetScalarType(typ)
            r_dtype = get_numeric_array_type(typ)
        img_data.Update()
    else:
        if typ == vtkConstants.VTK_ID_TYPE:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            r_dtype = get_numeric_array_type(typ)
        img_data.Modified()

    exp = vtk.vtkImageExport()
    if is_old_pipeline():
        exp.SetInput(img_data)
    else:
        exp.SetInputData(img_data)

    # Create an array of the right size and export the image into it.
    im_arr = numpy.empty((shape[0]*shape[1],), r_dtype)
    exp.Export(im_arr)

    # Now reshape it.
    if shape[1] == 1:
        shape = (shape[0], )
    im_arr = numpy.reshape(im_arr, shape)
    return im_arr
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from mayavi.modules.api import ImagePlaneWidget

        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1 + float(n)) / 10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0 * (0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3, 3, 3], spacing=[1, 1, 1])
        if is_old_pipeline():
            p.scalar_type = 'int'

        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name = 'second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name = 'third'
        if is_old_pipeline():
            p.update()

        # Make the pipeline.
        self.new_scene()
        src = VTKDataSource(data=p)
        script.add_source(src)
        ipw = ImagePlaneWidget()
        script.add_module(ipw)

        # Test.
        ipw = ipw.ipw
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr1), max(arr1)
        assert r == expect
        o = src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'

        src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 11
            assert st == 'double'

        src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'
Example #55
0
# you want is the first `source`.  OTOH if you want the N'th `source`
# use get_source(N).
# g.source = cs.output
configure_source_data(g, cs.output)
cs.update()
g.update()

m = tvtk.PolyDataMapper()
configure_input_data(m, g.output)
a = tvtk.Actor(mapper=m)

# Read the texture from image and set the texture on the actor.  If
# you don't like this image, replace with your favorite -- any image
# will do (you must use a suitable reader though).
img = tvtk.JPEGReader(file_name='images/masonry.jpg')
t = tvtk.Texture(interpolate = 1)
if is_old_pipeline():
    t.input = img.output
else:
    t.input_connection = img.output_port
a.texture = t

# Renderwindow stuff and add actor.
rw = tvtk.RenderWindow(size=(600, 600))
ren = tvtk.Renderer(background=(0.5, 0.5, 0.5))
rw.add_renderer(ren)
rwi = tvtk.RenderWindowInteractor(render_window=rw)
ren.add_actor(a)
rwi.initialize()
rwi.start()
Example #56
0
 def _color_changed(self, val):
     if is_old_pipeline():
         self.source.color = val
     else:
         self.source.set_color(val)
     self.glyph.set_color(val)