2011-01-19 34 views
2

我試圖設計一個需要全球定位數據的項目,例如城市和州名以及緯度和位置。我也會在每一對城市之間有距離。我想用所有這些信息製作一個圖表,並操縱它來執行一些圖表算法。我決定擁有包含每個位置數據的城市對象。現在我應該有一個散列函數來區分對象嗎?我應該如何處理組合節點和移除邊的圖算法?我應該如何創建我的對象,以便它能很好地與networkx協同工作?

def minCut(self): 
    """Returns the lowest-cost set of edges that will disconnect a graph""" 

    smcut = (float('infinity'), None) 
    cities = self.__selectedcities[:] 
    edges = self.__selectededges[:] 
    g = self.__makeGRAPH(cities, edges) 
    if not nx.is_connected(g): 
     print("The graph is already diconnected!") 
     return 
    while len(g.nodes()) >1: 
     stphasecut = self.mincutphase(g) 
     if stphasecut[2] < smcut: 
      smcut = (stphasecut[2], None) 
     self.__merge(g, stphasecut[0], stphasecut[1]) 
    print("Weight of the min-cut: "+str(smcut[1])) 

它的形狀非常糟糕。我正在重寫我的原始程序,但這是我從以前的版本中採取的方法。

+0

怎麼樣一些示例代碼? – Spaceghost 2011-01-19 18:54:23

回答

1

根據您安裝的networkx版本,可以使用min_cut的內置實現。

我安裝了1.0RC1軟件包,但沒有提供..但我升級到1.4,min_cut在那裏。

這裏有一個(傻)例如:

import networkx as nx 
g = nx.DiGraph() 
g.add_nodes_from(['London', 'Boston', 'NY', 'Dallas']) 
g.add_edge('NY', 'Boston', capacity) 
g.add_edge('Dallas', 'Boston') 
g.add_edge('Dallas', 'London') 
# add capacity to existing edge 
g.edge['Dallas']['London']['capacity'] = 2 
# create edge with capacity attribute 
g.add_edge('NY', 'London', capacity=3) 
print nx.min_cut(g, 'NY', 'London') 
0

您不需要爲城市對象創建哈希函數,您可以直接將城市對象傳遞給Networkx - 從教程「節點可以是任何可哈希對象,例如文本字符串,圖像,XML對象,另一個Graph,一個自定義節點對象等。「

您可以遍歷城市列表並將它們添加爲節點,然後迭代距離信息以生成圖形。

你看過教程嗎? http://networkx.lanl.gov/tutorial/tutorial.html

+0

是的,我讀過教程。我只是不知道如何處理節點,當我想在圖表上執行一個最小切割算法時。 – Trim 2011-01-19 18:57:23

0

在合併節點時,您可以創建新節點並將這些新節點散列到已合併城市的列表中。例如,在上面的代碼中,您可以命名新節點len(g),並將其散列到stphasecut [0] + stphasecut [1]#,假設stphasecut [1]和[2]是列表。

相關問題