How to convert a shapefile into a graph in which use Dijkstra

The sg module uses Fiona to read the shapefiles (see shapegraph.py ) and if you can use the module, therefore Fiona is installed.

If you cannot use nx_shp.py (because of osgeo) and you have problems with sg, you can use Fiona and Networkx to create a Networkx Graph. (GSE: How to calculate edge length in Networkx for example).

from shapely.geometry import shape
import fiona
geoms =[shape(feature['geometry']) for feature in fiona.open("stac_graphe.shp")]
import itertools
# create a Graph
import networkx as nx
G = nx.Graph()
for line in geoms:
   for seg_start, seg_end in itertools.izip(list(line.coords),list(line.coords)[1:]):
    G.add_edge(seg_start, seg_end) 

Result

enter image description here

You can also create a Planar Graph

from shapely.ops import unary_union
res = unary_union(geoms)
G = nx.Graph()
for line in res:
    for seg_start, seg_end in itertools.izip(list(line.coords),list(line.coords)[1:]):
        G.add_edge(seg_start, seg_end) 

enter image description here

New

There is a problem if some geometries are Multigeometries
For example:

 geoms =[shape(feature['geometry']) for feature in fiona.open("multiline.shp")]
 for line in geoms:
     print line
 MULTILINESTRING ((3 4, 10 50, 20 25), (-5 -8, -10 -8, -15 -4))

With geoms[0], you decompose the Multigeometry

 for line in geoms[0]:
     print line

 LINESTRING (3 4, 10 50, 20 25)
 LINESTRING (-5 -8, -10 -8, -15 -4)

Therefore the script becomes

  if line.geom_type== "MultiLineString":
        ....
   else: