示例#1
0
 def picker_callback(self,picker_obj, evt):
     print self.scene.mlab.view()
     picker_obj = tvtk.to_tvtk(picker_obj)
     position =  picker_obj.pick_position
     self.volumeEditor.changeSlice(int(position[0]-1),0)
     self.volumeEditor.changeSlice(int(position[1]-1),1)
     self.volumeEditor.changeSlice(int(position[2]-1),2)
示例#2
0
def update_offset(widget, event):
    ipw = tvtk.to_tvtk(widget)
    translate = reslice.reslice_axes_origin
    ipw.update_traits()
    translate[0] = ipw.slice_position - p2_pos
    print 'translation:', translate
    reslice.reslice_axes_origin = (ipw.slice_position-p2_pos), 0, 0
示例#3
0
 def picker_callback(self, picker_obj, evt):
     print self.scene.mlab.view()
     picker_obj = tvtk.to_tvtk(picker_obj)
     position = picker_obj.pick_position
     self.volumeEditor.changeSlice(int(position[0] - 1), 0)
     self.volumeEditor.changeSlice(int(position[1] - 1), 1)
     self.volumeEditor.changeSlice(int(position[2] - 1), 2)
示例#4
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()
示例#5
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()
示例#6
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.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
示例#7
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
示例#8
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
示例#9
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
示例#10
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()
示例#11
0
文件: xipy_fos.py 项目: cindeem/xipy
def tvtk_line(lines, colors, opacity=1.0):
    ''' Create an actor for one or more lines.    
    
    Parameters
    ----------
    lines :  list of arrays representing lines as 3d points  for example            
            lines=[np.random.rand(10,3),np.random.rand(20,3)]   
            represents 2 lines the first with 10 points and the second with
            20 points in x,y,z coordinates.
    colors : array, shape (N,3)
            Colormap where every triplet is encoding red, green and blue e.g. 
            r1,g1,b1
            r2,g2,b2
            ...
            rN,gN,bN        
            
            where
            0=<r<=1,
            0=<g<=1,
            0=<b<=1
            
    opacity : float, default 1
                    0<=transparency <=1
    linewidth : float, default is 1
                    line thickness
                    
    
    Returns
    ----------
    vtkActor object
    
    Examples
    --------    
    >>> from <???> import fos
    >>> from enthought.mayavi import mlab
    >>> lines=[np.random.rand(10,3),np.random.rand(20,3)]    
    >>> colors=np.random.rand(2,3)
    >>> c=fos.line(lines,colors)
    >>> f = mlab.figure()
    >>> f.scene.add_actor(c)
    '''
    cell_lines = tvtk.CellArray()
    line_scalars = tvtk.FloatArray()
    pts = tvtk.Points()

    LUT = tvtk.to_tvtk(_lookup(colors))
    LUT.table_range = (0, LUT.number_of_colors)
    multicolor = (LUT.number_of_colors > 1)
    list_of_colors = []
    color_level = 0

    lcnts = np.array([ len(line) for line in lines ])
    total_pts = lcnts.sum()
    flattened_pts = np.empty((total_pts, 3), lines[0].dtype)
    lc = 0
    for n in xrange(len(lines)):
        flattened_pts[lc:lc+lcnts[n]] = lines[n]
        cell_lines.insert_next_cell( range(lc, lc+lcnts[n]) )
        if multicolor:
            list_of_colors += [color_level] * lcnts[n]
            color_level += 1
        lc += lcnts[n]

    pts.data.from_array(flattened_pts)
    
    if multicolor:
        line_scalars.from_array( np.array(list_of_colors) )
    else:
        line_scalars.from_array( np.zeros(pts.number_of_points) )

    pd = tvtk.PolyData()
    pd.lines = cell_lines
    pd.points = pts
    pd.point_data.scalars = line_scalars
    pd.point_data.scalars.name = 'lines'
    return pd, LUT
示例#12
0
    def _nodepicked_callback(self, picker_obj, evt):
        """ The callback function to determine what to do with a picked node """
        from enthought.tvtk.api import tvtk

        picker_obj = tvtk.to_tvtk(picker_obj)
        picked = picker_obj.actors

        # if picked actor are the glyphs
        if self.nodes.actor.actor._vtk_obj in [o._vtk_obj for o in picked]:

            pos = picker_obj.picked_positions[0]
            
            dist_small = sys.maxint # the biggest integer
            
            for i, points in enumerate(self.nodes.mlab_source.points):
                # if picked positions ON a node
                dist = np.linalg.norm((np.array(pos)-  points))
                # save the smallest distance node
                if dist <= dist_small:
                    j = i
                    dist_small = dist

            # get the id of the picked node
            picknodeid = 'n' + str(j+1)

            if self.nodepicker.show_info:
                
                # generate a nice view for the information
                nodedata = self.network.graph.node[picknodeid]

                nodedata['dn_internal_id'] = picknodeid

                deg = self.network.graph.degree(picknodeid)
                from types import IntType, StringType
                if type(deg) == IntType or type(deg) == StringType:
                    nodedata['degree'] = deg
                    
                # does this node has a self-loop?
                if self.network.graph.has_edge(picknodeid, picknodeid):
                    nodedata['has_selfloop'] = True
                else:
                    nodedata['has_selfloop'] = True
                    
                mynode = Node(nodedata=nodedata)
                mynode.configure_traits()
            

            elif self.nodepicker.toggle_selection:
                # toggles the selection of a node
                if self.datasourcemanager._srcobj.selected_nodes[j] == 1:
                    # unpick
                    self._select_nodes(selection_node_array = np.array([j]), \
                                       first_is_selected = True, change_vector = False)
                else:
                    # pick
                    self._select_nodes(selection_node_array = np.array([j]), activate = True, \
                                       first_is_selected = True, change_vector = False)

            elif self.nodepicker.select_node:
                # toggle the picking state              
                if self.datasourcemanager._srcobj.selected_nodes[j] == 1:
                    # unpick
                    self._select_nodes(selection_node_array = np.array([j]), \
                                       first_is_selected = True)
                else:
                    # pick
                    self._select_nodes(selection_node_array = np.array([j]), activate = True, \
                                       first_is_selected = True)

            elif self.nodepicker.select_node2:
                
                # get the neighbors of the picked node in an array
                nbrs = self.datasourcemanager._srcobj.relabled_graph.neighbors(j)
                # put the two lists together
                cur_nodes = np.append(j, np.array(nbrs))
                
                if self.datasourcemanager._srcobj.selected_nodes[j] == 1:
                    # unpick
                    self._select_nodes(selection_node_array = cur_nodes, \
                                       first_is_selected = True)
                else:
                    # pick
                    self._select_nodes(selection_node_array = cur_nodes, activate = True ,\
                                       first_is_selected = True)
                    
            elif self.nodepicker.toggle_label:
                
                if self.node_labels.has_key(j):
                    # we want to remove the node label from the pipeline first
                    # and then delete the entry in the dictionary
                    a = self.node_labels[j]
                    a.remove()
                    del self.node_labels[j]
                    
                else:
                    srcobj = self.datasourcemanager._srcobj
                    # create the text3d instance and add it to the dictionary
                    from enthought.mayavi import mlab
                    a = mlab.text3d(srcobj.positions[j,0], srcobj.positions[j,1], \
                                                srcobj.positions[j,2], \
                                                '     ' + srcobj.labels[j], # white spaces are hackish
                                                name = 'Node ' + srcobj.labels[j])
                    self.node_labels[j] = a

            else:
                logger.info("No valid pick operation.")
示例#13
0
文件: scene.py 项目: sjl421/code-2
    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
示例#14
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