2

I'm creating a complete graph with 50 randomly created nodes. Each node is defined as a Cartesian coordinate as follows:

n = 50
V = []
V=range(n)

random.seed()

pos = {i:(random.randint(0,500),random.randint(0,500)) for i in V}

I need to assign the Euclidean distance between each node as the edge weight corresponds to that pair of nodes.

I have already defined the Euclidean distance between two nodes as follows:

points = []
positions = []
for i in pos:
    points.append(pos[i])
    positions.append(i)
    positions.append(pos[i])

def distance(points, i, j):
    dx = points[i][0] - points[j][0]
    dy = points[i][1] - points[j][1]
    return math.sqrt(dx*dx + dy*dy)

I tried assigning Euclidean distance as their weight as follows:

for u in V:
    for v in V:
        weights = distance(points, u,v)

G = nx.complete_graph(n)
for e in G.edges():
   weights[e] = distance(points, e[0],e[1])

But this returns the following error.

    weights[e] = distance(points, e[0],e[1])

TypeError: 'float' object does not support item assignment

Can someone suggest me a way to do that?

cs95
  • 379,657
  • 97
  • 704
  • 746
ccc
  • 574
  • 2
  • 9
  • 22

2 Answers2

2

The problem you have is that after

for u in V:
    for v in V:
        weights = distance(points, u,v)

weights is a float (the distance of the last pair compared).

Now you do

for e in G.edges():
    weights[e] = distance(points, e[0],e[1])

You're assigning the eth item of the float weights to be something. Not allowed.

What I think you want is

for u,v in G.edges():
    G[u][v]['distance'] = distance(points, u, v)

As a note, rather than having points defined, I would make the nodes be a tuple of cartesian coordinates. See Relabeling Nodes of a graph in networkx

Joel
  • 22,598
  • 6
  • 69
  • 93
2

In addition to what Joel mentioned, here is the code that works.

import random
import networkx as nx
import math
import itertools    
import matplotlib.pyplot as plt
n = 50
V = []
V=range(n)

random.seed()

pos = {i:(random.randint(0,500),random.randint(0,500)) for i in V}
points = []
positions = []
for i in pos:
    points.append(pos[i])
    positions.append(i)
    positions.append(pos[i])

def distance(points, i, j):
    dx = points[i][0] - points[j][0]
    dy = points[i][1] - points[j][1]
    return math.sqrt(dx*dx + dy*dy)

G=nx.empty_graph(n)

for u in V:
    for v in V:
        wt = distance(points, u,v)
        G.add_edge(u,v,weight = wt)

nx.draw(G,pos)
edges,weights = zip(*nx.get_edge_attributes(G,'weight').items())
nx.draw(G, pos, node_color='k', edgelist=edges, edge_color=weights, width=1, edge_cmap=plt.cm.Reds)

Edges colored by edgeweights

user8401743
  • 110
  • 8