Reputation: 63
I want to define an objective function for the max-cut problem on graphs. I use the following expression, 0.5*sum([w[i,j]*(1-spin[i]*spin[j]) for i,j in G.edges])
where G
is a networkx graph, w
is the numpy matrix generated from that graph (connectivity matrix), and spin
is an array with entries -1 or 1 to denote which side of the partition the node is in.
All good I thought, but it turns out that the labelling of the edges is not consistent with the labelling of the nodes, see code below. For example in the graph G1, edge weight w[1,5]
is 0 even though the edge (1,5) is in the graph. Any recommendations on how to fix this?
Cheers
import networkx as nx
G1 = nx.random_regular_graph(3,6, seed = 1)
G2 = nx.random_regular_graph(3,6, seed = 1)
# labelling seems not to be conserved when transforming to matrix and back
G2 = nx.to_numpy_matrix(G2)
G2 = nx.from_numpy_matrix(G2)
print(nx.to_numpy_matrix(G1))
print(G1.edges)
print(nx.to_numpy_matrix(G2))
print(G2.edges)
Output
[[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]
[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]
[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]] # matrix of G1
[(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)] # edges of G1
[[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]
[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]
[0. 1. 0. 1. 0. 1.]
[1. 0. 1. 0. 1. 0.]] # matrix of G2
[(0, 1), (0, 3), (0, 5), (1, 2), (1, 4), (2, 3), (2, 5), (3, 4), (4, 5)] # edges of G2
Upvotes: 1
Views: 178
Reputation: 4892
As described in to_numpy_matrix
documentation, the method implicitly uses the ordering of G.nodes()
, if the parameter nodelist
is not used.
Using the following code should fix the ordering
nx.to_numpy_matrix(G, nodelist=sorted(G))
Upvotes: 0