mosek
需求
求解mixed-integer problem
Introduction
优秀的数学优化求解器
官方网址:https://www.mosek.com/ 其中,重要说明:
- 认证文件下载:https://docs.mosek.com/9.3/licensing/quickstart.html#i-don-t-have-a-license-file-yet
按照要求放在指定的文件夹位置。python正常方法按照mosek包即可使用 - https://www.mosek.com/documentation/
有比较比较多的使用说明,主要是两个API文档FusionAPI和OptimizerAPI,一个是面向对象的一个是面向过程的用法,fusion更直观好用。尾页有一cookbook也可以更深入了解模型理论 使用求解器首先要自己完成建模过程,分清楚三个要素:variable、constraint、cost
Study
FusionAPI整数线性规划的例题
from mosek.fusion import *
def main(args):
A = [[50.0, 31.0],
[3.0, -2.0]]
c = [1.0, 0.64]
with Model('milo1') as M:
x = M.variable('x', 2, Domain.integral(Domain.greaterThan(0.0)))
M.constraint('c1', Expr.dot(A[0], x), Domain.lessThan(250.0))
M.constraint('c2', Expr.dot(A[1], x), Domain.greaterThan(-4.0))
M.setSolverParam('mioMaxTime', 60.0)
M.setSolverParam('mioTolRelGap', 1e-4)
M.setSolverParam('mioTolAbsGap', 0.0)
M.objective('obj', ObjectiveSense.Maximize, Expr.dot(c, x))
M.solve()
print('[x0, x1] = ', x.level())
print("MIP rel gap = %.2f (%f)" % (M.getSolverDoubleInfo(
"mioObjRelGap"), M.getSolverDoubleInfo("mioObjAbsGap")))
Practice
网上随便找一道有答案的自我验证例题
def mosek_fusion_integer_test():
"""
网上找的游泳问题,测试一下是否正确
测试完成,可以解
求解结果
0 0 0 1 甲自由泳
1 0 0 0 乙蝶泳
0 1 0 0 丙仰泳
0 0 1 0 丁蛙泳
0 0 0 0 戊不参加
:return:
"""
c = [[66.8, 75.6, 87, 58.6],
[57.2, 66, 66.4, 53],
[78, 67.8, 84.6, 59.4],
[70, 74.2, 69.6, 57.2],
[67.4, 71, 83.8, 62.4]]
A = [[1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0],
[0,0,0,0, 1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0],
[0,0,0,0, 0,0,0,0, 1,1,1,1, 0,0,0,0, 0,0,0,0],
[0,0,0,0, 0,0,0,0, 0,0,0,0, 1,1,1,1, 0,0,0,0],
[0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 1,1,1,1],
[1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,0,0],
[0,1,0,0, 0,1,0,0, 0,1,0,0, 0,1,0,0, 0,1,0,0],
[0,0,1,0, 0,0,1,0, 0,0,1,0, 0,0,1,0, 0,0,1,0],
[0,0,0,1, 0,0,0,1, 0,0,0,1, 0,0,0,1, 0,0,0,1],
]
with Model("swim") as M:
x = M.variable('x', 20, Domain.integral(Domain.greaterThan(0.0)))
M.constraint(x, Domain.lessThan(1.0))
M.constraint("c1", Expr.dot(A[0], x), Domain.lessThan(1.0))
M.constraint("c2", Expr.dot(A[1], x), Domain.lessThan(1.0))
M.constraint("c3", Expr.dot(A[2], x), Domain.lessThan(1.0))
M.constraint("c4", Expr.dot(A[3], x), Domain.lessThan(1.0))
M.constraint("c5", Expr.dot(A[4], x), Domain.lessThan(1.0))
M.constraint("ca", Expr.dot(A[5], x), Domain.equalsTo(1.0))
M.constraint("cb", Expr.dot(A[6], x), Domain.equalsTo(1.0))
M.constraint("cc", Expr.dot(A[7], x), Domain.equalsTo(1.0))
M.constraint("cd", Expr.dot(A[8], x), Domain.equalsTo(1.0))
M.setSolverParam('mioMaxTime', 60.0)
M.setSolverParam('mioTolRelGap', 1e-4)
M.setSolverParam('mioTolAbsGap', 0.0)
cc = [ii for i in c for ii in i]
M.objective('obj', ObjectiveSense.Minimize, Expr.dot(cc, x))
M.solve()
print('[x] = ', x.level())
print("MIP rel gap = %.2f (%f)" % (M.getSolverDoubleInfo(
"mioObjRelGap"), M.getSolverDoubleInfo("mioObjAbsGap")))
[未完待续]
|