【问题标题】:How to save each line of a np.matrix to a 9 pair touple array?如何将 np.matrix 的每一行保存到 9 对元组数组中?
【发布时间】: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 工作,所以我想做的更像是:

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

【问题讨论】:

    标签: python numpy matplotlib matrix networkx


    【解决方案1】:

    如果nPath(没有s)是带有节点路径的矩阵,假设形状为(P, N)P 的路径N 节点),您可以创建一个数组,例如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...
    

    【讨论】:

    • 谢谢!它可以满足我的需要,但是当我尝试对其进行动画处理时遇到一个小问题,我需要使用 update_path(num) 为每一行设置动画,因为我理解 num 将迭代动画并且如果我设置 frames= 1 然后 num 将迭代超过 1,我正确吗?以及每次调用 num 时如何只访问第一行?
    • @Jorge 没错,如果您想选择num-th 路径,那么您将使用edges = nPathEdges[num]w = W_paths[num] 而不是for 循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2019-08-31
    • 2021-04-29
    • 2015-05-20
    相关资源
    最近更新 更多