Search code examples
pythonalgorithmgraphgeojsonsumo

graph_to_gdfs not working even with simple examples


I'm using osmnx and networkx modelues in Python to convert a sumo network into a geojson file. I've got an error when using graph_to_gdfs I've tried this simple example after trying on a more complicated, but still having the same error:

# Example graph
G = nx.DiGraph()
G.add_node(1, y=37.77, x=-122.42)  # Coordenadas de San Francisco
G.add_node(2, y=37.76, x=-122.43)
G.add_edge(1, 2, weight=0.5)
G.graph['crs']='WGS84'
# Converting 
gdf_nodes, gdf_edges = ox.utils_graph.graph_to_gdfs(G, nodes=True, edges=True)

print(gdf_nodes)
print(gdf_edges)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last) Cell In\[62\], line 8 6 G.graph\['crs'\]='WGS84' 7 # Convertir a GeoDataFrame 8 gdf_nodes, gdf_edges = ox.utils_graph.graph_to_gdfs(G, nodes=True, edges=True) 10 print(gdf_nodes) 11 print(gdf_edges)

File \~/micromamba/envs/geo/lib/python3.12/site-packages/osmnx/utils_graph.py:41, in graph_to_gdfs(G, nodes, edges, node_geometry, fill_edge_geometry) 34 msg = ( 35     "The `graph_to_gdfs` function has moved to the `convert` module. Calling " 36     "`utils_graph.graph_to_gdfs` is deprecated and will be removed in the " 37     "v2.0.0 release. Call it via `convert.graph_to_gdfs` instead. " 38     "See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123" 39 ) 40 warn(msg, FutureWarning, stacklevel=2) 41 return convert.graph_to_gdfs(G, nodes, edges, node_geometry, fill_edge_geometry)

File \~/micromamba/envs/geo/lib/python3.12/site-packages/osmnx/convert.py:65, in graph_to_gdfs(G, nodes, edges, node_geometry, fill_edge_geometry) 62     msg = "Graph contains no edges" 63     raise ValueError(msg) 65 u, v, k, data = zip(\*G.edges(keys=True, data=True)) 67 if fill_edge_geometry: 68     # subroutine to get geometry for every edge: if edge already has 69     # geometry return it, otherwise create it using the incident nodes 70     x_lookup = nx.get_node_attributes(G, "x")

TypeError: OutEdgeView.__call__() got an unexpected keyword argument 'keys'

I've tried to delete the keyword argument 'keys' in convert.py without success.


Solution

  • Per the OSMnx documentation, the graph_to_gdf function accepts a MultiGraph or a MultiDiGraph as input. But you are passing it a DiGraph, which by definition lacks the keys attribute, and thereby causes your error.

    You can resolve this error by passing a MultiGraph or a MultiDiGraph. And you can avoid this kind of error by type checking your code.

    See also the OSMnx getting started guide for details on expected/required graph model attributes.