def __getKdTree(self): particles_vtk_pts = vtk.vtkPoints() particles_vtk_pts.SetData( numpy_support.numpy_to_vtk(self.alive_particles_coordinates)) kdtree = vtk.vtkKdTree() kdtree.SetNumberOfRegionsOrLess(self.numberOfProcessors) kdtree.BuildLocatorFromPoints(particles_vtk_pts) return kdtree
def __init__(self): VTKPythonAlgorithmBase.__init__(self, nInputPorts=1, inputType='vtkUnstructuredGrid', nOutputPorts=0) self.cc = vtk.vtkCellCenters() # tried using a vtkCellLocator for FindCellsAlongLine # but it wouldn't find the vertex cells for some reason... self.tree = vtk.vtkKdTree() self._empty_dataset = False
def __init__(self,init_node): self.nodes=[] self.nodes.append(init_node) self.last_node=0 self.end_nodes=[] points = vtk.vtkPoints() for node in self.nodes: points.InsertNextPoint( node[0], node[1], node[2] ) self.vtk_tree=vtk.vtkKdTree() self.vtk_tree.BuildLocatorFromPoints(points) #self.tree=cKDTree(self.nodes) self._logger = logging.getLogger('fractal-tree')
def meshPointCloud( inputVTKfile, searchRad ): reader = v.vtkPolyDataReader() reader.SetFileName( inputVTKfile ) reader.Update() pd = reader.GetOutput() N = pd.GetNumberOfPoints() kdt = v.vtkKdTree() kdt.BuildLocatorFromPoints( pd.GetPoints() ) polys = v.vtkCellArray() for i in range( N ): currPoint = pd.GetPoint(i) idList = v.vtkIdList() kdt.FindPointsWithinRadius( searchRad, currPoint, idList ) neighbors = [] for j in range( idList.GetNumberOfIds() ): currId = idList.GetId(j) if j != i: neighbors.append(currId)
def registration_error(points, surface): ''' Input: points and surface are all vtkPolyData Workflow: 1. construct a kd-tree from surface 2. iterate points to find nearst points ''' kdTree = vtk.vtkKdTree() kdTree.BuildLocatorFromPoints(surface.GetPoints()) num_points = points.GetNumberOfPoints() dist = np.zeros(num_points) for i in range(num_points): print 'progress: %4f%%' % (float(i) * 100 / float(num_points)) closestPointDist = vtk.mutable(0.0) closestPointID = 0 testPoint = points.GetPoint(i) closestPointID = kdTree.FindClosestPoint(testPoint, closestPointDist) dist[i] = closestPointDist return dist
def update_collision_tree(self,nodes_to_exclude): """This function updates the collision_tree excluding a list of nodes from all the nodes in the tree. If all the existing nodes are excluded, one distant node is added. Args: nodes_to_exclude (list): contains the nodes to exclude from the tree. Usually it should be the mother and the brother branch nodes. Returns: none """ nodes=set(range(len(self.nodes))) nodes=nodes.difference(nodes_to_exclude) nodes_to_consider=[self.nodes[x] for x in nodes] self.nodes_to_consider_keys=[x for x in nodes] if len(nodes_to_consider)==0: nodes_to_consider=[np.array([-100000000000.0,-100000000000.0,-100000000000.0])] self.nodes_to_consider_keys=[100000000] self._logger.debug("No nodes to consider") points = vtk.vtkPoints() for node in nodes_to_consider: points.InsertNextPoint( node[0], node[1], node[2] ) self.vtk_collision_tree=vtk.vtkKdTree() self.vtk_collision_tree.BuildLocatorFromPoints(points)
def add_nodes(self,queue): """This function stores a list of nodes of a branch and returns the node indices. It also updates the tree to compute distances. Args: queue (list): a list of arrays containing the coordinates of the nodes of one branch. Returns: nodes_id (list): the indices of the added nodes. """ nodes_id=[] for point in queue: self.nodes.append(point) self.last_node+=1 nodes_id.append(self.last_node) points = vtk.vtkPoints() for node in self.nodes: points.InsertNextPoint( node[0], node[1], node[2] ) self.vtk_tree=vtk.vtkKdTree() self.vtk_tree.BuildLocatorFromPoints(points) #self.tree=cKDTree(self.nodes) return nodes_id
def update(self): normalArray = vtkFloatArray() normalArray.SetNumberOfComponents( 3 ) normalArray.SetNumberOfTuples( self.input_.GetNumberOfPoints() ) normalArray.SetName( "Normals" ) kDTree = vtkKdTree() kDTree.BuildLocatorFromPoints(self.input_.GetPoints()) # Estimate the normal at each point. for pointId in xrange(0, self.input_.GetNumberOfPoints()): point = [0,0,0] self.input_.GetPoint(pointId, point) neighborIds = vtkIdList() if self.mode == FIXED_NUMBER: kDTree.FindClosestNPoints(self.number_neighbors, point, neighborIds) elif self.mode == RADIUS: kDTree.FindPointsWithinRadius(self.radius, point, neighborIds) #If there are not at least 3 points within the specified radius (the current # #point gets included in the neighbors set), a plane is not defined. Instead, # #force it to use 3 points. if neighborIds.GetNumberOfIds() < 3 : kDTree.FindClosestNPoints(3, point, neighborIds) bestPlane = vtkPlane() self.best_fit_plane(self.input_.GetPoints(), bestPlane, neighborIds) normal = bestPlane.GetNormal() normalArray.SetTuple( pointId, normal ) self.output_ = vtkPolyData() self.output_.ShallowCopy(self.input_) self.output_.GetPointData().SetNormals(normalArray)
def update(self): normalArray = vtkFloatArray() normalArray.SetNumberOfComponents( 3 ) normalArray.SetNumberOfTuples( self.input_.GetNumberOfPoints() ) normalArray.SetName( "Normals" ) kDTree = vtkKdTree() kDTree.BuildLocatorFromPoints(self.input_.GetPoints()) # Estimate the normal at each point. for pointId in range(0, self.input_.GetNumberOfPoints()): point = [0,0,0] self.input_.GetPoint(pointId, point) neighborIds = vtkIdList() if self.mode == FIXED_NUMBER: kDTree.FindClosestNPoints(self.number_neighbors, point, neighborIds) elif self.mode == RADIUS: kDTree.FindPointsWithinRadius(self.radius, point, neighborIds) #If there are not at least 3 points within the specified radius (the current # #point gets included in the neighbors set), a plane is not defined. Instead, # #force it to use 3 points. if neighborIds.GetNumberOfIds() < 3 : kDTree.FindClosestNPoints(3, point, neighborIds) bestPlane = vtkPlane() self.best_fit_plane(self.input_.GetPoints(), bestPlane, neighborIds) normal = bestPlane.GetNormal() normalArray.SetTuple( pointId, normal ) self.output_ = vtkPolyData() self.output_.ShallowCopy(self.input_) self.output_.GetPointData().SetNormals(normalArray)
def __init__(self,filename): vtp_filename = filename print("Input file name %s" % filename) #vtu_filename = "sphere.vtu" verts, connectivity, points = self.loadVtp(vtp_filename) #verts, connectivity, points = self.loadVtu(vtu_filename) #verts, connectivity = self.loadOBJ(filename) self.verts=np.array(verts) self.connectivity=np.array(connectivity) self.normals=np.zeros(self.connectivity.shape) self.node_to_tri=collections.defaultdict(list) for i in range(len(self.connectivity)): for j in range(3): self.node_to_tri[self.connectivity[i,j]].append(i) u=self.verts[self.connectivity[i,1],:]-self.verts[self.connectivity[i,0],:] v=self.verts[self.connectivity[i,2],:]-self.verts[self.connectivity[i,0],:] n=np.cross(u,v) self.normals[i,:]=n/np.linalg.norm(n) #self.tree=cKDTree(verts) self.tree=vtk.vtkKdTree() #self.tree.BuildLocatorFromPoints(verts) self.tree.BuildLocatorFromPoints(points)
numAttempts = 3 params = np.array([ alphaM[0], alphaP, alphaN, alphaC, E, re, s, K, a, b, \ searchRad]) # Read a input file reader = v.vtkPolyDataReader() reader.SetFileName(fileNameExt) reader.Update() # Fetch the polydata pd = reader.GetOutput() numPoints = pd.GetNumberOfPoints() # Compute the average distance between neighboring particles for normalization. kdt = v.vtkKdTree() kdt.BuildLocatorFromPoints( pd ) avgLen = 0.0 numberOfEdges = 0 for i in range( numPoints ): currPoint = np.array( pd.GetPoint( i ) ) neighbors = v.vtkIdList() kdt.FindPointsWithinRadius( initialRad, currPoint, neighbors ) # One of the points is the input itself. So we need to skip it numNeighbors = neighbors.GetNumberOfIds() - 1 numberOfEdges += numNeighbors for j in range( numNeighbors + 1 ): neighborId = neighbors.GetId( j ) if neighborId != i: neighbor = np.array( pd.GetPoint( neighborId ) ) avgLen += la.norm( neighbor - currPoint )
print "filtered segment %d" % (k) cleaner_2 = vtk.vtkCleanPolyData() cleaner_2.SetInputConnection(tri_2.GetOutputPort()) cleaner_2.SetTolerance(0.005) cleaner_2.Update() print "cleaned segment %d" % (k) dataMapper = vtk.vtkPolyDataMapper() dataMapper.SetInput(cleaner_2.GetOutput()) model = vtk.vtkActor() model.SetMapper(dataMapper) model.GetProperty().SetColor(random.random(),random.random(),random.random()) print "data mapped segment %d" % (k) obb = vtk.vtkKdTree() obb.SetDataSet(cleaner_2.GetOutput()) obb.AutomaticOff() obb.SetMaxLevel(30) obb.SetMinCells(10) obb.BuildLocator() poly = vtk.vtkPolyData() obb.GenerateRepresentation(20, poly) #obb.PrintTree() octreeMapper = vtk.vtkPolyDataMapper() octreeMapper.SetInputConnection(poly.GetProducerPort()) octreeActor = vtk.vtkActor()
pointgrid.SetVerts(vertices) pointgrid.Update() # Find out which points reside inside mesh geometry if options.verbose: sys.stdout.write("\nIDENTIFYING POINTS INSIDE MESH GEOMETRY\n") enclosedPoints = vtk.vtkSelectEnclosedPoints() enclosedPoints.SetSurface(surface) enclosedPoints.SetInput(pointgrid) enclosedPoints.Update() # Build kdtree from mesh IPs and match mesh IPs to point grid if options.verbose: sys.stdout.write("\nBUILDING MAPPING OF GRID POINTS") kdTree = vtk.vtkKdTree() kdTree.BuildLocatorFromPoints(meshIPs.GetPoints()) gridToMesh = [] ids = vtk.vtkIdList() NenclosedPoints = 0 for i in range(pointgrid.GetNumberOfPoints()): gridToMesh.append([]) if enclosedPoints.IsInside(i): NenclosedPoints += 1 # here one could use faster(?) "FindClosestPoint" if only first nearest neighbor required kdTree.FindClosestNPoints(options.interpolation, pointgrid.GetPoint(i), ids) for j in range(ids.GetNumberOfIds()): gridToMesh[-1].extend([ids.GetId(j)]) if options.verbose: sys.stdout.write("\rBUILDING MAPPING OF GRID POINTS %d%%" %
def sysEnergyJacobian(x, params, calcJac=True): N_tot = len(x) / 6 N = int(N_tot) # Create vtkPoints from x pts = v.vtkPoints() for i in range(N): si = i * 6 currPoint = x[si + 3:si + 6] pts.InsertNextPoint(currPoint) # Build k-d tree to search for neighbors kdt = v.vtkKdTree() kdt.BuildLocatorFromPoints(pts) # Get the search radius from params searchRad = params[10] params_internal = params[0:10] # Calculate energy and Jacobian energy = 0.0 jacobian = zeros(N * 6) if calcJac is False: for i in range(N): si = i * 6 centerRotVec = x[si:si + 3] centerPoint = x[si + 3:si + 6] # Fetch neighbor ids currPointSet = v.vtkIdList() kdt.FindPointsWithinRadius(searchRad, centerPoint, currPointSet) # Separate center-point from neighbors list currNeighbors = [] currNumPts = 1 for j in range(currPointSet.GetNumberOfIds()): currId = currPointSet.GetId(j) if (currId != i): currNeighbors.append(currId) currNumPts += 1 # Create ith point-set x-vector currX = zeros(currNumPts * 6) currX[0:3] = centerRotVec currX[3:6] = centerPoint sj = 6 for j in currNeighbors: lsi = j * 6 currX[sj:sj + 3] = x[lsi:lsi + 3] currX[sj + 3:sj + 6] = x[lsi + 3:lsi + 6] sj += 6 EAndJ = pointEnergyJacobian(currX, params_internal, calcJac=False) energy += EAndJ[0] else: for i in range(N): si = i * 6 centerRotVec = x[si:si + 3] centerPoint = x[si + 3:si + 6] # Fetch neighbor ids currPointSet = v.vtkIdList() kdt.FindPointsWithinRadius(searchRad, centerPoint, currPointSet) # Separate center-point from neighbors list currNeighbors = [] currNumPts = 1 for j in range(currPointSet.GetNumberOfIds()): currId = currPointSet.GetId(j) if (currId != i): currNeighbors.append(currId) currNumPts += 1 # Create ith point-set x-vector currX = zeros(currNumPts * 6) currX[0:3] = centerRotVec currX[3:6] = centerPoint sj = 6 for j in currNeighbors: lsi = j * 6 currX[sj:sj + 3] = x[lsi:lsi + 3] currX[sj + 3:sj + 6] = x[lsi + 3:lsi + 6] sj += 6 EAndJ = pointEnergyJacobian(currX, params_internal) energy += EAndJ[0] currJacobian = EAndJ[1:] # Assemble into total jacobian jacobian[si:si + 3] += currJacobian[0:3] jacobian[si + 3:si + 6] += currJacobian[3:6] sj = 6 for j in currNeighbors: lsi = j * 6 jacobian[lsi:lsi + 3] += currJacobian[sj:sj + 3] jacobian[lsi + 3:lsi + 6] += currJacobian[sj + 3:sj + 6] sj += 6 return energy, jacobian
# If simulation was deformable wall get also displacement and deform to current state if disp == 1: reference_displacement = results["/displacement/%d" % cycle_start][:] disp_arr = results["/displacement/%d" % step_start][:] domain_pts[map_wall_to_domain] += disp_arr[map_wall_to_domain]-reference_displacement[map_wall_to_domain] reference_displacement[:] = disp_arr else: reference_displacement = None # Split particles among processes for probefilter input particles_partition = np.zeros((nliveparticles,),dtype=np.int64) if rank ==0: kdtree = vtk.vtkKdTree() kdtree.SetNumberOfRegionsOrLess(nprocs) kdtree.BuildLocatorFromPoints(particles_vtk_pts) offset=0 for i in range(nprocs): if i < kdtree.GetNumberOfRegions(): points_in_regions = numpy_support.vtk_to_numpy(kdtree.GetPointsInRegion(i)) offset += points_in_regions.shape[0] particles_partition[points_in_regions]=i particles_offsets[i+1] = offset print("Broadcasting...") comm.Bcast(particles_offsets,root=0) comm.Bcast(particles_partition,root=0) map_local_to_global = particles_indices[np.where(particles_partition==rank)] # Create polydata containing local particles coordinates. For Runge Kutta integration we need 4 local_particles_coordinates = particles_coordinates[map_local_to_global]
tubes0.SetInputConnection(cutStrips0.GetOutputPort()) # works tubes0.CappingOn() tubes0.SidesShareVerticesOff() tubes0.SetNumberOfSides(12) tubes0.SetRadius(1.0) edgeMapper0 = vtk.vtkPolyDataMapper() edgeMapper0.ScalarVisibilityOff() edgeMapper0.SetInputConnection(tubes0.GetOutputPort()) intActors.append(vtk.vtkActor()) intActors[iPlane].SetMapper(edgeMapper0) if 1: points = surfCircle.GetPoints() pointTree = vtk.vtkKdTree() pointTree.BuildLocatorFromPoints(points) nClosest = 3 result = vtk.vtkIdList() pointTree.FindClosestNPoints(nClosest + 1, centers[iPlane], result) #dataArray = points.GetData() #x = dataArray.GetComponent(result.GetId(2), 0) #y = dataArray.GetComponent(result.GetId(0), 1) #z = dataArray.GetComponent(result.GetId(0), 2) if 0: #print(x,y,z) print(points.GetPoint(result.GetId(nClosest))) # Visualize line #lineSource = vtk.vtkLineSource()
def __init__(self): self.m_kdTree = vtk.vtkKdTree()