繁体   English   中英

Python中生成特定的邻接矩阵

[英]Generating a specific adjacency matrix in Python

我有一个带有节点和顶点的网络以及以下编号方案。 我想为节点0,1生成邻接矩阵A ,如下所示。 我尝试使用networkx 我介绍了当前和预期的输出。

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

当前output是

在此处输入图像描述

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

预期的 output 是

在此处输入图像描述

您需要节点及其边缘之间的邻接矩阵,但您正在使用的 function 查找相邻节点。

为了构建 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

编辑:概括连接搜索。

您可以使用嵌套列表在 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