コード例 #1
0
ファイル: box_picker.py プロジェクト: mjredmond/FEMApp
    def __init__(self):
        vtkCameraManipulator.__init__(self)

        self.picked_data = None
        self.box_picker = vtk.vtkExtractSelectedFrustum()
        self._start_position = [0, 0]
        self._end_position = [0, 0]
        self._pixel_array = vtk.vtkUnsignedCharArray()

        self.ex = vtk.vtkExtractSelection()
        self.selection_node = vtk.vtkSelectionNode()
        self.selection_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS)
        self.ex_selection = vtk.vtkSelection()
        self.ex_selection.AddNode(self.selection_node)

        self.ex.SetInputConnection(0, self.box_picker.GetOutputPort())
        self.ex.SetInputData(1, self.ex_selection)

        self._down_pos = None
        self._up_pos = None

        self.iren = None
        self.ren_win = None
        self.ren_win_size = None

        self.data_picked = MrSignal()
        self.done_picking = MrSignal()

        self._picking_active = False

        # self.vtk_graphics = VTKGraphics.instance()

        from .picking_manager import PickingManager
        self.picking_manager = PickingManager.instance()
コード例 #2
0
    def __init__(self):
        VTKPythonAlgorithmBase.__init__(self,
                                        nInputPorts=1,
                                        inputType='vtkUnstructuredGrid',
                                        nOutputPorts=1,
                                        outputType='vtkUnstructuredGrid')

        self.selection_list = vtk.vtkIntArray()
        self.selection_node = vtk.vtkSelectionNode()
        self.selection = vtk.vtkSelection()
        self.ex = vtk.vtkExtractSelection()

        self.active_groups = set()
        self.active_types = set()
        self.visible_ids = set()
        self.visible_on = True

        self.selection_list.SetName('visible')
        self.selection_list.SetNumberOfValues(2)
        self.selection_list.SetValue(0, 1)
        self.selection_list.SetValue(1, 1)

        self.selection_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS)
        self.selection_node.SetSelectionList(self.selection_list)
        self.selection.AddNode(self.selection_node)
        self.ex.ReleaseDataFlagOn()
        self.ex.SetInputDataObject(1, self.selection)
コード例 #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkExtractSelection(), 'Processing.',
         ('vtkDataSet', 'vtkSelection'), ('vtkDataSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
コード例 #4
0
ファイル: case.py プロジェクト: JLoos92/master_thesis
    def extract_boundary_cells(self, boundary):
        """Extract cells adjacent to a certain boundary.

        Parameters
        ----------
        boundary : str
            The name of the boundary.

        Returns
        -------
            vtkExtractSelection

        """
        if boundary not in self.vtkData.FieldData.keys():
            raise(NameError("No boundary named "+boundary))

        cellIds = self.vtkData.FieldData[boundary]
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(numpy_to_vtk(cellIds))

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        extractSelection = vtk.vtkExtractSelection()

        extractSelection.SetInputData(0, self.vtkData.VTKObject)
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()

        return extractSelection
コード例 #5
0
    def __init__(self):
        VTKPythonAlgorithmBase.__init__(self)

        self.SetNumberOfInputPorts(1)
        self.SetNumberOfOutputPorts(1)

        self.visible = True

        self.visible_selection = vtk.vtkIntArray()
        self.visible_selection.SetName("visible")
        self.visible_selection.InsertNextValue(1)
        self.visible_selection.InsertNextValue(1)

        self.selection_vis_node = vtk.vtkSelectionNode()
        self.selection_vis_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS)
        self.selection_vis_node.SetSelectionList(self.visible_selection)

        self.selection_vis = vtk.vtkSelection()
        self.selection_vis.AddNode(self.selection_vis_node)

        self.ex_vis = vtk.vtkExtractSelection()
        self.ex_vis.ReleaseDataFlagOn()
        self.ex_vis.SetInputDataObject(1, self.selection_vis)

        self._callbacks = []
コード例 #6
0
ファイル: utils.py プロジェクト: RomainUSA/fly-by-cnn
def ExtractFiber(surf, list_random_id):
    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)
    ids.InsertNextValue(list_random_id)

    # extract a subset from a dataset
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(0)
    selectionNode.SetContentType(4)
    selectionNode.SetSelectionList(ids)

    # set containing cell to 1 = extract cell
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.CONTAINING_CELLS(),
                                      1)

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    # extract the cell from the cluster
    extractSelection = vtk.vtkExtractSelection()
    extractSelection.SetInputData(0, surf)
    extractSelection.SetInputData(1, selection)
    extractSelection.Update()

    # convert the extract cell to a polygonal type (a line here)
    geometryFilter = vtk.vtkGeometryFilter()
    geometryFilter.SetInputData(extractSelection.GetOutput())
    geometryFilter.Update()

    tubefilter = GetTubeFilter(geometryFilter.GetOutput())

    return tubefilter
コード例 #7
0
ファイル: colorpicker.py プロジェクト: devarajun/uvcdat
    def selectCell(self, cellId):
        if cellId in (None, -1):
            return
        ids = vtk.vtkIdTypeArray();
        ids.SetNumberOfComponents(1);
        ids.InsertNextValue(cellId);

        selectionNode = vtk.vtkSelectionNode();
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL);
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES);
        selectionNode.SetSelectionList(ids);

        selection = vtk.vtkSelection();
        selection.AddNode(selectionNode);

        extractSelection = vtk.vtkExtractSelection();

        extractSelection.SetInputData(0, self.actor.GetMapper().GetInput());
        extractSelection.SetInputData(1, selection);

        extractSelection.Update();

        selected = vtk.vtkUnstructuredGrid();
        selected.ShallowCopy(extractSelection.GetOutput());

        self.selectedMapper.SetInputData(selected);
        self.selectedMapper.Update()
コード例 #8
0
def _extract(polydata, celltypes):
    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    for i in range(polydata.GetNumberOfCells()):
        c = polydata.GetCell(i)
        if c.GetCellType() in celltypes:
            ids.InsertNextValue(i)

    sn = vtk.vtkSelectionNode()
    sn.SetFieldType(vtk.vtkSelectionNode.CELL)
    sn.SetContentType(vtk.vtkSelectionNode.INDICES)
    sn.SetSelectionList(ids)

    sel = vtk.vtkSelection()
    sel.AddNode(sn)

    es = vtk.vtkExtractSelection()
    es.SetInputData(0, polydata)
    es.SetInputData(1, sel)
    es.Update()

    gf = vtk.vtkGeometryFilter()
    gf.SetInputConnection(es.GetOutputPort())
    return gf
コード例 #9
0
def extractRegion(mesh, selection_nodes, vprint):
    #Intialize variables
    ids = vtk.vtkIdTypeArray()
    cell_nodes = vtk.vtkIdList()
    cell_vtk_Id_list = vtk.vtkIdList()
    cellIds = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    #Determines the cells enclosed by selection_nodes (which are points)
    for i in xrange(0, selection_nodes.GetNumberOfIds()):
        ids.InsertNextValue(selection_nodes.GetId(i))
        mesh.GetPointCells(selection_nodes.GetId(i), cell_nodes)
        for i in xrange(0, cell_nodes.GetNumberOfIds()):
            cell_vtk_Id_list.InsertUniqueId(cell_nodes.GetId(i))

    #Converts the vtkIdList into vtkIdTypeArray
    for i in xrange(0, cell_vtk_Id_list.GetNumberOfIds()):
        cellIds.InsertNextValue(cell_vtk_Id_list.GetId(i))

    #Creates the selection object to extract the subset of cells from the mesh
    region = vtk.vtkExtractSelection()
    region.SetInputData(0, mesh)
    tempCells = vtk.vtkSelectionNode()
    tempCells.SetFieldType(vtk.vtkSelectionNode.CELL)
    tempCells.SetContentType(vtk.vtkSelectionNode.INDICES)
    tempCells.SetSelectionList(cellIds)
    tempSelection = vtk.vtkSelection()
    tempSelection.AddNode(tempCells)
    region.SetInputData(1, tempSelection)
    region.Update()

    #Outputs the mesh as an unstructured grid object
    output = vtk.vtkUnstructuredGrid()
    output.ShallowCopy(region.GetOutput())
    return output
コード例 #10
0
ファイル: colorpicker.py プロジェクト: govtmirror/uvcdat
    def selectCell(self, cellId):
        if cellId in (None, -1):
            return
        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        ids.InsertNextValue(cellId)

        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(ids)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        extractSelection = vtk.vtkExtractSelection()

        extractSelection.SetInputData(0, self.actor.GetMapper().GetInput())
        extractSelection.SetInputData(1, selection)

        extractSelection.Update()

        selected = vtk.vtkUnstructuredGrid()
        selected.ShallowCopy(extractSelection.GetOutput())

        self.selectedMapper.SetInputData(selected)
        self.selectedMapper.Update()
コード例 #11
0
ファイル: grid.py プロジェクト: leapmanlab/vtkInterface
    def ExtractSelectionPoints(self, ind):
        """
        Returns a subset of an unstructured grid

        Parameters
        ----------
        ind : np.ndarray
            Numpy array of point indices to be extracted.

        Returns
        -------
        subgrid : vtki.UnstructuredGrid
            Subselected grid.

        """
        # Convert to vtk indices
        if ind.dtype != np.int64:
            ind = ind.astype(np.int64)
        vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=True)

        # Create selection objects
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(vtk_ind)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # extract
        extractSelection = vtk.vtkExtractSelection()
        extractSelection.SetInputData(0, self)
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()
        return UnstructuredGrid(extractSelection.GetOutput())
コード例 #12
0
def isolateCap(model, cap, caps_location):
    cap_vtp = intializeVTP(caps_location + '/' + cap + '.vtp')
    cellIds = vtk.vtkIdTypeArray()
    cap_cell_set = set()
    for i_cell in range(0, cap_vtp.GetNumberOfCells()):
        cap_cell_set.add(
            cap_vtp.GetCellData().GetArray('GlobalElementID').GetValue(i_cell))
    for i_cell in range(0, model.GetNumberOfCells()):
        if (model.GetCellData().GetArray('GlobalElementID').GetValue(i_cell)
                in cap_cell_set):
            cellIds.InsertNextValue(i_cell)
    #print(cellIds.GetNumberOfValues())
    #Creates the selection object to extract the subset of cells from the mesh
    region = vtk.vtkExtractSelection()
    region.SetInputData(0, model)
    tempCells = vtk.vtkSelectionNode()
    tempCells.SetFieldType(vtk.vtkSelectionNode.CELL)
    tempCells.SetContentType(vtk.vtkSelectionNode.INDICES)
    tempCells.SetSelectionList(cellIds)
    tempSelection = vtk.vtkSelection()
    tempSelection.AddNode(tempCells)
    region.SetInputData(1, tempSelection)
    region.Update()

    #Outputs the mesh as an polyData object
    dssf = vtk.vtkDataSetSurfaceFilter()
    dssf.SetInputConnection(region.GetOutputPort())
    dssf.Update()
    return dssf.GetOutput(), cellIds
コード例 #13
0
    def extractCellsByID(self, idlist, usePointIDs=False):
        """Return a new TetMesh composed of the specified subset of indices."""
        selectionNode = vtk.vtkSelectionNode()
        if usePointIDs:
            selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT)
            contcells = vtk.vtkSelectionNode.CONTAINING_CELLS()
            selectionNode.GetProperties().Set(contcells, 1)
        else:
            selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        vidlist = numpy_to_vtkIdTypeArray(np.array(idlist).astype(np.int64))
        selectionNode.SetSelectionList(vidlist)
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)
        es = vtk.vtkExtractSelection()
        es.SetInputData(0, self._ugrid)
        es.SetInputData(1, selection)
        es.Update()
        tm_sel = TetMesh(es.GetOutput())
        pr = vtk.vtkVolumeProperty()
        pr.DeepCopy(self.GetProperty())
        tm_sel.SetProperty(pr)

        #assign the same transformation to the copy
        tm_sel.SetOrigin(self.GetOrigin())
        tm_sel.SetScale(self.GetScale())
        tm_sel.SetOrientation(self.GetOrientation())
        tm_sel.SetPosition(self.GetPosition())
        tm_sel._mapper.SetLookupTable(utils.ctf2lut(self))
        return tm_sel
コード例 #14
0
def extract_fiber(bundle, ids):
    print "ids selected: ", ids.GetNumberOfTuples()
    sys.stdout.flush()
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection = vtk.vtkSelection()
    extractSelection = vtk.vtkExtractSelection()
    vtu2vtkFilter = vtk.vtkDataSetSurfaceFilter()

    selectionNode.SetSelectionList(ids)
    selection.AddNode(selectionNode)
    if vtk.VTK_MAJOR_VERSION > 5:
        extractSelection.SetInputData(0, bundle)
        del bundle
        extractSelection.SetInputData(1, selection)
        del selection
        extractSelection.Update()
        vtu2vtkFilter.SetInputData(extractSelection.GetOutput())
        del extractSelection
    else:
        extractSelection.SetInput(0, bundle)
        del bundle
        extractSelection.SetInput(1, selection)
        del selection
        extractSelection.Update()
        vtu2vtkFilter.SetInput(extractSelection.GetOutput())
        del extractSelection
    vtu2vtkFilter.Update()
    extract = vtk.vtkPolyData()
    extract = vtu2vtkFilter.GetOutput()
    del vtu2vtkFilter
    del selectionNode
    return extract
コード例 #15
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkExtractSelection(),
                                       'Processing.',
                                       ('vtkDataSet', 'vtkSelection'),
                                       ('vtkDataSet', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
コード例 #16
0
    def __init__(self):
        VTKPythonAlgorithmBase.__init__(self)

        self.SetNumberOfInputPorts(1)
        self.SetNumberOfOutputPorts(1)

        self.selection_group = vtk.vtkSelection()

        self.ex_group = vtk.vtkExtractSelection()
        self.ex_group.ReleaseDataFlagOn()
        self.ex_group.SetInputDataObject(1, self.selection_group)
コード例 #17
0
def extract_selection_node_from_grid_to_ugrid(grid, selection_node):
    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    extract_selection.SetInputData(0, grid)
    extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    ugrid = extract_selection.GetOutput()
    return ugrid
コード例 #18
0
    def _highlight_picker_by_selection_node(self, grid, selection_node,
                                            representation='surface'):
        selection = vtk.vtkSelection()
        selection.AddNode(selection_node)

        extract_selection = vtk.vtkExtractSelection()
        extract_selection.SetInputData(0, grid)
        extract_selection.SetInputData(1, selection)
        extract_selection.Update()

        ugrid = extract_selection.GetOutput()
        return self.create_highlighted_actor(ugrid, representation=representation)
コード例 #19
0
ファイル: grid.py プロジェクト: leapmanlab/vtkInterface
    def ExtractSelectionCells(self, ind):
        """
        Returns a subset of the grid

        Parameters
        ----------
        ind : np.ndarray
            Numpy array of cell indices to be extracted.

        Returns
        -------
        subgrid : vtki.UnstructuredGrid
            Subselected grid

        """
        # Convert to vtk indices
        if not isinstance(ind, np.ndarray):
            ind = np.array(ind, np.int64)

        if ind.dtype == np.bool:
            ind = ind.nonzero()[0]

        if ind.dtype != np.int64:
            ind = ind.astype(np.int64)

        if not ind.flags.c_contiguous:
            ind = np.ascontiguousarray(ind)

        vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=True)

        # Create selection objects
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(vtk_ind)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # extract
        extractSelection = vtk.vtkExtractSelection()
        extractSelection.SetInputData(0, self)
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()
        subgrid = UnstructuredGrid(extractSelection.GetOutput())

        # extracts only in float32
        if self.GetNumpyPoints().dtype is not np.dtype('float32'):
            ind = subgrid.GetPointScalars('vtkOriginalPointIds')
            subgrid.SetNumpyPoints(self.GetNumpyPoints()[ind])

        return subgrid
コード例 #20
0
    def leftButtonPressEvent(self, obj, event):
        # obj is a vtkInteractorStyleTrackballCamera
        # event is just a string
        pos = self.GetInteractor().GetEventPosition()
        print pos

        picker = vtk.vtkCellPicker()
        picker.SetTolerance(0.0005)
        picker.Pick(pos[0], pos[1], 0, self.GetDefaultRenderer())
        worldPosition = picker.GetPickPosition()

        if (picker.GetCellId() != -1):
            # clicked on object
            # print worldPosition
            ids = vtk.vtkIdTypeArray()
            ids.SetNumberOfComponents(1)
            ids.InsertNextValue(picker.GetCellId())

            selectionNode = vtk.vtkSelectionNode()
            selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
            selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
            selectionNode.SetSelectionList(ids)

            selection = vtk.vtkSelection()
            selection.AddNode(selectionNode)

            extractSelection = vtk.vtkExtractSelection()
            extractSelection.SetInput(0, self.Data)
            extractSelection.SetInput(1, selection)
            extractSelection.Update()

            selected = vtk.vtkUnstructuredGrid()
            selected = extractSelection.GetOutput()

            # points in object frame
            # print "NumP points: ", selected.GetNumberOfPoints()
            # for i in xrange(0, selected.GetNumberOfPoints()):
            #     print selected.GetPoint(i)

            self.selectedMapper.SetInputConnection(selected.GetProducerPort())

            self.selectedActor.SetMapper(self.selectedMapper)
            self.selectedActor.GetProperty().EdgeVisibilityOn()
            self.selectedActor.GetProperty().SetEdgeColor(1, 0, 0)
            self.selectedActor.GetProperty().SetLineWidth(3)

            self.GetInteractor().GetRenderWindow().GetRenderers(
            ).GetFirstRenderer().AddActor(self.selectedActor)
            self.GetInteractor().GetRenderWindow().Render()

        self.OnLeftButtonDown()
        return
コード例 #21
0
    def __init__(self):
        VTKPythonAlgorithmBase.__init__(self,
                                        nInputPorts=1, inputType='vtkUnstructuredGrid',
                                        nOutputPorts=4, outputType='vtkUnstructuredGrid')

        self.selection_node = vtk.vtkSelectionNode()
        self.selection = vtk.vtkSelection()
        self.ex = vtk.vtkExtractSelection()
        self.ex.ReleaseDataFlagOn()

        self.selection_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS)
        self.selection.AddNode(self.selection_node)
        self.ex.SetInputDataObject(1, self.selection)
コード例 #22
0
ファイル: main.py プロジェクト: orxshi/stencilwalkgui
    def leftButtonPressEvent(self, obj, event):
        clickPos = self.GetInteractor().GetEventPosition()

        picker = vtk.vtkCellPicker()
        picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer())

        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        ids.InsertNextValue(picker.GetCellId())

        self.NewPickedActor = picker.GetActor()

        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(4)
        selectionNode.SetSelectionList(ids)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        extractSelection = vtk.vtkExtractSelection()
        extractSelection.SetInputData(0, self.user_data)
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()
        selected = extractSelection.GetOutput()

        if selected:
            if not self.currentactor:
                newactor = vtk.vtkActor()
                self.currectactor = newactor
            else:
                newactor = self.currentactor

            newmapper = vtk.vtkDataSetMapper()
            newmapper.SetInputData(selected)
            newmapper.SetScalarVisibility(0)
            newactor.SetMapper(newmapper)
            newactor.GetProperty().SetColor(0.0, 1.0, 0.0)
            newactor.GetProperty().EdgeVisibilityOn()
            self.ren.AddActor(newactor)
            self.rw.Render()

            if self.LastPickedActor:
                self.LastPickedActor.GetProperty().SetColor(1.0, 1.0, 1.0)
                self.LastPickedActor.GetProperty().EdgeVisibilityOn()

            self.LastPickedActor = newactor

        self.OnLeftButtonDown()
        self.RemoveObserver(self.leftag)
        return picker.GetCellId()
コード例 #23
0
    def __init__(self, main_window):
        super(VTKWidget, self).__init__()

        self.renderer = vtk.vtkRenderer()
        self.renderer_picked = vtk.vtkRenderer()
        self.renderer_hovered = vtk.vtkRenderer()

        self.data_source = BDFDataSource()
        self.group_selections_ = vtk.vtkPolyData()
        self.group_filter = GroupFilter()
        self.visible_filter = VisibleFilter()

        self.main_pipeline = MainPipelineHelper(self.renderer)
        self.selected_pipeline = SelectedPipelineHelper(
            self, self.renderer_picked)
        self.hovered_pipeline = HoveredPipelineHelper(self,
                                                      self.renderer_hovered)

        self.set_up_pipeline()
        self.set_up_view(main_window)

        self.visible_filter.add_callback(
            self.interactor_style.model_picker.set_data)

        ui = self.main_window.ui

        ui.left_click_combo.currentIndexChanged[str].connect(
            self.interactor_style.set_left_button)
        ui.middle_click_combo.currentIndexChanged[str].connect(
            self.interactor_style.set_middle_button)
        ui.right_click_combo.currentIndexChanged[str].connect(
            self.interactor_style.set_right_button)
        ui.ctrl_left_click_combo.currentIndexChanged[str].connect(
            self.interactor_style.set_ctrl_left_button)

        self.show_hide = False
        self.show = True

        self.bdf = None

        self.toggle_filter = vtk.vtkExtractSelection()
        self.toggle_filter.SetInputConnection(0,
                                              self.visible_filter.all_port())

        self.toggle_selection_node = vtk.vtkSelectionNode()
        self.toggle_selection_node.SetContentType(
            vtk.vtkSelectionNode.GLOBALIDS)
        self.toggle_selection = vtk.vtkSelection()
        self.toggle_selection.AddNode(self.toggle_selection_node)

        self.toggle_filter.SetInputData(1, self.toggle_selection)
コード例 #24
0
ファイル: Selection.py プロジェクト: andrsd/otter
    def __init__(self, data):
        """
        @param data vtkDataObject that will be "filtered" to extract the
                    selection
        """
        self._extract_selection = vtk.vtkExtractSelection()
        self._extract_selection.SetInputData(0, data)

        self._selected = vtk.vtkUnstructuredGrid()

        self._mapper = vtk.vtkDataSetMapper()
        self._mapper.SetInputData(self._selected)

        self._actor = vtk.vtkActor()
        self._actor.SetMapper(self._mapper)
コード例 #25
0
 def extractCellType(self, ctype):
     """Extract a specific cell type and return a new UGrid."""
     uarr = self._data.GetCellTypesArray()
     ctarrtyp = np.where(vtk_to_numpy(uarr) == ctype)[0]
     uarrtyp = numpy_to_vtkIdTypeArray(ctarrtyp, deep=False)
     selectionNode = vtk.vtkSelectionNode()
     selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
     selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
     selectionNode.SetSelectionList(uarrtyp)
     selection = vtk.vtkSelection()
     selection.AddNode(selectionNode)
     es = vtk.vtkExtractSelection()
     es.SetInputData(0, self._data)
     es.SetInputData(1, selection)
     es.Update()
     return UGrid(es.GetOutput())
コード例 #26
0
  def renderSegmentedData(self, modelNode, outputModelNode, selectedTexture):
	
    fullPolyData = modelNode.GetPolyData()
    pointData=fullPolyData.GetPointData()
	
    data = np.load('C:/Users/Brand/OneDrive/Documents/CISC 472/test segmentation_model/classified_texture.pkl')
    size_of_data = data.shape
    print(size_of_data)
    print(int(data[1][0]))
    print(' ')
    print(selectedTexture)
	
    segmentedPointIds = vtk.vtkIdTypeArray()

    print('begin classifiacation')
    for point in range(size_of_data[1]):
      if int(data[1][point]) == selectedTexture:
        segmentedPointIds.InsertNextValue(int(data[0][point]))
        segmentedPointIds.InsertNextValue(int(data[0][point]))
		
    print('calssification done')
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selectionNode.SetSelectionList(segmentedPointIds)
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.CONTAINING_CELLS(), 1);

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    extractSelection = vtk.vtkExtractSelection()
    extractSelection.SetInputData(0,fullPolyData)
    extractSelection.SetInputData(1,selection);
    extractSelection.Update();
	
    convertToPolydata = vtk.vtkDataSetSurfaceFilter()
    convertToPolydata.SetInputConnection(extractSelection.GetOutputPort())
    convertToPolydata.Update()
    outputModelNode.SetAndObservePolyData(convertToPolydata.GetOutput())

    if not outputModelNode.GetDisplayNode():
      md2 = slicer.vtkMRMLModelDisplayNode()
      slicer.mrmlScene.AddNode(md2)
      outputModelNode.SetAndObserveDisplayNodeID(md2.GetID()) 
	
    print('done?')
    return 0	
コード例 #27
0
        def extract_using_vtk(self, ids):
            node = vtk.vtkSelectionNode()
            sel = vtk.vtkSelection()
            node.GetProperties().Set(vtk.vtkSelectionNode.CONTENT_TYPE(),\
                                     vtk.vtkSelectionNode.INDICES)
            node.GetProperties().Set(vtk.vtkSelectionNode.FIELD_TYPE(),\
                                     vtk.vtkSelectionNode.POINT)

            #Create Id Array with point Ids for each cluster
            vtk_ids = numpy_to_vtkIdTypeArray(ids)
            node.SetSelectionList(vtk_ids)
            #sel_filter = vtk.vtkExtractSelectedPolyDataIds()
            sel_filter = vtk.vtkExtractSelection()
            sel_filter.SetInput(0, self._in_vtk)
            sel_filter.SetInput(1, sel)
            sel_filter.Update()
            return sel_filter.GetOutput()
コード例 #28
0
 def extract_using_vtk(self,ids):
   node=vtk.vtkSelectionNode()
   sel = vtk.vtkSelection()
   node.GetProperties().Set(vtk.vtkSelectionNode.CONTENT_TYPE(),\
                            vtk.vtkSelectionNode.INDICES)
   node.GetProperties().Set(vtk.vtkSelectionNode.FIELD_TYPE(),\
                            vtk.vtkSelectionNode.POINT)
   
   #Create Id Array with point Ids for each cluster
   vtk_ids=numpy_to_vtkIdTypeArray(ids)
   node.SetSelectionList(vtk_ids)
   #sel_filter = vtk.vtkExtractSelectedPolyDataIds()
   sel_filter = vtk.vtkExtractSelection()
   sel_filter.SetInput(0,self._in_vtk)
   sel_filter.SetInput(1,sel)
   sel_filter.Update()
   return sel_filter.GetOutput()
コード例 #29
0
    def update_ids(self):
        if self.ClosestCellId != -1:
            return

        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(self.id_array)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        extractSelection = vtk.vtkExtractSelection()
        extractSelection.SetInputData(0, self.GetDataSet())
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()

        cc = vtk.vtkCellCenters()
        cc.VertexCellsOff()
        cc.SetInputData(extractSelection.GetOutput())
        cc.Update()

        poly_data = cc.GetOutput()

        min_d = 999999999.

        line = vtk.vtkLine()

        min_i = -1

        self.p_min = None

        #print poly_data.GetNumberOfPoints()

        for i in xrange(poly_data.GetNumberOfPoints()):
            p = poly_data.GetPoint(i)
            d = line.DistanceToLine(p, self.p1World[:3], self.p2World[:3])

            if d < min_d:
                min_i = i
                min_d = d
                self.p_min = p

        if min_i >= 0:
            self.ClosestCellId = self.id_list[min_i]
            self.ClosestCellGlobalId = self.global_id_list[min_i]
コード例 #30
0
def extract_selection_node_from_grid_to_ugrid(grid, selection_node):
    """
    Creates a sub-UGRID from a UGRID and a vtkSelectionNode.  In other
    words, we use a selection criteria (a definition of a subset of
    points or cells) and we create a reduced model.

    """
    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    extract_selection.SetInputData(0, grid)
    extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    ugrid = extract_selection.GetOutput()
    return ugrid
コード例 #31
0
def extractRegionVolume(mesh, selection_nodes):
    #Intialize variables
    ids = vtk.vtkIdTypeArray()
    cell_nodes = vtk.vtkIdList()
    cell_vtk_Id_list = vtk.vtkIdList()
    cellIds = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    #Determines the cells enclosed by selection_nodes (which are points)
    vprint('Number of nodes in this volume: ',
           selection_nodes.GetNumberOfIds())
    for i in range(0, selection_nodes.GetNumberOfIds()):
        ids.InsertNextValue(selection_nodes.GetId(i))
        mesh.GetPointCells(selection_nodes.GetId(i), cell_nodes)
        for j in range(0, cell_nodes.GetNumberOfIds()):
            cell_vtk_Id_list.InsertUniqueId(cell_nodes.GetId(j))

    #Converts the vtkIdList into vtkIdTypeArray
    for i in range(0, cell_vtk_Id_list.GetNumberOfIds()):
        cellIds.InsertNextValue(cell_vtk_Id_list.GetId(i))
    vprint('Number of cells in this volume: ',
           cell_vtk_Id_list.GetNumberOfIds())
    #Creates the selection object to extract the subset of cells from the mesh
    region = vtk.vtkExtractSelection()
    region.SetInputData(0, mesh)
    tempCells = vtk.vtkSelectionNode()
    tempCells.SetFieldType(vtk.vtkSelectionNode.CELL)
    tempCells.SetContentType(vtk.vtkSelectionNode.INDICES)
    tempCells.SetSelectionList(cellIds)
    tempSelection = vtk.vtkSelection()
    tempSelection.AddNode(tempCells)
    region.SetInputData(1, tempSelection)
    region.Update()

    #Outputs the mesh as an Mass object
    output = vtk.vtkPolyData()
    output.ShallowCopy(region.GetOutput())
    vprint(region.GetOutput().GetNumberOfCells())
    dssf = vtk.vtkDataSetSurfaceFilter()
    dssf.SetInputConnection(region.GetOutputPort())
    dssf.Update()
    Mass = vtk.vtkMassProperties()
    Mass.SetInputData(dssf.GetOutput())
    Mass.Update()
    return Mass
コード例 #32
0
def readUnstructuredGrid(filename, tets_only=False):
    extension = os.path.splitext(filename)[1]
    if extension == ".vtk":
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        #return reader.GetOutput()
    elif extension == ".vtu":
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()
        #return reader.GetOutput()
    else:
        print("Bad extension: %s", extension)
        return None

    if tets_only:  # may renumber points!

        print("reading unstructured grid keeping only tets -> this may result in renumbered points!")

        # select tets only
        ug = reader.GetOutput()
        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        for i in range(ug.GetNumberOfCells()):
            if ug.GetCellType(i) == vtk.VTK_TETRA:
                ids.InsertNextValue(i)

        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
        selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
        selectionNode.SetSelectionList(ids)

        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        extractSelection = vtk.vtkExtractSelection()
        extractSelection.SetInputData(0, ug)
        extractSelection.SetInputData(1, selection)
        extractSelection.Update()

        return extractSelection.GetOutput()
    else:
        return reader.GetOutput()
コード例 #33
0
    def __init__(self):
        VTKPythonAlgorithmBase.__init__(self,
                                        nInputPorts=1,
                                        inputType='vtkUnstructuredGrid',
                                        nOutputPorts=1,
                                        outputType='vtkUnstructuredGrid')

        self.selection_set = set()  # type: Set[int]
        self.selection_list = vtk.vtkIntArray()
        self.selection_node = vtk.vtkSelectionNode()
        self.selection = vtk.vtkSelection()
        self.ex = vtk.vtkExtractSelection()

        self.selection_list.SetName('global_ids')
        self.selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
        self.selection_node.SetSelectionList(self.selection_list)
        self.selection.AddNode(self.selection_node)
        self.ex.ReleaseDataFlagOn()
        self.ex.SetInputDataObject(1, self.selection)
