簡體   English   中英

python graph-tool訪問頂點屬性

[英]python graph-tool access vertex properties

對於我當前的項目,我想使用graph-tool庫,因為它們聲稱是最快的: https : //graph-tool.skewed.de/performance 我有一些算法(最短路徑等)可以在非常大的網絡上運行,所以速度越快越好!

第一個問題:這是“最快”的說法嗎? ;)

在嘗試構建適合我需要的圖形工具圖形時,我發現無法以有效的方式訪問頂點屬性。 也許我錯過了什么?

我的問題是,現在可以以更有效的方式編寫函數“ getVertexFromGraph(graph,position)”嗎? 或更一般地說:我可以有效地檢查頂點(由其position屬性賦予)是否在圖形中。

提前致謝!

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()

您正在尋找的功能是find_vertex()

https://graph-tool.skewed.de/static/doc/util.html#graph_tool.util.find_vertex

重要的是要意識到graph-tool通過將性能敏感的循環從Python卸載到C ++來達到其速度。 因此,每當像在代碼中那樣遍歷頂點時,就失去了任何優勢。

還要注意,盡管find_vertex()是用C ++實現的,因此比純Python中的等效函數快許多倍,但它仍然是O(N)操作。 對於大型圖形,最好創建一個良好的舊python字典,該字典將屬性值映射到頂點,而查找成本為O(1)。

暫無
暫無

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

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