I have a list of points (x, y) whose values are from 0 to 1
def generate_points(n):
"""Generates n points whose values are in the range (0, 1).
Args:
n (int): number of points to generate
"""
x = [random.uniform(0, 1) for r in range(n)]
y = [random.uniform(0, 1) for r in range(n)]
return list(itertools.product(x, y))
I’m trying to generate a 2D grid of these points using NetworkX, and also add edge weights to the graph where the weight from one node to its neighbor is simply the Euclidean distance.
I am not sure about how to go about this though: I’m not very sure how to split my list of points into the m and n required for nx.generators.lattice.grid_2d_graph, nor how to update the edge weights for each one. When I try something like
G = nx.generators.lattice.grid_2d_graph([(0,1), (0, 2)], [(1, 1), (1, 2)])
a different graph is generated each time, even the nodes are the same.
Advertisement
Answer
IIUC you want something like this?
#make grid graph
G=nx.generators.lattice.grid_2d_graph(10,10)
# from node names, compute positions with random offset
positions = {(x,y):(1*x+np.random.uniform(0,0.2),1*y+np.random.uniform(0,0.2)) for (x,y) in G.nodes()}
# compute weights using euclidean distance
weights = [np.linalg.norm(np.array(positions[x])-np.array(positions[y])) for (x,y) in G.edges()]
nx.draw_networkx_nodes(G, pos=positions)
nx.draw_networkx_edges(G, pos=positions, width=weights)