コード例 #34
0
ファイル: om_display.py プロジェクト: agramfort/openmeeg_viz
def PickData(object, event, selactor, state, view, text_init):
    picker = object.GetPicker()
    hsel = vtk.vtkHardwareSelector()
    ren = picker.GetRenderer(); hsel.SetRenderer(ren)
    hsel.SetArea(ren.GetPickX1(),ren.GetPickY1(),ren.GetPickX2(),ren.GetPickY2())
    if state:
        hsel.SetFieldAssociation(vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
    else:
        hsel.SetFieldAssociation(vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS)
    sel = hsel.Select(); ex = vtk.vtkExtractSelection()
    if picker.GetMapper():
        if (not sel.GetNumberOfNodes()==0):
            ex.SetInputConnection(picker.GetMapper().GetInputConnection(0,0))
            ex.SetSelectionConnection(sel.GetProducerPort()); ex.Update()
            selmapper = vtk.vtkDataSetMapper(); data = ex.GetOutput()
            selmapper.SetInput(data); selmapper.ScalarVisibilityOff()
            selactor.SetMapper(selmapper); selactor.PickableOff(); 
            selactor.GetProperty().SetColor(0.0, 1.0, 0.0)
            selactor.GetProperty().SetOpacity(0.5); selactor.GetProperty().SetPointSize(5)
            ren.AddActor(selactor)
            PlotSelectedData(data, state, view, text_init)
コード例 #35
0
def main():
    """
    ^y
    |
    8----9----10---11
    |  / |  / |  / |
    4----5----6----7
    |  / |  / |  / |
    0----1----2----3 --> x
    """
    ugrid = vtk.vtkUnstructuredGrid()
    xyzs = [
        [0., 0., 0.],
        [1., 0., 0.],
        [2., 0., 0.],
        [3., 0., 0.],

        [0., 1., 0.],
        [1., 1., 0.],
        [2., 1., 0.],
        [3., 1., 0.],

        [0., 2., 0.],
        [1., 2., 0.],
        [2., 2., 0.],
        [3., 2., 0.],
    ]
    # we make the lower triangle first, then the upper one to finish off the quad
    # go accross each row, left to right
    tris = [
        [0, 1, 5],
        [0, 5, 4],
        [1, 2, 6],
        [1, 6, 5],
        [2, 3, 7],
        [2, 7, 6],

        [4, 5, 9],
        [4, 9, 8],
        [5, 6, 10],
        [5, 10, 9],
        [6, 7, 11],
        [6, 11, 10],
    ]
    ids_to_show = [0, 1, #2, 3,
                   4, 5, 6, 7, 8, 9, 10, 11, 12]
    ids_to_show_updated = [
        0, 1, #2, 3,
        #4, 5,
        6, 7, 8, 9, 10, 11, 12]

    nnodes = len(xyzs)
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(nnodes)

    nid = 0
    for i, xyz in enumerate(xyzs):
        points.InsertPoint(nid, *xyz)
        nid += 1

    for tri in tris:
        elem = vtk.vtkTriangle()
        (n1, n2, n3) = tri
        elem.GetPointIds().SetId(0, n1)
        elem.GetPointIds().SetId(1, n2)
        elem.GetPointIds().SetId(2, n3)
        ugrid.InsertNextCell(elem.GetCellType(), elem.GetPointIds())

    ugrid.SetPoints(points)

    grid_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        grid_mapper.SetInputConnection(ugrid.GetProducerPort())
    else:
        grid_mapper.SetInputData(ugrid)
    input_actor = vtk.vtkActor()
    input_actor.SetMapper(grid_mapper)

    render_window = vtk.vtkRenderWindow()
    camera = vtk.vtkCamera()
    interactor = vtk.vtkRenderWindowInteractor()

    interactor.SetRenderWindow(render_window)



    print("There are %s input points" % ugrid.GetNumberOfPoints())
    print("There are %s input cells" % ugrid.GetNumberOfCells())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)
    ids.Allocate(len(ids_to_show))

    for id_to_show in ids_to_show:
        ids.InsertNextValue(id_to_show)


    selection_node = vtk.vtkSelectionNode()
    selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(ids)


    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    if vtk.VTK_MAJOR_VERSION <= 5:
        extract_selection.SetInput(0, ugrid)
        extract_selection.SetInput(1, selection)
    else:
        extract_selection.SetInputData(0, ugrid)
        extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    # In selection
    grid_selected = vtk.vtkUnstructuredGrid()
    grid_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points in the selection" % grid_selected.GetNumberOfPoints())
    print("There are %s cells in the selection" % grid_selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    # invert the selection
    selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
    extract_selection.Update()

    not_selected = vtk.vtkUnstructuredGrid()
    not_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points NOT in the selection" % not_selected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" % not_selected.GetNumberOfCells())


    selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        selected_mapper.SetInputConnection(grid_selected.GetProducerPort())
    else:
        selected_mapper.SetInputData(grid_selected)

    selected_actor = vtk.vtkActor()
    selected_actor.SetMapper(selected_mapper)

    not_selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        not_selected_mapper.SetInputConnection(not_selected.GetProducerPort())
    else:
        not_selected_mapper.SetInputData(not_selected)

    not_selected_actor = vtk.vtkActor()
    not_selected_actor.SetMapper(not_selected_mapper)

    # There will be one render window
    render_window = vtk.vtkRenderWindow()
    render_window.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    left_viewport = [0.0, 0.0, 0.5, 1.0]
    right_viewport = [0.5, 0.0, 1.0, 1.0]

    # Create a camera for all renderers
    camera = vtk.vtkCamera()

    # Setup the renderers
    left_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(left_renderer)
    left_renderer.SetViewport(left_viewport)
    left_renderer.SetBackground(.6, .5, .4)
    left_renderer.SetActiveCamera(camera)

    right_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(right_renderer)
    right_renderer.SetViewport(right_viewport)
    right_renderer.SetBackground(.3, .1, .4)
    right_renderer.SetActiveCamera(camera)
    right_renderer.AddActor(selected_actor)

    left_renderer.AddActor(input_actor)
    right_renderer.AddActor(not_selected_actor)

    right_renderer.ResetCamera()

    interactor.Start()
    #-----------------
    ids.Reset()
    ids.Allocate(len(ids_to_show_updated))
    for id_to_show in ids_to_show_updated:
        ids.InsertNextValue(id_to_show)
    ids.Modified()
    grid_selected.Modified()

    #ids.Update()
    ids.Modified()
    #selection_node.Update()
    selection_node.Modified()
    #selection.Update()
    selection.Modified()
    extract_selection.Update()
    extract_selection.Modified()
    #grid_selected.Update()
    grid_selected.Modified()
    selected_mapper.Update()
    selected_mapper.Modified()
    #selected_actor.Update()
    selected_actor.Modified()

    right_renderer.Modified()
    #right_renderer.Update()

    interactor.Modified()
    #interactor.Update()
    #-----------------
    render_window.Render()

    render_window.Modified()
コード例 #36
0
	sn.SetFieldType(1)		# POINTS (vtkSelectionNode enum)
	sn.SetContentType(4)	# INDICES ('')
	s = vtk.vtkSelection()
	idsArray = vtk.vtkIdTypeArray()
	
	pointsList = vtk.vtkIdList()
	locator.FindPointsWithinRadius(0.01, centerTuple, pointsList)
	
	for ii in range(pointsList.GetNumberOfIds()):
		idsArray.InsertNextValue(pointsList.GetId(ii))
	
	sn.SetSelectionList(idsArray)
	s.AddNode(sn)
	
	# Extract just this one group of vertices for one fiber bundle (stromal cell)
	ex = vtk.vtkExtractSelection()
	ex.SetInput(0,reader.GetOutputDataObject(0))
	ex.SetInput(1,s)
	ex.PreserveTopologyOff()
	
	# Glyphing uncovered fibers for lines or tubes display
	lineGlyph = vtk.vtkGlyph3D()
	lineGlyph.SetInputConnection(ex.GetOutputPort(0))
	lineGlyph.SetSource(line.GetOutput())
	lineGlyph.ScalingOn()
	lineGlyph.SetScaleModeToScaleByVector()
	lineGlyph.SetScaleFactor(1.0)
	lineGlyph.OrientOn()
	lineGlyph.SetVectorModeToUseVector()
	lineGlyph.SetColorModeToColorByScalar()
		
