Reputation: 630
I have to create a lattice graph of dimensions mxn.
In networkx I would do the following:
N = 5
M = 4
G = nx.generators.lattice.grid_2d_graph(N,M, periodic=True)
and I would expect a networkx.graph object as a result.
The problem is that, if I call for instance
G.nodes
It does not print the list of nodes as a vector. For instance, if I, instead of using grid_2d_graph, would have used:
G = nx.erdos_renyi_graph(int(N),0.3)
print G.nodes
I would have got a list of numbers
[0,1,2,3,4...,N]
In case of the lattice graph instead I got:
[(0, 1), (1, 2), (3, 2), (0, 0), (3, 3), (3, 0), (3, 1), (2, 1), (0, 2), (2, 0), (1, 3), (2, 3), (4, 3), (2, 2), (1, 0), (4, 2), (0, 3), (4, 1), (1, 1), (4, 0)]
which is like a Matrix.
I would like to get a vector of nodes (as in the other case) and the adjacency matrix of this graph. What can I do?
Upvotes: 0
Views: 1283
Reputation: 23887
It is a list of nodes, you just don't recognize it because the names aren't integers. For the 2d lattice, the nodes are named by their coordinate. So (0,1)
is a node.
Try it:
import networkx as nx
N = 5
M = 4
G = nx.generators.lattice.grid_2d_graph(N,M, periodic=True)
list(G.neighbors((0,10)))
> [(1, 1), (0, 0), (0, 2), (4, 1)]
G.degree((0,1))
> 4
[note, it appears you're using networkx version 1.11 or earlier. In 2.x, G.nodes
is a "NodeView" rather than a list. If you upgrade, you can convert the "NodeView" into a list using list(G.nodes)
, like what I did with G.neighbors
(also not a list in newer networkx versions)].
If you don't want the nodes to be tuples, it is possible to relabel them using nx.relabel_nodes
. Let me know if you'd like help with that.
Upvotes: 0