Aru*_*run 6 delaunay scipy python-3.x scipy-spatial
我正在阅读有关Delaunay (scipy)的内容的文章并发现了代码:
\nimport numpy as np\npoints = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])\n\nfrom scipy.spatial import Delaunay\ntri = Delaunay(points)\n\nimport matplotlib.pyplot as plt\nplt.triplot(points[:,0], points[:,1], tri.simplices.copy())\nplt.plot(points[:,0], points[:,1], \'o\')\nplt.show()\nRun Code Online (Sandbox Code Playgroud)\n据我了解,单纯形是三角形到更高维度的推广。
\n我不明白下面代码的含义,希望帮助理解它:
\n# Point indices and coordinates for the two triangles forming the triangulation:\n\ntri.simplices\narray([[3, 2, 0],\n [3, 1, 0]], dtype=int32)\n\npoints[tri.simplices]\narray([[[ 1. , 1. ],\n [ 1. , 0. ],\n [ 0. , 0. ]],\n [[ 1. , 1. ],\n [ 0. , 1.1],\n [ 0. , 0. ]]])\n\nTriangle 0 is the only neighbor of triangle 1, and it\xe2\x80\x99s opposite to vertex 1 of triangle 1:\n\n\ntri.neighbors[1]\n# array([-1, 0, -1], dtype=int32)\n\npoints[tri.simplices[1,1]]\narray([ 0. , 1.1])\nRun Code Online (Sandbox Code Playgroud)\n谢谢!
\n此代码从包含两个三角形的四个顶点创建 Delaunay 三角剖分。三角剖分看起来像这样:
代码首先在数组中定义四个顶点:
points = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])
Run Code Online (Sandbox Code Playgroud)
接下来,scipy 为这些点构建 Delaunay 三角剖分:
from scipy.spatial import Delaunay
tri = Delaunay(points)
Run Code Online (Sandbox Code Playgroud)
现在,tri.simplices 包含 Delaunay 三角剖分中的三角形列表(在此 2D 情况下)。每个三角形都表示为三个整数:每个值表示原始点数组中的一个索引。
tri.simplices
array([[3, 2, 0],
[3, 1, 0]], dtype=int32)
Run Code Online (Sandbox Code Playgroud)
因此 [3,2,0] 是顶点 3 (1,1)、顶点 2 (1,0) 和顶点 0 (0,0) 之间的三角形。下一个代码连接点和 tri 数据结构来计算每个三角形顶点的坐标,消除间接:
points[tri.simplices]
array([[[ 1. , 1. ],
[ 1. , 0. ],
[ 0. , 0. ]],
[[ 1. , 1. ],
[ 0. , 1.1],
[ 0. , 0. ]]])
Run Code Online (Sandbox Code Playgroud)
tri.neighbors 数组包含有关哪些三角形彼此相邻的信息。
tri.neighbors[1]
# array([-1, 0, -1], dtype=int32)
Run Code Online (Sandbox Code Playgroud)
回想一下三角形 1(位置 1 处的 tri.simplices)具有顶点 [3,1,0]。三角形 0 与顶点 1 相对的三角形 1 相邻,这就是为什么结果在第二个元素中值为 0(对应于 [3,1,0] 中的 1)。没有与顶点 3 相对的三角形(即,沿着顶点 0 和 1 之间的边连接)或与顶点 0 相对的三角形,因此在这些位置中,neighbors 数组包含 -1。
最后就是这段代码了。
points[tri.simplices[1,1]]
array([ 0. , 1.1])
Run Code Online (Sandbox Code Playgroud)
回想一下上面的 tri.simplices 数据结构,单纯形 1 中的位置 1 包含一个值 1(即 [3,1,0]。这一行只是查找顶点 1 的坐标。
最后要注意的是,返回的单纯形中的顶点顺序不需要与此原始示例相匹配,并且可能因版本而异。这是最近的一次运行,与下面评论中的观察相匹配,该观察与原始顶点顺序(原始文档中提供)不一致: