1 Replies - 489 Views - Last Post: 26 August 2019 - 11:37 PM Rate Topic: -----

#1 stixmagiggins   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 5
  • Joined: 24-August 19

Key Error when Calculating shortest path with Multidigraph

Posted 24 August 2019 - 09:08 PM

I have two point layers, one with bus stops and train stations, and another with playground centrepoints.
From QGIS I created a cleaned up network containing roads and footpaths, which I have converted to a multidigraph in Python. This is so I can loop through each bus/train station and find the network to the playground point, if there is one.

The problem is trying to get the closest edge node to the playground spits out an error.

path = "C:\\........\\Footpath_Roads_Extended_Python.shp"
def read_multi_shp(path): #create multidigraph
    """
    copied from read_shp, but allowing MultiDiGraph instead.
    """
    try:
        from osgeo import ogr
    except ImportError:
        raise ImportError("read_shp requires OGR: http://www.gdal.org/")
 
    net = nx.MultiDiGraph()
 
    def getfieldinfo(lyr, feature, flds):
            f = feature
            return [f.GetField(f.GetFieldIndex(x)) for x in flds]
 
    def addlyr(lyr, fields):
        for findex in range(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)
 
    if isinstance(path, str):
        shp = ogr.Open(path)
        lyrcount = shp.GetLayerCount()
        for lyrindex in range(lyrcount):
            lyr = shp.GetLayerByIndex(lyrindex)
            flds = [x.GetName() for x in lyr.schema]
            addlyr(lyr, flds)
     
    return net
 
H=read_multi_shp(path)
 
PTV_Playground_Shortest_Path_300_400 = []
while i < len(PTV_Playground_Joined_initial): #loop through playgrounds and find nearest path node
 
    orig_xy = (df.loc[i,"PTV_N"], "-"+df.loc[i,"PTV_E"])
 
    target_xy = (df.loc[i,"Playgroun1"], df.loc[i,"Playground"])
     
    orig_node = ox.get_nearest_node(H, orig_xy, method='euclidean') #the error is when this calls the get_nearest_node function in utils.py. I is trying to get the x,y coords of H but fails


The error is

Traceback (most recent call last):
  File "C:\Users\geogjo\Desktop\PythonTraining\Network_Analysis_Test.py", line 100, in <module>
    orig_node = ox.get_nearest_node(H, orig_xy, method='euclidean')
  File "C:\Users\geogjo\AppData\Local\Continuum\anaconda3\lib\site-packages\osmnx\utils.py", line 461, in get_nearest_node
    coords = [[node, data['x'], data['y']] for node, data in G.nodes(data=True)]
  File "C:\Users\geogjo\AppData\Local\Continuum\anaconda3\lib\site-packages\osmnx\utils.py", line 461, in <listcomp>
    coords = [[node, data['x'], data['y']] for node, data in G.nodes(data=True)]
KeyError: 'x'


My multidigraph nodes look ok when I print them

[(327688.2817133684, 5739552.011543424), (341508.08128750307, 5767378.745506252), (341481.1308291708, 5767277.219589586), (341364.9730373633, 5767271.420884848), (341364.8637279594, 5767271.415428021), (341374.82312183146, 5767212.4025153965).... 


The coordinates for the other point features look ok also.

According to the documentation in https://osmnx.readth...able/osmnx.html it should be able to handle a multidigraph. A key error would mean it can't find that key (x). In this case x should come from the node coordinates, but this isn't an actual key in the multidigraph, and I can't modify the multidigraph to make x and y a key. Any thoughts on this? Could something have broken with Python 3.7?

Sorry I had since edited the code.
The coordinates of the point features are extracted like this.

orig_xy = (float(df.loc[i,"PTV_E"]), float(df.loc[i,"PTV_N"]))

    target_xy = (float(df.loc[i,"Playground"]), float(df.loc[i,"Playgroun1"]))


Problem still remains so it isn't these points.

Is This A Good Question/Topic? 0
  • +

Replies To: Key Error when Calculating shortest path with Multidigraph

#2 stixmagiggins   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 5
  • Joined: 24-August 19

Re: Key Error when Calculating shortest path with Multidigraph

Posted 26 August 2019 - 11:37 PM

Is there a way I can alter the multidigraph so that the first value is assigned the key 'X', and the second assigned 'Y'?
I've tried this without luck. Do I need to create a new multidigraph and assign it there?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1