I have a list of points (x, y) whose values are from 0 to 1
JavaScript
x
10
10
1
def generate_points(n):
2
"""Generates n points whose values are in the range (0, 1).
3
4
Args:
5
n (int): number of points to generate
6
"""
7
x = [random.uniform(0, 1) for r in range(n)]
8
y = [random.uniform(0, 1) for r in range(n)]
9
return list(itertools.product(x, y))
10
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
JavaScript
1
2
1
G = nx.generators.lattice.grid_2d_graph([(0,1), (0, 2)], [(1, 1), (1, 2)])
2
a different graph is generated each time, even the nodes are the same.
Advertisement
Answer
IIUC you want something like this?
JavaScript
1
12
12
1
#make grid graph
2
G=nx.generators.lattice.grid_2d_graph(10,10)
3
4
# from node names, compute positions with random offset
5
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()}
6
7
# compute weights using euclidean distance
8
weights = [np.linalg.norm(np.array(positions[x])-np.array(positions[y])) for (x,y) in G.edges()]
9
10
nx.draw_networkx_nodes(G, pos=positions)
11
nx.draw_networkx_edges(G, pos=positions, width=weights)
12