PVGeo.filters.AddCellConnToPoints
用VTK_LINE
和VTK_POLYLINE
把离散的点集联通起来。可以按照点的索引顺序连接也可以按照邻近的距离。按照邻近距离进行连接是最合理恰当的。
"""
Add Cell Connectivity To Points
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example for :class:`PVGeo.filters.AddCellConnToPoints`
This filter will add **linear** cell connectivity between scattered points.
You have the option to add ``VTK_LINE`` or ``VTK_POLYLINE`` connectivity.
``VTK_LINE`` connectivity makes a straight line between the points in order
(either in the order by index or using a nearest neighbor calculation).
The ``VTK_POLYLINE`` adds polyline connectivity between all points as one
spline (either in the order by index or using a nearest neighbor calculation).
"""
import numpy as np
import pyvista
from PVGeo import points_to_poly_data
from PVGeo.filters import AddCellConnToPoints
# 首先,产生一些离散的点
def path1(y):
"""Equation: x = a(y-h)^2 + k"""
a = - 110.0 / 160.0**2
x = a*y**2 + 110.0
idxs = np.argwhere(x>0)
return x[idxs][:,0], y[idxs][:,0]
x, y = path1(np.arange(0.0, 200.0, 25.0))
zo = np.linspace(9.0, 11.0, num=len(y))
coords = np.vstack((x,y,zo)).T
# 打乱点集的顺序
np.random.shuffle(coords)
# Make a VTK data object for the filter to use
vtkPoints = points_to_poly_data(coords)
###############################################################################
# Apply the Filter
# ++++++++++++++++
#
# Now that you have the points generated, lets go ahead and apply
# the **Add Cell Connectivity To Points** filter from
# *Filters->PVGeo: General Filters->Add Cell Connectivity To Points*.
# The output data should look really wacky and incorrectly built like the image
# below; this is good.
line = AddCellConnToPoints().apply(vtkPoints)
p = pyvista.Plotter()
p.add_mesh(line, line_width=5, point_size=10)
p.show()
按照索引顺序连接,看起来杂乱无章。
# Use the filter: Here is vtkPolyData containing the connected line:
line_o = AddCellConnToPoints(nearest_nbr=True).apply(vtkPoints)
p = pyvista.Plotter()
p.add_mesh(line_o, line_width=5, point_size=10)
p.show()
按照点集的邻近距离进行连通。
如何寻找最短邻近距离的点:即寻找一个最短的路径,遍历每一个点找出K个最近的点组成一条路径,通过“打擂”的方式找出最短路径。
def _find_min_path(points):
try:
# sklearn's KDTree is faster: use it if available
from sklearn.neighbors import KDTree as Tree
except ImportError:
from scipy.spatial import cKDTree as Tree
_compute_dist = lambda pt0, pt1: np.linalg.norm(pt0-pt1)
ind, min_dist = None, np.inf
tree = Tree(points)
for pt in points:
cur_ind = tree.query([pt], k=len(points))[1].ravel()
dist = 0.
for i in range(len(cur_ind)-1):
dist += _compute_dist(points[cur_ind[i]], points[cur_ind[i+1]])
if dist < min_dist:
ind = cur_ind
min_dist = dist
return ind.ravel()