繁体   English   中英

从 python 中的邻接矩阵计算距离矩阵

[英]Computing the distance matrix from an adjacency matrix in python

编写从图(图论)生成距离矩阵的代码,该代码应使用邻接矩阵并且不能使用 NetworkX 模块中的任何函数,除了 .networkx.adjacency_matrix()。

我了解距离矩阵如何工作的过程。 我关于如何涉及邻接矩阵的理论是它采用连接两个节点的元素并增加距离。 例如,假设我有节点 A、B 和 C。A 连接到 B,B 连接到 C。两个连接节点之间的距离为 1。因此从 A 到 C 的距离为 2。

我唯一的问题是如何将其实现到代码中,以便它为任何给定的图形创建一个距离矩阵。

感谢您的帮助,如果我的解释不清楚,请抱歉,如果您希望我澄清任何事情,请告诉我。

检查以下代码是否有帮助。

#G is a networkX graph.
def get_actual_distance_between_two_nodes(G, i, j):
    pos=nx.spring_layout(G, seed=random_seed)
    sp = nx.shortest_path(G, i, j)
    edges_set = [[sp[i], sp[i+1]] for i in range(len(sp)-1)]

    distance_list = []
    for edge in edges_set:
        start_node = edge[0]
        end_node = edge[1]

        x1 = pos[start_node][0]
        y1 = pos[start_node][1]
        x2 = pos[end_node][0]
        y2 = pos[end_node][1]

        distance = math.dist([x1,y1], [x2,y2])
        distance_list.append(distance)

    return (sum(distance_list)) 
    
def nodes_connected(G, u, v):
    return u in G.neighbors(v)

def create_distance_matrix(G, nodes_list):
    distance_matrix_custom = []
    for i in range(len(nodes_list)):
        current_node = nodes_list[i]
        #print("Current Node: --->", current_node)
        list_of_distance = []
        for j in range(len(nodes_list)):
            target_node = nodes_list[j]
            #print("Target Node: --->", target_node)
            
            if(current_node == target_node):
                actual_distance = 0
            elif(G.has_edge(current_node, target_node)):
                actual_distance = get_actual_distance_between_two_nodes(G, current_node, target_node)                
            else:
                #actual_distance = float('inf')
                actual_distance = 10000000000
            list_of_distance.append(actual_distance)
        distance_matrix_custom.append(list_of_distance)

    return distance_matrix_custom
        
distance_matrix_custom = create_distance_matrix(G, nodes_list)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM