def InterpolatePatchCenterlines(patchCenterlines, parentCenterlines, additionalPoint, lower, version): if additionalPoint is not None: additionalPointIds = [] for i in range(parentCenterlines.GetNumberOfCells()): line = ExtractSingleLine(parentCenterlines, i) additionalPointIds.append(line.FindPoint(additionalPoint)) else: additionalPointIds = [ "" for i in range(parentCenterlines.GetNumberOfCells()) ] interpolatedLines = vtk.vtkPolyData() interpolatedPoints = vtk.vtkPoints() interpolatedCellArray = vtk.vtkCellArray() pointsInserted = 0 interpolatedCellArray.Initialize() for i in range(parentCenterlines.GetNumberOfCells()): startingCell = vtk.vtkGenericCell() endingCell = vtk.vtkGenericCell() numberOfInterpolationPoints = parentCenterlines.GetCell( i).GetNumberOfPoints() patchCenterlines.GetCell(0, startingCell) patchCenterlines.GetCell(i + 1, endingCell) if version: splinePoints = InterpolateSpline(startingCell, endingCell, additionalPoint) else: splinePoints = InterpolateTwoCells(startingCell, endingCell, \ numberOfInterpolationPoints, \ additionalPointIds[i], additionalPoint, lower) interpolatedCellArray.InsertNextCell(splinePoints.GetNumberOfPoints()) for j in range(splinePoints.GetNumberOfPoints()): interpolatedPoints.InsertNextPoint(splinePoints.GetPoint(j)) interpolatedCellArray.InsertCellPoint(pointsInserted + j) pointsInserted += splinePoints.GetNumberOfPoints() interpolatedLines.SetPoints(interpolatedPoints) interpolatedLines.SetLines(interpolatedCellArray) attributeFilter = vtkvmtk.vtkvmtkCenterlineAttributesFilter() attributeFilter.SetInput(interpolatedLines) attributeFilter.SetAbscissasArrayName(AbscissasArrayName) attributeFilter.SetParallelTransportNormalsArrayName( parallelTransportNormalsArrayName) attributeFilter.Update() attributeInterpolatedLines = attributeFilter.GetOutput() return attributeInterpolatedLines
def InterpolatePatchCenterlines(patchCenterlines, parentCenterlines): additionalPoint = [-1.0, -1.0, -1.0] additionalPointIds = [] if (useAdditionalInterpolationPoint == 1): additionalPoint = divergingPoints.GetPoint(0) line1 = ExtractSingleLine(parentCenterlines, 0) line2 = ExtractSingleLine(parentCenterlines, 1) additionalPointIds.append(line1.FindPoint(additionalPoint)) additionalPointIds.append(line2.FindPoint(additionalPoint)) else: for i in range(parentCenterlines.GetNumberOfCells()): additionalPoint = clippingPoints.GetPoint(0) line1 = ExtractSingleLine(parentCenterlines, 0) additionalPointIds.append(line1.FindPoint(additionalPoint)) interpolatedLines = vtk.vtkPolyData() interpolatedPoints = vtk.vtkPoints() interpolatedCellArray = vtk.vtkCellArray() pointsInserted = 0 interpolatedCellArray.Initialize() for i in range(parentCenterlines.GetNumberOfCells()): startingCell = vtk.vtkGenericCell() endingCell = vtk.vtkGenericCell() numberOfInterpolationPoints = parentCenterlines.GetCell( i).GetNumberOfPoints() patchCenterlines.GetCell(0, startingCell) patchCenterlines.GetCell(i + 1, endingCell) splinePoints = InterpolateTwoCells(startingCell, endingCell, numberOfInterpolationPoints, additionalPointIds[i], additionalPoint) interpolatedCellArray.InsertNextCell(splinePoints.GetNumberOfPoints()) for j in range(splinePoints.GetNumberOfPoints()): interpolatedPoints.InsertNextPoint(splinePoints.GetPoint(j)) interpolatedCellArray.InsertCellPoint(pointsInserted + j) pointsInserted += splinePoints.GetNumberOfPoints() interpolatedLines.SetPoints(interpolatedPoints) interpolatedLines.SetLines(interpolatedCellArray) attributeFilter = vtkvmtk.vtkvmtkCenterlineAttributesFilter() attributeFilter.SetInputData(interpolatedLines) attributeFilter.SetAbscissasArrayName(abscissasArrayName) attributeFilter.SetParallelTransportNormalsArrayName( parallelTransportNormalsArrayName) attributeFilter.Update() attributeInterpolatedLines = attributeFilter.GetOutput() return attributeInterpolatedLines
def InterpolatePatchCenterlines(patchCenterlines, parentCenterlines): additionalPoint = [-1.0, -1.0, -1.0] additionalPointIds = [] if useAdditionalInterpolationPoint == 1: additionalPoint = divergingPoints.GetPoint(0) line1 = ExtractSingleLine(parentCenterlines, 0) line2 = ExtractSingleLine(parentCenterlines, 1) additionalPointIds.append(line1.FindPoint(additionalPoint)) additionalPointIds.append(line2.FindPoint(additionalPoint)) else: for i in range(parentCenterlines.GetNumberOfCells()): additionalPoint = clippingPoints.GetPoint(0) line1 = ExtractSingleLine(parentCenterlines, 0) additionalPointIds.append(line1.FindPoint(additionalPoint)) interpolatedLines = vtk.vtkPolyData() interpolatedPoints = vtk.vtkPoints() interpolatedCellArray = vtk.vtkCellArray() pointsInserted = 0 interpolatedCellArray.Initialize() for i in range(parentCenterlines.GetNumberOfCells()): startingCell = vtk.vtkGenericCell() endingCell = vtk.vtkGenericCell() numberOfInterpolationPoints = parentCenterlines.GetCell(i).GetNumberOfPoints() patchCenterlines.GetCell(0, startingCell) patchCenterlines.GetCell(i + 1, endingCell) splinePoints = InterpolateTwoCells( startingCell, endingCell, numberOfInterpolationPoints, additionalPointIds[i], additionalPoint ) interpolatedCellArray.InsertNextCell(splinePoints.GetNumberOfPoints()) for j in range(splinePoints.GetNumberOfPoints()): interpolatedPoints.InsertNextPoint(splinePoints.GetPoint(j)) interpolatedCellArray.InsertCellPoint(pointsInserted + j) pointsInserted += splinePoints.GetNumberOfPoints() interpolatedLines.SetPoints(interpolatedPoints) interpolatedLines.SetLines(interpolatedCellArray) attributeFilter = vtkvmtk.vtkvmtkCenterlineAttributesFilter() attributeFilter.SetInput(interpolatedLines) attributeFilter.SetAbscissasArrayName(abscissasArrayName) attributeFilter.SetParallelTransportNormalsArrayName(parallelTransportNormalsArrayName) attributeFilter.Update() attributeInterpolatedLines = attributeFilter.GetOutput() return attributeInterpolatedLines
def TreeTraversal(startingCell): branchesToExplore = vtk.vtkPriorityQueue() points1 = vtk.vtkGenericCell() cellIds = vtk.vtkIdList() priority = int(lines.GetNumberOfCells()) path = [startingCell] paths = [] traversal = [] lengths = [0] * int(lines.GetNumberOfCells()) branchesToExplore.Insert(priority, startingCell) priority -= 1 centreline.GetCell(startingCell, points1) lengths[startingCell] = int(points1.GetNumberOfPoints() - 1) currentId = startingCell while branchesToExplore.GetNumberOfItems() != 0: points2 = vtk.vtkGenericCell() centreline.GetCell(currentId, points2) endPointId = int(points2.GetPointId(points2.GetNumberOfPoints() - 1)) centreline.GetPointCells(endPointId, cellIds) if cellIds.GetNumberOfIds() > 1: for pos in range(1, cellIds.GetNumberOfIds()): branchesToExplore.Insert(priority, cellIds.GetId(pos)) priority -= 1 centreline.GetCell(cellIds.GetId(pos), points2) lengths[cellIds.GetId(pos)] = int(points2.GetNumberOfPoints() - 1 + lengths[currentId]) paths.append(path[:] + [int(cellIds.GetId(pos))]) else: traversal.append([path, lengths[currentId]]) currentId = int(branchesToExplore.Pop()) if len(paths) != 0: path = paths.pop() traversal.sort(key=lambda x: x[1], reverse=True) return traversal
def TreeTraversal(startingCell): branchesToExplore = vtk.vtkPriorityQueue() points1 = vtk.vtkGenericCell() cellIds = vtk.vtkIdList() priority = int(lines.GetNumberOfCells()) path = [startingCell] paths = [] traversal = [] lengths = [0] * int(lines.GetNumberOfCells()) branchesToExplore.Insert(priority, startingCell) priority -= 1 centreline.GetCell(startingCell, points1) lengths[startingCell] = int(points1.GetNumberOfPoints() - 1) currentId = startingCell while branchesToExplore.GetNumberOfItems() != 0: points2 = vtk.vtkGenericCell() centreline.GetCell(currentId, points2) endPointId = int(points2.GetPointId(points2.GetNumberOfPoints() - 1)) centreline.GetPointCells(endPointId, cellIds) if cellIds.GetNumberOfIds() > 1: for pos in range(1, cellIds.GetNumberOfIds()): branchesToExplore.Insert(priority, cellIds.GetId(pos)) priority -= 1 centreline.GetCell(cellIds.GetId(pos), points2) lengths[cellIds.GetId(pos)] = int(points2.GetNumberOfPoints() - 1 + lengths[currentId]) paths.append(path[:] + [int(cellIds.GetId(pos))]) else: traversal.append([path,lengths[currentId]]) currentId = int(branchesToExplore.Pop()) if len(paths) != 0: path = paths.pop() traversal.sort(key = lambda x: x[1], reverse = True) return traversal
def ExtractLine(cellid,centerlines): cell = vtk.vtkGenericCell() centerlines.GetCell(cellid,cell) numberOfPoints = cell.GetNumberOfPoints() line = vtk.vtkPolyData() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(numberOfPoints) linePoints = cell.GetPoints() ptnArray = vtk.vtkDoubleArray() ptnArray.SetNumberOfComponents(3) ptnArray.SetNumberOfTuples(numberOfPoints) ptnArray.SetName(parallelTransportNormalsArrayName) ptnArray.FillComponent(0,0.0) ptnArray.FillComponent(1,0.0) ptnArray.FillComponent(2,0.0) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) normal = centerlines.GetPointData().GetArray(parallelTransportNormalsArrayName).GetTuple3(cell.GetPointId(i)) ptnArray.SetTuple3(i,normal[0],normal[1],normal[2]) line.SetPoints(linePoints) line.SetLines(cellArray) line.GetPointData().AddArray(ptnArray) return line
def ExtractPatch(id,centerlines): cell = vtk.vtkGenericCell() centerlines.GetCell(id,cell) numberOfPoints = cell.GetNumberOfPoints() line = vtk.vtkPolyData() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(numberOfPoints) linePoints = cell.GetPoints() radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(numberOfPoints) radiusArray.SetName(radiusArrayName) radiusArray.FillComponent(0,0.0) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) radius = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i)) radiusArray.SetTuple1(i,radius) line.SetPoints(linePoints) line.SetLines(cellArray) line.GetPointData().AddArray(radiusArray) return line
def ComputePatchEndPointParameters(id,centerlines): point0 = [0.0,0.0,0.0] point1 = [0.0,0.0,0.0] tan = [0.0,0.0,0.0] radius0 = -1 cell = vtk.vtkGenericCell() centerlines.GetCell(id,cell) if (id == 0): point0 = cell.GetPoints().GetPoint(cell.GetNumberOfPoints()-1) point1 = cell.GetPoints().GetPoint(cell.GetNumberOfPoints()-2) radius0 = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(cell.GetNumberOfPoints()-1)) tan[0] = point1[0]-point0[0] tan[1] = point1[1]-point0[1] tan[2] = point1[2]-point0[2] vtk.vtkMath.Normalize(tan) else: point0 = cell.GetPoints().GetPoint(0) point1 = cell.GetPoints().GetPoint(1) radius0 = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(0)) tan[0] = point1[0]-point0[0] tan[1] = point1[1]-point0[1] tan[2] = point1[2]-point0[2] vtk.vtkMath.Normalize(tan) return tan, point0, radius0
def ExtractSingleLine(centerlines,id): cell = vtk.vtkGenericCell() centerlines.GetCell(id,cell) line = vtk.vtkPolyData() points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(cell.GetNumberOfPoints()) radiusArray = vtk.vtkDoubleArray() radiusArray.SetName(radiusArrayName) radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(cell.GetNumberOfPoints()) radiusArray.FillComponent(0,0.0) for i in range(cell.GetNumberOfPoints()): point = [0.0,0.0,0.0] point = cell.GetPoints().GetPoint(i) points.InsertNextPoint(point) cellArray.InsertCellPoint(i) radius = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i)) radiusArray.SetTuple1(i,radius) line.SetPoints(points) line.SetLines(cellArray) line.GetPointData().AddArray(radiusArray) return line
def ComputePatchEndPointParameters(id, centerlines): point0 = [0.0, 0.0, 0.0] point1 = [0.0, 0.0, 0.0] tan = [0.0, 0.0, 0.0] radius0 = -1 cell = vtk.vtkGenericCell() centerlines.GetCell(id, cell) if (id == 0): point0 = cell.GetPoints().GetPoint(cell.GetNumberOfPoints() - 1) point1 = cell.GetPoints().GetPoint(cell.GetNumberOfPoints() - 2) radius0 = centerlines.GetPointData().GetArray( radiusArrayName).GetTuple1( cell.GetPointId(cell.GetNumberOfPoints() - 1)) else: point0 = cell.GetPoints().GetPoint(0) point1 = cell.GetPoints().GetPoint(1) radius0 = centerlines.GetPointData().GetArray( radiusArrayName).GetTuple1(cell.GetPointId(0)) tan[0] = point1[0] - point0[0] tan[1] = point1[1] - point0[1] tan[2] = point1[2] - point0[2] vtk.vtkMath.Normalize(tan) return tan, point0, radius0
def surface2surfacedistance(ref, target, arrayname): """Compute distance between two surfaces. Output is added as point array.""" # adapted from vtkvmtkSurfaceDistance # initialise locator = vtk.vtkCellLocator() genericcell = vtk.vtkGenericCell() cellid = vtk.mutable(0) point = [0., 0., 0.] closestpoint = [0., 0., 0.] subid = vtk.mutable(0) distance2 = vtk.mutable(0) # create array distarray = vtk.vtkDoubleArray() distarray.SetName(arrayname) distarray.SetNumberOfTuples(target.GetNumberOfPoints()) target.GetPointData().AddArray(distarray) # build locator locator.SetDataSet(ref) locator.BuildLocator() # compute distance for i in range(target.GetNumberOfPoints()): point = target.GetPoint(i) locator.FindClosestPoint(point, closestpoint, genericcell, cellid, subid, distance2) distance = math.sqrt(distance2) # add value to array distarray.SetValue(i, distance) target.Update() return target
def SaveParentArtery(centerlines): numberOfCells = centerlines.GetNumberOfCells() cell0 = centerlines.GetCell(0) numberOfArteryPoints = centerlines.GetNumberOfPoints()-cell0.GetNumberOfPoints() artery = vtk.vtkPolyData() arteryPoints = vtk.vtkPoints() arteryCellArray = vtk.vtkCellArray() radiusArray = vtk.vtkDoubleArray() radiusArray.SetName(radiusArrayName) radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(numberOfArteryPoints) radiusArray.FillComponent(0,0.0) count = 0 for i in range(1,numberOfCells): # cell0 is the one that goes to the aneurysm dome cell = vtk.vtkGenericCell() centerlines.GetCell(i,cell) arteryCellArray.InsertNextCell(cell.GetNumberOfPoints()) for j in range(cell.GetNumberOfPoints()): arteryPoints.InsertNextPoint(cell.GetPoints().GetPoint(j)) radiusArray.SetTuple1(count,centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(j))) arteryCellArray.InsertCellPoint(count) count+=1 artery.SetPoints(arteryPoints) artery.SetLines(arteryCellArray) artery.GetPointData().AddArray(radiusArray) return artery
def write_vtk(filename, points, cells = None, cell_types = None, pointdata = None, tag = None): if(cell_types is not None): assert(len(cell_types) in [0, len(cells)]) if(pointdata is not None): assert(len(pointdata) in [0, len(points)]) import vtk data = vtk.vtkUnstructuredGrid() # is also vtkDataSet scalars = vtk.vtkDoubleArray() if tag: scalars.SetName(tag) vtkpoints = vtk.vtkPoints() for i, point in enumerate(points): vtkpoints.InsertPoint(i, point) if pointdata is not None and len(pointdata) > 0: scalars.InsertTuple1(i, pointdata[i]) data.SetPoints(vtkpoints) if cells: cellArray = vtk.vtkCellArray() for i, cell in enumerate(cells): vtkCell = vtk.vtkGenericCell() vtkCell.SetCellType(cell_types[i]) idList = vtk.vtkIdList() for cellid in cell: idList.InsertNextId(cellid) vtkCell.SetPointIds(idList) cellArray.InsertNextCell(vtkCell) data.SetCells(cell_types, cellArray) pointData = data.GetPointData() pointData.SetScalars(scalars) write_dataset(filename, data) writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(data) writer.Write()
def particle_in_system(self, particle_list, time, rank): """ Check that the particles of X are inside the system data """ out = [] if self.temporal_cache is None: out[:] = True return out obj = self.temporal_cache(time)[0][0][2] loc=vtk.vtkCellLocator() if obj.IsA('vtkUnstructuredGrid'): loc.SetDataSet(obj) else: loc.SetDataSet(obj.GetBlock(0)) loc.BuildLocator() cell = vtk.vtkGenericCell() pcoords = [0.0,0.0,0.0] w=[0.0,0.0,0.0,0.0] for par in particle_list: out.append(loc.FindCell(par.pos)> -1) return out
def computeVols (pdata): # compute volume of the mesh (array of |K_i|) it = pdata.NewCellIterator () it.InitTraversal () vols = np.zeros ((pdata.GetNumberOfCells (), 1)) i = 0 while not it.IsDoneWithTraversal(): type = it.GetCellType () # get type of K_i points = it.GetPoints () # get points of K_i volCell = 0. # volume of K_i cell = vtk.vtkGenericCell () it.GetCell (cell) if type == 3: # cell is a line volCell = volumeLine (points.GetPoint (0), points.GetPoint (1)) elif type == 5: # cell is a triangle volCell = volumeTriangle (points.GetPoint (0), points.GetPoint (1), points.GetPoint (2)) elif type == 10: # cell is a tetrahedra volCell = volumeTetra (points.GetPoint (0), points.GetPoint (1), points.GetPoint (2), points.GetPoint (3)) vols [i] = volCell # store |K_i| it.GoToNextCell () i = i + 1 return vols
def ExtractLine(cellid, centerlines): cell = vtk.vtkGenericCell() centerlines.GetCell(cellid, cell) numberOfPoints = cell.GetNumberOfPoints() line = vtk.vtkPolyData() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(numberOfPoints) linePoints = cell.GetPoints() ptnArray = vtk.vtkDoubleArray() ptnArray.SetNumberOfComponents(3) ptnArray.SetNumberOfTuples(numberOfPoints) ptnArray.SetName(parallelTransportNormalsArrayName) ptnArray.FillComponent(0, 0.0) ptnArray.FillComponent(1, 0.0) ptnArray.FillComponent(2, 0.0) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) normal = centerlines.GetPointData().GetArray( parallelTransportNormalsArrayName).GetTuple3(cell.GetPointId(i)) ptnArray.SetTuple3(i, normal[0], normal[1], normal[2]) line.SetPoints(linePoints) line.SetLines(cellArray) line.GetPointData().AddArray(ptnArray) return line
def ExtractSingleLine(centerlines, id): cell = vtk.vtkGenericCell() centerlines.GetCell(id, cell) line = vtk.vtkPolyData() points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(cell.GetNumberOfPoints()) radiusArray = vtk.vtkDoubleArray() radiusArray.SetName(radiusArrayName) radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(cell.GetNumberOfPoints()) radiusArray.FillComponent(0, 0.0) for i in range(cell.GetNumberOfPoints()): point = [0.0, 0.0, 0.0] point = cell.GetPoints().GetPoint(i) points.InsertNextPoint(point) cellArray.InsertCellPoint(i) radius = centerlines.GetPointData().GetArray( radiusArrayName).GetTuple1(cell.GetPointId(i)) radiusArray.SetTuple1(i, radius) line.SetPoints(points) line.SetLines(cellArray) line.GetPointData().AddArray(radiusArray) return line
def computeWeights(self): """ Compute the interpolation weights assuming the field values are stored on vertices """ dstPtIds = vtk.vtkIdList() cell = vtk.vtkGenericCell() pcoords = numpy.zeros((3, ), numpy.float64) ws = numpy.zeros((4, ), numpy.float64) numSrcCells = self.srcGrid.GetNumberOfCells() numDstCells = self.dstGrid.GetNumberOfCells() # iterate over the dst grid cells for dstCellId in range(numDstCells): # iterate over the four vertices of the dst cell self.dstGrid.GetCellPoints(dstCellId, dstPtIds) for i0 in range(4): dstVert = self.dstGrid.GetPoint(dstPtIds.GetId(i0)) # bilinear interpolation srcCellId = self.srcLoc.FindCell(dstVert, self.EPS, cell, pcoords, ws) if srcCellId >= 0: k = (dstCellId, srcCellId) if not self.weights.has_key(k): # initialize the weights self.weights[k] = self.ZERO4x4.copy() # a point can only be in one cell, so no need to use += self.weights[k][i0, :] = ws
def addMappingFromPointsToCells(ugrid_points, ugrid_cells, verbose=True): if (verbose): print '*** addMappingFromPointsToCells ***' nb_points = ugrid_points.GetNumberOfPoints() nb_cells = ugrid_cells.GetNumberOfCells() print "nb_points = " + str(nb_points) print "nb_cells = " + str(nb_cells) cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(ugrid_cells) cell_locator.Update() closest_point = [0.] * 3 generic_cell = vtk.vtkGenericCell() num_cell = vtk.mutable(0) subId = vtk.mutable(0) dist = vtk.mutable(0.) iarray_num_cell = createIntArray("num_cell", 1, nb_points) for num_point in range(nb_points): point = ugrid_points.GetPoint(num_point) cell_locator.FindClosestPoint(point, closest_point, generic_cell, num_cell, subId, dist) #num_cell = cell_locator.FindCell(point) iarray_num_cell.InsertTuple(num_point, [num_cell]) #print "num_point = " + str(num_point) #print "num_cell = " + str(num_cell) ugrid_points.GetPointData().AddArray(iarray_num_cell)
def ExtractPatch(id, centerlines): cell = vtk.vtkGenericCell() centerlines.GetCell(id, cell) numberOfPoints = cell.GetNumberOfPoints() line = vtk.vtkPolyData() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(numberOfPoints) linePoints = cell.GetPoints() radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(numberOfPoints) radiusArray.SetName(radiusArrayName) radiusArray.FillComponent(0, 0.0) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) radius = centerlines.GetPointData().GetArray( radiusArrayName).GetTuple1(cell.GetPointId(i)) radiusArray.SetTuple1(i, radius) line.SetPoints(linePoints) line.SetLines(cellArray) line.GetPointData().AddArray(radiusArray) return line
def BuildDecreasingRadiiScalars(): print 'Generating decreasing vessel radii...' radii.SetNumberOfValues(points.GetNumberOfPoints()) radii.InsertValue(0, radiusBase) alreadyBuilt = [] bifurcationValues = dict() distanceCovered = 0 traversal = TreeTraversal(0) # For every path, starting from longest route. for path, length in traversal: distanceCovered = 0 # For each cellId in path, check hasn't already been done. for cellId in path: connectedCellIds = vtk.vtkIdList() ids = vtk.vtkGenericCell() centreline.GetCell(cellId, ids) newId = ids.GetPointId(0) centreline.GetPointCells(newId, connectedCellIds) if connectedCellIds.GetNumberOfIds() > 1: minCellId = connectedCellIds.GetId(0) for i in range(1, connectedCellIds.GetNumberOfIds()): minCellId = min(minCellId, connectedCellIds.GetId(i)) scalarValue = bifurcationValues[minCellId] else: # for first iteration (inlet) scalarValue = radiusBase if cellId not in alreadyBuilt: start = int(ids.GetPointId(1)) end = int(ids.GetNumberOfPoints()) + start - 1 p = length - distanceCovered i = 1 for pointId in range(start, end): k = (math.log(0.5)-math.log(scalarValue))/p x0 = math.exp(math.log(0.5)-k*p) x = x0 * math.exp(k*i) radii.SetValue(pointId, x) i += 1 bifurcationValues[cellId] = x alreadyBuilt.append(cellId) distanceCovered += int(ids.GetNumberOfPoints() - 1)
def BuildDecreasingRadiiScalars(): print("Generating decreasing vessel radii...") radii.SetNumberOfValues(points.GetNumberOfPoints()) radii.InsertValue(0, radiusBase) alreadyBuilt = [] bifurcationValues = dict() distanceCovered = 0 traversal = TreeTraversal(0) # For every path, starting from longest route. for path, length in traversal: distanceCovered = 0 # For each cellId in path, check hasn't already been done. for cellId in path: connectedCellIds = vtk.vtkIdList() ids = vtk.vtkGenericCell() centreline.GetCell(cellId, ids) newId = ids.GetPointId(0) centreline.GetPointCells(newId, connectedCellIds) if connectedCellIds.GetNumberOfIds() > 1: minCellId = connectedCellIds.GetId(0) for i in range(1, connectedCellIds.GetNumberOfIds()): minCellId = min(minCellId, connectedCellIds.GetId(i)) scalarValue = bifurcationValues[minCellId] else: # for first iteration (inlet) scalarValue = radiusBase if cellId not in alreadyBuilt: start = int(ids.GetPointId(1)) end = int(ids.GetNumberOfPoints()) + start - 1 p = length - distanceCovered i = 1 for pointId in range(start, end): k = (math.log(0.5) - math.log(scalarValue)) / p x0 = math.exp(math.log(0.5) - k * p) x = x0 * math.exp(k * i) radii.SetValue(pointId, x) i += 1 bifurcationValues[cellId] = x alreadyBuilt.append(cellId) distanceCovered += int(ids.GetNumberOfPoints() - 1)
def CreateParentArteryPatches(parentCenterlines, clipPoints): numberOfDaughterPatches = parentCenterlines.GetNumberOfCells() patchedCenterlines = vtk.vtkPolyData() patchedCenterlinesPoints = vtk.vtkPoints() patchedCenterlinesCellArray = vtk.vtkCellArray() patchedRadiusArray = vtk.vtkDoubleArray() clipIds, numberOfPatchedCenterlinesPoints = ExtractPatchesIds( parentCenterlines, clipPoints) print('Clipping Point Ids ', clipIds) radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetName(radiusArrayName) radiusArray.SetNumberOfTuples(numberOfPatchedCenterlinesPoints) radiusArray.FillComponent(0, 0.0) numberOfCommonPatch = clipIds[0] + 1 patchedCenterlinesCellArray.InsertNextCell(numberOfCommonPatch) count = 0 for i in range(0, numberOfCommonPatch): patchedCenterlinesPoints.InsertNextPoint(parentCenterlines.GetPoint(i)) patchedCenterlinesCellArray.InsertCellPoint(i) radiusArray.SetTuple1( i, parentCenterlines.GetPointData().GetArray( radiusArrayName).GetTuple1(i)) count += 1 for j in range(numberOfDaughterPatches): cell = vtk.vtkGenericCell() parentCenterlines.GetCell(j, cell) numberOfCellPoints = cell.GetNumberOfPoints() startId = clipIds[j + 1] patchNumberOfPoints = numberOfCellPoints - startId patchedCenterlinesCellArray.InsertNextCell(patchNumberOfPoints) for i in range(startId, cell.GetNumberOfPoints()): point = cell.GetPoints().GetPoint(i) patchedCenterlinesPoints.InsertNextPoint(point) patchedCenterlinesCellArray.InsertCellPoint(count) radiusArray.SetTuple1( count, parentCenterlines.GetPointData().GetArray( radiusArrayName).GetTuple1(cell.GetPointId(i))) count += 1 patchedCenterlines.SetPoints(patchedCenterlinesPoints) patchedCenterlines.SetLines(patchedCenterlinesCellArray) patchedCenterlines.GetPointData().AddArray(radiusArray) return patchedCenterlines
def write_vtk(filename, points, cells=None, cell_types=None, pointdata=None, tag=None, datadim=1): import vtk data = vtk.vtkUnstructuredGrid() # is also vtkDataSet DataArray = vtk.vtkDoubleArray() DataArray.SetNumberOfComponents(datadim) if tag: DataArray.SetName(tag) vtkpoints = vtk.vtkPoints() for i, point in enumerate(points): vtkpoints.InsertPoint(i, point) if pointdata is not None and len(pointdata) > 0: if len(pointdata.shape ) == 1 or pointdata.shape[1] == 1: #scalar data DataArray.InsertTuple1(i, pointdata[i]) elif len(pointdata.shape ) > 1 and pointdata.shape[1] == 2: #two dimensional data DataArray.InsertTuple2(i, pointdata[i, 0], pointdata[i, 1]) elif len( pointdata.shape) > 1 and pointdata.shape[1] == 3: #3D-data DataArray.InsertTuple3(i, pointdata[i, 0], pointdata[i, 1], pointdata[i, 2]) data.SetPoints(vtkpoints) if cells: cellArray = vtk.vtkCellArray() for i, cell in enumerate(cells): vtkCell = vtk.vtkGenericCell() vtkCell.SetCellType(cell_types[i]) idList = vtk.vtkIdList() for cellid in cell: idList.InsertNextId(cellid) vtkCell.SetPointIds(idList) cellArray.InsertNextCell(vtkCell) data.SetCells(cell_types, cellArray) pointData = data.GetPointData() if len(pointdata.shape) == 1 or pointdata.shape[1] == 1: pointData.SetScalars(DataArray) print("Writing scalar data...") else: pointData.SetVectors(DataArray) print("Writing Vector data...") write_dataset(filename, data) writer = vtk.vtkUnstructuredGridWriter() writer.SetFileName(filename) writer.SetInputData(data) writer.Write()
def CreateParentArteryPatches(parentCenterlines, clipPoints): numberOfDaughterPatches = parentCenterlines.GetNumberOfCells() patchedCenterlines = vtk.vtkPolyData() patchedCenterlinesPoints = vtk.vtkPoints() patchedCenterlinesCellArray = vtk.vtkCellArray() patchedRadiusArray = vtk.vtkDoubleArray() clipIds, numberOfPatchedCenterlinesPoints = ExtractPatchesIds(parentCenterlines, clipPoints) print "Clipping Point Ids ", clipIds radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetName(radiusArrayName) radiusArray.SetNumberOfTuples(numberOfPatchedCenterlinesPoints) radiusArray.FillComponent(0, 0.0) numberOfCommonPatch = clipIds[0] + 1 patchedCenterlinesCellArray.InsertNextCell(numberOfCommonPatch) count = 0 for i in range(0, numberOfCommonPatch): patchedCenterlinesPoints.InsertNextPoint(parentCenterlines.GetPoint(i)) patchedCenterlinesCellArray.InsertCellPoint(i) radiusArray.SetTuple1(i, parentCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(i)) count += 1 for j in range(numberOfDaughterPatches): cell = vtk.vtkGenericCell() parentCenterlines.GetCell(j, cell) numberOfCellPoints = cell.GetNumberOfPoints() startId = clipIds[j + 1] patchNumberOfPoints = numberOfCellPoints - startId patchedCenterlinesCellArray.InsertNextCell(patchNumberOfPoints) for i in range(startId, cell.GetNumberOfPoints()): point = cell.GetPoints().GetPoint(i) patchedCenterlinesPoints.InsertNextPoint(point) patchedCenterlinesCellArray.InsertCellPoint(count) radiusArray.SetTuple1( count, parentCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i)) ) count += 1 patchedCenterlines.SetPoints(patchedCenterlinesPoints) patchedCenterlines.SetLines(patchedCenterlinesCellArray) patchedCenterlines.GetPointData().AddArray(radiusArray) return patchedCenterlines
def ExtractSingleLine(centerlines, id, startID=0, endID=None): cell = vtk.vtkGenericCell() centerlines.GetCell(id, cell) N = cell.GetNumberOfPoints() if endID is None else endID + 1 line = vtk.vtkPolyData() cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(N - startID) linePoints = vtk.vtkPoints() arrays = [] N_, names = get_number_of_arrays(centerlines) for i in range(N_): tmp = centerlines.GetPointData().GetArray(names[i]) tmp_comp = tmp.GetNumberOfComponents() radiusArray = get_vtk_array(names[i], tmp_comp, N - startID) arrays.append(radiusArray) getArray = [] for i in range(N_): getArray.append(centerlines.GetPointData().GetArray(names[i])) count = 0 for i in range(startID, N): cellArray.InsertCellPoint(count) linePoints.InsertNextPoint(cell.GetPoints().GetPoint(i)) for j in range(N_): num = getArray[j].GetNumberOfComponents() if num == 1: tmp = getArray[j].GetTuple1(i) arrays[j].SetTuple1(count, tmp) elif num == 2: tmp = getArray[j].GetTuple2(i) arrays[j].SetTuple2(count, tmp[0], tmp[1]) elif num == 3: tmp = getArray[j].GetTuple3(i) arrays[j].SetTuple3(count, tmp[0], tmp[1], tmp[2]) elif num == 9: tmp = getArray[j].GetTuple9(i) arrays[j].SetTuple9(count, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], tmp[8]) count += 1 line.SetPoints(linePoints) line.SetLines(cellArray) for j in range(N_): line.GetPointData().AddArray(arrays[j]) return line
def getPointOnOtherMesh( a, a_locator, b, p ): '''Given two vtkPolyData's with matching topology and a vtkCellLocator for the first, carry point p from one to the other.''' cell_id = vtk.mutable(0) sub_id = vtk.mutable(0) d2 = vtk.mutable(0.0) cell = vtk.vtkGenericCell() p2 = p found = a_locator.FindClosestPoint( p, p2, cell, cell_id, sub_id, d2 ) p3 = p2 pcoords = [0,0,0] weights = [] cell.EvaluatePosition( p2, p3, sub_id, pcoords, d2, weights ) p4 = p3 b.GetCell( cell_id ).EvaluateLocation( sub_id, pcoords, p4, weights ) return p4
def getCellLocator(mesh, verbose=0): myVTK.myPrint(verbose, "*** getCellLocator ***") cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(mesh) cell_locator.Update() closest_point = [0.] * 3 generic_cell = vtk.vtkGenericCell() k_cell = vtk.mutable(0) subId = vtk.mutable(0) dist = vtk.mutable(0.) return (cell_locator, closest_point, generic_cell, k_cell, subId, dist)
def getPointOnOtherMesh(a, a_locator, b, p): '''Given two vtkPolyData's with matching topology and a vtkCellLocator for the first, carry point p from one to the other.''' cell_id = vtk.mutable(0) sub_id = vtk.mutable(0) d2 = vtk.mutable(0.0) cell = vtk.vtkGenericCell() p2 = p found = a_locator.FindClosestPoint(p, p2, cell, cell_id, sub_id, d2) p3 = p2 pcoords = [0, 0, 0] weights = [] cell.EvaluatePosition(p2, p3, sub_id, pcoords, d2, weights) p4 = p3 b.GetCell(cell_id).EvaluateLocation(sub_id, pcoords, p4, weights) return p4
def __init__(self, dset): self.dset = dset.VTKObject self.xyz = [-10000, -20000, -30000] self.pids = vtk.reference([0] * 10) self.nverts = -1 self.pc = [0] * 3 self.wts = [0] * 10 self.gc = vtk.vtkGenericCell() self.sid = 2 if self.dset.IsA('vtkUnstructuredGrid'): self.locator = vtk.vtkCellTreeLocator() self.locator.SetDataSet(dset.VTKObject) self.locator.BuildLocator() self.is_vtu = True else: self.is_vtu = False
def __init__(self, grid): """ Constructor @param grid vtkUnstructuredGrid instance """ self.grid = grid self.cellLocator = vtk.vtkCellLocator() self.cellLocator.SetDataSet(self.grid) self.cellLocator.BuildLocator() self.cell = vtk.vtkGenericCell() self.cellId = -1 self.subId = vtk.mutable(0) self.x = numpy.zeros((3, ), numpy.float64) # hexagon self.weights = numpy.zeros((8, ), numpy.float64) self.tol2 = 1.e-12 self.pcoords = numpy.zeros((3, ), numpy.float64)
def writeObj(filename, polydata): vertices = [] faces = [] for i in range(0, polydata.GetNumberOfPoints()): point = polydata.GetPoint(i) vertices.append(point) cell = vtk.vtkGenericCell() it = polydata.NewCellIterator() it.InitTraversal() # Iterate over the original cells while not it.IsDoneWithTraversal(): it.GetCell(cell) ids = [] numOfPoints = cell.GetNumberOfPoints() for i in range(0, numOfPoints): id = cell.GetPointId(i) + 1 ids.append(id) faces.append(ids) it.GoToNextCell() if os.path.isfile(filename): os.remove(filename) with open(filename, 'a') as resFile: # vertices for vertex in vertices: line = "v" for c in vertex: line = line + " " + str(c) line = line + "\n" resFile.write(line) for face in faces: line = "f" for f in face: line = line + " " + str(f) line = line + "\n" resFile.write(line)
def __call__(self, caller, ev): sliderWidget = caller value = sliderWidget.GetRepresentation().GetValue() self.tessellate.SetChordError(value) self.tessellate.SetMaximumNumberOfSubdivisions(5) self.tessellate.Update() cellMap = dict() numTets = 0 cell = vtk.vtkGenericCell() it = self.tessellate.GetOutput().NewCellIterator() it.InitTraversal() while not it.IsDoneWithTraversal(): it.GetCell(cell) cellMap[cell.GetRepresentativeCell().GetClassName()] = numTets numTets += 1 it.GoToNextCell() ss = '# of Tetras: ' + str(numTets) self.textMapper.SetInput(ss)
def getCellLocator( mesh, verbose=0): myVTK.myPrint(verbose, "*** getCellLocator ***") cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(mesh) cell_locator.Update() closest_point = [0.]*3 generic_cell = vtk.vtkGenericCell() k_cell = vtk.mutable(0) subId = vtk.mutable(0) dist = vtk.mutable(0.) return (cell_locator, closest_point, generic_cell, k_cell, subId, dist)
def _map_points_to_cells(pts, dataset, tol=1e-3): locator = vtk.vtkCellLocator() locator.SetDataSet(dataset) locator.BuildLocator() closest_pt = np.zeros(3) generic_cell = vtk.vtkGenericCell() cell_id, sub_id, dist2, inside = vtk.mutable(0), vtk.mutable( 0, ), vtk.mutable(0.0), vtk.mutable(0) map_to_cells = np.zeros(len(pts), dtype=np.int64) for pt_id, pt in enumerate(pts): if locator.FindClosestPointWithinRadius( pt, tol, closest_pt, generic_cell, cell_id, sub_id, dist2, inside, ): map_to_cells[pt_id] = cell_id.get() return map_to_cells
def __init__(self, data): self.polyData = data self.polyData.BuildCells() self.polyData.BuildLinks() self.tCoords = data.GetPointData().GetTCoords() self.points = data.GetPoints() self.npTCoords = np.empty((data.GetPolys().GetNumberOfCells(), 6)) self.npPolys = np.empty((data.GetPolys().GetNumberOfCells(), 3), dtype=np.uint16) nTuples = self.tCoords.GetNumberOfTuples() tCoordPoints = vtk.vtkFloatArray() tCoordPoints.SetNumberOfComponents(3) # tCoordPoints.SetNumberOfTuples(3) tCoordPoints.Allocate(nTuples * 3) tCoordPoints.SetNumberOfTuples(nTuples) tCoordPoints.CopyComponent(0, self.tCoords, 0) tCoordPoints.CopyComponent(1, self.tCoords, 1) tCoordPoints.FillComponent(2, 0) self.polyData2D = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(tCoordPoints) self.polyData2D.SetPoints(points) self.polyData2D.SetPolys(data.GetPolys()) self.polyData2D.BuildCells() self.polyData2D.BuildLinks() self.pointLocator = vtk.vtkCellLocator() self.pointLocator.SetDataSet(data) self.pointLocator.BuildLocator() self.pointLocator2D = vtk.vtkCellLocator() self.pointLocator2D.SetDataSet(self.polyData2D) self.pointLocator2D.BuildLocator() # Reused variables self._cell = vtk.vtkGenericCell() self._cell.SetCellTypeToTriangle()
def apply_load(self): uGrid = self.uGrid cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(uGrid) cell_locator.BuildLocator() closest_point = [0.0, 0.0, 0.0] # coordinate of closest point (to be returned) gen_cell = vtk.vtkGenericCell( ) # when having many query points, accelerate the cell locator by allocating once cell_id = vtk.reference(0) # located cell (to be returned) sub_id = vtk.reference(0) # rarely used (to be returned) dist2 = vtk.reference(0.0) self.applied_forces = [] for i, l in enumerate(self.cell_lists): force = self.forces[i] for ids in l: cell_locator.FindClosestPoint( [self.center_x[ids[0]], self.center_y[ids[1]], 0.0], closest_point, gen_cell, cell_id, sub_id, dist2) cellId = cell_id.get() force_info = [cellId, force, 0] self.applied_forces.append(force_info)
def _get_pids_sphere(source, target, source_mask=None, target_mask=None): """Spheres `source` and `target` must be aligned.""" c = vtkGenericCell() close_pt, pcoord = np.empty((2, 3)) cid, subcid, dist = [vtk_mutable(0) for _ in range(3)] if source_mask is not None: gids = np.arange(source.n_points) name_ids = source.append_array(gids, at='p') source_masked = mask_points(source, source_mask) source.remove_array(name_ids) source = source_masked if source.n_points != np.count_nonzero(source_mask): raise ValueError('Source mask is not fully connected.') celoc = vtkCellLocator() celoc.SetDataSet(source.VTKObject) celoc.BuildLocator() tp = me.get_points(target, mask=target_mask) n_pts = tp.shape[0] weights = np.empty((n_pts, 3)) pids = np.empty((n_pts, 3), dtype=np.int64) for i, p in enumerate(tp): celoc.FindClosestPoint(p, close_pt, c, cid, subcid, dist) c.EvaluatePosition(close_pt, close_pt, subcid, pcoord, dist, weights[i]) pids[i] = [c.GetPointIds().GetId(k) for k in range(3)] if source_mask is not None: gids = source.get_array(name_ids, at='p') pids = np.unique(gids, return_inverse=True)[1][pids] return pids, weights
# now that we have a simple polydata set up, test the reference # annoyance quad1 = poly.GetCell(0) print "quad1", quad1.GetBounds() quad2 = poly.GetCell(1) print "quad2", quad2.GetBounds() print "quad1", quad1.GetBounds() # this gives this output, the reference to quad 1 is overwritten! ## quad1 (0.0, 1.0, 0.0, 1.0, 0.0, 0.0) ## quad2 (1.0, 2.0, 0.0, 1.0, 0.0, 0.0) ## quad1 (1.0, 2.0, 0.0, 1.0, 0.0, 0.0) # try using another version of GetCell quad1 = vtk.vtkGenericCell() quad2 = vtk.vtkGenericCell() poly.GetCell(0,quad1) print "quad1", quad1.GetBounds() poly.GetCell(1,quad2) print "quad2", quad2.GetBounds() print "quad1", quad1.GetBounds() # this fixes the problem! ## quad1 (0.0, 1.0, 0.0, 1.0, 0.0, 0.0) ## quad2 (1.0, 2.0, 0.0, 1.0, 0.0, 0.0) ## quad1 (0.0, 1.0, 0.0, 1.0, 0.0, 0.0)
patchCenterlines = ReadPolyData(patchCenterlinesFilename) clippedVoronoi = ReadPolyData(clippedVoronoiFilename) clippingPoints = ReadPolyData(clippingPointsFilename) completeVoronoiDiagram = vtk.vtkPolyData() completeVoronoiDiagram.DeepCopy(clippedVoronoi) numberOfInterpolatedCenterlinesCells = interpolatedCenterlines.GetNumberOfCells( ) for j in range(1, numberOfInterpolatedCenterlinesCells + 1): interpolationCellId = j - 1 startId = 0 endId = j startCell = vtk.vtkGenericCell() patchCenterlines.GetCell(startId, startCell) startCellPointId = startCell.GetPointId(startCell.GetNumberOfPoints() - 1) startCellPoint = patchCenterlines.GetPoint(startCellPointId) startCellPointRadius = patchCenterlines.GetPointData().GetArray( radiusArrayName).GetTuple1(startCellPointId) startCellPointHalfRadius = startCellPointRadius / 7.0 startInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram( startId, startCellPointId, startCellPointRadius, clippedVoronoi, patchCenterlines) startHalfInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram( startId, startCellPointId, startCellPointHalfRadius, clippedVoronoi, patchCenterlines)
interpolatedCenterlines = ReadPolyData(interpolatedCenterlinesFilename) patchCenterlines = ReadPolyData(patchCenterlinesFilename) clippedVoronoi = ReadPolyData(clippedVoronoiFilename) clippingPoints = ReadPolyData(clippingPointsFilename) completeVoronoiDiagram = vtk.vtkPolyData() completeVoronoiDiagram.DeepCopy(clippedVoronoi) numberOfInterpolatedCenterlinesCells = interpolatedCenterlines.GetNumberOfCells() for j in range(1,numberOfInterpolatedCenterlinesCells+1): interpolationCellId = j-1 startId = 0 endId = j startCell = vtk.vtkGenericCell() patchCenterlines.GetCell(startId,startCell) startCellPointId = startCell.GetPointId(startCell.GetNumberOfPoints()-1) startCellPoint = patchCenterlines.GetPoint(startCellPointId) startCellPointRadius = patchCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(startCellPointId) startCellPointHalfRadius = startCellPointRadius/7.0 startInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(startId,startCellPointId,startCellPointRadius,clippedVoronoi,patchCenterlines) startHalfInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(startId,startCellPointId,startCellPointHalfRadius,clippedVoronoi,patchCenterlines) endCell = vtk.vtkGenericCell() patchCenterlines.GetCell(endId,endCell) endCellPointId = endCell.GetPointId(0) endCellPoint = patchCenterlines.GetPoint(endCellPointId)
def addLocalProlateSpheroidalDirections(ugrid_wall, pdata_end, pdata_epi, type_of_support="cell", epiflip=False, endoflip=False, apexflip=False, points_AB=None, eCCname="eCC", eLLname="eLL", eRRname="eRR", verbose=True): if (verbose): print '*** addLocalProlateSpheroidalDirections ***' if (points_AB == None): points_AB = getABPointsFromBoundsAndCenter(pdata_epi, verbose) assert (points_AB.GetNumberOfPoints() == 2), "points_AB must have two points. Aborting." point_A = numpy.array([0.]*3) point_B = numpy.array([0.]*3) points_AB.GetPoint(0, point_A) points_AB.GetPoint(1, point_B) if(apexflip): eL = point_A - point_B else: eL = point_B - point_A eL /= numpy.linalg.norm(eL) if (type_of_support == "cell"): pdata_cell_centers = getCellCenters(ugrid_wall) if (verbose): print "Computing cell normals..." if(epiflip): pdata_epi = getPDataNormals(pdata_epi, flip=1) else: pdata_epi = getPDataNormals(pdata_epi, flip=0) if(endoflip): pdata_end = getPDataNormals(pdata_end, flip=1) else: pdata_end = getPDataNormals(pdata_end, flip=0) if (verbose): print "Computing surface bounds..." bounds_end = pdata_end.GetBounds() bounds_epi = pdata_epi.GetBounds() z_min_end = bounds_end[4] z_min_epi = bounds_epi[4] z_max_end = bounds_end[5] z_max_epi = bounds_epi[5] L_end = z_max_end-z_min_end L_epi = z_max_epi-z_min_epi if (verbose): print "Initializing cell locators..." cell_locator_end = vtk.vtkCellLocator() cell_locator_end.SetDataSet(pdata_end) cell_locator_end.Update() cell_locator_epi = vtk.vtkCellLocator() cell_locator_epi.SetDataSet(pdata_epi) cell_locator_epi.Update() closest_point_end = [0.]*3 closest_point_epi = [0.]*3 generic_cell = vtk.vtkGenericCell() cellId_end = vtk.mutable(0) cellId_epi = vtk.mutable(0) subId = vtk.mutable(0) dist_end = vtk.mutable(0.) dist_epi = vtk.mutable(0.) if (verbose): print "Computing local prolate spheroidal directions..." if (type_of_support == "cell"): nb_cells = ugrid_wall.GetNumberOfCells() elif (type_of_support == "point"): nb_cells = ugrid_wall.GetNumberOfPoints() farray_norm_dist_end = createFloatArray("norm_dist_end", 1, nb_cells) farray_norm_dist_epi = createFloatArray("norm_dist_epi", 1, nb_cells) farray_norm_z_end = createFloatArray("norm_z_end", 1, nb_cells) farray_norm_z_epi = createFloatArray("norm_z_epi", 1, nb_cells) farray_eRR = createFloatArray(eRRname, 3, nb_cells) farray_eCC = createFloatArray(eCCname, 3, nb_cells) farray_eLL = createFloatArray(eLLname, 3, nb_cells) for num_cell in range(nb_cells): if (type_of_support == "cell"): cell_center = numpy.array(pdata_cell_centers.GetPoints().GetPoint(num_cell)) elif (type_of_support == "point"): cell_center = numpy.array(ugrid_wall.GetPoints().GetPoint(num_cell)) cell_locator_end.FindClosestPoint(cell_center, closest_point_end, generic_cell, cellId_end, subId, dist_end) cell_locator_epi.FindClosestPoint(cell_center, closest_point_epi, generic_cell, cellId_epi, subId, dist_epi) norm_dist_end = dist_end/(dist_end+dist_epi) norm_dist_epi = dist_epi/(dist_end+dist_epi) farray_norm_dist_end.InsertTuple(num_cell, [norm_dist_end]) farray_norm_dist_epi.InsertTuple(num_cell, [norm_dist_epi]) norm_z_end = (closest_point_end[2]-z_min_end)/L_end norm_z_epi = (closest_point_epi[2]-z_min_epi)/L_epi farray_norm_z_end.InsertTuple(num_cell, [norm_z_end]) farray_norm_z_epi.InsertTuple(num_cell, [norm_z_epi]) normal_end = numpy.reshape(pdata_end.GetCellData().GetNormals().GetTuple(cellId_end), (3)) normal_epi = numpy.reshape(pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi), (3)) eRR = -1*(1.-norm_dist_end) * normal_end + (1.-norm_dist_epi) * normal_epi eRR /= numpy.linalg.norm(eRR) eCC = numpy.cross(eL, eRR) eCC /= numpy.linalg.norm(eCC) eLL = numpy.cross(eRR, eCC) farray_eRR.InsertTuple(num_cell, eRR) farray_eCC.InsertTuple(num_cell, eCC) farray_eLL.InsertTuple(num_cell, eLL) if (verbose): print "Filling mesh..." if (type_of_support == "cell"): ugrid_wall.GetCellData().AddArray(farray_norm_dist_end) ugrid_wall.GetCellData().AddArray(farray_norm_dist_epi) ugrid_wall.GetCellData().AddArray(farray_norm_z_end) ugrid_wall.GetCellData().AddArray(farray_norm_z_epi) ugrid_wall.GetCellData().AddArray(farray_eRR) ugrid_wall.GetCellData().AddArray(farray_eCC) ugrid_wall.GetCellData().AddArray(farray_eLL) elif (type_of_support == "point"): ugrid_wall.GetPointData().AddArray(farray_norm_dist_end) ugrid_wall.GetPointData().AddArray(farray_norm_dist_epi) ugrid_wall.GetPointData().AddArray(farray_norm_z_end) ugrid_wall.GetPointData().AddArray(farray_norm_z_epi) ugrid_wall.GetPointData().AddArray(farray_eRR) ugrid_wall.GetPointData().AddArray(farray_eCC) ugrid_wall.GetPointData().AddArray(farray_eLL)
def fillCaps(self): # read the .obj and center it # polydata = Helpers.centerPolyData(Helpers.getObjData(modelFn)) # TODO: centering seems to glitch the tetgen somewhy polydata = Helpers.getObjData(modelFn) size = Helpers.getBounds(polydata) print "Model sizes:" + str(size) fillHolesFilter = vtk.vtkFillHolesFilter() fillHolesFilter.SetInputData(polydata) fillHolesFilter.SetHoleSize( 1000.0 ) # TODO: hole size: compute using model size (some factor of it) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(fillHolesFilter.GetOutputPort()) normals.ConsistencyOn() normals.SplittingOff() normals.Update() normals.GetOutput().GetPointData().SetNormals( polydata.GetPointData().GetNormals()) numOriginalCells = polydata.GetNumberOfCells() numNewCells = normals.GetOutput().GetNumberOfCells() it = normals.GetOutput().NewCellIterator() numCells = 0 it.InitTraversal() # Iterate over the original cells while (not it.IsDoneWithTraversal()) and numCells < numOriginalCells: it.GoToNextCell() numCells += 1 holePolyData = vtk.vtkPolyData() holePolyData.Allocate(normals.GetOutput(), numNewCells - numOriginalCells) holePolyData.SetPoints(normals.GetOutput().GetPoints()) cell = vtk.vtkGenericCell() # The remaining cells are the new ones from the hole filler while not it.IsDoneWithTraversal(): it.GetCell(cell) holePolyData.InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(holePolyData) connectivity.SetExtractionModeToAllRegions() connectivity.ColorRegionsOn() connectivity.Update() capRegions = connectivity.GetOutput() outPD = vtk.vtkPolyData() outPD.Allocate(normals.GetOutput(), numNewCells) outPD.SetPoints(capRegions.GetPoints()) numOfCaps = connectivity.GetNumberOfExtractedRegions() print "Found " + str(numOfCaps) + " holes." # create the cap polydatas capPDs = [] for i in range(0, numOfCaps): capPD = vtk.vtkPolyData() capPD.Allocate(normals.GetOutput(), numNewCells) capPD.SetPoints(capRegions.GetPoints()) capPDs.append(capPD) capScalars = capRegions.GetCellData().GetScalars() cell = vtk.vtkGenericCell() it = capRegions.NewCellIterator() i = 0 while not it.IsDoneWithTraversal(): it.GetCell(cell) # outPD.InsertNextCell(it.GetCellType(), cell.GetPointIds()) capIdx = capScalars.GetValue(i) capPDs[capIdx].InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() i = i + 1 sortedCaps = [] for i in range(0, len(capPDs)): capPD = capPDs[i] cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputData(capPD) cleanFilter.Update() cleanedPD = cleanFilter.GetOutput() area = Helpers.getArea(cleanedPD) radius = math.sqrt(area / math.pi) sortedCaps.append([cleanedPD, area, radius]) capPDs[i] = cleanedPD sortedCaps = sorted(sortedCaps, key=lambda x: x[1], reverse=True) [lastPd, area, radius] = sortedCaps[len(capPDs) - 1] print "Recommended edge size: " + str(radius / 2) scalarsName = "ModelFaceID" Helpers.appendScalars(polydata, 1, scalarsName) # 1 for the walls appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(outPD) appendFilter.AddInputData(polydata) scalarIdx = 2 for [capPD, area, radius] in sortedCaps: # if radius < 0.1: # Helpers.appendScalars(capPD, 1, scalarsName) # append the face ID idx # else: # Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx appendFilter.AddInputData(capPD) print "Cap radius: " + str(radius) scalarIdx += 1 appendFilter.Update() cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(appendFilter.GetOutputPort()) cleanFilter.Update() joinedPD = cleanFilter.GetOutput() # joinedPD.GetCellData().SetScalars(scalars) # Write as VTP Helpers.writeVTP(meshFn, joinedPD) return [ polydata, [[capPD, radius] for [capPD, area, radius] in sortedCaps] ]
sphere.SetRadius(mandel.GetOutput().GetLength()/4) # Clip data to spit out unstructured tets clipper = vtk.vtkClipDataSet() clipper.SetInputConnection(mandel.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.InsideOutOn() clipper.Update() output = clipper.GetOutput() numCells = output.GetNumberOfCells() bounds = output.GetBounds() #print bounds # Support subsequent method calls genCell = vtk.vtkGenericCell() t = vtk.reference(0.0) x = [0,0,0] pc = [0,0,0] subId = vtk.reference(0) cellId = vtk.reference(0) # Build the locator locator = vtk.vtkStaticCellLocator() #locator = vtk.vtkCellLocator() locator.SetDataSet(output) locator.AutomaticOn() locator.SetNumberOfCellsPerNode(20) locator.CacheCellBoundsOn() locator.BuildLocator()
def SimpleFindStrips(poly, coord): # Just do the cells in their given order # This method reduces the number of polys in the 20x20x20 by a factor of 3.623 # reduces the number of polys in the 100x100x100 by 2.216 #dirs=[0,1,2] #dirs.remove(coord) bounds = poly.GetBounds() numCells = poly.GetNumberOfCells() current = vtk.vtkGenericCell() newcell = vtk.vtkGenericCell() poly.GetCell(0, current) sharedpts = vtk.vtkIdList() sharedpts.DeepCopy(current.GetPointIds()) newPoints = vtk.vtkPoints() newPoints.DeepCopy(poly.GetPoints()) consolidatedpoly = vtk.vtkPolyData() consolidatedpoly.Allocate(1000,1000) consolidatedpoly.SetPoints(newPoints) x = [0,0,0] for i in xrange(1,numCells): poly.GetCell(i, newcell) # check if this cell shares an edge sharedpts.IntersectWith(newcell.GetPointIds()) # if they share an edge, the current cell becomes the union of the 2 cells if sharedpts.GetNumberOfIds() == 2: quad = vtk.vtkQuad() ptIds = [] for j in xrange(4): if sharedpts.IsId(current.GetPointIds().GetId(j)) == -1: ptIds.append(j) if ptIds == [0,3]: ptIds.reverse() current.GetPoints().GetPoint(ptIds[0],x) quad.GetPointIds().InsertId(0,current.GetPointIds().GetId(ptIds[0])) quad.GetPoints().InsertPoint(0,x) current.GetPoints().GetPoint(ptIds[1],x) quad.GetPointIds().InsertId(1,current.GetPointIds().GetId(ptIds[1])) quad.GetPoints().InsertPoint(1,x) ptIds = [] for j in xrange(4): if sharedpts.IsId(newcell.GetPointIds().GetId(j)) == -1: ptIds.append(j) if ptIds == [0,3]: ptIds.reverse() newcell.GetPoints().GetPoint(ptIds[0],x) quad.GetPointIds().InsertId(2,newcell.GetPointIds().GetId(ptIds[0])) quad.GetPoints().InsertPoint(2,x) newcell.GetPoints().GetPoint(ptIds[1],x) quad.GetPointIds().InsertId(3,newcell.GetPointIds().GetId(ptIds[1])) quad.GetPoints().InsertPoint(3,x) current.DeepCopy(quad) #consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds()) else: consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds()) current.DeepCopy(newcell) sharedpts.DeepCopy(current.GetPointIds()) consolidatedpoly.InsertNextCell(current.GetCellType(),current.GetPointIds()) cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(consolidatedpoly) consolidatedpoly = cleaner.GetOutput() consolidatedpoly.Squeeze() consolidatedpoly.Update() return consolidatedpoly
# plane hash is coord * plane value facesInPlane = {} polysInPlane = {} for i in indexlist: facesInPlane[i]={} polysInPlane[i]={} # needed to calulate normal and area polygon = vtk.vtkPolygon() triangle = vtk.vtkTriangle() normal = [0.0,0.0,0.0] pt=[0.0,0.0,0.0] sharedpts = vtk.vtkIdList() newpoints = vtk.vtkIdList() tempcell = vtk.vtkGenericCell() numinplane11 = 0 # loop over voxels and add faces that border different pixel groups to polydata for i in xrange(indexedImage.GetNumberOfCells()): voxel = indexedImage.GetCell(i) p = voxel.GetPoints().GetPoint(0) point = primitives.iPoint(p[0]-x0,p[1]-y0,p[2]-z0) value = indexedImage.GetScalarComponentAsFloat(point[0],point[1],point[2],0) for j in xrange(3): point2 = point+dirs[j] if point2[0] >= imageBounds[0] and point2[0] <= imageBounds[1]-1 and point2[1] >= imageBounds[2] and point2[1] <= imageBounds[3]-1 and point2[2] >= imageBounds[4] and point2[2] <= imageBounds[5]-1: value2 = indexedImage.GetScalarComponentAsFloat(point2[0],point2[1],point2[2],0) if value2 != value: face=voxel.GetFace(j*2)