import networkx as nx
from networkx.algorithms import approximation as ax

Road = nx.read_shp('/Users/benjaminhendel/Downloads/scatteredroads.shp') #Reading Road Data 
Base = nx.read_shp('/Users/benjaminhendel/Downloads/testptssnapped.shp') #Reading Terminal Node
nodes = list(Base.nodes) #Creating list of terminal nodes
Road = Road.to_undirected()
st_tree = ax.steinertree.steiner_tree(Road,nodes,weight='length')

I'm trying to read a shapefile into networkx and run steiner_tree approximation on it. It tells me that my graph is directed. When I make it undirected, it gives me the error:

networkx.exception.NetworkXError: G is not a connected graph. metric_closure is not defined.
  • 1
    Not relevant, but should be Base.nodes() ? – FelixIP May 12 at 2:39

A graph is said to be connected if there is a path between every pair of vertex.

Therefore create a new full connected Graph with itertools

 import itertools
 Road = nx.read_shp('stac_graph.shp')
 # control
 Road2 = Road.to_undirected()
 # new graph with path between every pair of vertex
 G = nx.Graph()
 # add original nodes
 # create edges
 G.add_edges_from(itertools.combinations(Road, 2))
 # control
 # and
 nodes = list(G.nodes) 
 <networkx.classes.graph.Graph object at 0xa27c5da58>
  • I don't understand. What is G-ex? it is never defined. And where do I input my nodes shapefile? – Benny Henny May 13 at 7:35
  • And doesn't this create an edge between every node? This isn't what my original road network file is like – Benny Henny May 13 at 7:39
  • a mistake, corrected, thanks – gene May 13 at 8:12
  • Doesn't work, it connects every vertex, I wanted it to run on a second shapefile of nodes – Ben Hendel May 18 at 1:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.