python - NetworkX - How to create MultiDiGraph from Shapefile? -
i'm picking networkx , trying learn how use shapefiles.
right have .shp road network want represent in graph networkx, can find shortest path between 2 gps points. tried using this, problem when run write_shp() function lose edges because digraph not allow more 1 edge between same 2 nodes. arrow in figure below shows example of edge lose using digraph.

so wondering if there's way create multidigraph don't lose edges, or if there's way around use. thinking maybe write code extract attributes shapefile , create multidigraph without using networkx's read_shp(), don't have experience @ working graphs, i'm not sure if it'd possible.
i'd appreciate or guidance give me, or if i've missed documentation please let me know. in advance.
as best can follow question, following it, copied original read_shp command.
def read_multi_shp(path): """ copied read_shp, allowing multidigraph instead. """ try: osgeo import ogr except importerror: raise importerror("read_shp requires ogr: http://www.gdal.org/") net = nx.multidigraph() # <--- here main change made def getfieldinfo(lyr, feature, flds): f = feature return [f.getfield(f.getfieldindex(x)) x in flds] def addlyr(lyr, fields): findex in xrange(lyr.getfeaturecount()): f = lyr.getfeature(findex) flddata = getfieldinfo(lyr, f, fields) g = f.geometry() attributes = dict(zip(fields, flddata)) attributes["shpname"] = lyr.getname() if g.getgeometrytype() == 1: # point net.add_node((g.getpoint_2d(0)), attributes) if g.getgeometrytype() == 2: # linestring attributes["wkb"] = g.exporttowkb() attributes["wkt"] = g.exporttowkt() attributes["json"] = g.exporttojson() last = g.getpointcount() - 1 net.add_edge(g.getpoint_2d(0), g.getpoint_2d(last), attr_dict=attributes) #<--- changed line if isinstance(path, str): shp = ogr.open(path) lyrcount = shp.getlayercount() # multiple layers indicate directory lyrindex in xrange(lyrcount): lyr = shp.getlayerbyindex(lyrindex) flds = [x.getname() x in lyr.schema] addlyr(lyr, flds) return net i changed returned graph digraph multidigraph , had change add_edge command since multidigraph version has different syntax digraph
Comments
Post a Comment