【发布时间】:2018-11-09 02:39:25
【问题描述】:
好吧,我正在尝试使用 networkx 为图形创建 matplotlib 动画,但在尝试读取包含节点序列的矩阵时遇到了困难,该节点表示要遵循的路径,并且在每行的末尾都有该路径的总权重。所以它看起来像这样:
[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)] 使用那条线的重量并测试它是否最短。
- 在图表中显示路径,然后返回并立即使用第 2 行尝试。
- 重复。
这是我目前的代码:
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()
【问题讨论】:
标签: python numpy matplotlib matrix networkx