networkx + ogr

Python code posted by bwreilly
created at 21 Jul 01:10

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import osgeo.ogr as ogr
import networkx

class Network(networkx.DiGraph):
    """Basic utility network object   
    """

    def load(self, path):
        """Load a shapefile into the network.
        """
        def getfieldinfo(feature, flds):
                f = feature
                return [f.GetField(f.GetFieldIndex(x)) for x in flds]
                
        def addlyr(shp, fields):
            for findex in xrange(shp.GetFeatureCount()):
                f = shp.GetFeature(findex)
                fldinfo = getfieldinfo(f, fields)
                g = f.geometry()
                attributes = dict(zip(fields, fldinfo))
                if g.GetGeometryType() == 1: #point
                    self.add_node((g.GetPoint(0)), attributes)
                if g.GetGeometryType() == 2: #linestring
                    last = g.GetPointCount() - 1
                    self.add_edge(g.GetPoint(0), g.GetPoint(last), attributes)
                    
        if isinstance(path, str) and path.split(".")[-1] == "shp":
            shp = ogr.Open(path)
            lyrcount = shp.GetLayerCount()
            for lyrindex in xrange(lyrcount):
                lyr = shp.GetLayerByIndex(lyrcount - 1)
                flds = [x.GetName() for x in lyr.schema]
                addlyr(lyr, flds)
1.29 KB in 3 ms with coderay