Search code examples
pythonpython-3.xgraphnetworkxminimum-spanning-tree

How to get Minimum Spanning Tree Matrix in python


Initially, i have 2d array. By using this array i have created a graph with weight on its edges. Now i am trying to use this Graph to make Minimum Spanning Tree matrix but i cant make it as desire. I am using the following code to make graph.

 G = nx.from_numpy_matrix(ED_Matrix, create_using=nx.DiGraph)
 layout = nx.spring_layout(G)
 sizes = len(ED_Matrix)
 nx.draw(G, layout, with_labels=True, node_size=sizes)
 labels = nx.get_edge_attributes(G, "weight")
 output = nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels)
 plt.show()

And its gives the output like this enter image description here

Now i am using MST code, to get the its MST matrix but its gives error like this.

 from scipy.sparse import csr_matrix
 from scipy.sparse.csgraph import minimum_spanning_tree
 Tcsr = minimum_spanning_tree(G)
 Tcsr.toarray().astype(int)

enter image description here


Solution

  • Taking into account example from docs of scipy, it should be constructed from adjacency matrix of G, not from G.

    You might want to replace G with nx.adjacency_matrix(G) or csr_matrix(nx.adjacency_matrix(G)) or ED_Matrix itself in calculation (assignment) of Tcsr:

    Tcsr = minimum_spanning_tree(nx.adjacency_matrix(G)) #or
    Tcsr = minimum_spanning_tree(csr_matrix(nx.adjacency_matrix(G))) #or
    Tcsr = minimum_spanning_tree(ED_Matrix)
    

    Tcsr is a sparse matrix which is later converted to numpy array.