Пример #1
0
    def _highlight_picker_node(self, cell_id, grid, node_xyz):
        """won't handle multiple cell_ids/node_xyz"""
        cell = grid.GetCell(cell_id)
        nnodes = cell.GetNumberOfPoints()
        points = cell.GetPoints()

        point0 = points.GetPoint(0)
        dist_min = vtk.vtkMath.Distance2BetweenPoints(point0, node_xyz)

        imin = 0
        point_min = point0
        for ipoint in range(1, nnodes):
            #point = array(points.GetPoint(ipoint), dtype='float32')
            #dist = norm(point - node_xyz)
            point = points.GetPoint(ipoint)
            dist = vtk.vtkMath.Distance2BetweenPoints(point, node_xyz)
            if dist < dist_min:
                dist_min = dist
                imin = ipoint
                point_min = point
        node_id = cell.GetPointId(imin)

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

        selection_node = vtk.vtkSelectionNode()
        #selection_node.SetContainingCellsOn()
        #selection_node.Initialize()
        selection_node.SetFieldType(vtk.vtkSelectionNode.POINT)
        selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
        selection_node.SetSelectionList(ids)
        actor = self._highlight_picker_by_selection_node(
            grid, selection_node, representation='points')
        return actor
Пример #2
0
def create_vtk_selection_node_by_cell_ids(cell_ids):
    id_type_array = _convert_ids_to_vtk_idtypearray(cell_ids)
    selection_node = vtk.vtkSelectionNode()
    selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(id_type_array)
    return selection_node
Пример #3
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)
Пример #4
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
Пример #5
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
def extractUGridBasedOnThreshold(ugrid, arrayname, thresholdval):

	selectionNode = vtk.vtkSelectionNode();
  	selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL);

	idArray = vtk.vtkIdTypeArray()
	if(type(thresholdval) == list):
  		selectionNode.SetContentType(vtk.vtkSelectionNode.THRESHOLDS);
		idArray.SetNumberOfTuples(len(thresholdval)*2)
		cnt = 0
		for tval in thresholdval:
 			idArray.SetValue(cnt, tval)
 			idArray.SetValue(cnt+1, tval)
			cnt += 2
	else:
  		selectionNode.SetContentType(vtk.vtkSelectionNode.THRESHOLDS);
		idArray.SetNumberOfTuples(2)
 		idArray.SetValue(0, thresholdval)
 		idArray.SetValue(1, thresholdval)

 	selectionNode.SetSelectionList(idArray)

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

	extract = vtk.vtkExtractSelectedThresholds();
  	extract.SetInputData(0, ugrid);
  	extract.SetInputData(1, selection);
  	extract.Update();


	return extract.GetOutput()
Пример #7
0
    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
Пример #8
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 = []
Пример #9
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
Пример #10
0
    def RequestData(self, request, inInfo, outInfo):

        inp1 = vtk.vtkUnstructuredGrid.GetData(inInfo[0])

        self.selection_group.RemoveAllNodes()

        group_selections = self.group_selections

        if group_selections is not None:

            for i in xrange(group_selections.GetNumberOfArrays()):
                node = vtk.vtkSelectionNode()
                node.SetContentType(vtk.vtkSelectionNode.GLOBALIDS)
                node.SetSelectionList(group_selections.GetArray(i))

                self.selection_group.AddNode(node)

        self.selection_group.Modified()

        self.ex_group.SetInputDataObject(0, inp1)

        self.ex_group.Update()

        info = outInfo.GetInformationObject(0)
        opt = vtk.vtkUnstructuredGrid.GetData(info)

        new_output = self.ex_group.GetOutputDataObject(0)
        # to remove warnings, not used, seems to be a bug in vtk
        new_output.GetPointData().RemoveArray("vtkOriginalPointIds")

        opt.ShallowCopy(new_output)

        return 1
Пример #11
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
Пример #12
0
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
Пример #13
0
    def highlight_elements(self, eids, model_name=''):
        """
        Highlights a series of elements

        Parameters
        ----------
        eids : int, List[int]
            the elements to apply a message to
        model_name : str, List[str]
            the name of the actor to highlight the elements for

        """
        raise NotImplementedError('need to define active_ugrid')
        grid = active_ugrid
        all_eids = self.gui.get_element_ids(model_name=model_name, ids=None)
        cell_ids = np.searchsorted(all_eids, eids)

        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        for cell_id in cell_ids:
            ids.InsertNextValue(cell_id)

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

        actor = self._highlight_picker_by_selection_node(
            grid, selection_node, representation='surface')
        return actor
Пример #14
0
    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()
Пример #15
0
    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()
Пример #16
0
    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())
Пример #17
0
    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()
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
Пример #19
0
def create_vtk_selection_node_by_point_ids(point_ids):
    id_type_array = _convert_ids_to_vtk_idtypearray(point_ids)
    selection_node = vtk.vtkSelectionNode()
    #selection_node.SetContainingCellsOn()
    #selection_node.Initialize()
    selection_node.SetFieldType(vtk.vtkSelectionNode.POINT)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(id_type_array)
    return selection_node
	def ScaleSelectionCallback(self, caller, event):
		# This will contain a scale value from detail_image_flow, which should
		# only exist if there is also a highlight_selection from image_flow.
		# Here combine those two pieces of information to select the correct tree
		# node corresponding to that pedigree_id highlight and scale value
		
		# This call doesn't make sense if there isn't a highlight link
		# since it follows that highlighted individual to the selected scale
		if self.highlight_link is None:
			return
		
		# Don't want to update if this is an internal call
		if self.scale_internal_call:
			self.scale_internal_call = False
			return
		
		# The content type is Index for now...
		scaleSel = caller.GetCurrentSelection()
		
		# Note: Empty selection should still contain a node, but no tuples
		if (scaleSel.GetNumberOfNodes() > 0) and (scaleSel.GetNode(0).GetSelectionList().GetNumberOfTuples() > 0):
			# This should only contain a single value or none
			scaleVal = scaleSel.GetNode(0).GetSelectionList().GetValue(0)
			print "Scale value from detail to icicle: ", scaleVal
			
			# Highlight should also contain a single pedigree id...
			pedSel = self.highlight_link.GetCurrentSelection()
			pedIdVal = pedSel.GetNode(0).GetSelectionList().GetValue(0)
			print "Pedigree ID value right now in icicle highlight", pedIdVal
			
			# NOTE: Accessing member variable
			nodes_at_scale = N.nonzero(self.ds.Scales==scaleVal)[0].tolist()
			
			for node_id in nodes_at_scale:
				if (self.ds.PointsInNet[node_id]==pedIdVal).any():
					
					# Assuming for now that this is a cell "Index", so getting pedigree ID
					sel = vtk.vtkSelection()
					node = vtk.vtkSelectionNode()
					node.SetFieldType(0)		# Cell
					node.SetContentType(4)		# Indices
					id_array = N.array([node_id], dtype='int64')
					id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
					node.SetSelectionList(id_vtk)
					sel.AddNode(node)
					# Note: When selection is cleared, the current selection does NOT contain any nodes
					self.areapoly1.Update()
					cs = vtk.vtkConvertSelection()
					pedIdSelection = cs.ToPedigreeIdSelection(sel, self.areapoly1.GetOutput())
					pedIdSelection.GetNode(0).SetFieldType(3)	# convert to vertext selection
					
					# Copy converted selection to output annotation link (fires AnnotationChangedEvent)
					self.output_link.SetCurrentSelection(pedIdSelection)
					self.applycolors1.Update()
					self.renWin.Render()
Пример #21
0
    def selectPoint(self, point_id):
        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        ids.InsertNextValue(point_id)

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

        self._setSelection(selection_node)
Пример #22
0
    def selectCell(self, cell_id):
        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        ids.InsertNextValue(cell_id)

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

        self._setSelection(selection_node)
Пример #23
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
Пример #24
0
    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
Пример #25
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)
Пример #26
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)
Пример #27
0
    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()
Пример #28
0
    def updateSelection(self, selectedIds):
        if len(selectedIds) == 0: return

        Ids = VN.numpy_to_vtkIdTypeArray(np.array(selectedIds), deep=True)

        node = vtk.vtkSelectionNode()
        node.SetContentType(vtk.vtkSelectionNode.INDICES)
        node.SetFieldType(vtk.vtkSelectionNode.POINT)
        node.SetSelectionList(Ids)

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

        self.annotationLink.SetCurrentSelection(selection)
        self.widget.Render()
Пример #29
0
    def updateSelection(self, selectedIds):
        if len(selectedIds)==0: return

        Ids = VN.numpy_to_vtkIdTypeArray(np.array(selectedIds), deep=True)

        node = vtk.vtkSelectionNode()
        node.SetContentType(vtk.vtkSelectionNode.INDICES)
        node.SetFieldType(vtk.vtkSelectionNode.POINT)
        node.SetSelectionList(Ids)
        
        selection = vtk.vtkSelection()
        selection.AddNode(node)
        
        self.annotationLink.SetCurrentSelection(selection)
        self.widget.Render()
Пример #30
0
    def _highlight_picker_cell(self, cell_ids, grid):
        """won't handle multiple cell_ids/node_xyz"""
        if isinstance(cell_ids, integer_types):
            cell_ids = [cell_ids]
        ids = vtk.vtkIdTypeArray()
        ids.SetNumberOfComponents(1)
        for cell_id in cell_ids:
            ids.InsertNextValue(cell_id)

        selection_node = vtk.vtkSelectionNode()
        selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
        selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
        selection_node.SetSelectionList(ids)
        actor = self._highlight_picker_by_selection_node(
            grid, selection_node, representation='surface')
        return actor
Пример #31
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())
Пример #32
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	
Пример #33
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]
 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()
def GetSelection(ids, inverse=False):
    selNode = vtk.vtkSelectionNode()
    selNode.SetContentType(vtk.vtkSelectionNode.BLOCKS)

    idArray = vtk.vtkIdTypeArray()
    idArray.SetNumberOfTuples(len(ids))
    for i in range(len(ids)):
        idArray.SetValue(i, ids[i])
    selNode.SetSelectionList(idArray)

    if inverse:
        selNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)

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

    return sel
	def LoadData(self):
		
		# Remove all old actors from renderer
		self.renderer.RemoveAllViewProps()
		# Put back nav menu
		menu_actor_list = self.menu.GetActorList()
		for m_actor in menu_actor_list:
			self.renderer.AddActor(m_actor)
		
		tree = self.ds.GetTree()
		
		# Parallel pipeline with no shrinkage to get TCoords
		self.TreeLevels = vtk.vtkTreeLevelsFilter()
		self.TreeLevels.SetInput(tree)
		
		VertexDegree = vtk.vtkVertexDegree()
		VertexDegree.SetInputConnection(self.TreeLevels.GetOutputPort(0))
		
		TreeAggregation = vtk.vtkTreeFieldAggregator()
		TreeAggregation.LeafVertexUnitSizeOff()
		TreeAggregation.SetField('size')
		TreeAggregation.SetInputConnection(VertexDegree.GetOutputPort(0))
		
		# Layout without shrinkage for generating texture coordinates
		strategy = vtk.vtkStackedTreeLayoutStrategy()
		strategy.UseRectangularCoordinatesOn()
		strategy.SetRootStartAngle(0.0)
		strategy.SetRootEndAngle(15.0)
		strategy.SetRingThickness(self.THICK)	# layer thickness
		strategy.ReverseOn()
		strategy.SetShrinkPercentage(0.0)
		layout = vtk.vtkAreaLayout()
		layout.SetLayoutStrategy(strategy)
		layout.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout.SetAreaArrayName("area")
		layout.SetSizeArrayName("num_in_vertex")
		areapoly = vtk.vtkTreeMapToPolyData()
		areapoly.SetInputConnection(layout.GetOutputPort(0))
		areapoly.SetAddNormals(0)
		areapoly.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		texPlane = vtk.vtkTextureMapToPlane()
		texPlane.SetInputConnection(areapoly.GetOutputPort(0))
		texPlane.AutomaticPlaneGenerationOn()
		texPlane.Update()
		
		# Layout with shrinkage for generating geometry
		strategy0 = vtk.vtkStackedTreeLayoutStrategy()
		strategy0.UseRectangularCoordinatesOn()
		strategy0.SetRootStartAngle(0.0)
		strategy0.SetRootEndAngle(15.0)
		strategy0.SetRingThickness(self.THICK)	# layer thickness
		strategy0.ReverseOn()
		strategy0.SetShrinkPercentage(self.SHRINK)
		layout0 = vtk.vtkAreaLayout()
		layout0.SetLayoutStrategy(strategy0)
		layout0.SetInputConnection(TreeAggregation.GetOutputPort(0))
		layout0.SetAreaArrayName("area")
		layout0.SetSizeArrayName("num_in_vertex")
		areapoly0 = vtk.vtkTreeMapToPolyData()
		areapoly0.SetAddNormals(0)
		areapoly0.SetInputConnection(layout0.GetOutputPort(0))
		areapoly0.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		areapoly0.Update()
		
		# Copy over texture coordinates
		def transferTCoords():
			input = paf.GetInputDataObject(0,0)
			refin = paf.GetInputList().GetItem(0)
			output = paf.GetPolyDataOutput()
			
			TCorig = refin.GetPointData().GetTCoords()
			
			TC = vtk.vtkFloatArray()
			TC.SetNumberOfComponents(TCorig.GetNumberOfComponents())
			TC.SetNumberOfTuples(TCorig.GetNumberOfTuples())
			TC.SetName('Texture Coordinates')
			for ii in range(TCorig.GetNumberOfTuples()):
				ff = TCorig.GetTuple2(ii)
				TC.SetTuple2(ii,ff[0],ff[1])
			
			output.GetPointData().AddArray(TC)
			output.GetPointData().SetActiveTCoords('Texture Coordinates')
			
		paf = vtk.vtkProgrammableAttributeDataFilter()
		paf.SetInput(areapoly0.GetOutput())
		paf.AddInput(texPlane.GetOutput())
		paf.SetExecuteMethod(transferTCoords)
		
		# Need to find proper ordering of wavelet coeffs based on icicle layout
		# tree.GetVertexData().GetArray('area') is 4-component (Xmin,Xmax,Ymin,Ymax)
		print 'Reordering wavelet coeffs'
		out_polys = areapoly.GetOutputDataObject(0)
		isleaf = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('leaf'))
		poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area'))
		vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids'))
		
		self.LeafIds = vertex_ids[isleaf>0]
		self.LeafXmins = poly_bounds[isleaf>0,0]
		self.XOrderedLeafIds = self.LeafIds[self.LeafXmins.argsort()]
					

		# Grab texture images and color map
		self.GrabTextureImagesAndLUT()
		

		# For each node and corresponding image data in self.WCimageDataList, need to create a texture,
		# then pull out the correct rectangle from areapoly0 (using vtkExtractSelectedPolyDataIds
		# and create a mapper and actor and apply the texture. 
		
		self.texture_list = []
		self.tex_mapper_list = []
		self.tex_actor_list = []
		
		for ii in range(len(self.WCimageDataList)):
			
			# Set up texture with lookup table for matrix polys
			tex = vtk.vtkTexture()
			tex.SetInput(self.WCimageDataList[ii])
			tex.SetLookupTable(self.lut)
			self.texture_list.append(tex)
			
			# Grab correct poly out of areapoly0
			sel = vtk.vtkSelection()
			node = vtk.vtkSelectionNode()
			node.SetContentType(4)	# 4 = indices
			node.SetFieldType(0)		# 0 = cell
			id_array = N.array([ii],dtype='int64')
			id_list = VN.numpy_to_vtkIdTypeArray(id_array)
			node.SetSelectionList(id_list)
			sel.AddNode(node)

			ext_id_poly = vtk.vtkExtractSelectedPolyDataIds()
			ext_id_poly.SetInput(1, sel)
			ext_id_poly.SetInputConnection(0, areapoly0.GetOutputPort(0))
			# ext_id_poly.Update()
			# print ext_id_poly.GetOutput()
			poly_tm = vtk.vtkTextureMapToPlane()
			poly_tm.SetInputConnection(ext_id_poly.GetOutputPort(0))
			poly_tm.AutomaticPlaneGenerationOn()
			poly_tm.Update()

			# Separate mapper and actor for textured polys
			map2 = vtk.vtkPolyDataMapper()
			map2.SetInputConnection(poly_tm.GetOutputPort(0))
			map2.ScalarVisibilityOff()
			self.tex_mapper_list.append(map2)
			
			act2 = vtk.vtkActor()
			act2.SetMapper(self.tex_mapper_list[ii])
			act2.SetTexture(self.texture_list[ii])
			act2.GetProperty().SetColor(1,1,1)
			act2.SetPickable(0)
			act2.SetPosition(0,0,0.1)	# ???
			self.tex_actor_list.append(act2)
			
			# Add textured polys to the view
			self.renderer.AddActor(self.tex_actor_list[ii])

				
		# Layout with shrinkage for generating outline geometry for showing selections
		self.applycolors1 = vtk.vtkApplyColors()
		self.applycolors1.SetInputConnection(0,layout0.GetOutputPort(0))
		self.applycolors1.AddInputConnection(1,self.output_link.GetOutputPort(0))
		self.applycolors1.SetDefaultPointColor(self.theme.GetPointColor())
		self.applycolors1.SetDefaultPointOpacity(self.theme.GetPointOpacity())
		self.applycolors1.SetSelectedPointColor(self.theme.GetSelectedPointColor())
		self.applycolors1.SetSelectedPointOpacity(self.theme.GetSelectedPointOpacity())

		self.areapoly1 = vtk.vtkTreeMapToPolyData()
		self.areapoly1.SetInputConnection(self.applycolors1.GetOutputPort(0))
		self.areapoly1.SetAddNormals(0)
		self.areapoly1.SetInputArrayToProcess( 0, 0, 0, 4, "area")  # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES
		
		# Separate mapper and actor for icicle polys outlines (pickable)
		map = vtk.vtkPolyDataMapper()
		map.SetInputConnection(self.areapoly1.GetOutputPort(0))
		map.SetScalarModeToUseCellFieldData()
		map.SelectColorArray("vtkApplyColors color")
		map.SetScalarVisibility(True)
		act = vtk.vtkActor()
		act.SetMapper(map)
		act.GetProperty().SetColor(1,1,1)
		act.SetPickable(True)
		act.SetPosition(0,0,0)
		act.GetProperty().SetRepresentationToWireframe()
		act.GetProperty().SetLineWidth(4.0)
		
		self.icicle_actor = act
		
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act)
		
		
		# Now need to set up data for generating "selection lines" which come from 
		# xy or pcoords chart. Basic method is to create a new scalar array out of x-coord
		# of the texture coordinates, then do a Delaunay2D on the shrunken polys and contour
		# that at values obtained by finding what normalized distance along data set are
		# selected pedigree ids.

		self.calc = vtk.vtkArrayCalculator()
		self.calc.SetInputConnection(paf.GetOutputPort())
		self.calc.SetAttributeModeToUsePointData()
		self.calc.AddScalarVariable("tcoords_X", "Texture Coordinates", 0)
		self.calc.SetFunction("tcoords_X")
		self.calc.SetResultArrayName("tcx")
		# self.calc.Update()
		# print VN.vtk_to_numpy(self.calc.GetOutput().GetPointData().GetArray('tcx'))
		
		self.group_contour = vtk.vtkContourFilter()
		self.group_contour.SetInputConnection(self.calc.GetOutputPort(0))
		self.group_contour.SetInputArrayToProcess(0,0,0,0,'tcx')

		self.highlight_contour = vtk.vtkContourFilter()
		self.highlight_contour.SetInputConnection(self.calc.GetOutputPort(0))
		self.highlight_contour.SetInputArrayToProcess(0,0,0,0,'tcx')

		# Separate mapper and actor group selection (pcoords or xy) lines
		map3 = vtk.vtkPolyDataMapper()
		map3.SetInputConnection(self.group_contour.GetOutputPort(0))
		map3.SetScalarVisibility(0)
		act3 = vtk.vtkActor()
		act3.SetMapper(map3)
		act3.SetPickable(False)
		act3.SetPosition(0,0,0.2)
		act3.GetProperty().SetRepresentationToWireframe()
		act3.GetProperty().SetLineWidth(2.0)
		act3.GetProperty().SetColor(1,0,0)
		act3.GetProperty().SetOpacity(0.6)
		
		self.group_actor = act3
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act3)
		
		# Separate mapper and actor for individual (image_flow) selection highlight
		map4 = vtk.vtkPolyDataMapper()
		map4.SetInputConnection(self.highlight_contour.GetOutputPort(0))
		map4.SetScalarVisibility(0)
		act4 = vtk.vtkActor()
		act4.SetMapper(map4)
		act4.SetPickable(False)
		act4.SetPosition(0,0,0.25)
		act4.GetProperty().SetRepresentationToWireframe()
		act4.GetProperty().SetLineWidth(3.0)
		act4.GetProperty().SetColor(0,0.5,1)
		act4.GetProperty().SetOpacity(0.6)
		
		self.highlight_actor = act4
		# Add actor for selection highlight outlines
		self.renderer.AddActor(act4)
		
		# Get Ordered fractional positions for pedigree ids (for setting contour values)
		self.ped_id_fracs = self.ds.GetIdsFractionalPosition(self.XOrderedLeafIds)
		
		# Clear out selections on data change
		self.output_link.GetCurrentSelection().RemoveAllNodes()
		self.output_link.InvokeEvent("AnnotationChangedEvent")

		self.renderer.ResetCamera(self.icicle_actor.GetBounds())
Пример #37
0
basisFunc = VN.numpy_to_vtk(Esub)
basisFunc.SetName('ExtBasis')
basisFuncSq = VN.numpy_to_vtk(EsubSq)
basisFuncSq.SetName('ExtBasisSq')

vertexData = graph.GetVertexData()
vertexData.AddArray(basisFunc)
vertexData.AddArray(basisFuncSq)

# Do selection the new way rather than using vtkSelectionSource...
selArr = vtk.vtkDoubleArray()
selArr.InsertNextValue(basisCutoff)	# min
selArr.InsertNextValue(100)			# max
selArr.SetName("ExtBasisSq")		# array name matches vertex array name

selNode = vtk.vtkSelectionNode()
selNode.SetContentType(7) 			# vtkSelectionNode::THRESHOLDS
selNode.SetFieldType(3) 			# vtkSelectionNode::VERTEX
selNode.SetSelectionList(selArr)

selection = vtk.vtkSelection()
selection.AddNode(selNode)
selection.Update()

minmax = "(%3.2e, %3.2e)" % (EsubSq.min(), EsubSq.max())
ui_window.label_basisCutoff_minmax.setText(minmax)

# ----------
# Back to pipeline
subgraph = vtk.vtkExtractSelectedGraph()
subgraph.SetRemoveIsolatedVertices(False)
Пример #38
0
line.SetPoint2(1,0,0)
line.SetResolution(2)