コード例 #37
0
def main():
    sphere_source = vtk.vtkSphereSource()
    sphere_source.Update()

    print("There are %s input points" % sphere_source.GetOutput().GetNumberOfPoints())
    print("There are %s input cells" % sphere_source.GetOutput().GetNumberOfCells())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    # Specify that we want to extract cells 10 through 19
    i = 10
    while i < 20:
        ids.InsertNextValue(i)
        i += 1

    selection_node = vtk.vtkSelectionNode()
    selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(ids)


    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    if vtk.VTK_MAJOR_VERSION <= 5:
        extract_selection.SetInputConnection(0, sphere_source.GetOutputPort())
        extract_selection.SetInput(1, selection)
    else:
        extract_selection.SetInputConnection(0, sphere_source.GetOutputPort())
        extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    # In selection
    grid_selected = vtk.vtkUnstructuredGrid()
    grid_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points in the selection" % grid_selected.GetNumberOfPoints())
    print("There are %s cells in the selection" % grid_selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    # invert the selection
    selection_node.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
    extract_selection.Update()

    not_selected = vtk.vtkUnstructuredGrid()
    not_selected.ShallowCopy(extract_selection.GetOutput())

    print("There are %s points NOT in the selection" % not_selected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" % not_selected.GetNumberOfCells())


    backfaces = vtk.vtkProperty()
    backfaces.SetColor(1, 0, 0)

    input_mapper = vtk.vtkDataSetMapper()
    input_mapper.SetInputConnection(sphere_source.GetOutputPort())
    input_actor = vtk.vtkActor()
    input_actor.SetMapper(input_mapper)
    input_actor.SetBackfaceProperty(backfaces)

    selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        selected_mapper.SetInputConnection(grid_selected.GetProducerPort())
    else:
        selected_mapper.SetInputData(grid_selected)

    selected_actor = vtk.vtkActor()
    selected_actor.SetMapper(selected_mapper)
    selected_actor.SetBackfaceProperty(backfaces)

    not_selected_mapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        not_selected_mapper.SetInputConnection(not_selected.GetProducerPort())
    else:
        not_selected_mapper.SetInputData(not_selected)

    not_selected_actor = vtk.vtkActor()
    not_selected_actor.SetMapper(not_selected_mapper)
    not_selected_actor.SetBackfaceProperty(backfaces)

    # There will be one render window
    render_window = vtk.vtkRenderWindow()
    render_window.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    left_viewport = [0.0, 0.0, 0.5, 1.0]
    center_viewport = [0.33, 0.0, .66, 1.0]
    right_viewport = [0.66, 0.0, 1.0, 1.0]

    # Create a camera for all renderers
    camera = vtk.vtkCamera()

    # Setup the renderers
    left_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(left_renderer)
    left_renderer.SetViewport(left_viewport)
    left_renderer.SetBackground(.6, .5, .4)
    left_renderer.SetActiveCamera(camera)

    center_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(center_renderer)
    center_renderer.SetViewport(center_viewport)
    center_renderer.SetBackground(.3, .1, .4)
    center_renderer.SetActiveCamera(camera)

    right_renderer = vtk.vtkRenderer()
    render_window.AddRenderer(right_renderer)
    right_renderer.SetViewport(right_viewport)
    right_renderer.SetBackground(.4, .5, .6)
    right_renderer.SetActiveCamera(camera)

    left_renderer.AddActor(input_actor)
    center_renderer.AddActor(selected_actor)
    right_renderer.AddActor(not_selected_actor)

    left_renderer.ResetCamera()

    render_window.Render()
    interactor.Start()
コード例 #38
0
def ExtractSelection(fileList):
    # Report our CWD just for testing purposes.
    print "CWD:", os.getcwd()

    ringOffset = numQuadsPerRing * numSMCsPerCol * 4
    branchOffset = numRingsPerBranch * ringOffset

    # Prepare selection id array.    
    selectionIds = vtk.vtkIdTypeArray()
    
    for branch in branches:
        thisBranchOffset = branch * branchOffset
        # print thisBranchOffset,
    
        for ring in range(numRingsPerBranch):
            thisRingOffset = ring * ringOffset
            # print thisRingOffset, 
            
            for cell in range(numSMCsPerCol):
                thisOffset = start + thisBranchOffset + thisRingOffset + cell
                # print thisOffset,
                selectionIds.InsertNextValue(thisOffset)
    
    # Create selection node.
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(selectionNode.CELL)
    selectionNode.SetContentType(selectionNode.INDICES)
    selectionNode.SetSelectionList(selectionIds)
    
    # Create selection.
    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)
    
    sortNicely(fileList)
    
    # Process every file by extracting selection.
    for inFile in fileList:
        print 'Reading file', inFile
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(inFile)
        
        print '\tExtracting ', selectionIds.GetNumberOfTuples(), 'cells...'
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputConnection(reader.GetOutputPort())
        if vtk.vtkVersion().GetVTKMajorVersion() > 5:
            selectionExtractor.SetInputData(1, selection)
        else:
            selectionExtractor.SetInput(1, selection)
        
        baseName = os.path.basename(inFile)
        number = [int(s) for s in re.split('([0-9]+)', baseName) if s.isdigit()]
        outFile = outputPattern + str(number[0]) + '.vtu'
        
        print '\t\tSaving file', outFile
        writer = vtk.vtkXMLUnstructuredGridWriter()
        writer.SetInputConnection(selectionExtractor.GetOutputPort())
        writer.SetFileName(outFile)
        writer.Update()
        
        print '\n'
    
    print 'All done...'
コード例 #39
0
ファイル: visible_triangles.py プロジェクト: Ignotus/VtkDemo
surface_actor = vtk.vtkActor()
surface_actor.SetMapper(mapper)

ren.AddActor(surface_actor)

ren.Render()


hw_filter = vtk.vtkHardwareSelector()
hw_filter.SetRenderer(ren)
window_size = ren_win.GetSize()
hw_filter.SetArea(1, 1, window_size[0], window_size[1])
hw_filter.SetFieldAssociation(vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
selection = hw_filter.Select()

extract_selection = vtk.vtkExtractSelection()

extract_selection.SetInputData(0, polydata)
extract_selection.SetInputData(1, selection)
extract_selection.Update()

selection = extract_selection.GetOutput()

polydata.BuildLinks()

for i in xrange(polydata.GetNumberOfCells()):
    polydata.DeleteCell(i)
polydata.RemoveDeletedCells()

original_point = selection.GetPointData().GetArray(1)
コード例 #40
0
def writeHdf5():
    
    if timeStep < 0.01:
        exit("Timestep is too small, choose 0.01 or larger")
    
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()
    print taskMeshIn
    
    numQuadsPerRing = circQuads

    # Working with the task mesh junt to figure out the quads and rows numbers.
    taskMeshReader = vtk.vtkXMLPolyDataReader()
    taskMeshReader.SetFileName(taskMeshIn)
    taskMeshReader.Update()

    taskMesh = taskMeshReader.GetOutput()
    print taskMesh.GetNumberOfPoints()

    
    # Get the range of branch labels.
    labelRange = [0, 0]
    taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0)

    # Convert label range to a list of labels.
    labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1)
    print "Labels found in task mesh:", labelRange

    # Store the number of rings for each label. 
    numRingsPerLabel = {}   

    # For every label in the range of labels we want to extract all cells/quads.
    for label in labelRange:
        
        # Use this filter to extract the cells for a given label value.
        branchSelector = vtk.vtkThreshold()
        branchSelector.SetInputData(taskMesh)
        branchSelector.ThresholdBetween(label,label);
        branchSelector.Update()

        taskMeshBranch = branchSelector.GetOutput()

        numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing;
        numRingsPerLabel[label] = numQuadRowsPerBranch
        
        
    atpFiles = glob.glob(atpMeshPattern)
    
    parentFile = h5py.File(atpHdf5Files[0], 'w')
    leftBranchFile = h5py.File(atpHdf5Files[1], 'w')
    rightBranchFile = h5py.File(atpHdf5Files[2], 'w')
    
    for atpIndex in range(0, len(atpFiles), int(timeStep / originalTimeStep)):
        print "Time step " + str(atpIndex * timeStep )
        

        atpMeshReader = vtk.vtkXMLPolyDataReader()
        atpMeshReader.SetFileName(atpFiles[atpIndex])
        atpMeshReader.Update()
    
        atpMesh = atpMeshReader.GetOutput()

        # For every label in the range of labels we want to extract all ECs.
        for label in labelRange:
            
    
            # Keep track of how many branches we need to skip.
            numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad
            atpCellOffset = label * numECsPerLabel
    
    
            # Collect cell ids to select.
            selectionIds = vtk.vtkIdTypeArray()
            for sId in range(0, numECsPerLabel):
                selectionIds.InsertNextValue(atpCellOffset + sId)
    
            # Create selecion node.
            selectionNode = vtk.vtkSelectionNode()
            selectionNode.SetFieldType(selectionNode.CELL)
            selectionNode.SetContentType(selectionNode.INDICES)
            selectionNode.SetSelectionList(selectionIds)
    
            # Create selection.
            selection = vtk.vtkSelection()
            selection.AddNode(selectionNode)
    
            # Use vtkSelection filter.
            selectionExtractor = vtk.vtkExtractSelection()
            selectionExtractor.SetInputData(0, atpMesh)
            selectionExtractor.SetInputData(1, selection)
            selectionExtractor.Update()
    
            extractedCells = selectionExtractor.GetOutput()
    
            # Ring ids list for traversal.
            ringIds = range(0, numRingsPerLabel[label])
            ringIds.reverse()
    
            # Number of ECs rows is the number of ECs per quad.
            rowIds = range(0, numECsPerCol)
            rowIds.reverse()
    
            # Decide which h5 files to write to.
            pointsOf = ''
            
            if label == 0:
                pointsOf = parentFile
            elif label == 1:
                pointsOf = leftBranchFile
            elif label == 2:
                pointsOf = rightBranchFile
    
                
            dset = pointsOf.create_dataset("/" + str(atpIndex), (numECsPerLabel,), 'f')
                
            i = 0
    
            # Iterate over the rings in reverse order.
            for ringNum in ringIds:
                # Iterate over the 'imaginary' quads of cells in normal order.
                for quadNum in range(0, numQuadsPerRing):
                    # Iterate over the rows of cells in reverse order.
                    # Calculate the 'real' id for the 'imaginary' quad.
                    quadId = ringNum * numQuadsPerRing + quadNum
                    # Iterate over rows of cells in reverse order.
                    for rowNum in rowIds:
                        # Iterate over the rows of cells in normal order.
                        for cellNum in range(0, numECsPerRow):
                            # Calculate the 'real' ec cell id and get the corresponding cell.
                            realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum
                            
                            atpVal = extractedCells.GetCellData().GetArray("ATP").GetValue(realId)
    
                            # Write the value to the txt file.
                            dset[i] = atpVal
                            i += 1
                        

    parentFile.close()
    leftBranchFile.close()
    rightBranchFile.close()
    

    print "All done ..."
コード例 #41
0
def writeHdf5():
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()
    print taskMeshIn
    
    numQuadsPerRing = circQuads

    # Working with the task mesh junt to figure out the quads and rows numbers.
    taskMeshReader = vtk.vtkXMLPolyDataReader()
    taskMeshReader.SetFileName(taskMeshIn)
    taskMeshReader.Update()

    taskMesh = taskMeshReader.GetOutput()
    print taskMesh.GetNumberOfPoints()
    
    ecMeshReader = vtk.vtkXMLPolyDataReader()
    ecMeshReader.SetFileName(ecMeshIn)
    ecMeshReader.Update()
    
    ecMesh = ecMeshReader.GetOutput()
    print ecMesh.GetNumberOfPoints()
    
    # Get the range of branch labels.
    labelRange = [0, 0]
    taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0)

    # Convert label range to a list of labels.
    labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1)
    print "Labels found in task mesh:", labelRange

    # Store the number of rings for each label. 
    numRingsPerLabel = {}   

    # For every label in the range of labels we want to extract all cells/quads.
    for label in labelRange:
        
        # Use this filter to extract the cells for a given label value.
        branchSelector = vtk.vtkThreshold()
        branchSelector.SetInputData(taskMesh)
        branchSelector.ThresholdBetween(label,label);
        branchSelector.Update()

        taskMeshBranch = branchSelector.GetOutput()

        numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing;
        numRingsPerLabel[label] = numQuadRowsPerBranch

    # Working with EC mesh only
    atpMeshReader = vtk.vtkXMLPolyDataReader()
    atpMeshReader.SetFileName(atpMeshIn)
    atpMeshReader.Update()

    # Original ECs mesh to work with.
    atpMesh = atpMeshReader.GetOutput()
    print "There are", atpMesh.GetNumberOfCells(), "ATP values in total ..."

    parentFile = h5py.File(atpHdf5Files[0], 'w')
    leftBranchFile = h5py.File(atpHdf5Files[1], 'w')
    rightBranchFile = h5py.File(atpHdf5Files[2], 'w')
    
    appendPolyData = vtk.vtkAppendPolyData();

    # For every label in the range of labels we want to extract all ECs.
    for label in labelRange:
        
        ecMeshReader = vtk.vtkXMLPolyDataReader()
        ecMeshReader.SetFileName(ecVTPFiles[label])
        ecMeshReader.Update()
        tmpPolyData = ecMeshReader.GetOutput()

        # Keep track of how many branches we need to skip.
        numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad
        atpCellOffset = label * numECsPerLabel

        print "atpCellOffset", atpCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numECsPerLabel):
            selectionIds.InsertNextValue(atpCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, atpMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedCells = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of ECs rows is the number of ECs per quad.
        rowIds = range(0, numECsPerCol)
        rowIds.reverse()
        
        reorderedATPArray = vtk.vtkDoubleArray()
        reorderedATPArray.SetName("initialATP")

        # Decide which TXT files to write to.
        pointsOf = ''
        
        if label == 0:
            pointsOf = parentFile
        elif label == 1:
            pointsOf = leftBranchFile
        elif label == 2:
            pointsOf = rightBranchFile

        print "Writing H5 file for ECs ATP:"
        print pointsOf
        dset = pointsOf.create_dataset("/atp", (numECsPerLabel,), 'f')
        
        i = 0

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for cellNum in range(0, numECsPerRow):
                        # Calculate the 'real' ec cell id and get the corresponding cell.
                        realId = quadId * numECsPerQuad + rowNum * numECsPerRow + cellNum
                        
                        atpVal = extractedCells.GetCellData().GetArray("initialATP").GetValue(realId)
                        
                        reorderedATPArray.InsertNextValue(atpVal)
                        

                        # Write the value to the txt file.
                        dset[i] = atpVal
                        i += 1
        
        tmpPolyData.GetCellData().SetScalars(reorderedATPArray)
        appendPolyData.AddInputData(tmpPolyData)
                        

    parentFile.close()
    leftBranchFile.close()
    rightBranchFile.close()
    
    print "Writing reorderd ATP map for verification..."
    appendPolyData.Update()
    reorderedATPWriter = vtk.vtkXMLPolyDataWriter()
    reorderedATPWriter.SetInputData(appendPolyData.GetOutput())
    reorderedATPWriter.SetFileName("vtk/reordered_atp.vtp")
    reorderedATPWriter.Update()
    

    print "All done ..."
コード例 #42
0
def writeLegacyVTK():
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()
    
    if os.path.isdir("vtk") == False:
        os.makedirs("vtk")
        print "Cretated vtk output directory..."
    
    if os.path.isdir("files") == False:
        os.makedirs("files")
        print "Created files ouptut directory..."
        

    # Working with the task mesh.
    taskMeshReader = vtk.vtkXMLPolyDataReader()
    taskMeshReader.SetFileName(meshSet[0])
    taskMeshReader.Update()

    taskMesh = taskMeshReader.GetOutput()

    # Get the range of branch labels.
    labelRange = [0, 0]
    taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0)

    # Convert label range to a list of labels.
    labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1)
    print "Labels found in task mesh:", labelRange


    # Store the number of rings for each label. 
    numRingsPerLabel = {}

    # For every label in the range of labels we want to extract all cells/quads.
    for label in labelRange:
        # Use this filter to extract the cells for a given label value.
        branchSelector = vtk.vtkThreshold()
        branchSelector.SetInputData(taskMesh)
        branchSelector.ThresholdBetween(label,label);
        branchSelector.Update()

        taskMeshBranch = branchSelector.GetOutput()

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()
        numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing;
        numRingsPerLabel[label] = numQuadRowsPerBranch
        ringIds = range(0, numQuadRowsPerBranch);

        # Working with rows in reverse order: UPSTREAM.
        ringIds.reverse()


        rowBase = 0
        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the cells in normal order.
            for cellNum in range(0, numQuadsPerRing):
                # Calculate the 'real' cell id and get the corresponding cell.
                cellId = ringNum * numQuadsPerRing + cellNum
                cell = taskMeshBranch.GetCell(cellId)

                # The ids to be written to the TXT file.
                pointIdList = [cell.GetNumberOfPoints()]

                # Write the appropriate points to TXT file.
                for pPos in range(0, cell.GetNumberOfPoints()):
                    newPoint = False
                    if ringNum == ringIds[0]:
                        if cellNum == 0:
                            newPoint = True
                        elif pPos == 1 or pPos == 2:
                            newPoint = True
                    else:
                        if cellNum == 0:
                            if pPos == 0 or pPos == 1:
                                newPoint = True
                        else:
                            if pPos == 1:
                                newPoint = True

                    if newPoint == True:

                        # Inserting a new point...
                        point = taskMeshBranch.GetPoint(cell.GetPointId(pPos))
                        # ... with a new id.
                        newId = reorderedPoints.InsertNextPoint(point)
                        pointIdList.append(newId)

                        # To make it easier for remembering the number of points instered in a row.
                        if cellNum == 0 and pPos == 0:
                            rowBasePrev = newId
                    else:
                        # Perhaps this can be done in a nicer way.
                        # Calculate the id of a previously inserted point.
                        if ringNum == ringIds[0]:
                            if cellNum == 1:
                                if pPos == 0:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(2L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                elif pPos == 3:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                        elif ringNum == ringIds[1]:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(0L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(cellNum * 2 + 2))
                                elif pPos == 3:
                                    if cellNum == 1:
                                        pointIdList.append(1L)
                                    else:
                                        pointIdList.append(long(cellNum * 2))
                        else:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(long(rowBase + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase))
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(rowBase + cellNum + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase + cellNum))

                # print pointIdList, rowBase

                # Insert the ids into the cell array.
                newCell = vtk.vtkQuad()
                newCell.GetPointIds().Reset()
                for id in pointIdList[1:]:
                    newCell.GetPointIds().InsertNextId(id)
                reorderedCellArray.InsertNextCell(newCell)

            rowBase = rowBasePrev

        # print '\n'
        print "Inserted", reorderedPoints.GetNumberOfPoints(), "task mesh points for label", label, "..."
        print "Inserted", reorderedCellArray.GetNumberOfCells(), "task mesh cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedTaskMeshBranch = vtk.vtkPolyData()

        # Put the reordered points and cells into the reordered mesh.
        reorderedTaskMeshBranch.SetPoints(reorderedPoints)
        reorderedTaskMeshBranch.SetPolys(reorderedCellArray)

        # Write the VTK file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedTaskMeshBranch)
        reorderedMeshWriter.SetFileName(taskVTKFiles[label])
        reorderedMeshWriter.Update()

    print "Rings per label:", numRingsPerLabel, "..."
    ringsPerLabelVals = numRingsPerLabel.values()

    # Check all rings per label values are the same.
    assert ringsPerLabelVals[1:] == ringsPerLabelVals[:-1], "All values of rings per label must be identical. Generated output is invalid ..."

    # Working with EC mesh.

    ecMeshReader = vtk.vtkXMLPolyDataReader()
    ecMeshReader.SetFileName(meshSet[1])
    ecMeshReader.Update()

    # Original ECs mesh to work with.
    ecMesh = ecMeshReader.GetOutput()
    print "There are", ecMesh.GetNumberOfCells(), "ECs in total ..."

    # For every label in the range of labels we want to extract all ECs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad
        ecCellOffset = label * numECsPerLabel

        print "ecCellOffset", ecCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numECsPerLabel):
            selectionIds.InsertNextValue(ecCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, ecMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedECs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of ECs rows is the number of ECs per quad.
        rowIds = range(0, numECsPerCol)
        rowIds.reverse()

        # The ECs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for ecNum in range(0, numECsPerRow):
                        # Calculate the 'real' ec cell id and get the corresponding cell.
                        ecId = quadId * numECsPerQuad + rowNum * numECsPerRow + ecNum
                        ecCell = extractedECs.GetCell(ecId)
                        reorderedCellArray.InsertNextCell(ecCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedECMeshBranch.SetPoints(extractedECs.GetPoints())

        # Set the reordered cells to the reordered ECs mesh.
        reorderedECMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numECsPerCol):
                # Iterate over the ECs in the row in normal order.
                for ecNum in range(0, numECsPerRow):
                    # Calculate the 'real' ec cell id and get the corresponding cell.
                    ecId = quadNum * numECsPerQuad + rowNum * numECsPerRow + ecNum
                    ecCell = reorderedECMeshBranch.GetCell(ecId)

                    # The ids to be written to the TXT file.
                    pointIdList = [ecCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, ecCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if ecNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if ecNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True

                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedECMeshBranch.GetPoint(ecCell.GetPointId(pPos))
                            # ... with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)


                            if ecNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if ecNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum * 2 + 2))
                                    elif pPos == 3:
                                        if ecNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + ecNum * 2))
                            else:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + ecNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "ECs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "ECs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECs = vtk.vtkPolyData()

        # Put the reordered points and cells into the mesh.
        reorderedECs.SetPoints(reorderedPoints)
        reorderedECs.SetPolys(reorderedCellArray)

        # Write the VTK EC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedECs)
        reorderedMeshWriter.SetFileName(ecVTKFiles[label])
        reorderedMeshWriter.Update()

        # Use VTK centroid filter to get the centroids in the right order
        # from the reorderedECMeshBranch.
        centroidFilter = vtk.vtkCellCenters()
        centroidFilter.SetInputData(reorderedECs)
        centroidFilter.Update()

        # Create a vertex cell for each point.
        pointsToVerticesFilter = vtk.vtkVertexGlyphFilter()
        pointsToVerticesFilter.SetInputData(centroidFilter.GetOutput())
        pointsToVerticesFilter.Update()

        reorderedCentroidBranch = pointsToVerticesFilter.GetOutput()

        # Write the VTK EC centrouid file.
        centroidWriter = vtk.vtkXMLPolyDataWriter()
        centroidWriter.SetInputData(reorderedCentroidBranch)
        centroidWriter.SetFileName(ecCentroidVTKFiles[label])
        centroidWriter.Update()

        # Write the centroids to the TXT points and cells files.
        for cId in range(0, reorderedCentroidBranch.GetNumberOfCells()):
            centCell = reorderedCentroidBranch.GetCell(cId)
            centIds = [centCell.GetNumberOfPoints()]

            # Write centroid ids.
            ptId = centCell.GetPointId(0)
            centIds.append(ptId)

            # Write centroid points.
            point = reorderedCentroidBranch.GetPoint(ptId)




    # Working with SMC mesh.
    # Working with SMC mesh.
    # Working with SMC mesh.
    smcMeshReader = vtk.vtkXMLPolyDataReader()
    smcMeshReader.SetFileName(meshSet[2])
    smcMeshReader.Update()

    # Original SMCs mesh to work with.
    smcMesh = smcMeshReader.GetOutput()
    print "There are", smcMesh.GetNumberOfCells(), "SMCs in total ..."

    # For every label in the range of labels we want to extract all SMCs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numSMCsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numSMCsPerQuad
        smcCellOffset = label * numSMCsPerLabel

        print "smcCellOffset", smcCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numSMCsPerLabel):
            selectionIds.InsertNextValue(smcCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, smcMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedSMCs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of SMCs rows is the number of ECs per quad times 13.
        rowIds = range(0, numSMCsPerCol)
        rowIds.reverse()

        # The SMCs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for smcNum in range(0, numSMCsPerRow):
                        # Calculate the 'real' smc cell id and get the corresponding cell.
                        smcId = quadId * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                        smcCell = extractedSMCs.GetCell(smcId)
                        reorderedCellArray.InsertNextCell(smcCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedSMCMeshBranch.SetPoints(extractedSMCs.GetPoints())

        # Set the reordered cells to the reordered SMCs mesh.
        reorderedSMCMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numSMCsPerCol):
                # Iterate over the SMCs in the row in normal order.
                for smcNum in range(0, numSMCsPerRow):
                    # Calculate the 'real' smc cell id and get the corresponding cell.
                    smcId = quadNum * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                    smcCell = reorderedSMCMeshBranch.GetCell(smcId)

                    # The ids to be written to the TXT file.
                    pointIdList = [smcCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, smcCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if smcNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if smcNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True
                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedSMCMeshBranch.GetPoint(smcCell.GetPointId(pPos))
                            # with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)

                            if smcNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if smcNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum * 2 + 2))
                                    elif pPos == 3:
                                        if smcNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + smcNum * 2))
                            else:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + smcNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "SMCs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "SMCs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCs = vtk.vtkPolyData()

        # Put the reordered points and cells in to the mesh.
        reorderedSMCs.SetPoints(reorderedPoints)
        reorderedSMCs.SetPolys(reorderedCellArray)

        # Write the VTK SMC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedSMCs)
        reorderedMeshWriter.SetFileName(smcVTKFiles[label])
        reorderedMeshWriter.Update()

    print "All done ..."
    print "... Except the last configuration_info.txt file ..."

    configFile = open("files/configuration_info.txt", 'w')
    configFile.write("Processors information\n")
    configFile.write("Total number of points per branch (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numQuadsPerRing + 1) * (numRingsPerLabel[0] + 1), (numQuadsPerRing + 1), (numRingsPerLabel[0] + 1)))
    configFile.write("Total number of cells per branch (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numQuadsPerRing * numRingsPerLabel[0], numQuadsPerRing, numRingsPerLabel[0]))
    configFile.write("Total number of SMC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numSMCsPerCol + 1) * (numSMCsPerRow + 1), (numSMCsPerCol + 1), (numSMCsPerRow + 1)))
    configFile.write("Total number of SMC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numSMCsPerCol * numSMCsPerRow, numSMCsPerCol, numSMCsPerRow))
    configFile.write("Total number of EC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numECsPerCol + 1) * (numECsPerRow + 1), (numECsPerCol + 1), (numECsPerRow + 1)))
    configFile.write("Total number of EC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))

    configFile.close()

    print "Now it is all done for real ..."
コード例 #43
0
def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(50)
    pointSource.Update()

    print("There are %s input points\n" % pointSource.GetOutput().GetNumberOfPoints())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    # Set values
    i = 10
    while i < 20:
        ids.InsertNextValue(i)
        i += 1

    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(1) # POINT
    #  CELL_DATA = 0
    #  POINT_DATA = 1
    #  FIELD_DATA = 2
    #  VERTEX_DATA = 3
    #  EDGE_DATA = 4

    selectionNode.SetContentType(4) # INDICES
    #SELECTIONS = 0
    #GLOBALIDS = 1
    #PEDIGREEIDS = 2
    #VALUES = 3
    #INDICES = 4
    #FRUSTUM = 5
    #LOCATIONS = 6
    #THRESHOLDS = 7
    #BLOCKS = 8
    selectionNode.SetSelectionList(ids)

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    extractSelection = vtk.vtkExtractSelection()

    extractSelection.SetInputConnection(0, pointSource.GetOutputPort())
    if vtk.VTK_MAJOR_VERSION <= 5:
        extractSelection.SetInput(1, selection)
    else:
        extractSelection.SetInputData(1, selection)
    extractSelection.Update()

    # In selection
    selected = vtk.vtkUnstructuredGrid()
    selected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points in the selection" % selected.GetNumberOfPoints())
    print("There are %s cells in the selection" %selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    # invert the selection
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
    extractSelection.Update()

    notSelected = vtk.vtkUnstructuredGrid()
    notSelected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points NOT in the selection" % notSelected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" % notSelected.GetNumberOfCells())

    inputMapper = vtk.vtkDataSetMapper()
    inputMapper.SetInputConnection(pointSource.GetOutputPort())
    inputActor = vtk.vtkActor()
    inputActor.SetMapper(inputMapper)

    selectedMapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        selectedMapper.SetInputConnection(selected.GetProducerPort())
    else:
        selectedMapper.SetInputData(selected)
    selectedActor = vtk.vtkActor()
    selectedActor.SetMapper(selectedMapper)

    notSelectedMapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        notSelectedMapper.SetInputConnection(notSelected.GetProducerPort())
    else:
        notSelectedMapper.SetInputData(notSelected)
    notSelectedActor = vtk.vtkActor()
    notSelectedActor.SetMapper(notSelectedMapper)


    # There will be one render window
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    leftViewport = [0.0, 0.0, 0.33, 1.0]
    centerViewport = [0.33, 0.0, .66, 1.0]
    rightViewport = [0.66, 0.0, 1.0, 1.0]

    # Setup the renderers
    leftRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(leftRenderer)
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(.6, .5, .4)

    centerRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(centerRenderer)
    centerRenderer.SetViewport(centerViewport)
    centerRenderer.SetBackground(.3, .1, .4)

    rightRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(rightRenderer)
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(.4, .5, .6)

    leftRenderer.AddActor(inputActor)
    centerRenderer.AddActor(selectedActor)
    rightRenderer.AddActor(notSelectedActor)

    leftRenderer.ResetCamera()
    centerRenderer.ResetCamera()
    rightRenderer.ResetCamera()

    renderWindow.Render()
    interactor.Start()