代码之家  ›  专栏  ›  技术社区  ›  ccc

根据节点之间的欧几里德距离指定边权重

  •  2
  • ccc  · 技术社区  · 6 年前

    我正在创建一个包含50个随机创建的节点的完整图。每个节点定义为笛卡尔坐标,如下所示:

    n = 50
    V = []
    V=range(n)
    
    random.seed()
    
    pos = {i:(random.randint(0,500),random.randint(0,500)) for i in V}
    

    我需要指定每个节点之间的欧几里德距离,因为边权重对应于这对节点。

    我已经定义了两个节点之间的欧几里德距离,如下所示:

    points = []
    positions = []
    for i in pos:
        points.append(pos[i])
        positions.append(i)
        positions.append(pos[i])
    
    def distance(points, i, j):
        dx = points[i][0] - points[j][0]
        dy = points[i][1] - points[j][1]
        return math.sqrt(dx*dx + dy*dy)
    

    我尝试将欧几里德距离指定为其权重,如下所示:

    for u in V:
        for v in V:
            weights = distance(points, u,v)
    
    G = nx.complete_graph(n)
    for e in G.edges():
       weights[e] = distance(points, e[0],e[1])
    

    但这将返回以下错误。

        weights[e] = distance(points, e[0],e[1])
    
    TypeError: 'float' object does not support item assignment
    

    有人能给我一个建议吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Joel    6 年前

    你的问题是

    for u in V:
        for v in V:
            weights = distance(points, u,v)
    

    weights 是一个浮点(比较的最后一对的距离)。

    现在你知道了

    for e in G.edges():
        weights[e] = distance(points, e[0],e[1])
    

    您正在分配 e 浮点数第项 重量 成为某样东西。不允许。

    我想你想要的是

    for u,v in G.edges():
        G[u][v]['distance'] = distance(points, u, v)
    

    作为注释,而不是 points 定义后,我将使节点成为笛卡尔坐标的元组。看见 Relabeling Nodes of a graph in networkx

        2
  •  1
  •   user8401743    6 年前

    除了Joel提到的内容之外,下面是有效的代码。

    import random
    import networkx as nx
    import math
    import itertools    
    import matplotlib.pyplot as plt
    n = 50
    V = []
    V=range(n)
    
    random.seed()
    
    pos = {i:(random.randint(0,500),random.randint(0,500)) for i in V}
    points = []
    positions = []
    for i in pos:
        points.append(pos[i])
        positions.append(i)
        positions.append(pos[i])
    
    def distance(points, i, j):
        dx = points[i][0] - points[j][0]
        dy = points[i][1] - points[j][1]
        return math.sqrt(dx*dx + dy*dy)
    
    G=nx.empty_graph(n)
    
    for u in V:
        for v in V:
            wt = distance(points, u,v)
            G.add_edge(u,v,weight = wt)
    
    nx.draw(G,pos)
    edges,weights = zip(*nx.get_edge_attributes(G,'weight').items())
    nx.draw(G, pos, node_color='k', edgelist=edges, edge_color=weights, width=1, edge_cmap=plt.cm.Reds)
    

    Edges colored by edgeweights