Example #1
0
def add_dataset(dataset, name='', **kwargs):
    """Add a dataset object to the Mayavi pipeline.

    **Parameters**

    :dataset: a tvtk/vtk dataset/tvtk/VTK Algorithm, or a Mayavi source. The
              dataset added to the Mayavi pipeline

    :figure: a figure identifier number or string, None or False, optional.

            If no `figure` keyword argument is given, the data
            is added to the current figure (a new figure if created if
            necessary).

            If a `figure` keyword argument is given, it should either the name
            the number of the figure the dataset should be added to, or None,
            in which case the data is not added to the pipeline.

            If figure is False, a null engine is created. This null
            engine does not create figures, and is mainly usefull for
            tensting, or using the VTK algorithms without visualization.

    **Returns**

    The corresponding Mayavi source is returned.

    """
    if isinstance(dataset, (tvtk.DataSet, vtk.vtkDataSet)):
        d = VTKDataSource()
        d.data = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, (tvtk.DataObject, vtk.vtkDataObject)):
        d = VTKObjectSource()
        tp = tvtk.TrivialProducer()
        tp.set_output(tvtk.to_tvtk(dataset))
        d.object = tp
    elif isinstance(dataset, (tvtk.Object, vtk.vtkObject)):
        d = VTKObjectSource()
        d.object = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, Source):
        d = dataset
    else:
        raise TypeError(
              "first argument should be either a TVTK object"
              " or a mayavi source")

    if len(name) > 0:
        d.name = name
    engine = _get_engine_from_kwarg(kwargs)
    if engine is None:
        # Return early, as we don't want to add the source to an engine.
        return d
    engine.add_source(d)
    return d
Example #2
0
def add_dataset(dataset, name='', **kwargs):
    """Add a dataset object to the Mayavi pipeline.

    **Parameters**

    :dataset: a tvtk/vtk dataset/tvtk/VTK Algorithm, or a Mayavi source. The
              dataset added to the Mayavi pipeline

    :figure: a figure identifier number or string, None or False, optionnal.

            If no `figure` keyword argument is given, the data
            is added to the current figure (a new figure if created if
            necessary).

            If a `figure` keyword argument is given, it should either the name
            the number of the figure the dataset should be added to, or None,
            in which case the data is not added to the pipeline.

            If figure is False, a null engine is created. This null
            engine does not create figures, and is mainly usefull for
            tensting, or using the VTK algorithms without visualization.

    **Returns**

    The corresponding Mayavi source is returned.

    """
    if isinstance(dataset, (tvtk.DataSet, vtk.vtkDataSet)):
        d = VTKDataSource()
        d.data = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, (tvtk.DataObject, vtk.vtkDataObject)):
        d = VTKObjectSource()
        tp = tvtk.TrivialProducer()
        tp.set_output(tvtk.to_tvtk(dataset))
        d.object = tp
    elif isinstance(dataset, (tvtk.Object, vtk.vtkObject)):
        d = VTKObjectSource()
        d.object = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, Source):
        d = dataset
    else:
        raise TypeError(
              "first argument should be either a TVTK object"
              " or a mayavi source")

    if len(name) > 0:
        d.name = name
    engine = _get_engine_from_kwarg(kwargs)
    if engine is None:
        # Return early, as we don't want to add the source to an engine.
        return d
    engine.add_source(d)
    return d
    def add_attribute(self, array, name, category='point'):
        """Add an attribute to the dataset to specified category ('point' or
        'cell').

        One may add a scalar, vector (3/4 components) or a tensor (9
        components).

        Note that it is the user's responsibility to set the correct size of
        the arrays. Also no automatic transposing of the data is done.

        Parameters
        ----------

        array: numpy array/list : array data to add.

        name: str: name of the array.

        category: 'point'/'cell': the category of the attribute data.

        """
        array = np.asarray(array)
        assert len(array.shape) <= 2, "Only 2D arrays can be added."
        data = getattr(self.image_data, '%s_data' % category)
        if len(array.shape) == 2:
            assert array.shape[1] in [1, 3, 4, 9], \
                    "Only N x m arrays where (m in [1,3,4,9]) are supported"
        va = tvtk.to_tvtk(array2vtk(array))
        va.name = name
        data.add_array(va)
Example #4
0
    def add_attribute(self, array, name, category='point'):
        """Add an attribute to the dataset to specified category ('point' or
        'cell').

        One may add a scalar, vector (3/4 components) or a tensor (9
        components).

        Note that it is the user's responsibility to set the correct size of
        the arrays. Also no automatic transposing of the data is done.

        Parameters
        ----------

        array: numpy array/list : array data to add.

        name: str: name of the array.

        category: 'point'/'cell': the category of the attribute data.

        """
        array = np.asarray(array)
        assert len(array.shape) <= 2, "Only 2D arrays can be added."
        data = getattr(self.image_data, '%s_data' % category)
        if len(array.shape) == 2:
            assert array.shape[1] in [1, 3, 4, 9], \
                    "Only N x m arrays where (m in [1,3,4,9]) are supported"
        va = tvtk.to_tvtk(array2vtk(array))
        va.name = name
        data.add_array(va)
Example #5
0
 def test_to_tvtk_returns_tvtk_object(self):
     # Given
     v = vtk.vtkContourFilter()
     # When
     x = tvtk.to_tvtk(v)
     # Then
     self.assertEqual(x.class_name, 'vtkContourFilter')
     self.assertTrue(isinstance(x, tvtk_base.TVTKBase))
     self.assertTrue(isinstance(x, tvtk.ContourFilter))
     self.assertTrue(v is x._vtk_obj)
Example #6
0
def set_arrays(dataset, particle_array):
    """ Code to add all the arrays to a dataset given a particle array."""
    props = set(particle_array.properties.keys())
    # Add the vector data.
    vec = numpy.empty((len(particle_array.x), 3), dtype=float)
    vec[:,0] = particle_array.u
    vec[:,1] = particle_array.v
    vec[:,2] = particle_array.w
    va = tvtk.to_tvtk(array2vtk(vec))
    va.name = 'velocity'
    dataset.data.point_data.add_array(vec)
    # Now add the scalar data.
    scalars = props - set(('u', 'v', 'w'))
    for sc in scalars:
        arr = particle_array.get(sc)
        va = tvtk.to_tvtk(array2vtk(arr))
        va.name = sc
        dataset.data.point_data.add_array(va)
    dataset._update_data()
Example #7
0
def set_arrays(dataset, particle_array):
    """ Code to add all the arrays to a dataset given a particle array."""
    props = set(particle_array.properties.keys())
    # Add the vector data.
    vec = numpy.empty((len(particle_array.x), 3), dtype=float)
    vec[:, 0] = particle_array.u
    vec[:, 1] = particle_array.v
    vec[:, 2] = particle_array.w
    va = tvtk.to_tvtk(array2vtk(vec))
    va.name = 'velocity'
    dataset.data.point_data.add_array(vec)
    # Now add the scalar data.
    scalars = props - set(('u', 'v', 'w'))
    for sc in scalars:
        arr = particle_array.get(sc)
        va = tvtk.to_tvtk(array2vtk(arr))
        va.name = sc
        dataset.data.point_data.add_array(va)
    dataset._update_data()
Example #8
0
 def intersect_line(self, lineP0, lineP1):
     ''' 计算与线段相交的交点,这里调用了tvtk的方法
     lineP0: 线段的第一个点,长度3的数组
     lineP1: 线段的第二个点
     return
     points: 所有的交点坐标
     cell_ids: 每个交点所属的面片ID '''
     intersectPoints = tvtk.to_vtk(tvtk.Points())
     intersectCells = tvtk.to_vtk(tvtk.IdList())
     self._obb_tree.intersect_with_line(lineP0, lineP1, intersectPoints,
                                        intersectCells)
     intersectPoints = tvtk.to_tvtk(intersectPoints)
     intersectCells = tvtk.to_tvtk(intersectCells)
     points = intersectPoints.to_array()
     cell_ids = [
         intersectCells.get_id(i)
         for i in range(intersectCells.number_of_ids)
     ]
     return points, cell_ids
Example #9
0
 def test_to_tvtk_returns_tvtk_object(self):
     # Given
     v = vtk.vtkContourFilter()
     # When
     x = tvtk.to_tvtk(v)
     # Then
     self.assertEqual(x.class_name, 'vtkContourFilter')
     self.assertTrue(isinstance(x, tvtk_base.TVTKBase))
     self.assertTrue(isinstance(x, tvtk.ContourFilter))
     self.assertTrue(v is x._vtk_obj)
Example #10
0
 def on_pick(self, vtk_picker, event):
     """ Dispatch the pick to the callback associated with the
         corresponding mouse button.
     """
     picker = tvtk.to_tvtk(vtk_picker)
     for event_type, event_picker in self._active_pickers.items():
         if picker is event_picker:
             for callback, type, button in self.callbacks:
                 if (type == event_type and button == self._current_button):
                     callback(picker)
         break
 def on_pick(self, vtk_picker, event):
     """ Dispatch the pick to the callback associated with the
         corresponding mouse button.
     """
     picker = tvtk.to_tvtk(vtk_picker)
     for event_type, event_picker in self._active_pickers.iteritems():
         if picker is event_picker:
             for callback, type, button in self.callbacks:
                 if ( type == event_type
                                 and button == self._current_button):
                     callback(picker)
         break
Example #12
0
        def _create_control(self, parent):
            """ Create the toolkit-specific control that represents the widget. """

            # Create the VTK widget.
            self._vtk_control = window = FlatInteractor(self,
                                                        parent,
                                                        stereo=self.stereo)

            # Switch the default interaction style to the trackball one.
            window.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            # Grab the renderwindow.
            renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow())
            renwin.set(point_smoothing=self.point_smoothing,
                       line_smoothing=self.line_smoothing,
                       polygon_smoothing=self.polygon_smoothing)
            # Create a renderer and add it to the renderwindow
            self._renderer = tvtk.Renderer()
            renwin.add_renderer(self._renderer)
            # Save a reference to our camera so it is not GC'd -- needed for
            # the sync_traits to work.
            self._camera = self.camera

            # Sync various traits.
            self._renderer.background = self.background
            self.sync_trait('background', self._renderer)
            self.renderer.on_trait_change(self.render, 'background')
            renwin.off_screen_rendering = self.off_screen_rendering
            self._camera.parallel_projection = self.parallel_projection
            self.sync_trait('parallel_projection', self._camera)
            self.sync_trait('off_screen_rendering', self._renwin)
            self.render_window.on_trait_change(self.render,
                                               'off_screen_rendering')
            self.render_window.on_trait_change(self.render, 'stereo_render')
            self.render_window.on_trait_change(self.render, 'stereo_type')
            self.camera.on_trait_change(self.render, 'parallel_projection')

            self._interactor = tvtk.to_tvtk(window._Iren)

            return window
Example #13
0
    def test_to_tvtk_wraps_subclass_of_vtk(self):
        # Given
        class MyAlgorithm(vtk.vtkPythonAlgorithm):
            pass

        a = MyAlgorithm()
        # When
        ta = tvtk.to_tvtk(a)

        # Then
        self.assertTrue(isinstance(ta, tvtk.PythonAlgorithm))

        # Given
        class B(MyAlgorithm):
            pass

        b = B()
        # When
        tb = tvtk.to_tvtk(b)

        # Then
        self.assertTrue(isinstance(tb, tvtk.PythonAlgorithm))
Example #14
0
 def add_array(self, array, name, category='point'):
     """
     Add an array to the dataset to specified category ('point' or
     'cell').
     """
     assert len(array.shape) <= 2, "Only 2D arrays can be added."
     data = getattr(self.dataset, '%s_data' % category)
     if len(array.shape) == 2:
         assert array.shape[1] in [1, 3, 4, 9], \
                 "Only Nxm arrays where (m in [1,3,4,9]) are supported"
         va = tvtk.to_tvtk(array2vtk(array))
         va.name = name
         data.add_array(va)
         mapping = {1: 'scalars', 3: 'vectors', 4: 'scalars', 9: 'tensors'}
         dict = getattr(self, '%s_%s' % (category, mapping[array.shape[1]]))
         dict[name] = array
     else:
         va = tvtk.to_tvtk(array2vtk(array))
         va.name = name
         data.add_array(va)
         dict = getattr(self, '%s_scalars' % (category))
         dict[name] = array
Example #15
0
    def test_to_tvtk_wraps_subclass_of_vtk(self):
        # Given
        class MyAlgorithm(vtk.vtkPythonAlgorithm):
            pass

        a = MyAlgorithm()
        # When
        ta = tvtk.to_tvtk(a)

        # Then
        self.assertTrue(isinstance(ta, tvtk.PythonAlgorithm))

        # Given
        class B(MyAlgorithm):
            pass

        b = B()
        # When
        tb = tvtk.to_tvtk(b)

        # Then
        self.assertTrue(isinstance(tb, tvtk.PythonAlgorithm))
    def add_attribute(self, array, name, category='point'):
        """Add an attribute to the dataset to specified category ('point' or
        'cell').

        One may add a scalar, vector (3/4 components) or a tensor (9 components).

        Note that it is the user's responsibility to set the correct size of
        the arrays.

        Parameters
        ----------

        array: numpy array/list : array data to add.

        name: str: name of the array.

        category: 'point'/'cell': the category of the attribute data.

        """
        array = np.asarray(array)
        assert len(array.shape) <= 2, "Only 2D arrays can be added."
        data = getattr(self.data, '%s_data' % category)
        if len(array.shape) == 2:
            assert array.shape[1] in [1, 3, 4, 9], \
                    "Only Nxm arrays where (m in [1,3,4,9]) are supported"
            va = tvtk.to_tvtk(array2vtk(array))
            va.name = name
            data.add_array(va)
            mapping = {1: 'scalars', 3: 'vectors', 4: 'scalars',
                       9: 'tensors'}
            attribute = '_%s_%s_list' % (category, mapping[array.shape[1]])
        else:
            va = tvtk.to_tvtk(array2vtk(array))
            va.name = name
            data.add_array(va)
            attribute = '_%s_scalars_list' % category
        names = set(getattr(self, attribute) + [name])
        setattr(self, attribute, sorted(names))
