def getClosestPointDistance(tree, x, y, z): closestPoint = [0.0, 0.0, 0.0] cellId = vtk.reference(0) subId = vtk.reference(0) distance = vtk.reference(0) tree.FindClosestPoint((x, y, z), closestPoint, cellId, subId, distance) return distance
def CloudMeanDist(source, target): # Source contains few points, target contains many locator = vtk.vtkCellLocator() locator.SetDataSet(target) locator.SetNumberOfCellsPerBucket(1) locator.BuildLocator() nPoints = source.GetNumberOfPoints() closestp = vtk.vtkPoints() closestp.SetNumberOfPoints(nPoints) subId = vtk.reference(0) dist2 = vtk.reference(0.0) cellId = vtk.reference(0) # mutable <-> reference outPoint = [0.0, 0.0, 0.0] for i in range(nPoints): locator.FindClosestPoint(source.GetPoint(i), outPoint, cellId, subId, dist2) closestp.SetPoint(i, outPoint) totaldist = 0.0 p1 = [0.0, 0.0, 0.0] p2 = [0.0, 0.0, 0.0] for i in range(nPoints): # RMS totaldist = totaldist + vtk.vtkMath.Distance2BetweenPoints( source.GetPoint(i), closestp.GetPoint(i)) return totaldist / nPoints
def RMS(sourceSurfaceFile, targetSurfaceFile, VTKobj=False): # Reading surfaces if not VTKobj: reader = vtk.vtkPolyDataReader() reader.SetFileName(sourceSurfaceFile) reader.Update() sourceSurface = reader.GetOutput() reader = vtk.vtkPolyDataReader() reader.SetFileName(targetSurfaceFile) reader.Update() targetSurface = reader.GetOutput() else: sourceSurface = sourceSurfaceFile targetSurface = targetSurfaceFile cellLocator = vtk.vtkCellLocator() cellLocator.SetDataSet(targetSurface) cellLocator.BuildLocator() sourcePoints = vtk_to_numpy(sourceSurface.GetPoints().GetData()) distances = np.zeros([np.size(sourcePoints, 0), 1]) idx = 0 for point in sourcePoints: closestPoint = [0, 0, 0] closestPointDist2 = vtk.reference(np.float64()) cellId = vtk.reference(1) subId = vtk.reference(1) cellLocator.FindClosestPoint(point, closestPoint, cellId, subId, closestPointDist2) distances[idx] = closestPointDist2 idx += 1 RMS = np.sqrt((distances).mean()) return RMS
def testPassTupleByReference(self): n = vtk.reference(0) t = vtk.reference((0,)) ca = vtk.vtkCellArray() ca.InsertNextCell(3, (1, 3, 0)) ca.GetCell(0, n, t) self.assertEqual(n, 3) self.assertEqual(tuple(t), (1, 3, 0))
def testFloatReference(self): m = vtk.reference(3.0) n = vtk.reference(4.0) m *= 2 self.assertEqual(m, 6.0) self.assertEqual(str(m), str(m.get())) o = n + m self.assertEqual(o, 10.0)
def testGetRangeTwoDoubleStarArg(self): cmap = vtk.vtkDiscretizableColorTransferFunction() localMin = vtk.reference(-1) localMax = vtk.reference(-1) cmap.GetRange(localMin, localMax) self.assertEqual(localMin, 0.0) self.assertEqual(localMax, 0.0)
def merge(feature_points_path, segment_points_path, merge_points_path): ''' feature_points_path:str, 特征点的文件路径 segment_points_path:str, 分割后网格的顶点的文件路径 merge_points_path:str, 合并后的顶点存储路径 ''' # 读取feature_points vertice_number = 0 feature_vertices = [] with open(feature_points_path, 'r') as f1: for line in f1.readlines(): line = str.split(line, ' ') vertice_number = vertice_number + 1 feature_vertices.append( [float(line[0]), float(line[1]), float(line[2])]) points = vtk.vtkPoints() points.SetNumberOfPoints(vertice_number) for i in range(vertice_number): points.SetPoint(i, feature_vertices[i]) # 初始化合并的顶点集 merge_points = vtk.vtkMergePoints() # merge_points.SetDataSet(points) merge_points.InitPointInsertion(points, points.GetBounds()) id = vtk.reference(0) for i in range(vertice_number): merge_points.InsertUniquePoint(points.GetPoint(i), id) vertice_number = 0 segment_points = [] with open(segment_points_path, 'r') as f2: for line in f2.readlines(): line = str.split(line, ' ') if line[0] == 'v': segment_points.append( [float(line[1]), float(line[2]), float(line[3])]) vertice_number = vertice_number + 1 else: break id = vtk.reference(0) replated_points_id = [] for i in range(vertice_number): inserted = merge_points.InsertUniquePoint(segment_points[i], id) if inserted == 0: replated_points_id.append([id, i]) result = merge_points.GetPoints() with open(merge_points_path, 'w') as f3: for i in range(result.GetNumberOfPoints()): pointTemp = result.GetPoint(i) f3.write("%f %f %f\n" % (pointTemp[0], pointTemp[1], pointTemp[2])) print("Replicated points number: %d" % len(replated_points_id)) return len(replated_points_id)
def compute_length_in_cell(self, cell, p1, p2): """Compute lenght of the line inside a cell. Parameters ---------- cell : vtkCell The cell to be cut by a line. p1 : type First endpoint describing the line. p2 : type Second endpoint describing the line. Returns ------- float Intersected length. """ # set up a bunch of dummy properties for passing to the cell functions. t = vtk.reference(0.0) dist = vtk.reference(0.0) pcords = [0.0, 0.0, 0.0] subid = vtk.reference(0) weights = [0.0] * cell.GetNumberOfPoints() dummy = [0.0, 0.0, 0.0] # Determine wether the points are inside the cell in1 = cell.EvaluatePosition(p1, dummy, subid, pcords, dist, weights) in2 = cell.EvaluatePosition(p2, dummy, subid, pcords, dist, weights) # Both points inside if in1 == 1 and in2 == 1: return np.linalg.norm(np.array(p2) - np.array(p1)) # Both points outside if in1 == 0 and in2 == 0: return 0.0 # Only point 2 inside if in1 == 0 and in2 == 1: x = [0.0, 0.0, 0.0] res = cell.IntersectWithLine(p1, p2, 0.0, t, x, pcords, subid) if res > 0: return np.linalg.norm(np.array(p2) - np.array(x)) else: return 0.0 # Only point 1 inside if in1 == 1 and in2 == 0: x = [0.0, 0.0, 0.0] res = cell.IntersectWithLine(p1, p2, 0.0, t, x, pcords, subid) if res > 0: return np.linalg.norm(np.array(p1) - np.array(x)) else: return 0.0 return 0.0
def nearest_neighbor(matrix, array, stlpath): reader1 = vtk.vtkSTLReader() reader1.SetFileName(stlpath) reader1.Update() target_polydata = reader1.GetOutput() # ============ create source points ============== print("Creating source points...") sourcePoints = vtk.vtkPoints() sourceVertices = vtk.vtkCellArray() for i in range(array.shape[0]): sp_id = sourcePoints.InsertNextPoint(array[i][0], array[i][1], array[i][2]) sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(sp_id) source = vtk.vtkPolyData() source.SetPoints(sourcePoints) source.SetVerts(sourceVertices) trans = vtk.vtkTransform() trans.SetMatrix(matrix) icpTransformFilter = vtk.vtkTransformPolyDataFilter() icpTransformFilter.SetInputData(source) icpTransformFilter.SetTransform(trans) icpTransformFilter.Update() transformedSource = icpTransformFilter.GetOutput() my_cell_locator = vtk.vtkCellLocator() my_cell_locator.SetDataSet( target_polydata) # reverse.GetOutput() --> vtkPolyData my_cell_locator.BuildLocator() # ============ display transformed points ============== pointCount = array.shape[0] transform_array = np.zeros(shape=(pointCount, 3)) for index in range(pointCount): point = [0, 0, 0] transformedSource.GetPoint(index, point) # print("transformed source point[%s] = [%.2f, %.2f, %.2f]" % (index, point[0], point[1], point[2])) cellId = vtk.reference(0) c = [0.0, 0.0, 0.0] subId = vtk.reference(0) d = vtk.reference(0.0) my_cell_locator.FindClosestPoint(point, c, cellId, subId, d) print("nearest neighbor point[%s] = [%.2f, %.2f, %.2f]" % (index, c[0], c[1], c[2])) transform_array[index] = c return transform_array
def merge(self): merge_points = vtk.vtkMergePoints() merge_points.InitPointInsertion(self.points, self.points.GetBounds()) id = vtk.reference(0) for i in range(self.vertice_number): merge_points.InsertUniquePoint(self.points.GetPoint(i), id) for i in range(self.Count, min(self.Count + self.interval, len(self.vertices))): inserted = merge_points.InsertUniquePoint(self.vertices[i], id) if inserted == 1: self.vertice_number += 1 if self.Count + self.interval < len(self.vertices): self.Count = self.Count + self.interval else: self.Count = len(self.vertices) self.points = merge_points.GetPoints() self.interactor.GetRenderWindow().GetRenderers().GetFirstRenderer( ).RemoveActor(self.actor) self.actor = create_points_actor(self.points) self.interactor.GetRenderWindow().GetRenderers().GetFirstRenderer( ).AddActor(self.actor) self.interactor.GetRenderWindow().Render()
def merge(self): merge_points = vtk.vtkMergePoints() merge_points.InitPointInsertion(self.points, self.points.GetBounds()) id = vtk.reference(0) for i in range(self.vertice_number): merge_points.InsertUniquePoint(self.points.GetPoint(i), id) with open(self.files[self.Count], 'r') as f: for line in f.readlines(): line = str.split(line, ' ') inserted = merge_points.InsertUniquePoint( [float(line[0]), float(line[1]), float(line[2])], id) if inserted == 1: self.vertice_number += 1 self.points = merge_points.GetPoints() self.Count += 1 renderers = self.interactor.GetRenderWindow().GetRenderers() renderers.InitTraversal() points_renderer = renderers.GetNextItem() points_renderer.RemoveActor(self.points_actor) self.points_actor = create_points_actor(points) points_renderer.AddActor(self.points_actor) surface_renderer = renderers.GetNextItem() surface_renderer.RemoveActor(self.surface_actor) self.surface_actor = create_surface_actor(points) surface_renderer.AddActor(self.surface_actor) self.interactor.GetRenderWindow().Render()
def distance_from_point(self,point): """This function returns the distance from any point to the closest node in the tree. Args: point (array): the coordinates of the point to calculate the distance from. Returns: d (float): the distance between point and the closest node in the tree. """ dist = 0.0 vtk_d = vtk.reference(dist) vtk_node = self.vtk_tree.FindClosestPoint( point, vtk_d ) vtk_d = sqrt(vtk_d) #if vtk_d == 0.0: vtk_d = 1.73205080756e+11 # [davep] #d,node=self.tree.query(point) self._logger.debug(" ----------------") self._logger.debug("point %s " % (str(point))) self._logger.debug("vtk d %f node %d" % (vtk_d, vtk_node)) #self._logger.debug("sci d %f node %d" % (d, node)) d = vtk_d node = vtk_node # distance=pool.map(lambda a: np.linalg.norm(a-point),self.nodes.values()) return d
def AssignLabelToRoots(root_canal, surf, label_name): label_array = surf.GetPointData().GetArray(label_name) RC_BoundingBox = root_canal.GetPoints().GetBounds() x = (RC_BoundingBox[0] + RC_BoundingBox[1]) / 2 y = (RC_BoundingBox[2] + RC_BoundingBox[3]) / 2 z = (RC_BoundingBox[4] + RC_BoundingBox[5]) / 2 surfID = vtk.vtkOctreePointLocator() surfID.SetDataSet(surf) surfID.BuildLocator() labelID = vtk.vtkIntArray() labelID.SetNumberOfComponents(1) labelID.SetNumberOfTuples(root_canal.GetNumberOfPoints()) labelID.SetName(label_name) labelID.Fill(-1) for pid in range(labelID.GetNumberOfTuples()): ID = surfID.FindClosestPoint(x, y, z, vtk.reference(20)) labelID.SetTuple(pid, (int(label_array.GetTuple(ID)[0]), )) root_canal.GetPointData().AddArray(labelID) return root_canal
def main(): line_p0 = (0.0, 0.0, 0.0) line_p1 = (2.0, 0.0, 0.0) p0 = (1.0, 0, 0) p1 = (1.0, 2.0, 0) # line = vtk.vtkSmartPointer() # line.GetPoints().SetPoint(0, lineP0) # line.GetPoints().SetPoint(0, lineP1) dist0 = vtk.vtkLine.DistanceToLine(p0, line_p0, line_p1) print("Dist0:", dist0) dist1 = vtk.vtkLine.DistanceToLine(p1, line_p0, line_p1) print("Dist1:", dist1) t = vtk.reference(0.0) closest = [0.0, 0.0, 0.0] dist0 = vtk.vtkLine.DistanceToLine(p0, line_p0, line_p1, t, closest) print( "Dist0:", dist0, "closest point:", closest[0], closest[1], closest[2]) dist1 = vtk.vtkLine.DistanceToLine(p1, line_p0, line_p1, t, closest) print("Dist1:", dist1, "closest point:", closest[0], closest[1], closest[2])
def testPassByReferenceerence(self): t = vtk.reference(0.0) p0 = (0.5, 0.0, 0.0) n = (1.0, 0.0, 0.0) p1 = (0.0, 0.0, 0.0) p2 = (1.0, 1.0, 1.0) x = [0.0, 0.0, 0.0] vtk.vtkPlane.IntersectWithLine(p1, p2, n, p0, t, x) self.assertEqual(round(t,6), 0.5) self.assertEqual(round(x[0],6), 0.5) self.assertEqual(round(x[1],6), 0.5) self.assertEqual(round(x[2],6), 0.5) vtk.vtkPlane().IntersectWithLine(p1, p2, n, p0, t, x) self.assertEqual(round(t,6), 0.5) self.assertEqual(round(x[0],6), 0.5) self.assertEqual(round(x[1],6), 0.5) self.assertEqual(round(x[2],6), 0.5) t.set(0) p = vtk.vtkPlane() p.SetOrigin(0.5, 0.0, 0.0) p.SetNormal(1.0, 0.0, 0.0) p.IntersectWithLine(p1, p2, t, x) self.assertEqual(round(t,6), 0.5) self.assertEqual(round(x[0],6), 0.5) self.assertEqual(round(x[1],6), 0.5) self.assertEqual(round(x[2],6), 0.5) vtk.vtkPlane.IntersectWithLine(p, p1, p2, t, x) self.assertEqual(round(t,6), 0.5) self.assertEqual(round(x[0],6), 0.5) self.assertEqual(round(x[1],6), 0.5) self.assertEqual(round(x[2],6), 0.5)
def collision(self,point): """This function returns the distance between one point and the closest node in the tree and the index of the closest node using the collision_tree. Args: point (array): the coordinates of the point to calculate the distance from. Returns: collision (tuple): (distance to the closest node, index of the closest node) """ dist = 0.0 vtk_d = vtk.reference(dist) vtk_node = self.vtk_collision_tree.FindClosestPoint( point, vtk_d ) vtk_d = sqrt(vtk_d) if vtk_d == 0.0: vtk_d = float("inf") # [davep] #d,node=self.collision_tree.query(point) self._logger.debug("----------------") self._logger.debug("point %s " % (str(point))) self._logger.debug("vtk d %f node %d" % (vtk_d, vtk_node)) #self._logger.debug("sci d %f node %d" % (d, node)) d = vtk_d node = vtk_node collision=(self.nodes_to_consider_keys[node],d) return collision
def Locate(self, xyz): if self.is_vtu: cid = self.locator.FindCell(xyz, 0.0, self.gc, self.pc, self.wts) if cid < 0: self.xyz = [] return False idl = vtk.vtkIdList() self.dset.GetCellPoints(cid, idl) self.ids = [idl.GetId(i) for i in range(idl.GetNumberOfIds())] #print("LOCATE cid", cid) #print("vids", self.ids) #print('wts', self.wts) else: vox = self.dset.FindAndGetCell(xyz, None, 0, 0.0, vtk.reference(self.sid), self.pc, self.wts) if vox == None: self.xyz = [] return None self.ids = [ vox.GetPointId(i) for i in range(vox.GetNumberOfPoints()) ] self.xyz = xyz return True
def distanceToClosestPointToLine(tree, point1, point2, precision): minDistance = 0 xEntry, yEntry, zEntry = point1[0], point1[1], point1[2] xTarget, yTarget, zTarget = point2[0], point2[1], point2[2] for step in np.arange(0, 1, precision): x = xEntry + step * (xTarget - xEntry) y = yEntry + step * (yTarget - yEntry) z = zEntry + step * (zTarget - zEntry) testPoint = (x, y, z) closestPoint = [0.0, 0.0, 0.0] vector = MathTools.returnVectorFromPoints(point1, point2) minDistance = MathTools.magnitudeVector(vector) ID = 0 cellId = vtk.reference(ID) subId = vtk.reference(ID) closestPointDist2 = vtk.reference(ID) tree.FindClosestPoint(testPoint, closestPoint, cellId, subId, closestPointDist2) if closestPointDist2 < minDistance: minDistance = closestPointDist2 minDistance return minDistance
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 __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 testGeo(): p1 = (2, 0, 0) p2 = (0, 1, 0) t = vtk.reference(1) closest = [0, 0, 0] dtl = vtk.vtkLine.DistanceToLine((0, 0, 0), p1, p2, t, closest) print(dtl, t, closest) print(vtk.vtkMath.Distance2BetweenPoints(p1, p2)) p = [1, 2, 3] project = [0, 0, 0] plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, 0, 1) plane.ProjectPoint(p, project) print('distance:', p, project) m = vtk.vtkMatrix4x4() m.SetElement(0, 0, 1) m.SetElement(0, 1, 0) m.SetElement(0, 2, 0) m.SetElement(0, 3, 0) m.SetElement(1, 0, 0) m.SetElement(1, 1, 2) m.SetElement(1, 2, 0) m.SetElement(1, 3, 0) m.SetElement(2, 0, 0) m.SetElement(2, 1, 0) m.SetElement(2, 2, 3) m.SetElement(2, 3, 0) m.SetElement(3, 0, 0) m.SetElement(3, 1, 0) m.SetElement(3, 2, 0) m.SetElement(3, 3, 4) transform = vtk.vtkTransform() transform.SetMatrix(m) normalProjection = [1.0] * 3 mNorm = transform.TransformFloatPoint(normalProjection) perspectiveTrans = vtk.vtkPerspectiveTransform() perspectiveTrans.SetMatrix(m) perspectiveProjection = [2] * 3 mPersp = perspectiveTrans.TransformFloatPoint(perspectiveProjection) # m.Identity() print('transform:', m.Determinant(), mNorm, mPersp, m.MultiplyPoint((1, 1, 1, 1)))
def Locate(self, xyz): if self.is_vtu: cid = self.locator.FindCell(xyz, 0.0, self.gc, self.pc, self.wts) if cid < 0 or min(self.wts[:4]) < 0 or max(self.wts[:4]) > 1: self.xyz = [] return False idl = vtk.vtkIdList() self.dset.GetCellPoints(cid, idl) self.ids = [idl.GetId(i) for i in range(idl.GetNumberOfIds())] else: vox = self.dset.FindAndGetCell(xyz, None, 0, 0.0, vtk.reference(self.sid), self.pc, self.wts) if vox == None: self.xyz = [] return None self.ids = [vox.GetPointId(i) for i in range(vox.GetNumberOfPoints())] self.xyz = xyz return True
def testMethods(self): """Test overloaded methods""" # single-argument method vtkTransform::SetMatrix() t = vtk.vtkTransform() m = vtk.vtkMatrix4x4() m.SetElement(0, 0, 2) t.SetMatrix(m) self.assertEqual(t.GetMatrix().GetElement(0, 0), 2) t.SetMatrix([0,1,0,0, 1,0,0,0, 0,0,-1,0, 0,0,0,1]) self.assertEqual(t.GetMatrix().GetElement(0, 0), 0) # mixed number of arguments fd = vtk.vtkFieldData() fa = vtk.vtkFloatArray() fa.SetName("Real") ia = vtk.vtkIntArray() ia.SetName("Integer") fd.AddArray(fa) fd.AddArray(ia) a = fd.GetArray("Real") self.assertEqual(id(a), id(fa)) i = vtk.reference(0) a = fd.GetArray("Integer", i) self.assertEqual(id(a), id(ia)) self.assertEqual(i, 1)
def project_landmarks_to_surface(self, mesh_name): pd = self.multi_read_surface(mesh_name) pd, t = self.apply_pre_transformation(pd) clean = vtk.vtkCleanPolyData() clean.SetInputData(pd) # clean.SetInputConnection(pd.GetOutputPort()) clean.Update() locator = vtk.vtkCellLocator() locator.SetDataSet(clean.GetOutput()) locator.SetNumberOfCellsPerBucket(1) locator.BuildLocator() projected_landmarks = np.copy(self.landmarks) n_landmarks = self.landmarks.shape[0] for i in range(n_landmarks): p = self.landmarks[i, :] cell_id = vtk.mutable(0) sub_id = vtk.mutable(0) dist2 = vtk.reference(0) tcp = np.zeros(3) locator.FindClosestPoint(p, tcp, cell_id, sub_id, dist2) # print('Nearest point in distance ', np.sqrt(np.float(dist2))) projected_landmarks[i, :] = tcp # self.landmarks = projected_landmarks self.landmarks = self.transform_landmarks_to_original_space( projected_landmarks, t) del pd del clean del locator
closest.SetNumberOfIds(numProbes) treeClosest = vtk.vtkIdList() treeClosest.SetNumberOfIds(numProbes) staticClosest = vtk.vtkIdList() staticClosest.SetNumberOfIds(numProbes) bspClosest = vtk.vtkIdList() bspClosest.SetNumberOfIds(numProbes) obbClosest = vtk.vtkIdList() obbClosest.SetNumberOfIds(numProbes) dsClosest = vtk.vtkIdList() dsClosest.SetNumberOfIds(numProbes) genCell = vtk.vtkGenericCell() pc = [0,0,0] weights = [0,0,0,0,0,0,0,0,0,0,0,0] subId = vtk.reference(0) # Print initial statistics print("Processing NumCells: {0}".format(numCells)) print("\n") timer = vtk.vtkTimerLog() ############################################################# # Time the creation and building of the static cell locator locator2 = vtk.vtkStaticCellLocator() locator2.SetDataSet(output) locator2.AutomaticOn() locator2.SetNumberOfCellsPerNode(20) locator2.CacheCellBoundsOn() timer.StartTimer()
def rainfall_quad_cast(polydata, dimensions, ray_direction, precision, region_of_interest, update_status): # configure ray direction dimensions = dimensions[::-1] negated = 1 if ray_direction in [ RayDirection.R, RayDirection.A, RayDirection.S ] else -1 castIndex = None if ray_direction is RayDirection.R or ray_direction is RayDirection.L: castIndex = 0 elif ray_direction is RayDirection.A or ray_direction is RayDirection.P: castIndex = 1 elif ray_direction is RayDirection.S or ray_direction is RayDirection.I: castIndex = 2 castVector = [0.0, 0.0, 0.0] castVector[castIndex] = 1.0 * negated castPlaneIndices = [0, 1, 2] castPlaneIndices.remove(castIndex) preciseHorizontalBounds, preciseVerticalBounds = int( float(dimensions[castPlaneIndices[0]]) / float(precision)), int( float(dimensions[castPlaneIndices[1]]) / float(precision)) def build_ray(i, j): start = [None, None, None] start[castIndex] = dimensions[castIndex] * negated start[castPlaneIndices[ 0]] = -dimensions[castPlaneIndices[0]] / 2.0 + i * precision start[castPlaneIndices[ 1]] = -dimensions[castPlaneIndices[1]] / 2.0 + j * precision end = start[:] end[castIndex] = end[castIndex] * -1.0 return start, end # build search tree update_status(text="Building intersection object tree...", progress=41) bspTree = vtk.vtkModifiedBSPTree() bspTree.SetDataSet(polydata) bspTree.BuildLocator() # cast rays update_status(text="Casting " + str(preciseHorizontalBounds * preciseVerticalBounds) + " rays downward...", progress=42) startTime = time.time() points, temporaryHitPoint = vtk.vtkPoints(), [0.0, 0.0, 0.0] hitPointMatrix = [[None for i in xrange(preciseHorizontalBounds)] for j in reversed(xrange(preciseVerticalBounds))] for i in reversed(xrange(preciseVerticalBounds)): for j in xrange(preciseHorizontalBounds): start, end = build_ray(i, j) res = bspTree.IntersectWithLine(start, end, 0, vtk.reference(0), temporaryHitPoint, [0.0, 0.0, 0.0], vtk.reference(0), vtk.reference(0)) if res != 0 and region_of_interest[0] <= temporaryHitPoint[ castIndex] < region_of_interest[1]: temporaryHitPoint[ castIndex] += 0.3 * negated # raised to improve visibility hitPointMatrix[i][j] = HitPoint( points.InsertNextPoint(temporaryHitPoint), temporaryHitPoint[:]) # form cells update_status(text="Forming top layer polygons", progress=64) cells = vtk.vtkCellArray() for i in xrange(len(hitPointMatrix) - 1): for j in xrange(len(hitPointMatrix[i]) - 1): hitPoints = [ hitPointMatrix[i][j], hitPointMatrix[i + 1][j], hitPointMatrix[i + 1][j + 1], hitPointMatrix[i][j + 1] ] if None in hitPoints: continue rawNormal = numpy.linalg.solve( numpy.array([ hitPoints[0].point, hitPoints[1].point, hitPoints[2].point ]), [1, 1, 1]) hitPointMatrix[i][j].normal = rawNormal / numpy.sqrt( numpy.sum(rawNormal**2)) v1, v2 = numpy.array( hitPointMatrix[i][j].normal), numpy.array(castVector) degrees = numpy.degrees( numpy.math.atan2(len(numpy.cross(v1, v2)), numpy.dot(v1, v2))) if degrees < 80: cells.InsertNextCell(4, [p.pid for p in hitPoints]) update_status(text="Finished ray-casting in " + str("%.1f" % (time.time() - startTime)) + "s, found " + str(cells.GetNumberOfCells()) + " cells...", progress=80) # build polydata topLayerPolyData = vtk.vtkPolyData() topLayerPolyData.SetPoints(points) topLayerPolyData.SetPolys(cells) topLayerPolyData.Modified() return topLayerPolyData, [ p for d0 in hitPointMatrix for p in d0 if p is not None ]
def ray_cast_color_thickness(poly_data, hit_point_list, cast_axis, dimensions, mm_of_air_past_bone, update_status, gradient_scale_factor=10.0): # ray direction cast axis index castIndex = BoneThicknessMappingLogic.determine_cast_axis_index( cast_axis) update_status(text="Building static cell locator...", progress=81) cellLocator = vtk.vtkStaticCellLocator() cellLocator.SetDataSet(poly_data) cellLocator.BuildLocator() total = len(hit_point_list) update_status(text="Calculating thickness (may take long, " + str(total) + " rays)...", progress=82) startTime = time.time() def init_array(name): a = vtk.vtkFloatArray() a.SetName(name) return a def interpret_distance(points): firstIn, lastOut = points[0], points[1] if len(points) > 2: for inOutPair in zip(*[iter(points[2:])] * 2): # TODO incorporate cast bounds # if newIn[1][cast_axis] < minBound and newOut[1][cast_axis] < minBound if calculate_distance( lastOut[1], inOutPair[0] [1]) < mm_of_air_past_bone * gradient_scale_factor: lastOut = inOutPair[1] return calculate_distance(firstIn[1], lastOut[1]) else: return calculate_distance(firstIn[1], points[-1][1]) def calculate_distance(point1, point2): d = numpy.linalg.norm( numpy.array((point1[0], point1[1], point1[2])) - numpy.array((point2[0], point2[1], point2[2]))) d = d * gradient_scale_factor return d skullThicknessArray, airCellDistanceArray = init_array( BoneThicknessMappingType.THICKNESS), init_array( BoneThicknessMappingType.AIR_CELL) tol, pCoords, subId = 0.000, [0, 0, 0], vtk.reference(0) pointsOfIntersection, cellsOfIntersection = vtk.vtkPoints( ), vtk.vtkIdList() for i, hitPoint in enumerate(hit_point_list): stretchFactor = dimensions[castIndex] start = [ hitPoint.point[0] + hitPoint.normal[0] * stretchFactor, hitPoint.point[1] + hitPoint.normal[1] * stretchFactor, hitPoint.point[2] + hitPoint.normal[2] * stretchFactor ] end = [ hitPoint.point[0] - hitPoint.normal[0] * stretchFactor, hitPoint.point[1] - hitPoint.normal[1] * stretchFactor, hitPoint.point[2] - hitPoint.normal[2] * stretchFactor ] cellLocator.FindCellsAlongLine(start, end, tol, cellsOfIntersection) distances = [] for cellIndex in range(cellsOfIntersection.GetNumberOfIds()): t = vtk.reference(0.0) p = [0.0, 0.0, 0.0] if poly_data.GetCell(cellsOfIntersection.GetId( cellIndex)).IntersectWithLine( start, end, tol, t, p, pCoords, subId) and 0.0 <= t <= 1.0: distances.append([t, p]) if len(distances) >= 2: distances = sorted(distances, key=lambda kv: kv[0]) skullThicknessArray.InsertTuple1(hitPoint.pid, interpret_distance(distances)) airCellDistanceArray.InsertTuple1( hitPoint.pid, calculate_distance(distances[0][1], distances[1][1])) else: skullThicknessArray.InsertTuple1(hitPoint.pid, 0) airCellDistanceArray.InsertTuple1(hitPoint.pid, 0) # update rays casted status if i % 200 == 0: update_status( text="Calculating thickness (~{0} of {1} rays)".format( i, total), progress=82 + int(round((i * 1.0 / total * 1.0) * 18.0))) update_status(text="Finished thickness calculation in " + str("%.1f" % (time.time() - startTime)) + "s...", progress=100) return skullThicknessArray, airCellDistanceArray
def rainfall_quad_cast(poly_data, seg_bounds, cast_axis, precision, region_of_interest, update_status): update_status(text="Building intersection object tree...", progress=41) bspTree = vtk.vtkModifiedBSPTree() bspTree.SetDataSet(poly_data) bspTree.BuildLocator() update_status(text="Calculating segmentation dimensions...", progress=42) negated = 1 if cast_axis in [ ctk.ctkAxesWidget.Right, ctk.ctkAxesWidget.Anterior, ctk.ctkAxesWidget.Superior ] else -1 castIndex = BoneThicknessMappingLogic.determine_cast_axis_index( cast_axis) castVector = [0.0, 0.0, 0.0] castVector[castIndex] = 1.0 * negated castPlaneIndices = [0, 1, 2] castPlaneIndices.remove(castIndex) update_status(text="Calculating segmentation cast-plane...", progress=43) depthIncrements = [seg_bounds[castIndex], seg_bounds[castIndex + 1]] if cast_axis in [ ctk.ctkAxesWidget.Right, ctk.ctkAxesWidget.Posterior, ctk.ctkAxesWidget.Superior ]: depthIncrements.reverse() horizontalIncrements = [ seg_bounds[castPlaneIndices[0] * 2], seg_bounds[castPlaneIndices[0] * 2 + 1] ] verticalIncrements = [ seg_bounds[castPlaneIndices[1] * 2], seg_bounds[castPlaneIndices[1] * 2 + 1] ] castPlaneIncrements = [ int( abs(horizontalIncrements[0] - horizontalIncrements[1]) / precision), int( abs(verticalIncrements[0] - verticalIncrements[1]) / precision), ] def build_ray(i, j): start = [None, None, None] start[castIndex] = depthIncrements[0] + negated * 100 start[ castPlaneIndices[0]] = horizontalIncrements[0] + i * precision start[castPlaneIndices[1]] = verticalIncrements[0] + j * precision end = start[:] end[castIndex] = depthIncrements[1] - negated * 100 return start, end # cast rays update_status( text="Casting " + str(int(castPlaneIncrements[0] * castPlaneIncrements[1])) + " rays...", progress=44) startTime = time.time() points, temporaryHitPoint = vtk.vtkPoints(), [0.0, 0.0, 0.0] hitPointMatrix = [[None for j in range(castPlaneIncrements[1])] for i in range(castPlaneIncrements[0])] for i in range(len(hitPointMatrix)): for j in range(len(hitPointMatrix[i])): start, end = build_ray(i, j) res = bspTree.IntersectWithLine(start, end, 0, vtk.reference(0), temporaryHitPoint, [0.0, 0.0, 0.0], vtk.reference(0), vtk.reference(0)) # if hit is found, and the top hitpoint is within ROI bounds if res != 0 and region_of_interest[0] <= temporaryHitPoint[ castIndex] < region_of_interest[1]: temporaryHitPoint[ castIndex] += 0.3 * negated # raised to improve visibility hitPointMatrix[i][j] = HitPoint( points.InsertNextPoint(temporaryHitPoint), temporaryHitPoint[:]) # form quads/cells update_status(text="Forming top layer polygons", progress=64) cells = vtk.vtkCellArray() for i in range(len(hitPointMatrix) - 1): # -1 as the end row/col will be taken into account for j in range(len(hitPointMatrix[i]) - 1): hitPoints = [ hitPointMatrix[i][j], hitPointMatrix[i + 1][j], hitPointMatrix[i + 1][j + 1], hitPointMatrix[i][j + 1] ] # check if full quad if None in hitPoints: continue # check if area is not extremely large d1 = numpy.linalg.norm( numpy.array(hitPoints[0].point) - numpy.array(hitPoints[1].point)) d2 = numpy.linalg.norm( numpy.array(hitPoints[0].point) - numpy.array(hitPoints[2].point)) d3 = numpy.linalg.norm( numpy.array(hitPoints[0].point) - numpy.array(hitPoints[3].point)) m = precision * 6 if d1 > m or d2 > m or d3 > m: continue # calculate normals rawNormal = numpy.linalg.solve( numpy.array([ hitPoints[0].point, hitPoints[1].point, hitPoints[2].point ]), [1, 1, 1]) hitPointMatrix[i][j].normal = rawNormal / numpy.sqrt( numpy.sum(rawNormal**2)) # # check if quad is acceptable by normal vs. cast vector # v1, v2 = numpy.array(hitPointMatrix[i][j].normal), numpy.array(castVector) # degrees = numpy.degrees(numpy.math.atan2(numpy.cross(v1, v2).shape[0], numpy.dot(v1, v2))) cells.InsertNextCell(4, [p.pid for p in hitPoints]) update_status(text="Finished ray-casting in " + str("%.1f" % (time.time() - startTime)) + "s, found " + str(cells.GetNumberOfCells()) + " cells...", progress=80) # build poly data topLayerPolyData = vtk.vtkPolyData() topLayerPolyData.SetPoints(points) topLayerPolyData.SetPolys(cells) topLayerPolyData.Modified() return topLayerPolyData, [ p for d0 in hitPointMatrix for p in d0 if p is not None ]
sphere2.Update() # Generate intersection points center = sphere.GetCenter() polyInts = vtk.vtkPolyData() pts = vtk.vtkPoints() spherePts = sphere2.GetOutput().GetPoints() numRays = spherePts.GetNumberOfPoints() pts.SetNumberOfPoints(numRays + 1) polyRays = vtk.vtkPolyData() rayPts = vtk.vtkPoints() rayPts.SetNumberOfPoints(numRays + 1) lines = vtk.vtkCellArray() t = vtk.reference(0.0) subId = vtk.reference(0) cellId = vtk.reference(0) xyz = [0.0,0.0,0.0] xInt = [0.0,0.0,0.0] pc = [0.0,0.0,0.0] pts.SetPoint(0,center) rayPts.SetPoint(0,center) for i in range(0, numRays): spherePts.GetPoint(i,xyz) rayPts.SetPoint(i+1,xyz) cellId = vtk.reference(i); hit = loc.IntersectWithLine(xyz, center, 0.001, t, xInt, pc, subId, cellId) if ( hit == 0 ): print("Missed: {}".format(i))
sphere2.Update() # Generate intersection points center = sphere.GetCenter() polyInts = vtk.vtkPolyData() pts = vtk.vtkPoints() spherePts = sphere2.GetOutput().GetPoints() numRays = spherePts.GetNumberOfPoints() pts.SetNumberOfPoints(numRays + 1) polyRays = vtk.vtkPolyData() rayPts = vtk.vtkPoints() rayPts.SetNumberOfPoints(numRays + 1) lines = vtk.vtkCellArray() t = vtk.reference(0.0) ptId = vtk.reference(0) xyz = [0.0,0.0,0.0] lineInt = [0.0,0.0,0.0] xInt = [0.0,0.0,0.0] pts.SetPoint(0,center) rayPts.SetPoint(0,center) for i in range(0, numRays): spherePts.GetPoint(i,xyz) rayPts.SetPoint(i+1,xyz) cellId = vtk.reference(i); hit = loc.IntersectWithLine(xyz, center, 0.05, t, lineInt, xInt, ptId) if ( hit == 0 ): print("Missed: {}".format(i)) pts.SetPoint(i+1,center)
def testStringReference(self): m = vtk.reference("%s %s!") m %= ("hello", "world") self.assertEqual(m, "hello world!")
def project_new_point(self,point): """This function projects any point to the surface defined by the mesh. Args: point (array): coordinates of the point to project. Returns: projected_point (array): the coordinates of the projected point that lies in the surface. intriangle (int): the index of the triangle where the projected point lies. If the point is outside surface, intriangle=-1. """ #Get the closest point dist = 0.0 d = vtk.reference(dist) node = self.tree.FindClosestPoint( point, d ) #d, node=self.tree.query(point) #print d, node #Get triangles connected to that node triangles=self.node_to_tri[node] #print triangles #Compute the vertex normal as the avergage of the triangle normals. vertex_normal=np.sum(self.normals[triangles],axis=0) #Normalize vertex_normal=vertex_normal/np.linalg.norm(vertex_normal) #Project to the point to the closest vertex plane pre_projected_point=point-vertex_normal*np.dot(point-self.verts[node],vertex_normal) #Calculate the distance from point to plane (Closest point projection) CPP=[] for tri in triangles: CPP.append(np.dot(pre_projected_point-self.verts[self.connectivity[tri,0],:],self.normals[tri,:])) CPP=np.array(CPP) # print 'CPP=',CPP triangles=np.array(triangles) #Sort from closest to furthest order=np.abs(CPP).argsort() # print CPP[order] #Check if point is in triangle intriangle=-1 for o in order: i=triangles[o] # print i projected_point=(pre_projected_point-CPP[o]*self.normals[i,:]) # print projected_point 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],:] w=projected_point-self.verts[self.connectivity[i,0],:] # print 'check ortogonality',np.dot(w,self.normals[i,:]) vxw=np.cross(v,w) vxu=np.cross(v,u) uxw=np.cross(u,w) sign_r=np.dot(vxw,vxu) sign_t=np.dot(uxw,-vxu) # print sign_r,sign_t if sign_r>=0 and sign_t>=0: r=np.linalg.norm(vxw)/np.linalg.norm(vxu) t=np.linalg.norm(uxw)/np.linalg.norm(vxu) # print 'sign ok', r , t if r<=1 and t<=1 and (r+t)<=1.001: # print 'in triangle',i intriangle = i break return projected_point, intriangle
def superpose(self): """Superpose results from multiple output files. Returns: [N x F mat]: superposition results. N = No. of query points, F = No. of field properties. Note: self.queryPoints is a concatenation of [evaluation points, query mesh points]. Superposition is done for both together, but results are separated at the end. """ print("> Superposing {} tires".format(len(self.tireCoordinates))) superposition = np.zeros( (len(self.queryPoints), len(cfg.FEM_FIELDS_3D))) # 0. Parameter placeholder for cell locator 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) # squared distance to the closest point (to be returned) # 1. Superpose all tires at every query point tires = self.tireCoordinates for i in range( len(tires) ): # for one tire, query all points and accumulate in result # mesh data mesh = readVTK(self.outputFileList[i]) pointData = mesh.GetPointData() # cellData = mesh.GetCellData() cellLocator = getCellLocator(mesh) X = vtk_to_numpy(pointData.GetArray('Radial_Distance')) Y = vtk_to_numpy(pointData.GetArray('Depth')) fields = np.array([ vtk_to_numpy(pointData.GetArray(f)) for f in cfg.FEM_FIELDS_2D ]).T # query all points for idx in range(len(self.queryPoints)): pt = self.queryPoints[idx] radial = np.sqrt( (tires[i, 0] - pt[0])**2 + (tires[i, 1] - pt[1])** 2) # radial distance from query point to tire location depth = pt[2] # find cell cellLocator.FindClosestPoint([radial, depth, 0.0], closest_point, gen_cell, cell_id, sub_id, dist2) elementShape = self.elementTypeMap[mesh.GetCellType( cell_id.get())] # get point list of the cell vtk_point_list = vtk.vtkIdList() mesh.GetCellPoints(cell_id.get(), vtk_point_list) point_list = [ vtk_point_list.GetId(i) for i in range(vtk_point_list.GetNumberOfIds()) ] # get shape functions at the query point(s) coord_nodes = np.hstack( (X[point_list].reshape(-1, 1), Y[point_list].reshape( -1, 1))) # global coord of element nodes coord_querys = np.array([radial, depth]).reshape( -1, 2) # global coord of query points shape_function = elementShape.query_shape( coord_nodes, coord_querys) # see class ShapeQ8 # interpolate the fields & accumulate/superpose interpolated = np.squeeze( np.matmul(shape_function, fields[ point_list, :])) # for Q8 & 6 fields, 1x8 * 8x6 = 1x6 # now six fields are cfg.FEM_FIELDS_2D = ['Displacement_Z', 'Displacement_R', 'Stress_R', 'Stress_Theta', 'Stress_Z', 'Stress_Shear'] # decompose radial displacement and stress into plane X-Y # projection cos(t) = a * b / (|a||b|) where |a|=|b|=1, normalized disp_R, stress_R = interpolated[1], interpolated[2] radial_vec = pt[:-1] - tires[i] # vector if np.linalg.norm(radial_vec) == 0: # if the query point is exactly AT any tire location, radial_vec is (0,0) disp_X = disp_R disp_Y = disp_R disp_Z = interpolated[0] stress_X = stress_R stress_Y = stress_R stress_Z = interpolated[4] else: radial_vec = radial_vec / np.linalg.norm( radial_vec) # normalization disp_X = np.dot(radial_vec, np.array([1, 0])) * disp_R disp_Y = np.dot(radial_vec, np.array([0, 1])) * disp_R disp_Z = interpolated[0] stress_X = np.dot(radial_vec, np.array([1, 0])) * stress_R stress_Y = np.dot(radial_vec, np.array([0, 1])) * stress_R stress_Z = interpolated[4] # accumulate results superposition[idx, :] += np.array( [disp_X, disp_Y, disp_Z, stress_X, stress_Y, stress_Z]) # 2. Separate evaluation point results from mesh points results self.results_eval, self.results_grid = np.split( superposition, [len(self.evalPoints) * len(cfg.DEPTH_COORDS)]) self.results_eval = self.results_eval.reshape( len(self.evalPoints), len(cfg.DEPTH_COORDS), len(cfg.FEM_FIELDS_3D)) # P x D x 6 for p in range(len(self.results_eval)): print("Evaluation point {} ({},{}):".format( p, self.evalPoints[p, 0], self.evalPoints[p, 1])) print(self.results_eval[p][:, 2])
staticClosest.SetId(i, staticLocator.FindClosestPoint(probePoints.GetPoint(i))) staticTimer.StopTimer() staticOpTime = staticTimer.GetElapsedTime() print(" Static Closest point probing: {0}".format(staticOpTime)) print(" Divisions: {0}".format( staticLocator.GetDivisions() )) # Poke other methods before deleting static locator class staticClosestN = vtk.vtkIdList() staticLocator.FindClosestNPoints(10, probePoints.GetPoint(0), staticClosestN) # Intersect with line # Out of plane line intersecction a0 = [0.5, 0.5, 1] a1 = [0.5, 0.5, -1] tol = 0.001 t = vtk.reference(0.0) lineX = [0.0,0.0,0.0] ptX = [0.0,0.0,0.0] ptId = vtk.reference(-100) staticLocator.IntersectWithLine(a0,a1,tol,t,lineX,ptX,ptId) print(" Out of plane line intersection: PtId {0}".format(ptId)) # In plane line intersection a0 = [-1.5, 0.5, 0] a1 = [ 1.5, 0.5, 0] tol = 0.001 t = vtk.reference(0.0) lineX = [0.0,0.0,0.0] ptX = [0.0,0.0,0.0] ptId = vtk.reference(-100) staticLocator.IntersectWithLine(a0,a1,tol,t,lineX,ptX,ptId)
# 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() # Now visualize the locator
def testIntReference(self): m = vtk.reference(3) n = vtk.reference(4) m |= n self.assertEqual(m, 7.0) self.assertEqual(str(m), str(m.get()))
def testTupleReference(self): m = vtk.reference((0,)) self.assertEqual(m, (0,)) self.assertEqual(len(m), 1) self.assertEqual(m[0], 0)