我创建了一个包含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
有人可以建议我这样做吗?
答案 0 :(得分:2)
你遇到的问题是
之后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
的{{1}}项。不允许。
我认为你想要的是
weights
作为一个注释,我不是定义for u,v in G.edges():
G[u][v]['distance'] = distance(points, u, v)
,而是让节点成为笛卡尔坐标的元组。见Relabeling Nodes of a graph in networkx
答案 1 :(得分:1)
除了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)