Example #17
0
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        # Create the VTK widget.
        self._vtk_control = window = _VTKRenderWindowInteractor(
            self, parent, stereo=self.stereo)

        # Switch the default interaction style to the trackball one.
        window.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        # Grab the renderwindow.
        renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow())
        renwin.set(point_smoothing=self.point_smoothing,
                   line_smoothing=self.line_smoothing,
                   polygon_smoothing=self.polygon_smoothing)
        # Create a renderer and add it to the renderwindow
        self._renderer = tvtk.Renderer()
        renwin.add_renderer(self._renderer)
        # Save a reference to our camera so it is not GC'd -- needed for
        # the sync_traits to work.
        self._camera = self.camera

        # Sync various traits.
        self._renderer.background = self.background
        self.sync_trait('background', self._renderer)
        self.renderer.on_trait_change(self.render, 'background')
        renwin.off_screen_rendering = self.off_screen_rendering
        self._camera.parallel_projection = self.parallel_projection
        self.sync_trait('parallel_projection', self._camera)
        self.sync_trait('off_screen_rendering', self._renwin)
        self.render_window.on_trait_change(self.render, 'off_screen_rendering')
        self.render_window.on_trait_change(self.render, 'stereo_render')
        self.render_window.on_trait_change(self.render, 'stereo_type')
        self.camera.on_trait_change(self.render, 'parallel_projection')

        self._interactor = tvtk.to_tvtk(window._Iren)

        return window
Example #18
0
 def on_key_down(iren_style, key):
     rendrr = iren_style.GetCurrentRenderer()
     rendrr = tvtk.to_tvtk(rendrr)
     if key == '+':
         for act in rendrr.actors:
             act.property.point_size *= 1.1
     elif key == '-':
         for act in rendrr.actors:
             act.property.point_size /= 1.1
     elif key == 's':
         ren_win = rendrr.render_window
         w2if = tvtk.WindowToImageFilter(input=ren_win)
         w2if.update()
         writer = tvtk.PNGWriter(file_name=snapshot_file, input=w2if.output)
         writer.write()
Example #19
0
 def add_array(self, array, name, category='point'):
     """
     Add an array to the dataset to specified category ('point' or
     'cell').
     """
     assert len(array.shape) <= 2, "Only 2D arrays can be added."
     data = getattr(self.dataset, '%s_data'%category)
     if len(array.shape) == 2:
         assert array.shape[1] in [1, 3, 4, 9], \
                 "Only Nxm arrays where (m in [1,3,4,9]) are supported"
         va = tvtk.to_tvtk(array2vtk(array))
         va.name = name
         data.add_array(va)
         mapping = {1:'scalars', 3: 'vectors', 4: 'scalars',
                    9: 'tensors'}
         dict = getattr(self, '%s_%s'%(category,
                                       mapping[array.shape[1]]))
         dict[name] = array
     else:
         va = tvtk.to_tvtk(array2vtk(array))
         va.name = name
         data.add_array(va)
         dict = getattr(self, '%s_scalars'%(category))
         dict[name] = array
Example #20
0
def display_3d_array(array_3d, color_map, figure):
    '''
    Method displays 3d array.

    Param:
        array_3d - np.array
        attenmap - np.array

    '''
    cm = color_map

    # Dislay 3D Array Rendering
    v = figure
    for j in range(len(array_3d)):
        c = tuple(cm[j])

        # Coordinate Information
        xx, yy, zz = np.where(array_3d[j] > 0.0)
        xx *= 100
        yy *= 100
        zz *= 100

        # Generate Voxels For Protein
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(xx)):
            input1 = vtk.vtkPolyData()
            voxel_source = vtk.vtkCubeSource()
            voxel_source.SetCenter(xx[i], yy[i], zz[i])
            voxel_source.SetXLength(100)
            voxel_source.SetYLength(100)
            voxel_source.SetZLength(100)
            voxel_source.Update()
            input1.ShallowCopy(voxel_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Voxels
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        cube_mapper = tvtk.PolyDataMapper()
        configure_input_data(cube_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=c)
        cube_actor = tvtk.Actor(mapper=cube_mapper, property=p)
        v.scene.add_actor(cube_actor)
Example #21
0
    def _picker_callback(self, picker_obj, evt):

        # test
        print 'come in the picker callback'

        picker_obj = tvtk.to_tvtk(picker_obj)
        tmp_pos = picker_obj.picked_positions.to_array()

        # test
        print tmp_pos

        if len(tmp_pos):
            distance = np.sum(np.abs(self.coords - tmp_pos[0]), axis=1)
            picked_id = np.argmin(distance)

            tmp_lut = self.rgba_lut.copy()
            self._toggle_color(tmp_lut[picked_id])
            self.surf.module_manager.scalar_lut_manager.lut.table = tmp_lut
Example #22
0
image.origin=nii.affine[0:3,3]
vImage=tvtk.to_vtk(image)
vPD=vImage.GetPointData()
vSC=vPD.GetScalars()
data=numpy_support.vtk_to_numpy(vSC)

indxs=np.unique(data)

for ind in indxs[1:]:
  print ind
  tmp=data.copy()
  tmp[tmp!=ind]=0
  tmp[tmp==ind]=1
  
  vPD.SetScalars(numpy_support.numpy_to_vtk(tmp))
  image=tvtk.to_tvtk(vImage)
  
  iso=tvtk.MarchingCubes()
  iso.set_input_data(image)
  iso.set_value(0,0.5)
  iso.update()
  smoother = tvtk.SmoothPolyDataFilter()
  smoother.convergence=0
  smoother.number_of_iterations=30
  smoother.relaxation_factor=0.1
  smoother.feature_angle=60
  smoother.feature_edge_smoothing=True
  smoother.boundary_smoothing=True
  smoother.set_input_data_object(iso.get_output_data_object(0))
  smoother.update()
Example #23
0
def display_3d_model(array_3d, pointcloud=None, centroids=None):
    '''
    Method renders space-filling atomic model of PDB data.
    Param:
        pdb_data - np.array ; mulitchanneled pdb atom coordinates
        skeletal - boolean ; if true shows model without radial information
        attenmap - np.array
    '''

    # Dislay 3D Mesh Rendering
    v = mlab.figure(bgcolor=(1.0,1.0,1.0))

    if array_3d is not None:

        # Color Mapping
        n = len(array_3d)
        cm = [winter(float(i)/n)[:3] for i in range(n)]

        for j in range(len(array_3d)):
            c = tuple(cm[j])

            # Coordinate Information
            xx, yy, zz = np.where(array_3d[j] > 0.0)
            xx = xx.astype('float') - ((resolution * array_3d.shape[1])/2.0)
            yy = yy.astype('float') - ((resolution * array_3d.shape[1])/2.0)
            zz = zz.astype('float') - ((resolution * array_3d.shape[1])/2.0)

            # Generate Voxels For Protein
            append_filter = vtk.vtkAppendPolyData()
            for i in range(len(xx)):
                input1 = vtk.vtkPolyData()
                voxel_source = vtk.vtkCubeSource()
                voxel_source.SetCenter(xx[i],yy[i],zz[i])
                voxel_source.SetXLength(1)
                voxel_source.SetYLength(1)
                voxel_source.SetZLength(1)
                voxel_source.Update()
                input1.ShallowCopy(voxel_source.GetOutput())
                append_filter.AddInputData(input1)
            append_filter.Update()

            #  Remove Any Duplicate Points.
            clean_filter = vtk.vtkCleanPolyData()
            clean_filter.SetInputConnection(append_filter.GetOutputPort())
            clean_filter.Update()

            # Render Voxels
            pd = tvtk.to_tvtk(clean_filter.GetOutput())
            cube_mapper = tvtk.PolyDataMapper()
            configure_input_data(cube_mapper, pd)
            p = tvtk.Property(opacity=1.0, color=c)
            cube_actor = tvtk.Actor(mapper=cube_mapper, property=p)
            v.scene.add_actor(cube_actor)

    if pointcloud is not None:

        # Generate Voxels For Pointcloud
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(pointcloud)):
            input1 = vtk.vtkPolyData()
            voxel_source = vtk.vtkCubeSource()
            voxel_source.SetCenter(pointcloud[i][0],pointcloud[i][1], pointcloud[i][2])
            voxel_source.SetXLength(1)
            voxel_source.SetYLength(1)
            voxel_source.SetZLength(1)
            voxel_source.Update()
            input1.ShallowCopy(voxel_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Voxels
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        cube_mapper = tvtk.PolyDataMapper()
        configure_input_data(cube_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0,0.5,0.5))
        cube_actor = tvtk.Actor(mapper=cube_mapper, property=p)
        v.scene.add_actor(cube_actor)

    if centroids is not None:

        # Generate Mesh For Centroids
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(centroids)):
            input1 = vtk.vtkPolyData()
            sphere_source = vtk.vtkSphereSource()
            sphere_source.SetCenter(centroids[i][0],centroids[i][1],centroids[i][2])
            sphere_source.SetRadius(4.0)
            sphere_source.Update()
            input1.ShallowCopy(sphere_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Mesh
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        sphere_mapper = tvtk.PolyDataMapper()
        configure_input_data(sphere_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0,0.0,1.0))
        sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
        v.scene.add_actor(sphere_actor)

    mlab.show()
