使用 Delaunay 三角剖分创建 networkx 图

Creating networkx graph using Delaunay Triangulation

我有一个 Delaunay 三角剖分 (DT) (scipy),如下所示:

# Take first 50 rows with 3 attributes to create a DT-
d = data.loc[:50, ['aid', 'x', 'y']].values
dt = Delaunay(points = d) 

# List of triangles in the DT-
dt.simplices                                       
'''
array([[1, 3, 4, 0],
       [1, 2, 3, 0],
       [1, 2, 3, 4]], dtype=int32)
'''

现在,我想使用 'networkx' 包创建一个图,并添加使用上面的 DT 找到的节点和边。

# Create an empty graph with no nodes and no edges.
G = nx.Graph()

我提出的将 DT 单纯形中的唯一节点添加到 'G' 中的代码是-

# Python3 list to contain nodes
nodes = []

for simplex in data_time_delaunay[1].simplices.tolist():
    for nde in simplex:
        if nde in nodes:
            continue
        else:
            nodes.append(nde)

nodes
# [1, 3, 4, 0, 2]

# Add nodes to graph-
G.add_nodes_from(nodes)

如何使用 'dt.simplices' 向 'G' 添加边?例如,第一个三角形是 [1, 3, 4, 0] 并且在 nodes/vertices 1, 3, 4 和 0 之间。我如何找出哪些节点相互连接然后将它们添加为边缘 'G'?

另外,有没有更好的方法来添加节点到'G'?

我正在使用 Python 3.8.

谢谢!

您可以将数组中的行添加为 paths。一条路径只包含一系列边,因此路径 1,2,3 转换为边列表 (1,2),(2,3)。 所以遍历行并使用 nx.add_path:

simplices = np.array([[1, 3, 4, 0],
                      [1, 2, 3, 0],
                      [1, 2, 3, 4]])

G = nx.Graph()
for path in simplices:
    nx.add_path(G, path)

nx.draw(G, with_labels=True, node_size=500, node_color='lightgreen')