vert = vtk.vtkGlyphSource2D()
vert.SetGlyphTypeToVertex()
vert.SetCenter(1,0,0)

surfaces = vtk.vtkAppendPolyData()
tubes = vtk.vtkAppendPolyData()
	
for pp in range(stroma.GetNumberOfPoints()):
# for pp in range(100):
	print pp
	centerTuple = stroma.GetPoint(pp)
	
	sn = vtk.vtkSelectionNode()
	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)
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()
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 ..."
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()
Пример #42
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...'
    def _CreateSkeleton(self):
        """Create the structure of the output vtkUnstructuredGrid and a map
        from the index of a point in the extraction file to the corresponding
        cellId in the skeleton.
        
        This method should only be called if the extraction object this 
        instance is working on has changed since the last time this method was
        called.
        """
        input = self.GetUnstructuredGridInput()
        
        # Get the centres as these should match the extracted property positions
        centers = vtk.vtkCellCenters()
        if vtk.vtkVersion().GetVTKMajorVersion() <= 5:
          centers.SetInput( input );
        else:
          centers.SetInputData( input );
        #centers.SetInput(input)
        centers.Update()
        # Use this to find the cell ID for each point.
        locator = vtk.vtkOctreePointLocator()
        locator.SetDataSet(centers.GetOutput())
        locator.BuildLocator()
        # Should be fine enough
        locator.SetTolerance(0.1 * self.Extracted.voxelSizeMetres)

        # Get the first set of extracted data from the file. We don't care
        # which as we only want to use the positions.
        extracted_positions = self.Extracted.GetByIndex(0).position
        nExtractedPoints = len(extracted_positions)
        
        # Make a list of the cell ids to keep; i.e. the cell in the input 
        # (whole geometry) with ID cellIdsGmy[i] contains  the point given by
        # extracted_positions[i]
        gmyCellIdsByInput = vtk.vtkIdTypeArray()
        gmyCellIdsByInput.SetNumberOfComponents(1)
        gmyCellIdsByInput.SetNumberOfTuples(nExtractedPoints)
        
        
        gmyCellIdsByInputNp = numpy_support.vtk_to_numpy(gmyCellIdsByInput)
         
        for i, point in enumerate(extracted_positions):
            # Get cell in geometry corresponding to the point
            cellId = locator.FindClosestPoint(point)

            if cellId == -1:
                raise ValueError("Can't find cell for point at " + str(point))

            gmyCellIdsByInputNp[i] = cellId
        
        # Make an object to select only the cell ids we want
        selector = vtk.vtkSelectionNode()
        selector.SetFieldType(CELL)
        selector.SetContentType(INDICES)
        selector.SetSelectionList(gmyCellIdsByInput)
        
        # Make an object to hold the selector
        selectors = vtk.vtkSelection()
        selectors.AddNode(selector)
        
        # Perform the selection
        extractSelection = vtk.vtkExtractSelectedIds()
        if vtk.vtkVersion().GetVTKMajorVersion() <= 5:        
            extractSelection.SetInput(0, input)
            extractSelection.SetInput(1, selectors)
        else:
            extractSelection.SetInputData(0, input)
            extractSelection.SetInputData(1, selectors)
        extractSelection.Update()
        
        gmyCellIdsByOutput = extractSelection.GetOutput().GetCellData().GetArray('vtkOriginalCellIds')
        
        
        gmyCellIdsByOutputNp = numpy_support.vtk_to_numpy(gmyCellIdsByOutput)
        
        self.OutputCellIdsByInputIndex = MatchCorresponding(gmyCellIdsByOutputNp,gmyCellIdsByInputNp)
        
        # Create the skeleton data object and only copy in the structure.
        self.Skeleton = vtk.vtkUnstructuredGrid()
        self.Skeleton.CopyStructure(extractSelection.GetOutput())
        return
Пример #44
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 ..."
Пример #45
0
def selectionChangedCallback(caller,eventId):
	x,y = istyle.GetInteractor().GetEventPosition()
	z = 0
	ren1.SetDisplayPoint(x,y,0)
	ren1.DisplayToWorld()
	# print (x,y)
	# print ren1.GetWorldPoint()
	
	picker.Pick(x,y,0,ren1)
	print picker.GetCellId()
	
	# List of offsets for creating frustrum corners from point
	o = []			# offsets
	t = 1.0			# amount
	o.append((-1*t,-1*t,-1.0))
	o.append([-1*t,-1*t,+1.0])
	o.append([-1*t,+1*t,-1.0])
	o.append([-1*t,+1*t,+1.0])
	o.append((+1*t,-1*t,-1.0))
	o.append([+1*t,-1*t,+1.0])
	o.append([+1*t,+1*t,-1.0])
	o.append([+1*t,+1*t,+1.0])
	
	frustcorners = vtk.vtkDoubleArray()
	frustcorners.SetNumberOfComponents(4)
	frustcorners.SetNumberOfTuples(8)
	
	for ii in range(8):
		ren1.SetDisplayPoint(x+o[ii][0],y+o[ii][1],z+o[ii][2])
		ren1.DisplayToWorld()
		(m,n,l,w) = ren1.GetWorldPoint()
		frustcorners.SetTuple4(ii,m,n,l,w)
	
	# Enumerator:	(content type)
		# SELECTIONS	
		# GLOBALIDS		
		# PEDIGREEIDS	
		# VALUES	
		# INDICES	
		# FRUSTUM	
		# LOCATIONS		
		# THRESHOLDS	
		# BLOCKS 
	# Enumerator: (field type)
		# CELL	
		# POINT		
		# FIELD		
		# VERTEX	
		# EDGE	
		# ROW	
		
	sel = vtk.vtkSelection()
	node = vtk.vtkSelectionNode()
	node.SetContentType(5)		# FRUSTRUM
	node.SetFieldType(0)		# CELL
	node.SetSelectionList(frustcorners)
	sel.AddNode(node);
	sel.Update()
	print 'Node prop:', node.GetSelectedProp()
	
	cs = vtk.vtkConvertSelection()
	outSel = cs.ToIndexSelection(sel, texPlane.GetOutput())	# INDICES
	outNode = outSel.GetNode(0)
	print 'Number of Tuples in outSelNode0: ', outNode.GetSelectionList().GetNumberOfTuples()
	print 'Tuple0: ', outNode.GetSelectionList().GetValue(0)
	
	cs2 = vtk.vtkConvertSelection()
	outSel2 = cs.ToPedigreeIdSelection(sel, texPlane.GetOutput())	# INDICES
	outNode2 = outSel.GetNode(0)
	print 'Number of Tuples in outSelNode0: ', outNode2.GetSelectionList().GetNumberOfTuples()
	print 'Tuple0: ', outNode2.GetSelectionList().GetValue(0)
	print 'Prop: ', outNode2.GetProperties().Get(outNode2.PROP())
	print 'Prop: ', outNode2.GetSelectedProp(), '\n'
	def selectNode(self):
		# (x0,y0) = self.interactor.GetLastEventPosition()
		(x,y) = self.interactor.GetEventPosition()
		cellPicker = vtk.vtkCellPicker()
		someCellPicked = cellPicker.Pick(x,y,0,self.renderer)
		pickedCellId = cellPicker.GetCellId()
		propPicker = vtk.vtkPropPicker()
		somePropPicked = propPicker.PickProp(x,y,self.renderer)
		pickedProp = propPicker.GetViewProp()
		navigated = False
		# NOTE: For some reason, sometimes on switching data sets
		#   we're getting to the print statement with scale_list undefined
		#   so I added this initialization...
		scale_list = []
		
		# Navigate with buttons
		if somePropPicked and (pickedProp != self.icicle_actor):
			# First, test whether there is a current selection because we can only move if
			# there was a selection to move in the first place
			if self.output_link.GetCurrentSelection().GetNumberOfNodes() > 0:
				# If so, get the current pedigree_id
				prev_ped_vtk = self.output_link.GetCurrentSelection().GetNode(0).GetSelectionList()
				# NOTE: Counting on a single ID
				prev_ped_id = prev_ped_vtk.GetValue(0)
				# Now figure out which menu item was picked
				for ii, m_actor in enumerate(self.menu.GetActorList()):
					if pickedProp == m_actor:
						# print "Menu Actor picked, index = ", ii
						# Call the proper nav routine and get back the new ped_id
						new_ped_id = self.menu_functions[ii](prev_ped_id)
						new_ped_n = N.array([new_ped_id], dtype='int64')
						new_ped_vtk = VN.numpy_to_vtkIdTypeArray(new_ped_n, deep=True)
						self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(new_ped_vtk)
						self.output_link.InvokeEvent("AnnotationChangedEvent")
						self.applycolors1.Update()
						self.renWin.Render()			
						# Set list for scale_link
						scale_list = [self.ds.Scales[new_ped_id]]
						navigated = True
					
		# Pick a cell of the icicle view
		# Cell picker doesn't work with Actor2D, so nav menu won't report any cells
		if someCellPicked and not navigated:
			print "Icicle picked cell index: ", pickedCellId
			# Assuming for now that this is a cell "Index", so getting pedigree ID
			sel = vtk.vtkSelection()
			node = vtk.vtkSelectionNode()
			node.SetFieldType(0)		# Cell
			node.SetContentType(4)		# Indices
			id_array = N.array([pickedCellId], dtype='int64')
			id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
			node.SetSelectionList(id_vtk)
			sel.AddNode(node)
			# Note: When selection is cleared, the current selection does NOT contain any nodes
			self.areapoly1.Update()
			cs = vtk.vtkConvertSelection()
			pedIdSelection = cs.ToPedigreeIdSelection(sel, self.areapoly1.GetOutput())
			pedIdSelection.GetNode(0).SetFieldType(3)	# convert to vertext selection
			
			# Copy converted selection to output annotation link (fires AnnotationChangedEvent)
			self.output_link.SetCurrentSelection(pedIdSelection)
			self.applycolors1.Update()
			self.renWin.Render()
			# Set list for scale_link
			scale_list = [self.ds.Scales[pickedCellId]]
			
		if not someCellPicked and not somePropPicked:
			# reset selection to blank
			print "Blank selection"
			return
			self.output_link.GetCurrentSelection().RemoveAllNodes()
			self.output_link.InvokeEvent("AnnotationChangedEvent")
			self.applycolors1.Update()
			self.renWin.Render()
			# Set list for scale_link
			scale_list = []

		print "scale picked in icicle view: ", scale_list
		
		id_array = N.array(scale_list, dtype='int64')
		id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
		self.scale_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk)
		# For now want this event to trigger detail view, but not internal scale selection callback
		self.scale_internal_call = True
		self.scale_link.InvokeEvent("AnnotationChangedEvent")
