Python Gurobi - 将对偶问题写入文件
Python Gurobi - Write dual problem to file
使用 gurobipy
,我可以使用 model.write()
来写我的原始问题。我也知道我可以用 m.getAttr("Pi", m.getConstrs())
计算对偶。现在我很好奇,如果不是在代码中手动写出对偶模型,是否可以轻松生成 LP 的对偶并将其写入文件,就像我们将原始问题写入 .lp
一样文件。这是我尝试使用的一些玩具代码,请随意测试它:
import gurobipy as gp
import os
from gurobipy import GRB
def write_to_file(model, filestring):
directory = os.getcwd()
filename = directory+filestring
model.write(filename)
nodes = ['s', 'a', 'b', 'c', 'd', 'e','t']
orig = 's'
dest = 't'
arcs, capacity = gp.multidict({
('s', 'a') : 1,
('a', 'b') : 3,
('b', 'a') : 2,
('c', 'e') : 4,
('s', 'b') : 4,
('a', 'd') : 4,
('b', 'd') : 3,
('d', 't') : 9,
('s', 'c') : 6,
('b', 'e') : 1,
('e', 't') : 4
})
m = gp.Model("Rec4")
# add our variables
flow = m.addVars(arcs, name = "flow")
# cannot go over capacity
m.addConstrs(
(flow.sum(i,j) <= capacity[i,j] for i,j in arcs), "cap")
# flow conservation
m.addConstrs(
(flow.sum(i,'*') - flow.sum('*',i) == 0 for i in nodes if i != orig and i != dest), "conservation")
# maximize flow
obj = (flow.sum('*', dest) - flow.sum(dest, '*'))
m.setObjective(obj, GRB.MAXIMIZE)
m.optimize()
# print solutions
if m.status == GRB.OPTIMAL:
solution = m.getAttr('x', flow)
for i, j in arcs:
if solution[i, j] > 0:
print('%s -> %s: %g' % (i, j, solution[i, j]))
write_to_file(m, "//test.lp")
########################################################################
# Dual problem
duals = m.getAttr("Pi", m.getConstrs())
print(duals)
Gurobi 目前不提供此功能。可能会在未来的版本中写出对偶问题。
使用 gurobipy
,我可以使用 model.write()
来写我的原始问题。我也知道我可以用 m.getAttr("Pi", m.getConstrs())
计算对偶。现在我很好奇,如果不是在代码中手动写出对偶模型,是否可以轻松生成 LP 的对偶并将其写入文件,就像我们将原始问题写入 .lp
一样文件。这是我尝试使用的一些玩具代码,请随意测试它:
import gurobipy as gp
import os
from gurobipy import GRB
def write_to_file(model, filestring):
directory = os.getcwd()
filename = directory+filestring
model.write(filename)
nodes = ['s', 'a', 'b', 'c', 'd', 'e','t']
orig = 's'
dest = 't'
arcs, capacity = gp.multidict({
('s', 'a') : 1,
('a', 'b') : 3,
('b', 'a') : 2,
('c', 'e') : 4,
('s', 'b') : 4,
('a', 'd') : 4,
('b', 'd') : 3,
('d', 't') : 9,
('s', 'c') : 6,
('b', 'e') : 1,
('e', 't') : 4
})
m = gp.Model("Rec4")
# add our variables
flow = m.addVars(arcs, name = "flow")
# cannot go over capacity
m.addConstrs(
(flow.sum(i,j) <= capacity[i,j] for i,j in arcs), "cap")
# flow conservation
m.addConstrs(
(flow.sum(i,'*') - flow.sum('*',i) == 0 for i in nodes if i != orig and i != dest), "conservation")
# maximize flow
obj = (flow.sum('*', dest) - flow.sum(dest, '*'))
m.setObjective(obj, GRB.MAXIMIZE)
m.optimize()
# print solutions
if m.status == GRB.OPTIMAL:
solution = m.getAttr('x', flow)
for i, j in arcs:
if solution[i, j] > 0:
print('%s -> %s: %g' % (i, j, solution[i, j]))
write_to_file(m, "//test.lp")
########################################################################
# Dual problem
duals = m.getAttr("Pi", m.getConstrs())
print(duals)
Gurobi 目前不提供此功能。可能会在未来的版本中写出对偶问题。