简体   繁体   English

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

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

Write a code that produces the distance matrix from a graph (graph theory), the code should use the adjacency matrix and cannot use any functions from NetworkX module, apart from.networkx.adjacency_matrix().编写从图(图论)生成距离矩阵的代码,该代码应使用邻接矩阵并且不能使用 NetworkX 模块中的任何函数,除了 .networkx.adjacency_matrix()。

I understand the process of how the distance matrix works.我了解距离矩阵如何工作的过程。 My theory of how the adjacency matrix is involved is that it takes an element that connects two nodes and adds the distance up.我关于如何涉及邻接矩阵的理论是它采用连接两个节点的元素并增加距离。 For example, lets say i have nodes A, B and C. A is connected to B, and B is connected to C. The distance between two connected nodes is 1. So the distance from A to C would be 2.例如,假设我有节点 A、B 和 C。A 连接到 B,B 连接到 C。两个连接节点之间的距离为 1。因此从 A 到 C 的距离为 2。

My only problem is how i can implement this into a code so that it creates a distance matrix for any given graph.我唯一的问题是如何将其实现到代码中,以便它为任何给定的图形创建一个距离矩阵。

Thank you for any help, sorry if my explanation is unclear, please let me know if you would like me to clarify anything.感谢您的帮助,如果我的解释不清楚,请抱歉,如果您希望我澄清任何事情,请告诉我。

Check if the below code helps.检查以下代码是否有帮助。

#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