2017-02-20 22 views
2

如果您考慮以下圖:NetworkX:在圖上構建一個簡單的流程研究

from __future__ import division 
import networkx as nx 
import matplotlib.pyplot as plt 
import numpy as np 
from numpy.linalg import inv 

G = nx.Graph() 

pos={1:(2,3),2:(0,0),3:(6,0)} 
G.add_nodes_from(pos.keys()) 
nx.set_node_attributes(G, 'coord', pos) 

PE={1:0,2:60,3:40} 
nx.set_node_attributes(G,'PE',PE) 
q={1:100,2:0,3:0} 
nx.set_node_attributes(G,'q',q) 

G.add_edge(1,2) 
G.add_edge(1,3) 
G.add_edge(2,3) 

import math 
lengths={} 
inv_lengths={} 
for edge in G.edges(): 
    startnode=edge[0] 
    endnode=edge[1] 
    lengths[edge]=round(math.sqrt(((pos[endnode][1]-pos[startnode][1])**2)+ 
             ((pos[endnode][0]-pos[startnode][0])**2)),2) 
    inv_lengths[edge]=round(1/lengths[edge],3) 
nx.set_edge_attributes(G, 'length', lengths) 
nx.set_edge_attributes(G, 'inv_length', inv_lengths) 
nx.draw(G,pos,node_size=1000,node_color='r',with_labels=True) 
nx.draw_networkx_edge_labels(G,pos) 
plt.show() 

enter image description here

而下面的流程問題:

enter image description here

其中1是僅供應節點和23僅供需求,如何到來在下面的解決方案產生奇怪的流量通過每個邊緣?看起來好像q1=100甚至沒有考慮,我預計L2flow=0

m=nx.laplacian_matrix(G,weight='inv_length') 
a=m.todense() 

flow={} 
res2=np.dot(a,b) #No inverse is required: x=ab 
res2=[round(item,3) for sublist in res2.tolist() for item in sublist] 
print res2 
for i,e in enumerate(G.edges()): 
    flow[e]=res2[i] 

b=[] 
for i,v in enumerate(PE.values()): 
    b.append(v) 
res2=np.dot(a,b) #No inverse is required: x=ab 
res2=[round(item,3) for sublist in res2.tolist() for item in sublist] 
print res2 

#res2=[-24.62, 19.96, 4.66] 

enter image description here

+0

你的代碼會拋出以下錯誤:'NameError:name'flow'未定義' – Tonechas

+0

Python也在抱怨第二個片段:'NameError:name'a'不是定義爲' – Tonechas

+0

是的,我的不好。 'a'是圖的拉普拉斯矩陣的'todense()'版本,這個版本產生你答案的'L'數組。檢查編輯。 – FaCoffee

回答

1

我已經冒昧來計算更簡單的方式邊長:

from scipy.spatial.distance import euclidean 
lengths = {} 
inv_lengths = {} 
for edge in G.edges(): 
    startnode = edge[0] 
    endnode = edge[1] 
    d = euclidean(pos[startnode], pos[endnode]) 
    lengths[edge] = d 
    inv_lengths[edge] = 1/d 

而且我這是怎麼實現的矩陣方程  matrix equation

E = np.array([[0], 
       [60], 
       [40]], dtype=np.float64) 

L1 = lengths[(1, 2)] 
L2 = lengths[(2, 3)] 
L3 = lengths[(1, 3)] 

L = np.array([[1/L1 + 1/L3,  -1/L1,  -1/L3], 
       [  -1/L1, 1/L1 + 1/L2,  -1/L2], 
       [  -1/L3,  -1/L2, 1/L2 + 1/L3]], dtype=np.float64) 

qLE = np.dot(L, E) 

上面的代碼產生相同的結果(大約):

In [55]: np.set_printoptions(precision=2) 

In [56]: qLE 
Out[56]: 
array([[-24.64], 
     [ 19.97], 
     [ 4.67]]) 

總之,我認爲這不是一個編程問題。也許你應該修改流模型...