[英]How to construct a graph (nodes and edges) in Python?
我有一個 txt 文件,其中包含多個矩形的坐標(X中心、Y中心、寬度、高度)。 我想創建一個無向圖網絡,其中節點代表矩形,邊代表節點之間的距離。
txt文件:
Xcenter Ycenter width height
0.568396 0.394130 0.176887 0.345912
0.391509 0.393082 0.172170 0.327044
0.717571 0.377358 0.119104 0.320755
0.254717 0.373166 0.103774 0.299790
在圖中,您可以將矩形表示為節點的“列表”,其中 x、y、高度和權重作為它們的屬性,並在鄰接矩陣中表示它們的邊緣,並在每個單元格中標記它們之間的距離。
下面是一個示例程序,它根據給定的數據創建一個完整的圖表。
import math
class node:
def __init__(self,x,y,height,width):
self.x=x
self.y=y
self.height=height
self.width=width
class graph:
def __init__(self,txt):
self.node_list=[]
for line in txt.split("\n"):
x,y,width,height=[i for i in line.strip().split(' ') if i!='']
new_node=node(x,y,height,width)
self.node_list.append(new_node)
self.adjacency_matrix= self.get_adjacenty_matrix()
def get_distance(self,x1,y1,x2,y2):
x1=float(x1)
y1=float(y1)
x2=float(x2)
y2=float(y2)
dis= math.sqrt(((x2-x1)**2)+((y2-y1)**2))
return dis
def get_adjacenty_matrix(self):
matrix=[]
for i in range(len(self.node_list)):
row=[0]*len(self.node_list)
for j in range(len(self.node_list)):
row[j]=self.get_distance(self.node_list[i].x, self.node_list[i].y, self.node_list[j].x, self.node_list[j].y)
print(row)
matrix.append(row)
return matrix
txt="""0.568396 0.394130 0.176887 0.345912
0.391509 0.393082 0.172170 0.327044
0.717571 0.377358 0.119104 0.320755
0.254717 0.373166 0.103774 0.299790"""
print(graph(txt).adjacency_matrix)
輸出(鄰接矩陣):
[[0.0, 0.17689010450842071, 0.15011489136324876, 0.314378759360425],
[0.17689010450842071, 0.0, 0.3264409165836905, 0.13823421544610434],
[0.15011489136324876, 0.3264409165836905, 0.0, 0.46287298277173183],
[0.314378759360425, 0.13823421544610434, 0.46287298277173183, 0.0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.