如何将 np.matrix 的每一行保存到 9 对的 touple 数组中?



好吧,我正在尝试使用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语言,所以我试图做的更像是:

  1. 检查矩阵中的第一行,读取节点并将其保存在元组数组中:

    nPath=[(node1,node2),(node2,node3),(node3,node4),...,(node8,node9),(node9,node1)]

  2. 使用该线的粗细并测试它是否最短。

  3. 在图形中显示路径,然后返回并立即尝试使用第 2 行。
  4. 重复。

这是我到目前为止的代码:

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()

如果nPath(不带s(是带有节点路径的矩阵,假设有形状(P, N)(N节点的P路径(,你可以创建一个数组,比如说nPathEdges,形状(P, N, 2)其中nPathEdges[i, j]包含i-th路径的j-th边(表示为[node1, node2](, 喜欢这个:

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...

最新更新