Example #24
0
def experiment(num_particles):
    L = 1
    #L = 50e-9
    D = 1
    #D = 1e-10
    
    timesteps = 100000
    #timesteps = 10000
    max_t = 4.0/(2.0*num_particles**0.5);
    mol_dt = max_t/timesteps
    #mol_dt = 0.025*1e-8
    #max_t = mol_dt * timesteps
    
    
    A = tyche.new_species(D)
    B = tyche.new_species(D)
    C = tyche.new_species(D)
    
    bd = tyche.new_diffusion()
    bd.add_species(A)
    bd.add_species(B)
    bd.add_species(C)
    

    xlow = tyche.new_xplane(0,1)
    xhigh = tyche.new_xplane(L,-1)
    ylow = tyche.new_yplane(0,1)
    yhigh = tyche.new_yplane(L,-1)
    zlow = tyche.new_zplane(0,1)
    zhigh = tyche.new_zplane(L,-1)


    xminboundary = tyche.new_jump_boundary(xlow,[L,0,0])
    xmaxboundary = tyche.new_jump_boundary(xhigh,[-L,0,0])
    yminboundary = tyche.new_jump_boundary(ylow,[0,L,0])
    ymaxboundary = tyche.new_jump_boundary(yhigh,[0,-L,0])
    zminboundary = tyche.new_jump_boundary(zlow,[0,0,L])
    zmaxboundary = tyche.new_jump_boundary(zhigh,[0,0,-L])

    boundaries = tyche.group([xminboundary, xmaxboundary, yminboundary, ymaxboundary, zminboundary, zmaxboundary])
    boundaries.add_species(A)
    boundaries.add_species(B)
    boundaries.add_species(C)


    algorithm = tyche.group([bd,boundaries])
    
    A.fill_uniform([0,0,0],[L,L,L],int(num_particles*L**3))
    B.fill_uniform([0,0,0],[L,L,L],int(num_particles*L**3))
    C.fill_uniform([0,0,0],[L,L,L],int(num_particles*L**3))

    
    output_dt = max_t/100.0
    time = 0;
    print algorithm
    
    
    for i in range(100):
        print A,B,C
        print 'time = ',time,' ',i,' percent done'
        time = algorithm.integrate_for_time(output_dt,mol_dt)
        grid = tvtk.to_tvtk(A.get_vtk())
        g = init_vis(grid)
    print algorithm
Example #25
0
def display_3d_model(pdb_data, centroids=None):
    '''
    Method renders space-filling atomic model of PDB data.
    Param:
        pdb_data - np.array ; mulitchanneled pdb atom coordinates
        skeletal - boolean ; if true shows model without radial information
        attenmap - np.array
    '''

    # Dislay 3D Mesh Rendering
    v = mlab.figure(bgcolor=(1.0, 1.0, 1.0))

    if pdb_data is not None:
        # Color Mapping
        n = len(pdb_data)
        cm = [jet(float(i) / n)[:3] for i in range(n)]

        for j in range(len(pdb_data)):
            c = cm[j]

            # Coordinate, Radius Information
            r = pdb_data[j][:, 0].astype('float')
            x = pdb_data[j][:, 1].astype('float')
            y = pdb_data[j][:, 2].astype('float')
            z = pdb_data[j][:, 3].astype('float')

            # Generate Mesh For Protein
            append_filter = vtk.vtkAppendPolyData()
            for i in range(len(pdb_data[j])):
                input1 = vtk.vtkPolyData()
                sphere_source = vtk.vtkSphereSource()
                sphere_source.SetCenter(x[i], y[i], z[i])
                sphere_source.SetRadius(r[i])
                sphere_source.Update()
                input1.ShallowCopy(sphere_source.GetOutput())
                append_filter.AddInputData(input1)
            append_filter.Update()

            #  Remove Any Duplicate Points.
            clean_filter = vtk.vtkCleanPolyData()
            clean_filter.SetInputConnection(append_filter.GetOutputPort())
            clean_filter.Update()

            # Render Mesh
            pd = tvtk.to_tvtk(clean_filter.GetOutput())
            sphere_mapper = tvtk.PolyDataMapper()
            configure_input_data(sphere_mapper, pd)
            p = tvtk.Property(opacity=1.0, color=(0.0, 0.4, 0.8))
            sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
            v.scene.add_actor(sphere_actor)

    if centroids is not None:

        # Generate Mesh For Protein
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(centroids)):
            input1 = vtk.vtkPolyData()
            sphere_source = vtk.vtkSphereSource()
            sphere_source.SetCenter(centroids[i][0], centroids[i][1],
                                    centroids[i][2])
            sphere_source.SetRadius(2.0)
            sphere_source.Update()
            input1.ShallowCopy(sphere_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Mesh
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        sphere_mapper = tvtk.PolyDataMapper()
        configure_input_data(sphere_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0, 0.0, 0.0))
        sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
        v.scene.add_actor(sphere_actor)

    mlab.show()
