简体   繁体   English

从 Python 中的掩码网格制作图形

[英]Make graph from mask grid in Python

I've got a 'mask' numpy 2D array with ones and zeros, eg我有一个带有 1 和 0 的“掩码”numpy 二维数组,例如

array([[0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0],
       [0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
       [1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1],
       [0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0],
       [1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1],
       [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0],
       [0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0],
       [0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0],
       [1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1],
       [0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0],
       [1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1],
       [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0]])

My task is to convert this matrix into a connected graph with the zeros as nodes connected with their direct neighbors, that is, for example, the graph in this case would contain several graphs (not connected with each other), like:我的任务是将此矩阵转换为一个连接图,其中零作为与其直接邻居连接的节点,也就是说,例如,在这种情况下,该图将包含多个图(彼此不连接),例如:

*         *---*
|
*---*            *
|                |
*                *
etc...

So basically each zero here is a node and edges are paths to other zeros which are their direct neighbors (on the top, bottom, right or left).所以基本上这里的每个零都是一个节点,边是到其他零的路径,这些零是它们的直接邻居(在顶部、底部、右侧或左侧)。 Direction of edges does matter!边缘的方向很重要! Edges are either vertical or horizontal, as in the input matrix.边缘是垂直的或水平的,就像在输入矩阵中一样。 My ultimate goal is to use the resulting graph / collection of graphs to perform a number of tests:我的最终目标是使用生成的图形/图形集合来执行许多测试:

  • connectivity of all nodes所有节点的连通性
  • max and min length of edges (in each orientation)边的最大和最小长度(在每个方向上)
  • etc.等等

I've found out the excellent networkx library which seems to be able to generate graphs from arrays, but the reference says it can only treat nd-arrays or pandas dataframes as 'adjacency' matrices and not as direct graph representations as in my case.我发现了出色的networkx库,它似乎能够从 arrays 生成图形,但参考资料说它只能将 nd-arrays 或 pandas 数据帧视为“邻接”矩阵,而不是像我的情况那样作为直接图形表示。

You can convert your representation of the graph to an adjacency matrix representation by finding the indices of all the zeros and calculating the distance between them.您可以通过查找所有零的索引并计算它们之间的距离,将您的图形表示转换为邻接矩阵表示。 After the transformation, you can pass the graph to networkx's functions.转换后,您可以将图形传递给 networkx 的函数。 Here is an example of a code that implements this idea and uses it on a small portion of your array:下面是一个实现这个想法并在数组的一小部分上使用它的代码示例: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM