简体   繁体   English

Python中生成特定的邻接矩阵

[英]Generating a specific adjacency matrix in Python

I have a.network with nodes and vertices and the following numbering scheme.我有一个带有节点和顶点的网络以及以下编号方案。 I want to generate an adjacency matrix A for the nodes 0,1 as shown below.我想为节点0,1生成邻接矩阵A ,如下所示。 I tried to do using networkx .我尝试使用networkx I present the current and expected outputs.我介绍了当前和预期的输出。

import networkx as nx
N=2
def pos():
    x, y = 1, N + 3 - 1
    for _ in range(N):
        yield (x, y)
        y -= (x + 2) // (N+1 )
        x = (x + 2) % (N+1)

G = nx.Graph()
it_pos = pos()
for u in range(N):
    G.add_node(u+1, pos=next(it_pos))
    if u % (2 * N) < N:
        for v in (u - 2 * N, u - N, u - N):
            if G.has_node(v + 1):
                G.add_edge(u + 2, v + 2)
    elif u % (2 * N) == N:
        G.add_edge(u + 1, u - N + 1)
    elif u % (2 * N + 1) < 2 * N:
        for v in (u - 1, u - N, u - N):
            G.add_edge(u + 1, v + 1)
    else:
        for v in (u - 1, u - N - 1):
            G.add_edge(u + 1, v + 1)

nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, font_weight='bold')  
Nodes=len(G.nodes)
A=nx.adjacency_matrix(G).todense()

The current output is当前output是

在此处输入图像描述

A=matrix([[0., 0.],
        [0., 0.]])

The expected output is预期的 output 是

在此处输入图像描述

You want the adjacency matrix between node and its edges, but the function you are using looks for neighbouring nodes.您需要节点及其边缘之间的邻接矩阵,但您正在使用的 function 查找相邻节点。

In order to build your.network and get your matrix, you could do the following:为了构建 your.network 并获取矩阵,您可以执行以下操作:

import networkx as nx
import numpy as np
import pandas as pd

# build the network with relevant edges
G = nx.Graph()
points = {
    0: (1, 1), 1: (2, 1),
    'a':(1, 2), 'b':(2, 2),
    'c':(0, 1), 'd':(3, 1),
    'e':(1, 0), 'f':(2, 0)
}
for key, pos in points.items():
    G.add_node(key, pos=pos)
G.add_edge('a', 0, name=0)
G.add_edge('b', 1, name=1)
G.add_edge('c', 0, name=2)
G.add_edge(0, 1, name=3)
G.add_edge(1, 'd', name=4)
G.add_edge(0, 'e', name=5)
G.add_edge(1, 'f', name=6)

# find connected edges to nodes 0 and 1
my_nodes = [0, 1]  # could be more here
edges = {
    node: [G.get_edge_data(*edge)['name'] for edge in G.edges(node)]
    for node in my_nodes
}
# build matirx
mat = np.zeros((len(my_nodes), 7), dtype=np.uint8)
for i, node in enumerate(my_nodes)):
    mat[i, edges[node]] = 1
    mat[i, edges[node]] = 1
A = pd.DataFrame(mat)
A

Edit: generalize the connection search.编辑:概括连接搜索。

You can implement the matrix in Python using a nested list:您可以使用嵌套列表在 Python 中实现矩阵:

A = [[1, 0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0, 1]]

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

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