gpt4 book ai didi

python - NetworkX - 如何从 Shapefile 创建 MultiDiGraph?

转载 作者:行者123 更新时间:2023-12-01 04:40:36 27 4
gpt4 key购买 nike

我刚刚开始学习 NetworkX 并尝试学习如何将它与 Shapefile 一起使用。

现在我有一个带有道路网络的 .shp 文件,我想用 NetworkX 在图表中表示它,这样我就可以找到 2 个 GPS 点之间的最短路径。我尝试使用 this ,但问题是,当我运行 write_shp() 函数时,我会丢失边缘,因为有向图不允许相同的两个节点之间存在多个边缘。下图中的箭头显示了我使用有向图丢失的边的示例。

enter image description here

所以我想知道是否有任何方法可以创建一个多重有向图,这样我就不会丢失任何边缘,或者是否有任何可以使用的方法。我在想也许我可以编写一些代码来从 Shapefile 中提取属性并创建 MultiDiGraph,而不使用 NetworkX 的 read_shp(),但我没有任何使用图形的经验,所以我不确定是否可以是有可能的。

我非常感谢您能给我的任何帮助或指导,或者如果我错过了任何文档,请告诉我。提前致谢。

最佳答案

据我所知,从你的问题中可以看出,下面的代码可以做到这一点,基本上是从原始的 read_shp 命令复制的。

def read_multi_shp(path):
"""
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() # <--- here is the main change I made

def getfieldinfo(lyr, feature, flds):
f = feature
return [f.GetField(f.GetFieldIndex(x)) for x in flds]

def addlyr(lyr, fields):
for 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) #<--- also changed this line

if isinstance(path, str):
shp = ogr.Open(path)
lyrcount = shp.GetLayerCount() # multiple layers indicate a directory
for lyrindex in xrange(lyrcount):
lyr = shp.GetLayerByIndex(lyrindex)
flds = [x.GetName() for x in lyr.schema]
addlyr(lyr, flds)
return net

我将返回的图形从DiGraph更改为MultiDigraph,并且我必须更改add_edge命令,因为MultiDiGraph 版本与 DiGraph

的语法不同

关于python - NetworkX - 如何从 Shapefile 创建 MultiDiGraph?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30770776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com