AEinstein
AEinstein

Reputation: 153

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. I tried to do using 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

enter image description here

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

The expected output is

enter image description here

Upvotes: 0

Views: 201

Answers (2)

Carlos Horn
Carlos Horn

Reputation: 1293

You want the adjacency matrix between node and its edges, but the function you are using looks for neighbouring nodes.

In order to build your network and get your matrix, you could do the following:

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.

Upvotes: 1

shamnad sherief
shamnad sherief

Reputation: 646

You can implement the matrix in Python using a nested list:

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

Upvotes: 0

Related Questions