如何在给定点列表的情况下制作 networkX 网格并添加边权重?

How to make a networkX grid given a list of points and add edge weights?

我有一个值从 0 到 1 的点列表 (x, y)

def generate_points(n):
    """Generates n points whose values are in the range (0, 1).

    Args:
        n (int): number of points to generate
    """
    x = [random.uniform(0, 1) for r in range(n)]
    y = [random.uniform(0, 1) for r in range(n)]
    return list(itertools.product(x, y))

我正在尝试使用 NetworkX 生成这些点的二维网格,并将边权重添加到图中,其中从一个节点到其邻居的权重只是欧氏距离。

虽然我不确定该怎么做:我不太确定如何将我的点列表拆分为 nx.generators.lattice.grid_2d_graph 所需的 mn ,也不知道如何更新每个边的权重。当我尝试

G = nx.generators.lattice.grid_2d_graph([(0,1), (0, 2)], [(1, 1), (1, 2)])

每次生成的图都不一样,连节点都一样

IIUC 你想要这样的东西吗?

#make grid graph
G=nx.generators.lattice.grid_2d_graph(10,10)

# from node names, compute positions with random offset
positions = {(x,y):(1*x+np.random.uniform(0,0.2),1*y+np.random.uniform(0,0.2)) for (x,y) in G.nodes()}

# compute weights using euclidean distance
weights = [np.linalg.norm(np.array(positions[x])-np.array(positions[y])) for (x,y) in G.edges()]    
    
nx.draw_networkx_nodes(G, pos=positions)
nx.draw_networkx_edges(G, pos=positions, width=weights)