1

我只是拿起 NetworkX 并尝试学习如何将它与 Shapefile 一起使用。

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

在此处输入图像描述

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

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

4

3 回答 3

3

尽我所能从您的问题中得出结论,以下将做到这一点,基本上是从原始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

我将返回的图形从 a 更改DiGraph为 aMultiDigraph并且我不得不更改add_edge命令,因为该MultiDiGraph版本的语法与DiGraph

于 2015-06-11T03:19:00.543 回答
1

如果多线在接头处断开,我认为这个库python-s2ghttps://github.com/caesar0301/python-s2g)可以帮助你。甚至 networkx 的 Graph 对象也在底层使用,这些多路径实际上是由图形数据记录的。

于 2016-12-15T13:47:59.810 回答
-1

I have implemented a solution here: https://gitlab.com/njacadieux/upstream_downstream_shortests_path_dijkstra

I read the shapefile using GeoPandas and not the networkx.readwrite.nx_shp.read_shp. When I build the graph, I check for parallel edges. If found, rather than skipping them, as does the networkx.readwrite.nx_shp.read_shp function, I split the parallel edges in two edges of equal length and then divide the user length by 2. The user length variable field name must be given.

于 2020-01-22T17:33:55.243 回答