1

I have a csr matrix from which I extracted data, rows, and columns. I want to create a bipartite graph using NetworkX, and I also tried several solutions without success (as an example: Plot bipartite graph using networkx in Python). The reasons why it doesn't work, in my opinion, is a matter of labeling. My two sets and the nodes inside them have no string name.

For example in a 10x10 matrix, the rows/cols indexes represent the name of the nodes of the two sets, while the intersection of these nodes is the weighted link between those nodes.

In my case, then, if I have (0,0)=0.5 it doesn't mean that it is a self-loop; instead, the link with weight 0.5 connects the "node 0" of the first set with the "node 0" of the second one.

import networkx as nx
from networkx.algorithms import bipartite
import matplotlib.pyplot as plt

def function(foo, n_row, n_col):
    n_row=10
    n_col=10

After the creation of the matrix, I obtain my data


    weights = weights.tocsr() 
    wcoo = weights.tocoo()
    m_data = wcoo.data
    m_rows = wcoo.row
    m_cols = wcoo.col

    g = nx.Graph()  

    # TRIAL 1
    g.add_nodes_from(m_cols, bipartite=0)
    g.add_nodes_from(m_rows, bipartite=1)
    bi_m = bipartite.matrix.biadjacency_matrix(g, m_data)
    # TRIAL 2
    g.add_weighted_edges_from(zip(m_cols, m_rows, m_data))


    nx.draw(g, node_size=500)
    plt.show()

I expected a bipartite graph with two sets of 10 nodes per each with a certain amount of weighted links among them (without link among the same set) as a result. I, instead, obtained a classic non-oriented graph with 10 nodes in total.

At the same time, I'd like to optimize as well as I can my code to speed-up the computational time without affecting the readability.

user5431233
  • 61
  • 1
  • 8
  • 1
    Possible duplicate of [Networkx bipartite graphs: nodes of different sets with the same number](https://stackoverflow.com/questions/29150408/networkx-bipartite-graphs-nodes-of-different-sets-with-the-same-number) – Moormanly Aug 06 '19 at 20:55
  • 1
    The problem you are having is due to using `m_cols` for one set of bipartite nodes and `m_rows` for the other set. Since `m_cols` and `m_rows` both take values from `[0, 1, ..., 9]`, [networkx thinks they refer to the same nodes](https://stackoverflow.com/a/29154229/9235855). You will need to uniquify the names of your nodes. – Moormanly Aug 06 '19 at 20:58
  • Thanks to your suggestions I solved by adding: `m_cols_label = ["a" + str(m_c) for m_c in m_cols]` `m_rows_label = ["b" + str(m_r) for m_r in m_rows]` using both my trials without the line: `bi_m = bipartite.matrix.biadjacency_matrix(g, m_data)` However, is not this solution quite expansive in terms of computational time because of the for-loops used ? In your opinion, is there any other way to manage this issue? – user5431233 Aug 28 '19 at 10:13

0 Answers0