[英]How to construct a graph (nodes and edges) in Python?
I have a txt file has coordinates for multiple rectangles (X center , Y center , width, height).我有一个 txt 文件,其中包含多个矩形的坐标(X中心、Y中心、宽度、高度)。 I would like to create an undirected graph network where the nodes of which stand for the rectangle and the edges of which represent distance between the nodes.
我想创建一个无向图网络,其中节点代表矩形,边代表节点之间的距离。
txt file: 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
In graph, you can represent rectangles as a 'list' of nodes with their x,y,height and weight as their properties, and represent their edges in an adjacency matrix, with distance between them marked in each cell.在图中,您可以将矩形表示为节点的“列表”,其中 x、y、高度和权重作为它们的属性,并在邻接矩阵中表示它们的边缘,并在每个单元格中标记它们之间的距离。
Below is a sample program, that creates a complete-graph out of given data.下面是一个示例程序,它根据给定的数据创建一个完整的图表。
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)
Output (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.