Example #26
0
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        # Create the VTK widget.
        self._vtk_control = window = wxVTKRenderWindowInteractor(parent, -1,
                                                                 stereo=self.stereo)

        # Override these handlers.
        wx.EVT_CHAR(window, None) # Remove the default handler.
        wx.EVT_CHAR(window, self.OnKeyDown)
        wx.EVT_KEY_UP(window, None) # Remove the default handler.
        wx.EVT_KEY_UP(window, self.OnKeyUp)
        wx.EVT_PAINT(window, None) # Remove the default handler.
        wx.EVT_PAINT(window, self.OnPaint)
        wx.EVT_SIZE(window, None) # Remove the default handler.
        wx.EVT_SIZE(window, self.OnSize)
        # Override the button down and up handlers as well to note the
        # interaction.  This is to toggle the busy status nicely.
        for evt in (wx.EVT_LEFT_DOWN, wx.EVT_RIGHT_DOWN,
                    wx.EVT_MIDDLE_DOWN):
            evt(window, None)
            evt(window, self.OnButtonDown)
        for evt in (wx.EVT_LEFT_UP, wx.EVT_RIGHT_UP,
                    wx.EVT_MIDDLE_UP):
            evt(window, None)
            evt(window, self.OnButtonUp)

        # Enable the widget.
        window.Enable(1)
        # Switch the default interaction style to the trackball one.
        window.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        # Grab the renderwindow.
        renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow())
        renwin.set(point_smoothing=self.point_smoothing,
                   line_smoothing=self.line_smoothing,
                   polygon_smoothing=self.polygon_smoothing)
        # Create a renderer and add it to the renderwindow
        self._renderer = tvtk.Renderer()
        renwin.add_renderer(self._renderer)
        # Save a reference to our camera so it is not GC'd -- needed for
        # the sync_traits to work.
        self._camera = self.camera

        # Sync various traits.
        self._renderer.background = self.background
        self.sync_trait('background', self._renderer)
        self.renderer.on_trait_change(self.render, 'background')
        self._camera.parallel_projection = self.parallel_projection
        self.sync_trait('parallel_projection', self._camera)
        renwin.off_screen_rendering = self.off_screen_rendering
        self.sync_trait('off_screen_rendering', self._renwin)
        self.render_window.on_trait_change(self.render, 'off_screen_rendering')
        self.render_window.on_trait_change(self.render, 'stereo_render')
        self.render_window.on_trait_change(self.render, 'stereo_type')
        self.camera.on_trait_change(self.render, 'parallel_projection')

        def _show_parent_hack(window, parent):
            """A hack to get the VTK scene properly setup for use."""
            # Force the parent to show itself.
            parent.Show(1)
            # on some platforms, this SetSize() is necessary to cause
            # an OnPaint() when the event loop begins; else we get an
            # empty window until we force a redraw.
            window.SetSize(parent.GetSize())
            # This is necessary on slow machines in order to force the
            # wx events to be handled.
            wx.GetApp().Yield(True)
            window.Render()

        if wx.Platform == '__WXMSW__':
            _show_parent_hack(window, parent)
        else:
            if (wx.VERSION[0] == 2) and (wx.VERSION[1] < 5):
                _show_parent_hack(window, parent)
            window.Update()

        # Because of the way the VTK widget is setup, and because we
        # set the size above, the window sizing is usually completely
        # messed up when the application window is shown.  To work
        # around this a dynamic IDLE event handler is added and
        # immediately removed once it executes.  This event handler
        # simply forces a resize to occur.  The _idle_count allows us
        # to execute the idle function a few times (this seems to work
        # better).
        def _do_idle(event, window=window):
            w = wx.GetTopLevelParent(window)
            # Force a resize
            sz = w.GetSize()
            w.SetSize((sz[0]-1, sz[1]-1))
            w.SetSize(sz)
            window._idle_count -= 1
            if window._idle_count < 1:
                wx.EVT_IDLE(window, None)
                del window._idle_count

        window._idle_count = 2
        wx.EVT_IDLE(window, _do_idle)

        self._interactor = tvtk.to_tvtk(window._Iren)
        return window
Example #27
0
            b = float(j)/N
            v = 0.5 + 0.5*cos(13*a)*cos(8*b+3*a*a)
            v = v**2
            method(i,j,0,0,v)
    geometry_filter = vtk.vtkImageDataGeometryFilter()
    geometry_filter.SetInput(image_data)
    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry_filter.GetOutput())
    warp.SetScaleFactor(8.1)
    normal_filter = vtk.vtkPolyDataNormals()
    normal_filter.SetInput(warp.GetOutput())
    data_mapper = vtk.vtkDataSetMapper()
    data_mapper.SetInput(normal_filter.GetOutput())
    data_actor = vtk.vtkActor()
    data_actor.SetMapper(data_mapper)
    renderer.AddActor(data_actor)

    table = vtk.vtkLookupTable()
    data_mapper.SetLookupTable(table)

    # the actual gradient editor code.
    def on_color_table_changed():
        render_window.Render()

    # Gradient editor only works with tvtk objects, so convert the lut
    # to a tvtk version.
    tvtk_table = tvtk.to_tvtk(table)
    editor = GradientEditor(root, tvtk_table, on_color_table_changed)

    root.mainloop()
Example #28
0
            b = float(j) / N
            v = 0.5 + 0.5 * cos(13 * a) * cos(8 * b + 3 * a * a)
            v = v**2
            method(i, j, 0, 0, v)
    geometry_filter = vtk.vtkImageDataGeometryFilter()
    geometry_filter.SetInput(image_data)
    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry_filter.GetOutput())
    warp.SetScaleFactor(8.1)
    normal_filter = vtk.vtkPolyDataNormals()
    normal_filter.SetInput(warp.GetOutput())
    data_mapper = vtk.vtkDataSetMapper()
    data_mapper.SetInput(normal_filter.GetOutput())
    data_actor = vtk.vtkActor()
    data_actor.SetMapper(data_mapper)
    renderer.AddActor(data_actor)

    table = vtk.vtkLookupTable()
    data_mapper.SetLookupTable(table)

    # the actual gradient editor code.
    def on_color_table_changed():
        render_window.Render()

    # Gradient editor only works with tvtk objects, so convert the lut
    # to a tvtk version.
    tvtk_table = tvtk.to_tvtk(table)
    editor = GradientEditor(root, tvtk_table, on_color_table_changed)

    root.mainloop()
Example #29
0
def experiment(num_particles,timesteps):
    L = 1
    D = 1
    k2 = 1000.0
    k1 = k2/num_particles**3
    max_t = 1.0

    DAB = D+D;
    DABC = D + D*D/DAB;
    Rsq =  ( k1 / (4*3.14**3*(DAB*DABC)**(3.0/2.0) ) )**0.5;
    mol_dt = Rsq/10000;
    
 
    A = tyche.new_species(D)
    B = tyche.new_species(D)
    C = tyche.new_species(D)


    bd = tyche.new_diffusion()
    bd.add_species(A)
    bd.add_species(B)
    bd.add_species(C)
    
    xlow = tyche.new_xplane(0,1)
    xhigh = tyche.new_xplane(L,-1)
    ylow = tyche.new_yplane(0,1)
    yhigh = tyche.new_yplane(L,-1)
    zlow = tyche.new_zplane(0,1)
    zhigh = tyche.new_zplane(L,-1)


    xminboundary = tyche.new_jump_boundary(xlow,[L,0,0])
    xmaxboundary = tyche.new_jump_boundary(xhigh,[-L,0,0])
    yminboundary = tyche.new_jump_boundary(ylow,[0,L,0])
    ymaxboundary = tyche.new_jump_boundary(yhigh,[0,-L,0])
    zminboundary = tyche.new_jump_boundary(zlow,[0,0,L])
    zmaxboundary = tyche.new_jump_boundary(zhigh,[0,0,-L])

    boundaries = tyche.group([xminboundary, xmaxboundary, yminboundary, ymaxboundary, zminboundary, zmaxboundary])
    boundaries.add_species(A)
    boundaries.add_species(B)
    boundaries.add_species(C)

    dr3 = tyche.new_tri_reaction(k1, A, B, C, [B,C], mol_dt,
                          [0,0,0], [L,L,L], [True, True, True])
        
     
    dr = tyche.new_zero_reaction(k2,[0,0,0],[L,L,L])
    dr.add_species(A)

    algorithm = tyche.group([bd,boundaries,dr,dr3])
    
    A.fill_uniform([0,0,0],[L,L,L],int(num_particles))
    B.fill_uniform([0,0,0],[L,L,L],int(num_particles))
    C.fill_uniform([0,0,0],[L,L,L],int(num_particles))
    
    N = 1000
    output_dt = max_t/N
    time = 0;
    print algorithm
    
    grid = tvtk.to_tvtk(A.get_vtk())
    
    numA = np.zeros(N)
    for i in range(N):
        print A,B,C
        numA[i] = A.get_concentration([0,0,0],[L,L,L],[1,1,1])[0]
        print 'time = ',time,' ',i*100.0/N,' percent done'
        time = algorithm.integrate_for_time(output_dt,mol_dt)
#        grid = tvtk.to_tvtk(A.get_vtk())
#        g = init_vis(grid)
    print algorithm
    return numA