This presentation is the property of its rightful owner.
1 / 7

# 最短路問題を G urobi で解こう！ PowerPoint PPT Presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

## 最短路問題をGurobiで解こう！

### 単純な実装

from gurobipy import *

E, cost = multidict(

{(0,1):10, (0,2):5, (1,2):2, (1,4):1, (2,1):3, (2,3):2, (3,4):6}

)

V=range(5)

print "E=",E

print "cost=",cost

E= [(0, 1), (1, 2), (2, 3), (1, 4), (3, 4), (0, 2), (2, 1)]

cost= {(0, 1): 10, (1, 2): 2, (2, 3): 2, (1, 4): 1, (3, 4): 6, (0, 2): 5, (2, 1): 3}

multidict( ) 関数は，辞書を入力

キー（枝）のリスト，費用を表す辞書 cost を返す．

### モデルの構築

m=Model()

x={}

for (i,j) in E:

m.update()

m.addConstr( -x[0,1] - x[0,2] == -1 , name="source")

m.addConstr( x[0,1] + x[2,1] -x[1,2] -x[1,4] ==0 , name="1" )

m.addConstr( x[0,2] + x[1,2] -x[2,1] -x[2,3] ==0 , name="2")

m.addConstr( x[2,3] - x[3,4] ==0 , name="3")

m.addConstr( x[1,4] + x[3,4] ==1 , name="sink")

m.setObjective(quicksum( cost[i,j]*x[i,j] for (i,j) in E ), GRB.MINIMIZE)

m.optimize()

### 結果の出力

Optimal Value= 9.0

0 1 0.0

1 2 0.0

1 4 1.0

2 3 0.0

2 1 1.0

3 4 0.0

0 2 1.0

source -5.0

1 3.0

2 0.0

3 2.0

sink 4.0

print "Optimal Value=",m.ObjVal

for (i,j) in x:

print i,j,x[i,j].X

for c in m.getConstrs():

print c.ConstrName, c.Pi

モデルオブジェクトm のgetConstrs()メソッド

で制約オブジェクトのリストを得る

Pi（π）で双対変数を得る！

### より一般的な実装

from gurobipy import *

E, cost = multidict(

{(0,1):10, (0,2):5, (1,2):2, (1,4):1, (2,1):3, (2,3):2, (3,4):6}

)

V=range(5)

Out =[ [] for i in V ]

In =[ [] for i in V ]

for (i,j) in E:

Out[i].append(j)

In[j].append(i)

print "Out=",Out

print "In=",In

Out= [[1, 2], [2, 4], [3, 1], [4], []]

In= [[], [0, 2], [1, 0], [2], [1, 3]]

### モデルの構築

m=Model()

x={}

for (i,j) in E:

m.update()

for i in V:

if i==0:

m.addConstr( quicksum( x[i,j] for j in Out[i]) ==1 )

elifi==4:

m.addConstr( quicksum( x[j,i] for j in In[i]) ==1 )

else:

m.addConstr( quicksum( x[j,i] for j in In[i]) ==

quicksum( x[i,j] for j in Out[i]) )

m.setObjective(quicksum( cost[i,j]*x[i,j] for (i,j) in E ), GRB.MINIMIZE)

### モデルの確認

Minimize

10 x(0,1) + 2 x(1,2) + 2 x(2,3) + x(1,4) + 6 x(3,4) + 5 x(0,2) + 3 x(2,1)

Subject To

R0: x(0,1) + x(0,2) = 1

R1: x(0,1) - x(1,2) - x(1,4) + x(2,1) = 0

R2: x(1,2) - x(2,3) + x(0,2) - x(2,1) = 0

R3: x(2,3) - x(3,4) = 0

R4: x(1,4) + x(3,4) = 1

Bounds

End

m.update()

m.write("sp.lp")

モデル更新 update()の後で

Writeメソッド

ファイル “sp.lp” が