简体   繁体   中英

Creating a network in Python

I am creating a.network by specifying points and edges. However, I want to make this code more generic so that it can handle large number of my_nodes (say 100) and generate a connection matrix. This means that I don't want to enter the points and edges manually cause it will be cumbersome. For every node, there should be 4 edges and the numbering is shown below.

How do I do this? I present the output as well.

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

Numbering is

在此处输入图像描述

The output is

   0  1  2  3  4  5  6
0  1  0  1  1  0  1  0
1  0  1  0  1  1  0  1

Use nx.adjacency_matrix :

# Keep only nodes with degree 4
my_nodes = [node for node, deg in G.degree if deg == 4]

A = pd.DataFrame(nx.adjacency_matrix(G).toarray(), index=G.nodes, columns=G.nodes)
B = A.loc[my_nodes]

Output:

>>> A
   0  1  a  b  c  d  e  f
0  0  1  1  0  1  0  1  0
1  1  0  0  1  0  1  0  1
a  1  0  0  0  0  0  0  0
b  0  1  0  0  0  0  0  0
c  1  0  0  0  0  0  0  0
d  0  1  0  0  0  0  0  0
e  1  0  0  0  0  0  0  0
f  0  1  0  0  0  0  0  0

>>> B
   0  1  a  b  c  d  e  f
0  0  1  1  0  1  0  1  0
1  1  0  0  1  0  1  0  1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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