将Numpy数组转换为单调图(networkx)

时间:2017-04-03 16:47:07

标签: python numpy networkx

我有一个简单的1和0数组,我想使用NetworkX将此数组转换为图形,但具有以下条件:

  • monotone
  • 定向
  • 加权图表(通过/不通过区域)
  • 从左下角开始,然后正常工作

有一个名为mongoClient.connect(databaseServerUrl, function(err, db) { const query = { $or: req.body.product.map(Product => ({ Product })) }; db.collection('Tests').find(query).toArray((err, docs) => { // ...handle `err` here... res.send(docs); db.close(); }); });

的内置函数

请参阅this

目标是获取此图并显示我可以从矩阵的左下角(想想栅格数据集)到达右上角而不向后或向下移动。

示例数组:

from_numpy_matrix

array = [[0,0,1,0,0], [1,0,0,1,0], [1,0,1,1,0], [0,0,1,1,0]] myarray = np.array(array)

1 个答案:

答案 0 :(得分:2)

这很有趣。

from_numpy_matrix没有帮助,因为没有从迷宫到邻接矩阵的简单转换。相反,更容易迭代允许的位置(即“不是墙”)并检查在允许的方向上是否存在允许的位置(向上,向右,对角线向右)。

import numpy as np
import matplotlib.pyplot as plt
import networkx as nx

def maze_to_graph(is_wall, allowed_steps):
    """
    Arguments:
    ----------
    is_wall       -- 2D boolean array marking the position of walls in the maze
    allowed_steps -- list of allowed steps; e.g. [(0, 1), (1, 1)] signifies that
                     from coming from tile (i, j) only tiles (i, j+1) and (i+1, j+1)
                     are reachable (iff there is no wall)

    Returns:
    --------
    g             -- networkx.DiGraph() instance
    pos2idx       -- dict mapping (i, j) position to node idx (for testing if path exists)
    idx2pos       -- dict mapping node idx to (i, j) position (for plotting)
    """

    # map array indices to node indices and vice versa
    node_idx = range(np.sum(~is_wall))
    node_pos = zip(*np.where(~is_wall))
    pos2idx = dict(zip(node_pos, node_idx))

    # create graph
    g = nx.DiGraph()
    for (i, j) in node_pos:
        for (delta_i, delta_j) in allowed_steps: # try to step in all allowed directions
            if (i+delta_i, j+delta_j) in pos2idx: # i.e. target node also exists
                g.add_edge(pos2idx[(i,j)], pos2idx[(i+delta_i, j+delta_j)])

    idx2pos = dict(zip(node_idx, node_pos))

    return g, idx2pos, pos2idx

def test():
    arr = np.array([[0,0,1,0,0],
                    [1,0,0,1,0],
                    [1,0,1,1,0],
                    [0,0,1,1,0]]).astype(np.bool)

    steps = [(0, 1),  # right
             (-1, 0), # up
             (-1, 1)] # diagonal up-right

    g, idx2pos, pos2idx = maze_to_graph(arr, steps)

    nx.draw(g, pos=idx2pos, node_size=1200, node_color='w', labels=idx2pos)

    start = (3, 0)
    stop = (0, 4)
    print "Has path: ", nx.has_path(g, pos2idx[start], pos2idx[stop])

    return

enter image description here