我正在尝试使用matplotlib
为图形创建networkx
动画,但在尝试读取包含一系列节点的矩阵时遇到困难,这表示要遵循的路径,并在每一行的末尾,它具有该路径的总重量。所以它看起来像这样:
[node1, node2, node3, ..., node9, weight1 ]
[node1, node3, node2, ..., node9, weight2 ](the nodes 1 to 9 are permuted and
. . . then drawed in pairs)
. . .
. . .
[node9, node8, node4, ..., node1, weight(9!)]
我是Python的新手,我习惯于在C中工作,所以我想做的更像是:
检查矩阵中的第一行,读取节点并将其保存在元组数组中:
nPath=[(node1,node2),(node2,node3),(node3,node4),...,(node8,node9),(node9,node1)]
使用该行的权重并测试它是否为最短行。
到目前为止,这是我的代码:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import itertools as it
import matplotlib.animation as animation
#Contains the combinations of each pair of nodes and their weight.
with open("pair_weight.txt","r") as file:
W_edges = np.loadtxt(file, dtype=int, delimiter=' ')
G = nx.Graph()
G.add_weighted_edges_from(W_edges)
fig, ax = plt.subplots(figsize=(6,4))
#Contains the total waight of each path 1 to 9.
with open("Path_Weights.txt","r") as file:
W_paths = np.loadtxt(file, dtype=int)
#contains all 9! permutations of the nodes
with open("Permutations.txt","r") as file:
nPath = np.loadtxt(file, dtype=int, delimiter=' ')
nPaths = np.c_[nPath, W_paths]
pos = nx.kamada_kawai_layout(G)
labels = {}
for node in G.nodes():
if node in pos:
labels[node] = node
npaths = []
def update_path(num):
for i in range(0,8):
if i==8: #This is were i'm trying to do it like in c.
npaths.append[(nPaths.item((num, i))),(nPaths.item((num,0)))]
npaths.append[(nPaths.item((num, i))),(nPaths.item((num,i+1)))]
nx.draw_networkx_edges(G, pos, width=2, edgelist=npaths, edge_color='r')
nx.draw_networkx_nodes(G, pos, node_size=900, node_color='skyblue', node_shape='o', alpha=0.7, edgecolor='deepskyblue')
nx.draw_networkx_labels(G, pos, labels, font_size=14, font_color='k', alpha=5)
nx.draw_networkx_edges(G, pos, edge_color='gray')
ani = animation.FuncAnimation(fig, update_path, frames=6, interval=1000, repeat=True)
plt.show()
答案 0 :(得分:0)
如果nPath
(不包含s
)是包含节点路径的矩阵,请假设(P, N)
P
个N
个节点的路径,你可以创建一个数组,比如说nPathEdges
,形状为(P, N, 2)
,其中nPathEdges[i, j]
包含{{1}的j
- 边(表示为[node1, node2]
)i
- 路径,像这样:
nPathEdges = np.stack([nPath, np.roll(nPath, -1, axis=1)], axis=2)
然后你可以迭代这个矩阵和权重,如:
w_min = np.inf
for edges, w in zip(nPathEdges, W_paths):
# You can have it as a list of tuples like this,
# although as far as I can tell NetworkX should work fine with a NumPy array too
edges = [tuple(e) for e in edges]
nx.draw_networkx_edges(G, pos, width=2, edgelist=npaths, edge_color='r')
if w < w_min:
w_min = w
# Do something for minimum weight...