in src/qubo_community.py [0:0]
def modularity_mx(nx_G):
"""
Create a sparse matrix for the modularity of a graph nx_G
:param nx_G: networkX graph
:return: scipy coo sparse matrix, the modularity matrix for nx_G with weighted edges
"""
# Generate a sparse adjacency matrix using networkx
adj = nx.adjacency_matrix(nx_G, nodelist=sorted(list(nx_G)), weight='weight')
# Create a numpy array for node's degree.
# Here we assumed an undirected graph, so `degrees` refers to both the in-degree and out-degree
sorted_degrees = sorted(nx_G.degree(weight='weight'))
degrees = np.array([degree[1] for degree in sorted_degrees])
m = sum(degrees) / 2
# Calculate the expected number of edges between two nodes for a null model.
# Note we use sparse matrix format here but this degree matrix is a dense one by definition
degrees = np.expand_dims(degrees.squeeze(), axis=0)
degree_mx = sp.csr_matrix(degrees.T).multiply(sp.csr_matrix(degrees)) / (2 * m)
# Create a modularity matrix and convert it into coo sparse matrix format (Torch sparse tensor compatible)
modu_mx_sparse = (sp.csr_matrix(adj) - degree_mx) / (2 * m)
modu_mx_sparse = sp.coo_matrix(modu_mx_sparse)
return modu_mx_sparse