Пример #47
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 ..."
Пример #48
0
  def rasterizeFibers(self,fiberNode,labelNode,labelValue=1,samplingDistance=0.1):
    """Trace through the given fiber bundles and
    set the corresponding pixels in the given labelNode volume"""
    print('rasterizing...')
    rasToIJK = vtk.vtkMatrix4x4()
    labelNode.GetRASToIJKMatrix(rasToIJK)
    labelArray = slicer.util.array(labelNode.GetID())
    polyData = fiberNode.GetPolyData()
    cellCount = polyData.GetNumberOfCells()

    selection = vtk.vtkSelection()
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)

    extractor = vtk.vtkExtractSelectedPolyDataIds()
    extractor.SetInputData(0, polyData)

    resampler = vtk.vtkPolyDataPointSampler()
    resampler.GenerateEdgePointsOn()
    resampler.GenerateVertexPointsOff()
    resampler.GenerateInteriorPointsOff()
    resampler.GenerateVerticesOff()
    resampler.SetDistance(samplingDistance)

    cellIds = vtk.vtkIdTypeArray()

    # as a compromise between memory blowup (for large fiberbundles) and not
    # eating time in the python loop, resample CELLS_TO_PROCESS at once.
    CELLS_TO_PROCESS = 100

    for startCellId in xrange(0, cellCount, CELLS_TO_PROCESS):
      # generate list of cell Ids to sample
      cellIdsAr = numpy.arange(startCellId,
                               min(cellCount, startCellId + CELLS_TO_PROCESS))
      cellIds.SetVoidArray(cellIdsAr, cellIdsAr.size, 1)

      # update the selection node to extract those cells
      selectionNode.SetSelectionList(cellIds)
      selection.AddNode(selectionNode)
      selection.Modified()
      extractor.SetInputData(1, selection)
      extractor.Update()
      resampler.SetInputConnection(extractor.GetOutputPort())
      resampler.Update()

      # get the resampler output
      # note: to test without resampling, just use
      # `pdSubset = extractor.GetOutput()` instead
      pdSubset = resampler.GetOutput()
      pointCount = pdSubset.GetNumberOfPoints()
      points = pdSubset.GetPoints()

      for pointIndex in xrange(pointCount):
        point = points.GetPoint(pointIndex)
        ijkFloat = rasToIJK.MultiplyPoint(point+(1,))[:3]

        # skip any negative indices to avoid wrap-around
        # to the other side of the image.
        if (any(coord < 0 for coord in ijkFloat)):
          continue

        ijk = [int(round(element)) for element in ijkFloat]
        ijk.reverse()
        try:
          # paint the voxels
          labelArray[tuple(ijk)] = labelValue
        except IndexError:
          pass
      # reset the selection node
      selection.RemoveAllNodes()

    labelNode.GetImageData().Modified()
    labelNode.Modified()
    print('finished')
Пример #49
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()