Search code examples
pythonnumpymatrixgraphnetworkx

How to make a graph from the produced in python


I have this code, it produces a random matrix of 1s and 0s. I want to create a graph from this matrix where the 1s in the matrix represent a node and each node has a maximum of 3 edges. How can i implement this, please help?

import numpy as np
from random import sample

N = int(input("Enter the number of nodes:"))
my_matrix = np.zeros((N,N), dtype='int8')

Solution

  • If you matrix is just random, probably, you don't need it. Instead, you can create graph from list of edges

    import networkx as nx
    from random import sample
    import numpy as np
    from numpy.random import randint
    
    
    n = 7  # number of nodes in graph
    max_connections = int(input("Enter max connections per node:"))  # input: 3
    
    nodes = np.arange(n)
    # create graph based on list of edges [(0, 1), (0, 4), ...]
    gr = nx.Graph([
        #     for each node      select <= 'max_connections' nodes as connections
        (i, j) for i in range(n) for j in sample(nodes[nodes != i].tolist(), randint(1, max_connections+1))
    ])
    
    # check number of connections
    for n in gr.nodes():
        nei = list(gr.neighbors(n))
        while len(nei) > max_connections:
            gr.remove_edge(n, random.choice(nei))
            nei = list(gr.neighbors(n))
    
    nx.draw_networkx(gr, with_labels=True, node_color='#7d99f5')
    

    Graph: enter image description here

    And you can get adjacency matrix using nx.adjacency_matrix()

    nx.adjacency_matrix(gr, nodelist=sorted(gr.nodes())).todense()
    
    matrix([[0, 1, 1, 0, 1, 0, 0],
            [1, 0, 0, 0, 0, 1, 1],
            [1, 0, 0, 1, 0, 1, 0],
            [0, 0, 1, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 1, 1],
            [0, 1, 1, 0, 1, 0, 0],
            [0, 1, 0, 1, 1, 0, 0]])