Networkx:查找Graph中多个节点之一的最短路径

Dan*_*kov 5 python graph networkx

我有一个不同位置的图表:

import networkx as nx

G = nx.Graph()
for edge in Edge.objects.all():
    G.add_edge(edge.from_location, edge.to_location, weight=edge.distance)
Run Code Online (Sandbox Code Playgroud)

位置(节点)有不同的类型(厕所,建筑物入口等)我需要找到从某个给定位置到特定类型的任何位置的最短路径.(例如:从给定节点查找最近的入口.)

Networkx库中是否有一些方法可以解决没有循环的问题?就像是:

nx.shortest_path(
     G,
     source=start_location,
     target=[first_location, second_location],
     weight='weight'
)
Run Code Online (Sandbox Code Playgroud)

如果两个位置属于同一类型,则结果将是first_location或second_location的最短路径.

是否有一些方法也返回路径长度?

Ram*_*han 6

我们将分三个步骤进行。

  • 步骤1:让我们创建一个虚拟图来说明
  • 第2步:绘制图形和颜色节点,以指示边长和特殊节点类型(厕所,入口等)
  • 步骤3:从任何给定节点(源)计算到所有可达节点的最短路径,然后子集到感兴趣的节点类型并选择具有最小长度的路径。

可以肯定地优化下面的代码,但这可能更容易遵循。

步骤1:建立图表

edge_objects = [(1,2, 0.4), (1, 3, 1.7), (2, 4, 1.2), (3, 4, 0.3), (4 , 5, 1.9), 
(4 ,6, 0.6), (1,7, 0.4), (3,5, 1.7), (2, 6, 1.2), (6, 7, 0.3), 
(6, 8, 1.9), (8,9, 0.6)]

toilets = [5,9] # Mark two nodes (5 & 9) to be toilets
entrances = [2,7] # Mark two nodes (2 & 7) to be Entrances
common_nodes = [1,3,4,6,8] #all the other nodes

node_types = [(9, 'toilet'), (5, 'toilet'),
              (7, 'entrance'), (2, 'entrance')]

#create the networkx Graph with node types and specifying edge distances
G = nx.Graph()

for n,typ in node_types:
    G.add_node(n, type=typ) #add each node to the graph

for from_loc, to_loc, dist in edge_objects:
    G.add_edge(from_loc, to_loc, distance=dist) #add all the edges   
Run Code Online (Sandbox Code Playgroud)

步骤2:绘制图形

#Draw the graph (optional step)
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
edge_labels = nx.get_edge_attributes(G,'distance')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels)
nx.draw_networkx_nodes(G, pos, nodelist=toilets, node_color='b')
nx.draw_networkx_nodes(G, pos, nodelist=entrances, node_color='g')
nx.draw_networkx_nodes(G, pos, nodelist=common_nodes, node_color='r')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

步骤3:创建小函数以找到节点类型的最短路径

def subset_typeofnode(G, typestr):
    '''return those nodes in graph G that match type = typestr.'''
    return [name for name, d in G.nodes(data=True) 
            if 'type' in d and (d['type'] ==typestr)]

#All computations happen in this function
def find_nearest(typeofnode, fromnode):

    #Calculate the length of paths from fromnode to all other nodes
    lengths=nx.single_source_dijkstra_path_length(G, fromnode, weight='distance')
    paths = nx.single_source_dijkstra_path(G, fromnode)

    #We are only interested in a particular type of node
    subnodes = subset_typeofnode(G, typeofnode)
    subdict = {k: v for k, v in lengths.items() if k in subnodes}

    #return the smallest of all lengths to get to typeofnode
    if subdict: #dict of shortest paths to all entrances/toilets
        nearest =  min(subdict, key=subdict.get) #shortest value among all the keys
        return(nearest, subdict[nearest], paths[nearest])
    else: #not found, no path from source to typeofnode
        return(None, None, None)
Run Code Online (Sandbox Code Playgroud)

测试:

 find_nearest('entrance', fromnode=5)
Run Code Online (Sandbox Code Playgroud)

产生:

 (7, 2.8, [5, 4, 6, 7])
Run Code Online (Sandbox Code Playgroud)

含义:距离5最近的“入口”节点为7,路径长度为2.8,完整路径为:[5、4、6、7]。希望这可以帮助您前进。请询问是否不清楚。