電阻距離求解

Networkx2.4 的新功能 求電阻距離

題記
求圖的兩點間電阻距離是圖論中的一類問題,Networkx2.4 內置了此功能,可以方便調用. 有關理論這裏進行省略, 以後有時間進行補充. 這裏針對具體圖提供計算的方案.

import networkx as nx 
G = nx.Graph()
elist=[(0,1),(1,2),(2,3),(0,3),(0,2)]
G.add_edges_from(elist)
nx.draw(G,with_labels=True,node_size=1300,font_size=10,edge_color='b',width=5.0)
S= nx.resistance_distance(G, 0, 2, weight=None, invert_weight=True)
print(S)
import numpy
resistancematrix = numpy.zeros(shape=(4,4))
for i in range(4):
    for j in range(4):
        if i ==j :
            resistancematrix[i][j]= 0
        else:
            resistancematrix[i][j]=nx.resistance_distance(G, i, j, weight=None)
print(resistancematrix) 

當然這裏電阻距離矩陣是對稱的(可思考),我們進行了重複計算, 讀者可自行優化。 下面是Mathematica 利用 laplacian 廣義逆求解的代碼.

resistanceDistance[connectionData_] := 
 Module[{Laplace = 
    Normal[(SparseArray[
          Band[{1, 1}] -> (Plus @@ (-#1) &) /@ #1] + #1 &)[
      SparseArray[
       Thread[Flatten[({Reverse[#1], #1} &) /@ connectionData, 
          1] -> -1]]]]}, ({#1, 
      Det[Delete[
         Transpose[
          Delete[Laplace, {{#1[[1]]}, {#1[[2]]}}]], {{#1[[1]]}, {#1[[
            2]]}}]]/
       Det[Delete[
         Transpose[Delete[Laplace, {#1[[1]]}]], {#1[[1]]}]]} &) /@ 
   Subsets[Range[Length[Laplace]], {2}]]

當然我可以採用更簡潔的代碼體現Wolfram 語言的簡潔性!

ResistanceMatrix[g_] := 
 With[{\[CapitalGamma] = PseudoInverse[KirchhoffMatrix[g]]}, 
  Outer[Plus, Diagonal[\[CapitalGamma]], 
    Diagonal[\[CapitalGamma]]] - \[CapitalGamma] - 
   Transpose[\[CapitalGamma]]]

演示示例:

g = GridGraph[{3, 3}]
ResistanceMatrix[g] // MatrixForm

在這裏插入圖片描述
可以計算電阻距離延伸的問題: 如求kirhoffindex。

kirhoffindex[g_] := 1/2*Total[ResistanceMatrix[g], Infinity]
kirhoffindex[g]*結果:69/2*
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章