簡體   English   中英

Python Scipy和Networkx:如何計算歐幾里得距離矩陣?

[英]Python Scipy and Networkx: How to compute a Euclidean distance matrix?

我正在使用Python Networkx構建圖形,並且以以下節點位置為例(positions.txt):

1 21.5 23
2 24.5 20
3 19.5 19
4 22.5 15
5 24.5 12  

節點ID,X,Y。我使用Pandas讀取文件,並將位置設置為Networkx中的節點屬性。 使用add_edge(id1, id2, weight)方法在for循環中添加節點(無自add_edge(id1, id2, weight) )。 到目前為止,我已經假定所有節點默認情況下都是彼此連接的,並且未考慮諸如半徑或節點距離之類的參數。
現在,我想使用這些節點位置來計算節點之間的歐幾里德半徑或距離矩陣,並希望使用該矩陣來打印屬於給定半徑n的節點的鄰居並將文件另存為csv矩陣文件。 一位朋友建議我使用scipyeuclidean方法,但是我不知道如何使用它來構建矩陣,因此我沒有起點。 我嘗試使用ego_graph()但沒有給我想要的結果。
感謝您為解決我的問題提供的任何幫助。
提前致謝。 (使用Ubuntu 14.04 32位VM和Python 2.7)

您可以使用scipy.spatial.distance.cdist()生成給定坐標列表的距離矩陣。

顯然,一個numpy數組始終為0索引,如果您的節點具有隨機數,則希望保留它們的列表以了解矩陣的哪一行/哪一列對應於哪一對。

在那之后您應該做些瑣碎的事,但是我將根據您的描述舉一個例子。 對於每個節點,請打印該節點的ID和您的閾值距離內的所有相鄰節點的ID。

import numpy as np
from scipy.spatial import distance

def neighbour_nodes_of(node, dist_matrix, distance):
    row = dist_matrix[node]
    return np.where((row <= distance) * (row > 0))[0]

ids = [1, 2, 3, 4, 5]
coords = [(21.5, 23),
          (24.5, 20),
          (19.5, 19),
          (22.5, 15),
          (24.5, 12),
          ]
threshold = 8.

dist_matrix = distance.cdist(coords, coords)

# this is something you can write to a file instead
for i, node_id in enumerate(ids):
    neighbours = neighbour_nodes_of(i, dist_matrix, threshold)
    neighbour_ids = [ids[n] for n in neighbours]
    print([node_id] + neighbour_ids)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM