2016-11-21 14 views
0

我有一個包含四個節點的圖,每個節點之間有兩個方向邊(a到b和b到a),所以我使用了多個圖。該圖已經具有默認定義的「權重」屬性,對於我來說,這個屬性代表每個邊緣的流量容量。我需要爲每條邊定義兩個屬性,比如說tcv1和tcv2。如何定義多個邊的多個屬性Digraph

作爲Python和networkx的初學者,我無法弄清楚這一點。一些谷歌搜索帶我here但我無法正確使用它。

add_attribute_to_edge(router_matrix, tmp_path[0][0], tmp_path[0][1], 'tcv1', traffic_cv[0]) 

我使用上述其中router_matrix是曲線圖,tmp_path [X] [X]將代表像 'A' 或 'B' 的節點名稱,tcv1是屬性和traffic_cv代碼[0]中的代碼將一個整數計算。打印tcv1只給出{}。

有人可以提出解決方案或指出我出錯的地方。

回答

1

您可以使用add_edge功能,新屬性在MultiDiGraph添加到現有的邊緣,但需要注意的key關鍵字(其值必須爲0)。

在我的例子中,我添加了tcv1屬性的第一個「一」 - >「b」的邊緣(我用你的變量名和我的例子與add_edges_from圖表創建):

import networkx as nx 

router_matrix = nx.MultiDiGraph() 

# add two weighted edges ("a" -> "b" and "b" -> "a") 
router_matrix.add_edges_from([ 
    ("a", "b", {"weight": 0.5}), 
    ("b", "a", {"weight": 0.99}) 
    ]) 

# print list of edges with all data 
print(router_matrix.edges(data=True)) 

tmp_path = [["a", "b"], ["b", "a"]] 
traffic_cv = [42, 66] 

# add "tcv1" for only the first edge of tmp_path 
router_matrix.add_edge(tmp_path[0][0], tmp_path[0][1], key=0, tcv1=traffic_cv[0]) 

print(router_matrix.edges(data=True)) 

要添加tcv1所有邊緣,你可以使用router_matrix.edges()遍歷所有槽邊緣(注意,這裏我使用G[src_node][dest_node][key][attribute]語法而不是add_edge):

# add new attribute to all edges 
counter = 0 
for src, dest in router_matrix.edges(): 
    router_matrix[src][dest][0]['tcv1'] = traffic_cv[counter] 
    counter += 1 

print(router_matrix.edges(data=True))