對於我當前的項目,我想使用圖形工具庫,因爲他們聲稱是最快的:https://graph-tool.skewed.de/performance。我有一些算法(最短路徑等)在真正的大型網絡上運行,所以越快越好!蟒蛇圖形工具訪問頂點屬性
第一個問題:這個說法'最快'是真的嗎? ;)
雖然試圖構建符合我需求的圖形工具圖,但我發現無法以高效的方式訪問頂點屬性。也許我錯過了什麼?
我的問題是現在,函數「getVertexFromGraph(圖形,位置)」可以寫在一個更有效的方式?或者更一般地說:我能否有效地檢查頂點(由其位置屬性給出)是否已經在圖中。
在此先感謝!
import graph_tool as gt
#from graph_tool.all import *
edgeList = [[(0.5,1),(2.1,4.3)],[(2.1,4.3),(5.4,3.3)],[(5.4,3.3),(1.3,3.5)],[(4.4,3.3),(2.3,3.5)]] #A lot more coordinate values....
# Initialize the graph
routableNetwork = gt.Graph()
# Initialize the vertex property "position" to store the vertex coordinates
vpPosition = routableNetwork.new_vertex_property("vector<double>")
routableNetwork.vertex_properties["position"] = vpPosition
def getVertexFromGraph(graph, position):
"""
This method checks if a vertex, identified by its position, is in the given graph or not.
:param graph: The graph containing all vertices to check
:param position: The vertex/position to check
:return: The ID of the vertex if the vertex is already in the graph, 'None' otherwise
"""
for v in graph.vertices():
if graph.vp.position[v] == position:
return v
return None
def main():
"""
This method creates the graph by looping over all given edges, inserting every:
- non existent vertex in the graph with its coordinates (property 'position')
- edge with its corresponding length (property 'distance')
:return: -
"""
for e in edgeList:
vertex0 = getVertexFromGraph(routableNetwork,e[0])
vertex1 = getVertexFromGraph(routableNetwork,e[1])
if vertex0 == None:
vertex0 = routableNetwork.add_vertex()
routableNetwork.vertex_properties['position'][vertex0] = e[0]
if vertex1 == None:
vertex1 = routableNetwork.add_vertex()
routableNetwork.vertex_properties['position'][vertex1] = e[1]
edge = routableNetwork.add_edge(vertex0,vertex1)
#routableNetwork.edge_properties['distance'][edge] = calculateDistance(e[0][0],e[0][1],e[1][0],e[1][1])
#saveRoutableNetwork(routableNetwork)
#graph_draw(routableNetwork, vertex_text=routableNetwork.vertex_index, vertex_font_size=18, output_size=(200, 200), output="two-nodes.png")
if __name__ == "__main__":
main()
感謝您的回答! 「對於大圖,你最好創建一個好的舊python字典,將屬性值映射到頂點,這些頂點的查找成本爲O(1)。」 - 我也這麼想。 – JustSomeone