inselberg
inselberg

Reputation: 959

Coordinates to graph

Is there a simpler, easier way to convert coordinates (long, lat) to a "networkx"-graph, than nested looping over those coordinates and adding weighted nodes/edges for each one?

for idx1, itm1 in enumerate(data):
    for idx2, itm2 in enumerate(data):
            pos1 = (itm1["lng"], itm1["lat"])
            pos2 = (itm2["lng"], itm2["lat"])
            distance = vincenty(pos1, pos2).meters #geopy distance
            # print(idx1, idx2, distance)
            graph.add_edge(idx1, idx2, weight=distance)

The target is representing points as a graph in order to use several functions on this graph.

Edit: Using an adjacency_matrix would still need a nested loop

Upvotes: 2

Views: 3238

Answers (1)

Aric
Aric

Reputation: 25289

You'll have to do some kind of loop. But if you are using an undirected graph you can eliminate half of the graph.add_edge() (only need to add u-v and not v-u). Also as @EdChum suggests you can use graph.add_weighted_edges_from() to make it go faster.

Here is a nifty way to do it

In [1]: from itertools import combinations

In [2]: import networkx as nx

In [3]: data = [10,20,30,40]

In [4]: edges = ( (s[0],t[0],s[1]+t[1]) for s,t in combinations(enumerate(data),2))

In [5]: G = nx.Graph()

In [6]: G.add_weighted_edges_from(edges)

In [7]: G.edges(data=True)
Out[7]: 
[(0, 1, {'weight': 30}),
 (0, 2, {'weight': 40}),
 (0, 3, {'weight': 50}),
 (1, 2, {'weight': 50}),
 (1, 3, {'weight': 60}),
 (2, 3, {'weight': 70})]

Upvotes: 3

Related Questions